-
Notifications
You must be signed in to change notification settings - Fork 6
/
codegen.go
129 lines (101 loc) · 2.17 KB
/
codegen.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package dsl
import (
"bufio"
"fmt"
"os"
"strings"
)
type CodeGenerator interface {
CompTopScope(Node) error
}
type AsmCodeGenerator struct {
indent int
writer *bufio.Writer
}
func NewAsmCodeGenerator() *AsmCodeGenerator {
return &AsmCodeGenerator{}
}
func (c *AsmCodeGenerator) EmitLine(line string) {
c.writer.WriteString(strings.Repeat("\t", c.indent))
c.writer.WriteString(line)
c.writer.WriteString("\n")
}
func (c *AsmCodeGenerator) Indent() {
c.indent += 1
}
func (c *AsmCodeGenerator) Deindent() {
c.indent -= 1
if c.indent < 0 {
c.indent = 0
}
}
func (c *AsmCodeGenerator) compNode(node Node) {
if node == nil {
return
}
switch n := node.(type) {
case *ProgramNode:
c.compNode(n.Front())
c.compNode(n.Next())
case *StatementNode:
c.compNode(n.Front())
c.compNode(n.Next())
case *TokenNode:
c.EmitLine(fmt.Sprintf("PUSH %s", n.Token))
case *AssignNode:
left := n.Front()
right := n.Next()
if tn, ok := right.(*TokenNode); ok {
c.EmitLine(fmt.Sprintf("PUSH %s", tn.Token))
} else if _, ok := right.(*OpNode); ok {
c.compNode(right)
}
if tn, ok := left.(*TokenNode); ok {
c.EmitLine(fmt.Sprintf("SET %s", tn.Token))
}
case *OpNode:
left := n.Front()
right := n.Next()
c.compNode(left)
c.compNode(right)
if n.Operator == "+" {
c.EmitLine("ADD")
} else if n.Operator == "-" {
c.EmitLine("SUB")
} else if n.Operator == "/" {
c.EmitLine("DIV")
} else if n.Operator == "*" {
c.EmitLine("MUL")
}
case *PrintNode:
left := n.Front()
c.compNode(left)
c.EmitLine("PRINT")
case *WhileNode:
left := n.Front()
right := n.Next()
blockNb = blockNb + 1
c.EmitLine(fmt.Sprintf("JMP cond%d", blockNb))
c.EmitLine(fmt.Sprintf("body%d%s", blockNb, ":"))
c.Indent()
c.compNode(right)
c.Deindent()
c.EmitLine(fmt.Sprintf("cond%d%s", blockNb, ":"))
c.Indent()
c.compNode(left)
c.EmitLine(fmt.Sprintf("JNZ body%d", blockNb))
c.Deindent()
}
return
}
func (c *AsmCodeGenerator) CompTopScope(ast Node) error {
file, err := os.Create("generated.txt")
defer file.Close()
if err != nil {
return err
}
c.writer = bufio.NewWriter(file)
c.compNode(ast)
c.writer.Flush()
return nil
}