import_cpp.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/import_cpp.h"
  5. #include <memory>
  6. #include <optional>
  7. #include <string>
  8. #include <tuple>
  9. #include <utility>
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/AST/RecordLayout.h"
  12. #include "clang/Basic/FileManager.h"
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Frontend/TextDiagnostic.h"
  17. #include "clang/Lex/PreprocessorOptions.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "common/check.h"
  20. #include "common/ostream.h"
  21. #include "common/raw_string_ostream.h"
  22. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "toolchain/base/kind_switch.h"
  26. #include "toolchain/check/class.h"
  27. #include "toolchain/check/context.h"
  28. #include "toolchain/check/convert.h"
  29. #include "toolchain/check/diagnostic_helpers.h"
  30. #include "toolchain/check/eval.h"
  31. #include "toolchain/check/function.h"
  32. #include "toolchain/check/import.h"
  33. #include "toolchain/check/inst.h"
  34. #include "toolchain/check/literal.h"
  35. #include "toolchain/check/pattern.h"
  36. #include "toolchain/check/pattern_match.h"
  37. #include "toolchain/check/type.h"
  38. #include "toolchain/diagnostics/diagnostic.h"
  39. #include "toolchain/diagnostics/diagnostic_emitter.h"
  40. #include "toolchain/diagnostics/format_providers.h"
  41. #include "toolchain/parse/node_ids.h"
  42. #include "toolchain/sem_ir/clang_decl.h"
  43. #include "toolchain/sem_ir/ids.h"
  44. #include "toolchain/sem_ir/inst.h"
  45. #include "toolchain/sem_ir/name_scope.h"
  46. #include "toolchain/sem_ir/typed_insts.h"
  47. namespace Carbon::Check {
  48. // Generates C++ file contents to #include all requested imports.
  49. static auto GenerateCppIncludesHeaderCode(
  50. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  51. -> std::string {
  52. std::string code;
  53. llvm::raw_string_ostream code_stream(code);
  54. for (const Parse::Tree::PackagingNames& import : imports) {
  55. // Add a line marker directive pointing at the location of the `import Cpp`
  56. // declaration in the Carbon source file. This will cause Clang's
  57. // diagnostics machinery to track and report the location in Carbon code
  58. // where the import was written.
  59. auto token = context.parse_tree().node_token(import.node_id);
  60. code_stream << "# " << context.tokens().GetLineNumber(token) << " \""
  61. << FormatEscaped(context.tokens().source().filename())
  62. << "\"\n";
  63. code_stream << "#include \""
  64. << FormatEscaped(
  65. context.string_literal_values().Get(import.library_id))
  66. << "\"\n";
  67. }
  68. return code;
  69. }
  70. // Adds the name to the scope with the given `inst_id`, if the `inst_id` is not
  71. // `None`.
  72. static auto AddNameToScope(Context& context, SemIR::NameScopeId scope_id,
  73. SemIR::NameId name_id, SemIR::InstId inst_id)
  74. -> void {
  75. if (inst_id.has_value()) {
  76. context.name_scopes().AddRequiredName(scope_id, name_id, inst_id);
  77. }
  78. }
  79. // Maps a Clang name to a Carbon `NameId`.
  80. static auto AddIdentifierName(Context& context, llvm::StringRef name)
  81. -> SemIR::NameId {
  82. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  83. }
  84. // Adds the given source location and an `ImportIRInst` referring to it in
  85. // `ImportIRId::Cpp`.
  86. static auto AddImportIRInst(Context& context,
  87. clang::SourceLocation clang_source_loc)
  88. -> SemIR::ImportIRInstId {
  89. SemIR::ClangSourceLocId clang_source_loc_id =
  90. context.sem_ir().clang_source_locs().Add(clang_source_loc);
  91. return context.import_ir_insts().Add(
  92. SemIR::ImportIRInst(clang_source_loc_id));
  93. }
  94. namespace {
  95. // Used to convert Clang diagnostics to Carbon diagnostics.
  96. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  97. public:
  98. // Creates an instance with the location that triggers calling Clang.
  99. // `context` must not be null.
  100. explicit CarbonClangDiagnosticConsumer(
  101. Context* context, std::shared_ptr<clang::CompilerInvocation> invocation)
  102. : context_(context), invocation_(std::move(invocation)) {}
  103. // Generates a Carbon warning for each Clang warning and a Carbon error for
  104. // each Clang error or fatal.
  105. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  106. const clang::Diagnostic& info) -> void override {
  107. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  108. SemIR::ImportIRInstId clang_import_ir_inst_id =
  109. AddImportIRInst(*context_, info.getLocation());
  110. llvm::SmallString<256> message;
  111. info.FormatDiagnostic(message);
  112. if (!info.hasSourceManager()) {
  113. // If we don't have a source manager, we haven't actually started
  114. // compiling yet, and this is an error from the driver or early in the
  115. // frontend. Pass it on directly.
  116. CARBON_CHECK(info.getLocation().isInvalid());
  117. diagnostic_infos_.push_back({.level = diag_level,
  118. .import_ir_inst_id = clang_import_ir_inst_id,
  119. .message = message.str().str()});
  120. return;
  121. }
  122. RawStringOstream diagnostics_stream;
  123. clang::TextDiagnostic text_diagnostic(diagnostics_stream,
  124. invocation_->getLangOpts(),
  125. invocation_->getDiagnosticOpts());
  126. text_diagnostic.emitDiagnostic(
  127. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  128. diag_level, message, info.getRanges(), info.getFixItHints());
  129. std::string diagnostics_str = diagnostics_stream.TakeStr();
  130. diagnostic_infos_.push_back({.level = diag_level,
  131. .import_ir_inst_id = clang_import_ir_inst_id,
  132. .message = diagnostics_str});
  133. }
  134. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  135. // be called after the AST is set in the context.
  136. auto EmitDiagnostics() -> void {
  137. for (const ClangDiagnosticInfo& info : diagnostic_infos_) {
  138. switch (info.level) {
  139. case clang::DiagnosticsEngine::Ignored:
  140. case clang::DiagnosticsEngine::Note:
  141. case clang::DiagnosticsEngine::Remark: {
  142. context_->TODO(
  143. SemIR::LocId(info.import_ir_inst_id),
  144. llvm::formatv(
  145. "Unsupported: C++ diagnostic level for diagnostic\n{0}",
  146. info.message));
  147. break;
  148. }
  149. case clang::DiagnosticsEngine::Warning:
  150. case clang::DiagnosticsEngine::Error:
  151. case clang::DiagnosticsEngine::Fatal: {
  152. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}",
  153. std::string);
  154. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  155. context_->emitter().Emit(
  156. SemIR::LocId(info.import_ir_inst_id),
  157. info.level == clang::DiagnosticsEngine::Warning
  158. ? CppInteropParseWarning
  159. : CppInteropParseError,
  160. info.message);
  161. break;
  162. }
  163. }
  164. }
  165. }
  166. private:
  167. // The type-checking context in which we're running Clang.
  168. Context* context_;
  169. // The compiler invocation that is producing the diagnostics.
  170. std::shared_ptr<clang::CompilerInvocation> invocation_;
  171. // Information on a Clang diagnostic that can be converted to a Carbon
  172. // diagnostic.
  173. struct ClangDiagnosticInfo {
  174. // The Clang diagnostic level.
  175. clang::DiagnosticsEngine::Level level;
  176. // The ID of the ImportIR instruction referring to the Clang source
  177. // location.
  178. SemIR::ImportIRInstId import_ir_inst_id;
  179. // The Clang diagnostic textual message.
  180. std::string message;
  181. };
  182. // Collects the information for all Clang diagnostics to be converted to
  183. // Carbon diagnostics after the context has been initialized with the Clang
  184. // AST.
  185. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  186. };
  187. } // namespace
  188. // Returns an AST for the C++ imports and a bool that represents whether
  189. // compilation errors where encountered or the generated AST is null due to an
  190. // error. Sets the AST in the context's `sem_ir`.
  191. // TODO: Consider to always have a (non-null) AST.
  192. static auto GenerateAst(Context& context,
  193. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  194. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  195. std::shared_ptr<clang::CompilerInvocation> invocation)
  196. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  197. // Build a diagnostics engine.
  198. auto diagnostics_consumer =
  199. std::make_unique<CarbonClangDiagnosticConsumer>(&context, invocation);
  200. llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diags(
  201. clang::CompilerInstance::createDiagnostics(
  202. *fs, invocation->getDiagnosticOpts(), diagnostics_consumer.get(),
  203. /*ShouldOwnClient=*/false));
  204. // Extract the input from the frontend invocation and make sure it makes
  205. // sense.
  206. const auto& inputs = invocation->getFrontendOpts().Inputs;
  207. CARBON_CHECK(inputs.size() == 1 &&
  208. inputs[0].getKind().getLanguage() == clang::Language::CXX &&
  209. inputs[0].getKind().getFormat() == clang::InputKind::Source);
  210. llvm::StringRef file_name = inputs[0].getFile();
  211. // Remap the imports file name to the corresponding `#include`s.
  212. // TODO: Modify the frontend options to specify this memory buffer as input
  213. // instead of remapping the file.
  214. std::string includes = GenerateCppIncludesHeaderCode(context, imports);
  215. auto includes_buffer = llvm::MemoryBuffer::getMemBuffer(includes, file_name);
  216. invocation->getPreprocessorOpts().addRemappedFile(file_name,
  217. includes_buffer.get());
  218. // Create the AST unit.
  219. auto ast = clang::ASTUnit::LoadFromCompilerInvocation(
  220. invocation, std::make_shared<clang::PCHContainerOperations>(), nullptr,
  221. diags, new clang::FileManager(invocation->getFileSystemOpts(), fs));
  222. // Remove remapped file before its underlying storage is destroyed.
  223. invocation->getPreprocessorOpts().clearRemappedFiles();
  224. // Attach the AST to SemIR. This needs to be done before we can emit any
  225. // diagnostics, so their locations can be properly interpreted by our
  226. // diagnostics machinery.
  227. context.sem_ir().set_cpp_ast(ast.get());
  228. // Emit any diagnostics we queued up while building the AST.
  229. diagnostics_consumer->EmitDiagnostics();
  230. bool any_errors = diagnostics_consumer->getNumErrors() > 0;
  231. // Transfer ownership of the consumer to the AST unit, in case more
  232. // diagnostics are produced by AST queries.
  233. ast->getDiagnostics().setClient(diagnostics_consumer.release(),
  234. /*ShouldOwnClient=*/true);
  235. return {std::move(ast), !ast || any_errors};
  236. }
  237. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  238. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  239. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  240. -> SemIR::NameScopeId {
  241. auto& import_cpps = context.sem_ir().import_cpps();
  242. import_cpps.Reserve(imports.size());
  243. for (const Parse::Tree::PackagingNames& import : imports) {
  244. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  245. import.node_id),
  246. .library_id = import.library_id});
  247. }
  248. return AddImportNamespaceToScope(
  249. context,
  250. GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  251. SemIR::NameId::ForPackageName(cpp_package_id),
  252. SemIR::NameScopeId::Package,
  253. /*diagnose_duplicate_namespace=*/false,
  254. [&]() {
  255. return AddInst<SemIR::ImportCppDecl>(
  256. context,
  257. context.parse_tree().As<Parse::ImportDeclId>(
  258. imports.front().node_id),
  259. {});
  260. })
  261. .add_result.name_scope_id;
  262. }
  263. auto ImportCppFiles(Context& context,
  264. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  265. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  266. std::shared_ptr<clang::CompilerInvocation> invocation)
  267. -> std::unique_ptr<clang::ASTUnit> {
  268. if (imports.empty()) {
  269. return nullptr;
  270. }
  271. CARBON_CHECK(!context.sem_ir().cpp_ast());
  272. PackageNameId package_id = imports.front().package_id;
  273. CARBON_CHECK(
  274. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  275. return import.package_id == package_id;
  276. }));
  277. auto name_scope_id = AddNamespace(context, package_id, imports);
  278. auto [generated_ast, ast_has_error] =
  279. GenerateAst(context, imports, fs, std::move(invocation));
  280. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  281. name_scope.set_is_closed_import(true);
  282. name_scope.set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  283. {.decl = generated_ast->getASTContext().getTranslationUnitDecl(),
  284. .inst_id = name_scope.inst_id()}));
  285. if (ast_has_error) {
  286. name_scope.set_has_error();
  287. }
  288. return std::move(generated_ast);
  289. }
  290. // Look ups the given name in the Clang AST in a specific scope. Returns the
  291. // lookup result if lookup was successful.
  292. static auto ClangLookup(Context& context, SemIR::NameScopeId scope_id,
  293. SemIR::NameId name_id)
  294. -> std::optional<clang::LookupResult> {
  295. std::optional<llvm::StringRef> name =
  296. context.names().GetAsStringIfIdentifier(name_id);
  297. if (!name) {
  298. // Special names never exist in C++ code.
  299. return std::nullopt;
  300. }
  301. clang::ASTUnit* ast = context.sem_ir().cpp_ast();
  302. CARBON_CHECK(ast);
  303. clang::Sema& sema = ast->getSema();
  304. clang::LookupResult lookup(
  305. sema,
  306. clang::DeclarationNameInfo(
  307. clang::DeclarationName(
  308. sema.getPreprocessor().getIdentifierInfo(*name)),
  309. clang::SourceLocation()),
  310. clang::Sema::LookupNameKind::LookupOrdinaryName);
  311. // TODO: Diagnose on access and return the `AccessKind` for storage. We'll
  312. // probably need a dedicated `DiagnosticConsumer` because
  313. // `TextDiagnosticPrinter` assumes we're processing a C++ source file.
  314. lookup.suppressDiagnostics();
  315. auto scope_clang_decl_context_id =
  316. context.name_scopes().Get(scope_id).clang_decl_context_id();
  317. bool found = sema.LookupQualifiedName(
  318. lookup,
  319. clang::dyn_cast<clang::DeclContext>(context.sem_ir()
  320. .clang_decls()
  321. .Get(scope_clang_decl_context_id)
  322. .decl));
  323. if (!found) {
  324. return std::nullopt;
  325. }
  326. return lookup;
  327. }
  328. // Returns whether `decl` already mapped to an instruction.
  329. static auto IsClangDeclImported(const Context& context, clang::Decl* decl)
  330. -> bool {
  331. return context.sem_ir()
  332. .clang_decls()
  333. .Lookup(decl->getCanonicalDecl())
  334. .has_value();
  335. }
  336. // If `decl` already mapped to an instruction, returns that instruction.
  337. // Otherwise returns `None`.
  338. static auto LookupClangDeclInstId(const Context& context, clang::Decl* decl)
  339. -> SemIR::InstId {
  340. const auto& clang_decls = context.sem_ir().clang_decls();
  341. if (auto context_clang_decl_id = clang_decls.Lookup(decl->getCanonicalDecl());
  342. context_clang_decl_id.has_value()) {
  343. return clang_decls.Get(context_clang_decl_id).inst_id;
  344. }
  345. return SemIR::InstId::None;
  346. }
  347. // Returns the parent of the given declaration. Skips declaration types we
  348. // ignore.
  349. static auto GetParentDecl(clang::Decl* clang_decl) -> clang::Decl* {
  350. clang::DeclContext* decl_context = clang_decl->getDeclContext();
  351. while (llvm::isa<clang::LinkageSpecDecl>(decl_context)) {
  352. decl_context = decl_context->getParent();
  353. }
  354. return llvm::cast<clang::Decl>(decl_context);
  355. }
  356. // Returns the given declaration's parent scope. Assumes the parent declaration
  357. // was already imported.
  358. static auto GetParentNameScopeId(Context& context, clang::Decl* clang_decl)
  359. -> SemIR::NameScopeId {
  360. SemIR::InstId parent_inst_id =
  361. LookupClangDeclInstId(context, GetParentDecl(clang_decl));
  362. CARBON_CHECK(parent_inst_id.has_value());
  363. CARBON_KIND_SWITCH(context.insts().Get(parent_inst_id)) {
  364. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  365. return context.classes().Get(class_decl.class_id).scope_id;
  366. }
  367. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  368. return context.interfaces().Get(interface_decl.interface_id).scope_id;
  369. }
  370. case CARBON_KIND(SemIR::Namespace namespace_inst): {
  371. return namespace_inst.name_scope_id;
  372. }
  373. default: {
  374. CARBON_FATAL("Unexpected parent instruction kind");
  375. }
  376. }
  377. }
  378. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  379. // the new Carbon namespace declaration `InstId`. If the declaration was already
  380. // imported, returns the mapped instruction.
  381. static auto ImportNamespaceDecl(Context& context,
  382. clang::NamespaceDecl* clang_decl)
  383. -> SemIR::InstId {
  384. // Check if the declaration is already mapped.
  385. if (SemIR::InstId existing_inst_id =
  386. LookupClangDeclInstId(context, clang_decl);
  387. existing_inst_id.has_value()) {
  388. return existing_inst_id;
  389. }
  390. auto result = AddImportNamespace(
  391. context, GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  392. AddIdentifierName(context, clang_decl->getName()),
  393. GetParentNameScopeId(context, clang_decl),
  394. /*import_id=*/SemIR::InstId::None);
  395. context.name_scopes()
  396. .Get(result.name_scope_id)
  397. .set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  398. {.decl = clang_decl->getCanonicalDecl(), .inst_id = result.inst_id}));
  399. return result.inst_id;
  400. }
  401. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  402. -> TypeExpr;
  403. // Creates a class declaration for the given class name in the given scope.
  404. // Returns the `InstId` for the declaration.
  405. static auto BuildClassDecl(Context& context,
  406. SemIR::ImportIRInstId import_ir_inst_id,
  407. SemIR::NameScopeId parent_scope_id,
  408. SemIR::NameId name_id)
  409. -> std::tuple<SemIR::ClassId, SemIR::TypeInstId> {
  410. // Add the class declaration.
  411. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeType::TypeId,
  412. .class_id = SemIR::ClassId::None,
  413. .decl_block_id = SemIR::InstBlockId::None};
  414. auto class_decl_id = AddPlaceholderInstInNoBlock(
  415. context,
  416. SemIR::LocIdAndInst::UncheckedLoc(import_ir_inst_id, class_decl));
  417. context.imports().push_back(class_decl_id);
  418. SemIR::Class class_info = {
  419. {.name_id = name_id,
  420. .parent_scope_id = parent_scope_id,
  421. .generic_id = SemIR::GenericId::None,
  422. .first_param_node_id = Parse::NodeId::None,
  423. .last_param_node_id = Parse::NodeId::None,
  424. .pattern_block_id = SemIR::InstBlockId::None,
  425. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  426. .param_patterns_id = SemIR::InstBlockId::None,
  427. .is_extern = false,
  428. .extern_library_id = SemIR::LibraryNameId::None,
  429. .non_owning_decl_id = SemIR::InstId::None,
  430. .first_owning_decl_id = class_decl_id},
  431. {// `.self_type_id` depends on the ClassType, so is set below.
  432. .self_type_id = SemIR::TypeId::None,
  433. // TODO: Support Dynamic classes.
  434. // TODO: Support Final classes.
  435. .inheritance_kind = SemIR::Class::Base}};
  436. class_decl.class_id = context.classes().Add(class_info);
  437. // Write the class ID into the ClassDecl.
  438. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  439. SetClassSelfType(context, class_decl.class_id);
  440. return {class_decl.class_id, context.types().GetAsTypeInstId(class_decl_id)};
  441. }
  442. // Checks that the specified finished class definition is valid and builds and
  443. // returns a corresponding complete type witness instruction.
  444. // TODO: Remove recursion into mapping field types.
  445. // NOLINTNEXTLINE(misc-no-recursion)
  446. static auto ImportClassObjectRepr(Context& context,
  447. SemIR::ImportIRInstId import_ir_inst_id,
  448. SemIR::TypeInstId class_type_inst_id,
  449. const clang::CXXRecordDecl* clang_def)
  450. -> SemIR::TypeInstId {
  451. // For now, if the class is empty, produce an empty struct as the object
  452. // representation. This allows our tests to continue to pass while we don't
  453. // properly support initializing imported C++ classes.
  454. // TODO: Remove this.
  455. if (clang_def->isEmpty()) {
  456. return context.types().GetAsTypeInstId(AddInst(
  457. context,
  458. MakeImportedLocIdAndInst(
  459. context, import_ir_inst_id,
  460. SemIR::StructType{.type_id = SemIR::TypeType::TypeId,
  461. .fields_id = SemIR::StructTypeFieldsId::Empty})));
  462. }
  463. const auto& clang_layout =
  464. context.ast_context().getASTRecordLayout(clang_def);
  465. llvm::SmallVector<uint64_t> layout;
  466. llvm::SmallVector<SemIR::StructTypeField> fields;
  467. static_assert(SemIR::CustomLayoutId::SizeIndex == 0);
  468. layout.push_back(clang_layout.getSize().getQuantity());
  469. static_assert(SemIR::CustomLayoutId::AlignIndex == 1);
  470. layout.push_back(clang_layout.getAlignment().getQuantity());
  471. static_assert(SemIR::CustomLayoutId::FirstFieldIndex == 2);
  472. // TODO: Import vptr(s).
  473. // TODO: Import bases.
  474. // Import fields.
  475. for (auto* field : clang_def->fields()) {
  476. if (field->isBitField()) {
  477. // TODO: Add a representation for named bitfield members.
  478. continue;
  479. }
  480. if (field->isAnonymousStructOrUnion()) {
  481. // TODO: Visit IndirectFieldDecls and add them to the layout.
  482. continue;
  483. }
  484. auto field_name_id = AddIdentifierName(context, field->getName());
  485. auto [field_type_inst_id, field_type_id] =
  486. MapType(context, import_ir_inst_id, field->getType());
  487. // Create a field now, as we know the index to use.
  488. // TODO: Consider doing this lazily instead.
  489. auto field_decl_id = AddInst(
  490. context, MakeImportedLocIdAndInst(
  491. context, import_ir_inst_id,
  492. SemIR::FieldDecl{
  493. .type_id = GetUnboundElementType(
  494. context, class_type_inst_id, field_type_inst_id),
  495. .name_id = field_name_id,
  496. .index = SemIR::ElementIndex(fields.size())}));
  497. context.sem_ir().clang_decls().Add(
  498. {.decl = field->getCanonicalDecl(), .inst_id = field_decl_id});
  499. layout.push_back(context.ast_context()
  500. .toCharUnitsFromBits(clang_layout.getFieldOffset(
  501. field->getFieldIndex()))
  502. .getQuantity());
  503. fields.push_back(
  504. {.name_id = field_name_id, .type_inst_id = field_type_inst_id});
  505. }
  506. // TODO: Add a field to prevent tail padding reuse if necessary.
  507. return AddTypeInst<SemIR::CustomLayoutType>(
  508. context, import_ir_inst_id,
  509. {.type_id = SemIR::TypeType::TypeId,
  510. .fields_id = context.struct_type_fields().Add(fields),
  511. .layout_id = context.custom_layouts().Add(layout)});
  512. }
  513. // Creates a class definition based on the information in the given Clang
  514. // declaration, which is assumed to be for a class definition.
  515. // TODO: Remove recursion into mapping field types.
  516. // NOLINTNEXTLINE(misc-no-recursion)
  517. static auto BuildClassDefinition(Context& context,
  518. SemIR::ImportIRInstId import_ir_inst_id,
  519. SemIR::ClassId class_id,
  520. SemIR::TypeInstId class_inst_id,
  521. SemIR::ClangDeclId clang_decl_id,
  522. clang::CXXRecordDecl* clang_def) -> void {
  523. auto& class_info = context.classes().Get(class_id);
  524. StartClassDefinition(context, class_info, class_inst_id);
  525. // Name lookup into the Carbon class looks in the C++ class definition.
  526. context.name_scopes()
  527. .Get(class_info.scope_id)
  528. .set_clang_decl_context_id(clang_decl_id);
  529. context.inst_block_stack().Push();
  530. // Compute the class's object representation.
  531. auto object_repr_id = ImportClassObjectRepr(context, import_ir_inst_id,
  532. class_inst_id, clang_def);
  533. class_info.complete_type_witness_id = AddInst<SemIR::CompleteTypeWitness>(
  534. context, import_ir_inst_id,
  535. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  536. .object_repr_type_inst_id = object_repr_id});
  537. class_info.body_block_id = context.inst_block_stack().Pop();
  538. }
  539. // Mark the given `Decl` as failed in `clang_decls`.
  540. static auto MarkFailedDecl(Context& context, clang::Decl* clang_decl) {
  541. context.sem_ir().clang_decls().Add({.decl = clang_decl->getCanonicalDecl(),
  542. .inst_id = SemIR::ErrorInst::InstId});
  543. }
  544. // Imports a record declaration from Clang to Carbon. If successful, returns
  545. // the new Carbon class declaration `InstId`.
  546. // TODO: Change `clang_decl` to `const &` when lookup is using `clang::DeclID`
  547. // and we don't need to store the decl for lookup context.
  548. // TODO: Remove recursion into mapping field types.
  549. // NOLINTNEXTLINE(misc-no-recursion)
  550. static auto ImportCXXRecordDecl(Context& context,
  551. clang::CXXRecordDecl* clang_decl)
  552. -> SemIR::InstId {
  553. clang::CXXRecordDecl* clang_def = clang_decl->getDefinition();
  554. if (clang_def) {
  555. clang_decl = clang_def;
  556. }
  557. auto import_ir_inst_id = AddImportIRInst(context, clang_decl->getLocation());
  558. auto [class_id, class_inst_id] = BuildClassDecl(
  559. context, import_ir_inst_id, GetParentNameScopeId(context, clang_decl),
  560. AddIdentifierName(context, clang_decl->getName()));
  561. // TODO: The caller does the same lookup. Avoid doing it twice.
  562. auto clang_decl_id = context.sem_ir().clang_decls().Add(
  563. {.decl = clang_decl->getCanonicalDecl(), .inst_id = class_inst_id});
  564. if (clang_def) {
  565. BuildClassDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  566. clang_decl_id, clang_def);
  567. }
  568. return class_inst_id;
  569. }
  570. // Creates an integer type of the given size.
  571. static auto MakeIntType(Context& context, IntId size_id, bool is_signed)
  572. -> TypeExpr {
  573. auto type_inst_id = MakeIntTypeLiteral(
  574. context, Parse::NodeId::None,
  575. is_signed ? SemIR::IntKind::Signed : SemIR::IntKind::Unsigned, size_id);
  576. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  577. }
  578. // Maps a C++ builtin type to a Carbon type.
  579. // TODO: Support more builtin types.
  580. static auto MapBuiltinType(Context& context, clang::QualType qual_type,
  581. const clang::BuiltinType& type) -> TypeExpr {
  582. if (type.isInteger()) {
  583. auto width = context.ast_context().getIntWidth(qual_type);
  584. bool is_signed = type.isSignedInteger();
  585. auto int_n_type =
  586. context.ast_context().getIntTypeForBitwidth(width, is_signed);
  587. if (context.ast_context().hasSameType(qual_type, int_n_type)) {
  588. return MakeIntType(context, context.ints().Add(width), is_signed);
  589. }
  590. // TODO: Handle integer types that map to named aliases.
  591. }
  592. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  593. }
  594. // Maps a C++ record type to a Carbon type.
  595. // TODO: Support more record types.
  596. // TODO: Remove recursion mapping fields of class types.
  597. // NOLINTNEXTLINE(misc-no-recursion)
  598. static auto MapRecordType(Context& context, const clang::RecordType& type)
  599. -> TypeExpr {
  600. auto* record_decl = clang::dyn_cast<clang::CXXRecordDecl>(type.getDecl());
  601. if (!record_decl) {
  602. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  603. }
  604. // Check if the declaration is already mapped.
  605. SemIR::InstId record_inst_id = LookupClangDeclInstId(context, record_decl);
  606. if (!record_inst_id.has_value()) {
  607. record_inst_id = ImportCXXRecordDecl(context, record_decl);
  608. }
  609. SemIR::TypeInstId record_type_inst_id =
  610. context.types().GetAsTypeInstId(record_inst_id);
  611. return {
  612. .inst_id = record_type_inst_id,
  613. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  614. }
  615. // Maps a C++ type that is not a wrapper type such as a pointer to a Carbon
  616. // type.
  617. // TODO: Support more types.
  618. // TODO: Remove recursion mapping fields of class types.
  619. // NOLINTNEXTLINE(misc-no-recursion)
  620. static auto MapNonWrapperType(Context& context, clang::QualType type)
  621. -> TypeExpr {
  622. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  623. return MapBuiltinType(context, type, *builtin_type);
  624. }
  625. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  626. return MapRecordType(context, *record_type);
  627. }
  628. CARBON_CHECK(!type.hasQualifiers() && !type->isPointerType(),
  629. "Should not see wrapper types here");
  630. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  631. }
  632. // Maps a qualified C++ type to a Carbon type.
  633. static auto MapQualifiedType(Context& context, SemIR::LocId loc_id,
  634. clang::QualType type, TypeExpr type_expr)
  635. -> TypeExpr {
  636. auto quals = type.getQualifiers();
  637. if (quals.hasConst()) {
  638. auto type_id = GetConstType(context, type_expr.inst_id);
  639. type_expr = {.inst_id = context.types().GetInstId(type_id),
  640. .type_id = type_id};
  641. quals.removeConst();
  642. }
  643. // TODO: Support other qualifiers.
  644. if (!quals.empty()) {
  645. context.TODO(loc_id, llvm::formatv("Unsupported: qualified type: {0}",
  646. type.getAsString()));
  647. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  648. .type_id = SemIR::ErrorInst::TypeId};
  649. }
  650. return type_expr;
  651. }
  652. // Maps a C++ pointer type to a Carbon pointer type.
  653. static auto MapPointerType(Context& context, SemIR::LocId loc_id,
  654. clang::QualType type, TypeExpr pointee_type_expr)
  655. -> TypeExpr {
  656. CARBON_CHECK(type->isPointerType());
  657. if (auto nullability = type->getNullability();
  658. !nullability.has_value() ||
  659. *nullability != clang::NullabilityKind::NonNull) {
  660. context.TODO(loc_id, llvm::formatv("Unsupported: nullable pointer: {0}",
  661. type.getAsString()));
  662. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  663. .type_id = SemIR::ErrorInst::TypeId};
  664. }
  665. SemIR::TypeId pointer_type_id =
  666. GetPointerType(context, pointee_type_expr.inst_id);
  667. return {.inst_id = context.types().GetInstId(pointer_type_id),
  668. .type_id = pointer_type_id};
  669. }
  670. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  671. // we check for pointer nullability and nullability will be lost by
  672. // canonicalization.
  673. // TODO: Remove recursion mapping fields of class types.
  674. // NOLINTNEXTLINE(misc-no-recursion)
  675. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  676. -> TypeExpr {
  677. // Unwrap any type modifiers and wrappers.
  678. llvm::SmallVector<clang::QualType> wrapper_types;
  679. while (true) {
  680. clang::QualType orig_type = type;
  681. if (type.hasQualifiers()) {
  682. type = type.getUnqualifiedType();
  683. } else if (type->isPointerType()) {
  684. type = type->getPointeeType();
  685. } else {
  686. break;
  687. }
  688. wrapper_types.push_back(orig_type);
  689. }
  690. auto mapped = MapNonWrapperType(context, type);
  691. for (auto wrapper : llvm::reverse(wrapper_types)) {
  692. if (!mapped.inst_id.has_value() ||
  693. mapped.type_id == SemIR::ErrorInst::TypeId) {
  694. break;
  695. }
  696. if (wrapper.hasQualifiers()) {
  697. mapped = MapQualifiedType(context, loc_id, wrapper, mapped);
  698. } else if (wrapper->isPointerType()) {
  699. mapped = MapPointerType(context, loc_id, wrapper, mapped);
  700. } else {
  701. CARBON_FATAL("Unexpected wrapper type {0}", wrapper.getAsString());
  702. }
  703. }
  704. return mapped;
  705. }
  706. // Returns a block for the implicit parameters of the given function
  707. // declaration. Because function templates are not yet supported, this currently
  708. // only contains the `self` parameter. On error, produces a diagnostic and
  709. // returns None.
  710. static auto MakeImplicitParamPatternsBlockId(
  711. Context& context, SemIR::LocId loc_id,
  712. const clang::FunctionDecl& clang_decl) -> SemIR::InstBlockId {
  713. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(&clang_decl);
  714. if (!method_decl || method_decl->isStatic()) {
  715. return SemIR::InstBlockId::Empty;
  716. }
  717. // Build a `self` parameter from the object parameter.
  718. BeginSubpattern(context);
  719. // Perform some special-case mapping for the object parameter:
  720. //
  721. // - If it's a const reference to T, produce a by-value `self: T` parameter.
  722. // - If it's a non-const reference to T, produce an `addr self: T*`
  723. // parameter.
  724. // - Otherwise, map it directly, which will currently fail for `&&`-qualified
  725. // methods.
  726. //
  727. // TODO: Some of this mapping should be performed for all parameters.
  728. clang::QualType param_type =
  729. method_decl->getFunctionObjectParameterReferenceType();
  730. bool addr_self = false;
  731. if (param_type->isLValueReferenceType()) {
  732. param_type = param_type.getNonReferenceType();
  733. if (param_type.isConstQualified()) {
  734. // TODO: Consider only doing this if `const` is the only qualifier. For
  735. // now, any other qualifier will fail when mapping the type.
  736. auto split_type = param_type.getSplitUnqualifiedType();
  737. split_type.Quals.removeConst();
  738. param_type = method_decl->getASTContext().getQualifiedType(split_type);
  739. } else {
  740. addr_self = true;
  741. }
  742. }
  743. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  744. SemIR::ExprRegionId type_expr_region_id =
  745. EndSubpatternAsExpr(context, type_inst_id);
  746. if (!type_id.has_value()) {
  747. context.TODO(loc_id,
  748. llvm::formatv("Unsupported: object parameter type: {0}",
  749. param_type.getAsString()));
  750. return SemIR::InstBlockId::None;
  751. }
  752. if (addr_self) {
  753. type_id = GetPointerType(context, type_inst_id);
  754. }
  755. SemIR::InstId pattern_id =
  756. // TODO: Fill in a location once available.
  757. AddBindingPattern(context, SemIR::LocId::None, SemIR::NameId::SelfValue,
  758. type_id, type_expr_region_id, /*is_generic*/ false,
  759. /*is_template*/ false)
  760. .pattern_id;
  761. // TODO: Fill in a location once available.
  762. pattern_id = AddPatternInst<SemIR::ValueParamPattern>(
  763. context, SemIR::LocId::None,
  764. {.type_id = context.insts().Get(pattern_id).type_id(),
  765. .subpattern_id = pattern_id,
  766. .index = SemIR::CallParamIndex::None});
  767. // If we're building `addr self: Self*`, do that now.
  768. if (addr_self) {
  769. // TODO: Fill in a location once available.
  770. pattern_id = AddPatternInst<SemIR::AddrPattern>(
  771. context, SemIR::LocId::None,
  772. {.type_id = GetPatternType(context, SemIR::AutoType::TypeId),
  773. .inner_id = pattern_id});
  774. }
  775. return context.inst_blocks().Add({pattern_id});
  776. }
  777. // Returns a block id for the explicit parameters of the given function
  778. // declaration. If the function declaration has no parameters, it returns
  779. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  780. // produces an error and returns `SemIR::InstBlockId::None`.
  781. // TODO: Consider refactoring to extract and reuse more logic from
  782. // `HandleAnyBindingPattern()`.
  783. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  784. const clang::FunctionDecl& clang_decl)
  785. -> SemIR::InstBlockId {
  786. if (clang_decl.parameters().empty()) {
  787. return SemIR::InstBlockId::Empty;
  788. }
  789. llvm::SmallVector<SemIR::InstId> params;
  790. params.reserve(clang_decl.parameters().size());
  791. for (const clang::ParmVarDecl* param : clang_decl.parameters()) {
  792. // TODO: Get the parameter type from the function, not from the
  793. // `ParmVarDecl`. The type of the `ParmVarDecl` is the type within the
  794. // function, and isn't in general the same as the type that's exposed to
  795. // callers. In particular, the parameter type exposed to callers will never
  796. // be cv-qualified.
  797. clang::QualType param_type = param->getType();
  798. // Mark the start of a region of insts, needed for the type expression
  799. // created later with the call of `EndSubpatternAsExpr()`.
  800. BeginSubpattern(context);
  801. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  802. // Type expression of the binding pattern - a single-entry/single-exit
  803. // region that allows control flow in the type expression e.g. fn F(x: if C
  804. // then i32 else i64).
  805. SemIR::ExprRegionId type_expr_region_id =
  806. EndSubpatternAsExpr(context, type_inst_id);
  807. if (!type_id.has_value()) {
  808. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  809. param_type.getAsString()));
  810. return SemIR::InstBlockId::None;
  811. }
  812. llvm::StringRef param_name = param->getName();
  813. SemIR::NameId name_id =
  814. param_name.empty()
  815. // Translate an unnamed parameter to an underscore to
  816. // match Carbon's naming of unnamed/unused function params.
  817. ? SemIR::NameId::Underscore
  818. : AddIdentifierName(context, param_name);
  819. // TODO: Fix this once templates are supported.
  820. bool is_template = false;
  821. // TODO: Fix this once generics are supported.
  822. bool is_generic = false;
  823. SemIR::InstId binding_pattern_id =
  824. // TODO: Fill in a location once available.
  825. AddBindingPattern(context, SemIR::LocId::None, name_id, type_id,
  826. type_expr_region_id, is_generic, is_template)
  827. .pattern_id;
  828. SemIR::InstId var_pattern_id = AddPatternInst(
  829. context,
  830. // TODO: Fill in a location once available.
  831. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  832. {.type_id = context.insts().Get(binding_pattern_id).type_id(),
  833. .subpattern_id = binding_pattern_id,
  834. .index = SemIR::CallParamIndex::None})));
  835. params.push_back(var_pattern_id);
  836. }
  837. return context.inst_blocks().Add(params);
  838. }
  839. // Returns the return type of the given function declaration. In case of an
  840. // unsupported return type, it produces a diagnostic and returns
  841. // `SemIR::ErrorInst::InstId`.
  842. // TODO: Support more return types.
  843. static auto GetReturnType(Context& context, SemIR::LocId loc_id,
  844. const clang::FunctionDecl* clang_decl)
  845. -> SemIR::InstId {
  846. clang::QualType ret_type = clang_decl->getReturnType();
  847. if (ret_type->isVoidType()) {
  848. return SemIR::InstId::None;
  849. }
  850. auto [type_inst_id, type_id] = MapType(context, loc_id, ret_type);
  851. if (!type_inst_id.has_value()) {
  852. context.TODO(loc_id, llvm::formatv("Unsupported: return type: {0}",
  853. ret_type.getAsString()));
  854. return SemIR::ErrorInst::InstId;
  855. }
  856. auto pattern_type_id = GetPatternType(context, type_id);
  857. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  858. // TODO: Fill in a location for the return type once available.
  859. context,
  860. SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  861. {.type_id = pattern_type_id, .type_inst_id = type_inst_id})));
  862. SemIR::InstId param_pattern_id = AddPatternInst(
  863. // TODO: Fill in a location for the return type once available.
  864. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  865. {.type_id = pattern_type_id,
  866. .subpattern_id = return_slot_pattern_id,
  867. .index = SemIR::CallParamIndex::None})));
  868. return param_pattern_id;
  869. }
  870. namespace {
  871. // Represents the parameter patterns block id, the return slot pattern id and
  872. // the call parameters block id for a function declaration.
  873. struct FunctionParamsInsts {
  874. SemIR::InstBlockId implicit_param_patterns_id;
  875. SemIR::InstBlockId param_patterns_id;
  876. SemIR::InstId return_slot_pattern_id;
  877. SemIR::InstBlockId call_params_id;
  878. };
  879. } // namespace
  880. // Creates a block containing the parameter pattern instructions for the
  881. // explicit parameters, a parameter pattern instruction for the return type and
  882. // a block containing the call parameters of the function. Emits a callee
  883. // pattern-match for the explicit parameter patterns and the return slot pattern
  884. // to create the Call parameters instructions block. Currently the implicit
  885. // parameter patterns are not taken into account. Returns the parameter patterns
  886. // block id, the return slot pattern id, and the call parameters block id.
  887. // Produces a diagnostic and returns `std::nullopt` if the function declaration
  888. // has an unsupported parameter type.
  889. static auto CreateFunctionParamsInsts(Context& context, SemIR::LocId loc_id,
  890. const clang::FunctionDecl* clang_decl)
  891. -> std::optional<FunctionParamsInsts> {
  892. if (isa<clang::CXXConstructorDecl, clang::CXXDestructorDecl>(clang_decl)) {
  893. context.TODO(loc_id, "Unsupported: Constructor/Destructor");
  894. return std::nullopt;
  895. }
  896. auto implicit_param_patterns_id =
  897. MakeImplicitParamPatternsBlockId(context, loc_id, *clang_decl);
  898. if (!implicit_param_patterns_id.has_value()) {
  899. return std::nullopt;
  900. }
  901. auto param_patterns_id =
  902. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  903. if (!param_patterns_id.has_value()) {
  904. return std::nullopt;
  905. }
  906. auto return_slot_pattern_id = GetReturnType(context, loc_id, clang_decl);
  907. if (SemIR::ErrorInst::InstId == return_slot_pattern_id) {
  908. return std::nullopt;
  909. }
  910. auto call_params_id =
  911. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  912. return_slot_pattern_id);
  913. return {{.implicit_param_patterns_id = implicit_param_patterns_id,
  914. .param_patterns_id = param_patterns_id,
  915. .return_slot_pattern_id = return_slot_pattern_id,
  916. .call_params_id = call_params_id}};
  917. }
  918. // Imports a function declaration from Clang to Carbon. If successful, returns
  919. // the new Carbon function declaration `InstId`. If the declaration was already
  920. // imported, returns the mapped instruction.
  921. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  922. clang::FunctionDecl* clang_decl)
  923. -> SemIR::InstId {
  924. // Check if the declaration is already mapped.
  925. if (SemIR::InstId existing_inst_id =
  926. LookupClangDeclInstId(context, clang_decl);
  927. existing_inst_id.has_value()) {
  928. return existing_inst_id;
  929. }
  930. if (clang_decl->isVariadic()) {
  931. context.TODO(loc_id, "Unsupported: Variadic function");
  932. MarkFailedDecl(context, clang_decl);
  933. return SemIR::ErrorInst::InstId;
  934. }
  935. if (clang_decl->getTemplatedKind() ==
  936. clang::FunctionDecl::TK_FunctionTemplate) {
  937. context.TODO(loc_id, "Unsupported: Template function");
  938. MarkFailedDecl(context, clang_decl);
  939. return SemIR::ErrorInst::InstId;
  940. }
  941. if (auto* method_decl = dyn_cast<clang::CXXMethodDecl>(clang_decl)) {
  942. if (method_decl->isVirtual()) {
  943. context.TODO(loc_id, "Unsupported: Virtual function");
  944. MarkFailedDecl(context, clang_decl);
  945. return SemIR::ErrorInst::InstId;
  946. }
  947. }
  948. context.scope_stack().PushForDeclName();
  949. context.inst_block_stack().Push();
  950. context.pattern_block_stack().Push();
  951. auto function_params_insts =
  952. CreateFunctionParamsInsts(context, loc_id, clang_decl);
  953. auto pattern_block_id = context.pattern_block_stack().Pop();
  954. auto decl_block_id = context.inst_block_stack().Pop();
  955. context.scope_stack().Pop();
  956. if (!function_params_insts.has_value()) {
  957. MarkFailedDecl(context, clang_decl);
  958. return SemIR::ErrorInst::InstId;
  959. }
  960. auto function_decl = SemIR::FunctionDecl{
  961. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  962. auto decl_id =
  963. AddPlaceholderInstInNoBlock(context, Parse::NodeId::None, function_decl);
  964. context.imports().push_back(decl_id);
  965. auto function_info = SemIR::Function{
  966. {.name_id = AddIdentifierName(context, clang_decl->getName()),
  967. .parent_scope_id = GetParentNameScopeId(context, clang_decl),
  968. .generic_id = SemIR::GenericId::None,
  969. .first_param_node_id = Parse::NodeId::None,
  970. .last_param_node_id = Parse::NodeId::None,
  971. .pattern_block_id = pattern_block_id,
  972. .implicit_param_patterns_id =
  973. function_params_insts->implicit_param_patterns_id,
  974. .param_patterns_id = function_params_insts->param_patterns_id,
  975. .is_extern = false,
  976. .extern_library_id = SemIR::LibraryNameId::None,
  977. .non_owning_decl_id = SemIR::InstId::None,
  978. .first_owning_decl_id = decl_id,
  979. .definition_id = SemIR::InstId::None},
  980. {.call_params_id = function_params_insts->call_params_id,
  981. .return_slot_pattern_id = function_params_insts->return_slot_pattern_id,
  982. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  983. .self_param_id = FindSelfPattern(
  984. context, function_params_insts->implicit_param_patterns_id),
  985. .clang_decl_id = context.sem_ir().clang_decls().Add(
  986. {.decl = clang_decl, .inst_id = decl_id})}};
  987. function_decl.function_id = context.functions().Add(function_info);
  988. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  989. SemIR::SpecificId::None);
  990. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  991. return decl_id;
  992. }
  993. // Returns all decls that need to be imported before importing the given type.
  994. static auto GetDependentUnimportedTypeDecls(const Context& context,
  995. clang::QualType type)
  996. -> llvm::SmallVector<clang::Decl*> {
  997. while (true) {
  998. type = type.getCanonicalType();
  999. if (type->isPointerType() || type->isReferenceType()) {
  1000. type = type->getPointeeType();
  1001. } else if (const clang::ArrayType* array_type =
  1002. type->getAsArrayTypeUnsafe()) {
  1003. type = array_type->getElementType();
  1004. } else {
  1005. break;
  1006. }
  1007. }
  1008. type = type.getUnqualifiedType();
  1009. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  1010. if (auto* record_decl =
  1011. clang::dyn_cast<clang::CXXRecordDecl>(record_type->getDecl())) {
  1012. if (!IsClangDeclImported(context, record_decl)) {
  1013. return {record_decl};
  1014. }
  1015. // TODO: Also collect field types.
  1016. }
  1017. }
  1018. return {};
  1019. }
  1020. // Returns all decls that need to be imported before importing the given
  1021. // function.
  1022. static auto GetDependentUnimportedFunctionDecls(
  1023. const Context& context, const clang::FunctionDecl& clang_decl)
  1024. -> llvm::SmallVector<clang::Decl*> {
  1025. llvm::SmallVector<clang::Decl*> decls;
  1026. for (const auto* param : clang_decl.parameters()) {
  1027. llvm::append_range(
  1028. decls, GetDependentUnimportedTypeDecls(context, param->getType()));
  1029. }
  1030. llvm::append_range(decls, GetDependentUnimportedTypeDecls(
  1031. context, clang_decl.getReturnType()));
  1032. return decls;
  1033. }
  1034. // Returns all decls that need to be imported before importing the given
  1035. // declaration.
  1036. static auto GetDependentUnimportedDecls(const Context& context,
  1037. clang::Decl* clang_decl)
  1038. -> llvm::SmallVector<clang::Decl*> {
  1039. llvm::SmallVector<clang::Decl*> decls;
  1040. if (auto* parent_decl = GetParentDecl(clang_decl);
  1041. !IsClangDeclImported(context, parent_decl)) {
  1042. decls.push_back(parent_decl);
  1043. }
  1044. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1045. llvm::append_range(decls, GetDependentUnimportedFunctionDecls(
  1046. context, *clang_function_decl));
  1047. } else if (auto* type_decl = clang::dyn_cast<clang::TypeDecl>(clang_decl)) {
  1048. llvm::append_range(
  1049. decls,
  1050. GetDependentUnimportedTypeDecls(
  1051. context, type_decl->getASTContext().getTypeDeclType(type_decl)));
  1052. }
  1053. return decls;
  1054. }
  1055. // Imports a declaration from Clang to Carbon. If successful, returns the
  1056. // instruction for the new Carbon declaration. Assumes all dependencies have
  1057. // already been imported.
  1058. static auto ImportDeclAfterDependencies(Context& context, SemIR::LocId loc_id,
  1059. clang::Decl* clang_decl)
  1060. -> SemIR::InstId {
  1061. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1062. return ImportFunctionDecl(context, loc_id, clang_function_decl);
  1063. }
  1064. if (auto* clang_namespace_decl =
  1065. clang::dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  1066. return ImportNamespaceDecl(context, clang_namespace_decl);
  1067. }
  1068. if (auto* type_decl = clang::dyn_cast<clang::TypeDecl>(clang_decl)) {
  1069. auto type = type_decl->getASTContext().getTypeDeclType(type_decl);
  1070. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  1071. if (!type_inst_id.has_value()) {
  1072. context.TODO(loc_id, llvm::formatv("Unsupported: Type declaration: {0}",
  1073. type.getAsString()));
  1074. return SemIR::ErrorInst::InstId;
  1075. }
  1076. return type_inst_id;
  1077. }
  1078. if (clang::isa<clang::FieldDecl>(clang_decl)) {
  1079. // Usable fields get imported as a side effect of importing the class.
  1080. if (SemIR::InstId existing_inst_id =
  1081. LookupClangDeclInstId(context, clang_decl);
  1082. existing_inst_id.has_value()) {
  1083. return existing_inst_id;
  1084. }
  1085. context.TODO(loc_id, "Unsupported: Unhandled kind of field declaration");
  1086. return SemIR::InstId::None;
  1087. }
  1088. context.TODO(loc_id, llvm::formatv("Unsupported: Declaration type {0}",
  1089. clang_decl->getDeclKindName())
  1090. .str());
  1091. return SemIR::InstId::None;
  1092. }
  1093. // Imports a declaration from Clang to Carbon. If successful, returns the
  1094. // instruction for the new Carbon declaration. All unimported dependencies would
  1095. // be imported first.
  1096. static auto ImportDeclAndDependencies(Context& context, SemIR::LocId loc_id,
  1097. clang::Decl* clang_decl)
  1098. -> SemIR::InstId {
  1099. // Collect dependencies.
  1100. llvm::SetVector<clang::Decl*> clang_decls;
  1101. clang_decls.insert(clang_decl);
  1102. for (size_t i = 0; i < clang_decls.size(); ++i) {
  1103. auto dependent_decls = GetDependentUnimportedDecls(context, clang_decls[i]);
  1104. for (clang::Decl* dependent_decl : dependent_decls) {
  1105. clang_decls.insert(dependent_decl);
  1106. }
  1107. }
  1108. // Import dependencies in reverse order.
  1109. auto inst_id = SemIR::InstId::None;
  1110. for (clang::Decl* clang_decl_to_import : llvm::reverse(clang_decls)) {
  1111. inst_id =
  1112. ImportDeclAfterDependencies(context, loc_id, clang_decl_to_import);
  1113. if (!inst_id.has_value()) {
  1114. break;
  1115. }
  1116. }
  1117. return inst_id;
  1118. }
  1119. // Imports a `clang::NamedDecl` into Carbon and adds that name into the
  1120. // `NameScope`.
  1121. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  1122. SemIR::NameScopeId scope_id,
  1123. SemIR::NameId name_id,
  1124. clang::NamedDecl* clang_decl)
  1125. -> SemIR::InstId {
  1126. SemIR::InstId inst_id =
  1127. ImportDeclAndDependencies(context, loc_id, clang_decl);
  1128. AddNameToScope(context, scope_id, name_id, inst_id);
  1129. return inst_id;
  1130. }
  1131. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  1132. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  1133. -> SemIR::InstId {
  1134. Diagnostics::AnnotationScope annotate_diagnostics(
  1135. &context.emitter(), [&](auto& builder) {
  1136. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  1137. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  1138. builder.Note(loc_id, InCppNameLookup, name_id);
  1139. });
  1140. auto lookup = ClangLookup(context, scope_id, name_id);
  1141. if (!lookup) {
  1142. return SemIR::InstId::None;
  1143. }
  1144. if (!lookup->isSingleResult()) {
  1145. context.TODO(loc_id,
  1146. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  1147. "find a single result; LookupResultKind: {0}",
  1148. static_cast<int>(lookup->getResultKind()))
  1149. .str());
  1150. context.name_scopes().AddRequiredName(scope_id, name_id,
  1151. SemIR::ErrorInst::InstId);
  1152. return SemIR::ErrorInst::InstId;
  1153. }
  1154. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id,
  1155. lookup->getFoundDecl());
  1156. }
  1157. } // namespace Carbon::Check