Skip to content

Commit 6a31007

Browse files
committed
Ensure that the source buffer passed to #if evaluation contains the condition
The implementation of `#if` configuration evaluation assumed that the SourceFile instance within the `Parser` contained all of the source ranges for code parsed within that `Parser` instance. This is not always the case, so avoid using the SourceFile directly and instead use the source buffer that directly contains the condition. Fixes swiftlang#76137. Big thank you to Alex Hoppen and the stress tester for finding this.
1 parent 225e562 commit 6a31007

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

lib/Sema/TypeChecker.cpp

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -781,11 +781,16 @@ std::pair<bool, bool> EvaluateIfConditionRequest::evaluate(
781781
// FIXME: When we migrate to SwiftParser, use the parsed syntax tree.
782782
ASTContext &ctx = sourceFile->getASTContext();
783783
auto &sourceMgr = ctx.SourceMgr;
784-
StringRef sourceFileText =
785-
sourceMgr.getEntireTextForBuffer(*sourceFile->getBufferID());
786-
StringRef conditionText =
787-
sourceMgr.extractText(Lexer::getCharSourceRangeFromSourceRange(
788-
sourceMgr, conditionRange));
784+
785+
// Extract the full buffer containing the condition.
786+
auto bufferID = sourceMgr.findBufferContainingLoc(conditionRange.Start);
787+
StringRef sourceFileText = sourceMgr.getEntireTextForBuffer(bufferID);
788+
789+
// Extract the condition text from that buffer.
790+
auto conditionCharRange = Lexer::getCharSourceRangeFromSourceRange(sourceMgr, conditionRange);
791+
StringRef conditionText = sourceMgr.extractText(conditionCharRange, bufferID);
792+
793+
// Evaluate the condition.
789794
intptr_t evalResult = swift_ASTGen_evaluatePoundIfCondition(
790795
ctx, &ctx.Diags, sourceFileText, conditionText, shouldEvaluate
791796
);
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
var description: String {
2+
3+
func test() {}
4+
5+
#if compiler()
6+
#endif
7+
8+
9+
// RUN: %sourcekitd-test -req=conformingmethods -pos=3:6 -repeat-request=2 %s -- %s
10+

0 commit comments

Comments
 (0)