import_cpp.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  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/AST/ASTContext.h"
  11. #include "clang/AST/RecordLayout.h"
  12. #include "clang/Basic/FileManager.h"
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Frontend/TextDiagnostic.h"
  17. #include "clang/Lex/PreprocessorOptions.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "common/check.h"
  20. #include "common/ostream.h"
  21. #include "common/raw_string_ostream.h"
  22. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "toolchain/base/kind_switch.h"
  26. #include "toolchain/check/class.h"
  27. #include "toolchain/check/context.h"
  28. #include "toolchain/check/convert.h"
  29. #include "toolchain/check/diagnostic_helpers.h"
  30. #include "toolchain/check/eval.h"
  31. #include "toolchain/check/function.h"
  32. #include "toolchain/check/import.h"
  33. #include "toolchain/check/inst.h"
  34. #include "toolchain/check/literal.h"
  35. #include "toolchain/check/pattern.h"
  36. #include "toolchain/check/pattern_match.h"
  37. #include "toolchain/check/type.h"
  38. #include "toolchain/diagnostics/diagnostic.h"
  39. #include "toolchain/diagnostics/diagnostic_emitter.h"
  40. #include "toolchain/diagnostics/format_providers.h"
  41. #include "toolchain/parse/node_ids.h"
  42. #include "toolchain/sem_ir/clang_decl.h"
  43. #include "toolchain/sem_ir/ids.h"
  44. #include "toolchain/sem_ir/inst.h"
  45. #include "toolchain/sem_ir/name_scope.h"
  46. #include "toolchain/sem_ir/typed_insts.h"
  47. namespace Carbon::Check {
  48. // Generates C++ file contents to #include all requested imports.
  49. static auto GenerateCppIncludesHeaderCode(
  50. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  51. -> std::string {
  52. std::string code;
  53. llvm::raw_string_ostream code_stream(code);
  54. for (const Parse::Tree::PackagingNames& import : imports) {
  55. // Add a line marker directive pointing at the location of the `import Cpp`
  56. // declaration in the Carbon source file. This will cause Clang's
  57. // diagnostics machinery to track and report the location in Carbon code
  58. // where the import was written.
  59. auto token = context.parse_tree().node_token(import.node_id);
  60. code_stream << "# " << context.tokens().GetLineNumber(token) << " \""
  61. << FormatEscaped(context.tokens().source().filename())
  62. << "\"\n";
  63. code_stream << "#include \""
  64. << FormatEscaped(
  65. context.string_literal_values().Get(import.library_id))
  66. << "\"\n";
  67. }
  68. return code;
  69. }
  70. // Adds the name to the scope with the given `access_kind` and `inst_id`.
  71. // `inst_id` must have a value.
  72. static auto AddNameToScope(Context& context, SemIR::NameScopeId scope_id,
  73. SemIR::NameId name_id, SemIR::AccessKind access_kind,
  74. SemIR::InstId inst_id) -> void {
  75. CARBON_CHECK(inst_id.has_value());
  76. context.name_scopes().Get(scope_id).AddRequired(
  77. {.name_id = name_id,
  78. .result = SemIR::ScopeLookupResult::MakeFound(inst_id, access_kind)});
  79. }
  80. // Maps a Clang name to a Carbon `NameId`.
  81. static auto AddIdentifierName(Context& context, llvm::StringRef name)
  82. -> SemIR::NameId {
  83. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  84. }
  85. // Adds the given source location and an `ImportIRInst` referring to it in
  86. // `ImportIRId::Cpp`.
  87. static auto AddImportIRInst(Context& context,
  88. clang::SourceLocation clang_source_loc)
  89. -> SemIR::ImportIRInstId {
  90. SemIR::ClangSourceLocId clang_source_loc_id =
  91. context.sem_ir().clang_source_locs().Add(clang_source_loc);
  92. return context.import_ir_insts().Add(
  93. SemIR::ImportIRInst(clang_source_loc_id));
  94. }
  95. namespace {
  96. // Used to convert Clang diagnostics to Carbon diagnostics.
  97. //
  98. // Handling of Clang notes is a little subtle: as far as Clang is concerned,
  99. // notes are separate diagnostics, not connected to the error or warning that
  100. // precedes them. But in Carbon's diagnostics system, notes are part of the
  101. // enclosing diagnostic. To handle this, we buffer Clang diagnostics until we
  102. // reach a point where we know we're not in the middle of a diagnostic, and then
  103. // emit a diagnostic along with all of its notes. This is triggered when adding
  104. // or removing a Carbon context note, which could otherwise get attached to the
  105. // wrong C++ diagnostics, and at the end of the Carbon program.
  106. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  107. public:
  108. // Creates an instance with the location that triggers calling Clang.
  109. // `context` must not be null.
  110. explicit CarbonClangDiagnosticConsumer(
  111. Context* context, std::shared_ptr<clang::CompilerInvocation> invocation)
  112. : context_(context), invocation_(std::move(invocation)) {
  113. context->emitter().AddFlushFn([this] { EmitDiagnostics(); });
  114. }
  115. ~CarbonClangDiagnosticConsumer() override {
  116. CARBON_CHECK(diagnostic_infos_.empty(),
  117. "Missing flush before destroying diagnostic consumer");
  118. }
  119. // Generates a Carbon warning for each Clang warning and a Carbon error for
  120. // each Clang error or fatal.
  121. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  122. const clang::Diagnostic& info) -> void override {
  123. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  124. SemIR::ImportIRInstId clang_import_ir_inst_id =
  125. AddImportIRInst(*context_, info.getLocation());
  126. llvm::SmallString<256> message;
  127. info.FormatDiagnostic(message);
  128. // Render a code snippet including any highlighted ranges and fixit hints.
  129. // TODO: Also include the #include stack and macro expansion stack in the
  130. // diagnostic output in some way.
  131. RawStringOstream snippet_stream;
  132. if (!info.hasSourceManager()) {
  133. // If we don't have a source manager, this is an error from early in the
  134. // frontend. Don't produce a snippet.
  135. CARBON_CHECK(info.getLocation().isInvalid());
  136. } else {
  137. CodeContextRenderer(snippet_stream, invocation_->getLangOpts(),
  138. invocation_->getDiagnosticOpts())
  139. .emitDiagnostic(
  140. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  141. diag_level, message, info.getRanges(), info.getFixItHints());
  142. }
  143. diagnostic_infos_.push_back({.level = diag_level,
  144. .import_ir_inst_id = clang_import_ir_inst_id,
  145. .message = message.str().str(),
  146. .snippet = snippet_stream.TakeStr()});
  147. }
  148. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  149. // be called after the AST is set in the context.
  150. auto EmitDiagnostics() -> void {
  151. CARBON_CHECK(context_->sem_ir().cpp_ast(),
  152. "Attempted to emit diagnostics before the AST Unit is loaded");
  153. for (size_t i = 0; i != diagnostic_infos_.size(); ++i) {
  154. const ClangDiagnosticInfo& info = diagnostic_infos_[i];
  155. switch (info.level) {
  156. case clang::DiagnosticsEngine::Ignored:
  157. case clang::DiagnosticsEngine::Note:
  158. case clang::DiagnosticsEngine::Remark: {
  159. context_->TODO(
  160. SemIR::LocId(info.import_ir_inst_id),
  161. llvm::formatv(
  162. "Unsupported: C++ diagnostic level for diagnostic\n{0}",
  163. info.message));
  164. break;
  165. }
  166. case clang::DiagnosticsEngine::Warning:
  167. case clang::DiagnosticsEngine::Error:
  168. case clang::DiagnosticsEngine::Fatal: {
  169. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}",
  170. std::string);
  171. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  172. auto builder = context_->emitter().Build(
  173. SemIR::LocId(info.import_ir_inst_id),
  174. info.level == clang::DiagnosticsEngine::Warning
  175. ? CppInteropParseWarning
  176. : CppInteropParseError,
  177. info.message);
  178. builder.OverrideSnippet(info.snippet);
  179. for (;
  180. i + 1 < diagnostic_infos_.size() &&
  181. diagnostic_infos_[i + 1].level == clang::DiagnosticsEngine::Note;
  182. ++i) {
  183. const ClangDiagnosticInfo& note_info = diagnostic_infos_[i + 1];
  184. CARBON_DIAGNOSTIC(CppInteropParseNote, Note, "{0}", std::string);
  185. builder
  186. .Note(SemIR::LocId(note_info.import_ir_inst_id),
  187. CppInteropParseNote, note_info.message)
  188. .OverrideSnippet(note_info.snippet);
  189. }
  190. // TODO: This will apply all current Carbon annotation functions. We
  191. // should instead track how Clang's context notes and Carbon's
  192. // annotation functions are interleaved, and interleave the notes in
  193. // the same order.
  194. builder.Emit();
  195. break;
  196. }
  197. }
  198. }
  199. diagnostic_infos_.clear();
  200. }
  201. private:
  202. // A diagnostics renderer based on clang's TextDiagnostic that captures just
  203. // the code context (the snippet).
  204. class CodeContextRenderer : public clang::TextDiagnostic {
  205. public:
  206. using TextDiagnostic::TextDiagnostic;
  207. void emitDiagnosticMessage(
  208. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  209. clang::DiagnosticsEngine::Level /*level*/, llvm::StringRef /*message*/,
  210. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/,
  211. clang::DiagOrStoredDiag /*info*/) override {}
  212. void emitDiagnosticLoc(
  213. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  214. clang::DiagnosticsEngine::Level /*level*/,
  215. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/) override {}
  216. // emitCodeContext is inherited from clang::TextDiagnostic.
  217. void emitIncludeLocation(clang::FullSourceLoc /*loc*/,
  218. clang::PresumedLoc /*ploc*/) override {}
  219. void emitImportLocation(clang::FullSourceLoc /*loc*/,
  220. clang::PresumedLoc /*ploc*/,
  221. llvm::StringRef /*module_name*/) override {}
  222. void emitBuildingModuleLocation(clang::FullSourceLoc /*loc*/,
  223. clang::PresumedLoc /*ploc*/,
  224. llvm::StringRef /*module_name*/) override {}
  225. // beginDiagnostic and endDiagnostic are inherited from
  226. // clang::TextDiagnostic in case it wants to do any setup / teardown work.
  227. };
  228. // Information on a Clang diagnostic that can be converted to a Carbon
  229. // diagnostic.
  230. struct ClangDiagnosticInfo {
  231. // The Clang diagnostic level.
  232. clang::DiagnosticsEngine::Level level;
  233. // The ID of the ImportIR instruction referring to the Clang source
  234. // location.
  235. SemIR::ImportIRInstId import_ir_inst_id;
  236. // The Clang diagnostic textual message.
  237. std::string message;
  238. // The code snippet produced by clang.
  239. std::string snippet;
  240. };
  241. // The type-checking context in which we're running Clang.
  242. Context* context_;
  243. // The compiler invocation that is producing the diagnostics.
  244. std::shared_ptr<clang::CompilerInvocation> invocation_;
  245. // Collects the information for all Clang diagnostics to be converted to
  246. // Carbon diagnostics after the context has been initialized with the Clang
  247. // AST.
  248. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  249. };
  250. // A wrapper around a clang::CompilerInvocation that allows us to make a shallow
  251. // copy of most of the invocation and only make a deep copy of the parts that we
  252. // want to change.
  253. //
  254. // clang::CowCompilerInvocation almost allows this, but doesn't derive from
  255. // CompilerInvocation or support shallow copies from a CompilerInvocation, so is
  256. // not useful to us as we can't build an ASTUnit from it.
  257. class ShallowCopyCompilerInvocation : public clang::CompilerInvocation {
  258. public:
  259. explicit ShallowCopyCompilerInvocation(
  260. const clang::CompilerInvocation& invocation) {
  261. shallow_copy_assign(invocation);
  262. // The preprocessor options are modified to hold a replacement includes
  263. // buffer, so make our own version of those options.
  264. PPOpts = std::make_shared<clang::PreprocessorOptions>(*PPOpts);
  265. }
  266. };
  267. } // namespace
  268. // Returns an AST for the C++ imports and a bool that represents whether
  269. // compilation errors where encountered or the generated AST is null due to an
  270. // error. Sets the AST in the context's `sem_ir`.
  271. // TODO: Consider to always have a (non-null) AST.
  272. static auto GenerateAst(
  273. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  274. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  275. std::shared_ptr<clang::CompilerInvocation> base_invocation)
  276. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  277. auto invocation =
  278. std::make_shared<ShallowCopyCompilerInvocation>(*base_invocation);
  279. // Build a diagnostics engine.
  280. llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diags(
  281. clang::CompilerInstance::createDiagnostics(
  282. *fs, invocation->getDiagnosticOpts(),
  283. new CarbonClangDiagnosticConsumer(&context, invocation),
  284. /*ShouldOwnClient=*/true));
  285. // Extract the input from the frontend invocation and make sure it makes
  286. // sense.
  287. const auto& inputs = invocation->getFrontendOpts().Inputs;
  288. CARBON_CHECK(inputs.size() == 1 &&
  289. inputs[0].getKind().getLanguage() == clang::Language::CXX &&
  290. inputs[0].getKind().getFormat() == clang::InputKind::Source);
  291. llvm::StringRef file_name = inputs[0].getFile();
  292. // Remap the imports file name to the corresponding `#include`s.
  293. // TODO: Modify the frontend options to specify this memory buffer as input
  294. // instead of remapping the file.
  295. std::string includes = GenerateCppIncludesHeaderCode(context, imports);
  296. auto includes_buffer =
  297. llvm::MemoryBuffer::getMemBufferCopy(includes, file_name);
  298. invocation->getPreprocessorOpts().addRemappedFile(file_name,
  299. includes_buffer.release());
  300. clang::DiagnosticErrorTrap trap(*diags);
  301. // Create the AST unit.
  302. auto ast = clang::ASTUnit::LoadFromCompilerInvocation(
  303. invocation, std::make_shared<clang::PCHContainerOperations>(), nullptr,
  304. diags, new clang::FileManager(invocation->getFileSystemOpts(), fs));
  305. // Attach the AST to SemIR. This needs to be done before we can emit any
  306. // diagnostics, so their locations can be properly interpreted by our
  307. // diagnostics machinery.
  308. context.sem_ir().set_cpp_ast(ast.get());
  309. // Emit any diagnostics we queued up while building the AST.
  310. context.emitter().Flush();
  311. return {std::move(ast), !ast || trap.hasErrorOccurred()};
  312. }
  313. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  314. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  315. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  316. -> SemIR::NameScopeId {
  317. auto& import_cpps = context.sem_ir().import_cpps();
  318. import_cpps.Reserve(imports.size());
  319. for (const Parse::Tree::PackagingNames& import : imports) {
  320. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  321. import.node_id),
  322. .library_id = import.library_id});
  323. }
  324. return AddImportNamespaceToScope(
  325. context,
  326. GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  327. SemIR::NameId::ForPackageName(cpp_package_id),
  328. SemIR::NameScopeId::Package,
  329. /*diagnose_duplicate_namespace=*/false,
  330. [&]() {
  331. return AddInst<SemIR::ImportCppDecl>(
  332. context,
  333. context.parse_tree().As<Parse::ImportDeclId>(
  334. imports.front().node_id),
  335. {});
  336. })
  337. .add_result.name_scope_id;
  338. }
  339. auto ImportCppFiles(Context& context,
  340. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  341. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  342. std::shared_ptr<clang::CompilerInvocation> invocation)
  343. -> std::unique_ptr<clang::ASTUnit> {
  344. if (imports.empty()) {
  345. return nullptr;
  346. }
  347. CARBON_CHECK(!context.sem_ir().cpp_ast());
  348. PackageNameId package_id = imports.front().package_id;
  349. CARBON_CHECK(
  350. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  351. return import.package_id == package_id;
  352. }));
  353. auto name_scope_id = AddNamespace(context, package_id, imports);
  354. auto [generated_ast, ast_has_error] =
  355. GenerateAst(context, imports, fs, std::move(invocation));
  356. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  357. name_scope.set_is_closed_import(true);
  358. name_scope.set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  359. {.decl = generated_ast->getASTContext().getTranslationUnitDecl(),
  360. .inst_id = name_scope.inst_id()}));
  361. if (ast_has_error) {
  362. name_scope.set_has_error();
  363. }
  364. return std::move(generated_ast);
  365. }
  366. // Look ups the given name in the Clang AST in a specific scope. Returns the
  367. // lookup result if lookup was successful.
  368. static auto ClangLookup(Context& context, SemIR::NameScopeId scope_id,
  369. SemIR::NameId name_id)
  370. -> std::optional<clang::LookupResult> {
  371. std::optional<llvm::StringRef> name =
  372. context.names().GetAsStringIfIdentifier(name_id);
  373. if (!name) {
  374. // Special names never exist in C++ code.
  375. return std::nullopt;
  376. }
  377. clang::ASTUnit* ast = context.sem_ir().cpp_ast();
  378. CARBON_CHECK(ast);
  379. clang::Sema& sema = ast->getSema();
  380. // TODO: Map the LocId of the lookup to a clang SourceLocation and provide it
  381. // here so that clang's diagnostics can point into the carbon code that uses
  382. // the name.
  383. clang::LookupResult lookup(
  384. sema,
  385. clang::DeclarationNameInfo(
  386. clang::DeclarationName(
  387. sema.getPreprocessor().getIdentifierInfo(*name)),
  388. clang::SourceLocation()),
  389. clang::Sema::LookupNameKind::LookupOrdinaryName);
  390. auto scope_clang_decl_context_id =
  391. context.name_scopes().Get(scope_id).clang_decl_context_id();
  392. bool found = sema.LookupQualifiedName(
  393. lookup,
  394. clang::dyn_cast<clang::DeclContext>(context.sem_ir()
  395. .clang_decls()
  396. .Get(scope_clang_decl_context_id)
  397. .decl));
  398. if (!found) {
  399. return std::nullopt;
  400. }
  401. return lookup;
  402. }
  403. // Returns whether `decl` already mapped to an instruction.
  404. static auto IsClangDeclImported(const Context& context, clang::Decl* decl)
  405. -> bool {
  406. return context.sem_ir()
  407. .clang_decls()
  408. .Lookup(decl->getCanonicalDecl())
  409. .has_value();
  410. }
  411. // If `decl` already mapped to an instruction, returns that instruction.
  412. // Otherwise returns `None`.
  413. static auto LookupClangDeclInstId(const Context& context, clang::Decl* decl)
  414. -> SemIR::InstId {
  415. const auto& clang_decls = context.sem_ir().clang_decls();
  416. if (auto context_clang_decl_id = clang_decls.Lookup(decl->getCanonicalDecl());
  417. context_clang_decl_id.has_value()) {
  418. return clang_decls.Get(context_clang_decl_id).inst_id;
  419. }
  420. return SemIR::InstId::None;
  421. }
  422. // Returns the parent of the given declaration. Skips declaration types we
  423. // ignore.
  424. static auto GetParentDecl(clang::Decl* clang_decl) -> clang::Decl* {
  425. return cast<clang::Decl>(
  426. clang_decl->getDeclContext()->getNonTransparentContext());
  427. }
  428. // Returns the given declaration's parent scope. Assumes the parent declaration
  429. // was already imported.
  430. static auto GetParentNameScopeId(Context& context, clang::Decl* clang_decl)
  431. -> SemIR::NameScopeId {
  432. SemIR::InstId parent_inst_id =
  433. LookupClangDeclInstId(context, GetParentDecl(clang_decl));
  434. CARBON_CHECK(parent_inst_id.has_value());
  435. CARBON_KIND_SWITCH(context.insts().Get(parent_inst_id)) {
  436. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  437. return context.classes().Get(class_decl.class_id).scope_id;
  438. }
  439. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  440. return context.interfaces().Get(interface_decl.interface_id).scope_id;
  441. }
  442. case CARBON_KIND(SemIR::Namespace namespace_inst): {
  443. return namespace_inst.name_scope_id;
  444. }
  445. default: {
  446. CARBON_FATAL("Unexpected parent instruction kind");
  447. }
  448. }
  449. }
  450. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  451. // the new Carbon namespace declaration `InstId`. If the declaration was already
  452. // imported, returns the mapped instruction.
  453. static auto ImportNamespaceDecl(Context& context,
  454. clang::NamespaceDecl* clang_decl)
  455. -> SemIR::InstId {
  456. // Check if the declaration is already mapped.
  457. if (SemIR::InstId existing_inst_id =
  458. LookupClangDeclInstId(context, clang_decl);
  459. existing_inst_id.has_value()) {
  460. return existing_inst_id;
  461. }
  462. auto result = AddImportNamespace(
  463. context, GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  464. AddIdentifierName(context, clang_decl->getName()),
  465. GetParentNameScopeId(context, clang_decl),
  466. /*import_id=*/SemIR::InstId::None);
  467. context.name_scopes()
  468. .Get(result.name_scope_id)
  469. .set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  470. {.decl = clang_decl->getCanonicalDecl(), .inst_id = result.inst_id}));
  471. return result.inst_id;
  472. }
  473. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  474. -> TypeExpr;
  475. // Creates a class declaration for the given class name in the given scope.
  476. // Returns the `InstId` for the declaration.
  477. static auto BuildClassDecl(Context& context,
  478. SemIR::ImportIRInstId import_ir_inst_id,
  479. SemIR::NameScopeId parent_scope_id,
  480. SemIR::NameId name_id)
  481. -> std::tuple<SemIR::ClassId, SemIR::TypeInstId> {
  482. // Add the class declaration.
  483. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeType::TypeId,
  484. .class_id = SemIR::ClassId::None,
  485. .decl_block_id = SemIR::InstBlockId::None};
  486. auto class_decl_id = AddPlaceholderInstInNoBlock(
  487. context,
  488. SemIR::LocIdAndInst::UncheckedLoc(import_ir_inst_id, class_decl));
  489. context.imports().push_back(class_decl_id);
  490. SemIR::Class class_info = {
  491. {.name_id = name_id,
  492. .parent_scope_id = parent_scope_id,
  493. .generic_id = SemIR::GenericId::None,
  494. .first_param_node_id = Parse::NodeId::None,
  495. .last_param_node_id = Parse::NodeId::None,
  496. .pattern_block_id = SemIR::InstBlockId::None,
  497. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  498. .param_patterns_id = SemIR::InstBlockId::None,
  499. .is_extern = false,
  500. .extern_library_id = SemIR::LibraryNameId::None,
  501. .non_owning_decl_id = SemIR::InstId::None,
  502. .first_owning_decl_id = class_decl_id},
  503. {// `.self_type_id` depends on the ClassType, so is set below.
  504. .self_type_id = SemIR::TypeId::None,
  505. // TODO: Support Dynamic classes.
  506. // TODO: Support Final classes.
  507. .inheritance_kind = SemIR::Class::Base}};
  508. class_decl.class_id = context.classes().Add(class_info);
  509. // Write the class ID into the ClassDecl.
  510. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  511. SetClassSelfType(context, class_decl.class_id);
  512. return {class_decl.class_id, context.types().GetAsTypeInstId(class_decl_id)};
  513. }
  514. // Imports a record declaration from Clang to Carbon. If successful, returns
  515. // the new Carbon class declaration `InstId`.
  516. static auto ImportCXXRecordDecl(Context& context,
  517. clang::CXXRecordDecl* clang_decl)
  518. -> SemIR::InstId {
  519. auto import_ir_inst_id = AddImportIRInst(context, clang_decl->getLocation());
  520. auto [class_id, class_inst_id] = BuildClassDecl(
  521. context, import_ir_inst_id, GetParentNameScopeId(context, clang_decl),
  522. AddIdentifierName(context, clang_decl->getName()));
  523. // TODO: The caller does the same lookup. Avoid doing it twice.
  524. auto clang_decl_id = context.sem_ir().clang_decls().Add(
  525. {.decl = clang_decl->getCanonicalDecl(), .inst_id = class_inst_id});
  526. // Name lookup into the Carbon class looks in the C++ class definition.
  527. auto& class_info = context.classes().Get(class_id);
  528. class_info.scope_id = context.name_scopes().Add(
  529. class_inst_id, SemIR::NameId::None, class_info.parent_scope_id);
  530. context.name_scopes()
  531. .Get(class_info.scope_id)
  532. .set_clang_decl_context_id(clang_decl_id);
  533. return class_inst_id;
  534. }
  535. // Determines the Carbon inheritance kind to use for a C++ class definition.
  536. static auto GetInheritanceKind(clang::CXXRecordDecl* class_def)
  537. -> SemIR::Class::InheritanceKind {
  538. if (class_def->isUnion()) {
  539. // Treat all unions as final classes to match their C++ semantics. While we
  540. // could support this, the author of a C++ union has no way to mark their
  541. // type as `final` to prevent it, and so we assume the intent was to
  542. // disallow inheritance.
  543. return SemIR::Class::Final;
  544. }
  545. if (class_def->hasAttr<clang::FinalAttr>()) {
  546. // The class is final in C++; don't allow Carbon types to derive from it.
  547. // Note that such a type might also be abstract in C++; we treat final as
  548. // taking precedence.
  549. //
  550. // We could also treat classes with a final destructor as being final, as
  551. // Clang does when determining whether a class is "effectively final", but
  552. // to keep our rules simpler we do not.
  553. return SemIR::Class::Final;
  554. }
  555. if (class_def->isAbstract()) {
  556. // If the class has any abstract members, it's abstract.
  557. return SemIR::Class::Abstract;
  558. }
  559. // Allow inheritance from any other C++ class type.
  560. return SemIR::Class::Base;
  561. }
  562. // Checks that the specified finished class definition is valid and builds and
  563. // returns a corresponding complete type witness instruction.
  564. static auto ImportClassObjectRepr(Context& context, SemIR::ClassId class_id,
  565. SemIR::ImportIRInstId import_ir_inst_id,
  566. SemIR::TypeInstId class_type_inst_id,
  567. const clang::CXXRecordDecl* clang_def)
  568. -> SemIR::TypeInstId {
  569. // For now, if the class is empty, produce an empty struct as the object
  570. // representation. This allows our tests to continue to pass while we don't
  571. // properly support initializing imported C++ classes.
  572. // TODO: Remove this.
  573. if (clang_def->isEmpty() && !clang_def->getNumBases()) {
  574. return context.types().GetAsTypeInstId(AddInst(
  575. context,
  576. MakeImportedLocIdAndInst(
  577. context, import_ir_inst_id,
  578. SemIR::StructType{.type_id = SemIR::TypeType::TypeId,
  579. .fields_id = SemIR::StructTypeFieldsId::Empty})));
  580. }
  581. const auto& clang_layout =
  582. context.ast_context().getASTRecordLayout(clang_def);
  583. llvm::SmallVector<uint64_t> layout;
  584. llvm::SmallVector<SemIR::StructTypeField> fields;
  585. static_assert(SemIR::CustomLayoutId::SizeIndex == 0);
  586. layout.push_back(clang_layout.getSize().getQuantity());
  587. static_assert(SemIR::CustomLayoutId::AlignIndex == 1);
  588. layout.push_back(clang_layout.getAlignment().getQuantity());
  589. static_assert(SemIR::CustomLayoutId::FirstFieldIndex == 2);
  590. // TODO: Import vptr(s).
  591. // Import bases.
  592. for (const auto& base : clang_def->bases()) {
  593. CARBON_CHECK(!base.isVirtual(),
  594. "Should not import definition for class with a virtual base");
  595. auto [base_type_inst_id, base_type_id] =
  596. MapType(context, import_ir_inst_id, base.getType());
  597. if (!base_type_id.has_value()) {
  598. // TODO: If the base class's type can't be mapped, skip it.
  599. continue;
  600. }
  601. auto base_decl_id = AddInst(
  602. context,
  603. MakeImportedLocIdAndInst(
  604. context, import_ir_inst_id,
  605. SemIR::BaseDecl{.type_id = GetUnboundElementType(
  606. context, class_type_inst_id, base_type_inst_id),
  607. .base_type_inst_id = base_type_inst_id,
  608. .index = SemIR::ElementIndex(fields.size())}));
  609. // If there's exactly one base class, treat it as a Carbon base class too.
  610. // TODO: Improve handling for the case where the class has multiple base
  611. // classes.
  612. if (clang_def->getNumBases() == 1) {
  613. auto& class_info = context.classes().Get(class_id);
  614. CARBON_CHECK(!class_info.base_id.has_value());
  615. class_info.base_id = base_decl_id;
  616. }
  617. auto* base_class = base.getType()->getAsCXXRecordDecl();
  618. CARBON_CHECK(base_class, "Base class {0} is not a class",
  619. base.getType().getAsString());
  620. auto base_offset = base.isVirtual()
  621. ? clang_layout.getVBaseClassOffset(base_class)
  622. : clang_layout.getBaseClassOffset(base_class);
  623. layout.push_back(base_offset.getQuantity());
  624. fields.push_back(
  625. {.name_id = SemIR::NameId::Base, .type_inst_id = base_type_inst_id});
  626. }
  627. // Import fields.
  628. for (auto* decl : clang_def->decls()) {
  629. auto* field = clang::dyn_cast<clang::FieldDecl>(decl);
  630. // Track the chain of fields from the class to this field. This chain is
  631. // only one element long unless the field is a member of an anonymous struct
  632. // or union.
  633. clang::NamedDecl* single_field_chain[1] = {field};
  634. llvm::ArrayRef<clang::NamedDecl*> chain = single_field_chain;
  635. // If this isn't a field, it might be an indirect field in an anonymous
  636. // struct or union.
  637. if (!field) {
  638. auto* indirect_field = clang::dyn_cast<clang::IndirectFieldDecl>(decl);
  639. if (!indirect_field) {
  640. continue;
  641. }
  642. chain = indirect_field->chain();
  643. field = indirect_field->getAnonField();
  644. }
  645. if (field->isBitField()) {
  646. // TODO: Add a representation for named bitfield members.
  647. continue;
  648. }
  649. if (field->isAnonymousStructOrUnion()) {
  650. // Fields within an anonymous structure or union will be added via their
  651. // IndirectFieldDecls.
  652. continue;
  653. }
  654. auto field_name_id = AddIdentifierName(context, field->getName());
  655. auto [field_type_inst_id, field_type_id] =
  656. MapType(context, import_ir_inst_id, field->getType());
  657. if (!field_type_inst_id.has_value()) {
  658. // TODO: For now, just skip over fields whose types we can't map.
  659. continue;
  660. }
  661. // Create a field now, as we know the index to use.
  662. // TODO: Consider doing this lazily instead.
  663. auto field_decl_id = AddInst(
  664. context, MakeImportedLocIdAndInst(
  665. context, import_ir_inst_id,
  666. SemIR::FieldDecl{
  667. .type_id = GetUnboundElementType(
  668. context, class_type_inst_id, field_type_inst_id),
  669. .name_id = field_name_id,
  670. .index = SemIR::ElementIndex(fields.size())}));
  671. context.sem_ir().clang_decls().Add(
  672. {.decl = decl->getCanonicalDecl(), .inst_id = field_decl_id});
  673. // Compute the offset to the field that appears directly in the class.
  674. uint64_t offset = clang_layout.getFieldOffset(
  675. clang::cast<clang::FieldDecl>(chain.front())->getFieldIndex());
  676. // If this is an indirect field, walk the path and accumulate the offset to
  677. // the named field.
  678. for (auto* inner_decl : chain.drop_front()) {
  679. auto* inner_field = clang::cast<clang::FieldDecl>(inner_decl);
  680. const auto& inner_layout =
  681. context.ast_context().getASTRecordLayout(inner_field->getParent());
  682. offset += inner_layout.getFieldOffset(inner_field->getFieldIndex());
  683. }
  684. layout.push_back(
  685. context.ast_context().toCharUnitsFromBits(offset).getQuantity());
  686. fields.push_back(
  687. {.name_id = field_name_id, .type_inst_id = field_type_inst_id});
  688. }
  689. // TODO: Add a field to prevent tail padding reuse if necessary.
  690. return AddTypeInst<SemIR::CustomLayoutType>(
  691. context, import_ir_inst_id,
  692. {.type_id = SemIR::TypeType::TypeId,
  693. .fields_id = context.struct_type_fields().Add(fields),
  694. .layout_id = context.custom_layouts().Add(layout)});
  695. }
  696. // Creates a class definition based on the information in the given Clang
  697. // declaration, which is assumed to be for a class definition.
  698. static auto BuildClassDefinition(Context& context,
  699. SemIR::ImportIRInstId import_ir_inst_id,
  700. SemIR::ClassId class_id,
  701. SemIR::TypeInstId class_inst_id,
  702. clang::CXXRecordDecl* clang_def) -> void {
  703. auto& class_info = context.classes().Get(class_id);
  704. CARBON_CHECK(!class_info.has_definition_started());
  705. class_info.definition_id = class_inst_id;
  706. context.inst_block_stack().Push();
  707. class_info.inheritance_kind = GetInheritanceKind(clang_def);
  708. // Compute the class's object representation.
  709. auto object_repr_id = ImportClassObjectRepr(
  710. context, class_id, import_ir_inst_id, class_inst_id, clang_def);
  711. class_info.complete_type_witness_id = AddInst<SemIR::CompleteTypeWitness>(
  712. context, import_ir_inst_id,
  713. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  714. .object_repr_type_inst_id = object_repr_id});
  715. class_info.body_block_id = context.inst_block_stack().Pop();
  716. }
  717. auto ImportCppClassDefinition(Context& context, SemIR::LocId loc_id,
  718. SemIR::ClassId class_id,
  719. SemIR::ClangDeclId clang_decl_id) -> bool {
  720. clang::ASTUnit* ast = context.sem_ir().cpp_ast();
  721. CARBON_CHECK(ast);
  722. auto* clang_decl = cast<clang::CXXRecordDecl>(
  723. context.sem_ir().clang_decls().Get(clang_decl_id).decl);
  724. auto class_inst_id = context.types().GetAsTypeInstId(
  725. context.classes().Get(class_id).first_owning_decl_id);
  726. // TODO: Map loc_id into a clang location and use it for diagnostics if
  727. // instantiation fails, instead of annotating the diagnostic with another
  728. // location.
  729. clang::SourceLocation loc = clang_decl->getLocation();
  730. Diagnostics::AnnotationScope annotate_diagnostics(
  731. &context.emitter(), [&](auto& builder) {
  732. CARBON_DIAGNOSTIC(InCppTypeCompletion, Note,
  733. "while completing C++ class type {0}", SemIR::TypeId);
  734. builder.Note(loc_id, InCppTypeCompletion,
  735. context.classes().Get(class_id).self_type_id);
  736. });
  737. // Ask Clang whether the type is complete. This triggers template
  738. // instantiation if necessary.
  739. clang::DiagnosticErrorTrap trap(ast->getDiagnostics());
  740. if (!ast->getSema().isCompleteType(
  741. loc, context.ast_context().getRecordType(clang_decl))) {
  742. // Type is incomplete. Nothing more to do, but tell the caller if we
  743. // produced an error.
  744. return !trap.hasErrorOccurred();
  745. }
  746. clang::CXXRecordDecl* clang_def = clang_decl->getDefinition();
  747. CARBON_CHECK(clang_def, "Complete type has no definition");
  748. if (clang_def->getNumVBases()) {
  749. // TODO: Handle virtual bases. We don't actually know where they go in the
  750. // layout. We may also want to use a different size in the layout for
  751. // `partial C`, excluding the virtual base. It's also not entirely safe to
  752. // just skip over the virtual base, as the type we would construct would
  753. // have a misleading size. For now, treat a C++ class with vbases as
  754. // incomplete in Carbon.
  755. context.TODO(loc_id, "class with virtual bases");
  756. return false;
  757. }
  758. auto import_ir_inst_id =
  759. context.insts().GetCanonicalLocId(class_inst_id).import_ir_inst_id();
  760. BuildClassDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  761. clang_def);
  762. return true;
  763. }
  764. // Mark the given `Decl` as failed in `clang_decls`.
  765. static auto MarkFailedDecl(Context& context, clang::Decl* clang_decl) {
  766. context.sem_ir().clang_decls().Add({.decl = clang_decl->getCanonicalDecl(),
  767. .inst_id = SemIR::ErrorInst::InstId});
  768. }
  769. // Creates an integer type of the given size.
  770. static auto MakeIntType(Context& context, IntId size_id, bool is_signed)
  771. -> TypeExpr {
  772. auto type_inst_id = MakeIntTypeLiteral(
  773. context, Parse::NodeId::None,
  774. is_signed ? SemIR::IntKind::Signed : SemIR::IntKind::Unsigned, size_id);
  775. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  776. }
  777. // Maps a C++ builtin type to a Carbon type.
  778. // TODO: Support more builtin types.
  779. static auto MapBuiltinType(Context& context, clang::QualType qual_type,
  780. const clang::BuiltinType& type) -> TypeExpr {
  781. clang::ASTContext& ast_context = context.ast_context();
  782. if (type.isBooleanType()) {
  783. CARBON_CHECK(ast_context.hasSameType(qual_type, ast_context.BoolTy));
  784. return ExprAsType(context, Parse::NodeId::None,
  785. context.types().GetInstId(GetSingletonType(
  786. context, SemIR::BoolType::TypeInstId)));
  787. }
  788. if (type.isInteger()) {
  789. auto width = ast_context.getIntWidth(qual_type);
  790. bool is_signed = type.isSignedInteger();
  791. auto int_n_type = ast_context.getIntTypeForBitwidth(width, is_signed);
  792. if (ast_context.hasSameType(qual_type, int_n_type)) {
  793. return MakeIntType(context, context.ints().Add(width), is_signed);
  794. }
  795. // TODO: Handle integer types that map to named aliases.
  796. } else if (type.isDoubleType()) {
  797. // TODO: Handle other floating point types when Carbon supports fN where N
  798. // != 64.
  799. CARBON_CHECK(ast_context.getTypeSize(qual_type) == 64);
  800. CARBON_CHECK(ast_context.hasSameType(qual_type, ast_context.DoubleTy));
  801. return ExprAsType(
  802. context, Parse::NodeId::None,
  803. MakeFloatTypeLiteral(context, Parse::NodeId::None,
  804. SemIR::FloatKind::None, context.ints().Add(64)));
  805. }
  806. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  807. }
  808. // Maps a C++ record type to a Carbon type.
  809. static auto MapRecordType(Context& context, const clang::RecordType& type)
  810. -> TypeExpr {
  811. auto* record_decl = clang::dyn_cast<clang::CXXRecordDecl>(type.getDecl());
  812. if (!record_decl) {
  813. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  814. }
  815. // Check if the declaration is already mapped.
  816. SemIR::InstId record_inst_id = LookupClangDeclInstId(context, record_decl);
  817. if (!record_inst_id.has_value()) {
  818. record_inst_id = ImportCXXRecordDecl(context, record_decl);
  819. }
  820. SemIR::TypeInstId record_type_inst_id =
  821. context.types().GetAsTypeInstId(record_inst_id);
  822. return {
  823. .inst_id = record_type_inst_id,
  824. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  825. }
  826. // Maps a C++ type that is not a wrapper type such as a pointer to a Carbon
  827. // type.
  828. // TODO: Support more types.
  829. static auto MapNonWrapperType(Context& context, clang::QualType type)
  830. -> TypeExpr {
  831. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  832. return MapBuiltinType(context, type, *builtin_type);
  833. }
  834. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  835. return MapRecordType(context, *record_type);
  836. }
  837. CARBON_CHECK(!type.hasQualifiers() && !type->isPointerType(),
  838. "Should not see wrapper types here");
  839. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  840. }
  841. // Maps a qualified C++ type to a Carbon type.
  842. static auto MapQualifiedType(Context& context, SemIR::LocId loc_id,
  843. clang::QualType type, TypeExpr type_expr)
  844. -> TypeExpr {
  845. auto quals = type.getQualifiers();
  846. if (quals.hasConst()) {
  847. auto type_id = GetConstType(context, type_expr.inst_id);
  848. type_expr = {.inst_id = context.types().GetInstId(type_id),
  849. .type_id = type_id};
  850. quals.removeConst();
  851. }
  852. // TODO: Support other qualifiers.
  853. if (!quals.empty()) {
  854. context.TODO(loc_id, llvm::formatv("Unsupported: qualified type: {0}",
  855. type.getAsString()));
  856. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  857. .type_id = SemIR::ErrorInst::TypeId};
  858. }
  859. return type_expr;
  860. }
  861. // Maps a C++ pointer type to a Carbon pointer type.
  862. static auto MapPointerType(Context& context, SemIR::LocId loc_id,
  863. clang::QualType type, TypeExpr pointee_type_expr)
  864. -> TypeExpr {
  865. CARBON_CHECK(type->isPointerType());
  866. if (auto nullability = type->getNullability();
  867. !nullability.has_value() ||
  868. *nullability != clang::NullabilityKind::NonNull) {
  869. context.TODO(loc_id, llvm::formatv("Unsupported: nullable pointer: {0}",
  870. type.getAsString()));
  871. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  872. .type_id = SemIR::ErrorInst::TypeId};
  873. }
  874. SemIR::TypeId pointer_type_id =
  875. GetPointerType(context, pointee_type_expr.inst_id);
  876. return {.inst_id = context.types().GetInstId(pointer_type_id),
  877. .type_id = pointer_type_id};
  878. }
  879. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  880. // we check for pointer nullability and nullability will be lost by
  881. // canonicalization.
  882. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  883. -> TypeExpr {
  884. // Unwrap any type modifiers and wrappers.
  885. llvm::SmallVector<clang::QualType> wrapper_types;
  886. while (true) {
  887. clang::QualType orig_type = type;
  888. if (type.hasQualifiers()) {
  889. type = type.getUnqualifiedType();
  890. } else if (type->isPointerType()) {
  891. type = type->getPointeeType();
  892. } else {
  893. break;
  894. }
  895. wrapper_types.push_back(orig_type);
  896. }
  897. auto mapped = MapNonWrapperType(context, type);
  898. for (auto wrapper : llvm::reverse(wrapper_types)) {
  899. if (!mapped.inst_id.has_value() ||
  900. mapped.type_id == SemIR::ErrorInst::TypeId) {
  901. break;
  902. }
  903. if (wrapper.hasQualifiers()) {
  904. mapped = MapQualifiedType(context, loc_id, wrapper, mapped);
  905. } else if (wrapper->isPointerType()) {
  906. mapped = MapPointerType(context, loc_id, wrapper, mapped);
  907. } else {
  908. CARBON_FATAL("Unexpected wrapper type {0}", wrapper.getAsString());
  909. }
  910. }
  911. return mapped;
  912. }
  913. // Returns a block for the implicit parameters of the given function
  914. // declaration. Because function templates are not yet supported, this currently
  915. // only contains the `self` parameter. On error, produces a diagnostic and
  916. // returns None.
  917. static auto MakeImplicitParamPatternsBlockId(
  918. Context& context, SemIR::LocId loc_id,
  919. const clang::FunctionDecl& clang_decl) -> SemIR::InstBlockId {
  920. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(&clang_decl);
  921. if (!method_decl || method_decl->isStatic()) {
  922. return SemIR::InstBlockId::Empty;
  923. }
  924. // Build a `self` parameter from the object parameter.
  925. BeginSubpattern(context);
  926. // Perform some special-case mapping for the object parameter:
  927. //
  928. // - If it's a const reference to T, produce a by-value `self: T` parameter.
  929. // - If it's a non-const reference to T, produce an `addr self: T*`
  930. // parameter.
  931. // - Otherwise, map it directly, which will currently fail for `&&`-qualified
  932. // methods.
  933. //
  934. // TODO: Some of this mapping should be performed for all parameters.
  935. clang::QualType param_type =
  936. method_decl->getFunctionObjectParameterReferenceType();
  937. bool addr_self = false;
  938. if (param_type->isLValueReferenceType()) {
  939. param_type = param_type.getNonReferenceType();
  940. if (param_type.isConstQualified()) {
  941. // TODO: Consider only doing this if `const` is the only qualifier. For
  942. // now, any other qualifier will fail when mapping the type.
  943. auto split_type = param_type.getSplitUnqualifiedType();
  944. split_type.Quals.removeConst();
  945. param_type = method_decl->getASTContext().getQualifiedType(split_type);
  946. } else {
  947. addr_self = true;
  948. }
  949. }
  950. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  951. SemIR::ExprRegionId type_expr_region_id =
  952. EndSubpatternAsExpr(context, type_inst_id);
  953. if (!type_id.has_value()) {
  954. context.TODO(loc_id,
  955. llvm::formatv("Unsupported: object parameter type: {0}",
  956. param_type.getAsString()));
  957. return SemIR::InstBlockId::None;
  958. }
  959. // TODO: Fill in a location once available.
  960. auto pattern_id =
  961. addr_self ? AddAddrSelfParamPattern(context, SemIR::LocId::None,
  962. type_expr_region_id, type_inst_id)
  963. : AddSelfParamPattern(context, SemIR::LocId::None,
  964. type_expr_region_id, type_id);
  965. return context.inst_blocks().Add({pattern_id});
  966. }
  967. // Returns a block id for the explicit parameters of the given function
  968. // declaration. If the function declaration has no parameters, it returns
  969. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  970. // produces an error and returns `SemIR::InstBlockId::None`.
  971. // TODO: Consider refactoring to extract and reuse more logic from
  972. // `HandleAnyBindingPattern()`.
  973. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  974. const clang::FunctionDecl& clang_decl)
  975. -> SemIR::InstBlockId {
  976. if (clang_decl.parameters().empty()) {
  977. return SemIR::InstBlockId::Empty;
  978. }
  979. llvm::SmallVector<SemIR::InstId> params;
  980. params.reserve(clang_decl.parameters().size());
  981. for (const clang::ParmVarDecl* param : clang_decl.parameters()) {
  982. // TODO: Get the parameter type from the function, not from the
  983. // `ParmVarDecl`. The type of the `ParmVarDecl` is the type within the
  984. // function, and isn't in general the same as the type that's exposed to
  985. // callers. In particular, the parameter type exposed to callers will never
  986. // be cv-qualified.
  987. clang::QualType param_type = param->getType();
  988. // Mark the start of a region of insts, needed for the type expression
  989. // created later with the call of `EndSubpatternAsExpr()`.
  990. BeginSubpattern(context);
  991. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  992. // Type expression of the binding pattern - a single-entry/single-exit
  993. // region that allows control flow in the type expression e.g. fn F(x: if C
  994. // then i32 else i64).
  995. SemIR::ExprRegionId type_expr_region_id =
  996. EndSubpatternAsExpr(context, type_inst_id);
  997. if (!type_id.has_value()) {
  998. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  999. param_type.getAsString()));
  1000. return SemIR::InstBlockId::None;
  1001. }
  1002. llvm::StringRef param_name = param->getName();
  1003. SemIR::NameId name_id =
  1004. param_name.empty()
  1005. // Translate an unnamed parameter to an underscore to
  1006. // match Carbon's naming of unnamed/unused function params.
  1007. ? SemIR::NameId::Underscore
  1008. : AddIdentifierName(context, param_name);
  1009. // TODO: Fix this once templates are supported.
  1010. bool is_template = false;
  1011. // TODO: Fix this once generics are supported.
  1012. bool is_generic = false;
  1013. SemIR::InstId binding_pattern_id =
  1014. // TODO: Fill in a location once available.
  1015. AddBindingPattern(context, SemIR::LocId::None, name_id, type_id,
  1016. type_expr_region_id, is_generic, is_template)
  1017. .pattern_id;
  1018. SemIR::InstId var_pattern_id = AddPatternInst(
  1019. context,
  1020. // TODO: Fill in a location once available.
  1021. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  1022. {.type_id = context.insts().Get(binding_pattern_id).type_id(),
  1023. .subpattern_id = binding_pattern_id,
  1024. .index = SemIR::CallParamIndex::None})));
  1025. params.push_back(var_pattern_id);
  1026. }
  1027. return context.inst_blocks().Add(params);
  1028. }
  1029. // Returns the return type of the given function declaration. In case of an
  1030. // unsupported return type, it produces a diagnostic and returns
  1031. // `SemIR::ErrorInst::InstId`.
  1032. // TODO: Support more return types.
  1033. static auto GetReturnType(Context& context, SemIR::LocId loc_id,
  1034. const clang::FunctionDecl* clang_decl)
  1035. -> SemIR::InstId {
  1036. clang::QualType ret_type = clang_decl->getReturnType();
  1037. if (ret_type->isVoidType()) {
  1038. return SemIR::InstId::None;
  1039. }
  1040. auto [type_inst_id, type_id] = MapType(context, loc_id, ret_type);
  1041. if (!type_inst_id.has_value()) {
  1042. context.TODO(loc_id, llvm::formatv("Unsupported: return type: {0}",
  1043. ret_type.getAsString()));
  1044. return SemIR::ErrorInst::InstId;
  1045. }
  1046. auto pattern_type_id = GetPatternType(context, type_id);
  1047. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  1048. // TODO: Fill in a location for the return type once available.
  1049. context,
  1050. SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  1051. {.type_id = pattern_type_id, .type_inst_id = type_inst_id})));
  1052. SemIR::InstId param_pattern_id = AddPatternInst(
  1053. // TODO: Fill in a location for the return type once available.
  1054. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  1055. {.type_id = pattern_type_id,
  1056. .subpattern_id = return_slot_pattern_id,
  1057. .index = SemIR::CallParamIndex::None})));
  1058. return param_pattern_id;
  1059. }
  1060. namespace {
  1061. // Represents the parameter patterns block id, the return slot pattern id and
  1062. // the call parameters block id for a function declaration.
  1063. struct FunctionParamsInsts {
  1064. SemIR::InstBlockId implicit_param_patterns_id;
  1065. SemIR::InstBlockId param_patterns_id;
  1066. SemIR::InstId return_slot_pattern_id;
  1067. SemIR::InstBlockId call_params_id;
  1068. };
  1069. } // namespace
  1070. // Creates a block containing the parameter pattern instructions for the
  1071. // explicit parameters, a parameter pattern instruction for the return type and
  1072. // a block containing the call parameters of the function. Emits a callee
  1073. // pattern-match for the explicit parameter patterns and the return slot pattern
  1074. // to create the Call parameters instructions block. Currently the implicit
  1075. // parameter patterns are not taken into account. Returns the parameter patterns
  1076. // block id, the return slot pattern id, and the call parameters block id.
  1077. // Produces a diagnostic and returns `std::nullopt` if the function declaration
  1078. // has an unsupported parameter type.
  1079. static auto CreateFunctionParamsInsts(Context& context, SemIR::LocId loc_id,
  1080. const clang::FunctionDecl* clang_decl)
  1081. -> std::optional<FunctionParamsInsts> {
  1082. if (isa<clang::CXXConstructorDecl, clang::CXXDestructorDecl>(clang_decl)) {
  1083. context.TODO(loc_id, "Unsupported: Constructor/Destructor");
  1084. return std::nullopt;
  1085. }
  1086. auto implicit_param_patterns_id =
  1087. MakeImplicitParamPatternsBlockId(context, loc_id, *clang_decl);
  1088. if (!implicit_param_patterns_id.has_value()) {
  1089. return std::nullopt;
  1090. }
  1091. auto param_patterns_id =
  1092. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  1093. if (!param_patterns_id.has_value()) {
  1094. return std::nullopt;
  1095. }
  1096. auto return_slot_pattern_id = GetReturnType(context, loc_id, clang_decl);
  1097. if (SemIR::ErrorInst::InstId == return_slot_pattern_id) {
  1098. return std::nullopt;
  1099. }
  1100. auto call_params_id =
  1101. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  1102. return_slot_pattern_id);
  1103. return {{.implicit_param_patterns_id = implicit_param_patterns_id,
  1104. .param_patterns_id = param_patterns_id,
  1105. .return_slot_pattern_id = return_slot_pattern_id,
  1106. .call_params_id = call_params_id}};
  1107. }
  1108. // Imports a function declaration from Clang to Carbon. If successful, returns
  1109. // the new Carbon function declaration `InstId`. If the declaration was already
  1110. // imported, returns the mapped instruction.
  1111. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  1112. clang::FunctionDecl* clang_decl)
  1113. -> SemIR::InstId {
  1114. // Check if the declaration is already mapped.
  1115. if (SemIR::InstId existing_inst_id =
  1116. LookupClangDeclInstId(context, clang_decl);
  1117. existing_inst_id.has_value()) {
  1118. return existing_inst_id;
  1119. }
  1120. if (clang_decl->isVariadic()) {
  1121. context.TODO(loc_id, "Unsupported: Variadic function");
  1122. MarkFailedDecl(context, clang_decl);
  1123. return SemIR::ErrorInst::InstId;
  1124. }
  1125. if (clang_decl->getTemplatedKind() ==
  1126. clang::FunctionDecl::TK_FunctionTemplate) {
  1127. context.TODO(loc_id, "Unsupported: Template function");
  1128. MarkFailedDecl(context, clang_decl);
  1129. return SemIR::ErrorInst::InstId;
  1130. }
  1131. if (auto* method_decl = dyn_cast<clang::CXXMethodDecl>(clang_decl)) {
  1132. if (method_decl->isVirtual()) {
  1133. context.TODO(loc_id, "Unsupported: Virtual function");
  1134. MarkFailedDecl(context, clang_decl);
  1135. return SemIR::ErrorInst::InstId;
  1136. }
  1137. }
  1138. context.scope_stack().PushForDeclName();
  1139. context.inst_block_stack().Push();
  1140. context.pattern_block_stack().Push();
  1141. auto function_params_insts =
  1142. CreateFunctionParamsInsts(context, loc_id, clang_decl);
  1143. auto pattern_block_id = context.pattern_block_stack().Pop();
  1144. auto decl_block_id = context.inst_block_stack().Pop();
  1145. context.scope_stack().Pop();
  1146. if (!function_params_insts.has_value()) {
  1147. MarkFailedDecl(context, clang_decl);
  1148. return SemIR::ErrorInst::InstId;
  1149. }
  1150. auto function_decl = SemIR::FunctionDecl{
  1151. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  1152. auto decl_id =
  1153. AddPlaceholderInstInNoBlock(context, Parse::NodeId::None, function_decl);
  1154. context.imports().push_back(decl_id);
  1155. auto function_info = SemIR::Function{
  1156. {.name_id = AddIdentifierName(context, clang_decl->getName()),
  1157. .parent_scope_id = GetParentNameScopeId(context, clang_decl),
  1158. .generic_id = SemIR::GenericId::None,
  1159. .first_param_node_id = Parse::NodeId::None,
  1160. .last_param_node_id = Parse::NodeId::None,
  1161. .pattern_block_id = pattern_block_id,
  1162. .implicit_param_patterns_id =
  1163. function_params_insts->implicit_param_patterns_id,
  1164. .param_patterns_id = function_params_insts->param_patterns_id,
  1165. .is_extern = false,
  1166. .extern_library_id = SemIR::LibraryNameId::None,
  1167. .non_owning_decl_id = SemIR::InstId::None,
  1168. .first_owning_decl_id = decl_id,
  1169. .definition_id = SemIR::InstId::None},
  1170. {.call_params_id = function_params_insts->call_params_id,
  1171. .return_slot_pattern_id = function_params_insts->return_slot_pattern_id,
  1172. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  1173. .self_param_id = FindSelfPattern(
  1174. context, function_params_insts->implicit_param_patterns_id),
  1175. .clang_decl_id = context.sem_ir().clang_decls().Add(
  1176. {.decl = clang_decl, .inst_id = decl_id})}};
  1177. function_decl.function_id = context.functions().Add(function_info);
  1178. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  1179. SemIR::SpecificId::None);
  1180. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  1181. return decl_id;
  1182. }
  1183. using DeclSet = llvm::SetVector<clang::Decl*>;
  1184. // Adds the given declaration to our list of declarations to import.
  1185. static auto AddDependentDecl(const Context& context, clang::Decl* decl,
  1186. DeclSet& decls) -> void {
  1187. // TODO: Do we need to also add the parent of the declaration, recursively?
  1188. if (!IsClangDeclImported(context, decl)) {
  1189. decls.insert(decl);
  1190. }
  1191. }
  1192. // Finds all decls that need to be imported before importing the given type and
  1193. // adds them to the given set.
  1194. static auto AddDependentUnimportedTypeDecls(const Context& context,
  1195. clang::QualType type,
  1196. DeclSet& decls) -> void {
  1197. while (true) {
  1198. if (type->isPointerType() || type->isReferenceType()) {
  1199. type = type->getPointeeType();
  1200. } else if (const clang::ArrayType* array_type =
  1201. type->getAsArrayTypeUnsafe()) {
  1202. type = array_type->getElementType();
  1203. } else {
  1204. break;
  1205. }
  1206. }
  1207. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  1208. AddDependentDecl(context, record_type->getDecl(), decls);
  1209. }
  1210. }
  1211. // Finds all decls that need to be imported before importing the given function
  1212. // and adds them to the given set.
  1213. static auto AddDependentUnimportedFunctionDecls(
  1214. const Context& context, const clang::FunctionDecl& clang_decl,
  1215. DeclSet& decls) -> void {
  1216. for (const auto* param : clang_decl.parameters()) {
  1217. AddDependentUnimportedTypeDecls(context, param->getType(), decls);
  1218. }
  1219. AddDependentUnimportedTypeDecls(context, clang_decl.getReturnType(), decls);
  1220. }
  1221. // Finds all decls that need to be imported before importing the given
  1222. // declaration and adds them to the given set.
  1223. static auto AddDependentUnimportedDecls(const Context& context,
  1224. clang::Decl* clang_decl, DeclSet& decls)
  1225. -> void {
  1226. if (auto* parent_decl = GetParentDecl(clang_decl)) {
  1227. AddDependentDecl(context, parent_decl, decls);
  1228. }
  1229. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1230. AddDependentUnimportedFunctionDecls(context, *clang_function_decl, decls);
  1231. } else if (auto* type_decl = clang::dyn_cast<clang::TypeDecl>(clang_decl)) {
  1232. AddDependentUnimportedTypeDecls(
  1233. context, type_decl->getASTContext().getTypeDeclType(type_decl), decls);
  1234. }
  1235. }
  1236. // Imports a declaration from Clang to Carbon. If successful, returns the
  1237. // instruction for the new Carbon declaration. Assumes all dependencies have
  1238. // already been imported.
  1239. static auto ImportDeclAfterDependencies(Context& context, SemIR::LocId loc_id,
  1240. clang::Decl* clang_decl)
  1241. -> SemIR::InstId {
  1242. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1243. return ImportFunctionDecl(context, loc_id, clang_function_decl);
  1244. }
  1245. if (auto* clang_namespace_decl =
  1246. clang::dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  1247. return ImportNamespaceDecl(context, clang_namespace_decl);
  1248. }
  1249. if (auto* type_decl = clang::dyn_cast<clang::TypeDecl>(clang_decl)) {
  1250. auto type = type_decl->getASTContext().getTypeDeclType(type_decl);
  1251. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  1252. if (!type_inst_id.has_value()) {
  1253. context.TODO(loc_id, llvm::formatv("Unsupported: Type declaration: {0}",
  1254. type.getAsString()));
  1255. return SemIR::ErrorInst::InstId;
  1256. }
  1257. return type_inst_id;
  1258. }
  1259. if (clang::isa<clang::FieldDecl, clang::IndirectFieldDecl>(clang_decl)) {
  1260. // Usable fields get imported as a side effect of importing the class.
  1261. if (SemIR::InstId existing_inst_id =
  1262. LookupClangDeclInstId(context, clang_decl);
  1263. existing_inst_id.has_value()) {
  1264. return existing_inst_id;
  1265. }
  1266. context.TODO(loc_id, "Unsupported: Unhandled kind of field declaration");
  1267. return SemIR::InstId::None;
  1268. }
  1269. context.TODO(loc_id, llvm::formatv("Unsupported: Declaration type {0}",
  1270. clang_decl->getDeclKindName())
  1271. .str());
  1272. return SemIR::InstId::None;
  1273. }
  1274. // Imports a declaration from Clang to Carbon. If successful, returns the
  1275. // instruction for the new Carbon declaration. All unimported dependencies would
  1276. // be imported first.
  1277. static auto ImportDeclAndDependencies(Context& context, SemIR::LocId loc_id,
  1278. clang::Decl* clang_decl)
  1279. -> SemIR::InstId {
  1280. // Collect dependencies.
  1281. llvm::SetVector<clang::Decl*> clang_decls;
  1282. clang_decls.insert(clang_decl);
  1283. for (size_t i = 0; i < clang_decls.size(); ++i) {
  1284. AddDependentUnimportedDecls(context, clang_decls[i], clang_decls);
  1285. }
  1286. // Import dependencies in reverse order.
  1287. auto inst_id = SemIR::InstId::None;
  1288. for (clang::Decl* clang_decl_to_import : llvm::reverse(clang_decls)) {
  1289. inst_id =
  1290. ImportDeclAfterDependencies(context, loc_id, clang_decl_to_import);
  1291. if (!inst_id.has_value()) {
  1292. break;
  1293. }
  1294. }
  1295. return inst_id;
  1296. }
  1297. // Maps `clang::AccessSpecifier` to `SemIR::AccessKind`.
  1298. static auto MapAccess(clang::AccessSpecifier access_specifier)
  1299. -> SemIR::AccessKind {
  1300. switch (access_specifier) {
  1301. case clang::AS_public:
  1302. case clang::AS_none:
  1303. return SemIR::AccessKind::Public;
  1304. case clang::AS_protected:
  1305. return SemIR::AccessKind::Protected;
  1306. case clang::AS_private:
  1307. return SemIR::AccessKind::Private;
  1308. }
  1309. }
  1310. // Imports a `clang::NamedDecl` into Carbon and adds that name into the
  1311. // `NameScope`.
  1312. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  1313. SemIR::NameScopeId scope_id,
  1314. SemIR::NameId name_id,
  1315. clang::NamedDecl* clang_decl,
  1316. clang::AccessSpecifier access)
  1317. -> SemIR::ScopeLookupResult {
  1318. SemIR::InstId inst_id =
  1319. ImportDeclAndDependencies(context, loc_id, clang_decl);
  1320. if (!inst_id.has_value()) {
  1321. return SemIR::ScopeLookupResult::MakeNotFound();
  1322. }
  1323. SemIR::AccessKind access_kind = MapAccess(access);
  1324. AddNameToScope(context, scope_id, name_id, access_kind, inst_id);
  1325. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1326. access_kind);
  1327. }
  1328. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  1329. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  1330. -> SemIR::ScopeLookupResult {
  1331. Diagnostics::AnnotationScope annotate_diagnostics(
  1332. &context.emitter(), [&](auto& builder) {
  1333. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  1334. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  1335. builder.Note(loc_id, InCppNameLookup, name_id);
  1336. });
  1337. auto lookup = ClangLookup(context, scope_id, name_id);
  1338. if (!lookup) {
  1339. return SemIR::ScopeLookupResult::MakeNotFound();
  1340. }
  1341. // Access checks are performed separately by the Carbon name lookup logic.
  1342. lookup->suppressAccessDiagnostics();
  1343. if (!lookup->isSingleResult()) {
  1344. // Clang will diagnose ambiguous lookup results for us.
  1345. if (!lookup->isAmbiguous()) {
  1346. context.TODO(loc_id,
  1347. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  1348. "find a single result; LookupResultKind: {0}",
  1349. static_cast<int>(lookup->getResultKind()))
  1350. .str());
  1351. }
  1352. context.name_scopes().AddRequiredName(scope_id, name_id,
  1353. SemIR::ErrorInst::InstId);
  1354. return SemIR::ScopeLookupResult::MakeError();
  1355. }
  1356. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id,
  1357. lookup->getFoundDecl(),
  1358. lookup->begin().getAccess());
  1359. }
  1360. } // namespace Carbon::Check