import_cpp.cpp 46 KB

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