import_cpp.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/import_cpp.h"
  5. #include <memory>
  6. #include <optional>
  7. #include <string>
  8. #include "clang/Frontend/TextDiagnostic.h"
  9. #include "clang/Sema/Lookup.h"
  10. #include "clang/Tooling/Tooling.h"
  11. #include "common/raw_string_ostream.h"
  12. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. #include "toolchain/check/class.h"
  16. #include "toolchain/check/context.h"
  17. #include "toolchain/check/convert.h"
  18. #include "toolchain/check/diagnostic_helpers.h"
  19. #include "toolchain/check/eval.h"
  20. #include "toolchain/check/import.h"
  21. #include "toolchain/check/inst.h"
  22. #include "toolchain/check/literal.h"
  23. #include "toolchain/check/type.h"
  24. #include "toolchain/diagnostics/diagnostic.h"
  25. #include "toolchain/diagnostics/format_providers.h"
  26. #include "toolchain/parse/node_ids.h"
  27. #include "toolchain/sem_ir/ids.h"
  28. #include "toolchain/sem_ir/name_scope.h"
  29. #include "toolchain/sem_ir/typed_insts.h"
  30. namespace Carbon::Check {
  31. // Generates C++ file contents to #include all requested imports.
  32. static auto GenerateCppIncludesHeaderCode(
  33. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  34. -> std::string {
  35. std::string code;
  36. llvm::raw_string_ostream code_stream(code);
  37. for (const Parse::Tree::PackagingNames& import : imports) {
  38. code_stream << "#include \""
  39. << FormatEscaped(
  40. context.string_literal_values().Get(import.library_id))
  41. << "\"\n";
  42. }
  43. return code;
  44. }
  45. namespace {
  46. // Used to convert Clang diagnostics to Carbon diagnostics.
  47. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  48. public:
  49. // Creates an instance with the location that triggers calling Clang.
  50. // `context` must not be null.
  51. explicit CarbonClangDiagnosticConsumer(Context* context, SemIRLoc loc)
  52. : context_(context), loc_(loc) {}
  53. // Generates a Carbon warning for each Clang warning and a Carbon error for
  54. // each Clang error or fatal.
  55. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  56. const clang::Diagnostic& info) -> void override {
  57. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  58. llvm::SmallString<256> message;
  59. info.FormatDiagnostic(message);
  60. RawStringOstream diagnostics_stream;
  61. clang::TextDiagnostic text_diagnostic(
  62. diagnostics_stream,
  63. // TODO: Consider allowing setting `LangOptions` or use
  64. // `ASTContext::getLangOptions()`.
  65. clang::LangOptions(),
  66. // TODO: Consider allowing setting `DiagnosticOptions` or use
  67. // `ASTUnit::getDiagnostics().::getLangOptions().getDiagnosticOptions()`.
  68. new clang::DiagnosticOptions());
  69. text_diagnostic.emitDiagnostic(
  70. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  71. diag_level, message, info.getRanges(), info.getFixItHints());
  72. std::string diagnostics_str = diagnostics_stream.TakeStr();
  73. switch (diag_level) {
  74. case clang::DiagnosticsEngine::Ignored:
  75. case clang::DiagnosticsEngine::Note:
  76. case clang::DiagnosticsEngine::Remark: {
  77. context_->TODO(
  78. loc_, llvm::formatv(
  79. "Unsupported: C++ diagnostic level for diagnostic\n{0}",
  80. diagnostics_str));
  81. return;
  82. }
  83. case clang::DiagnosticsEngine::Warning:
  84. case clang::DiagnosticsEngine::Error:
  85. case clang::DiagnosticsEngine::Fatal: {
  86. // TODO: Adjust diagnostics to drop the Carbon file here, and then
  87. // remove the "C++:\n" prefix.
  88. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "C++:\n{0}",
  89. std::string);
  90. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "C++:\n{0}",
  91. std::string);
  92. // TODO: This should be part of the location, instead of added as a note
  93. // here.
  94. CARBON_DIAGNOSTIC(InCppImport, Note, "in `Cpp` import");
  95. // TODO: Use a more specific location.
  96. context_->emitter()
  97. .Build(SemIR::LocId::None,
  98. diag_level == clang::DiagnosticsEngine::Warning
  99. ? CppInteropParseWarning
  100. : CppInteropParseError,
  101. diagnostics_str)
  102. .Note(loc_, InCppImport)
  103. .Emit();
  104. return;
  105. }
  106. }
  107. }
  108. private:
  109. // The type-checking context in which we're running Clang.
  110. Context* context_;
  111. // The location that triggered calling Clang.
  112. SemIRLoc loc_;
  113. };
  114. } // namespace
  115. // Returns an AST for the C++ imports and a bool that represents whether
  116. // compilation errors where encountered or the generated AST is null due to an
  117. // error.
  118. // TODO: Consider to always have a (non-null) AST.
  119. static auto GenerateAst(Context& context, llvm::StringRef importing_file_path,
  120. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  121. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs)
  122. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  123. // TODO: Use all import locations by referring each Clang diagnostic to the
  124. // relevant import.
  125. SemIRLoc loc = imports.back().node_id;
  126. CarbonClangDiagnosticConsumer diagnostics_consumer(&context, loc);
  127. // TODO: Share compilation flags with ClangRunner.
  128. auto ast = clang::tooling::buildASTFromCodeWithArgs(
  129. GenerateCppIncludesHeaderCode(context, imports),
  130. // Parse C++ (and not C)
  131. {"-x", "c++"}, (importing_file_path + ".generated.cpp_imports.h").str(),
  132. "clang-tool", std::make_shared<clang::PCHContainerOperations>(),
  133. clang::tooling::getClangStripDependencyFileAdjuster(),
  134. clang::tooling::FileContentMappings(), &diagnostics_consumer, fs);
  135. // Remove link to the diagnostics consumer before its deletion.
  136. ast->getDiagnostics().setClient(nullptr);
  137. return {std::move(ast), !ast || diagnostics_consumer.getNumErrors() > 0};
  138. }
  139. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  140. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  141. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  142. -> SemIR::NameScopeId {
  143. auto& import_cpps = context.sem_ir().import_cpps();
  144. import_cpps.Reserve(imports.size());
  145. for (const Parse::Tree::PackagingNames& import : imports) {
  146. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  147. import.node_id),
  148. .library_id = import.library_id});
  149. }
  150. return AddImportNamespaceToScope(
  151. context,
  152. GetSingletonType(context, SemIR::NamespaceType::SingletonInstId),
  153. SemIR::NameId::ForPackageName(cpp_package_id),
  154. SemIR::NameScopeId::Package,
  155. /*diagnose_duplicate_namespace=*/false,
  156. [&]() {
  157. return AddInst<SemIR::ImportCppDecl>(
  158. context,
  159. context.parse_tree().As<Parse::ImportDeclId>(
  160. imports.front().node_id),
  161. {});
  162. })
  163. .add_result.name_scope_id;
  164. }
  165. auto ImportCppFiles(Context& context, llvm::StringRef importing_file_path,
  166. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  167. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs)
  168. -> std::unique_ptr<clang::ASTUnit> {
  169. if (imports.empty()) {
  170. return nullptr;
  171. }
  172. CARBON_CHECK(!context.sem_ir().cpp_ast());
  173. auto [generated_ast, ast_has_error] =
  174. GenerateAst(context, importing_file_path, imports, fs);
  175. PackageNameId package_id = imports.front().package_id;
  176. CARBON_CHECK(
  177. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  178. return import.package_id == package_id;
  179. }));
  180. auto name_scope_id = AddNamespace(context, package_id, imports);
  181. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  182. name_scope.set_is_closed_import(true);
  183. name_scope.set_cpp_decl_context(
  184. generated_ast->getASTContext().getTranslationUnitDecl());
  185. context.sem_ir().set_cpp_ast(generated_ast.get());
  186. if (ast_has_error) {
  187. name_scope.set_has_error();
  188. }
  189. return std::move(generated_ast);
  190. }
  191. // Look ups the given name in the Clang AST in a specific scope. Returns the
  192. // lookup result if lookup was successful.
  193. static auto ClangLookup(Context& context, SemIR::NameScopeId scope_id,
  194. SemIR::NameId name_id)
  195. -> std::optional<clang::LookupResult> {
  196. std::optional<llvm::StringRef> name =
  197. context.names().GetAsStringIfIdentifier(name_id);
  198. if (!name) {
  199. // Special names never exist in C++ code.
  200. return std::nullopt;
  201. }
  202. clang::ASTUnit* ast = context.sem_ir().cpp_ast();
  203. CARBON_CHECK(ast);
  204. clang::Sema& sema = ast->getSema();
  205. clang::LookupResult lookup(
  206. sema,
  207. clang::DeclarationNameInfo(
  208. clang::DeclarationName(
  209. sema.getPreprocessor().getIdentifierInfo(*name)),
  210. clang::SourceLocation()),
  211. clang::Sema::LookupNameKind::LookupOrdinaryName);
  212. // TODO: Diagnose on access and return the `AccessKind` for storage. We'll
  213. // probably need a dedicated `DiagnosticConsumer` because
  214. // `TextDiagnosticPrinter` assumes we're processing a C++ source file.
  215. lookup.suppressDiagnostics();
  216. bool found = sema.LookupQualifiedName(
  217. lookup, context.name_scopes().Get(scope_id).cpp_decl_context());
  218. if (!found) {
  219. return std::nullopt;
  220. }
  221. return lookup;
  222. }
  223. // Creates an integer type of the given size.
  224. static auto MakeIntType(Context& context, IntId size_id) -> TypeExpr {
  225. // TODO: Fill in a location for the type once available.
  226. auto type_inst_id = MakeIntTypeLiteral(context, Parse::NodeId::None,
  227. SemIR::IntKind::Signed, size_id);
  228. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  229. }
  230. // Maps a C++ type to a Carbon type. Currently only 32-bit `int` is supported.
  231. // TODO: Support more types.
  232. static auto MapType(Context& context, clang::QualType type) -> TypeExpr {
  233. const auto* builtin_type = dyn_cast<clang::BuiltinType>(type);
  234. if (builtin_type && builtin_type->getKind() == clang::BuiltinType::Int &&
  235. context.ast_context().getTypeSize(type) == 32) {
  236. return MakeIntType(context, context.ints().Add(32));
  237. }
  238. return {.inst_id = SemIR::ErrorInst::SingletonInstId,
  239. .type_id = SemIR::ErrorInst::SingletonTypeId};
  240. }
  241. // Returns a block id for the explicit parameters of the given function
  242. // declaration. If the function declaration has no parameters, it returns
  243. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  244. // returns `SemIR::InstBlockId::None`.
  245. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  246. const clang::FunctionDecl& clang_decl)
  247. -> SemIR::InstBlockId {
  248. if (clang_decl.parameters().empty()) {
  249. return SemIR::InstBlockId::Empty;
  250. }
  251. SemIR::CallParamIndex next_index(0);
  252. llvm::SmallVector<SemIR::InstId> params;
  253. params.reserve(clang_decl.parameters().size());
  254. for (const clang::ParmVarDecl* param : clang_decl.parameters()) {
  255. clang::QualType param_type = param->getType().getCanonicalType();
  256. SemIR::TypeId type_id = MapType(context, param_type).type_id;
  257. if (type_id == SemIR::ErrorInst::SingletonTypeId) {
  258. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  259. param_type.getAsString()));
  260. return SemIR::InstBlockId::None;
  261. }
  262. llvm::StringRef param_name = param->getName();
  263. SemIR::EntityNameId entity_name_id = context.entity_names().Add(
  264. {.name_id =
  265. (param_name.empty())
  266. // Translate an unnamed parameter to an underscore to
  267. // match Carbon's naming of unnamed/unused function params.
  268. ? SemIR::NameId::Underscore
  269. : SemIR::NameId::ForIdentifier(
  270. context.sem_ir().identifiers().Add(param_name)),
  271. .parent_scope_id = SemIR::NameScopeId::None});
  272. SemIR::InstId binding_pattern_id = AddInstInNoBlock(
  273. // TODO: Fill in a location once available.
  274. context, SemIR::LocIdAndInst::NoLoc(SemIR::BindingPattern(
  275. {.type_id = type_id, .entity_name_id = entity_name_id})));
  276. SemIR::InstId var_pattern_id = AddInstInNoBlock(
  277. context,
  278. // TODO: Fill in a location once available.
  279. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  280. {.type_id = context.insts().Get(binding_pattern_id).type_id(),
  281. .subpattern_id = binding_pattern_id,
  282. .index = next_index})));
  283. ++next_index.index;
  284. params.push_back(var_pattern_id);
  285. }
  286. return context.inst_blocks().Add(params);
  287. }
  288. // Returns the return type of the given function declaration.
  289. // Currently only void and 32-bit int are supported.
  290. // TODO: Support more return types.
  291. static auto GetReturnType(Context& context, SemIRLoc loc_id,
  292. const clang::FunctionDecl* clang_decl)
  293. -> SemIR::InstId {
  294. clang::QualType ret_type = clang_decl->getReturnType().getCanonicalType();
  295. if (ret_type->isVoidType()) {
  296. return SemIR::InstId::None;
  297. }
  298. auto [type_inst_id, type_id] = MapType(context, ret_type);
  299. if (type_id == SemIR::ErrorInst::SingletonTypeId) {
  300. context.TODO(loc_id, llvm::formatv("Unsupported: return type: {0}",
  301. ret_type.getAsString()));
  302. return SemIR::ErrorInst::SingletonInstId;
  303. }
  304. SemIR::InstId return_slot_pattern_id = AddInstInNoBlock(
  305. // TODO: Fill in a location for the return type once available.
  306. context, SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  307. {.type_id = type_id, .type_inst_id = type_inst_id})));
  308. SemIR::InstId param_pattern_id = AddInstInNoBlock(
  309. // TODO: Fill in a location for the return type once available.
  310. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  311. {.type_id = type_id,
  312. .subpattern_id = return_slot_pattern_id,
  313. .index = SemIR::CallParamIndex::None})));
  314. return param_pattern_id;
  315. }
  316. // Imports a function declaration from Clang to Carbon. If successful, returns
  317. // the new Carbon function declaration `InstId`.
  318. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  319. SemIR::NameScopeId scope_id,
  320. SemIR::NameId name_id,
  321. const clang::FunctionDecl* clang_decl)
  322. -> SemIR::InstId {
  323. if (clang_decl->isVariadic()) {
  324. context.TODO(loc_id, "Unsupported: Variadic function");
  325. return SemIR::ErrorInst::SingletonInstId;
  326. }
  327. if (!clang_decl->isGlobal()) {
  328. context.TODO(loc_id, "Unsupported: Non-global function");
  329. return SemIR::ErrorInst::SingletonInstId;
  330. }
  331. if (clang_decl->getTemplatedKind() != clang::FunctionDecl::TK_NonTemplate) {
  332. context.TODO(loc_id, "Unsupported: Template function");
  333. return SemIR::ErrorInst::SingletonInstId;
  334. }
  335. auto param_patterns_id =
  336. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  337. if (!param_patterns_id.has_value()) {
  338. return SemIR::ErrorInst::SingletonInstId;
  339. }
  340. auto return_slot_pattern_id = GetReturnType(context, loc_id, clang_decl);
  341. if (SemIR::ErrorInst::SingletonInstId == return_slot_pattern_id) {
  342. return SemIR::ErrorInst::SingletonInstId;
  343. }
  344. auto function_decl = SemIR::FunctionDecl{
  345. SemIR::TypeId::None, SemIR::FunctionId::None, SemIR::InstBlockId::Empty};
  346. auto decl_id =
  347. AddPlaceholderInst(context, Parse::NodeId::None, function_decl);
  348. auto function_info = SemIR::Function{
  349. {.name_id = name_id,
  350. .parent_scope_id = scope_id,
  351. .generic_id = SemIR::GenericId::None,
  352. .first_param_node_id = Parse::NodeId::None,
  353. .last_param_node_id = Parse::NodeId::None,
  354. .pattern_block_id = SemIR::InstBlockId::Empty,
  355. .implicit_param_patterns_id = SemIR::InstBlockId::Empty,
  356. .param_patterns_id = param_patterns_id,
  357. .is_extern = false,
  358. .extern_library_id = SemIR::LibraryNameId::None,
  359. .non_owning_decl_id = SemIR::InstId::None,
  360. .first_owning_decl_id = decl_id,
  361. .definition_id = SemIR::InstId::None},
  362. {.call_params_id = SemIR::InstBlockId::Empty,
  363. .return_slot_pattern_id = return_slot_pattern_id,
  364. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  365. .self_param_id = SemIR::InstId::None,
  366. .cpp_decl = clang_decl}};
  367. function_decl.function_id = context.functions().Add(function_info);
  368. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  369. SemIR::SpecificId::None);
  370. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  371. return decl_id;
  372. }
  373. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  374. // the new Carbon namespace declaration `InstId`.
  375. static auto ImportNamespaceDecl(Context& context,
  376. SemIR::NameScopeId parent_scope_id,
  377. SemIR::NameId name_id,
  378. clang::NamespaceDecl* clang_decl)
  379. -> SemIR::InstId {
  380. auto result = AddImportNamespace(
  381. context, GetSingletonType(context, SemIR::NamespaceType::SingletonInstId),
  382. name_id, parent_scope_id, /*import_id=*/SemIR::InstId::None);
  383. context.name_scopes()
  384. .Get(result.name_scope_id)
  385. .set_cpp_decl_context(clang_decl);
  386. return result.inst_id;
  387. }
  388. // Creates a class declaration for the given class name in the given scope.
  389. // Returns the `InstId` for the declaration.
  390. static auto BuildClassDecl(Context& context, SemIR::NameScopeId parent_scope_id,
  391. SemIR::NameId name_id)
  392. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  393. // Add the class declaration.
  394. auto class_decl =
  395. SemIR::ClassDecl{.type_id = SemIR::TypeType::SingletonTypeId,
  396. .class_id = SemIR::ClassId::None,
  397. .decl_block_id = SemIR::InstBlockId::None};
  398. // TODO: Consider setting a proper location.
  399. auto class_decl_id =
  400. AddPlaceholderInst(context, SemIR::LocIdAndInst::NoLoc(class_decl));
  401. SemIR::Class class_info = {
  402. {.name_id = name_id,
  403. .parent_scope_id = parent_scope_id,
  404. .generic_id = SemIR::GenericId::None,
  405. .first_param_node_id = Parse::NodeId::None,
  406. .last_param_node_id = Parse::NodeId::None,
  407. .pattern_block_id = SemIR::InstBlockId::None,
  408. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  409. .param_patterns_id = SemIR::InstBlockId::None,
  410. .is_extern = false,
  411. .extern_library_id = SemIR::LibraryNameId::None,
  412. .non_owning_decl_id = SemIR::InstId::None,
  413. .first_owning_decl_id = class_decl_id},
  414. {// `.self_type_id` depends on the ClassType, so is set below.
  415. .self_type_id = SemIR::TypeId::None,
  416. // TODO: Support Dynamic classes.
  417. // TODO: Support Final classes.
  418. .inheritance_kind = SemIR::Class::Base}};
  419. class_decl.class_id = context.classes().Add(class_info);
  420. // Write the class ID into the ClassDecl.
  421. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  422. SetClassSelfType(context, class_decl.class_id);
  423. return {class_decl.class_id, class_decl_id};
  424. }
  425. // Creates a class definition for the given class name in the given scope based
  426. // on the information in the given Clang declaration. Returns the `InstId` for
  427. // the declaration, which is assumed to be for a class definition. Returns the
  428. // new class id and instruction id.
  429. static auto BuildClassDefinition(Context& context,
  430. SemIR::NameScopeId parent_scope_id,
  431. SemIR::NameId name_id,
  432. clang::CXXRecordDecl* clang_decl)
  433. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  434. auto [class_id, class_decl_id] =
  435. BuildClassDecl(context, parent_scope_id, name_id);
  436. auto& class_info = context.classes().Get(class_id);
  437. StartClassDefinition(context, class_info, class_decl_id);
  438. context.name_scopes()
  439. .Get(class_info.scope_id)
  440. .set_cpp_decl_context(clang_decl);
  441. return {class_id, class_decl_id};
  442. }
  443. // Imports a record declaration from Clang to Carbon. If successful, returns
  444. // the new Carbon class declaration `InstId`.
  445. // TODO: Change `clang_decl` to `const &` when lookup is using `clang::DeclID`
  446. // and we don't need to store the decl for lookup context.
  447. static auto ImportCXXRecordDecl(Context& context, SemIR::LocId loc_id,
  448. SemIR::NameScopeId parent_scope_id,
  449. SemIR::NameId name_id,
  450. clang::CXXRecordDecl* clang_decl)
  451. -> SemIR::InstId {
  452. clang::CXXRecordDecl* clang_def = clang_decl->getDefinition();
  453. if (!clang_def) {
  454. context.TODO(loc_id,
  455. "Unsupported: Record declarations without a definition");
  456. return SemIR::ErrorInst::SingletonInstId;
  457. }
  458. if (clang_def->isDynamicClass()) {
  459. context.TODO(loc_id, "Unsupported: Dynamic Class");
  460. return SemIR::ErrorInst::SingletonInstId;
  461. }
  462. auto [class_id, class_def_id] =
  463. BuildClassDefinition(context, parent_scope_id, name_id, clang_def);
  464. // The class type is now fully defined. Compute its object representation.
  465. ComputeClassObjectRepr(context,
  466. // TODO: Consider having a proper location here.
  467. Parse::NodeId::None, class_id,
  468. // TODO: Set fields.
  469. /*field_decls=*/{},
  470. // TODO: Set vtable.
  471. /*vtable_contents=*/{},
  472. // TODO: Set block.
  473. /*body=*/{});
  474. return class_def_id;
  475. }
  476. // Imports a declaration from Clang to Carbon. If successful, returns the
  477. // instruction for the new Carbon declaration.
  478. static auto ImportNameDecl(Context& context, SemIR::LocId loc_id,
  479. SemIR::NameScopeId scope_id, SemIR::NameId name_id,
  480. clang::NamedDecl* clang_decl) -> SemIR::InstId {
  481. if (const auto* clang_function_decl =
  482. clang::dyn_cast<clang::FunctionDecl>(clang_decl)) {
  483. return ImportFunctionDecl(context, loc_id, scope_id, name_id,
  484. clang_function_decl);
  485. }
  486. if (auto* clang_namespace_decl =
  487. clang::dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  488. return ImportNamespaceDecl(context, scope_id, name_id,
  489. clang_namespace_decl);
  490. }
  491. if (auto* clang_record_decl =
  492. clang::dyn_cast<clang::CXXRecordDecl>(clang_decl)) {
  493. return ImportCXXRecordDecl(context, loc_id, scope_id, name_id,
  494. clang_record_decl);
  495. }
  496. context.TODO(loc_id, llvm::formatv("Unsupported: Declaration type {0}",
  497. clang_decl->getDeclKindName())
  498. .str());
  499. return SemIR::InstId::None;
  500. }
  501. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  502. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  503. -> SemIR::InstId {
  504. Diagnostics::AnnotationScope annotate_diagnostics(
  505. &context.emitter(), [&](auto& builder) {
  506. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  507. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  508. builder.Note(loc_id, InCppNameLookup, name_id);
  509. });
  510. auto lookup = ClangLookup(context, scope_id, name_id);
  511. if (!lookup) {
  512. return SemIR::InstId::None;
  513. }
  514. if (!lookup->isSingleResult()) {
  515. context.TODO(loc_id,
  516. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  517. "find a single result; LookupResultKind: {0}",
  518. lookup->getResultKind())
  519. .str());
  520. return SemIR::ErrorInst::SingletonInstId;
  521. }
  522. return ImportNameDecl(context, loc_id, scope_id, name_id,
  523. lookup->getFoundDecl());
  524. }
  525. } // namespace Carbon::Check