org.antlr.v4.runtime.BaseErrorListener Java Examples

The following examples show how to use org.antlr.v4.runtime.BaseErrorListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExpectedParseTreeGenerator.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static ParseTree parseJavadocFromFile(File file)
    throws IOException {
    final String content = Files.toString(file, Charsets.UTF_8);
    final InputStream in = new ByteArrayInputStream(content.getBytes(Charsets.UTF_8));

    final ANTLRInputStream input = new ANTLRInputStream(in);
    final JavadocLexer lexer = new JavadocLexer(input);
    lexer.removeErrorListeners();

    final BaseErrorListener errorListener = new FailOnErrorListener();
    lexer.addErrorListener(errorListener);

    final CommonTokenStream tokens = new CommonTokenStream(lexer);

    final JavadocParser parser = new JavadocParser(tokens);
    parser.removeErrorListeners();
    parser.addErrorListener(errorListener);

    return parser.javadoc();
}
 
Example #2
Source File: LogInstruction.java    From onedev with MIT License 6 votes vote down vote up
public static InstructionContext parse(String instructionString) {
	CharStream is = CharStreams.fromString(instructionString); 
	LogInstructionLexer lexer = new LogInstructionLexer(is);
	lexer.removeErrorListeners();
	lexer.addErrorListener(new BaseErrorListener() {

		@Override
		public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
				int charPositionInLine, String msg, RecognitionException e) {
			throw new RuntimeException("Malformed log instruction");
		}
		
	});
	CommonTokenStream tokens = new CommonTokenStream(lexer);
	LogInstructionParser parser = new LogInstructionParser(tokens);
	parser.removeErrorListeners();
	parser.setErrorHandler(new BailErrorStrategy());
	return parser.instruction();
}
 
Example #3
Source File: QueryTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void simpleCommentsWork() throws Exception {
    String queryString = "select * where { ?s ?p ?o }#?s ?p ?o }";
    String expectedQuery = "select * where { ?s ?p ?o }";
    Sparql11Parser parser = Query.getParser(queryString);
    TokenStream tokens = parser.getTokenStream();
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
        }
    });

    parser.query();
    assertEquals(expectedQuery, tokens.getText());
}
 
Example #4
Source File: QueryTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void insensitiveToCase() throws Exception {
    String queryString = "select * WHERE { ?x ?Y ?z }";
    String queryNoSpaces = "select*WHERE{?x?Y?z}";
    Sparql11Parser parser = Query.getParser(queryString);
    TokenStream tokens = parser.getTokenStream();
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
        }
    });

    assertEquals(queryNoSpaces, parser.query().selectQuery().getText());
    assertEquals(queryString, tokens.getText());
}
 
Example #5
Source File: QueryTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void replaceDatasetClause() throws Exception {
    InputStream query = getClass().getResourceAsStream("/example2.rq");
    Sparql11Parser parser = Query.getParser(streamToString(query));
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
        }
    });

    Sparql11Parser.QueryContext queryContext = parser.query();

    // Rewrite the dataset clause
    TokenStreamRewriter rewriter = new TokenStreamRewriter(parser.getTokenStream());
    ParseTreeWalker walker = new ParseTreeWalker();
    DatasetListener listener = new DatasetListener(rewriter);
    walker.walk(listener, queryContext);

    // Test result
    String newText = rewriter.getText();
    parser = Query.getParser(newText);
    String datasetText = parser.query().selectQuery().datasetClause().get(0).getText();
    assertEquals(DATASET_REPLACEMENT, datasetText);
}
 
Example #6
Source File: Tool.java    From bookish with MIT License 5 votes vote down vote up
public static BaseErrorListener getErrorListener(String location) {
	return new BaseErrorListener() {
		@Override
		public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
			String srcName = ParrtIO.basename(recognizer.getInputStream().getSourceName());
			if ( srcName.startsWith("<") && location!=null ) {
				srcName = location;
			}
			System.err.println(srcName+" line "+line+":"+charPositionInLine+" "+msg);
		}
	};
}
 
Example #7
Source File: ScoreVisitorImplTest.java    From fix-orchestra with Apache License 2.0 5 votes vote down vote up
private ScoreParser parse(String expression) throws IOException {
  ScoreLexer l = new ScoreLexer(CharStreams.fromString(expression));
  ScoreParser p = new ScoreParser(new CommonTokenStream(l));
  p.addErrorListener(new BaseErrorListener() {
    @Override
    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
        int charPositionInLine, String msg, RecognitionException e) {
      throw new IllegalStateException(String.format(
          "Failed to parse at line %d position %d due to %s", line, charPositionInLine, msg), e);
    }
  });
  return p;
}
 
Example #8
Source File: QueryTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void insensitiveToCaseBuiltInCall() throws Exception {
    String queryString = "select * WHERE { ?s ?P ?o FILTeR (sameTeRm(?s, ?o))}";
    Sparql11Parser parser = Query.getParser(queryString);
    TokenStream tokens = parser.getTokenStream();
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
        }
    });

    parser.query();
    assertEquals(queryString, tokens.getText());
}
 
Example #9
Source File: QueryTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void multipleSelectVars() throws Exception {
    String queryString = "select ?s ?p where { ?s ?p ?o }";
    Sparql11Parser parser = Query.getParser(queryString);
    TokenStream tokens = parser.getTokenStream();
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
        }
    });

    parser.query();
    assertEquals(queryString, tokens.getText());
}
 
Example #10
Source File: QueryTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void parseSimpleQuery() throws Exception {
    InputStream query = getClass().getResourceAsStream("/example1.rq");
    Sparql11Parser parser = Query.getParser(streamToString(query));
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
        }
    });
    parser.query();
}
 
Example #11
Source File: Query.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Sparql11Parser getParser(String query) {
    Sparql11Lexer lexer = new Sparql11Lexer(new CaseInsensitiveInputStream(query));
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    Sparql11Parser parser = new Sparql11Parser(tokens);
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                                int charPositionInLine, String msg, RecognitionException ex) {
            throw new MalformedQueryException("Failed to parse at line " + line + " due to " + msg, ex);
        }
    });
    return parser;
}
 
Example #12
Source File: CollectdTags.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Map<String, Any2<String, Number>> parse(String pattern) {
    class DescriptiveErrorListener extends BaseErrorListener {
        public List<String> errors = new ArrayList<>();

        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
                                int line, int charPositionInLine,
                                String msg, RecognitionException e) {
            errors.add(String.format("%d:%d: %s", line, charPositionInLine, msg));
        }
    }

    final DescriptiveErrorListener error_listener = new DescriptiveErrorListener();

    final CollectdTagsLexer lexer = new CollectdTagsLexer(new ANTLRInputStream(pattern));
    lexer.removeErrorListeners();
    lexer.addErrorListener(error_listener);
    final CollectdTagsParser parser = new CollectdTagsParser(new UnbufferedTokenStream(lexer));
    parser.removeErrorListeners();
    parser.addErrorListener(error_listener);

    parser.setErrorHandler(new BailErrorStrategy());
    final CollectdTagsParser.ExprContext result = parser.expr();
    if (result.exception != null)
        throw new IllegalArgumentException("errors during parsing: " + pattern, result.exception);
    else if (!error_listener.errors.isEmpty())
        throw new IllegalArgumentException("syntax errors during parsing:\n" + String.join("\n", error_listener.errors.stream().map(s -> "  " + s).collect(Collectors.toList())));
    return result.result;
}
 
Example #13
Source File: StringTemplate.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static StringTemplate fromString(String pattern) {
    class DescriptiveErrorListener extends BaseErrorListener {
        public List<String> errors = new ArrayList<>();

        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
                                int line, int charPositionInLine,
                                String msg, RecognitionException e) {
            errors.add(String.format("%d:%d: %s", line, charPositionInLine, msg));
        }
    }

    final DescriptiveErrorListener error_listener = new DescriptiveErrorListener();

    final StringSubstitutionLexer lexer = new StringSubstitutionLexer(CharStreams.fromString(pattern));
    lexer.removeErrorListeners();
    lexer.addErrorListener(error_listener);
    final StringSubstitutionParser parser = new StringSubstitutionParser(new UnbufferedTokenStream(lexer));
    parser.removeErrorListeners();
    parser.addErrorListener(error_listener);

    parser.setErrorHandler(new BailErrorStrategy());
    final StringSubstitutionParser.ExprContext result = parser.expr();
    if (result.exception != null)
        throw new IllegalArgumentException("errors during parsing: " + pattern, result.exception);
    else if (!error_listener.errors.isEmpty())
        throw new IllegalArgumentException("syntax errors during parsing:\n" + String.join("\n", error_listener.errors.stream().map(s -> "  " + s).collect(Collectors.toList())));
    return result.s;
}
 
Example #14
Source File: AntlrConditionParser.java    From styx with Apache License 2.0 5 votes vote down vote up
@Override
public Condition parse(String condition) {
    ConditionParser parser = new ConditionParser(
            new CommonTokenStream(new ConditionLexer(new ANTLRInputStream(condition))));
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            throw new DslSyntaxError(line, charPositionInLine, msg, e);
        }
    });

    return new AntlrCondition(expressionVisitor.visit(parser.expression()));
}
 
Example #15
Source File: LexerWrapper.java    From antlr4-autosuggest with Apache License 2.0 5 votes vote down vote up
private TokenizationResult tokenize(String input) {
    Lexer lexer = this.createLexer(input);
    lexer.removeErrorListeners();
    final TokenizationResult result = new TokenizationResult();
    ANTLRErrorListener newErrorListener = new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException {
            result.untokenizedText = input.substring(charPositionInLine); // intended side effect
        }
    };
    lexer.addErrorListener(newErrorListener);
    result.tokens = lexer.getAllTokens();
    return result;
}
 
Example #16
Source File: Interpolative.java    From onedev with MIT License 5 votes vote down vote up
public static Interpolative parse(String interpolativeString) {
	CharStream is = CharStreams.fromString(interpolativeString); 
	InterpolativeLexer lexer = new InterpolativeLexer(is);
	lexer.removeErrorListeners();
	lexer.addErrorListener(new BaseErrorListener() {

		@Override
		public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
				int charPositionInLine, String msg, RecognitionException e) {
			throw new RuntimeException("Malformed interpolative: " + interpolativeString);
		}
		
	});
	CommonTokenStream tokens = new CommonTokenStream(lexer);
	InterpolativeParser parser = new InterpolativeParser(tokens);
	parser.removeErrorListeners();
	parser.setErrorHandler(new BailErrorStrategy());
	
	List<Segment> segments = new ArrayList<>();
	for (SegmentContext segment: parser.interpolative().segment()) {
		if (segment.Literal() != null) 
			segments.add(new Segment(Type.LITERAL, segment.Literal().getText()));
		else
			segments.add(new Segment(Type.VARIABLE, FenceAware.unfence(segment.Variable().getText())));
	}
	return new Interpolative(segments);
}
 
Example #17
Source File: PatternSet.java    From onedev with MIT License 5 votes vote down vote up
public static PatternSet parse(@Nullable String patternSetString) {
	Set<String> includes = new HashSet<>();
	Set<String> excludes = new HashSet<>();
	
	if (patternSetString != null) {
		CharStream is = CharStreams.fromString(patternSetString); 
		PatternSetLexer lexer = new PatternSetLexer(is);
		lexer.removeErrorListeners();
		lexer.addErrorListener(new BaseErrorListener() {

			@Override
			public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
					int charPositionInLine, String msg, RecognitionException e) {
				throw new RuntimeException("Malformed pattern set");
			}
			
		});
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		PatternSetParser parser = new PatternSetParser(tokens);
		parser.removeErrorListeners();
		parser.setErrorHandler(new BailErrorStrategy());
		
		PatternsContext patternsContext = parser.patterns();
		
		for (PatternContext pattern: patternsContext.pattern()) {
			String value;
			if (pattern.Quoted() != null) 
				value = FenceAware.unfence(pattern.Quoted().getText());
			else 
				value = pattern.NQuoted().getText();
			value = StringUtils.unescape(value);
			if (pattern.Excluded() != null)
				excludes.add(value);
			else 
				includes.add(value);
		}			
	}
	
	return new PatternSet(includes, excludes);
}
 
Example #18
Source File: UserMatch.java    From onedev with MIT License 5 votes vote down vote up
public static UserMatch parse(@Nullable String userMatchString) {
	List<UserMatchCriteria> criterias = new ArrayList<>();
	List<UserMatchCriteria> exceptCriterias = new ArrayList<>();
	
	if (userMatchString != null) {
		CharStream is = CharStreams.fromString(userMatchString); 
		UserMatchLexer lexer = new UserMatchLexer(is);
		lexer.removeErrorListeners();
		lexer.addErrorListener(new BaseErrorListener() {

			@Override
			public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
					int charPositionInLine, String msg, RecognitionException e) {
				throw new RuntimeException("Malformed user match");
			}
			
		});
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		UserMatchParser parser = new UserMatchParser(tokens);
		parser.removeErrorListeners();
		parser.setErrorHandler(new BailErrorStrategy());
		
		UserMatchContext userMatchContext = parser.userMatch();
		
		for (CriteriaContext criteriaContext: userMatchContext.criteria())
			criterias.add(getUserMatchCriteria(criteriaContext));
		
		for (ExceptCriteriaContext exceptCriteriaContext: userMatchContext.exceptCriteria()) {
			exceptCriterias.add(getUserMatchCriteria(exceptCriteriaContext.criteria()));
		}
	}
	
	return new UserMatch(criterias, exceptCriterias);
}
 
Example #19
Source File: PathMatcher.java    From monsoon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Read path matcher from reader.
 *
 * @param reader A reader supplying the input of a path expression.
 * @return A PathMatcher corresponding to the parsed input
 * from the reader.
 * @throws IOException on IO errors from the reader.
 * @throws
 * com.groupon.lex.metrics.PathMatcher.ParseException
 * on invalid path expression.
 */
public static PathMatcher valueOf(Reader reader) throws IOException, ParseException {
    class DescriptiveErrorListener extends BaseErrorListener {
        public List<String> errors = new ArrayList<>();

        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
                                int line, int charPositionInLine,
                                String msg, org.antlr.v4.runtime.RecognitionException e) {
            LOG.log(Level.INFO, "Parse error: {0}:{1} -> {2}", new Object[]{line, charPositionInLine, msg});
            errors.add(String.format("%d:%d: %s", line, charPositionInLine, msg));
        }
    }

    final DescriptiveErrorListener error_listener = new DescriptiveErrorListener();

    final PathMatcherLexer lexer = new PathMatcherLexer(CharStreams.fromReader(reader));
    lexer.removeErrorListeners();
    lexer.addErrorListener(error_listener);

    final PathMatcherGrammar parser = new PathMatcherGrammar(new BufferedTokenStream(lexer));
    parser.removeErrorListeners();
    parser.addErrorListener(error_listener);

    final PathMatcherGrammar.ExprContext expr;
    try {
        expr = parser.expr();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "parser yielded exceptional return", ex);
        if (!error_listener.errors.isEmpty())
            throw new ParseException(error_listener.errors, ex);
        else
            throw ex;
    }

    if (!error_listener.errors.isEmpty()) {
        if (expr.exception != null)
            throw new ParseException(error_listener.errors, expr.exception);
        throw new ParseException(error_listener.errors);
    } else if (expr.exception != null) {
        throw new ParseException(expr.exception);
    }
    return expr.s;
}
 
Example #20
Source File: TimeSeriesMetricExpression.java    From monsoon with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Read expression from reader.
 *
 * @param reader A reader supplying the input of an expression.
 * @return A TimeSeriesMetricExpression corresponding to the parsed input
 * from the reader.
 * @throws IOException on IO errors from the reader.
 * @throws
 * com.groupon.lex.metrics.timeseries.TimeSeriesMetricExpression.ParseException
 * on invalid expression.
 */
public static TimeSeriesMetricExpression valueOf(Reader reader) throws IOException, ParseException {
    final Logger LOG = Logger.getLogger(TimeSeriesMetricExpression.class.getName());

    class DescriptiveErrorListener extends BaseErrorListener {
        public List<String> errors = new ArrayList<>();

        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
                                int line, int charPositionInLine,
                                String msg, org.antlr.v4.runtime.RecognitionException e) {
            LOG.log(Level.INFO, "Parse error: {0}:{1} -> {2}", new Object[]{line, charPositionInLine, msg});
            errors.add(String.format("%d:%d: %s", line, charPositionInLine, msg));
        }
    }

    final DescriptiveErrorListener error_listener = new DescriptiveErrorListener();

    final ExpressionLexer lexer = new ExpressionLexer(CharStreams.fromReader(reader));
    lexer.removeErrorListeners();
    lexer.addErrorListener(error_listener);

    final Expression parser = new Expression(new BufferedTokenStream(lexer));
    parser.removeErrorListeners();
    parser.addErrorListener(error_listener);

    final Expression.ExprContext expr;
    try {
        expr = parser.expr();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, "parser yielded exceptional return", ex);
        if (!error_listener.errors.isEmpty())
            throw new ParseException(error_listener.errors, ex);
        else
            throw ex;
    }

    if (!error_listener.errors.isEmpty()) {
        if (expr.exception != null)
            throw new ParseException(error_listener.errors, expr.exception);
        throw new ParseException(error_listener.errors);
    } else if (expr.exception != null) {
        throw new ParseException(expr.exception);
    }
    return expr.s;
}
 
Example #21
Source File: ReviewRequirement.java    From onedev with MIT License 4 votes vote down vote up
public static ReviewRequirement parse(@Nullable String requirementString, boolean validate) {
	List<User> users = new ArrayList<>();
	Map<Group, Integer> groups = new LinkedHashMap<>();
	
	if (requirementString != null) {
		CharStream is = CharStreams.fromString(requirementString); 
		ReviewRequirementLexer lexer = new ReviewRequirementLexer(is);
		lexer.removeErrorListeners();
		lexer.addErrorListener(new BaseErrorListener() {

			@Override
			public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
					int charPositionInLine, String msg, RecognitionException e) {
				throw new RuntimeException("Malformed review requirement");
			}
			
		});
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		ReviewRequirementParser parser = new ReviewRequirementParser(tokens);
		parser.removeErrorListeners();
		parser.setErrorHandler(new BailErrorStrategy());
		
		RequirementContext requirementContext = parser.requirement();
		
		for (CriteriaContext criteria: requirementContext.criteria()) {
			if (criteria.userCriteria() != null) {
				String userName = getValue(criteria.userCriteria().Value());
				User user = OneDev.getInstance(UserManager.class).findByName(userName);
				if (user != null) {
					if (!users.contains(user)) 
						users.add(user);
					else if (validate)
						throw new OneException("User '" + userName + "' is included multiple times");
				} else if (validate) {
					throw new OneException("Unable to find user '" + userName + "'");
				}
			} else if (criteria.groupCriteria() != null) {
				String groupName = getValue(criteria.groupCriteria().Value());
				Group group = OneDev.getInstance(GroupManager.class).find(groupName);
				if (group != null) {
					if (!groups.containsKey(group)) {
						CountContext count = criteria.groupCriteria().count();
						if (count != null) {
							if (count.DIGIT() != null)
								groups.put(group, Integer.parseInt(count.DIGIT().getText()));
							else
								groups.put(group, 0);
						} else {
							groups.put(group, 1);
						}
					} else if (validate) {
						throw new OneException("Group '" + groupName + "' is included multiple times");
					}
				} else if (validate) {
					throw new OneException("Unable to find group '" + groupName + "'");
				}
			}
		}			
	}
	
	return new ReviewRequirement(users, groups);
}
 
Example #22
Source File: QueryTest.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
public void complexCommentsWork() throws Exception {
    String queryString = "########################\n" +
            "### Find all the things\n" +
            "########################\n" +
            "\n" +
            "prefix uhtc: <http://mobi.com/ontologies/uhtc#> # This is a comment\n" +
            "\n" +
            "select\n" +
            "\t?formula\n" +
            "\t?density # This is a comment\n" +
            "\t?meltingPointCelsius\n" +
            "\t(group_concat(distinct ?elementName;separator=',') as ?elements)\n" +
            "where { # This is a comment\n" +
            "    ?material a uhtc:Material ; # This is a comment\n" +
            "                uhtc:chemicalFormula ?formula ; # This is a comment\n" +
            "                uhtc:density ?density ;\n" +
            "                uhtc:meltingPoint ?meltingPointCelsius ;\n" +
            "                uhtc:element ?element . # This is a comment\n" +
            "    \n" +
            "    ?element a uhtc:Element ; # This is a comment\n" +
            "               uhtc:elementName ?elementName ;\n" +
            "               uhtc:symbol ?symbol .\n" +
            "} # This is a comment\n" +
            "GROUP BY ?formula ?density ?meltingPointCelsius" +
            "# This is a comment";
    String expectedQuery = "\nprefix uhtc: <http://mobi.com/ontologies/uhtc#> " +
            "\n" +
            "select\n" +
            "\t?formula\n" +
            "\t?density " +
            "\t?meltingPointCelsius\n" +
            "\t(group_concat(distinct ?elementName;separator=',') as ?elements)\n" +
            "where { " +
            "    ?material a uhtc:Material ; " +
            "                uhtc:chemicalFormula ?formula ; " +
            "                uhtc:density ?density ;\n" +
            "                uhtc:meltingPoint ?meltingPointCelsius ;\n" +
            "                uhtc:element ?element . " +
            "    \n" +
            "    ?element a uhtc:Element ; " +
            "               uhtc:elementName ?elementName ;\n" +
            "               uhtc:symbol ?symbol .\n" +
            "} " +
            "GROUP BY ?formula ?density ?meltingPointCelsius";
    Sparql11Parser parser = Query.getParser(queryString);
    TokenStream tokens = parser.getTokenStream();
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
        }
    });

    parser.query();
    assertEquals(expectedQuery, tokens.getText());
}
 
Example #23
Source File: CommitQuery.java    From onedev with MIT License 4 votes vote down vote up
public static CommitQuery parse(Project project, @Nullable String queryString) {
	List<CommitCriteria> criterias = new ArrayList<>();
	if (queryString != null) {
		CharStream is = CharStreams.fromString(queryString); 
		CommitQueryLexer lexer = new CommitQueryLexer(is);
		lexer.removeErrorListeners();
		lexer.addErrorListener(new BaseErrorListener() {

			@Override
			public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
					int charPositionInLine, String msg, RecognitionException e) {
				throw new RuntimeException("Malformed commit query", e);
			}
			
		});
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		CommitQueryParser parser = new CommitQueryParser(tokens);
		parser.removeErrorListeners();
		parser.setErrorHandler(new BailErrorStrategy());
		
		List<String> authorValues = new ArrayList<>();
		List<String> committerValues = new ArrayList<>();
		List<String> beforeValues = new ArrayList<>();
		List<String> afterValues = new ArrayList<>();
		List<String> pathValues = new ArrayList<>();
		List<String> messageValues = new ArrayList<>();
		List<Revision> revisions = new ArrayList<>();
		
		for (CriteriaContext criteria: parser.query().criteria()) {
			if (criteria.authorCriteria() != null) {
				if (criteria.authorCriteria().AuthoredByMe() != null)
					authorValues.add(null);
				else
					authorValues.add(getValue(criteria.authorCriteria().Value()));
			} else if (criteria.committerCriteria() != null) {
				if (criteria.committerCriteria().CommittedByMe() != null)
					committerValues.add(null);
				else
					committerValues.add(getValue(criteria.committerCriteria().Value()));
			} else if (criteria.messageCriteria() != null) { 
				messageValues.add(getValue(criteria.messageCriteria().Value()));
			} else if (criteria.pathCriteria() != null) {
				pathValues.add(getValue(criteria.pathCriteria().Value()));
			} else if (criteria.beforeCriteria() != null) {
				beforeValues.add(getValue(criteria.beforeCriteria().Value()));
			} else if (criteria.afterCriteria() != null) {
				afterValues.add(getValue(criteria.afterCriteria().Value()));
			} else if (criteria.revisionCriteria() != null) {
				String value;
				Revision.Scope scope;
				if (criteria.revisionCriteria().DefaultBranch() != null)
					value = project.getDefaultBranch();
				else 
					value = getValue(criteria.revisionCriteria().Value());
				if (criteria.revisionCriteria().BUILD() != null) {
					String numberStr = value;
					if (numberStr.startsWith("#"))
						numberStr = numberStr.substring(1);
					if (NumberUtils.isDigits(numberStr)) {
						Build build = OneDev.getInstance(BuildManager.class).find(project, Long.parseLong(numberStr));
						if (build == null)
							throw new OneException("Unable to find build: " + value);
						else
							value = build.getCommitHash();
					} else {
						throw new OneException("Invalid build number: " + numberStr);
					}
				}
				if (criteria.revisionCriteria().SINCE() != null)
					scope = Revision.Scope.SINCE;
				else if (criteria.revisionCriteria().UNTIL() != null)
					scope = Revision.Scope.UNTIL;
				else
					scope = null;
				revisions.add(new Revision(value, scope, criteria.revisionCriteria().getText()));
			}
		}
		
		if (!authorValues.isEmpty())
			criterias.add(new AuthorCriteria(authorValues));
		if (!committerValues.isEmpty())
			criterias.add(new CommitterCriteria(committerValues));
		if (!pathValues.isEmpty())
			criterias.add(new PathCriteria(pathValues));
		if (!messageValues.isEmpty())
			criterias.add(new MessageCriteria(messageValues));
		if (!beforeValues.isEmpty())
			criterias.add(new BeforeCriteria(beforeValues));
		if (!afterValues.isEmpty())
			criterias.add(new AfterCriteria(afterValues));
		if (!revisions.isEmpty())
			criterias.add(new RevisionCriteria(revisions));
	}
	
	return new CommitQuery(criterias);
}
 
Example #24
Source File: ScoreTranslatorTest.java    From fix-orchestra with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@ValueSource(strings = {
    "$x = 55", 
    "$x = -55",
    "$y = \"MyName\"", 
    "$x = 50 + 5", 
    "$z = in.OrdType",
    "out.OrdQty = 55", 
    "in.OrdType == ^Stop", 
    "in.OrdType in {^Stop, ^StopLimit}",
    "in.OrdType == ^Stop or in.OrdType == ^StopLimit", 
    "in.OrdQty > 0",
    "in.OrdQty != 0", 
    "in.OrdQty > 0 and in.OrdQty <= 10", 
    "in.Price < 100.00",
    "in.Price between 50.00 and 100.00",
    "in.Parties[PartyRole==4].PartyID=\"690\"",
    "out.Parties[1].PartyRole=4",
    "out.Parties[1].PartyRole=^ClearingFirm",
    "#2017-02-02T22:13:28Z#",
    "#2017-02-02T22:13:28.678Z#",
    "#22:13:28Z#",
    "#2017-02-02#",
    "#2017-02-02T22:13:28-06:00#",
    "#P30D#",
    "#PT30S#",
    "out.ExpireDate=#2017-02-03#",
    "out.ExpireTime=#2017-02-02T22:15:00Z#",
    "exists in.StopPx",
    "$Market.SecMassStatGrp[SecurityID==in.SecurityID].SecurityTradingStatus != ^TradingHalt and $Market.Phase == \"Open\"",
    "$Market.Phase == \"Closed\"",
    "!exists $Market.SecMassStatGrp[SecurityID==in.SecurityID]",
    })
public void testExampleFieldCondition(String expression) throws Exception {
  ScoreLexer l = new ScoreLexer(CharStreams.fromString(expression));
  ScoreParser p = new ScoreParser(new CommonTokenStream(l));
  p.addErrorListener(new BaseErrorListener() {
    @Override
    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
        int charPositionInLine, String msg, RecognitionException e) {
      throw new IllegalStateException(String.format(
          "Failed to parse at line %d position %d due to %s", line, charPositionInLine, msg), e);
    }
  });
  ScoreTranslator visitor = new ScoreTranslator();
  AnyExpressionContext ctx = p.anyExpression();
  String text = visitor.visitAnyExpression(ctx);
  //System.out.println(text);
}
 
Example #25
Source File: Program.java    From eo with MIT License 4 votes vote down vote up
/**
 * Compile it to Java and save.
 *
 * @throws IOException If fails
 */
public void compile() throws IOException {
    final String[] lines = new TextOf(this.input).asString().split("\n");
    final ANTLRErrorListener errors = new BaseErrorListener() {
        // @checkstyle ParameterNumberCheck (10 lines)
        @Override
        public void syntaxError(final Recognizer<?, ?> recognizer,
            final Object symbol, final int line,
            final int position, final String msg,
            final RecognitionException error) {
            throw new CompileException(
                String.format(
                    "[%d:%d] %s: \"%s\"",
                    line, position, msg, lines[line - 1]
                ),
                error
            );
        }
    };
    final org.eolang.compiler.ProgramLexer lexer =
        new org.eolang.compiler.ProgramLexer(
            CharStreams.fromStream(this.input.stream())
        );
    lexer.removeErrorListeners();
    lexer.addErrorListener(errors);
    final org.eolang.compiler.ProgramParser parser =
        new org.eolang.compiler.ProgramParser(
            new CommonTokenStream(lexer)
        );
    parser.removeErrorListeners();
    parser.addErrorListener(errors);
    final Tree tree = parser.program().ret;
    new IoCheckedScalar<>(
        new And(
            path -> {
                new LengthOf(
                    new TeeInput(
                        path.getValue(),
                        this.target.apply(path.getKey())
                    )
                ).value();
            },
            tree.java().entrySet()
        )
    ).value();
}
 
Example #26
Source File: Tool.java    From bookish with MIT License 4 votes vote down vote up
public static BaseErrorListener getErrorListener() {
	return getErrorListener(null);
}