operator at for dict

This commit is contained in:
2026-07-14 06:50:56 +02:00
parent bf2c7df0f0
commit 8c55f4ac4b
3 changed files with 38 additions and 5 deletions
+13 -5
View File
@@ -8,6 +8,7 @@ import (
"git.portale-stac.it/go-pkg/expr/kern"
"git.portale-stac.it/go-pkg/expr/scan"
"git.portale-stac.it/go-pkg/expr/types/array"
"git.portale-stac.it/go-pkg/expr/types/dict"
"git.portale-stac.it/go-pkg/expr/types/list"
)
@@ -37,13 +38,20 @@ func evalAt(ctx kern.ExprContext, opTerm *scan.Term) (v any, err error) {
if array.IsArray(rightValue) {
a, _ := rightValue.(*array.ArrayType)
v = a.IndexDeepSameCmp(leftValue)
// } else if dict.IsDict(rightValue) {
// dict, _ := rightValue.(*dict.DictType)
// v = dict.HasKey(leftValue)
if index := a.IndexDeepSameCmp(leftValue); index >= 0 {
v = index
}
} else if dict.IsDict(rightValue) {
dict, _ := rightValue.(*dict.DictType)
if k, exists := dict.FindKey(leftValue); exists {
v = k
}
} else if list.IsLinkedList(rightValue) {
ls, _ := rightValue.(*list.LinkedList)
v = ls.Index(leftValue)
if index := ls.Index(leftValue); index >= 0 {
v = index
}
} else {
err = opTerm.ErrIncompatibleTypes(leftValue, rightValue)
}
+14
View File
@@ -47,6 +47,9 @@ func TestDictParser(t *testing.T) {
/* 22 */ {`f=func(n){"x"+n}; d={f(5):10}`, dict.NewDict(map[any]any{"x5": int64(10)}), nil},
/* 23 */ {`f=func(n){"x"+n}; d={f(5); "z":10}`, nil, "[1:27] expected one of `:`, `}`, got `;`"},
/* 24 */ {`f=func(n){"x"+n}; d={f(5) but "z":10}`, dict.NewDict(map[any]any{"z": int64(10)}), nil},
/* 25 */ {`3 in {1:"one", 2:"two"}`, false, nil},
/* 26 */ {`1 at {"a":2, "b":3, "c":1}`, "c", nil},
/* 27 */ {`10 at {"a":2, "b":3, "c":1}`, nil, nil},
}
// RunTestSuiteSpec(t, section, inputs, 1)
@@ -88,6 +91,17 @@ func TestAccessSubFields(t *testing.T) {
// runCtxTestSuite(t, ctx, section, inputs)
}
func TestDictDeepAssign(t *testing.T) {
section := "Dict-DeepAssign"
inputs := []inputType{
/* 1 */ {`DD={"uno": 1, "due": 2}; D=DD; D["uno"]=11; DD`, dict.NewDict(map[any]any{"uno": int64(11), "due": int64(2)}), nil},
/* 2 */ {`DD={"uno": 1, "due": 2}; D:=DD; D["uno"]=11; DD`, dict.NewDict(map[any]any{"uno": int64(1), "due": int64(2)}), nil},
}
// runTestSuiteSpec(t, section, inputs, 4)
RunTestSuite(t, section, inputs)
}
func TestDictToStringMultiLine(t *testing.T) {
var good bool
section := "dict-ToString-ML"
+11
View File
@@ -160,6 +160,17 @@ func (dict *DictType) GetItem(key any) (value any, exists bool) {
return
}
func (dict *DictType) FindKey(item any) (key any, exists bool) {
for k, v := range *dict {
if kern.Equal(v, item) {
key = k
exists = true
break
}
}
return
}
func (dict *DictType) Clone() kern.Cloner {
c := newDict(nil)
for k, v := range *dict {