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

Merge pull request #555 from jplag/text-fix

Overhaul text frontend to improve code quality and reduce complexity
Timur Sağlam 4 лет назад
Родитель
Сommit
9a6fcd0f76

+ 21 - 23
jplag.frontend.text/src/main/antlr/text.g

@@ -1,30 +1,29 @@
-header
-{
-
+header {
 package de.jplag.text;
-
 }
 
 // tell ANTLR that we want to generate Java source code
-options
-{
+options {
   language="Java";
 }
 
 class TextParser extends Parser;
-options
-{
+options {
   k = 2;			  // two token lookahead
   //  exportVocab=Text;	          // Call its vocabulary "Text"
   codeGenMakeSwitchThreshold = 2; // Some optimizations
   codeGenBitsetTestThreshold = 3;
   defaultErrorHandler = true;
   buildAST = false;
-  ASTLabelType = "ParserToken";
+  ASTLabelType = "AntlrParserToken";
 }
 
 {
-public de.jplag.text.Parser parser;
+    private de.jplag.text.ParserAdapter parser;
+
+    public void setParserAdapter(de.jplag.text.ParserAdapter adapter) {
+        this.parser = adapter;
+    }
 }
 
 file : ( w:WORD { parser.add(w); } | PUNCTUATION | SPECIALS )* EOF ;
@@ -35,22 +34,21 @@ file : ( w:WORD { parser.add(w); } | PUNCTUATION | SPECIALS )* EOF ;
 
 {
 import de.jplag.text.InputState;
-import de.jplag.text.ParserToken;
+import de.jplag.text.AntlrParserToken;
 }
 
 class TextLexer extends Lexer;
-options
-{
-  //  exportVocab=Text;        // call the vocabulary "Text"
-  testLiterals = false;    // don't automatically test for literals
-  k = 2;                   // two characters of lookahead
-  charVocabulary = '\u0000'..'\u00FF';
+options {
+    //  exportVocab=Text;    // call the vocabulary "Text"
+    testLiterals = false;    // don't automatically test for literals
+    k = 2;                   // two characters of lookahead
+    charVocabulary = '\u0000'..'\u00FF';
 }
 
 {
     public void newline() {
         super.newline();
-        ((InputState) inputState).column = 1;
+        ((InputState) inputState).setColumnIndex(1);
     }
 
     public void consume() throws antlr.CharStreamException {
@@ -58,16 +56,16 @@ options
             InputState state = (InputState) inputState;
             if (text.length() == 0) {
                 // remember token start column
-                state.tokenColumn = state.column;
+                state.setTokenColumnIndex(state.getColumnIndex());
             }
-            state.column++;
+            state.setColumnIndex(state.getColumnIndex() + 1);
         }
         super.consume();
     }
 
     protected Token makeToken(int t) {
-        ParserToken token = (ParserToken) super.makeToken(t);
-        token.setColumn(((InputState) inputState).tokenColumn);
+        AntlrParserToken token = (AntlrParserToken) super.makeToken(t);
+        token.setColumn(((InputState) inputState).getTokenColumnIndex());
         return token;
     }
 }
@@ -88,7 +86,7 @@ SPECIALS : ('#' | '$' | '%' | '&' | '+' | '<' | '=' | '*' |
 
 // Whitespace -- ignored
 SPACE : ( ' '
-	  |	'\t' //{ ((InputState)inputState).column += 7; }
+	  |	'\t' //{ ((InputState)inputState).setColumnIndex((InputState)inputState).getColumnIndex() + 7); }
 	  |	'\f'
 	  |     '\240'
 	  |     ('\001' .. '\010')

+ 5 - 2
jplag.frontend.text/src/main/java/de/jplag/text/ParserToken.java → jplag.frontend.text/src/main/java/de/jplag/text/AntlrParserToken.java

@@ -2,7 +2,10 @@ package de.jplag.text;
 
 import antlr.Token;
 
-public class ParserToken extends Token {
+/**
+ * Token of the ANTLR grammar, needs to be converted into a JPlag token by the parser adapter.
+ */
+public class AntlrParserToken extends Token {
     /**
      * This variable holds the line number of the current token.
      */
@@ -23,7 +26,7 @@ public class ParserToken extends Token {
      */
     private int id = -1;
 
-    public ParserToken() {
+    public AntlrParserToken() {
         super();
     }
 

+ 18 - 9
jplag.frontend.text/src/main/java/de/jplag/text/InputState.java

@@ -10,31 +10,40 @@ import antlr.LexerSharedInputState;
  * This object contains the data associated with an input stream of characters. Multiple lexers share a single
  * LexerSharedInputState to lex the same input stream.
  */
-@SuppressWarnings({"java:S1104", "java:S2387"})
 public class InputState extends LexerSharedInputState {
-    public int column = 0;
-    public int tokenColumn = 0;
+    private int columnIndex = 1;
+    private int tokenColumnIndex = 1;
 
     public InputState(InputBuffer inputBuffer) {
         super(inputBuffer);
-        column = 1;
-        line = 1;
     }
 
     public InputState(InputStream inputStream) {
         super(inputStream);
-        column = 1;
-        line = 1;
     }
 
     public InputState(Reader inputReader) {
         super(inputReader);
-        column = 1;
-        line = 1;
     }
 
     @Override
     public int getLine() {
         return line;
     }
+
+    public int getColumnIndex() {
+        return columnIndex;
+    }
+
+    public void setColumnIndex(int columnIndex) {
+        this.columnIndex = columnIndex;
+    }
+
+    public int getTokenColumnIndex() {
+        return tokenColumnIndex;
+    }
+
+    public void setTokenColumnIndex(int tokenColumnIndex) {
+        this.tokenColumnIndex = tokenColumnIndex;
+    }
 }

+ 10 - 5
jplag.frontend.text/src/main/java/de/jplag/text/Language.java

@@ -4,12 +4,17 @@ import java.io.File;
 
 import de.jplag.TokenList;
 
+/**
+ * Language class for parsing (natural language) text. This language module employs a primitive approach where
+ * individual words are interpreted as token types. Whitespace and special characters are ignored. This approach works,
+ * but there are better approaches for text plagiarism out there (based on NLP techniques).
+ */
 public class Language implements de.jplag.Language {
 
-    private final Parser parser;
+    private final ParserAdapter parserAdapter;
 
     public Language() {
-        parser = new Parser();
+        parserAdapter = new ParserAdapter();
     }
 
     @Override
@@ -19,7 +24,7 @@ public class Language implements de.jplag.Language {
 
     @Override
     public String getName() {
-        return "Text Parser";
+        return "Text Parser (naive)";
     }
 
     @Override
@@ -34,12 +39,12 @@ public class Language implements de.jplag.Language {
 
     @Override
     public TokenList parse(File dir, String[] files) {
-        return this.parser.parse(dir, files);
+        return parserAdapter.parse(dir, files);
     }
 
     @Override
     public boolean hasErrors() {
-        return this.parser.hasErrors();
+        return parserAdapter.hasErrors();
     }
 
     @Override

+ 0 - 87
jplag.frontend.text/src/main/java/de/jplag/text/Parser.java

@@ -1,87 +0,0 @@
-package de.jplag.text;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.Hashtable;
-
-import antlr.Token;
-
-import de.jplag.AbstractParser;
-import de.jplag.TokenConstants;
-import de.jplag.TokenList;
-
-public class Parser extends AbstractParser {
-
-    protected Hashtable<String, Integer> table = new Hashtable<>();
-    protected int serial = 1; // 0 is FILE_END token
-
-    private TokenList tokens;
-
-    private String currentFile;
-
-    private boolean runOut = false;
-
-    /**
-     * Creates the parser.
-     */
-    public Parser() {
-        super();
-    }
-
-    public TokenList parse(File directory, String[] files) {
-        tokens = new TokenList();
-        errors = 0;
-        for (String file : files) {
-            logger.trace("Parsing file {}", file);
-            if (!parseFile(directory, file))
-                errors++;
-            tokens.addToken(new TextToken(TokenConstants.FILE_END, file, this));
-        }
-
-        TokenList tmp = tokens;
-        tokens = null;
-        return tmp;
-    }
-
-    public void add(Token token) {
-        ParserToken parserToken = (ParserToken) token;
-        tokens.addToken(new TextToken(token.getText(), currentFile, parserToken.getLine(), parserToken.getColumn(), parserToken.getLength(), this));
-    }
-
-    public void outOfSerials() {
-        if (runOut)
-            return;
-        runOut = true;
-        errors++;
-        logger.error("Out of serials!");
-    }
-
-    private boolean parseFile(File directory, String file) {
-        InputState inputState = null;
-        try {
-            FileInputStream inputStream = new FileInputStream(new File(directory, file));
-            currentFile = file;
-            // Create a scanner that reads from the input stream passed to us
-            inputState = new InputState(inputStream);
-            TextLexer lexer = new TextLexer(inputState);
-            lexer.setFilename(file);
-            lexer.setTokenObjectClass("de.jplag.text.ParserToken");
-
-            // Create a parser that reads from the scanner
-            TextParser parser = new TextParser(lexer);
-            parser.setFilename(file);
-            parser.parser = this;// Added by Emeric 26.01.05 BAD
-
-            // start parsing at the compilationUnit rule
-            parser.file();
-
-            // close file
-            inputStream.close();
-        } catch (Exception e) {
-            logger.error("Parsing Error in '" + file + "' (line " + (inputState != null ? "" + inputState.getLine() : "") + "):\n  " + e.getMessage(),
-                    e);
-            return false;
-        }
-        return true;
-    }
-}

+ 84 - 0
jplag.frontend.text/src/main/java/de/jplag/text/ParserAdapter.java

@@ -0,0 +1,84 @@
+package de.jplag.text;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+import antlr.Token;
+
+import de.jplag.AbstractParser;
+import de.jplag.TokenConstants;
+import de.jplag.TokenList;
+
+public class ParserAdapter extends AbstractParser {
+
+    private final Map<String, Integer> tokenTypes = new HashMap<>();
+    private int tokenTypeIndex = 1; // 0 is FILE_END token, SEPARATOR is not used as there are no methods.
+
+    private TokenList tokens;
+    private String currentFile;
+
+    public TokenList parse(File directory, String[] files) {
+        tokens = new TokenList();
+        errors = 0;
+        for (String file : files) {
+            logger.trace("Parsing file {}", file);
+            if (!parseFile(directory, file)) {
+                errors++;
+            }
+            tokens.addToken(new TextToken(TokenConstants.FILE_END, file));
+        }
+        return tokens;
+    }
+
+    /**
+     * Converts a ANTLR token into a JPlag token and adds it to the token list.
+     * @param token is the ANTLR token to convert.
+     */
+    public void add(Token token) {
+        if (token instanceof AntlrParserToken parserToken) {
+            String text = token.getText();
+            int type = getTokenType(text);
+            tokens.addToken(new TextToken(text, type, currentFile, parserToken));
+        } else {
+            throw new IllegalArgumentException("Illegal token implementation: " + token);
+        }
+    }
+
+    private boolean parseFile(File directory, String file) {
+        InputState inputState = null;
+        try (FileInputStream inputStream = new FileInputStream(new File(directory, file))) {
+            currentFile = file;
+            // Create a scanner that reads from the input stream passed to us
+            inputState = new InputState(inputStream);
+            TextLexer lexer = new TextLexer(inputState);
+            lexer.setFilename(file);
+            lexer.setTokenObjectClass("de.jplag.text.AntlrParserToken");
+
+            // Create a parser that reads from the scanner
+            TextParser parser = new TextParser(lexer);
+            parser.setFilename(file);
+            parser.setParserAdapter(this);
+
+            // start parsing at the compilationUnit rule
+            parser.file();
+        } catch (Exception e) {
+            logger.error("Parsing Error in " + file + " (line " + (inputState != null ? "" + inputState.getLine() : "") + "):" + e.getMessage(), e);
+            return false;
+        }
+        return true;
+    }
+
+    private int getTokenType(String text) {
+        text = text.toLowerCase();
+        tokenTypes.computeIfAbsent(text, it -> {
+            if (tokenTypeIndex == Integer.MAX_VALUE) {
+                throw new IllegalStateException("Too many token types, should not happen!");
+            }
+            return ++tokenTypeIndex;
+        });
+        return tokenTypes.get(text);
+
+    }
+}

+ 6 - 23
jplag.frontend.text/src/main/java/de/jplag/text/TextToken.java

@@ -1,36 +1,19 @@
 package de.jplag.text;
 
-import java.io.Serial;
-
 import de.jplag.Token;
 
 public class TextToken extends Token {
-    @Serial
-    private static final long serialVersionUID = 4301179216570538972L;
-
-    private static int getSerial(String text, Parser parser) {
-        text = text.toLowerCase();
-        Integer serial = parser.table.get(text);
-        if (serial == null) {
-            serial = parser.serial;
-            if (parser.serial == Integer.MAX_VALUE)
-                parser.outOfSerials();
-            else
-                parser.serial++;
-            parser.table.put(text, serial);
-        }
-        return serial;
-    }
 
-    private String text;
+    private static final String NO_TEXT = "<unknown>";
+    private final String text;
 
-    public TextToken(int type, String file, Parser parser) {
+    public TextToken(int type, String file) {
         super(type, file, -1, -1, -1);
+        this.text = NO_TEXT;
     }
 
-    public TextToken(String text, String file, int line, int column, int length, Parser parser) {
-        super(-1, file, line, column, length);
-        this.type = getSerial(text, parser);
+    public TextToken(String text, int type, String file, AntlrParserToken parserToken) {
+        super(type, file, parserToken.getLine(), parserToken.getColumn(), parserToken.getLength());
         this.text = text.toLowerCase();
     }
 

+ 54 - 0
jplag.frontend.text/src/test/java/jplag/text/TextFrontendTest.java

@@ -0,0 +1,54 @@
+package jplag.text;
+
+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.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.StreamSupport;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import de.jplag.Token;
+import de.jplag.TokenList;
+import de.jplag.TokenPrinter;
+import de.jplag.text.Language;
+
+class TextFrontendTest {
+    private final Logger logger = LoggerFactory.getLogger("JPlag-Test");
+
+    private static final Path BASE_PATH = Path.of("src", "test", "resources");
+    private static final String TEST_SUBJECT = "FutureJavaDoc.txt";
+
+    private de.jplag.Language frontend;
+    private File baseDirectory;
+
+    @BeforeEach
+    public void setUp() {
+        frontend = new Language();
+        baseDirectory = BASE_PATH.toFile();
+        assertTrue(baseDirectory.exists(), "Could not find base directory!");
+    }
+
+    @Test
+    void testParsingJavaDoc() {
+        // Parse test input
+        String[] input = new String[] {TEST_SUBJECT};
+        TokenList result = frontend.parse(baseDirectory, input);
+        logger.info(TokenPrinter.printTokens(result, baseDirectory, Arrays.asList(input)));
+
+        // Compare parsed tokens:
+        Map<Integer, Token> tokenTypes = new HashMap<>();
+        StreamSupport.stream(result.allTokens().spliterator(), false).forEach(it -> tokenTypes.put(it.getType(), it));
+
+        assertEquals(293, result.size());
+        assertEquals(156, tokenTypes.values().size());
+    }
+
+}

+ 50 - 0
jplag.frontend.text/src/test/resources/FutureJavaDoc.txt

@@ -0,0 +1,50 @@
+/**
+ * A {@code Future} represents the result of an asynchronous
+ * computation.  Methods are provided to check if the computation is
+ * complete, to wait for its completion, and to retrieve the result of
+ * the computation.  The result can only be retrieved using method
+ * {@code get} when the computation has completed, blocking if
+ * necessary until it is ready.  Cancellation is performed by the
+ * {@code cancel} method.  Additional methods are provided to
+ * determine if the task completed normally or was cancelled. Once a
+ * computation has completed, the computation cannot be cancelled.
+ * If you would like to use a {@code Future} for the sake
+ * of cancellability but not provide a usable result, you can
+ * declare types of the form {@code Future<?>} and
+ * return {@code null} as a result of the underlying task.
+ *
+ * <p><b>Sample Usage</b> (Note that the following classes are all
+ * made-up.)
+ *
+ * <pre> {@code
+ * interface ArchiveSearcher { String search(String target); }
+ * class App {
+ *   ExecutorService executor = ...;
+ *   ArchiveSearcher searcher = ...;
+ *   void showSearch(String target) throws InterruptedException {
+ *     Callable<String> task = () -> searcher.search(target);
+ *     Future<String> future = executor.submit(task);
+ *     displayOtherThings(); // do other things while searching
+ *     try {
+ *       displayText(future.get()); // use future
+ *     } catch (ExecutionException ex) { cleanup(); return; }
+ *   }
+ * }}</pre>
+ *
+ * The {@link FutureTask} class is an implementation of {@code Future} that
+ * implements {@code Runnable}, and so may be executed by an {@code Executor}.
+ * For example, the above construction with {@code submit} could be replaced by:
+ * <pre> {@code
+ * FutureTask<String> future = new FutureTask<>(task);
+ * executor.execute(future);}</pre>
+ *
+ * <p>Memory consistency effects: Actions taken by the asynchronous computation
+ * <a href="package-summary.html#MemoryVisibility"> <i>happen-before</i></a>
+ * actions following the corresponding {@code Future.get()} in another thread.
+ *
+ * @see FutureTask
+ * @see Executor
+ * @since 1.5
+ * @author Doug Lea
+ * @param <V> The result type returned by this Future's {@code get} method
+ */