Skip to content

Commit

Permalink
read symbols from environments in eval (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
JunNishimura committed Sep 28, 2024
1 parent 67499df commit aa3c84e
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
9 changes: 7 additions & 2 deletions evaluator/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func Eval(exp ast.Expression, env *object.Environment) object.Object {
}
return evalPrefixAtom(expt.Operator, right)
case *ast.Symbol:
return evalSymbol(expt)
return evalSymbol(expt, env)
case *ast.CommandObject:
return evalCommandObject(expt, env)
case *ast.IfExpression:
Expand Down Expand Up @@ -102,12 +102,17 @@ func evalExclamationPrefix(right object.Object) object.Object {
}
}

func evalSymbol(symbol *ast.Symbol) object.Object {
func evalSymbol(symbol *ast.Symbol, env *object.Environment) object.Object {
builtintFunc, ok := builtins[symbol.Value]
if ok {
return builtintFunc
}

obj, ok := env.Get(symbol.Value)
if ok {
return obj
}

return newError("symbol not found: %s", symbol.Value)
}

Expand Down
58 changes: 58 additions & 0 deletions evaluator/evaluator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,3 +399,61 @@ func TestSetExpression(t *testing.T) {
})
}
}

func TestMultipleExpressions(t *testing.T) {
tests := []struct {
name string
input string
expected int64
}{
{
name: "multiple atoms",
input: `
[
1,
2
]`,
expected: 2,
},
{
name: "multiple commands",
input: `
[
{
"command": {
"symbol": "+",
"args": [1, 2]
}
},
{
"command": {
"symbol": "-",
"args": [1, 2]
}
}
]`,
expected: -1,
},
{
name: "multiple commands with set expression",
input: `
[
{
"set": {
"var": "$x",
"val": 10
}
},
"$x"
]`,
expected: 10,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
evaluated := testEval(t, tt.input)
testIntegerObject(t, evaluated, tt.expected)
})
}
}

0 comments on commit aa3c84e

Please sign in to comment.