import_cpp.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  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_->clang_ast_unit(),
  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_clang_ast_unit(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().clang_ast_unit());
  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().clang_ast_unit();
  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().clang_ast_unit()->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().clang_ast_unit()->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().clang_ast_unit();
  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, clang::QualType type,
  982. TypeExpr type_expr) -> TypeExpr {
  983. auto quals = type.getQualifiers();
  984. if (quals.hasConst()) {
  985. auto type_id = GetConstType(context, type_expr.inst_id);
  986. type_expr = {.inst_id = context.types().GetInstId(type_id),
  987. .type_id = type_id};
  988. quals.removeConst();
  989. }
  990. // TODO: Support other qualifiers.
  991. if (!quals.empty()) {
  992. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  993. }
  994. return type_expr;
  995. }
  996. // Maps a C++ pointer type to a Carbon pointer type.
  997. static auto MapPointerType(Context& context, clang::QualType type,
  998. TypeExpr pointee_type_expr) -> TypeExpr {
  999. CARBON_CHECK(type->isPointerType());
  1000. if (auto nullability = type->getNullability();
  1001. !nullability.has_value() ||
  1002. *nullability != clang::NullabilityKind::NonNull) {
  1003. // TODO: Support nullable pointers.
  1004. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  1005. }
  1006. SemIR::TypeId pointer_type_id =
  1007. GetPointerType(context, pointee_type_expr.inst_id);
  1008. return {.inst_id = context.types().GetInstId(pointer_type_id),
  1009. .type_id = pointer_type_id};
  1010. }
  1011. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  1012. // we check for pointer nullability and nullability will be lost by
  1013. // canonicalization.
  1014. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  1015. -> TypeExpr {
  1016. // Unwrap any type modifiers and wrappers.
  1017. llvm::SmallVector<clang::QualType> wrapper_types;
  1018. while (true) {
  1019. clang::QualType orig_type = type;
  1020. if (type.hasQualifiers()) {
  1021. type = type.getUnqualifiedType();
  1022. } else if (type->isPointerType()) {
  1023. type = type->getPointeeType();
  1024. } else {
  1025. break;
  1026. }
  1027. wrapper_types.push_back(orig_type);
  1028. }
  1029. auto mapped = MapNonWrapperType(context, loc_id, type);
  1030. for (auto wrapper : llvm::reverse(wrapper_types)) {
  1031. if (!mapped.inst_id.has_value() ||
  1032. mapped.type_id == SemIR::ErrorInst::TypeId) {
  1033. break;
  1034. }
  1035. if (wrapper.hasQualifiers()) {
  1036. mapped = MapQualifiedType(context, wrapper, mapped);
  1037. } else if (wrapper->isPointerType()) {
  1038. mapped = MapPointerType(context, wrapper, mapped);
  1039. } else {
  1040. CARBON_FATAL("Unexpected wrapper type {0}", wrapper.getAsString());
  1041. }
  1042. }
  1043. return mapped;
  1044. }
  1045. // Returns a block for the implicit parameters of the given function
  1046. // declaration. Because function templates are not yet supported, this currently
  1047. // only contains the `self` parameter. On error, produces a diagnostic and
  1048. // returns None.
  1049. static auto MakeImplicitParamPatternsBlockId(
  1050. Context& context, SemIR::LocId loc_id,
  1051. const clang::FunctionDecl& clang_decl) -> SemIR::InstBlockId {
  1052. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(&clang_decl);
  1053. if (!method_decl || method_decl->isStatic() ||
  1054. isa<clang::CXXConstructorDecl>(clang_decl)) {
  1055. return SemIR::InstBlockId::Empty;
  1056. }
  1057. // Build a `self` parameter from the object parameter.
  1058. BeginSubpattern(context);
  1059. // Perform some special-case mapping for the object parameter:
  1060. //
  1061. // - If it's a const reference to T, produce a by-value `self: T` parameter.
  1062. // - If it's a non-const reference to T, produce an `addr self: T*`
  1063. // parameter.
  1064. // - Otherwise, map it directly, which will currently fail for `&&`-qualified
  1065. // methods.
  1066. //
  1067. // TODO: Some of this mapping should be performed for all parameters.
  1068. clang::QualType param_type =
  1069. method_decl->getFunctionObjectParameterReferenceType();
  1070. bool addr_self = false;
  1071. if (param_type->isLValueReferenceType()) {
  1072. param_type = param_type.getNonReferenceType();
  1073. if (param_type.isConstQualified()) {
  1074. // TODO: Consider only doing this if `const` is the only qualifier. For
  1075. // now, any other qualifier will fail when mapping the type.
  1076. auto split_type = param_type.getSplitUnqualifiedType();
  1077. split_type.Quals.removeConst();
  1078. param_type = method_decl->getASTContext().getQualifiedType(split_type);
  1079. } else {
  1080. addr_self = true;
  1081. }
  1082. }
  1083. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  1084. SemIR::ExprRegionId type_expr_region_id =
  1085. EndSubpatternAsExpr(context, type_inst_id);
  1086. if (!type_id.has_value()) {
  1087. context.TODO(loc_id,
  1088. llvm::formatv("Unsupported: object parameter type: {0}",
  1089. param_type.getAsString()));
  1090. return SemIR::InstBlockId::None;
  1091. }
  1092. // TODO: Fill in a location once available.
  1093. auto pattern_id =
  1094. addr_self ? AddAddrSelfParamPattern(context, SemIR::LocId::None,
  1095. type_expr_region_id, type_inst_id)
  1096. : AddSelfParamPattern(context, SemIR::LocId::None,
  1097. type_expr_region_id, type_id);
  1098. return context.inst_blocks().Add({pattern_id});
  1099. }
  1100. // Returns a block id for the explicit parameters of the given function
  1101. // declaration. If the function declaration has no parameters, it returns
  1102. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  1103. // produces an error and returns `SemIR::InstBlockId::None`.
  1104. // TODO: Consider refactoring to extract and reuse more logic from
  1105. // `HandleAnyBindingPattern()`.
  1106. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  1107. const clang::FunctionDecl& clang_decl)
  1108. -> SemIR::InstBlockId {
  1109. if (clang_decl.parameters().empty()) {
  1110. return SemIR::InstBlockId::Empty;
  1111. }
  1112. llvm::SmallVector<SemIR::InstId> params;
  1113. params.reserve(clang_decl.parameters().size());
  1114. for (const clang::ParmVarDecl* param : clang_decl.parameters()) {
  1115. // TODO: Get the parameter type from the function, not from the
  1116. // `ParmVarDecl`. The type of the `ParmVarDecl` is the type within the
  1117. // function, and isn't in general the same as the type that's exposed to
  1118. // callers. In particular, the parameter type exposed to callers will never
  1119. // be cv-qualified.
  1120. clang::QualType param_type = param->getType();
  1121. // Mark the start of a region of insts, needed for the type expression
  1122. // created later with the call of `EndSubpatternAsExpr()`.
  1123. BeginSubpattern(context);
  1124. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  1125. // Type expression of the binding pattern - a single-entry/single-exit
  1126. // region that allows control flow in the type expression e.g. fn F(x: if C
  1127. // then i32 else i64).
  1128. SemIR::ExprRegionId type_expr_region_id =
  1129. EndSubpatternAsExpr(context, type_inst_id);
  1130. if (!type_id.has_value()) {
  1131. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  1132. param_type.getAsString()));
  1133. return SemIR::InstBlockId::None;
  1134. }
  1135. llvm::StringRef param_name = param->getName();
  1136. SemIR::NameId name_id =
  1137. param_name.empty()
  1138. // Translate an unnamed parameter to an underscore to
  1139. // match Carbon's naming of unnamed/unused function params.
  1140. ? SemIR::NameId::Underscore
  1141. : AddIdentifierName(context, param_name);
  1142. // TODO: Fix this once templates are supported.
  1143. bool is_template = false;
  1144. // TODO: Fix this once generics are supported.
  1145. bool is_generic = false;
  1146. SemIR::InstId binding_pattern_id =
  1147. // TODO: Fill in a location once available.
  1148. AddBindingPattern(context, SemIR::LocId::None, name_id, type_id,
  1149. type_expr_region_id, is_generic, is_template)
  1150. .pattern_id;
  1151. SemIR::InstId var_pattern_id = AddPatternInst(
  1152. context,
  1153. // TODO: Fill in a location once available.
  1154. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  1155. {.type_id = context.insts().Get(binding_pattern_id).type_id(),
  1156. .subpattern_id = binding_pattern_id,
  1157. .index = SemIR::CallParamIndex::None})));
  1158. params.push_back(var_pattern_id);
  1159. }
  1160. return context.inst_blocks().Add(params);
  1161. }
  1162. // Returns the return `TypeExpr` of the given function declaration. In case of
  1163. // an unsupported return type, returns `SemIR::ErrorInst::InstId`. Constructors
  1164. // are treated as returning a class instance.
  1165. // TODO: Support more return types.
  1166. static auto GetReturnTypeExpr(Context& context, SemIR::LocId loc_id,
  1167. clang::FunctionDecl* clang_decl) -> TypeExpr {
  1168. clang::QualType ret_type = clang_decl->getReturnType();
  1169. if (!ret_type->isVoidType()) {
  1170. TypeExpr mapped_type = MapType(context, loc_id, ret_type);
  1171. if (!mapped_type.inst_id.has_value()) {
  1172. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1173. .type_id = SemIR::ErrorInst::TypeId};
  1174. }
  1175. return mapped_type;
  1176. }
  1177. if (!isa<clang::CXXConstructorDecl>(clang_decl)) {
  1178. // void.
  1179. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  1180. }
  1181. // TODO: Make this a `PartialType`.
  1182. SemIR::TypeInstId record_type_inst_id = context.types().GetAsTypeInstId(
  1183. context.sem_ir()
  1184. .clang_decls()
  1185. .Get(context.sem_ir().clang_decls().Lookup(
  1186. cast<clang::Decl>(clang_decl->getParent())))
  1187. .inst_id);
  1188. return {
  1189. .inst_id = record_type_inst_id,
  1190. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  1191. }
  1192. // Returns the return pattern of the given function declaration. In case of an
  1193. // unsupported return type, it produces a diagnostic and returns
  1194. // `SemIR::ErrorInst::InstId`. Constructors are treated as returning a class
  1195. // instance.
  1196. static auto GetReturnPattern(Context& context, SemIR::LocId loc_id,
  1197. clang::FunctionDecl* clang_decl) -> SemIR::InstId {
  1198. auto [type_inst_id, type_id] = GetReturnTypeExpr(context, loc_id, clang_decl);
  1199. if (!type_inst_id.has_value()) {
  1200. // void.
  1201. return SemIR::InstId::None;
  1202. }
  1203. if (type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1204. context.TODO(loc_id,
  1205. llvm::formatv("Unsupported: return type: {0}",
  1206. clang_decl->getReturnType().getAsString()));
  1207. return SemIR::ErrorInst::InstId;
  1208. }
  1209. auto pattern_type_id = GetPatternType(context, type_id);
  1210. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  1211. // TODO: Fill in a location for the return type once available.
  1212. context,
  1213. SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  1214. {.type_id = pattern_type_id, .type_inst_id = type_inst_id})));
  1215. SemIR::InstId param_pattern_id = AddPatternInst(
  1216. // TODO: Fill in a location for the return type once available.
  1217. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  1218. {.type_id = pattern_type_id,
  1219. .subpattern_id = return_slot_pattern_id,
  1220. .index = SemIR::CallParamIndex::None})));
  1221. return param_pattern_id;
  1222. }
  1223. namespace {
  1224. // Represents the parameter patterns block id, the return slot pattern id and
  1225. // the call parameters block id for a function declaration.
  1226. struct FunctionParamsInsts {
  1227. SemIR::InstBlockId implicit_param_patterns_id;
  1228. SemIR::InstBlockId param_patterns_id;
  1229. SemIR::InstId return_slot_pattern_id;
  1230. SemIR::InstBlockId call_params_id;
  1231. };
  1232. } // namespace
  1233. // Creates a block containing the parameter pattern instructions for the
  1234. // explicit parameters, a parameter pattern instruction for the return type and
  1235. // a block containing the call parameters of the function. Emits a callee
  1236. // pattern-match for the explicit parameter patterns and the return slot pattern
  1237. // to create the Call parameters instructions block. Currently the implicit
  1238. // parameter patterns are not taken into account. Returns the parameter patterns
  1239. // block id, the return slot pattern id, and the call parameters block id.
  1240. // Produces a diagnostic and returns `std::nullopt` if the function declaration
  1241. // has an unsupported parameter type.
  1242. static auto CreateFunctionParamsInsts(Context& context, SemIR::LocId loc_id,
  1243. clang::FunctionDecl* clang_decl)
  1244. -> std::optional<FunctionParamsInsts> {
  1245. if (isa<clang::CXXDestructorDecl>(clang_decl)) {
  1246. context.TODO(loc_id, "Unsupported: Destructor");
  1247. return std::nullopt;
  1248. }
  1249. auto implicit_param_patterns_id =
  1250. MakeImplicitParamPatternsBlockId(context, loc_id, *clang_decl);
  1251. if (!implicit_param_patterns_id.has_value()) {
  1252. return std::nullopt;
  1253. }
  1254. auto param_patterns_id =
  1255. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  1256. if (!param_patterns_id.has_value()) {
  1257. return std::nullopt;
  1258. }
  1259. auto return_slot_pattern_id = GetReturnPattern(context, loc_id, clang_decl);
  1260. if (SemIR::ErrorInst::InstId == return_slot_pattern_id) {
  1261. return std::nullopt;
  1262. }
  1263. auto call_params_id =
  1264. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  1265. return_slot_pattern_id);
  1266. return {{.implicit_param_patterns_id = implicit_param_patterns_id,
  1267. .param_patterns_id = param_patterns_id,
  1268. .return_slot_pattern_id = return_slot_pattern_id,
  1269. .call_params_id = call_params_id}};
  1270. }
  1271. // Creates a `FunctionDecl` and a `Function` without C++ thunk information.
  1272. // Returns std::nullopt on failure. The given Clang declaration is assumed to:
  1273. // * Have not been imported before.
  1274. // * Be of supported type (ignoring parameters).
  1275. static auto ImportFunction(Context& context, SemIR::LocId loc_id,
  1276. clang::FunctionDecl* clang_decl)
  1277. -> std::optional<SemIR::FunctionId> {
  1278. context.scope_stack().PushForDeclName();
  1279. context.inst_block_stack().Push();
  1280. context.pattern_block_stack().Push();
  1281. auto function_params_insts =
  1282. CreateFunctionParamsInsts(context, loc_id, clang_decl);
  1283. auto pattern_block_id = context.pattern_block_stack().Pop();
  1284. auto decl_block_id = context.inst_block_stack().Pop();
  1285. context.scope_stack().Pop();
  1286. if (!function_params_insts.has_value()) {
  1287. return std::nullopt;
  1288. }
  1289. auto function_decl = SemIR::FunctionDecl{
  1290. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  1291. auto decl_id =
  1292. AddPlaceholderInstInNoBlock(context, Parse::NodeId::None, function_decl);
  1293. context.imports().push_back(decl_id);
  1294. SemIR::NameId function_name_id =
  1295. isa<clang::CXXConstructorDecl>(clang_decl)
  1296. ? context.classes()
  1297. .Get(context.insts()
  1298. .GetAs<SemIR::ClassDecl>(LookupClangDeclInstId(
  1299. context,
  1300. cast<clang::Decl>(clang_decl->getParent())))
  1301. .class_id)
  1302. .name_id
  1303. : AddIdentifierName(context, clang_decl->getName());
  1304. auto function_info = SemIR::Function{
  1305. {.name_id = function_name_id,
  1306. .parent_scope_id = GetParentNameScopeId(context, clang_decl),
  1307. .generic_id = SemIR::GenericId::None,
  1308. .first_param_node_id = Parse::NodeId::None,
  1309. .last_param_node_id = Parse::NodeId::None,
  1310. .pattern_block_id = pattern_block_id,
  1311. .implicit_param_patterns_id =
  1312. function_params_insts->implicit_param_patterns_id,
  1313. .param_patterns_id = function_params_insts->param_patterns_id,
  1314. .is_extern = false,
  1315. .extern_library_id = SemIR::LibraryNameId::None,
  1316. .non_owning_decl_id = SemIR::InstId::None,
  1317. .first_owning_decl_id = decl_id,
  1318. .definition_id = SemIR::InstId::None},
  1319. {.call_params_id = function_params_insts->call_params_id,
  1320. .return_slot_pattern_id = function_params_insts->return_slot_pattern_id,
  1321. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  1322. .self_param_id = FindSelfPattern(
  1323. context, function_params_insts->implicit_param_patterns_id),
  1324. .clang_decl_id = context.sem_ir().clang_decls().Add(
  1325. {.decl = clang_decl, .inst_id = decl_id})}};
  1326. function_decl.function_id = context.functions().Add(function_info);
  1327. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  1328. SemIR::SpecificId::None);
  1329. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  1330. return function_decl.function_id;
  1331. }
  1332. // Imports a function declaration from Clang to Carbon. If successful, returns
  1333. // the new Carbon function declaration `InstId`. If the declaration was already
  1334. // imported, returns the mapped instruction.
  1335. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  1336. clang::FunctionDecl* clang_decl)
  1337. -> SemIR::InstId {
  1338. // Check if the declaration is already mapped.
  1339. if (SemIR::InstId existing_inst_id =
  1340. LookupClangDeclInstId(context, clang_decl);
  1341. existing_inst_id.has_value()) {
  1342. return existing_inst_id;
  1343. }
  1344. if (clang_decl->isVariadic()) {
  1345. context.TODO(loc_id, "Unsupported: Variadic function");
  1346. MarkFailedDecl(context, clang_decl);
  1347. return SemIR::ErrorInst::InstId;
  1348. }
  1349. if (clang_decl->getTemplatedKind() ==
  1350. clang::FunctionDecl::TK_FunctionTemplate) {
  1351. context.TODO(loc_id, "Unsupported: Template function");
  1352. MarkFailedDecl(context, clang_decl);
  1353. return SemIR::ErrorInst::InstId;
  1354. }
  1355. if (auto* method_decl = dyn_cast<clang::CXXMethodDecl>(clang_decl)) {
  1356. if (method_decl->isVirtual()) {
  1357. context.TODO(loc_id, "Unsupported: Virtual function");
  1358. MarkFailedDecl(context, clang_decl);
  1359. return SemIR::ErrorInst::InstId;
  1360. }
  1361. }
  1362. CARBON_CHECK(clang_decl->getFunctionType()->isFunctionProtoType(),
  1363. "Not Prototype function (non-C++ code)");
  1364. auto function_id = ImportFunction(context, loc_id, clang_decl);
  1365. if (!function_id) {
  1366. MarkFailedDecl(context, clang_decl);
  1367. return SemIR::ErrorInst::InstId;
  1368. }
  1369. SemIR::Function& function_info = context.functions().Get(*function_id);
  1370. if (IsCppThunkRequired(context, function_info)) {
  1371. clang::FunctionDecl* thunk_clang_decl =
  1372. BuildCppThunk(context, function_info);
  1373. if (thunk_clang_decl) {
  1374. SemIR::FunctionId thunk_function_id =
  1375. *ImportFunction(context, loc_id, thunk_clang_decl);
  1376. SemIR::InstId thunk_function_decl_id =
  1377. context.functions().Get(thunk_function_id).first_owning_decl_id;
  1378. function_info.SetHasCppThunk(thunk_function_decl_id);
  1379. }
  1380. }
  1381. return function_info.first_owning_decl_id;
  1382. }
  1383. using DeclSet = llvm::SetVector<clang::Decl*>;
  1384. // Adds the given declaration to our list of declarations to import.
  1385. static auto AddDependentDecl(const Context& context, clang::Decl* decl,
  1386. DeclSet& decls) -> void {
  1387. // TODO: Do we need to also add the parent of the declaration, recursively?
  1388. if (!IsClangDeclImported(context, decl)) {
  1389. decls.insert(decl);
  1390. }
  1391. }
  1392. // Finds all decls that need to be imported before importing the given type and
  1393. // adds them to the given set.
  1394. static auto AddDependentUnimportedTypeDecls(const Context& context,
  1395. clang::QualType type,
  1396. DeclSet& decls) -> void {
  1397. while (true) {
  1398. if (type->isPointerType() || type->isReferenceType()) {
  1399. type = type->getPointeeType();
  1400. } else if (const clang::ArrayType* array_type =
  1401. type->getAsArrayTypeUnsafe()) {
  1402. type = array_type->getElementType();
  1403. } else {
  1404. break;
  1405. }
  1406. }
  1407. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  1408. AddDependentDecl(context, record_type->getDecl(), decls);
  1409. }
  1410. }
  1411. // Finds all decls that need to be imported before importing the given function
  1412. // and adds them to the given set.
  1413. static auto AddDependentUnimportedFunctionDecls(
  1414. const Context& context, const clang::FunctionDecl& clang_decl,
  1415. DeclSet& decls) -> void {
  1416. for (const auto* param : clang_decl.parameters()) {
  1417. AddDependentUnimportedTypeDecls(context, param->getType(), decls);
  1418. }
  1419. AddDependentUnimportedTypeDecls(context, clang_decl.getReturnType(), decls);
  1420. }
  1421. // Finds all decls that need to be imported before importing the given
  1422. // declaration and adds them to the given set.
  1423. static auto AddDependentUnimportedDecls(const Context& context,
  1424. clang::Decl* clang_decl, DeclSet& decls)
  1425. -> void {
  1426. if (auto* parent_decl = GetParentDecl(clang_decl)) {
  1427. AddDependentDecl(context, parent_decl, decls);
  1428. }
  1429. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1430. AddDependentUnimportedFunctionDecls(context, *clang_function_decl, decls);
  1431. } else if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1432. AddDependentUnimportedTypeDecls(
  1433. context, type_decl->getASTContext().getTypeDeclType(type_decl), decls);
  1434. }
  1435. }
  1436. // Imports a declaration from Clang to Carbon. If successful, returns the
  1437. // instruction for the new Carbon declaration. Assumes all dependencies have
  1438. // already been imported.
  1439. static auto ImportDeclAfterDependencies(Context& context, SemIR::LocId loc_id,
  1440. clang::Decl* clang_decl)
  1441. -> SemIR::InstId {
  1442. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1443. return ImportFunctionDecl(context, loc_id, clang_function_decl);
  1444. }
  1445. if (auto* clang_namespace_decl = dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  1446. return ImportNamespaceDecl(context, clang_namespace_decl);
  1447. }
  1448. if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1449. auto type = clang_decl->getASTContext().getTypeDeclType(type_decl);
  1450. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  1451. if (!type_inst_id.has_value()) {
  1452. context.TODO(AddImportIRInst(context.sem_ir(), type_decl->getLocation()),
  1453. llvm::formatv("Unsupported: Type declaration: {0}",
  1454. type.getAsString()));
  1455. return SemIR::ErrorInst::InstId;
  1456. }
  1457. return type_inst_id;
  1458. }
  1459. if (isa<clang::FieldDecl, clang::IndirectFieldDecl>(clang_decl)) {
  1460. // Usable fields get imported as a side effect of importing the class.
  1461. if (SemIR::InstId existing_inst_id =
  1462. LookupClangDeclInstId(context, clang_decl);
  1463. existing_inst_id.has_value()) {
  1464. return existing_inst_id;
  1465. }
  1466. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1467. "Unsupported: field declaration has unhandled type or kind");
  1468. return SemIR::ErrorInst::InstId;
  1469. }
  1470. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1471. llvm::formatv("Unsupported: Declaration type {0}",
  1472. clang_decl->getDeclKindName()));
  1473. return SemIR::ErrorInst::InstId;
  1474. }
  1475. // Imports a declaration from Clang to Carbon. If successful, returns the
  1476. // instruction for the new Carbon declaration. All unimported dependencies would
  1477. // be imported first.
  1478. static auto ImportDeclAndDependencies(Context& context, SemIR::LocId loc_id,
  1479. clang::Decl* clang_decl)
  1480. -> SemIR::InstId {
  1481. // Collect dependencies.
  1482. llvm::SetVector<clang::Decl*> clang_decls;
  1483. clang_decls.insert(clang_decl);
  1484. for (size_t i = 0; i < clang_decls.size(); ++i) {
  1485. AddDependentUnimportedDecls(context, clang_decls[i], clang_decls);
  1486. }
  1487. // Import dependencies in reverse order.
  1488. auto inst_id = SemIR::InstId::None;
  1489. for (clang::Decl* clang_decl_to_import : llvm::reverse(clang_decls)) {
  1490. inst_id =
  1491. ImportDeclAfterDependencies(context, loc_id, clang_decl_to_import);
  1492. if (!inst_id.has_value()) {
  1493. break;
  1494. }
  1495. }
  1496. return inst_id;
  1497. }
  1498. // Maps `clang::AccessSpecifier` to `SemIR::AccessKind`.
  1499. static auto MapAccess(clang::AccessSpecifier access_specifier)
  1500. -> SemIR::AccessKind {
  1501. switch (access_specifier) {
  1502. case clang::AS_public:
  1503. case clang::AS_none:
  1504. return SemIR::AccessKind::Public;
  1505. case clang::AS_protected:
  1506. return SemIR::AccessKind::Protected;
  1507. case clang::AS_private:
  1508. return SemIR::AccessKind::Private;
  1509. }
  1510. }
  1511. // Imports a `clang::NamedDecl` into Carbon and adds that name into the
  1512. // `NameScope`.
  1513. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  1514. SemIR::NameScopeId scope_id,
  1515. SemIR::NameId name_id,
  1516. clang::NamedDecl* clang_decl,
  1517. clang::AccessSpecifier access)
  1518. -> SemIR::ScopeLookupResult {
  1519. SemIR::InstId inst_id =
  1520. ImportDeclAndDependencies(context, loc_id, clang_decl);
  1521. if (!inst_id.has_value()) {
  1522. return SemIR::ScopeLookupResult::MakeNotFound();
  1523. }
  1524. SemIR::AccessKind access_kind = MapAccess(access);
  1525. AddNameToScope(context, scope_id, name_id, access_kind, inst_id);
  1526. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1527. access_kind);
  1528. }
  1529. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  1530. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  1531. -> SemIR::ScopeLookupResult {
  1532. Diagnostics::AnnotationScope annotate_diagnostics(
  1533. &context.emitter(), [&](auto& builder) {
  1534. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  1535. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  1536. builder.Note(loc_id, InCppNameLookup, name_id);
  1537. });
  1538. auto decl_and_access = ClangLookup(context, loc_id, scope_id, name_id);
  1539. if (!decl_and_access) {
  1540. return SemIR::ScopeLookupResult::MakeNotFound();
  1541. }
  1542. auto [decl, access] = *decl_and_access;
  1543. if (!decl) {
  1544. context.name_scopes().AddRequiredName(scope_id, name_id,
  1545. SemIR::ErrorInst::InstId);
  1546. return SemIR::ScopeLookupResult::MakeError();
  1547. }
  1548. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id, decl,
  1549. access);
  1550. }
  1551. } // namespace Carbon::Check