parse_tree_fuzzer.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. auto source = SourceBuffer::CreateFromText(
  18. llvm::StringRef(reinterpret_cast<const char*>(data), size));
  19. // Lex the input.
  20. auto tokens = TokenizedBuffer::Lex(source, NullDiagnosticConsumer());
  21. if (tokens.HasErrors()) {
  22. return 0;
  23. }
  24. // Now parse it into a tree. Note that parsing will (when asserts are enabled)
  25. // walk the entire tree to verify it so we don't have to do that here.
  26. ParseTree tree = ParseTree::Parse(tokens, NullDiagnosticConsumer());
  27. if (tree.HasErrors()) {
  28. return 0;
  29. }
  30. // In the absence of parse errors, we should have exactly as many nodes as
  31. // tokens.
  32. CHECK(tree.Size() == tokens.Size()) << "Unexpected number of tree nodes!";
  33. return 0;
  34. }
  35. } // namespace Carbon::Testing