import_cpp.cpp 43 KB

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