Skip to content

Commit

Permalink
Wiring up the parser with the runtime.
Browse files Browse the repository at this point in the history
 - small bug fixes in scanner and parser logic
  • Loading branch information
iamsayantan committed Apr 9, 2022
1 parent 2c0e4ec commit ff4902b
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 16 deletions.
15 changes: 2 additions & 13 deletions ast_printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,8 @@ import (

type AstPrinter struct{}

func (ap *AstPrinter) Print() string {
exp := &Binary{
Left: &Unary{
Operator: NewToken(Minus, "-", nil, 1),
Right: &Literal{Value: 123},
},
Operator: NewToken(Star, "*", nil, 1),
Right: &Grouping{
Expression: &Literal{Value: 45.67},
},
}

return exp.Accept(ap).(string)
func (ap *AstPrinter) Print(expr Expr) string {
return expr.Accept(ap).(string)
}

func (ap *AstPrinter) VisitBinaryExpr(expr *Binary) interface{} {
Expand Down
12 changes: 11 additions & 1 deletion glox.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,17 @@ func (r *Runtime) Error(line int, message string) {

func (r *Runtime) run(source string) {
scanner := NewScanner(bytes.NewBuffer([]byte(source)), r)
_ = scanner.ScanTokens()
tokens := scanner.ScanTokens()

parser := NewParser(tokens, r)
expr := parser.Parse()

printer := &AstPrinter{}
if r.hadError {
return
}

fmt.Println(printer.Print(expr))

// for _, token := range tokens {
// if token.Type == String {
Expand Down
2 changes: 1 addition & 1 deletion parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ func (p *Parser) consume(tokenType TokenType, message string) (Token, error) {
return p.advance(), nil
}

return Token{}, NewParseError(message)
return Token{}, p.error(p.peek(), message)
}

// isAtEnd checks if we have run out of tokens to parse.
Expand Down
2 changes: 1 addition & 1 deletion scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func (sc *Scanner) scanToken() {
if sc.match('=') {
sc.addToken(BangEqual, nil)
} else {
sc.addToken(Equal, nil)
sc.addToken(Bang, nil)
}
case '=':
if sc.match('=') {
Expand Down

0 comments on commit ff4902b

Please sign in to comment.