import_cpp.cpp 62 KB

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