import_cpp.cpp 26 KB

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