parse_tree_fuzzer.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 "diagnostics/diagnostic_emitter.h"
  8. #include "diagnostics/null_diagnostics.h"
  9. #include "lexer/tokenized_buffer.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "parser/parse_tree.h"
  12. namespace Carbon {
  13. // NOLINTNEXTLINE: Match the documented fuzzer entry point declaration style.
  14. extern "C" int LLVMFuzzerTestOneInput(const unsigned char* data,
  15. std::size_t size) {
  16. // We need two bytes of data to compute a file name length.
  17. if (size < 2) {
  18. return 0;
  19. }
  20. uint16_t raw_filename_length;
  21. std::memcpy(&raw_filename_length, data, 2);
  22. data += 2;
  23. size -= 2;
  24. std::size_t filename_length = raw_filename_length;
  25. // We need enough data to populate this filename length.
  26. if (size < filename_length) {
  27. return 0;
  28. }
  29. llvm::StringRef filename(reinterpret_cast<const char*>(data),
  30. filename_length);
  31. data += filename_length;
  32. size -= filename_length;
  33. // The rest of the data is the source text.
  34. auto source = SourceBuffer::CreateFromText(
  35. llvm::StringRef(reinterpret_cast<const char*>(data), size), filename);
  36. // Lex the input.
  37. auto tokens = TokenizedBuffer::Lex(source, NullDiagnosticConsumer());
  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, NullDiagnosticConsumer());
  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