001/*
002 * Copyright (C) 2009-2011 Mathias Doenitz
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.parboiled.matchers;
018
019import org.parboiled.MatcherContext;
020import org.parboiled.Rule;
021import org.parboiled.errors.GrammarException;
022import org.parboiled.matchervisitors.MatcherVisitor;
023
024import static org.parboiled.common.Preconditions.checkArgNotNull;
025
026/**
027 * A {@link Matcher} that repeatedly tries its submatcher against the input. Always succeeds.
028 */
029public class ZeroOrMoreMatcher extends CustomDefaultLabelMatcher<ZeroOrMoreMatcher> {
030    public final Matcher subMatcher;
031
032    public ZeroOrMoreMatcher(Rule subRule) {
033        super(checkArgNotNull(subRule, "subRule"), "ZeroOrMore");
034        this.subMatcher = getChildren().get(0);
035    }
036
037    public boolean match(MatcherContext context) {
038        checkArgNotNull(context, "context");
039        int lastIndex = context.getCurrentIndex();
040        while (subMatcher.getSubContext(context).runMatcher()) {
041            int currentLocation = context.getCurrentIndex();
042            if (currentLocation == lastIndex) {
043                throw new GrammarException("The inner rule of ZeroOrMore rule '%s' must not allow empty matches",
044                        context.getPath());
045            }
046            lastIndex = currentLocation;
047        }
048
049        context.createNode();
050        return true;
051    }
052
053    public <R> R accept(MatcherVisitor<R> visitor) {
054        checkArgNotNull(visitor, "visitor");
055        return visitor.visit(this);
056    }
057
058}