Skip to content

Commit

Permalink
evaluating if statements!!
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonak-Adipta-Kalita committed Apr 8, 2023
1 parent a26f2f5 commit be8b61c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
32 changes: 30 additions & 2 deletions evaluator/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var (
func Eval(node ast.Node) object.Object {
switch node := node.(type) {
case *ast.Program:
return evalStatements(node.Statements)
return evalProgram(node)
case *ast.ExpressionStatement:
return Eval(node.Expression)
case *ast.PrefixExpression:
Expand All @@ -25,9 +25,12 @@ func Eval(node ast.Node) object.Object {
right := Eval(node.Right)
return evalInfixExpression(node.Operator, left, right)
case *ast.BlockStatement:
return evalStatements(node.Statements)
return evalBlockStatement(node)
case *ast.IfExpression:
return evalIfExpression(node)
case *ast.ReturnStatement:
val := Eval(node.ReturnValue)
return &object.ReturnValue{Value: val}

case *ast.IntegerLiteral:
return &object.Integer{Value: node.Value}
Expand All @@ -37,10 +40,35 @@ func Eval(node ast.Node) object.Object {
return nil
}

func evalProgram(program *ast.Program) object.Object {
var result object.Object
for _, statement := range program.Statements {
result = Eval(statement)
if returnValue, ok := result.(*object.ReturnValue); ok {
return returnValue.Value
}
}
return result
}

func evalBlockStatement(block *ast.BlockStatement) object.Object {
var result object.Object
for _, statement := range block.Statements {
result = Eval(statement)
if result != nil && result.Type() == object.RETURN_VALUE_OBJ {
return result
}
}
return result
}

func evalStatements(stmts []ast.Statement) object.Object {
var result object.Object
for _, statement := range stmts {
result = Eval(statement)
if returnValue, ok := result.(*object.ReturnValue); ok {
return returnValue.Value
}
}
return result
}
Expand Down
14 changes: 11 additions & 3 deletions object/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ type Object interface {
}

const (
INTEGER_OBJ = "INTEGER"
BOOLEAN_OBJ = "BOOLEAN"
NULL_OBJ = "NULL"
INTEGER_OBJ = "INTEGER"
BOOLEAN_OBJ = "BOOLEAN"
NULL_OBJ = "NULL"
RETURN_VALUE_OBJ = "RETURN_VALUE"
)

type Boolean struct {
Expand All @@ -33,3 +34,10 @@ type Null struct{}

func (n *Null) Type() ObjectType { return NULL_OBJ }
func (n *Null) Inspect() string { return "null" }

type ReturnValue struct {
Value Object
}

func (rv *ReturnValue) Type() ObjectType { return RETURN_VALUE_OBJ }
func (rv *ReturnValue) Inspect() string { return rv.Value.Inspect() }

0 comments on commit be8b61c

Please sign in to comment.