SwiftParserAdapter.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package de.jplag.swift;
  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.swift.grammar.Swift5Lexer;
  17. import de.jplag.swift.grammar.Swift5Parser;
  18. public class SwiftParserAdapter extends AbstractParser {
  19. public static final int NOT_SET = -1;
  20. private File currentFile;
  21. private List<Token> tokens;
  22. /**
  23. * Creates the SwiftParserAdapter
  24. */
  25. public SwiftParserAdapter() {
  26. super();
  27. }
  28. /**
  29. * Parsers a set of files into a single list of {@link Token}s.
  30. * @param files the set of files.
  31. * @return a list containing all tokens of all files.
  32. */
  33. public List<Token> parse(Set<File> files) throws ParsingException {
  34. tokens = new ArrayList<>();
  35. for (File file : files) {
  36. parse(file);
  37. tokens.add(Token.fileEnd(file));
  38. }
  39. return tokens;
  40. }
  41. private void parse(File file) throws ParsingException {
  42. try (FileInputStream inputStream = new FileInputStream(file)) {
  43. currentFile = file;
  44. Swift5Lexer lexer = new Swift5Lexer(CharStreams.fromStream(inputStream));
  45. CommonTokenStream tokenStream = new CommonTokenStream(lexer);
  46. Swift5Parser parser = new Swift5Parser(tokenStream);
  47. ParserRuleContext entryContext = parser.top_level();
  48. ParseTreeWalker treeWalker = new ParseTreeWalker();
  49. JPlagSwiftListener listener = new JPlagSwiftListener(this);
  50. for (int i = 0; i < entryContext.getChildCount(); i++) {
  51. ParseTree parseTree = entryContext.getChild(i);
  52. treeWalker.walk(listener, parseTree);
  53. }
  54. } catch (IOException exception) {
  55. throw new ParsingException(file, exception.getMessage(), exception);
  56. }
  57. }
  58. /**
  59. * Adds a new {@link Token} to the current token list.
  60. * @param tokenType the type of the new {@link Token}
  61. * @param line the line of the Token in the current file
  62. * @param column the start column of the Token in the line
  63. * @param length the length of the Token
  64. */
  65. /* package-private */ void addToken(SwiftTokenType tokenType, int line, int column, int length) {
  66. tokens.add(new Token(tokenType, currentFile, line, column, length));
  67. }
  68. }