~ubuntu-branches/ubuntu/wily/parboiled/wily-proposed

« back to all changes in this revision

Viewing changes to parboiled-core/src/main/java/org/parboiled/matchervisitors/GetStarterCharVisitor.java

  • Committer: Package Import Robot
  • Author(s): Emmanuel Bourg
  • Date: 2014-11-10 21:10:42 UTC
  • Revision ID: package-import@ubuntu.com-20141110211042-wcmfz25icr5ituj5
Tags: upstream-1.1.6
ImportĀ upstreamĀ versionĀ 1.1.6

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * Copyright (C) 2009-2011 Mathias Doenitz
 
3
 *
 
4
 * Licensed under the Apache License, Version 2.0 (the "License");
 
5
 * you may not use this file except in compliance with the License.
 
6
 * You may obtain a copy of the License at
 
7
 *
 
8
 * http://www.apache.org/licenses/LICENSE-2.0
 
9
 *
 
10
 * Unless required by applicable law or agreed to in writing, software
 
11
 * distributed under the License is distributed on an "AS IS" BASIS,
 
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
13
 * See the License for the specific language governing permissions and
 
14
 * limitations under the License.
 
15
 */
 
16
 
 
17
package org.parboiled.matchervisitors;
 
18
 
 
19
import org.parboiled.matchers.*;
 
20
import org.parboiled.support.Characters;
 
21
 
 
22
import java.util.Random;
 
23
 
 
24
/**
 
25
 * Returns the first character a given matcher can start a match with.
 
26
 * For all complex matchers, i.e. the ones not always matching just one character, the visitor returns null.
 
27
 */
 
28
public class GetStarterCharVisitor extends DefaultMatcherVisitor<Character> {
 
29
 
 
30
    @Override
 
31
    public Character visit(AnyMatcher matcher) {
 
32
        return 'X';
 
33
    }
 
34
 
 
35
    @Override
 
36
    public Character visit(AnyOfMatcher matcher) {
 
37
        Characters characters = matcher.characters;
 
38
        if (!characters.isSubtractive()) {
 
39
            return characters.getChars()[0];
 
40
        }
 
41
 
 
42
        // for substractive sets we try to randomly choose a fitting character
 
43
        Random random = new Random();
 
44
        char c;
 
45
        do {
 
46
            c = (char) random.nextInt(Character.MAX_VALUE);
 
47
        } while (!Character.isDefined(c) || !characters.contains(c));
 
48
        return c;
 
49
    }
 
50
 
 
51
    @Override
 
52
    public Character visit(CharIgnoreCaseMatcher matcher) {
 
53
        return matcher.charLow;
 
54
    }
 
55
 
 
56
    @Override
 
57
    public Character visit(CharMatcher matcher) {
 
58
        return matcher.character;
 
59
    }
 
60
 
 
61
    @Override
 
62
    public Character visit(CharRangeMatcher matcher) {
 
63
        return matcher.cLow;
 
64
    }
 
65
 
 
66
    @Override
 
67
    public Character visit(CustomMatcher matcher) {
 
68
        return matcher.getStarterChar();
 
69
    }
 
70
}