import_cpp.cpp 13 KB

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