RepeatTimesParser(Parser<? extends T> parser, int min, int max) { this(parser, min, max, ListFactory.<T>arrayListFactory()); }
@Override boolean apply(ParseContext ctxt) { List<T> result = listFactory.newList(); if (!ctxt.repeat(parser, min, result)) return false; if (repeatAtMost(max - min, result, ctxt)) { ctxt.result = result; return true; } return false; }
/** * A {@link Parser} that runs {@code this} for 1 ore more times separated and optionally terminated by {@code * delim}. For example: {@code "foo;foo;foo"} and {@code "foo;foo;"} both matches {@code foo.sepEndBy1(semicolon)}. * * <p>The return values are collected in a {@link List}. */ public final Parser<List<T>> sepEndBy1(final Parser<?> delim) { return next(first -> new DelimitedParser<T>(this, delim, ListFactory.arrayListFactoryWithFirstElement(first))); }
@Override boolean apply(ParseContext ctxt) { List<T> result = listFactory.newList(); if (!ctxt.repeat(parser, min, result)) return false; if (applyMany(ctxt, result)) { ctxt.result = result; return true; } return false; }
/** * A {@link Parser} that runs {@code this} 1 or more times separated by {@code delim}. * * <p>The return values are collected in a {@link List}. */ public final Parser<List<T>> sepBy1(Parser<?> delim) { final Parser<T> afterFirst = delim.asDelimiter().next(this); return next((Function<T, Parser<List<T>>>) firstValue -> new RepeatAtLeastParser<T>( afterFirst, 0, ListFactory.arrayListFactoryWithFirstElement(firstValue))); }
@Override final boolean apply(final ParseContext ctxt) { final List<T> result = listFactory.newList(); for (;;) { final int step0 = ctxt.step; final int at0 = ctxt.at; boolean r = ctxt.applyAsDelimiter(delim); if (!r) { ctxt.result = result; ctxt.setAt(step0, at0); return true; } final int step1 = ctxt.step; final int at1 = ctxt.at; r = parser.apply(ctxt); if (!r) { ctxt.result = result; ctxt.setAt(step1, at1); return true; } if (at0 == ctxt.at) { // infinite loop ctxt.result = result; return true; } result.add(parser.getReturn(ctxt)); } }
RepeatAtLeastParser(Parser<? extends T> parser, int min) { this(parser, min, ListFactory.<T>arrayListFactory()); }