New interface to Typer: the function TypeName() returns a more readable type name

This commit is contained in:
Celestino Amoroso 2024-05-19 02:23:28 +02:00
parent 9967918418
commit b92b19e1dd
4 changed files with 37 additions and 3 deletions

View File

@ -4,6 +4,8 @@
// formatter.go
package expr
import "fmt"
type FmtOpt uint16
const (
@ -18,3 +20,16 @@ const (
type Formatter interface {
ToString(options FmtOpt) string
}
type Typer interface {
TypeName() string
}
func getTypeName(v any) (name string) {
if typer, ok := v.(Typer); ok {
name = typer.TypeName()
} else {
name = fmt.Sprintf("%T", v)
}
return
}

View File

@ -90,6 +90,14 @@ func (dict *DictType) ToString(opt FmtOpt) string {
return sb.String()
}
func (dict *DictType) String() string {
return dict.ToString(0)
}
func (dict *DictType) TypeName() string {
return "dict"
}
func (dict *DictType) hasKey(target any) (ok bool) {
for key := range *dict {
if ok = reflect.DeepEqual(key, target); ok {

View File

@ -62,6 +62,10 @@ func (ls *ListType) String() string {
return ls.ToString(0)
}
func (ls *ListType) TypeName() string {
return "list"
}
func (list *ListType) indexDeepCmp(target any) (index int) {
index = -1
for i, item := range *list {

13
term.go
View File

@ -161,11 +161,18 @@ func (self *term) toInt(computedValue any, valueDescription string) (i int, err
}
func (self *term) errIncompatibleTypes(leftValue, rightValue any) error {
leftType := getTypeName(leftValue)
rightType := getTypeName(rightValue)
return self.tk.Errorf(
"left operand '%v' [%T] and right operand '%v' [%T] are not compatible with operator %q",
leftValue, leftValue,
rightValue, rightValue,
"left operand '%v' [%s] and right operand '%v' [%s] are not compatible with operator %q",
leftValue, leftType,
rightValue, rightType,
self.source())
// return self.tk.Errorf(
// "left operand '%v' [%T] and right operand '%v' [%T] are not compatible with operator %q",
// leftValue, leftValue,
// rightValue, rightValue,
// self.source())
}
func (self *term) errIncompatibleType(value any) error {