import_cpp.cpp 47 KB

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