Index: include/clang/Basic/DiagnosticSemaKinds.td =================================================================== --- include/clang/Basic/DiagnosticSemaKinds.td +++ include/clang/Basic/DiagnosticSemaKinds.td @@ -5712,6 +5712,8 @@ "member reference type %0 is not a pointer">; def err_typecheck_member_reference_suggestion : Error< "member reference type %0 is %select{a|not a}1 pointer; did you mean to use '%select{->|.}1'?">; +def note_typecheck_member_reference_full_suggestion : Note< + "member reference type %0 may %select{|not}1 be pointer; did you mean to use '%select{->|.}1'?">; def note_typecheck_member_reference_suggestion : Note< "did you mean to use '.' instead?">; def note_member_reference_arrow_from_operator_arrow : Note< Index: include/clang/Sema/CodeCompleteConsumer.h =================================================================== --- include/clang/Sema/CodeCompleteConsumer.h +++ include/clang/Sema/CodeCompleteConsumer.h @@ -782,6 +782,32 @@ /// \brief The availability of this result. CXAvailabilityKind Availability = CXAvailability_Available; + /// \brief FixIts that *must* be applied before inserting the text for the + /// corresponding completion item. + /// + /// Completion items with non-empty fixits will not be returned by default, + /// they should be explicitly requested by setting + /// CompletionOptions::IncludeFixIts. For the editors to be able to + /// compute position of the cursor for the completion item itself, the + /// following conditions are guaranteed to hold for RemoveRange of the stored + /// fixits: + /// - Ranges in the fixits are guaranteed to never contain the completion + /// point (or identifier under completion point, if any) inside them, except + /// at the start or at the end of the range. + /// - If a fixit range starts or ends with completion point (or starts or + /// ends after the identifier under completion point), it will contain at + /// least one character. It allows to unambiguously recompute completion + /// point after applying the fixit. + /// The intuition is that provided fixits change code around the identifier we + /// complete, but are not allowed to touch the identifier itself or the + /// completion point. One example of completion items with corrections are the + /// ones replacing '.' with '->' and vice versa: + /// std::unique_ptr> vec_ptr; + /// vec_ptr.^ // completion returns an item 'push_back', replacing '.' + /// with '->' vec_ptr->^ // completion returns an item 'release', + /// replacing '->' with '.' + std::vector FixIts; + /// \brief Whether this result is hidden by another name. bool Hidden : 1; @@ -806,15 +832,16 @@ NestedNameSpecifier *Qualifier = nullptr; /// \brief Build a result that refers to a declaration. - CodeCompletionResult(const NamedDecl *Declaration, - unsigned Priority, + CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority, NestedNameSpecifier *Qualifier = nullptr, bool QualifierIsInformative = false, - bool Accessible = true) + bool Accessible = true, + std::vector FixIts = std::vector()) : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration), Hidden(false), QualifierIsInformative(QualifierIsInformative), StartsNestedNameSpecifier(false), AllParametersAreInformative(false), - DeclaringEntity(false), Qualifier(Qualifier) { + DeclaringEntity(false), Qualifier(Qualifier), + FixIts(std::move(FixIts)) { computeCursorKindAndAvailability(Accessible); } @@ -1026,6 +1053,10 @@ return CodeCompleteOpts.IncludeBriefComments; } + /// \brief Whether to include completion items with small fix-its, e.g. change + /// '.' to '->' on member access, etc. + bool includeFixIts() const { return CodeCompleteOpts.IncludeFixIts; } + /// \brief Hint whether to load data from the external AST in order to provide /// full results. If false, declarations from the preamble may be omitted. bool loadExternal() const { Index: include/clang/Sema/CodeCompleteOptions.h =================================================================== --- include/clang/Sema/CodeCompleteOptions.h +++ include/clang/Sema/CodeCompleteOptions.h @@ -39,10 +39,14 @@ /// If false, namespace-level declarations from the preamble may be omitted. unsigned LoadExternal : 1; + /// Show also results after corrections (small fix-its), e.g. change '.' to + /// '->' on member access, etc. + unsigned IncludeFixIts : 1; + CodeCompleteOptions() : IncludeMacros(0), IncludeCodePatterns(0), IncludeGlobals(1), IncludeNamespaceLevelDecls(1), IncludeBriefComments(0), - LoadExternal(1) {} + LoadExternal(1), IncludeFixIts(0) {} }; } // namespace clang Index: include/clang/Sema/Sema.h =================================================================== --- include/clang/Sema/Sema.h +++ include/clang/Sema/Sema.h @@ -10229,7 +10229,7 @@ struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); - void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, + void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); Index: lib/Frontend/ASTUnit.cpp =================================================================== --- lib/Frontend/ASTUnit.cpp +++ lib/Frontend/ASTUnit.cpp @@ -2111,6 +2111,7 @@ CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty(); CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments; CodeCompleteOpts.LoadExternal = Consumer.loadExternal(); + CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts(); assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion); Index: lib/Parse/ParseExpr.cpp =================================================================== --- lib/Parse/ParseExpr.cpp +++ lib/Parse/ParseExpr.cpp @@ -1687,8 +1687,10 @@ CXXScopeSpec SS; ParsedType ObjectType; bool MayBePseudoDestructor = false; + Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr; + if (getLangOpts().CPlusPlus && !LHS.isInvalid()) { - Expr *Base = LHS.get(); + Expr *Base = OrigLHS; const Type* BaseType = Base->getType().getTypePtrOrNull(); if (BaseType && Tok.is(tok::l_paren) && (BaseType->isFunctionType() || @@ -1713,11 +1715,25 @@ } if (Tok.is(tok::code_completion)) { + tok::TokenKind CorrectedOpKind = + OpKind == tok::arrow ? tok::period : tok::arrow; + ExprResult CorrectedLHS(/*IsInvalid=*/true); + if (getLangOpts().CPlusPlus && OrigLHS) { + const bool DiagsAreSuppressed = Diags.getSuppressAllDiagnostics(); + Diags.setSuppressAllDiagnostics(true); + CorrectedLHS = Actions.ActOnStartCXXMemberReference( + getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType, + MayBePseudoDestructor); + Diags.setSuppressAllDiagnostics(DiagsAreSuppressed); + } + + Expr *Base = LHS.get(); + Expr *CorrectedBase = CorrectedLHS.get(); + // Code completion for a member access expression. - if (Expr *Base = LHS.get()) - Actions.CodeCompleteMemberReferenceExpr( - getCurScope(), Base, OpLoc, OpKind == tok::arrow, - ExprStatementTokLoc == Base->getLocStart()); + Actions.CodeCompleteMemberReferenceExpr( + getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow, + Base && ExprStatementTokLoc == Base->getLocStart()); cutOffParsing(); return ExprError(); Index: lib/Sema/SemaCodeComplete.cpp =================================================================== --- lib/Sema/SemaCodeComplete.cpp +++ lib/Sema/SemaCodeComplete.cpp @@ -1291,10 +1291,13 @@ class CodeCompletionDeclConsumer : public VisibleDeclConsumer { ResultBuilder &Results; DeclContext *CurContext; + std::vector FixIts; public: - CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext) - : Results(Results), CurContext(CurContext) { } + CodeCompletionDeclConsumer( + ResultBuilder &Results, DeclContext *CurContext, + std::vector FixIts = std::vector()) + : Results(Results), CurContext(CurContext), FixIts(std::move(FixIts)) {} void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass) override { @@ -1303,7 +1306,7 @@ Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx); ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr, - false, Accessible); + false, Accessible, FixIts); Results.AddResult(Result, CurContext, Hiding, InBaseClass); } @@ -3947,14 +3950,15 @@ static void AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results, Scope *S, QualType BaseType, - RecordDecl *RD) { + RecordDecl *RD, + std::vector &&FixIts) { // 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); + CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext, std::move(FixIts)); SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer, SemaRef.CodeCompleter->includeGlobals(), /*IncludeDependentBases=*/true, @@ -3981,107 +3985,138 @@ } 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()) - BaseType = Ptr->getPointeeType(); - else if (BaseType->isObjCObjectPointerType()) - /*Do nothing*/ ; - else - return; + if (const PointerType *Ptr = ConvertedBaseType->getAs()) + 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()) { - AddRecordMembersCompletionResults(*this, Results, S, BaseType, - Record->getDecl()); - } else if (const auto *TST = BaseType->getAs()) { - TemplateName TN = TST->getTemplateName(); - if (const auto *TD = - dyn_cast_or_null(TN.getAsTemplateDecl())) { - CXXRecordDecl *RD = TD->getTemplatedDecl(); - AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD); - } - } else if (const auto *ICNT = BaseType->getAs()) { - 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()->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()) - Class = ObjCPtr->getInterfaceDecl(); - else - Class = BaseType->getAs()->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()); + + auto DoCompletion = [&](Expr *Base, bool IsArrow, std::vector &&FixIts) -> 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()) + BaseType = Ptr->getPointeeType(); + else if (BaseType->isObjCObjectPointerType()) + /*Do nothing*/; + else + return false; + } + + if (const RecordType *Record = BaseType->getAs()) { + AddRecordMembersCompletionResults(*this, Results, S, BaseType, + Record->getDecl(), std::move(FixIts)); + } else if (const auto *TST = + BaseType->getAs()) { + TemplateName TN = TST->getTemplateName(); + if (const auto *TD = + dyn_cast_or_null(TN.getAsTemplateDecl())) { + CXXRecordDecl *RD = TD->getTemplatedDecl(); + AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, std::move(FixIts)); + } + } else if (const auto *ICNT = BaseType->getAs()) { + if (auto *RD = ICNT->getDecl()) + AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, std::move(FixIts)); + } 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()->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()) + Class = ObjCPtr->getInterfaceDecl(); + else + Class = BaseType->getAs()->getInterface(); + + // Add all ivars from this class and its superclasses. + if (Class) { + CodeCompletionDeclConsumer Consumer(Results, CurContext, std::move(FixIts)); + 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 = false; + + if (CodeCompleter->includeFixIts()) { + const char *Corr = IsArrow ? "." : "->"; + std::vector FixIts {FixItHint::CreateReplacement(OpLoc, Corr)}; + //FIXME: Add assert to check FixIt range requirements. + + CompletionSucceded = DoCompletion(OtherOpBase, !IsArrow, std::move(FixIts)); } - - // FIXME: How do we cope with isa? - + + CompletionSucceded |= DoCompletion(Base, IsArrow, std::vector()); + 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, Index: test/SemaCXX/member-expr.cpp =================================================================== --- test/SemaCXX/member-expr.cpp +++ test/SemaCXX/member-expr.cpp @@ -188,6 +188,11 @@ return c->a; // expected-error {{member reference type 'PR15045::Cl0' is not a pointer; did you mean to use '.'?}} } + int g() { + Cl0* c; + return c.a; // expected-error {{member reference type 'PR15045::Cl0 *' is a pointer; did you mean to use '->'?}} + } + struct bar { void func(); // expected-note {{'func' declared here}} };