parse_tree_fuzzer.cpp 2.0 KB

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