Skip to content

Commit

Permalink
Refactor checker to use Nature
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed May 31, 2024
1 parent 7e6e6f5 commit 9de0701
Show file tree
Hide file tree
Showing 28 changed files with 1,164 additions and 853 deletions.
38 changes: 34 additions & 4 deletions ast/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,20 @@ import (
"reflect"

"github.com/expr-lang/expr/file"
"github.com/expr-lang/expr/types"
)

var (
anyType = reflect.TypeOf(new(any)).Elem()
)

// Node represents items of abstract syntax tree.
type Node interface {
Location() file.Location
SetLocation(file.Location)
Nature() types.Nature
SetNature(types.Nature)
Kind() reflect.Kind
Type() reflect.Type
SetType(reflect.Type)
String() string
Expand All @@ -25,8 +33,8 @@ func Patch(node *Node, newNode Node) {

// base is a base struct for all nodes.
type base struct {
loc file.Location
nodeType reflect.Type
loc file.Location
nature types.Nature
}

// Location returns the location of the node in the source code.
Expand All @@ -39,14 +47,36 @@ func (n *base) SetLocation(loc file.Location) {
n.loc = loc
}

// Nature returns the nature of the node.
func (n *base) Nature() types.Nature {
return n.nature
}

// SetNature sets the nature of the node.
func (n *base) SetNature(nature types.Nature) {
n.nature = nature
}

// Kind returns the kind of the node.
// If the type is nil (meaning unknown) then it returns reflect.Interface.
func (n *base) Kind() reflect.Kind {
if n.nature.Type == nil {
return reflect.Interface
}
return n.nature.Type.Kind()
}

// Type returns the type of the node.
func (n *base) Type() reflect.Type {
return n.nodeType
if n.nature.Type == nil {
return anyType
}
return n.nature.Type
}

// SetType sets the type of the node.
func (n *base) SetType(t reflect.Type) {
n.nodeType = t
n.nature.Type = t
}

// NilNode represents nil.
Expand Down
2 changes: 1 addition & 1 deletion builtin/builtin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ func TestBuiltin_errors(t *testing.T) {
{`bitushr(-5, -2)`, "invalid operation: negative shift count -2 (type int) (1:1)"},
{`now(nil)`, "invalid number of arguments (expected 0, got 1)"},
{`date(nil)`, "interface {} is nil, not string (1:1)"},
{`timezone(nil)`, "interface {} is nil, not string (1:1)"},
{`timezone(nil)`, "cannot use nil as argument (type string) to call timezone (1:10)"},
}
for _, test := range errorTests {
t.Run(test.input, func(t *testing.T) {
Expand Down
Loading

0 comments on commit 9de0701

Please sign in to comment.