15ffd83dbSDimitry Andric //===-- CxxModuleHandler.cpp ----------------------------------------------===//
25ffd83dbSDimitry Andric //
35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ffd83dbSDimitry Andric //
75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
85ffd83dbSDimitry Andric
95ffd83dbSDimitry Andric #include "Plugins/ExpressionParser/Clang/CxxModuleHandler.h"
105ffd83dbSDimitry Andric #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
115ffd83dbSDimitry Andric
1281ad6265SDimitry Andric #include "lldb/Utility/LLDBLog.h"
135ffd83dbSDimitry Andric #include "lldb/Utility/Log.h"
145ffd83dbSDimitry Andric #include "clang/Sema/Lookup.h"
155ffd83dbSDimitry Andric #include "llvm/Support/Error.h"
16bdd1243dSDimitry Andric #include <optional>
175ffd83dbSDimitry Andric
185ffd83dbSDimitry Andric using namespace lldb_private;
195ffd83dbSDimitry Andric using namespace clang;
205ffd83dbSDimitry Andric
CxxModuleHandler(ASTImporter & importer,ASTContext * target)215ffd83dbSDimitry Andric CxxModuleHandler::CxxModuleHandler(ASTImporter &importer, ASTContext *target)
225ffd83dbSDimitry Andric : m_importer(&importer),
235ffd83dbSDimitry Andric m_sema(TypeSystemClang::GetASTContext(target)->getSema()) {
245ffd83dbSDimitry Andric
255ffd83dbSDimitry Andric std::initializer_list<const char *> supported_names = {
265ffd83dbSDimitry Andric // containers
27e8d8bef9SDimitry Andric "array",
285ffd83dbSDimitry Andric "deque",
295ffd83dbSDimitry Andric "forward_list",
305ffd83dbSDimitry Andric "list",
315ffd83dbSDimitry Andric "queue",
325ffd83dbSDimitry Andric "stack",
335ffd83dbSDimitry Andric "vector",
345ffd83dbSDimitry Andric // pointers
355ffd83dbSDimitry Andric "shared_ptr",
365ffd83dbSDimitry Andric "unique_ptr",
375ffd83dbSDimitry Andric "weak_ptr",
38fe6060f1SDimitry Andric // iterator
39fe6060f1SDimitry Andric "move_iterator",
40fe6060f1SDimitry Andric "__wrap_iter",
415ffd83dbSDimitry Andric // utility
425ffd83dbSDimitry Andric "allocator",
43e8d8bef9SDimitry Andric "pair",
445ffd83dbSDimitry Andric };
455ffd83dbSDimitry Andric m_supported_templates.insert(supported_names.begin(), supported_names.end());
465ffd83dbSDimitry Andric }
475ffd83dbSDimitry Andric
485ffd83dbSDimitry Andric /// Builds a list of scopes that point into the given context.
495ffd83dbSDimitry Andric ///
505ffd83dbSDimitry Andric /// \param sema The sema that will be using the scopes.
515ffd83dbSDimitry Andric /// \param ctxt The context that the scope should look into.
525ffd83dbSDimitry Andric /// \param result A list of scopes. The scopes need to be freed by the caller
535ffd83dbSDimitry Andric /// (except the TUScope which is owned by the sema).
makeScopes(Sema & sema,DeclContext * ctxt,std::vector<Scope * > & result)545ffd83dbSDimitry Andric static void makeScopes(Sema &sema, DeclContext *ctxt,
555ffd83dbSDimitry Andric std::vector<Scope *> &result) {
565ffd83dbSDimitry Andric // FIXME: The result should be a list of unique_ptrs, but the TUScope makes
575ffd83dbSDimitry Andric // this currently impossible as it's owned by the Sema.
585ffd83dbSDimitry Andric
595ffd83dbSDimitry Andric if (auto parent = ctxt->getParent()) {
605ffd83dbSDimitry Andric makeScopes(sema, parent, result);
615ffd83dbSDimitry Andric
625ffd83dbSDimitry Andric Scope *scope =
635ffd83dbSDimitry Andric new Scope(result.back(), Scope::DeclScope, sema.getDiagnostics());
645ffd83dbSDimitry Andric scope->setEntity(ctxt);
655ffd83dbSDimitry Andric result.push_back(scope);
665ffd83dbSDimitry Andric } else
675ffd83dbSDimitry Andric result.push_back(sema.TUScope);
685ffd83dbSDimitry Andric }
695ffd83dbSDimitry Andric
705ffd83dbSDimitry Andric /// Uses the Sema to look up the given name in the given DeclContext.
715ffd83dbSDimitry Andric static std::unique_ptr<LookupResult>
emulateLookupInCtxt(Sema & sema,llvm::StringRef name,DeclContext * ctxt)725ffd83dbSDimitry Andric emulateLookupInCtxt(Sema &sema, llvm::StringRef name, DeclContext *ctxt) {
735ffd83dbSDimitry Andric IdentifierInfo &ident = sema.getASTContext().Idents.get(name);
745ffd83dbSDimitry Andric
755ffd83dbSDimitry Andric std::unique_ptr<LookupResult> lookup_result;
765ffd83dbSDimitry Andric lookup_result = std::make_unique<LookupResult>(sema, DeclarationName(&ident),
775ffd83dbSDimitry Andric SourceLocation(),
785ffd83dbSDimitry Andric Sema::LookupOrdinaryName);
795ffd83dbSDimitry Andric
805ffd83dbSDimitry Andric // Usually during parsing we already encountered the scopes we would use. But
815ffd83dbSDimitry Andric // here don't have these scopes so we have to emulate the behavior of the
825ffd83dbSDimitry Andric // Sema during parsing.
835ffd83dbSDimitry Andric std::vector<Scope *> scopes;
845ffd83dbSDimitry Andric makeScopes(sema, ctxt, scopes);
855ffd83dbSDimitry Andric
865ffd83dbSDimitry Andric // Now actually perform the lookup with the sema.
875ffd83dbSDimitry Andric sema.LookupName(*lookup_result, scopes.back());
885ffd83dbSDimitry Andric
895ffd83dbSDimitry Andric // Delete all the allocated scopes beside the translation unit scope (which
905ffd83dbSDimitry Andric // has depth 0).
915ffd83dbSDimitry Andric for (Scope *s : scopes)
925ffd83dbSDimitry Andric if (s->getDepth() != 0)
935ffd83dbSDimitry Andric delete s;
945ffd83dbSDimitry Andric
955ffd83dbSDimitry Andric return lookup_result;
965ffd83dbSDimitry Andric }
975ffd83dbSDimitry Andric
985ffd83dbSDimitry Andric /// Error class for handling problems when finding a certain DeclContext.
995ffd83dbSDimitry Andric struct MissingDeclContext : public llvm::ErrorInfo<MissingDeclContext> {
1005ffd83dbSDimitry Andric
1015ffd83dbSDimitry Andric static char ID;
1025ffd83dbSDimitry Andric
MissingDeclContextMissingDeclContext1035ffd83dbSDimitry Andric MissingDeclContext(DeclContext *context, std::string error)
1045ffd83dbSDimitry Andric : m_context(context), m_error(error) {}
1055ffd83dbSDimitry Andric
1065ffd83dbSDimitry Andric DeclContext *m_context;
1075ffd83dbSDimitry Andric std::string m_error;
1085ffd83dbSDimitry Andric
logMissingDeclContext1095ffd83dbSDimitry Andric void log(llvm::raw_ostream &OS) const override {
1105ffd83dbSDimitry Andric OS << llvm::formatv("error when reconstructing context of kind {0}:{1}",
1115ffd83dbSDimitry Andric m_context->getDeclKindName(), m_error);
1125ffd83dbSDimitry Andric }
1135ffd83dbSDimitry Andric
convertToErrorCodeMissingDeclContext1145ffd83dbSDimitry Andric std::error_code convertToErrorCode() const override {
1155ffd83dbSDimitry Andric return llvm::inconvertibleErrorCode();
1165ffd83dbSDimitry Andric }
1175ffd83dbSDimitry Andric };
1185ffd83dbSDimitry Andric
1195ffd83dbSDimitry Andric char MissingDeclContext::ID = 0;
1205ffd83dbSDimitry Andric
1215ffd83dbSDimitry Andric /// Given a foreign decl context, this function finds the equivalent local
1225ffd83dbSDimitry Andric /// decl context in the ASTContext of the given Sema. Potentially deserializes
1235ffd83dbSDimitry Andric /// decls from the 'std' module if necessary.
1245ffd83dbSDimitry Andric static llvm::Expected<DeclContext *>
getEqualLocalDeclContext(Sema & sema,DeclContext * foreign_ctxt)1255ffd83dbSDimitry Andric getEqualLocalDeclContext(Sema &sema, DeclContext *foreign_ctxt) {
1265ffd83dbSDimitry Andric
1275ffd83dbSDimitry Andric // Inline namespaces don't matter for lookups, so let's skip them.
1285ffd83dbSDimitry Andric while (foreign_ctxt && foreign_ctxt->isInlineNamespace())
1295ffd83dbSDimitry Andric foreign_ctxt = foreign_ctxt->getParent();
1305ffd83dbSDimitry Andric
1315ffd83dbSDimitry Andric // If the foreign context is the TU, we just return the local TU.
1325ffd83dbSDimitry Andric if (foreign_ctxt->isTranslationUnit())
1335ffd83dbSDimitry Andric return sema.getASTContext().getTranslationUnitDecl();
1345ffd83dbSDimitry Andric
1355ffd83dbSDimitry Andric // Recursively find/build the parent DeclContext.
1365ffd83dbSDimitry Andric llvm::Expected<DeclContext *> parent =
1375ffd83dbSDimitry Andric getEqualLocalDeclContext(sema, foreign_ctxt->getParent());
1385ffd83dbSDimitry Andric if (!parent)
1395ffd83dbSDimitry Andric return parent;
1405ffd83dbSDimitry Andric
1415ffd83dbSDimitry Andric // We currently only support building namespaces.
1425ffd83dbSDimitry Andric if (foreign_ctxt->isNamespace()) {
14304eeddc0SDimitry Andric NamedDecl *ns = llvm::cast<NamedDecl>(foreign_ctxt);
1445ffd83dbSDimitry Andric llvm::StringRef ns_name = ns->getName();
1455ffd83dbSDimitry Andric
1465ffd83dbSDimitry Andric auto lookup_result = emulateLookupInCtxt(sema, ns_name, *parent);
1475ffd83dbSDimitry Andric for (NamedDecl *named_decl : *lookup_result) {
1485ffd83dbSDimitry Andric if (DeclContext *DC = llvm::dyn_cast<DeclContext>(named_decl))
1495ffd83dbSDimitry Andric return DC->getPrimaryContext();
1505ffd83dbSDimitry Andric }
1515ffd83dbSDimitry Andric return llvm::make_error<MissingDeclContext>(
1525ffd83dbSDimitry Andric foreign_ctxt,
1535ffd83dbSDimitry Andric "Couldn't find namespace " + ns->getQualifiedNameAsString());
1545ffd83dbSDimitry Andric }
1555ffd83dbSDimitry Andric
1565ffd83dbSDimitry Andric return llvm::make_error<MissingDeclContext>(foreign_ctxt, "Unknown context ");
1575ffd83dbSDimitry Andric }
1585ffd83dbSDimitry Andric
1595ffd83dbSDimitry Andric /// Returns true iff tryInstantiateStdTemplate supports instantiating a template
1605ffd83dbSDimitry Andric /// with the given template arguments.
templateArgsAreSupported(ArrayRef<TemplateArgument> a)1615ffd83dbSDimitry Andric static bool templateArgsAreSupported(ArrayRef<TemplateArgument> a) {
1625ffd83dbSDimitry Andric for (const TemplateArgument &arg : a) {
1635ffd83dbSDimitry Andric switch (arg.getKind()) {
1645ffd83dbSDimitry Andric case TemplateArgument::Type:
1655ffd83dbSDimitry Andric case TemplateArgument::Integral:
1665ffd83dbSDimitry Andric break;
1675ffd83dbSDimitry Andric default:
1685ffd83dbSDimitry Andric // TemplateArgument kind hasn't been handled yet.
1695ffd83dbSDimitry Andric return false;
1705ffd83dbSDimitry Andric }
1715ffd83dbSDimitry Andric }
1725ffd83dbSDimitry Andric return true;
1735ffd83dbSDimitry Andric }
1745ffd83dbSDimitry Andric
1755ffd83dbSDimitry Andric /// Constructor function for Clang declarations. Ensures that the created
1765ffd83dbSDimitry Andric /// declaration is registered with the ASTImporter.
1775ffd83dbSDimitry Andric template <typename T, typename... Args>
createDecl(ASTImporter & importer,Decl * from_d,Args &&...args)1785ffd83dbSDimitry Andric T *createDecl(ASTImporter &importer, Decl *from_d, Args &&... args) {
1795ffd83dbSDimitry Andric T *to_d = T::Create(std::forward<Args>(args)...);
1805ffd83dbSDimitry Andric importer.RegisterImportedDecl(from_d, to_d);
1815ffd83dbSDimitry Andric return to_d;
1825ffd83dbSDimitry Andric }
1835ffd83dbSDimitry Andric
tryInstantiateStdTemplate(Decl * d)184bdd1243dSDimitry Andric std::optional<Decl *> CxxModuleHandler::tryInstantiateStdTemplate(Decl *d) {
18581ad6265SDimitry Andric Log *log = GetLog(LLDBLog::Expressions);
1865ffd83dbSDimitry Andric
1875ffd83dbSDimitry Andric // If we don't have a template to instiantiate, then there is nothing to do.
1885ffd83dbSDimitry Andric auto td = dyn_cast<ClassTemplateSpecializationDecl>(d);
1895ffd83dbSDimitry Andric if (!td)
190bdd1243dSDimitry Andric return std::nullopt;
1915ffd83dbSDimitry Andric
1925ffd83dbSDimitry Andric // We only care about templates in the std namespace.
1935ffd83dbSDimitry Andric if (!td->getDeclContext()->isStdNamespace())
194bdd1243dSDimitry Andric return std::nullopt;
1955ffd83dbSDimitry Andric
1965ffd83dbSDimitry Andric // We have a list of supported template names.
197e8d8bef9SDimitry Andric if (!m_supported_templates.contains(td->getName()))
198bdd1243dSDimitry Andric return std::nullopt;
1995ffd83dbSDimitry Andric
2005ffd83dbSDimitry Andric // Early check if we even support instantiating this template. We do this
2015ffd83dbSDimitry Andric // before we import anything into the target AST.
2025ffd83dbSDimitry Andric auto &foreign_args = td->getTemplateInstantiationArgs();
2035ffd83dbSDimitry Andric if (!templateArgsAreSupported(foreign_args.asArray()))
204bdd1243dSDimitry Andric return std::nullopt;
2055ffd83dbSDimitry Andric
2065ffd83dbSDimitry Andric // Find the local DeclContext that corresponds to the DeclContext of our
2075ffd83dbSDimitry Andric // decl we want to import.
2085ffd83dbSDimitry Andric llvm::Expected<DeclContext *> to_context =
2095ffd83dbSDimitry Andric getEqualLocalDeclContext(*m_sema, td->getDeclContext());
2105ffd83dbSDimitry Andric if (!to_context) {
2115ffd83dbSDimitry Andric LLDB_LOG_ERROR(log, to_context.takeError(),
2125ffd83dbSDimitry Andric "Got error while searching equal local DeclContext for decl "
2135ffd83dbSDimitry Andric "'{1}':\n{0}",
2145ffd83dbSDimitry Andric td->getName());
215bdd1243dSDimitry Andric return std::nullopt;
2165ffd83dbSDimitry Andric }
2175ffd83dbSDimitry Andric
2185ffd83dbSDimitry Andric // Look up the template in our local context.
2195ffd83dbSDimitry Andric std::unique_ptr<LookupResult> lookup =
2205ffd83dbSDimitry Andric emulateLookupInCtxt(*m_sema, td->getName(), *to_context);
2215ffd83dbSDimitry Andric
2225ffd83dbSDimitry Andric ClassTemplateDecl *new_class_template = nullptr;
2235ffd83dbSDimitry Andric for (auto LD : *lookup) {
2245ffd83dbSDimitry Andric if ((new_class_template = dyn_cast<ClassTemplateDecl>(LD)))
2255ffd83dbSDimitry Andric break;
2265ffd83dbSDimitry Andric }
2275ffd83dbSDimitry Andric if (!new_class_template)
228bdd1243dSDimitry Andric return std::nullopt;
2295ffd83dbSDimitry Andric
2305ffd83dbSDimitry Andric // Import the foreign template arguments.
2315ffd83dbSDimitry Andric llvm::SmallVector<TemplateArgument, 4> imported_args;
2325ffd83dbSDimitry Andric
2335ffd83dbSDimitry Andric // If this logic is changed, also update templateArgsAreSupported.
2345ffd83dbSDimitry Andric for (const TemplateArgument &arg : foreign_args.asArray()) {
2355ffd83dbSDimitry Andric switch (arg.getKind()) {
2365ffd83dbSDimitry Andric case TemplateArgument::Type: {
2375ffd83dbSDimitry Andric llvm::Expected<QualType> type = m_importer->Import(arg.getAsType());
2385ffd83dbSDimitry Andric if (!type) {
2395ffd83dbSDimitry Andric LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}");
240bdd1243dSDimitry Andric return std::nullopt;
2415ffd83dbSDimitry Andric }
242*06c3fb27SDimitry Andric imported_args.push_back(
243*06c3fb27SDimitry Andric TemplateArgument(*type, /*isNullPtr*/ false, arg.getIsDefaulted()));
2445ffd83dbSDimitry Andric break;
2455ffd83dbSDimitry Andric }
2465ffd83dbSDimitry Andric case TemplateArgument::Integral: {
2475ffd83dbSDimitry Andric llvm::APSInt integral = arg.getAsIntegral();
2485ffd83dbSDimitry Andric llvm::Expected<QualType> type =
2495ffd83dbSDimitry Andric m_importer->Import(arg.getIntegralType());
2505ffd83dbSDimitry Andric if (!type) {
2515ffd83dbSDimitry Andric LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}");
252bdd1243dSDimitry Andric return std::nullopt;
2535ffd83dbSDimitry Andric }
254*06c3fb27SDimitry Andric imported_args.push_back(TemplateArgument(d->getASTContext(), integral,
255*06c3fb27SDimitry Andric *type, arg.getIsDefaulted()));
2565ffd83dbSDimitry Andric break;
2575ffd83dbSDimitry Andric }
2585ffd83dbSDimitry Andric default:
2595ffd83dbSDimitry Andric assert(false && "templateArgsAreSupported not updated?");
2605ffd83dbSDimitry Andric }
2615ffd83dbSDimitry Andric }
2625ffd83dbSDimitry Andric
2635ffd83dbSDimitry Andric // Find the class template specialization declaration that
2645ffd83dbSDimitry Andric // corresponds to these arguments.
2655ffd83dbSDimitry Andric void *InsertPos = nullptr;
2665ffd83dbSDimitry Andric ClassTemplateSpecializationDecl *result =
2675ffd83dbSDimitry Andric new_class_template->findSpecialization(imported_args, InsertPos);
2685ffd83dbSDimitry Andric
2695ffd83dbSDimitry Andric if (result) {
2705ffd83dbSDimitry Andric // We found an existing specialization in the module that fits our arguments
2715ffd83dbSDimitry Andric // so we can treat it as the result and register it with the ASTImporter.
2725ffd83dbSDimitry Andric m_importer->RegisterImportedDecl(d, result);
2735ffd83dbSDimitry Andric return result;
2745ffd83dbSDimitry Andric }
2755ffd83dbSDimitry Andric
2765ffd83dbSDimitry Andric // Instantiate the template.
2775ffd83dbSDimitry Andric result = createDecl<ClassTemplateSpecializationDecl>(
2785ffd83dbSDimitry Andric *m_importer, d, m_sema->getASTContext(),
2795ffd83dbSDimitry Andric new_class_template->getTemplatedDecl()->getTagKind(),
2805ffd83dbSDimitry Andric new_class_template->getDeclContext(),
2815ffd83dbSDimitry Andric new_class_template->getTemplatedDecl()->getLocation(),
2825ffd83dbSDimitry Andric new_class_template->getLocation(), new_class_template, imported_args,
2835ffd83dbSDimitry Andric nullptr);
2845ffd83dbSDimitry Andric
2855ffd83dbSDimitry Andric new_class_template->AddSpecialization(result, InsertPos);
2865ffd83dbSDimitry Andric if (new_class_template->isOutOfLine())
2875ffd83dbSDimitry Andric result->setLexicalDeclContext(
2885ffd83dbSDimitry Andric new_class_template->getLexicalDeclContext());
2895ffd83dbSDimitry Andric return result;
2905ffd83dbSDimitry Andric }
2915ffd83dbSDimitry Andric
Import(Decl * d)292bdd1243dSDimitry Andric std::optional<Decl *> CxxModuleHandler::Import(Decl *d) {
2935ffd83dbSDimitry Andric if (!isValid())
2945ffd83dbSDimitry Andric return {};
2955ffd83dbSDimitry Andric
2965ffd83dbSDimitry Andric return tryInstantiateStdTemplate(d);
2975ffd83dbSDimitry Andric }
298