Strings
Some checks failed
Build / build (push) Failing after 1m35s
Test / build (push) Failing after 1m31s

This commit is contained in:
Chuck Smith
2024-02-21 16:29:53 -05:00
parent 8caeaca559
commit e4bca02235
5 changed files with 189 additions and 5 deletions

View File

@@ -190,6 +190,10 @@ func (c *Compiler) Compile(node ast.Node) error {
c.emit(code.OpGetGlobal, symbol.Index)
case *ast.StringLiteral:
str := &object.String{Value: node.Value}
c.emit(code.OpConstant, c.addConstant(str))
}
return nil

View File

@@ -277,6 +277,31 @@ func TestGlobalLetStatements(t *testing.T) {
runCompilerTests(t, tests)
}
func TestStringExpressions(t *testing.T) {
tests := []compilerTestCase{
{
input: `"monkey"`,
expectedConstants: []interface{}{"monkey"},
expectedInstructions: []code.Instructions{
code.Make(code.OpConstant, 0),
code.Make(code.OpPop),
},
},
{
input: `"mon" + "key"`,
expectedConstants: []interface{}{"mon", "key"},
expectedInstructions: []code.Instructions{
code.Make(code.OpConstant, 0),
code.Make(code.OpConstant, 1),
code.Make(code.OpAdd),
code.Make(code.OpPop),
},
},
}
runCompilerTests(t, tests)
}
func runCompilerTests(t *testing.T, tests []compilerTestCase) {
t.Helper()
@@ -347,6 +372,12 @@ func testConstants(t *testing.T, expected []interface{}, actual []object.Object)
if err != nil {
return fmt.Errorf("constant %d = testIntegerObject failed : %s", i, err)
}
case string:
err := testStringObject(constant, actual[i])
if err != nil {
return fmt.Errorf("constant %d = testStringObject failed : %s", i, err)
}
}
}
return nil
@@ -364,3 +395,16 @@ func testIntegerObject(expected int64, actual object.Object) interface{} {
return nil
}
func testStringObject(expected string, actual object.Object) error {
result, ok := actual.(*object.String)
if !ok {
return fmt.Errorf("object is not String. got %T (%+v", actual, actual)
}
if result.Value != expected {
return fmt.Errorf("object has wrong value. got=%q, want=%q", result.Value, expected)
}
return nil
}