#include "clang/AST/ASTConcept.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprConcepts.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/QualTypeNames.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Type.h"
#include "clang/Basic/AttributeCommonInfo.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/CodeCompleteConsumer.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Designator.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Overload.h"
#include "clang/Sema/ParsedAttr.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <list>
#include <map>
#include <string>
#include <vector>
using namespace clang;
using namespace sema;
namespace {
class ResultBuilder {
public:
typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
typedef CodeCompletionResult Result;
private:
std::vector<Result> Results;
llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound;
typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
class ShadowMapEntry {
typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
unsigned SingleDeclIndex;
public:
ShadowMapEntry() : SingleDeclIndex(0) {}
ShadowMapEntry(const ShadowMapEntry &) = delete;
ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
SingleDeclIndex = Move.SingleDeclIndex;
DeclOrVector = Move.DeclOrVector;
Move.DeclOrVector = nullptr;
return *this;
}
void Add(const NamedDecl *ND, unsigned Index) {
if (DeclOrVector.isNull()) {
DeclOrVector = ND;
SingleDeclIndex = Index;
return;
}
if (const NamedDecl *PrevND =
DeclOrVector.dyn_cast<const NamedDecl *>()) {
DeclIndexPairVector *Vec = new DeclIndexPairVector;
Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
DeclOrVector = Vec;
}
DeclOrVector.get<DeclIndexPairVector *>()->push_back(
DeclIndexPair(ND, Index));
}
~ShadowMapEntry() {
if (DeclIndexPairVector *Vec =
DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
delete Vec;
DeclOrVector = ((NamedDecl *)nullptr);
}
}
class iterator;
iterator begin() const;
iterator end() const;
};
typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
Sema &SemaRef;
CodeCompletionAllocator &Allocator;
CodeCompletionTUInfo &CCTUInfo;
LookupFilter Filter;
bool AllowNestedNameSpecifiers;
CanQualType PreferredType;
std::list<ShadowMap> ShadowMaps;
llvm::DenseMap<std::pair<DeclContext *, uintptr_t>, ShadowMapEntry>
OverloadMap;
Qualifiers ObjectTypeQualifiers;
ExprValueKind ObjectKind;
bool HasObjectTypeQualifiers;
Selector PreferredSelector;
CodeCompletionContext CompletionContext;
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), CompletionContext(CompletionContext),
ObjCImplementation(nullptr) {
switch (CompletionContext.getKind()) {
case CodeCompletionContext::CCC_Expression:
case CodeCompletionContext::CCC_ObjCMessageReceiver:
case CodeCompletionContext::CCC_ParenthesizedExpression:
case CodeCompletionContext::CCC_Statement:
case CodeCompletionContext::CCC_Recovery:
if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
if (Method->isInstanceMethod())
if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
ObjCImplementation = Interface->getImplementation();
break;
default:
break;
}
}
unsigned getBasePriority(const NamedDecl *D);
bool includeCodePatterns() const {
return SemaRef.CodeCompleter &&
SemaRef.CodeCompleter->includeCodePatterns();
}
void setFilter(LookupFilter Filter) { this->Filter = Filter; }
Result *data() { return Results.empty() ? nullptr : &Results.front(); }
unsigned size() const { return Results.size(); }
bool empty() const { return Results.empty(); }
void setPreferredType(QualType T) {
PreferredType = SemaRef.Context.getCanonicalType(T);
}
void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
ObjectTypeQualifiers = Quals;
ObjectKind = Kind;
HasObjectTypeQualifiers = true;
}
void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
const CodeCompletionContext &getCompletionContext() const {
return CompletionContext;
}
void allowNestedNameSpecifiers(bool Allow = true) {
AllowNestedNameSpecifiers = Allow;
}
Sema &getSema() const { return SemaRef; }
CodeCompletionAllocator &getAllocator() const { return Allocator; }
CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
bool isInterestingDecl(const NamedDecl *ND,
bool &AsNestedNameSpecifier) const;
bool CheckHiddenResult(Result &R, DeclContext *CurContext,
const NamedDecl *Hiding);
void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
bool InBaseClass);
void AddResult(Result R);
void EnterNewScope();
void ExitScope();
void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
void addVisitedContext(DeclContext *Ctx) {
CompletionContext.addVisitedContext(Ctx);
}
bool IsOrdinaryName(const NamedDecl *ND) const;
bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
bool IsIntegralConstantValue(const NamedDecl *ND) const;
bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
bool IsNestedNameSpecifier(const NamedDecl *ND) const;
bool IsEnum(const NamedDecl *ND) const;
bool IsClassOrStruct(const NamedDecl *ND) const;
bool IsUnion(const NamedDecl *ND) const;
bool IsNamespace(const NamedDecl *ND) const;
bool IsNamespaceOrAlias(const NamedDecl *ND) const;
bool IsType(const NamedDecl *ND) const;
bool IsMember(const NamedDecl *ND) const;
bool IsObjCIvar(const NamedDecl *ND) const;
bool IsObjCMessageReceiver(const NamedDecl *ND) const;
bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
bool IsObjCCollection(const NamedDecl *ND) const;
bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
};
}
void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) {
if (!Enabled)
return;
if (isa<BlockDecl>(S.CurContext)) {
if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
ComputeType = nullptr;
Type = BSI->ReturnType;
ExpectedLoc = Tok;
}
} else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
ComputeType = nullptr;
Type = Function->getReturnType();
ExpectedLoc = Tok;
} else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
ComputeType = nullptr;
Type = Method->getReturnType();
ExpectedLoc = Tok;
}
}
void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) {
if (!Enabled)
return;
auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
ComputeType = nullptr;
Type = VD ? VD->getType() : QualType();
ExpectedLoc = Tok;
}
static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
QualType BaseType,
const Designation &D) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = getDesignatedType(BaseType, D);
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterFunctionArgument(
SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
if (!Enabled)
return;
this->ComputeType = ComputeType;
Type = QualType();
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok,
SourceLocation LParLoc) {
if (!Enabled)
return;
if (ExpectedLoc == LParLoc)
ExpectedLoc = Tok;
}
static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS,
tok::TokenKind Op) {
if (!LHS)
return QualType();
QualType LHSType = LHS->getType();
if (LHSType->isPointerType()) {
if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
return S.getASTContext().getPointerDiffType();
if (Op == tok::minus)
return LHSType;
}
switch (Op) {
case tok::comma:
return QualType();
case tok::plus:
case tok::plusequal:
case tok::minus:
case tok::minusequal:
case tok::percent:
case tok::percentequal:
case tok::slash:
case tok::slashequal:
case tok::star:
case tok::starequal:
case tok::equal:
case tok::equalequal:
case tok::exclaimequal:
case tok::less:
case tok::lessequal:
case tok::greater:
case tok::greaterequal:
case tok::spaceship:
return LHS->getType();
case tok::greatergreater:
case tok::greatergreaterequal:
case tok::lessless:
case tok::lesslessequal:
if (LHSType->isIntegralOrEnumerationType())
return S.getASTContext().IntTy;
return QualType();
case tok::ampamp:
case tok::pipepipe:
case tok::caretcaret:
return S.getASTContext().BoolTy;
case tok::pipe:
case tok::pipeequal:
case tok::caret:
case tok::caretequal:
case tok::amp:
case tok::ampequal:
if (LHSType->isIntegralOrEnumerationType())
return LHSType;
return QualType();
case tok::periodstar:
case tok::arrowstar:
return QualType();
default:
return QualType();
}
}
static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType,
tok::TokenKind Op) {
switch (Op) {
case tok::exclaim:
return S.getASTContext().BoolTy;
case tok::amp:
if (!ContextType.isNull() && ContextType->isPointerType())
return ContextType->getPointeeType();
return QualType();
case tok::star:
if (ContextType.isNull())
return QualType();
return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
case tok::plus:
case tok::minus:
case tok::tilde:
case tok::minusminus:
case tok::plusplus:
if (ContextType.isNull())
return S.getASTContext().IntTy;
return ContextType;
case tok::kw___real:
case tok::kw___imag:
return QualType();
default:
assert(false && "unhandled unary op");
return QualType();
}
}
void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS,
tok::TokenKind Op) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok,
Expr *Base) {
if (!Enabled || !Base)
return;
if (ExpectedLoc != Base->getBeginLoc())
return;
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok,
tok::TokenKind OpKind,
SourceLocation OpLoc) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok,
Expr *LHS) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = S.getASTContext().IntTy;
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok,
QualType CastType) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = S.getASTContext().BoolTy;
ExpectedLoc = Tok;
}
class ResultBuilder::ShadowMapEntry::iterator {
llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
unsigned SingleDeclIndex;
public:
typedef DeclIndexPair value_type;
typedef value_type reference;
typedef std::ptrdiff_t difference_type;
typedef std::input_iterator_tag iterator_category;
class pointer {
DeclIndexPair Value;
public:
pointer(const DeclIndexPair &Value) : Value(Value) {}
const DeclIndexPair *operator->() const { return &Value; }
};
iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
iterator(const NamedDecl *SingleDecl, unsigned Index)
: DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
iterator(const DeclIndexPair *Iterator)
: DeclOrIterator(Iterator), SingleDeclIndex(0) {}
iterator &operator++() {
if (DeclOrIterator.is<const NamedDecl *>()) {
DeclOrIterator = (NamedDecl *)nullptr;
SingleDeclIndex = 0;
return *this;
}
const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
++I;
DeclOrIterator = I;
return *this;
}
reference operator*() const {
if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
return reference(ND, SingleDeclIndex);
return *DeclOrIterator.get<const DeclIndexPair *>();
}
pointer operator->() const { return pointer(**this); }
friend bool operator==(const iterator &X, const iterator &Y) {
return X.DeclOrIterator.getOpaqueValue() ==
Y.DeclOrIterator.getOpaqueValue() &&
X.SingleDeclIndex == Y.SingleDeclIndex;
}
friend bool operator!=(const iterator &X, const iterator &Y) {
return !(X == Y);
}
};
ResultBuilder::ShadowMapEntry::iterator
ResultBuilder::ShadowMapEntry::begin() const {
if (DeclOrVector.isNull())
return iterator();
if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
return iterator(ND, SingleDeclIndex);
return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
}
ResultBuilder::ShadowMapEntry::iterator
ResultBuilder::ShadowMapEntry::end() const {
if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
return iterator();
return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
}
static NestedNameSpecifier *
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);
}
NestedNameSpecifier *Result = nullptr;
while (!TargetParents.empty()) {
const DeclContext *Parent = TargetParents.pop_back_val();
if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
if (!Namespace->getIdentifier())
continue;
Result = NestedNameSpecifier::Create(Context, Result, Namespace);
} else if (const auto *TD = dyn_cast<TagDecl>(Parent))
Result = NestedNameSpecifier::Create(
Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
}
return Result;
}
static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
return true;
if (Status == ReservedIdentifierStatus::StartsWithDoubleUnderscore &&
SemaRef.SourceMgr.isInSystemHeader(
SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
return true;
return false;
}
bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
bool &AsNestedNameSpecifier) const {
AsNestedNameSpecifier = false;
auto *Named = ND;
ND = ND->getUnderlyingDecl();
if (!ND->getDeclName())
return false;
if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
return false;
if (isa<ClassTemplateSpecializationDecl>(ND) ||
isa<ClassTemplatePartialSpecializationDecl>(ND))
return false;
if (isa<UsingDecl>(ND))
return false;
if (shouldIgnoreDueToReservedName(ND, SemaRef))
return false;
if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
(isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
AsNestedNameSpecifier = true;
if (Filter && !(this->*Filter)(Named)) {
if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
IsNestedNameSpecifier(ND) &&
(Filter != &ResultBuilder::IsMember ||
(isa<CXXRecordDecl>(ND) &&
cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
AsNestedNameSpecifier = true;
return true;
}
return false;
}
return true;
}
bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
const NamedDecl *Hiding) {
if (!SemaRef.getLangOpts().CPlusPlus)
return true;
const DeclContext *HiddenCtx =
R.Declaration->getDeclContext()->getRedeclContext();
if (HiddenCtx->isFunctionOrMethod())
return true;
if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
return true;
R.Hidden = true;
R.QualifierIsInformative = false;
if (!R.Qualifier)
R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
R.Declaration->getDeclContext());
return false;
}
SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
switch (T->getTypeClass()) {
case Type::Builtin:
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;
}
}
QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
ND = ND->getUnderlyingDecl();
if (const auto *Type = dyn_cast<TypeDecl>(ND))
return C.getTypeDeclType(Type);
if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
return C.getObjCInterfaceType(Iface);
QualType T;
if (const FunctionDecl *Function = ND->getAsFunction())
T = Function->getCallResultType();
else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
T = Method->getSendResultType();
else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
T = Property->getType();
else if (const auto *Value = dyn_cast<ValueDecl>(ND))
T = Value->getType();
if (T.isNull())
return QualType();
do {
if (const auto *Ref = T->getAs<ReferenceType>()) {
T = Ref->getPointeeType();
continue;
}
if (const auto *Pointer = T->getAs<PointerType>()) {
if (Pointer->getPointeeType()->isFunctionType()) {
T = Pointer->getPointeeType();
continue;
}
break;
}
if (const auto *Block = T->getAs<BlockPointerType>()) {
T = Block->getPointeeType();
continue;
}
if (const auto *Function = T->getAs<FunctionType>()) {
T = Function->getReturnType();
continue;
}
break;
} while (true);
return T;
}
unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
if (!ND)
return CCP_Unlikely;
const DeclContext *LexicalDC = ND->getLexicalDeclContext();
if (LexicalDC->isFunctionOrMethod()) {
if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
if (ImplicitParam->getIdentifier() &&
ImplicitParam->getIdentifier()->isStr("_cmd"))
return CCP_ObjC_cmd;
return CCP_LocalDeclaration;
}
const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
if (isa<CXXDestructorDecl>(ND))
return CCP_Unlikely;
auto DeclNameKind = ND->getDeclName().getNameKind();
if (DeclNameKind == DeclarationName::CXXOperatorName ||
DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
DeclNameKind == DeclarationName::CXXConversionFunctionName)
return CCP_Unlikely;
return CCP_MemberDeclaration;
}
if (isa<EnumConstantDecl>(ND))
return CCP_Constant;
if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
!(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
CompletionContext.getKind() ==
CodeCompletionContext::CCC_ObjCMessageReceiver ||
CompletionContext.getKind() ==
CodeCompletionContext::CCC_ParenthesizedExpression))
return CCP_Type;
return CCP_Declaration;
}
void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
if (!PreferredSelector.isNull())
if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
if (PreferredSelector == Method->getSelector())
R.Priority += CCD_SelectorMatch;
if (!PreferredType.isNull()) {
QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
if (!T.isNull()) {
CanQualType TC = SemaRef.Context.getCanonicalType(T);
if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
R.Priority /= CCF_ExactTypeMatch;
else if ((getSimplifiedTypeClass(PreferredType) ==
getSimplifiedTypeClass(TC)) &&
!(PreferredType->isEnumeralType() && TC->isEnumeralType()))
R.Priority /= CCF_SimilarTypeMatch;
}
}
}
static DeclContext::lookup_result getConstructors(ASTContext &Context,
const CXXRecordDecl *Record) {
QualType RecordTy = Context.getTypeDeclType(Record);
DeclarationName ConstructorName =
Context.DeclarationNames.getCXXConstructorName(
Context.getCanonicalType(RecordTy));
return Record->lookup(ConstructorName);
}
void ResultBuilder::MaybeAddConstructorResults(Result R) {
if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
!CompletionContext.wantConstructorResults())
return;
const NamedDecl *D = R.Declaration;
const CXXRecordDecl *Record = nullptr;
if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
Record = ClassTemplate->getTemplatedDecl();
else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
if (isa<ClassTemplateSpecializationDecl>(Record))
return;
} else {
return;
}
Record = Record->getDefinition();
if (!Record)
return;
for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
R.Declaration = Ctor;
R.CursorKind = getCursorKindForDecl(R.Declaration);
Results.push_back(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) {
Results.push_back(R);
return;
}
if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
CodeCompletionResult Result(Using->getTargetDecl(),
getBasePriority(Using->getTargetDecl()),
R.Qualifier, false,
(R.Availability == CXAvailability_Available ||
R.Availability == CXAvailability_Deprecated));
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;
if (isConstructor(R.Declaration))
return;
ShadowMap &SMap = ShadowMaps.back();
ShadowMapEntry::iterator I, IEnd;
ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
if (NamePos != SMap.end()) {
I = NamePos->second.begin();
IEnd = NamePos->second.end();
}
for (; I != IEnd; ++I) {
const NamedDecl *ND = I->first;
unsigned Index = I->second;
if (ND->getCanonicalDecl() == CanonDecl) {
Results[Index].Declaration = R.Declaration;
return;
}
}
std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
--SMEnd;
for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
ShadowMapEntry::iterator I, IEnd;
ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
if (NamePos != SM->end()) {
I = NamePos->second.begin();
IEnd = NamePos->second.end();
}
for (; I != IEnd; ++I) {
if (I->first->hasTagIdentifierNamespace() &&
(IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
continue;
if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
(IDNS & Decl::IDNS_ObjCProtocol)) &&
I->first->getIdentifierNamespace() != IDNS)
continue;
if (CheckHiddenResult(R, CurContext, I->first))
return;
break;
}
}
if (!AllDeclsFound.insert(CanonDecl).second)
return;
if (AsNestedNameSpecifier) {
R.StartsNestedNameSpecifier = true;
R.Priority = CCP_NestedNameSpecifier;
} else
AdjustResultPriorityForDecl(R);
if (R.QualifierIsInformative && !R.Qualifier &&
!R.StartsNestedNameSpecifier) {
const DeclContext *Ctx = R.Declaration->getDeclContext();
if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
R.Qualifier =
NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
R.Qualifier = NestedNameSpecifier::Create(
SemaRef.Context, nullptr, false,
SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
else
R.QualifierIsInformative = false;
}
SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
Results.push_back(R);
if (!AsNestedNameSpecifier)
MaybeAddConstructorResults(R);
}
static void setInBaseClass(ResultBuilder::Result &R) {
R.Priority += CCD_InBaseClass;
R.InBaseClass = true;
}
enum class OverloadCompare { BothViable, Dominates, Dominated };
static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate,
const CXXMethodDecl &Incumbent,
const Qualifiers &ObjectQuals,
ExprValueKind ObjectKind) {
if (Candidate.getDeclContext() != Incumbent.getDeclContext())
return OverloadCompare::BothViable;
if (Candidate.isVariadic() != Incumbent.isVariadic() ||
Candidate.getNumParams() != Incumbent.getNumParams() ||
Candidate.getMinRequiredArguments() !=
Incumbent.getMinRequiredArguments())
return OverloadCompare::BothViable;
for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I)
if (Candidate.parameters()[I]->getType().getCanonicalType() !=
Incumbent.parameters()[I]->getType().getCanonicalType())
return OverloadCompare::BothViable;
if (!llvm::empty(Candidate.specific_attrs<EnableIfAttr>()) ||
!llvm::empty(Incumbent.specific_attrs<EnableIfAttr>()))
return OverloadCompare::BothViable;
RefQualifierKind CandidateRef = Candidate.getRefQualifier();
RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
if (CandidateRef != IncumbentRef) {
if (ObjectKind == clang::VK_XValue)
return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
: OverloadCompare::Dominated;
}
Qualifiers CandidateQual = Candidate.getMethodQualifiers();
Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
if (CandidateSuperset == IncumbentSuperset)
return OverloadCompare::BothViable;
return IncumbentSuperset ? OverloadCompare::Dominates
: OverloadCompare::Dominated;
}
void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
NamedDecl *Hiding, bool InBaseClass = false) {
if (R.Kind != Result::RK_Declaration) {
Results.push_back(R);
return;
}
if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
CodeCompletionResult Result(Using->getTargetDecl(),
getBasePriority(Using->getTargetDecl()),
R.Qualifier, false,
(R.Availability == CXAvailability_Available ||
R.Availability == CXAvailability_Deprecated));
Result.ShadowDecl = Using;
AddResult(Result, CurContext, Hiding);
return;
}
bool AsNestedNameSpecifier = false;
if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
return;
if (isConstructor(R.Declaration))
return;
if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
return;
if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
return;
if (AsNestedNameSpecifier) {
R.StartsNestedNameSpecifier = true;
R.Priority = CCP_NestedNameSpecifier;
} else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
InBaseClass &&
isa<CXXRecordDecl>(
R.Declaration->getDeclContext()->getRedeclContext()))
R.QualifierIsInformative = true;
if (R.QualifierIsInformative && !R.Qualifier &&
!R.StartsNestedNameSpecifier) {
const DeclContext *Ctx = R.Declaration->getDeclContext();
if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
R.Qualifier =
NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
R.Qualifier = NestedNameSpecifier::Create(
SemaRef.Context, nullptr, false,
SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
else
R.QualifierIsInformative = false;
}
if (InBaseClass)
setInBaseClass(R);
AdjustResultPriorityForDecl(R);
if (HasObjectTypeQualifiers)
if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
if (Method->isInstance()) {
Qualifiers MethodQuals = Method->getMethodQualifiers();
if (ObjectTypeQualifiers == MethodQuals)
R.Priority += CCD_ObjectQualifierMatch;
else if (ObjectTypeQualifiers - MethodQuals) {
return;
}
switch (Method->getRefQualifier()) {
case RQ_LValue:
if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
return;
break;
case RQ_RValue:
if (ObjectKind == VK_LValue)
return;
break;
case RQ_None:
break;
}
auto &OverloadSet = OverloadMap[std::make_pair(
CurContext, Method->getDeclName().getAsOpaqueInteger())];
for (const DeclIndexPair Entry : OverloadSet) {
Result &Incumbent = Results[Entry.second];
switch (compareOverloads(*Method,
*cast<CXXMethodDecl>(Incumbent.Declaration),
ObjectTypeQualifiers, ObjectKind)) {
case OverloadCompare::Dominates:
Incumbent = std::move(R);
return;
case OverloadCompare::Dominated:
return;
case OverloadCompare::BothViable:
break;
}
}
OverloadSet.Add(Method, Results.size());
}
Results.push_back(R);
if (!AsNestedNameSpecifier)
MaybeAddConstructorResults(R);
}
void ResultBuilder::AddResult(Result R) {
assert(R.Kind != Result::RK_Declaration &&
"Declaration results need more context");
Results.push_back(R);
}
void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
void ResultBuilder::ExitScope() {
ShadowMaps.pop_back();
}
bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
ND = ND->getUnderlyingDecl();
unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
if (SemaRef.getLangOpts().CPlusPlus)
IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
else if (SemaRef.getLangOpts().ObjC) {
if (isa<ObjCIvarDecl>(ND))
return true;
}
return ND->getIdentifierNamespace() & IDNS;
}
bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
ND = ND->getUnderlyingDecl();
if (isa<TypeDecl>(ND))
return false;
if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
if (!ID->getDefinition())
return false;
}
unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
if (SemaRef.getLangOpts().CPlusPlus)
IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
else if (SemaRef.getLangOpts().ObjC) {
if (isa<ObjCIvarDecl>(ND))
return true;
}
return ND->getIdentifierNamespace() & IDNS;
}
bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
if (!IsOrdinaryNonTypeName(ND))
return false;
if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
if (VD->getType()->isIntegralOrEnumerationType())
return true;
return false;
}
bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
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) && !isa<ObjCPropertyDecl>(ND);
}
bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
ND = ClassTemplate->getTemplatedDecl();
return SemaRef.isAcceptableNestedNameSpecifier(ND);
}
bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
return isa<EnumDecl>(ND);
}
bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
ND = ClassTemplate->getTemplatedDecl();
if (const auto *RD = dyn_cast<RecordDecl>(ND))
return RD->getTagKind() == TTK_Class || RD->getTagKind() == TTK_Struct ||
RD->getTagKind() == TTK_Interface;
return false;
}
bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
ND = ClassTemplate->getTemplatedDecl();
if (const auto *RD = dyn_cast<RecordDecl>(ND))
return RD->getTagKind() == TTK_Union;
return false;
}
bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
return isa<NamespaceDecl>(ND);
}
bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
return isa<NamespaceDecl>(ND->getUnderlyingDecl());
}
bool ResultBuilder::IsType(const NamedDecl *ND) const {
ND = ND->getUnderlyingDecl();
return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
}
bool ResultBuilder::IsMember(const NamedDecl *ND) const {
ND = ND->getUnderlyingDecl();
return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
isa<ObjCPropertyDecl>(ND);
}
static bool isObjCReceiverType(ASTContext &C, QualType T) {
T = C.getCanonicalType(T);
switch (T->getTypeClass()) {
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;
return T->isDependentType() || T->isRecordType();
}
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);
}
bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
const NamedDecl *ND) const {
if (IsObjCMessageReceiver(ND))
return true;
const auto *Var = dyn_cast<VarDecl>(ND);
if (!Var)
return false;
return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
}
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() ||
(SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
}
bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
return false;
}
bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
return isa<ObjCIvarDecl>(ND);
}
namespace {
class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
ResultBuilder &Results;
DeclContext *InitialLookupCtx;
CXXRecordDecl *NamingClass;
QualType BaseType;
std::vector<FixItHint> FixIts;
public:
CodeCompletionDeclConsumer(
ResultBuilder &Results, DeclContext *InitialLookupCtx,
QualType BaseType = QualType(),
std::vector<FixItHint> FixIts = std::vector<FixItHint>())
: Results(Results), InitialLookupCtx(InitialLookupCtx),
FixIts(std::move(FixIts)) {
NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
if (BaseType.isNull()) {
auto ThisType = Results.getSema().getCurrentThisType();
if (!ThisType.isNull()) {
assert(ThisType->isPointerType());
BaseType = ThisType->getPointeeType();
if (!NamingClass)
NamingClass = BaseType->getAsCXXRecordDecl();
}
}
this->BaseType = BaseType;
}
void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) override {
ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
false, IsAccessible(ND, Ctx), FixIts);
Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass);
}
void EnteredContext(DeclContext *Ctx) override {
Results.addVisitedContext(Ctx);
}
private:
bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
auto *NamingClass = this->NamingClass;
QualType BaseType = this->BaseType;
if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
if (!NamingClass)
NamingClass = Cls;
if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
!NamingClass->isDerivedFrom(Cls)) {
NamingClass = Cls;
BaseType = QualType();
}
} else {
NamingClass = nullptr;
BaseType = QualType();
}
return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
}
};
}
static void AddTypeSpecifierResults(const LangOptions &LangOpts,
ResultBuilder &Results) {
typedef CodeCompletionResult Result;
Results.AddResult(Result("short", CCP_Type));
Results.AddResult(Result("long", CCP_Type));
Results.AddResult(Result("signed", CCP_Type));
Results.AddResult(Result("unsigned", CCP_Type));
Results.AddResult(Result("void", CCP_Type));
Results.AddResult(Result("char", CCP_Type));
Results.AddResult(Result("int", CCP_Type));
Results.AddResult(Result("float", CCP_Type));
Results.AddResult(Result("double", CCP_Type));
Results.AddResult(Result("enum", CCP_Type));
Results.AddResult(Result("struct", CCP_Type));
Results.AddResult(Result("union", CCP_Type));
Results.AddResult(Result("const", CCP_Type));
Results.AddResult(Result("volatile", CCP_Type));
if (LangOpts.C99) {
Results.AddResult(Result("_Complex", CCP_Type));
Results.AddResult(Result("_Imaginary", CCP_Type));
Results.AddResult(Result("_Bool", CCP_Type));
Results.AddResult(Result("restrict", CCP_Type));
}
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
if (LangOpts.CPlusPlus) {
Results.AddResult(
Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
Results.AddResult(Result("class", CCP_Type));
Results.AddResult(Result("wchar_t", CCP_Type));
Builder.AddTypedTextChunk("typename");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
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");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
}
} else
Results.AddResult(Result("__auto_type", CCP_Type));
if (LangOpts.GNUKeywords) {
Builder.AddTypedTextChunk("typeof");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("expression");
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("typeof");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
}
Results.AddResult(Result("_Nonnull", CCP_Type));
Results.AddResult(Result("_Null_unspecified", CCP_Type));
Results.AddResult(Result("_Nullable", CCP_Type));
}
static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
const LangOptions &LangOpts,
ResultBuilder &Results) {
typedef CodeCompletionResult Result;
Results.AddResult(Result("extern"));
Results.AddResult(Result("static"));
if (LangOpts.CPlusPlus11) {
CodeCompletionAllocator &Allocator = Results.getAllocator();
CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
Builder.AddTypedTextChunk("alignas");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Results.AddResult(Result("constexpr"));
Results.AddResult(Result("thread_local"));
}
}
static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
const LangOptions &LangOpts,
ResultBuilder &Results) {
typedef CodeCompletionResult Result;
switch (CCC) {
case Sema::PCC_Class:
case Sema::PCC_MemberTemplate:
if (LangOpts.CPlusPlus) {
Results.AddResult(Result("explicit"));
Results.AddResult(Result("friend"));
Results.AddResult(Result("mutable"));
Results.AddResult(Result("virtual"));
}
LLVM_FALLTHROUGH;
case Sema::PCC_ObjCInterface:
case Sema::PCC_ObjCImplementation:
case Sema::PCC_Namespace:
case Sema::PCC_Template:
if (LangOpts.CPlusPlus || LangOpts.C99)
Results.AddResult(Result("inline"));
break;
case Sema::PCC_ObjCInstanceVariableList:
case Sema::PCC_Expression:
case Sema::PCC_Statement:
case Sema::PCC_ForInit:
case Sema::PCC_Condition:
case Sema::PCC_RecoveryInFunction:
case Sema::PCC_Type:
case Sema::PCC_ParenthesizedExpression:
case Sema::PCC_LocalDeclarationSpecifiers:
break;
}
}
static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
static void AddObjCVisibilityResults(const LangOptions &LangOpts,
ResultBuilder &Results, bool NeedAt);
static void AddObjCImplementationResults(const LangOptions &LangOpts,
ResultBuilder &Results, bool NeedAt);
static void AddObjCInterfaceResults(const LangOptions &LangOpts,
ResultBuilder &Results, bool NeedAt);
static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
static void AddTypedefResult(ResultBuilder &Results) {
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Builder.AddTypedTextChunk("typedef");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("name");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(CodeCompletionResult(Builder.TakeString()));
}
static void AddUsingAliasResult(CodeCompletionBuilder &Builder,
ResultBuilder &Results) {
Builder.AddTypedTextChunk("using");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("name");
Builder.AddChunk(CodeCompletionString::CK_Equal);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(CodeCompletionResult(Builder.TakeString()));
}
static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
const LangOptions &LangOpts) {
switch (CCC) {
case Sema::PCC_Namespace:
case Sema::PCC_Class:
case Sema::PCC_ObjCInstanceVariableList:
case Sema::PCC_Template:
case Sema::PCC_MemberTemplate:
case Sema::PCC_Statement:
case Sema::PCC_RecoveryInFunction:
case Sema::PCC_Type:
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.ObjC || LangOpts.C99;
}
llvm_unreachable("Invalid ParserCompletionContext!");
}
static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
const Preprocessor &PP) {
PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
Policy.AnonymousTagLocations = false;
Policy.SuppressStrongLifetime = true;
Policy.SuppressUnwrittenScope = true;
Policy.SuppressScope = true;
Policy.CleanUglifiedParameters = true;
return Policy;
}
static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
return getCompletionPrintingPolicy(S.Context, S.PP);
}
static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
const PrintingPolicy &Policy,
CodeCompletionAllocator &Allocator) {
if (!T.getLocalQualifiers()) {
if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
return BT->getNameAsCString(Policy);
if (const TagType *TagT = dyn_cast<TagType>(T))
if (TagDecl *Tag = TagT->getDecl())
if (!Tag->hasNameForLinkage()) {
switch (Tag->getTagKind()) {
case TTK_Struct:
return "struct <anonymous>";
case TTK_Interface:
return "__interface <anonymous>";
case TTK_Class:
return "class <anonymous>";
case TTK_Union:
return "union <anonymous>";
case TTK_Enum:
return "enum <anonymous>";
}
}
}
std::string Result;
T.getAsStringInternal(Result, Policy);
return Allocator.CopyString(Result);
}
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, Policy, Allocator));
Builder.AddTypedTextChunk("this");
Results.AddResult(CodeCompletionResult(Builder.TakeString()));
}
static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
ResultBuilder &Results,
const LangOptions &LangOpts) {
if (!LangOpts.CPlusPlus11)
return;
Builder.AddTypedTextChunk("static_assert");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_Comma);
Builder.AddPlaceholderChunk("message");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(CodeCompletionResult(Builder.TakeString()));
}
static void AddOverrideResults(ResultBuilder &Results,
const CodeCompletionContext &CCContext,
CodeCompletionBuilder &Builder) {
Sema &S = Results.getSema();
const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
if (!CR)
return;
llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
for (auto *Method : CR->methods()) {
if (!Method->isVirtual() || !Method->getIdentifier())
continue;
Overrides[Method->getName()].push_back(Method);
}
for (const auto &Base : CR->bases()) {
const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
if (!BR)
continue;
for (auto *Method : BR->methods()) {
if (!Method->isVirtual() || !Method->getIdentifier())
continue;
const auto it = Overrides.find(Method->getName());
bool IsOverriden = false;
if (it != Overrides.end()) {
for (auto *MD : it->second) {
if (!S.IsOverload(MD, Method, false)) {
IsOverriden = true;
break;
}
}
}
if (!IsOverriden) {
std::string OverrideSignature;
llvm::raw_string_ostream OS(OverrideSignature);
CodeCompletionResult CCR(Method, 0);
PrintingPolicy Policy =
getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor());
auto *CCS = CCR.createCodeCompletionStringForOverride(
S.getPreprocessor(), S.getASTContext(), Builder,
false, CCContext, Policy);
Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
}
}
}
}
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:
if (SemaRef.getLangOpts().CPlusPlus) {
if (Results.includeCodePatterns()) {
Builder.AddTypedTextChunk("namespace");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("identifier");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("declarations");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
}
Builder.AddTypedTextChunk("namespace");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("name");
Builder.AddChunk(CodeCompletionString::CK_Equal);
Builder.AddPlaceholderChunk("namespace");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("using namespace");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("identifier");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("asm");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("string-literal");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
if (Results.includeCodePatterns()) {
Builder.AddTypedTextChunk("template");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("declaration");
Results.AddResult(Result(Builder.TakeString()));
} else {
Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
}
}
if (SemaRef.getLangOpts().ObjC)
AddObjCTopLevelResults(Results, true);
AddTypedefResult(Results);
LLVM_FALLTHROUGH;
case Sema::PCC_Class:
if (SemaRef.getLangOpts().CPlusPlus) {
Builder.AddTypedTextChunk("using");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("qualifier");
Builder.AddTextChunk("::");
Builder.AddPlaceholderChunk("name");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
if (SemaRef.getLangOpts().CPlusPlus11)
AddUsingAliasResult(Builder, Results);
if (SemaRef.CurContext->isDependentContext()) {
Builder.AddTypedTextChunk("using typename");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("qualifier");
Builder.AddTextChunk("::");
Builder.AddPlaceholderChunk("name");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
}
AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
if (CCC == Sema::PCC_Class) {
AddTypedefResult(Results);
bool IsNotInheritanceScope = !S->isClassInheritanceScope();
Builder.AddTypedTextChunk("public");
if (IsNotInheritanceScope && Results.includeCodePatterns())
Builder.AddChunk(CodeCompletionString::CK_Colon);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("protected");
if (IsNotInheritanceScope && Results.includeCodePatterns())
Builder.AddChunk(CodeCompletionString::CK_Colon);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("private");
if (IsNotInheritanceScope && Results.includeCodePatterns())
Builder.AddChunk(CodeCompletionString::CK_Colon);
Results.AddResult(Result(Builder.TakeString()));
AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion,
Builder);
}
}
LLVM_FALLTHROUGH;
case Sema::PCC_Template:
case Sema::PCC_MemberTemplate:
if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
Builder.AddTypedTextChunk("template");
Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
Builder.AddPlaceholderChunk("parameters");
Builder.AddChunk(CodeCompletionString::CK_RightAngle);
Results.AddResult(Result(Builder.TakeString()));
} else {
Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
}
AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
break;
case Sema::PCC_ObjCInterface:
AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
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: {
if (SemaRef.getLangOpts().CPlusPlus11)
AddUsingAliasResult(Builder, Results);
AddTypedefResult(Results);
if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
SemaRef.getLangOpts().CXXExceptions) {
Builder.AddTypedTextChunk("try");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTextChunk("catch");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("declaration");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
}
if (SemaRef.getLangOpts().ObjC)
AddObjCStatementResults(Results, true);
if (Results.includeCodePatterns()) {
Builder.AddTypedTextChunk("if");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
if (SemaRef.getLangOpts().CPlusPlus)
Builder.AddPlaceholderChunk("condition");
else
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("switch");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
if (SemaRef.getLangOpts().CPlusPlus)
Builder.AddPlaceholderChunk("condition");
else
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("cases");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
}
if (SemaRef.getCurFunction() &&
!SemaRef.getCurFunction()->SwitchStack.empty()) {
Builder.AddTypedTextChunk("case");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_Colon);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("default");
Builder.AddChunk(CodeCompletionString::CK_Colon);
Results.AddResult(Result(Builder.TakeString()));
}
if (Results.includeCodePatterns()) {
Builder.AddTypedTextChunk("while");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
if (SemaRef.getLangOpts().CPlusPlus)
Builder.AddPlaceholderChunk("condition");
else
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("do");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Builder.AddTextChunk("while");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("for");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
Builder.AddPlaceholderChunk("init-statement");
else
Builder.AddPlaceholderChunk("init-expression");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("condition");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("inc-expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) {
Builder.AddTypedTextChunk("for");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("range-declaration");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
if (SemaRef.getLangOpts().ObjC)
Builder.AddTextChunk("in");
else
Builder.AddChunk(CodeCompletionString::CK_Colon);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("range-expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
}
}
if (S->getContinueParent()) {
Builder.AddTypedTextChunk("continue");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
}
if (S->getBreakParent()) {
Builder.AddTypedTextChunk("break");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
}
QualType ReturnType;
if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
ReturnType = Function->getReturnType();
else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
ReturnType = Method->getReturnType();
else if (SemaRef.getCurBlock() &&
!SemaRef.getCurBlock()->ReturnType.isNull())
ReturnType = SemaRef.getCurBlock()->ReturnType;;
if (ReturnType.isNull() || ReturnType->isVoidType()) {
Builder.AddTypedTextChunk("return");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
} else {
assert(!ReturnType.isNull());
Builder.AddTypedTextChunk("return");
Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
if (ReturnType->isBooleanType()) {
Builder.AddTypedTextChunk("return true");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("return false");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
}
if (SemaRef.getLangOpts().CPlusPlus11 &&
(ReturnType->isPointerType() || ReturnType->isMemberPointerType())) {
Builder.AddTypedTextChunk("return nullptr");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
}
}
Builder.AddTypedTextChunk("goto");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("label");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("using namespace");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("identifier");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
Results.AddResult(Result(Builder.TakeString()));
AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
}
LLVM_FALLTHROUGH;
case Sema::PCC_ForInit:
case Sema::PCC_Condition:
AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
LLVM_FALLTHROUGH;
case Sema::PCC_ParenthesizedExpression:
if (SemaRef.getLangOpts().ObjCAutoRefCount &&
CCC == Sema::PCC_ParenthesizedExpression) {
Builder.AddTypedTextChunk("__bridge");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddPlaceholderChunk("expression");
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("__bridge_transfer");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("Objective-C type");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddPlaceholderChunk("expression");
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("__bridge_retained");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("CF type");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddPlaceholderChunk("expression");
Results.AddResult(Result(Builder.TakeString()));
}
LLVM_FALLTHROUGH;
case Sema::PCC_Expression: {
if (SemaRef.getLangOpts().CPlusPlus) {
addThisCompletion(SemaRef, Results);
Builder.AddResultTypeChunk("bool");
Builder.AddTypedTextChunk("true");
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("bool");
Builder.AddTypedTextChunk("false");
Results.AddResult(Result(Builder.TakeString()));
if (SemaRef.getLangOpts().RTTI) {
Builder.AddTypedTextChunk("dynamic_cast");
Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_RightAngle);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
}
Builder.AddTypedTextChunk("static_cast");
Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_RightAngle);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("reinterpret_cast");
Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_RightAngle);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("const_cast");
Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_RightAngle);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
if (SemaRef.getLangOpts().RTTI) {
Builder.AddResultTypeChunk("std::type_info");
Builder.AddTypedTextChunk("typeid");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression-or-type");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
}
Builder.AddTypedTextChunk("new");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expressions");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk("new");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
Builder.AddPlaceholderChunk("size");
Builder.AddChunk(CodeCompletionString::CK_RightBracket);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expressions");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("void");
Builder.AddTypedTextChunk("delete");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("expression");
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("void");
Builder.AddTypedTextChunk("delete");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
Builder.AddChunk(CodeCompletionString::CK_RightBracket);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("expression");
Results.AddResult(Result(Builder.TakeString()));
if (SemaRef.getLangOpts().CXXExceptions) {
Builder.AddResultTypeChunk("void");
Builder.AddTypedTextChunk("throw");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("expression");
Results.AddResult(Result(Builder.TakeString()));
}
if (SemaRef.getLangOpts().CPlusPlus11) {
Builder.AddResultTypeChunk("std::nullptr_t");
Builder.AddTypedTextChunk("nullptr");
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("size_t");
Builder.AddTypedTextChunk("alignof");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("bool");
Builder.AddTypedTextChunk("noexcept");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("size_t");
Builder.AddTypedTextChunk("sizeof...");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("parameter-pack");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
}
}
if (SemaRef.getLangOpts().ObjC) {
if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
if (ObjCInterfaceDecl *ID = Method->getClassInterface())
if (ID->getSuperClass()) {
std::string SuperType;
SuperType = ID->getSuperClass()->getNameAsString();
if (Method->isInstanceMethod())
SuperType += " *";
Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
Builder.AddTypedTextChunk("super");
Results.AddResult(Result(Builder.TakeString()));
}
}
AddObjCExpressionResults(Results, true);
}
if (SemaRef.getLangOpts().C11) {
Builder.AddResultTypeChunk("size_t");
if (SemaRef.PP.isMacroDefined("alignof"))
Builder.AddTypedTextChunk("alignof");
else
Builder.AddTypedTextChunk("_Alignof");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("type");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
}
Builder.AddResultTypeChunk("size_t");
Builder.AddTypedTextChunk("sizeof");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression-or-type");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
break;
}
case Sema::PCC_Type:
case Sema::PCC_LocalDeclarationSpecifiers:
break;
}
if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
Results.AddResult(Result("operator"));
}
static void AddResultTypeChunk(ASTContext &Context,
const PrintingPolicy &Policy,
const NamedDecl *ND, QualType BaseType,
CodeCompletionBuilder &Result) {
if (!ND)
return;
if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
return;
QualType T;
if (const FunctionDecl *Function = ND->getAsFunction())
T = Function->getReturnType();
else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
if (!BaseType.isNull())
T = Method->getSendResultType(BaseType);
else
T = Method->getReturnType();
} else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
T = clang::TypeName::getFullyQualifiedType(T, Context);
} else if (isa<UnresolvedUsingValueDecl>(ND)) {
} else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
if (!BaseType.isNull())
T = Ivar->getUsageType(BaseType);
else
T = Ivar->getType();
} else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
T = Value->getType();
} else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
if (!BaseType.isNull())
T = Property->getUsageType(BaseType);
else
T = Property->getType();
}
if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
return;
Result.AddResultTypeChunk(
GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
}
static void MaybeAddSentinel(Preprocessor &PP,
const NamedDecl *FunctionOrMethod,
CodeCompletionBuilder &Result) {
if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
if (Sentinel->getSentinel() == 0) {
if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
Result.AddTextChunk(", nil");
else if (PP.isMacroDefined("NULL"))
Result.AddTextChunk(", NULL");
else
Result.AddTextChunk(", (void*)0");
}
}
static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
QualType &Type) {
std::string Result;
if (ObjCQuals & Decl::OBJC_TQ_In)
Result += "in ";
else if (ObjCQuals & Decl::OBJC_TQ_Inout)
Result += "inout ";
else if (ObjCQuals & Decl::OBJC_TQ_Out)
Result += "out ";
if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
Result += "bycopy ";
else if (ObjCQuals & Decl::OBJC_TQ_Byref)
Result += "byref ";
if (ObjCQuals & Decl::OBJC_TQ_Oneway)
Result += "oneway ";
if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
if (auto nullability = AttributedType::stripOuterNullability(Type)) {
switch (*nullability) {
case NullabilityKind::NonNull:
Result += "nonnull ";
break;
case NullabilityKind::Nullable:
Result += "nullable ";
break;
case NullabilityKind::Unspecified:
Result += "null_unspecified ";
break;
case NullabilityKind::NullableResult:
llvm_unreachable("Not supported as a context-sensitive keyword!");
break;
}
}
}
return Result;
}
static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
FunctionTypeLoc &Block,
FunctionProtoTypeLoc &BlockProto,
bool SuppressBlock = false) {
if (!TSInfo)
return;
TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
while (true) {
if (!SuppressBlock) {
if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
if (TypeSourceInfo *InnerTSInfo =
TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
continue;
}
}
if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
TL = QualifiedTL.getUnqualifiedLoc();
continue;
}
if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
TL = AttrTL.getModifiedLoc();
continue;
}
}
if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
TL = BlockPtr.getPointeeLoc().IgnoreParens();
Block = TL.getAs<FunctionTypeLoc>();
BlockProto = TL.getAs<FunctionProtoTypeLoc>();
}
break;
}
}
static std::string
formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
bool SuppressBlockName = false,
bool SuppressBlock = false,
Optional<ArrayRef<QualType>> ObjCSubsts = None);
static std::string
FormatFunctionParameter(const PrintingPolicy &Policy,
const DeclaratorDecl *Param, bool SuppressName = false,
bool SuppressBlock = false,
Optional<ArrayRef<QualType>> ObjCSubsts = None) {
if (!Param)
return "int";
Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None;
if (const auto *PVD = dyn_cast<ParmVarDecl>(Param))
ObjCQual = PVD->getObjCDeclQualifier();
bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
if (Param->getType()->isDependentType() ||
!Param->getType()->isBlockPointerType()) {
std::string Result;
if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
Result = std::string(Param->getIdentifier()->deuglifiedName());
QualType Type = Param->getType();
if (ObjCSubsts)
Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
ObjCSubstitutionContext::Parameter);
if (ObjCMethodParam) {
Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
Result += Type.getAsString(Policy) + ")";
if (Param->getIdentifier() && !SuppressName)
Result += Param->getIdentifier()->deuglifiedName();
} else {
Type.getAsStringInternal(Result, Policy);
}
return Result;
}
FunctionTypeLoc Block;
FunctionProtoTypeLoc BlockProto;
findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
SuppressBlock);
if (!Block && ObjCMethodParam &&
cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
->findPropertyDecl(false))
findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
SuppressBlock);
}
if (!Block) {
std::string Result;
if (!ObjCMethodParam && Param->getIdentifier())
Result = std::string(Param->getIdentifier()->deuglifiedName());
QualType Type = Param->getType().getUnqualifiedType();
if (ObjCMethodParam) {
Result = Type.getAsString(Policy);
std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);
if (!Quals.empty())
Result = "(" + Quals + " " + Result + ")";
if (Result.back() != ')')
Result += " ";
if (Param->getIdentifier())
Result += Param->getIdentifier()->deuglifiedName();
} else {
Type.getAsStringInternal(Result, Policy);
}
return Result;
}
return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
false, SuppressBlock,
ObjCSubsts);
}
static std::string
formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
bool SuppressBlockName, bool SuppressBlock,
Optional<ArrayRef<QualType>> ObjCSubsts) {
std::string Result;
QualType ResultType = Block.getTypePtr()->getReturnType();
if (ObjCSubsts)
ResultType =
ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
ObjCSubstitutionContext::Result);
if (!ResultType->isVoidType() || SuppressBlock)
ResultType.getAsStringInternal(Result, Policy);
std::string Params;
if (!BlockProto || Block.getNumParams() == 0) {
if (BlockProto && BlockProto.getTypePtr()->isVariadic())
Params = "(...)";
else
Params = "(void)";
} else {
Params += "(";
for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
if (I)
Params += ", ";
Params += FormatFunctionParameter(Policy, Block.getParam(I),
false,
true, ObjCSubsts);
if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
Params += ", ...";
}
Params += ")";
}
if (SuppressBlock) {
Result = Result + " (^";
if (!SuppressBlockName && BlockDecl->getIdentifier())
Result += BlockDecl->getIdentifier()->getName();
Result += ")";
Result += Params;
} else {
Result = '^' + Result;
Result += Params;
if (!SuppressBlockName && BlockDecl->getIdentifier())
Result += BlockDecl->getIdentifier()->getName();
}
return Result;
}
static std::string GetDefaultValueString(const ParmVarDecl *Param,
const SourceManager &SM,
const LangOptions &LangOpts) {
const SourceRange SrcRange = Param->getDefaultArgRange();
CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
bool Invalid = CharSrcRange.isInvalid();
if (Invalid)
return "";
StringRef srcText =
Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
if (Invalid)
return "";
if (srcText.empty() || srcText == "=") {
return "";
}
std::string DefValue(srcText.str());
if (DefValue.at(0) != '=') {
return " = " + DefValue;
}
return " " + DefValue;
}
static void AddFunctionParameterChunks(Preprocessor &PP,
const PrintingPolicy &Policy,
const FunctionDecl *Function,
CodeCompletionBuilder &Result,
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) {
CodeCompletionBuilder Opt(Result.getAllocator(),
Result.getCodeCompletionTUInfo());
if (!FirstParameter)
Opt.AddChunk(CodeCompletionString::CK_Comma);
AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
Result.AddOptionalChunk(Opt.TakeString());
break;
}
if (FirstParameter)
FirstParameter = false;
else
Result.AddChunk(CodeCompletionString::CK_Comma);
InOptional = false;
std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
if (Param->hasDefaultArg())
PlaceholderStr +=
GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
if (Function->isVariadic() && P == N - 1)
PlaceholderStr += ", ...";
Result.AddPlaceholderChunk(
Result.getAllocator().CopyString(PlaceholderStr));
}
if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
if (Proto->isVariadic()) {
if (Proto->getNumParams() == 0)
Result.AddPlaceholderChunk("...");
MaybeAddSentinel(PP, Function, Result);
}
}
static void AddTemplateParameterChunks(
ASTContext &Context, const PrintingPolicy &Policy,
const TemplateDecl *Template, CodeCompletionBuilder &Result,
unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
bool FirstParameter = true;
Template = cast<TemplateDecl>(Template->getCanonicalDecl());
TemplateParameterList *Params = Template->getTemplateParameters();
TemplateParameterList::iterator PEnd = Params->end();
if (MaxParameters)
PEnd = Params->begin() + MaxParameters;
for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
++P) {
bool HasDefaultArg = false;
std::string PlaceholderStr;
if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
if (TTP->wasDeclaredWithTypename())
PlaceholderStr = "typename";
else if (const auto *TC = TTP->getTypeConstraint()) {
llvm::raw_string_ostream OS(PlaceholderStr);
TC->print(OS, Policy);
OS.flush();
} else
PlaceholderStr = "class";
if (TTP->getIdentifier()) {
PlaceholderStr += ' ';
PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
}
HasDefaultArg = TTP->hasDefaultArgument();
} else if (NonTypeTemplateParmDecl *NTTP =
dyn_cast<NonTypeTemplateParmDecl>(*P)) {
if (NTTP->getIdentifier())
PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName());
NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
HasDefaultArg = NTTP->hasDefaultArgument();
} else {
assert(isa<TemplateTemplateParmDecl>(*P));
TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
PlaceholderStr = "template<...> class";
if (TTP->getIdentifier()) {
PlaceholderStr += ' ';
PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
}
HasDefaultArg = TTP->hasDefaultArgument();
}
if (HasDefaultArg && !InDefaultArg) {
CodeCompletionBuilder Opt(Result.getAllocator(),
Result.getCodeCompletionTUInfo());
if (!FirstParameter)
Opt.AddChunk(CodeCompletionString::CK_Comma);
AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
P - Params->begin(), true);
Result.AddOptionalChunk(Opt.TakeString());
break;
}
InDefaultArg = false;
if (FirstParameter)
FirstParameter = false;
else
Result.AddChunk(CodeCompletionString::CK_Comma);
Result.AddPlaceholderChunk(
Result.getAllocator().CopyString(PlaceholderStr));
}
}
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);
Qualifier->print(OS, Policy);
}
if (QualifierIsInformative)
Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
else
Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
}
static void
AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
const FunctionDecl *Function) {
const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
if (!Proto || !Proto->getMethodQuals())
return;
if (Proto->getMethodQuals().hasOnlyConst()) {
Result.AddInformativeChunk(" const");
return;
}
if (Proto->getMethodQuals().hasOnlyVolatile()) {
Result.AddInformativeChunk(" volatile");
return;
}
if (Proto->getMethodQuals().hasOnlyRestrict()) {
Result.AddInformativeChunk(" restrict");
return;
}
std::string QualsStr;
if (Proto->isConst())
QualsStr += " const";
if (Proto->isVolatile())
QualsStr += " volatile";
if (Proto->isRestrict())
QualsStr += " restrict";
Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
}
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_Conditional:
case NUM_OVERLOADED_OPERATORS:
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;
case OO_Array_Delete:
OperatorName = "operator delete[]";
break;
case OO_Call:
OperatorName = "operator()";
break;
case OO_Subscript:
OperatorName = "operator[]";
break;
}
Result.AddTypedTextChunk(OperatorName);
break;
}
case DeclarationName::Identifier:
case DeclarationName::CXXConversionFunctionName:
case DeclarationName::CXXDestructorName:
case DeclarationName::CXXLiteralOperatorName:
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();
if (const auto *RecordTy = Ty->getAs<RecordType>())
Record = cast<CXXRecordDecl>(RecordTy->getDecl());
else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
Record = InjectedTy->getDecl();
else {
Result.AddTypedTextChunk(
Result.getAllocator().CopyString(ND->getNameAsString()));
break;
}
Result.AddTypedTextChunk(
Result.getAllocator().CopyString(Record->getNameAsString()));
if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
Result.AddChunk(CodeCompletionString::CK_LeftAngle);
AddTemplateParameterChunks(Context, Policy, Template, Result);
Result.AddChunk(CodeCompletionString::CK_RightAngle);
}
break;
}
}
}
CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
Sema &S, const CodeCompletionContext &CCContext,
CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
bool IncludeBriefComments) {
return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
CCTUInfo, IncludeBriefComments);
}
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();
Result.AddChunk(CodeCompletionString::CK_LeftParen);
MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
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;
}
Result.AddPlaceholderChunk(
Result.getAllocator().CopyString((*A)->getName()));
}
Result.AddChunk(CodeCompletionString::CK_RightParen);
return Result.TakeString();
}
CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
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();
if (const RawComment *RC =
getPatternCompletionComment(Ctx, Declaration)) {
Result.addBriefComment(RC->getBriefText(Ctx));
Pattern->BriefComment = Result.getBriefComment();
}
}
return Pattern;
}
if (Kind == RK_Keyword) {
Result.AddTypedTextChunk(Keyword);
return Result.TakeString();
}
assert(Kind == RK_Declaration && "Missed a result kind?");
return createCodeCompletionStringForDecl(
PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
}
static void printOverrideString(const CodeCompletionString &CCS,
std::string &BeforeName,
std::string &NameAndSignature) {
bool SeenTypedChunk = false;
for (auto &Chunk : CCS) {
if (Chunk.Kind == CodeCompletionString::CK_Optional) {
assert(SeenTypedChunk && "optional parameter before name");
printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
continue;
}
SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
if (SeenTypedChunk)
NameAndSignature += Chunk.Text;
else
BeforeName += Chunk.Text;
}
}
CodeCompletionString *
CodeCompletionResult::createCodeCompletionStringForOverride(
Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
bool IncludeBriefComments, const CodeCompletionContext &CCContext,
PrintingPolicy &Policy) {
auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
false,
CCContext, Policy);
std::string BeforeName;
std::string NameAndSignature;
printOverrideString(*CCS, BeforeName, NameAndSignature);
NameAndSignature += " override";
Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
return Result.TakeString();
}
static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) {
const auto *VD = dyn_cast<VarDecl>(ND);
if (!VD)
return nullptr;
const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
if (!RecordDecl || !RecordDecl->isLambda())
return nullptr;
return RecordDecl->getLambdaCallOperator();
}
CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl(
Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
bool IncludeBriefComments, const CodeCompletionContext &CCContext,
PrintingPolicy &Policy) {
const NamedDecl *ND = Declaration;
Result.addParentContext(ND->getDeclContext());
if (IncludeBriefComments) {
if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
Result.addBriefComment(RC->getBriefText(Ctx));
}
}
if (StartsNestedNameSpecifier) {
Result.AddTypedTextChunk(
Result.getAllocator().CopyString(ND->getNameAsString()));
Result.AddTextChunk("::");
return Result.TakeString();
}
for (const auto *I : ND->specific_attrs<AnnotateAttr>())
Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Ctx, Policy);
AddTypedNameChunk(Ctx, Policy, ND, Result);
Result.AddChunk(CodeCompletionString::CK_LeftParen);
AddFunctionParameterChunks(PP, Policy, Function, Result);
Result.AddChunk(CodeCompletionString::CK_RightParen);
AddFunctionTypeQualsToCompletionString(Result, Function);
};
if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
AddFunctionTypeAndResult(Function);
return Result.TakeString();
}
if (const auto *CallOperator =
dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) {
AddFunctionTypeAndResult(CallOperator);
return Result.TakeString();
}
AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
if (const FunctionTemplateDecl *FunTmpl =
dyn_cast<FunctionTemplateDecl>(ND)) {
AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Ctx, Policy);
FunctionDecl *Function = FunTmpl->getTemplatedDecl();
AddTypedNameChunk(Ctx, Policy, Function, Result);
llvm::SmallBitVector Deduced;
Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
unsigned LastDeducibleArgument;
for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
--LastDeducibleArgument) {
if (!Deduced[LastDeducibleArgument - 1]) {
bool HasDefaultArg = false;
NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
LastDeducibleArgument - 1);
if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
HasDefaultArg = TTP->hasDefaultArgument();
else if (NonTypeTemplateParmDecl *NTTP =
dyn_cast<NonTypeTemplateParmDecl>(Param))
HasDefaultArg = NTTP->hasDefaultArgument();
else {
assert(isa<TemplateTemplateParmDecl>(Param));
HasDefaultArg =
cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
}
if (!HasDefaultArg)
break;
}
}
if (LastDeducibleArgument) {
Result.AddChunk(CodeCompletionString::CK_LeftAngle);
AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
LastDeducibleArgument);
Result.AddChunk(CodeCompletionString::CK_RightAngle);
}
Result.AddChunk(CodeCompletionString::CK_LeftParen);
AddFunctionParameterChunks(PP, Policy, Function, Result);
Result.AddChunk(CodeCompletionString::CK_RightParen);
AddFunctionTypeQualsToCompletionString(Result, Function);
return Result.TakeString();
}
if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Ctx, Policy);
Result.AddTypedTextChunk(
Result.getAllocator().CopyString(Template->getNameAsString()));
Result.AddChunk(CodeCompletionString::CK_LeftAngle);
AddTemplateParameterChunks(Ctx, Policy, Template, Result);
Result.AddChunk(CodeCompletionString::CK_RightAngle);
return Result.TakeString();
}
if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
Selector Sel = Method->getSelector();
if (Sel.isUnarySelector()) {
Result.AddTypedTextChunk(
Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
return Result.TakeString();
}
std::string SelName = Sel.getNameForSlot(0).str();
SelName += ':';
if (StartParameter == 0)
Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
else {
Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
if (Method->param_size() == 1)
Result.AddTypedTextChunk("");
}
unsigned Idx = 0;
for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
PEnd = Method->param_end();
P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
if (Idx > 0) {
std::string Keyword;
if (Idx > StartParameter)
Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
Keyword += II->getName();
Keyword += ":";
if (Idx < StartParameter || AllParametersAreInformative)
Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
else
Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
}
if (Idx < StartParameter)
continue;
std::string Arg;
QualType ParamType = (*P)->getType();
Optional<ArrayRef<QualType>> ObjCSubsts;
if (!CCContext.getBaseType().isNull())
ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
if (ParamType->isBlockPointerType() && !DeclaringEntity)
Arg = FormatFunctionParameter(Policy, *P, true,
false, ObjCSubsts);
else {
if (ObjCSubsts)
ParamType = ParamType.substObjCTypeArgs(
Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
ParamType);
Arg += ParamType.getAsString(Policy) + ")";
if (IdentifierInfo *II = (*P)->getIdentifier())
if (DeclaringEntity || AllParametersAreInformative)
Arg += II->getName();
}
if (Method->isVariadic() && (P + 1) == PEnd)
Arg += ", ...";
if (DeclaringEntity)
Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
else if (AllParametersAreInformative)
Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
else
Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
}
if (Method->isVariadic()) {
if (Method->param_size() == 0) {
if (DeclaringEntity)
Result.AddTextChunk(", ...");
else if (AllParametersAreInformative)
Result.AddInformativeChunk(", ...");
else
Result.AddPlaceholderChunk(", ...");
}
MaybeAddSentinel(PP, Method, Result);
}
return Result.TakeString();
}
if (Qualifier)
AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Ctx, Policy);
Result.AddTypedTextChunk(
Result.getAllocator().CopyString(ND->getNameAsString()));
return Result.TakeString();
}
const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
const NamedDecl *ND) {
if (!ND)
return nullptr;
if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
return RC;
const auto *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 auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
if (!M || !M->isPropertyAccessor())
return nullptr;
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;
}
static void AddOverloadAggregateChunks(const RecordDecl *RD,
const PrintingPolicy &Policy,
CodeCompletionBuilder &Result,
unsigned CurrentArg) {
unsigned ChunkIndex = 0;
auto AddChunk = [&](llvm::StringRef Placeholder) {
if (ChunkIndex > 0)
Result.AddChunk(CodeCompletionString::CK_Comma);
const char *Copy = Result.getAllocator().CopyString(Placeholder);
if (ChunkIndex == CurrentArg)
Result.AddCurrentParameterChunk(Copy);
else
Result.AddPlaceholderChunk(Copy);
++ChunkIndex;
};
if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
for (const auto &Base : CRD->bases())
AddChunk(Base.getType().getAsString(Policy));
}
for (const auto &Field : RD->fields())
AddChunk(FormatFunctionParameter(Policy, Field));
}
static void AddOverloadParameterChunks(
ASTContext &Context, const PrintingPolicy &Policy,
const FunctionDecl *Function, const FunctionProtoType *Prototype,
FunctionProtoTypeLoc PrototypeLoc, CodeCompletionBuilder &Result,
unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) {
if (!Function && !Prototype) {
Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
return;
}
bool FirstParameter = true;
unsigned NumParams =
Function ? Function->getNumParams() : Prototype->getNumParams();
for (unsigned P = Start; P != NumParams; ++P) {
if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
CodeCompletionBuilder Opt(Result.getAllocator(),
Result.getCodeCompletionTUInfo());
if (!FirstParameter)
Opt.AddChunk(CodeCompletionString::CK_Comma);
AddOverloadParameterChunks(Context, Policy, Function, Prototype,
PrototypeLoc, Opt, CurrentArg, P,
true);
Result.AddOptionalChunk(Opt.TakeString());
return;
}
if (FirstParameter)
FirstParameter = false;
else
Result.AddChunk(CodeCompletionString::CK_Comma);
InOptional = false;
std::string Placeholder;
assert(P < Prototype->getNumParams());
if (Function || PrototypeLoc) {
const ParmVarDecl *Param =
Function ? Function->getParamDecl(P) : PrototypeLoc.getParam(P);
Placeholder = FormatFunctionParameter(Policy, Param);
if (Param->hasDefaultArg())
Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
Context.getLangOpts());
} else {
Placeholder = Prototype->getParamType(P).getAsString(Policy);
}
if (P == CurrentArg)
Result.AddCurrentParameterChunk(
Result.getAllocator().CopyString(Placeholder));
else
Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
}
if (Prototype && Prototype->isVariadic()) {
CodeCompletionBuilder Opt(Result.getAllocator(),
Result.getCodeCompletionTUInfo());
if (!FirstParameter)
Opt.AddChunk(CodeCompletionString::CK_Comma);
if (CurrentArg < NumParams)
Opt.AddPlaceholderChunk("...");
else
Opt.AddCurrentParameterChunk("...");
Result.AddOptionalChunk(Opt.TakeString());
}
}
static std::string
formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional,
const PrintingPolicy &Policy) {
if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) {
Optional = Type->hasDefaultArgument();
} else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Optional = NonType->hasDefaultArgument();
} else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) {
Optional = Template->hasDefaultArgument();
}
std::string Result;
llvm::raw_string_ostream OS(Result);
Param->print(OS, Policy);
return Result;
}
static std::string templateResultType(const TemplateDecl *TD,
const PrintingPolicy &Policy) {
if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD))
return CTD->getTemplatedDecl()->getKindName().str();
if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD))
return VTD->getTemplatedDecl()->getType().getAsString(Policy);
if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD))
return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
if (isa<TypeAliasTemplateDecl>(TD))
return "type";
if (isa<TemplateTemplateParmDecl>(TD))
return "class";
if (isa<ConceptDecl>(TD))
return "concept";
return "";
}
static CodeCompletionString *createTemplateSignatureString(
const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
const PrintingPolicy &Policy) {
llvm::ArrayRef<NamedDecl *> Params = TD->getTemplateParameters()->asArray();
CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
Builder.getCodeCompletionTUInfo());
std::string ResultType = templateResultType(TD, Policy);
if (!ResultType.empty())
Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
Builder.AddTextChunk(
Builder.getAllocator().CopyString(TD->getNameAsString()));
Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
CodeCompletionBuilder *Current = &Builder;
for (unsigned I = 0; I < Params.size(); ++I) {
bool Optional = false;
std::string Placeholder =
formatTemplateParameterPlaceholder(Params[I], Optional, Policy);
if (Optional)
Current = &OptionalBuilder;
if (I > 0)
Current->AddChunk(CodeCompletionString::CK_Comma);
Current->AddChunk(I == CurrentArg
? CodeCompletionString::CK_CurrentParameter
: CodeCompletionString::CK_Placeholder,
Current->getAllocator().CopyString(Placeholder));
}
if (Current == &OptionalBuilder)
Builder.AddOptionalChunk(OptionalBuilder.TakeString());
Builder.AddChunk(CodeCompletionString::CK_RightAngle);
if (isa<FunctionTemplateDecl>(TD))
Builder.AddInformativeChunk("()");
return Builder.TakeString();
}
CodeCompletionString *
CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments,
bool Braced) const {
PrintingPolicy Policy = getCompletionPrintingPolicy(S);
Policy.SuppressTemplateArgsInCXXConstructors = true;
CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
CXAvailability_Available);
if (getKind() == CK_Template)
return createTemplateSignatureString(getTemplate(), Result, CurrentArg,
Policy);
FunctionDecl *FDecl = getFunction();
const FunctionProtoType *Proto =
dyn_cast_or_null<FunctionProtoType>(getFunctionType());
if (getKind() == CK_Aggregate) {
Result.AddTextChunk(
Result.getAllocator().CopyString(getAggregate()->getName()));
} else if (FDecl) {
if (IncludeBriefComments) {
if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
Result.addBriefComment(RC->getBriefText(S.getASTContext()));
}
AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
std::string Name;
llvm::raw_string_ostream OS(Name);
FDecl->getDeclName().print(OS, Policy);
Result.AddTextChunk(Result.getAllocator().CopyString(OS.str()));
} else {
Result.AddResultTypeChunk(Result.getAllocator().CopyString(
getFunctionType()->getReturnType().getAsString(Policy)));
}
Result.AddChunk(Braced ? CodeCompletionString::CK_LeftBrace
: CodeCompletionString::CK_LeftParen);
if (getKind() == CK_Aggregate)
AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg);
else
AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto,
getFunctionProtoTypeLoc(), Result, CurrentArg);
Result.AddChunk(Braced ? CodeCompletionString::CK_RightBrace
: CodeCompletionString::CK_RightParen);
return Result.TakeString();
}
unsigned clang::getMacroUsagePriority(StringRef MacroName,
const LangOptions &LangOpts,
bool PreferredTypeIsPointer) {
unsigned Priority = CCP_Macro;
if (MacroName.equals("nil") || MacroName.equals("NULL") ||
MacroName.equals("Nil")) {
Priority = CCP_Constant;
if (PreferredTypeIsPointer)
Priority = Priority / CCF_SimilarTypeMatch;
}
else if (MacroName.equals("YES") || MacroName.equals("NO") ||
MacroName.equals("true") || MacroName.equals("false"))
Priority = CCP_Constant;
else if (MacroName.equals("bool"))
Priority = CCP_Type + (LangOpts.ObjC ? 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:
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::ObjCMethod:
return cast<ObjCMethodDecl>(D)->isInstanceMethod()
? CXCursor_ObjCInstanceMethodDecl
: CXCursor_ObjCClassMethodDecl;
case Decl::CXXMethod:
return CXCursor_CXXMethod;
case Decl::CXXConstructor:
return CXCursor_Constructor;
case Decl::CXXDestructor:
return CXCursor_Destructor;
case Decl::CXXConversion:
return CXCursor_ConversionFunction;
case Decl::ObjCProperty:
return CXCursor_ObjCPropertyDecl;
case Decl::ObjCProtocol:
return CXCursor_ObjCProtocolDecl;
case Decl::ParmVar:
return CXCursor_ParmDecl;
case Decl::Typedef:
return CXCursor_TypedefDecl;
case Decl::TypeAlias:
return CXCursor_TypeAliasDecl;
case Decl::TypeAliasTemplate:
return CXCursor_TypeAliasTemplateDecl;
case Decl::Var:
return CXCursor_VarDecl;
case Decl::Namespace:
return CXCursor_Namespace;
case Decl::NamespaceAlias:
return CXCursor_NamespaceAlias;
case Decl::TemplateTypeParm:
return CXCursor_TemplateTypeParameter;
case Decl::NonTypeTemplateParm:
return CXCursor_NonTypeTemplateParameter;
case Decl::TemplateTemplateParm:
return CXCursor_TemplateTemplateParameter;
case Decl::FunctionTemplate:
return CXCursor_FunctionTemplate;
case Decl::ClassTemplate:
return CXCursor_ClassTemplate;
case Decl::AccessSpec:
return CXCursor_CXXAccessSpecifier;
case Decl::ClassTemplatePartialSpecialization:
return CXCursor_ClassTemplatePartialSpecialization;
case Decl::UsingDirective:
return CXCursor_UsingDirective;
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:
return CXCursor_UsingDeclaration;
case Decl::UsingEnum:
return CXCursor_EnumDecl;
case Decl::ObjCPropertyImpl:
switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
case ObjCPropertyImplDecl::Dynamic:
return CXCursor_ObjCDynamicDecl;
case ObjCPropertyImplDecl::Synthesize:
return CXCursor_ObjCSynthesizeDecl;
}
llvm_unreachable("Unexpected Kind!");
case Decl::Import:
return CXCursor_ModuleImportDecl;
case Decl::ObjCTypeParam:
return CXCursor_TemplateTypeParameter;
case Decl::Concept:
return CXCursor_ConceptDecl;
default:
if (const auto *TD = dyn_cast<TagDecl>(D)) {
switch (TD->getTagKind()) {
case TTK_Interface: case TTK_Struct:
return CXCursor_StructDecl;
case TTK_Class:
return CXCursor_ClassDecl;
case TTK_Union:
return CXCursor_UnionDecl;
case TTK_Enum:
return CXCursor_EnumDecl;
}
}
}
return CXCursor_UnexposedDecl;
}
static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
bool LoadExternal, bool IncludeUndefined,
bool TargetTypeIsPointer = false) {
typedef CodeCompletionResult Result;
Results.EnterNewScope();
for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
MEnd = PP.macro_end(LoadExternal);
M != MEnd; ++M) {
auto MD = PP.getMacroDefinition(M->first);
if (IncludeUndefined || MD) {
MacroInfo *MI = MD.getMacroInfo();
if (MI && MI->isUsedForHeaderGuard())
continue;
Results.AddResult(
Result(M->first, MI,
getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
TargetTypeIsPointer)));
}
}
Results.ExitScope();
}
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)
Results.AddResult(Result("__func__", CCP_Constant));
Results.ExitScope();
}
static void HandleCodeCompleteResults(Sema *S,
CodeCompleteConsumer *CodeCompleter,
CodeCompletionContext Context,
CodeCompletionResult *Results,
unsigned NumResults) {
if (CodeCompleter)
CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
}
static CodeCompletionContext
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())
return CodeCompletionContext::CCC_TopLevel;
if (S.CurContext->isRecord())
return CodeCompletionContext::CCC_ClassStructUnion;
return CodeCompletionContext::CCC_Other;
case Sema::PCC_RecoveryInFunction:
return CodeCompletionContext::CCC_Recovery;
case Sema::PCC_ForInit:
if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
S.getLangOpts().ObjC)
return CodeCompletionContext::CCC_ParenthesizedExpression;
else
return CodeCompletionContext::CCC_Expression;
case Sema::PCC_Expression:
return CodeCompletionContext::CCC_Expression;
case Sema::PCC_Condition:
return CodeCompletionContext(CodeCompletionContext::CCC_Expression,
S.getASTContext().BoolTy);
case Sema::PCC_Statement:
return CodeCompletionContext::CCC_Statement;
case Sema::PCC_Type:
return CodeCompletionContext::CCC_Type;
case Sema::PCC_ParenthesizedExpression:
return CodeCompletionContext::CCC_ParenthesizedExpression;
case Sema::PCC_LocalDeclarationSpecifiers:
return CodeCompletionContext::CCC_Type;
}
llvm_unreachable("Invalid ParserCompletionContext!");
}
static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
ResultBuilder &Results) {
DeclContext *CurContext = S.CurContext;
while (isa<BlockDecl>(CurContext))
CurContext = CurContext->getParent();
CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
if (!Method || !Method->isVirtual())
return;
for (auto P : Method->parameters())
if (!P->getDeclName())
return;
PrintingPolicy Policy = getCompletionPrintingPolicy(S);
for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
continue;
if (!InContext) {
NestedNameSpecifier *NNS = getRequiredQualification(
S.Context, CurContext, Overridden->getDeclContext());
if (NNS) {
std::string Str;
llvm::raw_string_ostream OS(Str);
NNS->print(OS, Policy);
Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
}
} else if (!InContext->Equals(Overridden->getDeclContext()))
continue;
Builder.AddTypedTextChunk(
Results.getAllocator().CopyString(Overridden->getNameAsString()));
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
bool FirstParam = true;
for (auto P : Method->parameters()) {
if (FirstParam)
FirstParam = false;
else
Builder.AddChunk(CodeCompletionString::CK_Comma);
Builder.AddPlaceholderChunk(
Results.getAllocator().CopyString(P->getIdentifier()->getName()));
}
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(CodeCompletionResult(
Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
CXAvailability_Available, Overridden));
Results.Ignore(Overridden);
}
}
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;
if (Path.empty()) {
SmallVector<Module *, 8> Modules;
PP.getHeaderSearchInfo().collectAllModules(Modules);
for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
Builder.AddTypedTextChunk(
Builder.getAllocator().CopyString(Modules[I]->Name));
Results.AddResult(Result(
Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
Modules[I]->isAvailable() ? CXAvailability_Available
: CXAvailability_NotAvailable));
}
} else if (getLangOpts().Modules) {
Module *Mod =
PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
false);
if (Mod) {
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, CXCursor_ModuleImportDecl,
(*Sub)->isAvailable() ? CXAvailability_Available
: CXAvailability_NotAvailable));
}
}
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteOrdinaryName(Scope *S,
ParserCompletionContext CompletionContext) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
mapCodeCompletionContext(*this, CompletionContext));
Results.EnterNewScope();
switch (CompletionContext) {
case PCC_Namespace:
case PCC_Class:
case PCC_ObjCInterface:
case PCC_ObjCImplementation:
case PCC_ObjCInstanceVariableList:
case PCC_Template:
case PCC_MemberTemplate:
case PCC_Type:
case PCC_LocalDeclarationSpecifiers:
Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
break;
case PCC_Statement:
case PCC_ParenthesizedExpression:
case PCC_Expression:
case PCC_ForInit:
case PCC_Condition:
if (WantTypesInContext(CompletionContext, getLangOpts()))
Results.setFilter(&ResultBuilder::IsOrdinaryName);
else
Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
if (getLangOpts().CPlusPlus)
MaybeAddOverrideCalls(*this, nullptr, Results);
break;
case PCC_RecoveryInFunction:
break;
}
auto ThisType = getCurrentThisType();
if (!ThisType.isNull())
Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
VK_LValue);
CodeCompletionDeclConsumer Consumer(Results, CurContext);
LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
AddOrdinaryNameResults(CompletionContext, S, *this, Results);
Results.ExitScope();
switch (CompletionContext) {
case PCC_ParenthesizedExpression:
case PCC_Expression:
case PCC_Statement:
case PCC_RecoveryInFunction:
if (S->getFnParent())
AddPrettyFunctionResults(getLangOpts(), Results);
break;
case PCC_Namespace:
case PCC_Class:
case PCC_ObjCInterface:
case PCC_ObjCImplementation:
case PCC_ObjCInstanceVariableList:
case PCC_Template:
case PCC_MemberTemplate:
case PCC_ForInit:
case PCC_Condition:
case PCC_Type:
case PCC_LocalDeclarationSpecifiers:
break;
}
if (CodeCompleter->includeMacros())
AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression, bool IsSuper,
ResultBuilder &Results);
void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
bool AllowNonIdentifiers,
bool AllowNestedNameSpecifiers) {
typedef CodeCompletionResult Result;
ResultBuilder Results(
*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
AllowNestedNameSpecifiers
? CodeCompletionContext::CCC_SymbolOrNewName
: CodeCompletionContext::CCC_NewName);
Results.EnterNewScope();
Results.AddResult(Result("const"));
Results.AddResult(Result("volatile"));
if (getLangOpts().C99)
Results.AddResult(Result("restrict"));
if (getLangOpts().CPlusPlus) {
if (getLangOpts().CPlusPlus11 &&
(DS.getTypeSpecType() == DeclSpec::TST_class ||
DS.getTypeSpecType() == DeclSpec::TST_struct))
Results.AddResult("final");
if (AllowNonIdentifiers) {
Results.AddResult(Result("operator"));
}
if (AllowNestedNameSpecifiers) {
Results.allowNestedNameSpecifiers();
Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
CodeCompletionDeclConsumer Consumer(Results, CurContext);
LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
Results.setFilter(nullptr);
}
}
Results.ExitScope();
if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
DS.getTypeSpecType() == DeclSpec::TST_typename &&
DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
!DS.isTypeAltiVecVector() && S &&
(S->getFlags() & Scope::DeclScope) != 0 &&
(S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
Scope::FunctionPrototypeScope | Scope::AtCatchScope)) ==
0) {
ParsedType T = DS.getRepAsType();
if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
AddClassMessageCompletions(*this, S, T, None, false, false, Results);
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static const char *underscoreAttrScope(llvm::StringRef Scope) {
if (Scope == "clang")
return "_Clang";
if (Scope == "gnu")
return "__gnu__";
return nullptr;
}
static const char *noUnderscoreAttrScope(llvm::StringRef Scope) {
if (Scope == "_Clang")
return "clang";
if (Scope == "__gnu__")
return "gnu";
return nullptr;
}
void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax,
AttributeCompletion Completion,
const IdentifierInfo *InScope) {
if (Completion == AttributeCompletion::None)
return;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Attribute);
llvm::StringRef InScopeName;
bool InScopeUnderscore = false;
if (InScope) {
InScopeName = InScope->getName();
if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) {
InScopeName = NoUnderscore;
InScopeUnderscore = true;
}
}
bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU ||
Syntax == AttributeCommonInfo::AS_CXX11 ||
Syntax == AttributeCommonInfo::AS_C2x;
llvm::DenseSet<llvm::StringRef> FoundScopes;
auto AddCompletions = [&](const ParsedAttrInfo &A) {
if (A.IsTargetSpecific && !A.existsInTarget(Context.getTargetInfo()))
return;
if (!A.acceptsLangOpts(getLangOpts()))
return;
for (const auto &S : A.Spellings) {
if (S.Syntax != Syntax)
continue;
llvm::StringRef Name = S.NormalizedFullName;
llvm::StringRef Scope;
if ((Syntax == AttributeCommonInfo::AS_CXX11 ||
Syntax == AttributeCommonInfo::AS_C2x)) {
std::tie(Scope, Name) = Name.split("::");
if (Name.empty()) std::swap(Name, Scope);
}
if (Completion == AttributeCompletion::Scope) {
if (!Scope.empty() && FoundScopes.insert(Scope).second) {
Results.AddResult(
CodeCompletionResult(Results.getAllocator().CopyString(Scope)));
if (const char *Scope2 = underscoreAttrScope(Scope))
Results.AddResult(CodeCompletionResult(Scope2));
}
continue;
}
if (!InScopeName.empty()) {
if (Scope != InScopeName)
continue;
Scope = "";
}
auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name,
bool Underscores) {
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
llvm::SmallString<32> Text;
if (!Scope.empty()) {
Text.append(Scope);
Text.append("::");
}
if (Underscores)
Text.append("__");
Text.append(Name);
if (Underscores)
Text.append("__");
Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text));
if (!A.ArgNames.empty()) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen, "(");
bool First = true;
for (const char *Arg : A.ArgNames) {
if (!First)
Builder.AddChunk(CodeCompletionString::CK_Comma, ", ");
First = false;
Builder.AddPlaceholderChunk(Arg);
}
Builder.AddChunk(CodeCompletionString::CK_RightParen, ")");
}
Results.AddResult(Builder.TakeString());
};
if (!InScopeUnderscore)
Add(Scope, Name, false);
if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) {
llvm::SmallString<32> Guarded;
if (Scope.empty()) {
Add(Scope, Name, true);
} else {
const char *GuardedScope = underscoreAttrScope(Scope);
if (!GuardedScope)
continue;
Add(GuardedScope, Name, true);
}
}
}
};
for (const auto *A : ParsedAttrInfo::getAllBuiltin())
AddCompletions(*A);
for (const auto &Entry : ParsedAttrInfoRegistry::entries())
AddCompletions(*Entry.instantiate());
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
struct Sema::CodeCompleteExpressionData {
CodeCompleteExpressionData(QualType PreferredType = QualType(),
bool IsParenthesized = false)
: PreferredType(PreferredType), IntegralConstantExpression(false),
ObjCCollection(false), IsParenthesized(IsParenthesized) {}
QualType PreferredType;
bool IntegralConstantExpression;
bool ObjCCollection;
bool IsParenthesized;
SmallVector<Decl *, 4> IgnoreDecls;
};
namespace {
struct CoveredEnumerators {
llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen;
NestedNameSpecifier *SuggestedQualifier = nullptr;
};
}
static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
EnumDecl *Enum, DeclContext *CurContext,
const CoveredEnumerators &Enumerators) {
NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
Qualifier = getRequiredQualification(Context, CurContext, Enum);
}
Results.EnterNewScope();
for (auto *E : Enum->enumerators()) {
if (Enumerators.Seen.count(E))
continue;
CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
Results.AddResult(R, CurContext, nullptr, false);
}
Results.ExitScope();
}
static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) {
assert(!T.isNull());
if (auto *Specialization = T->getAs<TemplateSpecializationType>()) {
if (Specialization->getNumArgs() != 1)
return nullptr;
const TemplateArgument &Argument = Specialization->getArg(0);
if (Argument.getKind() != TemplateArgument::Type)
return nullptr;
return Argument.getAsType()->getAs<FunctionProtoType>();
}
if (T->isPointerType())
T = T->getPointeeType();
return T->getAs<FunctionProtoType>();
}
static void AddLambdaCompletion(ResultBuilder &Results,
llvm::ArrayRef<QualType> Parameters,
const LangOptions &LangOpts) {
if (!Results.includeCodePatterns())
return;
CodeCompletionBuilder Completion(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Completion.AddChunk(CodeCompletionString::CK_LeftBracket);
Completion.AddPlaceholderChunk("=");
Completion.AddChunk(CodeCompletionString::CK_RightBracket);
if (!Parameters.empty()) {
Completion.AddChunk(CodeCompletionString::CK_LeftParen);
bool First = true;
for (auto Parameter : Parameters) {
if (!First)
Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma);
else
First = false;
constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
std::string Type = std::string(NamePlaceholder);
Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
llvm::StringRef Prefix, Suffix;
std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
Prefix = Prefix.rtrim();
Suffix = Suffix.ltrim();
Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Completion.AddPlaceholderChunk("parameter");
Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
};
Completion.AddChunk(CodeCompletionString::CK_RightParen);
}
Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
Completion.AddChunk(CodeCompletionString::CK_LeftBrace);
Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Completion.AddPlaceholderChunk("body");
Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Completion.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Completion.TakeString());
}
void Sema::CodeCompleteExpression(Scope *S,
const CodeCompleteExpressionData &Data) {
ResultBuilder Results(
*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext(
Data.IsParenthesized
? CodeCompletionContext::CCC_ParenthesizedExpression
: CodeCompletionContext::CCC_Expression,
Data.PreferredType));
auto PCC =
Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
if (Data.ObjCCollection)
Results.setFilter(&ResultBuilder::IsObjCCollection);
else if (Data.IntegralConstantExpression)
Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
else if (WantTypesInContext(PCC, getLangOpts()))
Results.setFilter(&ResultBuilder::IsOrdinaryName);
else
Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
if (!Data.PreferredType.isNull())
Results.setPreferredType(Data.PreferredType.getNonReferenceType());
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->loadExternal());
Results.EnterNewScope();
AddOrdinaryNameResults(PCC, S, *this, Results);
Results.ExitScope();
bool PreferredTypeIsPointer = false;
if (!Data.PreferredType.isNull()) {
PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
Data.PreferredType->isMemberPointerType() ||
Data.PreferredType->isBlockPointerType();
if (Data.PreferredType->isEnumeralType()) {
EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl();
if (auto *Def = Enum->getDefinition())
Enum = Def;
AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators());
}
}
if (S->getFnParent() && !Data.ObjCCollection &&
!Data.IntegralConstantExpression)
AddPrettyFunctionResults(getLangOpts(), Results);
if (CodeCompleter->includeMacros())
AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false,
PreferredTypeIsPointer);
if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) {
if (const FunctionProtoType *F =
TryDeconstructFunctionLike(Data.PreferredType))
AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts());
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType,
bool IsParenthesized) {
return CodeCompleteExpression(
S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
}
void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E,
QualType PreferredType) {
if (E.isInvalid())
CodeCompleteExpression(S, PreferredType);
else if (getLangOpts().ObjC)
CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
}
typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet;
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;
}
static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
CodeCompletionBuilder &Builder,
const NamedDecl *BD,
const FunctionTypeLoc &BlockLoc,
const FunctionProtoTypeLoc &BlockProtoLoc) {
Builder.AddResultTypeChunk(
GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
Policy, Builder.getAllocator()));
AddTypedNameChunk(Context, Policy, BD, Builder);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
Builder.AddPlaceholderChunk("...");
} else {
for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
if (I)
Builder.AddChunk(CodeCompletionString::CK_Comma);
std::string PlaceholderStr =
FormatFunctionParameter(Policy, BlockLoc.getParam(I));
if (I == N - 1 && BlockProtoLoc &&
BlockProtoLoc.getTypePtr()->isVariadic())
PlaceholderStr += ", ...";
Builder.AddPlaceholderChunk(
Builder.getAllocator().CopyString(PlaceholderStr));
}
}
Builder.AddChunk(CodeCompletionString::CK_RightParen);
}
static void
AddObjCProperties(const CodeCompletionContext &CCContext,
ObjCContainerDecl *Container, bool AllowCategories,
bool AllowNullaryMethods, DeclContext *CurContext,
AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
bool IsBaseExprStatement = false,
bool IsClassProperty = false, bool InOriginalClass = true) {
typedef CodeCompletionResult Result;
Container = getContainerDef(Container);
const auto AddProperty = [&](const ObjCPropertyDecl *P) {
if (!AddedProperties.insert(P->getIdentifier()).second)
return;
if (!P->getType().getTypePtr()->isBlockPointerType() ||
!IsBaseExprStatement) {
Result R = Result(P, Results.getBasePriority(P), nullptr);
if (!InOriginalClass)
setInBaseClass(R);
Results.MaybeAddResult(R, CurContext);
return;
}
FunctionTypeLoc BlockLoc;
FunctionProtoTypeLoc BlockProtoLoc;
findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
BlockProtoLoc);
if (!BlockLoc) {
Result R = Result(P, Results.getBasePriority(P), nullptr);
if (!InOriginalClass)
setInBaseClass(R);
Results.MaybeAddResult(R, CurContext);
return;
}
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
AddObjCBlockCall(Container->getASTContext(),
getCompletionPrintingPolicy(Results.getSema()), Builder, P,
BlockLoc, BlockProtoLoc);
Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
if (!InOriginalClass)
setInBaseClass(R);
Results.MaybeAddResult(R, CurContext);
if (!P->isReadOnly()) {
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
AddResultTypeChunk(Container->getASTContext(),
getCompletionPrintingPolicy(Results.getSema()), P,
CCContext.getBaseType(), Builder);
Builder.AddTypedTextChunk(
Results.getAllocator().CopyString(P->getName()));
Builder.AddChunk(CodeCompletionString::CK_Equal);
std::string PlaceholderStr = formatBlockPlaceholder(
getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
BlockProtoLoc, true);
Builder.AddPlaceholderChunk(
Builder.getAllocator().CopyString(PlaceholderStr));
Result R =
Result(Builder.TakeString(), P,
Results.getBasePriority(P) +
(BlockLoc.getTypePtr()->getReturnType()->isVoidType()
? CCD_BlockPropertySetter
: -CCD_BlockPropertySetter));
if (!InOriginalClass)
setInBaseClass(R);
Results.MaybeAddResult(R, CurContext);
}
};
if (IsClassProperty) {
for (const auto *P : Container->class_properties())
AddProperty(P);
} else {
for (const auto *P : Container->instance_properties())
AddProperty(P);
}
if (AllowNullaryMethods) {
ASTContext &Context = Container->getASTContext();
PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
const auto AddMethod = [&](const ObjCMethodDecl *M) {
IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
if (!Name)
return;
if (!AddedProperties.insert(Name).second)
return;
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
Builder.AddTypedTextChunk(
Results.getAllocator().CopyString(Name->getName()));
Result R = Result(Builder.TakeString(), M,
CCP_MemberDeclaration + CCD_MethodAsProperty);
if (!InOriginalClass)
setInBaseClass(R);
Results.MaybeAddResult(R, CurContext);
};
if (IsClassProperty) {
for (const auto *M : Container->methods()) {
if (!M->getSelector().isUnarySelector() ||
M->getReturnType()->isVoidType() || M->isInstanceMethod())
continue;
AddMethod(M);
}
} else {
for (auto *M : Container->methods()) {
if (M->getSelector().isUnarySelector())
AddMethod(M);
}
}
}
if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
for (auto *P : Protocol->protocols())
AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
CurContext, AddedProperties, Results,
IsBaseExprStatement, IsClassProperty,
false);
} else if (ObjCInterfaceDecl *IFace =
dyn_cast<ObjCInterfaceDecl>(Container)) {
if (AllowCategories) {
for (auto *Cat : IFace->known_categories())
AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
CurContext, AddedProperties, Results,
IsBaseExprStatement, IsClassProperty,
InOriginalClass);
}
for (auto *I : IFace->all_referenced_protocols())
AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
CurContext, AddedProperties, Results,
IsBaseExprStatement, IsClassProperty,
false);
if (IFace->getSuperClass())
AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
AllowNullaryMethods, CurContext, AddedProperties,
Results, IsBaseExprStatement, IsClassProperty,
false);
} else if (const auto *Category =
dyn_cast<ObjCCategoryDecl>(Container)) {
for (auto *P : Category->protocols())
AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
CurContext, AddedProperties, Results,
IsBaseExprStatement, IsClassProperty,
false);
}
}
static void AddRecordMembersCompletionResults(
Sema &SemaRef, ResultBuilder &Results, Scope *S, QualType BaseType,
ExprValueKind BaseKind, RecordDecl *RD, Optional<FixItHint> AccessOpFixIt) {
Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind);
Results.allowNestedNameSpecifiers();
std::vector<FixItHint> FixIts;
if (AccessOpFixIt)
FixIts.emplace_back(*AccessOpFixIt);
CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
SemaRef.CodeCompleter->includeGlobals(),
true,
SemaRef.CodeCompleter->loadExternal());
if (SemaRef.getLangOpts().CPlusPlus) {
if (!Results.empty()) {
bool IsDependent = BaseType->isDependentType();
if (!IsDependent) {
for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
if (DeclContext *Ctx = DepScope->getEntity()) {
IsDependent = Ctx->isDependentContext();
break;
}
}
if (IsDependent)
Results.AddResult(CodeCompletionResult("template"));
}
}
}
static RecordDecl *getAsRecordDecl(const QualType BaseType) {
if (auto *RD = BaseType->getAsRecordDecl()) {
if (const auto *CTSD =
llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
}
return RD;
}
if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
TST->getTemplateName().getAsTemplateDecl())) {
return TD->getTemplatedDecl();
}
}
return nullptr;
}
namespace {
class ConceptInfo {
public:
struct Member {
const IdentifierInfo *Name = nullptr;
llvm::Optional<SmallVector<QualType, 1>> ArgTypes;
enum AccessOperator {
Colons,
Arrow,
Dot,
} Operator = Dot;
const TypeConstraint *ResultType = nullptr;
CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc,
CodeCompletionTUInfo &Info) const {
CodeCompletionBuilder B(Alloc, Info);
if (ResultType) {
std::string AsString;
{
llvm::raw_string_ostream OS(AsString);
QualType ExactType = deduceType(*ResultType);
if (!ExactType.isNull())
ExactType.print(OS, getCompletionPrintingPolicy(S));
else
ResultType->print(OS, getCompletionPrintingPolicy(S));
}
B.AddResultTypeChunk(Alloc.CopyString(AsString));
}
B.AddTypedTextChunk(Alloc.CopyString(Name->getName()));
if (ArgTypes) {
B.AddChunk(clang::CodeCompletionString::CK_LeftParen);
bool First = true;
for (QualType Arg : *ArgTypes) {
if (First)
First = false;
else {
B.AddChunk(clang::CodeCompletionString::CK_Comma);
B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
}
B.AddPlaceholderChunk(Alloc.CopyString(
Arg.getAsString(getCompletionPrintingPolicy(S))));
}
B.AddChunk(clang::CodeCompletionString::CK_RightParen);
}
return B.TakeString();
}
};
ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) {
auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S);
for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity))
believe(E, &BaseType);
}
std::vector<Member> members() {
std::vector<Member> Results;
for (const auto &E : this->Results)
Results.push_back(E.second);
llvm::sort(Results, [](const Member &L, const Member &R) {
return L.Name->getName() < R.Name->getName();
});
return Results;
}
private:
void believe(const Expr *E, const TemplateTypeParmType *T) {
if (!E || !T)
return;
if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) {
ConceptDecl *CD = CSE->getNamedConcept();
TemplateParameterList *Params = CD->getTemplateParameters();
unsigned Index = 0;
for (const auto &Arg : CSE->getTemplateArguments()) {
if (Index >= Params->size())
break; if (isApprox(Arg, T)) {
auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index));
if (!TTPD)
continue;
auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl());
believe(CD->getConstraintExpr(), TT);
}
++Index;
}
} else if (auto *BO = dyn_cast<BinaryOperator>(E)) {
if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
believe(BO->getLHS(), T);
believe(BO->getRHS(), T);
}
} else if (auto *RE = dyn_cast<RequiresExpr>(E)) {
for (const concepts::Requirement *Req : RE->getRequirements()) {
if (!Req->isDependent())
continue;
if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) {
QualType AssertedType = TR->getType()->getType();
ValidVisitor(this, T).TraverseType(AssertedType);
} else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
ValidVisitor Visitor(this, T);
if (ER->getReturnTypeRequirement().isTypeConstraint()) {
Visitor.OuterType =
ER->getReturnTypeRequirement().getTypeConstraint();
Visitor.OuterExpr = ER->getExpr();
}
Visitor.TraverseStmt(ER->getExpr());
} else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) {
believe(NR->getConstraintExpr(), T);
}
}
}
}
class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> {
ConceptInfo *Outer;
const TemplateTypeParmType *T;
CallExpr *Caller = nullptr;
Expr *Callee = nullptr;
public:
Expr *OuterExpr = nullptr;
const TypeConstraint *OuterType = nullptr;
ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T)
: Outer(Outer), T(T) {
assert(T);
}
bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
const Type *Base = E->getBaseType().getTypePtr();
bool IsArrow = E->isArrow();
if (Base->isPointerType() && IsArrow) {
IsArrow = false;
Base = Base->getPointeeType().getTypePtr();
}
if (isApprox(Base, T))
addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot);
return true;
}
bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T))
addValue(E, E->getDeclName(), Member::Colons);
return true;
}
bool VisitDependentNameType(DependentNameType *DNT) {
const auto *Q = DNT->getQualifier();
if (Q && isApprox(Q->getAsType(), T))
addType(DNT->getIdentifier());
return true;
}
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) {
if (NNSL) {
NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier();
const auto *Q = NNS->getPrefix();
if (Q && isApprox(Q->getAsType(), T))
addType(NNS->getAsIdentifier());
}
return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL);
}
bool VisitCallExpr(CallExpr *CE) {
Caller = CE;
Callee = CE->getCallee();
return true;
}
private:
void addResult(Member &&M) {
auto R = Outer->Results.try_emplace(M.Name);
Member &O = R.first->second;
if ( R.second ||
std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr,
M.Operator) > std::make_tuple(O.ArgTypes.has_value(),
O.ResultType != nullptr,
O.Operator))
O = std::move(M);
}
void addType(const IdentifierInfo *Name) {
if (!Name)
return;
Member M;
M.Name = Name;
M.Operator = Member::Colons;
addResult(std::move(M));
}
void addValue(Expr *E, DeclarationName Name,
Member::AccessOperator Operator) {
if (!Name.isIdentifier())
return;
Member Result;
Result.Name = Name.getAsIdentifierInfo();
Result.Operator = Operator;
if (Caller != nullptr && Callee == E) {
Result.ArgTypes.emplace();
for (const auto *Arg : Caller->arguments())
Result.ArgTypes->push_back(Arg->getType());
if (Caller == OuterExpr) {
Result.ResultType = OuterType;
}
} else {
if (E == OuterExpr)
Result.ResultType = OuterType;
}
addResult(std::move(Result));
}
};
static bool isApprox(const TemplateArgument &Arg, const Type *T) {
return Arg.getKind() == TemplateArgument::Type &&
isApprox(Arg.getAsType().getTypePtr(), T);
}
static bool isApprox(const Type *T1, const Type *T2) {
return T1 && T2 &&
T1->getCanonicalTypeUnqualified() ==
T2->getCanonicalTypeUnqualified();
}
static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D,
Scope *S) {
if (D == nullptr)
return nullptr;
Scope *Inner = nullptr;
while (S) {
if (S->isTemplateParamScope() && S->isDeclScope(D))
return Inner ? Inner->getEntity() : nullptr;
Inner = S;
S = S->getParent();
}
return nullptr;
}
static SmallVector<const Expr *, 1>
constraintsForTemplatedEntity(DeclContext *DC) {
SmallVector<const Expr *, 1> Result;
if (DC == nullptr)
return Result;
if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate())
TD->getAssociatedConstraints(Result);
if (const auto *CTPSD =
dyn_cast<ClassTemplatePartialSpecializationDecl>(DC))
CTPSD->getAssociatedConstraints(Result);
if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC))
VTPSD->getAssociatedConstraints(Result);
return Result;
}
static QualType deduceType(const TypeConstraint &T) {
DeclarationName DN = T.getNamedConcept()->getDeclName();
if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as"))
if (const auto *Args = T.getTemplateArgsAsWritten())
if (Args->getNumTemplateArgs() == 1) {
const auto &Arg = Args->arguments().front().getArgument();
if (Arg.getKind() == TemplateArgument::Type)
return Arg.getAsType();
}
return {};
}
llvm::DenseMap<const IdentifierInfo *, Member> Results;
};
QualType getApproximateType(const Expr *E) {
QualType Unresolved = E->getType();
if (Unresolved.isNull() ||
!Unresolved->isSpecificBuiltinType(BuiltinType::Dependent))
return Unresolved;
E = E->IgnoreParens();
if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) {
QualType Callee = getApproximateType(CE->getCallee());
if (Callee.isNull() ||
Callee->isSpecificPlaceholderType(BuiltinType::BoundMember))
Callee = Expr::findBoundMemberType(CE->getCallee());
if (Callee.isNull())
return Unresolved;
if (const auto *FnTypePtr = Callee->getAs<PointerType>()) {
Callee = FnTypePtr->getPointeeType();
} else if (const auto *BPT = Callee->getAs<BlockPointerType>()) {
Callee = BPT->getPointeeType();
}
if (const FunctionType *FnType = Callee->getAs<FunctionType>())
return FnType->getReturnType().getNonReferenceType();
if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) {
const Type *Common = nullptr;
for (const auto *D : OE->decls()) {
QualType ReturnType;
if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
ReturnType = FD->getReturnType();
else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D))
ReturnType = FTD->getTemplatedDecl()->getReturnType();
if (ReturnType.isNull())
continue;
const Type *Candidate =
ReturnType.getNonReferenceType().getCanonicalType().getTypePtr();
if (Common && Common != Candidate)
return Unresolved; Common = Candidate;
}
if (Common != nullptr)
return QualType(Common, 0);
}
}
if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) {
QualType Base = CDSME->isImplicitAccess()
? CDSME->getBaseType()
: getApproximateType(CDSME->getBase());
if (CDSME->isArrow() && !Base.isNull())
Base = Base->getPointeeType(); auto *RD =
Base.isNull()
? nullptr
: llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base));
if (RD && RD->isCompleteDefinition()) {
for (const auto *Member : RD->lookupDependentName(
CDSME->getMember(), [](const NamedDecl *Member) {
return llvm::isa<ValueDecl>(Member);
})) {
return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType();
}
}
}
return Unresolved;
}
Expr *unwrapParenList(Expr *Base) {
if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) {
if (PLE->getNumExprs() == 0)
return nullptr;
Base = PLE->getExpr(PLE->getNumExprs() - 1);
}
return Base;
}
}
void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
Expr *OtherOpBase,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement,
QualType PreferredType) {
Base = unwrapParenList(Base);
OtherOpBase = unwrapParenList(OtherOpBase);
if (!Base || !CodeCompleter)
return;
ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
if (ConvertedBase.isInvalid())
return;
QualType ConvertedBaseType = getApproximateType(ConvertedBase.get());
enum CodeCompletionContext::Kind contextKind;
if (IsArrow) {
if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
ConvertedBaseType = Ptr->getPointeeType();
}
if (IsArrow) {
contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
} else {
if (ConvertedBaseType->isObjCObjectPointerType() ||
ConvertedBaseType->isObjCObjectOrInterfaceType()) {
contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
} else {
contextKind = CodeCompletionContext::CCC_DotMemberAccess;
}
}
CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
CCContext.setPreferredType(PreferredType);
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(), CCContext,
&ResultBuilder::IsMember);
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 = getApproximateType(Base);
if (BaseType.isNull())
return false;
ExprValueKind BaseKind = Base->getValueKind();
if (IsArrow) {
if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
BaseType = Ptr->getPointeeType();
BaseKind = VK_LValue;
} else if (BaseType->isObjCObjectPointerType() ||
BaseType->isTemplateTypeParmType()) {
} else {
return false;
}
}
if (RecordDecl *RD = getAsRecordDecl(BaseType)) {
AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
RD, std::move(AccessOpFixIt));
} else if (const auto *TTPT =
dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) {
auto Operator =
IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot;
for (const auto &R : ConceptInfo(*TTPT, S).members()) {
if (R.Operator != Operator)
continue;
CodeCompletionResult Result(
R.render(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo()));
if (AccessOpFixIt)
Result.FixIts.push_back(*AccessOpFixIt);
Results.AddResult(std::move(Result));
}
} else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
if (AccessOpFixIt) {
return false;
}
AddedPropertiesSet AddedProperties;
if (const ObjCObjectPointerType *ObjCPtr =
BaseType->getAsObjCInterfacePointerType()) {
assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
true, CurContext,
AddedProperties, Results, IsBaseExprStatement);
}
for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals())
AddObjCProperties(CCContext, I, true, true,
CurContext, AddedProperties, Results,
IsBaseExprStatement, false,
false);
} else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
(!IsArrow && BaseType->isObjCObjectType())) {
if (AccessOpFixIt) {
return false;
}
ObjCInterfaceDecl *Class = nullptr;
if (const ObjCObjectPointerType *ObjCPtr =
BaseType->getAs<ObjCObjectPointerType>())
Class = ObjCPtr->getInterfaceDecl();
else
Class = BaseType->castAs<ObjCObjectType>()->getInterface();
if (Class) {
CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
Results.setFilter(&ResultBuilder::IsObjCIvar);
LookupVisibleDecls(
Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
false, CodeCompleter->loadExternal());
}
}
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 ? "." : "->"));
}
Results.ExitScope();
if (!CompletionSucceded)
return;
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
IdentifierInfo &ClassName,
SourceLocation ClassNameLoc,
bool IsBaseExprStatement) {
IdentifierInfo *ClassNamePtr = &ClassName;
ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
if (!IFace)
return;
CodeCompletionContext CCContext(
CodeCompletionContext::CCC_ObjCPropertyAccess);
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(), CCContext,
&ResultBuilder::IsMember);
Results.EnterNewScope();
AddedPropertiesSet AddedProperties;
AddObjCProperties(CCContext, IFace, true,
true, CurContext, AddedProperties,
Results, IsBaseExprStatement,
true);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
if (!CodeCompleter)
return;
ResultBuilder::LookupFilter Filter = nullptr;
enum CodeCompletionContext::Kind ContextKind =
CodeCompletionContext::CCC_Other;
switch ((DeclSpec::TST)TagSpec) {
case DeclSpec::TST_enum:
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);
Results.setFilter(Filter);
LookupVisibleDecls(S, LookupTagName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
if (CodeCompleter->includeGlobals()) {
Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
const LangOptions &LangOpts) {
if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
Results.AddResult("const");
if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
Results.AddResult("volatile");
if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
Results.AddResult("restrict");
if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
Results.AddResult("_Atomic");
if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
Results.AddResult("__unaligned");
}
void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_TypeQualifiers);
Results.EnterNewScope();
AddTypeQualifierResults(DS, Results, LangOpts);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
const VirtSpecifiers *VS) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_TypeQualifiers);
Results.EnterNewScope();
AddTypeQualifierResults(DS, Results, LangOpts);
if (LangOpts.CPlusPlus11) {
Results.AddResult("noexcept");
if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() &&
!D.isStaticMember()) {
if (!VS || !VS->isFinalSpecified())
Results.AddResult("final");
if (!VS || !VS->isOverrideSpecified())
Results.AddResult("override");
}
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteBracketDeclarator(Scope *S) {
CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
}
void Sema::CodeCompleteCase(Scope *S) {
if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
return;
SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer();
if (!Switch->getCond())
return;
QualType type = Switch->getCond()->IgnoreImplicit()->getType();
if (!type->isEnumeralType()) {
CodeCompleteExpressionData Data(type);
Data.IntegralConstantExpression = true;
CodeCompleteExpression(S, Data);
return;
}
EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
if (EnumDecl *Def = Enum->getDefinition())
Enum = Def;
CoveredEnumerators Enumerators;
for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
SC = SC->getNextSwitchCase()) {
CaseStmt *Case = dyn_cast<CaseStmt>(SC);
if (!Case)
continue;
Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
if (auto *Enumerator =
dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
Enumerators.Seen.insert(Enumerator);
Enumerators.SuggestedQualifier = DRE->getQualifier();
}
}
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Expression);
AddEnumerators(Results, Context, Enum, CurContext, Enumerators);
if (CodeCompleter->includeMacros()) {
AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static bool anyNullArguments(ArrayRef<Expr *> Args) {
if (Args.size() && !Args.data())
return true;
for (unsigned I = 0; I != Args.size(); ++I)
if (!Args[I])
return true;
return false;
}
typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
static void mergeCandidatesWithResults(
Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) {
llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
const OverloadCandidate &Y) {
return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
CandidateSet.getKind());
});
for (OverloadCandidate &Candidate : CandidateSet) {
if (Candidate.Function) {
if (Candidate.Function->isDeleted())
continue;
if (shouldEnforceArgLimit(true,
Candidate.Function) &&
Candidate.Function->getNumParams() <= ArgSize &&
ArgSize > 0)
continue;
}
if (Candidate.Viable)
Results.push_back(ResultCandidate(Candidate.Function));
}
}
static QualType getParamType(Sema &SemaRef,
ArrayRef<ResultCandidate> Candidates, unsigned N) {
QualType ParamType;
for (auto &Candidate : Candidates) {
QualType CandidateParamType = Candidate.getParamType(N);
if (CandidateParamType.isNull())
continue;
if (ParamType.isNull()) {
ParamType = CandidateParamType;
continue;
}
if (!SemaRef.Context.hasSameUnqualifiedType(
ParamType.getNonReferenceType(),
CandidateParamType.getNonReferenceType()))
return QualType();
}
return ParamType;
}
static QualType
ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates,
unsigned CurrentArg, SourceLocation OpenParLoc,
bool Braced) {
if (Candidates.empty())
return QualType();
if (SemaRef.getPreprocessor().isCodeCompletionReached())
SemaRef.CodeCompleter->ProcessOverloadCandidates(
SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc,
Braced);
return getParamType(SemaRef, Candidates, CurrentArg);
}
static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
TypeLoc Target;
if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) {
Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc();
} else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) {
const auto *D = DR->getDecl();
if (const auto *const VD = dyn_cast<VarDecl>(D)) {
Target = VD->getTypeSourceInfo()->getTypeLoc();
}
}
if (!Target)
return {};
if (auto P = Target.getAs<PointerTypeLoc>()) {
Target = P.getPointeeLoc();
}
if (auto P = Target.getAs<ParenTypeLoc>()) {
Target = P.getInnerLoc();
}
if (auto F = Target.getAs<FunctionProtoTypeLoc>()) {
return F;
}
return {};
}
QualType Sema::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
SourceLocation OpenParLoc) {
Fn = unwrapParenList(Fn);
if (!CodeCompleter || !Fn)
return QualType();
if (Fn->isTypeDependent() || anyNullArguments(Args))
return QualType();
auto ArgsWithoutDependentTypes =
Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); });
SmallVector<ResultCandidate, 8> Results;
Expr *NakedFn = Fn->IgnoreParenCasts();
SourceLocation Loc = Fn->getExprLoc();
OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) {
AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, CandidateSet,
true);
} else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
if (UME->hasExplicitTemplateArgs()) {
UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
TemplateArgs = &TemplateArgsBuffer;
}
SmallVector<Expr *, 12> ArgExprs(
1, UME->isImplicitAccess() ? nullptr : UME->getBase());
ArgExprs.append(ArgsWithoutDependentTypes.begin(),
ArgsWithoutDependentTypes.end());
UnresolvedSet<8> Decls;
Decls.append(UME->decls_begin(), UME->decls_end());
const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
false,
true, FirstArgumentIsBase);
} else {
FunctionDecl *FD = nullptr;
if (auto *MCE = dyn_cast<MemberExpr>(NakedFn))
FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn))
FD = dyn_cast<FunctionDecl>(DRE->getDecl());
if (FD) { if (!getLangOpts().CPlusPlus ||
!FD->getType()->getAs<FunctionProtoType>())
Results.push_back(ResultCandidate(FD));
else
AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
ArgsWithoutDependentTypes, CandidateSet,
false,
true);
} else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
if (isCompleteType(Loc, NakedFn->getType())) {
DeclarationName OpName =
Context.DeclarationNames.getCXXOperatorName(OO_Call);
LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
LookupQualifiedName(R, DC);
R.suppressDiagnostics();
SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
ArgExprs.append(ArgsWithoutDependentTypes.begin(),
ArgsWithoutDependentTypes.end());
AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
nullptr,
false,
true);
}
} else {
FunctionProtoTypeLoc P = GetPrototypeLoc(NakedFn);
QualType T = NakedFn->getType();
if (!T->getPointeeType().isNull())
T = T->getPointeeType();
if (auto FP = T->getAs<FunctionProtoType>()) {
if (!TooManyArguments(FP->getNumParams(),
ArgsWithoutDependentTypes.size(),
true) ||
FP->isVariadic()) {
if (P) {
Results.push_back(ResultCandidate(P));
} else {
Results.push_back(ResultCandidate(FP));
}
}
} else if (auto FT = T->getAs<FunctionType>())
Results.push_back(ResultCandidate(FT));
}
}
mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
QualType ParamType = ProduceSignatureHelp(*this, Results, Args.size(),
OpenParLoc, false);
return !CandidateSet.empty() ? ParamType : QualType();
}
static llvm::Optional<unsigned>
getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate,
ArrayRef<Expr *> Args) {
static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max();
assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate);
IdentifierInfo *DesignatedFieldName = nullptr;
unsigned ArgsAfterDesignator = 0;
for (const Expr *Arg : Args) {
if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) {
if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) {
DesignatedFieldName = DIE->getDesignator(0)->getFieldName();
ArgsAfterDesignator = 0;
} else {
return Invalid; }
} else if (isa<DesignatedInitUpdateExpr>(Arg)) {
return Invalid; } else {
++ArgsAfterDesignator;
}
}
if (!DesignatedFieldName)
return llvm::None;
unsigned DesignatedIndex = 0;
const FieldDecl *DesignatedField = nullptr;
for (const auto *Field : Aggregate.getAggregate()->fields()) {
if (Field->getIdentifier() == DesignatedFieldName) {
DesignatedField = Field;
break;
}
++DesignatedIndex;
}
if (!DesignatedField)
return Invalid;
unsigned AggregateSize = Aggregate.getNumParams();
while (DesignatedIndex < AggregateSize &&
Aggregate.getParamDecl(DesignatedIndex) != DesignatedField)
++DesignatedIndex;
return DesignatedIndex + ArgsAfterDesignator + 1;
}
QualType Sema::ProduceConstructorSignatureHelp(QualType Type,
SourceLocation Loc,
ArrayRef<Expr *> Args,
SourceLocation OpenParLoc,
bool Braced) {
if (!CodeCompleter)
return QualType();
SmallVector<ResultCandidate, 8> Results;
RecordDecl *RD =
isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr;
if (!RD)
return Type;
CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD);
if (Braced && !RD->isUnion() &&
(!LangOpts.CPlusPlus || (CRD && CRD->isAggregate()))) {
ResultCandidate AggregateSig(RD);
unsigned AggregateSize = AggregateSig.getNumParams();
if (auto NextIndex =
getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) {
if (*NextIndex >= AggregateSize)
return Type;
Results.push_back(AggregateSig);
return ProduceSignatureHelp(*this, Results, *NextIndex, OpenParLoc,
Braced);
}
if (Args.size() < AggregateSize)
Results.push_back(AggregateSig);
}
if (CRD) {
OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
for (NamedDecl *C : LookupConstructors(CRD)) {
if (auto *FD = dyn_cast<FunctionDecl>(C)) {
if (Braced && LangOpts.CPlusPlus && isInitListConstructor(FD))
continue;
AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args,
CandidateSet,
false,
true,
true);
} else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) {
if (Braced && LangOpts.CPlusPlus &&
isInitListConstructor(FTD->getTemplatedDecl()))
continue;
AddTemplateOverloadCandidate(
FTD, DeclAccessPair::make(FTD, C->getAccess()),
nullptr, Args, CandidateSet,
false,
true);
}
}
mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
}
return ProduceSignatureHelp(*this, Results, Args.size(), OpenParLoc, Braced);
}
QualType Sema::ProduceCtorInitMemberSignatureHelp(
Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
bool Braced) {
if (!CodeCompleter)
return QualType();
CXXConstructorDecl *Constructor =
dyn_cast<CXXConstructorDecl>(ConstructorDecl);
if (!Constructor)
return QualType();
if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl(
Constructor->getParent(), SS, TemplateTypeTy, II))
return ProduceConstructorSignatureHelp(MemberDecl->getType(),
MemberDecl->getLocation(), ArgExprs,
OpenParLoc, Braced);
return QualType();
}
static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg,
unsigned Index,
const TemplateParameterList &Params) {
const NamedDecl *Param;
if (Index < Params.size())
Param = Params.getParam(Index);
else if (Params.hasParameterPack())
Param = Params.asArray().back();
else
return false;
switch (Arg.getKind()) {
case ParsedTemplateArgument::Type:
return llvm::isa<TemplateTypeParmDecl>(Param); case ParsedTemplateArgument::NonType:
return llvm::isa<NonTypeTemplateParmDecl>(Param); case ParsedTemplateArgument::Template:
return llvm::isa<TemplateTemplateParmDecl>(Param); }
llvm_unreachable("Unhandled switch case");
}
QualType Sema::ProduceTemplateArgumentSignatureHelp(
TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args,
SourceLocation LAngleLoc) {
if (!CodeCompleter || !ParsedTemplate)
return QualType();
SmallVector<ResultCandidate, 8> Results;
auto Consider = [&](const TemplateDecl *TD) {
bool Matches = true;
for (unsigned I = 0; I < Args.size(); ++I) {
if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) {
Matches = false;
break;
}
}
if (Matches)
Results.emplace_back(TD);
};
TemplateName Template = ParsedTemplate.get();
if (const auto *TD = Template.getAsTemplateDecl()) {
Consider(TD);
} else if (const auto *OTS = Template.getAsOverloadedTemplate()) {
for (const NamedDecl *ND : *OTS)
if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND))
Consider(TD);
}
return ProduceSignatureHelp(*this, Results, Args.size(), LAngleLoc,
false);
}
static QualType getDesignatedType(QualType BaseType, const Designation &Desig) {
for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) {
if (BaseType.isNull())
break;
QualType NextType;
const auto &D = Desig.getDesignator(I);
if (D.isArrayDesignator() || D.isArrayRangeDesignator()) {
if (BaseType->isArrayType())
NextType = BaseType->getAsArrayTypeUnsafe()->getElementType();
} else {
assert(D.isFieldDesignator());
auto *RD = getAsRecordDecl(BaseType);
if (RD && RD->isCompleteDefinition()) {
for (const auto *Member : RD->lookup(D.getField()))
if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) {
NextType = FD->getType();
break;
}
}
}
BaseType = NextType;
}
return BaseType;
}
void Sema::CodeCompleteDesignator(QualType BaseType,
llvm::ArrayRef<Expr *> InitExprs,
const Designation &D) {
BaseType = getDesignatedType(BaseType, D);
if (BaseType.isNull())
return;
const auto *RD = getAsRecordDecl(BaseType);
if (!RD || RD->fields().empty())
return;
CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess,
BaseType);
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(), CCC);
Results.EnterNewScope();
for (const Decl *D : RD->decls()) {
const FieldDecl *FD;
if (auto *IFD = dyn_cast<IndirectFieldDecl>(D))
FD = IFD->getAnonField();
else if (auto *DFD = dyn_cast<FieldDecl>(D))
FD = DFD;
else
continue;
ResultBuilder::Result Result(FD, Results.getBasePriority(FD));
Results.AddResult(Result, CurContext, nullptr);
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
if (!VD) {
CodeCompleteOrdinaryName(S, PCC_Expression);
return;
}
CodeCompleteExpressionData Data;
Data.PreferredType = VD->getType();
Data.IgnoreDecls.push_back(VD);
CodeCompleteExpression(S, Data);
}
void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
mapCodeCompletionContext(*this, PCC_Statement));
Results.setFilter(&ResultBuilder::IsOrdinaryName);
Results.EnterNewScope();
CodeCompletionDeclConsumer Consumer(Results, CurContext);
LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
auto AddElseBodyPattern = [&] {
if (IsBracedThen) {
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
} else {
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("statement");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
}
};
Builder.AddTypedTextChunk("else");
if (Results.includeCodePatterns())
AddElseBodyPattern();
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("else if");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
if (getLangOpts().CPlusPlus)
Builder.AddPlaceholderChunk("condition");
else
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
if (Results.includeCodePatterns()) {
AddElseBodyPattern();
}
Results.AddResult(Builder.TakeString());
Results.ExitScope();
if (S->getFnParent())
AddPrettyFunctionResults(getLangOpts(), Results);
if (CodeCompleter->includeMacros())
AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
bool EnteringContext,
bool IsUsingDeclaration, QualType BaseType,
QualType PreferredType) {
if (SS.isEmpty() || !CodeCompleter)
return;
CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType);
CC.setIsUsingDeclaration(IsUsingDeclaration);
CC.setCXXScopeSpecifier(SS);
if (SS.isInvalid()) {
ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(), CC);
if (!PreferredType.isNull())
DummyResults.setPreferredType(PreferredType);
if (S->getEntity()) {
CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(),
BaseType);
LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
false,
false);
}
HandleCodeCompleteResults(this, CodeCompleter,
DummyResults.getCompletionContext(), nullptr, 0);
return;
}
DeclContext *Ctx = computeDeclContext(SS, true);
NestedNameSpecifier *NNS = SS.getScopeRep();
if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) {
if (Ctx == nullptr || RequireCompleteDeclContext(SS, Ctx))
return;
}
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(), CC);
if (!PreferredType.isNull())
Results.setPreferredType(PreferredType);
Results.EnterNewScope();
if (!Results.empty() && NNS->isDependent())
Results.AddResult("template");
if (const auto *TTPT =
dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) {
for (const auto &R : ConceptInfo(*TTPT, S).members()) {
if (R.Operator != ConceptInfo::Member::Colons)
continue;
Results.AddResult(CodeCompletionResult(
R.render(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo())));
}
}
if (Ctx && !EnteringContext)
MaybeAddOverrideCalls(*this, Ctx, Results);
Results.ExitScope();
if (Ctx &&
(CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) {
CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType);
LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
true,
true,
CodeCompleter->loadExternal());
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteUsing(Scope *S) {
if (!CodeCompleter)
return;
CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName);
Context.setIsUsingDeclaration(true);
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(), Context,
&ResultBuilder::IsNestedNameSpecifier);
Results.EnterNewScope();
if (!S->isClassScope())
Results.AddResult(CodeCompletionResult("namespace"));
CodeCompletionDeclConsumer Consumer(Results, CurContext);
LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteUsingDirective(Scope *S) {
if (!CodeCompleter)
return;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Namespace,
&ResultBuilder::IsNamespaceOrAlias);
Results.EnterNewScope();
CodeCompletionDeclConsumer Consumer(Results, CurContext);
LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
Results.ExitScope();
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) {
std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
for (DeclContext::specific_decl_iterator<NamespaceDecl>
NS(Ctx->decls_begin()),
NSEnd(Ctx->decls_end());
NS != NSEnd; ++NS)
OrigToLatest[NS->getOriginalNamespace()] = *NS;
Results.EnterNewScope();
for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
NS = OrigToLatest.begin(),
NSEnd = OrigToLatest.end();
NS != NSEnd; ++NS)
Results.AddResult(
CodeCompletionResult(NS->second, Results.getBasePriority(NS->second),
nullptr),
CurContext, nullptr, false);
Results.ExitScope();
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
if (!CodeCompleter)
return;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Namespace,
&ResultBuilder::IsNamespaceOrAlias);
CodeCompletionDeclConsumer Consumer(Results, CurContext);
LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteOperatorName(Scope *S) {
if (!CodeCompleter)
return;
typedef CodeCompletionResult Result;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Type,
&ResultBuilder::IsType);
Results.EnterNewScope();
#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
if (OO_##Name != OO_Conditional) \
Results.AddResult(Result(Spelling));
#include "clang/Basic/OperatorKinds.def"
Results.allowNestedNameSpecifiers();
CodeCompletionDeclConsumer Consumer(Results, CurContext);
LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
AddTypeSpecifierResults(getLangOpts(), Results);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteConstructorInitializer(
Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) {
if (!ConstructorD)
return;
AdjustDeclIfTemplate(ConstructorD);
auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
if (!Constructor)
return;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Symbol);
Results.EnterNewScope();
llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
if (Initializers[I]->isBaseInitializer())
InitializedBases.insert(Context.getCanonicalType(
QualType(Initializers[I]->getBaseClass(), 0)));
else
InitializedFields.insert(
cast<FieldDecl>(Initializers[I]->getAnyMember()));
}
PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
bool SawLastInitializer = Initializers.empty();
CXXRecordDecl *ClassDecl = Constructor->getParent();
auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) {
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Builder.AddTypedTextChunk(Name);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
if (const auto *Function = dyn_cast<FunctionDecl>(ND))
AddFunctionParameterChunks(PP, Policy, Function, Builder);
else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND))
AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(),
Builder);
Builder.AddChunk(CodeCompletionString::CK_RightParen);
return Builder.TakeString();
};
auto AddDefaultCtorInit = [&](const char *Name, const char *Type,
const NamedDecl *ND) {
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Builder.AddTypedTextChunk(Name);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk(Type);
Builder.AddChunk(CodeCompletionString::CK_RightParen);
if (ND) {
auto CCR = CodeCompletionResult(
Builder.TakeString(), ND,
SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration);
if (isa<FieldDecl>(ND))
CCR.CursorKind = CXCursor_MemberRef;
return Results.AddResult(CCR);
}
return Results.AddResult(CodeCompletionResult(
Builder.TakeString(),
SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration));
};
auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority,
const char *Name, const FieldDecl *FD) {
if (!RD)
return AddDefaultCtorInit(Name,
FD ? Results.getAllocator().CopyString(
FD->getType().getAsString(Policy))
: Name,
FD);
auto Ctors = getConstructors(Context, RD);
if (Ctors.begin() == Ctors.end())
return AddDefaultCtorInit(Name, Name, RD);
for (const NamedDecl *Ctor : Ctors) {
auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority);
CCR.CursorKind = getCursorKindForDecl(Ctor);
Results.AddResult(CCR);
}
};
auto AddBase = [&](const CXXBaseSpecifier &Base) {
const char *BaseName =
Results.getAllocator().CopyString(Base.getType().getAsString(Policy));
const auto *RD = Base.getType()->getAsCXXRecordDecl();
AddCtorsWithName(
RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
BaseName, nullptr);
};
auto AddField = [&](const FieldDecl *FD) {
const char *FieldName =
Results.getAllocator().CopyString(FD->getIdentifier()->getName());
const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
AddCtorsWithName(
RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
FieldName, FD);
};
for (const auto &Base : ClassDecl->bases()) {
if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
.second) {
SawLastInitializer =
!Initializers.empty() && Initializers.back()->isBaseInitializer() &&
Context.hasSameUnqualifiedType(
Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
continue;
}
AddBase(Base);
SawLastInitializer = false;
}
for (const auto &Base : ClassDecl->vbases()) {
if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
.second) {
SawLastInitializer =
!Initializers.empty() && Initializers.back()->isBaseInitializer() &&
Context.hasSameUnqualifiedType(
Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
continue;
}
AddBase(Base);
SawLastInitializer = false;
}
for (auto *Field : ClassDecl->fields()) {
if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
.second) {
SawLastInitializer = !Initializers.empty() &&
Initializers.back()->isAnyMemberInitializer() &&
Initializers.back()->getAnyMember() == Field;
continue;
}
if (!Field->getDeclName())
continue;
AddField(Field);
SawLastInitializer = false;
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static bool isNamespaceScope(Scope *S) {
DeclContext *DC = S->getEntity();
if (!DC)
return false;
return DC->isFileContext();
}
void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
bool AfterAmpersand) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
bool IncludedThis = false;
for (const auto &C : Intro.Captures) {
if (C.Kind == LCK_This) {
IncludedThis = true;
continue;
}
Known.insert(C.Id);
}
for (; S && !isNamespaceScope(S); S = S->getParent()) {
for (const auto *D : S->decls()) {
const auto *Var = dyn_cast<VarDecl>(D);
if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>())
continue;
if (Known.insert(Var->getIdentifier()).second)
Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
CurContext, nullptr, false);
}
}
if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
addThisCompletion(*this, Results);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) {
if (!LangOpts.CPlusPlus11)
return;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
auto ShouldAddDefault = [&D, this]() {
if (!D.isFunctionDeclarator())
return false;
auto &Id = D.getName();
if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName)
return true;
if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName &&
D.getFunctionTypeInfo().NumParams <= 1)
return true;
if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) {
auto Op = Id.OperatorFunctionId.Operator;
if (Op == OverloadedOperatorKind::OO_Equal)
return true;
if (LangOpts.CPlusPlus20 &&
(Op == OverloadedOperatorKind::OO_EqualEqual ||
Op == OverloadedOperatorKind::OO_ExclaimEqual ||
Op == OverloadedOperatorKind::OO_Less ||
Op == OverloadedOperatorKind::OO_LessEqual ||
Op == OverloadedOperatorKind::OO_Greater ||
Op == OverloadedOperatorKind::OO_GreaterEqual ||
Op == OverloadedOperatorKind::OO_Spaceship))
return true;
}
return false;
};
Results.EnterNewScope();
if (ShouldAddDefault())
Results.AddResult("default");
Results.AddResult("delete");
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
#define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
static void AddObjCImplementationResults(const LangOptions &LangOpts,
ResultBuilder &Results, bool NeedAt) {
typedef CodeCompletionResult Result;
Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
if (LangOpts.ObjC) {
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic"));
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("property");
Results.AddResult(Result(Builder.TakeString()));
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;
Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
if (LangOpts.ObjC) {
Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")));
Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")));
Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")));
}
}
static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
typedef CodeCompletionResult Result;
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class"));
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("name");
Results.AddResult(Result(Builder.TakeString()));
if (Results.includeCodePatterns()) {
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface"));
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("class");
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("protocol");
Results.AddResult(Result(Builder.TakeString()));
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation"));
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("class");
Results.AddResult(Result(Builder.TakeString()));
}
Builder.AddTypedTextChunk(
OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias"));
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("alias");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("class");
Results.AddResult(Result(Builder.TakeString()));
if (Results.getSema().getLangOpts().Modules) {
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("module");
Results.AddResult(Result(Builder.TakeString()));
}
}
void Sema::CodeCompleteObjCAtDirective(Scope *S) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
if (isa<ObjCImplDecl>(CurContext))
AddObjCImplementationResults(getLangOpts(), Results, false);
else if (CurContext->isObjCContainer())
AddObjCInterfaceResults(getLangOpts(), Results, false);
else
AddObjCTopLevelResults(Results, false);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
typedef CodeCompletionResult Result;
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
const char *EncodeType = "char[]";
if (Results.getSema().getLangOpts().CPlusPlus ||
Results.getSema().getLangOpts().ConstStrings)
EncodeType = "const char[]";
Builder.AddResultTypeChunk(EncodeType);
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode"));
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("type-name");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("Protocol *");
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("protocol-name");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("SEL");
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector"));
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("selector");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("NSString *");
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\""));
Builder.AddPlaceholderChunk("string");
Builder.AddTextChunk("\"");
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("NSArray *");
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "["));
Builder.AddPlaceholderChunk("objects, ...");
Builder.AddChunk(CodeCompletionString::CK_RightBracket);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("NSDictionary *");
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{"));
Builder.AddPlaceholderChunk("key");
Builder.AddChunk(CodeCompletionString::CK_Colon);
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("object, ...");
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
Builder.AddResultTypeChunk("id");
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Result(Builder.TakeString()));
}
static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
typedef CodeCompletionResult Result;
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
if (Results.includeCodePatterns()) {
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try"));
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Builder.AddTextChunk("@catch");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("parameter");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Builder.AddTextChunk("@finally");
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
}
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw"));
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("expression");
Results.AddResult(Result(Builder.TakeString()));
if (Results.includeCodePatterns()) {
Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized"));
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
Results.AddResult(Result(Builder.TakeString()));
}
}
static void AddObjCVisibilityResults(const LangOptions &LangOpts,
ResultBuilder &Results, bool NeedAt) {
typedef CodeCompletionResult Result;
Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private")));
Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected")));
Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public")));
if (LangOpts.ObjC)
Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package")));
}
void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
AddObjCVisibilityResults(getLangOpts(), Results, false);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCAtStatement(Scope *S) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
AddObjCStatementResults(Results, false);
AddObjCExpressionResults(Results, false);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCAtExpression(Scope *S) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
AddObjCExpressionResults(Results, false);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
if (Attributes & NewFlag)
return true;
Attributes |= NewFlag;
if ((Attributes & ObjCPropertyAttribute::kind_readonly) &&
(Attributes & ObjCPropertyAttribute::kind_readwrite))
return true;
unsigned AssignCopyRetMask =
Attributes &
(ObjCPropertyAttribute::kind_assign |
ObjCPropertyAttribute::kind_unsafe_unretained |
ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain |
ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak);
if (AssignCopyRetMask &&
AssignCopyRetMask != ObjCPropertyAttribute::kind_assign &&
AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained &&
AssignCopyRetMask != ObjCPropertyAttribute::kind_copy &&
AssignCopyRetMask != ObjCPropertyAttribute::kind_retain &&
AssignCopyRetMask != ObjCPropertyAttribute::kind_strong &&
AssignCopyRetMask != ObjCPropertyAttribute::kind_weak)
return true;
return false;
}
void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
if (!CodeCompleter)
return;
unsigned Attributes = ODS.getPropertyAttributes();
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_readonly))
Results.AddResult(CodeCompletionResult("readonly"));
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_assign))
Results.AddResult(CodeCompletionResult("assign"));
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_unsafe_unretained))
Results.AddResult(CodeCompletionResult("unsafe_unretained"));
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_readwrite))
Results.AddResult(CodeCompletionResult("readwrite"));
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_retain))
Results.AddResult(CodeCompletionResult("retain"));
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_strong))
Results.AddResult(CodeCompletionResult("strong"));
if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy))
Results.AddResult(CodeCompletionResult("copy"));
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_nonatomic))
Results.AddResult(CodeCompletionResult("nonatomic"));
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_atomic))
Results.AddResult(CodeCompletionResult("atomic"));
if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_weak))
Results.AddResult(CodeCompletionResult("weak"));
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_setter)) {
CodeCompletionBuilder Setter(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Setter.AddTypedTextChunk("setter");
Setter.AddTextChunk("=");
Setter.AddPlaceholderChunk("method");
Results.AddResult(CodeCompletionResult(Setter.TakeString()));
}
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_getter)) {
CodeCompletionBuilder Getter(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Getter.AddTypedTextChunk("getter");
Getter.AddTextChunk("=");
Getter.AddPlaceholderChunk("method");
Results.AddResult(CodeCompletionResult(Getter.TakeString()));
}
if (!ObjCPropertyFlagConflicts(Attributes,
ObjCPropertyAttribute::kind_nullability)) {
Results.AddResult(CodeCompletionResult("nonnull"));
Results.AddResult(CodeCompletionResult("nullable"));
Results.AddResult(CodeCompletionResult("null_unspecified"));
Results.AddResult(CodeCompletionResult("null_resettable"));
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
enum ObjCMethodKind {
MK_Any, MK_ZeroArgSelector, MK_OneArgSelector };
static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind,
ArrayRef<IdentifierInfo *> SelIdents,
bool AllowSameLength = true) {
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;
}
static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
ObjCMethodKind WantKind,
ArrayRef<IdentifierInfo *> SelIdents,
bool AllowSameLength = true) {
return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
AllowSameLength);
}
typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
static void AddObjCMethods(ObjCContainerDecl *Container,
bool WantInstanceMethods, ObjCMethodKind WantKind,
ArrayRef<IdentifierInfo *> SelIdents,
DeclContext *CurContext,
VisitedSelectorSet &Selectors, bool AllowSameLength,
ResultBuilder &Results, bool InOriginalClass = true,
bool IsRootClass = false) {
typedef CodeCompletionResult Result;
Container = getContainerDef(Container);
ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
for (ObjCMethodDecl *M : Container->methods()) {
if (M->isInstanceMethod() == WantInstanceMethods ||
(IsRootClass && !WantInstanceMethods)) {
if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
continue;
if (!Selectors.insert(M->getSelector()).second)
continue;
Result R = Result(M, Results.getBasePriority(M), nullptr);
R.StartParameter = SelIdents.size();
R.AllParametersAreInformative = (WantKind != MK_Any);
if (!InOriginalClass)
setInBaseClass(R);
Results.MaybeAddResult(R, CurContext);
}
}
if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
if (Protocol->hasDefinition()) {
const ObjCList<ObjCProtocolDecl> &Protocols =
Protocol->getReferencedProtocols();
for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
E = Protocols.end();
I != E; ++I)
AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
Selectors, AllowSameLength, Results, false, IsRootClass);
}
}
if (!IFace || !IFace->hasDefinition())
return;
for (ObjCProtocolDecl *I : IFace->protocols())
AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
Selectors, AllowSameLength, Results, false, IsRootClass);
for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) {
AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
CurContext, Selectors, AllowSameLength, Results,
InOriginalClass, IsRootClass);
const ObjCList<ObjCProtocolDecl> &Protocols =
CatDecl->getReferencedProtocols();
for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
E = Protocols.end();
I != E; ++I)
AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
Selectors, AllowSameLength, Results, false, IsRootClass);
if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
Selectors, AllowSameLength, Results, InOriginalClass,
IsRootClass);
}
if (IFace->getSuperClass())
AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
SelIdents, CurContext, Selectors, AllowSameLength, Results,
false);
if (ObjCImplementationDecl *Impl = IFace->getImplementation())
AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
Selectors, AllowSameLength, Results, InOriginalClass,
IsRootClass);
}
void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
if (!Class) {
if (ObjCCategoryDecl *Category =
dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Class = Category->getClassInterface();
if (!Class)
return;
}
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
VisitedSelectorSet Selectors;
AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
true, Results);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
if (!Class) {
if (ObjCCategoryDecl *Category =
dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
Class = Category->getClassInterface();
if (!Class)
return;
}
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
VisitedSelectorSet Selectors;
AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, Selectors,
true, Results);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
bool IsParameter) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Type);
Results.EnterNewScope();
bool AddedInOut = false;
if ((DS.getObjCDeclQualifier() &
(ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
Results.AddResult("in");
Results.AddResult("inout");
AddedInOut = true;
}
if ((DS.getObjCDeclQualifier() &
(ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
Results.AddResult("out");
if (!AddedInOut)
Results.AddResult("inout");
}
if ((DS.getObjCDeclQualifier() &
(ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
ObjCDeclSpec::DQ_Oneway)) == 0) {
Results.AddResult("bycopy");
Results.AddResult("byref");
Results.AddResult("oneway");
}
if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
Results.AddResult("nonnull");
Results.AddResult("nullable");
Results.AddResult("null_unspecified");
}
if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
PP.isMacroDefined("IBAction")) {
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo(),
CCP_CodePattern, CXAvailability_Available);
Builder.AddTypedTextChunk("IBAction");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddPlaceholderChunk("selector");
Builder.AddChunk(CodeCompletionString::CK_Colon);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddTextChunk("id");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("sender");
Results.AddResult(CodeCompletionResult(Builder.TakeString()));
}
if (!IsParameter) {
Results.AddResult(CodeCompletionResult("instancetype"));
}
AddOrdinaryNameResults(PCC_Type, S, *this, Results);
Results.ExitScope();
Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
CodeCompletionDeclConsumer Consumer(Results, CurContext);
LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
if (CodeCompleter->includeMacros())
AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
if (!Msg)
return nullptr;
Selector Sel = Msg->getSelector();
if (Sel.isNull())
return nullptr;
IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
if (!Id)
return nullptr;
ObjCMethodDecl *Method = Msg->getMethodDecl();
if (!Method)
return nullptr;
ObjCInterfaceDecl *IFace = nullptr;
switch (Msg->getReceiverKind()) {
case ObjCMessageExpr::Class:
if (const ObjCObjectType *ObjType =
Msg->getClassReceiver()->getAs<ObjCObjectType>())
IFace = ObjType->getInterface();
break;
case ObjCMessageExpr::Instance: {
QualType T = Msg->getInstanceReceiver()->getType();
if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
IFace = Ptr->getInterfaceDecl();
break;
}
case ObjCMessageExpr::SuperInstance:
case ObjCMessageExpr::SuperClass:
break;
}
if (!IFace)
return nullptr;
ObjCInterfaceDecl *Super = IFace->getSuperClass();
if (Method->isInstanceMethod())
return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
.Case("retain", IFace)
.Case("strong", IFace)
.Case("autorelease", IFace)
.Case("copy", IFace)
.Case("copyWithZone", IFace)
.Case("mutableCopy", IFace)
.Case("mutableCopyWithZone", IFace)
.Case("awakeFromCoder", IFace)
.Case("replacementObjectFromCoder", IFace)
.Case("class", IFace)
.Case("classForCoder", IFace)
.Case("superclass", Super)
.Default(nullptr);
return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
.Case("new", IFace)
.Case("alloc", IFace)
.Case("allocWithZone", IFace)
.Case("class", IFace)
.Case("superclass", Super)
.Default(nullptr);
}
static ObjCMethodDecl *
AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
ArrayRef<IdentifierInfo *> SelIdents,
ResultBuilder &Results) {
ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
if (!CurMethod)
return nullptr;
ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
if (!Class)
return nullptr;
ObjCMethodDecl *SuperMethod = nullptr;
while ((Class = Class->getSuperClass()) && !SuperMethod) {
SuperMethod = Class->getMethod(CurMethod->getSelector(),
CurMethod->isInstanceMethod());
if (!SuperMethod) {
for (const auto *Cat : Class->known_categories()) {
if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
CurMethod->isInstanceMethod())))
break;
}
}
}
if (!SuperMethod)
return nullptr;
if (CurMethod->param_size() != SuperMethod->param_size() ||
CurMethod->isVariadic() != SuperMethod->isVariadic())
return nullptr;
for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
CurPEnd = CurMethod->param_end(),
SuperP = SuperMethod->param_begin();
CurP != CurPEnd; ++CurP, ++SuperP) {
if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
(*SuperP)->getType()))
return nullptr;
if (!(*CurP)->getIdentifier())
return nullptr;
}
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
Results.getCompletionContext().getBaseType(), Builder);
if (NeedSuperKeyword) {
Builder.AddTypedTextChunk("super");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
}
Selector Sel = CurMethod->getSelector();
if (Sel.isUnarySelector()) {
if (NeedSuperKeyword)
Builder.AddTextChunk(
Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
else
Builder.AddTypedTextChunk(
Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
} else {
ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
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(Sel.getNameForSlot(I) + ":"));
else if (NeedSuperKeyword || I > SelIdents.size()) {
Builder.AddTextChunk(
Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
(*CurP)->getIdentifier()->getName()));
} else {
Builder.AddTypedTextChunk(
Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
(*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(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_ObjCMessageReceiver,
getLangOpts().CPlusPlus11
? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
: &ResultBuilder::IsObjCMessageReceiver);
CodeCompletionDeclConsumer Consumer(Results, CurContext);
Results.EnterNewScope();
LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
CodeCompleter->includeGlobals(),
CodeCompleter->loadExternal());
if (ObjCMethodDecl *Method = getCurMethodDecl())
if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
if (Iface->getSuperClass()) {
Results.AddResult(Result("super"));
AddSuperSendCompletion(*this, true, None, Results);
}
if (getLangOpts().CPlusPlus11)
addThisCompletion(*this, Results);
Results.ExitScope();
if (CodeCompleter->includeMacros())
AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression) {
ObjCInterfaceDecl *CDecl = nullptr;
if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
CDecl = CurMethod->getClassInterface();
if (!CDecl)
return;
CDecl = CDecl->getSuperClass();
if (!CDecl)
return;
if (CurMethod->isInstanceMethod()) {
return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
AtArgumentExpression, CDecl);
}
} else {
IdentifierInfo *Super = getSuperIdentifier();
NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName);
if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
} else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
if (const ObjCObjectType *Iface =
Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
CDecl = Iface->getInterface();
} else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
} else {
CXXScopeSpec SS;
SourceLocation TemplateKWLoc;
UnqualifiedId id;
id.setIdentifier(Super, SuperLoc);
ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
false,
false);
return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
SelIdents, AtArgumentExpression);
}
}
ParsedType Receiver;
if (CDecl)
Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
AtArgumentExpression,
true);
}
static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
unsigned NumSelIdents) {
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 &&
isa<ObjCMethodDecl>(R.Declaration)) {
if (R.Priority <= BestPriority) {
const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
if (NumSelIdents <= Method->param_size()) {
QualType MyPreferredType =
Method->parameters()[NumSelIdents - 1]->getType();
if (R.Priority < BestPriority || PreferredType.isNull()) {
BestPriority = R.Priority;
PreferredType = MyPreferredType;
} else if (!Context.hasSameUnqualifiedType(PreferredType,
MyPreferredType)) {
PreferredType = QualType();
}
}
}
}
}
return PreferredType;
}
static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression, bool IsSuper,
ResultBuilder &Results) {
typedef CodeCompletionResult Result;
ObjCInterfaceDecl *CDecl = nullptr;
if (Receiver) {
QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
if (!T.isNull())
if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
CDecl = Interface->getInterface();
}
Results.EnterNewScope();
if (IsSuper) {
if (ObjCMethodDecl *SuperMethod =
AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
Results.Ignore(SuperMethod);
}
if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
Results.setPreferredSelector(CurMethod->getSelector());
VisitedSelectorSet Selectors;
if (CDecl)
AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext,
Selectors, AtArgumentExpression, Results);
else {
if (SemaRef.getExternalSource()) {
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->getNext()) {
if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
continue;
Result R(MethList->getMethod(),
Results.getBasePriority(MethList->getMethod()), nullptr);
R.StartParameter = SelIdents.size();
R.AllParametersAreInformative = false;
Results.MaybeAddResult(R, SemaRef.CurContext);
}
}
}
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 (AtArgumentExpression) {
QualType PreferredType =
getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
if (PreferredType.isNull())
CodeCompleteOrdinaryName(S, PCC_Expression);
else
CodeCompleteExpression(S, PreferredType);
return;
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
ObjCInterfaceDecl *Super) {
typedef CodeCompletionResult Result;
Expr *RecExpr = static_cast<Expr *>(Receiver);
if (RecExpr) {
ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
if (Conv.isInvalid()) return;
RecExpr = Conv.get();
}
QualType ReceiverType = RecExpr
? RecExpr->getType()
: Super ? Context.getObjCObjectPointerType(
Context.getObjCInterfaceType(Super))
: Context.getObjCIdType();
if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
if (ReceiverType->isObjCClassType())
return CodeCompleteObjCClassMessage(
S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents,
AtArgumentExpression, Super);
ReceiverType =
Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace));
}
} else if (RecExpr && getLangOpts().CPlusPlus) {
ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
if (Conv.isUsable()) {
RecExpr = Conv.get();
ReceiverType = RecExpr->getType();
}
}
ResultBuilder Results(
*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
ReceiverType, SelIdents));
Results.EnterNewScope();
if (Super) {
if (ObjCMethodDecl *SuperMethod =
AddSuperSendCompletion(*this, false, SelIdents, Results))
Results.Ignore(SuperMethod);
}
if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
Results.setPreferredSelector(CurMethod->getSelector());
VisitedSelectorSet Selectors;
if (ReceiverType->isObjCClassType() ||
ReceiverType->isObjCQualifiedClassType()) {
if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext,
Selectors, AtArgumentExpression, Results);
}
}
else if (const ObjCObjectPointerType *QualID =
ReceiverType->getAsObjCQualifiedIdType()) {
for (auto *I : QualID->quals())
AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
AtArgumentExpression, Results);
}
else if (const ObjCObjectPointerType *IFacePtr =
ReceiverType->getAsObjCInterfacePointerType()) {
AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
CurContext, Selectors, AtArgumentExpression, Results);
for (auto *I : IFacePtr->quals())
AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
AtArgumentExpression, Results);
}
else if (ReceiverType->isObjCIdType()) {
if (ExternalSource) {
for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
I != N; ++I) {
Selector Sel = ExternalSource->GetExternalSelector(I);
if (Sel.isNull() || MethodPool.count(Sel))
continue;
ReadMethodPool(Sel);
}
}
for (GlobalMethodPool::iterator M = MethodPool.begin(),
MEnd = MethodPool.end();
M != MEnd; ++M) {
for (ObjCMethodList *MethList = &M->second.first;
MethList && MethList->getMethod(); MethList = MethList->getNext()) {
if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
continue;
if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
continue;
Result R(MethList->getMethod(),
Results.getBasePriority(MethList->getMethod()), nullptr);
R.StartParameter = SelIdents.size();
R.AllParametersAreInformative = false;
Results.MaybeAddResult(R, CurContext);
}
}
}
Results.ExitScope();
if (AtArgumentExpression) {
QualType PreferredType =
getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
if (PreferredType.isNull())
CodeCompleteOrdinaryName(S, PCC_Expression);
else
CodeCompleteExpression(S, PreferredType);
return;
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
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) {
if (*I)
Data.IgnoreDecls.push_back(*I);
}
}
CodeCompleteExpression(S, Data);
}
void Sema::CodeCompleteObjCSelector(Scope *S,
ArrayRef<IdentifierInfo *> SelIdents) {
if (ExternalSource) {
for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
++I) {
Selector Sel = ExternalSource->GetExternalSelector(I);
if (Sel.isNull() || MethodPool.count(Sel))
continue;
ReadMethodPool(Sel);
}
}
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_SelectorName);
Results.EnterNewScope();
for (GlobalMethodPool::iterator M = MethodPool.begin(),
MEnd = MethodPool.end();
M != MEnd; ++M) {
Selector Sel = M->first;
if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
continue;
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
if (Sel.isUnarySelector()) {
Builder.AddTypedTextChunk(
Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
Results.AddResult(Builder.TakeString());
continue;
}
std::string Accumulator;
for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
if (I == SelIdents.size()) {
if (!Accumulator.empty()) {
Builder.AddInformativeChunk(
Builder.getAllocator().CopyString(Accumulator));
Accumulator.clear();
}
}
Accumulator += Sel.getNameForSlot(I);
Accumulator += ':';
}
Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator));
Results.AddResult(Builder.TakeString());
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
bool OnlyForwardDeclarations,
ResultBuilder &Results) {
typedef CodeCompletionResult Result;
for (const auto *D : Ctx->decls()) {
if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
if (!OnlyForwardDeclarations || !Proto->hasDefinition())
Results.AddResult(
Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext,
nullptr, false);
}
}
void Sema::CodeCompleteObjCProtocolReferences(
ArrayRef<IdentifierLocPair> Protocols) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_ObjCProtocolName);
if (CodeCompleter->includeGlobals()) {
Results.EnterNewScope();
for (const IdentifierLocPair &Pair : Protocols)
if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second))
Results.Ignore(Protocol);
AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
Results);
Results.ExitScope();
}
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();
AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
Results);
Results.ExitScope();
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
bool OnlyForwardDeclarations,
bool OnlyUnimplemented,
ResultBuilder &Results) {
typedef CodeCompletionResult Result;
for (const auto *D : Ctx->decls()) {
if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
(!OnlyUnimplemented || !Class->getImplementation()))
Results.AddResult(
Result(Class, Results.getBasePriority(Class), nullptr), CurContext,
nullptr, false);
}
}
void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_ObjCInterfaceName);
Results.EnterNewScope();
if (CodeCompleter->includeGlobals()) {
AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
false, Results);
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
SourceLocation ClassNameLoc) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_ObjCInterfaceName);
Results.EnterNewScope();
NamedDecl *CurClass =
LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
Results.Ignore(CurClass);
if (CodeCompleter->includeGlobals()) {
AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
false, Results);
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_ObjCImplementation);
Results.EnterNewScope();
if (CodeCompleter->includeGlobals()) {
AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
true, Results);
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc) {
typedef CodeCompletionResult Result;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_ObjCCategoryName);
llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
NamedDecl *CurClass =
LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
if (ObjCInterfaceDecl *Class =
dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) {
for (const auto *Cat : Class->visible_categories())
CategoryNames.insert(Cat->getIdentifier());
}
Results.EnterNewScope();
TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
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, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc) {
typedef CodeCompletionResult Result;
NamedDecl *CurClass =
LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
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);
llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
Results.EnterNewScope();
bool IgnoreImplemented = true;
while (Class) {
for (const auto *Cat : Class->visible_categories()) {
if ((!IgnoreImplemented || !Cat->getImplementation()) &&
CategoryNames.insert(Cat->getIdentifier()).second)
Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
CurContext, nullptr, false);
}
Class = Class->getSuperClass();
IgnoreImplemented = false;
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(), CCContext);
ObjCContainerDecl *Container =
dyn_cast_or_null<ObjCContainerDecl>(CurContext);
if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
!isa<ObjCCategoryImplDecl>(Container)))
return;
Container = getContainerDef(Container);
for (const auto *D : Container->decls())
if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
Results.Ignore(PropertyImpl->getPropertyDecl());
AddedPropertiesSet AddedProperties;
Results.EnterNewScope();
if (ObjCImplementationDecl *ClassImpl =
dyn_cast<ObjCImplementationDecl>(Container))
AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
false, CurContext,
AddedProperties, Results);
else
AddObjCProperties(CCContext,
cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
false, false, CurContext,
AddedProperties, Results);
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCPropertySynthesizeIvar(
Scope *S, IdentifierInfo *PropertyName) {
typedef CodeCompletionResult Result;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
ObjCContainerDecl *Container =
dyn_cast_or_null<ObjCContainerDecl>(CurContext);
if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
!isa<ObjCCategoryImplDecl>(Container)))
return;
ObjCInterfaceDecl *Class = nullptr;
if (ObjCImplementationDecl *ClassImpl =
dyn_cast<ObjCImplementationDecl>(Container))
Class = ClassImpl->getClassInterface();
else
Class = cast<ObjCCategoryImplDecl>(Container)
->getCategoryDecl()
->getClassInterface();
QualType PropertyType = Context.getObjCIdType();
if (Class) {
if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
PropertyType =
Property->getType().getNonReferenceType().getUnqualifiedType();
Results.setPreferredType(PropertyType);
}
}
Results.EnterNewScope();
bool SawSimilarlyNamedIvar = false;
std::string NameWithPrefix;
NameWithPrefix += '_';
NameWithPrefix += PropertyName->getName();
std::string NameWithSuffix = PropertyName->getName().str();
NameWithSuffix += '_';
for (; Class; Class = Class->getSuperClass()) {
for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
Ivar = Ivar->getNextIvar()) {
Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
CurContext, nullptr, false);
if ((PropertyName == Ivar->getIdentifier() ||
NameWithPrefix == Ivar->getName() ||
NameWithSuffix == Ivar->getName())) {
SawSimilarlyNamedIvar = true;
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) {
unsigned Priority = CCP_MemberDeclaration + 1;
typedef CodeCompletionResult Result;
CodeCompletionAllocator &Allocator = Results.getAllocator();
CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
Priority, CXAvailability_Available);
PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
Builder.AddResultTypeChunk(
GetCompletionTypeString(PropertyType, Context, Policy, Allocator));
Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
Results.AddResult(
Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl));
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
typedef llvm::DenseMap<Selector,
llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>>
KnownMethodsMap;
static void FindImplementableMethods(ASTContext &Context,
ObjCContainerDecl *Container,
Optional<bool> WantInstanceMethods,
QualType ReturnType,
KnownMethodsMap &KnownMethods,
bool InOriginalClass = true) {
if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
if (!IFace->hasDefinition())
return;
IFace = IFace->getDefinition();
Container = IFace;
const ObjCList<ObjCProtocolDecl> &Protocols =
IFace->getReferencedProtocols();
for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
E = Protocols.end();
I != E; ++I)
FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
KnownMethods, InOriginalClass);
for (auto *Cat : IFace->visible_categories()) {
FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
KnownMethods, false);
}
if (IFace->getSuperClass())
FindImplementableMethods(Context, IFace->getSuperClass(),
WantInstanceMethods, ReturnType, KnownMethods,
false);
}
if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
const ObjCList<ObjCProtocolDecl> &Protocols =
Category->getReferencedProtocols();
for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
E = Protocols.end();
I != E; ++I)
FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
KnownMethods, InOriginalClass);
if (InOriginalClass && Category->getClassInterface())
FindImplementableMethods(Context, Category->getClassInterface(),
WantInstanceMethods, ReturnType, KnownMethods,
false);
}
if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
if (!Protocol->hasDefinition())
return;
Protocol = Protocol->getDefinition();
Container = Protocol;
const ObjCList<ObjCProtocolDecl> &Protocols =
Protocol->getReferencedProtocols();
for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
E = Protocols.end();
I != E; ++I)
FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
KnownMethods, false);
}
for (auto *M : Container->methods()) {
if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
if (!ReturnType.isNull() &&
!Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
continue;
KnownMethods[M->getSelector()] =
KnownMethodsMap::mapped_type(M, InOriginalClass);
}
}
}
static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals,
ASTContext &Context,
const PrintingPolicy &Policy,
CodeCompletionBuilder &Builder) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
if (!Quals.empty())
Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
Builder.AddTextChunk(
GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator()));
Builder.AddChunk(CodeCompletionString::CK_RightParen);
}
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);
}
static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
bool IsInstanceMethod,
QualType ReturnType, ASTContext &Context,
VisitedSelectorSet &KnownSelectors,
ResultBuilder &Results) {
IdentifierInfo *PropName = Property->getIdentifier();
if (!PropName || PropName->getLength() == 0)
return;
PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
typedef CodeCompletionResult Result;
CodeCompletionAllocator &Allocator = Results.getAllocator();
CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
SelectorTable &Selectors = Context.Selectors;
struct KeyHolder {
CodeCompletionAllocator &Allocator;
StringRef Key;
const char *CopiedKey;
KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
: Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
operator const char *() {
if (CopiedKey)
return CopiedKey;
return CopiedKey = Allocator.CopyString(Key);
}
} Key(Allocator, PropName->getName());
std::string UpperKey = std::string(PropName->getName());
if (!UpperKey.empty())
UpperKey[0] = toUppercase(UpperKey[0]);
bool ReturnTypeMatchesProperty =
ReturnType.isNull() ||
Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
Property->getType());
bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType();
if (IsInstanceMethod &&
KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
if (ReturnType.isNull())
AddObjCPassingTypeChunk(Property->getType(), 0, Context, Policy,
Builder);
Builder.AddTypedTextChunk(Key);
Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
CXCursor_ObjCInstanceMethodDecl));
}
if (IsInstanceMethod &&
((!ReturnType.isNull() &&
(ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
(ReturnType.isNull() && (Property->getType()->isIntegerType() ||
Property->getType()->isBooleanType())))) {
std::string SelectorName = (Twine("is") + UpperKey).str();
IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
.second) {
if (ReturnType.isNull()) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddTextChunk("BOOL");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
}
Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid &&
!Property->getSetterMethodDecl()) {
std::string SelectorName = (Twine("set") + UpperKey).str();
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(SelectorId->getName() + ":"));
AddObjCPassingTypeChunk(Property->getType(), 0, Context, Policy,
Builder);
Builder.AddTextChunk(Key);
Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
CXCursor_ObjCInstanceMethodDecl));
}
}
unsigned IndexedGetterPriority = CCP_CodePattern;
unsigned IndexedSetterPriority = CCP_CodePattern;
unsigned UnorderedGetterPriority = CCP_CodePattern;
unsigned UnorderedSetterPriority = CCP_CodePattern;
if (const auto *ObjCPointer =
Property->getType()->getAs<ObjCObjectPointerType>()) {
if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
if (!InheritsFromClassNamed(IFace, "NSArray"))
IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
}
if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
if (!InheritsFromClassNamed(IFace, "NSSet"))
UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
}
}
} else {
IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
}
if (IsInstanceMethod &&
(ReturnType.isNull() || ReturnType->isIntegerType())) {
std::string SelectorName = (Twine("countOf") + UpperKey).str();
IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
.second) {
if (ReturnType.isNull()) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddTextChunk("NSUInteger");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
}
Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
Results.AddResult(
Result(Builder.TakeString(),
std::min(IndexedGetterPriority, UnorderedGetterPriority),
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod &&
(ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str();
IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
if (ReturnType.isNull()) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
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,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod &&
(ReturnType.isNull() ||
(ReturnType->isObjCObjectPointerType() &&
ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
ReturnType->castAs<ObjCObjectPointerType>()
->getInterfaceDecl()
->getName() == "NSArray"))) {
std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str();
IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
if (ReturnType.isNull()) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
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,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName = (Twine("get") + UpperKey).str();
IdentifierInfo *SelectorIds[2] = {&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");
Builder.AddTextChunk(" **");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("buffer");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTypedTextChunk("range:");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddTextChunk("NSRange");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("inRange");
Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
IdentifierInfo *SelectorIds[2] = {&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");
Builder.AddTextChunk(" *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("object");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("NSUInteger");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("index");
Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName = (Twine("insert") + UpperKey).str();
IdentifierInfo *SelectorIds[2] = {&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 *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("array");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTypedTextChunk("atIndexes:");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("NSIndexSet *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("indexes");
Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName =
(Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
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,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str();
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,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName =
(Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
IdentifierInfo *SelectorIds[2] = {&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");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("index");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTypedTextChunk("withObject:");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddTextChunk("id");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("object");
Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
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 *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("indexes");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddTextChunk("NSArray *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("array");
Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod &&
(ReturnType.isNull() ||
(ReturnType->isObjCObjectPointerType() &&
ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
ReturnType->castAs<ObjCObjectPointerType>()
->getInterfaceDecl()
->getName() == "NSEnumerator"))) {
std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
.second) {
if (ReturnType.isNull()) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddTextChunk("NSEnumerator *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
}
Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod &&
(ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
std::string SelectorName = (Twine("memberOf") + UpperKey).str();
IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
if (ReturnType.isNull()) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("object-type");
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, Policy, Builder.getAllocator()));
}
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("object");
Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName =
(Twine("add") + UpperKey + Twine("Object")).str();
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.AddPlaceholderChunk("object-type");
Builder.AddTextChunk(" *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("object");
Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName = (Twine("add") + UpperKey).str();
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("NSSet *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("objects");
Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName =
(Twine("remove") + UpperKey + Twine("Object")).str();
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.AddPlaceholderChunk("object-type");
Builder.AddTextChunk(" *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("object");
Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName = (Twine("remove") + UpperKey).str();
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("NSSet *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("objects");
Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (IsInstanceMethod && ReturnTypeMatchesVoid) {
std::string SelectorName = (Twine("intersect") + UpperKey).str();
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("NSSet *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Builder.AddTextChunk("objects");
Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
CXCursor_ObjCInstanceMethodDecl));
}
}
if (!IsInstanceMethod &&
(ReturnType.isNull() ||
(ReturnType->isObjCObjectPointerType() &&
ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
ReturnType->castAs<ObjCObjectPointerType>()
->getInterfaceDecl()
->getName() == "NSSet"))) {
std::string SelectorName =
(Twine("keyPathsForValuesAffecting") + UpperKey).str();
IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
.second) {
if (ReturnType.isNull()) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddTextChunk("NSSet<NSString *> *");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
}
Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
CXCursor_ObjCClassMethodDecl));
}
}
if (!IsInstanceMethod &&
(ReturnType.isNull() || ReturnType->isIntegerType() ||
ReturnType->isBooleanType())) {
std::string SelectorName =
(Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
.second) {
if (ReturnType.isNull()) {
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddTextChunk("BOOL");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
}
Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
CXCursor_ObjCClassMethodDecl));
}
}
}
void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
ParsedType ReturnTy) {
QualType ReturnType = GetTypeFromParser(ReturnTy);
Decl *IDecl = nullptr;
if (CurContext->isObjCContainer()) {
ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
IDecl = OCD;
}
ObjCContainerDecl *SearchDecl = nullptr;
bool IsInImplementation = false;
if (Decl *D = IDecl) {
if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
SearchDecl = Impl->getClassInterface();
IsInImplementation = true;
} else if (ObjCCategoryImplDecl *CatImpl =
dyn_cast<ObjCCategoryImplDecl>(D)) {
SearchDecl = CatImpl->getCategoryDecl();
IsInImplementation = true;
} else
SearchDecl = dyn_cast<ObjCContainerDecl>(D);
}
if (!SearchDecl && S) {
if (DeclContext *DC = S->getEntity())
SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
}
if (!SearchDecl) {
HandleCodeCompleteResults(this, CodeCompleter,
CodeCompletionContext::CCC_Other, nullptr, 0);
return;
}
KnownMethodsMap KnownMethods;
FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType,
KnownMethods);
typedef CodeCompletionResult Result;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
for (KnownMethodsMap::iterator M = KnownMethods.begin(),
MEnd = KnownMethods.end();
M != MEnd; ++M) {
ObjCMethodDecl *Method = M->second.getPointer();
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
if (!IsInstanceMethod) {
Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
}
if (ReturnType.isNull()) {
QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
AttributedType::stripOuterNullability(ResTy);
AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context,
Policy, Builder);
}
Selector Sel = Method->getSelector();
if (Sel.isUnarySelector()) {
Builder.AddTypedTextChunk(
Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
} else {
unsigned I = 0;
for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
PEnd = Method->param_end();
P != PEnd; (void)++P, ++I) {
if (I == 0)
Builder.AddTypedTextChunk(
Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
else if (I < Sel.getNumArgs()) {
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTypedTextChunk(
Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
} else
break;
QualType ParamType;
if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
ParamType = (*P)->getType();
else
ParamType = (*P)->getOriginalType();
ParamType = ParamType.substObjCTypeArgs(
Context, {}, ObjCSubstitutionContext::Parameter);
AttributedType::stripOuterNullability(ParamType);
AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(),
Context, Policy, Builder);
if (IdentifierInfo *Id = (*P)->getIdentifier())
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()) {
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
if (!Method->getReturnType()->isVoidType()) {
Builder.AddTextChunk("return");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("expression");
Builder.AddChunk(CodeCompletionString::CK_SemiColon);
} else
Builder.AddPlaceholderChunk("statements");
Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
Builder.AddChunk(CodeCompletionString::CK_RightBrace);
}
unsigned Priority = CCP_CodePattern;
auto R = Result(Builder.TakeString(), Method, Priority);
if (!M->second.getInt())
setInBaseClass(R);
Results.AddResult(std::move(R));
}
if (Context.getLangOpts().ObjC) {
SmallVector<ObjCContainerDecl *, 4> Containers;
Containers.push_back(SearchDecl);
VisitedSelectorSet KnownSelectors;
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)
llvm::append_range(Containers, IFace->visible_categories());
if (IsInstanceMethod) {
for (unsigned I = 0, N = Containers.size(); I != N; ++I)
for (auto *P : Containers[I]->instance_properties())
AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
KnownSelectors, Results);
}
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteObjCMethodDeclSelector(
Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy,
ArrayRef<IdentifierInfo *> SelIdents) {
if (ExternalSource) {
for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
++I) {
Selector Sel = ExternalSource->GetExternalSelector(I);
if (Sel.isNull() || MethodPool.count(Sel))
continue;
ReadMethodPool(Sel);
}
}
typedef CodeCompletionResult Result;
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
if (ReturnTy)
Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
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->getNext()) {
if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
continue;
if (AtParameterName) {
unsigned NumSelIdents = SelIdents.size();
if (NumSelIdents &&
NumSelIdents <= MethList->getMethod()->param_size()) {
ParmVarDecl *Param =
MethList->getMethod()->parameters()[NumSelIdents - 1];
if (Param->getIdentifier()) {
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
Param->getIdentifier()->getName()));
Results.AddResult(Builder.TakeString());
}
}
continue;
}
Result R(MethList->getMethod(),
Results.getBasePriority(MethList->getMethod()), nullptr);
R.StartParameter = SelIdents.size();
R.AllParametersAreInformative = false;
R.DeclaringEntity = true;
Results.MaybeAddResult(R, CurContext);
}
}
Results.ExitScope();
if (!AtParameterName && !SelIdents.empty() &&
SelIdents.front()->getName().startswith("init")) {
for (const auto &M : PP.macros()) {
if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
continue;
Results.EnterNewScope();
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Builder.AddTypedTextChunk(
Builder.getAllocator().CopyString(M.first->getName()));
Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
CXCursor_MacroDefinition));
Results.ExitScope();
}
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_PreprocessorDirective);
Results.EnterNewScope();
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Builder.AddTypedTextChunk("if");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("condition");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("ifdef");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("macro");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("ifndef");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("macro");
Results.AddResult(Builder.TakeString());
if (InConditional) {
Builder.AddTypedTextChunk("elif");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("condition");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("elifdef");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("macro");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("elifndef");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("macro");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("else");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("endif");
Results.AddResult(Builder.TakeString());
}
Builder.AddTypedTextChunk("include");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTextChunk("\"");
Builder.AddPlaceholderChunk("header");
Builder.AddTextChunk("\"");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("include");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTextChunk("<");
Builder.AddPlaceholderChunk("header");
Builder.AddTextChunk(">");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("define");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("macro");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("define");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("macro");
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("args");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("undef");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("macro");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("line");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("number");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("line");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("number");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTextChunk("\"");
Builder.AddPlaceholderChunk("filename");
Builder.AddTextChunk("\"");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("error");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("message");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("pragma");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("arguments");
Results.AddResult(Builder.TakeString());
if (getLangOpts().ObjC) {
Builder.AddTypedTextChunk("import");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTextChunk("\"");
Builder.AddPlaceholderChunk("header");
Builder.AddTextChunk("\"");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("import");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTextChunk("<");
Builder.AddPlaceholderChunk("header");
Builder.AddTextChunk(">");
Results.AddResult(Builder.TakeString());
}
Builder.AddTypedTextChunk("include_next");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTextChunk("\"");
Builder.AddPlaceholderChunk("header");
Builder.AddTextChunk("\"");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("include_next");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddTextChunk("<");
Builder.AddPlaceholderChunk("header");
Builder.AddTextChunk(">");
Results.AddResult(Builder.TakeString());
Builder.AddTypedTextChunk("warning");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddPlaceholderChunk("message");
Results.AddResult(Builder.TakeString());
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction
: Sema::PCC_Namespace);
}
void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
IsDefinition ? CodeCompletionContext::CCC_MacroName
: CodeCompletionContext::CCC_MacroNameUse);
if (!IsDefinition && CodeCompleter->includeMacros()) {
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Results.EnterNewScope();
for (Preprocessor::macro_iterator M = PP.macro_begin(),
MEnd = PP.macro_end();
M != MEnd; ++M) {
Builder.AddTypedTextChunk(
Builder.getAllocator().CopyString(M->first->getName()));
Results.AddResult(CodeCompletionResult(
Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition));
}
Results.ExitScope();
} else if (IsDefinition) {
}
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompletePreprocessorExpression() {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_PreprocessorExpression);
if (CodeCompleter->includeMacros())
AddMacroResults(PP, Results, CodeCompleter->loadExternal(), true);
Results.EnterNewScope();
CodeCompletionBuilder Builder(Results.getAllocator(),
Results.getCodeCompletionTUInfo());
Builder.AddTypedTextChunk("defined");
Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
Builder.AddChunk(CodeCompletionString::CK_LeftParen);
Builder.AddPlaceholderChunk("macro");
Builder.AddChunk(CodeCompletionString::CK_RightParen);
Results.AddResult(Builder.TakeString());
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned Argument) {
}
void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) {
std::string RelDir = llvm::sys::path::convert_to_slash(Dir);
SmallString<128> NativeRelDir = StringRef(RelDir);
llvm::sys::path::native(NativeRelDir);
llvm::vfs::FileSystem &FS =
getSourceManager().getFileManager().getVirtualFileSystem();
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_IncludedFile);
llvm::DenseSet<StringRef> SeenResults;
auto AddCompletion = [&](StringRef Filename, bool IsDirectory) {
SmallString<64> TypedChunk = Filename;
TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"');
auto R = SeenResults.insert(TypedChunk);
if (R.second) { const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk);
*R.first = InternedTyped; CodeCompletionBuilder Builder(CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo());
Builder.AddTypedTextChunk(InternedTyped);
Results.AddResult(CodeCompletionResult(Builder.TakeString()));
}
};
auto AddFilesFromIncludeDir = [&](StringRef IncludeDir,
bool IsSystem,
DirectoryLookup::LookupType_t LookupType) {
llvm::SmallString<128> Dir = IncludeDir;
if (!NativeRelDir.empty()) {
if (LookupType == DirectoryLookup::LT_Framework) {
auto Begin = llvm::sys::path::begin(NativeRelDir);
auto End = llvm::sys::path::end(NativeRelDir);
llvm::sys::path::append(Dir, *Begin + ".framework", "Headers");
llvm::sys::path::append(Dir, ++Begin, End);
} else {
llvm::sys::path::append(Dir, NativeRelDir);
}
}
const StringRef &Dirname = llvm::sys::path::filename(Dir);
const bool isQt = Dirname.startswith("Qt") || Dirname == "ActiveQt";
const bool ExtensionlessHeaders =
IsSystem || isQt || Dir.endswith(".framework/Headers");
std::error_code EC;
unsigned Count = 0;
for (auto It = FS.dir_begin(Dir, EC);
!EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) {
if (++Count == 2500) break; StringRef Filename = llvm::sys::path::filename(It->path());
llvm::sys::fs::file_type Type = It->type();
if (Type == llvm::sys::fs::file_type::symlink_file) {
if (auto FileStatus = FS.status(It->path()))
Type = FileStatus->getType();
}
switch (Type) {
case llvm::sys::fs::file_type::directory_file:
if (LookupType == DirectoryLookup::LT_Framework &&
NativeRelDir.empty() && !Filename.consume_back(".framework"))
break;
AddCompletion(Filename, true);
break;
case llvm::sys::fs::file_type::regular_file: {
const bool IsHeader = Filename.endswith_insensitive(".h") ||
Filename.endswith_insensitive(".hh") ||
Filename.endswith_insensitive(".hpp") ||
Filename.endswith_insensitive(".inc") ||
(ExtensionlessHeaders && !Filename.contains('.'));
if (!IsHeader)
break;
AddCompletion(Filename, false);
break;
}
default:
break;
}
}
};
auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir,
bool IsSystem) {
switch (IncludeDir.getLookupType()) {
case DirectoryLookup::LT_HeaderMap:
break;
case DirectoryLookup::LT_NormalDir:
AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem,
DirectoryLookup::LT_NormalDir);
break;
case DirectoryLookup::LT_Framework:
AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem,
DirectoryLookup::LT_Framework);
break;
}
};
const auto &S = PP.getHeaderSearchInfo();
using llvm::make_range;
if (!Angled) {
const FileEntry *CurFile = PP.getCurrentFileLexer()->getFileEntry();
if (CurFile && CurFile->getDir())
AddFilesFromIncludeDir(CurFile->getDir()->getName(), false,
DirectoryLookup::LT_NormalDir);
for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end()))
AddFilesFromDirLookup(D, false);
}
for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end()))
AddFilesFromDirLookup(D, false);
for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end()))
AddFilesFromDirLookup(D, true);
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::CodeCompleteNaturalLanguage() {
HandleCodeCompleteResults(this, CodeCompleter,
CodeCompletionContext::CCC_NaturalLanguage, nullptr,
0);
}
void Sema::CodeCompleteAvailabilityPlatformName() {
ResultBuilder Results(*this, CodeCompleter->getAllocator(),
CodeCompleter->getCodeCompletionTUInfo(),
CodeCompletionContext::CCC_Other);
Results.EnterNewScope();
static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
for (const char *Platform : llvm::makeArrayRef(Platforms)) {
Results.AddResult(CodeCompletionResult(Platform));
Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
Twine(Platform) + "ApplicationExtension")));
}
Results.ExitScope();
HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
Results.data(), Results.size());
}
void Sema::GatherGlobalCodeCompletions(
CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
SmallVectorImpl<CodeCompletionResult> &Results) {
ResultBuilder Builder(*this, Allocator, CCTUInfo,
CodeCompletionContext::CCC_Recovery);
if (!CodeCompleter || CodeCompleter->includeGlobals()) {
CodeCompletionDeclConsumer Consumer(Builder,
Context.getTranslationUnitDecl());
LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
Consumer,
!CodeCompleter || CodeCompleter->loadExternal());
}
if (!CodeCompleter || CodeCompleter->includeMacros())
AddMacroResults(PP, Builder,
!CodeCompleter || CodeCompleter->loadExternal(), true);
Results.clear();
Results.insert(Results.end(), Builder.data(),
Builder.data() + Builder.size());
}