import_cpp.cpp 29 KB

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