|
|
@@ -0,0 +1,97 @@
|
|
|
+package parser
|
|
|
+
|
|
|
+import (
|
|
|
+ "github/runnignwater/monkey/ast"
|
|
|
+ "github/runnignwater/monkey/lexer"
|
|
|
+ "github/runnignwater/monkey/token"
|
|
|
+)
|
|
|
+
|
|
|
+/**
|
|
|
+ * @Author: simon
|
|
|
+ * @Author: ynwdlxm@163.com
|
|
|
+ * @Date: 2022/10/2 下午9:55
|
|
|
+ * @Desc:
|
|
|
+ */
|
|
|
+type Parser struct {
|
|
|
+ l *lexer.Lexer // point to the instance of the lexer
|
|
|
+
|
|
|
+ curToken token.Token // point to the current token
|
|
|
+ peekToken token.Token // point to the next token
|
|
|
+}
|
|
|
+
|
|
|
+func New(l *lexer.Lexer) *Parser {
|
|
|
+ p := &Parser{l: l}
|
|
|
+
|
|
|
+ // Read two tokens, so curToken and peekToken are both set
|
|
|
+ p.nextToken()
|
|
|
+ p.nextToken()
|
|
|
+
|
|
|
+ return p
|
|
|
+}
|
|
|
+
|
|
|
+func (p *Parser) nextToken() {
|
|
|
+ p.curToken = p.peekToken
|
|
|
+ p.peekToken = p.l.NextToken()
|
|
|
+}
|
|
|
+
|
|
|
+func (p *Parser) ParseProgram() *ast.Program {
|
|
|
+ program := &ast.Program{}
|
|
|
+ program.Statements = []ast.Statement{}
|
|
|
+
|
|
|
+ for p.curToken.Type != token.EOF {
|
|
|
+ stmt := p.parseStatement()
|
|
|
+ if stmt != nil {
|
|
|
+ program.Statements = append(program.Statements, stmt)
|
|
|
+ }
|
|
|
+ p.nextToken()
|
|
|
+
|
|
|
+ }
|
|
|
+ return program
|
|
|
+}
|
|
|
+
|
|
|
+func (p *Parser) parseStatement() ast.Statement {
|
|
|
+ switch p.curToken.Type {
|
|
|
+ case token.LET:
|
|
|
+ return p.parseLetStatement()
|
|
|
+ default:
|
|
|
+ return nil
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// let <identifier> = <expression>;
|
|
|
+func (p *Parser) parseLetStatement() *ast.LetStatement {
|
|
|
+ stmt := &ast.LetStatement{Token: p.curToken}
|
|
|
+
|
|
|
+ if !p.expectPeek(token.IDENT) {
|
|
|
+ return nil
|
|
|
+ }
|
|
|
+
|
|
|
+ stmt.Name = &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}
|
|
|
+ if !p.expectPeek(token.ASSIGN) {
|
|
|
+ return nil
|
|
|
+ }
|
|
|
+
|
|
|
+ // TODO: we're skipping the expression until we
|
|
|
+ // we encounter a semicolon
|
|
|
+ for !p.curTokenIs(token.SEMICOLON) {
|
|
|
+ p.nextToken()
|
|
|
+ }
|
|
|
+ return stmt
|
|
|
+}
|
|
|
+
|
|
|
+func (p *Parser) curTokenIs(t token.TypeToken) bool {
|
|
|
+ return p.curToken.Type == t
|
|
|
+}
|
|
|
+
|
|
|
+func (p *Parser) peekTokenIs(t token.TypeToken) bool {
|
|
|
+ return p.peekToken.Type == t
|
|
|
+}
|
|
|
+
|
|
|
+func (p *Parser) expectPeek(t token.TypeToken) bool {
|
|
|
+ if p.peekTokenIs(t) {
|
|
|
+ p.nextToken()
|
|
|
+ return true
|
|
|
+ } else {
|
|
|
+ return false
|
|
|
+ }
|
|
|
+}
|