Skip to content

Commit

Permalink
Merge pull request #26 from quephird/cannot_initialize_an_empty_list
Browse files Browse the repository at this point in the history
Addressed bug in parser and added supporting tests.
  • Loading branch information
quephird committed Mar 22, 2024
2 parents f186e05 + 7f7af93 commit 7c68a60
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
8 changes: 4 additions & 4 deletions slox/Parser.swift
Expand Up @@ -552,7 +552,7 @@ struct Parser {
return nil
}

let args = try parseArguments()
let args = try parseArguments(endTokenType: .rightParen)

guard currentTokenMatchesAny(types: [.rightParen]) else {
throw ParseError.missingCloseParenAfterArguments(currentToken)
Expand Down Expand Up @@ -662,7 +662,7 @@ struct Parser {
return nil
}

let elements = try parseArguments()
let elements = try parseArguments(endTokenType: .rightBracket)

guard currentTokenMatchesAny(types: [.rightBracket]) else {
throw ParseError.missingClosingBracket(previousToken)
Expand Down Expand Up @@ -728,9 +728,9 @@ struct Parser {
return parameters
}

mutating private func parseArguments() throws -> [Expression] {
mutating private func parseArguments(endTokenType: TokenType) throws -> [Expression] {
var args: [Expression] = []
if currentToken.type != .rightParen {
if currentToken.type != endTokenType {
repeat {
let newArg = try parseExpression()
args.append(newArg)
Expand Down
12 changes: 12 additions & 0 deletions sloxTests/InterpreterTests.swift
Expand Up @@ -467,6 +467,18 @@ baz[1][1]
XCTAssertEqual(actual, expected)
}

func testInterpretCreateAnEmptyList() throws {
let input = """
var quux = [];
quux.count
"""

let interpreter = Interpreter()
let actual = try interpreter.interpretRepl(source: input)
let expected: LoxValue = .number(0)
XCTAssertEqual(actual, expected)
}

func testInterpretExpressionWithListSubscriptingMethodInvocationAndPropertyGetting() throws {
let input = """
class Foo { }
Expand Down
18 changes: 18 additions & 0 deletions sloxTests/ParserTests.swift
Expand Up @@ -1215,4 +1215,22 @@ final class ParserTests: XCTestCase {
XCTAssertEqual(actualError as! ParseError, expectedError)
}
}

func testParseAnEmptyList() throws {
// [ ]
let tokens: [Token] = [
Token(type: .leftBracket, lexeme: "[", line: 1),
Token(type: .rightBracket, lexeme: "]", line: 1),
Token(type: .eof, lexeme: "", line: 1)
]

var parser = Parser(tokens: tokens)
let actual = try parser.parse()
let expected: [Statement] = [
.expression(
.list([
]))
]
XCTAssertEqual(actual, expected)
}
}

0 comments on commit 7c68a60

Please sign in to comment.