clang API Documentation

SemaInternal.h
Go to the documentation of this file.
00001 //===--- SemaInternal.h - Internal Sema Interfaces --------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file provides common API and #includes for the internal
00011 // implementation of Sema.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
00016 #define LLVM_CLANG_SEMA_SEMAINTERNAL_H
00017 
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/Sema/Lookup.h"
00020 #include "clang/Sema/Sema.h"
00021 #include "clang/Sema/SemaDiagnostic.h"
00022 
00023 namespace clang {
00024 
00025 inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
00026   return PartialDiagnostic(DiagID, Context.getDiagAllocator());
00027 }
00028 
00029 inline bool
00030 FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
00031   return FTI.NumParams == 1 && !FTI.isVariadic &&
00032          FTI.Params[0].Ident == nullptr && FTI.Params[0].Param &&
00033          cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType();
00034 }
00035 
00036 inline bool
00037 FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
00038   // Assume FTI is well-formed.
00039   return FTI.NumParams && !FTIHasSingleVoidParameter(FTI);
00040 }
00041 
00042 // This requires the variable to be non-dependent and the initializer
00043 // to not be value dependent.
00044 inline bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context) {
00045   const VarDecl *DefVD = nullptr;
00046   return !isa<ParmVarDecl>(Var) &&
00047     Var->isUsableInConstantExpressions(Context) &&
00048     Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE(); 
00049 }
00050 
00051 // Directly mark a variable odr-used. Given a choice, prefer to use 
00052 // MarkVariableReferenced since it does additional checks and then 
00053 // calls MarkVarDeclODRUsed.
00054 // If the variable must be captured:
00055 //  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
00056 //  - else capture it in the DeclContext that maps to the 
00057 //    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.  
00058 inline void MarkVarDeclODRUsed(VarDecl *Var,
00059     SourceLocation Loc, Sema &SemaRef,
00060     const unsigned *const FunctionScopeIndexToStopAt) {
00061   // Keep track of used but undefined variables.
00062   // FIXME: We shouldn't suppress this warning for static data members.
00063   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
00064     !Var->isExternallyVisible() &&
00065     !(Var->isStaticDataMember() && Var->hasInit())) {
00066       SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
00067       if (old.isInvalid()) old = Loc;
00068   }
00069   QualType CaptureType, DeclRefType;
00070   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 
00071     /*EllipsisLoc*/ SourceLocation(),
00072     /*BuildAndDiagnose*/ true, 
00073     CaptureType, DeclRefType, 
00074     FunctionScopeIndexToStopAt);
00075 
00076   Var->markUsed(SemaRef.Context);
00077 }
00078 
00079 /// Return a DLL attribute from the declaration.
00080 inline InheritableAttr *getDLLAttr(Decl *D) {
00081   assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
00082          "A declaration cannot be both dllimport and dllexport.");
00083   if (auto *Import = D->getAttr<DLLImportAttr>())
00084     return Import;
00085   if (auto *Export = D->getAttr<DLLExportAttr>())
00086     return Export;
00087   return nullptr;
00088 }
00089 
00090 class TypoCorrectionConsumer : public VisibleDeclConsumer {
00091   typedef SmallVector<TypoCorrection, 1> TypoResultList;
00092   typedef llvm::StringMap<TypoResultList> TypoResultsMap;
00093   typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
00094 
00095 public:
00096   TypoCorrectionConsumer(Sema &SemaRef,
00097                          const DeclarationNameInfo &TypoName,
00098                          Sema::LookupNameKind LookupKind,
00099                          Scope *S, CXXScopeSpec *SS,
00100                          std::unique_ptr<CorrectionCandidateCallback> CCC,
00101                          DeclContext *MemberContext,
00102                          bool EnteringContext)
00103       : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
00104         SemaRef(SemaRef), S(S),
00105         SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
00106         CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
00107         Result(SemaRef, TypoName, LookupKind),
00108         Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
00109         EnteringContext(EnteringContext), SearchNamespaces(false) {
00110     Result.suppressDiagnostics();
00111     // Arrange for ValidatedCorrections[0] to always be an empty correction.
00112     ValidatedCorrections.push_back(TypoCorrection());
00113   }
00114 
00115   bool includeHiddenDecls() const override { return true; }
00116 
00117   // Methods for adding potential corrections to the consumer.
00118   void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
00119                  bool InBaseClass) override;
00120   void FoundName(StringRef Name);
00121   void addKeywordResult(StringRef Keyword);
00122   void addCorrection(TypoCorrection Correction);
00123 
00124   bool empty() const {
00125     return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
00126   }
00127 
00128   /// \brief Return the list of TypoCorrections for the given identifier from
00129   /// the set of corrections that have the closest edit distance, if any.
00130   TypoResultList &operator[](StringRef Name) {
00131     return CorrectionResults.begin()->second[Name];
00132   }
00133 
00134   /// \brief Return the edit distance of the corrections that have the
00135   /// closest/best edit distance from the original typop.
00136   unsigned getBestEditDistance(bool Normalized) {
00137     if (CorrectionResults.empty())
00138       return (std::numeric_limits<unsigned>::max)();
00139 
00140     unsigned BestED = CorrectionResults.begin()->first;
00141     return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
00142   }
00143 
00144   /// \brief Set-up method to add to the consumer the set of namespaces to use
00145   /// in performing corrections to nested name specifiers. This method also
00146   /// implicitly adds all of the known classes in the current AST context to the
00147   /// to the consumer for correcting nested name specifiers.
00148   void
00149   addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
00150 
00151   /// \brief Return the next typo correction that passes all internal filters
00152   /// and is deemed valid by the consumer's CorrectionCandidateCallback,
00153   /// starting with the corrections that have the closest edit distance. An
00154   /// empty TypoCorrection is returned once no more viable corrections remain
00155   /// in the consumer.
00156   const TypoCorrection &getNextCorrection();
00157 
00158   /// \brief Get the last correction returned by getNextCorrection().
00159   const TypoCorrection &getCurrentCorrection() {
00160     return CurrentTCIndex < ValidatedCorrections.size()
00161                ? ValidatedCorrections[CurrentTCIndex]
00162                : ValidatedCorrections[0];  // The empty correction.
00163   }
00164 
00165   /// \brief Reset the consumer's position in the stream of viable corrections
00166   /// (i.e. getNextCorrection() will return each of the previously returned
00167   /// corrections in order before returning any new corrections).
00168   void resetCorrectionStream() {
00169     CurrentTCIndex = 0;
00170   }
00171 
00172   /// \brief Return whether the end of the stream of corrections has been
00173   /// reached.
00174   bool finished() {
00175     return CorrectionResults.empty() &&
00176            CurrentTCIndex >= ValidatedCorrections.size();
00177   }
00178 
00179   ASTContext &getContext() const { return SemaRef.Context; }
00180   const LookupResult &getLookupResult() const { return Result; }
00181 
00182 private:
00183   class NamespaceSpecifierSet {
00184     struct SpecifierInfo {
00185       DeclContext* DeclCtx;
00186       NestedNameSpecifier* NameSpecifier;
00187       unsigned EditDistance;
00188     };
00189 
00190     typedef SmallVector<DeclContext*, 4> DeclContextList;
00191     typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
00192 
00193     ASTContext &Context;
00194     DeclContextList CurContextChain;
00195     std::string CurNameSpecifier;
00196     SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
00197     SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
00198     bool isSorted;
00199 
00200     SpecifierInfoList Specifiers;
00201     llvm::SmallSetVector<unsigned, 4> Distances;
00202     llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
00203 
00204     /// \brief Helper for building the list of DeclContexts between the current
00205     /// context and the top of the translation unit
00206     static DeclContextList buildContextChain(DeclContext *Start);
00207 
00208     void sortNamespaces();
00209 
00210     unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
00211                                       NestedNameSpecifier *&NNS);
00212 
00213    public:
00214     NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
00215                           CXXScopeSpec *CurScopeSpec);
00216 
00217     /// \brief Add the DeclContext (a namespace or record) to the set, computing
00218     /// the corresponding NestedNameSpecifier and its distance in the process.
00219     void addNameSpecifier(DeclContext *Ctx);
00220 
00221     typedef SpecifierInfoList::iterator iterator;
00222     iterator begin() {
00223       if (!isSorted) sortNamespaces();
00224       return Specifiers.begin();
00225     }
00226     iterator end() { return Specifiers.end(); }
00227   };
00228 
00229   void addName(StringRef Name, NamedDecl *ND,
00230                NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
00231 
00232   /// \brief Find any visible decls for the given typo correction candidate.
00233   /// If none are found, it to the set of candidates for which qualified lookups
00234   /// will be performed to find possible nested name specifier changes.
00235   bool resolveCorrection(TypoCorrection &Candidate);
00236 
00237   /// \brief Perform qualified lookups on the queued set of typo correction
00238   /// candidates and add the nested name specifier changes to each candidate if
00239   /// a lookup succeeds (at which point the candidate will be returned to the
00240   /// main pool of potential corrections).
00241   void performQualifiedLookups();
00242 
00243   /// \brief The name written that is a typo in the source.
00244   IdentifierInfo *Typo;
00245 
00246   /// \brief The results found that have the smallest edit distance
00247   /// found (so far) with the typo name.
00248   ///
00249   /// The pointer value being set to the current DeclContext indicates
00250   /// whether there is a keyword with this name.
00251   TypoEditDistanceMap CorrectionResults;
00252 
00253   SmallVector<TypoCorrection, 4> ValidatedCorrections;
00254   size_t CurrentTCIndex;
00255 
00256   Sema &SemaRef;
00257   Scope *S;
00258   std::unique_ptr<CXXScopeSpec> SS;
00259   std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
00260   DeclContext *MemberContext;
00261   LookupResult Result;
00262   NamespaceSpecifierSet Namespaces;
00263   SmallVector<TypoCorrection, 2> QualifiedResults;
00264   bool EnteringContext;
00265   bool SearchNamespaces;
00266 };
00267 
00268 inline Sema::TypoExprState::TypoExprState() {}
00269 
00270 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) LLVM_NOEXCEPT {
00271   *this = std::move(other);
00272 }
00273 
00274 inline Sema::TypoExprState &Sema::TypoExprState::operator=(
00275     Sema::TypoExprState &&other) LLVM_NOEXCEPT {
00276   Consumer = std::move(other.Consumer);
00277   DiagHandler = std::move(other.DiagHandler);
00278   RecoveryHandler = std::move(other.RecoveryHandler);
00279   return *this;
00280 }
00281 
00282 } // end namespace clang
00283 
00284 #endif