swc_xml_parser/parser/
input.rs

1use std::{fmt::Debug, mem::take};
2
3use swc_common::{BytePos, Span};
4use swc_xml_ast::{Token, TokenAndSpan};
5
6use super::PResult;
7use crate::error::Error;
8
9pub trait ParserInput: Iterator<Item = TokenAndSpan> {
10    fn start_pos(&mut self) -> BytePos;
11
12    fn last_pos(&mut self) -> BytePos;
13
14    fn take_errors(&mut self) -> Vec<Error>;
15}
16
17#[derive(Debug)]
18pub(super) struct Buffer<I>
19where
20    I: ParserInput,
21{
22    cur: Option<TokenAndSpan>,
23    input: I,
24}
25
26impl<I> Buffer<I>
27where
28    I: ParserInput,
29{
30    pub fn new(input: I) -> Self {
31        Buffer { cur: None, input }
32    }
33
34    /// Last start position
35    pub fn start_pos(&mut self) -> PResult<BytePos> {
36        Ok(self.input.start_pos())
37    }
38
39    /// Last end position
40    pub fn last_pos(&mut self) -> PResult<BytePos> {
41        Ok(self.input.last_pos())
42    }
43
44    pub fn cur_span(&mut self) -> PResult<Span> {
45        if self.cur.is_none() {
46            self.bump_inner()?;
47        }
48
49        Ok(self.cur.as_ref().map(|cur| cur.span).unwrap_or_default())
50    }
51
52    pub fn cur(&mut self) -> PResult<Option<&Token>> {
53        if self.cur.is_none() {
54            self.bump_inner()?;
55        }
56
57        Ok(self.cur.as_ref().map(|v| &v.token))
58    }
59
60    #[track_caller]
61    pub fn bump(&mut self) -> PResult<Option<TokenAndSpan>> {
62        debug_assert!(
63            self.cur.is_some(),
64            "bump() is called without checking current token"
65        );
66
67        let token = self.cur.take();
68
69        Ok(token)
70    }
71
72    fn bump_inner(&mut self) -> PResult<()> {
73        self.cur = None;
74
75        if self.cur.is_none() {
76            let result = self.input.next();
77
78            if let Some(result) = result {
79                self.cur = Some(result);
80            } else {
81                return Ok(());
82            }
83        }
84
85        Ok(())
86    }
87
88    pub fn take_errors(&mut self) -> Vec<Error> {
89        take(&mut self.input.take_errors())
90    }
91}