ucl/cmdlang/env.go

74 lines
1.3 KiB
Go
Raw Normal View History

2024-04-10 10:45:58 +00:00
package cmdlang
type evalCtx struct {
2024-04-12 23:25:16 +00:00
parent *evalCtx
commands map[string]invokable
2024-04-13 11:46:50 +00:00
macros map[string]macroable
2024-04-12 23:25:16 +00:00
vars map[string]object
2024-04-10 10:45:58 +00:00
}
func (ec *evalCtx) addCmd(name string, inv invokable) {
if ec.commands == nil {
ec.commands = make(map[string]invokable)
}
ec.commands[name] = inv
}
2024-04-13 11:46:50 +00:00
func (ec *evalCtx) addMacro(name string, inv macroable) {
if ec.macros == nil {
ec.macros = make(map[string]macroable)
}
ec.macros[name] = inv
}
func (ec *evalCtx) setVar(name string, val object) {
if ec.vars == nil {
ec.vars = make(map[string]object)
}
ec.vars[name] = val
}
func (ec *evalCtx) getVar(name string) (object, bool) {
if ec.vars == nil {
return nil, false
}
if v, ok := ec.vars[name]; ok {
return v, true
} else if ec.parent != nil {
return ec.parent.getVar(name)
}
return nil, false
}
2024-04-13 11:46:50 +00:00
func (ec *evalCtx) lookupInvokable(name string) invokable {
if ec == nil {
return nil
}
2024-04-10 10:45:58 +00:00
2024-04-13 11:46:50 +00:00
for e := ec; e != nil; e = e.parent {
if cmd, ok := e.commands[name]; ok {
2024-04-13 11:46:50 +00:00
return cmd
2024-04-10 10:45:58 +00:00
}
2024-04-13 11:46:50 +00:00
}
return ec.parent.lookupInvokable(name)
}
func (ec *evalCtx) lookupMacro(name string) macroable {
if ec == nil {
return nil
}
2024-04-10 10:45:58 +00:00
2024-04-13 11:46:50 +00:00
for e := ec; e != nil; e = e.parent {
if cmd, ok := e.macros[name]; ok {
return cmd
}
2024-04-10 10:45:58 +00:00
}
2024-04-13 11:46:50 +00:00
return ec.parent.lookupMacro(name)
2024-04-10 10:45:58 +00:00
}