-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
#20 - add AST generator for the current grammar
no tests haha
- Loading branch information
1 parent
525fd21
commit 51db379
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |