import_cpp.cpp 26 KB

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