import_cpp.cpp 63 KB

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