Added scope package
This commit is contained in:
parent
fd66296826
commit
8e725da9c6
37 changed files with 416 additions and 371 deletions
12
src/build/scope/Scope.go
Normal file
12
src/build/scope/Scope.go
Normal file
|
@ -0,0 +1,12 @@
|
|||
package scope
|
||||
|
||||
import (
|
||||
"git.akyoto.dev/cli/q/src/build/cpu"
|
||||
)
|
||||
|
||||
// Scope represents an independent code block.
|
||||
type Scope struct {
|
||||
Variables map[string]*Variable
|
||||
InLoop bool
|
||||
cpu.State
|
||||
}
|
51
src/build/scope/Stack.go
Normal file
51
src/build/scope/Stack.go
Normal file
|
@ -0,0 +1,51 @@
|
|||
package scope
|
||||
|
||||
import (
|
||||
"git.akyoto.dev/cli/q/src/build/ast"
|
||||
"git.akyoto.dev/cli/q/src/build/token"
|
||||
)
|
||||
|
||||
type Stack struct {
|
||||
Scopes []*Scope
|
||||
}
|
||||
|
||||
// CurrentScope returns the current scope.
|
||||
func (stack *Stack) CurrentScope() *Scope {
|
||||
return stack.Scopes[len(stack.Scopes)-1]
|
||||
}
|
||||
|
||||
// PopScope removes the scope at the top of the stack.
|
||||
func (stack *Stack) PopScope() {
|
||||
stack.Scopes = stack.Scopes[:len(stack.Scopes)-1]
|
||||
}
|
||||
|
||||
// PushScope pushes a new scope to the top of the stack.
|
||||
func (stack *Stack) PushScope(body ast.AST) *Scope {
|
||||
s := &Scope{}
|
||||
|
||||
if len(stack.Scopes) > 0 {
|
||||
lastScope := stack.Scopes[len(stack.Scopes)-1]
|
||||
s.State = lastScope.State
|
||||
s.Variables = make(map[string]*Variable, len(lastScope.Variables))
|
||||
s.InLoop = lastScope.InLoop
|
||||
|
||||
for k, v := range lastScope.Variables {
|
||||
count := ast.Count(body, token.Identifier, v.Name)
|
||||
|
||||
if count == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
s.Variables[k] = &Variable{
|
||||
Name: v.Name,
|
||||
Register: v.Register,
|
||||
Alive: count,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
s.Variables = map[string]*Variable{}
|
||||
}
|
||||
|
||||
stack.Scopes = append(stack.Scopes, s)
|
||||
return s
|
||||
}
|
13
src/build/scope/Variable.go
Normal file
13
src/build/scope/Variable.go
Normal file
|
@ -0,0 +1,13 @@
|
|||
package scope
|
||||
|
||||
import (
|
||||
"git.akyoto.dev/cli/q/src/build/cpu"
|
||||
)
|
||||
|
||||
// Variable represents a named register.
|
||||
type Variable struct {
|
||||
Scope *Scope
|
||||
Name string
|
||||
Register cpu.Register
|
||||
Alive int
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue