Skip to content

Commit 90374a7

Browse files
committed
[SyntaxParse] Fix memory leak
1 parent f0395a4 commit 90374a7

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

include/swift/Parse/HiddenLibSyntaxAction.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ class HiddenLibSyntaxAction : public SyntaxParseActions {
6161
/// been created by the explicit action.
6262
OpaqueSyntaxNode getLibSyntaxNodeFor(OpaqueSyntaxNode explicitNode);
6363

64+
bool isReleaseNeeded() {
65+
return ExplicitAction == LibSyntaxAction || !areBothLibSyntax();
66+
}
67+
6468
/// Returns the underlying libSyntax SyntaxTreeCreator.
6569
std::shared_ptr<SyntaxTreeCreator> getLibSyntaxAction() {
6670
return LibSyntaxAction;

include/swift/Parse/LibSyntaxGenerator.h

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@ class LibSyntaxGenerator {
5555
auto Children = Node.getDeferredChildren();
5656

5757
auto Recorded = Recorder.recordRawSyntax(Kind, Children);
58-
auto Raw = static_cast<RawSyntax *>(Recorded.getOpaqueNode());
58+
RC<RawSyntax> Raw {static_cast<RawSyntax *>(Recorded.getOpaqueNode()) };
59+
Raw->Release(); // -1 since it's transfer of ownership.
5960
return make<SyntaxNode>(Raw);
6061
}
6162

@@ -68,6 +69,13 @@ class LibSyntaxGenerator {
6869
auto Raw = static_cast<RawSyntax *>(Actions->getLibSyntaxNodeFor(Node));
6970
return make<SyntaxNode>(Raw);
7071
}
72+
73+
void releaseLibSyntaxNodeIfNeededFor(OpaqueSyntaxNode Node) {
74+
if (!Actions->isReleaseNeeded())
75+
return;
76+
auto Raw = static_cast<RawSyntax *>(Actions->getLibSyntaxNodeFor(Node));
77+
Raw->Release();
78+
}
7179
};
7280
} // namespace swift
7381

lib/Parse/SyntaxParsingContext.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,7 @@ ParsedRawSyntaxNode SyntaxParsingContext::finalizeRoot() {
280280
return ParsedRawSyntaxNode::null(); // already finalized.
281281
}
282282
ParsedRawSyntaxNode root = finalizeSourceFile();
283+
getSyntaxCreator().releaseLibSyntaxNodeIfNeededFor(root.getOpaqueNode());
283284

284285
// Clear the parts because we will call this function again when destroying
285286
// the root context.
@@ -353,6 +354,10 @@ SyntaxParsingContext::~SyntaxParsingContext() {
353354
// Remove all parts in this context.
354355
case AccumulationMode::Discard: {
355356
auto &nodes = getStorage();
357+
for (auto i = nodes.begin()+Offset, e = nodes.end(); i != e; ++i)
358+
if (i->isRecorded())
359+
getSyntaxCreator().releaseLibSyntaxNodeIfNeededFor(i->getOpaqueNode());
360+
356361
nodes.erase(nodes.begin()+Offset, nodes.end());
357362
break;
358363
}

0 commit comments

Comments
 (0)