ScalaFrontendTest.java 6.7 KB

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