RustParserAdapter.java 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package de.jplag.rust;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.Set;
  8. import org.antlr.v4.runtime.CharStreams;
  9. import org.antlr.v4.runtime.CommonTokenStream;
  10. import org.antlr.v4.runtime.ParserRuleContext;
  11. import org.antlr.v4.runtime.tree.ParseTree;
  12. import org.antlr.v4.runtime.tree.ParseTreeWalker;
  13. import de.jplag.AbstractParser;
  14. import de.jplag.ParsingException;
  15. import de.jplag.Token;
  16. import de.jplag.rust.grammar.RustLexer;
  17. import de.jplag.rust.grammar.RustParser;
  18. public class RustParserAdapter extends AbstractParser {
  19. private File currentFile;
  20. private List<Token> tokens;
  21. /**
  22. * Parsers a set of files into a single list of {@link Token}s.
  23. * @param files the set of files.
  24. * @return a list containing all tokens of all files.
  25. */
  26. public List<Token> parse(Set<File> files) throws ParsingException {
  27. tokens = new ArrayList<>();
  28. for (File file : files) {
  29. parseFile(file);
  30. tokens.add(Token.fileEnd(file));
  31. }
  32. return tokens;
  33. }
  34. private void parseFile(File file) throws ParsingException {
  35. try (FileInputStream inputStream = new FileInputStream(file)) {
  36. currentFile = file;
  37. // create a lexer, a parser and a buffer between them.
  38. RustLexer lexer = new RustLexer(CharStreams.fromStream(inputStream));
  39. CommonTokenStream tokenStream = new CommonTokenStream(lexer);
  40. RustParser parser = new RustParser(tokenStream);
  41. // Create a tree walker and the entry context defined by the parser grammar
  42. ParserRuleContext entryContext = parser.crate();
  43. ParseTreeWalker treeWalker = new ParseTreeWalker();
  44. // Walk over the parse tree:
  45. for (int i = 0; i < entryContext.getChildCount(); i++) {
  46. ParseTree parseTree = entryContext.getChild(i);
  47. treeWalker.walk(new JPlagRustListener(this), parseTree);
  48. }
  49. } catch (IOException exception) {
  50. throw new ParsingException(file, exception.getMessage(), exception);
  51. }
  52. }
  53. /**
  54. * Adds a new {@link Token} to the current token list.
  55. * @param type the type of the new {@link Token}
  56. * @param line the line of the Token in the current file
  57. * @param start the start column of the Token in the line
  58. * @param length the length of the Token
  59. */
  60. /* package-private */ void addToken(RustTokenType type, int line, int start, int length) {
  61. tokens.add(new Token(type, currentFile, line, start, length));
  62. }
  63. }