parser.go 21 KB

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