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

type ScopeID int

type ScopeChain struct {
	scopes []Scope
}

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

	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,
		symbols: make(map[string]Symbol),
	})
}

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) bool {
	// Check whether the symbol is already declared in any of the scopes.
	for _, scope := range sc.scopes {
		if _, ok := scope.symbols[name]; ok {
			return false
		}
	}

	// Declare the symbol in the current scope.
	sc.Current().symbols[name] = Symbol{
		kind:       SymbolKindVariable,
		name:       name,
		localIndex: len(sc.Current().symbols),
	}

	return true
}

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

	return Symbol{}, false
}

type ScopeKind int

const (
	ScopeKindGlobal ScopeKind = iota
	ScopeKindFunction
	ScopeKindBlock
)

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