org.parboiled.support.ParsingResult Java Examples

The following examples show how to use org.parboiled.support.ParsingResult. 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: RunParser.java    From immutables with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) {

    Parser templateParser = Parboiled.createParser(Parser.class);
    ParsingResult<Object> result = new ReportingParseRunner<>(templateParser.Unit()).run(input2);

    ImmutableList<Object> copy = ImmutableList.copyOf(result.valueStack.iterator());

    if (!copy.isEmpty()) {
      Unit unit = (Unit) copy.get(0);

      Unit balance = Balancing.balance(unit);
      System.out.println(balance);
    }

    if (result.hasErrors()) {
      System.err.println(ErrorUtils.printParseErrors(result.parseErrors));
    }
    // System.out.println(ParseTreeUtils.printNodeTree(result));
  }
 
Example #2
Source File: OfficialLeelazAnalyzerV1.java    From mylizzie with GNU General Public License v3.0 6 votes vote down vote up
public static MoveData parseMoveDataLine(String line) {
    ParsingResult<?> result = runner.run(line);
    if (!result.matched) {
        return null;
    }

    MutableMap<String, Object> data = (MutableMap<String, Object>) result.valueStack.peek();

    MutableList<String> variation = (MutableList<String>) data.get("PV");
    String coordinate = (String) data.get("MOVE");
    int playouts = Integer.parseInt((String) data.get("CALCULATION"));
    double winrate = Double.parseDouble((String) data.get("VALUE")) / 100.0;
    double probability = getRate((String) data.get("POLICY"));

    return new MoveData(coordinate, playouts, winrate, probability, variation);
}
 
Example #3
Source File: ParboiledAutoComplete.java    From batfish with Apache License 2.0 6 votes vote down vote up
private Set<PotentialMatch> getPotentialMatches(String query) {
  /**
   * Before passing the query to the parser, we make it illegal by adding a funny, non-ascii
   * character (soccer ball :)). We will not get any errors backs if the string is legal.
   */
  String testQuery = query + new String(Character.toChars(ILLEGAL_CHAR));

  ParsingResult<AstNode> result = new ReportingParseRunner<AstNode>(_inputRule).run(testQuery);
  if (result.parseErrors.isEmpty()) {
    throw new IllegalStateException("Failed to force erroneous input");
  }

  InvalidInputError error = (InvalidInputError) result.parseErrors.get(0);

  return ParserUtils.getPotentialMatches(error, _completionTypes, false);
}
 
Example #4
Source File: TestBase.java    From nb-springboot with Apache License 2.0 6 votes vote down vote up
protected void parseMatch(String input) {
    ParsingResult<?> result = reportingRunner.run(input);
    if (result.matched) {
        System.out.println(ParseTreeUtils.printNodeTree(result));
        final Properties pp = parser.getParsedProps();
        if (!pp.isEmpty()) {
            listPropsOrdered(pp);
        }
    } else {
        result = tracingRunner.run(input);
        System.out.println("\n\nParser did not match input:");
        for (ParseError pe : result.parseErrors) {
            System.out.format("\t%s%n", ErrorUtils.printParseError(pe));
        }
    }
    assertTrue(result.matched);
    assertFalse(result.hasErrors());
}
 
Example #5
Source File: ParboiledLocationSpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an {@link LocationSpecifier} based on {@code input} which is parsed as {@link
 * Grammar#LOCATION_SPECIFIER}.
 *
 * @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
 */
public static ParboiledLocationSpecifier parse(String input) {

  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(
              Parser.instance().getInputRule(Grammar.LOCATION_SPECIFIER))
          .run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input,
            Grammar.LOCATION_SPECIFIER,
            (InvalidInputError) result.parseErrors.get(0),
            Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);
  checkArgument(
      ast instanceof LocationAstNode,
      "ParboiledLocationSpecifier requires a LocationSpecifier input");

  return new ParboiledLocationSpecifier((LocationAstNode) ast);
}
 
Example #6
Source File: ParboiledNameSetSpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an {@link NameSetSpecifier} based on parsing the {@code input} according to the
 * specified grammar
 *
 * @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
 */
public static ParboiledNameSetSpecifier parse(String input, Grammar grammar) {
  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(Parser.instance().getInputRule(grammar)).run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input, grammar, (InvalidInputError) result.parseErrors.get(0), Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);
  checkArgument(
      ast instanceof NameSetAstNode,
      "Unexpected AST when parsing '%s' as enum grammar: %s",
      input,
      ast);

  return new ParboiledNameSetSpecifier((NameSetAstNode) ast, grammar);
}
 
Example #7
Source File: ParboiledInterfaceSpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an {@link InterfaceSpecifier} based on {@code input} which is parsed as {@link
 * Grammar#INTERFACE_SPECIFIER}.
 *
 * @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
 */
public static ParboiledInterfaceSpecifier parse(String input) {
  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(
              Parser.instance().getInputRule(Grammar.INTERFACE_SPECIFIER))
          .run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input,
            Grammar.INTERFACE_SPECIFIER,
            (InvalidInputError) result.parseErrors.get(0),
            Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);
  checkArgument(
      ast instanceof InterfaceAstNode,
      "ParboiledInterfaceSpecifier requires an InterfaceSpecifier input");

  return new ParboiledInterfaceSpecifier((InterfaceAstNode) ast);
}
 
Example #8
Source File: ParboiledFilterSpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an {@link FilterSpecifier} based on {@code input} which is parsed as {@link
 * Grammar#FILTER_SPECIFIER}.
 *
 * @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
 */
public static ParboiledFilterSpecifier parse(String input) {
  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(Parser.instance().getInputRule(Grammar.FILTER_SPECIFIER))
          .run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input,
            Grammar.FILTER_SPECIFIER,
            (InvalidInputError) result.parseErrors.get(0),
            Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);
  checkArgument(
      ast instanceof FilterAstNode, "ParboiledFilterSpecifier requires an FilterSpecifier input");

  return new ParboiledFilterSpecifier((FilterAstNode) ast);
}
 
Example #9
Source File: ParboiledEnumSetSpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an {@link EnumSetSpecifier} based on parsing the {@code input} according to the
 * specified grammar
 *
 * @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
 */
public static <T> ParboiledEnumSetSpecifier<T> parse(String input, Grammar grammar) {
  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(Parser.instance().getInputRule(grammar)).run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input, grammar, (InvalidInputError) result.parseErrors.get(0), Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);
  checkArgument(
      ast instanceof EnumSetAstNode,
      "Unexpected AST when parsing '%s' as enum grammar: %s",
      input,
      ast);

  return new ParboiledEnumSetSpecifier<>((EnumSetAstNode) ast, grammar);
}
 
Example #10
Source File: ParboiledAppSpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an {@link ApplicationSpecifier} based on {@code input} which is parsed as {@link
 * Grammar#APPLICATION_SPECIFIER}.
 *
 * @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
 */
public static ParboiledAppSpecifier parse(String input) {
  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(
              Parser.instance().getInputRule(Grammar.APPLICATION_SPECIFIER))
          .run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input,
            Grammar.APPLICATION_SPECIFIER,
            (InvalidInputError) result.parseErrors.get(0),
            Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);
  checkArgument(
      ast instanceof AppAstNode, "ParboiledAppSpecifier requires an IP protocol specifier input");

  return new ParboiledAppSpecifier((AppAstNode) ast);
}
 
Example #11
Source File: ParboiledIpSpaceSpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an {@link IpSpaceSpecifier} based on {@code input} which is parsed as {@link
 * Grammar#IP_SPACE_SPECIFIER}.
 *
 * @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
 */
public static ParboiledIpSpaceSpecifier parse(String input) {
  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(
              Parser.instance().getInputRule(Grammar.IP_SPACE_SPECIFIER))
          .run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input,
            Grammar.IP_SPACE_SPECIFIER,
            (InvalidInputError) result.parseErrors.get(0),
            Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);
  checkArgument(
      ast instanceof IpSpaceAstNode, "ParboiledIpSpaceSpecifier requires an IpSpace input");

  return new ParboiledIpSpaceSpecifier((IpSpaceAstNode) ast);
}
 
Example #12
Source File: ParboiledRoutingPolicySpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an {@link RoutingPolicySpecifier} based on {@code input} which is parsed as {@link
 * Grammar#ROUTING_POLICY_SPECIFIER}.
 *
 * @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
 */
public static ParboiledRoutingPolicySpecifier parse(String input) {
  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(
              Parser.instance().getInputRule(Grammar.ROUTING_POLICY_SPECIFIER))
          .run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input,
            Grammar.ROUTING_POLICY_SPECIFIER,
            (InvalidInputError) result.parseErrors.get(0),
            Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);

  checkArgument(
      ast instanceof RoutingPolicyAstNode,
      "ParboiledRoutingPolicySpecifier requires an RoutingPolicySpecifier input");

  return new ParboiledRoutingPolicySpecifier((RoutingPolicyAstNode) ast);
}
 
Example #13
Source File: ParboiledIpProtocolSpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an {@link IpProtocolSpecifier} based on {@code input} which is parsed as {@link
 * Grammar#IP_PROTOCOL_SPECIFIER}.
 *
 * @throws IllegalArgumentException if the parsing fails or does not produce the expected AST
 */
public static ParboiledIpProtocolSpecifier parse(String input) {
  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(
              Parser.instance().getInputRule(Grammar.IP_PROTOCOL_SPECIFIER))
          .run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input,
            Grammar.IP_PROTOCOL_SPECIFIER,
            (InvalidInputError) result.parseErrors.get(0),
            Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);
  checkArgument(
      ast instanceof IpProtocolAstNode,
      "ParboiledIpProtocolSpecifier requires an IP protocol specifier input");

  return new ParboiledIpProtocolSpecifier((IpProtocolAstNode) ast);
}
 
Example #14
Source File: OfficialLeelazAnalyzerV2.java    From mylizzie with GNU General Public License v3.0 6 votes vote down vote up
public static MutableList<MoveData> parseMoveDataLine(String line) {
    ParsingResult<?> result = runner.run(line);
    if (!result.matched) {
        return null;
    }

    return Streams.stream(result.valueStack)
            .map(o -> {
                MutableMap<String, Object> data = (MutableMap<String, Object>) o;

                MutableList<String> variation = (MutableList<String>) data.get("PV");
                String coordinate = (String) data.get("MOVE");
                int playouts = Integer.parseInt((String) data.get("CALCULATION"));
                double winrate = Double.parseDouble((String) data.get("VALUE")) / 100.0;
                double probability = getRate((String) data.get("POLICY")) + getRate((String) data.get("OLDPOLICY"));

                return new MoveData(coordinate, playouts, winrate, probability, variation);
            })
            .collect(Collectors.toCollection(Lists.mutable::empty))
            .reverseThis()
            ;
}
 
Example #15
Source File: ParboiledNodeSpecifier.java    From batfish with Apache License 2.0 6 votes vote down vote up
static NodeAstNode getAst(String input) {
  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(Parser.instance().getInputRule(Grammar.NODE_SPECIFIER))
          .run(input);

  if (!result.parseErrors.isEmpty()) {
    throw new IllegalArgumentException(
        ParserUtils.getErrorString(
            input,
            Grammar.NODE_SPECIFIER,
            (InvalidInputError) result.parseErrors.get(0),
            Parser.ANCHORS));
  }

  AstNode ast = ParserUtils.getAst(result);
  checkArgument(
      ast instanceof NodeAstNode, "Unexpected AST for nodeSpec input '%s': '%s'", input, ast);

  return (NodeAstNode) ast;
}
 
Example #16
Source File: ParserUtilsTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetErrorStringHasUrl() {
  String input = new String(Character.toChars(0x26bd)); // invalid input

  ParsingResult<AstNode> result =
      new ReportingParseRunner<AstNode>(
              Parser.instance().getInputRule(Grammar.IP_SPACE_SPECIFIER))
          .run(input);

  String errorString =
      ParserUtils.getErrorString(
          input,
          Grammar.IP_SPACE_SPECIFIER,
          (InvalidInputError) result.parseErrors.get(0),
          Parser.ANCHORS);

  assertThat(errorString, containsString(Grammar.IP_SPACE_SPECIFIER.getFullUrl()));
}
 
Example #17
Source File: MapSelectionExpressionParserTest.java    From jtwig-core with Apache License 2.0 6 votes vote down vote up
@Test
public void expressionRule() throws Exception {
    DefaultJtwigParserConfiguration config = new DefaultJtwigParserConfiguration();
    ParserContext context = ParserContext.instance(
            ResourceReference.inline("Hello"),
            config,
            config.getAddonParserProviders(),
            config.getUnaryOperators(),
            config.getBinaryOperators(),
            config.getTestExpressionParsers()
    );

    MapSelectionExpressionParser parser = context.parser(MapSelectionExpressionParser.class);

    TracingParseRunner<Expression> runner = new TracingParseRunner<>(parser.ExpressionRule());
    ParsingResult<Expression> result = runner.run("list[position.size]");
    Expression resultValue = result.resultValue;

    System.out.println(resultValue);
}
 
Example #18
Source File: IfNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void ifNodeWithMultipleElseIf() throws Exception {
    ParsingResult<IfNode> result = parse(underTest.NodeRule(), "{% if (true) %}{% elseif (false) %}{% elseif (false) %}{% endif %}");


    assertThat(result.matched, is(true));
    IfNode ifNode = result.valueStack.pop();
    assertThat(ifNode.getConditionNodes().size(), is(3));
}
 
Example #19
Source File: IncludeNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void NodeRuleIgnoreMissingWithOnly() throws Exception {
    ParsingResult<IncludeNode> result = parse(underTest.NodeRule(), "{% include 'test' ignore missing with joao only %}");

    assertThat(result.matched, is(true));
    IncludeNode node = result.valueStack.pop();
    assertThat(node.isIgnoreMissing(), is(true));
    assertThat(node.isInheritModel(), is(false));
    assertThat(node.getMapExpression(), instanceOf(VariableExpression.class));
}
 
Example #20
Source File: IncludeNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void NodeRuleIgnoreMissing() throws Exception {
    ParsingResult<IncludeNode> result = parse(underTest.NodeRule(), "{% include 'test' ignore missing %}");

    assertThat(result.matched, is(true));
    IncludeNode node = result.valueStack.pop();
    assertThat(node.isIgnoreMissing(), is(true));
    assertThat(node.isInheritModel(), is(true));
    assertThat(node.getMapExpression(), instanceOf(MapExpression.class));
}
 
Example #21
Source File: IncludeNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void NodeRuleSimple() throws Exception {
    ParsingResult<IncludeNode> result = parse(underTest.NodeRule(), "{% include 'test' %}");

    assertThat(result.matched, is(true));
    IncludeNode node = result.valueStack.pop();
    assertThat(node.isIgnoreMissing(), is(false));
    assertThat(node.isInheritModel(), is(true));
    assertThat(node.getMapExpression(), instanceOf(MapExpression.class));
}
 
Example #22
Source File: SetNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void set() throws Exception {
    ParsingResult<SetNode> result = parse(underTest.NodeRule(), "{% set a = 123 %}");

    assertThat(result.matched, is(true));
    assertThat(result.valueStack.isEmpty(), is(false));
}
 
Example #23
Source File: OutputNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void output() throws Exception {
    ParsingResult<OutputNode> result = parse(underTest.NodeRule(), "{{ one }}");

    assertThat(result.matched, is(true));
    OutputNode outputNode = result.valueStack.pop();
    assertThat(outputNode.getExpression(), instanceOf(VariableExpression.class));
}
 
Example #24
Source File: MacroNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void macroNodeWithNames() throws Exception {
    ParsingResult<MacroNode> result = parse(underTest.NodeRule(), "{% macro test(jtwig) %}{% endmacro %}");

    assertThat(result.matched, is(true));
    MacroNode macroNode = result.valueStack.pop();
    assertThat(macroNode.getMacroName().getIdentifier(), is("test"));
    assertThat(macroNode.getMacroArgumentNames().size(), is(1));
    assertThat(macroNode.getMacroArgumentNames().iterator().next(), is("jtwig"));

}
 
Example #25
Source File: ForLoopNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void forLoopNode() throws Exception {
    ParsingResult<ForLoopNode> result = parse(underTest.NodeRule(), "{% for a in test %}{% endfor %}");

    assertThat(result.matched, is(true));
    ForLoopNode loopNode = result.valueStack.pop();
    assertThat(loopNode.getVariableExpression().getIdentifier(), is("a"));
    assertThat(loopNode.getKeyVariableExpression().isPresent(), is(false));
}
 
Example #26
Source File: GroupWildcard.java    From batfish with Apache License 2.0 5 votes vote down vote up
/** Like {@link #toJavaRegex(String)}, but for debugging. */
@SuppressWarnings("unused") // leaving here for future debugging.
@Nonnull
static String debugToJavaRegex(String regex) {
  GroupWildcard parser = Parboiled.createParser(GroupWildcard.class);
  TracingParseRunner<String> runner =
      new TracingParseRunner<String>(parser.TopLevel()).withLog(new StringBuilderSink());
  ParsingResult<String> result = runner.run(regex);
  if (!result.matched) {
    throw new IllegalArgumentException("Unhandled input: " + regex + "\n" + runner.getLog());
  }
  return result.resultValue;
}
 
Example #27
Source File: ParserInterfaceTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
/** This testParses if we have proper completion annotations on the rules */
@Test
public void testAnchorAnnotations() {
  ParsingResult<?> result = getRunner().run("");

  // not barfing means all potential paths have completion annotation at least for empty input
  ParserUtils.getPotentialMatches(
      (InvalidInputError) result.parseErrors.get(0), Parser.ANCHORS, false);
}
 
Example #28
Source File: BlockNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void blockWithEndError() throws Exception {
    ParsingResult<BlockNode> result = parse(underTest.NodeRule(), "{% block test %}{% endblock testa %}");


    assertThat(result.matched, is(true));
    assertThat(result.hasErrors(), is(true));
}
 
Example #29
Source File: BlockNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void blockWithEnd() throws Exception {
    ParsingResult<BlockNode> result = parse(underTest.NodeRule(), "{% block test %}{% endblock test %}");


    assertThat(result.matched, is(true));
    BlockNode node = result.valueStack.pop();
    assertThat(node.getBlockIdentifier().getIdentifier(), is("test"));
}
 
Example #30
Source File: DoNodeParserTest.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void set() throws Exception {
    ParsingResult<SetNode> result = parse(underTest.NodeRule(), "{% do 1 + 123 %}");

    assertThat(result.matched, is(true));
    assertThat(result.valueStack.isEmpty(), is(false));
}