import_cpp.cpp 5.6 KB

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