基于Predictive Parsing的ABNF语法分析器(三)——ABNF语法解析器的基本框架

本文介绍了基于Predictive Parsing的ABNF语法分析器的构建,重点阐述了AbnfParser类的设计,使用PeekableInputStream处理输入流,并详细说明了在解析过程中可能遇到的MatchException异常。内容包括PeekableInputStream的来源与增强,以及分析器的基本框架搭建。
摘要由CSDN通过智能技术生成

前面说过,一个能够识别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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值