import_cpp.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 "clang/Frontend/TextDiagnosticPrinter.h"
  9. #include "clang/Sema/Lookup.h"
  10. #include "clang/Tooling/Tooling.h"
  11. #include "common/raw_string_ostream.h"
  12. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. #include "toolchain/check/context.h"
  16. #include "toolchain/check/diagnostic_helpers.h"
  17. #include "toolchain/check/import.h"
  18. #include "toolchain/check/inst.h"
  19. #include "toolchain/check/type.h"
  20. #include "toolchain/diagnostics/diagnostic.h"
  21. #include "toolchain/diagnostics/format_providers.h"
  22. #include "toolchain/parse/node_ids.h"
  23. #include "toolchain/sem_ir/ids.h"
  24. #include "toolchain/sem_ir/name_scope.h"
  25. namespace Carbon::Check {
  26. // Generates C++ file contents to #include all requested imports.
  27. static auto GenerateCppIncludesHeaderCode(
  28. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  29. -> std::string {
  30. std::string code;
  31. llvm::raw_string_ostream code_stream(code);
  32. for (const Parse::Tree::PackagingNames& import : imports) {
  33. code_stream << "#include \""
  34. << FormatEscaped(
  35. context.string_literal_values().Get(import.library_id))
  36. << "\"\n";
  37. }
  38. return code;
  39. }
  40. // Returns an AST for the C++ imports and a bool that represents whether
  41. // compilation errors where encountered or the generated AST is null due to an
  42. // error.
  43. // TODO: Consider to always have a (non-null) AST.
  44. static auto GenerateAst(Context& context, llvm::StringRef importing_file_path,
  45. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  46. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs)
  47. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  48. // TODO: Use all import locations by referring each Clang diagnostic to the
  49. // relevant import.
  50. SemIRLoc loc = imports.back().node_id;
  51. std::string diagnostics_str;
  52. llvm::raw_string_ostream diagnostics_stream(diagnostics_str);
  53. llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnostic_options(
  54. new clang::DiagnosticOptions());
  55. clang::TextDiagnosticPrinter diagnostics_consumer(diagnostics_stream,
  56. diagnostic_options.get());
  57. // TODO: Share compilation flags with ClangRunner.
  58. auto ast = clang::tooling::buildASTFromCodeWithArgs(
  59. GenerateCppIncludesHeaderCode(context, imports),
  60. // Parse C++ (and not C)
  61. {"-x", "c++"}, (importing_file_path + ".generated.cpp_imports.h").str(),
  62. "clang-tool", std::make_shared<clang::PCHContainerOperations>(),
  63. clang::tooling::getClangStripDependencyFileAdjuster(),
  64. clang::tooling::FileContentMappings(), &diagnostics_consumer, fs);
  65. // Remove link to the diagnostics consumer before its deletion.
  66. ast->getDiagnostics().setClient(nullptr);
  67. // TODO: Implement and use a DynamicRecursiveASTVisitor to traverse the AST.
  68. int num_errors = diagnostics_consumer.getNumErrors();
  69. int num_warnings = diagnostics_consumer.getNumWarnings();
  70. int num_imports = imports.size();
  71. if (num_errors > 0) {
  72. // TODO: Remove the warnings part when there are no warnings.
  73. CARBON_DIAGNOSTIC(
  74. CppInteropParseError, Error,
  75. "{0} error{0:s} and {1} warning{1:s} in {2} `Cpp` import{2:s}:\n{3}",
  76. IntAsSelect, IntAsSelect, IntAsSelect, std::string);
  77. context.emitter().Emit(loc, CppInteropParseError, num_errors, num_warnings,
  78. num_imports, diagnostics_str);
  79. } else if (num_warnings > 0) {
  80. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning,
  81. "{0} warning{0:s} in `Cpp` {1} import{1:s}:\n{2}",
  82. IntAsSelect, IntAsSelect, std::string);
  83. context.emitter().Emit(loc, CppInteropParseWarning, num_warnings,
  84. num_imports, diagnostics_str);
  85. }
  86. return {std::move(ast), !ast || num_errors > 0};
  87. }
  88. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  89. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  90. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  91. -> SemIR::NameScopeId {
  92. auto& import_cpps = context.sem_ir().import_cpps();
  93. import_cpps.Reserve(imports.size());
  94. for (const Parse::Tree::PackagingNames& import : imports) {
  95. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  96. import.node_id),
  97. .library_id = import.library_id});
  98. }
  99. return AddImportNamespaceToScope(
  100. context,
  101. GetSingletonType(context, SemIR::NamespaceType::SingletonInstId),
  102. SemIR::NameId::ForPackageName(cpp_package_id),
  103. SemIR::NameScopeId::Package,
  104. /*diagnose_duplicate_namespace=*/false,
  105. [&]() {
  106. return AddInst<SemIR::ImportCppDecl>(
  107. context,
  108. context.parse_tree().As<Parse::ImportDeclId>(
  109. imports.front().node_id),
  110. {});
  111. })
  112. .add_result.name_scope_id;
  113. }
  114. auto ImportCppFiles(Context& context, llvm::StringRef importing_file_path,
  115. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  116. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs)
  117. -> std::unique_ptr<clang::ASTUnit> {
  118. if (imports.empty()) {
  119. return nullptr;
  120. }
  121. CARBON_CHECK(!context.sem_ir().cpp_ast());
  122. auto [generated_ast, ast_has_error] =
  123. GenerateAst(context, importing_file_path, imports, fs);
  124. PackageNameId package_id = imports.front().package_id;
  125. CARBON_CHECK(
  126. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  127. return import.package_id == package_id;
  128. }));
  129. auto name_scope_id = AddNamespace(context, package_id, imports);
  130. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  131. name_scope.set_is_closed_import(true);
  132. name_scope.set_cpp_decl_context(
  133. generated_ast->getASTContext().getTranslationUnitDecl());
  134. context.sem_ir().set_cpp_ast(generated_ast.get());
  135. if (ast_has_error) {
  136. name_scope.set_has_error();
  137. }
  138. return std::move(generated_ast);
  139. }
  140. // Look ups the given name in the Clang AST in a specific scope. Returns the
  141. // lookup result if lookup was successful.
  142. static auto ClangLookup(Context& context, SemIR::LocId loc_id,
  143. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  144. -> std::optional<clang::LookupResult> {
  145. std::optional<llvm::StringRef> name =
  146. context.names().GetAsStringIfIdentifier(name_id);
  147. if (!name) {
  148. // Special names never exist in C++ code.
  149. return std::nullopt;
  150. }
  151. clang::ASTUnit* ast = context.sem_ir().cpp_ast();
  152. CARBON_CHECK(ast);
  153. clang::Sema& sema = ast->getSema();
  154. clang::LookupResult lookup(
  155. sema,
  156. clang::DeclarationNameInfo(
  157. clang::DeclarationName(
  158. sema.getPreprocessor().getIdentifierInfo(*name)),
  159. clang::SourceLocation()),
  160. clang::Sema::LookupNameKind::LookupOrdinaryName);
  161. bool found = sema.LookupQualifiedName(
  162. lookup, context.name_scopes().Get(scope_id).cpp_decl_context());
  163. if (lookup.isClassLookup()) {
  164. // TODO: To support class lookup, also return the AccessKind for storage.
  165. context.TODO(loc_id, "Unsupported: Lookup in Class");
  166. return std::nullopt;
  167. }
  168. if (!found) {
  169. return std::nullopt;
  170. }
  171. return lookup;
  172. }
  173. // Imports a function declaration from Clang to Carbon. If successful, returns
  174. // the new Carbon function declaration `InstId`.
  175. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  176. SemIR::NameScopeId scope_id,
  177. SemIR::NameId name_id,
  178. const clang::FunctionDecl* clang_decl)
  179. -> SemIR::InstId {
  180. if (clang_decl->isVariadic()) {
  181. context.TODO(loc_id, "Unsupported: Variadic function");
  182. return SemIR::ErrorInst::SingletonInstId;
  183. }
  184. if (!clang_decl->isGlobal()) {
  185. context.TODO(loc_id, "Unsupported: Non-global function");
  186. return SemIR::ErrorInst::SingletonInstId;
  187. }
  188. if (clang_decl->getTemplatedKind() != clang::FunctionDecl::TK_NonTemplate) {
  189. context.TODO(loc_id, "Unsupported: Template function");
  190. return SemIR::ErrorInst::SingletonInstId;
  191. }
  192. if (!clang_decl->param_empty()) {
  193. context.TODO(loc_id, "Unsupported: Function with parameters");
  194. return SemIR::ErrorInst::SingletonInstId;
  195. }
  196. if (!clang_decl->getReturnType()->isVoidType()) {
  197. context.TODO(loc_id, "Unsupported: Function with non-void return type");
  198. return SemIR::ErrorInst::SingletonInstId;
  199. }
  200. auto function_decl = SemIR::FunctionDecl{
  201. SemIR::TypeId::None, SemIR::FunctionId::None, SemIR::InstBlockId::Empty};
  202. auto decl_id = AddPlaceholderInst(
  203. context, SemIR::LocIdAndInst(Parse::NodeId::None, function_decl));
  204. auto function_info = SemIR::Function{
  205. {.name_id = name_id,
  206. .parent_scope_id = scope_id,
  207. .generic_id = SemIR::GenericId::None,
  208. .first_param_node_id = Parse::NodeId::None,
  209. .last_param_node_id = Parse::NodeId::None,
  210. .pattern_block_id = SemIR::InstBlockId::Empty,
  211. .implicit_param_patterns_id = SemIR::InstBlockId::Empty,
  212. .param_patterns_id = SemIR::InstBlockId::Empty,
  213. .is_extern = false,
  214. .extern_library_id = SemIR::LibraryNameId::None,
  215. .non_owning_decl_id = SemIR::InstId::None,
  216. .first_owning_decl_id = decl_id,
  217. .definition_id = SemIR::InstId::None},
  218. {.call_params_id = SemIR::InstBlockId::Empty,
  219. .return_slot_pattern_id = SemIR::InstId::None,
  220. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  221. .self_param_id = SemIR::InstId::None,
  222. .cpp_decl = clang_decl}};
  223. function_decl.function_id = context.functions().Add(function_info);
  224. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  225. SemIR::SpecificId::None);
  226. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  227. return decl_id;
  228. }
  229. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  230. // the new Carbon namespace declaration `InstId`.
  231. static auto ImportNamespaceDecl(Context& context,
  232. SemIR::NameScopeId parent_scope_id,
  233. SemIR::NameId name_id,
  234. clang::NamespaceDecl* clang_decl)
  235. -> SemIR::InstId {
  236. auto result = AddImportNamespace(
  237. context, GetSingletonType(context, SemIR::NamespaceType::SingletonInstId),
  238. name_id, parent_scope_id, /*import_id=*/SemIR::InstId::None);
  239. context.name_scopes()
  240. .Get(result.name_scope_id)
  241. .set_cpp_decl_context(clang_decl);
  242. return result.inst_id;
  243. }
  244. // Imports a declaration from Clang to Carbon. If successful, returns the
  245. // instruction for the new Carbon declaration.
  246. static auto ImportNameDecl(Context& context, SemIR::LocId loc_id,
  247. SemIR::NameScopeId scope_id, SemIR::NameId name_id,
  248. clang::NamedDecl* clang_decl) -> SemIR::InstId {
  249. if (const auto* clang_function_decl =
  250. clang::dyn_cast<clang::FunctionDecl>(clang_decl)) {
  251. return ImportFunctionDecl(context, loc_id, scope_id, name_id,
  252. clang_function_decl);
  253. }
  254. if (auto* clang_namespace_decl =
  255. clang::dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  256. return ImportNamespaceDecl(context, scope_id, name_id,
  257. clang_namespace_decl);
  258. }
  259. context.TODO(loc_id, llvm::formatv("Unsupported: Declaration type {0}",
  260. clang_decl->getDeclKindName())
  261. .str());
  262. return SemIR::InstId::None;
  263. }
  264. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  265. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  266. -> SemIR::InstId {
  267. auto lookup = ClangLookup(context, loc_id, scope_id, name_id);
  268. if (!lookup) {
  269. return SemIR::InstId::None;
  270. }
  271. DiagnosticAnnotationScope annotate_diagnostics(
  272. &context.emitter(), [&](auto& builder) {
  273. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  274. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  275. builder.Note(loc_id, InCppNameLookup, name_id);
  276. });
  277. if (!lookup->isSingleResult()) {
  278. context.TODO(loc_id,
  279. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  280. "find a single result; LookupResultKind: {0}",
  281. lookup->getResultKind())
  282. .str());
  283. return SemIR::ErrorInst::SingletonInstId;
  284. }
  285. return ImportNameDecl(context, loc_id, scope_id, name_id,
  286. lookup->getFoundDecl());
  287. }
  288. } // namespace Carbon::Check