Skip to content

Commit 6ab4f36

Browse files
authored
Merge pull request #76441 from vincentisambart/macro-decl-format
[SourceKit] Format macro decl without crashing
2 parents 576dfca + 93c0673 commit 6ab4f36

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

lib/IDE/Formatting.cpp

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1414,6 +1414,12 @@ class FormatWalker : public ASTWalker {
14141414
// interpolated string literal.
14151415
if (E->getArgs() == Args)
14161416
ContextLoc = getContextLocForArgs(SM, E);
1417+
} else if (auto *D = Parent.getAsDecl()) {
1418+
if (auto *MED = dyn_cast<MacroExpansionDecl>(D)) {
1419+
if (MED->getArgs() == Args) {
1420+
ContextLoc = MED->getStartLoc();
1421+
}
1422+
}
14171423
}
14181424

14191425
auto Action = HandlePre(Args, Args->isImplicit());
@@ -2700,10 +2706,17 @@ class FormatWalker : public ASTWalker {
27002706
if (TrailingTarget)
27012707
return std::nullopt;
27022708

2703-
auto *ParentE = Parent.getAsExpr();
2704-
assert(ParentE && "Trailing closures can only occur in expr contexts");
2705-
return IndentContext{
2706-
ContextLoc, !OutdentChecker::hasOutdent(SM, ContextToEnd, ParentE)};
2709+
bool hasOutdent;
2710+
if (auto *ParentE = Parent.getAsExpr()) {
2711+
hasOutdent = OutdentChecker::hasOutdent(SM, ContextToEnd, ParentE);
2712+
} else if (auto *ParentD = Parent.getAsDecl()) {
2713+
assert(isa<MacroExpansionDecl>(ParentD) && "Trailing closures in decls can only occur in macro expansions");
2714+
hasOutdent = OutdentChecker::hasOutdent(SM, ContextToEnd, ParentD);
2715+
} else {
2716+
assert(false && "Trailing closures can only occur in expr contexts and macro expansions");
2717+
return std::nullopt;
2718+
}
2719+
return IndentContext{ContextLoc, !hasOutdent};
27072720
}
27082721

27092722
std::optional<IndentContext>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
@available(iOS 17, *)
2+
#Preview("") {
3+
UIView()
4+
}
5+
6+
// RUN: %sourcekitd-test -req=format -line=3 -length=1 %s >%t.response
7+
// RUN: %FileCheck --strict-whitespace %s <%t.response
8+
9+
// CHECK: key.sourcetext: " UIView()"

0 commit comments

Comments
 (0)