Skip to content

Commit

Permalink
Fixed crash when inline function has out of bound indexes (#1342)
Browse files Browse the repository at this point in the history
  • Loading branch information
art-divin authored Jun 8, 2024
1 parent 418ebbe commit 7629411
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
8 changes: 6 additions & 2 deletions SourceryFramework/Sources/Parsing/Utils/StringView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -392,8 +392,12 @@ public struct StringView {
- returns: An equivalent `NSRange`.
*/
public func NSRangeToByteRange(start: Int, length: Int) -> ByteRange? {
let startUTF16Index = utf16View.index(utf16View.startIndex, offsetBy: start)
let endUTF16Index = utf16View.index(startUTF16Index, offsetBy: length)
guard
let startUTF16Index = utf16View.index(utf16View.startIndex, offsetBy: start, limitedBy: utf16View.endIndex),
let endUTF16Index = utf16View.index(startUTF16Index, offsetBy: length, limitedBy: utf16View.endIndex)
else {
return nil
}

guard let startUTF8Index = startUTF16Index.samePosition(in: utf8View),
let endUTF8Index = endUTF16Index.samePosition(in: utf8View) else {
Expand Down
45 changes: 45 additions & 0 deletions SourceryTests/SourcerySpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,51 @@ class SourcerySpecTests: QuickSpec {
expect(result).to(equal(expectedResult))
}

it("replaces inline contents without crashing") {
update(code: """
struct MyStruct {
// sourcery:inline:MyStruct.Inlined
// This will be replaced
// sourcery:end
// sourcery:inline:MyStruct.Inlined.Foo
// sourcery: stub = "A"
let basic: String;
// sourcery: stub = "B"
let caseProperty: String;
// sourcery: stub = "C"
let casesProperty: String;
// sourcery: stub = "D"
let CaseProperty: String;
// sourcery:end
}
""", in: sourcePath)
update(code: """
// sourcery:inline:MyStruct.Inlined
{% for type in types.all %}
{% for variable in type.storedVariables %}
let {{ variable.name }}XXX = "{{ variable.annotations["stub"] }}";
{% endfor %}
{% endfor %}
// sourcery:end
// sourcery:inline:MyStruct.Inlined.Foo
// sourcery:end
""", in: templatePath)

expect { try Sourcery(watcherEnabled: false, cacheDisabled: true).processFiles(.sources(Paths(include: [sourcePath])), usingTemplates: Paths(include: [templatePath]), output: output, baseIndentation: 0) }.toNot(throwError())

let expectedResult = """
struct MyStruct {
// sourcery:inline:MyStruct.Inlined
// sourcery:end
// sourcery:inline:MyStruct.Inlined.Foo
// sourcery:end
}
"""

let result = try? sourcePath.read(.utf8)
expect(result).to(equal(expectedResult))
}

it("handles previously generated code with UTF16 characters") {
update(code: """
class A {
Expand Down

0 comments on commit 7629411

Please sign in to comment.