@@ -112,12 +112,11 @@ unsigned SwiftMangler::getExtensionIndex(const swift::ExtensionDecl* decl,
112112 if (auto found = preloadedExtensionIndexes.extract (decl)) {
113113 return found.mapped ();
114114 }
115- if (auto parentModule = llvm::dyn_cast<swift::ModuleDecl>(parent)) {
116- llvm::SmallVector<swift::Decl*> siblings;
117- parentModule->getTopLevelDecls (siblings);
118- indexExtensions (siblings);
115+
116+ if (llvm::isa<swift::ModuleDecl>(parent)) {
117+ indexNominalTypeExtensions (decl->getExtendedNominal ()->getExtensions (), parent);
119118 } else if (auto iterableParent = llvm::dyn_cast<swift::IterableDeclContext>(parent)) {
120- indexExtensions (iterableParent->getAllMembers ());
119+ indexIterableExtensions (iterableParent->getAllMembers ());
121120 } else {
122121 // TODO use a generic logging handle for Swift entities here, once it's available
123122 CODEQL_ASSERT (false , " non-local context must be module or iterable decl context" );
@@ -128,13 +127,46 @@ unsigned SwiftMangler::getExtensionIndex(const swift::ExtensionDecl* decl,
128127 return found.mapped ();
129128}
130129
131- void SwiftMangler::indexExtensions (llvm::ArrayRef<swift::Decl*> siblings) {
130+ void SwiftMangler::indexNominalTypeExtensions (swift::ExtensionRange unsortedExtensions,
131+ const swift::Decl* parent) {
132+ std::vector<const swift::ExtensionDecl*> extensions;
133+ for (const auto & extension : unsortedExtensions) {
134+ extensions.emplace_back (extension);
135+ }
136+
137+ std::ranges::sort (extensions, [](const auto & e1 , const auto & e2 ) {
138+ if (auto f1 = e1 ->getSourceFileName ()) {
139+ if (auto f2 = e2 ->getSourceFileName ()) {
140+ int result = f1.value ().compare (f2.value ());
141+ if (result != 0 ) {
142+ return result < 0 ;
143+ }
144+ }
145+ }
146+ if (auto o1 = e1 ->getSourceOrder ()) {
147+ if (auto o2 = e2 ->getSourceOrder ()) {
148+ return o1.value () < o2.value ();
149+ }
150+ }
151+ return false ;
152+ });
153+
154+ auto index = 0u ;
155+ for (const auto & extension : extensions) {
156+ if (getParent (extension) == parent) {
157+ preloadedExtensionIndexes.emplace (extension, index);
158+ index++;
159+ }
160+ }
161+ }
162+
163+ void SwiftMangler::indexIterableExtensions (llvm::ArrayRef<swift::Decl*> siblings) {
132164 auto index = 0u ;
133165 for (auto sibling : siblings) {
134166 if (sibling->getKind () == swift::DeclKind::Extension) {
135167 preloadedExtensionIndexes.emplace (sibling, index);
168+ ++index;
136169 }
137- ++index;
138170 }
139171}
140172
0 commit comments