2018-09-18 22:42:38 +02:00
|
|
|
package compiler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
scope struct {
|
|
|
|
parent *scope
|
|
|
|
vars map[string]core.Type
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func newRootScope() *scope {
|
|
|
|
return &scope{
|
|
|
|
vars: make(map[string]core.Type),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func newScope(parent *scope) *scope {
|
|
|
|
s := newRootScope()
|
|
|
|
s.parent = parent
|
|
|
|
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *scope) GetVariable(name string) (core.Type, error) {
|
|
|
|
local, exists := s.vars[name]
|
|
|
|
|
|
|
|
if exists {
|
|
|
|
return local, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.parent != nil {
|
|
|
|
parents, err := s.parent.GetVariable(name)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return core.NoneType, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return parents, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return core.NoneType, core.Error(ErrVariableNotFound, name)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *scope) SetVariable(name string) error {
|
|
|
|
_, exists := s.vars[name]
|
|
|
|
|
|
|
|
if exists {
|
2018-10-28 07:45:26 +02:00
|
|
|
return core.Error(ErrVariableNotUnique, name)
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: add type detection
|
|
|
|
s.vars[name] = core.NoneType
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-10-25 03:30:05 +02:00
|
|
|
func (s *scope) RemoveVariable(name string) error {
|
|
|
|
_, exists := s.vars[name]
|
|
|
|
|
|
|
|
if !exists {
|
2018-10-28 07:45:26 +02:00
|
|
|
return core.Error(ErrVariableNotFound, name)
|
2018-10-25 03:30:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
delete(s.vars, name)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2018-10-28 07:45:26 +02:00
|
|
|
func (s *scope) ClearVariables() {
|
|
|
|
s.vars = make(map[string]core.Type)
|
|
|
|
}
|
|
|
|
|
2018-09-18 22:42:38 +02:00
|
|
|
func (s *scope) Fork() *scope {
|
|
|
|
return newScope(s)
|
|
|
|
}
|