package de.jplag.R; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeWalker; import de.jplag.AbstractParser; import de.jplag.ErrorConsumer; import de.jplag.R.grammar.RFilter; import de.jplag.R.grammar.RLexer; import de.jplag.R.grammar.RParser; import de.jplag.TokenList; /** * This class sets up the lexer and parser generated by ANTLR4, feeds the submissions through them and passes the * selected tokens on to the main program. */ public class RParserAdapter extends AbstractParser implements RTokenConstants { private String currentFile; private TokenList tokens; /** * Creates the RParserAdapter * @param errorConsumer the ErrorConsumer that parser errors are passed on to. */ public RParserAdapter(ErrorConsumer errorConsumer) { super(errorConsumer); } /** * Parsers a list of files into a single {@link TokenList}. * @param directory the directory of the files. * @param fileNames the file names of the files. * @return a {@link TokenList} containing all tokens of all files. */ public TokenList parse(File directory, String[] fileNames) { tokens = new TokenList(); errors = 0; for (String fileName : fileNames) { if (!parseFile(directory, fileName)) { errors++; } tokens.addToken(new RToken(FILE_END, fileName, -1, -1, -1)); } return tokens; } private boolean parseFile(File directory, String fileName) { File file = new File(directory, fileName); try (FileInputStream inputStream = new FileInputStream(file)) { currentFile = fileName; // create a lexer, a parser and a buffer between them. RLexer lexer = new RLexer(CharStreams.fromStream(inputStream)); CommonTokenStream tokens = new CommonTokenStream(lexer); RFilter filter = new RFilter(tokens); filter.stream(); tokens.seek(0); RParser parser = new RParser(tokens); // Create a tree walker and the entry context defined by the parser grammar ParserRuleContext entryContext = parser.prog(); ParseTreeWalker treeWalker = new ParseTreeWalker(); // Walk over the parse tree: for (int i = 0; i < entryContext.getChildCount(); i++) { ParseTree parseTree = entryContext.getChild(i); treeWalker.walk(new JplagRListener(this), parseTree); } } catch (IOException exception) { getErrorConsumer().addError("Parsing Error in '" + fileName + "':" + File.separator + exception); return false; } return true; } /** * Adds a new {@link de.jplag.Token} to the current {@link TokenList}. * @param type the type of the new {@link de.jplag.Token} * @param line the line of the Token in the current file * @param start the start column of the Token in the line * @param end the end column of the Token in the line */ /* package-private */ void addToken(int type, int line, int start, int end) { tokens.addToken(new RToken(type, currentFile, line, start, end - start)); } }