import_cpp.cpp 48 KB

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