Clang Project

clang_source_code/include/clang/Sema/SemaInternal.h
1//===--- SemaInternal.h - Internal Sema Interfaces --------------*- 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 provides common API and #includes for the internal
10// implementation of Sema.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
15#define LLVM_CLANG_SEMA_SEMAINTERNAL_H
16
17#include "clang/AST/ASTContext.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/Sema.h"
20#include "clang/Sema/SemaDiagnostic.h"
21
22namespace clang {
23
24inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
25  return PartialDiagnostic(DiagIDContext.getDiagAllocator());
26}
27
28inline bool
29FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
30  return FTI.NumParams == 1 && !FTI.isVariadic &&
31         FTI.Params[0].Ident == nullptr && FTI.Params[0].Param &&
32         cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType();
33}
34
35inline bool
36FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
37  // Assume FTI is well-formed.
38  return FTI.NumParams && !FTIHasSingleVoidParameter(FTI);
39}
40
41// This requires the variable to be non-dependent and the initializer
42// to not be value dependent.
43inline bool IsVariableAConstantExpression(VarDecl *VarASTContext &Context) {
44  const VarDecl *DefVD = nullptr;
45  return !isa<ParmVarDecl>(Var) &&
46    Var->isUsableInConstantExpressions(Context) &&
47    Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE();
48}
49
50// Helper function to check whether D's attributes match current CUDA mode.
51// Decls with mismatched attributes and related diagnostics may have to be
52// ignored during this CUDA compilation pass.
53inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOptsDecl *D) {
54  if (!LangOpts.CUDA || !D)
55    return true;
56  bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
57                          D->hasAttr<CUDASharedAttr>() ||
58                          D->hasAttr<CUDAGlobalAttr>();
59  return isDeviceSideDecl == LangOpts.CUDAIsDevice;
60}
61
62// Directly mark a variable odr-used. Given a choice, prefer to use
63// MarkVariableReferenced since it does additional checks and then
64// calls MarkVarDeclODRUsed.
65// If the variable must be captured:
66//  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
67//  - else capture it in the DeclContext that maps to the
68//    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
69inline void MarkVarDeclODRUsed(VarDecl *Var,
70    SourceLocation LocSema &SemaRef,
71    const unsigned *const FunctionScopeIndexToStopAt) {
72  // Keep track of used but undefined variables.
73  // FIXME: We shouldn't suppress this warning for static data members.
74  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
75      (!Var->isExternallyVisible() || Var->isInline() ||
76       SemaRef.isExternalWithNoLinkageType(Var)) &&
77      !(Var->isStaticDataMember() && Var->hasInit())) {
78    SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
79    if (old.isInvalid())
80      old = Loc;
81  }
82  QualType CaptureTypeDeclRefType;
83  SemaRef.tryCaptureVariable(VarLocSema::TryCapture_Implicit,
84    /*EllipsisLoc*/ SourceLocation(),
85    /*BuildAndDiagnose*/ true,
86    CaptureTypeDeclRefType,
87    FunctionScopeIndexToStopAt);
88
89  Var->markUsed(SemaRef.Context);
90}
91
92/// Return a DLL attribute from the declaration.
93inline InheritableAttr *getDLLAttr(Decl *D) {
94   (0) . __assert_fail ("!(D->hasAttr() && D->hasAttr()) && \"A declaration cannot be both dllimport and dllexport.\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Sema/SemaInternal.h", 95, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
95 (0) . __assert_fail ("!(D->hasAttr() && D->hasAttr()) && \"A declaration cannot be both dllimport and dllexport.\"", "/home/seafit/code_projects/clang_source/clang/include/clang/Sema/SemaInternal.h", 95, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">         "A declaration cannot be both dllimport and dllexport.");
96  if (auto *Import = D->getAttr<DLLImportAttr>())
97    return Import;
98  if (auto *Export = D->getAttr<DLLExportAttr>())
99    return Export;
100  return nullptr;
101}
102
103/// Retrieve the depth and index of a template parameter.
104inline std::pair<unsignedunsignedgetDepthAndIndex(NamedDecl *ND) {
105  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
106    return std::make_pair(TTP->getDepth(), TTP->getIndex());
107
108  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
109    return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
110
111  const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
112  return std::make_pair(TTP->getDepth(), TTP->getIndex());
113}
114
115/// Retrieve the depth and index of an unexpanded parameter pack.
116inline std::pair<unsignedunsigned>
117getDepthAndIndex(UnexpandedParameterPack UPP) {
118  if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
119    return std::make_pair(TTP->getDepth(), TTP->getIndex());
120
121  return getDepthAndIndex(UPP.first.get<NamedDecl *>());
122}
123
124class TypoCorrectionConsumer : public VisibleDeclConsumer {
125  typedef SmallVector<TypoCorrection1TypoResultList;
126  typedef llvm::StringMap<TypoResultList> TypoResultsMap;
127  typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
128
129public:
130  TypoCorrectionConsumer(Sema &SemaRef,
131                         const DeclarationNameInfo &TypoName,
132                         Sema::LookupNameKind LookupKind,
133                         Scope *SCXXScopeSpec *SS,
134                         std::unique_ptr<CorrectionCandidateCallback> CCC,
135                         DeclContext *MemberContext,
136                         bool EnteringContext)
137      : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
138        SavedTCIndex(0), SemaRef(SemaRef), S(S),
139        SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
140        CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
141        Result(SemaRef, TypoName, LookupKind),
142        Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
143        EnteringContext(EnteringContext), SearchNamespaces(false) {
144    Result.suppressDiagnostics();
145    // Arrange for ValidatedCorrections[0] to always be an empty correction.
146    ValidatedCorrections.push_back(TypoCorrection());
147  }
148
149  bool includeHiddenDecls() const override { return true; }
150
151  // Methods for adding potential corrections to the consumer.
152  void FoundDecl(NamedDecl *NDNamedDecl *HidingDeclContext *Ctx,
153                 bool InBaseClass) override;
154  void FoundName(StringRef Name);
155  void addKeywordResult(StringRef Keyword);
156  void addCorrection(TypoCorrection Correction);
157
158  bool empty() const {
159    return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
160  }
161
162  /// Return the list of TypoCorrections for the given identifier from
163  /// the set of corrections that have the closest edit distance, if any.
164  TypoResultList &operator[](StringRef Name) {
165    return CorrectionResults.begin()->second[Name];
166  }
167
168  /// Return the edit distance of the corrections that have the
169  /// closest/best edit distance from the original typop.
170  unsigned getBestEditDistance(bool Normalized) {
171    if (CorrectionResults.empty())
172      return (std::numeric_limits<unsigned>::max)();
173
174    unsigned BestED = CorrectionResults.begin()->first;
175    return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
176  }
177
178  /// Set-up method to add to the consumer the set of namespaces to use
179  /// in performing corrections to nested name specifiers. This method also
180  /// implicitly adds all of the known classes in the current AST context to the
181  /// to the consumer for correcting nested name specifiers.
182  void
183  addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
184
185  /// Return the next typo correction that passes all internal filters
186  /// and is deemed valid by the consumer's CorrectionCandidateCallback,
187  /// starting with the corrections that have the closest edit distance. An
188  /// empty TypoCorrection is returned once no more viable corrections remain
189  /// in the consumer.
190  const TypoCorrection &getNextCorrection();
191
192  /// Get the last correction returned by getNextCorrection().
193  const TypoCorrection &getCurrentCorrection() {
194    return CurrentTCIndex < ValidatedCorrections.size()
195               ? ValidatedCorrections[CurrentTCIndex]
196               : ValidatedCorrections[0];  // The empty correction.
197  }
198
199  /// Return the next typo correction like getNextCorrection, but keep
200  /// the internal state pointed to the current correction (i.e. the next time
201  /// getNextCorrection is called, it will return the same correction returned
202  /// by peekNextcorrection).
203  const TypoCorrection &peekNextCorrection() {
204    auto Current = CurrentTCIndex;
205    const TypoCorrection &TC = getNextCorrection();
206    CurrentTCIndex = Current;
207    return TC;
208  }
209
210  /// Reset the consumer's position in the stream of viable corrections
211  /// (i.e. getNextCorrection() will return each of the previously returned
212  /// corrections in order before returning any new corrections).
213  void resetCorrectionStream() {
214    CurrentTCIndex = 0;
215  }
216
217  /// Return whether the end of the stream of corrections has been
218  /// reached.
219  bool finished() {
220    return CorrectionResults.empty() &&
221           CurrentTCIndex >= ValidatedCorrections.size();
222  }
223
224  /// Save the current position in the correction stream (overwriting any
225  /// previously saved position).
226  void saveCurrentPosition() {
227    SavedTCIndex = CurrentTCIndex;
228  }
229
230  /// Restore the saved position in the correction stream.
231  void restoreSavedPosition() {
232    CurrentTCIndex = SavedTCIndex;
233  }
234
235  ASTContext &getContext() const { return SemaRef.Context; }
236  const LookupResult &getLookupResult() const { return Result; }
237
238  bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
239  const CXXScopeSpec *getSS() const { return SS.get(); }
240  Scope *getScope() const { return S; }
241  CorrectionCandidateCallback *getCorrectionValidator() const {
242    return CorrectionValidator.get();
243  }
244
245private:
246  class NamespaceSpecifierSet {
247    struct SpecifierInfo {
248      DeclContextDeclCtx;
249      NestedNameSpecifierNameSpecifier;
250      unsigned EditDistance;
251    };
252
253    typedef SmallVector<DeclContext*, 4DeclContextList;
254    typedef SmallVector<SpecifierInfo16SpecifierInfoList;
255
256    ASTContext &Context;
257    DeclContextList CurContextChain;
258    std::string CurNameSpecifier;
259    SmallVector<const IdentifierInfo*, 4CurContextIdentifiers;
260    SmallVector<const IdentifierInfo*, 4CurNameSpecifierIdentifiers;
261
262    std::map<unsigned, SpecifierInfoList> DistanceMap;
263
264    /// Helper for building the list of DeclContexts between the current
265    /// context and the top of the translation unit
266    static DeclContextList buildContextChain(DeclContext *Start);
267
268    unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
269                                      NestedNameSpecifier *&NNS);
270
271   public:
272    NamespaceSpecifierSet(ASTContext &ContextDeclContext *CurContext,
273                          CXXScopeSpec *CurScopeSpec);
274
275    /// Add the DeclContext (a namespace or record) to the set, computing
276    /// the corresponding NestedNameSpecifier and its distance in the process.
277    void addNameSpecifier(DeclContext *Ctx);
278
279    /// Provides flat iteration over specifiers, sorted by distance.
280    class iterator
281        : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
282                                            SpecifierInfo> {
283      /// Always points to the last element in the distance map.
284      const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
285      /// Iterator on the distance map.
286      std::map<unsigned, SpecifierInfoList>::iterator Outer;
287      /// Iterator on an element in the distance map.
288      SpecifierInfoList::iterator Inner;
289
290    public:
291      iterator(NamespaceSpecifierSet &Setbool IsAtEnd)
292          : OuterBack(std::prev(Set.DistanceMap.end())),
293            Outer(Set.DistanceMap.begin()),
294            Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
295        assert(!Set.DistanceMap.empty());
296      }
297
298      iterator &operator++() {
299        ++Inner;
300        if (Inner == Outer->second.end() && Outer != OuterBack) {
301          ++Outer;
302          Inner = Outer->second.begin();
303        }
304        return *this;
305      }
306
307      SpecifierInfo &operator*() { return *Inner; }
308      bool operator==(const iterator &RHSconst { return Inner == RHS.Inner; }
309    };
310
311    iterator begin() { return iterator(*this/*IsAtEnd=*/false); }
312    iterator end() { return iterator(*this/*IsAtEnd=*/true); }
313  };
314
315  void addName(StringRef NameNamedDecl *ND,
316               NestedNameSpecifier *NNS = nullptrbool isKeyword = false);
317
318  /// Find any visible decls for the given typo correction candidate.
319  /// If none are found, it to the set of candidates for which qualified lookups
320  /// will be performed to find possible nested name specifier changes.
321  bool resolveCorrection(TypoCorrection &Candidate);
322
323  /// Perform qualified lookups on the queued set of typo correction
324  /// candidates and add the nested name specifier changes to each candidate if
325  /// a lookup succeeds (at which point the candidate will be returned to the
326  /// main pool of potential corrections).
327  void performQualifiedLookups();
328
329  /// The name written that is a typo in the source.
330  IdentifierInfo *Typo;
331
332  /// The results found that have the smallest edit distance
333  /// found (so far) with the typo name.
334  ///
335  /// The pointer value being set to the current DeclContext indicates
336  /// whether there is a keyword with this name.
337  TypoEditDistanceMap CorrectionResults;
338
339  SmallVector<TypoCorrection4ValidatedCorrections;
340  size_t CurrentTCIndex;
341  size_t SavedTCIndex;
342
343  Sema &SemaRef;
344  Scope *S;
345  std::unique_ptr<CXXScopeSpec> SS;
346  std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
347  DeclContext *MemberContext;
348  LookupResult Result;
349  NamespaceSpecifierSet Namespaces;
350  SmallVector<TypoCorrection2QualifiedResults;
351  bool EnteringContext;
352  bool SearchNamespaces;
353};
354
355inline Sema::TypoExprState::TypoExprState() {}
356
357inline Sema::TypoExprState::TypoExprState(TypoExprState &&othernoexcept {
358  *this = std::move(other);
359}
360
361inline Sema::TypoExprState &Sema::TypoExprState::
362operator=(Sema::TypoExprState &&othernoexcept {
363  Consumer = std::move(other.Consumer);
364  DiagHandler = std::move(other.DiagHandler);
365  RecoveryHandler = std::move(other.RecoveryHandler);
366  return *this;
367}
368
369// end namespace clang
370
371#endif
372
clang::Sema::PDiag
clang::TypoCorrectionConsumer::includeHiddenDecls
clang::TypoCorrectionConsumer::FoundDecl
clang::TypoCorrectionConsumer::FoundName
clang::TypoCorrectionConsumer::addKeywordResult
clang::TypoCorrectionConsumer::addCorrection
clang::TypoCorrectionConsumer::empty
clang::TypoCorrectionConsumer::getBestEditDistance
clang::TypoCorrectionConsumer::addNamespaces
clang::TypoCorrectionConsumer::getNextCorrection
clang::TypoCorrectionConsumer::getCurrentCorrection
clang::TypoCorrectionConsumer::peekNextCorrection
clang::TypoCorrectionConsumer::resetCorrectionStream
clang::TypoCorrectionConsumer::finished
clang::TypoCorrectionConsumer::saveCurrentPosition
clang::TypoCorrectionConsumer::restoreSavedPosition
clang::TypoCorrectionConsumer::getContext
clang::TypoCorrectionConsumer::getLookupResult
clang::TypoCorrectionConsumer::isAddressOfOperand
clang::TypoCorrectionConsumer::getSS
clang::TypoCorrectionConsumer::getScope
clang::TypoCorrectionConsumer::getCorrectionValidator
clang::TypoCorrectionConsumer::NamespaceSpecifierSet
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::SpecifierInfo
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::SpecifierInfo::DeclCtx
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::SpecifierInfo::NameSpecifier
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::SpecifierInfo::EditDistance
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::Context
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::CurContextChain
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::CurNameSpecifier
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::CurContextIdentifiers
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::CurNameSpecifierIdentifiers
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::DistanceMap
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::iterator
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::iterator::OuterBack
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::iterator::Outer
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::iterator::Inner
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::begin
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::end
clang::TypoCorrectionConsumer::addName
clang::TypoCorrectionConsumer::resolveCorrection
clang::TypoCorrectionConsumer::performQualifiedLookups
clang::TypoCorrectionConsumer::Typo
clang::TypoCorrectionConsumer::CorrectionResults
clang::TypoCorrectionConsumer::ValidatedCorrections
clang::TypoCorrectionConsumer::CurrentTCIndex
clang::TypoCorrectionConsumer::SavedTCIndex
clang::TypoCorrectionConsumer::SemaRef
clang::TypoCorrectionConsumer::S
clang::TypoCorrectionConsumer::SS
clang::TypoCorrectionConsumer::CorrectionValidator
clang::TypoCorrectionConsumer::MemberContext
clang::TypoCorrectionConsumer::Result
clang::TypoCorrectionConsumer::Namespaces
clang::TypoCorrectionConsumer::QualifiedResults
clang::TypoCorrectionConsumer::EnteringContext
clang::TypoCorrectionConsumer::SearchNamespaces