Parser.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package de.jplag.python3;
  2. import java.io.BufferedInputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import org.antlr.v4.runtime.CharStream;
  7. import org.antlr.v4.runtime.CharStreams;
  8. import org.antlr.v4.runtime.CommonTokenStream;
  9. import org.antlr.v4.runtime.Token;
  10. import org.antlr.v4.runtime.tree.ParseTree;
  11. import org.antlr.v4.runtime.tree.ParseTreeWalker;
  12. import de.jplag.AbstractParser;
  13. import de.jplag.TokenList;
  14. import de.jplag.python3.grammar.Python3Lexer;
  15. import de.jplag.python3.grammar.Python3Parser;
  16. import de.jplag.python3.grammar.Python3Parser.File_inputContext;
  17. public class Parser extends AbstractParser implements Python3TokenConstants {
  18. private TokenList struct = new TokenList();
  19. private String currentFile;
  20. public TokenList parse(File dir, String files[]) {
  21. struct = new TokenList();
  22. errors = 0;
  23. for (int i = 0; i < files.length; i++) {
  24. getErrorConsumer().print(null, "Parsing file " + files[i]);
  25. if (!parseFile(dir, files[i])) {
  26. errors++;
  27. }
  28. System.gc();// Emeric
  29. struct.addToken(new Python3Token(FILE_END, files[i], -1, -1, -1));
  30. }
  31. this.parseEnd();
  32. return struct;
  33. }
  34. private boolean parseFile(File dir, String file) {
  35. BufferedInputStream fis;
  36. CharStream input;
  37. try {
  38. fis = new BufferedInputStream(new FileInputStream(new File(dir, file)));
  39. currentFile = file;
  40. input = CharStreams.fromStream(fis);
  41. // create a lexer that feeds off of input CharStream
  42. Python3Lexer lexer = new Python3Lexer(input);
  43. // create a buffer of tokens pulled from the lexer
  44. CommonTokenStream tokens = new CommonTokenStream(lexer);
  45. // create a parser that feeds off the tokens buffer
  46. Python3Parser parser = new Python3Parser(tokens);
  47. File_inputContext in = parser.file_input();
  48. ParseTreeWalker ptw = new ParseTreeWalker();
  49. for (int i = 0; i < in.getChildCount(); i++) {
  50. ParseTree pt = in.getChild(i);
  51. ptw.walk(new JplagPython3Listener(this), pt);
  52. }
  53. } catch (IOException e) {
  54. getErrorConsumer().addError("Parsing Error in '" + file + "':\n" + e.getMessage());
  55. return false;
  56. }
  57. return true;
  58. }
  59. public void add(int type, Token tok) {
  60. struct.addToken(new Python3Token(type, (currentFile == null ? "null" : currentFile), tok.getLine(), tok.getCharPositionInLine() + 1,
  61. tok.getText().length()));
  62. }
  63. public void addEnd(int type, Token tok) {
  64. struct.addToken(new Python3Token(type, (currentFile == null ? "null" : currentFile), tok.getLine(),
  65. struct.getToken(struct.size() - 1).getColumn() + 1, 0));
  66. }
  67. }