import_cpp.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. // TODO: Implement and use a DynamicRecursiveASTVisitor to traverse the AST.
  66. int num_errors = diagnostics_consumer.getNumErrors();
  67. int num_warnings = diagnostics_consumer.getNumWarnings();
  68. int num_imports = imports.size();
  69. if (num_errors > 0) {
  70. // TODO: Remove the warnings part when there are no warnings.
  71. CARBON_DIAGNOSTIC(
  72. CppInteropParseError, Error,
  73. "{0} error{0:s} and {1} warning{1:s} in {2} `Cpp` import{2:s}:\n{3}",
  74. IntAsSelect, IntAsSelect, IntAsSelect, std::string);
  75. context.emitter().Emit(loc, CppInteropParseError, num_errors, num_warnings,
  76. num_imports, diagnostics_str);
  77. } else if (num_warnings > 0) {
  78. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning,
  79. "{0} warning{0:s} in `Cpp` {1} import{1:s}:\n{2}",
  80. IntAsSelect, IntAsSelect, std::string);
  81. context.emitter().Emit(loc, CppInteropParseWarning, num_warnings,
  82. num_imports, diagnostics_str);
  83. }
  84. return {std::move(ast), !ast || num_errors > 0};
  85. }
  86. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  87. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  88. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  89. -> SemIR::NameScopeId {
  90. auto& import_cpps = context.sem_ir().import_cpps();
  91. import_cpps.Reserve(imports.size());
  92. for (const Parse::Tree::PackagingNames& import : imports) {
  93. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  94. import.node_id),
  95. .library_id = import.library_id});
  96. }
  97. return AddImportNamespaceToScope(
  98. context,
  99. GetSingletonType(context, SemIR::NamespaceType::SingletonInstId),
  100. SemIR::NameId::ForPackageName(cpp_package_id),
  101. SemIR::NameScopeId::Package,
  102. /*diagnose_duplicate_namespace=*/false,
  103. [&]() {
  104. return AddInst<SemIR::ImportCppDecl>(
  105. context,
  106. context.parse_tree().As<Parse::ImportDeclId>(
  107. imports.front().node_id),
  108. {});
  109. })
  110. .add_result.name_scope_id;
  111. }
  112. auto ImportCppFiles(Context& context, llvm::StringRef importing_file_path,
  113. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  114. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs)
  115. -> std::unique_ptr<clang::ASTUnit> {
  116. if (imports.empty()) {
  117. return nullptr;
  118. }
  119. CARBON_CHECK(!context.sem_ir().cpp_ast());
  120. auto [generated_ast, ast_has_error] =
  121. GenerateAst(context, importing_file_path, imports, fs);
  122. PackageNameId package_id = imports.front().package_id;
  123. CARBON_CHECK(
  124. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  125. return import.package_id == package_id;
  126. }));
  127. auto name_scope_id = AddNamespace(context, package_id, imports);
  128. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  129. name_scope.set_is_closed_import(true);
  130. name_scope.set_cpp_decl_context(
  131. generated_ast->getASTContext().getTranslationUnitDecl());
  132. context.sem_ir().set_cpp_ast(generated_ast.get());
  133. if (ast_has_error) {
  134. name_scope.set_has_error();
  135. }
  136. return std::move(generated_ast);
  137. }
  138. // Look ups the given name in the Clang AST in a specific scope. Returns the
  139. // lookup result if lookup was successful.
  140. static auto ClangLookup(Context& context, SemIR::LocId loc_id,
  141. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  142. -> std::optional<clang::LookupResult> {
  143. std::optional<llvm::StringRef> name =
  144. context.names().GetAsStringIfIdentifier(name_id);
  145. if (!name) {
  146. // Special names never exist in C++ code.
  147. return std::nullopt;
  148. }
  149. clang::ASTUnit* ast = context.sem_ir().cpp_ast();
  150. CARBON_CHECK(ast);
  151. clang::Sema& sema = ast->getSema();
  152. clang::LookupResult lookup(
  153. sema,
  154. clang::DeclarationNameInfo(
  155. clang::DeclarationName(
  156. sema.getPreprocessor().getIdentifierInfo(*name)),
  157. clang::SourceLocation()),
  158. clang::Sema::LookupNameKind::LookupOrdinaryName);
  159. bool found = sema.LookupQualifiedName(
  160. lookup, context.name_scopes().Get(scope_id).cpp_decl_context());
  161. if (lookup.isClassLookup()) {
  162. // TODO: To support class lookup, also return the AccessKind for storage.
  163. context.TODO(loc_id, "Unsupported: Lookup in Class");
  164. return std::nullopt;
  165. }
  166. if (!found) {
  167. return std::nullopt;
  168. }
  169. return lookup;
  170. }
  171. // Imports a function declaration from Clang to Carbon. If successful, returns
  172. // the new Carbon function declaration `InstId`.
  173. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  174. SemIR::NameScopeId scope_id,
  175. SemIR::NameId name_id,
  176. const clang::FunctionDecl* clang_decl)
  177. -> SemIR::InstId {
  178. if (clang_decl->isVariadic()) {
  179. context.TODO(loc_id, "Unsupported: Variadic function");
  180. return SemIR::ErrorInst::SingletonInstId;
  181. }
  182. if (!clang_decl->isGlobal()) {
  183. context.TODO(loc_id, "Unsupported: Non-global function");
  184. return SemIR::ErrorInst::SingletonInstId;
  185. }
  186. if (clang_decl->getTemplatedKind() != clang::FunctionDecl::TK_NonTemplate) {
  187. context.TODO(loc_id, "Unsupported: Template function");
  188. return SemIR::ErrorInst::SingletonInstId;
  189. }
  190. if (!clang_decl->param_empty()) {
  191. context.TODO(loc_id, "Unsupported: Function with parameters");
  192. return SemIR::ErrorInst::SingletonInstId;
  193. }
  194. if (!clang_decl->getReturnType()->isVoidType()) {
  195. context.TODO(loc_id, "Unsupported: Function with non-void return type");
  196. return SemIR::ErrorInst::SingletonInstId;
  197. }
  198. auto function_decl = SemIR::FunctionDecl{
  199. SemIR::TypeId::None, SemIR::FunctionId::None, SemIR::InstBlockId::Empty};
  200. auto decl_id = AddPlaceholderInst(
  201. context, SemIR::LocIdAndInst(Parse::NodeId::None, function_decl));
  202. auto function_info = SemIR::Function{
  203. {.name_id = name_id,
  204. .parent_scope_id = scope_id,
  205. .generic_id = SemIR::GenericId::None,
  206. .first_param_node_id = Parse::NodeId::None,
  207. .last_param_node_id = Parse::NodeId::None,
  208. .pattern_block_id = SemIR::InstBlockId::Empty,
  209. .implicit_param_patterns_id = SemIR::InstBlockId::Empty,
  210. .param_patterns_id = SemIR::InstBlockId::Empty,
  211. .call_params_id = SemIR::InstBlockId::Empty,
  212. .is_extern = false,
  213. .extern_library_id = SemIR::LibraryNameId::None,
  214. .non_owning_decl_id = SemIR::InstId::None,
  215. .first_owning_decl_id = decl_id,
  216. .definition_id = SemIR::InstId::None},
  217. {.return_slot_pattern_id = SemIR::InstId::None,
  218. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  219. .self_param_id = SemIR::InstId::None,
  220. .cpp_decl = clang_decl}};
  221. function_decl.function_id = context.functions().Add(function_info);
  222. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  223. SemIR::SpecificId::None);
  224. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  225. return decl_id;
  226. }
  227. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  228. // the new Carbon namespace declaration `InstId`.
  229. static auto ImportNamespaceDecl(Context& context,
  230. SemIR::NameScopeId parent_scope_id,
  231. SemIR::NameId name_id,
  232. clang::NamespaceDecl* clang_decl)
  233. -> SemIR::InstId {
  234. auto result = AddImportNamespace(
  235. context, GetSingletonType(context, SemIR::NamespaceType::SingletonInstId),
  236. name_id, parent_scope_id, /*import_id=*/SemIR::InstId::None);
  237. context.name_scopes()
  238. .Get(result.name_scope_id)
  239. .set_cpp_decl_context(clang_decl);
  240. return result.inst_id;
  241. }
  242. // Imports a declaration from Clang to Carbon. If successful, returns the
  243. // instruction for the new Carbon declaration.
  244. static auto ImportNameDecl(Context& context, SemIR::LocId loc_id,
  245. SemIR::NameScopeId scope_id, SemIR::NameId name_id,
  246. clang::NamedDecl* clang_decl) -> SemIR::InstId {
  247. if (const auto* clang_function_decl =
  248. clang::dyn_cast<clang::FunctionDecl>(clang_decl)) {
  249. return ImportFunctionDecl(context, loc_id, scope_id, name_id,
  250. clang_function_decl);
  251. }
  252. if (auto* clang_namespace_decl =
  253. clang::dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  254. return ImportNamespaceDecl(context, scope_id, name_id,
  255. clang_namespace_decl);
  256. }
  257. context.TODO(loc_id, llvm::formatv("Unsupported: Declaration type {0}",
  258. clang_decl->getDeclKindName())
  259. .str());
  260. return SemIR::InstId::None;
  261. }
  262. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  263. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  264. -> SemIR::InstId {
  265. auto lookup = ClangLookup(context, loc_id, scope_id, name_id);
  266. if (!lookup) {
  267. return SemIR::InstId::None;
  268. }
  269. DiagnosticAnnotationScope annotate_diagnostics(
  270. &context.emitter(), [&](auto& builder) {
  271. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  272. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  273. builder.Note(loc_id, InCppNameLookup, name_id);
  274. });
  275. if (!lookup->isSingleResult()) {
  276. context.TODO(loc_id,
  277. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  278. "find a single result; LookupResultKind: {0}",
  279. lookup->getResultKind())
  280. .str());
  281. return SemIR::ErrorInst::SingletonInstId;
  282. }
  283. return ImportNameDecl(context, loc_id, scope_id, name_id,
  284. lookup->getFoundDecl());
  285. }
  286. } // namespace Carbon::Check