test-cpp-parser.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2021, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/LexicalPath.h>
  7. #include <LibCore/DirIterator.h>
  8. #include <LibCore/Stream.h>
  9. #include <LibCpp/Parser.h>
  10. #include <LibTest/TestCase.h>
  11. #include <unistd.h>
  12. constexpr char TESTS_ROOT_DIR[] = "/home/anon/Tests/cpp-tests/parser";
  13. static DeprecatedString read_all(DeprecatedString const& path)
  14. {
  15. auto file = MUST(Core::Stream::File::open(path, Core::Stream::OpenMode::Read));
  16. auto file_size = MUST(file->size());
  17. auto content = MUST(ByteBuffer::create_uninitialized(file_size));
  18. MUST(file->read_entire_buffer(content.bytes()));
  19. return DeprecatedString { content.bytes() };
  20. }
  21. TEST_CASE(test_regression)
  22. {
  23. Core::DirIterator directory_iterator(TESTS_ROOT_DIR, Core::DirIterator::Flags::SkipDots);
  24. while (directory_iterator.has_next()) {
  25. auto file_path = directory_iterator.next_full_path();
  26. auto path = LexicalPath { file_path };
  27. if (!path.has_extension(".cpp"sv))
  28. continue;
  29. outln("Checking {}...", path.basename());
  30. auto ast_file_path = DeprecatedString::formatted("{}.ast", file_path.substring(0, file_path.length() - sizeof(".cpp") + 1));
  31. auto source = read_all(file_path);
  32. auto target_ast = read_all(ast_file_path);
  33. StringView source_view(source);
  34. Cpp::Preprocessor preprocessor(file_path, source_view);
  35. Cpp::Parser parser(preprocessor.process_and_lex(), file_path);
  36. auto root = parser.parse();
  37. EXPECT(parser.errors().is_empty());
  38. int pipefd[2] = {};
  39. if (pipe(pipefd) < 0) {
  40. perror("pipe");
  41. exit(1);
  42. }
  43. FILE* input_stream = fdopen(pipefd[0], "r");
  44. FILE* output_stream = fdopen(pipefd[1], "w");
  45. root->dump(output_stream);
  46. fclose(output_stream);
  47. ByteBuffer buffer;
  48. while (!feof(input_stream)) {
  49. char chunk[4096];
  50. size_t size = fread(chunk, sizeof(char), sizeof(chunk), input_stream);
  51. if (size == 0)
  52. break;
  53. buffer.append(chunk, size);
  54. }
  55. fclose(input_stream);
  56. DeprecatedString content { reinterpret_cast<char const*>(buffer.data()), buffer.size() };
  57. auto equal = content == target_ast;
  58. EXPECT(equal);
  59. }
  60. }