import_cpp.cpp 24 KB

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