Просмотр исходного кода

Merge branch 'master' into report-viewer-fix

Sebastian Hahner 4 лет назад
Родитель
Сommit
dc1bf0872c
88 измененных файлов с 1824 добавлено и 1331 удалено
  1. 36 22
      README.md
  2. 30 24
      cli/src/main/java/de/jplag/CLI.java
  3. 2 4
      cli/src/main/java/de/jplag/CommandLineArgument.java
  4. 2 2
      cli/src/test/java/de/jplag/cli/BaseCodeOptionTest.java
  5. 4 4
      cli/src/test/java/de/jplag/cli/SimiliarityThresholdTest.java
  6. 6 8
      core/src/main/java/de/jplag/JPlagComparison.java
  7. 8 9
      core/src/main/java/de/jplag/JPlagResult.java
  8. 16 33
      core/src/main/java/de/jplag/Submission.java
  9. 2 2
      core/src/main/java/de/jplag/SubmissionSet.java
  10. 18 98
      core/src/main/java/de/jplag/SubmissionSetBuilder.java
  11. 143 75
      core/src/main/java/de/jplag/options/JPlagOptions.java
  12. 2 2
      core/src/main/java/de/jplag/options/SimilarityMetric.java
  13. 0 13
      core/src/main/java/de/jplag/options/Verbosity.java
  14. 8 2
      core/src/main/java/de/jplag/reporting/jsonfactory/ComparisonReportWriter.java
  15. 3 3
      core/src/main/java/de/jplag/reporting/reportobject/ReportObjectFactory.java
  16. 2 2
      core/src/main/java/de/jplag/reporting/reportobject/model/ComparisonReport.java
  17. 1 1
      core/src/main/java/de/jplag/reporting/reportobject/model/TopComparison.java
  18. 2 2
      core/src/main/java/de/jplag/strategy/SubmissionTuple.java
  19. 4 5
      core/src/main/resources/de/jplag/messages.properties
  20. 46 17
      core/src/test/java/de/jplag/BaseCodeTest.java
  21. 49 0
      core/src/test/java/de/jplag/LegacyBaseCodeParallelComparisonTest.java
  22. 75 0
      core/src/test/java/de/jplag/LegacyBaseCodeTest.java
  23. 1 1
      core/src/test/java/de/jplag/NewJavaFeaturesTest.java
  24. 15 23
      core/src/test/java/de/jplag/ParallelComparisonTest.java
  25. 5 4
      core/src/test/java/de/jplag/TestBase.java
  26. 1 1
      core/src/test/java/de/jplag/special/VolumeTest.java
  27. 7 0
      core/src/test/resources/de/jplag/samples/SubdirectoryBase/src/SimpleDuplicate.java
  28. 11 0
      core/src/test/resources/de/jplag/samples/SubdirectoryDuplicate/A/src/SimpleDuplicate.java
  29. 12 0
      core/src/test/resources/de/jplag/samples/SubdirectoryDuplicate/B/src/SimpleDuplicate.java
  30. 7 0
      core/src/test/resources/de/jplag/samples/SubdirectoryDuplicate/Base/src/SimpleDuplicate.java
  31. 5 2
      endtoend-testing/src/test/java/de/jplag/endtoend/EndToEndSuiteTest.java
  32. 317 317
      endtoend-testing/src/test/resources/results/java/sortAlgo.json
  33. 0 8
      language-api/src/main/java/de/jplag/AbstractParser.java
  34. 5 10
      language-api/src/main/java/de/jplag/Language.java
  35. 1 1
      language-api/src/main/java/de/jplag/LanguageLoader.java
  36. 87 0
      language-api/src/main/java/de/jplag/ParsingException.java
  37. 6 4
      language-api/src/main/java/de/jplag/Token.java
  38. 7 10
      language-api/src/main/java/de/jplag/TokenPrinter.java
  39. 23 22
      language-api/src/test/java/de/jplag/TokenPrinterTest.java
  40. 7 6
      language-testutils/src/test/java/de/jplag/testutils/TokenUtils.java
  41. 4 7
      languages/cpp/src/main/java/de/jplag/cpp/Language.java
  42. 7 8
      languages/cpp/src/main/java/de/jplag/cpp/Scanner.java
  43. 10 9
      languages/cpp/src/main/javacc/CPP.jj
  44. 12 17
      languages/csharp/src/main/java/de/jplag/csharp/CSharpParserAdapter.java
  45. 4 8
      languages/csharp/src/main/java/de/jplag/csharp/Language.java
  46. 4 3
      languages/csharp/src/test/java/de/jplag/csharp/MinimalCSharpTest.java
  47. 3 2
      languages/emf-metamodel-dynamic/src/main/java/de/jplag/emf/dynamic/DynamicMetamodelToken.java
  48. 8 5
      languages/emf-metamodel-dynamic/src/test/java/de/jplag/emf/dynamic/MinimalDynamicMetamodelTest.java
  49. 4 8
      languages/emf-metamodel/src/main/java/de/jplag/emf/Language.java
  50. 7 6
      languages/emf-metamodel/src/main/java/de/jplag/emf/MetamodelToken.java
  51. 14 15
      languages/emf-metamodel/src/main/java/de/jplag/emf/parser/EcoreParser.java
  52. 4 5
      languages/emf-metamodel/src/main/java/de/jplag/emf/util/EMFUtil.java
  53. 5 5
      languages/emf-metamodel/src/main/java/de/jplag/emf/util/MetamodelTreeView.java
  54. 8 5
      languages/emf-metamodel/src/test/java/de/jplag/emf/MinimalMetamodelTest.java
  55. 9 12
      languages/golang/src/main/java/de/jplag/golang/GoParserAdapter.java
  56. 4 8
      languages/golang/src/main/java/de/jplag/golang/Language.java
  57. 4 2
      languages/golang/src/test/java/de/jplag/golang/GoLanguageTest.java
  58. 27 25
      languages/java/src/main/java/de/jplag/java/JavacAdapter.java
  59. 4 8
      languages/java/src/main/java/de/jplag/java/Language.java
  60. 6 11
      languages/java/src/main/java/de/jplag/java/Parser.java
  61. 18 6
      languages/java/src/main/java/de/jplag/java/TokenGeneratingTreeScanner.java
  62. 11 15
      languages/kotlin/src/main/java/de/jplag/kotlin/KotlinParserAdapter.java
  63. 4 7
      languages/kotlin/src/main/java/de/jplag/kotlin/Language.java
  64. 4 2
      languages/kotlin/src/test/java/de/jplag/kotlin/KotlinLanguageTest.java
  65. 4 7
      languages/python-3/src/main/java/de/jplag/python3/Language.java
  66. 13 25
      languages/python-3/src/main/java/de/jplag/python3/Parser.java
  67. 4 7
      languages/rlang/src/main/java/de/jplag/rlang/Language.java
  68. 12 17
      languages/rlang/src/main/java/de/jplag/rlang/RParserAdapter.java
  69. 4 2
      languages/rlang/src/test/java/de/jplag/rlang/RLanguageTest.java
  70. 4 8
      languages/rust/src/main/java/de/jplag/rust/Language.java
  71. 12 17
      languages/rust/src/main/java/de/jplag/rust/RustParserAdapter.java
  72. 4 2
      languages/rust/src/test/java/de/jplag/rust/RustLanguageTest.java
  73. 3 5
      languages/scala/src/main/scala/de/jplag/scala/Language.scala
  74. 8 17
      languages/scala/src/main/scala/de/jplag/scala/Parser.scala
  75. 2 1
      languages/scala/src/test/java/de/jplag/scala/ScalaLanguageTest.java
  76. 4 7
      languages/scheme/src/main/java/de/jplag/scheme/Language.java
  77. 7 8
      languages/scheme/src/main/java/de/jplag/scheme/Parser.java
  78. 10 10
      languages/scheme/src/main/javacc/Scheme.jj
  79. 4 7
      languages/text/src/main/java/de/jplag/text/Language.java
  80. 11 19
      languages/text/src/main/java/de/jplag/text/ParserAdapter.java
  81. 12 11
      languages/text/src/test/java/jplag/text/TextLanguageTest.java
  82. 526 206
      report-viewer/package-lock.json
  83. 5 5
      report-viewer/package.json
  84. 6 6
      report-viewer/src/components/ComparisonsTable.vue
  85. 5 5
      report-viewer/src/model/Comparison.ts
  86. 1 1
      report-viewer/src/model/ComparisonListElement.ts
  87. 1 1
      report-viewer/src/model/factories/OverviewFactory.ts
  88. 1 1
      report-viewer/src/views/ComparisonView.vue

+ 36 - 22
README.md

@@ -59,28 +59,42 @@ JPlag can either be used via the CLI or directly via its Java API. For more info
 *Note that the [legacy CLI](https://github.com/jplag/jplag/blob/legacy/README.md) is varying slightly.*
 
 ```
-JPlag - Detecting Software Plagiarism
-
-Usage: JPlag [ options ] [ <root-dir> ... ] [ -new <new-dir> ... ] [ -old <old-dir> ... ]
- <root-dir>        Root-directory with submissions to check for plagiarism
- <new-dir>         Root-directory with submissions to check for plagiarism
- <old-dir>         Root-directory with prior submissions to compare against
+positional arguments:
+  rootDir                Root-directory with submissions to check for plagiarism
 
 named arguments:
-  -h, --help       show this help message and exit
-  -l               {java,python3,cpp,csharp,golang,kotlin,rlang,rust,scala,text,scheme,emf-metamodel,emf-metamodel-dynamic} Select the language to parse the submissions (default: java)
-  -bc BC           Path of the directory containing the base code (common framework used in all submissions)
-  -v               {quiet,long} Verbosity of the logging (default: quiet)
-  -d               Debug parser. Non-parsable files will be stored (default: false)
-  -S S             Look in directories <root-dir>/*/<dir> for programs
-  -p P             comma-separated list of all filename suffixes that are included
-  -x X             All files named in this file will be ignored in the comparison (line-separated list)
-  -t T             Tunes the comparison sensitivity by adjusting the minimum token  required  to be counted as a matching section. A smaller
-                        <n> increases the sensitivity but might lead to more false-positives
-  -m M             Comparison similarity threshold [0-100]: All comparisons above this threshold will be saved (default: 0.0)
-  -n N             The maximum number of comparisons that will be shown in the  generated report, if set to -1 all comparisons will be shown
-                        (default: 30)
-  -r R             Name of the directory in which the comparison results will be stored (default: result)
+  -h, --help             show this help message and exit
+  -new NEW [NEW ...]     Root-directory with submissions to check for plagiarism (same as the root directory)
+  -old OLD [OLD ...]     Root-directory with prior submissions to compare against
+  -l {cpp,csharp,emf-metamodel,emf-metamodel-dynamic,go,java,kotlin,python3,rlang,scala,scheme,text}
+                         Select the language to parse the submissions (default: java)
+  -bc BC                 Path of  the  directory  containing  the  base  code  (common  framework  used  in  all
+                         submissions)
+  -t T                   Tunes the comparison sensitivity by adjusting the  minimum token required to be counted
+                         as a matching section. A smaller <n>  increases  the sensitivity but might lead to more
+                         false-positives
+  -n N                   The maximum number of comparisons that will  be  shown  in the generated report, if set
+                         to -1 all comparisons will be shown (default: 30)
+  -r R                   Name of the directory in which the comparison results will be stored (default: result)
+
+Advanced:
+  -d                     Debug parser. Non-parsable files will be stored (default: false)
+  -s S                   Look in directories <root-dir>/*/<dir> for programs
+  -p P                   comma-separated list of all filename suffixes that are included
+  -x X                   All files named in this file will be ignored in the comparison (line-separated list)
+  -m M                   Comparison similarity threshold [0.0-1.0]:  All  comparisons  above this threshold will
+                         be saved (default: 0.0)
+
+Clustering:
+  --cluster-skip         Skips the clustering (default: false)
+  --cluster-alg {AGGLOMERATIVE,SPECTRAL}
+                         Which clustering algorithm to use. Agglomerative  merges similar submissions bottom up.
+                         Spectral clustering is  combined  with  Bayesian  Optimization  to  execute the k-Means
+                         clustering  algorithm  multiple   times,   hopefully   finding   a   "good"  clustering
+                         automatically. (default: spectral)
+  --cluster-metric {AVG,MIN,MAX,INTERSECTION}
+                         The metric used for clustering. AVG  is  intersection  over  union, MAX can expose some
+                         attempts of obfuscation. (default: MAX)
 ```
 
 ### Java API
@@ -88,8 +102,8 @@ named arguments:
 The new API makes it easy to integrate JPlag's plagiarism detection into external Java projects:
 
 ```java
-JPlagOptions options = new JPlagOptions(List.of("/path/to/rootDir"), List.of(), LanguageOption.JAVA);
-options.setBaseCodeSubmissionName("template");
+Language language = LanguageLoader.getLanguage(Language.IDENTIFIER).orElseThrow();
+JPlagOptions options = new JPlagOptions(language, List.of("/path/to/rootDir"), List.of()).withBaseCodeSubmissionPath("template");
 
 JPlag jplag = new JPlag(options);
 JPlagResult result = jplag.run();

+ 30 - 24
cli/src/main/java/de/jplag/CLI.java

@@ -27,13 +27,14 @@ import static de.jplag.CommandLineArgument.SHOWN_COMPARISONS;
 import static de.jplag.CommandLineArgument.SIMILARITY_THRESHOLD;
 import static de.jplag.CommandLineArgument.SUBDIRECTORY;
 import static de.jplag.CommandLineArgument.SUFFIXES;
-import static de.jplag.CommandLineArgument.VERBOSITY;
 
+import java.io.File;
 import java.security.SecureRandom;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Random;
+import java.util.stream.Collectors;
 
 import net.sourceforge.argparse4j.ArgumentParsers;
 import net.sourceforge.argparse4j.inf.ArgumentParser;
@@ -49,7 +50,6 @@ import de.jplag.clustering.Preprocessing;
 import de.jplag.exceptions.ExitException;
 import de.jplag.logger.CollectedLoggerFactory;
 import de.jplag.options.JPlagOptions;
-import de.jplag.options.Verbosity;
 import de.jplag.reporting.reportobject.ReportObjectFactory;
 
 /**
@@ -58,7 +58,7 @@ import de.jplag.reporting.reportobject.ReportObjectFactory;
  */
 public final class CLI {
 
-    private static final Logger logger = LoggerFactory.getLogger(CLI.class);
+    private static final Logger logger = LoggerFactory.getLogger("JPlag");
 
     private static final Random RANDOM = new SecureRandom();
 
@@ -83,14 +83,13 @@ public final class CLI {
             CLI cli = new CLI();
             Namespace arguments = cli.parseArguments(args);
             JPlagOptions options = cli.buildOptionsFromArguments(arguments);
-            JPlag program = new JPlag(options);
-            logger.info("JPlag initialized");
-            JPlagResult result = program.run();
+            JPlag jplag = new JPlag(options);
+            logger.debug("JPlag initialized");
+            JPlagResult result = jplag.run();
             ReportObjectFactory reportObjectFactory = new ReportObjectFactory();
             reportObjectFactory.createAndSaveReport(result, arguments.getString(RESULT_FOLDER.flagWithoutDash()));
-
         } catch (ExitException exception) {
-            logger.error(exception.getMessage(), exception);
+            logger.error(exception.getMessage()); // do not pass exception here to keep log clean
             finalizeLogger();
             System.exit(1);
         }
@@ -142,19 +141,30 @@ public final class CLI {
         }
 
         // Collect the root directories.
-        List<String> submissionDirectories = new ArrayList<>();
-        List<String> oldSubmissionDirectories = new ArrayList<>();
-        addAllMultiValueArgument(ROOT_DIRECTORY.getListFrom(namespace), submissionDirectories);
-        addAllMultiValueArgument(NEW_DIRECTORY.getListFrom(namespace), submissionDirectories);
-        addAllMultiValueArgument(OLD_DIRECTORY.getListFrom(namespace), oldSubmissionDirectories);
+        List<String> submissionDirectoryPaths = new ArrayList<>();
+        List<String> oldSubmissionDirectoryPaths = new ArrayList<>();
+        addAllMultiValueArgument(ROOT_DIRECTORY.getListFrom(namespace), submissionDirectoryPaths);
+        addAllMultiValueArgument(NEW_DIRECTORY.getListFrom(namespace), submissionDirectoryPaths);
+        addAllMultiValueArgument(OLD_DIRECTORY.getListFrom(namespace), oldSubmissionDirectoryPaths);
+        var submissionDirectories = submissionDirectoryPaths.stream().map(File::new).collect(Collectors.toSet());
+        var oldSubmissionDirectories = oldSubmissionDirectoryPaths.stream().map(File::new).collect(Collectors.toSet());
 
         var language = LanguageLoader.getLanguage(LANGUAGE.getFrom(namespace)).orElseThrow();
         ClusteringOptions clusteringOptions = getClusteringOptions(namespace);
 
-        return new JPlagOptions(language, MIN_TOKEN_MATCH.getFrom(namespace), submissionDirectories, oldSubmissionDirectories,
-                BASE_CODE.getFrom(namespace), SUBDIRECTORY.getFrom(namespace), Arrays.stream(fileSuffixes).toList(), EXCLUDE_FILE.getFrom(namespace),
+        JPlagOptions options = new JPlagOptions(language, MIN_TOKEN_MATCH.getFrom(namespace), submissionDirectories, oldSubmissionDirectories, null,
+                SUBDIRECTORY.getFrom(namespace), Arrays.stream(fileSuffixes).toList(), EXCLUDE_FILE.getFrom(namespace),
                 JPlagOptions.DEFAULT_SIMILARITY_METRIC, SIMILARITY_THRESHOLD.getFrom(namespace), SHOWN_COMPARISONS.getFrom(namespace),
-                clusteringOptions, Verbosity.fromOption(VERBOSITY.getFrom(namespace)), DEBUG.getFrom(namespace));
+                clusteringOptions, DEBUG.getFrom(namespace));
+
+        String baseCodePath = BASE_CODE.getFrom(namespace);
+        File baseCodeDirectory = baseCodePath == null ? null : new File(baseCodePath);
+        if (baseCodeDirectory == null || baseCodeDirectory.exists()) {
+            return options.withBaseCodeSubmissionDirectory(baseCodeDirectory);
+        } else {
+            logger.warn("Using legacy partial base code API. Please migrate to new full path base code API.");
+            return options.withBaseCodeSubmissionName(baseCodePath);
+        }
     }
 
     private static ClusteringOptions getClusteringOptions(Namespace namespace) {
@@ -191,15 +201,11 @@ public final class CLI {
             clusteringOptions = clusteringOptions
                     .withAgglomerativeInterClusterSimilarity(CLUSTER_AGGLOMERATIVE_INTER_CLUSTER_SIMILARITY.getFrom(namespace));
         }
-        if (CLUSTER_PREPROCESSING_NONE.isSet(namespace)) {
-            if (CLUSTER_PREPROCESSING_NONE.getFrom(namespace)) {
-                clusteringOptions = clusteringOptions.withPreprocessor(Preprocessing.NONE);
-            }
+        if (CLUSTER_PREPROCESSING_NONE.isSet(namespace) && Boolean.TRUE.equals(CLUSTER_PREPROCESSING_NONE.getFrom(namespace))) {
+            clusteringOptions = clusteringOptions.withPreprocessor(Preprocessing.NONE);
         }
-        if (CLUSTER_PREPROCESSING_CDF.isSet(namespace)) {
-            if (CLUSTER_PREPROCESSING_CDF.getFrom(namespace)) {
-                clusteringOptions = clusteringOptions.withPreprocessor(Preprocessing.CUMULATIVE_DISTRIBUTION_FUNCTION);
-            }
+        if (CLUSTER_PREPROCESSING_CDF.isSet(namespace) && Boolean.TRUE.equals(CLUSTER_PREPROCESSING_CDF.getFrom(namespace))) {
+            clusteringOptions = clusteringOptions.withPreprocessor(Preprocessing.CUMULATIVE_DISTRIBUTION_FUNCTION);
         }
         if (CLUSTER_PREPROCESSING_PERCENTILE.isSet(namespace)) {
             clusteringOptions = clusteringOptions.withPreprocessor(Preprocessing.PERCENTILE)

+ 2 - 4
cli/src/main/java/de/jplag/CommandLineArgument.java

@@ -37,12 +37,10 @@ public enum CommandLineArgument {
             new Builder("-l", String.class).defaultsTo(de.jplag.java.Language.IDENTIFIER)
                     .choices(LanguageLoader.getAllAvailableLanguageIdentifiers())),
     BASE_CODE("-bc", String.class),
-    VERBOSITY(new Builder("-v", String.class).defaultsTo("quiet").choices("quiet", "long").argumentGroup(ADVANCED_GROUP)), // TODO SH: Replace
-                                                                                                                           // verbosity when
-                                                                                                                           // integrating a
+
     // real logging library
     DEBUG(new Builder("-d", Boolean.class).argumentGroup(ADVANCED_GROUP)),
-    SUBDIRECTORY(new Builder("-S", String.class).argumentGroup(ADVANCED_GROUP)),
+    SUBDIRECTORY(new Builder("-s", String.class).argumentGroup(ADVANCED_GROUP)),
     SUFFIXES(new Builder("-p", String.class).argumentGroup(ADVANCED_GROUP)),
     EXCLUDE_FILE(new Builder("-x", String.class).argumentGroup(ADVANCED_GROUP)),
     MIN_TOKEN_MATCH("-t", Integer.class),

+ 2 - 2
cli/src/test/java/de/jplag/cli/BaseCodeOptionTest.java

@@ -14,13 +14,13 @@ class BaseCodeOptionTest extends CommandLineInterfaceTest {
     @Test
     void testDefaultValue() {
         buildOptionsFromCLI(CURRENT_DIRECTORY);
-        assertNull(options.baseCodeSubmissionName());
+        assertNull(options.baseCodeSubmissionDirectory());
     }
 
     @Test
     void testCustomName() {
         String argument = buildArgument(CommandLineArgument.BASE_CODE, NAME);
         buildOptionsFromCLI(argument, CURRENT_DIRECTORY);
-        assertEquals(NAME, options.baseCodeSubmissionName());
+        assertEquals(NAME, options.baseCodeSubmissionDirectory().getName());
     }
 }

+ 4 - 4
cli/src/test/java/de/jplag/cli/SimiliarityThresholdTest.java

@@ -25,21 +25,21 @@ class SimiliarityThresholdTest extends CommandLineInterfaceTest {
 
     @Test
     void testLowerBound() {
-        String argument = buildArgument(CommandLineArgument.SIMILARITY_THRESHOLD, Double.toString(-1.0));
+        String argument = buildArgument(CommandLineArgument.SIMILARITY_THRESHOLD, Double.toString(-0.01));
         buildOptionsFromCLI(argument, CURRENT_DIRECTORY);
         assertEquals(0.0, options.similarityThreshold(), DELTA);
     }
 
     @Test
     void testUpperBound() {
-        String argument = buildArgument(CommandLineArgument.SIMILARITY_THRESHOLD, Double.toString(101.0));
+        String argument = buildArgument(CommandLineArgument.SIMILARITY_THRESHOLD, Double.toString(1.01));
         buildOptionsFromCLI(argument, CURRENT_DIRECTORY);
-        assertEquals(100.0, options.similarityThreshold(), DELTA);
+        assertEquals(1.0, options.similarityThreshold(), DELTA);
     }
 
     @Test
     void testValidThreshold() {
-        double expectedValue = 50.0;
+        double expectedValue = 0.5;
         String argument = buildArgument(CommandLineArgument.SIMILARITY_THRESHOLD, Double.toString(expectedValue));
         buildOptionsFromCLI(argument, CURRENT_DIRECTORY);
         assertEquals(expectedValue, options.similarityThreshold(), DELTA);

+ 6 - 8
core/src/main/java/de/jplag/JPlagComparison.java

@@ -30,21 +30,21 @@ public record JPlagComparison(Submission firstSubmission, Submission secondSubmi
     }
 
     /**
-     * @return Maximum similarity in percent of both submissions.
+     * @return Maximum similarity in interval [0, 1]. O means no similarity, 1 means maximum similarity.
      */
     public final double maximalSimilarity() {
         return Math.max(similarityOfFirst(), similarityOfSecond());
     }
 
     /**
-     * @return Minimum similarity in percent of both submissions.
+     * @return Minimum similarity in interval [0, 1]. O means no similarity, 1 means maximum similarity.
      */
     public final double minimalSimilarity() {
         return Math.min(similarityOfFirst(), similarityOfSecond());
     }
 
     /**
-     * @return Similarity in percent (what percentage of tokens across both submissions are matched).
+     * @return Average similarity in interval [0, 1]. O means no similarity, 1 means maximum similarity.
      */
     public final double similarity() {
         boolean subtractBaseCode = firstSubmission.hasBaseCodeMatches() && secondSubmission.hasBaseCodeMatches();
@@ -54,8 +54,7 @@ public record JPlagComparison(Submission firstSubmission, Submission secondSubmi
     }
 
     /**
-     * @return Similarity in percent for the first submission (what percent of the first submission is similar to the
-     * second).
+     * @return Similarity of the first submission in interval [0, 1]. O means no similarity, 1 means maximum similarity.
      */
     public final double similarityOfFirst() {
         int divisor = firstSubmission.getSimilarityDivisor(true);
@@ -63,8 +62,7 @@ public record JPlagComparison(Submission firstSubmission, Submission secondSubmi
     }
 
     /**
-     * @return Similarity in percent for the second submission (what percent of the second submission is similar to the
-     * first).
+     * @return Similarity of the second submission in interval [0, 1]. O means no similarity, 1 means maximum similarity.
      */
     public final double similarityOfSecond() {
         int divisor = secondSubmission.getSimilarityDivisor(true);
@@ -77,6 +75,6 @@ public record JPlagComparison(Submission firstSubmission, Submission secondSubmi
     }
 
     private double similarity(int divisor) {
-        return (divisor == 0 ? 0.0 : (getNumberOfMatchedTokens() * 100 / (double) divisor));
+        return (divisor == 0 ? 0.0 : (getNumberOfMatchedTokens() / (double) divisor));
     }
 }

+ 8 - 9
core/src/main/java/de/jplag/JPlagResult.java

@@ -26,7 +26,7 @@ public class JPlagResult {
     private final int SIMILARITY_DISTRIBUTION_SIZE = 10;
 
     public JPlagResult(List<JPlagComparison> comparisons, SubmissionSet submissions, long durationInMillis, JPlagOptions options) {
-        // sort comparisons by percentage (descending)
+        // sort by similarity (descending)
         this.comparisons = comparisons.stream().sorted((first, second) -> Double.compare(second.similarity(), first.similarity())).toList();
         this.submissions = submissions;
         this.durationInMillis = durationInMillis;
@@ -36,7 +36,7 @@ public class JPlagResult {
 
     /**
      * Drops elements from the comparison list to free memory. Note, that this affects the similarity distribution and is
-     * only meant to be used if you don't need the information about comparisons with lower match percentage anymore.
+     * only meant to be used if you don't need the information about comparisons with lower match similarity anymore.
      * @param limit the number of comparisons to keep in the list
      */
     public void dropComparisons(int limit) {
@@ -48,17 +48,17 @@ public class JPlagResult {
     }
 
     /**
-     * @return a list of all comparisons sorted by percentage (descending)
+     * @return a list of all comparisons sorted by similarity (descending)
      */
     public List<JPlagComparison> getAllComparisons() {
         return comparisons;
     }
 
     /**
-     * Returns the first n comparisons (sorted by percentage, descending), limited by the specified parameter.
+     * Returns the first n comparisons (sorted by similarity, descending), limited by the specified parameter.
      * @param numberOfComparisons specifies the number of requested comparisons. If set to -1, all comparisons will be
      * returned.
-     * @return a list of comparisons sorted descending by percentage.
+     * @return a list of comparisons sorted descending by similarity.
      */
     public List<JPlagComparison> getComparisons(int numberOfComparisons) {
         if (numberOfComparisons == JPlagOptions.SHOW_ALL_COMPARISONS) {
@@ -136,11 +136,10 @@ public class JPlagResult {
 
     private int[] calculateDistributionFor(List<JPlagComparison> comparisons, ToDoubleFunction<JPlagComparison> similarityExtractor) {
         int[] similarityDistribution = new int[SIMILARITY_DISTRIBUTION_SIZE];
-        int similarityDistributionBucketSize = 100 / SIMILARITY_DISTRIBUTION_SIZE;
         for (JPlagComparison comparison : comparisons) {
-            double similarity = similarityExtractor.applyAsDouble(comparison); // extract similarity in percent: 0f <= similarity <= 100f
-            int index = (int) (similarity / similarityDistributionBucketSize); // divide similarity by bucket size to find index of correct bucket.
-            index = Math.min(index, SIMILARITY_DISTRIBUTION_SIZE - 1);// index is out of bounds when similarity is 100%. decrease by one to count
+            double similarity = similarityExtractor.applyAsDouble(comparison); // extract similarity: 0.0 <= similarity <= 1.0
+            int index = (int) (similarity * SIMILARITY_DISTRIBUTION_SIZE); // divide similarity by bucket size to find index of correct bucket.
+            index = Math.min(index, SIMILARITY_DISTRIBUTION_SIZE - 1);// index is out of bounds when similarity is 1.0. decrease by one to count
                                                                       // towards the highest value bucket
             similarityDistribution[SIMILARITY_DISTRIBUTION_SIZE - 1 - index]++; // count comparison towards its determined bucket. bucket order is
             // reversed, so that the highest value bucket has the lowest index

+ 16 - 33
core/src/main/java/de/jplag/Submission.java

@@ -3,9 +3,9 @@ package de.jplag;
 import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
-import java.nio.file.Path;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Objects;
 
@@ -232,23 +232,6 @@ public class Submission implements Comparable<Submission> {
         return subdirectory;
     }
 
-    /**
-     * Map all files of this submission to their path relative to the submission directory.
-     * <p>
-     * This method is required to stay compatible with `language.parse(...)` as it requires the given file paths to be
-     * relative to the submission directory.
-     * <p>
-     * In a future update, `language.parse(...)` should probably just take a list of files.
-     * @param baseFile - File to base all relative file paths on.
-     * @param files - List of files to map.
-     * @return an array of file paths relative to the submission directory.
-     */
-    private String[] getRelativeFilePaths(File baseFile, Collection<File> files) {
-        Path baseFilePath = baseFile.toPath();
-
-        return files.stream().map(File::toPath).map(baseFilePath::relativize).map(Path::toString).toArray(String[]::new);
-    }
-
     /* package-private */ void markAsErroneous() {
         hasErrors = true;
     }
@@ -265,24 +248,24 @@ public class Submission implements Comparable<Submission> {
             return false;
         }
 
-        String[] relativeFilePaths = getRelativeFilePaths(submissionRootFile, files);
-
-        tokenList = language.parse(submissionRootFile, relativeFilePaths);
-        if (!language.hasErrors()) {
-            if (tokenList.size() < 3) {
-                logger.error("Submission \"{}\" is too short!", name);
-                tokenList = null;
-                hasErrors = true; // invalidate submission
-                return false;
+        try {
+            tokenList = language.parse(new HashSet<>(files));
+        } catch (ParsingException e) {
+            logger.warn("Failed to parse submission {} with error {}", this, e);
+            tokenList = null;
+            hasErrors = true;
+            if (debugParser) {
+                copySubmission();
             }
-            return true;
+            return false;
         }
 
-        tokenList = null;
-        hasErrors = true; // invalidate submission
-        if (debugParser) {
-            copySubmission();
+        if (tokenList.size() < 3) {
+            logger.error("Submission \"{}\" is too short!", name);
+            tokenList = null;
+            hasErrors = true; // invalidate submission
+            return false;
         }
-        return false;
+        return true;
     }
 }

+ 2 - 2
core/src/main/java/de/jplag/SubmissionSet.java

@@ -114,13 +114,13 @@ public class SubmissionSet {
      */
     private void parseBaseCodeSubmission(Submission baseCode) throws BasecodeException {
         long startTime = System.currentTimeMillis();
-        logger.info("----- Parsing basecode submission: " + baseCode.getName());
+        logger.trace("----- Parsing basecode submission: " + baseCode.getName());
         if (!baseCode.parse(options.debugParser())) {
             throw new BasecodeException("Could not successfully parse basecode submission!");
         } else if (baseCode.getNumberOfTokens() < options.minimumTokenMatch()) {
             throw new BasecodeException("Basecode submission contains fewer tokens than minimum match length allows!");
         }
-        logger.info("Basecode submission parsed!");
+        logger.trace("Basecode submission parsed!");
         long duration = System.currentTimeMillis() - startTime;
         logger.trace("Time for parsing Basecode: " + TimeUtil.formatDuration(duration));
 

+ 18 - 98
core/src/main/java/de/jplag/SubmissionSetBuilder.java

@@ -70,37 +70,36 @@ public class SubmissionSetBuilder {
             processRootDirectoryEntries(oldDirectory, multipleRoots, foundSubmissions, false);
         }
 
-        Optional<Submission> baseCodeSubmission = loadBaseCode(submissionDirectories, oldSubmissionDirectories, foundSubmissions);
+        Optional<Submission> baseCodeSubmission = loadBaseCode();
+        baseCodeSubmission.ifPresent(baseSubmission -> foundSubmissions.remove(baseSubmission.getRoot()));
 
         // Merge everything in a submission set.
         List<Submission> submissions = new ArrayList<>(foundSubmissions.values());
-
         return new SubmissionSet(submissions, baseCodeSubmission.orElse(null), options);
     }
 
     /**
      * Verify that the given root directories exist and have no duplicate entries.
      */
-    private Set<File> verifyRootDirectories(List<String> rootDirectoryNames, boolean areNewDirectories) throws ExitException {
+    private Set<File> verifyRootDirectories(Set<File> rootDirectoryNames, boolean areNewDirectories) throws ExitException {
         if (areNewDirectories && rootDirectoryNames.isEmpty()) {
             throw new RootDirectoryException("No root directories specified with submissions to check for plagiarism!");
         }
 
         Set<File> canonicalRootDirectories = new HashSet<>(rootDirectoryNames.size());
-        for (String rootDirectoryName : rootDirectoryNames) {
-            File rootDirectory = new File(rootDirectoryName);
-
+        for (final File rootDirectory : rootDirectoryNames) {
             if (!rootDirectory.exists()) {
-                throw new RootDirectoryException(String.format("Root directory \"%s\" does not exist!", rootDirectoryName));
+                throw new RootDirectoryException(String.format("Root directory \"%s\" does not exist!", rootDirectory));
             }
             if (!rootDirectory.isDirectory()) {
-                throw new RootDirectoryException(String.format("Root directory \"%s\" is not a directory!", rootDirectoryName));
+                throw new RootDirectoryException(String.format("Root directory \"%s\" is not a directory!", rootDirectory));
             }
 
-            rootDirectory = makeCanonical(rootDirectory, it -> new RootDirectoryException("Cannot read root directory: " + rootDirectoryName, it));
-            if (!canonicalRootDirectories.add(rootDirectory)) {
+            File canonicalRootDirectory = makeCanonical(rootDirectory,
+                    it -> new RootDirectoryException("Cannot read root directory: " + rootDirectory, it));
+            if (!canonicalRootDirectories.add(canonicalRootDirectory)) {
                 // Root directory was already added, report a warning.
-                logger.warn("Root directory \"{}\" was specified more than once, duplicates will be ignored.", rootDirectoryName);
+                logger.warn("Root directory \"{}\" was specified more than once, duplicates will be ignored.", canonicalRootDirectory);
             }
         }
         return canonicalRootDirectories;
@@ -127,102 +126,23 @@ public class SubmissionSetBuilder {
         }
     }
 
-    private Optional<Submission> loadBaseCode(Set<File> submissionDirectories, Set<File> oldSubmissionDirectories,
-            Map<File, Submission> foundSubmissions) throws ExitException {
+    private Optional<Submission> loadBaseCode() throws ExitException {
         if (!options.hasBaseCode()) {
             return Optional.empty();
         }
 
-        String baseCodeName = Optional.ofNullable(options.baseCodeSubmissionName()).orElseThrow();
-        Submission baseCode = loadBaseCodeAsPath(baseCodeName);
-        if (baseCode == null) {
-            int numberOfRootDirectories = submissionDirectories.size() + oldSubmissionDirectories.size();
-            if (numberOfRootDirectories > 1) {
-                throw new BasecodeException("The base code submission needs to be specified by path instead of by name!");
-            }
-
-            // There is one root directory, and the submissionDirectories variable has been checked to be non-empty.
-            // That set thus contains the one and only root directory.
-            File rootDirectory = submissionDirectories.iterator().next();
-
-            // Single root-directory, try the legacy way of specifying basecode.
-            baseCode = loadBaseCodeViaName(baseCodeName, rootDirectory, foundSubmissions);
+        File baseCodeSubmissionDirectory = options.baseCodeSubmissionDirectory();
+        if (!baseCodeSubmissionDirectory.exists()) {
+            throw new BasecodeException("Basecode directory \"%s\" does not exist".formatted(baseCodeSubmissionDirectory));
         }
-
-        if (baseCode != null) {
-            logger.info("Basecode directory \"{}\" will be used.", baseCode.getName());
-
-            // Basecode may also be registered as a user submission. If so, remove the latter.
-            Submission removed = foundSubmissions.remove(baseCode.getRoot());
-            if (removed != null) {
-                logger.info("Submission \"{}\" is the specified basecode, it will be skipped during comparison.", removed.getName());
-            }
-        }
-        return Optional.ofNullable(baseCode);
-    }
-
-    /**
-     * Try to load the basecode under the assumption of being a path.
-     * @return Base code submission if the option value can be interpreted as global path, else {@code null}.
-     * @throws ExitException when the option value is a path with errors.
-     */
-    private Submission loadBaseCodeAsPath(String baseCodeName) throws ExitException {
-        File basecodeSubmission = new File(baseCodeName);
-        if (!basecodeSubmission.exists()) {
-            return null;
-        }
-
-        String errorMessage = isExcludedEntry(basecodeSubmission);
+        String errorMessage = isExcludedEntry(baseCodeSubmissionDirectory);
         if (errorMessage != null) {
             throw new BasecodeException(errorMessage); // Stating an excluded path as basecode isn't very useful.
         }
 
-        try {
-            // Use an unlikely short name for the base code. If all is well, this name should not appear
-            // in the output since basecode matches are removed from it
-            return processSubmission(basecodeSubmission.getName(), basecodeSubmission, false);
-        } catch (SubmissionException exception) {
-            throw new BasecodeException(exception.getMessage(), exception); // Change thrown exception to basecode exception.
-        }
-    }
-
-    /**
-     * Try to load the basecode by looking up the basecode name in the root directory.
-     * @return the base code submission if a fitting subdirectory was found, else {@code null}.
-     * @throws ExitException when the option value is a sub-directory with errors.
-     */
-    private Submission loadBaseCodeViaName(String baseCodeName, File rootDirectory, Map<File, Submission> foundSubmissions) throws ExitException {
-        // Is the option value a single name after trimming spurious separators?
-        String name = baseCodeName;
-        while (name.startsWith(File.separator)) {
-            name = name.substring(1);
-        }
-        while (name.endsWith(File.separator)) {
-            name = name.substring(0, name.length() - 1);
-        }
-
-        // If it is not a name of a single sub-directory, bail out.
-        if (name.isEmpty() || name.contains(File.separator)) {
-            return null;
-        }
-
-        if (name.contains(".")) {
-            throw new BasecodeException("The basecode directory name \"" + name + "\" cannot contain dots!");
-        }
-
-        // Grab the basecode submission from the regular submissions.
-        File basecodePath = new File(rootDirectory, baseCodeName);
-
-        Submission baseCode = foundSubmissions
-                .get(makeCanonical(basecodePath, it -> new BasecodeException("Cannot compute canonical file path: " + basecodePath, it)));
-        if (baseCode == null) {
-            // No base code found at all, report an error.
-            throw new BasecodeException(String.format("Basecode path \"%s\" relative to the working directory could not be found.", baseCodeName));
-        } else {
-            // Found a base code as a submission, warn about legacy usage.
-            logger.warn("Legacy use of the base code option found, please specify the basecode by path instead of by name!");
-        }
-        return baseCode;
+        Submission baseCodeSubmission = processSubmission(baseCodeSubmissionDirectory.getName(), baseCodeSubmissionDirectory, false);
+        logger.info("Basecode directory \"{}\" will be used.", baseCodeSubmission.getName());
+        return Optional.ofNullable(baseCodeSubmission);
     }
 
     /**

+ 143 - 75
core/src/main/java/de/jplag/options/JPlagOptions.java

@@ -1,8 +1,7 @@
 package de.jplag.options;
 
-import static de.jplag.options.Verbosity.LONG;
-
 import java.io.BufferedReader;
+import java.io.File;
 import java.io.FileReader;
 import java.io.IOException;
 import java.nio.charset.Charset;
@@ -20,6 +19,7 @@ import org.slf4j.LoggerFactory;
 import de.jplag.JPlag;
 import de.jplag.Language;
 import de.jplag.clustering.ClusteringOptions;
+import de.jplag.exceptions.BasecodeException;
 
 /**
  * This record defines the options to configure {@link JPlag}.
@@ -28,7 +28,7 @@ import de.jplag.clustering.ClusteringOptions;
  * matching section. A smaller {@code <n>} increases the sensitivity but might lead to more false-positives.
  * @param submissionDirectories Directories with new submissions. These must be checked for plagiarism.
  * @param oldSubmissionDirectories Directories with old submissions to check against.
- * @param baseCodeSubmissionName Path name of the directory containing the base code.
+ * @param baseCodeSubmissionDirectory Directory containing the base code.
  * @param subdirectoryName Example: If the subdirectoryName is 'src', only the code inside submissionDir/src of each
  * submission will be used for comparison.
  * @param fileSuffixes List of file suffixes that should be included.
@@ -36,19 +36,18 @@ import de.jplag.clustering.ClusteringOptions;
  * @param similarityMetric The similarity metric determines how the minimum similarity threshold required for a
  * comparison (of two submissions) is calculated. This affects which comparisons are stored and thus make it into the
  * result object.
- * @param similarityThreshold Percentage value (must be between 0 and 100). Comparisons (of submissions pairs) with a
+ * @param similarityThreshold Similarity value (must be between 0 and 1). Comparisons (of submissions pairs) with a
  * similarity below this threshold will be ignored. The default value of 0 allows all matches to be stored. This affects
  * which comparisons are stored and thus make it into the result object. See also {@link #similarityMetric()}.
  * @param maximumNumberOfComparisons The maximum number of comparisons that will be shown in the generated report. If
  * set to {@link #SHOW_ALL_COMPARISONS} all comparisons will be shown.
  * @param clusteringOptions Clustering options
- * @param verbosity Level of output verbosity.
  * @param debugParser If true, submissions that cannot be parsed will be stored in a separate directory.
  */
-public record JPlagOptions(Language language, Integer minimumTokenMatch, List<String> submissionDirectories, List<String> oldSubmissionDirectories,
-        String baseCodeSubmissionName, String subdirectoryName, List<String> fileSuffixes, String exclusionFileName,
+public record JPlagOptions(Language language, Integer minimumTokenMatch, Set<File> submissionDirectories, Set<File> oldSubmissionDirectories,
+        File baseCodeSubmissionDirectory, String subdirectoryName, List<String> fileSuffixes, String exclusionFileName,
         SimilarityMetric similarityMetric, double similarityThreshold, int maximumNumberOfComparisons, ClusteringOptions clusteringOptions,
-        Verbosity verbosity, boolean debugParser) {
+        boolean debugParser) {
 
     public static final double DEFAULT_SIMILARITY_THRESHOLD = 0;
     public static final int DEFAULT_SHOWN_COMPARISONS = 30;
@@ -58,15 +57,15 @@ public record JPlagOptions(Language language, Integer minimumTokenMatch, List<St
 
     private static final Logger logger = LoggerFactory.getLogger(JPlag.class);
 
-    public JPlagOptions(Language language, List<String> submissionDirectories, List<String> oldSubmissionDirectories) {
+    public JPlagOptions(Language language, Set<File> submissionDirectories, Set<File> oldSubmissionDirectories) {
         this(language, null, submissionDirectories, oldSubmissionDirectories, null, null, null, null, DEFAULT_SIMILARITY_METRIC,
-                DEFAULT_SIMILARITY_THRESHOLD, DEFAULT_SHOWN_COMPARISONS, new ClusteringOptions(), null, false);
+                DEFAULT_SIMILARITY_THRESHOLD, DEFAULT_SHOWN_COMPARISONS, new ClusteringOptions(), false);
     }
 
-    public JPlagOptions(Language language, Integer minimumTokenMatch, List<String> submissionDirectories, List<String> oldSubmissionDirectories,
-            String baseCodeSubmissionName, String subdirectoryName, List<String> fileSuffixes, String exclusionFileName,
+    public JPlagOptions(Language language, Integer minimumTokenMatch, Set<File> submissionDirectories, Set<File> oldSubmissionDirectories,
+            File baseCodeSubmissionDirectory, String subdirectoryName, List<String> fileSuffixes, String exclusionFileName,
             SimilarityMetric similarityMetric, double similarityThreshold, int maximumNumberOfComparisons, ClusteringOptions clusteringOptions,
-            Verbosity verbosity, boolean debugParser) {
+            boolean debugParser) {
         this.language = language;
         this.debugParser = debugParser;
         this.fileSuffixes = fileSuffixes == null || fileSuffixes.isEmpty() ? null : Collections.unmodifiableList(fileSuffixes);
@@ -75,100 +74,93 @@ public record JPlagOptions(Language language, Integer minimumTokenMatch, List<St
         this.similarityMetric = similarityMetric;
         this.minimumTokenMatch = normalizeMinimumTokenMatch(minimumTokenMatch);
         this.exclusionFileName = exclusionFileName;
-        this.submissionDirectories = submissionDirectories == null ? null : Collections.unmodifiableList(submissionDirectories);
-        this.oldSubmissionDirectories = oldSubmissionDirectories == null ? null : Collections.unmodifiableList(oldSubmissionDirectories);
-        this.baseCodeSubmissionName = (baseCodeSubmissionName == null || baseCodeSubmissionName.isBlank()) ? null : baseCodeSubmissionName;
+        this.submissionDirectories = submissionDirectories == null ? null : Collections.unmodifiableSet(submissionDirectories);
+        this.oldSubmissionDirectories = oldSubmissionDirectories == null ? null : Collections.unmodifiableSet(oldSubmissionDirectories);
+        this.baseCodeSubmissionDirectory = baseCodeSubmissionDirectory;
         this.subdirectoryName = subdirectoryName;
-        this.verbosity = verbosity;
         this.clusteringOptions = clusteringOptions;
     }
 
     public JPlagOptions withLanguageOption(Language language) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public JPlagOptions withDebugParser(boolean debugParser) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public JPlagOptions withFileSuffixes(List<String> fileSuffixes) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public JPlagOptions withSimilarityThreshold(double similarityThreshold) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public JPlagOptions withMaximumNumberOfComparisons(int maximumNumberOfComparisons) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public JPlagOptions withSimilarityMetric(SimilarityMetric similarityMetric) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public JPlagOptions withMinimumTokenMatch(Integer minimumTokenMatch) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public JPlagOptions withExclusionFileName(String exclusionFileName) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
-    public JPlagOptions withSubmissionDirectories(List<String> submissionDirectories) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+    public JPlagOptions withSubmissionDirectories(Set<File> submissionDirectories) {
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
-    public JPlagOptions withOldSubmissionDirectories(List<String> oldSubmissionDirectories) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+    public JPlagOptions withOldSubmissionDirectories(Set<File> oldSubmissionDirectories) {
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
-    public JPlagOptions withBaseCodeSubmissionName(String baseCodeSubmissionName) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+    public JPlagOptions withBaseCodeSubmissionDirectory(File baseCodeSubmissionDirectory) {
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public JPlagOptions withSubdirectoryName(String subdirectoryName) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
-                subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
-    }
-
-    public JPlagOptions withVerbosity(Verbosity verbosity) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public JPlagOptions withClusteringOptions(ClusteringOptions clusteringOptions) {
-        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionName,
+        return new JPlagOptions(language, minimumTokenMatch, submissionDirectories, oldSubmissionDirectories, baseCodeSubmissionDirectory,
                 subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
-                clusteringOptions, verbosity, debugParser);
+                clusteringOptions, debugParser);
     }
 
     public boolean hasBaseCode() {
-        return baseCodeSubmissionName != null;
+        return baseCodeSubmissionDirectory != null;
     }
 
     public Set<String> excludedFiles() {
@@ -183,23 +175,6 @@ public record JPlagOptions(Language language, Integer minimumTokenMatch, List<St
         return fileSuffixes == null ? null : Collections.unmodifiableList(fileSuffixes);
     }
 
-    /**
-     * Path name of the directory containing the base code.<br>
-     * For backwards compatibility it may also be a directory name inside the root directory. Condition for the latter is
-     * <ul>
-     * <li>Specified path does not exist.</li>
-     * <li>Name has not have a separator character after trimming them from both ends (leaving at least a one-character
-     * name).</li>
-     * <li>A submission with the specified name exists in the root directory.</li>
-     * </ul>
-     * It's an error if a string has been provided, but it is neither an existing path nor does it fulfill all the
-     * conditions of the compatibility fallback listed above.
-     */
-    @Override
-    public String baseCodeSubmissionName() {
-        return baseCodeSubmissionName;
-    }
-
     @Override
     public Integer minimumTokenMatch() {
         var language = language();
@@ -211,8 +186,8 @@ public record JPlagOptions(Language language, Integer minimumTokenMatch, List<St
     private Set<String> readExclusionFile(final String exclusionFileName) {
         try (BufferedReader reader = new BufferedReader(new FileReader(exclusionFileName, JPlagOptions.CHARSET))) {
             final var excludedFileNames = reader.lines().collect(Collectors.toSet());
-            if (verbosity() == LONG && logger.isInfoEnabled()) {
-                logger.info("Excluded files:\n{}", String.join("\n", excludedFileNames));
+            if (logger.isDebugEnabled()) {
+                logger.debug("Excluded files:{}{}", System.lineSeparator(), String.join(System.lineSeparator(), excludedFileNames));
             }
             return excludedFileNames;
         } catch (IOException e) {
@@ -222,9 +197,9 @@ public record JPlagOptions(Language language, Integer minimumTokenMatch, List<St
     }
 
     private static double normalizeSimilarityThreshold(double similarityThreshold) {
-        if (similarityThreshold > 100) {
-            logger.warn("Maximum threshold of 100 used instead of {}", similarityThreshold);
-            return 100;
+        if (similarityThreshold > 1) {
+            logger.warn("Maximum threshold of 1 used instead of {}", similarityThreshold);
+            return 1;
         } else if (similarityThreshold < 0) {
             logger.warn("Minimum threshold of 0 used instead of {}", similarityThreshold);
             return 0;
@@ -240,4 +215,97 @@ public record JPlagOptions(Language language, Integer minimumTokenMatch, List<St
     private Integer normalizeMinimumTokenMatch(Integer minimumTokenMatch) {
         return (minimumTokenMatch != null && minimumTokenMatch < 1) ? Integer.valueOf(1) : minimumTokenMatch;
     }
+
+    /**
+     * Creates new options to configure {@link JPlag}.
+     * @param language Language to use when parsing the submissions.
+     * @param minimumTokenMatch Tunes the comparison sensitivity by adjusting the minimum token required to be counted as
+     * matching section. A smaller {@code <n>} increases the sensitivity but might lead to more false-positives.
+     * @param submissionDirectory Directory with new submissions. These must be checked for plagiarism. To check more than
+     * one submission directory, use the default initializer.
+     * @param oldSubmissionDirectories Directories with old submissions to check against.
+     * @param baseCodeSubmissionName Path name of the directory containing the base code.
+     * @param subdirectoryName Example: If the subdirectoryName is 'src', only the code inside submissionDir/src of each
+     * submission will be used for comparison.
+     * @param fileSuffixes List of file suffixes that should be included.
+     * @param exclusionFileName Name of the file that contains the names of files to exclude from comparison.
+     * @param similarityMetric The similarity metric determines how the minimum similarity threshold required for a
+     * comparison (of two submissions) is calculated. This affects which comparisons are stored and thus make it into the
+     * result object.
+     * @param similarityThreshold Percentage value (must be between 0 and 100). Comparisons (of submissions pairs) with a
+     * similarity below this threshold will be ignored. The default value of 0 allows all matches to be stored. This affects
+     * which comparisons are stored and thus make it into the result object. See also {@link #similarityMetric()}.
+     * @param maximumNumberOfComparisons The maximum number of comparisons that will be shown in the generated report. If
+     * set to {@link #SHOW_ALL_COMPARISONS} all comparisons will be shown.
+     * @param clusteringOptions Clustering options
+     * @param debugParser If true, submissions that cannot be parsed will be stored in a separate directory.
+     * @deprecated Use the default initializer with @{{@link #baseCodeSubmissionDirectory} instead.
+     */
+    @Deprecated(since = "4.0.0", forRemoval = true)
+    public JPlagOptions(Language language, Integer minimumTokenMatch, File submissionDirectory, Set<File> oldSubmissionDirectories,
+            String baseCodeSubmissionName, String subdirectoryName, List<String> fileSuffixes, String exclusionFileName,
+            SimilarityMetric similarityMetric, double similarityThreshold, int maximumNumberOfComparisons, ClusteringOptions clusteringOptions,
+            boolean debugParser) throws BasecodeException {
+        this(language, minimumTokenMatch, Set.of(submissionDirectory), oldSubmissionDirectories,
+                convertLegacyBaseCodeToFile(baseCodeSubmissionName, submissionDirectory), subdirectoryName, fileSuffixes, exclusionFileName,
+                similarityMetric, similarityThreshold, maximumNumberOfComparisons, clusteringOptions, debugParser);
+    }
+
+    /**
+     * Creates a new options instance with the provided base code submission name
+     * @param baseCodeSubmissionName the path or name of the base code submission
+     * @return a new options instance with the provided base code submission name
+     * @deprecated Use @{{@link #withBaseCodeSubmissionDirectory} instead.
+     */
+    @Deprecated(since = "4.0.0", forRemoval = true)
+    public JPlagOptions withBaseCodeSubmissionName(String baseCodeSubmissionName) {
+        File baseCodeDirectory = new File(baseCodeSubmissionName);
+        if (baseCodeDirectory.exists()) {
+            return this.withBaseCodeSubmissionDirectory(baseCodeDirectory);
+        }
+
+        if (submissionDirectories.size() != 1) {
+            throw new IllegalArgumentException("Partial path based base code requires exactly one submission directory");
+        }
+        File submissionDirectory = submissionDirectories.iterator().next();
+        try {
+            return new JPlagOptions(language, minimumTokenMatch, submissionDirectory, oldSubmissionDirectories, baseCodeSubmissionName,
+                    subdirectoryName, fileSuffixes, exclusionFileName, similarityMetric, similarityThreshold, maximumNumberOfComparisons,
+                    clusteringOptions, debugParser);
+        } catch (BasecodeException e) {
+            throw new IllegalArgumentException(e.getMessage(), e.getCause());
+        }
+    }
+
+    /**
+     * Converts a legacy base code submission name to a directory path.
+     * @deprecated Use the default initializer with @{{@link #baseCodeSubmissionDirectory} instead.
+     */
+    @Deprecated(since = "4.0.0", forRemoval = true)
+    private static File convertLegacyBaseCodeToFile(String baseCodeSubmissionName, File submissionDirectory) throws BasecodeException {
+        if (baseCodeSubmissionName == null) {
+            return null;
+        }
+        File baseCodeAsAbsolutePath = new File(baseCodeSubmissionName);
+        if (baseCodeAsAbsolutePath.exists()) {
+            return baseCodeAsAbsolutePath;
+        } else {
+            String normalizedName = baseCodeSubmissionName;
+            while (normalizedName.startsWith(File.separator)) {
+                normalizedName = normalizedName.substring(1);
+            }
+            while (normalizedName.endsWith(File.separator)) {
+                normalizedName = normalizedName.substring(0, normalizedName.length() - 1);
+            }
+            if (normalizedName.isEmpty() || normalizedName.contains(File.separator)) {
+                throw new BasecodeException(
+                        "The basecode directory name \"" + normalizedName + "\" cannot contain dots! Please migrate to the path-based API.");
+            }
+            if (normalizedName.contains(".")) {
+                throw new BasecodeException(
+                        "The basecode directory name \"" + normalizedName + "\" cannot contain dots! Please migrate to the path-based API.");
+            }
+            return new File(submissionDirectory, baseCodeSubmissionName);
+        }
+    }
 }

+ 2 - 2
core/src/main/java/de/jplag/options/SimilarityMetric.java

@@ -12,8 +12,8 @@ public enum SimilarityMetric implements ToDoubleFunction<JPlagComparison> {
 
     private final ToDoubleFunction<JPlagComparison> similarityFunction;
 
-    SimilarityMetric(ToDoubleFunction<JPlagComparison> determinePercentage) {
-        this.similarityFunction = determinePercentage;
+    SimilarityMetric(ToDoubleFunction<JPlagComparison> similarityFunction) {
+        this.similarityFunction = similarityFunction;
     }
 
     public boolean isAboveThreshold(JPlagComparison comparison, double similarityThreshold) {

+ 0 - 13
core/src/main/java/de/jplag/options/Verbosity.java

@@ -1,13 +0,0 @@
-package de.jplag.options;
-
-public enum Verbosity {
-    QUIET,
-    LONG;
-
-    public static Verbosity fromOption(String optionValue) {
-        for (Verbosity verbosity : Verbosity.values())
-            if (verbosity.name().equalsIgnoreCase(optionValue))
-                return verbosity;
-        return QUIET;
-    }
-}

+ 8 - 2
core/src/main/java/de/jplag/reporting/jsonfactory/ComparisonReportWriter.java

@@ -1,5 +1,6 @@
 package de.jplag.reporting.jsonfactory;
 
+import java.io.File;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
@@ -97,8 +98,13 @@ public class ComparisonReportWriter {
         Token startOfSecond = tokensSecond.get(match.startOfSecond());
         Token endOfSecond = tokensSecond.get(match.startOfSecond() + match.length() - 1);
 
-        return new Match(startOfFirst.getFile(), startOfSecond.getFile(), startOfFirst.getLine(), endOfFirst.getLine(), startOfSecond.getLine(),
-                endOfSecond.getLine(), match.length());
+        return new Match(relativizedFilePath(startOfFirst.getFile(), comparison.firstSubmission()),
+                relativizedFilePath(startOfSecond.getFile(), comparison.secondSubmission()), startOfFirst.getLine(), endOfFirst.getLine(),
+                startOfSecond.getLine(), endOfSecond.getLine(), match.length());
+    }
+
+    private String relativizedFilePath(File file, Submission submission) {
+        return submission.getRoot().toPath().relativize(file.toPath()).toString();
     }
 
 }

+ 3 - 3
core/src/main/java/de/jplag/reporting/reportobject/ReportObjectFactory.java

@@ -134,14 +134,14 @@ public class ReportObjectFactory {
 
     private void writeOverview(JPlagResult result, String path) {
 
-        List<String> folders = new ArrayList<>();
+        List<File> folders = new ArrayList<>();
         folders.addAll(result.getOptions().submissionDirectories());
         folders.addAll(result.getOptions().oldSubmissionDirectories());
 
-        String baseCodePath = result.getOptions().hasBaseCode() ? result.getOptions().baseCodeSubmissionName() : "";
+        String baseCodePath = result.getOptions().hasBaseCode() ? result.getOptions().baseCodeSubmissionDirectory().getName() : "";
         ClusteringResultMapper clusteringResultMapper = new ClusteringResultMapper(submissionToIdFunction);
 
-        OverviewReport overviewReport = new OverviewReport(folders, // submissionFolderPath
+        OverviewReport overviewReport = new OverviewReport(folders.stream().map(File::getPath).toList(), // submissionFolderPath
                 baseCodePath, // baseCodeFolderPath
                 result.getOptions().language().getName(), // language
                 result.getOptions().fileSuffixes(), // fileExtensions

+ 2 - 2
core/src/main/java/de/jplag/reporting/reportobject/model/ComparisonReport.java

@@ -8,10 +8,10 @@ import com.fasterxml.jackson.annotation.JsonProperty;
  * ReportViewer DTO for the comparison of two submissions.
  * @param firstSubmissionId id of the first submission
  * @param secondSubmissionId id of the second submission
- * @param matchPercentage similarity in percent. between 0f and 100f.
+ * @param similarity average similarity. between 0.0 and 1.0.
  * @param matches the list of matches found in the comparison of the two submissions
  */
 public record ComparisonReport(@JsonProperty("id1") String firstSubmissionId, @JsonProperty("id2") String secondSubmissionId,
-        @JsonProperty("similarity") double matchPercentage, @JsonProperty("matches") List<Match> matches) {
+        @JsonProperty("similarity") double similarity, @JsonProperty("matches") List<Match> matches) {
 
 }

+ 1 - 1
core/src/main/java/de/jplag/reporting/reportobject/model/TopComparison.java

@@ -3,5 +3,5 @@ package de.jplag.reporting.reportobject.model;
 import com.fasterxml.jackson.annotation.JsonProperty;
 
 public record TopComparison(@JsonProperty("first_submission") String firstSubmission, @JsonProperty("second_submission") String secondSubmission,
-        @JsonProperty("match_percentage") double matchPercentage) {
+        @JsonProperty("similarity") double similarity) {
 }

+ 2 - 2
core/src/main/java/de/jplag/strategy/SubmissionTuple.java

@@ -3,11 +3,11 @@ package de.jplag.strategy;
 import de.jplag.Submission;
 
 /**
- * Tupel of source code submissions.
+ * Tuple of source code submissions.
  */
 public record SubmissionTuple(Submission left, Submission right) {
     /**
-     * Creates a tupel from two submissions.
+     * Creates a tuple from two submissions.
      */
     public SubmissionTuple {
         if (left == null || right == null) {

+ 4 - 5
core/src/main/resources/de/jplag/messages.properties

@@ -5,13 +5,12 @@ CommandLineArgument.ExcludeFile=All files named in this file will be ignored in
 CommandLineArgument.Language=Select the language to parse the submissions
 CommandLineArgument.MinTokenMatch=Tunes the comparison sensitivity by adjusting the minimum token required to be counted as a matching section. A smaller <n> increases the sensitivity but might lead to more false-positives
 CommandLineArgument.ResultFolder=Name of the directory in which the comparison results will be stored
-CommandLineArgument.RootDirectory=Root-directory with submissions to check for plagiarism
-CommandLineArgument.PlagiarismDirectory=Root-directory with submissions to check for plagiarism
-CommandLineArgument.PriorDirectory=Root-directory with prior submissions to compare against
+CommandLineArgument.RootDirectory=Root directories with submissions to check for plagiarism
+CommandLineArgument.NewDirectory=Root directories with submissions to check for plagiarism (same as the root directory)
+CommandLineArgument.OldDirectory=Root directories with prior submissions to compare against
 CommandLineArgument.ShownComparisons=The maximum number of comparisons that will be shown in the generated report, if set to -1 all comparisons will be shown
-CommandLineArgument.SimilarityThreshold=Comparison similarity threshold [0-100]: All comparisons above this threshold will be saved
+CommandLineArgument.SimilarityThreshold=Comparison similarity threshold [0.0-1.0]: All comparisons above this threshold will be saved
 CommandLineArgument.Subdirectory=Look in directories <root-dir>/*/<dir> for programs
-CommandLineArgument.Verbosity=Verbosity of the logging
 CommandLineArgument.ClusterDisable=Skips the clustering
 CommandLineArgument.ClusterAlgorithm=Which clustering algorithm to use. Agglomerative merges similar submissions bottom up. Spectral clustering is combined with Bayesian Optimization to execute the k-Means clustering algorithm multiple times, hopefully finding a "good" clustering automatically.
 CommandLineArgument.ClusterMetric=The metric used for clustering. AVG is intersection over union, MAX can expose some attempts of obfuscation.

+ 46 - 17
core/src/test/java/de/jplag/BaseCodeTest.java

@@ -4,7 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import java.io.File;
-import java.util.List;
+import java.util.Set;
 
 import org.junit.jupiter.api.Test;
 
@@ -16,53 +16,82 @@ public class BaseCodeTest extends TestBase {
 
     @Test
     void testBasecodeUserSubmissionComparison() throws ExitException {
-        JPlagResult result = runJPlag("basecode", it -> it.withBaseCodeSubmissionName("base"));
+        JPlagResult result = runJPlag("basecode",
+                it -> it.withBaseCodeSubmissionDirectory(new File(it.submissionDirectories().iterator().next(), "base")));
         verifyResults(result);
     }
 
     @Test
     void testTinyBasecode() {
-        assertThrows(BasecodeException.class, () -> runJPlag("TinyBasecode", it -> it.withBaseCodeSubmissionName("base")));
+        assertThrows(BasecodeException.class, () -> runJPlag("TinyBasecode",
+                it -> it.withBaseCodeSubmissionDirectory(new File(it.submissionDirectories().iterator().next(), "base"))));
     }
 
     @Test
     void testEmptySubmission() throws ExitException {
-        JPlagResult result = runJPlag("emptysubmission", it -> it.withBaseCodeSubmissionName("base"));
+        JPlagResult result = runJPlag("emptysubmission",
+                it -> it.withBaseCodeSubmissionDirectory(new File(it.submissionDirectories().iterator().next(), "base")));
         verifyResults(result);
     }
 
-    @Test
-    void testAutoTrimFileSeparators() throws ExitException {
-        JPlagResult result = runJPlag("basecode", it -> it.withBaseCodeSubmissionName(File.separator + "base" + File.separator));
-        verifyResults(result);
-    }
-
-    private void verifyResults(JPlagResult result) {
+    protected void verifyResults(JPlagResult result) {
         assertEquals(2, result.getNumberOfSubmissions());
         assertEquals(1, result.getAllComparisons().size());
         assertEquals(1, result.getAllComparisons().get(0).matches().size());
         assertEquals(1, result.getSimilarityDistribution()[1]);
-        assertEquals(85, result.getAllComparisons().get(0).similarity(), DELTA);
+        assertEquals(0.85, result.getAllComparisons().get(0).similarity(), DELTA);
     }
 
     @Test
     void testBasecodePathComparison() throws ExitException {
-        JPlagResult result = runJPlag("basecode", it -> it.withBaseCodeSubmissionName(getBasePath("basecode-base")));
+        JPlagResult result = runJPlag("basecode", it -> it.withBaseCodeSubmissionDirectory(new File(BASE_PATH, "basecode-base")));
         assertEquals(3, result.getNumberOfSubmissions()); // "basecode/base" is now a user submission.
     }
 
     @Test
     void testInvalidRoot() {
-        assertThrows(RootDirectoryException.class, () -> runJPlag("basecode", it -> it.withSubmissionDirectories(List.of("WrongRoot"))));
+        assertThrows(RootDirectoryException.class, () -> runJPlag("basecode", it -> it.withSubmissionDirectories(Set.of(new File("WrongRoot")))));
     }
 
     @Test
     void testInvalidBasecode() {
-        assertThrows(BasecodeException.class, () -> runJPlag("basecode", it -> it.withBaseCodeSubmissionName("WrongBasecode")));
+        assertThrows(BasecodeException.class, () -> runJPlag("basecode",
+                it -> it.withBaseCodeSubmissionDirectory(new File(it.submissionDirectories().iterator().next(), "WrongBasecode"))));
+    }
+
+    /**
+     * The simple duplicate contains obvious plagiarism.
+     */
+    @Test
+    void testSubdirectoryGlobalBasecode() throws ExitException {
+        String basecode = getBasePath("SubdirectoryBase");
+        JPlagResult result = runJPlag("SubdirectoryDuplicate",
+                it -> it.withSubdirectoryName("src").withBaseCodeSubmissionDirectory(new File(basecode)));
+        verifySimpleSubdirectoryDuplicate(result, 3, 3);
     }
 
+    /**
+     * The simple duplicate contains obvious plagiarism.
+     */
     @Test
-    void testBasecodeUserSubmissionWithDots() {
-        assertThrows(BasecodeException.class, () -> runJPlag("basecode", it -> it.withBaseCodeSubmissionName("base.ext")));
+    void testSubdirectoryLocalBasecode() throws ExitException {
+        JPlagResult result = runJPlag("SubdirectoryDuplicate",
+                it -> it.withSubdirectoryName("src").withBaseCodeSubmissionDirectory(new File(it.submissionDirectories().iterator().next(), "Base")));
+        verifySimpleSubdirectoryDuplicate(result, 2, 1);
+    }
+
+    protected void verifySimpleSubdirectoryDuplicate(JPlagResult result, int submissions, int comparisons) {
+        result.getSubmissions().getSubmissions().forEach(this::hasSubdirectoryRoot);
+        hasSubdirectoryRoot(result.getSubmissions().getBaseCode());
+
+        assertEquals(submissions, result.getNumberOfSubmissions());
+        assertEquals(comparisons, result.getAllComparisons().size());
+        assertEquals(1, result.getAllComparisons().get(0).matches().size());
+        assertEquals(1, result.getSimilarityDistribution()[3]);
+        assertEquals(0.6207, result.getAllComparisons().get(0).similarity(), DELTA);
+    }
+
+    private void hasSubdirectoryRoot(Submission submission) {
+        assertEquals("src", submission.getRoot().getName());
     }
 }

+ 49 - 0
core/src/test/java/de/jplag/LegacyBaseCodeParallelComparisonTest.java

@@ -0,0 +1,49 @@
+package de.jplag;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import de.jplag.exceptions.ExitException;
+
+/**
+ * Tests for the legacy behaviour of the String-based base code initializer.
+ */
+@Deprecated(since = "4.0.0", forRemoval = true)
+class LegacyBaseCodeParallelComparisonTest extends ParallelComparisonTest {
+    @Test
+    void testMultiRootDirSeparateBasecode() throws ExitException {
+        String basecodePath = getBasePath("basecode-base");
+        List<String> paths = List.of(getBasePath("basecode"), getBasePath("SimpleDuplicate")); // 3 + 2 submissions.
+        JPlagResult result = runJPlag(paths, it -> it.withBaseCodeSubmissionName(basecodePath));
+        assertEquals(5, result.getNumberOfSubmissions());
+    }
+
+    @Test
+    void testMultiRootDirBasecodeInSubmissionDir() throws ExitException {
+        String basecodePath = getBasePath("basecode", "base");
+        List<String> paths = List.of(getBasePath("basecode"), getBasePath("SimpleDuplicate")); // 2 + 2 submissions.
+        JPlagResult result = runJPlag(paths, it -> it.withBaseCodeSubmissionName(basecodePath));
+        assertEquals(4, result.getNumberOfSubmissions());
+    }
+
+    @Test
+    void testMultiRootDirBasecodeName() {
+        List<String> paths = List.of(getBasePath("basecode"), getBasePath("SimpleDuplicate"));
+        String basecodePath = "base"; // Should *not* find basecode/base
+        assertThrows(IllegalArgumentException.class, () -> runJPlag(paths, it -> it.withBaseCodeSubmissionName(basecodePath)));
+    }
+
+    @Test
+    void testBasecodeInOldDirectory() throws ExitException {
+        String basecodePath = getBasePath("basecode", "base");
+        List<String> newDirectories = List.of(getBasePath("SimpleDuplicate")); // 2 submissions
+        List<String> oldDirectories = List.of(getBasePath("basecode")); // 3 - 1 submissions
+        JPlagResult result = runJPlag(newDirectories, oldDirectories, it -> it.withBaseCodeSubmissionName(basecodePath));
+        int numberOfExpectedComparison = 1 + 2 * 2;
+        assertEquals(numberOfExpectedComparison, result.getAllComparisons().size());
+    }
+}

+ 75 - 0
core/src/test/java/de/jplag/LegacyBaseCodeTest.java

@@ -0,0 +1,75 @@
+package de.jplag;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.io.File;
+
+import org.junit.jupiter.api.Test;
+
+import de.jplag.exceptions.BasecodeException;
+import de.jplag.exceptions.ExitException;
+
+/**
+ * Tests for the legacy behaviour of the String-based base code initializer.
+ */
+@Deprecated(since = "4.0.0", forRemoval = true)
+class LegacyBaseCodeTest extends BaseCodeTest {
+    @Test
+    void testBasecodeUserSubmissionComparison() throws ExitException {
+        JPlagResult result = runJPlag("basecode", it -> it.withBaseCodeSubmissionName("base"));
+        verifyResults(result);
+    }
+
+    @Test
+    void testTinyBasecode() {
+        assertThrows(BasecodeException.class, () -> runJPlag("TinyBasecode", it -> it.withBaseCodeSubmissionName("base")));
+    }
+
+    @Test
+    void testEmptySubmission() throws ExitException {
+        JPlagResult result = runJPlag("emptysubmission", it -> it.withBaseCodeSubmissionName("base"));
+        verifyResults(result);
+    }
+
+    @Test
+    void testAutoTrimFileSeparators() throws ExitException {
+        JPlagResult result = runJPlag("basecode", it -> it.withBaseCodeSubmissionName(File.separator + "base" + File.separator));
+        verifyResults(result);
+    }
+
+    @Test
+    void testBasecodePathComparison() throws ExitException {
+        JPlagResult result = runJPlag("basecode", it -> it.withBaseCodeSubmissionName(getBasePath("basecode-base")));
+        assertEquals(3, result.getNumberOfSubmissions()); // "basecode/base" is now a user submission.
+    }
+
+    @Test
+    void testInvalidBasecode() {
+        assertThrows(BasecodeException.class, () -> runJPlag("basecode", it -> it.withBaseCodeSubmissionName("WrongBasecode")));
+    }
+
+    @Test
+    void testBasecodeUserSubmissionWithDots() {
+        assertThrows(IllegalArgumentException.class, () -> runJPlag("basecode", it -> it.withBaseCodeSubmissionName("base.ext")));
+    }
+
+    /**
+     * The simple duplicate contains obvious plagiarism.
+     */
+    @Test
+    void testSubdirectoryGlobalBasecode() throws ExitException {
+        String basecode = getBasePath("SubdirectoryBase");
+        JPlagResult result = runJPlag("SubdirectoryDuplicate", it -> it.withSubdirectoryName("src").withBaseCodeSubmissionName(basecode));
+        verifySimpleSubdirectoryDuplicate(result, 3, 3);
+    }
+
+    /**
+     * The simple duplicate contains obvious plagiarism.
+     */
+    @Test
+    void testSubdirectoryLocalBasecode() throws ExitException {
+        JPlagResult result = runJPlag("SubdirectoryDuplicate", it -> it.withSubdirectoryName("src").withBaseCodeSubmissionName("Base"));
+        verifySimpleSubdirectoryDuplicate(result, 2, 1);
+    }
+}

+ 1 - 1
core/src/test/java/de/jplag/NewJavaFeaturesTest.java

@@ -8,7 +8,7 @@ import de.jplag.exceptions.ExitException;
 
 public class NewJavaFeaturesTest extends TestBase {
     private static final int EXPECTED_MATCHES = 6; // might change if you add files to the submissions
-    private static final double EXPECTED_SIMILARITY = 96.0; // might change if you add files to the submissions
+    private static final double EXPECTED_SIMILARITY = 0.96; // might change if you add files to the submissions
 
     private static final String EXCLUSION_FILE_NAME = "blacklist.txt";
     private static final String ROOT_DIRECTORY = "NewJavaFeatures";

+ 15 - 23
core/src/test/java/de/jplag/ParallelComparisonTest.java

@@ -2,17 +2,16 @@ package de.jplag;
 
 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
 
+import java.io.File;
 import java.util.List;
 import java.util.Optional;
 
 import org.junit.jupiter.api.Test;
 
-import de.jplag.exceptions.BasecodeException;
 import de.jplag.exceptions.ExitException;
 
-public class ParallelComparisonTest extends TestBase {
+class ParallelComparisonTest extends TestBase {
 
     /**
      * The simple duplicate contains obvious plagiarism.
@@ -25,7 +24,7 @@ public class ParallelComparisonTest extends TestBase {
         assertEquals(1, result.getAllComparisons().size());
         assertEquals(1, result.getAllComparisons().get(0).matches().size());
         assertEquals(1, result.getSimilarityDistribution()[3]);
-        assertEquals(62.07, result.getAllComparisons().get(0).similarity(), DELTA);
+        assertEquals(0.6207, result.getAllComparisons().get(0).similarity(), DELTA);
     }
 
     /**
@@ -40,7 +39,7 @@ public class ParallelComparisonTest extends TestBase {
         assertEquals(1, result.getAllComparisons().size());
         assertEquals(2, result.getAllComparisons().get(0).matches().size());
         assertArrayEquals(expectedDistribution, result.getSimilarityDistribution());
-        assertEquals(96.55, result.getAllComparisons().get(0).similarity(), DELTA);
+        assertEquals(0.9655, result.getAllComparisons().get(0).similarity(), DELTA);
     }
 
     /**
@@ -74,17 +73,17 @@ public class ParallelComparisonTest extends TestBase {
                 .forEach(comparison -> assertEquals(0, comparison.similarity(), DELTA));
 
         // Hard coded assertions on selected comparisons
-        assertEquals(24.6, getSelectedPercent(result, "A", "B"), DELTA);
-        assertEquals(99.7, getSelectedPercent(result, "A", "C"), DELTA);
-        assertEquals(77.9, getSelectedPercent(result, "A", "D"), DELTA);
-        assertEquals(24.6, getSelectedPercent(result, "B", "C"), DELTA);
-        assertEquals(28.3, getSelectedPercent(result, "B", "D"), DELTA);
-        assertEquals(77.9, getSelectedPercent(result, "C", "D"), DELTA);
+        assertEquals(0.246, getSelectedPercent(result, "A", "B"), DELTA);
+        assertEquals(0.997, getSelectedPercent(result, "A", "C"), DELTA);
+        assertEquals(0.779, getSelectedPercent(result, "A", "D"), DELTA);
+        assertEquals(0.246, getSelectedPercent(result, "B", "C"), DELTA);
+        assertEquals(0.283, getSelectedPercent(result, "B", "D"), DELTA);
+        assertEquals(0.779, getSelectedPercent(result, "C", "D"), DELTA);
 
         // More detailed assertions for the plagiarism in A-D
         var biggestMatch = getSelectedComparison(result, "A", "D");
-        assertEquals(96.4, biggestMatch.get().maximalSimilarity(), DELTA);
-        assertEquals(65.3, biggestMatch.get().minimalSimilarity(), DELTA);
+        assertEquals(0.964, biggestMatch.get().maximalSimilarity(), DELTA);
+        assertEquals(0.653, biggestMatch.get().minimalSimilarity(), DELTA);
         assertEquals(12, biggestMatch.get().matches().size());
     }
 
@@ -111,7 +110,7 @@ public class ParallelComparisonTest extends TestBase {
     void testMultiRootDirSeparateBasecode() throws ExitException {
         String basecodePath = getBasePath("basecode-base");
         List<String> paths = List.of(getBasePath("basecode"), getBasePath("SimpleDuplicate")); // 3 + 2 submissions.
-        JPlagResult result = runJPlag(paths, it -> it.withBaseCodeSubmissionName(basecodePath));
+        JPlagResult result = runJPlag(paths, it -> it.withBaseCodeSubmissionDirectory(new File(basecodePath)));
         assertEquals(5, result.getNumberOfSubmissions());
     }
 
@@ -119,17 +118,10 @@ public class ParallelComparisonTest extends TestBase {
     void testMultiRootDirBasecodeInSubmissionDir() throws ExitException {
         String basecodePath = getBasePath("basecode", "base");
         List<String> paths = List.of(getBasePath("basecode"), getBasePath("SimpleDuplicate")); // 2 + 2 submissions.
-        JPlagResult result = runJPlag(paths, it -> it.withBaseCodeSubmissionName(basecodePath));
+        JPlagResult result = runJPlag(paths, it -> it.withBaseCodeSubmissionDirectory(new File(basecodePath)));
         assertEquals(4, result.getNumberOfSubmissions());
     }
 
-    @Test
-    void testMultiRootDirBasecodeName() {
-        List<String> paths = List.of(getBasePath("basecode"), getBasePath("SimpleDuplicate"));
-        String basecodePath = "base"; // Should *not* find basecode/base
-        assertThrows(BasecodeException.class, () -> runJPlag(paths, it -> it.withBaseCodeSubmissionName(basecodePath)));
-    }
-
     @Test
     void testDisjunctNewAndOldRootDirectories() throws ExitException {
         List<String> newDirectories = List.of(getBasePath("SimpleDuplicate")); // 2 submissions
@@ -153,7 +145,7 @@ public class ParallelComparisonTest extends TestBase {
         String basecodePath = getBasePath("basecode", "base");
         List<String> newDirectories = List.of(getBasePath("SimpleDuplicate")); // 2 submissions
         List<String> oldDirectories = List.of(getBasePath("basecode")); // 3 - 1 submissions
-        JPlagResult result = runJPlag(newDirectories, oldDirectories, it -> it.withBaseCodeSubmissionName(basecodePath));
+        JPlagResult result = runJPlag(newDirectories, oldDirectories, it -> it.withBaseCodeSubmissionDirectory(new File(basecodePath)));
         int numberOfExpectedComparison = 1 + 2 * 2;
         assertEquals(numberOfExpectedComparison, result.getAllComparisons().size());
     }

+ 5 - 4
core/src/test/java/de/jplag/TestBase.java

@@ -5,16 +5,16 @@ import java.nio.file.Path;
 import java.util.List;
 import java.util.StringJoiner;
 import java.util.function.Function;
+import java.util.stream.Collectors;
 
 import de.jplag.exceptions.ExitException;
 import de.jplag.java.Language;
 import de.jplag.options.JPlagOptions;
-import de.jplag.options.Verbosity;
 
 public abstract class TestBase {
 
     protected static final String BASE_PATH = Path.of("src", "test", "resources", "de", "jplag", "samples").toString();
-    protected static final double DELTA = 0.1;
+    protected static final double DELTA = 0.001;
 
     protected String getBasePath() {
         return BASE_PATH;
@@ -48,9 +48,10 @@ public abstract class TestBase {
 
     protected JPlagResult runJPlag(List<String> newPaths, List<String> oldPaths, Function<JPlagOptions, JPlagOptions> customization)
             throws ExitException {
-        JPlagOptions options = new JPlagOptions(LanguageLoader.getLanguage(Language.IDENTIFIER).orElseThrow(), newPaths, oldPaths);
+        var newFiles = newPaths.stream().map(path -> new File(path)).collect(Collectors.toSet());
+        var oldFiles = oldPaths.stream().map(path -> new File(path)).collect(Collectors.toSet());
+        JPlagOptions options = new JPlagOptions(LanguageLoader.getLanguage(Language.IDENTIFIER).orElseThrow(), newFiles, oldFiles);
         options = customization.apply(options);
-        options = options.withVerbosity(Verbosity.LONG);
         JPlag jplag = new JPlag(options);
         return jplag.run();
     }

+ 1 - 1
core/src/test/java/de/jplag/special/VolumeTest.java

@@ -36,7 +36,7 @@ public class VolumeTest extends TestBase {
 
     /**
      * This test requires a folder "data" with submissions and a file named "matches_avg.csv" inside the volume folder.
-     * Accepts a derivation of 0.1% in the matching percentage
+     * Accepts a derivation of {@link #DELTA} in the matching similarity
      */
     @Test
     @Disabled

+ 7 - 0
core/src/test/resources/de/jplag/samples/SubdirectoryBase/src/SimpleDuplicate.java

@@ -0,0 +1,7 @@
+public class SimpleDuplicate {
+
+    public static void main(String[] args) {
+        System.out.println("Hello World!");
+    }
+
+}

+ 11 - 0
core/src/test/resources/de/jplag/samples/SubdirectoryDuplicate/A/src/SimpleDuplicate.java

@@ -0,0 +1,11 @@
+public class SimpleDuplicate {
+
+    public static void main(String[] args) {
+        System.out.println("Hello World!");
+
+        for(int i = 0; i < 10; i++) {
+            System.out.println("Number is " + i);
+        }
+    }
+
+}

+ 12 - 0
core/src/test/resources/de/jplag/samples/SubdirectoryDuplicate/B/src/SimpleDuplicate.java

@@ -0,0 +1,12 @@
+public class SimpleDuplicate {
+
+    public static void main(String[] args) {
+        System.out.println("Hello Plagiarism!");
+
+        int max = 10;
+        for(int j = 0; j < max; j++) {
+            System.out.println("Number is " + j);
+        }
+    }
+
+}

+ 7 - 0
core/src/test/resources/de/jplag/samples/SubdirectoryDuplicate/Base/src/SimpleDuplicate.java

@@ -0,0 +1,7 @@
+public class SimpleDuplicate {
+
+    public static void main(String[] args) {
+        System.out.println("Hello World!");
+    }
+
+}

+ 5 - 2
endtoend-testing/src/test/java/de/jplag/endtoend/EndToEndSuiteTest.java

@@ -3,6 +3,7 @@ package de.jplag.endtoend;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import java.io.File;
 import java.io.IOException;
 import java.nio.file.Path;
 import java.util.ArrayList;
@@ -13,7 +14,9 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Optional;
+import java.util.Set;
 import java.util.StringJoiner;
+import java.util.stream.Collectors;
 
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.DynamicTest;
@@ -147,8 +150,8 @@ public class EndToEndSuiteTest {
         String[] submissionPath = FileHelper.createNewTestCaseDirectory(testFiles);
 
         var language = LanguageLoader.getLanguage(languageIdentifier).orElseThrow();
-        JPlagOptions jplagOptions = new JPlagOptions(language, Arrays.asList(submissionPath), new ArrayList<>())
-                .withMinimumTokenMatch(options.minimumTokenMatch());
+        JPlagOptions jplagOptions = new JPlagOptions(language, Arrays.stream(submissionPath).map(path -> new File(path)).collect(Collectors.toSet()),
+                Set.of()).withMinimumTokenMatch(options.minimumTokenMatch());
         JPlagResult jplagResult = new JPlag(jplagOptions).run();
 
         List<JPlagComparison> currentJPlagComparison = jplagResult.getAllComparisons();

Разница между файлами не показана из-за своего большого размера
+ 317 - 317
endtoend-testing/src/test/resources/results/java/sortAlgo.json


+ 0 - 8
language-api/src/main/java/de/jplag/AbstractParser.java

@@ -8,17 +8,9 @@ import org.slf4j.LoggerFactory;
  * @author Emeric Kwemou
  */
 public abstract class AbstractParser {
-    protected int errors = 0;
     public final Logger logger;
 
     protected AbstractParser() {
         this.logger = LoggerFactory.getLogger(this.getClass());
     }
-
-    /**
-     * @return true if the last parse call (which could be still ongoing) lead to one or more errors.
-     */
-    public boolean hasErrors() {
-        return errors != 0;
-    }
 }

+ 5 - 10
language-api/src/main/java/de/jplag/Language.java

@@ -2,6 +2,7 @@ package de.jplag;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
 /**
  * Common interface for all languages. Each language-front end must provide a concrete language implementation.
@@ -29,17 +30,12 @@ public interface Language {
     int minimumTokenMatch();
 
     /**
-     * Parses a set files in a directory.
-     * @param directory is the directory where the files are located.
-     * @param files are the names of the files to parse.
+     * Parses a set of files.
+     * @param files are the files to parse.
      * @return the list of parsed JPlag tokens.
+     * @throws ParsingException if an error during parsing the files occurred.
      */
-    List<Token> parse(File directory, String[] files);
-
-    /**
-     * Whether errors were found during the last {@link #parse}.
-     */
-    boolean hasErrors();
+    List<Token> parse(Set<File> files) throws ParsingException;
 
     /**
      * Determines whether a fixed-width font should be used to display that language.
@@ -62,5 +58,4 @@ public interface Language {
     default String viewFileSuffix() {
         return "";
     }
-
 }

+ 1 - 1
language-api/src/main/java/de/jplag/LanguageLoader.java

@@ -16,7 +16,7 @@ import org.slf4j.LoggerFactory;
  * @author Dominik Fuchss
  */
 public final class LanguageLoader {
-    private static final Logger logger = LoggerFactory.getLogger(LanguageLoader.class);
+    private static final Logger logger = LoggerFactory.getLogger("JPlag");
 
     private static Map<String, Language> cachedLanguageInstances = null;
 

+ 87 - 0
language-api/src/main/java/de/jplag/ParsingException.java

@@ -0,0 +1,87 @@
+package de.jplag;
+
+import java.io.File;
+import java.io.Serial;
+import java.util.Collection;
+import java.util.stream.Collectors;
+
+/**
+ * An exception to throw if any error occurred while parsing files in a language frontend.
+ */
+public class ParsingException extends Exception {
+    @Serial
+    private static final long serialVersionUID = 4385949762027596330L; // generated
+
+    /**
+     * Constructs a new exception indicating a parsing exception in the given file without a specific reason.
+     * @param file the file in which a parsing error occurred. (A null value is permitted, and indicates that the file is
+     * nonexistent or unknown.)
+     */
+    public ParsingException(File file) {
+        this(file, (String) null);
+    }
+
+    /**
+     * Constructs a new exception indicating a parsing exception in the given file with the given reason.
+     * @param file the file in which a parsing error occurred. (A null value is permitted, and indicates that the file is
+     * nonexistent or unknown.)
+     * @param reason the reason the parsing failed. A null value is permitted.)
+     */
+    public ParsingException(File file, String reason) {
+        super(constructMessage(file, reason));
+    }
+
+    /**
+     * Constructs a new exception indicating a parsing exception in the given file with the given cause.
+     * @param file the file in which a parsing error occurred. (A null value is permitted, and indicates that the file is
+     * nonexistent or unknown.)
+     * @param cause the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
+     */
+    public ParsingException(File file, Throwable cause) {
+        this(file, null, cause);
+    }
+
+    /**
+     * Constructs a new exception indicating a parsing exception in the given file with the given reason and cause.
+     * @param file the file in which a parsing error occurred. (A null value is permitted, and indicates that the file is
+     * nonexistent or unknown.)
+     * @param reason the reason the parsing failed. A null value is permitted.)
+     * @param cause the cause. (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
+     */
+    public ParsingException(File file, String reason, Throwable cause) {
+        super(constructMessage(file, reason), cause);
+    }
+
+    /**
+     * Creates a new parsing exception which wraps the provided exceptions. If no exception to wrap is provided, null is
+     * returned. If only one exception is provided, it is returned.
+     * @param exceptions the collection of exceptions to wrap.
+     * @return a new parsing exception wrapping the provided exceptions, <code>null</code> if no exceptions are provided, or
+     * the provided exception if only one was provided.
+     */
+    public static ParsingException wrappingExceptions(Collection<ParsingException> exceptions) {
+        switch (exceptions.size()) {
+            case 0:
+                return null;
+            case 1:
+                return exceptions.iterator().next();
+            default: {
+                String message = exceptions.stream().map(ParsingException::getMessage).collect(Collectors.joining("\n"));
+                return new ParsingException(message);
+            }
+        }
+    }
+
+    private ParsingException(String message) {
+        super(message);
+    }
+
+    private static String constructMessage(File file, String reason) {
+        StringBuilder messageBuilder = new StringBuilder();
+        messageBuilder.append("failed to parse '%s'".formatted(file));
+        if (!reason.isEmpty() && !reason.isBlank()) {
+            messageBuilder.append(" with reason: %s".formatted(reason));
+        }
+        return messageBuilder.toString();
+    }
+}

+ 6 - 4
language-api/src/main/java/de/jplag/Token.java

@@ -1,5 +1,7 @@
 package de.jplag;
 
+import java.io.File;
+
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -16,14 +18,14 @@ public class Token {
     private int line;
     private int column;
     private int length;
-    private String file;
+    private File file;
     private TokenType type;
 
     /**
      * Creates a token of type {@link SharedTokenType#FILE_END FILE_END} without information about line, column, and length.
      * @param file is the name of the source code file.
      */
-    public static Token fileEnd(String file) {
+    public static Token fileEnd(File file) {
         return new Token(SharedTokenType.FILE_END, file, NO_VALUE, NO_VALUE, NO_VALUE);
     }
 
@@ -35,7 +37,7 @@ public class Token {
      * @param column is the column index, meaning where the token starts in the line. Index is 1-based.
      * @param length is the length of the token in the source code.
      */
-    public Token(TokenType type, String file, int line, int column, int length) {
+    public Token(TokenType type, File file, int line, int column, int length) {
         if (line == 0) {
             logger.warn("Creating a token with line index 0 while index is 1-based");
         }
@@ -60,7 +62,7 @@ public class Token {
     /**
      * @return the name of the file where the source code that the token represents is located in.
      */
-    public String getFile() {
+    public File getFile() {
         return file;
     }
 

+ 7 - 10
language-api/src/main/java/de/jplag/TokenPrinter.java

@@ -65,12 +65,12 @@ public final class TokenPrinter {
      */
     public static String printTokens(List<Token> tokenList, File rootDirectory, Optional<String> suffix) {
         PrinterOutputBuilder builder = new PrinterOutputBuilder();
-        Map<String, List<Token>> fileToTokens = groupTokensByFile(tokenList);
+        Map<File, List<Token>> fileToTokens = groupTokensByFile(tokenList);
 
-        fileToTokens.forEach((String fileName, List<Token> fileTokens) -> {
-            builder.append(fileName);
+        fileToTokens.forEach((File file, List<Token> fileTokens) -> {
+            builder.append(rootDirectory.toPath().relativize(file.toPath()).toString());
 
-            List<LineData> lineDatas = getLineData(fileTokens, rootDirectory, suffix);
+            List<LineData> lineDatas = getLineData(fileTokens, suffix);
             lineDatas.forEach(lineData -> {
                 builder.setLine(lineData.lineNumber());
 
@@ -113,12 +113,9 @@ public final class TokenPrinter {
         return builder.toString();
     }
 
-    private static List<LineData> getLineData(List<Token> fileTokens, File root, Optional<String> suffix) {
+    private static List<LineData> getLineData(List<Token> fileTokens, Optional<String> suffix) {
         // We expect that all fileTokens share the same Token.file!
-
-        String fileName = fileTokens.get(0).getFile();
-        // handle 'files as submissions' mode
-        File file = fileName.isEmpty() ? root : new File(root, fileName);
+        File file = fileTokens.get(0).getFile();
         if (suffix.isPresent()) {
             file = new File(file.getPath() + suffix.get());
         }
@@ -144,7 +141,7 @@ public final class TokenPrinter {
                 .toList();
     }
 
-    private static Map<String, List<Token>> groupTokensByFile(List<Token> tokens) {
+    private static Map<File, List<Token>> groupTokensByFile(List<Token> tokens) {
         return tokens.stream().collect(Collectors.groupingBy(Token::getFile));
     }
 

+ 23 - 22
language-api/src/test/java/de/jplag/TokenPrinterTest.java

@@ -1,9 +1,9 @@
 package de.jplag;
 
-import static de.jplag.SharedTokenType.FILE_END;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import java.io.File;
 import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.List;
@@ -28,37 +28,38 @@ class TokenPrinterTest {
 
         // See TokenPrinterTest.txt for the intended behaviour
         List<Token> tokens = new ArrayList<>();
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 1, 1, "STRING".length()));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 2, 1, "STRING".length() + 1));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 3, 1, "STRING".length() + 2));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 4, 1, "STRING".length() + 10));
+        File testFile = new File(TEST_FILE_LOCATION.toFile(), TEST_FILE_NAME);
+        tokens.add(new Token(TestTokenType.STRING, testFile, 1, 1, "STRING".length()));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 2, 1, "STRING".length() + 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 3, 1, "STRING".length() + 2));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 4, 1, "STRING".length() + 10));
 
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 6, 3, 1));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 7, 9, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 6, 3, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 7, 9, 1));
 
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 9, 1, 1));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 9, 10, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 9, 1, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 9, 10, 1));
 
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 10, 1, 1));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 10, 5, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 10, 1, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 10, 5, 1));
 
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 12, 1, 1));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 12, 5, 1));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 12, 10, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 12, 1, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 12, 5, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 12, 10, 1));
 
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 14, 10, 1));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 14, 5, 1));
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 14, 1, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 14, 10, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 14, 5, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 14, 1, 1));
 
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 16, -5, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 16, -5, 1));
 
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 19, 100, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 19, 100, 1));
 
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 22, 1, 100));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 22, 1, 100));
 
-        tokens.add(new Token(FILE_END, TEST_FILE_NAME, Token.NO_VALUE, Token.NO_VALUE, Token.NO_VALUE));
+        tokens.add(Token.fileEnd(testFile));
 
-        tokens.add(new Token(TestTokenType.STRING, TEST_FILE_NAME, 100, 1, 1));
+        tokens.add(new Token(TestTokenType.STRING, testFile, 100, 1, 1));
 
         String output = TokenPrinter.printTokens(tokens, TEST_FILE_LOCATION.toFile());
         logger.info(output); // no additional newline required

+ 7 - 6
language-testutils/src/test/java/de/jplag/testutils/TokenUtils.java

@@ -1,5 +1,6 @@
 package de.jplag.testutils;
 
+import java.io.File;
 import java.util.List;
 
 import de.jplag.Token;
@@ -14,21 +15,21 @@ public final class TokenUtils {
     /**
      * Returns the type of all tokens that belong to a certain file.
      * @param tokens is the list of {@link Token Tokens}.
-     * @param name is the name of the target file.
+     * @param file is the target file.
      * @return the immutable list of token types.
      */
-    public static List<TokenType> tokenTypesByFile(List<Token> tokens, String name) {
-        return tokensByFile(tokens, name).stream().map(Token::getType).toList();
+    public static List<TokenType> tokenTypesByFile(List<Token> tokens, File file) {
+        return tokensByFile(tokens, file).stream().map(Token::getType).toList();
     }
 
     /**
      * Returns the tokens that belong to a certain file.
      * @param tokens is the list of {@link Token Tokens}.
-     * @param name is the name of the target file.
+     * @param file is the target file.
      * @return the immutable list of tokens.
      */
-    public static List<Token> tokensByFile(List<Token> tokens, String name) {
-        return tokens.stream().filter(it -> it.getFile().startsWith(name)).toList();
+    public static List<Token> tokensByFile(List<Token> tokens, File file) {
+        return tokens.stream().filter(it -> it.getFile().equals(file)).toList();
     }
 
 }

+ 4 - 7
languages/cpp/src/main/java/de/jplag/cpp/Language.java

@@ -2,9 +2,11 @@ package de.jplag.cpp;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 @MetaInfServices(de.jplag.Language.class)
@@ -38,12 +40,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File dir, String[] files) {
-        return this.scanner.scan(dir, files);
-    }
-
-    @Override
-    public boolean hasErrors() {
-        return this.scanner.hasErrors();
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return this.scanner.scan(files);
     }
 }

+ 7 - 8
languages/cpp/src/main/java/de/jplag/cpp/Scanner.java

@@ -3,12 +3,14 @@ package de.jplag.cpp;
 import java.io.File;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 public class Scanner extends AbstractParser {
-    private String currentFile;
+    private File currentFile;
 
     private List<Token> tokens;
 
@@ -19,15 +21,12 @@ public class Scanner extends AbstractParser {
         super();
     }
 
-    public List<Token> scan(File directory, String[] files) {
+    public List<Token> scan(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        errors = 0;
-        for (String currentFile : files) {
-            this.currentFile = currentFile;
+        for (File file : files) {
+            this.currentFile = file;
             logger.trace("Scanning file {}", currentFile);
-            if (!CPPScanner.scanFile(directory, currentFile, this)) {
-                errors++;
-            }
+            CPPScanner.scanFile(file, this);
             tokens.add(Token.fileEnd(currentFile));
         }
         return tokens;

+ 10 - 9
languages/cpp/src/main/javacc/CPP.jj

@@ -19,30 +19,31 @@ import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 
+import de.jplag.ParsingException;
+
 import static de.jplag.cpp.CPPTokenType.*;
 
 public class CPPScanner {
     private Scanner delegatingScanner;
 
-    public static boolean scanFile(File dir, String fileName, Scanner delegatingScanner) {
+    public static void scanFile(File file, Scanner delegatingScanner) throws ParsingException {
         CPPScanner scanner;
-        try(InputStream input = new NewlineStream(new FileInputStream(new File(dir, fileName)))) {
+        try(InputStream input = new NewlineStream(new FileInputStream(file))) {
             scanner = new CPPScanner(input, "UTF-8");
             scanner.delegatingScanner = delegatingScanner;
         } catch (IOException e) {
-            System.out.println("C/C++ Scanner: File " + fileName + " not found.");
-            return false;
+            System.out.println("C/C++ Scanner: File " + file.getName() + " not found.");
+            throw new ParsingException(file, e.getMessage(), e);
         }
         try {
             scanner.scan();
         } catch (ParseException e) {
-            delegatingScanner.logger.error("Parsing Error in '" + fileName + "': " + e.getMessage());
-            return false;
+            delegatingScanner.logger.error("Parsing Error in '" + file.getName() + "': " + e.getMessage());
+            throw new ParsingException(file, e.getMessage(), e);
         } catch (TokenMgrException e) {
-            delegatingScanner.logger.error("Scanning Error in '" + fileName + "': " + e.getMessage());
-            return false;
+            delegatingScanner.logger.error("Scanning Error in '" + file.getName() + "': " + e.getMessage());
+            throw new ParsingException(file, e.getMessage(), e);
         }
-        return true;
     }
 }
 PARSER_END(CPPScanner)

+ 12 - 17
languages/csharp/src/main/java/de/jplag/csharp/CSharpParserAdapter.java

@@ -5,6 +5,7 @@ import java.io.FileInputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import org.antlr.v4.runtime.CharStreams;
 import org.antlr.v4.runtime.CommonTokenStream;
@@ -13,6 +14,7 @@ import org.antlr.v4.runtime.tree.ParseTree;
 import org.antlr.v4.runtime.tree.ParseTreeWalker;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.TokenType;
 import de.jplag.csharp.grammar.CSharpLexer;
@@ -25,7 +27,7 @@ import de.jplag.csharp.grammar.CSharpParser;
  */
 public class CSharpParserAdapter extends AbstractParser {
     private List<Token> tokens;
-    private String currentFile;
+    private File currentFile;
 
     /**
      * Creates the parser adapter.
@@ -35,27 +37,22 @@ public class CSharpParserAdapter extends AbstractParser {
     }
 
     /**
-     * Parses all tokens form a list of files.
-     * @param directory is the base directory.
-     * @param fileNames is the list of file names.
+     * Parses all tokens from a set of files.
+     * @param files is the set of files.
      * @return the list of parsed tokens.
      */
-    public List<Token> parse(File directory, List<String> fileNames) {
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        errors = 0;
-        for (String fileName : fileNames) {
-            if (!parseFile(directory, fileName)) {
-                errors++;
-            }
-            tokens.add(Token.fileEnd(fileName));
+        for (File file : files) {
+            parseFile(file);
+            tokens.add(Token.fileEnd(file));
         }
         return tokens;
     }
 
-    private boolean parseFile(File directory, String fileName) {
-        File file = new File(directory, fileName);
+    private void parseFile(File file) throws ParsingException {
         try (FileInputStream inputStream = new FileInputStream(file)) {
-            currentFile = fileName;
+            currentFile = file;
 
             // create a lexer, a parser and a buffer between them.
             CSharpLexer lexer = new CSharpLexer(CharStreams.fromStream(inputStream));
@@ -72,10 +69,8 @@ public class CSharpParserAdapter extends AbstractParser {
                 treeWalker.walk(new CSharpListener(this), parseTree);
             }
         } catch (IOException exception) {
-            logger.error("Parsing Error in '" + fileName + "':" + File.separator + exception, exception);
-            return false;
+            throw new ParsingException(file, exception.getMessage(), exception);
         }
-        return true;
     }
 
     /* package-private */ void addToken(TokenType type, int line, int column, int length) {

+ 4 - 8
languages/csharp/src/main/java/de/jplag/csharp/Language.java

@@ -1,11 +1,12 @@
 package de.jplag.csharp;
 
 import java.io.File;
-import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 /**
@@ -46,12 +47,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File dir, String[] files) {
-        return parser.parse(dir, Arrays.asList(files));
-    }
-
-    @Override
-    public boolean hasErrors() {
-        return parser.hasErrors();
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return parser.parse(files);
     }
 }

+ 4 - 3
languages/csharp/src/test/java/de/jplag/csharp/MinimalCSharpTest.java

@@ -26,12 +26,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.nio.file.Path;
 import java.util.List;
+import java.util.Set;
 
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import de.jplag.ParsingException;
 import de.jplag.SharedTokenType;
 import de.jplag.Token;
 import de.jplag.TokenPrinter;
@@ -54,15 +56,14 @@ class MinimalCSharpTest {
     }
 
     @Test
-    void testParsingTestClass() {
+    void testParsingTestClass() throws ParsingException {
         List<TokenType> expectedToken = List.of(CLASS, CLASS_BEGIN, FIELD, CONSTRUCTOR, LOCAL_VARIABLE, METHOD, METHOD_BEGIN, IF, IF_BEGIN,
                 INVOCATION, IF_END, IF_BEGIN, INVOCATION, IF_END, METHOD_END, PROPERTY, ACCESSORS_BEGIN, ACCESSOR_BEGIN, ACCESSOR_END, ACCESSOR_BEGIN,
                 ACCESSOR_END, ACCESSORS_END, FIELD, PROPERTY, ACCESSORS_BEGIN, ACCESSOR_BEGIN, RETURN, ACCESSOR_END, ACCESSOR_BEGIN, ASSIGNMENT,
                 ACCESSOR_END, ACCESSORS_END, CLASS_END, SharedTokenType.FILE_END);
 
         // Parse test input
-        String[] input = new String[] {TEST_SUBJECT};
-        List<Token> result = language.parse(baseDirectory, input);
+        List<Token> result = language.parse(Set.of(new File(baseDirectory, TEST_SUBJECT)));
         logger.info(TokenPrinter.printTokens(result, baseDirectory));
 
         // Compare parsed tokens:

+ 3 - 2
languages/emf-metamodel-dynamic/src/main/java/de/jplag/emf/dynamic/DynamicMetamodelToken.java

@@ -1,5 +1,6 @@
 package de.jplag.emf.dynamic;
 
+import java.io.File;
 import java.util.Optional;
 
 import org.eclipse.emf.ecore.EObject;
@@ -13,11 +14,11 @@ import de.jplag.emf.MetamodelToken;
  */
 public class DynamicMetamodelToken extends MetamodelToken {
 
-    public DynamicMetamodelToken(TokenType type, String file, EObject eObject) {
+    public DynamicMetamodelToken(TokenType type, File file, EObject eObject) {
         super(type, file, NO_VALUE, NO_VALUE, NO_VALUE, Optional.of(eObject));
     }
 
-    public DynamicMetamodelToken(TokenType type, String file) {
+    public DynamicMetamodelToken(TokenType type, File file) {
         super(type, file);
     }
 }

+ 8 - 5
languages/emf-metamodel-dynamic/src/test/java/de/jplag/emf/dynamic/MinimalDynamicMetamodelTest.java

@@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.File;
 import java.nio.file.Path;
+import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Optional;
@@ -16,6 +17,7 @@ import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.TokenPrinter;
 import de.jplag.TokenType;
@@ -39,17 +41,18 @@ class MinimalDynamicMetamodelTest {
     }
 
     @Test
-    void testBookstoreMetamodels() {
-        List<Token> result = language.parse(baseDirectory, TEST_SUBJECTS);
+    void testBookstoreMetamodels() throws ParsingException {
+        List<File> testFiles = Arrays.stream(TEST_SUBJECTS).map(path -> new File(BASE_PATH.toFile(), path)).toList();
+        List<Token> result = language.parse(new HashSet<>(testFiles));
         List<TokenType> tokenTypes = result.stream().map(Token::getType).toList();
         logger.debug(TokenPrinter.printTokens(result, baseDirectory, Optional.of(Language.VIEW_FILE_SUFFIX)));
         logger.info("parsed token types: " + tokenTypes.stream().map(TokenType::getDescription).toList().toString());
         assertEquals(64, tokenTypes.size());
         assertEquals(7, new HashSet<>(tokenTypes.stream().filter(DynamicMetamodelTokenType.class::isInstance).toList()).size());
 
-        var bookstoreTokens = TokenUtils.tokenTypesByFile(result, TEST_SUBJECTS[0]);
-        var bookstoreRenamedTokens = TokenUtils.tokenTypesByFile(result, TEST_SUBJECTS[2]);
-        var bookstoreExtendedTokens = TokenUtils.tokenTypesByFile(result, TEST_SUBJECTS[1]);
+        var bookstoreTokens = TokenUtils.tokenTypesByFile(result, testFiles.get(0));
+        var bookstoreRenamedTokens = TokenUtils.tokenTypesByFile(result, testFiles.get(2));
+        var bookstoreExtendedTokens = TokenUtils.tokenTypesByFile(result, testFiles.get(1));
         assertTrue(bookstoreTokens.size() < bookstoreExtendedTokens.size());
         assertIterableEquals(bookstoreTokens, bookstoreRenamedTokens);
     }

+ 4 - 8
languages/emf-metamodel/src/main/java/de/jplag/emf/Language.java

@@ -1,12 +1,13 @@
 package de.jplag.emf;
 
 import java.io.File;
-import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 
 import org.eclipse.emf.ecore.EcorePackage;
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.emf.parser.EcoreParser;
 
@@ -54,13 +55,8 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File dir, String[] files) {
-        return parser.parse(dir, Arrays.asList(files));
-    }
-
-    @Override
-    public boolean hasErrors() {
-        return parser.hasErrors();
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return parser.parse(files);
     }
 
     @Override

+ 7 - 6
languages/emf-metamodel/src/main/java/de/jplag/emf/MetamodelToken.java

@@ -1,5 +1,6 @@
 package de.jplag.emf;
 
+import java.io.File;
 import java.util.Optional;
 
 import org.eclipse.emf.ecore.EObject;
@@ -18,32 +19,32 @@ public class MetamodelToken extends Token {
     /**
      * Creates an Ecore metamodel token that corresponds to an EObject.
      * @param type is the type of the token.
-     * @param file is the name of the source model file.
+     * @param file is the source model file.
      * @param eObject is the corresponding eObject in the model from which this token was extracted.
      */
-    public MetamodelToken(MetamodelTokenType type, String file, EObject eObject) {
+    public MetamodelToken(MetamodelTokenType type, File file, EObject eObject) {
         this(type, file, NO_VALUE, NO_VALUE, NO_VALUE, Optional.of(eObject));
     }
 
     /**
      * Creates an Ecore metamodel token.
      * @param type is the type of the token.
-     * @param file is the name of the source model file.
+     * @param file is the source model file.
      */
-    public MetamodelToken(TokenType type, String file) {
+    public MetamodelToken(TokenType type, File file) {
         this(type, file, NO_VALUE, NO_VALUE, NO_VALUE, Optional.empty());
     }
 
     /**
      * Creates a token with column and length information.
      * @param type is the token type.
-     * @param file is the name of the source code file.
+     * @param file is the source code file.
      * @param line is the line index in the source code where the token resides. Cannot be smaller than 1.
      * @param column is the column index, meaning where the token starts in the line.
      * @param length is the length of the token in the source code.
      * @param eObject is the corresponding eObject in the model from which this token was extracted
      */
-    public MetamodelToken(TokenType type, String file, int line, int column, int length, Optional<EObject> eObject) {
+    public MetamodelToken(TokenType type, File file, int line, int column, int length, Optional<EObject> eObject) {
         super(type, file, line, column, length);
         this.eObject = eObject;
     }

+ 14 - 15
languages/emf-metamodel/src/main/java/de/jplag/emf/parser/EcoreParser.java

@@ -3,10 +3,12 @@ package de.jplag.emf.parser;
 import java.io.File;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import org.eclipse.emf.ecore.EObject;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.emf.Language;
 import de.jplag.emf.MetamodelToken;
@@ -21,7 +23,7 @@ import de.jplag.emf.util.MetamodelTreeView;
  */
 public class EcoreParser extends AbstractParser {
     protected List<Token> tokens;
-    protected String currentFile;
+    protected File currentFile;
     protected MetamodelTreeView treeView;
     protected AbstractMetamodelVisitor visitor;
 
@@ -33,31 +35,28 @@ public class EcoreParser extends AbstractParser {
     }
 
     /**
-     * Parses all tokens form a list of files.
-     * @param directory is the base directory.
-     * @param fileNames is the list of file names.
+     * Parses all tokens from a set of files.
+     * @param files is the set of files.
      * @return the list of parsed tokens.
      */
-    public List<Token> parse(File directory, List<String> fileNames) {
-        errors = 0;
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        for (String fileName : fileNames) {
-            currentFile = fileName;
-            String filePath = fileName.isEmpty() ? directory.toString() : directory.toString() + File.separator + fileName;
-            parseModelFile(filePath);
+        for (File file : files) {
+            parseModelFile(file);
         }
         return tokens;
     }
 
     /**
      * Loads a metamodel from a file and parses it.
-     * @param filePath is the path to the metamodel file.
+     * @param file is the metamodel file.
      */
-    protected void parseModelFile(String filePath) {
-        treeView = new MetamodelTreeView(filePath);
-        List<EObject> model = EMFUtil.loadModel(filePath);
+    protected void parseModelFile(File file) throws ParsingException {
+        currentFile = file;
+        treeView = new MetamodelTreeView(file);
+        List<EObject> model = EMFUtil.loadModel(file);
         if (model == null) {
-            errors++;
+            throw new ParsingException(file, "failed to load model");
         } else {
             for (EObject root : model) {
                 visitor = createMetamodelVisitor();

+ 4 - 5
languages/emf-metamodel/src/main/java/de/jplag/emf/util/EMFUtil.java

@@ -57,17 +57,16 @@ public final class EMFUtil {
 
     /**
      * Loads a model or metamodel from a absolute file path.
-     * @param filePath is the absolute path to the (meta)model.
+     * @param file is file to the (meta)model.
      * @return the content of the loaded (meta)model resource or null if it could not be loaded.
      */
-    public static List<EObject> loadModel(String filePath) {
+    public static List<EObject> loadModel(File file) {
         final ResourceSet resourceSet = new ResourceSetImpl();
         try {
-            final Resource resource = resourceSet.getResource(URI.createFileURI(filePath), true);
+            final Resource resource = resourceSet.getResource(URI.createFileURI(file.getAbsolutePath()), true);
             return resource.getContents();
         } catch (WrappedException exception) {
-            String name = new File(filePath).getName();
-            logger.error("Could not load " + name + ": " + exception.getCause().getMessage());
+            logger.error("Could not load {}: {}", file, exception.getCause().getMessage());
         }
         return null;
     }

+ 5 - 5
languages/emf-metamodel/src/main/java/de/jplag/emf/util/MetamodelTreeView.java

@@ -19,7 +19,7 @@ import de.jplag.emf.MetamodelToken;
  * @author Timur Saglam
  */
 public class MetamodelTreeView {
-    private final String filePath;
+    private final File file;
     private int lineIndex;
     private int columnIndex;
     private final StringBuilder viewBuilder;
@@ -28,10 +28,10 @@ public class MetamodelTreeView {
 
     /**
      * Creates a tree view for a metamodel.
-     * @param filePath is the path to the file where the metamodel is persisted.
+     * @param file is the file where the metamodel is persisted.
      */
-    public MetamodelTreeView(String filePath) {
-        this.filePath = filePath;
+    public MetamodelTreeView(File file) {
+        this.file = file;
         logger = LoggerFactory.getLogger(this.getClass());
         viewBuilder = new StringBuilder();
     }
@@ -85,7 +85,7 @@ public class MetamodelTreeView {
      * @param suffix is the suffix of the file to be written.
      */
     public void writeToFile(String suffix) {
-        File treeViewFile = new File(filePath + suffix);
+        File treeViewFile = new File(file, suffix);
         try (BufferedWriter writer = new BufferedWriter(new FileWriter(treeViewFile));) {
             if (!treeViewFile.createNewFile()) {
                 logger.warn("Overwriting tree view file: {}", treeViewFile);

+ 8 - 5
languages/emf-metamodel/src/test/java/de/jplag/emf/MinimalMetamodelTest.java

@@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.File;
 import java.nio.file.Path;
+import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Optional;
@@ -16,6 +17,7 @@ import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.TokenPrinter;
 import de.jplag.TokenType;
@@ -39,8 +41,9 @@ class MinimalMetamodelTest {
     }
 
     @Test
-    void testBookstoreMetamodels() {
-        List<Token> result = language.parse(baseDirectory, TEST_SUBJECTS);
+    void testBookstoreMetamodels() throws ParsingException {
+        List<File> testFiles = Arrays.stream(TEST_SUBJECTS).map(path -> new File(BASE_PATH.toFile(), path)).toList();
+        List<Token> result = language.parse(new HashSet<>(testFiles));
 
         logger.debug(TokenPrinter.printTokens(result, baseDirectory, Optional.of(Language.VIEW_FILE_SUFFIX)));
         List<TokenType> tokenTypes = result.stream().map(Token::getType).toList();
@@ -48,9 +51,9 @@ class MinimalMetamodelTest {
         assertEquals(43, tokenTypes.size());
         assertEquals(10, new HashSet<>(tokenTypes).size());
 
-        var bookstoreTokens = TokenUtils.tokenTypesByFile(result, TEST_SUBJECTS[0]);
-        var bookstoreRenamedTokens = TokenUtils.tokenTypesByFile(result, TEST_SUBJECTS[2]);
-        var bookstoreExtendedTokens = TokenUtils.tokenTypesByFile(result, TEST_SUBJECTS[1]);
+        var bookstoreTokens = TokenUtils.tokenTypesByFile(result, testFiles.get(0));
+        var bookstoreRenamedTokens = TokenUtils.tokenTypesByFile(result, testFiles.get(2));
+        var bookstoreExtendedTokens = TokenUtils.tokenTypesByFile(result, testFiles.get(1));
         assertTrue(bookstoreTokens.size() < bookstoreExtendedTokens.size());
         assertIterableEquals(bookstoreTokens, bookstoreRenamedTokens);
     }

+ 9 - 12
languages/golang/src/main/java/de/jplag/golang/GoParserAdapter.java

@@ -5,6 +5,7 @@ import java.io.FileInputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import org.antlr.v4.runtime.CharStreams;
 import org.antlr.v4.runtime.CommonTokenStream;
@@ -13,30 +14,28 @@ import org.antlr.v4.runtime.tree.ParseTree;
 import org.antlr.v4.runtime.tree.ParseTreeWalker;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.TokenType;
 import de.jplag.golang.grammar.GoLexer;
 import de.jplag.golang.grammar.GoParser;
 
 public class GoParserAdapter extends AbstractParser {
-    private String currentFile;
+    private File currentFile;
     private List<Token> tokens;
 
-    public List<Token> parse(File directory, String[] fileNames) {
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        for (String file : fileNames) {
-            if (!parseFile(directory, file)) {
-                errors++;
-            }
+        for (File file : files) {
+            parseFile(file);
             tokens.add(Token.fileEnd(file));
         }
         return tokens;
     }
 
-    private boolean parseFile(File directory, String fileName) {
-        File file = new File(directory, fileName);
+    private void parseFile(File file) throws ParsingException {
         try (FileInputStream inputStream = new FileInputStream(file)) {
-            currentFile = fileName;
+            currentFile = file;
 
             GoLexer lexer = new GoLexer(CharStreams.fromStream(inputStream));
             CommonTokenStream tokenStream = new CommonTokenStream(lexer);
@@ -51,10 +50,8 @@ public class GoParserAdapter extends AbstractParser {
                 treeWalker.walk(listener, parseTree);
             }
         } catch (IOException exception) {
-            logger.error("Parsing Error in '%s':".formatted(fileName), exception);
-            return false;
+            throw new ParsingException(file, exception.getMessage(), exception);
         }
-        return true;
     }
 
     public void addToken(TokenType tokenType, int line, int column, int length) {

+ 4 - 8
languages/golang/src/main/java/de/jplag/golang/Language.java

@@ -2,9 +2,11 @@ package de.jplag.golang;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 @MetaInfServices(de.jplag.Language.class)
@@ -41,13 +43,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File directory, String[] files) {
-        return parserAdapter.parse(directory, files);
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return parserAdapter.parse(files);
     }
-
-    @Override
-    public boolean hasErrors() {
-        return parserAdapter.hasErrors();
-    }
-
 }

+ 4 - 2
languages/golang/src/test/java/de/jplag/golang/GoLanguageTest.java

@@ -12,6 +12,7 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.Objects;
 import java.util.OptionalInt;
+import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 
@@ -20,6 +21,7 @@ import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import de.jplag.ParsingException;
 import de.jplag.SharedTokenType;
 import de.jplag.Token;
 import de.jplag.TokenPrinter;
@@ -56,9 +58,9 @@ class GoLanguageTest {
     }
 
     @Test
-    void parseTestFiles() {
+    void parseTestFiles() throws ParsingException {
         for (String fileName : testFiles) {
-            List<Token> tokens = language.parse(testFileLocation, new String[] {fileName});
+            List<Token> tokens = language.parse(Set.of(new File(testFileLocation, fileName)));
             String output = TokenPrinter.printTokens(tokens, testFileLocation);
             logger.info(output);
 

+ 27 - 25
languages/java/src/main/java/de/jplag/java/JavacAdapter.java

@@ -3,14 +3,16 @@ package de.jplag.java;
 import java.io.File;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
-import java.nio.file.Paths;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+import java.util.Locale;
+import java.util.Set;
 
-import javax.tools.Diagnostic;
 import javax.tools.DiagnosticCollector;
 import javax.tools.JavaCompiler;
 import javax.tools.JavaCompiler.CompilationTask;
+import javax.tools.JavaFileObject;
 import javax.tools.StandardJavaFileManager;
 import javax.tools.ToolProvider;
 
@@ -22,17 +24,19 @@ import com.sun.source.util.JavacTask;
 import com.sun.source.util.SourcePositions;
 import com.sun.source.util.Trees;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 public class JavacAdapter {
 
     private static final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
 
-    public int parseFiles(File directory, Iterable<File> pathedFiles, final Parser parser) {
+    public void parseFiles(Set<File> files, final Parser parser) throws ParsingException {
         var listener = new DiagnosticCollector<>();
 
+        List<ParsingException> parsingExceptions = new ArrayList<>();
         try (final StandardJavaFileManager fileManager = javac.getStandardFileManager(listener, null, StandardCharsets.UTF_8)) {
-            var javaFiles = fileManager.getJavaFileObjectsFromFiles(pathedFiles);
+            var javaFiles = fileManager.getJavaFileObjectsFromFiles(files);
 
             // We need to disable annotation processing, see
             // https://stackoverflow.com/questions/72737445/system-java-compiler-behaves-different-depending-on-dependencies-defined-in-mave
@@ -40,15 +44,20 @@ public class JavacAdapter {
             final Trees trees = Trees.instance(task);
             final SourcePositions positions = trees.getSourcePositions();
             for (final CompilationUnitTree ast : executeCompilationTask(task, parser.logger)) {
-                final String filename = fileNameOf(directory, ast);
+                File file = new File(ast.getSourceFile().toUri());
                 final LineMap map = ast.getLineMap();
-                ast.accept(new TokenGeneratingTreeScanner(filename, parser, map, positions, ast), null);
-                parser.add(Token.fileEnd(filename));
+                var scanner = new TokenGeneratingTreeScanner(file, parser, map, positions, ast);
+                ast.accept(scanner, null);
+                parsingExceptions.addAll(scanner.getParsingExceptions());
+                parser.add(Token.fileEnd(file));
             }
         } catch (IOException exception) {
-            parser.logger.error(exception.getMessage(), exception);
+            throw new ParsingException(null, exception.getMessage(), exception);
+        }
+        parsingExceptions.addAll(processErrors(parser.logger, listener));
+        if (!parsingExceptions.isEmpty()) {
+            throw ParsingException.wrappingExceptions(parsingExceptions);
         }
-        return processErrors(parser.logger, listener);
     }
 
     private Iterable<? extends CompilationUnitTree> executeCompilationTask(final CompilationTask task, Logger logger) {
@@ -61,23 +70,16 @@ public class JavacAdapter {
         return abstractSyntaxTrees;
     }
 
-    private String fileNameOf(File directory, final CompilationUnitTree ast) {
-        if (directory == null)
-            return ast.getSourceFile().getName();
-        else {
-            return Paths.get(directory.toURI()).relativize(Paths.get(ast.getSourceFile().toUri())).toString();
-        }
-    }
-
-    private int processErrors(Logger logger, DiagnosticCollector<Object> listener) {
-        int errors = 0;
-        for (Diagnostic<?> diagnosticItem : listener.getDiagnostics()) {
-            if (diagnosticItem.getKind() == javax.tools.Diagnostic.Kind.ERROR) {
-                logger.error("{}", diagnosticItem);
-                errors++;
+    private List<ParsingException> processErrors(Logger logger, DiagnosticCollector<Object> listener) {
+        return listener.getDiagnostics().stream().filter(it -> it.getKind() == javax.tools.Diagnostic.Kind.ERROR).map(diagnosticItem -> {
+            File file = null;
+            if (diagnosticItem.getSource() instanceof JavaFileObject) {
+                JavaFileObject fileObject = (JavaFileObject) diagnosticItem.getSource();
+                file = new File(fileObject.toUri());
             }
-        }
-        return errors;
+            logger.error("{}", diagnosticItem);
+            return new ParsingException(file, diagnosticItem.getMessage(Locale.getDefault()));
+        }).toList();
     }
 
 }

+ 4 - 8
languages/java/src/main/java/de/jplag/java/Language.java

@@ -2,9 +2,11 @@ package de.jplag.java;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 /**
@@ -41,13 +43,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File directory, String[] files) {
-        return this.parser.parse(directory, files);
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return this.parser.parse(files);
     }
-
-    @Override
-    public boolean hasErrors() {
-        return this.parser.hasErrors();
-    }
-
 }

+ 6 - 11
languages/java/src/main/java/de/jplag/java/Parser.java

@@ -2,10 +2,11 @@ package de.jplag.java;
 
 import java.io.File;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.TokenType;
 
@@ -19,23 +20,17 @@ public class Parser extends AbstractParser {
         super();
     }
 
-    public List<Token> parse(File directory, String[] files) {
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        errors = 0;
-        var pathedFiles = Arrays.stream(files).map(it -> new File(directory, it)).toList();
-        errors += new JavacAdapter().parseFiles(directory, pathedFiles, this);
+        new JavacAdapter().parseFiles(files, this);
         return tokens;
     }
 
-    public void add(TokenType type, String filename, long line, long column, long length) {
-        add(new Token(type, filename, (int) line, (int) column, (int) length));
+    public void add(TokenType type, File file, long line, long column, long length) {
+        add(new Token(type, file, (int) line, (int) column, (int) length));
     }
 
     public void add(Token token) {
         tokens.add(token);
     }
-
-    public void increaseErrors() {
-        errors++;
-    }
 }

+ 18 - 6
languages/java/src/main/java/de/jplag/java/TokenGeneratingTreeScanner.java

@@ -1,5 +1,9 @@
 package de.jplag.java;
 
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+
 import com.sun.source.tree.AnnotationTree;
 import com.sun.source.tree.AssertTree;
 import com.sun.source.tree.AssignmentTree;
@@ -42,21 +46,29 @@ import com.sun.source.tree.YieldTree;
 import com.sun.source.util.SourcePositions;
 import com.sun.source.util.TreeScanner;
 
+import de.jplag.ParsingException;
+
 final class TokenGeneratingTreeScanner extends TreeScanner<Object, Object> {
-    private final String filename;
+    private final File file;
     private final Parser parser;
     private final LineMap map;
     private final SourcePositions positions;
     private final CompilationUnitTree ast;
 
-    public TokenGeneratingTreeScanner(String filename, Parser parser, LineMap map, SourcePositions positions, CompilationUnitTree ast) {
-        this.filename = filename;
+    private List<ParsingException> parsingExceptions = new ArrayList<>();
+
+    public TokenGeneratingTreeScanner(File file, Parser parser, LineMap map, SourcePositions positions, CompilationUnitTree ast) {
+        this.file = file;
         this.parser = parser;
         this.map = map;
         this.positions = positions;
         this.ast = ast;
     }
 
+    public List<ParsingException> getParsingExceptions() {
+        return parsingExceptions;
+    }
+
     /**
      * Convenience method that adds a specific token.
      * @param tokenType is the type of the token.
@@ -64,7 +76,7 @@ final class TokenGeneratingTreeScanner extends TreeScanner<Object, Object> {
      * @param length is the length of the token.
      */
     private void addToken(JavaTokenType tokenType, long position, int length) {
-        parser.add(tokenType, filename, map.getLineNumber(position), map.getColumnNumber(position), length);
+        parser.add(tokenType, file, map.getLineNumber(position), map.getColumnNumber(position), length);
     }
 
     /**
@@ -74,7 +86,7 @@ final class TokenGeneratingTreeScanner extends TreeScanner<Object, Object> {
      * @param end is the end position of the token for the calculation of the length.
      */
     private void addToken(JavaTokenType tokenType, long start, long end) {
-        parser.add(tokenType, filename, map.getLineNumber(start), map.getColumnNumber(start), (end - start));
+        parser.add(tokenType, file, map.getLineNumber(start), map.getColumnNumber(start), (end - start));
     }
 
     @Override
@@ -391,7 +403,7 @@ final class TokenGeneratingTreeScanner extends TreeScanner<Object, Object> {
 
     @Override
     public Object visitErroneous(ErroneousTree node, Object p) {
-        parser.increaseErrors();
+        parsingExceptions.add(new ParsingException(file, "error while visiting %s".formatted(node)));
         return super.visitErroneous(node, p);
     }
 

+ 11 - 15
languages/kotlin/src/main/java/de/jplag/kotlin/KotlinParserAdapter.java

@@ -5,6 +5,7 @@ import java.io.FileInputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import org.antlr.v4.runtime.CharStreams;
 import org.antlr.v4.runtime.CommonTokenStream;
@@ -13,12 +14,13 @@ import org.antlr.v4.runtime.tree.ParseTree;
 import org.antlr.v4.runtime.tree.ParseTreeWalker;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.kotlin.grammar.KotlinLexer;
 import de.jplag.kotlin.grammar.KotlinParser;
 
 public class KotlinParserAdapter extends AbstractParser {
-    private String currentFile;
+    private File currentFile;
     private List<Token> tokens;
 
     /**
@@ -29,26 +31,22 @@ public class KotlinParserAdapter extends AbstractParser {
     }
 
     /**
-     * Parsers a list of files into a single list of {@link Token}s.
-     * @param directory the directory of the files.
-     * @param fileNames the file names of the files.
+     * Parsers a set of files into a single list of {@link Token}s.
+     * @param files the set of files.
      * @return a list containing all tokens of all files.
      */
-    public List<Token> parse(File directory, String[] fileNames) {
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        for (String file : fileNames) {
-            if (!parseFile(directory, file)) {
-                errors++;
-            }
+        for (File file : files) {
+            parseFile(file);
             tokens.add(Token.fileEnd(file));
         }
         return tokens;
     }
 
-    private boolean parseFile(File directory, String fileName) {
-        File file = new File(directory, fileName);
+    private void parseFile(File file) throws ParsingException {
         try (FileInputStream inputStream = new FileInputStream(file)) {
-            currentFile = fileName;
+            currentFile = file;
 
             KotlinLexer lexer = new KotlinLexer(CharStreams.fromStream(inputStream));
             CommonTokenStream tokenStream = new CommonTokenStream(lexer);
@@ -63,10 +61,8 @@ public class KotlinParserAdapter extends AbstractParser {
                 treeWalker.walk(listener, parseTree);
             }
         } catch (IOException exception) {
-            logger.error("Parsing Error in '{}': {}{}", fileName, File.separator, exception);
-            return false;
+            throw new ParsingException(file, exception.getMessage(), exception);
         }
-        return true;
     }
 
     /**

+ 4 - 7
languages/kotlin/src/main/java/de/jplag/kotlin/Language.java

@@ -2,9 +2,11 @@ package de.jplag.kotlin;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 /**
@@ -44,12 +46,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File directory, String[] files) {
-        return parserAdapter.parse(directory, files);
-    }
-
-    @Override
-    public boolean hasErrors() {
-        return parserAdapter.hasErrors();
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return parserAdapter.parse(files);
     }
 }

+ 4 - 2
languages/kotlin/src/test/java/de/jplag/kotlin/KotlinLanguageTest.java

@@ -10,6 +10,7 @@ import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 
@@ -18,6 +19,7 @@ import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import de.jplag.ParsingException;
 import de.jplag.SharedTokenType;
 import de.jplag.Token;
 import de.jplag.TokenPrinter;
@@ -55,9 +57,9 @@ class KotlinLanguageTest {
     }
 
     @Test
-    void parseTestFiles() {
+    void parseTestFiles() throws ParsingException {
         for (String fileName : testFiles) {
-            List<Token> tokens = language.parse(testFileLocation, new String[] {fileName});
+            List<Token> tokens = language.parse(Set.of(new File(testFileLocation, fileName)));
             String output = TokenPrinter.printTokens(tokens, testFileLocation);
             logger.info(output);
 

+ 4 - 7
languages/python-3/src/main/java/de/jplag/python3/Language.java

@@ -2,9 +2,11 @@ package de.jplag.python3;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 @MetaInfServices(de.jplag.Language.class)
@@ -39,12 +41,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File dir, String[] files) {
-        return this.parser.parse(dir, files);
-    }
-
-    @Override
-    public boolean hasErrors() {
-        return this.parser.hasErrors();
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return this.parser.parse(files);
     }
 }

+ 13 - 25
languages/python-3/src/main/java/de/jplag/python3/Parser.java

@@ -1,19 +1,19 @@
 package de.jplag.python3;
 
-import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
-import org.antlr.v4.runtime.CharStream;
 import org.antlr.v4.runtime.CharStreams;
 import org.antlr.v4.runtime.CommonTokenStream;
 import org.antlr.v4.runtime.tree.ParseTree;
 import org.antlr.v4.runtime.tree.ParseTreeWalker;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.TokenType;
 import de.jplag.python3.grammar.Python3Lexer;
@@ -23,7 +23,7 @@ import de.jplag.python3.grammar.Python3Parser.File_inputContext;
 public class Parser extends AbstractParser {
 
     private List<Token> tokens;
-    private String currentFile;
+    private File currentFile;
 
     /**
      * Creates the parser.
@@ -32,30 +32,22 @@ public class Parser extends AbstractParser {
         super();
     }
 
-    public List<Token> parse(File directory, String[] files) {
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        errors = 0;
-        for (String file : files) {
-            logger.trace("Parsing file {}", file);
-            if (!parseFile(directory, file)) {
-                errors++;
-            }
+        for (File file : files) {
+            logger.trace("Parsing file {}", file.getName());
+            parseFile(file);
             tokens.add(Token.fileEnd(file));
         }
         return tokens;
     }
 
-    private boolean parseFile(File directory, String file) {
-        BufferedInputStream inputStream;
-
-        CharStream input;
-        try {
-            inputStream = new BufferedInputStream(new FileInputStream(new File(directory, file)));
+    private void parseFile(File file) throws ParsingException {
+        try (FileInputStream fileInputStream = new FileInputStream((file))) {
             currentFile = file;
-            input = CharStreams.fromStream(inputStream);
 
             // create a lexer that feeds off of input CharStream
-            Python3Lexer lexer = new Python3Lexer(input);
+            Python3Lexer lexer = new Python3Lexer(CharStreams.fromStream(fileInputStream));
 
             // create a buffer of tokens pulled from the lexer
             CommonTokenStream tokens = new CommonTokenStream(lexer);
@@ -71,19 +63,15 @@ public class Parser extends AbstractParser {
             }
 
         } catch (IOException e) {
-            logger.error("Parsing Error in '" + file + "': " + e.getMessage(), e);
-            return false;
+            throw new ParsingException(file, e.getMessage(), e);
         }
-
-        return true;
     }
 
     public void add(TokenType type, org.antlr.v4.runtime.Token token) {
-        tokens.add(new Token(type, (currentFile == null ? "null" : currentFile), token.getLine(), token.getCharPositionInLine() + 1,
-                token.getText().length()));
+        tokens.add(new Token(type, currentFile, token.getLine(), token.getCharPositionInLine() + 1, token.getText().length()));
     }
 
     public void addEnd(TokenType type, org.antlr.v4.runtime.Token token) {
-        tokens.add(new Token(type, (currentFile == null ? "null" : currentFile), token.getLine(), tokens.get(tokens.size() - 1).getColumn() + 1, 0));
+        tokens.add(new Token(type, currentFile, token.getLine(), tokens.get(tokens.size() - 1).getColumn() + 1, 0));
     }
 }

+ 4 - 7
languages/rlang/src/main/java/de/jplag/rlang/Language.java

@@ -2,9 +2,11 @@ package de.jplag.rlang;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 /**
@@ -44,12 +46,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File directory, String[] files) {
-        return parserAdapter.parse(directory, files);
-    }
-
-    @Override
-    public boolean hasErrors() {
-        return parserAdapter.hasErrors();
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return parserAdapter.parse(files);
     }
 }

+ 12 - 17
languages/rlang/src/main/java/de/jplag/rlang/RParserAdapter.java

@@ -5,6 +5,7 @@ import java.io.FileInputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import org.antlr.v4.runtime.CharStreams;
 import org.antlr.v4.runtime.CommonTokenStream;
@@ -13,6 +14,7 @@ import org.antlr.v4.runtime.tree.ParseTree;
 import org.antlr.v4.runtime.tree.ParseTreeWalker;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.TokenType;
 import de.jplag.rlang.grammar.RFilter;
@@ -25,7 +27,7 @@ import de.jplag.rlang.grammar.RParser;
  */
 public class RParserAdapter extends AbstractParser {
 
-    private String currentFile;
+    private File currentFile;
     private List<Token> tokens;
 
     /**
@@ -36,27 +38,22 @@ public class RParserAdapter extends AbstractParser {
     }
 
     /**
-     * Parsers a list of files into a single token list of {@link Token}s.
-     * @param directory the directory of the files.
-     * @param fileNames the file names of the files.
+     * Parsers a set of files into a single token list of {@link Token}s.
+     * @param files the set of files.
      * @return a list containing all tokens of all files.
      */
-    public List<Token> parse(File directory, String[] fileNames) {
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        errors = 0;
-        for (String fileName : fileNames) {
-            if (!parseFile(directory, fileName)) {
-                errors++;
-            }
-            tokens.add(Token.fileEnd(fileName));
+        for (File file : files) {
+            parseFile(file);
+            tokens.add(Token.fileEnd(file));
         }
         return tokens;
     }
 
-    private boolean parseFile(File directory, String fileName) {
-        File file = new File(directory, fileName);
+    private void parseFile(File file) throws ParsingException {
         try (FileInputStream inputStream = new FileInputStream(file)) {
-            currentFile = fileName;
+            currentFile = file;
 
             // create a lexer, a parser and a buffer between them.
             RLexer lexer = new RLexer(CharStreams.fromStream(inputStream));
@@ -78,10 +75,8 @@ public class RParserAdapter extends AbstractParser {
                 treeWalker.walk(new JPlagRListener(this), parseTree);
             }
         } catch (IOException exception) {
-            logger.error("Parsing Error in '" + fileName + "': " + File.separator + exception.getMessage(), exception);
-            return false;
+            throw new ParsingException(file, exception.getMessage(), exception);
         }
-        return true;
     }
 
     /**

+ 4 - 2
languages/rlang/src/test/java/de/jplag/rlang/RLanguageTest.java

@@ -10,6 +10,7 @@ import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 
@@ -18,6 +19,7 @@ import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import de.jplag.ParsingException;
 import de.jplag.SharedTokenType;
 import de.jplag.Token;
 import de.jplag.TokenPrinter;
@@ -45,9 +47,9 @@ class RLanguageTest {
     }
 
     @Test
-    void parseTestFiles() {
+    void parseTestFiles() throws ParsingException {
         for (String fileName : testFiles) {
-            List<Token> tokens = language.parse(testFileLocation, new String[] {fileName});
+            List<Token> tokens = language.parse(Set.of(new File(testFileLocation, fileName)));
             String output = TokenPrinter.printTokens(tokens, testFileLocation);
             logger.info(output);
 

+ 4 - 8
languages/rust/src/main/java/de/jplag/rust/Language.java

@@ -2,7 +2,9 @@ package de.jplag.rust;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 public class Language implements de.jplag.Language {
@@ -39,13 +41,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File directory, String[] files) {
-        return parserAdapter.parse(directory, files);
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return parserAdapter.parse(files);
     }
-
-    @Override
-    public boolean hasErrors() {
-        return parserAdapter.hasErrors();
-    }
-
 }

+ 12 - 17
languages/rust/src/main/java/de/jplag/rust/RustParserAdapter.java

@@ -5,6 +5,7 @@ import java.io.FileInputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import org.antlr.v4.runtime.CharStreams;
 import org.antlr.v4.runtime.CommonTokenStream;
@@ -13,37 +14,33 @@ import org.antlr.v4.runtime.tree.ParseTree;
 import org.antlr.v4.runtime.tree.ParseTreeWalker;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.rust.grammar.RustLexer;
 import de.jplag.rust.grammar.RustParser;
 
 public class RustParserAdapter extends AbstractParser {
 
-    private String currentFile;
+    private File currentFile;
     private List<Token> tokens;
 
     /**
-     * Parsers a list of files into a single list of {@link Token}s.
-     * @param directory the directory of the files.
-     * @param fileNames the file names of the files.
+     * Parsers a set of files into a single list of {@link Token}s.
+     * @param files the set of files.
      * @return a list containing all tokens of all files.
      */
-    public List<Token> parse(File directory, String[] fileNames) {
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        errors = 0;
-        for (String fileName : fileNames) {
-            if (!parseFile(directory, fileName)) {
-                errors++;
-            }
-            tokens.add(Token.fileEnd(fileName));
+        for (File file : files) {
+            parseFile(file);
+            tokens.add(Token.fileEnd(file));
         }
         return tokens;
     }
 
-    private boolean parseFile(File directory, String fileName) {
-        File file = new File(directory, fileName);
+    private void parseFile(File file) throws ParsingException {
         try (FileInputStream inputStream = new FileInputStream(file)) {
-            currentFile = fileName;
+            currentFile = file;
 
             // create a lexer, a parser and a buffer between them.
             RustLexer lexer = new RustLexer(CharStreams.fromStream(inputStream));
@@ -61,10 +58,8 @@ public class RustParserAdapter extends AbstractParser {
                 treeWalker.walk(new JPlagRustListener(this), parseTree);
             }
         } catch (IOException exception) {
-            logger.error("Parsing Error in '" + fileName + "':" + File.separator, exception);
-            return false;
+            throw new ParsingException(file, exception.getMessage(), exception);
         }
-        return true;
     }
 
     /**

+ 4 - 2
languages/rust/src/test/java/de/jplag/rust/RustLanguageTest.java

@@ -9,6 +9,7 @@ import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 
@@ -17,6 +18,7 @@ import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import de.jplag.ParsingException;
 import de.jplag.SharedTokenType;
 import de.jplag.Token;
 import de.jplag.TokenPrinter;
@@ -49,9 +51,9 @@ class RustLanguageTest {
     }
 
     @Test
-    void parseTestFiles() {
+    void parseTestFiles() throws ParsingException {
         for (String fileName : testFiles) {
-            List<Token> tokens = language.parse(testFileLocation, new String[] {fileName});
+            List<Token> tokens = language.parse(Set.of(new File(testFileLocation, fileName)));
             String output = TokenPrinter.printTokens(tokens, testFileLocation);
             logger.info(output);
 

+ 3 - 5
languages/scala/src/main/scala/de/jplag/scala/Language.scala

@@ -5,7 +5,8 @@ import de.jplag.Token
 import java.io.File
 import org.kohsuke.MetaInfServices
 
-import scala.jdk.CollectionConverters.SeqHasAsJava
+import java.util
+import scala.jdk.CollectionConverters.{SeqHasAsJava, SetHasAsScala}
 
 class Language extends de.jplag.Language {
   private val parser = new Parser
@@ -19,8 +20,5 @@ class Language extends de.jplag.Language {
 
   override def minimumTokenMatch = 8
 
-  override def parse(dir: File, files: Array[String]): java.util.List[Token] = this.parser.parse(dir, files).asJava
-
-  override def hasErrors: Boolean = this.parser.hasErrors
-
+  override def parse(files: util.Set[File]): java.util.List[Token] = this.parser.parse(files.asScala.toSet).asJava
 }

+ 8 - 17
languages/scala/src/main/scala/de/jplag/scala/Parser.scala

@@ -1,16 +1,15 @@
 package de.jplag.scala
 
 import de.jplag.scala.ScalaTokenType._
-import de.jplag.{AbstractParser, Token}
+import de.jplag.{AbstractParser, ParsingException, Token}
 
 import java.io.File
-
-import scala.collection.mutable.ListBuffer 
+import scala.collection.mutable.ListBuffer
 import scala.meta._
 
 
 class Parser extends AbstractParser {
-    private var currentFile: String = _
+    private var currentFile: File = _
 
     private var tokens: ListBuffer[Token] = _
 
@@ -330,26 +329,20 @@ class Parser extends AbstractParser {
         }
     }
 
-    def parse(directory: File, files: Array[String]): List[Token] = {
+    def parse(files: Set[File]): List[Token] = {
         tokens = ListBuffer()
-        errors = 0
-
         for (file <- files) {
-            currentFile = file
-            if (!parseFile(directory, file)) {
-                errors += 1
-            }
+            parseFile(file)
             System.gc()
         }
 
         tokens.toList
     }
 
-    private def parseFile(directory: File, fileName: String): Boolean = {
-        currentFile = fileName
+    private def parseFile(file: File) = {
+        currentFile = file
 
         try {
-            val file = new File(directory, fileName)
             val bytes = java.nio.file.Files.readAllBytes(file.toPath)
             val text = new String(bytes, "UTF-8")
             val input = Input.VirtualFile(file.getPath, text)
@@ -360,10 +353,8 @@ class Parser extends AbstractParser {
         } catch {
             case exception: Throwable =>
                 exception.printStackTrace()
-                return false
+                throw new ParsingException(file, exception.getMessage, exception)
         }
-
-        true
     }
 
     /**

+ 2 - 1
languages/scala/src/test/java/de/jplag/scala/ScalaLanguageTest.java

@@ -10,6 +10,7 @@ import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 
@@ -58,7 +59,7 @@ class ScalaLanguageTest {
     @Test
     void parseTestFiles() {
         for (String fileName : testFiles) {
-            List<Token> tokens = language.parse(testFileLocation, new String[] {fileName});
+            List<Token> tokens = language.parse(Set.of(new File(testFileLocation, fileName)));
             String output = TokenPrinter.printTokens(tokens, testFileLocation);
             logger.info(output);
 

+ 4 - 7
languages/scheme/src/main/java/de/jplag/scheme/Language.java

@@ -2,9 +2,11 @@ package de.jplag.scheme;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 @MetaInfServices(de.jplag.Language.class)
@@ -38,12 +40,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File dir, String[] files) {
-        return this.parser.parse(dir, files);
-    }
-
-    @Override
-    public boolean hasErrors() {
-        return this.parser.hasErrors();
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return this.parser.parse(files);
     }
 }

+ 7 - 8
languages/scheme/src/main/java/de/jplag/scheme/Parser.java

@@ -3,13 +3,15 @@ package de.jplag.scheme;
 import java.io.File;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.TokenType;
 
 public class Parser extends AbstractParser {
-    private String currentFile;
+    private File currentFile;
 
     private List<Token> tokens;
 
@@ -20,15 +22,12 @@ public class Parser extends AbstractParser {
         super();
     }
 
-    public List<Token> parse(File directory, String[] files) {
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        errors = 0;
-        for (String file : files) {
+        for (File file : files) {
             currentFile = file;
-            logger.trace("Parsing file {}", file);
-            if (!SchemeParser.parseFile(directory, file, null, this)) {
-                errors++;
-            }
+            logger.trace("Parsing file {}", file.getName());
+            SchemeParser.parseFile(file, null, this);
             tokens.add(Token.fileEnd(currentFile));
         }
         return tokens;

+ 10 - 10
languages/scheme/src/main/javacc/Scheme.jj

@@ -58,15 +58,16 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 
+import de.jplag.ParsingException;
+
 public class SchemeParser {
     /* used for context in the template production rule */
     private static int templateParam;
     private Parser parser2;
 
-    public static boolean parseFile(File dir, String fileName, SchemeParser parser, Parser parserX) {
-        File file = null;
+    public static void parseFile(File file, SchemeParser parser, Parser parserX) throws ParsingException {
         try {
-            FileInputStream in = new FileInputStream(file = new File(dir, fileName));
+            FileInputStream in = new FileInputStream(file);
             if (parser == null) {
                 parser = new SchemeParser(in, "UTF-8");
             } else {
@@ -74,19 +75,18 @@ public class SchemeParser {
             }
             parser.parser2 = parserX;
         } catch (FileNotFoundException e) {
-            System.out.println("Scheme Parser R4RS:  File " + fileName + " not found.");
-            return false;
+            System.out.println("Scheme Parser R4RS:  File " + file.getName() + " not found.");
+            throw new ParsingException(file, e.getMessage(), e);
         }
         try {
             parser.Program();
         } catch (ParseException e) {
-            parserX.logger.error("Parsing Error in '" + fileName + "': " + e.getMessage());
-            return false;
+            parserX.logger.error("Parsing Error in '" + file.getName() + "': " + e.getMessage());
+            throw new ParsingException(file, e.getMessage(), e);
         } catch (TokenMgrException e) {
-            parserX.logger.error("Scanning Error in '" + fileName + "': " + e.getMessage());
-            return false;
+            parserX.logger.error("Scanning Error in '" + file.getName() + "': " + e.getMessage());
+            throw new ParsingException(file, e.getMessage(), e);
         }
-        return true;
     }
 }
 PARSER_END(SchemeParser)

+ 4 - 7
languages/text/src/main/java/de/jplag/text/Language.java

@@ -2,9 +2,11 @@ package de.jplag.text;
 
 import java.io.File;
 import java.util.List;
+import java.util.Set;
 
 import org.kohsuke.MetaInfServices;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 /**
@@ -43,12 +45,7 @@ public class Language implements de.jplag.Language {
     }
 
     @Override
-    public List<Token> parse(File dir, String[] files) {
-        return parserAdapter.parse(dir, files);
-    }
-
-    @Override
-    public boolean hasErrors() {
-        return parserAdapter.hasErrors();
+    public List<Token> parse(Set<File> files) throws ParsingException {
+        return parserAdapter.parse(files);
     }
 }

+ 11 - 19
languages/text/src/main/java/de/jplag/text/ParserAdapter.java

@@ -3,12 +3,13 @@ package de.jplag.text;
 import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
-import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
+import java.util.Set;
 
 import de.jplag.AbstractParser;
+import de.jplag.ParsingException;
 import de.jplag.Token;
 
 import edu.stanford.nlp.ling.CoreLabel;
@@ -24,7 +25,7 @@ public class ParserAdapter extends AbstractParser {
     private final StanfordCoreNLP pipeline;
 
     private List<Token> tokens;
-    private String currentFile;
+    private File currentFile;
     private int currentLine;
     /**
      * The position of the current line break in the content string
@@ -37,28 +38,21 @@ public class ParserAdapter extends AbstractParser {
         this.pipeline = new StanfordCoreNLP(properties);
     }
 
-    public List<Token> parse(File directory, String[] files) {
+    public List<Token> parse(Set<File> files) throws ParsingException {
         tokens = new ArrayList<>();
-        errors = 0;
-        for (String file : files) {
+        for (File file : files) {
             logger.trace("Parsing file {}", file);
-            if (!parseFile(directory, file)) {
-                errors++;
-            }
+            parseFile(file);
             tokens.add(Token.fileEnd(file));
         }
         return tokens;
     }
 
-    private boolean parseFile(File directory, String file) {
+    private void parseFile(File file) throws ParsingException {
         this.currentFile = file;
         this.currentLine = 1; // lines start at 1
         this.currentLineBreakIndex = 0;
-        Path filePath = directory.toPath().resolve(file);
-        String content = readFile(filePath);
-        if (content == null) {
-            return false;
-        }
+        String content = readFile(file);
         int lastTokenEnd = 0;
         CoreDocument coreDocument = pipeline.processToCoreDocument(content);
         for (CoreLabel token : coreDocument.tokens()) {
@@ -68,7 +62,6 @@ public class ParserAdapter extends AbstractParser {
                 addToken(token);
             }
         }
-        return true;
     }
 
     /**
@@ -105,12 +98,11 @@ public class ParserAdapter extends AbstractParser {
         tokens.add(new Token(new TextTokenType(text), currentFile, currentLine, column, length));
     }
 
-    private String readFile(Path filePath) {
+    private String readFile(File file) throws ParsingException {
         try {
-            return Files.readString(filePath);
+            return Files.readString(file.toPath());
         } catch (IOException e) {
-            logger.error("Error reading from file {}", filePath, e);
-            return null;
+            throw new ParsingException(file, e.getMessage(), e);
         }
     }
 }

+ 12 - 11
languages/text/src/test/java/jplag/text/TextLanguageTest.java

@@ -9,6 +9,7 @@ import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -18,6 +19,7 @@ import org.junit.jupiter.params.provider.ValueSource;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import de.jplag.ParsingException;
 import de.jplag.Token;
 import de.jplag.TokenPrinter;
 import de.jplag.TokenType;
@@ -40,10 +42,9 @@ class TextLanguageTest {
     }
 
     @Test
-    void testParsingJavaDoc() {
+    void testParsingJavaDoc() throws ParsingException {
         // Parse test input
-        String[] input = new String[] {TEST_SUBJECT};
-        List<Token> result = language.parse(baseDirectory, input);
+        List<Token> result = language.parse(Set.of(new File(BASE_PATH.toFile(), TEST_SUBJECT)));
         logger.info(TokenPrinter.printTokens(result, baseDirectory));
 
         List<TokenType> tokenTypes = result.stream().map(Token::getType).toList();
@@ -53,19 +54,19 @@ class TextLanguageTest {
 
     @ParameterizedTest
     @ValueSource(strings = {"\n", "\r", "\r\n",})
-    void testLineBreakInputs(String input, @TempDir Path tempDir) throws IOException {
-        Path file = tempDir.resolve("input.txt");
-        Files.writeString(file, input);
-        List<Token> result = language.parse(tempDir.toFile(), new String[] {"input.txt"});
+    void testLineBreakInputs(String input, @TempDir Path tempDir) throws IOException, ParsingException {
+        Path filePath = tempDir.resolve("input.txt");
+        Files.writeString(filePath, input);
+        List<Token> result = language.parse(Set.of(filePath.toFile()));
         assertEquals(1, result.size());
     }
 
     @ParameterizedTest
     @ValueSource(strings = {"\ntoken", "\rtoken", "\r\ntoken",})
-    void testTokenAfterLineBreak(String input, @TempDir Path tempDir) throws IOException {
-        Path file = tempDir.resolve("input.txt");
-        Files.writeString(file, input);
-        List<Token> result = language.parse(tempDir.toFile(), new String[] {"input.txt"});
+    void testTokenAfterLineBreak(String input, @TempDir Path tempDir) throws IOException, ParsingException {
+        Path filePath = tempDir.resolve("input.txt");
+        Files.writeString(filePath, input);
+        List<Token> result = language.parse(Set.of(filePath.toFile()));
         assertEquals(2, result.get(0).getLine());
     }
 

Разница между файлами не показана из-за своего большого размера
+ 526 - 206
report-viewer/package-lock.json


+ 5 - 5
report-viewer/package.json

@@ -12,13 +12,13 @@
     "@highlightjs/vue-plugin": "^2.1.0",
     "chart.js": "^3.9.1",
     "chartjs-plugin-datalabels": "^2.1.0",
-    "core-js": "^3.25.1",
+    "core-js": "^3.25.2",
     "gitart-vue-dialog": "^2.4.0",
     "highlight.js": "^11.6.0",
     "jszip": "^3.10.0",
     "node-polyfill-webpack-plugin": "^2.0.0",
     "slash": "^4.0.0",
-    "vue": "^3.2.39",
+    "vue": "^3.2.40",
     "vue-chart-3": "^3.1.8",
     "vue-draggable-next": "^2.1.1",
     "vue-router": "^4.1.5",
@@ -26,8 +26,8 @@
     "vuex": "^4.0.2"
   },
   "devDependencies": {
-    "@typescript-eslint/eslint-plugin": "^5.37.0",
-    "@typescript-eslint/parser": "^5.37.0",
+    "@typescript-eslint/eslint-plugin": "^5.38.1",
+    "@typescript-eslint/parser": "^5.38.0",
     "@vue/cli-plugin-babel": "~5.0.8",
     "@vue/cli-plugin-eslint": "~5.0.8",
     "@vue/cli-plugin-router": "~5.0.8",
@@ -41,7 +41,7 @@
     "eslint-plugin-vue": "^8.7.1",
     "lint-staged": "^13.0.3",
     "prettier": "^2.7.1",
-    "typescript": "~4.8.3"
+    "typescript": "~4.8.4"
   },
   "gitHooks": {
     "pre-commit": "lint-staged"

+ 6 - 6
report-viewer/src/components/ComparisonsTable.vue

@@ -15,7 +15,7 @@
       :key="
         comparison.firstSubmissionId +
         comparison.secondSubmissionId +
-        comparison.matchPercentage
+        comparison.similarity
       "
       class="selectable"
     >
@@ -81,7 +81,7 @@
           )
         "
       >
-        {{ formattedMatchPercentage(comparison.matchPercentage) }}
+        {{ formattedMatchPercentage(comparison.similarity) }}
       </td>
       <td>
         <img
@@ -144,7 +144,7 @@ export default defineComponent({
   },
   setup(props) {
     const store = useStore();
-    let formattedMatchPercentage = (num: number) => num.toFixed(2);
+    let formattedMatchPercentage = (num: number) => (num * 100).toFixed(2);
     const dialog: Ref<Array<boolean>> = ref([]);
     props.topComparisons.forEach(() => dialog.value.push(false));
     const displayName = (submissionId: string) =>
@@ -154,7 +154,7 @@ export default defineComponent({
       dialog.value[index] = true;
     };
 
-    const navigateToComparisonView = (firstId: string, secondId: string) => {
+    const navigateToComparisonView = (firstId : string, secondId: string) => {
       if (!store.state.single) {
         router.push({
           name: "ComparisonView",
@@ -185,7 +185,7 @@ export default defineComponent({
         ) {
           matches.push({
             matchedWith: comparison.secondSubmissionId,
-            percentage: comparison.matchPercentage,
+            percentage: comparison.similarity,
           });
         } else if (
           comparison.secondSubmissionId.includes(id) &&
@@ -193,7 +193,7 @@ export default defineComponent({
         ) {
           matches.push({
             matchedWith: comparison.firstSubmissionId,
-            percentage: comparison.matchPercentage,
+            percentage: comparison.similarity,
           });
         }
       });

+ 5 - 5
report-viewer/src/model/Comparison.ts

@@ -8,16 +8,16 @@ import { MatchInSingleFile } from "./MatchInSingleFile";
 export class Comparison {
   private readonly _firstSubmissionId: string;
   private readonly _secondSubmissionId: string;
-  private readonly _match_percentage: number;
+  private readonly _similarity: number;
 
   constructor(
     firstSubmissionId: string,
     secondSubmissionId: string,
-    match_percentage: number
+    similarity: number
   ) {
     this._firstSubmissionId = firstSubmissionId;
     this._secondSubmissionId = secondSubmissionId;
-    this._match_percentage = match_percentage;
+    this._similarity = similarity;
     this._filesOfFirstSubmission = new Map();
     this._filesOfSecondSubmission = new Map();
     this._colors = [];
@@ -94,7 +94,7 @@ export class Comparison {
     return this._secondSubmissionId;
   }
 
-  get match_percentage(): number {
-    return this._match_percentage;
+  get similarity(): number {
+    return this._similarity;
   }
 }

+ 1 - 1
report-viewer/src/model/ComparisonListElement.ts

@@ -5,5 +5,5 @@
 export type ComparisonListElement = {
     firstSubmissionId: string,
     secondSubmissionId: string,
-    matchPercentage: number
+    similarity: number
 }

+ 1 - 1
report-viewer/src/model/factories/OverviewFactory.ts

@@ -27,7 +27,7 @@ export class OverviewFactory {
           const comparison: ComparisonListElement = {
             firstSubmissionId: jsonComparison.first_submission as string,
             secondSubmissionId: jsonComparison.second_submission as string,
-            matchPercentage: jsonComparison.match_percentage as number,
+            similarity: jsonComparison.similarity as number,
           };
           comparisons.push(comparison);
         }

+ 1 - 1
report-viewer/src/views/ComparisonView.vue

@@ -31,7 +31,7 @@
         :value="store.getters.submissionDisplayName(secondId)"
         label="Submission 2"
       />
-      <TextInformation :value="comparison.match_percentage" label="Match %" />
+      <TextInformation :value="(comparison.similarity * 100).toFixed(2)" label="Match %" />
       <MatchTable
         :id1="firstId"
         :id2="secondId"

Некоторые файлы не были показаны из-за большого количества измененных файлов