Skip to content

Commit

Permalink
Fix crash with missing parameter (#130)
Browse files Browse the repository at this point in the history
  • Loading branch information
b-nassler authored Mar 20, 2024
1 parent 38e3144 commit f6a08a1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
32 changes: 22 additions & 10 deletions Sources/LeafKit/LeafParser/LeafParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -183,13 +183,20 @@ internal struct LeafParser {

var group = [ParameterDeclaration]()
var paramsList = [ParameterDeclaration]()

func dump() {
defer { group = [] }
if group.isEmpty { return }
group.evaluate()
if group.count > 1 { paramsList.append(.expression(group)) }
else { paramsList.append(group.first!) }

func dump() throws {
defer { group = [] }
if group.isEmpty { return }
group.evaluate()
if group.count > 1 { paramsList.append(.expression(group)) }
else {
guard let first = group.first else {
// It's better to handle this case as well, even though logically it might never happen
// since you're checking if group.isEmpty before.
throw LeafError(.unknownError("Found nil while iterating through params"), file: #file, function: #function, line: #line, column: #column)
}
paramsList.append(first)
}
}

outer: while let next = peek() {
Expand All @@ -200,7 +207,12 @@ internal struct LeafParser {
let params = try readParameters()
// parameter tags not permitted to have bodies
if params.count > 1 { group.append(.expression(params)) }
else { group.append(params.first!) }
else {
guard let firstParam = params.first else {
throw LeafError(.unknownError("Found nil while iterating through params"))
}
group.append(firstParam)
}
case .parameter(let p):
pop()
switch p {
Expand All @@ -214,11 +226,11 @@ internal struct LeafParser {
}
case .parametersEnd:
pop()
dump()
try dump()
break outer
case .parameterDelimiter:
pop()
dump()
try dump()
case .whitespace:
pop()
continue
Expand Down
17 changes: 17 additions & 0 deletions Tests/LeafKitTests/LeafErrorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,21 @@ final class LeafErrorTests: XCTestCase {
XCTFail("Wrong error: \(error.localizedDescription)")
}
}

/// Verify that rendering a template with a missing required parameter will throw `LeafError.missingParameter`
func testMissingParameterError() {
var test = TestFiles()
// Assuming "/missingParam.leaf" is a template that requires a parameter we intentionally don't provide
test.files["/missingParam.leaf"] = """
#(foo.bar.trim())
"""
XCTAssertThrowsError(try TestRenderer(sources: .singleSource(test))
.render(path: "missingParam", context: [:])
.wait()
) {
guard case .unknownError("Found nil while iterating through params") = ($0 as? LeafError)?.reason else {
return XCTFail("Expected LeafError.unknownError(\"Found nil while iterating through params\"), got \(String(reflecting: $0))")
}
}
}
}

0 comments on commit f6a08a1

Please sign in to comment.