Parsing 在Rust-Peek中编写解析器-前面有两个字符

Parsing 在Rust-Peek中编写解析器-前面有两个字符,parsing,iterator,rust,peek,Parsing,Iterator,Rust,Peek,我正在研究Rust中的解析器。目标是解析为AST,然后使用serde将AST序列化为JSON 我将要解析的DSL与JavaScript半相似,但要简单得多 pub struct Parser<'a> { source: Peekable<str::Chars<'a>>, } impl<'a> Parser<'a> { pub fn new(source: &str) -> Parser {

我正在研究Rust中的解析器。目标是解析为AST,然后使用serde将AST序列化为JSON

我将要解析的DSL与JavaScript半相似,但要简单得多

pub struct Parser<'a> {
    source: Peekable<str::Chars<'a>>,
}

impl<'a> Parser<'a> {
    pub fn new(source: &str) -> Parser {
        Parser {
            source: source.chars().peekable(),
        }
    }

    pub fn parse(&mut self) -> Resource {
        let mut entities = Map::new();

        self.skip_ws();

        loop {
            let entity = self.get_entity();
            entities.insert(entity.id, entity);
            self.skip_ws();
        }
        Resource(entities)
    }

    fn get_entity(&mut self) {
        let id = self.get_identifier();
        self.skip_line_ws();

        if !self.next_char('=') {
            panic!();
        }

        self.bump();

        self.skip_line_ws();

        let value = self.get_pattern();

        if self.next_char('[') && self.next_char('[', 1) {
           // get attributes
           // return entity with attributes
        } else {
           // return entity without attributes
        }
    }
}
pub结构分析器>,
}
恳求{
pub fn new(源代码:&str)->解析器{
分析器{
source:source.chars().peek(),
}
}
发布fn解析(&mut self)->资源{
让mut entities=Map::new();
self.skip_ws();
环路{
让entity=self.get_entity();
实体。插入(entity.id,entity);
self.skip_ws();
}
资源(实体)
}
fn获取实体(&mut self){
让id=self.get_identifier();
self.skip_line_ws();
if!self.next_char('=')){
恐慌!();
}
self.bump();
self.skip_line_ws();
让value=self.get_pattern();
if self.next_char('[')和&self.next_char('[',1){
//获取属性
//返回具有属性的实体
}否则{
//返回不带属性的实体
}
}
}
在两种情况下,仅查看一个字符不足以识别我正在收集的令牌。例如,如果查看的字符是“[”,然后是“[”,则它不是实体的一部分,但如果它是“[”,然后不是“[”,则它是一个属性

我知道理论上我可以使用
next()
收集一个字符,然后使用
peek()
查看下一个字符,但当您确定结果不是实体的一部分时,这会带来一个问题,因为在这种情况下,我希望将指针移回一个字符,然后返回

这也不能解决我需要向前看3个字符的场景中的问题

在我看来,我要么需要向前看两个字符的能力,要么需要向前推进迭代器然后向后移动迭代器的能力。 我在Itertools中发现了
multipeek
,该工具声称可以查看前面的多个字符,但我不知道如何将其放入解析器中。
有人可以指导我或指出一种不同的方法吗?

但我不知道如何将它放入我的解析器中-就像使用
Peekable
一样,只是使用
Multipeek
来代替。您提供的代码示例不是a(这里强调C和M)具体来说,它缺少一些关键部分,如
next\u char
skip\u ws
get\u identifier
get\u pattern
skip\u line\u ws
Resource
Map
,等等。您是否承诺为数据保留chars迭代器?在这种情况下,您可以访问o整个字符串,并可以使用它进行前瞻(我会在不使用可查看项的情况下这样做)。例如:
chars\u iter.as\u str()以(“[[”)
)开头。只有当您想对数据使用泛型迭代器时,才需要找到另一个解决方案。