Skip to content

Commit

Permalink
feat: interpret callable values
Browse files Browse the repository at this point in the history
  • Loading branch information
silverhairs committed Aug 20, 2023
1 parent 1921d25 commit 864e8d2
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion glox/ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ func parenthesize(name ExpType, value string) string {

out.WriteString("(" + string(name) + " ")
out.WriteString(value)
out.WriteString(" )")
out.WriteString(")")

return out.String()
}
Expand Down
36 changes: 36 additions & 0 deletions glox/interpreter/interpreter.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"glox/ast"
"glox/env"
"glox/exception"
"glox/object"
"glox/token"
"io"
"math"
Expand Down Expand Up @@ -319,6 +320,41 @@ func (i *Interpreter) VisitWhile(exp *ast.WhileStmt) any {
return nil
}

func (i *Interpreter) VisitCall(expr *ast.Call) any {
calle := i.evaluate(expr.Callee)
err, isErr := calle.(error)
if !isErr {
args := []any{}
for _, arg := range expr.Args {
val := i.evaluate(arg)
if err, isErr = val.(error); isErr {
break
}
args = append(args, val)
}
if err != nil {
return err
}
function, isOk := calle.(object.Callable[*Interpreter])
if !isOk {
return exception.Runtime(expr.Paren, fmt.Sprintf("'%v' cannot be called.", expr.Callee.String()))
} else if function.Arity() != len(args) {
want, got := function.Arity(), len(args)
var msg string
if got > want {
msg = fmt.Sprintf("too many arguments passed. expected %d but got %d.", want, got)
} else {
msg = fmt.Sprintf("not enough arguments passed. expected %d but got %d.", want, got)
}
return exception.Runtime(expr.Paren, msg)
}
return function.Call(i, args)
}

return err

}

func (i *Interpreter) execLoop(loop *ast.WhileStmt) (res any, err error) {
//FIXME: The `continue` statement doesn't seem to work as expected.
defer func() {
Expand Down
6 changes: 6 additions & 0 deletions glox/object/object.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package object

type Callable[T any] interface {
Call(i T, arguments []any) any
Arity() int
}

0 comments on commit 864e8d2

Please sign in to comment.