-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (84 loc) · 2.47 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"strconv"
"github.com/igorbelo/gocalc/parser"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/llir/llvm/ir"
"github.com/llir/llvm/ir/constant"
"github.com/llir/llvm/ir/types"
"github.com/llir/llvm/ir/value"
)
var i64 = types.I64
var m = ir.NewModule()
var fun = m.NewFunc("calc", i64)
var block = fun.NewBlock("")
type calcListener struct {
*parser.BaseCalcListener
stack []value.Value
}
func (l *calcListener) push(v value.Value) {
l.stack = append(l.stack, v)
}
func (l *calcListener) pop() value.Value {
if len(l.stack) < 1 {
panic("stack is empty unable to pop")
}
// Get the last value from the stack.
result := l.stack[len(l.stack)-1]
// Pop the last element from the stack.
l.stack = l.stack[:len(l.stack)-1]
return result
}
// ExitMulDiv is called when exiting the MulDiv production.
func (l *calcListener) ExitMulDiv(c *parser.MulDivContext) {
right, left := l.pop(), l.pop()
switch c.GetOp().GetTokenType() {
case parser.CalcParserMUL:
l.push(block.NewMul(left, right))
case parser.CalcParserDIV:
l.push(block.NewUDiv(left, right))
default:
panic(fmt.Sprintf("unexpected operation: %s", c.GetOp().GetText()))
}
}
// ExitAddSub is called when exiting the AddSub production.
func (l *calcListener) ExitAddSub(c *parser.AddSubContext) {
right, left := l.pop(), l.pop()
switch c.GetOp().GetTokenType() {
case parser.CalcParserADD:
l.push(block.NewAdd(left, right))
case parser.CalcParserSUB:
l.push(block.NewSub(left, right))
default:
panic(fmt.Sprintf("unexpected operation: %s", c.GetOp().GetText()))
}
}
// ExitNumber is called when exiting the Number production.
func (l *calcListener) ExitNumber(c *parser.NumberContext) {
i, err := strconv.Atoi(c.GetText())
if err != nil {
panic(err.Error())
}
l.push(constant.NewInt(i64, int64(i)))
}
func (l *calcListener) ExitStart(_ *parser.StartContext) {
block.NewRet(l.pop())
}
// calc takes a string expression and returns the evaluated result.
func calc(input string) {
// Setup the input
is := antlr.NewInputStream(input)
// Create the Lexer
lexer := parser.NewCalcLexer(is)
stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
// Create the Parser
p := parser.NewCalcParser(stream)
// Finally parse the expression (by walking the tree)
var listener calcListener
antlr.ParseTreeWalkerDefault.Walk(&listener, p.Start())
}
func main() {
calc("(1 + (2-3)) * 3")
fmt.Println(m)
}