import_cpp.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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/Basic/FileManager.h"
  11. #include "clang/Frontend/ASTUnit.h"
  12. #include "clang/Frontend/CompilerInstance.h"
  13. #include "clang/Frontend/CompilerInvocation.h"
  14. #include "clang/Frontend/TextDiagnostic.h"
  15. #include "clang/Lex/PreprocessorOptions.h"
  16. #include "clang/Sema/Lookup.h"
  17. #include "common/ostream.h"
  18. #include "common/raw_string_ostream.h"
  19. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include "toolchain/check/class.h"
  23. #include "toolchain/check/context.h"
  24. #include "toolchain/check/convert.h"
  25. #include "toolchain/check/diagnostic_helpers.h"
  26. #include "toolchain/check/eval.h"
  27. #include "toolchain/check/function.h"
  28. #include "toolchain/check/import.h"
  29. #include "toolchain/check/inst.h"
  30. #include "toolchain/check/literal.h"
  31. #include "toolchain/check/pattern.h"
  32. #include "toolchain/check/pattern_match.h"
  33. #include "toolchain/check/type.h"
  34. #include "toolchain/diagnostics/diagnostic.h"
  35. #include "toolchain/diagnostics/diagnostic_emitter.h"
  36. #include "toolchain/diagnostics/format_providers.h"
  37. #include "toolchain/parse/node_ids.h"
  38. #include "toolchain/sem_ir/clang_decl.h"
  39. #include "toolchain/sem_ir/ids.h"
  40. #include "toolchain/sem_ir/name_scope.h"
  41. #include "toolchain/sem_ir/typed_insts.h"
  42. namespace Carbon::Check {
  43. // Generates C++ file contents to #include all requested imports.
  44. static auto GenerateCppIncludesHeaderCode(
  45. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  46. -> std::string {
  47. std::string code;
  48. llvm::raw_string_ostream code_stream(code);
  49. for (const Parse::Tree::PackagingNames& import : imports) {
  50. // Add a line marker directive pointing at the location of the `import Cpp`
  51. // declaration in the Carbon source file. This will cause Clang's
  52. // diagnostics machinery to track and report the location in Carbon code
  53. // where the import was written.
  54. auto token = context.parse_tree().node_token(import.node_id);
  55. code_stream << "# " << context.tokens().GetLineNumber(token) << " \""
  56. << FormatEscaped(context.tokens().source().filename())
  57. << "\"\n";
  58. code_stream << "#include \""
  59. << FormatEscaped(
  60. context.string_literal_values().Get(import.library_id))
  61. << "\"\n";
  62. }
  63. return code;
  64. }
  65. // Adds the name to the scope with the given `inst_id`, if the `inst_id` is not
  66. // `None`.
  67. static auto AddNameToScope(Context& context, SemIR::NameScopeId scope_id,
  68. SemIR::NameId name_id, SemIR::InstId inst_id)
  69. -> void {
  70. if (inst_id.has_value()) {
  71. context.name_scopes().AddRequiredName(scope_id, name_id, inst_id);
  72. }
  73. }
  74. // Maps a Clang name to a Carbon `NameId`.
  75. static auto AddIdentifierName(Context& context, llvm::StringRef name)
  76. -> SemIR::NameId {
  77. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  78. }
  79. // Adds the given source location and an `ImportIRInst` referring to it in
  80. // `ImportIRId::Cpp`.
  81. static auto AddImportIRInst(Context& context,
  82. clang::SourceLocation clang_source_loc)
  83. -> SemIR::ImportIRInstId {
  84. SemIR::ClangSourceLocId clang_source_loc_id =
  85. context.sem_ir().clang_source_locs().Add(clang_source_loc);
  86. return context.import_ir_insts().Add(
  87. SemIR::ImportIRInst(clang_source_loc_id));
  88. }
  89. namespace {
  90. // Used to convert Clang diagnostics to Carbon diagnostics.
  91. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  92. public:
  93. // Creates an instance with the location that triggers calling Clang.
  94. // `context` must not be null.
  95. explicit CarbonClangDiagnosticConsumer(Context* context,
  96. clang::CompilerInvocation* invocation)
  97. : context_(context), invocation_(invocation) {}
  98. // Generates a Carbon warning for each Clang warning and a Carbon error for
  99. // each Clang error or fatal.
  100. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  101. const clang::Diagnostic& info) -> void override {
  102. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  103. SemIR::ImportIRInstId clang_import_ir_inst_id =
  104. AddImportIRInst(*context_, info.getLocation());
  105. llvm::SmallString<256> message;
  106. info.FormatDiagnostic(message);
  107. if (!info.hasSourceManager()) {
  108. // If we don't have a source manager, we haven't actually started
  109. // compiling yet, and this is an error from the driver or early in the
  110. // frontend. Pass it on directly.
  111. CARBON_CHECK(info.getLocation().isInvalid());
  112. diagnostic_infos_.push_back({.level = diag_level,
  113. .import_ir_inst_id = clang_import_ir_inst_id,
  114. .message = message.str().str()});
  115. return;
  116. }
  117. RawStringOstream diagnostics_stream;
  118. clang::TextDiagnostic text_diagnostic(diagnostics_stream,
  119. invocation_->getLangOpts(),
  120. invocation_->getDiagnosticOpts());
  121. text_diagnostic.emitDiagnostic(
  122. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  123. diag_level, message, info.getRanges(), info.getFixItHints());
  124. std::string diagnostics_str = diagnostics_stream.TakeStr();
  125. diagnostic_infos_.push_back({.level = diag_level,
  126. .import_ir_inst_id = clang_import_ir_inst_id,
  127. .message = diagnostics_str});
  128. }
  129. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  130. // be called after the AST is set in the context.
  131. auto EmitDiagnostics() -> void {
  132. for (const ClangDiagnosticInfo& info : diagnostic_infos_) {
  133. switch (info.level) {
  134. case clang::DiagnosticsEngine::Ignored:
  135. case clang::DiagnosticsEngine::Note:
  136. case clang::DiagnosticsEngine::Remark: {
  137. context_->TODO(
  138. SemIR::LocId(info.import_ir_inst_id),
  139. llvm::formatv(
  140. "Unsupported: C++ diagnostic level for diagnostic\n{0}",
  141. info.message));
  142. break;
  143. }
  144. case clang::DiagnosticsEngine::Warning:
  145. case clang::DiagnosticsEngine::Error:
  146. case clang::DiagnosticsEngine::Fatal: {
  147. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}",
  148. std::string);
  149. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  150. context_->emitter().Emit(
  151. SemIR::LocId(info.import_ir_inst_id),
  152. info.level == clang::DiagnosticsEngine::Warning
  153. ? CppInteropParseWarning
  154. : CppInteropParseError,
  155. info.message);
  156. break;
  157. }
  158. }
  159. }
  160. }
  161. private:
  162. // The type-checking context in which we're running Clang.
  163. Context* context_;
  164. // The compiler invocation that is producing the diagnostics.
  165. clang::CompilerInvocation* invocation_;
  166. // Information on a Clang diagnostic that can be converted to a Carbon
  167. // diagnostic.
  168. struct ClangDiagnosticInfo {
  169. // The Clang diagnostic level.
  170. clang::DiagnosticsEngine::Level level;
  171. // The ID of the ImportIR instruction referring to the Clang source
  172. // location.
  173. SemIR::ImportIRInstId import_ir_inst_id;
  174. // The Clang diagnostic textual message.
  175. std::string message;
  176. };
  177. // Collects the information for all Clang diagnostics to be converted to
  178. // Carbon diagnostics after the context has been initialized with the Clang
  179. // AST.
  180. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  181. };
  182. } // namespace
  183. // Returns an AST for the C++ imports and a bool that represents whether
  184. // compilation errors where encountered or the generated AST is null due to an
  185. // error. Sets the AST in the context's `sem_ir`.
  186. // TODO: Consider to always have a (non-null) AST.
  187. static auto GenerateAst(Context& context,
  188. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  189. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  190. std::shared_ptr<clang::CompilerInvocation> invocation)
  191. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  192. // Build a diagnostics engine.
  193. CarbonClangDiagnosticConsumer diagnostics_consumer(&context,
  194. invocation.get());
  195. llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diags(
  196. clang::CompilerInstance::createDiagnostics(
  197. *fs, invocation->getDiagnosticOpts(), &diagnostics_consumer,
  198. /*ShouldOwnClient=*/false));
  199. // Extract the input from the frontend invocation and make sure it makes
  200. // sense.
  201. const auto& inputs = invocation->getFrontendOpts().Inputs;
  202. CARBON_CHECK(inputs.size() == 1 &&
  203. inputs[0].getKind().getLanguage() == clang::Language::CXX &&
  204. inputs[0].getKind().getFormat() == clang::InputKind::Source);
  205. llvm::StringRef file_name = inputs[0].getFile();
  206. // Remap the imports file name to the corresponding `#include`s.
  207. // TODO: Modify the frontend options to specify this memory buffer as input
  208. // instead of remapping the file.
  209. std::string includes = GenerateCppIncludesHeaderCode(context, imports);
  210. auto includes_buffer = llvm::MemoryBuffer::getMemBuffer(includes, file_name);
  211. invocation->getPreprocessorOpts().addRemappedFile(file_name,
  212. includes_buffer.get());
  213. // Create the AST unit.
  214. auto ast = clang::ASTUnit::LoadFromCompilerInvocation(
  215. invocation, std::make_shared<clang::PCHContainerOperations>(), nullptr,
  216. diags, new clang::FileManager(invocation->getFileSystemOpts(), fs));
  217. // Remove link to the diagnostics consumer before its destruction.
  218. ast->getDiagnostics().setClient(nullptr);
  219. // Remove remapped file before its underlying storage is destroyed.
  220. invocation->getPreprocessorOpts().clearRemappedFiles();
  221. // Attach the AST to SemIR. This needs to be done before we can emit any
  222. // diagnostics, so their locations can be properly interpreted by our
  223. // diagnostics machinery.
  224. context.sem_ir().set_cpp_ast(ast.get());
  225. // Emit any diagnostics we queued up while building the AST.
  226. diagnostics_consumer.EmitDiagnostics();
  227. return {std::move(ast), !ast || diagnostics_consumer.getNumErrors() > 0};
  228. }
  229. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  230. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  231. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  232. -> SemIR::NameScopeId {
  233. auto& import_cpps = context.sem_ir().import_cpps();
  234. import_cpps.Reserve(imports.size());
  235. for (const Parse::Tree::PackagingNames& import : imports) {
  236. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  237. import.node_id),
  238. .library_id = import.library_id});
  239. }
  240. return AddImportNamespaceToScope(
  241. context,
  242. GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  243. SemIR::NameId::ForPackageName(cpp_package_id),
  244. SemIR::NameScopeId::Package,
  245. /*diagnose_duplicate_namespace=*/false,
  246. [&]() {
  247. return AddInst<SemIR::ImportCppDecl>(
  248. context,
  249. context.parse_tree().As<Parse::ImportDeclId>(
  250. imports.front().node_id),
  251. {});
  252. })
  253. .add_result.name_scope_id;
  254. }
  255. auto ImportCppFiles(Context& context,
  256. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  257. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  258. std::shared_ptr<clang::CompilerInvocation> invocation)
  259. -> std::unique_ptr<clang::ASTUnit> {
  260. if (imports.empty()) {
  261. return nullptr;
  262. }
  263. CARBON_CHECK(!context.sem_ir().cpp_ast());
  264. PackageNameId package_id = imports.front().package_id;
  265. CARBON_CHECK(
  266. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  267. return import.package_id == package_id;
  268. }));
  269. auto name_scope_id = AddNamespace(context, package_id, imports);
  270. auto [generated_ast, ast_has_error] =
  271. GenerateAst(context, imports, fs, std::move(invocation));
  272. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  273. name_scope.set_is_closed_import(true);
  274. name_scope.set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  275. {.decl = generated_ast->getASTContext().getTranslationUnitDecl(),
  276. .inst_id = name_scope.inst_id()}));
  277. if (ast_has_error) {
  278. name_scope.set_has_error();
  279. }
  280. return std::move(generated_ast);
  281. }
  282. // Look ups the given name in the Clang AST in a specific scope. Returns the
  283. // lookup result if lookup was successful.
  284. static auto ClangLookup(Context& context, SemIR::NameScopeId scope_id,
  285. SemIR::NameId name_id)
  286. -> std::optional<clang::LookupResult> {
  287. std::optional<llvm::StringRef> name =
  288. context.names().GetAsStringIfIdentifier(name_id);
  289. if (!name) {
  290. // Special names never exist in C++ code.
  291. return std::nullopt;
  292. }
  293. clang::ASTUnit* ast = context.sem_ir().cpp_ast();
  294. CARBON_CHECK(ast);
  295. clang::Sema& sema = ast->getSema();
  296. clang::LookupResult lookup(
  297. sema,
  298. clang::DeclarationNameInfo(
  299. clang::DeclarationName(
  300. sema.getPreprocessor().getIdentifierInfo(*name)),
  301. clang::SourceLocation()),
  302. clang::Sema::LookupNameKind::LookupOrdinaryName);
  303. // TODO: Diagnose on access and return the `AccessKind` for storage. We'll
  304. // probably need a dedicated `DiagnosticConsumer` because
  305. // `TextDiagnosticPrinter` assumes we're processing a C++ source file.
  306. lookup.suppressDiagnostics();
  307. auto scope_clang_decl_context_id =
  308. context.name_scopes().Get(scope_id).clang_decl_context_id();
  309. bool found = sema.LookupQualifiedName(
  310. lookup,
  311. clang::dyn_cast<clang::DeclContext>(context.sem_ir()
  312. .clang_decls()
  313. .Get(scope_clang_decl_context_id)
  314. .decl));
  315. if (!found) {
  316. return std::nullopt;
  317. }
  318. return lookup;
  319. }
  320. // If `decl` already mapped to an instruction, returns that instruction.
  321. // Otherwise returns `None`.
  322. static auto LookupClangDeclInstId(Context& context, clang::Decl* decl)
  323. -> SemIR::InstId {
  324. auto& clang_decls = context.sem_ir().clang_decls();
  325. if (auto context_clang_decl_id = clang_decls.Lookup(decl);
  326. context_clang_decl_id.has_value()) {
  327. return clang_decls.Get(context_clang_decl_id).inst_id;
  328. }
  329. return SemIR::InstId::None;
  330. }
  331. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  332. // the new Carbon namespace declaration `InstId`. If the declaration was already
  333. // imported, returns the mapped instruction.
  334. static auto ImportNamespaceDecl(Context& context,
  335. SemIR::NameScopeId parent_scope_id,
  336. SemIR::NameId name_id,
  337. clang::NamespaceDecl* clang_decl)
  338. -> SemIR::InstId {
  339. auto result = AddImportNamespace(
  340. context, GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  341. name_id, parent_scope_id, /*import_id=*/SemIR::InstId::None);
  342. context.name_scopes()
  343. .Get(result.name_scope_id)
  344. .set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  345. {.decl = clang_decl, .inst_id = result.inst_id}));
  346. return result.inst_id;
  347. }
  348. // Maps a C++ declaration context to a Carbon namespace.
  349. static auto AsCarbonNamespace(Context& context,
  350. clang::DeclContext* decl_context)
  351. -> SemIR::InstId {
  352. CARBON_CHECK(decl_context);
  353. // Check if the declaration is already mapped.
  354. // TODO: Try to avoid this check by rotating the loops below so they treat the
  355. // given decl_context the same at its enclosing contexts.
  356. if (SemIR::InstId existing_inst_id = LookupClangDeclInstId(
  357. context, clang::dyn_cast<clang::Decl>(decl_context));
  358. existing_inst_id.has_value()) {
  359. return existing_inst_id;
  360. }
  361. auto& clang_decls = context.sem_ir().clang_decls();
  362. // We know we have at least one context to map, add all decl contexts we need
  363. // to map.
  364. llvm::SmallVector<clang::DeclContext*> decl_contexts;
  365. auto parent_decl_id = SemIR::ClangDeclId::None;
  366. do {
  367. decl_contexts.push_back(decl_context);
  368. decl_context = decl_context->getParent();
  369. parent_decl_id =
  370. clang_decls.Lookup(clang::dyn_cast<clang::Decl>(decl_context));
  371. } while (!parent_decl_id.has_value());
  372. // We know the parent of the last decl context is mapped, map the rest.
  373. auto namespace_inst_id = SemIR::InstId::None;
  374. do {
  375. decl_context = decl_contexts.pop_back_val();
  376. auto parent_inst_id = clang_decls.Get(parent_decl_id).inst_id;
  377. auto parent_namespace =
  378. context.insts().GetAs<SemIR::Namespace>(parent_inst_id);
  379. namespace_inst_id = ImportNamespaceDecl(
  380. context, parent_namespace.name_scope_id,
  381. AddIdentifierName(
  382. context, llvm::dyn_cast<clang::NamedDecl>(decl_context)->getName()),
  383. clang::dyn_cast<clang::NamespaceDecl>(decl_context));
  384. parent_decl_id = clang_decls.Add({
  385. .decl = clang::dyn_cast<clang::Decl>(decl_context),
  386. .inst_id = namespace_inst_id,
  387. });
  388. } while (!decl_contexts.empty());
  389. return namespace_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 = AddPlaceholderInstInNoBlock(
  402. context, SemIR::LocIdAndInst::NoLoc(class_decl));
  403. context.imports().push_back(class_decl_id);
  404. SemIR::Class class_info = {
  405. {.name_id = name_id,
  406. .parent_scope_id = parent_scope_id,
  407. .generic_id = SemIR::GenericId::None,
  408. .first_param_node_id = Parse::NodeId::None,
  409. .last_param_node_id = Parse::NodeId::None,
  410. .pattern_block_id = SemIR::InstBlockId::None,
  411. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  412. .param_patterns_id = SemIR::InstBlockId::None,
  413. .is_extern = false,
  414. .extern_library_id = SemIR::LibraryNameId::None,
  415. .non_owning_decl_id = SemIR::InstId::None,
  416. .first_owning_decl_id = class_decl_id},
  417. {// `.self_type_id` depends on the ClassType, so is set below.
  418. .self_type_id = SemIR::TypeId::None,
  419. // TODO: Support Dynamic classes.
  420. // TODO: Support Final classes.
  421. .inheritance_kind = SemIR::Class::Base}};
  422. class_decl.class_id = context.classes().Add(class_info);
  423. // Write the class ID into the ClassDecl.
  424. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  425. SetClassSelfType(context, class_decl.class_id);
  426. return {class_decl.class_id, class_decl_id};
  427. }
  428. // Creates a class definition for the given class name in the given scope based
  429. // on the information in the given Clang declaration. Returns the `InstId` for
  430. // the declaration, which is assumed to be for a class definition. Returns the
  431. // new class id and instruction id.
  432. static auto BuildClassDefinition(Context& context,
  433. SemIR::NameScopeId parent_scope_id,
  434. SemIR::NameId name_id,
  435. clang::CXXRecordDecl* clang_decl)
  436. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  437. auto [class_id, class_inst_id] =
  438. BuildClassDecl(context, parent_scope_id, name_id);
  439. auto& class_info = context.classes().Get(class_id);
  440. StartClassDefinition(context, class_info, class_inst_id);
  441. context.name_scopes()
  442. .Get(class_info.scope_id)
  443. .set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  444. {.decl = clang_decl, .inst_id = class_inst_id}));
  445. return {class_id, class_inst_id};
  446. }
  447. // Mark the given `Decl` as failed in `clang_decls`.
  448. static auto MarkFailedDecl(Context& context, clang::Decl* clang_decl) {
  449. context.sem_ir().clang_decls().Add(
  450. {.decl = clang_decl, .inst_id = SemIR::ErrorInst::InstId});
  451. }
  452. // Imports a record declaration from Clang to Carbon. If successful, returns
  453. // the new Carbon class declaration `InstId`.
  454. // TODO: Change `clang_decl` to `const &` when lookup is using `clang::DeclID`
  455. // and we don't need to store the decl for lookup context.
  456. static auto ImportCXXRecordDecl(Context& context, SemIR::LocId loc_id,
  457. SemIR::NameScopeId parent_scope_id,
  458. SemIR::NameId name_id,
  459. clang::CXXRecordDecl* clang_decl)
  460. -> SemIR::InstId {
  461. clang::CXXRecordDecl* clang_def = clang_decl->getDefinition();
  462. if (!clang_def) {
  463. context.TODO(loc_id,
  464. "Unsupported: Record declarations without a definition");
  465. MarkFailedDecl(context, clang_decl);
  466. return SemIR::ErrorInst::InstId;
  467. }
  468. if (clang_def->isDynamicClass()) {
  469. context.TODO(loc_id, "Unsupported: Dynamic Class");
  470. MarkFailedDecl(context, clang_decl);
  471. return SemIR::ErrorInst::InstId;
  472. }
  473. if (clang_def->isUnion() && !clang_def->fields().empty()) {
  474. context.TODO(loc_id, "Unsupported: Non-empty union");
  475. MarkFailedDecl(context, clang_decl);
  476. return SemIR::ErrorInst::InstId;
  477. }
  478. auto [class_id, class_def_id] =
  479. BuildClassDefinition(context, parent_scope_id, name_id, clang_def);
  480. // The class type is now fully defined. Compute its object representation.
  481. ComputeClassObjectRepr(context,
  482. // TODO: Consider having a proper location here.
  483. Parse::ClassDefinitionId::None, class_id,
  484. // TODO: Set fields.
  485. /*field_decls=*/{},
  486. // TODO: Set vtable.
  487. /*vtable_contents=*/{},
  488. // TODO: Set block.
  489. /*body=*/{});
  490. return class_def_id;
  491. }
  492. // Creates an integer type of the given size.
  493. static auto MakeIntType(Context& context, IntId size_id) -> TypeExpr {
  494. // TODO: Fill in a location for the type once available.
  495. auto type_inst_id = MakeIntTypeLiteral(context, Parse::NodeId::None,
  496. SemIR::IntKind::Signed, size_id);
  497. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  498. }
  499. // Maps a C++ builtin type to a Carbon type.
  500. // TODO: Support more builtin types.
  501. static auto MapBuiltinType(Context& context, const clang::BuiltinType& type)
  502. -> TypeExpr {
  503. // TODO: Refactor to avoid duplication.
  504. switch (type.getKind()) {
  505. case clang::BuiltinType::Short:
  506. if (context.ast_context().getTypeSize(&type) == 16) {
  507. return MakeIntType(context, context.ints().Add(16));
  508. }
  509. break;
  510. case clang::BuiltinType::Int:
  511. if (context.ast_context().getTypeSize(&type) == 32) {
  512. return MakeIntType(context, context.ints().Add(32));
  513. }
  514. break;
  515. default:
  516. break;
  517. }
  518. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  519. }
  520. // Maps a C++ record type to a Carbon type.
  521. // TODO: Support more record types.
  522. static auto MapRecordType(Context& context, SemIR::LocId loc_id,
  523. const clang::RecordType& type) -> TypeExpr {
  524. auto* record_decl = clang::dyn_cast<clang::CXXRecordDecl>(type.getDecl());
  525. if (!record_decl) {
  526. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  527. }
  528. // Check if the declaration is already mapped.
  529. SemIR::InstId record_inst_id = LookupClangDeclInstId(context, record_decl);
  530. if (!record_inst_id.has_value()) {
  531. clang::DeclContext* decl_context = record_decl->getDeclContext();
  532. if (!clang::isa<clang::TranslationUnitDecl>(decl_context) &&
  533. !clang::isa<clang::NamespaceDecl>(decl_context)) {
  534. context.TODO(loc_id,
  535. "Unsupported mapping of a C++ record to a type within a "
  536. "declaration context that is not the translation unit or "
  537. "a namespace");
  538. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  539. .type_id = SemIR::ErrorInst::TypeId};
  540. }
  541. auto parent_inst_id = AsCarbonNamespace(context, decl_context);
  542. auto parent_name_scope_id =
  543. context.insts().GetAs<SemIR::Namespace>(parent_inst_id).name_scope_id;
  544. SemIR::NameId record_name_id =
  545. AddIdentifierName(context, record_decl->getName());
  546. record_inst_id = ImportCXXRecordDecl(context, loc_id, parent_name_scope_id,
  547. record_name_id, record_decl);
  548. }
  549. SemIR::TypeInstId record_type_inst_id =
  550. context.types().GetAsTypeInstId(record_inst_id);
  551. return {
  552. .inst_id = record_type_inst_id,
  553. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  554. }
  555. // Maps a C++ type that is not a wrapper type such as a pointer to a Carbon
  556. // type.
  557. // TODO: Support more types.
  558. static auto MapNonWrapperType(Context& context, SemIR::LocId loc_id,
  559. clang::QualType type) -> TypeExpr {
  560. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  561. return MapBuiltinType(context, *builtin_type);
  562. }
  563. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  564. return MapRecordType(context, loc_id, *record_type);
  565. }
  566. CARBON_CHECK(!type.hasQualifiers() && !type->isPointerType(),
  567. "Should not see wrapper types here");
  568. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  569. }
  570. // Maps a qualified C++ type to a Carbon type.
  571. static auto MapQualifiedType(Context& context, SemIR::LocId loc_id,
  572. clang::QualType type, TypeExpr type_expr)
  573. -> TypeExpr {
  574. auto quals = type.getQualifiers();
  575. if (quals.hasConst()) {
  576. auto type_id = GetConstType(context, type_expr.inst_id);
  577. type_expr = {.inst_id = context.types().GetInstId(type_id),
  578. .type_id = type_id};
  579. quals.removeConst();
  580. }
  581. // TODO: Support other qualifiers.
  582. if (!quals.empty()) {
  583. context.TODO(loc_id, llvm::formatv("Unsupported: qualified type: {0}",
  584. type.getAsString()));
  585. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  586. .type_id = SemIR::ErrorInst::TypeId};
  587. }
  588. return type_expr;
  589. }
  590. // Maps a C++ pointer type to a Carbon pointer type.
  591. static auto MapPointerType(Context& context, SemIR::LocId loc_id,
  592. clang::QualType type, TypeExpr pointee_type_expr)
  593. -> TypeExpr {
  594. CARBON_CHECK(type->isPointerType());
  595. if (auto nullability = type->getNullability();
  596. !nullability.has_value() ||
  597. *nullability != clang::NullabilityKind::NonNull) {
  598. context.TODO(loc_id, llvm::formatv("Unsupported: nullable pointer: {0}",
  599. type.getAsString()));
  600. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  601. .type_id = SemIR::ErrorInst::TypeId};
  602. }
  603. SemIR::TypeId pointer_type_id =
  604. GetPointerType(context, pointee_type_expr.inst_id);
  605. return {.inst_id = context.types().GetInstId(pointer_type_id),
  606. .type_id = pointer_type_id};
  607. }
  608. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  609. // we check for pointer nullability and nullability will be lost by
  610. // canonicalization.
  611. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  612. -> TypeExpr {
  613. // Unwrap any type modifiers and wrappers.
  614. llvm::SmallVector<clang::QualType> wrapper_types;
  615. while (true) {
  616. clang::QualType orig_type = type;
  617. if (type.hasQualifiers()) {
  618. type = type.getUnqualifiedType();
  619. } else if (type->isPointerType()) {
  620. type = type->getPointeeType();
  621. } else {
  622. break;
  623. }
  624. wrapper_types.push_back(orig_type);
  625. }
  626. auto mapped = MapNonWrapperType(context, loc_id, type);
  627. for (auto wrapper : llvm::reverse(wrapper_types)) {
  628. if (!mapped.inst_id.has_value() ||
  629. mapped.type_id == SemIR::ErrorInst::TypeId) {
  630. break;
  631. }
  632. if (wrapper.hasQualifiers()) {
  633. mapped = MapQualifiedType(context, loc_id, wrapper, mapped);
  634. } else if (wrapper->isPointerType()) {
  635. mapped = MapPointerType(context, loc_id, wrapper, mapped);
  636. } else {
  637. CARBON_FATAL("Unexpected wrapper type {0}", wrapper.getAsString());
  638. }
  639. }
  640. return mapped;
  641. }
  642. // Returns a block for the implicit parameters of the given function
  643. // declaration. Because function templates are not yet supported, this currently
  644. // only contains the `self` parameter. On error, produces a diagnostic and
  645. // returns None.
  646. static auto MakeImplicitParamPatternsBlockId(
  647. Context& context, SemIR::LocId loc_id,
  648. const clang::FunctionDecl& clang_decl) -> SemIR::InstBlockId {
  649. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(&clang_decl);
  650. if (!method_decl || method_decl->isStatic()) {
  651. return SemIR::InstBlockId::Empty;
  652. }
  653. // Build a `self` parameter from the object parameter.
  654. BeginSubpattern(context);
  655. // Perform some special-case mapping for the object parameter:
  656. //
  657. // - If it's a const reference to T, produce a by-value `self: T` parameter.
  658. // - If it's a non-const reference to T, produce an `addr self: T*`
  659. // parameter.
  660. // - Otherwise, map it directly, which will currently fail for `&&`-qualified
  661. // methods.
  662. //
  663. // TODO: Some of this mapping should be performed for all parameters.
  664. clang::QualType param_type =
  665. method_decl->getFunctionObjectParameterReferenceType();
  666. bool addr_self = false;
  667. if (param_type->isLValueReferenceType()) {
  668. param_type = param_type.getNonReferenceType();
  669. if (param_type.isConstQualified()) {
  670. // TODO: Consider only doing this if `const` is the only qualifier. For
  671. // now, any other qualifier will fail when mapping the type.
  672. auto split_type = param_type.getSplitUnqualifiedType();
  673. split_type.Quals.removeConst();
  674. param_type = method_decl->getASTContext().getQualifiedType(split_type);
  675. } else {
  676. addr_self = true;
  677. }
  678. }
  679. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  680. SemIR::ExprRegionId type_expr_region_id =
  681. EndSubpatternAsExpr(context, type_inst_id);
  682. if (!type_id.has_value()) {
  683. context.TODO(loc_id,
  684. llvm::formatv("Unsupported: object parameter type: {0}",
  685. param_type.getAsString()));
  686. return SemIR::InstBlockId::None;
  687. }
  688. if (addr_self) {
  689. type_id = GetPointerType(context, type_inst_id);
  690. }
  691. SemIR::InstId pattern_id =
  692. // TODO: Fill in a location once available.
  693. AddBindingPattern(context, SemIR::LocId::None, SemIR::NameId::SelfValue,
  694. type_id, type_expr_region_id, /*is_generic*/ false,
  695. /*is_template*/ false)
  696. .pattern_id;
  697. // TODO: Fill in a location once available.
  698. pattern_id = AddPatternInst<SemIR::ValueParamPattern>(
  699. context, SemIR::LocId::None,
  700. {.type_id = context.insts().Get(pattern_id).type_id(),
  701. .subpattern_id = pattern_id,
  702. .index = SemIR::CallParamIndex::None});
  703. // If we're building `addr self: Self*`, do that now.
  704. if (addr_self) {
  705. // TODO: Fill in a location once available.
  706. pattern_id = AddPatternInst<SemIR::AddrPattern>(
  707. context, SemIR::LocId::None,
  708. {.type_id = GetPatternType(context, SemIR::AutoType::TypeId),
  709. .inner_id = pattern_id});
  710. }
  711. return context.inst_blocks().Add({pattern_id});
  712. }
  713. // Returns a block id for the explicit parameters of the given function
  714. // declaration. If the function declaration has no parameters, it returns
  715. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  716. // produces an error and returns `SemIR::InstBlockId::None`.
  717. // TODO: Consider refactoring to extract and reuse more logic from
  718. // `HandleAnyBindingPattern()`.
  719. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  720. const clang::FunctionDecl& clang_decl)
  721. -> SemIR::InstBlockId {
  722. if (clang_decl.parameters().empty()) {
  723. return SemIR::InstBlockId::Empty;
  724. }
  725. llvm::SmallVector<SemIR::InstId> params;
  726. params.reserve(clang_decl.parameters().size());
  727. for (const clang::ParmVarDecl* param : clang_decl.parameters()) {
  728. // TODO: Get the parameter type from the function, not from the
  729. // `ParmVarDecl`. The type of the `ParmVarDecl` is the type within the
  730. // function, and isn't in general the same as the type that's exposed to
  731. // callers. In particular, the parameter type exposed to callers will never
  732. // be cv-qualified.
  733. clang::QualType param_type = param->getType();
  734. // Mark the start of a region of insts, needed for the type expression
  735. // created later with the call of `EndSubpatternAsExpr()`.
  736. BeginSubpattern(context);
  737. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  738. // Type expression of the binding pattern - a single-entry/single-exit
  739. // region that allows control flow in the type expression e.g. fn F(x: if C
  740. // then i32 else i64).
  741. SemIR::ExprRegionId type_expr_region_id =
  742. EndSubpatternAsExpr(context, type_inst_id);
  743. if (!type_id.has_value()) {
  744. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  745. param_type.getAsString()));
  746. return SemIR::InstBlockId::None;
  747. }
  748. llvm::StringRef param_name = param->getName();
  749. SemIR::NameId name_id =
  750. param_name.empty()
  751. // Translate an unnamed parameter to an underscore to
  752. // match Carbon's naming of unnamed/unused function params.
  753. ? SemIR::NameId::Underscore
  754. : AddIdentifierName(context, param_name);
  755. // TODO: Fix this once templates are supported.
  756. bool is_template = false;
  757. // TODO: Fix this once generics are supported.
  758. bool is_generic = false;
  759. SemIR::InstId binding_pattern_id =
  760. // TODO: Fill in a location once available.
  761. AddBindingPattern(context, SemIR::LocId::None, name_id, type_id,
  762. type_expr_region_id, is_generic, is_template)
  763. .pattern_id;
  764. SemIR::InstId var_pattern_id = AddPatternInst(
  765. context,
  766. // TODO: Fill in a location once available.
  767. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  768. {.type_id = context.insts().Get(binding_pattern_id).type_id(),
  769. .subpattern_id = binding_pattern_id,
  770. .index = SemIR::CallParamIndex::None})));
  771. params.push_back(var_pattern_id);
  772. }
  773. return context.inst_blocks().Add(params);
  774. }
  775. // Returns the return type of the given function declaration. In case of an
  776. // unsupported return type, it produces a diagnostic and returns
  777. // `SemIR::ErrorInst::InstId`.
  778. // TODO: Support more return types.
  779. static auto GetReturnType(Context& context, SemIR::LocId loc_id,
  780. const clang::FunctionDecl* clang_decl)
  781. -> SemIR::InstId {
  782. clang::QualType ret_type = clang_decl->getReturnType();
  783. if (ret_type->isVoidType()) {
  784. return SemIR::InstId::None;
  785. }
  786. auto [type_inst_id, type_id] = MapType(context, loc_id, ret_type);
  787. if (!type_inst_id.has_value()) {
  788. context.TODO(loc_id, llvm::formatv("Unsupported: return type: {0}",
  789. ret_type.getAsString()));
  790. return SemIR::ErrorInst::InstId;
  791. }
  792. auto pattern_type_id = GetPatternType(context, type_id);
  793. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  794. // TODO: Fill in a location for the return type once available.
  795. context,
  796. SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  797. {.type_id = pattern_type_id, .type_inst_id = type_inst_id})));
  798. SemIR::InstId param_pattern_id = AddPatternInst(
  799. // TODO: Fill in a location for the return type once available.
  800. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  801. {.type_id = pattern_type_id,
  802. .subpattern_id = return_slot_pattern_id,
  803. .index = SemIR::CallParamIndex::None})));
  804. return param_pattern_id;
  805. }
  806. namespace {
  807. // Represents the parameter patterns block id, the return slot pattern id and
  808. // the call parameters block id for a function declaration.
  809. struct FunctionParamsInsts {
  810. SemIR::InstBlockId implicit_param_patterns_id;
  811. SemIR::InstBlockId param_patterns_id;
  812. SemIR::InstId return_slot_pattern_id;
  813. SemIR::InstBlockId call_params_id;
  814. };
  815. } // namespace
  816. // Creates a block containing the parameter pattern instructions for the
  817. // explicit parameters, a parameter pattern instruction for the return type and
  818. // a block containing the call parameters of the function. Emits a callee
  819. // pattern-match for the explicit parameter patterns and the return slot pattern
  820. // to create the Call parameters instructions block. Currently the implicit
  821. // parameter patterns are not taken into account. Returns the parameter patterns
  822. // block id, the return slot pattern id, and the call parameters block id.
  823. // Produces a diagnostic and returns `std::nullopt` if the function declaration
  824. // has an unsupported parameter type.
  825. static auto CreateFunctionParamsInsts(Context& context, SemIR::LocId loc_id,
  826. const clang::FunctionDecl* clang_decl)
  827. -> std::optional<FunctionParamsInsts> {
  828. if (isa<clang::CXXConstructorDecl, clang::CXXDestructorDecl>(clang_decl)) {
  829. context.TODO(loc_id, "Unsupported: Constructor/Destructor");
  830. return std::nullopt;
  831. }
  832. auto implicit_param_patterns_id =
  833. MakeImplicitParamPatternsBlockId(context, loc_id, *clang_decl);
  834. if (!implicit_param_patterns_id.has_value()) {
  835. return std::nullopt;
  836. }
  837. auto param_patterns_id =
  838. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  839. if (!param_patterns_id.has_value()) {
  840. return std::nullopt;
  841. }
  842. auto return_slot_pattern_id = GetReturnType(context, loc_id, clang_decl);
  843. if (SemIR::ErrorInst::InstId == return_slot_pattern_id) {
  844. return std::nullopt;
  845. }
  846. auto call_params_id =
  847. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  848. return_slot_pattern_id);
  849. return {{.implicit_param_patterns_id = implicit_param_patterns_id,
  850. .param_patterns_id = param_patterns_id,
  851. .return_slot_pattern_id = return_slot_pattern_id,
  852. .call_params_id = call_params_id}};
  853. }
  854. // Imports a function declaration from Clang to Carbon. If successful, returns
  855. // the new Carbon function declaration `InstId`. If the declaration was already
  856. // imported, returns the mapped instruction.
  857. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  858. SemIR::NameScopeId scope_id,
  859. SemIR::NameId name_id,
  860. clang::FunctionDecl* clang_decl)
  861. -> SemIR::InstId {
  862. // Check if the declaration is already mapped.
  863. if (SemIR::InstId existing_inst_id =
  864. LookupClangDeclInstId(context, clang_decl);
  865. existing_inst_id.has_value()) {
  866. return existing_inst_id;
  867. }
  868. if (clang_decl->isVariadic()) {
  869. context.TODO(loc_id, "Unsupported: Variadic function");
  870. MarkFailedDecl(context, clang_decl);
  871. return SemIR::ErrorInst::InstId;
  872. }
  873. if (clang_decl->getTemplatedKind() ==
  874. clang::FunctionDecl::TK_FunctionTemplate) {
  875. context.TODO(loc_id, "Unsupported: Template function");
  876. MarkFailedDecl(context, clang_decl);
  877. return SemIR::ErrorInst::InstId;
  878. }
  879. context.scope_stack().PushForDeclName();
  880. context.inst_block_stack().Push();
  881. context.pattern_block_stack().Push();
  882. auto function_params_insts =
  883. CreateFunctionParamsInsts(context, loc_id, clang_decl);
  884. auto pattern_block_id = context.pattern_block_stack().Pop();
  885. auto decl_block_id = context.inst_block_stack().Pop();
  886. context.scope_stack().Pop();
  887. if (!function_params_insts.has_value()) {
  888. MarkFailedDecl(context, clang_decl);
  889. return SemIR::ErrorInst::InstId;
  890. }
  891. auto function_decl = SemIR::FunctionDecl{
  892. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  893. auto decl_id =
  894. AddPlaceholderInstInNoBlock(context, Parse::NodeId::None, function_decl);
  895. context.imports().push_back(decl_id);
  896. auto function_info = SemIR::Function{
  897. {.name_id = name_id,
  898. .parent_scope_id = scope_id,
  899. .generic_id = SemIR::GenericId::None,
  900. .first_param_node_id = Parse::NodeId::None,
  901. .last_param_node_id = Parse::NodeId::None,
  902. .pattern_block_id = pattern_block_id,
  903. .implicit_param_patterns_id =
  904. function_params_insts->implicit_param_patterns_id,
  905. .param_patterns_id = function_params_insts->param_patterns_id,
  906. .is_extern = false,
  907. .extern_library_id = SemIR::LibraryNameId::None,
  908. .non_owning_decl_id = SemIR::InstId::None,
  909. .first_owning_decl_id = decl_id,
  910. .definition_id = SemIR::InstId::None},
  911. {.call_params_id = function_params_insts->call_params_id,
  912. .return_slot_pattern_id = function_params_insts->return_slot_pattern_id,
  913. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  914. .self_param_id = FindSelfPattern(
  915. context, function_params_insts->implicit_param_patterns_id),
  916. .clang_decl_id = context.sem_ir().clang_decls().Add(
  917. {.decl = clang_decl, .inst_id = decl_id})}};
  918. function_decl.function_id = context.functions().Add(function_info);
  919. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  920. SemIR::SpecificId::None);
  921. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  922. return decl_id;
  923. }
  924. // Imports a declaration from Clang to Carbon. If successful, returns the
  925. // instruction for the new Carbon declaration.
  926. // TODO: Remove `scope_id` parameter since we the scope the name was found in
  927. // isn't necessarily the parent scope. See
  928. // https://github.com/carbon-language/carbon-lang/pull/5789/files/a5629ebb303c5b1aef46181eb860b7065ca1aaf1#r2201769611
  929. static auto ImportNameDecl(Context& context, SemIR::LocId loc_id,
  930. SemIR::NameScopeId scope_id, SemIR::NameId name_id,
  931. clang::NamedDecl* clang_decl) -> SemIR::InstId {
  932. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  933. return ImportFunctionDecl(context, loc_id, scope_id, name_id,
  934. clang_function_decl);
  935. }
  936. if (auto* clang_namespace_decl =
  937. clang::dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  938. return AsCarbonNamespace(
  939. context, llvm::dyn_cast<clang::DeclContext>(clang_namespace_decl));
  940. }
  941. if (auto* type_decl = clang::dyn_cast<clang::TypeDecl>(clang_decl)) {
  942. auto type = type_decl->getASTContext().getTypeDeclType(type_decl);
  943. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  944. if (!type_inst_id.has_value()) {
  945. context.TODO(loc_id, llvm::formatv("Unsupported: Type declaration: {0}",
  946. type.getAsString()));
  947. return SemIR::ErrorInst::InstId;
  948. }
  949. return type_inst_id;
  950. }
  951. context.TODO(loc_id, llvm::formatv("Unsupported: Declaration type {0}",
  952. clang_decl->getDeclKindName())
  953. .str());
  954. return SemIR::InstId::None;
  955. }
  956. // Imports a `clang::NamedDecl` into Carbon and adds that name into the
  957. // `NameScope`.
  958. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  959. SemIR::NameScopeId scope_id,
  960. SemIR::NameId name_id,
  961. clang::NamedDecl* clang_decl)
  962. -> SemIR::InstId {
  963. SemIR::InstId inst_id =
  964. ImportNameDecl(context, loc_id, scope_id, name_id, clang_decl);
  965. AddNameToScope(context, scope_id, name_id, inst_id);
  966. return inst_id;
  967. }
  968. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  969. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  970. -> SemIR::InstId {
  971. Diagnostics::AnnotationScope annotate_diagnostics(
  972. &context.emitter(), [&](auto& builder) {
  973. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  974. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  975. builder.Note(loc_id, InCppNameLookup, name_id);
  976. });
  977. auto lookup = ClangLookup(context, scope_id, name_id);
  978. if (!lookup) {
  979. return SemIR::InstId::None;
  980. }
  981. if (!lookup->isSingleResult()) {
  982. context.TODO(loc_id,
  983. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  984. "find a single result; LookupResultKind: {0}",
  985. static_cast<int>(lookup->getResultKind()))
  986. .str());
  987. context.name_scopes().AddRequiredName(scope_id, name_id,
  988. SemIR::ErrorInst::InstId);
  989. return SemIR::ErrorInst::InstId;
  990. }
  991. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id,
  992. lookup->getFoundDecl());
  993. }
  994. } // namespace Carbon::Check