parser.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. package parser
  2. import (
  3. "fmt"
  4. "strconv"
  5. "code.osinet.fr/fgm/waiig15/ast"
  6. "code.osinet.fr/fgm/waiig15/lexer"
  7. "code.osinet.fr/fgm/waiig15/token"
  8. )
  9. // Precedence constants.
  10. const (
  11. _ int = iota
  12. LOWEST
  13. EQUALS // ==
  14. LESSGREATER // > or <
  15. SUM // +
  16. PRODUCT // *
  17. PREFIX // -X or !X
  18. CALL // myFunction(X)
  19. )
  20. var precedences = map[token.TokenType]int{
  21. token.EQ: EQUALS,
  22. token.NOT_EQ: EQUALS,
  23. token.LT: LESSGREATER,
  24. token.GT: LESSGREATER,
  25. token.PLUS: SUM,
  26. token.MINUS: SUM,
  27. token.SLASH: PRODUCT,
  28. token.ASTERISK: PRODUCT,
  29. }
  30. type (
  31. prefixParseFn func() ast.Expression
  32. infixParseFn func(ast.Expression) ast.Expression
  33. )
  34. // Parser implements the parsing mechanism top-level layer.
  35. type Parser struct {
  36. l *lexer.Lexer
  37. errors []string
  38. curToken token.Token
  39. peekToken token.Token
  40. prefixParseFns map[token.TokenType]prefixParseFn
  41. infixParseFns map[token.TokenType]infixParseFn
  42. }
  43. // New returns a new Parser instance with the first two parser tokens already
  44. // loaded.
  45. func New(l *lexer.Lexer) *Parser {
  46. p := &Parser{
  47. l: l,
  48. errors: []string{},
  49. }
  50. p.prefixParseFns = make(map[token.TokenType]prefixParseFn)
  51. p.registerPrefix(token.IDENT, p.parseIdentifier)
  52. p.registerPrefix(token.INT, p.parseIntegerLiteral)
  53. p.registerPrefix(token.BANG, p.parsePrefixExpression)
  54. p.registerPrefix(token.MINUS, p.parsePrefixExpression)
  55. p.registerPrefix(token.TRUE, p.parseBoolean)
  56. p.registerPrefix(token.FALSE, p.parseBoolean)
  57. p.registerPrefix(token.LPAREN, p.parseGroupedExpression)
  58. p.infixParseFns = make(map[token.TokenType]infixParseFn)
  59. for _, tok := range []token.TokenType{
  60. token.ASTERISK,
  61. token.EQ,
  62. token.GT,
  63. token.LT,
  64. token.MINUS,
  65. token.NOT_EQ,
  66. token.PLUS,
  67. token.SLASH,
  68. } {
  69. p.registerInfix(tok, p.parseInfixExpression)
  70. }
  71. // Read two tokens, so curToken and peekToken are both set
  72. p.nextToken()
  73. p.nextToken()
  74. return p
  75. }
  76. func (p *Parser) nextToken() {
  77. p.curToken = p.peekToken
  78. p.peekToken = p.l.NextToken()
  79. }
  80. // Is the current token in the parser of the given type ?
  81. func (p *Parser) curTokenIs(t token.TokenType) bool {
  82. return p.curToken.Type == t
  83. }
  84. // Is the next token in the parser of the given type ? Don't consume it.
  85. func (p *Parser) peekTokenIs(t token.TokenType) bool {
  86. return p.peekToken.Type == t
  87. }
  88. // Is the next token in the parser of the given type ? If it is, consume it,
  89. // else don't.
  90. func (p *Parser) expectPeek(t token.TokenType) bool {
  91. if p.peekTokenIs(t) {
  92. p.nextToken()
  93. return true
  94. }
  95. p.peekError(t)
  96. return false
  97. }
  98. // Errors is a getter for Parser.errors.
  99. func (p *Parser) Errors() []string {
  100. return p.errors
  101. }
  102. // Log a mismatch error on the peek token type in the parser instance.
  103. //
  104. // - t is the type of token that was expected
  105. func (p *Parser) peekError(t token.TokenType) {
  106. msg := fmt.Sprintf("expected next token to be %s, got %s instead",
  107. t, p.peekToken.Type)
  108. p.errors = append(p.errors, msg)
  109. }
  110. func (p *Parser) noPrefixParseFnError(t token.TokenType) {
  111. msg := fmt.Sprintf("no prefix parse function for %s found", t)
  112. p.errors = append(p.errors, msg)
  113. }
  114. // ParseProgram is the outermost parsing logic, accumulating statements in a
  115. // Program instance and returning that instance once parsing is done.
  116. func (p *Parser) ParseProgram() *ast.Program {
  117. defer untrace(trace("ParseProgram"))
  118. program := &ast.Program{
  119. Statements: []ast.Statement{},
  120. }
  121. for !p.curTokenIs(token.EOF) {
  122. stmt := p.parseStatement()
  123. if stmt != nil {
  124. program.Statements = append(program.Statements, stmt)
  125. }
  126. p.nextToken()
  127. }
  128. return program
  129. }
  130. func (p *Parser) parseStatement() ast.Statement {
  131. defer untrace(trace("parseStatement"))
  132. switch p.curToken.Type {
  133. case token.LET:
  134. return p.parseLetStatement()
  135. case token.RETURN:
  136. return p.parseReturnStatement()
  137. default:
  138. return p.parseExpressionStatement()
  139. }
  140. }
  141. func (p *Parser) parseLetStatement() *ast.LetStatement {
  142. defer untrace(trace("parseLetStatement"))
  143. stmt := &ast.LetStatement{
  144. Token: p.curToken,
  145. }
  146. // Let statement starts with an IDENT token, so if next token is not an
  147. // IDENT, the next statement cannot be a Let statement.
  148. if !p.expectPeek(token.IDENT) {
  149. return nil
  150. }
  151. stmt.Name = &ast.Identifier{
  152. Token: p.curToken,
  153. Value: p.curToken.Literal,
  154. }
  155. // The previous expectPeek() call fetched the next token, so we should now
  156. // be on the assignment.
  157. if !p.expectPeek(token.ASSIGN) {
  158. return nil
  159. }
  160. // Skip the expression for now, progress to the semicolon terminating the
  161. // statement.
  162. for !p.curTokenIs(token.SEMICOLON) {
  163. p.nextToken()
  164. }
  165. return stmt
  166. }
  167. func (p *Parser) parseReturnStatement() *ast.ReturnStatement {
  168. defer untrace(trace("parseReturnStatement"))
  169. stmt := &ast.ReturnStatement{
  170. Token: p.curToken,
  171. }
  172. // There should be an expression to consume here.
  173. p.nextToken()
  174. // Skip the expression for now, progress to the semicolon terminating the
  175. // statement.
  176. for !p.curTokenIs(token.SEMICOLON) {
  177. p.nextToken()
  178. }
  179. return stmt
  180. }
  181. func (p *Parser) parseExpressionStatement() *ast.ExpressionStatement {
  182. defer untrace(trace("parseExpressionStatement"))
  183. stmt := &ast.ExpressionStatement{
  184. Token: p.curToken,
  185. }
  186. stmt.Expression = p.parseExpression(LOWEST)
  187. // Semicolons are optional to help use REPL input.
  188. if p.peekTokenIs(token.SEMICOLON) {
  189. p.nextToken()
  190. }
  191. return stmt
  192. }
  193. func (p *Parser) parseExpression(precedence int) ast.Expression {
  194. defer untrace(trace("parseExpression"))
  195. prefix := p.prefixParseFns[p.curToken.Type]
  196. if prefix == nil {
  197. p.noPrefixParseFnError(p.curToken.Type)
  198. return nil
  199. }
  200. leftExp := prefix()
  201. for !p.peekTokenIs(token.SEMICOLON) && precedence < p.peekPrecedence() {
  202. infix := p.infixParseFns[p.peekToken.Type]
  203. if infix == nil {
  204. return leftExp
  205. }
  206. p.nextToken()
  207. leftExp = infix(leftExp)
  208. }
  209. return leftExp
  210. }
  211. // Look forward for the precedence of the next token without advancing.
  212. func (p *Parser) peekPrecedence() int {
  213. if precedence, ok := precedences[p.peekToken.Type]; ok {
  214. return precedence
  215. }
  216. return LOWEST
  217. }
  218. // Return the precedence for the current token without advancing.
  219. func (p *Parser) curPrecedence() int {
  220. if precedence, ok := precedences[p.curToken.Type]; ok {
  221. return precedence
  222. }
  223. return LOWEST
  224. }
  225. // parseIdentifier does not advance the tokens or call nextToken, and this is
  226. // important.
  227. func (p *Parser) parseIdentifier() ast.Expression {
  228. return &ast.Identifier{
  229. Token: p.curToken,
  230. Value: p.curToken.Literal,
  231. }
  232. }
  233. func (p *Parser) parseIntegerLiteral() ast.Expression {
  234. defer untrace(trace("parseIntegerLiteral"))
  235. lit := &ast.IntegerLiteral{
  236. Token: p.curToken,
  237. }
  238. // Base 0 allows straight interpretation of octal 0755 or hex 0xABCD.
  239. value, err := strconv.ParseInt(p.curToken.Literal, 0, 64)
  240. if err != nil {
  241. msg := fmt.Sprintf("could not parse %q as integer",
  242. p.curToken.Literal)
  243. p.errors = append(p.errors, msg)
  244. return nil
  245. }
  246. lit.Value = value
  247. return lit
  248. }
  249. func (p *Parser) parsePrefixExpression() ast.Expression {
  250. defer untrace(trace("parsePrefixExpression"))
  251. expression := &ast.PrefixExpression{
  252. Token: p.curToken,
  253. Operator: p.curToken.Literal,
  254. }
  255. // Consume the operator token to progress to the prefixed expression.
  256. p.nextToken()
  257. // The precedence is now that of the prefix operator instead of the lowest.
  258. expression.Right = p.parseExpression(PREFIX)
  259. return expression
  260. }
  261. func (p *Parser) parseInfixExpression(left ast.Expression) ast.Expression {
  262. defer untrace(trace("parseInfixExpression"))
  263. expression := &ast.InfixExpression{
  264. Token: p.curToken,
  265. Operator: p.curToken.Literal,
  266. Left: left,
  267. }
  268. precedence := p.curPrecedence()
  269. p.nextToken()
  270. expression.Right = p.parseExpression(precedence)
  271. return expression
  272. }
  273. func (p *Parser) parseBoolean() ast.Expression {
  274. defer untrace(trace("parseBoolean"))
  275. expression := &ast.Boolean{
  276. Token: p.curToken,
  277. Value: p.curTokenIs(token.TRUE),
  278. }
  279. return expression
  280. }
  281. func (p *Parser) parseGroupedExpression() ast.Expression {
  282. p.nextToken()
  283. exp := p.parseExpression(LOWEST)
  284. if !p.expectPeek(token.RPAREN) {
  285. return nil
  286. }
  287. return exp
  288. }
  289. func (p *Parser) registerPrefix(tokenType token.TokenType, fn prefixParseFn) {
  290. p.prefixParseFns[tokenType] = fn
  291. }
  292. func (p *Parser) registerInfix(tokenType token.TokenType, fn infixParseFn) {
  293. p.infixParseFns[tokenType] = fn
  294. }