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 <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. }
  18. unsigned short raw_filename_length;
  19. std::memcpy(&raw_filename_length, data, 2);
  20. data += 2;
  21. size -= 2;
  22. std::size_t filename_length = raw_filename_length;
  23. // We need enough data to populate this filename length.
  24. if (size < filename_length) {
  25. return 0;
  26. }
  27. llvm::StringRef filename(reinterpret_cast<const char*>(data),
  28. filename_length);
  29. data += filename_length;
  30. size -= filename_length;
  31. // The rest of the data is the source text.
  32. auto source = SourceBuffer::CreateFromText(
  33. llvm::StringRef(reinterpret_cast<const char*>(data), size), filename);
  34. // Use a real diagnostic emitter to get lazy codepaths to execute.
  35. DiagnosticEmitter emitter = NullDiagnosticEmitter();
  36. // Lex the input.
  37. auto tokens = TokenizedBuffer::Lex(source, emitter);
  38. if (tokens.HasErrors()) {
  39. return 0;
  40. }
  41. // Now parse it into a tree. Note that parsing will (when asserts are enabled)
  42. // walk the entire tree to verify it so we don't have to do that here.
  43. ParseTree tree = ParseTree::Parse(tokens, emitter);
  44. if (tree.HasErrors()) {
  45. return 0;
  46. }
  47. // In the absence of parse errors, we should have exactly as many nodes as
  48. // tokens.
  49. assert(tree.Size() == tokens.Size() && "Unexpected number of tree nodes!");
  50. return 0;
  51. }
  52. } // namespace Carbon