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 6007af2
Show file tree
Hide file tree
Showing 28 changed files with 1,200 additions and 901 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/nature"
)

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

// Node represents items of abstract syntax tree.
type Node interface {
Location() file.Location
SetLocation(file.Location)
Nature() nature.Nature
SetNature(nature.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 nature.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() nature.Nature {
return n.nature
}

// SetNature sets the nature of the node.
func (n *base) SetNature(nature nature.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 6007af2

Please sign in to comment.