parse_tree_fuzzer.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 <cstddef>
  5. #include <cstdint>
  6. #include <cstring>
  7. #include "common/check.h"
  8. #include "llvm/ADT/StringRef.h"
  9. #include "toolchain/diagnostics/diagnostic_emitter.h"
  10. #include "toolchain/diagnostics/null_diagnostics.h"
  11. #include "toolchain/lexer/tokenized_buffer.h"
  12. #include "toolchain/parser/parse_tree.h"
  13. namespace Carbon::Testing {
  14. // NOLINTNEXTLINE: Match the documented fuzzer entry point declaration style.
  15. extern "C" int LLVMFuzzerTestOneInput(const unsigned char* data,
  16. std::size_t size) {
  17. // We need two bytes of data to compute a file name length.
  18. if (size < 2) {
  19. return 0;
  20. }
  21. uint16_t raw_filename_length;
  22. std::memcpy(&raw_filename_length, data, 2);
  23. data += 2;
  24. size -= 2;
  25. std::size_t filename_length = raw_filename_length;
  26. // We need enough data to populate this filename length.
  27. if (size < filename_length) {
  28. return 0;
  29. }
  30. llvm::StringRef filename(reinterpret_cast<const char*>(data),
  31. filename_length);
  32. data += filename_length;
  33. size -= filename_length;
  34. // The rest of the data is the source text.
  35. auto source = SourceBuffer::CreateFromText(
  36. llvm::StringRef(reinterpret_cast<const char*>(data), size), filename);
  37. // Lex the input.
  38. auto tokens = TokenizedBuffer::Lex(source, NullDiagnosticConsumer());
  39. if (tokens.HasErrors()) {
  40. return 0;
  41. }
  42. // Now parse it into a tree. Note that parsing will (when asserts are enabled)
  43. // walk the entire tree to verify it so we don't have to do that here.
  44. ParseTree tree = ParseTree::Parse(tokens, NullDiagnosticConsumer());
  45. if (tree.HasErrors()) {
  46. return 0;
  47. }
  48. // In the absence of parse errors, we should have exactly as many nodes as
  49. // tokens.
  50. CHECK(tree.Size() == tokens.Size()) << "Unexpected number of tree nodes!";
  51. return 0;
  52. }
  53. } // namespace Carbon::Testing