/
generator.go
64 lines (54 loc) · 1.86 KB
/
generator.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
package bytecode
import (
"github.com/goby-lang/goby/compiler/ast"
)
type scope struct {
program *ast.Program
localTable *localTable
anchors map[string]*anchor
}
func newScope() *scope {
return &scope{localTable: newLocalTable(0), anchors: make(map[string]*anchor)}
}
// Generator contains program's AST and will store generated instruction sets
type Generator struct {
REPL bool
instructionSets []*InstructionSet
blockCounter int
scope *scope
instructionsWithAnchor []*Instruction
}
// NewGenerator initializes new Generator with complete AST tree.
func NewGenerator() *Generator {
return &Generator{instructionsWithAnchor: []*Instruction{}}
}
// ResetInstructionSets clears generator's instruction sets
func (g *Generator) ResetInstructionSets() {
g.instructionSets = []*InstructionSet{}
}
// InitTopLevelScope sets generator's scope with program node, which means it's the top level scope
func (g *Generator) InitTopLevelScope(program *ast.Program) {
g.scope = &scope{program: program, localTable: newLocalTable(0), anchors: make(map[string]*anchor)}
}
// GenerateInstructions returns compiled instructions
func (g *Generator) GenerateInstructions(stmts []ast.Statement) []*InstructionSet {
g.compileStatements(stmts, g.scope, g.scope.localTable)
// Use anchor's exact position to replace anchor obj
for _, i := range g.instructionsWithAnchor {
i.Params[0] = i.AnchorLine()
}
//fmt.Println(g.instructionsToString())
//fmt.Print()
return g.instructionSets
}
func (g *Generator) compileCodeBlock(is *InstructionSet, stmt *ast.BlockStatement, scope *scope, table *localTable) {
for _, s := range stmt.Statements {
g.compileStatement(is, s, scope, table)
}
}
func (g *Generator) endInstructions(is *InstructionSet, sourceLine int) {
if g.REPL && is.name == Program {
return
}
is.define(Leave, sourceLine)
}