ucl/cmdlang/env.go

85 lines
1.5 KiB
Go
Raw Normal View History

2024-04-10 10:45:58 +00:00
package cmdlang
type evalCtx struct {
root *evalCtx
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
}
2024-04-18 12:24:19 +00:00
func (ec *evalCtx) forkAndIsolate() *evalCtx {
newEc := &evalCtx{parent: ec}
newEc.root = newEc
return newEc
}
2024-04-16 12:28:12 +00:00
func (ec *evalCtx) fork() *evalCtx {
return &evalCtx{parent: ec, root: ec.root}
2024-04-16 12:28:12 +00:00
}
2024-04-10 10:45:58 +00:00
func (ec *evalCtx) addCmd(name string, inv invokable) {
2024-04-18 12:24:19 +00:00
if ec.root.commands == nil {
ec.root.commands = make(map[string]invokable)
2024-04-10 10:45:58 +00:00
}
2024-04-18 12:24:19 +00:00
ec.root.commands[name] = inv
2024-04-10 10:45:58 +00:00
}
2024-04-13 11:46:50 +00:00
func (ec *evalCtx) addMacro(name string, inv macroable) {
2024-04-18 12:24:19 +00:00
if ec.root.macros == nil {
ec.root.macros = make(map[string]macroable)
2024-04-13 11:46:50 +00:00
}
2024-04-18 12:24:19 +00:00
ec.root.macros[name] = inv
2024-04-13 11:46:50 +00:00
}
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
}