parser.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. package muesli
  2. import (
  3. _ "bufio"
  4. _ "bytes"
  5. _ "errors"
  6. "fmt"
  7. _ "io"
  8. _ "os"
  9. _ "reflect"
  10. _ "runtime"
  11. _ "strings"
  12. _ "unicode"
  13. // "gitlab.com/beoran/woe/graphviz"
  14. // _ "gitlab.com/beoran/woe/monolog"
  15. )
  16. /* Grammar:
  17. Desrired syntax (verified LL(1) on smlweb.cpsc.ucalgary.ca)
  18. In Muesli, the program is first tokenized by a lexer. The lexer uses the first
  19. character, and only the first character of every token to determine it's type.
  20. Then, the tokens are parsed with a recursive descent parser with a structured
  21. syntax, which has been verified to be LL(1) on smlweb.cpsc.ucalgary.ca. This
  22. means the parser only needs one token of lookahead to be able to parse the
  23. syntax. The syntax can be described as follows:
  24. PROGRAM -> STATEMENTS .
  25. STATEMENTS -> STATEMENT STATEMENTS | .
  26. STATEMENT -> BLOCK | CHAIN eos | eos .
  27. CHAIN -> EXPRESSION OPERATIONS .
  28. OPERATIONS -> LINK | .
  29. LINK -> OPERATION | REDIRECT | METHOD .
  30. METHOD -> method EXPRESSION .
  31. REDIRECT -> redirect EXPRESSION .
  32. OPERATION -> operator EXPRESSION .
  33. EXPRESSION -> COMMAND | SUBSTITUTION | LITERAL .
  34. COMMAND -> NAME PARAMETERS.
  35. PARAMETERS -> PARAMETER PARAMETERS | .
  36. PARAMETER -> LITERAL | BLOCK | SUBSTITUTION | NAME .
  37. SUBSTITUTION -> GETTER | SETTER | LIST | PARENTHESIS .
  38. PARENTHESIS -> closeparen CHAIN openparen .
  39. BLOCK -> openblock STATEMENTS closeblock .
  40. LIST -> openlist PARAMETERS closelist .
  41. LITERAL -> string | int | float .
  42. NAME -> word | symbol | type .
  43. SETTER -> set PARAMETER PARAMETER .
  44. GETTER -> get PARAMETER .
  45. The semantics of a muesli program are based on this syntax and can be explained
  46. as follows:
  47. - A muesli program consists of statements, which are executed from top to
  48. bottom.
  49. - A statement is either a block, or a command chain terminated by end of
  50. statement, eos, or an empty statement terminated by eos. The period . and
  51. the unescaped newline characters are eos.
  52. - A block consist of statements between braces { }. The statements of a block
  53. are not executed but compiled to a block which can be called to execute them
  54. later.
  55. - A command chain consists of an expression optionally followed by links.
  56. A command chain is executed by executing it's expression and applying the,
  57. operator, redirect and method links from left to right.
  58. - A link is either operator, redirect or method.
  59. - An operator begins with a token with one of the following characters: -+/*^%~
  60. Next is an expression. The effect of an operator is to evaluate the
  61. links before it and after it as a substitution, and then look up the callable
  62. with the name of the operator and execute that.
  63. - A redirect starts with a token of the following characters: |&><@
  64. Next is an expression. The effect of a redirect is to evaluate the
  65. links before it and after it as a block, and then look up the callable
  66. with the name of the operator and execute that.
  67. - A method start with a token with one of the following characters: ,;
  68. Next is an expression. The effect of a method is to evaluate the
  69. links before it and after it as a list of ast expressions, shuffle them
  70. so the operator comes first, but the rest is kept in order, and then look up
  71. the callable with the name of the operator and execute that.
  72. - A command may be a direct command, an indirect command, or a literal value.
  73. - A direct command
  74. - A () parenthesis gets substituted inline by the value returned by executing it
  75. anywhere it occurs, also in the beginning of a command.
  76. - A bracketed list [ elem1 elem2 ... ] is syntactic sugar for (list elem1 elem 2)
  77. - A dollar getter $varname is syntactic sugar for (get varname)
  78. - A equals setter =varname value is syntactic sugar for (set varname value)
  79. - Therefore, parenthesis, lists, getters and setters are allowed anywhere,
  80. also in the beginning of the command with substitution semantics.
  81. - If a command starts with a substitution, it is an indirect command. The
  82. substitution is evaluated and it's value is looked up as the command name.
  83. In case the result is not a name, this is a run time error.
  84. In case the result is a list, each value of the list is executed as a command
  85. with the same parameters.
  86. - A literal evaluate to itself.
  87. - A name also evaluates as itself but is specific for direct commands.
  88. *
  89. * program -> statements
  90. * statements -> statement+
  91. * statement -> get / set / command
  92. *
  93. */
  94. type Parser struct {
  95. Lexer *Lexer
  96. current Token
  97. LoggerWrapper
  98. Errors []ParserError
  99. }
  100. // panic with this type on errors that would prevent the parser
  101. // from making progress.
  102. type ParserError struct {
  103. *Parser
  104. *Token
  105. Chain error
  106. }
  107. func (pe ParserError) Error() string {
  108. return fmt.Sprintf("%s %s", pe.Token.String(), pe.Chain.Error())
  109. }
  110. func (parser *Parser) SetLogger(logger Logger) {
  111. parser.LoggerWrapper = LoggerWrapper{logger}
  112. }
  113. func (parser *Parser) SetDefaultLogger() {
  114. lg := &testLogger{}
  115. parser.LoggerWrapper = LoggerWrapper{lg}
  116. }
  117. func (parser *Parser) SetVmLogger(vm * VM) {
  118. parser.LoggerWrapper = vm.Console.LoggerWrapper
  119. }
  120. func (parser *Parser) Errorf(message string, args ...interface{}) ParserError {
  121. err := fmt.Errorf(message, args...)
  122. pe := ParserError { Parser: parser, Token:&parser.current, Chain: err }
  123. parser.Errors = append(parser.Errors, pe)
  124. return pe
  125. }
  126. func (parser *Parser) Panicf(message string, args ...interface{}) {
  127. pe := parser.Errorf(message, args...)
  128. panic(pe)
  129. }
  130. func (parser *Parser) Advance() {
  131. token := parser.Lexer.Lex()
  132. parser.current = token
  133. parser.LogDebug("Next token: %s\n", token.String())
  134. }
  135. /* Skips tokens until a closer, namely ), }, ], EOX or EOF is found,
  136. * to skip parse errors, and to be able to continue parsing despite errors. */
  137. func (parser *Parser) SkipError() Token {
  138. parser.Advance()
  139. for {
  140. parser.Advance()
  141. if parser.NextIsErrorSkipped() {
  142. return parser.current
  143. }
  144. if parser.NextIs(TokenKindError, TokenKindNone) {
  145. parser.Panicf("Cannot recover from parse error. Parse ended.")
  146. }
  147. }
  148. return parser.current
  149. }
  150. /* Looks at the current token and advances the lexer if the token is of any of
  151. the token kinds given in kinds. In this case it will return the accepted
  152. token and advance the parser. Otherwise, it will call parser.Panicf with a
  153. * "Syntax error unexpected <token>".*/
  154. func (parser *Parser) Require(kinds ...TokenKind) Token {
  155. if parser.current.IsNone() {
  156. parser.Advance()
  157. }
  158. expected := ""
  159. sep := ""
  160. for _, kind := range kinds {
  161. if kind == parser.current.TokenKind {
  162. accepted := parser.current
  163. parser.Advance()
  164. parser.LogDebug("Require: Accepted token: %s\n", accepted.String())
  165. return accepted
  166. }
  167. expected = fmt.Sprintf("%s%s%s", expected, sep, kind.String())
  168. }
  169. parser.Panicf("error: expected one of the following: %s", expected)
  170. return Token{}
  171. }
  172. func (parser *Parser) NewAstError(message string, args ...interface{}) *Ast {
  173. sv := StringValue(fmt.Sprintf(message+" at token "+parser.current.String(), args))
  174. pos := parser.current.Position
  175. tok := NewToken(TokenKindError, sv, pos)
  176. parser.Errorf(message, args...)
  177. return NewAst(AstKindError, nil, EmptyAstArray(), tok)
  178. }
  179. // Also handles none or error vales of the token
  180. func (parser *Parser) NewAst(kind AstKind, parent * Ast, children []*Ast, value Token) *Ast{
  181. if value.IsNone() {
  182. return NewAstNone()
  183. }
  184. if value.IsError() {
  185. return NewAst(AstKindError, parent, children, value)
  186. }
  187. return NewAst(kind, parent, children, value)
  188. }
  189. func (parser *Parser) ParseValue() *Ast {
  190. parser.LogDebug("ParseValue: %s\n", parser.current.String())
  191. value := parser.Require(TokenKindInteger, TokenKindString,
  192. TokenKindBoolean, TokenKindNil, TokenKindFloat, TokenKindSymbol)
  193. return parser.NewAst(AstKindValue, nil, EmptyAstArray(), value)
  194. }
  195. func AstKindForToken(token Token) AstKind {
  196. switch token.TokenKind {
  197. case TokenKindInteger, TokenKindString, TokenKindBoolean,
  198. TokenKindNil, TokenKindFloat, TokenKindSymbol:
  199. return AstKindValue
  200. case TokenKindWord:
  201. return AstKindWord
  202. case TokenKindType:
  203. return AstKindType
  204. default:
  205. return AstKindError
  206. }
  207. }
  208. func (parser *Parser) ParseLiteral() *Ast {
  209. parser.LogDebug("ParseLiteral: %s\n", parser.current.String())
  210. value := parser.Require(TokenKindInteger, TokenKindString,
  211. TokenKindBoolean, TokenKindNil, TokenKindFloat)
  212. astKind := AstKindForToken(value)
  213. return parser.NewAst(astKind, nil, EmptyAstArray(), value)
  214. }
  215. func (parser *Parser) ParseName() *Ast {
  216. parser.LogDebug("ParseName: %s\n", parser.current.String())
  217. value := parser.Require(TokenKindWord, TokenKindType, TokenKindSymbol)
  218. astKind := AstKindForToken(value)
  219. return parser.NewAst(astKind, nil, EmptyAstArray(), value)
  220. }
  221. func (parser *Parser) ParseArgument() *Ast {
  222. parser.LogDebug("ParseArgument: %s\n", parser.current.String())
  223. switch {
  224. case parser.NextIsName(): return parser.ParseName()
  225. case parser.NextIsBlock(): return parser.ParseBlock()
  226. case parser.NextIsSubstitution(): return parser.ParseSubstitution()
  227. case parser.NextIsLiteral(): return parser.ParseLiteral()
  228. default: parser.Panicf("error: in argument: expected $, =, }, word or value")
  229. return nil
  230. }
  231. }
  232. func (parser *Parser) ParseArguments(extra ... *Ast) *Ast {
  233. parser.LogDebug("ParseArguments: %s\n", parser.current.String())
  234. ast := NewAstWithToken(AstKindArguments, parser.current)
  235. var children []*Ast
  236. for _, arg := range extra {
  237. children = append(children, arg)
  238. }
  239. for parser.NextIsArgument() {
  240. child := parser.ParseArgument()
  241. children = append(children, child)
  242. }
  243. ast.AppendChildren(children...)
  244. return ast
  245. }
  246. func (parser *Parser) ParseList() *Ast {
  247. parser.LogDebug("ParseList: %s\n", parser.current.String())
  248. op := parser.Require(TokenKindOpenList)
  249. if op.IsError() {
  250. return parser.NewAstError("Unexpected value.")
  251. }
  252. ast := NewAstWithToken(AstKindList, op)
  253. args := parser.ParseArguments()
  254. if AstIsError(args) {
  255. return args
  256. }
  257. if cp := parser.Require(TokenKindCloseList); cp.IsError() {
  258. return parser.NewAstError("expected closing brackets")
  259. }
  260. ast.AppendChild(args)
  261. return ast
  262. }
  263. func (parser *Parser) ParseParenthesis() *Ast {
  264. parser.LogDebug("ParseParenthesis: %s\n", parser.current.String())
  265. op := parser.Require(TokenKindOpenParen)
  266. if op.IsError() {
  267. return parser.NewAstError("Unexpected value.")
  268. }
  269. ast := NewAstWithToken(AstKindParenthesis, op)
  270. expr := parser.ParseChain()
  271. if expr.IsNone() {
  272. return parser.NewAstError("expected chain")
  273. }
  274. if AstIsError(expr) {
  275. return expr
  276. }
  277. if cp := parser.Require(TokenKindCloseParen); cp.IsError() {
  278. return parser.NewAstError("expected closing parenthesis")
  279. }
  280. ast.AppendChild(expr)
  281. return ast
  282. }
  283. func (parser *Parser) ParseBlock() *Ast {
  284. parser.LogDebug("ParseBlock: %s\n", parser.current.String())
  285. op := parser.Require(TokenKindOpenBlock)
  286. if op.IsError() {
  287. return parser.NewAstError("Unexpected value.")
  288. }
  289. ast := NewAstWithToken(AstKindBlock, op)
  290. stats := parser.ParseStatements()
  291. if stats.IsNone() {
  292. return parser.NewAstError("expected expression")
  293. }
  294. if AstIsError(stats) {
  295. return stats
  296. }
  297. if cp := parser.Require(TokenKindCloseBlock); cp.IsError() {
  298. return parser.NewAstError("expected closing block")
  299. }
  300. ast.AppendChild(stats)
  301. return ast
  302. }
  303. func (parser *Parser) RequireName() Token {
  304. return parser.Require(TokenKindWord, TokenKindType, TokenKindSymbol)
  305. }
  306. /* Parses the target of a set expression */
  307. func (parser *Parser) ParseTarget() *Ast {
  308. parser.LogDebug("ParseTarget: %s\n", parser.current.String())
  309. var target *Ast
  310. switch {
  311. case parser.NextIsName():
  312. // Direct target to a set
  313. token := parser.RequireName()
  314. target = NewAstWithToken(AstKindTarget, token)
  315. case parser.NextIsSubstitution():
  316. // Indirect target
  317. target = NewAstWithToken(AstKindTarget, parser.current)
  318. target.AppendChild(parser.ParseSubstitution())
  319. default:
  320. parser.Panicf("Malformed setter.")
  321. return nil
  322. }
  323. argument := parser.ParseArgument()
  324. if argument.IsNone() {
  325. return parser.NewAstError("Expected argument to set")
  326. }
  327. target.AppendChild(argument)
  328. return target
  329. }
  330. /* Parses the origin of a get expression */
  331. func (parser *Parser) ParseOrigin() *Ast {
  332. parser.LogDebug("ParseOrigin: %s\n", parser.current.String())
  333. var target *Ast
  334. switch {
  335. case parser.NextIsName():
  336. // Direct target to a set
  337. token := parser.RequireName()
  338. target = NewAstWithToken(AstKindTarget, token)
  339. case parser.NextIsSubstitution():
  340. target = NewAstWithToken(AstKindTarget, parser.current)
  341. target.AppendChild(parser.ParseSubstitution())
  342. default:
  343. parser.Panicf("Malformed getter")
  344. return nil
  345. }
  346. return target
  347. }
  348. func (parser *Parser) ParseSet() *Ast {
  349. parser.LogDebug("ParseSet: %s\n", parser.current.String())
  350. set := parser.Require(TokenKindSet)
  351. ast := NewAstWithToken(AstKindSet, set)
  352. target := parser.ParseTarget()
  353. ast.AppendChild(target)
  354. return ast
  355. }
  356. func (parser *Parser) ParseGet() *Ast {
  357. parser.LogDebug("ParseGet: %s\n", parser.current.String())
  358. get := parser.Require(TokenKindGet)
  359. ast := NewAstWithToken(AstKindGet, get)
  360. target := parser.ParseOrigin()
  361. ast.AppendChild(target)
  362. return ast
  363. }
  364. func (parser *Parser) ParseCommand() *Ast {
  365. parser.LogDebug("ParseCommand: %s\n", parser.current.String())
  366. word := parser.Require(TokenKindWord, TokenKindType)
  367. arguments := parser.ParseArguments()
  368. command := NewAstWithToken(AstKindCommand, word)
  369. command.AppendChild(arguments)
  370. return command
  371. }
  372. func (parser *Parser) ParseSubstitution() *Ast {
  373. parser.LogDebug("ParseSubstitution: %s\n", parser.current.String())
  374. switch {
  375. case parser.NextIs(TokenKindOpenParen): return parser.ParseParenthesis()
  376. case parser.NextIs(TokenKindOpenList): return parser.ParseList()
  377. case parser.NextIs(TokenKindGet): return parser.ParseGet()
  378. case parser.NextIs(TokenKindSet): return parser.ParseSet()
  379. default:
  380. parser.Panicf("Syntax error in substitution, expected $, =, (, [")
  381. return nil
  382. }
  383. }
  384. func (parser *Parser) ParseExpression() *Ast {
  385. parser.LogDebug("ParseExpression: %s\n", parser.current.String())
  386. switch {
  387. case parser.NextIsWord(): return parser.ParseCommand()
  388. case parser.NextIsSubstitution(): return parser.ParseSubstitution()
  389. case parser.NextIsLiteral(): return parser.ParseLiteral()
  390. default:
  391. parser.Panicf("Syntax error in expression, expected word, $, =, value")
  392. return nil
  393. }
  394. }
  395. func (parser *Parser) ParseExpressionStatement() *Ast {
  396. parser.LogDebug("ParseExpressionStatement: %s\n", parser.current.String())
  397. expr := parser.ParseExpression()
  398. if expr.IsNone() {
  399. return NewAstNone()
  400. }
  401. // Expression statements must end on EOX or EOF
  402. if eox := parser.Require(TokenKindEOX, TokenKindEOF); eox.IsError() {
  403. return parser.NewAstError("expected end of statement")
  404. }
  405. return expr
  406. }
  407. func (parser *Parser) ParseEmptyStatement() *Ast {
  408. parser.LogDebug("ParseEmptyStatement: %s\n", parser.current.String())
  409. if eox := parser.Require(TokenKindEOX, TokenKindEOF); eox.IsError() {
  410. return parser.NewAstError("expected end of statement")
  411. }
  412. return NewAstWithToken(AstKindStatement, parser.current)
  413. }
  414. func (parser Parser) NextIs(kinds ...TokenKind) bool {
  415. if (parser.current.TokenKind == TokenKindNone) {
  416. parser.Advance()
  417. }
  418. for _, kind := range kinds {
  419. if kind == parser.current.TokenKind {
  420. return true
  421. }
  422. }
  423. return false
  424. }
  425. func (parser Parser) NextIsBlock() bool {
  426. return parser.NextIs(TokenKindOpenBlock)
  427. }
  428. func (parser Parser) NextIsSubstitution() bool {
  429. return parser.NextIs(TokenKindOpenList, TokenKindOpenParen,
  430. TokenKindSet, TokenKindGet)
  431. }
  432. func (parser Parser) NextIsWord() bool {
  433. return parser.NextIs(TokenKindWord)
  434. }
  435. func (parser Parser) NextIsGet() bool {
  436. return parser.NextIs(TokenKindGet)
  437. }
  438. func (parser Parser) NextIsSet() bool {
  439. return parser.NextIs(TokenKindSet)
  440. }
  441. func (parser Parser) NextIsLiteral() bool {
  442. return parser.NextIs(TokenKindString, TokenKindInteger, TokenKindFloat,
  443. TokenKindBoolean, TokenKindNil)
  444. }
  445. func (parser Parser) NextIsName() bool {
  446. return parser.NextIs(TokenKindWord, TokenKindType, TokenKindSymbol)
  447. }
  448. func (parser Parser) NextIsOperator() bool {
  449. return parser.NextIs(TokenKindOperator, TokenKindRedirect, TokenKindMethod)
  450. }
  451. func (parser Parser) NextIsArgument() bool {
  452. return parser.NextIsName() || parser.NextIsLiteral() ||
  453. parser.NextIsSubstitution() || parser.NextIsBlock()
  454. }
  455. func (parser Parser) NextIsCommand() bool {
  456. return parser.NextIsName()
  457. }
  458. func (parser Parser) NextIsErrorSkipped() bool {
  459. return parser.NextIs(TokenKindCloseBlock, TokenKindCloseList, TokenKindCloseParen,
  460. TokenKindEOX, TokenKindEOF)
  461. }
  462. func (parser Parser) NextIsEOX() bool {
  463. return parser.NextIs(TokenKindEOX)
  464. }
  465. func (parser Parser) NextIsEOF() bool {
  466. return parser.NextIs(TokenKindEOF)
  467. }
  468. func (parser Parser) NextIsExpression() bool {
  469. return parser.NextIsCommand() || parser.NextIsSubstitution() ||
  470. parser.NextIsLiteral()
  471. }
  472. func (parser Parser) NextIsChain() bool {
  473. return parser.NextIsExpression()
  474. }
  475. func (parser Parser) NextIsStatement() bool {
  476. return parser.NextIsChain() || parser.NextIsBlock() || parser.NextIsEOX()
  477. }
  478. func (parser *Parser) newMethodChain(oper Token, expr1, expr2 *Ast) *Ast {
  479. chain := NewAstWithToken(AstKindOperation, oper)
  480. chain.AppendChildren(expr1)
  481. chain.AppendChild(NewAstWithToken(AstKindForToken(expr2.Token()), expr2.Token()))
  482. chain.AppendChildren(expr2.Children()...)
  483. parser.LogDebug("New method chain: %v", chain)
  484. return chain
  485. }
  486. func (parser *Parser) newChain(oper Token, expr1, expr2 *Ast) * Ast {
  487. var astkind AstKind = AstKindParenthesis
  488. if oper.TokenKind == TokenKindRedirect {
  489. parser.LogDebug("New redirect chain.")
  490. astkind = AstKindStatements
  491. } else if oper.TokenKind == TokenKindMethod {
  492. return parser.newMethodChain(oper, expr1, expr2)
  493. }
  494. subst1 := NewAstWithToken(astkind, oper)
  495. subst1.AppendChildren(expr1)
  496. subst2 := NewAstWithToken(astkind, oper)
  497. subst2.AppendChildren(expr2)
  498. chain := NewAstWithToken(AstKindOperation, oper)
  499. chain.AppendChildren(subst1, subst2)
  500. return chain
  501. }
  502. func (parser *Parser) composeChain(oper Token, chain, nextExpr *Ast) * Ast {
  503. var astkind AstKind = AstKindParenthesis
  504. if oper.TokenKind == TokenKindRedirect {
  505. parser.LogDebug("Composed redirect chain: %v", chain)
  506. astkind = AstKindStatements
  507. } else if oper.TokenKind == TokenKindMethod {
  508. chain.AppendChild(NewAstWithToken(AstKindForToken(nextExpr.Token()), nextExpr.Token()))
  509. chain.AppendChildren(nextExpr.Children()...)
  510. parser.LogDebug("Composed method chain: %v", chain)
  511. return chain
  512. } else {
  513. parser.LogDebug("Composed normal chain: %v", chain)
  514. }
  515. subst := NewAstWithToken(astkind, oper)
  516. subst.AppendChildren(nextExpr)
  517. newChain := NewAstWithToken(AstKindOperation, oper)
  518. newChain.AppendChildren(chain, subst)
  519. return newChain
  520. }
  521. func (parser *Parser) ParseChain() *Ast {
  522. expression := parser.ParseExpression()
  523. if !parser.NextIsOperator() {
  524. return expression
  525. }
  526. var expressions = []*Ast{ expression }
  527. var operators = []Token {}
  528. for parser.NextIsOperator() {
  529. oper := parser.Require(TokenKindOperator, TokenKindRedirect, TokenKindMethod)
  530. expression := parser.ParseExpression()
  531. if expression == nil {
  532. parser.Panicf("Expected expression after operator.")
  533. }
  534. expressions = append(expressions, expression)
  535. operators = append(operators, oper)
  536. }
  537. // Now there are N expressions and N - 1 operators, iterate
  538. // for easy composition
  539. var chain *Ast
  540. parser.LogDebug("Working on operator chain: %v %v", operators, expressions)
  541. for i, j := 0, 0 ; i < len(expressions) && j < len(operators) ; i, j = i + 1 , j + 1 {
  542. expression := expressions[i]
  543. oper := operators[j]
  544. if chain == nil {
  545. expression2 := expressions[i+1]
  546. chain = parser.newChain(oper, expression, expression2)
  547. i++
  548. } else {
  549. chain = parser.composeChain(oper, chain, expression)
  550. }
  551. }
  552. return chain
  553. }
  554. func (parser *Parser) ParseStatement() *Ast {
  555. parser.LogDebug("ParseStatement: %s\n", parser.current.String())
  556. switch {
  557. case parser.NextIsBlock(): return parser.ParseBlock()
  558. case parser.NextIsExpression(): return parser.ParseChain()
  559. case parser.NextIsEOX(): return parser.ParseEmptyStatement()
  560. default:
  561. parser.Panicf("Expected block, command, or EOX in statement")
  562. return parser.NewAstError("Expected closed, expression, or EOX in statement")
  563. }
  564. }
  565. func (parser *Parser) ParseStatements() *Ast {
  566. parser.LogDebug("ParseStatements: %s\n", parser.current.String())
  567. ast := NewAstWithToken(AstKindStatements, parser.current)
  568. var children []*Ast
  569. for parser.NextIsStatement() {
  570. child := parser.ParseStatement()
  571. children = append(children, child)
  572. }
  573. ast.AppendChildren(children...)
  574. return ast
  575. }
  576. func (parser *Parser) ParseProgram() *Ast {
  577. parser.LogDebug("ParseProgram: %s\n", parser.current.String())
  578. stats := parser.ParseStatements()
  579. eof := parser.Require(TokenKindEOF)
  580. aeof := NewAstWithToken(AstKindEnd, eof)
  581. if eof.IsNone() {
  582. aeof = parser.NewAstError("Expected EOF, have: %s", parser.current.String())
  583. }
  584. children := []*Ast{stats, aeof}
  585. return NewAst(AstKindProgram, nil, children, NoToken())
  586. }
  587. func (parser *Parser) Parse() (ast *Ast) {
  588. defer func() {
  589. if err := recover() ; err != nil {
  590. if perr, ok := err.(ParserError) ; ok{
  591. ast = parser.NewAstError("Parse error, recovered: %s\n", perr)
  592. } else {
  593. panic(err)
  594. }
  595. }
  596. } ()
  597. parser.Advance()
  598. ast = parser.ParseProgram()
  599. return ast
  600. }
  601. func NewParser(lexer *Lexer) *Parser {
  602. parser := &Parser{Lexer: lexer, current: NoToken(), LoggerWrapper: LoggerWrapper{nil}}
  603. return parser
  604. }
  605. func NewParserFromString(input string) *Parser {
  606. lexer := NewLexerFromString(input)
  607. return NewParser(lexer)
  608. }
  609. func NewParserFromFilename(filename string) (*Parser, error) {
  610. lexer, err := NewLexerFromFilename(filename)
  611. if err != nil {
  612. return nil, err
  613. }
  614. return NewParser(lexer), nil
  615. }
  616. func (parser * Parser) NewKeyword(name string, tk TokenKind, val Value) *Keyword {
  617. return parser.Lexer.NewKeyword(name, tk, val)
  618. }
  619. func (parser * Parser) AddKeyword(kw * Keyword) *Keyword {
  620. return parser.Lexer.AddKeyword(kw)
  621. }
  622. func (parser * Parser) AddKeywords(keywords []*Keyword) {
  623. for _, kw := range keywords {
  624. parser.AddKeyword(kw)
  625. }
  626. }
  627. func (parser * Parser) AddDefaultKeywords() {
  628. parser.AddKeywords(DefaultKeywords)
  629. }