Skip to content

Commit 847bab6

Browse files
ddddxxxharlanhaskins
authored andcommitted
fix: wrongly dispose unowned translation unit
1 parent 3780c73 commit 847bab6

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

Sources/Clang/Cursor.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ extension Cursor {
197197

198198
/// Returns the translation unit that a cursor originated from.
199199
public var translationUnit: TranslationUnit {
200-
return TranslationUnit(clang: clang_Cursor_getTranslationUnit(asClang()))
200+
return TranslationUnit(clang: clang_Cursor_getTranslationUnit(asClang()), owned: false)
201201
}
202202

203203
/// Retrieves all the children of the provided cursor.

Sources/Clang/TranslationUnit.swift

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,9 +126,11 @@ public struct TranslationUnitSaveOptions: OptionSet {
126126

127127
public class TranslationUnit {
128128
let clang: CXTranslationUnit
129+
private let owned: Bool
129130

130-
init(clang: CXTranslationUnit) {
131+
init(clang: CXTranslationUnit, owned: Bool) {
131132
self.clang = clang
133+
self.owned = owned
132134
}
133135

134136

@@ -162,6 +164,7 @@ public class TranslationUnit {
162164
}
163165
return unit!
164166
}
167+
self.owned = true
165168
}
166169

167170
/// Creates a `TranslationUnit` by parsing the source code passed,
@@ -236,6 +239,7 @@ public class TranslationUnit {
236239
}
237240

238241
self.clang = unit!
242+
self.owned = true
239243
}
240244

241245
/// Retrieve the cursor that represents the given translation unit.
@@ -471,6 +475,8 @@ public class TranslationUnit {
471475
}
472476

473477
deinit {
474-
clang_disposeTranslationUnit(clang)
478+
if owned {
479+
clang_disposeTranslationUnit(clang)
480+
}
475481
}
476482
}

Tests/ClangTests/ClangTests.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,19 @@ class ClangTests: XCTestCase {
235235
XCTFail("\(error)")
236236
}
237237
}
238+
239+
func testDisposeTranslateUnit() {
240+
do {
241+
let filename = "input_tests/init-ast.c"
242+
let unit = try TranslationUnit(filename: filename)
243+
let cursor = unit.cursor
244+
for _ in 0..<2 {
245+
_ = cursor.translationUnit
246+
}
247+
} catch {
248+
XCTFail("\(error)")
249+
}
250+
}
238251

239252
static var allTests : [(String, (ClangTests) -> () throws -> Void)] {
240253
return [

0 commit comments

Comments
 (0)