Skip to content

Commit

Permalink
#20 - add AST generator for the current grammar
Browse files Browse the repository at this point in the history
no tests haha
  • Loading branch information
danilopedraza committed Feb 29, 2024
1 parent 525fd21 commit 51db379
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
45 changes: 45 additions & 0 deletions ast/antlr_ast.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package ast

import (
"lang/parsing"
"strconv"
)

type CSTWalker struct {
parsing.BaselangParserVisitor
}

func (c *CSTWalker) VisitInteger(ctx *parsing.IntegerContext) Integer {
val, _ := strconv.Atoi(ctx.INTEGER().GetText())
return Integer{val}
}

func (c *CSTWalker) VisitSum(ctx *parsing.SumContext) Infix {
return Infix{"+", c.Visit(ctx.Exp(0)), c.Visit(ctx.Exp(1))}
}

func (c *CSTWalker) VisitProduct(ctx *parsing.ProductContext) Infix {
return Infix{"*", c.Visit(ctx.Exp(0)), c.Visit(ctx.Exp(1))}
}

func (c *CSTWalker) VisitParens(ctx *parsing.ParensContext) interface{} {
return c.Visit(ctx.Exp())
}

func (c *CSTWalker) VisitIdent(ctx *parsing.IdentContext) Identifier {
return Identifier{ctx.IDENTIFIER().GetText()}
}

func (c *CSTWalker) VisitReal(ctx *parsing.RealContext) Real {
val, _ := strconv.ParseFloat(ctx.REAL().GetText(), 64)
return Real{val}
}

func (c *CSTWalker) VisitLet_statement(ctx *parsing.Let_statementContext) LetStatement {
return LetStatement{ctx.IDENTIFIER(0).GetText(), ctx.IDENTIFIER(1).GetText(), c.Visit(ctx.Exp())}
}

func (c *CSTWalker) VisitProgram(ctx *parsing.ProgramContext) Program {
list := make([]interface{}, 0)
return Program{list}
}
29 changes: 29 additions & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package ast

type Identifier struct {
val string
}

type Infix struct {
op string
lhs interface{}
rhs interface{}
}

type Integer struct {
val int
}

type LetStatement struct {
kind string
name string
val interface{}
}

type Program struct {
sentences []interface{}
}

type Real struct {
val float64
}

0 comments on commit 51db379

Please # to comment.