import_cpp.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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/Frontend/TextDiagnostic.h"
  11. #include "clang/Sema/Lookup.h"
  12. #include "clang/Tooling/Tooling.h"
  13. #include "common/raw_string_ostream.h"
  14. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/Support/raw_ostream.h"
  17. #include "toolchain/check/class.h"
  18. #include "toolchain/check/context.h"
  19. #include "toolchain/check/convert.h"
  20. #include "toolchain/check/diagnostic_helpers.h"
  21. #include "toolchain/check/eval.h"
  22. #include "toolchain/check/import.h"
  23. #include "toolchain/check/inst.h"
  24. #include "toolchain/check/literal.h"
  25. #include "toolchain/check/pattern.h"
  26. #include "toolchain/check/pattern_match.h"
  27. #include "toolchain/check/type.h"
  28. #include "toolchain/diagnostics/diagnostic.h"
  29. #include "toolchain/diagnostics/format_providers.h"
  30. #include "toolchain/parse/node_ids.h"
  31. #include "toolchain/sem_ir/ids.h"
  32. #include "toolchain/sem_ir/name_scope.h"
  33. #include "toolchain/sem_ir/typed_insts.h"
  34. namespace Carbon::Check {
  35. // Generates C++ file contents to #include all requested imports.
  36. static auto GenerateCppIncludesHeaderCode(
  37. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  38. -> std::string {
  39. std::string code;
  40. llvm::raw_string_ostream code_stream(code);
  41. for (const Parse::Tree::PackagingNames& import : imports) {
  42. code_stream << "#include \""
  43. << FormatEscaped(
  44. context.string_literal_values().Get(import.library_id))
  45. << "\"\n";
  46. }
  47. return code;
  48. }
  49. // Adds the name to the scope with the given `inst_id`, if the `inst_id` is not
  50. // `None`.
  51. static auto AddNameToScope(Context& context, SemIR::NameScopeId scope_id,
  52. SemIR::NameId name_id, SemIR::InstId inst_id)
  53. -> void {
  54. if (inst_id.has_value()) {
  55. context.name_scopes().AddRequiredName(scope_id, name_id, inst_id);
  56. }
  57. }
  58. // Maps a Clang name to a Carbon `NameId`.
  59. static auto AddIdentifierName(Context& context, llvm::StringRef name)
  60. -> SemIR::NameId {
  61. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  62. }
  63. // Adds the given source location and an `ImportIRInst` referring to it in
  64. // `ImportIRId::Cpp`.
  65. static auto AddImportIRInst(Context& context,
  66. clang::SourceLocation clang_source_loc)
  67. -> SemIR::ImportIRInstId {
  68. SemIR::ClangSourceLocId clang_source_loc_id =
  69. context.sem_ir().clang_source_locs().Add(clang_source_loc);
  70. return context.import_ir_insts().Add(
  71. SemIR::ImportIRInst(clang_source_loc_id));
  72. }
  73. namespace {
  74. // Used to convert Clang diagnostics to Carbon diagnostics.
  75. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  76. public:
  77. // Creates an instance with the location that triggers calling Clang.
  78. // `context` must not be null.
  79. explicit CarbonClangDiagnosticConsumer(Context* context)
  80. : context_(context) {}
  81. // Generates a Carbon warning for each Clang warning and a Carbon error for
  82. // each Clang error or fatal.
  83. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  84. const clang::Diagnostic& info) -> void override {
  85. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  86. SemIR::ImportIRInstId clang_import_ir_inst_id =
  87. AddImportIRInst(*context_, info.getLocation());
  88. llvm::SmallString<256> message;
  89. info.FormatDiagnostic(message);
  90. RawStringOstream diagnostics_stream;
  91. // TODO: Consider allowing setting `LangOptions` or use
  92. // `ASTContext::getLangOptions()`.
  93. clang::LangOptions lang_options;
  94. // TODO: Consider allowing setting `DiagnosticOptions` or use
  95. // `ASTUnit::getDiagnostics().getLangOptions().getDiagnosticOptions()`.
  96. clang::DiagnosticOptions diagnostic_options;
  97. clang::TextDiagnostic text_diagnostic(diagnostics_stream, lang_options,
  98. diagnostic_options);
  99. text_diagnostic.emitDiagnostic(
  100. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  101. diag_level, message, info.getRanges(), info.getFixItHints());
  102. std::string diagnostics_str = diagnostics_stream.TakeStr();
  103. diagnostic_infos_.push_back({.level = diag_level,
  104. .import_ir_inst_id = clang_import_ir_inst_id,
  105. .message = diagnostics_str});
  106. }
  107. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  108. // be called after the AST is set in the context.
  109. auto EmitDiagnostics() -> void {
  110. for (const ClangDiagnosticInfo& info : diagnostic_infos_) {
  111. switch (info.level) {
  112. case clang::DiagnosticsEngine::Ignored:
  113. case clang::DiagnosticsEngine::Note:
  114. case clang::DiagnosticsEngine::Remark: {
  115. context_->TODO(
  116. SemIR::LocId(info.import_ir_inst_id),
  117. llvm::formatv(
  118. "Unsupported: C++ diagnostic level for diagnostic\n{0}",
  119. info.message));
  120. break;
  121. }
  122. case clang::DiagnosticsEngine::Warning:
  123. case clang::DiagnosticsEngine::Error:
  124. case clang::DiagnosticsEngine::Fatal: {
  125. // TODO: Parse the message to select the relevant C++ import and add
  126. // that information to the location.
  127. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}",
  128. std::string);
  129. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  130. context_->emitter().Emit(
  131. SemIR::LocId(info.import_ir_inst_id),
  132. info.level == clang::DiagnosticsEngine::Warning
  133. ? CppInteropParseWarning
  134. : CppInteropParseError,
  135. info.message);
  136. break;
  137. }
  138. }
  139. }
  140. }
  141. private:
  142. // The type-checking context in which we're running Clang.
  143. Context* context_;
  144. // Information on a Clang diagnostic that can be converted to a Carbon
  145. // diagnostic.
  146. struct ClangDiagnosticInfo {
  147. // The Clang diagnostic level.
  148. clang::DiagnosticsEngine::Level level;
  149. // The ID of the ImportIR instruction referring to the Clang source
  150. // location.
  151. SemIR::ImportIRInstId import_ir_inst_id;
  152. // The Clang diagnostic textual message.
  153. std::string message;
  154. };
  155. // Collects the information for all Clang diagnostics to be converted to
  156. // Carbon diagnostics after the context has been initialized with the Clang
  157. // AST.
  158. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  159. };
  160. } // namespace
  161. // Returns an AST for the C++ imports and a bool that represents whether
  162. // compilation errors where encountered or the generated AST is null due to an
  163. // error. Sets the AST in the context's `sem_ir`.
  164. // TODO: Consider to always have a (non-null) AST.
  165. static auto GenerateAst(Context& context, llvm::StringRef importing_file_path,
  166. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  167. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  168. llvm::StringRef target)
  169. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  170. CarbonClangDiagnosticConsumer diagnostics_consumer(&context);
  171. // TODO: Share compilation flags with ClangRunner.
  172. auto ast = clang::tooling::buildASTFromCodeWithArgs(
  173. GenerateCppIncludesHeaderCode(context, imports),
  174. // Parse C++ (and not C).
  175. {
  176. "-x",
  177. "c++",
  178. // Propagate the target to Clang.
  179. "-target",
  180. target.str(),
  181. // Require PIE. Note its default is configurable in Clang.
  182. "-fPIE",
  183. },
  184. (importing_file_path + ".generated.cpp_imports.h").str(), "clang-tool",
  185. std::make_shared<clang::PCHContainerOperations>(),
  186. clang::tooling::getClangStripDependencyFileAdjuster(),
  187. clang::tooling::FileContentMappings(), &diagnostics_consumer, fs);
  188. // Remove link to the diagnostics consumer before its deletion.
  189. ast->getDiagnostics().setClient(nullptr);
  190. // In order to emit diagnostics, we need the AST.
  191. context.sem_ir().set_cpp_ast(ast.get());
  192. diagnostics_consumer.EmitDiagnostics();
  193. return {std::move(ast), !ast || diagnostics_consumer.getNumErrors() > 0};
  194. }
  195. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  196. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  197. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  198. -> SemIR::NameScopeId {
  199. auto& import_cpps = context.sem_ir().import_cpps();
  200. import_cpps.Reserve(imports.size());
  201. for (const Parse::Tree::PackagingNames& import : imports) {
  202. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  203. import.node_id),
  204. .library_id = import.library_id});
  205. }
  206. return AddImportNamespaceToScope(
  207. context,
  208. GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  209. SemIR::NameId::ForPackageName(cpp_package_id),
  210. SemIR::NameScopeId::Package,
  211. /*diagnose_duplicate_namespace=*/false,
  212. [&]() {
  213. return AddInst<SemIR::ImportCppDecl>(
  214. context,
  215. context.parse_tree().As<Parse::ImportDeclId>(
  216. imports.front().node_id),
  217. {});
  218. })
  219. .add_result.name_scope_id;
  220. }
  221. auto ImportCppFiles(Context& context, llvm::StringRef importing_file_path,
  222. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  223. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  224. llvm::StringRef target) -> std::unique_ptr<clang::ASTUnit> {
  225. if (imports.empty()) {
  226. return nullptr;
  227. }
  228. CARBON_CHECK(!context.sem_ir().cpp_ast());
  229. PackageNameId package_id = imports.front().package_id;
  230. CARBON_CHECK(
  231. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  232. return import.package_id == package_id;
  233. }));
  234. auto name_scope_id = AddNamespace(context, package_id, imports);
  235. auto [generated_ast, ast_has_error] =
  236. GenerateAst(context, importing_file_path, imports, fs, target);
  237. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  238. name_scope.set_is_closed_import(true);
  239. name_scope.set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  240. {.decl = generated_ast->getASTContext().getTranslationUnitDecl(),
  241. .inst_id = name_scope.inst_id()}));
  242. if (ast_has_error) {
  243. name_scope.set_has_error();
  244. }
  245. return std::move(generated_ast);
  246. }
  247. // Look ups the given name in the Clang AST in a specific scope. Returns the
  248. // lookup result if lookup was successful.
  249. static auto ClangLookup(Context& context, SemIR::NameScopeId scope_id,
  250. SemIR::NameId name_id)
  251. -> std::optional<clang::LookupResult> {
  252. std::optional<llvm::StringRef> name =
  253. context.names().GetAsStringIfIdentifier(name_id);
  254. if (!name) {
  255. // Special names never exist in C++ code.
  256. return std::nullopt;
  257. }
  258. clang::ASTUnit* ast = context.sem_ir().cpp_ast();
  259. CARBON_CHECK(ast);
  260. clang::Sema& sema = ast->getSema();
  261. clang::LookupResult lookup(
  262. sema,
  263. clang::DeclarationNameInfo(
  264. clang::DeclarationName(
  265. sema.getPreprocessor().getIdentifierInfo(*name)),
  266. clang::SourceLocation()),
  267. clang::Sema::LookupNameKind::LookupOrdinaryName);
  268. // TODO: Diagnose on access and return the `AccessKind` for storage. We'll
  269. // probably need a dedicated `DiagnosticConsumer` because
  270. // `TextDiagnosticPrinter` assumes we're processing a C++ source file.
  271. lookup.suppressDiagnostics();
  272. auto scope_clang_decl_context_id =
  273. context.name_scopes().Get(scope_id).clang_decl_context_id();
  274. bool found = sema.LookupQualifiedName(
  275. lookup,
  276. clang::dyn_cast<clang::DeclContext>(context.sem_ir()
  277. .clang_decls()
  278. .Get(scope_clang_decl_context_id)
  279. .decl));
  280. if (!found) {
  281. return std::nullopt;
  282. }
  283. return lookup;
  284. }
  285. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  286. // the new Carbon namespace declaration `InstId`.
  287. static auto ImportNamespaceDecl(Context& context,
  288. SemIR::NameScopeId parent_scope_id,
  289. SemIR::NameId name_id,
  290. clang::NamespaceDecl* clang_decl)
  291. -> SemIR::InstId {
  292. auto result = AddImportNamespace(
  293. context, GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  294. name_id, parent_scope_id, /*import_id=*/SemIR::InstId::None);
  295. context.name_scopes()
  296. .Get(result.name_scope_id)
  297. .set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  298. {.decl = clang_decl, .inst_id = result.inst_id}));
  299. return result.inst_id;
  300. }
  301. // Maps a C++ declaration context to a Carbon namespace.
  302. static auto AsCarbonNamespace(Context& context,
  303. clang::DeclContext* decl_context)
  304. -> SemIR::InstId {
  305. CARBON_CHECK(decl_context);
  306. auto& clang_decls = context.sem_ir().clang_decls();
  307. // Check if the decl context is already mapped to a Carbon namespace.
  308. if (auto context_clang_decl_id = clang_decls.Lookup(
  309. {.decl = clang::dyn_cast<clang::Decl>(decl_context),
  310. .inst_id = SemIR::InstId::None});
  311. context_clang_decl_id.has_value()) {
  312. return clang_decls.Get(context_clang_decl_id).inst_id;
  313. }
  314. // We know we have at least one context to map, add all decl contexts we need
  315. // to map.
  316. llvm::SmallVector<clang::DeclContext*> decl_contexts;
  317. auto parent_decl_id = SemIR::ClangDeclId::None;
  318. do {
  319. decl_contexts.push_back(decl_context);
  320. decl_context = decl_context->getParent();
  321. parent_decl_id =
  322. clang_decls.Lookup({.decl = clang::dyn_cast<clang::Decl>(decl_context),
  323. .inst_id = SemIR::InstId::None});
  324. } while (!parent_decl_id.has_value());
  325. // We know the parent of the last decl context is mapped, map the rest.
  326. auto namespace_inst_id = SemIR::InstId::None;
  327. do {
  328. decl_context = decl_contexts.pop_back_val();
  329. auto parent_inst_id = clang_decls.Get(parent_decl_id).inst_id;
  330. auto parent_namespace =
  331. context.insts().GetAs<SemIR::Namespace>(parent_inst_id);
  332. namespace_inst_id = ImportNamespaceDecl(
  333. context, parent_namespace.name_scope_id,
  334. AddIdentifierName(
  335. context, llvm::dyn_cast<clang::NamedDecl>(decl_context)->getName()),
  336. clang::dyn_cast<clang::NamespaceDecl>(decl_context));
  337. parent_decl_id = clang_decls.Add({
  338. .decl = clang::dyn_cast<clang::Decl>(decl_context),
  339. .inst_id = namespace_inst_id,
  340. });
  341. } while (!decl_contexts.empty());
  342. return namespace_inst_id;
  343. }
  344. // Creates a class declaration for the given class name in the given scope.
  345. // Returns the `InstId` for the declaration.
  346. static auto BuildClassDecl(Context& context, SemIR::NameScopeId parent_scope_id,
  347. SemIR::NameId name_id)
  348. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  349. // Add the class declaration.
  350. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeType::TypeId,
  351. .class_id = SemIR::ClassId::None,
  352. .decl_block_id = SemIR::InstBlockId::None};
  353. // TODO: Consider setting a proper location.
  354. auto class_decl_id = AddPlaceholderInstInNoBlock(
  355. context, SemIR::LocIdAndInst::NoLoc(class_decl));
  356. context.imports().push_back(class_decl_id);
  357. SemIR::Class class_info = {
  358. {.name_id = name_id,
  359. .parent_scope_id = parent_scope_id,
  360. .generic_id = SemIR::GenericId::None,
  361. .first_param_node_id = Parse::NodeId::None,
  362. .last_param_node_id = Parse::NodeId::None,
  363. .pattern_block_id = SemIR::InstBlockId::None,
  364. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  365. .param_patterns_id = SemIR::InstBlockId::None,
  366. .is_extern = false,
  367. .extern_library_id = SemIR::LibraryNameId::None,
  368. .non_owning_decl_id = SemIR::InstId::None,
  369. .first_owning_decl_id = class_decl_id},
  370. {// `.self_type_id` depends on the ClassType, so is set below.
  371. .self_type_id = SemIR::TypeId::None,
  372. // TODO: Support Dynamic classes.
  373. // TODO: Support Final classes.
  374. .inheritance_kind = SemIR::Class::Base}};
  375. class_decl.class_id = context.classes().Add(class_info);
  376. // Write the class ID into the ClassDecl.
  377. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  378. SetClassSelfType(context, class_decl.class_id);
  379. return {class_decl.class_id, class_decl_id};
  380. }
  381. // Creates a class definition for the given class name in the given scope based
  382. // on the information in the given Clang declaration. Returns the `InstId` for
  383. // the declaration, which is assumed to be for a class definition. Returns the
  384. // new class id and instruction id.
  385. static auto BuildClassDefinition(Context& context,
  386. SemIR::NameScopeId parent_scope_id,
  387. SemIR::NameId name_id,
  388. clang::CXXRecordDecl* clang_decl)
  389. -> std::tuple<SemIR::ClassId, SemIR::InstId> {
  390. auto [class_id, class_inst_id] =
  391. BuildClassDecl(context, parent_scope_id, name_id);
  392. auto& class_info = context.classes().Get(class_id);
  393. StartClassDefinition(context, class_info, class_inst_id);
  394. context.name_scopes()
  395. .Get(class_info.scope_id)
  396. .set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  397. {.decl = clang_decl, .inst_id = class_inst_id}));
  398. return {class_id, class_inst_id};
  399. }
  400. // Imports a record declaration from Clang to Carbon. If successful, returns
  401. // the new Carbon class declaration `InstId`.
  402. // TODO: Change `clang_decl` to `const &` when lookup is using `clang::DeclID`
  403. // and we don't need to store the decl for lookup context.
  404. static auto ImportCXXRecordDecl(Context& context, SemIR::LocId loc_id,
  405. SemIR::NameScopeId parent_scope_id,
  406. SemIR::NameId name_id,
  407. clang::CXXRecordDecl* clang_decl)
  408. -> SemIR::InstId {
  409. clang::CXXRecordDecl* clang_def = clang_decl->getDefinition();
  410. if (!clang_def) {
  411. context.TODO(loc_id,
  412. "Unsupported: Record declarations without a definition");
  413. return SemIR::ErrorInst::InstId;
  414. }
  415. if (clang_def->isDynamicClass()) {
  416. context.TODO(loc_id, "Unsupported: Dynamic Class");
  417. return SemIR::ErrorInst::InstId;
  418. }
  419. auto [class_id, class_def_id] =
  420. BuildClassDefinition(context, parent_scope_id, name_id, clang_def);
  421. // The class type is now fully defined. Compute its object representation.
  422. ComputeClassObjectRepr(context,
  423. // TODO: Consider having a proper location here.
  424. Parse::ClassDefinitionId::None, class_id,
  425. // TODO: Set fields.
  426. /*field_decls=*/{},
  427. // TODO: Set vtable.
  428. /*vtable_contents=*/{},
  429. // TODO: Set block.
  430. /*body=*/{});
  431. return class_def_id;
  432. }
  433. // Creates an integer type of the given size.
  434. static auto MakeIntType(Context& context, IntId size_id) -> TypeExpr {
  435. // TODO: Fill in a location for the type once available.
  436. auto type_inst_id = MakeIntTypeLiteral(context, Parse::NodeId::None,
  437. SemIR::IntKind::Signed, size_id);
  438. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  439. }
  440. // Maps a C++ builtin type to a Carbon type.
  441. // TODO: Support more builtin types.
  442. static auto MapBuiltinType(Context& context, const clang::BuiltinType& type)
  443. -> TypeExpr {
  444. // TODO: Refactor to avoid duplication.
  445. switch (type.getKind()) {
  446. case clang::BuiltinType::Short:
  447. if (context.ast_context().getTypeSize(&type) == 16) {
  448. return MakeIntType(context, context.ints().Add(16));
  449. }
  450. break;
  451. case clang::BuiltinType::Int:
  452. if (context.ast_context().getTypeSize(&type) == 32) {
  453. return MakeIntType(context, context.ints().Add(32));
  454. }
  455. break;
  456. default:
  457. break;
  458. }
  459. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  460. .type_id = SemIR::ErrorInst::TypeId};
  461. }
  462. // Maps a C++ record type to a Carbon type.
  463. // TODO: Support more record types.
  464. static auto MapRecordType(Context& context, SemIR::LocId loc_id,
  465. const clang::RecordType& type) -> TypeExpr {
  466. auto* record_decl = clang::dyn_cast<clang::CXXRecordDecl>(type.getDecl());
  467. if (record_decl && record_decl->isStruct()) {
  468. auto& clang_decls = context.sem_ir().clang_decls();
  469. SemIR::InstId struct_inst_id = SemIR::InstId::None;
  470. if (auto struct_clang_decl_id = clang_decls.Lookup(
  471. {.decl = record_decl, .inst_id = SemIR::InstId::None});
  472. struct_clang_decl_id.has_value()) {
  473. struct_inst_id = clang_decls.Get(struct_clang_decl_id).inst_id;
  474. } else {
  475. auto parent_inst_id =
  476. AsCarbonNamespace(context, record_decl->getDeclContext());
  477. auto parent_name_scope_id =
  478. context.insts().GetAs<SemIR::Namespace>(parent_inst_id).name_scope_id;
  479. SemIR::NameId struct_name_id =
  480. AddIdentifierName(context, record_decl->getName());
  481. struct_inst_id = ImportCXXRecordDecl(
  482. context, loc_id, parent_name_scope_id, struct_name_id, record_decl);
  483. AddNameToScope(context, parent_name_scope_id, struct_name_id,
  484. struct_inst_id);
  485. }
  486. SemIR::TypeInstId struct_type_inst_id =
  487. context.types().GetAsTypeInstId(struct_inst_id);
  488. return {
  489. .inst_id = struct_type_inst_id,
  490. .type_id = context.types().GetTypeIdForTypeInstId(struct_type_inst_id)};
  491. }
  492. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  493. .type_id = SemIR::ErrorInst::TypeId};
  494. }
  495. // Maps a C++ type to a Carbon type.
  496. // TODO: Support more types.
  497. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  498. -> TypeExpr {
  499. if (const auto* builtin_type = dyn_cast<clang::BuiltinType>(type)) {
  500. return MapBuiltinType(context, *builtin_type);
  501. }
  502. if (const auto* record_type = clang::dyn_cast<clang::RecordType>(type)) {
  503. return MapRecordType(context, loc_id, *record_type);
  504. }
  505. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  506. .type_id = SemIR::ErrorInst::TypeId};
  507. }
  508. // Returns a block id for the explicit parameters of the given function
  509. // declaration. If the function declaration has no parameters, it returns
  510. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  511. // returns `SemIR::InstBlockId::None`.
  512. // TODO: Consider refactoring to extract and reuse more logic from
  513. // `HandleAnyBindingPattern()`.
  514. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  515. const clang::FunctionDecl& clang_decl)
  516. -> SemIR::InstBlockId {
  517. if (clang_decl.parameters().empty()) {
  518. return SemIR::InstBlockId::Empty;
  519. }
  520. llvm::SmallVector<SemIR::InstId> params;
  521. params.reserve(clang_decl.parameters().size());
  522. for (const clang::ParmVarDecl* param : clang_decl.parameters()) {
  523. clang::QualType param_type = param->getType().getCanonicalType();
  524. // Mark the start of a region of insts, needed for the type expression
  525. // created later with the call of `EndSubpatternAsExpr()`.
  526. BeginSubpattern(context);
  527. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  528. // Type expression of the binding pattern - a single-entry/single-exit
  529. // region that allows control flow in the type expression e.g. fn F(x: if C
  530. // then i32 else i64).
  531. SemIR::ExprRegionId type_expr_region_id =
  532. EndSubpatternAsExpr(context, type_inst_id);
  533. if (type_id == SemIR::ErrorInst::TypeId) {
  534. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  535. param_type.getAsString()));
  536. return SemIR::InstBlockId::None;
  537. }
  538. llvm::StringRef param_name = param->getName();
  539. SemIR::NameId name_id =
  540. param_name.empty()
  541. // Translate an unnamed parameter to an underscore to
  542. // match Carbon's naming of unnamed/unused function params.
  543. ? SemIR::NameId::Underscore
  544. : AddIdentifierName(context, param_name);
  545. // TODO: Fix this once templates are supported.
  546. bool is_template = false;
  547. // TODO: Fix this once generics are supported.
  548. bool is_generic = false;
  549. SemIR::InstId binding_pattern_id =
  550. // TODO: Fill in a location once available.
  551. AddBindingPattern(context, SemIR::LocId::None, name_id, type_id,
  552. type_expr_region_id, is_generic, is_template)
  553. .pattern_id;
  554. SemIR::InstId var_pattern_id = AddPatternInst(
  555. context,
  556. // TODO: Fill in a location once available.
  557. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  558. {.type_id = context.insts().Get(binding_pattern_id).type_id(),
  559. .subpattern_id = binding_pattern_id,
  560. .index = SemIR::CallParamIndex::None})));
  561. params.push_back(var_pattern_id);
  562. }
  563. return context.inst_blocks().Add(params);
  564. }
  565. // Returns the return type of the given function declaration. In case of an
  566. // unsupported return type, it returns `SemIR::ErrorInst::InstId`.
  567. // TODO: Support more return types.
  568. static auto GetReturnType(Context& context, SemIR::LocId loc_id,
  569. const clang::FunctionDecl* clang_decl)
  570. -> SemIR::InstId {
  571. clang::QualType ret_type = clang_decl->getReturnType().getCanonicalType();
  572. if (ret_type->isVoidType()) {
  573. return SemIR::InstId::None;
  574. }
  575. auto [type_inst_id, type_id] = MapType(context, loc_id, ret_type);
  576. if (type_id == SemIR::ErrorInst::TypeId) {
  577. context.TODO(loc_id, llvm::formatv("Unsupported: return type: {0}",
  578. ret_type.getAsString()));
  579. return SemIR::ErrorInst::InstId;
  580. }
  581. auto pattern_type_id = GetPatternType(context, type_id);
  582. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  583. // TODO: Fill in a location for the return type once available.
  584. context,
  585. SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  586. {.type_id = pattern_type_id, .type_inst_id = type_inst_id})));
  587. SemIR::InstId param_pattern_id = AddPatternInst(
  588. // TODO: Fill in a location for the return type once available.
  589. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  590. {.type_id = pattern_type_id,
  591. .subpattern_id = return_slot_pattern_id,
  592. .index = SemIR::CallParamIndex::None})));
  593. return param_pattern_id;
  594. }
  595. namespace {
  596. // Represents the parameter patterns block id, the return slot pattern id and
  597. // the call parameters block id for a function declaration.
  598. struct FunctionParamsInsts {
  599. SemIR::InstBlockId param_patterns_id;
  600. SemIR::InstId return_slot_pattern_id;
  601. SemIR::InstBlockId call_params_id;
  602. };
  603. } // namespace
  604. // Creates a block containing the parameter pattern instructions for the
  605. // explicit parameters, a parameter pattern instruction for the return type and
  606. // a block containing the call parameters of the function. Emits a callee
  607. // pattern-match for the explicit parameter patterns and the return slot pattern
  608. // to create the Call parameters instructions block. Currently the implicit
  609. // parameter patterns are not taken into account. Returns the parameter patterns
  610. // block id, the return slot pattern id, and the call parameters block id.
  611. // Returns `std::nullopt` if the function declaration has an unsupported
  612. // parameter type.
  613. static auto CreateFunctionParamsInsts(Context& context, SemIR::LocId loc_id,
  614. const clang::FunctionDecl* clang_decl)
  615. -> std::optional<FunctionParamsInsts> {
  616. auto param_patterns_id =
  617. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  618. if (!param_patterns_id.has_value()) {
  619. return std::nullopt;
  620. }
  621. auto return_slot_pattern_id = GetReturnType(context, loc_id, clang_decl);
  622. if (SemIR::ErrorInst::InstId == return_slot_pattern_id) {
  623. return std::nullopt;
  624. }
  625. // TODO: Add support for implicit parameters.
  626. auto call_params_id = CalleePatternMatch(
  627. context, /*implicit_param_patterns_id=*/SemIR::InstBlockId::None,
  628. param_patterns_id, return_slot_pattern_id);
  629. return {{.param_patterns_id = param_patterns_id,
  630. .return_slot_pattern_id = return_slot_pattern_id,
  631. .call_params_id = call_params_id}};
  632. }
  633. // Imports a function declaration from Clang to Carbon. If successful, returns
  634. // the new Carbon function declaration `InstId`.
  635. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  636. SemIR::NameScopeId scope_id,
  637. SemIR::NameId name_id,
  638. clang::FunctionDecl* clang_decl)
  639. -> SemIR::InstId {
  640. if (clang_decl->isVariadic()) {
  641. context.TODO(loc_id, "Unsupported: Variadic function");
  642. return SemIR::ErrorInst::InstId;
  643. }
  644. if (!clang_decl->isGlobal()) {
  645. context.TODO(loc_id, "Unsupported: Non-global function");
  646. return SemIR::ErrorInst::InstId;
  647. }
  648. if (clang_decl->getTemplatedKind() != clang::FunctionDecl::TK_NonTemplate) {
  649. context.TODO(loc_id, "Unsupported: Template function");
  650. return SemIR::ErrorInst::InstId;
  651. }
  652. context.inst_block_stack().Push();
  653. context.pattern_block_stack().Push();
  654. auto function_params_insts =
  655. CreateFunctionParamsInsts(context, loc_id, clang_decl);
  656. auto pattern_block_id = context.pattern_block_stack().Pop();
  657. auto decl_block_id = context.inst_block_stack().Pop();
  658. if (!function_params_insts.has_value()) {
  659. return SemIR::ErrorInst::InstId;
  660. }
  661. auto function_decl = SemIR::FunctionDecl{
  662. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  663. auto decl_id =
  664. AddPlaceholderInstInNoBlock(context, Parse::NodeId::None, function_decl);
  665. context.imports().push_back(decl_id);
  666. auto function_info = SemIR::Function{
  667. {.name_id = name_id,
  668. .parent_scope_id = scope_id,
  669. .generic_id = SemIR::GenericId::None,
  670. .first_param_node_id = Parse::NodeId::None,
  671. .last_param_node_id = Parse::NodeId::None,
  672. .pattern_block_id = pattern_block_id,
  673. .implicit_param_patterns_id = SemIR::InstBlockId::Empty,
  674. .param_patterns_id = function_params_insts->param_patterns_id,
  675. .is_extern = false,
  676. .extern_library_id = SemIR::LibraryNameId::None,
  677. .non_owning_decl_id = SemIR::InstId::None,
  678. .first_owning_decl_id = decl_id,
  679. .definition_id = SemIR::InstId::None},
  680. {.call_params_id = function_params_insts->call_params_id,
  681. .return_slot_pattern_id = function_params_insts->return_slot_pattern_id,
  682. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  683. .self_param_id = SemIR::InstId::None,
  684. .clang_decl_id = context.sem_ir().clang_decls().Add(
  685. {.decl = clang_decl, .inst_id = decl_id})}};
  686. function_decl.function_id = context.functions().Add(function_info);
  687. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  688. SemIR::SpecificId::None);
  689. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  690. return decl_id;
  691. }
  692. // Imports a declaration from Clang to Carbon. If successful, returns the
  693. // instruction for the new Carbon declaration.
  694. static auto ImportNameDecl(Context& context, SemIR::LocId loc_id,
  695. SemIR::NameScopeId scope_id, SemIR::NameId name_id,
  696. clang::NamedDecl* clang_decl) -> SemIR::InstId {
  697. if (auto* clang_function_decl =
  698. clang::dyn_cast<clang::FunctionDecl>(clang_decl)) {
  699. return ImportFunctionDecl(context, loc_id, scope_id, name_id,
  700. clang_function_decl);
  701. }
  702. if (auto* clang_namespace_decl =
  703. clang::dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  704. return ImportNamespaceDecl(context, scope_id, name_id,
  705. clang_namespace_decl);
  706. }
  707. if (auto* clang_record_decl =
  708. clang::dyn_cast<clang::CXXRecordDecl>(clang_decl)) {
  709. return ImportCXXRecordDecl(context, loc_id, scope_id, name_id,
  710. clang_record_decl);
  711. }
  712. context.TODO(loc_id, llvm::formatv("Unsupported: Declaration type {0}",
  713. clang_decl->getDeclKindName())
  714. .str());
  715. return SemIR::InstId::None;
  716. }
  717. // Imports a `clang::NamedDecl` into Carbon and adds that name into the
  718. // `NameScope`.
  719. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  720. SemIR::NameScopeId scope_id,
  721. SemIR::NameId name_id,
  722. clang::NamedDecl* clang_decl)
  723. -> SemIR::InstId {
  724. SemIR::InstId inst_id =
  725. ImportNameDecl(context, loc_id, scope_id, name_id, clang_decl);
  726. AddNameToScope(context, scope_id, name_id, inst_id);
  727. return inst_id;
  728. }
  729. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  730. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  731. -> SemIR::InstId {
  732. Diagnostics::AnnotationScope annotate_diagnostics(
  733. &context.emitter(), [&](auto& builder) {
  734. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  735. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  736. builder.Note(loc_id, InCppNameLookup, name_id);
  737. });
  738. auto lookup = ClangLookup(context, scope_id, name_id);
  739. if (!lookup) {
  740. return SemIR::InstId::None;
  741. }
  742. if (!lookup->isSingleResult()) {
  743. context.TODO(loc_id,
  744. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  745. "find a single result; LookupResultKind: {0}",
  746. static_cast<int>(lookup->getResultKind()))
  747. .str());
  748. context.name_scopes().AddRequiredName(scope_id, name_id,
  749. SemIR::ErrorInst::InstId);
  750. return SemIR::ErrorInst::InstId;
  751. }
  752. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id,
  753. lookup->getFoundDecl());
  754. }
  755. } // namespace Carbon::Check