1212795Sdim//===--- SemaInternal.h - Internal Sema Interfaces --------------*- C++ -*-===//
2212795Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6212795Sdim//
7212795Sdim//===----------------------------------------------------------------------===//
8212795Sdim//
9212795Sdim// This file provides common API and #includes for the internal
10212795Sdim// implementation of Sema.
11212795Sdim//
12212795Sdim//===----------------------------------------------------------------------===//
13212795Sdim
14280031Sdim#ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
15280031Sdim#define LLVM_CLANG_SEMA_SEMAINTERNAL_H
16212795Sdim
17249423Sdim#include "clang/AST/ASTContext.h"
18280031Sdim#include "clang/Sema/Lookup.h"
19212795Sdim#include "clang/Sema/Sema.h"
20212795Sdim#include "clang/Sema/SemaDiagnostic.h"
21212795Sdim
22212795Sdimnamespace clang {
23212795Sdim
24212795Sdiminline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
25212795Sdim  return PartialDiagnostic(DiagID, Context.getDiagAllocator());
26212795Sdim}
27276479Sdim
28276479Sdiminline bool
29276479SdimFTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
30276479Sdim  return FTI.NumParams == 1 && !FTI.isVariadic &&
31276479Sdim         FTI.Params[0].Ident == nullptr && FTI.Params[0].Param &&
32276479Sdim         cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType();
33212795Sdim}
34276479Sdim
35276479Sdiminline bool
36276479SdimFTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
37276479Sdim  // Assume FTI is well-formed.
38276479Sdim  return FTI.NumParams && !FTIHasSingleVoidParameter(FTI);
39261991Sdim}
40212795Sdim
41288943Sdim// Helper function to check whether D's attributes match current CUDA mode.
42288943Sdim// Decls with mismatched attributes and related diagnostics may have to be
43288943Sdim// ignored during this CUDA compilation pass.
44288943Sdiminline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
45288943Sdim  if (!LangOpts.CUDA || !D)
46288943Sdim    return true;
47288943Sdim  bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
48288943Sdim                          D->hasAttr<CUDASharedAttr>() ||
49288943Sdim                          D->hasAttr<CUDAGlobalAttr>();
50288943Sdim  return isDeviceSideDecl == LangOpts.CUDAIsDevice;
51288943Sdim}
52288943Sdim
53276479Sdim/// Return a DLL attribute from the declaration.
54276479Sdiminline InheritableAttr *getDLLAttr(Decl *D) {
55276479Sdim  assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
56276479Sdim         "A declaration cannot be both dllimport and dllexport.");
57276479Sdim  if (auto *Import = D->getAttr<DLLImportAttr>())
58276479Sdim    return Import;
59276479Sdim  if (auto *Export = D->getAttr<DLLExportAttr>())
60276479Sdim    return Export;
61276479Sdim  return nullptr;
62276479Sdim}
63276479Sdim
64341825Sdim/// Retrieve the depth and index of a template parameter.
65341825Sdiminline std::pair<unsigned, unsigned> getDepthAndIndex(NamedDecl *ND) {
66341825Sdim  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
67341825Sdim    return std::make_pair(TTP->getDepth(), TTP->getIndex());
68341825Sdim
69341825Sdim  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
70341825Sdim    return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
71341825Sdim
72341825Sdim  const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
73341825Sdim  return std::make_pair(TTP->getDepth(), TTP->getIndex());
74341825Sdim}
75341825Sdim
76341825Sdim/// Retrieve the depth and index of an unexpanded parameter pack.
77341825Sdiminline std::pair<unsigned, unsigned>
78341825SdimgetDepthAndIndex(UnexpandedParameterPack UPP) {
79341825Sdim  if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
80341825Sdim    return std::make_pair(TTP->getDepth(), TTP->getIndex());
81341825Sdim
82341825Sdim  return getDepthAndIndex(UPP.first.get<NamedDecl *>());
83341825Sdim}
84341825Sdim
85280031Sdimclass TypoCorrectionConsumer : public VisibleDeclConsumer {
86280031Sdim  typedef SmallVector<TypoCorrection, 1> TypoResultList;
87280031Sdim  typedef llvm::StringMap<TypoResultList> TypoResultsMap;
88280031Sdim  typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
89280031Sdim
90280031Sdimpublic:
91280031Sdim  TypoCorrectionConsumer(Sema &SemaRef,
92280031Sdim                         const DeclarationNameInfo &TypoName,
93280031Sdim                         Sema::LookupNameKind LookupKind,
94280031Sdim                         Scope *S, CXXScopeSpec *SS,
95280031Sdim                         std::unique_ptr<CorrectionCandidateCallback> CCC,
96280031Sdim                         DeclContext *MemberContext,
97280031Sdim                         bool EnteringContext)
98280031Sdim      : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
99280031Sdim        SavedTCIndex(0), SemaRef(SemaRef), S(S),
100360784Sdim        SS(SS ? std::make_unique<CXXScopeSpec>(*SS) : nullptr),
101280031Sdim        CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
102280031Sdim        Result(SemaRef, TypoName, LookupKind),
103280031Sdim        Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
104280031Sdim        EnteringContext(EnteringContext), SearchNamespaces(false) {
105280031Sdim    Result.suppressDiagnostics();
106280031Sdim    // Arrange for ValidatedCorrections[0] to always be an empty correction.
107280031Sdim    ValidatedCorrections.push_back(TypoCorrection());
108280031Sdim  }
109280031Sdim
110280031Sdim  bool includeHiddenDecls() const override { return true; }
111280031Sdim
112280031Sdim  // Methods for adding potential corrections to the consumer.
113280031Sdim  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
114280031Sdim                 bool InBaseClass) override;
115280031Sdim  void FoundName(StringRef Name);
116280031Sdim  void addKeywordResult(StringRef Keyword);
117280031Sdim  void addCorrection(TypoCorrection Correction);
118280031Sdim
119280031Sdim  bool empty() const {
120280031Sdim    return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
121280031Sdim  }
122280031Sdim
123341825Sdim  /// Return the list of TypoCorrections for the given identifier from
124280031Sdim  /// the set of corrections that have the closest edit distance, if any.
125280031Sdim  TypoResultList &operator[](StringRef Name) {
126280031Sdim    return CorrectionResults.begin()->second[Name];
127280031Sdim  }
128280031Sdim
129341825Sdim  /// Return the edit distance of the corrections that have the
130280031Sdim  /// closest/best edit distance from the original typop.
131280031Sdim  unsigned getBestEditDistance(bool Normalized) {
132280031Sdim    if (CorrectionResults.empty())
133280031Sdim      return (std::numeric_limits<unsigned>::max)();
134280031Sdim
135280031Sdim    unsigned BestED = CorrectionResults.begin()->first;
136280031Sdim    return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
137280031Sdim  }
138280031Sdim
139341825Sdim  /// Set-up method to add to the consumer the set of namespaces to use
140280031Sdim  /// in performing corrections to nested name specifiers. This method also
141280031Sdim  /// implicitly adds all of the known classes in the current AST context to the
142280031Sdim  /// to the consumer for correcting nested name specifiers.
143280031Sdim  void
144280031Sdim  addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
145280031Sdim
146341825Sdim  /// Return the next typo correction that passes all internal filters
147280031Sdim  /// and is deemed valid by the consumer's CorrectionCandidateCallback,
148280031Sdim  /// starting with the corrections that have the closest edit distance. An
149280031Sdim  /// empty TypoCorrection is returned once no more viable corrections remain
150280031Sdim  /// in the consumer.
151280031Sdim  const TypoCorrection &getNextCorrection();
152280031Sdim
153341825Sdim  /// Get the last correction returned by getNextCorrection().
154280031Sdim  const TypoCorrection &getCurrentCorrection() {
155280031Sdim    return CurrentTCIndex < ValidatedCorrections.size()
156280031Sdim               ? ValidatedCorrections[CurrentTCIndex]
157280031Sdim               : ValidatedCorrections[0];  // The empty correction.
158280031Sdim  }
159280031Sdim
160341825Sdim  /// Return the next typo correction like getNextCorrection, but keep
161280031Sdim  /// the internal state pointed to the current correction (i.e. the next time
162280031Sdim  /// getNextCorrection is called, it will return the same correction returned
163280031Sdim  /// by peekNextcorrection).
164280031Sdim  const TypoCorrection &peekNextCorrection() {
165280031Sdim    auto Current = CurrentTCIndex;
166280031Sdim    const TypoCorrection &TC = getNextCorrection();
167280031Sdim    CurrentTCIndex = Current;
168280031Sdim    return TC;
169280031Sdim  }
170280031Sdim
171341825Sdim  /// Reset the consumer's position in the stream of viable corrections
172280031Sdim  /// (i.e. getNextCorrection() will return each of the previously returned
173280031Sdim  /// corrections in order before returning any new corrections).
174280031Sdim  void resetCorrectionStream() {
175280031Sdim    CurrentTCIndex = 0;
176280031Sdim  }
177280031Sdim
178341825Sdim  /// Return whether the end of the stream of corrections has been
179280031Sdim  /// reached.
180280031Sdim  bool finished() {
181280031Sdim    return CorrectionResults.empty() &&
182280031Sdim           CurrentTCIndex >= ValidatedCorrections.size();
183280031Sdim  }
184280031Sdim
185341825Sdim  /// Save the current position in the correction stream (overwriting any
186280031Sdim  /// previously saved position).
187280031Sdim  void saveCurrentPosition() {
188280031Sdim    SavedTCIndex = CurrentTCIndex;
189280031Sdim  }
190280031Sdim
191341825Sdim  /// Restore the saved position in the correction stream.
192280031Sdim  void restoreSavedPosition() {
193280031Sdim    CurrentTCIndex = SavedTCIndex;
194280031Sdim  }
195280031Sdim
196280031Sdim  ASTContext &getContext() const { return SemaRef.Context; }
197280031Sdim  const LookupResult &getLookupResult() const { return Result; }
198280031Sdim
199280031Sdim  bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
200280031Sdim  const CXXScopeSpec *getSS() const { return SS.get(); }
201280031Sdim  Scope *getScope() const { return S; }
202309124Sdim  CorrectionCandidateCallback *getCorrectionValidator() const {
203309124Sdim    return CorrectionValidator.get();
204309124Sdim  }
205280031Sdim
206280031Sdimprivate:
207280031Sdim  class NamespaceSpecifierSet {
208280031Sdim    struct SpecifierInfo {
209280031Sdim      DeclContext* DeclCtx;
210280031Sdim      NestedNameSpecifier* NameSpecifier;
211280031Sdim      unsigned EditDistance;
212280031Sdim    };
213280031Sdim
214280031Sdim    typedef SmallVector<DeclContext*, 4> DeclContextList;
215280031Sdim    typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
216280031Sdim
217280031Sdim    ASTContext &Context;
218280031Sdim    DeclContextList CurContextChain;
219280031Sdim    std::string CurNameSpecifier;
220280031Sdim    SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
221280031Sdim    SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
222280031Sdim
223288943Sdim    std::map<unsigned, SpecifierInfoList> DistanceMap;
224280031Sdim
225341825Sdim    /// Helper for building the list of DeclContexts between the current
226280031Sdim    /// context and the top of the translation unit
227280031Sdim    static DeclContextList buildContextChain(DeclContext *Start);
228280031Sdim
229280031Sdim    unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
230280031Sdim                                      NestedNameSpecifier *&NNS);
231280031Sdim
232280031Sdim   public:
233280031Sdim    NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
234280031Sdim                          CXXScopeSpec *CurScopeSpec);
235280031Sdim
236341825Sdim    /// Add the DeclContext (a namespace or record) to the set, computing
237280031Sdim    /// the corresponding NestedNameSpecifier and its distance in the process.
238280031Sdim    void addNameSpecifier(DeclContext *Ctx);
239280031Sdim
240341825Sdim    /// Provides flat iteration over specifiers, sorted by distance.
241288943Sdim    class iterator
242288943Sdim        : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
243288943Sdim                                            SpecifierInfo> {
244288943Sdim      /// Always points to the last element in the distance map.
245288943Sdim      const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
246288943Sdim      /// Iterator on the distance map.
247288943Sdim      std::map<unsigned, SpecifierInfoList>::iterator Outer;
248288943Sdim      /// Iterator on an element in the distance map.
249288943Sdim      SpecifierInfoList::iterator Inner;
250288943Sdim
251288943Sdim    public:
252288943Sdim      iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
253288943Sdim          : OuterBack(std::prev(Set.DistanceMap.end())),
254288943Sdim            Outer(Set.DistanceMap.begin()),
255288943Sdim            Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
256288943Sdim        assert(!Set.DistanceMap.empty());
257288943Sdim      }
258288943Sdim
259288943Sdim      iterator &operator++() {
260288943Sdim        ++Inner;
261288943Sdim        if (Inner == Outer->second.end() && Outer != OuterBack) {
262288943Sdim          ++Outer;
263288943Sdim          Inner = Outer->second.begin();
264288943Sdim        }
265288943Sdim        return *this;
266288943Sdim      }
267288943Sdim
268288943Sdim      SpecifierInfo &operator*() { return *Inner; }
269288943Sdim      bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
270288943Sdim    };
271288943Sdim
272288943Sdim    iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
273288943Sdim    iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
274280031Sdim  };
275280031Sdim
276280031Sdim  void addName(StringRef Name, NamedDecl *ND,
277280031Sdim               NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
278280031Sdim
279341825Sdim  /// Find any visible decls for the given typo correction candidate.
280280031Sdim  /// If none are found, it to the set of candidates for which qualified lookups
281280031Sdim  /// will be performed to find possible nested name specifier changes.
282280031Sdim  bool resolveCorrection(TypoCorrection &Candidate);
283280031Sdim
284341825Sdim  /// Perform qualified lookups on the queued set of typo correction
285280031Sdim  /// candidates and add the nested name specifier changes to each candidate if
286280031Sdim  /// a lookup succeeds (at which point the candidate will be returned to the
287280031Sdim  /// main pool of potential corrections).
288280031Sdim  void performQualifiedLookups();
289280031Sdim
290341825Sdim  /// The name written that is a typo in the source.
291280031Sdim  IdentifierInfo *Typo;
292280031Sdim
293341825Sdim  /// The results found that have the smallest edit distance
294280031Sdim  /// found (so far) with the typo name.
295280031Sdim  ///
296280031Sdim  /// The pointer value being set to the current DeclContext indicates
297280031Sdim  /// whether there is a keyword with this name.
298280031Sdim  TypoEditDistanceMap CorrectionResults;
299280031Sdim
300280031Sdim  SmallVector<TypoCorrection, 4> ValidatedCorrections;
301280031Sdim  size_t CurrentTCIndex;
302280031Sdim  size_t SavedTCIndex;
303280031Sdim
304280031Sdim  Sema &SemaRef;
305280031Sdim  Scope *S;
306280031Sdim  std::unique_ptr<CXXScopeSpec> SS;
307280031Sdim  std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
308280031Sdim  DeclContext *MemberContext;
309280031Sdim  LookupResult Result;
310280031Sdim  NamespaceSpecifierSet Namespaces;
311280031Sdim  SmallVector<TypoCorrection, 2> QualifiedResults;
312280031Sdim  bool EnteringContext;
313280031Sdim  bool SearchNamespaces;
314280031Sdim};
315280031Sdim
316280031Sdiminline Sema::TypoExprState::TypoExprState() {}
317280031Sdim
318314564Sdiminline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
319280031Sdim  *this = std::move(other);
320276479Sdim}
321276479Sdim
322314564Sdiminline Sema::TypoExprState &Sema::TypoExprState::
323314564Sdimoperator=(Sema::TypoExprState &&other) noexcept {
324280031Sdim  Consumer = std::move(other.Consumer);
325280031Sdim  DiagHandler = std::move(other.DiagHandler);
326280031Sdim  RecoveryHandler = std::move(other.RecoveryHandler);
327280031Sdim  return *this;
328280031Sdim}
329280031Sdim
330280031Sdim} // end namespace clang
331280031Sdim
332212795Sdim#endif
333