Skip to content

Commit 80d2712

Browse files
committed
[Macros] Do not edit macro buffer or position when refactoring
Rather than editing the macro buffer in refactoring, add appropriate padding and braces when creating the macro. Don't edit the insertion location - we should update this in a later PR as well.
1 parent 2a7aa37 commit 80d2712

File tree

5 files changed

+54
-92
lines changed

5 files changed

+54
-92
lines changed

lib/AST/Decl.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6113,10 +6113,10 @@ void AbstractStorageDecl::setAccessors(SourceLoc lbraceLoc,
61136113
ArrayRef<AccessorDecl *> accessors,
61146114
SourceLoc rbraceLoc) {
61156115
// This method is called after we've already recorded an accessors clause
6116-
// only on recovery paths and only when that clause was empty.
6116+
// only on recovery paths and only when that clause was empty, or when a
6117+
// macro expands to accessors (in which case, we may already have accessors).
61176118
auto record = Accessors.getPointer();
61186119
if (record) {
6119-
assert(record->getAllAccessors().empty());
61206120
for (auto accessor : accessors) {
61216121
(void) record->addOpaqueAccessor(accessor);
61226122
}

lib/ASTGen/Sources/ASTGen/Macros.swift

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -515,22 +515,7 @@ func expandAttachedMacro(
515515
}
516516

517517
// Fixup the source.
518-
var expandedSource: String
519-
switch MacroRole(rawValue: rawMacroRole)! {
520-
case .Accessor:
521-
expandedSource = expandedSources.joined(separator: "\n\n")
522-
case .Member:
523-
expandedSource = expandedSources.joined(separator: "\n\n")
524-
case .MemberAttribute:
525-
expandedSource = expandedSources.joined(separator: " ")
526-
case .Peer:
527-
expandedSource = expandedSources.joined(separator: "\n\n")
528-
case .Conformance:
529-
expandedSource = expandedSources.joined(separator: "\n\n")
530-
case .Expression,
531-
.FreestandingDeclaration:
532-
fatalError("unreachable")
533-
}
518+
var expandedSource: String = collapse(expansions: expandedSources, for: MacroRole(rawValue: rawMacroRole)!, attachedTo: declarationNode)
534519

535520
// Form the result buffer for our caller.
536521
expandedSource.withUTF8 { utf8 in
@@ -829,3 +814,44 @@ func expandAttachedMacroInProcess(
829814

830815
return expandedSources
831816
}
817+
818+
fileprivate func collapse<Node: SyntaxProtocol>(
819+
expansions: [String],
820+
for role: MacroRole,
821+
attachedTo declarationNode: Node
822+
) -> String {
823+
var separator: String = "\n\n"
824+
var prefix: String = ""
825+
var suffix: String = ""
826+
827+
switch role {
828+
case .Accessor:
829+
if let varDecl = declarationNode.as(VariableDeclSyntax.self),
830+
let binding = varDecl.bindings.first,
831+
binding.accessor == nil {
832+
prefix = "{\n"
833+
suffix = "\n}"
834+
}
835+
case .Member:
836+
prefix = "\n\n"
837+
suffix = "\n"
838+
case .MemberAttribute:
839+
separator = " "
840+
suffix = " "
841+
case .Peer:
842+
prefix = "\n\n"
843+
suffix = "\n"
844+
case .Conformance:
845+
prefix = "\n\n"
846+
suffix = "\n"
847+
case .Expression,
848+
.FreestandingDeclaration:
849+
fatalError("unreachable")
850+
}
851+
852+
let separated = expansions.joined(separator: separator)
853+
if separated.isEmpty {
854+
return separated
855+
}
856+
return prefix + separated + suffix
857+
}

lib/Parse/ParseDecl.cpp

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7082,11 +7082,13 @@ void Parser::parseTopLevelAccessors(
70827082
staticLoc = binding->getStaticLoc();
70837083
}
70847084

7085+
bool hadLBrace = consumeIf(tok::l_brace);
7086+
70857087
ParserStatus status;
70867088
ParsedAccessors accessors;
70877089
bool hasEffectfulGet = false;
70887090
bool parsingLimitedSyntax = false;
7089-
while (!Tok.is(tok::eof)) {
7091+
while (!Tok.isAny(tok::r_brace, tok::eof)) {
70907092
DeclAttributes attributes;
70917093
AccessorKind kind = AccessorKind::Get;
70927094
SourceLoc loc;
@@ -7100,6 +7102,10 @@ void Parser::parseTopLevelAccessors(
71007102
);
71017103
}
71027104

7105+
if (hadLBrace && Tok.is(tok::r_brace)) {
7106+
consumeToken(tok::r_brace);
7107+
}
7108+
71037109
// Consume remaining tokens.
71047110
// FIXME: Emit a diagnostic here?
71057111
while (!Tok.is(tok::eof)) {

lib/Refactoring/Refactoring.cpp

Lines changed: 1 addition & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -8617,51 +8617,6 @@ bool RefactoringActionExpandMacro::isApplicable(ResolvedCursorInfoPtr Info,
86178617
return !getMacroExpansionBuffers(Diag.SourceMgr, Info).empty();
86188618
}
86198619

8620-
/// Given the expanded code for a particular macro, perform whitespace
8621-
/// adjustments to make the refactoring more.
8622-
static StringRef adjustMacroExpansionWhitespace(
8623-
GeneratedSourceInfo::Kind kind, StringRef expandedCode,
8624-
llvm::SmallString<64> &scratch
8625-
) {
8626-
scratch.clear();
8627-
8628-
switch (kind) {
8629-
case GeneratedSourceInfo::ExpressionMacroExpansion:
8630-
case GeneratedSourceInfo::FreestandingDeclMacroExpansion:
8631-
return expandedCode;
8632-
8633-
case GeneratedSourceInfo::AccessorMacroExpansion:
8634-
// For accessor macros, wrap curly braces around the buffer contents.
8635-
scratch += "{\n";
8636-
scratch += expandedCode;
8637-
scratch += "\n}";
8638-
return scratch;
8639-
8640-
case GeneratedSourceInfo::MemberAttributeMacroExpansion:
8641-
// For member-attribute macros, add a space at the end.
8642-
scratch += expandedCode;
8643-
scratch += " ";
8644-
return scratch;
8645-
8646-
case GeneratedSourceInfo::PeerMacroExpansion:
8647-
case GeneratedSourceInfo::ConformanceMacroExpansion:
8648-
// For peers and conformances, add a newline to create some separation.
8649-
scratch += "\n";
8650-
LLVM_FALLTHROUGH;
8651-
8652-
case GeneratedSourceInfo::MemberMacroExpansion:
8653-
// For members, add a newline.
8654-
scratch += "\n";
8655-
scratch += expandedCode;
8656-
scratch += "\n";
8657-
return scratch;
8658-
8659-
case GeneratedSourceInfo::ReplacedFunctionBody:
8660-
case GeneratedSourceInfo::PrettyPrinted:
8661-
return expandedCode;
8662-
}
8663-
}
8664-
86658620
bool RefactoringActionExpandMacro::performChange() {
86668621
auto bufferIDs = getMacroExpansionBuffers(SM, CursorInfo);
86678622
if (bufferIDs.empty())
@@ -8682,33 +8637,6 @@ bool RefactoringActionExpandMacro::performChange() {
86828637
rewrittenBuffer.empty())
86838638
continue;
86848639

8685-
auto originalSourceRange = generatedInfo->originalSourceRange;
8686-
8687-
SmallString<64> scratchBuffer;
8688-
if (generatedInfo->kind == GeneratedSourceInfo::MemberMacroExpansion) {
8689-
// For member macros, adjust the source range from before-the-close-brace
8690-
// to after-the-open-brace.
8691-
ASTNode node = ASTNode::getFromOpaqueValue(generatedInfo->astNode);
8692-
auto decl = node.dyn_cast<Decl *>();
8693-
if (!decl)
8694-
continue;
8695-
8696-
SourceLoc leftBraceLoc;
8697-
if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
8698-
leftBraceLoc = nominal->getBraces().Start;
8699-
} else if (auto ext = dyn_cast<ExtensionDecl>(decl)) {
8700-
leftBraceLoc = ext->getBraces().Start;
8701-
}
8702-
if (leftBraceLoc.isInvalid())
8703-
continue;
8704-
8705-
auto afterLeftBraceLoc = Lexer::getLocForEndOfToken(SM, leftBraceLoc);
8706-
originalSourceRange = CharSourceRange(afterLeftBraceLoc, 0);
8707-
}
8708-
8709-
rewrittenBuffer = adjustMacroExpansionWhitespace(
8710-
generatedInfo->kind, rewrittenBuffer, scratchBuffer);
8711-
87128640
// `TheFile` is the file of the actual expansion site, where as
87138641
// `OriginalFile` is the possibly enclosing buffer. Concretely:
87148642
// ```
@@ -8727,6 +8655,7 @@ bool RefactoringActionExpandMacro::performChange() {
87278655
// site (`@_someBufferName`). Thus, we need to include the path to the
87288656
// original source as well. Note that this path could itself be another
87298657
// expansion.
8658+
auto originalSourceRange = generatedInfo->originalSourceRange;
87308659
SourceFile *originalFile =
87318660
MD->getSourceFileContainingLocation(originalSourceRange.getStart());
87328661
StringRef originalPath;

test/SourceKit/Macros/macro_basic.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,8 @@ struct S4 { }
139139
// ATTACHED_EXPAND-NEXT: source.edit.kind.active:
140140
// ATTACHED_EXPAND-NEXT: 24:3-24:3 (@__swiftmacro_9MacroUser1SV13myTypeWrapperfMA0_.swift) "@accessViaStorage "
141141
// ATTACHED_EXPAND-NEXT: source.edit.kind.active:
142-
// ATTACHED_EXPAND-NEXT: 22:11-22:11 (@__swiftmacro_9MacroUser1SV13myTypeWrapperfMm_.swift) "
142+
// ATTACHED_EXPAND-NEXT: 25:1-25:1 (@__swiftmacro_9MacroUser1SV13myTypeWrapperfMm_.swift) "
143+
// ATTACHED_EXPAND-EMPTY:
143144
// ATTACHED_EXPAND-NEXT: private var _storage = _Storage()
144145
// ATTACHED_EXPAND-NEXT: "
145146
// ATTACHED_EXPAND-NEXT: source.edit.kind.active:

0 commit comments

Comments
 (0)