Parser.java 2.8 KB

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