I can successfully parse a comma-delimited list with dart-petitparser, but the same code fails when confronted with a space-delimited list:
class MyDefinition extends GrammarDefinition {
@override
Parser start() => throw UnsupportedError('Not yet.');
Parser commas() =>
ref0(number).separatedBy(char(','), includeSeparators: false);
Parser spaces() =>
ref0(number).separatedBy(char(' '), includeSeparators: false);
Parser<int> number() => digit().plus().flatten().trim().map(int.parse);
}
test('commas', () {
var defn = MyDefinition();
var parser = defn.build(start: defn.commas);
expect(parser.parse("7,4,9,5").value, [7, 4, 9, 5]); // PASS
});
test('spaces', () {
var defn = MyDefinition();
var parser = defn.build(start: defn.spaces);
expect(parser.parse("7 4 9 5").value, [7, 4, 9, 5]); // FAIL
});
It fails with the following:
Expected: [7, 4, 9, 5]
Actual: [7]
Which: at location [1] is [7] which shorter than expected
What am I doing wrong? I've dug through a bunch of the example grammars, and didn't find a whitespace-delimited list anywhere.
The .trim()
parser in your number parser is consuming whitespaces before and after the number. This prevents the space-delimited list parser from finding a separating whitespace.
I suggest to rewrite as:
Parser spaces() =>
ref0(number).separatedBy(char(' ').plus(), includeSeparators: false);
// add this ^^^^^^^
Parser<int> number() =>
digit().plus().flatten().map(int.parse);
// remove trim, here ^