001/* 002 * Java Genetic Algorithm Library (jenetics-7.2.0). 003 * Copyright (c) 2007-2023 Franz Wilhelmstötter 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 * 017 * Author: 018 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) 019 */ 020package io.jenetics.ext.internal.parser; 021 022import static java.lang.String.format; 023 024import io.jenetics.ext.internal.parser.Token.Type; 025 026/** 027 * Parser implementation for parsing explicit {@link Token} sequences. 028 * 029 * @param <V> the token value type 030 * 031 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> 032 * @since 7.1 033 * @version 7.1 034 */ 035public class TokenParser<V> extends Parser<Token<V>> { 036 037 /** 038 * Create a new parser object with the given {@code tokenizer} and lookahead 039 * count {@code k}. 040 * 041 * @param tokenizer the token source {@code this} parser uses 042 * @param k the lookahead count 043 */ 044 public TokenParser(final Tokenizer<Token<V>> tokenizer, final int k) { 045 super(tokenizer, k); 046 } 047 048 /** 049 * Return the token type code for the given lookahead index. 050 * 051 * @param index lookahead index 052 * @return the token type code for the given lookahead index 053 */ 054 public int LA(final int index) { 055 final var token = LT(index); 056 return token != null ? token.type().code() : Type.EOF.code(); 057 } 058 059 /** 060 * Try to <em>match</em> and consume the next token of the given 061 * {@code type}. If the current token is not from the given type, a 062 * {@link ParsingException} is thrown. 063 * 064 * @param type the token type to match 065 * @return the matched token 066 * @throws NullPointerException if the given token {@code type} is 067 * {@code null} 068 * @throws ParsingException if the current token doesn't match the desired 069 * token {@code type} 070 */ 071 public Token<V> match(final Type type) { 072 if (LA(1) == type.code()) { 073 final var token = LT(1); 074 consume(); 075 return token; 076 } else { 077 throw new ParsingException(format( 078 "Expecting %s but found %s.", 079 type, LT(1) 080 )); 081 } 082 } 083 084}