@@ -535,6 +535,69 @@ class TypeRefinementContextBuilder : private ASTWalker {
535535 return MacroWalking::Arguments;
536536 }
537537
538+ // / Check whether this declaration is in a source file buried within
539+ // / a macro expansion of the
540+ bool isDeclInMacroExpansion (Decl *decl) const override {
541+ // If it's not in a macro expansion relative to its context, it's not
542+ // considered to be in a macro expansion.
543+ if (!decl->isInMacroExpansionInContext ())
544+ return false ;
545+
546+ auto module = decl->getDeclContext ()->getParentModule ();
547+ auto *declFile = module ->getSourceFileContainingLocation (decl->getLoc ());
548+ if (!declFile)
549+ return false ;
550+
551+ // Look for a parent context that implies that we are producing a
552+ // type refinement context for this expansion.
553+ for (auto iter = ContextStack.rbegin (), endIter = ContextStack.rend ();
554+ iter != endIter; ++iter) {
555+ const auto &context = *iter;
556+ if (auto contextRTC = context.TRC ) {
557+ // If the context is the same source file, don't treat it as an
558+ // expansion.
559+ auto introNode = contextRTC->getIntroductionNode ();
560+ switch (auto reason = contextRTC->getReason ()) {
561+ case TypeRefinementContext::Reason::Root:
562+ if (auto contextFile = introNode.getAsSourceFile ())
563+ if (declFile == contextFile)
564+ return false ;
565+
566+ break ;
567+
568+ case TypeRefinementContext::Reason::Decl:
569+ case TypeRefinementContext::Reason::DeclImplicit:
570+ // If the context is a declaration, check whether the declaration
571+ // is in the same source file as this declaration.
572+ if (auto contextDecl = introNode.getAsDecl ()) {
573+ if (decl == contextDecl)
574+ return false ;
575+
576+ auto contextModule =
577+ contextDecl->getDeclContext ()->getParentModule ();
578+ SourceLoc contextDeclLoc = contextDecl->getLoc ();
579+ auto contextDeclFile =
580+ contextModule->getSourceFileContainingLocation (contextDeclLoc);
581+ if (declFile == contextDeclFile)
582+ return false ;
583+ }
584+ break ;
585+
586+ case TypeRefinementContext::Reason::IfStmtThenBranch:
587+ case TypeRefinementContext::Reason::IfStmtElseBranch:
588+ case TypeRefinementContext::Reason::ConditionFollowingAvailabilityQuery:
589+ case TypeRefinementContext::Reason::GuardStmtFallthrough:
590+ case TypeRefinementContext::Reason::GuardStmtElseBranch:
591+ case TypeRefinementContext::Reason::WhileStmtBody:
592+ // Nothing to check here.
593+ break ;
594+ }
595+ }
596+ }
597+
598+ return true ;
599+ }
600+
538601 bool shouldSkipDecl (Decl *D) const {
539602 // Only visit a node that has a corresponding concrete syntax node if we are
540603 // already walking that concrete syntax node.
0 commit comments