fuzzer_util.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 "explorer/fuzzing/fuzzer_util.h"
  5. #include <google/protobuf/text_format.h>
  6. #include "common/check.h"
  7. #include "common/error.h"
  8. #include "common/fuzzing/proto_to_carbon.h"
  9. #include "explorer/interpreter/exec_program.h"
  10. #include "explorer/interpreter/trace_stream.h"
  11. #include "explorer/syntax/parse.h"
  12. #include "explorer/syntax/prelude.h"
  13. #include "llvm/Support/FileSystem.h"
  14. #include "llvm/Support/Path.h"
  15. #include "tools/cpp/runfiles/runfiles.h"
  16. namespace Carbon {
  17. auto GetRunfilesFile(const std::string& file) -> ErrorOr<std::string> {
  18. using bazel::tools::cpp::runfiles::Runfiles;
  19. std::string error;
  20. // `Runfiles::Create()` fails if passed an empty `argv0`.
  21. std::unique_ptr<Runfiles> runfiles(Runfiles::Create(
  22. /*argv0=*/llvm::sys::fs::getMainExecutable(nullptr, nullptr), &error));
  23. if (runfiles == nullptr) {
  24. return Error(error);
  25. }
  26. std::string full_path = runfiles->Rlocation(file);
  27. if (!llvm::sys::fs::exists(full_path)) {
  28. return ErrorBuilder() << full_path << " doesn't exist";
  29. }
  30. return full_path;
  31. }
  32. auto ParseAndExecute(const Fuzzing::Carbon& carbon) -> ErrorOr<int> {
  33. const std::string source = ProtoToCarbon(carbon, /*maybe_add_main=*/true);
  34. Arena arena;
  35. CARBON_ASSIGN_OR_RETURN(AST ast,
  36. ParseFromString(&arena, "Fuzzer.carbon", source,
  37. /*parser_debug=*/false));
  38. const ErrorOr<std::string> prelude_path =
  39. GetRunfilesFile("carbon/explorer/data/prelude.carbon");
  40. // Can't do anything without a prelude, so it's a fatal error.
  41. CARBON_CHECK(prelude_path.ok()) << prelude_path.error();
  42. AddPrelude(*prelude_path, &arena, &ast.declarations,
  43. &ast.num_prelude_declarations);
  44. TraceStream trace_stream;
  45. // Use llvm::nulls() to suppress output from the Print intrinsic.
  46. CARBON_ASSIGN_OR_RETURN(
  47. ast, AnalyzeProgram(&arena, ast, &trace_stream, &llvm::nulls()));
  48. return ExecProgram(&arena, ast, &trace_stream, &llvm::nulls());
  49. }
  50. } // namespace Carbon