前面说过,一个能够识别ABNF文法并且自动构造ABNF文法解析器的生成器(parser generator),它首先要能够识别ABNF文法,即把ABNF读入内存并结构化之后,才能进行后续的生成解析器的步骤。我把这个读入ABNF文法的模块称为AbnfParser类。下面先来看看这个类的基本结构:
/*
This file is one of the component a Context-free Grammar Parser Generator,
which accept a piece of text as the input, and generates a parser
for the inputted context-free grammar.
Copyright (C) 2013, Junbiao Pan (Email: panjunbiao@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
// ABNF文法解析器
public class AbnfParser {
// ABNF文法解析器的输入流,这是一个支持peek和read操作的输入流,
// 支持peek是因为这是一个预测解析器,即需要向前看1~2个字符,
// 以决定下一步所需要匹配的ABNF文法产生式(或元素)。
protected PeekableInputStream is;
public PeekableInputStream getInputStream() { return is; }
protected String prefix;
// match函数用来判断两个字符是否相同
// (例如判断输入的字符是否与期望的字符相同)
public boolean match(int value, int expected) {
return value == expected;
}
// match函数用来判断字符是否在某个范围之内
// (例如判断输入的字符是否是字母、或数字字符等)
public boolean match(int value, int lower, int upper) {
return value >= lower && value <= upper;
}
// match函数用来判断字符是否与某个字符相同
// (忽略大小写)
public boolean match(int value, char expected) {
return Character.toUpperCase(value) == Character.toUpperCase(expected);
}
// match函数用来判断字符是否与某些字符相同
// (例如判断输入的字符是否为'-','+',或'%')
public boolean match(int value, int[] expected) {
for(int index = 0; index < expected.length; index ++) {
if (value == expected[index]) return true;
}
return false;
}
// 如果不匹配则抛出MatchException异常
// MatchExceptio