import_cpp.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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++ non-pointer type to a Carbon type.
  616. // TODO: Support more types.
  617. static auto MapNonPointerType(Context& context, SemIR::LocId loc_id,
  618. clang::QualType type) -> TypeExpr {
  619. if (type.hasQualifiers()) {
  620. // TODO: Support type qualifiers.
  621. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  622. }
  623. CARBON_CHECK(!type->isPointerType());
  624. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  625. return MapBuiltinType(context, *builtin_type);
  626. }
  627. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  628. return MapRecordType(context, loc_id, *record_type);
  629. }
  630. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  631. }
  632. // Maps a C++ pointer type to a Carbon pointer type.
  633. static auto MapPointerType(Context& context, SemIR::LocId loc_id,
  634. clang::QualType type) -> TypeExpr {
  635. CARBON_CHECK(type->isPointerType());
  636. if (auto nullability = type->getNullability();
  637. !nullability.has_value() ||
  638. *nullability != clang::NullabilityKind::NonNull) {
  639. context.TODO(loc_id, llvm::formatv("Unsupported: nullable pointer: {0}",
  640. type.getAsString()));
  641. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  642. .type_id = SemIR::ErrorInst::TypeId};
  643. }
  644. clang::QualType pointee_type = type->getPointeeType();
  645. if (pointee_type->isAnyPointerType()) {
  646. context.TODO(loc_id,
  647. llvm::formatv("Unsupported: pointer to pointer type: {0}",
  648. pointee_type.getAsString()));
  649. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  650. .type_id = SemIR::ErrorInst::TypeId};
  651. }
  652. TypeExpr pointee_type_expr = MapNonPointerType(context, loc_id, pointee_type);
  653. if (!pointee_type_expr.inst_id.has_value()) {
  654. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  655. }
  656. SemIR::TypeId pointer_type_id =
  657. GetPointerType(context, pointee_type_expr.inst_id);
  658. return {.inst_id = context.types().GetInstId(pointer_type_id),
  659. .type_id = pointer_type_id};
  660. }
  661. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  662. // we check for pointer nullability and nullability will be lost by
  663. // canonicalization.
  664. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  665. -> TypeExpr {
  666. if (type->isPointerType()) {
  667. return MapPointerType(context, loc_id, type);
  668. }
  669. return MapNonPointerType(context, loc_id, type);
  670. }
  671. // Returns a block id for the explicit parameters of the given function
  672. // declaration. If the function declaration has no parameters, it returns
  673. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  674. // produces an error and returns `SemIR::InstBlockId::None`.
  675. // TODO: Consider refactoring to extract and reuse more logic from
  676. // `HandleAnyBindingPattern()`.
  677. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  678. const clang::FunctionDecl& clang_decl)
  679. -> SemIR::InstBlockId {
  680. if (clang_decl.parameters().empty()) {
  681. return SemIR::InstBlockId::Empty;
  682. }
  683. llvm::SmallVector<SemIR::InstId> params;
  684. params.reserve(clang_decl.parameters().size());
  685. for (const clang::ParmVarDecl* param : clang_decl.parameters()) {
  686. clang::QualType param_type = param->getType();
  687. // Mark the start of a region of insts, needed for the type expression
  688. // created later with the call of `EndSubpatternAsExpr()`.
  689. BeginSubpattern(context);
  690. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  691. // Type expression of the binding pattern - a single-entry/single-exit
  692. // region that allows control flow in the type expression e.g. fn F(x: if C
  693. // then i32 else i64).
  694. SemIR::ExprRegionId type_expr_region_id =
  695. EndSubpatternAsExpr(context, type_inst_id);
  696. if (!type_id.has_value()) {
  697. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  698. param_type.getAsString()));
  699. return SemIR::InstBlockId::None;
  700. }
  701. llvm::StringRef param_name = param->getName();
  702. SemIR::NameId name_id =
  703. param_name.empty()
  704. // Translate an unnamed parameter to an underscore to
  705. // match Carbon's naming of unnamed/unused function params.
  706. ? SemIR::NameId::Underscore
  707. : AddIdentifierName(context, param_name);
  708. // TODO: Fix this once templates are supported.
  709. bool is_template = false;
  710. // TODO: Fix this once generics are supported.
  711. bool is_generic = false;
  712. SemIR::InstId binding_pattern_id =
  713. // TODO: Fill in a location once available.
  714. AddBindingPattern(context, SemIR::LocId::None, name_id, type_id,
  715. type_expr_region_id, is_generic, is_template)
  716. .pattern_id;
  717. SemIR::InstId var_pattern_id = AddPatternInst(
  718. context,
  719. // TODO: Fill in a location once available.
  720. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  721. {.type_id = context.insts().Get(binding_pattern_id).type_id(),
  722. .subpattern_id = binding_pattern_id,
  723. .index = SemIR::CallParamIndex::None})));
  724. params.push_back(var_pattern_id);
  725. }
  726. return context.inst_blocks().Add(params);
  727. }
  728. // Returns the return type of the given function declaration. In case of an
  729. // unsupported return type, it produces a diagnostic and returns
  730. // `SemIR::ErrorInst::InstId`.
  731. // TODO: Support more return types.
  732. static auto GetReturnType(Context& context, SemIR::LocId loc_id,
  733. const clang::FunctionDecl* clang_decl)
  734. -> SemIR::InstId {
  735. clang::QualType ret_type = clang_decl->getReturnType();
  736. if (ret_type->isVoidType()) {
  737. return SemIR::InstId::None;
  738. }
  739. auto [type_inst_id, type_id] = MapType(context, loc_id, ret_type);
  740. if (!type_inst_id.has_value()) {
  741. context.TODO(loc_id, llvm::formatv("Unsupported: return type: {0}",
  742. ret_type.getAsString()));
  743. return SemIR::ErrorInst::InstId;
  744. }
  745. auto pattern_type_id = GetPatternType(context, type_id);
  746. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  747. // TODO: Fill in a location for the return type once available.
  748. context,
  749. SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  750. {.type_id = pattern_type_id, .type_inst_id = type_inst_id})));
  751. SemIR::InstId param_pattern_id = AddPatternInst(
  752. // TODO: Fill in a location for the return type once available.
  753. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  754. {.type_id = pattern_type_id,
  755. .subpattern_id = return_slot_pattern_id,
  756. .index = SemIR::CallParamIndex::None})));
  757. return param_pattern_id;
  758. }
  759. namespace {
  760. // Represents the parameter patterns block id, the return slot pattern id and
  761. // the call parameters block id for a function declaration.
  762. struct FunctionParamsInsts {
  763. SemIR::InstBlockId param_patterns_id;
  764. SemIR::InstId return_slot_pattern_id;
  765. SemIR::InstBlockId call_params_id;
  766. };
  767. } // namespace
  768. // Creates a block containing the parameter pattern instructions for the
  769. // explicit parameters, a parameter pattern instruction for the return type and
  770. // a block containing the call parameters of the function. Emits a callee
  771. // pattern-match for the explicit parameter patterns and the return slot pattern
  772. // to create the Call parameters instructions block. Currently the implicit
  773. // parameter patterns are not taken into account. Returns the parameter patterns
  774. // block id, the return slot pattern id, and the call parameters block id.
  775. // Produces a diagnostic and returns `std::nullopt` if the function declaration
  776. // has an unsupported parameter type.
  777. static auto CreateFunctionParamsInsts(Context& context, SemIR::LocId loc_id,
  778. const clang::FunctionDecl* clang_decl)
  779. -> std::optional<FunctionParamsInsts> {
  780. auto param_patterns_id =
  781. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  782. if (!param_patterns_id.has_value()) {
  783. return std::nullopt;
  784. }
  785. auto return_slot_pattern_id = GetReturnType(context, loc_id, clang_decl);
  786. if (SemIR::ErrorInst::InstId == return_slot_pattern_id) {
  787. return std::nullopt;
  788. }
  789. // TODO: Add support for implicit parameters.
  790. auto call_params_id = CalleePatternMatch(
  791. context, /*implicit_param_patterns_id=*/SemIR::InstBlockId::None,
  792. param_patterns_id, return_slot_pattern_id);
  793. return {{.param_patterns_id = param_patterns_id,
  794. .return_slot_pattern_id = return_slot_pattern_id,
  795. .call_params_id = call_params_id}};
  796. }
  797. // Imports a function declaration from Clang to Carbon. If successful, returns
  798. // the new Carbon function declaration `InstId`.
  799. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  800. SemIR::NameScopeId scope_id,
  801. SemIR::NameId name_id,
  802. clang::FunctionDecl* clang_decl)
  803. -> SemIR::InstId {
  804. if (clang_decl->isVariadic()) {
  805. context.TODO(loc_id, "Unsupported: Variadic function");
  806. MarkFailedDecl(context, clang_decl);
  807. return SemIR::ErrorInst::InstId;
  808. }
  809. if (!clang_decl->isGlobal()) {
  810. context.TODO(loc_id, "Unsupported: Non-global function");
  811. MarkFailedDecl(context, clang_decl);
  812. return SemIR::ErrorInst::InstId;
  813. }
  814. if (clang_decl->getTemplatedKind() != clang::FunctionDecl::TK_NonTemplate) {
  815. context.TODO(loc_id, "Unsupported: Template function");
  816. MarkFailedDecl(context, clang_decl);
  817. return SemIR::ErrorInst::InstId;
  818. }
  819. context.scope_stack().PushForDeclName();
  820. context.inst_block_stack().Push();
  821. context.pattern_block_stack().Push();
  822. auto function_params_insts =
  823. CreateFunctionParamsInsts(context, loc_id, clang_decl);
  824. auto pattern_block_id = context.pattern_block_stack().Pop();
  825. auto decl_block_id = context.inst_block_stack().Pop();
  826. context.scope_stack().Pop();
  827. if (!function_params_insts.has_value()) {
  828. MarkFailedDecl(context, clang_decl);
  829. return SemIR::ErrorInst::InstId;
  830. }
  831. auto function_decl = SemIR::FunctionDecl{
  832. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  833. auto decl_id =
  834. AddPlaceholderInstInNoBlock(context, Parse::NodeId::None, function_decl);
  835. context.imports().push_back(decl_id);
  836. auto function_info = SemIR::Function{
  837. {.name_id = name_id,
  838. .parent_scope_id = scope_id,
  839. .generic_id = SemIR::GenericId::None,
  840. .first_param_node_id = Parse::NodeId::None,
  841. .last_param_node_id = Parse::NodeId::None,
  842. .pattern_block_id = pattern_block_id,
  843. .implicit_param_patterns_id = SemIR::InstBlockId::Empty,
  844. .param_patterns_id = function_params_insts->param_patterns_id,
  845. .is_extern = false,
  846. .extern_library_id = SemIR::LibraryNameId::None,
  847. .non_owning_decl_id = SemIR::InstId::None,
  848. .first_owning_decl_id = decl_id,
  849. .definition_id = SemIR::InstId::None},
  850. {.call_params_id = function_params_insts->call_params_id,
  851. .return_slot_pattern_id = function_params_insts->return_slot_pattern_id,
  852. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  853. .self_param_id = SemIR::InstId::None,
  854. .clang_decl_id = context.sem_ir().clang_decls().Add(
  855. {.decl = clang_decl, .inst_id = decl_id})}};
  856. function_decl.function_id = context.functions().Add(function_info);
  857. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  858. SemIR::SpecificId::None);
  859. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  860. return decl_id;
  861. }
  862. // Imports a declaration from Clang to Carbon. If successful, returns the
  863. // instruction for the new Carbon declaration.
  864. static auto ImportNameDecl(Context& context, SemIR::LocId loc_id,
  865. SemIR::NameScopeId scope_id, SemIR::NameId name_id,
  866. clang::NamedDecl* clang_decl) -> SemIR::InstId {
  867. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  868. return ImportFunctionDecl(context, loc_id, scope_id, name_id,
  869. clang_function_decl);
  870. }
  871. if (auto* clang_namespace_decl =
  872. clang::dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  873. return ImportNamespaceDecl(context, scope_id, name_id,
  874. clang_namespace_decl);
  875. }
  876. if (auto* type_decl = clang::dyn_cast<clang::TypeDecl>(clang_decl)) {
  877. auto type = type_decl->getASTContext().getTypeDeclType(type_decl);
  878. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  879. if (!type_inst_id.has_value()) {
  880. context.TODO(loc_id, llvm::formatv("Unsupported: Type declaration: {0}",
  881. type.getAsString()));
  882. return SemIR::ErrorInst::InstId;
  883. }
  884. return type_inst_id;
  885. }
  886. context.TODO(loc_id, llvm::formatv("Unsupported: Declaration type {0}",
  887. clang_decl->getDeclKindName())
  888. .str());
  889. return SemIR::InstId::None;
  890. }
  891. // Imports a `clang::NamedDecl` into Carbon and adds that name into the
  892. // `NameScope`.
  893. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  894. SemIR::NameScopeId scope_id,
  895. SemIR::NameId name_id,
  896. clang::NamedDecl* clang_decl)
  897. -> SemIR::InstId {
  898. SemIR::InstId inst_id =
  899. ImportNameDecl(context, loc_id, scope_id, name_id, clang_decl);
  900. AddNameToScope(context, scope_id, name_id, inst_id);
  901. return inst_id;
  902. }
  903. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  904. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  905. -> SemIR::InstId {
  906. Diagnostics::AnnotationScope annotate_diagnostics(
  907. &context.emitter(), [&](auto& builder) {
  908. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  909. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  910. builder.Note(loc_id, InCppNameLookup, name_id);
  911. });
  912. auto lookup = ClangLookup(context, scope_id, name_id);
  913. if (!lookup) {
  914. return SemIR::InstId::None;
  915. }
  916. if (!lookup->isSingleResult()) {
  917. context.TODO(loc_id,
  918. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  919. "find a single result; LookupResultKind: {0}",
  920. static_cast<int>(lookup->getResultKind()))
  921. .str());
  922. context.name_scopes().AddRequiredName(scope_id, name_id,
  923. SemIR::ErrorInst::InstId);
  924. return SemIR::ErrorInst::InstId;
  925. }
  926. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id,
  927. lookup->getFoundDecl());
  928. }
  929. } // namespace Carbon::Check