2024-04-19 09:05:26 +02:00
|
|
|
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
|
|
|
|
// All rights reserved.
|
|
|
|
|
|
|
|
// operator-dot.go
|
|
|
|
package expr
|
|
|
|
|
2024-04-21 14:24:56 +02:00
|
|
|
import "fmt"
|
|
|
|
|
2024-04-19 09:05:26 +02:00
|
|
|
// -------- dot term
|
|
|
|
func newDotTerm(tk *Token) (inst *term) {
|
|
|
|
return &term{
|
|
|
|
tk: *tk,
|
|
|
|
children: make([]*term, 0, 2),
|
|
|
|
position: posInfix,
|
|
|
|
priority: priDot,
|
|
|
|
evalFunc: evalDot,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-27 14:44:52 +02:00
|
|
|
func verifyIndex(indexTerm *term, indexValue any, maxValue int) (index int, err error) {
|
|
|
|
var v int
|
|
|
|
if v, err = indexTerm.toInt(indexValue, "index expression value must be integer"); err == nil {
|
|
|
|
if v >= 0 && v < maxValue {
|
|
|
|
index = v
|
|
|
|
} else if index >= -maxValue {
|
|
|
|
index = maxValue + v
|
|
|
|
} else {
|
|
|
|
err = indexTerm.Errorf("index %d out of bounds", v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-04-19 09:05:26 +02:00
|
|
|
func evalDot(ctx ExprContext, self *term) (v any, err error) {
|
|
|
|
var leftValue, rightValue any
|
|
|
|
|
|
|
|
if leftValue, rightValue, err = self.evalInfix(ctx); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
indexTerm := self.children[1]
|
|
|
|
|
2024-04-27 14:44:52 +02:00
|
|
|
switch unboxedValue := leftValue.(type) {
|
|
|
|
case []any:
|
2024-04-21 14:24:56 +02:00
|
|
|
var index int
|
2024-04-27 14:44:52 +02:00
|
|
|
if index, err = verifyIndex(indexTerm, rightValue, len(unboxedValue)); err == nil {
|
|
|
|
v = unboxedValue[index]
|
2024-04-21 14:24:56 +02:00
|
|
|
}
|
2024-04-27 14:44:52 +02:00
|
|
|
case string:
|
2024-04-21 14:24:56 +02:00
|
|
|
var index int
|
2024-04-27 14:44:52 +02:00
|
|
|
if index, err = verifyIndex(indexTerm, rightValue, len(unboxedValue)); err == nil {
|
|
|
|
v = unboxedValue[index]
|
2024-04-19 09:05:26 +02:00
|
|
|
}
|
2024-04-27 14:44:52 +02:00
|
|
|
case map[any]any:
|
2024-04-21 14:24:56 +02:00
|
|
|
var ok bool
|
2024-04-27 14:44:52 +02:00
|
|
|
if v, ok = unboxedValue[rightValue]; !ok {
|
2024-04-21 14:24:56 +02:00
|
|
|
err = fmt.Errorf("key %v does not belong to the dictionary", rightValue)
|
|
|
|
}
|
2024-04-27 14:44:52 +02:00
|
|
|
default:
|
2024-04-19 09:05:26 +02:00
|
|
|
err = self.errIncompatibleTypes(leftValue, rightValue)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// init
|
|
|
|
func init() {
|
|
|
|
registerTermConstructor(SymDot, newDotTerm)
|
|
|
|
}
|