ScalaFrontendTest.java 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package de.jplag.scala;
  2. import static org.junit.jupiter.api.Assertions.fail;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.stream.Collectors;
  10. import java.util.stream.IntStream;
  11. import java.util.stream.StreamSupport;
  12. import org.junit.jupiter.api.BeforeEach;
  13. import org.junit.jupiter.api.Test;
  14. import org.slf4j.Logger;
  15. import org.slf4j.LoggerFactory;
  16. import de.jplag.Token;
  17. import de.jplag.TokenConstants;
  18. import de.jplag.TokenList;
  19. import de.jplag.TokenPrinter;
  20. class ScalaFrontendTest {
  21. /**
  22. * Test source file that is supposed to produce a complete set of tokens, i.e. all types of tokens.
  23. */
  24. private static final String COMPLETE_TEST_FILE = "Complete.scala";
  25. /**
  26. * Regular expression that describes lines consisting only of whitespace and optionally a line comment.
  27. */
  28. private static final String EMPTY_OR_SINGLE_LINE_COMMENT = "\\s*(//.*|/\\*.*\\*/)?";
  29. /**
  30. * Regular expression that describes lines containing the start of a multiline comment and no code before it.
  31. */
  32. private static final String DELIMITED_COMMENT_START = "\\s*/\\*(?:(?!\\*/).)*$";
  33. /**
  34. * Regular expression that describes lines containing the end of a multiline comment and no more code after that.
  35. */
  36. private static final String DELIMITED_COMMENT_END = ".*\\*/\\s*$";
  37. private static final String EMPTY_STRING = "";
  38. private static final int NOT_SET = -1;
  39. private static final double EPSILON = 1E-6;
  40. private final Logger logger = LoggerFactory.getLogger("Scala frontend test");
  41. private final String[] testFiles = new String[] {"Complete.scala", "Parser.scala"};
  42. private final File testFileLocation = Path.of("src", "test", "resources", "de", "jplag", "scala").toFile();
  43. private Language language;
  44. @BeforeEach
  45. void setup() {
  46. language = new Language();
  47. }
  48. @Test
  49. void parseTestFiles() {
  50. for (String fileName : testFiles) {
  51. TokenList tokens = language.parse(testFileLocation, new String[] {fileName});
  52. String output = TokenPrinter.printTokens(tokens, testFileLocation, List.of(fileName));
  53. logger.info(output);
  54. if (fileName.equals(COMPLETE_TEST_FILE)) {
  55. testTokenCoverage(tokens, fileName);
  56. }
  57. testSourceCoverage(fileName, tokens);
  58. }
  59. }
  60. /**
  61. * Confirms that every type of ScalaToken has a Sting representation associated to it.
  62. */
  63. @Test
  64. void testTokenToString() {
  65. var missingTokens = IntStream.range(0, ScalaTokenConstants.numberOfTokens())
  66. .mapToObj(type -> new ScalaToken(type, EMPTY_STRING, NOT_SET, NOT_SET, NOT_SET))
  67. .filter(token -> token.type2string().contains("UNKNOWN")).toList();
  68. if (!missingTokens.isEmpty()) {
  69. var typeList = missingTokens.stream().map(Token::getType).map(Object::toString).collect(Collectors.joining(", "));
  70. fail("Found token types with no string representation: %s".formatted(typeList));
  71. }
  72. }
  73. /**
  74. * Confirms that the code is covered to a basic extent, i.e. each line of code contains at least one token.
  75. * @param fileName a code sample file name
  76. * @param tokens the TokenList generated from the sample
  77. */
  78. private void testSourceCoverage(String fileName, TokenList tokens) {
  79. File testFile = new File(testFileLocation, fileName);
  80. try {
  81. List<String> lines = Files.readAllLines(testFile.toPath());
  82. // All lines that contain code
  83. var codeLines = new ArrayList<>(getCodeLines(lines));
  84. // All lines that contain token
  85. var tokenLines = IntStream.range(0, tokens.size()).mapToObj(tokens::getToken).mapToInt(Token::getLine).distinct().boxed().toList();
  86. // Keep only lines that have no tokens
  87. codeLines.removeAll(tokenLines);
  88. double coverage = 1.d - (codeLines.size() * 1.d / (codeLines.size() + tokenLines.size()));
  89. if (coverage == 1) {
  90. logger.info("All lines covered.");
  91. } else {
  92. logger.info("Coverage: %.1f%%.".formatted(coverage * 100));
  93. logger.info("Missing lines {}", codeLines);
  94. if (coverage - 0.9 > EPSILON) {
  95. fail("Source coverage is unsatisfactory");
  96. }
  97. }
  98. } catch (IOException exception) {
  99. logger.info("Error while reading test file %s".formatted(fileName), exception);
  100. fail();
  101. }
  102. }
  103. /**
  104. * Gets the line numbers of lines containing actual code, omitting empty lines and comment lines.
  105. * @param lines lines of a code file
  106. * @return an array of the line numbers of code lines
  107. */
  108. private List<Integer> getCodeLines(List<String> lines) {
  109. // This boxed boolean can be accessed from within the lambda method below
  110. var state = new Object() {
  111. boolean insideComment = false;
  112. };
  113. var codeLines = IntStream.rangeClosed(1, lines.size()).sequential().filter(idx -> {
  114. String line = lines.get(idx - 1);
  115. if (line.matches(EMPTY_OR_SINGLE_LINE_COMMENT)) {
  116. return false;
  117. } else if (line.matches(DELIMITED_COMMENT_START)) {
  118. state.insideComment = true;
  119. return false;
  120. } else if (state.insideComment) {
  121. // This fails if code follows after '*/'. If the code is formatted well, this should not happen.
  122. if (line.matches(DELIMITED_COMMENT_END)) {
  123. state.insideComment = false;
  124. }
  125. return false;
  126. }
  127. return true;
  128. });
  129. return codeLines.boxed().toList();
  130. }
  131. /**
  132. * Confirms that all Token types are 'reachable' with a complete code example.
  133. * @param tokens TokenList which is supposed to contain all types of tokens
  134. * @param fileName The file name of the complete code example
  135. */
  136. private void testTokenCoverage(TokenList tokens, String fileName) {
  137. var foundTokens = StreamSupport.stream(tokens.allTokens().spliterator(), true).mapToInt(Token::getType).distinct().boxed().toList();
  138. var allTokens = IntStream.range(0, ScalaTokenConstants.numberOfTokens()).boxed().toList();
  139. allTokens = new ArrayList<>(allTokens);
  140. // Only non-found tokens are left
  141. allTokens.removeAll(foundTokens);
  142. // Exclude SEPARATOR_TOKEN, as it does not occur
  143. allTokens.remove((Integer) (TokenConstants.SEPARATOR_TOKEN));
  144. if (!allTokens.isEmpty()) {
  145. var notFoundTypes = allTokens.stream().map(ScalaTokenConstants::apply).toList();
  146. fail("Some %d token types were not found in the complete code example '%s':\n%s".formatted(notFoundTypes.size(), fileName,
  147. notFoundTypes));
  148. }
  149. }
  150. }