import_cpp.cpp 35 KB

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