Parser - An Example in Go
A Parser is a program that reads the tokens and converts it into an abstract syntax tree (AST). It is the second part of an interpreter. What the usage looks like // for an input `let five = 5;` input := `let five = 5;` l := lexer.New(input) p := parser.New(l) // result is a list of statements result := []ast.Statement{ &ast.LetStatement{ Token: token.Token{Type: token.LET, Literal: "let"}, Name: &ast.Identifier{ Token: token.Token{Type: token.IDENT, Literal: "five"}, Value: "five", }, Value: &ast.IntegerLiteral{ Token: token.Token{Type: token.INT, Literal: "5"}, Value: 5, }, }, } input2 := "1 + 2 + 3;" l2 := lexer.New(input2) p2 := parser.New(l2) result2 := []ast.Statement{ &ast.ExpressionStatement{ Token: token.Token{Type: token.INT, Literal: "1"}, Expression: &ast.InfixExpression{ Token: token.Token{Type: token.PLUS, Literal: "+"}, Left: &ast.IntegerLiteral{ Token: token.Token{Type: token.INT, Literal: "1"}, Value: 1, }, Operator: "+", Right: &ast.InfixExpression{ Token: token.Token{Type: token.PLUS, Literal: "+"}, Left: &ast.IntegerLiteral{ Token: token.Token{Type: token.INT, Literal: "2"}, Value: 2, }, Operator: "+", Right: &ast.IntegerLiteral{ Token: token.Token{Type: token.INT, Literal: "3"}, Value: 3, }, }, }, }, } The parser also needs to handle operator precedence and associativity. It is a complex part of an interpreter. ...