Skip to content

Commit

Permalink
refactor(eval): improve switch case readability (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
vit0rr authored Oct 5, 2024
1 parent 9fea90c commit a011897
Showing 1 changed file with 36 additions and 21 deletions.
57 changes: 36 additions & 21 deletions evaluator/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,47 @@ var (

func Eval(node ast.Node, env *object.Environment) object.Object {
switch node := node.(type) {
// Statements
case *ast.Program:
return evalProgram(node, env)
case *ast.ExpressionStatement:
return Eval(node.Expression, env)
case *ast.Boolean:
return nativeBoolToBooleanObject(node.Value)
case *ast.PrefixExpression:
right := Eval(node.Right, env)
if isError(right) {
return right
}
return evalPrefixExpression(node.Operator, right)

case *ast.BlockStatement:
return evalBlockStatement(node, env)
case *ast.IfExpression:
return evalIfExpression(node, env)

case *ast.ExpressionStatement:
return Eval(node.Expression, env)

case *ast.ReturnStatement:
val := Eval(node.ReturnValue, env)
if isError(val) {
return val
}
return &object.ReturnValue{Value: val}

case *ast.LetStatement:
val := Eval(node.Value, env)
if isError(val) {
return val
}
env.Set(node.Name.Value, val)

// Expressions
case *ast.IntegerLiteral:
return &object.Integer{Value: node.Value}

case *ast.StringLiteral:
return &object.String{Value: node.Value}

case *ast.Boolean:
return nativeBoolToBooleanObject(node.Value)

case *ast.PrefixExpression:
right := Eval(node.Right, env)
if isError(right) {
return right
}
return evalPrefixExpression(node.Operator, right)

case *ast.InfixExpression:
left := Eval(node.Left, env)
if isError(left) {
Expand All @@ -49,31 +66,29 @@ func Eval(node ast.Node, env *object.Environment) object.Object {
return right
}
return evalInfixExpression(node.Operator, left, right)
case *ast.LetStatement:
val := Eval(node.Value, env)
if isError(val) {
return val
}
env.Set(node.Name.Value, val)

case *ast.IfExpression:
return evalIfExpression(node, env)

case *ast.Identifier:
return evalIdentifier(node, env)

case *ast.FunctionLiteral:
params := node.Parameters
body := node.Body
return &object.Function{Parameters: params, Body: body, Env: env}

case *ast.CallExpression:
function := Eval(node.Function, env)
if isError(function) {
return function
}

args := evalExpressions(node.Arguments, env)
if len(args) == 1 && isError(args[0]) {
return args[0]
}

return applyFunction(function, args)
case *ast.StringLiteral:
return &object.String{Value: node.Value}
}

return nil
Expand Down

0 comments on commit a011897

Please sign in to comment.