Skip to content

Commit

Permalink
Introduced helper in Interpreter to reduce duplication, and fortifi…
Browse files Browse the repository at this point in the history
…ed supporting unit test.
  • Loading branch information
quephird committed Mar 23, 2024
1 parent 2e7ddca commit 2c69877
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
24 changes: 11 additions & 13 deletions slox/Interpreter.swift
Expand Up @@ -387,13 +387,8 @@ class Interpreter {
if case .instance(let leftList as LoxList) = leftValue,
case .instance(let rightList as LoxList) = rightValue,
case .plus = oper.type {
guard case .instance(let listClass as LoxClass) = try environment.getValue(name: "List") else {
fatalError()
}

let newElements = leftList.elements + rightList.elements
let list = LoxList(elements: newElements, klass: listClass)
return .instance(list)
return try makeList(elements: newElements)
}

switch oper.type {
Expand Down Expand Up @@ -530,13 +525,7 @@ class Interpreter {
return try evaluate(expr: element)
}

guard case .instance(let listClass as LoxClass) = try environment.getValue(name: "List") else {
// TODO: Do we need throw an exception here?
fatalError()
}

let list = LoxList(elements: elementValues, klass: listClass)
return .instance(list)
return try makeList(elements: elementValues)
}

private func handleSubscriptGetExpression(listExpr: ResolvedExpression,
Expand Down Expand Up @@ -568,4 +557,13 @@ class Interpreter {
list[Int(index)] = value
return value
}

private func makeList(elements: [LoxValue]) throws -> LoxValue {
guard case .instance(let listClass as LoxClass) = try environment.getValue(name: "List") else {
fatalError()
}

let list = LoxList(elements: elements, klass: listClass)
return .instance(list)
}
}
17 changes: 14 additions & 3 deletions sloxTests/InterpreterTests.swift
Expand Up @@ -482,12 +482,23 @@ quux.count
func testInterpretAddingTwoLists() throws {
let input = """
var xyzzy = [1, 2, 3] + [4, 5, 6];
xyzzy.count
xyzzy
"""

let interpreter = Interpreter()
let actual = try interpreter.interpretRepl(source: input)
let expected: LoxValue = .number(6)
guard case .instance(let list as LoxList) = try interpreter.interpretRepl(source: input) else {
XCTFail()
return
}
let actual = list.elements
let expected: [LoxValue] = [
.number(1),
.number(2),
.number(3),
.number(4),
.number(5),
.number(6),
]
XCTAssertEqual(actual, expected)
}

Expand Down

0 comments on commit 2c69877

Please sign in to comment.