diff options
author | Dimitry Andric <dim@FreeBSD.org> | 2018-07-28 11:06:01 +0000 |
---|---|---|
committer | Dimitry Andric <dim@FreeBSD.org> | 2018-07-28 11:06:01 +0000 |
commit | 486754660bb926339aefcf012a3f848592babb8b (patch) | |
tree | ecdbc446c9876f4f120f701c243373cd3cb43db3 /lib/Sema/SemaCodeComplete.cpp | |
parent | 55e6d896ad333f07bb3b1ba487df214fc268a4ab (diff) |
Notes
Diffstat (limited to 'lib/Sema/SemaCodeComplete.cpp')
-rw-r--r-- | lib/Sema/SemaCodeComplete.cpp | 2365 |
1 files changed, 1232 insertions, 1133 deletions
diff --git a/lib/Sema/SemaCodeComplete.cpp b/lib/Sema/SemaCodeComplete.cpp index 9aed178763dc9..4e571eba17e96 100644 --- a/lib/Sema/SemaCodeComplete.cpp +++ b/lib/Sema/SemaCodeComplete.cpp @@ -40,39 +40,39 @@ using namespace clang; using namespace sema; namespace { - /// \brief A container of code-completion results. + /// A container of code-completion results. class ResultBuilder { public: - /// \brief The type of a name-lookup filter, which can be provided to the + /// The type of a name-lookup filter, which can be provided to the /// name-lookup routines to specify which declarations should be included in /// the result set (when it returns true) and which declarations should be /// filtered out (returns false). typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const; typedef CodeCompletionResult Result; - + private: - /// \brief The actual results we have found. + /// The actual results we have found. std::vector<Result> Results; - - /// \brief A record of all of the declarations we have found and placed + + /// A record of all of the declarations we have found and placed /// into the result set, used to ensure that no declaration ever gets into /// the result set twice. llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound; - + typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair; - /// \brief An entry in the shadow map, which is optimized to store + /// An entry in the shadow map, which is optimized to store /// a single (declaration, index) mapping (the common case) but /// can also store a list of (declaration, index) mappings. class ShadowMapEntry { typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector; - /// \brief Contains either the solitary NamedDecl * or a vector + /// Contains either the solitary NamedDecl * or a vector /// of (declaration, index) pairs. llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector; - /// \brief When the entry contains a single declaration, this is + /// When the entry contains a single declaration, this is /// the index associated with that entry. unsigned SingleDeclIndex; @@ -115,72 +115,72 @@ namespace { iterator end() const; }; - /// \brief A mapping from declaration names to the declarations that have + /// A mapping from declaration names to the declarations that have /// this name within a particular scope and their index within the list of /// results. typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; - - /// \brief The semantic analysis object for which results are being + + /// The semantic analysis object for which results are being /// produced. Sema &SemaRef; - /// \brief The allocator used to allocate new code-completion strings. + /// The allocator used to allocate new code-completion strings. CodeCompletionAllocator &Allocator; CodeCompletionTUInfo &CCTUInfo; - - /// \brief If non-NULL, a filter function used to remove any code-completion + + /// If non-NULL, a filter function used to remove any code-completion /// results that are not desirable. LookupFilter Filter; - /// \brief Whether we should allow declarations as + /// Whether we should allow declarations as /// nested-name-specifiers that would otherwise be filtered out. bool AllowNestedNameSpecifiers; - /// \brief If set, the type that we would prefer our resulting value + /// If set, the type that we would prefer our resulting value /// declarations to have. /// - /// Closely matching the preferred type gives a boost to a result's + /// Closely matching the preferred type gives a boost to a result's /// priority. CanQualType PreferredType; - - /// \brief A list of shadow maps, which is used to model name hiding at + + /// A list of shadow maps, which is used to model name hiding at /// different levels of, e.g., the inheritance hierarchy. std::list<ShadowMap> ShadowMaps; - - /// \brief If we're potentially referring to a C++ member function, the set + + /// If we're potentially referring to a C++ member function, the set /// of qualifiers applied to the object type. Qualifiers ObjectTypeQualifiers; - - /// \brief Whether the \p ObjectTypeQualifiers field is active. + + /// Whether the \p ObjectTypeQualifiers field is active. bool HasObjectTypeQualifiers; - - /// \brief The selector that we prefer. + + /// The selector that we prefer. Selector PreferredSelector; - - /// \brief The completion context in which we are gathering results. + + /// The completion context in which we are gathering results. CodeCompletionContext CompletionContext; - - /// \brief If we are in an instance method definition, the \@implementation + + /// If we are in an instance method definition, the \@implementation /// object. ObjCImplementationDecl *ObjCImplementation; void AdjustResultPriorityForDecl(Result &R); void MaybeAddConstructorResults(Result R); - + public: explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, const CodeCompletionContext &CompletionContext, LookupFilter Filter = nullptr) : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo), - Filter(Filter), - AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false), + Filter(Filter), + AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false), CompletionContext(CompletionContext), ObjCImplementation(nullptr) - { - // If this is an Objective-C instance method definition, dig out the + { + // If this is an Objective-C instance method definition, dig out the // corresponding implementation. switch (CompletionContext.getKind()) { case CodeCompletionContext::CCC_Expression: @@ -193,23 +193,23 @@ namespace { if (ObjCInterfaceDecl *Interface = Method->getClassInterface()) ObjCImplementation = Interface->getImplementation(); break; - + default: break; } } - /// \brief Determine the priority for a reference to the given declaration. + /// Determine the priority for a reference to the given declaration. unsigned getBasePriority(const NamedDecl *D); - /// \brief Whether we should include code patterns in the completion + /// Whether we should include code patterns in the completion /// results. bool includeCodePatterns() const { - return SemaRef.CodeCompleter && + return SemaRef.CodeCompleter && SemaRef.CodeCompleter->includeCodePatterns(); } - - /// \brief Set the filter used for code-completion results. + + /// Set the filter used for code-completion results. void setFilter(LookupFilter Filter) { this->Filter = Filter; } @@ -217,25 +217,25 @@ namespace { Result *data() { return Results.empty()? nullptr : &Results.front(); } unsigned size() const { return Results.size(); } bool empty() const { return Results.empty(); } - - /// \brief Specify the preferred type. - void setPreferredType(QualType T) { - PreferredType = SemaRef.Context.getCanonicalType(T); + + /// Specify the preferred type. + void setPreferredType(QualType T) { + PreferredType = SemaRef.Context.getCanonicalType(T); } - - /// \brief Set the cv-qualifiers on the object type, for us in filtering + + /// Set the cv-qualifiers on the object type, for us in filtering /// calls to member functions. /// /// When there are qualifiers in this set, they will be used to filter - /// out member functions that aren't available (because there will be a + /// out member functions that aren't available (because there will be a /// cv-qualifier mismatch) or prefer functions with an exact qualifier /// match. void setObjectTypeQualifiers(Qualifiers Quals) { ObjectTypeQualifiers = Quals; HasObjectTypeQualifiers = true; } - - /// \brief Set the preferred selector. + + /// Set the preferred selector. /// /// When an Objective-C method declaration result is added, and that /// method's selector matches this preferred selector, we give that method @@ -243,28 +243,28 @@ namespace { void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; } - - /// \brief Retrieve the code-completion context for which results are + + /// Retrieve the code-completion context for which results are /// being collected. - const CodeCompletionContext &getCompletionContext() const { - return CompletionContext; + const CodeCompletionContext &getCompletionContext() const { + return CompletionContext; } - - /// \brief Specify whether nested-name-specifiers are allowed. + + /// Specify whether nested-name-specifiers are allowed. void allowNestedNameSpecifiers(bool Allow = true) { AllowNestedNameSpecifiers = Allow; } - /// \brief Return the semantic analysis object for which we are collecting + /// Return the semantic analysis object for which we are collecting /// code completion results. Sema &getSema() const { return SemaRef; } - - /// \brief Retrieve the allocator used to allocate code completion strings. + + /// Retrieve the allocator used to allocate code completion strings. CodeCompletionAllocator &getAllocator() const { return Allocator; } CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; } - - /// \brief Determine whether the given declaration is at all interesting + + /// Determine whether the given declaration is at all interesting /// as a code-completion result. /// /// \param ND the declaration that we are inspecting. @@ -273,8 +273,8 @@ namespace { /// only interesting when it is a nested-name-specifier. bool isInterestingDecl(const NamedDecl *ND, bool &AsNestedNameSpecifier) const; - - /// \brief Check whether the result is hidden by the Hiding declaration. + + /// Check whether the result is hidden by the Hiding declaration. /// /// \returns true if the result is hidden and cannot be found, false if /// the hidden result could still be found. When false, \p R may be @@ -282,9 +282,9 @@ namespace { /// qualification). bool CheckHiddenResult(Result &R, DeclContext *CurContext, const NamedDecl *Hiding); - - /// \brief Add a new result to this result set (if it isn't already in one - /// of the shadow maps), or replace an existing result (for, e.g., a + + /// Add a new result to this result set (if it isn't already in one + /// of the shadow maps), or replace an existing result (for, e.g., a /// redeclaration). /// /// \param R the result to add (if it is unique). @@ -292,7 +292,7 @@ namespace { /// \param CurContext the context in which this result will be named. void MaybeAddResult(Result R, DeclContext *CurContext = nullptr); - /// \brief Add a new result to this result set, where we already know + /// Add a new result to this result set, where we already know /// the hiding declaration (if any). /// /// \param R the result to add (if it is unique). @@ -305,24 +305,29 @@ namespace { /// class of the searched context. void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding, bool InBaseClass); - - /// \brief Add a new non-declaration result to this result set. + + /// Add a new non-declaration result to this result set. void AddResult(Result R); - /// \brief Enter into a new scope. + /// Enter into a new scope. void EnterNewScope(); - - /// \brief Exit from the current scope. + + /// Exit from the current scope. void ExitScope(); - - /// \brief Ignore this declaration, if it is seen again. + + /// Ignore this declaration, if it is seen again. void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); } + /// Add a visited context. + void addVisitedContext(DeclContext *Ctx) { + CompletionContext.addVisitedContext(Ctx); + } + /// \name Name lookup predicates /// /// These predicates can be passed to the name lookup functions to filter the /// results of name lookup. All of the predicates have the same type, so that - /// + /// //@{ bool IsOrdinaryName(const NamedDecl *ND) const; bool IsOrdinaryNonTypeName(const NamedDecl *ND) const; @@ -341,8 +346,8 @@ namespace { bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const; bool IsObjCCollection(const NamedDecl *ND) const; bool IsImpossibleToSatisfy(const NamedDecl *ND) const; - //@} - }; + //@} + }; } class ResultBuilder::ShadowMapEntry::iterator { @@ -354,7 +359,7 @@ public: typedef value_type reference; typedef std::ptrdiff_t difference_type; typedef std::input_iterator_tag iterator_category; - + class pointer { DeclIndexPair Value; @@ -415,7 +420,7 @@ public: } }; -ResultBuilder::ShadowMapEntry::iterator +ResultBuilder::ShadowMapEntry::iterator ResultBuilder::ShadowMapEntry::begin() const { if (DeclOrVector.isNull()) return iterator(); @@ -426,7 +431,7 @@ ResultBuilder::ShadowMapEntry::begin() const { return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin()); } -ResultBuilder::ShadowMapEntry::iterator +ResultBuilder::ShadowMapEntry::iterator ResultBuilder::ShadowMapEntry::end() const { if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull()) return iterator(); @@ -434,7 +439,7 @@ ResultBuilder::ShadowMapEntry::end() const { return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end()); } -/// \brief Compute the qualification required to get from the current context +/// Compute the qualification required to get from the current context /// (\p CurContext) to the target context (\p TargetContext). /// /// \param Context the AST context in which the qualification will be used. @@ -442,7 +447,7 @@ ResultBuilder::ShadowMapEntry::end() const { /// \param CurContext the context where an entity is being named, which is /// typically based on the current scope. /// -/// \param TargetContext the context in which the named entity actually +/// \param TargetContext the context in which the named entity actually /// resides. /// /// \returns a nested name specifier that refers into the target context, or @@ -452,14 +457,14 @@ getRequiredQualification(ASTContext &Context, const DeclContext *CurContext, const DeclContext *TargetContext) { SmallVector<const DeclContext *, 4> TargetParents; - + for (const DeclContext *CommonAncestor = TargetContext; CommonAncestor && !CommonAncestor->Encloses(CurContext); CommonAncestor = CommonAncestor->getLookupParent()) { if (CommonAncestor->isTransparentContext() || CommonAncestor->isFunctionOrMethod()) continue; - + TargetParents.push_back(CommonAncestor); } @@ -477,7 +482,7 @@ getRequiredQualification(ASTContext &Context, Result = NestedNameSpecifier::Create(Context, Result, false, Context.getTypeDeclType(TD).getTypePtr()); - } + } return Result; } @@ -526,17 +531,17 @@ bool ResultBuilder::isInterestingDecl(const NamedDecl *ND, // Skip unnamed entities. if (!ND->getDeclName()) return false; - + // Friend declarations and declarations introduced due to friends are never // added as results. if (ND->getFriendObjectKind() == Decl::FOK_Undeclared) return false; - + // Class template (partial) specializations are never added as results. if (isa<ClassTemplateSpecializationDecl>(ND) || isa<ClassTemplatePartialSpecializationDecl>(ND)) return false; - + // Using declarations themselves are never added as results. if (isa<UsingDecl>(ND)) return false; @@ -554,17 +559,17 @@ bool ResultBuilder::isInterestingDecl(const NamedDecl *ND, // Filter out any unwanted results. if (Filter && !(this->*Filter)(Named)) { // Check whether it is interesting as a nested-name-specifier. - if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus && + if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus && IsNestedNameSpecifier(ND) && (Filter != &ResultBuilder::IsMember || - (isa<CXXRecordDecl>(ND) && + (isa<CXXRecordDecl>(ND) && cast<CXXRecordDecl>(ND)->isInjectedClassName()))) { AsNestedNameSpecifier = true; return true; } return false; - } + } // ... then it must be interesting! return true; } @@ -576,29 +581,29 @@ bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext, // name if we introduce the tag type. if (!SemaRef.getLangOpts().CPlusPlus) return true; - + const DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext(); - + // There is no way to qualify a name declared in a function or method. if (HiddenCtx->isFunctionOrMethod()) return true; - + if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext()) return true; - + // We can refer to the result with the appropriate qualification. Do it. R.Hidden = true; R.QualifierIsInformative = false; - + if (!R.Qualifier) - R.Qualifier = getRequiredQualification(SemaRef.Context, - CurContext, + R.Qualifier = getRequiredQualification(SemaRef.Context, + CurContext, R.Declaration->getDeclContext()); return false; } -/// \brief A simplified classification of types used to determine whether two +/// A simplified classification of types used to determine whether two /// types are "similar enough" when adjusting priorities. SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) { switch (T->getTypeClass()) { @@ -606,77 +611,77 @@ SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) { switch (cast<BuiltinType>(T)->getKind()) { case BuiltinType::Void: return STC_Void; - + case BuiltinType::NullPtr: return STC_Pointer; - + case BuiltinType::Overload: case BuiltinType::Dependent: return STC_Other; - + case BuiltinType::ObjCId: case BuiltinType::ObjCClass: case BuiltinType::ObjCSel: return STC_ObjectiveC; - + default: return STC_Arithmetic; } case Type::Complex: return STC_Arithmetic; - + case Type::Pointer: return STC_Pointer; - + case Type::BlockPointer: return STC_Block; - + case Type::LValueReference: case Type::RValueReference: return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType()); - + case Type::ConstantArray: case Type::IncompleteArray: case Type::VariableArray: case Type::DependentSizedArray: return STC_Array; - + case Type::DependentSizedExtVector: case Type::Vector: case Type::ExtVector: return STC_Arithmetic; - + case Type::FunctionProto: case Type::FunctionNoProto: return STC_Function; - + case Type::Record: return STC_Record; - + case Type::Enum: return STC_Arithmetic; - + case Type::ObjCObject: case Type::ObjCInterface: case Type::ObjCObjectPointer: return STC_ObjectiveC; - + default: return STC_Other; } } -/// \brief Get the type that a given expression will have if this declaration +/// Get the type that a given expression will have if this declaration /// is used as an expression in its "typical" code-completion form. QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) { - ND = cast<NamedDecl>(ND->getUnderlyingDecl()); - + ND = ND->getUnderlyingDecl(); + if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND)) return C.getTypeDeclType(Type); if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND)) return C.getObjCInterfaceType(Iface); - + QualType T; if (const FunctionDecl *Function = ND->getAsFunction()) T = Function->getCallResultType(); @@ -721,7 +726,7 @@ QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) { break; } while (true); - + return T; } @@ -781,7 +786,7 @@ void ResultBuilder::AdjustResultPriorityForDecl(Result &R) { if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration)) if (PreferredSelector == Method->getSelector()) R.Priority += CCD_SelectorMatch; - + // If we have a preferred type, adjust the priority for results with exactly- // matching or nearly-matching types. if (!PreferredType.isNull()) { @@ -795,16 +800,16 @@ void ResultBuilder::AdjustResultPriorityForDecl(Result &R) { else if ((getSimplifiedTypeClass(PreferredType) == getSimplifiedTypeClass(TC)) && !(PreferredType->isEnumeralType() && TC->isEnumeralType())) - R.Priority /= CCF_SimilarTypeMatch; + R.Priority /= CCF_SimilarTypeMatch; } - } + } } void ResultBuilder::MaybeAddConstructorResults(Result R) { if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration || !CompletionContext.wantConstructorResults()) return; - + ASTContext &Context = SemaRef.Context; const NamedDecl *D = R.Declaration; const CXXRecordDecl *Record = nullptr; @@ -818,12 +823,12 @@ void ResultBuilder::MaybeAddConstructorResults(Result R) { // There are no constructors here. return; } - + Record = Record->getDefinition(); if (!Record) return; - + QualType RecordTy = Context.getTypeDeclType(Record); DeclarationName ConstructorName = Context.DeclarationNames.getCXXConstructorName( @@ -838,9 +843,15 @@ void ResultBuilder::MaybeAddConstructorResults(Result R) { } } +static bool isConstructor(const Decl *ND) { + if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND)) + ND = Tmpl->getTemplatedDecl(); + return isa<CXXConstructorDecl>(ND); +} + void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { assert(!ShadowMaps.empty() && "Must enter into a results scope"); - + if (R.Kind != Result::RK_Declaration) { // For non-declaration results, just add the result. Results.push_back(R); @@ -848,24 +859,24 @@ void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { } // Look through using declarations. - if (const UsingShadowDecl *Using = - dyn_cast<UsingShadowDecl>(R.Declaration)) { - MaybeAddResult(Result(Using->getTargetDecl(), - getBasePriority(Using->getTargetDecl()), - R.Qualifier), - CurContext); + if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) { + CodeCompletionResult Result(Using->getTargetDecl(), + getBasePriority(Using->getTargetDecl()), + R.Qualifier); + Result.ShadowDecl = Using; + MaybeAddResult(Result, CurContext); return; } - + const Decl *CanonDecl = R.Declaration->getCanonicalDecl(); unsigned IDNS = CanonDecl->getIdentifierNamespace(); bool AsNestedNameSpecifier = false; if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) return; - + // C++ constructors are never found by name lookup. - if (isa<CXXConstructorDecl>(R.Declaration)) + if (isConstructor(R.Declaration)) return; ShadowMap &SMap = ShadowMaps.back(); @@ -882,12 +893,12 @@ void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { if (ND->getCanonicalDecl() == CanonDecl) { // This is a redeclaration. Always pick the newer declaration. Results[Index].Declaration = R.Declaration; - + // We're done. return; } } - + // This is a new declaration in this scope. However, check whether this // declaration name is hidden by a similarly-named declaration in an outer // scope. @@ -906,21 +917,21 @@ void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol))) continue; - + // Protocols are in distinct namespaces from everything else. if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) || (IDNS & Decl::IDNS_ObjCProtocol)) && I->first->getIdentifierNamespace() != IDNS) continue; - + // The newly-added result is hidden by an entry in the shadow map. if (CheckHiddenResult(R, CurContext, I->first)) return; - + break; } } - + // Make sure that any given declaration only shows up in the result set once. if (!AllDeclsFound.insert(CanonDecl).second) return; @@ -930,9 +941,9 @@ void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { if (AsNestedNameSpecifier) { R.StartsNestedNameSpecifier = true; R.Priority = CCP_NestedNameSpecifier; - } else + } else AdjustResultPriorityForDecl(R); - + // If this result is supposed to have an informative qualifier, add one. if (R.QualifierIsInformative && !R.Qualifier && !R.StartsNestedNameSpecifier) { @@ -946,17 +957,17 @@ void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { else R.QualifierIsInformative = false; } - + // Insert this result into the set of results and into the current shadow // map. SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size()); Results.push_back(R); - + if (!AsNestedNameSpecifier) MaybeAddConstructorResults(R); } -void ResultBuilder::AddResult(Result R, DeclContext *CurContext, +void ResultBuilder::AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding, bool InBaseClass = false) { if (R.Kind != Result::RK_Declaration) { // For non-declaration results, just add the result. @@ -966,19 +977,20 @@ void ResultBuilder::AddResult(Result R, DeclContext *CurContext, // Look through using declarations. if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) { - AddResult(Result(Using->getTargetDecl(), - getBasePriority(Using->getTargetDecl()), - R.Qualifier), - CurContext, Hiding); + CodeCompletionResult Result(Using->getTargetDecl(), + getBasePriority(Using->getTargetDecl()), + R.Qualifier); + Result.ShadowDecl = Using; + AddResult(Result, CurContext, Hiding); return; } - + bool AsNestedNameSpecifier = false; if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) return; - + // C++ constructors are never found by name lookup. - if (isa<CXXConstructorDecl>(R.Declaration)) + if (isConstructor(R.Declaration)) return; if (Hiding && CheckHiddenResult(R, CurContext, Hiding)) @@ -987,16 +999,16 @@ void ResultBuilder::AddResult(Result R, DeclContext *CurContext, // Make sure that any given declaration only shows up in the result set once. if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second) return; - + // If the filter is for nested-name-specifiers, then this result starts a // nested-name-specifier. if (AsNestedNameSpecifier) { R.StartsNestedNameSpecifier = true; R.Priority = CCP_NestedNameSpecifier; - } - else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass && - isa<CXXRecordDecl>(R.Declaration->getDeclContext() - ->getRedeclContext())) + } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && + InBaseClass && + isa<CXXRecordDecl>( + R.Declaration->getDeclContext()->getRedeclContext())) R.QualifierIsInformative = true; // If this result is supposed to have an informative qualifier, add one. @@ -1012,13 +1024,13 @@ void ResultBuilder::AddResult(Result R, DeclContext *CurContext, else R.QualifierIsInformative = false; } - + // Adjust the priority if this result comes from a base class. if (InBaseClass) R.Priority += CCD_InBaseClass; - + AdjustResultPriorityForDecl(R); - + if (HasObjectTypeQualifiers) if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration)) if (Method->isInstance()) { @@ -1027,43 +1039,43 @@ void ResultBuilder::AddResult(Result R, DeclContext *CurContext, if (ObjectTypeQualifiers == MethodQuals) R.Priority += CCD_ObjectQualifierMatch; else if (ObjectTypeQualifiers - MethodQuals) { - // The method cannot be invoked, because doing so would drop + // The method cannot be invoked, because doing so would drop // qualifiers. return; } } - + // Insert this result into the set of results. Results.push_back(R); - + if (!AsNestedNameSpecifier) MaybeAddConstructorResults(R); } void ResultBuilder::AddResult(Result R) { - assert(R.Kind != Result::RK_Declaration && + assert(R.Kind != Result::RK_Declaration && "Declaration results need more context"); Results.push_back(R); } -/// \brief Enter into a new scope. +/// Enter into a new scope. void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); } -/// \brief Exit from the current scope. +/// Exit from the current scope. void ResultBuilder::ExitScope() { for (ShadowMap::iterator E = ShadowMaps.back().begin(), EEnd = ShadowMaps.back().end(); E != EEnd; ++E) E->second.Destroy(); - + ShadowMaps.pop_back(); } -/// \brief Determines whether this given declaration will be found by +/// Determines whether this given declaration will be found by /// ordinary name lookup. bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const { - ND = cast<NamedDecl>(ND->getUnderlyingDecl()); + ND = ND->getUnderlyingDecl(); // If name lookup finds a local extern declaration, then we are in a // context where it behaves like an ordinary name. @@ -1074,14 +1086,14 @@ bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const { if (isa<ObjCIvarDecl>(ND)) return true; } - + return ND->getIdentifierNamespace() & IDNS; } -/// \brief Determines whether this given declaration will be found by +/// Determines whether this given declaration will be found by /// ordinary name lookup but is not a type name. bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const { - ND = cast<NamedDecl>(ND->getUnderlyingDecl()); + ND = ND->getUnderlyingDecl(); if (isa<TypeDecl>(ND)) return false; // Objective-C interfaces names are not filtered by this method because they @@ -1099,51 +1111,51 @@ bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const { if (isa<ObjCIvarDecl>(ND)) return true; } - + return ND->getIdentifierNamespace() & IDNS; } bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const { if (!IsOrdinaryNonTypeName(ND)) return 0; - + if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl())) if (VD->getType()->isIntegralOrEnumerationType()) return true; - + return false; } -/// \brief Determines whether this given declaration will be found by +/// Determines whether this given declaration will be found by /// ordinary name lookup. bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const { - ND = cast<NamedDecl>(ND->getUnderlyingDecl()); + ND = ND->getUnderlyingDecl(); unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; if (SemaRef.getLangOpts().CPlusPlus) IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace; - - return (ND->getIdentifierNamespace() & IDNS) && - !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) && + + return (ND->getIdentifierNamespace() & IDNS) && + !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND); } -/// \brief Determines whether the given declaration is suitable as the +/// Determines whether the given declaration is suitable as the /// start of a C++ nested-name-specifier, e.g., a class or namespace. bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const { // Allow us to find class templates, too. if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) ND = ClassTemplate->getTemplatedDecl(); - + return SemaRef.isAcceptableNestedNameSpecifier(ND); } -/// \brief Determines whether the given declaration is an enumeration. +/// Determines whether the given declaration is an enumeration. bool ResultBuilder::IsEnum(const NamedDecl *ND) const { return isa<EnumDecl>(ND); } -/// \brief Determines whether the given declaration is a class or struct. +/// Determines whether the given declaration is a class or struct. bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const { // Allow us to find class templates, too. if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) @@ -1154,40 +1166,40 @@ bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const { return RD->getTagKind() == TTK_Class || RD->getTagKind() == TTK_Struct || RD->getTagKind() == TTK_Interface; - + return false; } -/// \brief Determines whether the given declaration is a union. +/// Determines whether the given declaration is a union. bool ResultBuilder::IsUnion(const NamedDecl *ND) const { // Allow us to find class templates, too. if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) ND = ClassTemplate->getTemplatedDecl(); - + if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND)) return RD->getTagKind() == TTK_Union; - + return false; } -/// \brief Determines whether the given declaration is a namespace. +/// Determines whether the given declaration is a namespace. bool ResultBuilder::IsNamespace(const NamedDecl *ND) const { return isa<NamespaceDecl>(ND); } -/// \brief Determines whether the given declaration is a namespace or +/// Determines whether the given declaration is a namespace or /// namespace alias. bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const { return isa<NamespaceDecl>(ND->getUnderlyingDecl()); } -/// \brief Determines whether the given declaration is a type. +/// Determines whether the given declaration is a type. bool ResultBuilder::IsType(const NamedDecl *ND) const { ND = ND->getUnderlyingDecl(); return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); } -/// \brief Determines which members of a class should be visible via +/// Determines which members of a class should be visible via /// "." or "->". Only value declarations, nested name specifiers, and /// using declarations thereof should show up. bool ResultBuilder::IsMember(const NamedDecl *ND) const { @@ -1199,31 +1211,31 @@ bool ResultBuilder::IsMember(const NamedDecl *ND) const { static bool isObjCReceiverType(ASTContext &C, QualType T) { T = C.getCanonicalType(T); switch (T->getTypeClass()) { - case Type::ObjCObject: + case Type::ObjCObject: case Type::ObjCInterface: case Type::ObjCObjectPointer: return true; - + case Type::Builtin: switch (cast<BuiltinType>(T)->getKind()) { case BuiltinType::ObjCId: case BuiltinType::ObjCClass: case BuiltinType::ObjCSel: return true; - + default: break; } return false; - + default: break; } - + if (!C.getLangOpts().CPlusPlus) return false; - // FIXME: We could perform more analysis here to determine whether a + // FIXME: We could perform more analysis here to determine whether a // particular class type has any conversions to Objective-C types. For now, // just accept all class types. return T->isDependentType() || T->isRecordType(); @@ -1233,7 +1245,7 @@ bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const { QualType T = getDeclUsageType(SemaRef.Context, ND); if (T.isNull()) return false; - + T = SemaRef.Context.getBaseElementType(T); return isObjCReceiverType(SemaRef.Context, T); } @@ -1241,11 +1253,11 @@ bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const { bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const { if (IsObjCMessageReceiver(ND)) return true; - + const VarDecl *Var = dyn_cast<VarDecl>(ND); if (!Var) return false; - + return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>(); } @@ -1253,14 +1265,14 @@ bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const { if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) || (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND))) return false; - + QualType T = getDeclUsageType(SemaRef.Context, ND); if (T.isNull()) return false; - + T = SemaRef.Context.getBaseElementType(T); return T->isObjCObjectType() || T->isObjCObjectPointerType() || - T->isObjCIdType() || + T->isObjCIdType() || (SemaRef.getLangOpts().CPlusPlus && T->isRecordType()); } @@ -1268,37 +1280,69 @@ bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const { return false; } -/// \brief Determines whether the given declaration is an Objective-C +/// Determines whether the given declaration is an Objective-C /// instance variable. bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const { return isa<ObjCIvarDecl>(ND); } namespace { - /// \brief Visible declaration consumer that adds a code-completion result + /// Visible declaration consumer that adds a code-completion result /// for each visible declaration. class CodeCompletionDeclConsumer : public VisibleDeclConsumer { ResultBuilder &Results; DeclContext *CurContext; - + std::vector<FixItHint> FixIts; + public: - CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext) - : Results(Results), CurContext(CurContext) { } + CodeCompletionDeclConsumer( + ResultBuilder &Results, DeclContext *CurContext, + std::vector<FixItHint> FixIts = std::vector<FixItHint>()) + : Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)) {} void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass) override { bool Accessible = true; - if (Ctx) - Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx); + if (Ctx) { + DeclContext *AccessingCtx = Ctx; + // If ND comes from a base class, set the naming class back to the + // derived class if the search starts from the derived class (i.e. + // InBaseClass is true). + // + // Example: + // class B { protected: int X; } + // class D : public B { void f(); } + // void D::f() { this->^; } + // The completion after "this->" will have `InBaseClass` set to true and + // `Ctx` set to "B", when looking up in `B`. We need to set the actual + // accessing context (i.e. naming class) to "D" so that access can be + // calculated correctly. + if (InBaseClass && isa<CXXRecordDecl>(Ctx)) { + CXXRecordDecl *RC = nullptr; + // Get the enclosing record. + for (DeclContext *DC = CurContext; !DC->isFileContext(); + DC = DC->getParent()) { + if ((RC = dyn_cast<CXXRecordDecl>(DC))) + break; + } + if (RC) + AccessingCtx = RC; + } + Accessible = Results.getSema().IsSimplyAccessible(ND, AccessingCtx); + } ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr, - false, Accessible); + false, Accessible, FixIts); Results.AddResult(Result, CurContext, Hiding, InBaseClass); } + + void EnteredContext(DeclContext* Ctx) override { + Results.addVisitedContext(Ctx); + } }; } -/// \brief Add type specifiers for the current language as keyword results. +/// Add type specifiers for the current language as keyword results. static void AddTypeSpecifierResults(const LangOptions &LangOpts, ResultBuilder &Results) { typedef CodeCompletionResult Result; @@ -1324,16 +1368,16 @@ static void AddTypeSpecifierResults(const LangOptions &LangOpts, Results.AddResult(Result("_Bool", CCP_Type)); Results.AddResult(Result("restrict", CCP_Type)); } - + CodeCompletionBuilder Builder(Results.getAllocator(), Results.getCodeCompletionTUInfo()); if (LangOpts.CPlusPlus) { // C++-specific - Results.AddResult(Result("bool", CCP_Type + + Results.AddResult(Result("bool", CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0))); Results.AddResult(Result("class", CCP_Type)); Results.AddResult(Result("wchar_t", CCP_Type)); - + // typename qualified-id Builder.AddTypedTextChunk("typename"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -1341,12 +1385,12 @@ static void AddTypeSpecifierResults(const LangOptions &LangOpts, Builder.AddTextChunk("::"); Builder.AddPlaceholderChunk("name"); Results.AddResult(Result(Builder.TakeString())); - + if (LangOpts.CPlusPlus11) { Results.AddResult(Result("auto", CCP_Type)); Results.AddResult(Result("char16_t", CCP_Type)); Results.AddResult(Result("char32_t", CCP_Type)); - + Builder.AddTypedTextChunk("decltype"); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("expression"); @@ -1356,13 +1400,13 @@ static void AddTypeSpecifierResults(const LangOptions &LangOpts, } else Results.AddResult(Result("__auto_type", CCP_Type)); - // GNU extensions - if (LangOpts.GNUMode) { + // GNU keywords + if (LangOpts.GNUKeywords) { // FIXME: Enable when we actually support decimal floating point. // Results.AddResult(Result("_Decimal32")); // Results.AddResult(Result("_Decimal64")); // Results.AddResult(Result("_Decimal128")); - + Builder.AddTypedTextChunk("typeof"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("expression"); @@ -1382,7 +1426,7 @@ static void AddTypeSpecifierResults(const LangOptions &LangOpts, } static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC, - const LangOptions &LangOpts, + const LangOptions &LangOpts, ResultBuilder &Results) { typedef CodeCompletionResult Result; // Note: we don't suggest either "auto" or "register", because both @@ -1408,7 +1452,7 @@ static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC, } static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC, - const LangOptions &LangOpts, + const LangOptions &LangOpts, ResultBuilder &Results) { typedef CodeCompletionResult Result; switch (CCC) { @@ -1419,7 +1463,7 @@ static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC, Results.AddResult(Result("friend")); Results.AddResult(Result("mutable")); Results.AddResult(Result("virtual")); - } + } LLVM_FALLTHROUGH; case Sema::PCC_ObjCInterface: @@ -1447,7 +1491,7 @@ static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt); static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt); static void AddObjCVisibilityResults(const LangOptions &LangOpts, ResultBuilder &Results, - bool NeedAt); + bool NeedAt); static void AddObjCImplementationResults(const LangOptions &LangOpts, ResultBuilder &Results, bool NeedAt); @@ -1464,7 +1508,7 @@ static void AddTypedefResult(ResultBuilder &Results) { Builder.AddPlaceholderChunk("type"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("name"); - Results.AddResult(CodeCompletionResult(Builder.TakeString())); + Results.AddResult(CodeCompletionResult(Builder.TakeString())); } static bool WantTypesInContext(Sema::ParserCompletionContext CCC, @@ -1481,15 +1525,15 @@ static bool WantTypesInContext(Sema::ParserCompletionContext CCC, case Sema::PCC_ParenthesizedExpression: case Sema::PCC_LocalDeclarationSpecifiers: return true; - + case Sema::PCC_Expression: case Sema::PCC_Condition: return LangOpts.CPlusPlus; - + case Sema::PCC_ObjCInterface: case Sema::PCC_ObjCImplementation: return false; - + case Sema::PCC_ForInit: return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99; } @@ -1507,12 +1551,12 @@ static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context, return Policy; } -/// \brief Retrieve a printing policy suitable for code completion. +/// Retrieve a printing policy suitable for code completion. static PrintingPolicy getCompletionPrintingPolicy(Sema &S) { return getCompletionPrintingPolicy(S.Context, S.PP); } -/// \brief Retrieve the string representation of the given type as a string +/// Retrieve the string representation of the given type as a string /// that has the appropriate lifetime for code completion. /// /// This routine provides a fast path where we provide constant strings for @@ -1525,7 +1569,7 @@ static const char *GetCompletionTypeString(QualType T, // Built-in type names are constant strings. if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) return BT->getNameAsCString(Policy); - + // Anonymous tag types are constant strings. if (const TagType *TagT = dyn_cast<TagType>(T)) if (TagDecl *Tag = TagT->getDecl()) @@ -1539,24 +1583,24 @@ static const char *GetCompletionTypeString(QualType T, } } } - + // Slow path: format the type as a string. std::string Result; T.getAsStringInternal(Result, Policy); return Allocator.CopyString(Result); } -/// \brief Add a completion for "this", if we're in a member function. +/// Add a completion for "this", if we're in a member function. static void addThisCompletion(Sema &S, ResultBuilder &Results) { QualType ThisTy = S.getCurrentThisType(); if (ThisTy.isNull()) return; - + CodeCompletionAllocator &Allocator = Results.getAllocator(); CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); PrintingPolicy Policy = getCompletionPrintingPolicy(S); - Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy, - S.Context, + Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy, + S.Context, Policy, Allocator)); Builder.AddTypedTextChunk("this"); @@ -1578,14 +1622,14 @@ static void AddStaticAssertResult(CodeCompletionBuilder &Builder, Results.AddResult(CodeCompletionResult(Builder.TakeString())); } -/// \brief Add language constructs that show up for "ordinary" names. +/// Add language constructs that show up for "ordinary" names. static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S, Sema &SemaRef, ResultBuilder &Results) { CodeCompletionAllocator &Allocator = Results.getAllocator(); CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); - + typedef CodeCompletionResult Result; switch (CCC) { case Sema::PCC_Namespace: @@ -1601,7 +1645,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_RightBrace); Results.AddResult(Result(Builder.TakeString())); } - + // namespace identifier = identifier ; Builder.AddTypedTextChunk("namespace"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -1618,7 +1662,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddPlaceholderChunk("identifier"); Results.AddResult(Result(Builder.TakeString())); - // asm(string-literal) + // asm(string-literal) Builder.AddTypedTextChunk("asm"); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("string-literal"); @@ -1633,10 +1677,10 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Results.AddResult(Result(Builder.TakeString())); } } - + if (SemaRef.getLangOpts().ObjC1) AddObjCTopLevelResults(Results, true); - + AddTypedefResult(Results); LLVM_FALLTHROUGH; @@ -1649,7 +1693,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddTextChunk("::"); Builder.AddPlaceholderChunk("name"); Results.AddResult(Result(Builder.TakeString())); - + // using typename qualifier::name (only in a dependent context) if (SemaRef.CurContext->isDependentContext()) { Builder.AddTypedTextChunk("using"); @@ -1710,17 +1754,17 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); break; - + case Sema::PCC_ObjCImplementation: AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true); AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); break; - + case Sema::PCC_ObjCInstanceVariableList: AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true); break; - + case Sema::PCC_RecoveryInFunction: case Sema::PCC_Statement: { AddTypedefResult(Results); @@ -1744,7 +1788,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, } if (SemaRef.getLangOpts().ObjC1) AddObjCStatementResults(Results, true); - + if (Results.includeCodePatterns()) { // if (condition) { statements } Builder.AddTypedTextChunk("if"); @@ -1773,7 +1817,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_RightBrace); Results.AddResult(Result(Builder.TakeString())); } - + // Switch-specific statements. if (!SemaRef.getCurFunction()->SwitchStack.empty()) { // case expression: @@ -1835,7 +1879,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_RightBrace); Results.AddResult(Result(Builder.TakeString())); } - + if (S->getContinueParent()) { // continue ; Builder.AddTypedTextChunk("continue"); @@ -1856,7 +1900,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext)) isVoid = Method->getReturnType()->isVoidType(); - else if (SemaRef.getCurBlock() && + else if (SemaRef.getCurBlock() && !SemaRef.getCurBlock()->ReturnType.isNull()) isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType(); Builder.AddTypedTextChunk("return"); @@ -1870,7 +1914,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddTypedTextChunk("goto"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("label"); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); // Using directives Builder.AddTypedTextChunk("using"); @@ -1900,7 +1944,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddPlaceholderChunk("type"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddPlaceholderChunk("expression"); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); // (__bridge_transfer <Objective-C type>)<expression> Builder.AddTypedTextChunk("__bridge_transfer"); @@ -1908,7 +1952,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddPlaceholderChunk("Objective-C type"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddPlaceholderChunk("expression"); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); // (__bridge_retained <CF type>)<expression> Builder.AddTypedTextChunk("__bridge_retained"); @@ -1916,7 +1960,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddPlaceholderChunk("CF type"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddPlaceholderChunk("expression"); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); } // Fall through LLVM_FALLTHROUGH; @@ -1925,12 +1969,12 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, if (SemaRef.getLangOpts().CPlusPlus) { // 'this', if we're in a non-static member function. addThisCompletion(SemaRef, Results); - + // true Builder.AddResultTypeChunk("bool"); Builder.AddTypedTextChunk("true"); Results.AddResult(Result(Builder.TakeString())); - + // false Builder.AddResultTypeChunk("bool"); Builder.AddTypedTextChunk("false"); @@ -1945,9 +1989,9 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("expression"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); } - + // static_cast < type-id > ( expression ) Builder.AddTypedTextChunk("static_cast"); Builder.AddChunk(CodeCompletionString::CK_LeftAngle); @@ -1956,7 +2000,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("expression"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); // reinterpret_cast < type-id > ( expression ) Builder.AddTypedTextChunk("reinterpret_cast"); @@ -1966,7 +2010,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("expression"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); // const_cast < type-id > ( expression ) Builder.AddTypedTextChunk("const_cast"); @@ -1976,7 +2020,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("expression"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); if (SemaRef.getLangOpts().RTTI) { // typeid ( expression-or-type ) @@ -1985,9 +2029,9 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("expression-or-type"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); } - + // new T ( ... ) Builder.AddTypedTextChunk("new"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -1995,7 +2039,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("expressions"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); // new T [ ] ( ... ) Builder.AddTypedTextChunk("new"); @@ -2007,14 +2051,14 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("expressions"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); // delete expression Builder.AddResultTypeChunk("void"); Builder.AddTypedTextChunk("delete"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("expression"); - Results.AddResult(Result(Builder.TakeString())); + Results.AddResult(Result(Builder.TakeString())); // delete [] expression Builder.AddResultTypeChunk("void"); @@ -2034,7 +2078,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Builder.AddPlaceholderChunk("expression"); Results.AddResult(Result(Builder.TakeString())); } - + // FIXME: Rethrow? if (SemaRef.getLangOpts().CPlusPlus11) { @@ -2079,7 +2123,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, SuperType = ID->getSuperClass()->getNameAsString(); if (Method->isInstanceMethod()) SuperType += " *"; - + Builder.AddResultTypeChunk(Allocator.CopyString(SuperType)); Builder.AddTypedTextChunk("super"); Results.AddResult(Result(Builder.TakeString())); @@ -2111,7 +2155,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Results.AddResult(Result(Builder.TakeString())); break; } - + case Sema::PCC_Type: case Sema::PCC_LocalDeclarationSpecifiers: break; @@ -2124,7 +2168,7 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Results.AddResult(Result("operator")); } -/// \brief If the given declaration has an associated type, add it as a result +/// If the given declaration has an associated type, add it as a result /// type chunk. static void AddResultTypeChunk(ASTContext &Context, const PrintingPolicy &Policy, @@ -2136,7 +2180,7 @@ static void AddResultTypeChunk(ASTContext &Context, // Skip constructors and conversion functions, which have their return types // built into their names. - if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND)) + if (isConstructor(ND) || isa<CXXConversionDecl>(ND)) return; // Determine the type of the declaration (if it has a type). @@ -2166,10 +2210,10 @@ static void AddResultTypeChunk(ASTContext &Context, else T = Property->getType(); } - + if (T.isNull() || Context.hasSameType(T, Context.DependentTy)) return; - + Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy, Result.getAllocator())); } @@ -2188,7 +2232,7 @@ static void MaybeAddSentinel(Preprocessor &PP, } } -static std::string formatObjCParamQualifiers(unsigned ObjCQuals, +static std::string formatObjCParamQualifiers(unsigned ObjCQuals, QualType &Type) { std::string Result; if (ObjCQuals & Decl::OBJC_TQ_In) @@ -2223,7 +2267,7 @@ static std::string formatObjCParamQualifiers(unsigned ObjCQuals, return Result; } -/// \brief Tries to find the most appropriate type location for an Objective-C +/// Tries to find the most appropriate type location for an Objective-C /// block placeholder. /// /// This function ignores things like typedefs and qualifiers in order to @@ -2285,13 +2329,13 @@ static std::string FormatFunctionParameter(const PrintingPolicy &Policy, bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext()); if (Param->getType()->isDependentType() || !Param->getType()->isBlockPointerType()) { - // The argument for a dependent or non-block parameter is a placeholder + // The argument for a dependent or non-block parameter is a placeholder // containing that parameter's type. std::string Result; - + if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName) Result = Param->getIdentifier()->getName(); - + QualType Type = Param->getType(); if (ObjCSubsts) Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts, @@ -2332,7 +2376,7 @@ static std::string FormatFunctionParameter(const PrintingPolicy &Policy, Result = Param->getIdentifier()->getName(); QualType Type = Param->getType().getUnqualifiedType(); - + if (ObjCMethodParam) { Result = Type.getAsString(Policy); std::string Quals = @@ -2346,7 +2390,7 @@ static std::string FormatFunctionParameter(const PrintingPolicy &Policy, } else { Type.getAsStringInternal(Result, Policy); } - + return Result; } @@ -2357,14 +2401,14 @@ static std::string FormatFunctionParameter(const PrintingPolicy &Policy, ObjCSubsts); } -/// \brief Returns a placeholder string that corresponds to an Objective-C block +/// Returns a placeholder string that corresponds to an Objective-C block /// declaration. /// /// \param BlockDecl A declaration with an Objective-C block type. /// /// \param Block The most relevant type location for that block type. /// -/// \param SuppressBlockName Determines wether or not the name of the block +/// \param SuppressBlockName Determines whether or not the name of the block /// declaration is included in the resulting string. static std::string formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, @@ -2449,7 +2493,7 @@ static std::string GetDefaultValueString(const ParmVarDecl *Param, return " " + DefValue; } -/// \brief Add function parameter chunks to the given code completion string. +/// Add function parameter chunks to the given code completion string. static void AddFunctionParameterChunks(Preprocessor &PP, const PrintingPolicy &Policy, const FunctionDecl *Function, @@ -2457,10 +2501,10 @@ static void AddFunctionParameterChunks(Preprocessor &PP, unsigned Start = 0, bool InOptional = false) { bool FirstParameter = true; - + for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) { const ParmVarDecl *Param = Function->getParamDecl(P); - + if (Param->hasDefaultArg() && !InOptional) { // When we see an optional default argument, put that argument and // the remaining default arguments into a new, optional string. @@ -2472,14 +2516,14 @@ static void AddFunctionParameterChunks(Preprocessor &PP, Result.AddOptionalChunk(Opt.TakeString()); break; } - + if (FirstParameter) FirstParameter = false; else Result.AddChunk(CodeCompletionString::CK_Comma); - + InOptional = false; - + // Format the placeholder string. std::string PlaceholderStr = FormatFunctionParameter(Policy, Param); if (Param->hasDefaultArg()) @@ -2492,8 +2536,8 @@ static void AddFunctionParameterChunks(Preprocessor &PP, Result.AddPlaceholderChunk( Result.getAllocator().CopyString(PlaceholderStr)); } - - if (const FunctionProtoType *Proto + + if (const FunctionProtoType *Proto = Function->getType()->getAs<FunctionProtoType>()) if (Proto->isVariadic()) { if (Proto->getNumParams() == 0) @@ -2503,7 +2547,7 @@ static void AddFunctionParameterChunks(Preprocessor &PP, } } -/// \brief Add template parameter chunks to the given code completion string. +/// Add template parameter chunks to the given code completion string. static void AddTemplateParameterChunks(ASTContext &Context, const PrintingPolicy &Policy, const TemplateDecl *Template, @@ -2521,7 +2565,7 @@ static void AddTemplateParameterChunks(ASTContext &Context, TemplateParameterList::iterator PEnd = Params->end(); if (MaxParameters) PEnd = Params->begin() + MaxParameters; - for (TemplateParameterList::iterator P = Params->begin() + Start; + for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd; ++P) { bool HasDefaultArg = false; std::string PlaceholderStr; @@ -2530,14 +2574,14 @@ static void AddTemplateParameterChunks(ASTContext &Context, PlaceholderStr = "typename"; else PlaceholderStr = "class"; - + if (TTP->getIdentifier()) { PlaceholderStr += ' '; PlaceholderStr += TTP->getIdentifier()->getName(); } - + HasDefaultArg = TTP->hasDefaultArgument(); - } else if (NonTypeTemplateParmDecl *NTTP + } else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { if (NTTP->getIdentifier()) PlaceholderStr = NTTP->getIdentifier()->getName(); @@ -2546,7 +2590,7 @@ static void AddTemplateParameterChunks(ASTContext &Context, } else { assert(isa<TemplateTemplateParmDecl>(*P)); TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); - + // Since putting the template argument list into the placeholder would // be very, very long, we just use an abbreviation. PlaceholderStr = "template<...> class"; @@ -2554,10 +2598,10 @@ static void AddTemplateParameterChunks(ASTContext &Context, PlaceholderStr += ' '; PlaceholderStr += TTP->getIdentifier()->getName(); } - + HasDefaultArg = TTP->hasDefaultArgument(); } - + if (HasDefaultArg && !InDefaultArg) { // When we see an optional default argument, put that argument and // the remaining default arguments into a new, optional string. @@ -2570,31 +2614,31 @@ static void AddTemplateParameterChunks(ASTContext &Context, Result.AddOptionalChunk(Opt.TakeString()); break; } - + InDefaultArg = false; - + if (FirstParameter) FirstParameter = false; else Result.AddChunk(CodeCompletionString::CK_Comma); - + // Add the placeholder string. Result.AddPlaceholderChunk( Result.getAllocator().CopyString(PlaceholderStr)); - } + } } -/// \brief Add a qualifier to the given code-completion string, if the +/// Add a qualifier to the given code-completion string, if the /// provided nested-name-specifier is non-NULL. -static void -AddQualifierToCompletionString(CodeCompletionBuilder &Result, - NestedNameSpecifier *Qualifier, +static void +AddQualifierToCompletionString(CodeCompletionBuilder &Result, + NestedNameSpecifier *Qualifier, bool QualifierIsInformative, ASTContext &Context, const PrintingPolicy &Policy) { if (!Qualifier) return; - + std::string PrintedNNS; { llvm::raw_string_ostream OS(PrintedNNS); @@ -2606,7 +2650,7 @@ AddQualifierToCompletionString(CodeCompletionBuilder &Result, Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS)); } -static void +static void AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, const FunctionDecl *Function) { const FunctionProtoType *Proto @@ -2615,7 +2659,7 @@ AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, return; // FIXME: Add ref-qualifier! - + // Handle single qualifiers without copying if (Proto->getTypeQuals() == Qualifiers::Const) { Result.AddInformativeChunk(" const"); @@ -2643,29 +2687,29 @@ AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr)); } -/// \brief Add the name of the given declaration +/// Add the name of the given declaration static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, const NamedDecl *ND, CodeCompletionBuilder &Result) { DeclarationName Name = ND->getDeclName(); if (!Name) return; - + switch (Name.getNameKind()) { case DeclarationName::CXXOperatorName: { const char *OperatorName = nullptr; switch (Name.getCXXOverloadedOperator()) { - case OO_None: + case OO_None: case OO_Conditional: case NUM_OVERLOADED_OPERATORS: - OperatorName = "operator"; + OperatorName = "operator"; break; - + #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ case OO_##Name: OperatorName = "operator" Spelling; break; #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) #include "clang/Basic/OperatorKinds.def" - + case OO_New: OperatorName = "operator new"; break; case OO_Delete: OperatorName = "operator delete"; break; case OO_Array_New: OperatorName = "operator new[]"; break; @@ -2676,7 +2720,7 @@ static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, Result.AddTypedTextChunk(OperatorName); break; } - + case DeclarationName::Identifier: case DeclarationName::CXXConversionFunctionName: case DeclarationName::CXXDestructorName: @@ -2684,14 +2728,14 @@ static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, Result.AddTypedTextChunk( Result.getAllocator().CopyString(ND->getNameAsString())); break; - + case DeclarationName::CXXDeductionGuideName: case DeclarationName::CXXUsingDirective: case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: break; - + case DeclarationName::CXXConstructorName: { CXXRecordDecl *Record = nullptr; QualType Ty = Name.getCXXNameType(); @@ -2705,7 +2749,7 @@ static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, Result.getAllocator().CopyString(ND->getNameAsString())); break; } - + Result.AddTypedTextChunk( Result.getAllocator().CopyString(Record->getNameAsString())); if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) { @@ -2727,7 +2771,53 @@ CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S, CCTUInfo, IncludeBriefComments); } -/// \brief If possible, create a new code completion string for the given +CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro( + Preprocessor &PP, CodeCompletionAllocator &Allocator, + CodeCompletionTUInfo &CCTUInfo) { + assert(Kind == RK_Macro); + CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); + const MacroInfo *MI = PP.getMacroInfo(Macro); + Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName())); + + if (!MI || !MI->isFunctionLike()) + return Result.TakeString(); + + // Format a function-like macro with placeholders for the arguments. + Result.AddChunk(CodeCompletionString::CK_LeftParen); + MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end(); + + // C99 variadic macros add __VA_ARGS__ at the end. Skip it. + if (MI->isC99Varargs()) { + --AEnd; + + if (A == AEnd) { + Result.AddPlaceholderChunk("..."); + } + } + + for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) { + if (A != MI->param_begin()) + Result.AddChunk(CodeCompletionString::CK_Comma); + + if (MI->isVariadic() && (A + 1) == AEnd) { + SmallString<32> Arg = (*A)->getName(); + if (MI->isC99Varargs()) + Arg += ", ..."; + else + Arg += "..."; + Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); + break; + } + + // Non-variadic macros are simple. + Result.AddPlaceholderChunk( + Result.getAllocator().CopyString((*A)->getName())); + } + Result.AddChunk(CodeCompletionString::CK_RightParen); + return Result.TakeString(); +} + +/// If possible, create a new code completion string for the given /// result. /// /// \returns Either a new, heap-allocated code completion string describing @@ -2740,104 +2830,42 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments) { + if (Kind == RK_Macro) + return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo); + CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); - + PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP); if (Kind == RK_Pattern) { Pattern->Priority = Priority; Pattern->Availability = Availability; - + if (Declaration) { Result.addParentContext(Declaration->getDeclContext()); Pattern->ParentName = Result.getParentName(); - // Provide code completion comment for self.GetterName where - // GetterName is the getter method for a property with name - // different from the property name (declared via a property - // getter attribute. - const NamedDecl *ND = Declaration; - if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND)) - if (M->isPropertyAccessor()) - if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl()) - if (PDecl->getGetterName() == M->getSelector() && - PDecl->getIdentifier() != M->getIdentifier()) { - if (const RawComment *RC = - Ctx.getRawCommentForAnyRedecl(M)) { - Result.addBriefComment(RC->getBriefText(Ctx)); - Pattern->BriefComment = Result.getBriefComment(); - } - else if (const RawComment *RC = - Ctx.getRawCommentForAnyRedecl(PDecl)) { - Result.addBriefComment(RC->getBriefText(Ctx)); - Pattern->BriefComment = Result.getBriefComment(); - } - } - } - - return Pattern; - } - - if (Kind == RK_Keyword) { - Result.AddTypedTextChunk(Keyword); - return Result.TakeString(); - } - - if (Kind == RK_Macro) { - const MacroInfo *MI = PP.getMacroInfo(Macro); - Result.AddTypedTextChunk( - Result.getAllocator().CopyString(Macro->getName())); - - if (!MI || !MI->isFunctionLike()) - return Result.TakeString(); - - // Format a function-like macro with placeholders for the arguments. - Result.AddChunk(CodeCompletionString::CK_LeftParen); - MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end(); - - // C99 variadic macros add __VA_ARGS__ at the end. Skip it. - if (MI->isC99Varargs()) { - --AEnd; - - if (A == AEnd) { - Result.AddPlaceholderChunk("..."); + if (const RawComment *RC = + getPatternCompletionComment(Ctx, Declaration)) { + Result.addBriefComment(RC->getBriefText(Ctx)); + Pattern->BriefComment = Result.getBriefComment(); } } - - for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) { - if (A != MI->param_begin()) - Result.AddChunk(CodeCompletionString::CK_Comma); - if (MI->isVariadic() && (A+1) == AEnd) { - SmallString<32> Arg = (*A)->getName(); - if (MI->isC99Varargs()) - Arg += ", ..."; - else - Arg += "..."; - Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); - break; - } + return Pattern; + } - // Non-variadic macros are simple. - Result.AddPlaceholderChunk( - Result.getAllocator().CopyString((*A)->getName())); - } - Result.AddChunk(CodeCompletionString::CK_RightParen); + if (Kind == RK_Keyword) { + Result.AddTypedTextChunk(Keyword); return Result.TakeString(); } - assert(Kind == RK_Declaration && "Missed a result kind?"); const NamedDecl *ND = Declaration; Result.addParentContext(ND->getDeclContext()); if (IncludeBriefComments) { // Add documentation comment, if it exists. - if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) { + if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) { Result.addBriefComment(RC->getBriefText(Ctx)); - } - else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND)) - if (OMD->isPropertyAccessor()) - if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) - if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl)) - Result.addBriefComment(RC->getBriefText(Ctx)); + } } if (StartsNestedNameSpecifier) { @@ -2851,9 +2879,9 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation())); AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result); - + if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) { - AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, + AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, Ctx, Policy); AddTypedNameChunk(Ctx, Policy, ND, Result); Result.AddChunk(CodeCompletionString::CK_LeftParen); @@ -2862,9 +2890,9 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, AddFunctionTypeQualsToCompletionString(Result, Function); return Result.TakeString(); } - + if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) { - AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, + AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, Ctx, Policy); FunctionDecl *Function = FunTmpl->getTemplatedDecl(); AddTypedNameChunk(Ctx, Policy, Function, Result); @@ -2885,30 +2913,30 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, LastDeducibleArgument - 1); if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) HasDefaultArg = TTP->hasDefaultArgument(); - else if (NonTypeTemplateParmDecl *NTTP + else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) HasDefaultArg = NTTP->hasDefaultArgument(); else { assert(isa<TemplateTemplateParmDecl>(Param)); - HasDefaultArg + HasDefaultArg = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument(); } - + if (!HasDefaultArg) break; } } - + if (LastDeducibleArgument) { // Some of the function template arguments cannot be deduced from a // function call, so we introduce an explicit template argument list // containing all of the arguments up to the first deducible argument. Result.AddChunk(CodeCompletionString::CK_LeftAngle); - AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result, + AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result, LastDeducibleArgument); Result.AddChunk(CodeCompletionString::CK_RightAngle); } - + // Add the function parameters Result.AddChunk(CodeCompletionString::CK_LeftParen); AddFunctionParameterChunks(PP, Policy, Function, Result); @@ -2916,9 +2944,9 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, AddFunctionTypeQualsToCompletionString(Result, Function); return Result.TakeString(); } - + if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) { - AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, + AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, Ctx, Policy); Result.AddTypedTextChunk( Result.getAllocator().CopyString(Template->getNameAsString())); @@ -2927,7 +2955,7 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, Result.AddChunk(CodeCompletionString::CK_RightAngle); return Result.TakeString(); } - + if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) { Selector Sel = Method->getSelector(); if (Sel.isUnarySelector()) { @@ -2942,7 +2970,7 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName)); else { Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName)); - + // If there is only one parameter, and we're past it, add an empty // typed-text chunk since there is nothing to type. if (Method->param_size() == 1) @@ -2961,10 +2989,10 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, Keyword += ":"; if (Idx < StartParameter || AllParametersAreInformative) Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword)); - else + else Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword)); } - + // If we're before the starting parameter, skip the placeholder. if (Idx < StartParameter) continue; @@ -2990,10 +3018,10 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, if (DeclaringEntity || AllParametersAreInformative) Arg += II->getName(); } - + if (Method->isVariadic() && (P + 1) == PEnd) Arg += ", ..."; - + if (DeclaringEntity) Result.AddTextChunk(Result.getAllocator().CopyString(Arg)); else if (AllParametersAreInformative) @@ -3011,15 +3039,15 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, else Result.AddPlaceholderChunk(", ..."); } - + MaybeAddSentinel(PP, Method, Result); } - + return Result.TakeString(); } if (Qualifier) - AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, + AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, Ctx, Policy); Result.AddTypedTextChunk( @@ -3027,7 +3055,60 @@ CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx, return Result.TakeString(); } -/// \brief Add function overload parameter chunks to the given code completion +const RawComment *clang::getCompletionComment(const ASTContext &Ctx, + const NamedDecl *ND) { + if (!ND) + return nullptr; + if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND)) + return RC; + + // Try to find comment from a property for ObjC methods. + const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND); + if (!M) + return nullptr; + const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); + if (!PDecl) + return nullptr; + + return Ctx.getRawCommentForAnyRedecl(PDecl); +} + +const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx, + const NamedDecl *ND) { + const ObjCMethodDecl *M = dyn_cast_or_null<ObjCMethodDecl>(ND); + if (!M || !M->isPropertyAccessor()) + return nullptr; + + // Provide code completion comment for self.GetterName where + // GetterName is the getter method for a property with name + // different from the property name (declared via a property + // getter attribute. + const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); + if (!PDecl) + return nullptr; + if (PDecl->getGetterName() == M->getSelector() && + PDecl->getIdentifier() != M->getIdentifier()) { + if (auto *RC = Ctx.getRawCommentForAnyRedecl(M)) + return RC; + if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl)) + return RC; + } + return nullptr; +} + +const RawComment *clang::getParameterComment( + const ASTContext &Ctx, + const CodeCompleteConsumer::OverloadCandidate &Result, + unsigned ArgIndex) { + auto FDecl = Result.getFunction(); + if (!FDecl) + return nullptr; + if (ArgIndex < FDecl->getNumParams()) + return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex)); + return nullptr; +} + +/// Add function overload parameter chunks to the given code completion /// string. static void AddOverloadParameterChunks(ASTContext &Context, const PrintingPolicy &Policy, @@ -3110,7 +3191,7 @@ CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(getFunctionType()); if (!FDecl && !Proto) { - // Function without a prototype. Just give the return type and a + // Function without a prototype. Just give the return type and a // highlighted ellipsis. const FunctionType *FT = getFunctionType(); Result.AddResultTypeChunk(Result.getAllocator().CopyString( @@ -3122,10 +3203,10 @@ CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( } if (FDecl) { - if (IncludeBriefComments && CurrentArg < FDecl->getNumParams()) - if (auto RC = S.getASTContext().getRawCommentForAnyRedecl( - FDecl->getParamDecl(CurrentArg))) + if (IncludeBriefComments) { + if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg)) Result.addBriefComment(RC->getBriefText(S.getASTContext())); + } AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result); Result.AddTextChunk( Result.getAllocator().CopyString(FDecl->getNameAsString())); @@ -3143,18 +3224,18 @@ CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( return Result.TakeString(); } -unsigned clang::getMacroUsagePriority(StringRef MacroName, +unsigned clang::getMacroUsagePriority(StringRef MacroName, const LangOptions &LangOpts, bool PreferredTypeIsPointer) { unsigned Priority = CCP_Macro; - + // Treat the "nil", "Nil" and "NULL" macros as null pointer constants. - if (MacroName.equals("nil") || MacroName.equals("NULL") || + if (MacroName.equals("nil") || MacroName.equals("NULL") || MacroName.equals("Nil")) { Priority = CCP_Constant; if (PreferredTypeIsPointer) Priority = Priority / CCF_SimilarTypeMatch; - } + } // Treat "YES", "NO", "true", and "false" as constants. else if (MacroName.equals("YES") || MacroName.equals("NO") || MacroName.equals("true") || MacroName.equals("false")) @@ -3162,27 +3243,27 @@ unsigned clang::getMacroUsagePriority(StringRef MacroName, // Treat "bool" as a type. else if (MacroName.equals("bool")) Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0); - - + + return Priority; } CXCursorKind clang::getCursorKindForDecl(const Decl *D) { if (!D) return CXCursor_UnexposedDecl; - + switch (D->getKind()) { case Decl::Enum: return CXCursor_EnumDecl; case Decl::EnumConstant: return CXCursor_EnumConstantDecl; case Decl::Field: return CXCursor_FieldDecl; - case Decl::Function: + case Decl::Function: return CXCursor_FunctionDecl; case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl; case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl; case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl; case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl; - case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl; + case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl; case Decl::ObjCMethod: return cast<ObjCMethodDecl>(D)->isInstanceMethod() ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl; @@ -3211,17 +3292,17 @@ CXCursorKind clang::getCursorKindForDecl(const Decl *D) { case Decl::StaticAssert: return CXCursor_StaticAssert; case Decl::Friend: return CXCursor_FriendDecl; case Decl::TranslationUnit: return CXCursor_TranslationUnit; - + case Decl::Using: case Decl::UnresolvedUsingValue: - case Decl::UnresolvedUsingTypename: + case Decl::UnresolvedUsingTypename: return CXCursor_UsingDeclaration; - + case Decl::ObjCPropertyImpl: switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) { case ObjCPropertyImplDecl::Dynamic: return CXCursor_ObjCDynamicDecl; - + case ObjCPropertyImplDecl::Synthesize: return CXCursor_ObjCSynthesizeDecl; } @@ -3242,7 +3323,7 @@ CXCursorKind clang::getCursorKindForDecl(const Decl *D) { } } } - + return CXCursor_UnexposedDecl; } @@ -3250,10 +3331,10 @@ static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, bool IncludeUndefined, bool TargetTypeIsPointer = false) { typedef CodeCompletionResult Result; - + Results.EnterNewScope(); - - for (Preprocessor::macro_iterator M = PP.macro_begin(), + + for (Preprocessor::macro_iterator M = PP.macro_begin(), MEnd = PP.macro_end(); M != MEnd; ++M) { auto MD = PP.getMacroDefinition(M->first); @@ -3268,17 +3349,17 @@ static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, TargetTypeIsPointer))); } } - + Results.ExitScope(); - + } -static void AddPrettyFunctionResults(const LangOptions &LangOpts, +static void AddPrettyFunctionResults(const LangOptions &LangOpts, ResultBuilder &Results) { typedef CodeCompletionResult Result; - + Results.EnterNewScope(); - + Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant)); Results.AddResult(Result("__FUNCTION__", CCP_Constant)); if (LangOpts.C99 || LangOpts.CPlusPlus11) @@ -3295,24 +3376,24 @@ static void HandleCodeCompleteResults(Sema *S, CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults); } -static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S, +static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) { switch (PCC) { case Sema::PCC_Namespace: return CodeCompletionContext::CCC_TopLevel; - + case Sema::PCC_Class: return CodeCompletionContext::CCC_ClassStructUnion; case Sema::PCC_ObjCInterface: return CodeCompletionContext::CCC_ObjCInterface; - + case Sema::PCC_ObjCImplementation: return CodeCompletionContext::CCC_ObjCImplementation; case Sema::PCC_ObjCInstanceVariableList: return CodeCompletionContext::CCC_ObjCIvarList; - + case Sema::PCC_Template: case Sema::PCC_MemberTemplate: if (S.CurContext->isFileContext()) @@ -3320,7 +3401,7 @@ static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S, if (S.CurContext->isRecord()) return CodeCompletionContext::CCC_ClassStructUnion; return CodeCompletionContext::CCC_Other; - + case Sema::PCC_RecoveryInFunction: return CodeCompletionContext::CCC_Recovery; @@ -3334,7 +3415,7 @@ static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S, case Sema::PCC_Expression: case Sema::PCC_Condition: return CodeCompletionContext::CCC_Expression; - + case Sema::PCC_Statement: return CodeCompletionContext::CCC_Statement; @@ -3343,7 +3424,7 @@ static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S, case Sema::PCC_ParenthesizedExpression: return CodeCompletionContext::CCC_ParenthesizedExpression; - + case Sema::PCC_LocalDeclarationSpecifiers: return CodeCompletionContext::CCC_Type; } @@ -3351,27 +3432,27 @@ static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S, llvm_unreachable("Invalid ParserCompletionContext!"); } -/// \brief If we're in a C++ virtual member function, add completion results -/// that invoke the functions we override, since it's common to invoke the +/// If we're in a C++ virtual member function, add completion results +/// that invoke the functions we override, since it's common to invoke the /// overridden function as well as adding new functionality. /// /// \param S The semantic analysis object for which we are generating results. /// /// \param InContext This context in which the nested-name-specifier preceding -/// the code-completion point +/// the code-completion point static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, ResultBuilder &Results) { // Look through blocks. DeclContext *CurContext = S.CurContext; while (isa<BlockDecl>(CurContext)) CurContext = CurContext->getParent(); - - + + CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext); if (!Method || !Method->isVirtual()) return; - - // We need to have names for all of the parameters, if we're going to + + // We need to have names for all of the parameters, if we're going to // generate a forwarding call. for (auto P : Method->parameters()) if (!P->getDeclName()) @@ -3383,7 +3464,7 @@ static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, Results.getCodeCompletionTUInfo()); if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl()) continue; - + // If we need a nested-name-specifier, add one now. if (!InContext) { NestedNameSpecifier *NNS @@ -3397,8 +3478,8 @@ static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, } } else if (!InContext->Equals(Overridden->getDeclContext())) continue; - - Builder.AddTypedTextChunk(Results.getAllocator().CopyString( + + Builder.AddTypedTextChunk(Results.getAllocator().CopyString( Overridden->getNameAsString())); Builder.AddChunk(CodeCompletionString::CK_LeftParen); bool FirstParam = true; @@ -3421,14 +3502,14 @@ static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, } } -void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, +void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path) { typedef CodeCompletionResult Result; ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_Other); Results.EnterNewScope(); - + CodeCompletionAllocator &Allocator = Results.getAllocator(); CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); typedef CodeCompletionResult Result; @@ -3440,7 +3521,7 @@ void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, Builder.AddTypedTextChunk( Builder.getAllocator().CopyString(Modules[I]->Name)); Results.AddResult(Result(Builder.TakeString(), - CCP_Declaration, + CCP_Declaration, CXCursor_ModuleImportDecl, Modules[I]->isAvailable() ? CXAvailability_Available @@ -3453,14 +3534,14 @@ void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, /*IsInclusionDirective=*/false); // Enumerate submodules. if (Mod) { - for (Module::submodule_iterator Sub = Mod->submodule_begin(), + for (Module::submodule_iterator Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end(); Sub != SubEnd; ++Sub) { - + Builder.AddTypedTextChunk( Builder.getAllocator().CopyString((*Sub)->Name)); Results.AddResult(Result(Builder.TakeString(), - CCP_Declaration, + CCP_Declaration, CXCursor_ModuleImportDecl, (*Sub)->isAvailable() ? CXAvailability_Available @@ -3468,18 +3549,18 @@ void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, } } } - Results.ExitScope(); + Results.ExitScope(); HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(),Results.size()); } -void Sema::CodeCompleteOrdinaryName(Scope *S, +void Sema::CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext) { ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), mapCodeCompletionContext(*this, CompletionContext)); Results.EnterNewScope(); - + // Determine how to filter results, e.g., so that the names of // values (functions, enumerators, function templates, etc.) are // only allowed where we can have an expression. @@ -3505,11 +3586,11 @@ void Sema::CodeCompleteOrdinaryName(Scope *S, Results.setFilter(&ResultBuilder::IsOrdinaryName); else Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); - + if (getLangOpts().CPlusPlus) MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results); break; - + case PCC_RecoveryInFunction: // Unfiltered break; @@ -3521,10 +3602,11 @@ void Sema::CodeCompleteOrdinaryName(Scope *S, if (CurMethod->isInstance()) Results.setObjectTypeQualifiers( Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers())); - + CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(S, LookupOrdinaryName, Consumer, - CodeCompleter->includeGlobals()); + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); AddOrdinaryNameResults(CompletionContext, S, *this, Results); Results.ExitScope(); @@ -3537,7 +3619,7 @@ void Sema::CodeCompleteOrdinaryName(Scope *S, if (S->getFnParent()) AddPrettyFunctionResults(getLangOpts(), Results); break; - + case PCC_Namespace: case PCC_Class: case PCC_ObjCInterface: @@ -3551,15 +3633,15 @@ void Sema::CodeCompleteOrdinaryName(Scope *S, case PCC_LocalDeclarationSpecifiers: break; } - + if (CodeCompleter->includeMacros()) AddMacroResults(PP, Results, false); - + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(),Results.size()); } -static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, +static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, @@ -3576,7 +3658,7 @@ void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, ? CodeCompletionContext::CCC_PotentiallyQualifiedName : CodeCompletionContext::CCC_Name); Results.EnterNewScope(); - + // Type qualifiers can come after names. Results.AddResult(Result("const")); Results.AddResult(Result("volatile")); @@ -3590,16 +3672,17 @@ void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, Results.AddResult("final"); if (AllowNonIdentifiers) { - Results.AddResult(Result("operator")); + Results.AddResult(Result("operator")); } - + // Add nested-name-specifiers. if (AllowNestedNameSpecifiers) { Results.allowNestedNameSpecifiers(); Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy); CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, - CodeCompleter->includeGlobals()); + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); Results.setFilter(nullptr); } } @@ -3618,7 +3701,7 @@ void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, S && (S->getFlags() & Scope::DeclScope) != 0 && (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope | - Scope::FunctionPrototypeScope | + Scope::FunctionPrototypeScope | Scope::AtCatchScope)) == 0) { ParsedType T = DS.getRepAsType(); if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType()) @@ -3628,29 +3711,31 @@ void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, // Note that we intentionally suppress macro results here, since we do not // encourage using macros to produce the names of entities. - HandleCodeCompleteResults(this, CodeCompleter, + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(), Results.size()); } struct Sema::CodeCompleteExpressionData { - CodeCompleteExpressionData(QualType PreferredType = QualType()) + CodeCompleteExpressionData(QualType PreferredType = QualType()) : PreferredType(PreferredType), IntegralConstantExpression(false), ObjCCollection(false) { } - + QualType PreferredType; bool IntegralConstantExpression; bool ObjCCollection; SmallVector<Decl *, 4> IgnoreDecls; }; -/// \brief Perform code-completion in an expression context when we know what +/// Perform code-completion in an expression context when we know what /// type we're looking for. -void Sema::CodeCompleteExpression(Scope *S, +void Sema::CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data) { - ResultBuilder Results(*this, CodeCompleter->getAllocator(), - CodeCompleter->getCodeCompletionTUInfo(), - CodeCompletionContext::CCC_Expression); + ResultBuilder Results( + *this, CodeCompleter->getAllocator(), + CodeCompleter->getCodeCompletionTUInfo(), + CodeCompletionContext(CodeCompletionContext::CCC_Expression, + Data.PreferredType)); if (Data.ObjCCollection) Results.setFilter(&ResultBuilder::IsObjCCollection); else if (Data.IntegralConstantExpression) @@ -3662,36 +3747,35 @@ void Sema::CodeCompleteExpression(Scope *S, if (!Data.PreferredType.isNull()) Results.setPreferredType(Data.PreferredType.getNonReferenceType()); - + // Ignore any declarations that we were told that we don't care about. for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) Results.Ignore(Data.IgnoreDecls[I]); - + CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(S, LookupOrdinaryName, Consumer, - CodeCompleter->includeGlobals()); - + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); + Results.EnterNewScope(); AddOrdinaryNameResults(PCC_Expression, S, *this, Results); Results.ExitScope(); - + bool PreferredTypeIsPointer = false; if (!Data.PreferredType.isNull()) PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() - || Data.PreferredType->isMemberPointerType() + || Data.PreferredType->isMemberPointerType() || Data.PreferredType->isBlockPointerType(); - - if (S->getFnParent() && - !Data.ObjCCollection && + + if (S->getFnParent() && + !Data.ObjCCollection && !Data.IntegralConstantExpression) AddPrettyFunctionResults(getLangOpts(), Results); if (CodeCompleter->includeMacros()) AddMacroResults(PP, Results, false, PreferredTypeIsPointer); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext(CodeCompletionContext::CCC_Expression, - Data.PreferredType), - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) { @@ -3701,29 +3785,29 @@ void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) { CodeCompleteObjCInstanceMessage(S, E.get(), None, false); } -/// \brief The set of properties that have already been added, referenced by +/// The set of properties that have already been added, referenced by /// property name. typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet; -/// \brief Retrieve the container definition, if any? +/// Retrieve the container definition, if any? static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) { if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { if (Interface->hasDefinition()) return Interface->getDefinition(); - + return Interface; } - + if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { if (Protocol->hasDefinition()) return Protocol->getDefinition(); - + return Protocol; } return Container; } -/// \brief Adds a block invocation code completion result for the given block +/// Adds a block invocation code completion result for the given block /// declaration \p BD. static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy, CodeCompletionBuilder &Builder, @@ -3770,7 +3854,7 @@ static void AddObjCProperties( // Retrieve the definition. Container = getContainerDef(Container); - + // Add properties in this container. const auto AddProperty = [&](const ObjCPropertyDecl *P) { if (!AddedProperties.insert(P->getIdentifier()).second) @@ -3889,7 +3973,7 @@ static void AddObjCProperties( } } } - + // Add properties in referenced protocols. if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { for (auto *P : Protocol->protocols()) @@ -3929,17 +4013,22 @@ static void AddObjCProperties( static void AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results, Scope *S, QualType BaseType, - RecordDecl *RD) { + RecordDecl *RD, + Optional<FixItHint> AccessOpFixIt) { // Indicate that we are performing a member access, and the cv-qualifiers // for the base object type. Results.setObjectTypeQualifiers(BaseType.getQualifiers()); // Access to a C/C++ class, struct, or union. Results.allowNestedNameSpecifiers(); - CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); + std::vector<FixItHint> FixIts; + if (AccessOpFixIt) + FixIts.emplace_back(AccessOpFixIt.getValue()); + CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext, std::move(FixIts)); SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer, SemaRef.CodeCompleter->includeGlobals(), - /*IncludeDependentBases=*/true); + /*IncludeDependentBases=*/true, + SemaRef.CodeCompleter->loadExternal()); if (SemaRef.getLangOpts().CPlusPlus) { if (!Results.empty()) { @@ -3962,106 +4051,138 @@ static void AddRecordMembersCompletionResults(Sema &SemaRef, } void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, + Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement) { if (!Base || !CodeCompleter) return; - + ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); if (ConvertedBase.isInvalid()) return; - Base = ConvertedBase.get(); - - QualType BaseType = Base->getType(); + QualType ConvertedBaseType = ConvertedBase.get()->getType(); + + enum CodeCompletionContext::Kind contextKind; if (IsArrow) { - if (const PointerType *Ptr = BaseType->getAs<PointerType>()) - BaseType = Ptr->getPointeeType(); - else if (BaseType->isObjCObjectPointerType()) - /*Do nothing*/ ; - else - return; + if (const PointerType *Ptr = ConvertedBaseType->getAs<PointerType>()) + ConvertedBaseType = Ptr->getPointeeType(); } - - enum CodeCompletionContext::Kind contextKind; - + if (IsArrow) { contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; - } - else { - if (BaseType->isObjCObjectPointerType() || - BaseType->isObjCObjectOrInterfaceType()) { + } else { + if (ConvertedBaseType->isObjCObjectPointerType() || + ConvertedBaseType->isObjCObjectOrInterfaceType()) { contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; - } - else { + } else { contextKind = CodeCompletionContext::CCC_DotMemberAccess; } } - CodeCompletionContext CCContext(contextKind, BaseType); + CodeCompletionContext CCContext(contextKind, ConvertedBaseType); ResultBuilder Results(*this, CodeCompleter->getAllocator(), - CodeCompleter->getCodeCompletionTUInfo(), - CCContext, + CodeCompleter->getCodeCompletionTUInfo(), CCContext, &ResultBuilder::IsMember); - Results.EnterNewScope(); - if (const RecordType *Record = BaseType->getAs<RecordType>()) { - AddRecordMembersCompletionResults(*this, Results, S, BaseType, - Record->getDecl()); - } else if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) { - TemplateName TN = TST->getTemplateName(); - if (const auto *TD = - dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) { - CXXRecordDecl *RD = TD->getTemplatedDecl(); - AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD); - } - } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) { - if (auto *RD = ICNT->getDecl()) - AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD); - } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { - // Objective-C property reference. - AddedPropertiesSet AddedProperties; - - if (const ObjCObjectPointerType *ObjCPtr = - BaseType->getAsObjCInterfacePointerType()) { - // Add property results based on our interface. - assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); - AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, - /*AllowNullaryMethods=*/true, CurContext, - AddedProperties, Results, IsBaseExprStatement); - } - - // Add properties from the protocols in a qualified interface. - for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals()) - AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, - CurContext, AddedProperties, Results, - IsBaseExprStatement); - } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || - (!IsArrow && BaseType->isObjCObjectType())) { - // Objective-C instance variable access. - ObjCInterfaceDecl *Class = nullptr; - if (const ObjCObjectPointerType *ObjCPtr - = BaseType->getAs<ObjCObjectPointerType>()) - Class = ObjCPtr->getInterfaceDecl(); - else - Class = BaseType->getAs<ObjCObjectType>()->getInterface(); - - // Add all ivars from this class and its superclasses. - if (Class) { - CodeCompletionDeclConsumer Consumer(Results, CurContext); - Results.setFilter(&ResultBuilder::IsObjCIvar); - LookupVisibleDecls(Class, LookupMemberName, Consumer, - CodeCompleter->includeGlobals()); + + auto DoCompletion = [&](Expr *Base, bool IsArrow, Optional<FixItHint> AccessOpFixIt) -> bool { + if (!Base) + return false; + + ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); + if (ConvertedBase.isInvalid()) + return false; + Base = ConvertedBase.get(); + + QualType BaseType = Base->getType(); + + if (IsArrow) { + if (const PointerType *Ptr = BaseType->getAs<PointerType>()) + BaseType = Ptr->getPointeeType(); + else if (BaseType->isObjCObjectPointerType()) + /*Do nothing*/; + else + return false; + } + + if (const RecordType *Record = BaseType->getAs<RecordType>()) { + AddRecordMembersCompletionResults(*this, Results, S, BaseType, + Record->getDecl(), + std::move(AccessOpFixIt)); + } else if (const auto *TST = + BaseType->getAs<TemplateSpecializationType>()) { + TemplateName TN = TST->getTemplateName(); + if (const auto *TD = + dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) { + CXXRecordDecl *RD = TD->getTemplatedDecl(); + AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, + std::move(AccessOpFixIt)); + } + } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) { + if (auto *RD = ICNT->getDecl()) + AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, + std::move(AccessOpFixIt)); + } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { + // Objective-C property reference. + AddedPropertiesSet AddedProperties; + + if (const ObjCObjectPointerType *ObjCPtr = + BaseType->getAsObjCInterfacePointerType()) { + // Add property results based on our interface. + assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); + AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, + /*AllowNullaryMethods=*/true, CurContext, + AddedProperties, Results, IsBaseExprStatement); + } + + // Add properties from the protocols in a qualified interface. + for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals()) + AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, + CurContext, AddedProperties, Results, + IsBaseExprStatement); + } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || + (!IsArrow && BaseType->isObjCObjectType())) { + // Objective-C instance variable access. + ObjCInterfaceDecl *Class = nullptr; + if (const ObjCObjectPointerType *ObjCPtr = + BaseType->getAs<ObjCObjectPointerType>()) + Class = ObjCPtr->getInterfaceDecl(); + else + Class = BaseType->getAs<ObjCObjectType>()->getInterface(); + + // Add all ivars from this class and its superclasses. + if (Class) { + CodeCompletionDeclConsumer Consumer(Results, CurContext); + Results.setFilter(&ResultBuilder::IsObjCIvar); + LookupVisibleDecls( + Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(), + /*IncludeDependentBases=*/false, CodeCompleter->loadExternal()); + } } + + // FIXME: How do we cope with isa? + return true; + }; + + Results.EnterNewScope(); + + bool CompletionSucceded = DoCompletion(Base, IsArrow, None); + if (CodeCompleter->includeFixIts()) { + const CharSourceRange OpRange = + CharSourceRange::getTokenRange(OpLoc, OpLoc); + CompletionSucceded |= DoCompletion( + OtherOpBase, !IsArrow, + FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->")); } - - // FIXME: How do we cope with isa? - + Results.ExitScope(); + if (!CompletionSucceded) + return; + // Hand off the results found for code completion. - HandleCodeCompleteResults(this, CodeCompleter, - Results.getCompletionContext(), - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S, @@ -4100,23 +4221,23 @@ void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { Filter = &ResultBuilder::IsEnum; ContextKind = CodeCompletionContext::CCC_EnumTag; break; - + case DeclSpec::TST_union: Filter = &ResultBuilder::IsUnion; ContextKind = CodeCompletionContext::CCC_UnionTag; break; - + case DeclSpec::TST_struct: case DeclSpec::TST_class: case DeclSpec::TST_interface: Filter = &ResultBuilder::IsClassOrStruct; ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; break; - + default: llvm_unreachable("Unknown type specifier kind in CodeCompleteTag"); } - + ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), ContextKind); CodeCompletionDeclConsumer Consumer(Results, CurContext); @@ -4124,14 +4245,17 @@ void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { // First pass: look for tags. Results.setFilter(Filter); LookupVisibleDecls(S, LookupTagName, Consumer, - CodeCompleter->includeGlobals()); + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); if (CodeCompleter->includeGlobals()) { // Second pass: look for nested name specifiers. Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); - LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer); + LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); } - + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(),Results.size()); } @@ -4157,7 +4281,7 @@ void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { Results.EnterNewScope(); AddTypeQualifierResults(DS, Results, LangOpts); Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(), Results.size()); } @@ -4171,8 +4295,8 @@ void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, AddTypeQualifierResults(DS, Results, LangOpts); if (LangOpts.CPlusPlus11) { Results.AddResult("noexcept"); - if (D.getContext() == Declarator::MemberContext && !D.isCtorOrDtor() && - !D.isStaticMember()) { + if (D.getContext() == DeclaratorContext::MemberContext && + !D.isCtorOrDtor() && !D.isStaticMember()) { if (!VS || !VS->isFinalSpecified()) Results.AddResult("final"); if (!VS || !VS->isOverrideSpecified()) @@ -4192,7 +4316,7 @@ void Sema::CodeCompleteCase(Scope *S) { if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) return; - SwitchStmt *Switch = getCurFunction()->SwitchStack.back(); + SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer(); QualType type = Switch->getCond()->IgnoreImplicit()->getType(); if (!type->isEnumeralType()) { CodeCompleteExpressionData Data(type); @@ -4200,20 +4324,20 @@ void Sema::CodeCompleteCase(Scope *S) { CodeCompleteExpression(S, Data); return; } - + // Code-complete the cases of a switch statement over an enumeration type - // by providing the list of + // by providing the list of EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); if (EnumDecl *Def = Enum->getDefinition()) Enum = Def; - + // Determine which enumerators we have already seen in the switch statement. // FIXME: Ideally, we would also be able to look *past* the code-completion // token, in case we are code-completing in the middle of the switch and not // at the end. However, we aren't able to do so at the moment. llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen; NestedNameSpecifier *Qualifier = nullptr; - for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; + for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; SC = SC->getNextSwitchCase()) { CaseStmt *Case = dyn_cast<CaseStmt>(SC); if (!Case) @@ -4221,16 +4345,16 @@ void Sema::CodeCompleteCase(Scope *S) { Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal)) - if (EnumConstantDecl *Enumerator + if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { - // We look into the AST of the case statement to determine which - // enumerator was named. Alternatively, we could compute the value of + // We look into the AST of the case statement to determine which + // enumerator was named. Alternatively, we could compute the value of // the integral constant expression, then compare it against the - // values of each enumerator. However, value-based approach would not - // work as well with C++ templates where enumerators declared within a + // values of each enumerator. However, value-based approach would not + // work as well with C++ templates where enumerators declared within a // template are type- and value-dependent. EnumeratorsSeen.insert(Enumerator); - + // If this is a qualified-id, keep track of the nested-name-specifier // so that we can reproduce it as part of code completion, e.g., // @@ -4245,14 +4369,14 @@ void Sema::CodeCompleteCase(Scope *S) { Qualifier = DRE->getQualifier(); } } - + if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) { - // If there are no prior enumerators in C++, check whether we have to + // If there are no prior enumerators in C++, check whether we have to // qualify the names of the enumerators that we suggest, because they // may not be visible in this scope. Qualifier = getRequiredQualification(Context, CurContext, Enum); } - + // Add any enumerators that have not yet been mentioned. ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), @@ -4261,23 +4385,17 @@ void Sema::CodeCompleteCase(Scope *S) { for (auto *E : Enum->enumerators()) { if (EnumeratorsSeen.count(E)) continue; - + CodeCompletionResult R(E, CCP_EnumInCase, Qualifier); Results.AddResult(R, CurContext, nullptr, false); } Results.ExitScope(); - //We need to make sure we're setting the right context, - //so only say we include macros if the code completer says we do - enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other; if (CodeCompleter->includeMacros()) { AddMacroResults(PP, Results, false); - kind = CodeCompletionContext::CCC_OtherWithMacros; } - - HandleCodeCompleteResults(this, CodeCompleter, - kind, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } static bool anyNullArguments(ArrayRef<Expr *> Args) { @@ -4316,7 +4434,7 @@ static void mergeCandidatesWithResults(Sema &SemaRef, } } -/// \brief Get the type of the Nth parameter from a given set of overload +/// Get the type of the Nth parameter from a given set of overload /// candidates. static QualType getParamType(Sema &SemaRef, ArrayRef<ResultCandidate> Candidates, @@ -4470,10 +4588,8 @@ void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc, return; // A complete type is needed to lookup for constructors. - if (!isCompleteType(Loc, Type)) - return; - - CXXRecordDecl *RD = Type->getAsCXXRecordDecl(); + CXXRecordDecl *RD = + isCompleteType(Loc, Type) ? Type->getAsCXXRecordDecl() : nullptr; if (!RD) { CodeCompleteExpression(S, Type); return; @@ -4511,7 +4627,7 @@ void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { CodeCompleteOrdinaryName(S, PCC_Expression); return; } - + CodeCompleteExpression(S, VD->getType()); } @@ -4537,13 +4653,14 @@ void Sema::CodeCompleteAfterIf(Scope *S) { mapCodeCompletionContext(*this, PCC_Statement)); Results.setFilter(&ResultBuilder::IsOrdinaryName); Results.EnterNewScope(); - + CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(S, LookupOrdinaryName, Consumer, - CodeCompleter->includeGlobals()); - + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); + AddOrdinaryNameResults(PCC_Statement, S, *this, Results); - + // "else" block CodeCompletionBuilder Builder(Results.getAllocator(), Results.getCodeCompletionTUInfo()); @@ -4580,13 +4697,13 @@ void Sema::CodeCompleteAfterIf(Scope *S) { Results.AddResult(Builder.TakeString()); Results.ExitScope(); - + if (S->getFnParent()) AddPrettyFunctionResults(getLangOpts(), Results); - + if (CodeCompleter->includeMacros()) AddMacroResults(PP, Results, false); - + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(),Results.size()); } @@ -4649,7 +4766,8 @@ void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer, /*IncludeGlobalScope=*/true, - /*IncludeDependentBases=*/true); + /*IncludeDependentBases=*/true, + CodeCompleter->loadExternal()); } auto CC = Results.getCompletionContext(); @@ -4662,33 +4780,33 @@ void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, void Sema::CodeCompleteUsing(Scope *S) { if (!CodeCompleter) return; - + ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_PotentiallyQualifiedName, &ResultBuilder::IsNestedNameSpecifier); Results.EnterNewScope(); - + // If we aren't in class scope, we could see the "namespace" keyword. if (!S->isClassScope()) Results.AddResult(CodeCompletionResult("namespace")); - - // After "using", we can see anything that would start a + + // After "using", we can see anything that would start a // nested-name-specifier. CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(S, LookupOrdinaryName, Consumer, - CodeCompleter->includeGlobals()); + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_PotentiallyQualifiedName, - Results.data(),Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteUsingDirective(Scope *S) { if (!CodeCompleter) return; - + // After "using namespace", we expect to see a namespace name or namespace // alias. ResultBuilder Results(*this, CodeCompleter->getAllocator(), @@ -4698,46 +4816,46 @@ void Sema::CodeCompleteUsingDirective(Scope *S) { Results.EnterNewScope(); CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(S, LookupOrdinaryName, Consumer, - CodeCompleter->includeGlobals()); + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Namespace, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteNamespaceDecl(Scope *S) { if (!CodeCompleter) return; - + DeclContext *Ctx = S->getEntity(); if (!S->getParent()) Ctx = Context.getTranslationUnitDecl(); - + bool SuppressedGlobalResults = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); - + ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), SuppressedGlobalResults ? CodeCompletionContext::CCC_Namespace : CodeCompletionContext::CCC_Other, &ResultBuilder::IsNamespace); - + if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { // We only want to see those namespaces that have already been defined // within this scope, because its likely that the user is creating an - // extended namespace declaration. Keep track of the most recent + // extended namespace declaration. Keep track of the most recent // definition of each namespace. std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; - for (DeclContext::specific_decl_iterator<NamespaceDecl> + for (DeclContext::specific_decl_iterator<NamespaceDecl> NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end()); NS != NSEnd; ++NS) OrigToLatest[NS->getOriginalNamespace()] = *NS; - - // Add the most recent definition (or extended definition) of each + + // Add the most recent definition (or extended definition) of each // namespace to the list of results. Results.EnterNewScope(); - for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator + for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end(); NS != NSEnd; ++NS) @@ -4747,8 +4865,8 @@ void Sema::CodeCompleteNamespaceDecl(Scope *S) { CurContext, nullptr, false); Results.ExitScope(); } - - HandleCodeCompleteResults(this, CodeCompleter, + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(),Results.size()); } @@ -4756,7 +4874,7 @@ void Sema::CodeCompleteNamespaceDecl(Scope *S) { void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { if (!CodeCompleter) return; - + // After "namespace", we expect to see a namespace or alias. ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), @@ -4764,8 +4882,9 @@ void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { &ResultBuilder::IsNamespaceOrAlias); CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(S, LookupOrdinaryName, Consumer, - CodeCompleter->includeGlobals()); - HandleCodeCompleteResults(this, CodeCompleter, + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(),Results.size()); } @@ -4780,26 +4899,26 @@ void Sema::CodeCompleteOperatorName(Scope *S) { CodeCompletionContext::CCC_Type, &ResultBuilder::IsType); Results.EnterNewScope(); - + // Add the names of overloadable operators. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ if (std::strcmp(Spelling, "?")) \ Results.AddResult(Result(Spelling)); #include "clang/Basic/OperatorKinds.def" - + // Add any type names visible from the current scope Results.allowNestedNameSpecifiers(); CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(S, LookupOrdinaryName, Consumer, - CodeCompleter->includeGlobals()); - + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); + // Add any type specifiers AddTypeSpecifierResults(getLangOpts(), Results); Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Type, - Results.data(),Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteConstructorInitializer( @@ -4813,12 +4932,12 @@ void Sema::CodeCompleteConstructorInitializer( CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); if (!Constructor) return; - + ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_PotentiallyQualifiedName); Results.EnterNewScope(); - + // Fill in any already-initialized fields or base classes. llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; llvm::SmallPtrSet<CanQualType, 4> InitializedBases; @@ -4830,7 +4949,7 @@ void Sema::CodeCompleteConstructorInitializer( InitializedFields.insert(cast<FieldDecl>( Initializers[I]->getAnyMember())); } - + // Add completions for base classes. CodeCompletionBuilder Builder(Results.getAllocator(), Results.getCodeCompletionTUInfo()); @@ -4841,69 +4960,69 @@ void Sema::CodeCompleteConstructorInitializer( if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) .second) { SawLastInitializer - = !Initializers.empty() && + = !Initializers.empty() && Initializers.back()->isBaseInitializer() && Context.hasSameUnqualifiedType(Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); continue; } - + Builder.AddTypedTextChunk( Results.getAllocator().CopyString( Base.getType().getAsString(Policy))); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("args"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(CodeCompletionResult(Builder.TakeString(), + Results.AddResult(CodeCompletionResult(Builder.TakeString(), SawLastInitializer? CCP_NextInitializer : CCP_MemberDeclaration)); SawLastInitializer = false; } - + // Add completions for virtual base classes. for (const auto &Base : ClassDecl->vbases()) { if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) .second) { SawLastInitializer - = !Initializers.empty() && + = !Initializers.empty() && Initializers.back()->isBaseInitializer() && Context.hasSameUnqualifiedType(Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); continue; } - + Builder.AddTypedTextChunk( Builder.getAllocator().CopyString( Base.getType().getAsString(Policy))); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("args"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(CodeCompletionResult(Builder.TakeString(), + Results.AddResult(CodeCompletionResult(Builder.TakeString(), SawLastInitializer? CCP_NextInitializer : CCP_MemberDeclaration)); SawLastInitializer = false; } - + // Add completions for members. for (auto *Field : ClassDecl->fields()) { if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) .second) { SawLastInitializer - = !Initializers.empty() && + = !Initializers.empty() && Initializers.back()->isAnyMemberInitializer() && Initializers.back()->getAnyMember() == Field; continue; } - + if (!Field->getDeclName()) continue; - + Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Field->getIdentifier()->getName())); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("args"); Builder.AddChunk(CodeCompletionString::CK_RightParen); - Results.AddResult(CodeCompletionResult(Builder.TakeString(), + Results.AddResult(CodeCompletionResult(Builder.TakeString(), SawLastInitializer? CCP_NextInitializer : CCP_MemberDeclaration, CXCursor_MemberRef, @@ -4912,12 +5031,12 @@ void Sema::CodeCompleteConstructorInitializer( SawLastInitializer = false; } Results.ExitScope(); - + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(), Results.size()); } -/// \brief Determine whether this scope denotes a namespace. +/// Determine whether this scope denotes a namespace. static bool isNamespaceScope(Scope *S) { DeclContext *DC = S->getEntity(); if (!DC) @@ -4941,10 +5060,10 @@ void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, IncludedThis = true; continue; } - + Known.insert(C.Id); } - + // Look for other capturable variables. for (; S && !isNamespaceScope(S); S = S->getParent()) { for (const auto *D : S->decls()) { @@ -4953,7 +5072,7 @@ void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>()) continue; - + if (Known.insert(Var->getIdentifier()).second) Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), CurContext, nullptr, false); @@ -4963,9 +5082,9 @@ void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, // Add 'this', if it would be valid. if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) addThisCompletion(*this, Results); - + Results.ExitScope(); - + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(), Results.size()); } @@ -4980,7 +5099,7 @@ static void AddObjCImplementationResults(const LangOptions &LangOpts, typedef CodeCompletionResult Result; // Since we have an implementation, we can end it. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end"))); - + CodeCompletionBuilder Builder(Results.getAllocator(), Results.getCodeCompletionTUInfo()); if (LangOpts.ObjC2) { @@ -4989,30 +5108,30 @@ static void AddObjCImplementationResults(const LangOptions &LangOpts, Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("property"); Results.AddResult(Result(Builder.TakeString())); - + // @synthesize Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize")); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("property"); Results.AddResult(Result(Builder.TakeString())); - } + } } static void AddObjCInterfaceResults(const LangOptions &LangOpts, ResultBuilder &Results, bool NeedAt) { typedef CodeCompletionResult Result; - + // Since we have an interface or protocol, we can end it. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end"))); - + if (LangOpts.ObjC2) { // @property Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property"))); - + // @required Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required"))); - + // @optional Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional"))); } @@ -5022,35 +5141,35 @@ static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { typedef CodeCompletionResult Result; CodeCompletionBuilder Builder(Results.getAllocator(), Results.getCodeCompletionTUInfo()); - + // @class name ; Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class")); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("name"); Results.AddResult(Result(Builder.TakeString())); - + if (Results.includeCodePatterns()) { - // @interface name - // FIXME: Could introduce the whole pattern, including superclasses and + // @interface name + // FIXME: Could introduce the whole pattern, including superclasses and // such. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface")); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("class"); Results.AddResult(Result(Builder.TakeString())); - + // @protocol name Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol")); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("protocol"); Results.AddResult(Result(Builder.TakeString())); - + // @implementation name Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation")); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("class"); Results.AddResult(Result(Builder.TakeString())); } - + // @compatibility_alias name Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias")); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -5080,9 +5199,8 @@ void Sema::CodeCompleteObjCAtDirective(Scope *S) { else AddObjCTopLevelResults(Results, false); Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { @@ -5101,7 +5219,7 @@ static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { Builder.AddPlaceholderChunk("type-name"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Results.AddResult(Result(Builder.TakeString())); - + // @protocol ( protocol-name ) Builder.AddResultTypeChunk("Protocol *"); Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol")); @@ -5154,7 +5272,7 @@ static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { typedef CodeCompletionResult Result; CodeCompletionBuilder Builder(Results.getAllocator(), Results.getCodeCompletionTUInfo()); - + if (Results.includeCodePatterns()) { // @try { statements } @catch ( declaration ) { statements } @finally // { statements } @@ -5175,13 +5293,13 @@ static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { Builder.AddChunk(CodeCompletionString::CK_RightBrace); Results.AddResult(Result(Builder.TakeString())); } - + // @throw Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw")); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("expression"); Results.AddResult(Result(Builder.TakeString())); - + if (Results.includeCodePatterns()) { // @synchronized ( expression ) { statements } Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized")); @@ -5214,9 +5332,8 @@ void Sema::CodeCompleteObjCAtVisibility(Scope *S) { Results.EnterNewScope(); AddObjCVisibilityResults(getLangOpts(), Results, false); Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteObjCAtStatement(Scope *S) { @@ -5227,9 +5344,8 @@ void Sema::CodeCompleteObjCAtStatement(Scope *S) { AddObjCStatementResults(Results, false); AddObjCExpressionResults(Results, false); Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteObjCAtExpression(Scope *S) { @@ -5239,25 +5355,24 @@ void Sema::CodeCompleteObjCAtExpression(Scope *S) { Results.EnterNewScope(); AddObjCExpressionResults(Results, false); Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } -/// \brief Determine whether the addition of the given flag to an Objective-C +/// Determine whether the addition of the given flag to an Objective-C /// property's attributes will cause a conflict. static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { // Check if we've already added this flag. if (Attributes & NewFlag) return true; - + Attributes |= NewFlag; - + // Check for collisions with "readonly". if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) return true; - + // Check for more than one of { assign, copy, retain, strong, weak }. unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_unsafe_unretained | @@ -5273,16 +5388,16 @@ static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong && AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak) return true; - + return false; } -void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { +void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { if (!CodeCompleter) return; - + unsigned Attributes = ODS.getPropertyAttributes(); - + ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_Other); @@ -5335,12 +5450,11 @@ void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { Results.AddResult(CodeCompletionResult("null_resettable")); } Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } -/// \brief Describes the kind of Objective-C method that we want to find +/// Describes the kind of Objective-C method that we want to find /// via code completion. enum ObjCMethodKind { MK_Any, ///< Any kind of method, provided it means other specified criteria. @@ -5355,20 +5469,20 @@ static bool isAcceptableObjCSelector(Selector Sel, unsigned NumSelIdents = SelIdents.size(); if (NumSelIdents > Sel.getNumArgs()) return false; - + switch (WantKind) { case MK_Any: break; case MK_ZeroArgSelector: return Sel.isUnarySelector(); case MK_OneArgSelector: return Sel.getNumArgs() == 1; } - + if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) return false; - + for (unsigned I = 0; I != NumSelIdents; ++I) if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) return false; - + return true; } @@ -5381,16 +5495,16 @@ static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, } namespace { - /// \brief A set of selectors, which is used to avoid introducing multiple + /// A set of selectors, which is used to avoid introducing multiple /// completions with the same selector into the result set. typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; } -/// \brief Add all of the Objective-C methods in the given Objective-C +/// Add all of the Objective-C methods in the given Objective-C /// container to the set of results. /// -/// The container will be a class, protocol, category, or implementation of -/// any of the above. This mether will recurse to include methods from +/// The container will be a class, protocol, category, or implementation of +/// any of the above. This mether will recurse to include methods from /// the superclasses of classes along with their categories, protocols, and /// implementations. /// @@ -5422,7 +5536,7 @@ static void AddObjCMethods(ObjCContainerDecl *Container, // metaclass. if (M->isInstanceMethod() == WantInstanceMethods || (IsRootClass && !WantInstanceMethods)) { - // Check whether the selector identifiers we've been given are a + // Check whether the selector identifiers we've been given are a // subset of the identifiers for this particular method. if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) continue; @@ -5438,23 +5552,23 @@ static void AddObjCMethods(ObjCContainerDecl *Container, Results.MaybeAddResult(R, CurContext); } } - + // Visit the protocols of protocols. if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { if (Protocol->hasDefinition()) { const ObjCList<ObjCProtocolDecl> &Protocols = Protocol->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), - E = Protocols.end(); + E = Protocols.end(); I != E; ++I) AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, Selectors, AllowSameLength, Results, false, IsRootClass); } } - + if (!IFace || !IFace->hasDefinition()) return; - + // Add methods in protocols. for (auto *I : IFace->protocols()) AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, @@ -5467,7 +5581,7 @@ static void AddObjCMethods(ObjCContainerDecl *Container, InOriginalClass, IsRootClass); // Add a categories protocol methods. - const ObjCList<ObjCProtocolDecl> &Protocols + const ObjCList<ObjCProtocolDecl> &Protocols = CatDecl->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), E = Protocols.end(); @@ -5481,7 +5595,7 @@ static void AddObjCMethods(ObjCContainerDecl *Container, Selectors, AllowSameLength, Results, InOriginalClass, IsRootClass); } - + // Add methods in superclass. // Avoid passing in IsRootClass since root classes won't have super classes. if (IFace->getSuperClass()) @@ -5519,9 +5633,8 @@ void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors, /*AllowSameLength=*/true, Results); Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteObjCPropertySetter(Scope *S) { @@ -5548,9 +5661,8 @@ void Sema::CodeCompleteObjCPropertySetter(Scope *S) { Selectors, /*AllowSameLength=*/true, Results); Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, @@ -5559,22 +5671,22 @@ void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_Type); Results.EnterNewScope(); - + // Add context-sensitive, Objective-C parameter-passing keywords. bool AddedInOut = false; - if ((DS.getObjCDeclQualifier() & + if ((DS.getObjCDeclQualifier() & (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { Results.AddResult("in"); Results.AddResult("inout"); AddedInOut = true; } - if ((DS.getObjCDeclQualifier() & + if ((DS.getObjCDeclQualifier() & (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { Results.AddResult("out"); if (!AddedInOut) Results.AddResult("inout"); } - if ((DS.getObjCDeclQualifier() & + if ((DS.getObjCDeclQualifier() & (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | ObjCDeclSpec::DQ_Oneway)) == 0) { Results.AddResult("bycopy"); @@ -5586,8 +5698,8 @@ void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, Results.AddResult("nullable"); Results.AddResult("null_unspecified"); } - - // If we're completing the return type of an Objective-C method and the + + // If we're completing the return type of an Objective-C method and the // identifier IBAction refers to a macro, provide a completion item for // an action, e.g., // IBAction)<#selector#>:(id)sender @@ -5611,26 +5723,26 @@ void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, if (!IsParameter) { Results.AddResult(CodeCompletionResult("instancetype")); } - + // Add various builtin type names and specifiers. AddOrdinaryNameResults(PCC_Type, S, *this, Results); Results.ExitScope(); - + // Add the various type names Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); CodeCompletionDeclConsumer Consumer(Results, CurContext); LookupVisibleDecls(S, LookupOrdinaryName, Consumer, - CodeCompleter->includeGlobals()); - + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); + if (CodeCompleter->includeMacros()) AddMacroResults(PP, Results, false); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Type, + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(), Results.size()); } -/// \brief When we have an expression with type "id", we may assume +/// When we have an expression with type "id", we may assume /// that it has some more-specific class type based on knowledge of /// common uses of Objective-C. This routine returns that class type, /// or NULL if no better result could be determined. @@ -5702,7 +5814,7 @@ static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { } // Add a special completion for a message send to "super", which fills in the -// most likely case of forwarding all of our arguments to the superclass +// most likely case of forwarding all of our arguments to the superclass // function. /// /// \param S The semantic analysis object. @@ -5715,7 +5827,7 @@ static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { /// /// \param Results The set of results to augment. /// -/// \returns the Objective-C method declaration that would be invoked by +/// \returns the Objective-C method declaration that would be invoked by /// this "super" completion. If NULL, no completion was added. static ObjCMethodDecl *AddSuperSendCompletion( Sema &S, bool NeedSuperKeyword, @@ -5733,7 +5845,7 @@ static ObjCMethodDecl *AddSuperSendCompletion( ObjCMethodDecl *SuperMethod = nullptr; while ((Class = Class->getSuperClass()) && !SuperMethod) { // Check in the class - SuperMethod = Class->getMethod(CurMethod->getSelector(), + SuperMethod = Class->getMethod(CurMethod->getSelector(), CurMethod->isInstanceMethod()); // Check in categories or class extensions. @@ -5759,7 +5871,7 @@ static ObjCMethodDecl *AddSuperSendCompletion( SuperP = SuperMethod->param_begin(); CurP != CurPEnd; ++CurP, ++SuperP) { // Make sure the parameter types are compatible. - if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), + if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), (*SuperP)->getType())) return nullptr; @@ -5767,11 +5879,11 @@ static ObjCMethodDecl *AddSuperSendCompletion( if (!(*CurP)->getIdentifier()) return nullptr; } - + // We have a superclass method. Now, form the send-to-super completion. CodeCompletionBuilder Builder(Results.getAllocator(), Results.getCodeCompletionTUInfo()); - + // Give this completion a return type. AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, Results.getCompletionContext().getBaseType(), @@ -5782,7 +5894,7 @@ static ObjCMethodDecl *AddSuperSendCompletion( Builder.AddTypedTextChunk("super"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); } - + Selector Sel = CurMethod->getSelector(); if (Sel.isUnarySelector()) { if (NeedSuperKeyword) @@ -5796,7 +5908,7 @@ static ObjCMethodDecl *AddSuperSendCompletion( for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { if (I > SelIdents.size()) Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); - + if (I < SelIdents.size()) Builder.AddInformativeChunk( Builder.getAllocator().CopyString( @@ -5812,16 +5924,16 @@ static ObjCMethodDecl *AddSuperSendCompletion( Builder.getAllocator().CopyString( Sel.getNameForSlot(I) + ":")); Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( - (*CurP)->getIdentifier()->getName())); + (*CurP)->getIdentifier()->getName())); } } } - + Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, CCP_SuperCompletion)); return SuperMethod; } - + void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { typedef CodeCompletionResult Result; ResultBuilder Results(*this, CodeCompleter->getAllocator(), @@ -5830,32 +5942,33 @@ void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { getLangOpts().CPlusPlus11 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture : &ResultBuilder::IsObjCMessageReceiver); - + CodeCompletionDeclConsumer Consumer(Results, CurContext); Results.EnterNewScope(); LookupVisibleDecls(S, LookupOrdinaryName, Consumer, - CodeCompleter->includeGlobals()); - + CodeCompleter->includeGlobals(), + CodeCompleter->loadExternal()); + // If we are in an Objective-C method inside a class that has a superclass, // add "super" as an option. if (ObjCMethodDecl *Method = getCurMethodDecl()) if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) if (Iface->getSuperClass()) { Results.AddResult(Result("super")); - + AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results); } - + if (getLangOpts().CPlusPlus11) addThisCompletion(*this, Results); - + Results.ExitScope(); - + if (CodeCompleter->includeMacros()) AddMacroResults(PP, Results, false); HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(), Results.size()); - + } void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, @@ -5867,7 +5980,7 @@ void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, CDecl = CurMethod->getClassInterface(); if (!CDecl) return; - + // Find the superclass of this class. CDecl = CDecl->getSuperClass(); if (!CDecl) @@ -5887,7 +6000,7 @@ void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, // "super" may be the name of a type or variable. Figure out which // it is. IdentifierInfo *Super = getSuperIdentifier(); - NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, + NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName); if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { // "super" names an interface. Use it. @@ -5916,24 +6029,24 @@ void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ParsedType Receiver; if (CDecl) Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); - return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, + return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, AtArgumentExpression, /*IsSuper=*/true); } -/// \brief Given a set of code-completion results for the argument of a message +/// Given a set of code-completion results for the argument of a message /// send, determine the preferred type (if any) for that argument expression. static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, unsigned NumSelIdents) { - typedef CodeCompletionResult Result; + typedef CodeCompletionResult Result; ASTContext &Context = Results.getSema().Context; - + QualType PreferredType; unsigned BestPriority = CCP_Unlikely * 2; Result *ResultsData = Results.data(); for (unsigned I = 0, N = Results.size(); I != N; ++I) { Result &R = ResultsData[I]; - if (R.Kind == Result::RK_Declaration && + if (R.Kind == Result::RK_Declaration && isa<ObjCMethodDecl>(R.Declaration)) { if (R.Priority <= BestPriority) { const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); @@ -5955,7 +6068,7 @@ static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, return PreferredType; } -static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, +static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, @@ -5968,55 +6081,55 @@ static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, // corresponding declaration. if (Receiver) { QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); - if (!T.isNull()) + if (!T.isNull()) if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) CDecl = Interface->getInterface(); } - + // Add all of the factory methods in this Objective-C class, its protocols, // superclasses, categories, implementation, etc. Results.EnterNewScope(); - - // If this is a send-to-super, try to add the special "super" send + + // If this is a send-to-super, try to add the special "super" send // completion. if (IsSuper) { if (ObjCMethodDecl *SuperMethod = AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) Results.Ignore(SuperMethod); } - + // If we're inside an Objective-C method definition, prefer its selector to // others. if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) Results.setPreferredSelector(CurMethod->getSelector()); - + VisitedSelectorSet Selectors; - if (CDecl) + if (CDecl) AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext, Selectors, AtArgumentExpression, - Results); + Results); else { // We're messaging "id" as a type; provide all class/factory methods. - + // If we have an external source, load the entire class method // pool from the AST file. if (SemaRef.getExternalSource()) { - for (uint32_t I = 0, + for (uint32_t I = 0, N = SemaRef.getExternalSource()->GetNumExternalSelectors(); I != N; ++I) { Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) continue; - + SemaRef.ReadMethodPool(Sel); } } - + for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), MEnd = SemaRef.MethodPool.end(); M != MEnd; ++M) { for (ObjCMethodList *MethList = &M->second.second; - MethList && MethList->getMethod(); + MethList && MethList->getMethod(); MethList = MethList->getNext()) { if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) continue; @@ -6029,32 +6142,32 @@ static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, } } } - - Results.ExitScope(); + + Results.ExitScope(); } void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper) { - + QualType T = this->GetTypeFromParser(Receiver); - + ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T, SelIdents)); - + AddClassMessageCompletions(*this, S, Receiver, SelIdents, AtArgumentExpression, IsSuper, Results); - - // If we're actually at the argument expression (rather than prior to the + + // If we're actually at the argument expression (rather than prior to the // selector), we're actually performing code completion for an expression. - // Determine whether we have a single, best method. If so, we can + // Determine whether we have a single, best method. If so, we can // code-complete the expression using the corresponding parameter type as // our preferred type, improving completion results. if (AtArgumentExpression) { - QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, + QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); if (PreferredType.isNull()) CodeCompleteOrdinaryName(S, PCC_Expression); @@ -6063,7 +6176,7 @@ void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, return; } - HandleCodeCompleteResults(this, CodeCompleter, + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(), Results.size()); } @@ -6073,9 +6186,9 @@ void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, bool AtArgumentExpression, ObjCInterfaceDecl *Super) { typedef CodeCompletionResult Result; - + Expr *RecExpr = static_cast<Expr *>(Receiver); - + // If necessary, apply function/array conversion to the receiver. // C99 6.7.5.3p[7,8]. if (RecExpr) { @@ -6084,18 +6197,18 @@ void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, return; RecExpr = Conv.get(); } - QualType ReceiverType = RecExpr? RecExpr->getType() + QualType ReceiverType = RecExpr? RecExpr->getType() : Super? Context.getObjCObjectPointerType( Context.getObjCInterfaceType(Super)) : Context.getObjCIdType(); - + // If we're messaging an expression with type "id" or "Class", check // whether we know something special about the receiver that allows // us to assume a more-specific receiver type. if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { if (ReceiverType->isObjCClassType()) - return CodeCompleteObjCClassMessage(S, + return CodeCompleteObjCClassMessage(S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents, AtArgumentExpression, Super); @@ -6116,36 +6229,36 @@ void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, ReceiverType, SelIdents)); - + Results.EnterNewScope(); - // If this is a send-to-super, try to add the special "super" send + // If this is a send-to-super, try to add the special "super" send // completion. if (Super) { if (ObjCMethodDecl *SuperMethod = AddSuperSendCompletion(*this, false, SelIdents, Results)) Results.Ignore(SuperMethod); } - + // If we're inside an Objective-C method definition, prefer its selector to // others. if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) Results.setPreferredSelector(CurMethod->getSelector()); - + // Keep track of the selectors we've already added. VisitedSelectorSet Selectors; - + // Handle messages to Class. This really isn't a message to an instance // method, so we treat it the same way we would treat a message send to a // class method. - if (ReceiverType->isObjCClassType() || + if (ReceiverType->isObjCClassType() || ReceiverType->isObjCQualifiedClassType()) { if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext, Selectors, AtArgumentExpression, Results); } - } + } // Handle messages to a qualified ID ("id<foo>"). else if (const ObjCObjectPointerType *QualID = ReceiverType->getAsObjCQualifiedIdType()) { @@ -6161,7 +6274,7 @@ void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, CurContext, Selectors, AtArgumentExpression, Results); - + // Search protocols for instance methods. for (auto *I : IFacePtr->quals()) AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, @@ -6189,11 +6302,11 @@ void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, MEnd = MethodPool.end(); M != MEnd; ++M) { for (ObjCMethodList *MethList = &M->second.first; - MethList && MethList->getMethod(); + MethList && MethList->getMethod(); MethList = MethList->getNext()) { if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) continue; - + if (!Selectors.insert(MethList->getMethod()->getSelector()).second) continue; @@ -6206,15 +6319,15 @@ void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, } } Results.ExitScope(); - - - // If we're actually at the argument expression (rather than prior to the + + + // If we're actually at the argument expression (rather than prior to the // selector), we're actually performing code completion for an expression. - // Determine whether we have a single, best method. If so, we can + // Determine whether we have a single, best method. If so, we can // code-complete the expression using the corresponding parameter type as // our preferred type, improving completion results. if (AtArgumentExpression) { - QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, + QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); if (PreferredType.isNull()) CodeCompleteOrdinaryName(S, PCC_Expression); @@ -6222,17 +6335,17 @@ void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, CodeCompleteExpression(S, PreferredType); return; } - - HandleCodeCompleteResults(this, CodeCompleter, + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(),Results.size()); } -void Sema::CodeCompleteObjCForCollection(Scope *S, +void Sema::CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar) { CodeCompleteExpressionData Data; Data.ObjCCollection = true; - + if (IterationVar.getAsOpaquePtr()) { DeclGroupRef DG = IterationVar.get(); for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { @@ -6240,7 +6353,7 @@ void Sema::CodeCompleteObjCForCollection(Scope *S, Data.IgnoreDecls.push_back(*I); } } - + CodeCompleteExpression(S, Data); } @@ -6254,11 +6367,11 @@ void Sema::CodeCompleteObjCSelector(Scope *S, Selector Sel = ExternalSource->GetExternalSelector(I); if (Sel.isNull() || MethodPool.count(Sel)) continue; - + ReadMethodPool(Sel); } } - + ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_SelectorName); @@ -6266,7 +6379,7 @@ void Sema::CodeCompleteObjCSelector(Scope *S, for (GlobalMethodPool::iterator M = MethodPool.begin(), MEnd = MethodPool.end(); M != MEnd; ++M) { - + Selector Sel = M->first; if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) continue; @@ -6279,7 +6392,7 @@ void Sema::CodeCompleteObjCSelector(Scope *S, Results.AddResult(Builder.TakeString()); continue; } - + std::string Accumulator; for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { if (I == SelIdents.size()) { @@ -6289,7 +6402,7 @@ void Sema::CodeCompleteObjCSelector(Scope *S, Accumulator.clear(); } } - + Accumulator += Sel.getNameForSlot(I); Accumulator += ':'; } @@ -6297,19 +6410,18 @@ void Sema::CodeCompleteObjCSelector(Scope *S, Results.AddResult(Builder.TakeString()); } Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_SelectorName, + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(), Results.size()); } -/// \brief Add all of the protocol declarations that we find in the given +/// Add all of the protocol declarations that we find in the given /// (translation unit) context. static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, bool OnlyForwardDeclarations, ResultBuilder &Results) { typedef CodeCompletionResult Result; - + for (const auto *D : Ctx->decls()) { // Record any protocols we find. if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) @@ -6324,10 +6436,10 @@ void Sema::CodeCompleteObjCProtocolReferences( ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_ObjCProtocolName); - + if (CodeCompleter->includeGlobals()) { Results.EnterNewScope(); - + // Tell the result set to ignore all of the protocols we have // already seen. // FIXME: This doesn't work when caching code-completion results. @@ -6342,40 +6454,38 @@ void Sema::CodeCompleteObjCProtocolReferences( Results.ExitScope(); } - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_ObjCProtocolName, - Results.data(),Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteObjCProtocolDecl(Scope *) { ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_ObjCProtocolName); - + if (CodeCompleter->includeGlobals()) { Results.EnterNewScope(); - + // Add all protocols. AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, Results); Results.ExitScope(); } - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_ObjCProtocolName, - Results.data(),Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } -/// \brief Add all of the Objective-C interface declarations that we find in +/// Add all of the Objective-C interface declarations that we find in /// the given (translation unit) context. static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, bool OnlyForwardDeclarations, bool OnlyUnimplemented, ResultBuilder &Results) { typedef CodeCompletionResult Result; - + for (const auto *D : Ctx->decls()) { // Record any interfaces we find. if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) @@ -6386,32 +6496,31 @@ static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, } } -void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { +void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), - CodeCompletionContext::CCC_Other); + CodeCompletionContext::CCC_ObjCInterfaceName); Results.EnterNewScope(); - + if (CodeCompleter->includeGlobals()) { // Add all classes. AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, false, Results); } - + Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_ObjCInterfaceName, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, - SourceLocation ClassNameLoc) { + SourceLocation ClassNameLoc) { ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_ObjCInterfaceName); Results.EnterNewScope(); - + // Make sure that we ignore the class we're currently defining. NamedDecl *CurClass = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); @@ -6423,18 +6532,17 @@ void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, false, Results); } - + Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_ObjCInterfaceName, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } -void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { +void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), - CodeCompletionContext::CCC_Other); + CodeCompletionContext::CCC_ObjCImplementation); Results.EnterNewScope(); if (CodeCompleter->includeGlobals()) { @@ -6442,23 +6550,22 @@ void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, true, Results); } - + Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_ObjCInterfaceName, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } -void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, +void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) { typedef CodeCompletionResult Result; - + ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_ObjCCategoryName); - + // Ignore any categories we find that have already been implemented by this // interface. llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; @@ -6472,24 +6579,23 @@ void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, // Add all of the categories we know about. Results.EnterNewScope(); TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); - for (const auto *D : TU->decls()) + for (const auto *D : TU->decls()) if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) if (CategoryNames.insert(Category->getIdentifier()).second) Results.AddResult(Result(Category, Results.getBasePriority(Category), nullptr), CurContext, nullptr, false); Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_ObjCCategoryName, - Results.data(),Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } -void Sema::CodeCompleteObjCImplementationCategory(Scope *S, +void Sema::CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) { typedef CodeCompletionResult Result; - + // Find the corresponding interface. If we couldn't find the interface, the // program itself is ill-formed. However, we'll try to be helpful still by // providing the list of all of the categories we know about. @@ -6498,12 +6604,12 @@ void Sema::CodeCompleteObjCImplementationCategory(Scope *S, ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); if (!Class) return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); - + ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_ObjCCategoryName); - - // Add all of the categories that have have corresponding interface + + // Add all of the categories that have have corresponding interface // declarations in this class and any of its superclasses, except for // already-implemented categories in the class itself. llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; @@ -6516,15 +6622,14 @@ void Sema::CodeCompleteObjCImplementationCategory(Scope *S, Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), CurContext, nullptr, false); } - + Class = Class->getSuperClass(); IgnoreImplemented = false; } Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_ObjCCategoryName, - Results.data(),Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { @@ -6536,38 +6641,37 @@ void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { // Figure out where this @synthesize lives. ObjCContainerDecl *Container = dyn_cast_or_null<ObjCContainerDecl>(CurContext); - if (!Container || - (!isa<ObjCImplementationDecl>(Container) && + if (!Container || + (!isa<ObjCImplementationDecl>(Container) && !isa<ObjCCategoryImplDecl>(Container))) - return; + return; // Ignore any properties that have already been implemented. Container = getContainerDef(Container); for (const auto *D : Container->decls()) if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) Results.Ignore(PropertyImpl->getPropertyDecl()); - + // Add any properties that we find. AddedPropertiesSet AddedProperties; Results.EnterNewScope(); if (ObjCImplementationDecl *ClassImpl = dyn_cast<ObjCImplementationDecl>(Container)) AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, - /*AllowNullaryMethods=*/false, CurContext, + /*AllowNullaryMethods=*/false, CurContext, AddedProperties, Results); else AddObjCProperties(CCContext, cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), - false, /*AllowNullaryMethods=*/false, CurContext, + false, /*AllowNullaryMethods=*/false, CurContext, AddedProperties, Results); Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } -void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, +void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName) { typedef CodeCompletionResult Result; ResultBuilder Results(*this, CodeCompleter->getAllocator(), @@ -6577,11 +6681,11 @@ void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, // Figure out where this @synthesize lives. ObjCContainerDecl *Container = dyn_cast_or_null<ObjCContainerDecl>(CurContext); - if (!Container || - (!isa<ObjCImplementationDecl>(Container) && + if (!Container || + (!isa<ObjCImplementationDecl>(Container) && !isa<ObjCCategoryImplDecl>(Container))) - return; - + return; + // Figure out which interface we're looking into. ObjCInterfaceDecl *Class = nullptr; if (ObjCImplementationDecl *ClassImpl @@ -6596,10 +6700,10 @@ void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, if (Class) { if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { - PropertyType + PropertyType = Property->getType().getNonReferenceType().getUnqualifiedType(); - - // Give preference to ivars + + // Give preference to ivars Results.setPreferredType(PropertyType); } } @@ -6613,32 +6717,32 @@ void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, std::string NameWithSuffix = PropertyName->getName().str(); NameWithSuffix += '_'; for(; Class; Class = Class->getSuperClass()) { - for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; + for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; Ivar = Ivar->getNextIvar()) { Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), CurContext, nullptr, false); - // Determine whether we've seen an ivar with a name similar to the + // Determine whether we've seen an ivar with a name similar to the // property. if ((PropertyName == Ivar->getIdentifier() || NameWithPrefix == Ivar->getName() || NameWithSuffix == Ivar->getName())) { SawSimilarlyNamedIvar = true; - + // Reduce the priority of this result by one, to give it a slight // advantage over other results whose names don't match so closely. - if (Results.size() && - Results.data()[Results.size() - 1].Kind + if (Results.size() && + Results.data()[Results.size() - 1].Kind == CodeCompletionResult::RK_Declaration && Results.data()[Results.size() - 1].Declaration == Ivar) Results.data()[Results.size() - 1].Priority--; } } } - + if (!SawSimilarlyNamedIvar) { // Create ivar result _propName, that the user can use to synthesize - // an ivar of the appropriate type. + // an ivar of the appropriate type. unsigned Priority = CCP_MemberDeclaration + 1; typedef CodeCompletionResult Result; CodeCompletionAllocator &Allocator = Results.getAllocator(); @@ -6649,15 +6753,14 @@ void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context, Policy, Allocator)); Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); - Results.AddResult(Result(Builder.TakeString(), Priority, + Results.AddResult(Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl)); } - + Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } // Mapping from selectors to the methods that implement that selector, along @@ -6665,7 +6768,7 @@ void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, typedef llvm::DenseMap< Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap; -/// \brief Find all of the methods that reside in the given container +/// Find all of the methods that reside in the given container /// (and its superclasses, protocols, etc.) that meet the given /// criteria. Insert those methods into the map of known methods, /// indexed by selector so they can be easily found. @@ -6682,11 +6785,11 @@ static void FindImplementableMethods(ASTContext &Context, IFace = IFace->getDefinition(); Container = IFace; - + const ObjCList<ObjCProtocolDecl> &Protocols = IFace->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), - E = Protocols.end(); + E = Protocols.end(); I != E; ++I) FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, KnownMethods, InOriginalClass); @@ -6694,12 +6797,12 @@ static void FindImplementableMethods(ASTContext &Context, // Add methods from any class extensions and categories. for (auto *Cat : IFace->visible_categories()) { FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, - KnownMethods, false); + KnownMethods, false); } // Visit the superclass. if (IFace->getSuperClass()) - FindImplementableMethods(Context, IFace->getSuperClass(), + FindImplementableMethods(Context, IFace->getSuperClass(), WantInstanceMethods, ReturnType, KnownMethods, false); } @@ -6709,14 +6812,14 @@ static void FindImplementableMethods(ASTContext &Context, const ObjCList<ObjCProtocolDecl> &Protocols = Category->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), - E = Protocols.end(); + E = Protocols.end(); I != E; ++I) FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, KnownMethods, InOriginalClass); - + // If this category is the original class, jump to the interface. if (InOriginalClass && Category->getClassInterface()) - FindImplementableMethods(Context, Category->getClassInterface(), + FindImplementableMethods(Context, Category->getClassInterface(), WantInstanceMethods, ReturnType, KnownMethods, false); } @@ -6727,12 +6830,12 @@ static void FindImplementableMethods(ASTContext &Context, return; Protocol = Protocol->getDefinition(); Container = Protocol; - + // Recurse into protocols. const ObjCList<ObjCProtocolDecl> &Protocols = Protocol->getReferencedProtocols(); for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), - E = Protocols.end(); + E = Protocols.end(); I != E; ++I) FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, KnownMethods, false); @@ -6753,7 +6856,7 @@ static void FindImplementableMethods(ASTContext &Context, } } -/// \brief Add the parenthesized return or parameter type chunk to a code +/// Add the parenthesized return or parameter type chunk to a code /// completion string. static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, @@ -6769,20 +6872,20 @@ static void AddObjCPassingTypeChunk(QualType Type, Builder.AddChunk(CodeCompletionString::CK_RightParen); } -/// \brief Determine whether the given class is or inherits from a class by +/// Determine whether the given class is or inherits from a class by /// the given name. -static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, +static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) { if (!Class) return false; - + if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) return true; - + return InheritsFromClassNamed(Class->getSuperClass(), Name); } - -/// \brief Add code completions for Objective-C Key-Value Coding (KVC) and + +/// Add code completions for Objective-C Key-Value Coding (KVC) and /// Key-Value Observing (KVO). static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, bool IsInstanceMethod, @@ -6793,17 +6896,17 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, IdentifierInfo *PropName = Property->getIdentifier(); if (!PropName || PropName->getLength() == 0) return; - + PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); // Builder that will create each code completion. typedef CodeCompletionResult Result; CodeCompletionAllocator &Allocator = Results.getAllocator(); CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); - + // The selector table. SelectorTable &Selectors = Context.Selectors; - + // The property name, copied into the code completion allocation region // on demand. struct KeyHolder { @@ -6817,22 +6920,22 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, operator const char *() { if (CopiedKey) return CopiedKey; - + return CopiedKey = Allocator.CopyString(Key); } } Key(Allocator, PropName->getName()); - + // The uppercased name of the property name. std::string UpperKey = PropName->getName(); if (!UpperKey.empty()) UpperKey[0] = toUppercase(UpperKey[0]); - + bool ReturnTypeMatchesProperty = ReturnType.isNull() || - Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), + Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), Property->getType()); - bool ReturnTypeMatchesVoid + bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType(); - + // Add the normal accessor -(type)key. if (IsInstanceMethod && KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && @@ -6840,19 +6943,19 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, if (ReturnType.isNull()) AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, Builder); - + Builder.AddTypedTextChunk(Key); - Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, + Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, CXCursor_ObjCInstanceMethodDecl)); } - + // If we have an integral or boolean property (or the user has provided // an integral or boolean return type), add the accessor -(type)isKey. if (IsInstanceMethod && - ((!ReturnType.isNull() && + ((!ReturnType.isNull() && (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || - (ReturnType.isNull() && - (Property->getType()->isIntegerType() || + (ReturnType.isNull() && + (Property->getType()->isIntegerType() || Property->getType()->isBooleanType())))) { std::string SelectorName = (Twine("is") + UpperKey).str(); IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); @@ -6863,16 +6966,16 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("BOOL"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk( Allocator.CopyString(SelectorId->getName())); - Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, + Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, CXCursor_ObjCInstanceMethodDecl)); } } - + // Add the normal mutator. - if (IsInstanceMethod && ReturnTypeMatchesVoid && + if (IsInstanceMethod && ReturnTypeMatchesVoid && !Property->getSetterMethodDecl()) { std::string SelectorName = (Twine("set") + UpperKey).str(); IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); @@ -6882,36 +6985,36 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk( Allocator.CopyString(SelectorId->getName())); Builder.AddTypedTextChunk(":"); AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, Builder); Builder.AddTextChunk(Key); - Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, + Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, CXCursor_ObjCInstanceMethodDecl)); } } - + // Indexed and unordered accessors unsigned IndexedGetterPriority = CCP_CodePattern; unsigned IndexedSetterPriority = CCP_CodePattern; unsigned UnorderedGetterPriority = CCP_CodePattern; unsigned UnorderedSetterPriority = CCP_CodePattern; - if (const ObjCObjectPointerType *ObjCPointer + if (const ObjCObjectPointerType *ObjCPointer = Property->getType()->getAs<ObjCObjectPointerType>()) { if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { // If this interface type is not provably derived from a known // collection, penalize the corresponding completions. if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { - IndexedSetterPriority += CCD_ProbablyNotObjCCollection; + IndexedSetterPriority += CCD_ProbablyNotObjCCollection; if (!InheritsFromClassNamed(IFace, "NSArray")) IndexedGetterPriority += CCD_ProbablyNotObjCCollection; } if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { - UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; + UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; if (!InheritsFromClassNamed(IFace, "NSSet")) UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; } @@ -6922,9 +7025,9 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; } - + // Add -(NSUInteger)countOf<key> - if (IsInstanceMethod && + if (IsInstanceMethod && (ReturnType.isNull() || ReturnType->isIntegerType())) { std::string SelectorName = (Twine("countOf") + UpperKey).str(); IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); @@ -6935,16 +7038,16 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("NSUInteger"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk( Allocator.CopyString(SelectorId->getName())); - Results.AddResult(Result(Builder.TakeString(), - std::min(IndexedGetterPriority, + Results.AddResult(Result(Builder.TakeString(), + std::min(IndexedGetterPriority, UnorderedGetterPriority), CXCursor_ObjCInstanceMethodDecl)); } } - + // Indexed getters // Add -(id)objectInKeyAtIndex:(NSUInteger)index if (IsInstanceMethod && @@ -6958,20 +7061,20 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("id"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("NSUInteger"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("index"); - Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, + Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } - + // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes if (IsInstanceMethod && - (ReturnType.isNull() || + (ReturnType.isNull() || (ReturnType->isObjCObjectPointerType() && ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() @@ -6985,17 +7088,17 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("NSArray *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("NSIndexSet *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("indexes"); - Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, + Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } - + // Add -(void)getKey:(type **)buffer range:(NSRange)inRange if (IsInstanceMethod && ReturnTypeMatchesVoid) { std::string SelectorName = (Twine("get") + UpperKey).str(); @@ -7003,14 +7106,14 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, &Context.Idents.get(SelectorName), &Context.Idents.get("range") }; - + if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { if (ReturnType.isNull()) { Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("object-type"); @@ -7023,13 +7126,13 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("NSRange"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("inRange"); - Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, + Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } - + // Mutable indexed accessors - + // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index if (IsInstanceMethod && ReturnTypeMatchesVoid) { std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); @@ -7037,14 +7140,14 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, &Context.Idents.get("insertObject"), &Context.Idents.get(SelectorName) }; - + if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { if (ReturnType.isNull()) { Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk("insertObject:"); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("object-type"); @@ -7057,11 +7160,11 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddPlaceholderChunk("NSUInteger"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("index"); - Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } - + // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes if (IsInstanceMethod && ReturnTypeMatchesVoid) { std::string SelectorName = (Twine("insert") + UpperKey).str(); @@ -7069,14 +7172,14 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, &Context.Idents.get(SelectorName), &Context.Idents.get("atIndexes") }; - + if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { if (ReturnType.isNull()) { Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("NSArray *"); @@ -7088,55 +7191,55 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddPlaceholderChunk("NSIndexSet *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("indexes"); - Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } - + // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index if (IsInstanceMethod && ReturnTypeMatchesVoid) { std::string SelectorName = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); - IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); + IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { if (ReturnType.isNull()) { Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("NSUInteger"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("index"); - Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } - + // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes if (IsInstanceMethod && ReturnTypeMatchesVoid) { std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str(); - IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); + IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { if (ReturnType.isNull()) { Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("NSIndexSet *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("indexes"); - Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } - + // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object if (IsInstanceMethod && ReturnTypeMatchesVoid) { std::string SelectorName @@ -7145,14 +7248,14 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, &Context.Idents.get(SelectorName), &Context.Idents.get("withObject") }; - + if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { if (ReturnType.isNull()) { Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("NSUInteger"); @@ -7164,28 +7267,28 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("id"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("object"); - Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } - + // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array if (IsInstanceMethod && ReturnTypeMatchesVoid) { - std::string SelectorName1 + std::string SelectorName1 = (Twine("replace") + UpperKey + "AtIndexes").str(); std::string SelectorName2 = (Twine("with") + UpperKey).str(); IdentifierInfo *SelectorIds[2] = { &Context.Idents.get(SelectorName1), &Context.Idents.get(SelectorName2) }; - + if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { if (ReturnType.isNull()) { Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("NSIndexSet *"); @@ -7197,15 +7300,15 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("NSArray *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("array"); - Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } - } - + } + // Unordered getters // - (NSEnumerator *)enumeratorOfKey - if (IsInstanceMethod && - (ReturnType.isNull() || + if (IsInstanceMethod && + (ReturnType.isNull() || (ReturnType->isObjCObjectPointerType() && ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() @@ -7219,15 +7322,15 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("NSEnumerator *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); - Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, + Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } // - (type *)memberOfKey:(type *)object - if (IsInstanceMethod && + if (IsInstanceMethod && (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { std::string SelectorName = (Twine("memberOf") + UpperKey).str(); IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); @@ -7238,24 +7341,24 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk(" *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); if (ReturnType.isNull()) { Builder.AddPlaceholderChunk("object-type"); Builder.AddTextChunk(" *"); } else { - Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context, + Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context, Policy, Builder.getAllocator())); } Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("object"); - Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, + Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, CXCursor_ObjCInstanceMethodDecl)); } } - + // Mutable unordered accessors // - (void)addKeyObject:(type *)object if (IsInstanceMethod && ReturnTypeMatchesVoid) { @@ -7268,17 +7371,17 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("object-type"); Builder.AddTextChunk(" *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("object"); - Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } - } + } // - (void)addKey:(NSSet *)objects if (IsInstanceMethod && ReturnTypeMatchesVoid) { @@ -7290,17 +7393,17 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("NSSet *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("objects"); - Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } - } - + } + // - (void)removeKeyObject:(type *)object if (IsInstanceMethod && ReturnTypeMatchesVoid) { std::string SelectorName @@ -7312,18 +7415,18 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddPlaceholderChunk("object-type"); Builder.AddTextChunk(" *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("object"); - Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } - } - + } + // - (void)removeKey:(NSSet *)objects if (IsInstanceMethod && ReturnTypeMatchesVoid) { std::string SelectorName = (Twine("remove") + UpperKey).str(); @@ -7334,16 +7437,16 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("NSSet *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("objects"); - Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } - } + } // - (void)intersectKey:(NSSet *)objects if (IsInstanceMethod && ReturnTypeMatchesVoid) { @@ -7355,26 +7458,26 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("void"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); Builder.AddChunk(CodeCompletionString::CK_LeftParen); Builder.AddTextChunk("NSSet *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Builder.AddTextChunk("objects"); - Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, + Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, CXCursor_ObjCInstanceMethodDecl)); } - } - + } + // Key-Value Observing // + (NSSet *)keyPathsForValuesAffectingKey - if (!IsInstanceMethod && - (ReturnType.isNull() || + if (!IsInstanceMethod && + (ReturnType.isNull() || (ReturnType->isObjCObjectPointerType() && ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() ->getName() == "NSSet"))) { - std::string SelectorName + std::string SelectorName = (Twine("keyPathsForValuesAffecting") + UpperKey).str(); IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) @@ -7384,9 +7487,9 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("NSSet<NSString *> *"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); - Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, + Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, CXCursor_ObjCClassMethodDecl)); } } @@ -7394,9 +7497,9 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, // + (BOOL)automaticallyNotifiesObserversForKey if (!IsInstanceMethod && (ReturnType.isNull() || - ReturnType->isIntegerType() || + ReturnType->isIntegerType() || ReturnType->isBooleanType())) { - std::string SelectorName + std::string SelectorName = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) @@ -7406,9 +7509,9 @@ static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, Builder.AddTextChunk("BOOL"); Builder.AddChunk(CodeCompletionString::CK_RightParen); } - + Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); - Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, + Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, CXCursor_ObjCClassMethodDecl)); } } @@ -7422,7 +7525,7 @@ void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, Decl *IDecl = nullptr; if (CurContext->isObjCContainer()) { ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); - IDecl = cast<Decl>(OCD); + IDecl = OCD; } // Determine where we should start searching for methods. ObjCContainerDecl *SearchDecl = nullptr; @@ -7431,7 +7534,7 @@ void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { SearchDecl = Impl->getClassInterface(); IsInImplementation = true; - } else if (ObjCCategoryImplDecl *CatImpl + } else if (ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D)) { SearchDecl = CatImpl->getCategoryDecl(); IsInImplementation = true; @@ -7445,17 +7548,17 @@ void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, } if (!SearchDecl) { - HandleCodeCompleteResults(this, CodeCompleter, + HandleCodeCompleteResults(this, CodeCompleter, CodeCompletionContext::CCC_Other, nullptr, 0); return; } - + // Find all of the methods that we could declare/implement here. KnownMethodsMap KnownMethods; - FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, + FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType, KnownMethods); - + // Add declarations or definitions for each of the known methods. typedef CodeCompletionResult Result; ResultBuilder Results(*this, CodeCompleter->getAllocator(), @@ -7463,7 +7566,7 @@ void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, CodeCompletionContext::CCC_Other); Results.EnterNewScope(); PrintingPolicy Policy = getCompletionPrintingPolicy(*this); - for (KnownMethodsMap::iterator M = KnownMethods.begin(), + for (KnownMethodsMap::iterator M = KnownMethods.begin(), MEnd = KnownMethods.end(); M != MEnd; ++M) { ObjCMethodDecl *Method = M->second.getPointer(); @@ -7494,7 +7597,7 @@ void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, // Add parameters to the pattern. unsigned I = 0; - for (ObjCMethodDecl::param_iterator P = Method->param_begin(), + for (ObjCMethodDecl::param_iterator P = Method->param_begin(), PEnd = Method->param_end(); P != PEnd; (void)++P, ++I) { // Add the part of the selector name. @@ -7520,16 +7623,16 @@ void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, (*P)->getObjCDeclQualifier(), Context, Policy, Builder); - + if (IdentifierInfo *Id = (*P)->getIdentifier()) - Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName())); + Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName())); } if (Method->isVariadic()) { if (Method->param_size() > 0) Builder.AddChunk(CodeCompletionString::CK_Comma); Builder.AddTextChunk("..."); - } + } if (IsInImplementation && Results.includeCodePatterns()) { // We will be defining the method here, so add a compound statement. @@ -7544,7 +7647,7 @@ void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, Builder.AddChunk(CodeCompletionString::CK_SemiColon); } else Builder.AddPlaceholderChunk("statements"); - + Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); Builder.AddChunk(CodeCompletionString::CK_RightBrace); } @@ -7552,28 +7655,28 @@ void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, unsigned Priority = CCP_CodePattern; if (!M->second.getInt()) Priority += CCD_InBaseClass; - + Results.AddResult(Result(Builder.TakeString(), Method, Priority)); } - // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of + // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of // the properties in this class and its categories. if (Context.getLangOpts().ObjC2) { SmallVector<ObjCContainerDecl *, 4> Containers; Containers.push_back(SearchDecl); - + VisitedSelectorSet KnownSelectors; - for (KnownMethodsMap::iterator M = KnownMethods.begin(), + for (KnownMethodsMap::iterator M = KnownMethods.begin(), MEnd = KnownMethods.end(); M != MEnd; ++M) KnownSelectors.insert(M->first); - + ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); if (!IFace) if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) IFace = Category->getClassInterface(); - + if (IFace) for (auto *Cat : IFace->visible_categories()) Containers.push_back(Cat); @@ -7585,15 +7688,14 @@ void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, KnownSelectors, Results); } } - + Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } -void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, +void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy, @@ -7616,21 +7718,21 @@ void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_Other); - + if (ReturnTy) Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); - Results.EnterNewScope(); + Results.EnterNewScope(); for (GlobalMethodPool::iterator M = MethodPool.begin(), MEnd = MethodPool.end(); M != MEnd; ++M) { for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first : &M->second.second; - MethList && MethList->getMethod(); + MethList && MethList->getMethod(); MethList = MethList->getNext()) { if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) continue; - + if (AtParameterName) { // Suggest parameter names we've seen before. unsigned NumSelIdents = SelIdents.size(); @@ -7646,7 +7748,7 @@ void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, Results.AddResult(Builder.TakeString()); } } - + continue; } @@ -7658,7 +7760,7 @@ void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, Results.MaybeAddResult(R, CurContext); } } - + Results.ExitScope(); if (!AtParameterName && !SelIdents.empty() && @@ -7677,9 +7779,8 @@ void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, } } - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, - Results.data(),Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompletePreprocessorDirective(bool InConditional) { @@ -7687,7 +7788,7 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_PreprocessorDirective); Results.EnterNewScope(); - + // #if <condition> CodeCompletionBuilder Builder(Results.getAllocator(), Results.getCodeCompletionTUInfo()); @@ -7695,13 +7796,13 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("condition"); Results.AddResult(Builder.TakeString()); - + // #ifdef <macro> Builder.AddTypedTextChunk("ifdef"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("macro"); Results.AddResult(Builder.TakeString()); - + // #ifndef <macro> Builder.AddTypedTextChunk("ifndef"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -7723,7 +7824,7 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { Builder.AddTypedTextChunk("endif"); Results.AddResult(Builder.TakeString()); } - + // #include "header" Builder.AddTypedTextChunk("include"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -7739,13 +7840,13 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { Builder.AddPlaceholderChunk("header"); Builder.AddTextChunk(">"); Results.AddResult(Builder.TakeString()); - + // #define <macro> Builder.AddTypedTextChunk("define"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("macro"); Results.AddResult(Builder.TakeString()); - + // #define <macro>(<args>) Builder.AddTypedTextChunk("define"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -7754,7 +7855,7 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { Builder.AddPlaceholderChunk("args"); Builder.AddChunk(CodeCompletionString::CK_RightParen); Results.AddResult(Builder.TakeString()); - + // #undef <macro> Builder.AddTypedTextChunk("undef"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -7766,7 +7867,7 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); Builder.AddPlaceholderChunk("number"); Results.AddResult(Builder.TakeString()); - + // #line <number> "filename" Builder.AddTypedTextChunk("line"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -7776,7 +7877,7 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { Builder.AddPlaceholderChunk("filename"); Builder.AddTextChunk("\""); Results.AddResult(Builder.TakeString()); - + // #error <message> Builder.AddTypedTextChunk("error"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -7797,7 +7898,7 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { Builder.AddPlaceholderChunk("header"); Builder.AddTextChunk("\""); Results.AddResult(Builder.TakeString()); - + // #import <header> Builder.AddTypedTextChunk("import"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -7806,7 +7907,7 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { Builder.AddTextChunk(">"); Results.AddResult(Builder.TakeString()); } - + // #include_next "header" Builder.AddTypedTextChunk("include_next"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -7814,7 +7915,7 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { Builder.AddPlaceholderChunk("header"); Builder.AddTextChunk("\""); Results.AddResult(Builder.TakeString()); - + // #include_next <header> Builder.AddTypedTextChunk("include_next"); Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); @@ -7835,15 +7936,14 @@ void Sema::CodeCompletePreprocessorDirective(bool InConditional) { // FIXME: we don't support #assert or #unassert, so don't suggest them. Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_PreprocessorDirective, + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), Results.data(), Results.size()); } void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { CodeCompleteOrdinaryName(S, - S->getFnParent()? Sema::PCC_RecoveryInFunction + S->getFnParent()? Sema::PCC_RecoveryInFunction : Sema::PCC_Namespace); } @@ -7853,11 +7953,11 @@ void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { IsDefinition? CodeCompletionContext::CCC_MacroName : CodeCompletionContext::CCC_MacroNameUse); if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { - // Add just the names of macros, not their arguments. + // Add just the names of macros, not their arguments. CodeCompletionBuilder Builder(Results.getAllocator(), Results.getCodeCompletionTUInfo()); Results.EnterNewScope(); - for (Preprocessor::macro_iterator M = PP.macro_begin(), + for (Preprocessor::macro_iterator M = PP.macro_begin(), MEnd = PP.macro_end(); M != MEnd; ++M) { Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( @@ -7870,19 +7970,19 @@ void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { } else if (IsDefinition) { // FIXME: Can we detect when the user just wrote an include guard above? } - + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), - Results.data(), Results.size()); + Results.data(), Results.size()); } void Sema::CodeCompletePreprocessorExpression() { ResultBuilder Results(*this, CodeCompleter->getAllocator(), CodeCompleter->getCodeCompletionTUInfo(), CodeCompletionContext::CCC_PreprocessorExpression); - + if (!CodeCompleter || CodeCompleter->includeMacros()) AddMacroResults(PP, Results, true); - + // defined (<macro>) Results.EnterNewScope(); CodeCompletionBuilder Builder(Results.getAllocator(), @@ -7894,10 +7994,9 @@ void Sema::CodeCompletePreprocessorExpression() { Builder.AddChunk(CodeCompletionString::CK_RightParen); Results.AddResult(Builder.TakeString()); Results.ExitScope(); - - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_PreprocessorExpression, - Results.data(), Results.size()); + + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, @@ -7906,7 +8005,7 @@ void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, unsigned Argument) { // FIXME: In the future, we could provide "overload" results, much like we // do for function calls. - + // Now just ignore this. There will be another code-completion callback // for the expanded tokens. } @@ -7929,9 +8028,8 @@ void Sema::CodeCompleteAvailabilityPlatformName() { Twine(Platform) + "ApplicationExtension"))); } Results.ExitScope(); - HandleCodeCompleteResults(this, CodeCompleter, - CodeCompletionContext::CCC_Other, Results.data(), - Results.size()); + HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), + Results.data(), Results.size()); } void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, @@ -7940,16 +8038,17 @@ void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, ResultBuilder Builder(*this, Allocator, CCTUInfo, CodeCompletionContext::CCC_Recovery); if (!CodeCompleter || CodeCompleter->includeGlobals()) { - CodeCompletionDeclConsumer Consumer(Builder, + CodeCompletionDeclConsumer Consumer(Builder, Context.getTranslationUnitDecl()); - LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, - Consumer); + LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, + Consumer, + !CodeCompleter || CodeCompleter->loadExternal()); } - + if (!CodeCompleter || CodeCompleter->includeMacros()) AddMacroResults(PP, Builder, true); - + Results.clear(); - Results.insert(Results.end(), + Results.insert(Results.end(), Builder.data(), Builder.data() + Builder.size()); } |