Skip to content

Commit

Permalink
Add test to try to expose #24 bug
Browse files Browse the repository at this point in the history
  • Loading branch information
mattmassicotte committed Jul 3, 2024
1 parent e06be7d commit f46c79e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 19 deletions.
44 changes: 25 additions & 19 deletions Sources/SwiftTreeSitter/Input.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,28 +46,34 @@ final class Input {
}
}

private func readFunction(payload: UnsafeMutableRawPointer?, byteIndex: UInt32, position: TSPoint, bytesRead: UnsafeMutablePointer<UInt32>?) -> UnsafePointer<Int8>? {
// get our self reference
let wrapper: Input = Unmanaged.fromOpaque(payload!).takeUnretainedValue()
private func readFunction(
payload: UnsafeMutableRawPointer?,
byteIndex: UInt32,
position: TSPoint,
bytesRead: UnsafeMutablePointer<UInt32>?
) -> UnsafePointer<Int8>? {
// get our self reference
let wrapper: Input = Unmanaged.fromOpaque(payload!).takeUnretainedValue()

// call our Swift-friendly reader block, or early out if there's no data to copy.
guard let data = wrapper.readBlock(Int(byteIndex), Point(internalPoint: position)),
data.count > 0
else
{
bytesRead?.pointee = 0
return nil
}
// call our Swift-friendly reader block, or early out if there's no data to copy.
guard
let data = wrapper.readBlock(Int(byteIndex), Point(internalPoint: position)),
data.count > 0
else
{
bytesRead?.pointee = 0
return nil
}

// copy the data into an internally-managed buffer with a lifetime of wrapper
let buffer = Input.Buffer.allocate(capacity: data.count)
let copiedLength = data.copyBytes(to: buffer)
precondition(copiedLength == data.count)
// copy the data into an internally-managed buffer with a lifetime of wrapper
let buffer = Input.Buffer.allocate(capacity: data.count)
let copiedLength = data.copyBytes(to: buffer)
precondition(copiedLength == data.count)

wrapper.buffer = buffer
wrapper.buffer = buffer

// return to the caller
bytesRead?.pointee = UInt32(buffer.count)
// return to the caller
bytesRead?.pointee = UInt32(buffer.count)

return wrapper.bufferPointer
return wrapper.bufferPointer
}
14 changes: 14 additions & 0 deletions Tests/SwiftTreeSitterTests/ParserTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,17 @@ func main😃😃() {
}
#endif
}

extension ParserTests {
// Attempt to expose the bug introduced by https://github.com/ChimeHQ/SwiftTreeSitter/pull/24
func testReadEmptyData() throws {
let language = Language(language: tree_sitter_swift())

let parser = Parser()
try parser.setLanguage(language)

let _ = parser.parse(tree: Tree?.none, readBlock: { _, _ in
return nil
})
}
}

0 comments on commit f46c79e

Please sign in to comment.