test-cpp-parser.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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/File.h>
  9. #include <LibCpp/Parser.h>
  10. #include <LibTest/TestCase.h>
  11. #include <fcntl.h>
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <unistd.h>
  15. constexpr char TESTS_ROOT_DIR[] = "/home/anon/cpp-tests/parser";
  16. static String read_all(const String& path)
  17. {
  18. auto result = Core::File::open(path, Core::OpenMode::ReadOnly);
  19. VERIFY(!result.is_error());
  20. auto content = result.value()->read_all();
  21. return { reinterpret_cast<const char*>(content.data()), content.size() };
  22. }
  23. TEST_CASE(test_regression)
  24. {
  25. Core::DirIterator directory_iterator(TESTS_ROOT_DIR, Core::DirIterator::Flags::SkipDots);
  26. while (directory_iterator.has_next()) {
  27. auto file_path = directory_iterator.next_full_path();
  28. auto path = LexicalPath { file_path };
  29. if (!path.has_extension(".cpp"))
  30. continue;
  31. outln("Checking {}...", path.basename());
  32. auto ast_file_path = String::formatted("{}.ast", file_path.substring(0, file_path.length() - sizeof(".cpp") + 1));
  33. auto source = read_all(file_path);
  34. auto target_ast = read_all(ast_file_path);
  35. StringView source_view(source);
  36. Cpp::Preprocessor preprocessor(file_path, source_view);
  37. Cpp::Parser parser(preprocessor.process_and_lex(), file_path);
  38. auto root = parser.parse();
  39. EXPECT(parser.errors().is_empty());
  40. int pipefd[2] = {};
  41. if (pipe(pipefd) < 0) {
  42. perror("pipe");
  43. exit(1);
  44. }
  45. FILE* input_stream = fdopen(pipefd[0], "r");
  46. FILE* output_stream = fdopen(pipefd[1], "w");
  47. root->dump(output_stream);
  48. fclose(output_stream);
  49. ByteBuffer buffer;
  50. while (!feof(input_stream)) {
  51. char chunk[4096];
  52. size_t size = fread(chunk, sizeof(char), sizeof(chunk), input_stream);
  53. if (size == 0)
  54. break;
  55. buffer.append(chunk, size);
  56. }
  57. fclose(input_stream);
  58. String content { reinterpret_cast<const char*>(buffer.data()), buffer.size() };
  59. auto equal = content == target_ast;
  60. EXPECT(equal);
  61. }
  62. }