01 /*
02 * Java Genetic Algorithm Library (jenetics-7.1.2).
03 * Copyright (c) 2007-2023 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19 */
20 package io.jenetics.ext.internal.parser;
21
22 import static java.lang.String.format;
23
24 import io.jenetics.ext.internal.parser.Token.Type;
25
26 /**
27 * Parser implementation for parsing explicit {@link Token} sequences.
28 *
29 * @param <V> the token value type
30 *
31 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
32 * @since 7.1
33 * @version 7.1
34 */
35 public class TokenParser<V> extends Parser<Token<V>> {
36
37 /**
38 * Create a new parser object with the given {@code tokenizer} and lookahead
39 * count {@code k}.
40 *
41 * @param tokenizer the token source {@code this} parser uses
42 * @param k the lookahead count
43 */
44 public TokenParser(final Tokenizer<Token<V>> tokenizer, final int k) {
45 super(tokenizer, k);
46 }
47
48 /**
49 * Return the token type code for the given lookahead index.
50 *
51 * @param index lookahead index
52 * @return the token type code for the given lookahead index
53 */
54 public int LA(final int index) {
55 final var token = LT(index);
56 return token != null ? token.type().code() : Type.EOF.code();
57 }
58
59 /**
60 * Try to <em>match</em> and consume the next token of the given
61 * {@code type}. If the current token is not from the given type, a
62 * {@link ParsingException} is thrown.
63 *
64 * @param type the token type to match
65 * @return the matched token
66 * @throws NullPointerException if the given token {@code type} is
67 * {@code null}
68 * @throws ParsingException if the current token doesn't match the desired
69 * token {@code type}
70 */
71 public Token<V> match(final Type type) {
72 if (LA(1) == type.code()) {
73 final var token = LT(1);
74 consume();
75 return token;
76 } else {
77 throw new ParsingException(format(
78 "Expecting %s but found %s.",
79 type, LT(1)
80 ));
81 }
82 }
83
84 }
|