import_cpp.cpp 11 KB

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