import_cpp.cpp 71 KB

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