Skip to content

Instantly share code, notes, and snippets.

@butlermh
Last active December 17, 2015 01:39
Show Gist options
  • Save butlermh/5529862 to your computer and use it in GitHub Desktop.
Save butlermh/5529862 to your computer and use it in GitHub Desktop.
A minimal test case that shows the problem I am encountered parsing quoted strings with regex expressions in Parboiled.
import static org.junit.Assert.*;
import static org.parboiled.support.ParseTreeUtils.printNodeTree;
import org.junit.Test;
import org.parboiled.BaseParser;
import org.parboiled.Parboiled;
import org.parboiled.Rule;
import org.parboiled.annotations.BuildParseTree;
import org.parboiled.buffers.IndentDedentInputBuffer;
import org.parboiled.errors.ErrorUtils;
import org.parboiled.matchers.CharMatcher;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
public class MinimalTest {
MyDSLParser parser = Parboiled.createParser(MyDSLParser.class);
void parse(Rule rule, String input) {
ParsingResult<?> result = new ReportingParseRunner(rule)
.run(new IndentDedentInputBuffer(input.toCharArray(), 2, ";",
true, true));
if (!result.parseErrors.isEmpty()) {
System.out.println(ErrorUtils.printParseError(result.parseErrors
.get(0)));
} else {
System.out.println("NodeTree: " + printNodeTree(result) + '\n');
}
assertTrue(result.parseErrors.isEmpty());
}
// this fails
@Test
public void testQuotedString() {
parse(parser.quotedString(), "\";\"");
}
}
@BuildParseTree
class MyDSLParser extends BaseParser<Object> {
Rule quotedString() {
return Sequence(
quote(),
stringValue(),
quote());
}
public Rule stringValue() {
return Sequence(
ZeroOrMore(
FirstOf(
semicolon(),
escapedQuote(),
Sequence(TestNot(quote()), ANY))),
push(match()));
}
public Rule semicolon() {
return new CharMatcher(';');
}
public Rule escapedQuote() {
return Sequence(escape(), quote());
}
public Rule quote() {
return new CharMatcher('"');
}
public Rule escape() {
return String("\\");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment