-
By default, the code |
Beta Was this translation helpful? Give feedback.
Answered by
antonmedv
Dec 8, 2023
Replies: 2 comments
-
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
fmarcia
-
For the record, here is how I got through it: package main
import (
"fmt"
"strings"
"github.com/expr-lang/expr/ast"
"github.com/expr-lang/expr/parser"
)
type (
T = map[string]any
visitor struct {
symbols []string
}
)
func main() {
env := T{"var": 1, "obj": T{"prop": T{"sub": "abc"}}}
tests := []struct {
code string
unknown string
}{
{`obj.prop.sub == "abc" || var == 1`, ""},
{`obj2.prop.sub == "abc" || var == 1`, "obj2"},
{`obj.prop2.sub == "abc" || var == 1`, "obj.prop2"},
{`obj.prop.sub2 == "abc" || var == 1`, "obj.prop.sub2"},
{`obj.prop2.sub2 == "abc" || var == 1`, "obj.prop2"},
{`obj2.prop2.sub2 == "abc" || var == 1`, "obj2"},
{`obj.prop.sub == "abc" || var2 == 1`, "var2"},
{`obj2.prop.sub == "abc" || var2 == 1`, "obj2"},
}
fmt.Println("with", env)
for _, t := range tests {
tree, _ := parser.Parse(t.code)
v := &visitor{}
ast.Walk(&tree.Node, v)
unknown := check(env, v.symbols)
fmt.Printf("[%s]\t(unknown == %s) == %v\n", t.code, `"`+unknown+`"`, t.unknown == unknown)
}
}
func (v *visitor) Visit(node *ast.Node) {
if s, ok := (*node).(*ast.MemberNode); ok {
v.symbols = append(v.symbols, s.String())
} else if s, ok := (*node).(*ast.IdentifierNode); ok {
v.symbols = append(v.symbols, s.String())
}
}
func check(env T, symbols []string) string {
for _, symbol := range symbols {
var current any = env
var acc []string
parts := strings.Split(symbol, ".")
last := len(parts) - 1
for rank, part := range parts {
current = current.(T)[part]
acc = append(acc, part)
if rank == last && current == nil {
return strings.Join(acc, ".")
}
}
}
return ""
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
obj
ismap[string]any
, prop or any other string may be there.obj
is a structtype Obj struct { Prop int `expr:"prop"` }
, you will get an error.