import_cpp.cpp 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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/Tooling/Tooling.h"
  10. #include "common/raw_string_ostream.h"
  11. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  12. #include "llvm/ADT/StringRef.h"
  13. #include "llvm/Support/raw_ostream.h"
  14. #include "toolchain/check/context.h"
  15. #include "toolchain/check/diagnostic_helpers.h"
  16. #include "toolchain/check/import.h"
  17. #include "toolchain/check/inst.h"
  18. #include "toolchain/check/type.h"
  19. #include "toolchain/diagnostics/diagnostic.h"
  20. #include "toolchain/diagnostics/format_providers.h"
  21. #include "toolchain/sem_ir/name_scope.h"
  22. namespace Carbon::Check {
  23. // Generates C++ file contents to #include all requested imports.
  24. static auto GenerateCppIncludesHeaderCode(
  25. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  26. -> std::string {
  27. std::string code;
  28. llvm::raw_string_ostream code_stream(code);
  29. for (const Parse::Tree::PackagingNames& import : imports) {
  30. code_stream << "#include \""
  31. << FormatEscaped(
  32. context.string_literal_values().Get(import.library_id))
  33. << "\"\n";
  34. }
  35. return code;
  36. }
  37. // Returns an AST for the C++ imports and a bool that represents whether
  38. // compilation errors where encountered or the generated AST is null due to an
  39. // error.
  40. // TODO: Consider to always have a (non-null) AST.
  41. static auto GenerateAst(Context& context, llvm::StringRef importing_file_path,
  42. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  43. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs)
  44. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  45. // TODO: Use all import locations by referring each Clang diagnostic to the
  46. // relevant import.
  47. SemIRLoc loc = imports.back().node_id;
  48. std::string diagnostics_str;
  49. llvm::raw_string_ostream diagnostics_stream(diagnostics_str);
  50. llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnostic_options(
  51. new clang::DiagnosticOptions());
  52. clang::TextDiagnosticPrinter diagnostics_consumer(diagnostics_stream,
  53. diagnostic_options.get());
  54. // TODO: Share compilation flags with ClangRunner.
  55. auto ast = clang::tooling::buildASTFromCodeWithArgs(
  56. GenerateCppIncludesHeaderCode(context, imports), {},
  57. (importing_file_path + ".generated.cpp_imports.h").str(), "clang-tool",
  58. std::make_shared<clang::PCHContainerOperations>(),
  59. clang::tooling::getClangStripDependencyFileAdjuster(),
  60. clang::tooling::FileContentMappings(), &diagnostics_consumer, fs);
  61. // TODO: Implement and use a DynamicRecursiveASTVisitor to traverse the AST.
  62. int num_errors = diagnostics_consumer.getNumErrors();
  63. int num_warnings = diagnostics_consumer.getNumWarnings();
  64. int num_imports = imports.size();
  65. if (num_errors > 0) {
  66. // TODO: Remove the warnings part when there are no warnings.
  67. CARBON_DIAGNOSTIC(
  68. CppInteropParseError, Error,
  69. "{0} error{0:s} and {1} warning{1:s} in {2} `Cpp` import{2:s}:\n{3}",
  70. IntAsSelect, IntAsSelect, IntAsSelect, std::string);
  71. context.emitter().Emit(loc, CppInteropParseError, num_errors, num_warnings,
  72. num_imports, diagnostics_str);
  73. } else if (num_warnings > 0) {
  74. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning,
  75. "{0} warning{0:s} in `Cpp` {1} import{1:s}:\n{2}",
  76. IntAsSelect, IntAsSelect, std::string);
  77. context.emitter().Emit(loc, CppInteropParseWarning, num_warnings,
  78. num_imports, diagnostics_str);
  79. }
  80. return {std::move(ast), !ast || num_errors > 0};
  81. }
  82. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  83. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  84. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  85. -> SemIR::NameScopeId {
  86. auto& import_cpps = context.sem_ir().import_cpps();
  87. import_cpps.Reserve(imports.size());
  88. for (const Parse::Tree::PackagingNames& import : imports) {
  89. import_cpps.Add(
  90. {.node_id = import.node_id, .library_id = import.library_id});
  91. }
  92. return AddImportNamespace(
  93. context,
  94. GetSingletonType(context, SemIR::NamespaceType::SingletonInstId),
  95. SemIR::NameId::ForPackageName(cpp_package_id),
  96. SemIR::NameScopeId::Package,
  97. /*diagnose_duplicate_namespace=*/false,
  98. [&]() {
  99. return AddInst<SemIR::ImportCppDecl>(
  100. context, imports.front().node_id, {});
  101. })
  102. .name_scope_id;
  103. }
  104. auto ImportCppFiles(Context& context, llvm::StringRef importing_file_path,
  105. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  106. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs)
  107. -> void {
  108. if (imports.empty()) {
  109. return;
  110. }
  111. auto [ast, ast_has_error] =
  112. GenerateAst(context, importing_file_path, imports, fs);
  113. PackageNameId package_id = imports.front().package_id;
  114. CARBON_CHECK(
  115. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  116. return import.package_id == package_id;
  117. }));
  118. auto name_scope_id = AddNamespace(context, package_id, imports);
  119. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  120. name_scope.set_is_closed_import(true);
  121. if (ast_has_error) {
  122. name_scope.set_has_error();
  123. }
  124. }
  125. } // namespace Carbon::Check