import_cpp.cpp 65 KB

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