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