1 #include "ExpectedTypes.h" 2 #include "clang/AST/ASTContext.h" 3 #include "clang/AST/Type.h" 4 #include "clang/Index/USRGeneration.h" 5 #include "clang/Sema/CodeCompleteConsumer.h" 6 #include "llvm/ADT/STLExtras.h" 7 8 using namespace llvm; 9 10 namespace clang { 11 namespace clangd { 12 namespace { 13 14 static const Type *toEquivClass(ASTContext &Ctx, QualType T) { 15 if (T.isNull() || T->isDependentType()) 16 return nullptr; 17 // Drop references, we do not handle reference inits properly anyway. 18 T = T.getCanonicalType().getNonReferenceType(); 19 // Numeric types are the simplest case. 20 if (T->isBooleanType()) 21 return Ctx.BoolTy.getTypePtr(); 22 if (T->isIntegerType() && !T->isEnumeralType()) 23 return Ctx.IntTy.getTypePtr(); // All integers are equivalent. 24 if (T->isFloatingType() && !T->isComplexType()) 25 return Ctx.FloatTy.getTypePtr(); // All floats are equivalent. 26 27 // Do some simple transformations. 28 if (T->isArrayType()) // Decay arrays to pointers. 29 return Ctx.getPointerType(QualType(T->getArrayElementTypeNoTypeQual(), 0)) 30 .getTypePtr(); 31 // Drop the qualifiers and return the resulting type. 32 // FIXME: also drop qualifiers from pointer types, e.g. 'const T* => T*' 33 return T.getTypePtr(); 34 } 35 36 static Optional<QualType> typeOfCompletion(const CodeCompletionResult &R) { 37 auto *VD = dyn_cast_or_null<ValueDecl>(R.Declaration); 38 if (!VD) 39 return None; // We handle only variables and functions below. 40 auto T = VD->getType(); 41 if (auto FuncT = T->getAs<FunctionType>()) { 42 // Functions are a special case. They are completed as 'foo()' and we want 43 // to match their return type rather than the function type itself. 44 // FIXME(ibiryukov): in some cases, we might want to avoid completing `()` 45 // after the function name, e.g. `std::cout << std::endl`. 46 return FuncT->getReturnType(); 47 } 48 return T; 49 } 50 } // namespace 51 52 Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) { 53 if (T.isNull()) 54 return None; 55 const Type *C = toEquivClass(Ctx, T); 56 if (!C) 57 return None; 58 SmallString<128> Encoded; 59 if (index::generateUSRForType(QualType(C, 0), Ctx, Encoded)) 60 return None; 61 return OpaqueType(Encoded.str()); 62 } 63 64 OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {} 65 66 Optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx, QualType Type) { 67 return encode(Ctx, Type); 68 } 69 70 Optional<OpaqueType> 71 OpaqueType::fromCompletionResult(ASTContext &Ctx, 72 const CodeCompletionResult &R) { 73 auto T = typeOfCompletion(R); 74 if (!T) 75 return None; 76 return encode(Ctx, *T); 77 } 78 79 } // namespace clangd 80 } // namespace clang 81