Skip to content

Commit fc24471

Browse files
authored
Merge pull request #66532 from hborla/suppress-expansion-in-macro-argument
[Macros] Use source locations to determine whether to suppress macro expansions.
2 parents b1f99b8 + 2cc1204 commit fc24471

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

66 files changed

+513
-250
lines changed

include/swift/AST/ASTScope.h

+26-17
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,10 @@ class ASTScopeImpl : public ASTAllocated<ASTScopeImpl> {
218218
return nullptr;
219219
}
220220

221+
virtual NullablePtr<MacroExpansionDecl> getFreestandingMacro() const {
222+
return nullptr;
223+
}
224+
221225
#pragma mark - debugging and printing
222226

223227
public:
@@ -278,6 +282,10 @@ class ASTScopeImpl : public ASTAllocated<ASTScopeImpl> {
278282
static std::pair<CaseStmt *, CaseStmt *>
279283
lookupFallthroughSourceAndDest(SourceFile *sourceFile, SourceLoc loc);
280284

285+
static void lookupEnclosingMacroScope(
286+
SourceFile *sourceFile, SourceLoc loc,
287+
llvm::function_ref<bool(ASTScope::PotentialMacro)> consume);
288+
281289
/// Scopes that cannot bind variables may set this to true to create more
282290
/// compact scope tree in the debug info.
283291
virtual bool ignoreInDebugInfo() const { return false; }
@@ -840,24 +848,20 @@ class DefaultArgumentInitializerScope final : public ASTScopeImpl {
840848
bool ignoreInDebugInfo() const override { return true; }
841849
};
842850

843-
/// Consider:
844-
/// @_propertyWrapper
845-
/// struct WrapperWithInitialValue {
846-
/// }
847-
/// struct HasWrapper {
848-
/// @WrapperWithInitialValue var y = 17
849-
/// }
850-
/// Lookup has to be able to find the use of WrapperWithInitialValue, that's
851-
/// what this scope is for. Because the source positions are screwy.
852-
853-
class AttachedPropertyWrapperScope final : public ASTScopeImpl {
851+
/// The scope for custom attributes and their arguments, such as for
852+
/// attached property wrappers and for attached macros.
853+
///
854+
/// Source locations for the attribute name and its arguments are in the
855+
/// custom attribute, so lookup is invoked from within the attribute
856+
/// itself.
857+
class CustomAttributeScope final : public ASTScopeImpl {
854858
public:
855859
CustomAttr *attr;
856-
VarDecl *decl;
860+
Decl *decl;
857861

858-
AttachedPropertyWrapperScope(CustomAttr *attr, VarDecl *decl)
862+
CustomAttributeScope(CustomAttr *attr,Decl *decl)
859863
: attr(attr), decl(decl) {}
860-
virtual ~AttachedPropertyWrapperScope() {}
864+
virtual ~CustomAttributeScope() {}
861865

862866
protected:
863867
ASTScopeImpl *expandSpecifically(ScopeCreator &) override;
@@ -871,7 +875,8 @@ class AttachedPropertyWrapperScope final : public ASTScopeImpl {
871875
NullablePtr<DeclAttribute> getDeclAttributeIfAny() const override {
872876
return attr;
873877
}
874-
bool ignoreInDebugInfo() const override { return true; }
878+
bool ignoreInDebugInfo() const override { return true; }
879+
875880
private:
876881
void expandAScopeThatDoesNotCreateANewInsertionPoint(ScopeCreator &);
877882
};
@@ -1134,9 +1139,9 @@ class SpecializeAttributeScope final : public ASTScopeImpl {
11341139
class DifferentiableAttributeScope final : public ASTScopeImpl {
11351140
public:
11361141
DifferentiableAttr *const differentiableAttr;
1137-
ValueDecl *const attributedDeclaration;
1142+
Decl *const attributedDeclaration;
11381143

1139-
DifferentiableAttributeScope(DifferentiableAttr *diffAttr, ValueDecl *decl)
1144+
DifferentiableAttributeScope(DifferentiableAttr *diffAttr, Decl *decl)
11401145
: differentiableAttr(diffAttr), attributedDeclaration(decl) {}
11411146
virtual ~DifferentiableAttributeScope() {}
11421147

@@ -1270,6 +1275,10 @@ class MacroExpansionDeclScope final : public ASTScopeImpl {
12701275
SourceRange
12711276
getSourceRangeOfThisASTNode(bool omitAssertions = false) const override;
12721277

1278+
NullablePtr<MacroExpansionDecl> getFreestandingMacro() const override {
1279+
return decl;
1280+
}
1281+
12731282
protected:
12741283
void printSpecifics(llvm::raw_ostream &out) const override;
12751284

include/swift/AST/Decl.h

+3-2
Original file line numberDiff line numberDiff line change
@@ -3902,7 +3902,7 @@ class NominalTypeDecl : public GenericTypeDecl, public IterableDeclContext {
39023902
/// protocols to which the nominal type conforms. Furthermore, the resulting
39033903
/// set of declarations has not been filtered for visibility, nor have
39043904
/// overridden declarations been removed.
3905-
TinyPtrVector<ValueDecl *> lookupDirect(DeclName name,
3905+
TinyPtrVector<ValueDecl *> lookupDirect(DeclName name, SourceLoc loc = SourceLoc(),
39063906
OptionSet<LookupDirectFlags> flags =
39073907
OptionSet<LookupDirectFlags>());
39083908

@@ -4457,7 +4457,8 @@ class ClassDecl final : public NominalTypeDecl {
44574457
// Force loading all the members, which will add this attribute if any of
44584458
// members are determined to be missing while loading.
44594459
auto mutableThis = const_cast<ClassDecl *>(this);
4460-
(void)mutableThis->lookupDirect(DeclBaseName::createConstructor());
4460+
(void)mutableThis->lookupDirect(DeclBaseName::createConstructor(),
4461+
getStartLoc());
44614462
}
44624463

44634464
if (Bits.ClassDecl.ComputedHasMissingDesignatedInitializers)

include/swift/AST/DeclContext.h

+4-3
Original file line numberDiff line numberDiff line change
@@ -598,7 +598,8 @@ class alignas(1 << DeclContextAlignInBits) DeclContext
598598
/// lookup.
599599
///
600600
/// \returns true if anything was found.
601-
bool lookupQualified(Type type, DeclNameRef member, NLOptions options,
601+
bool lookupQualified(Type type, DeclNameRef member,
602+
SourceLoc loc, NLOptions options,
602603
SmallVectorImpl<ValueDecl *> &decls) const;
603604

604605
/// Look for the set of declarations with the given name within the
@@ -616,12 +617,12 @@ class alignas(1 << DeclContextAlignInBits) DeclContext
616617
///
617618
/// \returns true if anything was found.
618619
bool lookupQualified(ArrayRef<NominalTypeDecl *> types, DeclNameRef member,
619-
NLOptions options,
620+
SourceLoc loc, NLOptions options,
620621
SmallVectorImpl<ValueDecl *> &decls) const;
621622

622623
/// Perform qualified lookup for the given member in the given module.
623624
bool lookupQualified(ModuleDecl *module, DeclNameRef member,
624-
NLOptions options,
625+
SourceLoc loc, NLOptions options,
625626
SmallVectorImpl<ValueDecl *> &decls) const;
626627

627628
/// Look up all Objective-C methods with the given selector visible

include/swift/AST/DiagnosticsSema.def

+4
Original file line numberDiff line numberDiff line change
@@ -7194,6 +7194,10 @@ ERROR(macro_accessor_missing_from_expansion,none,
71947194
ERROR(macro_init_accessor_not_documented,none,
71957195
"expansion of macro %0 produced an unexpected 'init' accessor",
71967196
(DeclName))
7197+
ERROR(global_arbitrary_name,none,
7198+
"'%0' macros are not allowed to introduce arbitrary names "
7199+
"at global scope",
7200+
(StringRef))
71977201

71987202
ERROR(macro_resolve_circular_reference, none,
71997203
"circular reference resolving %select{freestanding|attached}0 macro %1",

include/swift/AST/Evaluator.h

-22
Original file line numberDiff line numberDiff line change
@@ -208,18 +208,6 @@ class Evaluator {
208208
/// is treated as a stack and is used to detect cycles.
209209
llvm::SetVector<ActiveRequest> activeRequests;
210210

211-
/// How many `ResolveMacroRequest` requests are active.
212-
///
213-
/// This allows us to quickly determine whether there is any
214-
/// `ResolveMacroRequest` active in the active request stack.
215-
/// It saves us from a linear scan through `activeRequests` when
216-
/// we need to determine this information.
217-
///
218-
/// Why on earth would we need to determine this information?
219-
/// Please see the extended comment that goes with the constructor
220-
/// of `UnqualifiedLookupRequest`.
221-
unsigned numActiveResolveMacroRequests = 0;
222-
223211
/// A cache that stores the results of requests.
224212
evaluator::RequestCache cache;
225213

@@ -342,16 +330,6 @@ class Evaluator {
342330
return activeRequests.count(ActiveRequest(request));
343331
}
344332

345-
/// Determine whether there is any active "resolve macro" request
346-
/// on the request stack.
347-
///
348-
/// Why on earth would we need to determine this information?
349-
/// Please see the extended comment that goes with the constructor
350-
/// of `UnqualifiedLookupRequest`.
351-
bool hasActiveResolveMacroRequest() const {
352-
return numActiveResolveMacroRequests > 0;
353-
}
354-
355333
private:
356334
/// Diagnose a cycle detected in the evaluation of the given
357335
/// request.

include/swift/AST/ModuleNameLookup.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ void lookupInModule(const DeclContext *moduleOrFile,
6262
DeclName name, SmallVectorImpl<ValueDecl *> &decls,
6363
NLKind lookupKind, ResolutionKind resolutionKind,
6464
const DeclContext *moduleScopeContext,
65-
NLOptions options);
65+
SourceLoc loc, NLOptions options);
6666

6767
/// Performs a qualified lookup into the given module and, if necessary, its
6868
/// reexports, observing proper shadowing rules.

include/swift/AST/NameLookup.h

+26-1
Original file line numberDiff line numberDiff line change
@@ -513,7 +513,7 @@ void lookupVisibleDecls(VisibleDeclConsumer &Consumer,
513513
///
514514
/// \param CurrDC the DeclContext from which the lookup is done.
515515
void lookupVisibleMemberDecls(VisibleDeclConsumer &Consumer,
516-
Type BaseTy,
516+
Type BaseTy, SourceLoc loc,
517517
const DeclContext *CurrDC,
518518
bool includeInstanceMembers,
519519
bool includeDerivedRequirements,
@@ -545,6 +545,15 @@ template <typename Result>
545545
void filterForDiscriminator(SmallVectorImpl<Result> &results,
546546
DebuggerClient *debugClient);
547547

548+
/// \returns The set of macro declarations with the given name that
549+
/// fulfill any of the given macro roles.
550+
SmallVector<MacroDecl *, 1>
551+
lookupMacros(DeclContext *dc, DeclNameRef macroName, MacroRoles roles);
552+
553+
/// \returns Whether the given source location is inside an attached
554+
/// or freestanding macro argument.
555+
bool isInMacroArgument(SourceFile *sourceFile, SourceLoc loc);
556+
548557
/// Call the given function body with each macro declaration and its associated
549558
/// role attribute for the given role.
550559
///
@@ -816,6 +825,22 @@ class ASTScope : public ASTAllocated<ASTScope> {
816825
static std::pair<CaseStmt *, CaseStmt *>
817826
lookupFallthroughSourceAndDest(SourceFile *sourceFile, SourceLoc loc);
818827

828+
using PotentialMacro =
829+
llvm::PointerUnion<FreestandingMacroExpansion *, CustomAttr *>;
830+
831+
/// Look up the scope tree for the nearest enclosing macro scope at
832+
/// the given source location.
833+
///
834+
/// \param sourceFile The source file containing the given location.
835+
/// \param loc The source location to start lookup from.
836+
/// \param consume A function that is called when a potential macro
837+
/// scope is found. If \c consume returns \c true, lookup
838+
/// will stop. If \c consume returns \c false, lookup will
839+
/// continue up the scope tree.
840+
static void lookupEnclosingMacroScope(
841+
SourceFile *sourceFile, SourceLoc loc,
842+
llvm::function_ref<bool(PotentialMacro macro)> consume);
843+
819844
SWIFT_DEBUG_DUMP;
820845
void print(llvm::raw_ostream &) const;
821846
void dumpOneScopeMapLocation(std::pair<unsigned, unsigned>);

include/swift/AST/NameLookupRequests.h

+4-4
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,7 @@ class LookupInModuleRequest
461461
LookupInModuleRequest(
462462
const DeclContext *, DeclName, NLKind,
463463
namelookup::ResolutionKind, const DeclContext *,
464-
NLOptions);
464+
SourceLoc, NLOptions);
465465

466466
private:
467467
friend SimpleRequest;
@@ -511,7 +511,7 @@ class ModuleQualifiedLookupRequest
511511
public:
512512
ModuleQualifiedLookupRequest(const DeclContext *,
513513
ModuleDecl *, DeclNameRef,
514-
NLOptions);
514+
SourceLoc, NLOptions);
515515

516516
private:
517517
friend SimpleRequest;
@@ -537,7 +537,7 @@ class QualifiedLookupRequest
537537
public:
538538
QualifiedLookupRequest(const DeclContext *,
539539
SmallVector<NominalTypeDecl *, 4>,
540-
DeclNameRef, NLOptions);
540+
DeclNameRef, SourceLoc, NLOptions);
541541

542542
private:
543543
friend SimpleRequest;
@@ -588,7 +588,7 @@ class DirectLookupRequest
588588
TinyPtrVector<ValueDecl *>(DirectLookupDescriptor),
589589
RequestFlags::Uncached|RequestFlags::DependencySink> {
590590
public:
591-
DirectLookupRequest(DirectLookupDescriptor);
591+
DirectLookupRequest(DirectLookupDescriptor, SourceLoc);
592592

593593
private:
594594
friend SimpleRequest;

include/swift/AST/TypeCheckRequests.h

+3
Original file line numberDiff line numberDiff line change
@@ -3249,6 +3249,9 @@ class UnresolvedMacroReference {
32493249
public:
32503250
UnresolvedMacroReference(FreestandingMacroExpansion *exp) : pointer(exp) {}
32513251
UnresolvedMacroReference(CustomAttr *attr) : pointer(attr) {}
3252+
UnresolvedMacroReference(
3253+
llvm::PointerUnion<FreestandingMacroExpansion *, CustomAttr *> pointer)
3254+
: pointer(pointer) {}
32523255

32533256
FreestandingMacroExpansion *getFreestanding() const {
32543257
return pointer.dyn_cast<FreestandingMacroExpansion *>();

include/swift/Sema/ConstraintSystem.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -2910,7 +2910,8 @@ class ConstraintSystem {
29102910
/// and no new names are introduced after that point.
29112911
///
29122912
/// \returns A reference to the member-lookup result.
2913-
LookupResult &lookupMember(Type base, DeclNameRef name);
2913+
LookupResult &lookupMember(Type base, DeclNameRef name,
2914+
SourceLoc loc);
29142915

29152916
/// Retrieve the set of "alternative" literal types that we'll explore
29162917
/// for a given literal protocol kind.

lib/AST/ASTContext.cpp

+4-3
Original file line numberDiff line numberDiff line change
@@ -1072,8 +1072,8 @@ DECLTYPE *ASTContext::get##NAME##Decl() const { \
10721072
/* Note: lookupQualified() will search both the Swift overlay \
10731073
* and the Clang module it imports. */ \
10741074
SmallVector<ValueDecl *, 1> decls; \
1075-
M->lookupQualified(M, DeclNameRef(getIdentifier(#NAME)), NL_OnlyTypes, \
1076-
decls); \
1075+
M->lookupQualified(M, DeclNameRef(getIdentifier(#NAME)), SourceLoc(), \
1076+
NL_OnlyTypes, decls); \
10771077
if (decls.size() == 1 && isa<DECLTYPE>(decls[0])) { \
10781078
auto decl = cast<DECLTYPE>(decls[0]); \
10791079
if (isa<ProtocolDecl>(decl) \
@@ -1336,7 +1336,8 @@ ConcreteDeclRef ASTContext::getRegexInitDecl(Type regexType) const {
13361336
{Id_regexString, Id_version});
13371337
SmallVector<ValueDecl *, 1> results;
13381338
spModule->lookupQualified(getRegexType(), DeclNameRef(name),
1339-
NL_IncludeUsableFromInline, results);
1339+
SourceLoc(), NL_IncludeUsableFromInline,
1340+
results);
13401341
assert(results.size() == 1);
13411342
auto *foundDecl = cast<ConstructorDecl>(results[0]);
13421343
auto subs = regexType->getMemberSubstitutionMap(spModule, foundDecl);

lib/AST/ASTScope.cpp

+7-1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,12 @@ std::pair<CaseStmt *, CaseStmt *> ASTScope::lookupFallthroughSourceAndDest(
6060
return ASTScopeImpl::lookupFallthroughSourceAndDest(sourceFile, loc);
6161
}
6262

63+
void ASTScope::lookupEnclosingMacroScope(
64+
SourceFile *sourceFile, SourceLoc loc,
65+
llvm::function_ref<bool(PotentialMacro)> body) {
66+
return ASTScopeImpl::lookupEnclosingMacroScope(sourceFile, loc, body);
67+
}
68+
6369
#if SWIFT_COMPILER_IS_MSVC
6470
#pragma warning(push)
6571
#pragma warning(disable : 4996)
@@ -138,7 +144,7 @@ DEFINE_GET_CLASS_NAME(AbstractFunctionDeclScope)
138144
DEFINE_GET_CLASS_NAME(ParameterListScope)
139145
DEFINE_GET_CLASS_NAME(FunctionBodyScope)
140146
DEFINE_GET_CLASS_NAME(DefaultArgumentInitializerScope)
141-
DEFINE_GET_CLASS_NAME(AttachedPropertyWrapperScope)
147+
DEFINE_GET_CLASS_NAME(CustomAttributeScope)
142148
DEFINE_GET_CLASS_NAME(PatternEntryDeclScope)
143149
DEFINE_GET_CLASS_NAME(PatternEntryInitializerScope)
144150
DEFINE_GET_CLASS_NAME(ConditionalClausePatternUseScope)

lib/AST/ASTScopeCreation.cpp

+9-9
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ class ScopeCreator final : public ASTAllocated<ScopeCreator> {
180180
addChildrenForParsedAccessors(AbstractStorageDecl *asd,
181181
ASTScopeImpl *parent);
182182

183-
void addChildrenForKnownAttributes(ValueDecl *decl,
183+
void addChildrenForKnownAttributes(Decl *decl,
184184
ASTScopeImpl *parent);
185185

186186
/// Add PatternEntryDeclScopes for each pattern binding entry.
@@ -569,7 +569,7 @@ void ScopeCreator::addChildrenForParsedAccessors(
569569
});
570570
}
571571

572-
void ScopeCreator::addChildrenForKnownAttributes(ValueDecl *decl,
572+
void ScopeCreator::addChildrenForKnownAttributes(Decl *decl,
573573
ASTScopeImpl *parent) {
574574
SmallVector<DeclAttribute *, 2> relevantAttrs;
575575

@@ -601,10 +601,8 @@ void ScopeCreator::addChildrenForKnownAttributes(ValueDecl *decl,
601601
parent, specAttr, afd);
602602
}
603603
} else if (auto *customAttr = dyn_cast<CustomAttr>(attr)) {
604-
if (auto *vd = dyn_cast<VarDecl>(decl)) {
605-
constructExpandAndInsert<AttachedPropertyWrapperScope>(
606-
parent, customAttr, vd);
607-
}
604+
constructExpandAndInsert<CustomAttributeScope>(
605+
parent, customAttr, decl);
608606
}
609607
}
610608
}
@@ -716,7 +714,7 @@ CREATES_NEW_INSERTION_POINT(ConditionalClausePatternUseScope)
716714

717715
NO_NEW_INSERTION_POINT(FunctionBodyScope)
718716
NO_NEW_INSERTION_POINT(AbstractFunctionDeclScope)
719-
NO_NEW_INSERTION_POINT(AttachedPropertyWrapperScope)
717+
NO_NEW_INSERTION_POINT(CustomAttributeScope)
720718
NO_NEW_INSERTION_POINT(EnumElementScope)
721719
NO_NEW_INSERTION_POINT(GuardStmtBodyScope)
722720
NO_NEW_INSERTION_POINT(ParameterListScope)
@@ -1177,7 +1175,7 @@ void DefaultArgumentInitializerScope::
11771175
scopeCreator.addToScopeTree(initExpr, this);
11781176
}
11791177

1180-
void AttachedPropertyWrapperScope::
1178+
void CustomAttributeScope::
11811179
expandAScopeThatDoesNotCreateANewInsertionPoint(
11821180
ScopeCreator &scopeCreator) {
11831181
if (auto *args = attr->getArgs()) {
@@ -1192,7 +1190,9 @@ ASTScopeImpl *GenericTypeOrExtensionWholePortion::expandScope(
11921190
GenericTypeOrExtensionScope *scope, ScopeCreator &scopeCreator) const {
11931191
// Get now in case recursion emancipates scope
11941192
auto *const ip = scope->getParent().get();
1195-
1193+
1194+
scopeCreator.addChildrenForKnownAttributes(scope->getDecl(), scope);
1195+
11961196
auto *context = scope->getGenericContext();
11971197
auto *genericParams = (isa<TypeAliasDecl>(context)
11981198
? context->getParsedGenericParams()

0 commit comments

Comments
 (0)