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.matchervisitors.MatcherVisitor;
021import org.parboiled.support.Chars;
022import org.parboiled.support.Chars;
023
024import static org.parboiled.common.Preconditions.checkArgNotNull;
025import static org.parboiled.common.StringUtils.escape;
026
027/**
028 * A {@link Matcher} matching a single given character.
029 */
030public class CharMatcher extends AbstractMatcher {
031    public final char character;
032
033    public CharMatcher(char character) {
034        super(getLabel(character));
035        this.character = character;
036    }
037
038    private static String getLabel(char c) {
039        switch (c) {
040            case Chars.DEL_ERROR:
041            case Chars.INS_ERROR:
042            case Chars.RESYNC:
043            case Chars.RESYNC_START:
044            case Chars.RESYNC_END:
045            case Chars.RESYNC_EOI:
046            case Chars.INDENT:
047            case Chars.DEDENT:
048            case Chars.EOI:
049                return escape(c);
050            default:
051                return '\'' + escape(c) + '\'';
052        }
053    }
054
055    public boolean match(MatcherContext context) {
056        if (context.getCurrentChar() != character) return false;
057        context.advanceIndex(1);
058        context.createNode();
059        return true;
060    }
061
062    public <R> R accept(MatcherVisitor<R> visitor) {
063        checkArgNotNull(visitor, "visitor");
064        return visitor.visit(this);
065    }
066
067}