import_cpp.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 <string>
  7. #include "clang/Frontend/TextDiagnosticPrinter.h"
  8. #include "clang/Tooling/Tooling.h"
  9. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/Support/raw_ostream.h"
  12. #include "toolchain/check/context.h"
  13. #include "toolchain/check/diagnostic_helpers.h"
  14. #include "toolchain/diagnostics/diagnostic.h"
  15. #include "toolchain/diagnostics/format_providers.h"
  16. namespace Carbon::Check {
  17. auto ImportCppFile(Context& context, SemIRLoc loc,
  18. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  19. llvm::StringRef file_path, llvm::StringRef code) -> void {
  20. std::string diagnostics_str;
  21. llvm::raw_string_ostream diagnostics_stream(diagnostics_str);
  22. llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagnostic_options(
  23. new clang::DiagnosticOptions());
  24. clang::TextDiagnosticPrinter diagnostics_consumer(diagnostics_stream,
  25. diagnostic_options.get());
  26. // TODO: Share compilation flags with ClangRunner.
  27. auto ast = clang::tooling::buildASTFromCodeWithArgs(
  28. code, {}, file_path, "clang-tool",
  29. std::make_shared<clang::PCHContainerOperations>(),
  30. clang::tooling::getClangStripDependencyFileAdjuster(),
  31. clang::tooling::FileContentMappings(), &diagnostics_consumer, fs);
  32. // TODO: Implement and use a DynamicRecursiveASTVisitor to traverse the AST.
  33. int num_errors = diagnostics_consumer.getNumErrors();
  34. int num_warnings = diagnostics_consumer.getNumWarnings();
  35. if (num_errors > 0) {
  36. // TODO: Remove the warnings part when there are no warnings.
  37. CARBON_DIAGNOSTIC(
  38. CppInteropParseError, Error,
  39. "{0} error{0:s} and {1} warning{1:s} in `Cpp` import `{2}`:\n{3}",
  40. IntAsSelect, IntAsSelect, std::string, std::string);
  41. context.emitter().Emit(loc, CppInteropParseError, num_errors, num_warnings,
  42. file_path.str(), diagnostics_str);
  43. } else if (num_warnings > 0) {
  44. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning,
  45. "{0} warning{0:s} in `Cpp` import `{1}`:\n{2}",
  46. IntAsSelect, std::string, std::string);
  47. context.emitter().Emit(loc, CppInteropParseWarning, num_warnings,
  48. file_path.str(), diagnostics_str);
  49. }
  50. }
  51. } // namespace Carbon::Check