1 //===- ASTImporter.h - Importing ASTs from other Contexts -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the ASTImporter class which imports AST nodes from one
10 //  context into another context.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_AST_ASTIMPORTER_H
15 #define LLVM_CLANG_AST_ASTIMPORTER_H
16 
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/AST/TemplateName.h"
23 #include "clang/AST/Type.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/IdentifierTable.h"
26 #include "clang/Basic/LLVM.h"
27 #include "clang/Basic/SourceLocation.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/Error.h"
33 #include <utility>
34 
35 namespace clang {
36 
37 class ASTContext;
38 class ASTImporterSharedState;
39 class Attr;
40 class CXXBaseSpecifier;
41 class CXXCtorInitializer;
42 class Decl;
43 class DeclContext;
44 class Expr;
45 class FileManager;
46 class NamedDecl;
47 class Stmt;
48 class TagDecl;
49 class TranslationUnitDecl;
50 class TypeSourceInfo;
51 
52   class ImportError : public llvm::ErrorInfo<ImportError> {
53   public:
54     /// \brief Kind of error when importing an AST component.
55     enum ErrorKind {
56         NameConflict, /// Naming ambiguity (likely ODR violation).
57         UnsupportedConstruct, /// Not supported node or case.
58         Unknown /// Other error.
59     };
60 
61     ErrorKind Error;
62 
63     static char ID;
64 
65     ImportError() : Error(Unknown) {}
66     ImportError(const ImportError &Other) : Error(Other.Error) {}
67     ImportError &operator=(const ImportError &Other) {
68       Error = Other.Error;
69       return *this;
70     }
71     ImportError(ErrorKind Error) : Error(Error) { }
72 
73     std::string toString() const;
74 
75     void log(raw_ostream &OS) const override;
76     std::error_code convertToErrorCode() const override;
77   };
78 
79   // \brief Returns with a list of declarations started from the canonical decl
80   // then followed by subsequent decls in the translation unit.
81   // This gives a canonical list for each entry in the redecl chain.
82   // `Decl::redecls()` gives a list of decls which always start from the
83   // previous decl and the next item is actually the previous item in the order
84   // of source locations.  Thus, `Decl::redecls()` gives different lists for
85   // the different entries in a given redecl chain.
86   llvm::SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D);
87 
88   /// Imports selected nodes from one AST context into another context,
89   /// merging AST nodes where appropriate.
90   class ASTImporter {
91     friend class ASTNodeImporter;
92   public:
93     using NonEquivalentDeclSet = llvm::DenseSet<std::pair<Decl *, Decl *>>;
94     using ImportedCXXBaseSpecifierMap =
95         llvm::DenseMap<const CXXBaseSpecifier *, CXXBaseSpecifier *>;
96 
97     enum class ODRHandlingType { Conservative, Liberal };
98 
99     // An ImportPath is the list of the AST nodes which we visit during an
100     // Import call.
101     // If node `A` depends on node `B` then the path contains an `A`->`B` edge.
102     // From the call stack of the import functions we can read the very same
103     // path.
104     //
105     // Now imagine the following AST, where the `->` represents dependency in
106     // therms of the import.
107     // ```
108     // A->B->C->D
109     //    `->E
110     // ```
111     // We would like to import A.
112     // The import behaves like a DFS, so we will visit the nodes in this order:
113     // ABCDE.
114     // During the visitation we will have the following ImportPaths:
115     // ```
116     // A
117     // AB
118     // ABC
119     // ABCD
120     // ABC
121     // AB
122     // ABE
123     // AB
124     // A
125     // ```
126     // If during the visit of E there is an error then we set an error for E,
127     // then as the call stack shrinks for B, then for A:
128     // ```
129     // A
130     // AB
131     // ABC
132     // ABCD
133     // ABC
134     // AB
135     // ABE // Error! Set an error to E
136     // AB  // Set an error to B
137     // A   // Set an error to A
138     // ```
139     // However, during the import we could import C and D without any error and
140     // they are independent from A,B and E.
141     // We must not set up an error for C and D.
142     // So, at the end of the import we have an entry in `ImportDeclErrors` for
143     // A,B,E but not for C,D.
144     //
145     // Now what happens if there is a cycle in the import path?
146     // Let's consider this AST:
147     // ```
148     // A->B->C->A
149     //    `->E
150     // ```
151     // During the visitation we will have the below ImportPaths and if during
152     // the visit of E there is an error then we will set up an error for E,B,A.
153     // But what's up with C?
154     // ```
155     // A
156     // AB
157     // ABC
158     // ABCA
159     // ABC
160     // AB
161     // ABE // Error! Set an error to E
162     // AB  // Set an error to B
163     // A   // Set an error to A
164     // ```
165     // This time we know that both B and C are dependent on A.
166     // This means we must set up an error for C too.
167     // As the call stack reverses back we get to A and we must set up an error
168     // to all nodes which depend on A (this includes C).
169     // But C is no longer on the import path, it just had been previously.
170     // Such situation can happen only if during the visitation we had a cycle.
171     // If we didn't have any cycle, then the normal way of passing an Error
172     // object through the call stack could handle the situation.
173     // This is why we must track cycles during the import process for each
174     // visited declaration.
175     class ImportPathTy {
176     public:
177       using VecTy = llvm::SmallVector<Decl *, 32>;
178 
179       void push(Decl *D) {
180         Nodes.push_back(D);
181         ++Aux[D];
182       }
183 
184       void pop() {
185         if (Nodes.empty())
186           return;
187         --Aux[Nodes.back()];
188         Nodes.pop_back();
189       }
190 
191       /// Returns true if the last element can be found earlier in the path.
192       bool hasCycleAtBack() const {
193         auto Pos = Aux.find(Nodes.back());
194         return Pos != Aux.end() && Pos->second > 1;
195       }
196 
197       using Cycle = llvm::iterator_range<VecTy::const_reverse_iterator>;
198       Cycle getCycleAtBack() const {
199         assert(Nodes.size() >= 2);
200         return Cycle(Nodes.rbegin(),
201                      std::find(Nodes.rbegin() + 1, Nodes.rend(), Nodes.back()) +
202                          1);
203       }
204 
205       /// Returns the copy of the cycle.
206       VecTy copyCycleAtBack() const {
207         auto R = getCycleAtBack();
208         return VecTy(R.begin(), R.end());
209       }
210 
211     private:
212       // All nodes of the path.
213       VecTy Nodes;
214       // Auxiliary container to be able to answer "Do we have a cycle ending
215       // at last element?" as fast as possible.
216       // We count each Decl's occurrence over the path.
217       llvm::SmallDenseMap<Decl *, int, 32> Aux;
218     };
219 
220   private:
221     std::shared_ptr<ASTImporterSharedState> SharedState = nullptr;
222 
223     /// The path which we go through during the import of a given AST node.
224     ImportPathTy ImportPath;
225     /// Sometimes we have to save some part of an import path, so later we can
226     /// set up properties to the saved nodes.
227     /// We may have several of these import paths associated to one Decl.
228     using SavedImportPathsForOneDecl =
229         llvm::SmallVector<ImportPathTy::VecTy, 32>;
230     using SavedImportPathsTy =
231         llvm::SmallDenseMap<Decl *, SavedImportPathsForOneDecl, 32>;
232     SavedImportPathsTy SavedImportPaths;
233 
234     /// The contexts we're importing to and from.
235     ASTContext &ToContext, &FromContext;
236 
237     /// The file managers we're importing to and from.
238     FileManager &ToFileManager, &FromFileManager;
239 
240     /// Whether to perform a minimal import.
241     bool Minimal;
242 
243     ODRHandlingType ODRHandling;
244 
245     /// Whether the last diagnostic came from the "from" context.
246     bool LastDiagFromFrom = false;
247 
248     /// Mapping from the already-imported types in the "from" context
249     /// to the corresponding types in the "to" context.
250     llvm::DenseMap<const Type *, const Type *> ImportedTypes;
251 
252     /// Mapping from the already-imported declarations in the "from"
253     /// context to the corresponding declarations in the "to" context.
254     llvm::DenseMap<Decl *, Decl *> ImportedDecls;
255 
256     /// Mapping from the already-imported declarations in the "from"
257     /// context to the error status of the import of that declaration.
258     /// This map contains only the declarations that were not correctly
259     /// imported. The same declaration may or may not be included in
260     /// ImportedDecls. This map is updated continuously during imports and never
261     /// cleared (like ImportedDecls).
262     llvm::DenseMap<Decl *, ImportError> ImportDeclErrors;
263 
264     /// Mapping from the already-imported declarations in the "to"
265     /// context to the corresponding declarations in the "from" context.
266     llvm::DenseMap<Decl *, Decl *> ImportedFromDecls;
267 
268     /// Mapping from the already-imported statements in the "from"
269     /// context to the corresponding statements in the "to" context.
270     llvm::DenseMap<Stmt *, Stmt *> ImportedStmts;
271 
272     /// Mapping from the already-imported FileIDs in the "from" source
273     /// manager to the corresponding FileIDs in the "to" source manager.
274     llvm::DenseMap<FileID, FileID> ImportedFileIDs;
275 
276     /// Mapping from the already-imported CXXBasesSpecifier in
277     ///  the "from" source manager to the corresponding CXXBasesSpecifier
278     ///  in the "to" source manager.
279     ImportedCXXBaseSpecifierMap ImportedCXXBaseSpecifiers;
280 
281     /// Declaration (from, to) pairs that are known not to be equivalent
282     /// (which we have already complained about).
283     NonEquivalentDeclSet NonEquivalentDecls;
284 
285     using FoundDeclsTy = SmallVector<NamedDecl *, 2>;
286     FoundDeclsTy findDeclsInToCtx(DeclContext *DC, DeclarationName Name);
287 
288     void AddToLookupTable(Decl *ToD);
289 
290   protected:
291     /// Can be overwritten by subclasses to implement their own import logic.
292     /// The overwritten method should call this method if it didn't import the
293     /// decl on its own.
294     virtual Expected<Decl *> ImportImpl(Decl *From);
295 
296     /// Used only in unittests to verify the behaviour of the error handling.
297     virtual bool returnWithErrorInTest() { return false; };
298 
299   public:
300 
301     /// \param ToContext The context we'll be importing into.
302     ///
303     /// \param ToFileManager The file manager we'll be importing into.
304     ///
305     /// \param FromContext The context we'll be importing from.
306     ///
307     /// \param FromFileManager The file manager we'll be importing into.
308     ///
309     /// \param MinimalImport If true, the importer will attempt to import
310     /// as little as it can, e.g., by importing declarations as forward
311     /// declarations that can be completed at a later point.
312     ///
313     /// \param SharedState The importer specific lookup table which may be
314     /// shared amongst several ASTImporter objects.
315     /// If not set then the original C/C++ lookup is used.
316     ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
317                 ASTContext &FromContext, FileManager &FromFileManager,
318                 bool MinimalImport,
319                 std::shared_ptr<ASTImporterSharedState> SharedState = nullptr);
320 
321     virtual ~ASTImporter();
322 
323     /// Whether the importer will perform a minimal import, creating
324     /// to-be-completed forward declarations when possible.
325     bool isMinimalImport() const { return Minimal; }
326 
327     void setODRHandling(ODRHandlingType T) { ODRHandling = T; }
328 
329     /// \brief Import the given object, returns the result.
330     ///
331     /// \param To Import the object into this variable.
332     /// \param From Object to import.
333     /// \return Error information (success or error).
334     template <typename ImportT>
335     LLVM_NODISCARD llvm::Error importInto(ImportT &To, const ImportT &From) {
336       auto ToOrErr = Import(From);
337       if (ToOrErr)
338         To = *ToOrErr;
339       return ToOrErr.takeError();
340     }
341 
342     /// Import cleanup objects owned by ExprWithCleanup.
343     llvm::Expected<ExprWithCleanups::CleanupObject>
344     Import(ExprWithCleanups::CleanupObject From);
345 
346     /// Import the given type from the "from" context into the "to"
347     /// context.
348     ///
349     /// \returns The equivalent type in the "to" context, or the import error.
350     llvm::Expected<const Type *> Import(const Type *FromT);
351 
352     /// Import the given qualified type from the "from" context into the "to"
353     /// context. A null type is imported as a null type (no error).
354     ///
355     /// \returns The equivalent type in the "to" context, or the import error.
356     llvm::Expected<QualType> Import(QualType FromT);
357 
358     /// Import the given type source information from the
359     /// "from" context into the "to" context.
360     ///
361     /// \returns The equivalent type source information in the "to"
362     /// context, or the import error.
363     llvm::Expected<TypeSourceInfo *> Import(TypeSourceInfo *FromTSI);
364 
365     /// Import the given attribute from the "from" context into the
366     /// "to" context.
367     ///
368     /// \returns The equivalent attribute in the "to" context, or the import
369     /// error.
370     llvm::Expected<Attr *> Import(const Attr *FromAttr);
371 
372     /// Import the given declaration from the "from" context into the
373     /// "to" context.
374     ///
375     /// \returns The equivalent declaration in the "to" context, or the import
376     /// error.
377     llvm::Expected<Decl *> Import(Decl *FromD);
378     llvm::Expected<const Decl *> Import(const Decl *FromD) {
379       return Import(const_cast<Decl *>(FromD));
380     }
381 
382     llvm::Expected<InheritedConstructor>
383     Import(const InheritedConstructor &From);
384 
385     /// Return the copy of the given declaration in the "to" context if
386     /// it has already been imported from the "from" context.  Otherwise return
387     /// nullptr.
388     Decl *GetAlreadyImportedOrNull(const Decl *FromD) const;
389 
390     /// Return the translation unit from where the declaration was
391     /// imported. If it does not exist nullptr is returned.
392     TranslationUnitDecl *GetFromTU(Decl *ToD);
393 
394     /// Return the declaration in the "from" context from which the declaration
395     /// in the "to" context was imported. If it was not imported or of the wrong
396     /// type a null value is returned.
397     template <typename DeclT>
398     llvm::Optional<DeclT *> getImportedFromDecl(const DeclT *ToD) const {
399       auto FromI = ImportedFromDecls.find(ToD);
400       if (FromI == ImportedFromDecls.end())
401         return {};
402       auto *FromD = dyn_cast<DeclT>(FromI->second);
403       if (!FromD)
404         return {};
405       return FromD;
406     }
407 
408     /// Import the given declaration context from the "from"
409     /// AST context into the "to" AST context.
410     ///
411     /// \returns the equivalent declaration context in the "to"
412     /// context, or error value.
413     llvm::Expected<DeclContext *> ImportContext(DeclContext *FromDC);
414 
415     /// Import the given expression from the "from" context into the
416     /// "to" context.
417     ///
418     /// \returns The equivalent expression in the "to" context, or the import
419     /// error.
420     llvm::Expected<Expr *> Import(Expr *FromE);
421 
422     /// Import the given statement from the "from" context into the
423     /// "to" context.
424     ///
425     /// \returns The equivalent statement in the "to" context, or the import
426     /// error.
427     llvm::Expected<Stmt *> Import(Stmt *FromS);
428 
429     /// Import the given nested-name-specifier from the "from"
430     /// context into the "to" context.
431     ///
432     /// \returns The equivalent nested-name-specifier in the "to"
433     /// context, or the import error.
434     llvm::Expected<NestedNameSpecifier *> Import(NestedNameSpecifier *FromNNS);
435 
436     /// Import the given nested-name-specifier-loc from the "from"
437     /// context into the "to" context.
438     ///
439     /// \returns The equivalent nested-name-specifier-loc in the "to"
440     /// context, or the import error.
441     llvm::Expected<NestedNameSpecifierLoc>
442     Import(NestedNameSpecifierLoc FromNNS);
443 
444     /// Import the given template name from the "from" context into the
445     /// "to" context, or the import error.
446     llvm::Expected<TemplateName> Import(TemplateName From);
447 
448     /// Import the given source location from the "from" context into
449     /// the "to" context.
450     ///
451     /// \returns The equivalent source location in the "to" context, or the
452     /// import error.
453     llvm::Expected<SourceLocation> Import(SourceLocation FromLoc);
454 
455     /// Import the given source range from the "from" context into
456     /// the "to" context.
457     ///
458     /// \returns The equivalent source range in the "to" context, or the import
459     /// error.
460     llvm::Expected<SourceRange> Import(SourceRange FromRange);
461 
462     /// Import the given declaration name from the "from"
463     /// context into the "to" context.
464     ///
465     /// \returns The equivalent declaration name in the "to" context, or the
466     /// import error.
467     llvm::Expected<DeclarationName> Import(DeclarationName FromName);
468 
469     /// Import the given identifier from the "from" context
470     /// into the "to" context.
471     ///
472     /// \returns The equivalent identifier in the "to" context. Note: It
473     /// returns nullptr only if the FromId was nullptr.
474     IdentifierInfo *Import(const IdentifierInfo *FromId);
475 
476     /// Import the given Objective-C selector from the "from"
477     /// context into the "to" context.
478     ///
479     /// \returns The equivalent selector in the "to" context, or the import
480     /// error.
481     llvm::Expected<Selector> Import(Selector FromSel);
482 
483     /// Import the given file ID from the "from" context into the
484     /// "to" context.
485     ///
486     /// \returns The equivalent file ID in the source manager of the "to"
487     /// context, or the import error.
488     llvm::Expected<FileID> Import(FileID, bool IsBuiltin = false);
489 
490     /// Import the given C++ constructor initializer from the "from"
491     /// context into the "to" context.
492     ///
493     /// \returns The equivalent initializer in the "to" context, or the import
494     /// error.
495     llvm::Expected<CXXCtorInitializer *> Import(CXXCtorInitializer *FromInit);
496 
497     /// Import the given CXXBaseSpecifier from the "from" context into
498     /// the "to" context.
499     ///
500     /// \returns The equivalent CXXBaseSpecifier in the source manager of the
501     /// "to" context, or the import error.
502     llvm::Expected<CXXBaseSpecifier *> Import(const CXXBaseSpecifier *FromSpec);
503 
504     /// Import the given APValue from the "from" context into
505     /// the "to" context.
506     ///
507     /// \return the equivalent APValue in the "to" context or the import
508     /// error.
509     llvm::Expected<APValue> Import(const APValue &FromValue);
510 
511     /// Import the definition of the given declaration, including all of
512     /// the declarations it contains.
513     LLVM_NODISCARD llvm::Error ImportDefinition(Decl *From);
514 
515     /// Cope with a name conflict when importing a declaration into the
516     /// given context.
517     ///
518     /// This routine is invoked whenever there is a name conflict while
519     /// importing a declaration. The returned name will become the name of the
520     /// imported declaration. By default, the returned name is the same as the
521     /// original name, leaving the conflict unresolve such that name lookup
522     /// for this name is likely to find an ambiguity later.
523     ///
524     /// Subclasses may override this routine to resolve the conflict, e.g., by
525     /// renaming the declaration being imported.
526     ///
527     /// \param Name the name of the declaration being imported, which conflicts
528     /// with other declarations.
529     ///
530     /// \param DC the declaration context (in the "to" AST context) in which
531     /// the name is being imported.
532     ///
533     /// \param IDNS the identifier namespace in which the name will be found.
534     ///
535     /// \param Decls the set of declarations with the same name as the
536     /// declaration being imported.
537     ///
538     /// \param NumDecls the number of conflicting declarations in \p Decls.
539     ///
540     /// \returns the name that the newly-imported declaration should have. Or
541     /// an error if we can't handle the name conflict.
542     virtual Expected<DeclarationName>
543     HandleNameConflict(DeclarationName Name, DeclContext *DC, unsigned IDNS,
544                        NamedDecl **Decls, unsigned NumDecls);
545 
546     /// Retrieve the context that AST nodes are being imported into.
547     ASTContext &getToContext() const { return ToContext; }
548 
549     /// Retrieve the context that AST nodes are being imported from.
550     ASTContext &getFromContext() const { return FromContext; }
551 
552     /// Retrieve the file manager that AST nodes are being imported into.
553     FileManager &getToFileManager() const { return ToFileManager; }
554 
555     /// Retrieve the file manager that AST nodes are being imported from.
556     FileManager &getFromFileManager() const { return FromFileManager; }
557 
558     /// Report a diagnostic in the "to" context.
559     DiagnosticBuilder ToDiag(SourceLocation Loc, unsigned DiagID);
560 
561     /// Report a diagnostic in the "from" context.
562     DiagnosticBuilder FromDiag(SourceLocation Loc, unsigned DiagID);
563 
564     /// Return the set of declarations that we know are not equivalent.
565     NonEquivalentDeclSet &getNonEquivalentDecls() { return NonEquivalentDecls; }
566 
567     /// Called for ObjCInterfaceDecl, ObjCProtocolDecl, and TagDecl.
568     /// Mark the Decl as complete, filling it in as much as possible.
569     ///
570     /// \param D A declaration in the "to" context.
571     virtual void CompleteDecl(Decl* D);
572 
573     /// Subclasses can override this function to observe all of the \c From ->
574     /// \c To declaration mappings as they are imported.
575     virtual void Imported(Decl *From, Decl *To) {}
576 
577     void RegisterImportedDecl(Decl *FromD, Decl *ToD);
578 
579     /// Store and assign the imported declaration to its counterpart.
580     /// It may happen that several decls from the 'from' context are mapped to
581     /// the same decl in the 'to' context.
582     Decl *MapImported(Decl *From, Decl *To);
583 
584     /// Called by StructuralEquivalenceContext.  If a RecordDecl is
585     /// being compared to another RecordDecl as part of import, completing the
586     /// other RecordDecl may trigger importation of the first RecordDecl. This
587     /// happens especially for anonymous structs.  If the original of the second
588     /// RecordDecl can be found, we can complete it without the need for
589     /// importation, eliminating this loop.
590     virtual Decl *GetOriginalDecl(Decl *To) { return nullptr; }
591 
592     /// Return if import of the given declaration has failed and if yes
593     /// the kind of the problem. This gives the first error encountered with
594     /// the node.
595     llvm::Optional<ImportError> getImportDeclErrorIfAny(Decl *FromD) const;
596 
597     /// Mark (newly) imported declaration with error.
598     void setImportDeclError(Decl *From, ImportError Error);
599 
600     /// Determine whether the given types are structurally
601     /// equivalent.
602     bool IsStructurallyEquivalent(QualType From, QualType To,
603                                   bool Complain = true);
604 
605     /// Determine the index of a field in its parent record.
606     /// F should be a field (or indirect field) declaration.
607     /// \returns The index of the field in its parent context (starting from 0).
608     /// On error `None` is returned (parent context is non-record).
609     static llvm::Optional<unsigned> getFieldIndex(Decl *F);
610   };
611 
612 } // namespace clang
613 
614 #endif // LLVM_CLANG_AST_ASTIMPORTER_H
615