about summary refs log tree commit diff
path: root/pkg/lang/compiler/scope_chain.go
blob: 6b7e693d0e1cfab8757212fdb927c938870ce743 (plain)
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
package compiler

type ScopeID int

type ScopeChain struct {
	scopes []Scope
}

func NewScopeChain() ScopeChain {
	scopes := make([]Scope, 1)
	scopes[0] = Scope{
		kind:         ScopeKindGlobal,
		nameToSymbol: make(map[string]int),
		symbols:      make([]Symbol, 0),
	}

	return ScopeChain{
		scopes: scopes,
	}
}

func (sc *ScopeChain) Current() *Scope {
	return &sc.scopes[len(sc.scopes)-1]
}

func (sc *ScopeChain) Enter(kind ScopeKind) {
	sc.scopes = append(sc.scopes, Scope{
		kind:         kind,
		nameToSymbol: make(map[string]int),
		symbols:      make([]Symbol, 0),
	})
}

func (sc *ScopeChain) Exit() {
	sc.scopes[len(sc.scopes)-1] = Scope{}
	sc.scopes = sc.scopes[:len(sc.scopes)-1]
}

func (sc *ScopeChain) Declare(name string) (int, bool) {
	// Check whether the symbol is already declared in any of the scopes.
	for _, scope := range sc.scopes {
		if _, ok := scope.nameToSymbol[name]; ok {
			return 0, false
		}
	}

	current := sc.Current()
	index := len(current.symbols)

	// Declare the symbol in the current scope.
	current.symbols = append(current.symbols, Symbol{
		kind:       SymbolKindVariable,
		name:       name,
		localIndex: index,
	})

	current.nameToSymbol[name] = index

	return index, true
}

func (sc *ScopeChain) DeclareAnonymous() int {
	current := sc.Current()
	index := len(current.symbols)

	// Declare the symbol in the current scope.
	current.symbols = append(current.symbols, Symbol{
		kind:       SymbolKindVariable,
		name:       "",
		localIndex: index,
	})

	return index
}

func (sc *ScopeChain) DeclareTemporary() int {
	return len(sc.Current().symbols)
}

func (sc *ScopeChain) Lookup(name string) (Symbol, bool) {
	for i := len(sc.scopes) - 1; i >= 0; i-- {
		if symbol, ok := sc.scopes[i].nameToSymbol[name]; ok {
			return sc.scopes[i].symbols[symbol], true
		}
	}

	return Symbol{}, false
}

type ScopeKind int

const (
	ScopeKindGlobal ScopeKind = iota
	ScopeKindFunction
	ScopeKindBlock
)

type Scope struct {
	kind         ScopeKind
	nameToSymbol map[string]int
	symbols      []Symbol
}