use crate::{
error::{ErrorKind, ScanError},
input::{str::StrInput, BorrowedInput, BufferedInput},
parser::{Event, ParseResult, Parser, ParserTrait, SpannedEventReceiver},
scanner::Span,
Options,
};
use alloc::{borrow::Cow, boxed::Box, string::String, vec::Vec};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct SourceId(pub u64);
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Sourced<T> {
pub source_id: Option<SourceId>,
pub value: T,
}
pub struct ReplayParser<'input> {
events: alloc::vec::IntoIter<(Event<'input>, Span)>,
anchor_offset: usize,
}
impl<'input> ReplayParser<'input> {
#[must_use]
pub fn new(events: Vec<(Event<'input>, Span)>, anchor_offset: usize) -> Self {
Self {
events: events.into_iter(),
anchor_offset,
}
}
#[must_use]
pub fn anchor_offset(&self) -> usize {
self.anchor_offset
}
pub fn set_anchor_offset(&mut self, offset: usize) {
self.anchor_offset = offset;
}
fn advance_anchor_offset(&mut self, event: &Event<'input>) {
if let Some(anchor_id) = event.anchor_id() {
self.anchor_offset = self.anchor_offset.max(anchor_id.saturating_add(1));
}
}
}
impl<'input> ParserTrait<'input> for ReplayParser<'input> {
fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
self.events.as_slice().first().map(Ok)
}
fn next_event(&mut self) -> Option<ParseResult<'input>> {
let event = self.events.next()?;
self.advance_anchor_offset(&event.0);
Some(Ok(event))
}
fn load<R: SpannedEventReceiver<'input>>(
&mut self,
recv: &mut R,
multi: bool,
) -> Result<(), ScanError> {
while let Some(res) = self.next_event() {
let (ev, span) = res?;
let is_doc_end = matches!(ev, Event::DocumentEnd { .. });
let is_stream_end = matches!(ev, Event::StreamEnd);
recv.on_event(ev, span);
if is_stream_end {
break;
}
if !multi && is_doc_end {
break;
}
}
Ok(())
}
}
impl<'input> Iterator for ReplayParser<'input> {
type Item = ParseResult<'input>;
fn next(&mut self) -> Option<Self::Item> {
self.next_event()
}
}
impl core::iter::FusedIterator for ReplayParser<'_> {}
enum AnyParser<'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
String {
parser: Parser<'input, StrInput<'input>>,
name: String,
source_id: Option<SourceId>,
},
Iter {
parser: Parser<'static, BufferedInput<I>>,
name: String,
source_id: Option<SourceId>,
},
Custom {
parser: Parser<'input, T>,
primed: Option<(Event<'input>, Span)>,
anchor_floor: usize,
name: String,
source_id: Option<SourceId>,
},
Replay {
parser: ReplayParser<'input>,
name: String,
source_id: Option<SourceId>,
},
}
impl<'input, I, T> AnyParser<'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
fn name(&self) -> &str {
match self {
Self::String { name, .. }
| Self::Iter { name, .. }
| Self::Custom { name, .. }
| Self::Replay { name, .. } => name,
}
}
fn next_event(&mut self) -> Option<ParseResult<'input>> {
match self {
Self::String { parser, .. } => parser.next_event(),
Self::Iter { parser, .. } => parser.next_event(),
Self::Custom {
parser,
primed,
anchor_floor,
..
} => {
let result = primed.take().map(Ok).or_else(|| parser.next_event());
if *anchor_floor == 0 {
return result;
}
let Some(Ok((event, span))) = &result else {
return result;
};
match event.anchor_id().or_else(|| event.alias_id()) {
Some(anchor_id) if anchor_id < *anchor_floor => {
let kind = ErrorKind::AnchorIdCollision {
anchor_id,
first_free_id: *anchor_floor,
};
Some(Err(ScanError::from_kind(span.start, kind)))
}
_ => result,
}
}
Self::Replay { parser, .. } => parser.next_event(),
}
}
fn source_id(&self) -> Option<SourceId> {
match self {
Self::String { source_id, .. }
| Self::Iter { source_id, .. }
| Self::Custom { source_id, .. }
| Self::Replay { source_id, .. } => *source_id,
}
}
fn set_source_id(&mut self, id: SourceId) {
match self {
Self::String { source_id, .. }
| Self::Iter { source_id, .. }
| Self::Custom { source_id, .. }
| Self::Replay { source_id, .. } => *source_id = Some(id),
}
}
fn anchor_offset(&self) -> usize {
match self {
AnyParser::String { parser, .. } => parser.anchor_offset(),
AnyParser::Iter { parser, .. } => parser.anchor_offset(),
AnyParser::Custom { parser, .. } => parser.anchor_offset(),
AnyParser::Replay { parser, .. } => parser.anchor_offset(),
}
}
fn set_anchor_offset(&mut self, offset: usize) {
match self {
AnyParser::String { parser, .. } => parser.set_anchor_offset(offset),
AnyParser::Iter { parser, .. } => parser.set_anchor_offset(offset),
AnyParser::Custom { parser, .. } => parser.set_anchor_offset(offset),
AnyParser::Replay { parser, .. } => parser.set_anchor_offset(offset),
}
}
}
pub struct SourceNames<'stack, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
parsers: core::slice::Iter<'stack, AnyParser<'input, I, T>>,
}
impl<'stack, 'input, I, T> Iterator for SourceNames<'stack, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
type Item = &'stack str;
fn next(&mut self) -> Option<Self::Item> {
self.parsers.next().map(AnyParser::name)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.parsers.size_hint()
}
}
impl<'input, I, T> DoubleEndedIterator for SourceNames<'_, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.parsers.next_back().map(AnyParser::name)
}
}
impl<'input, I, T> ExactSizeIterator for SourceNames<'_, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
}
impl<'input, I, T> core::iter::FusedIterator for SourceNames<'_, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
}
pub struct SourceIds<'stack, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
parsers: core::slice::Iter<'stack, AnyParser<'input, I, T>>,
}
impl<'input, I, T> Iterator for SourceIds<'_, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
type Item = Option<SourceId>;
fn next(&mut self) -> Option<Self::Item> {
self.parsers.next().map(AnyParser::source_id)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.parsers.size_hint()
}
}
impl<'input, I, T> DoubleEndedIterator for SourceIds<'_, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.parsers.next_back().map(AnyParser::source_id)
}
}
impl<'input, I, T> ExactSizeIterator for SourceIds<'_, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
}
impl<'input, I, T> core::iter::FusedIterator for SourceIds<'_, 'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
}
pub struct ParserStack<'input, I = core::iter::Empty<char>, T = StrInput<'input>>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
options: Options,
parsers: Vec<AnyParser<'input, I, T>>,
#[cfg(feature = "comments")]
pending_document_ends: Vec<(usize, Span)>,
peeked: Option<ParseResult<'input>>,
emitted_source_id: Option<SourceId>,
stream_end_emitted: bool,
#[allow(clippy::type_complexity)]
include_resolver: Option<Box<dyn FnMut(&str) -> Result<Cow<'input, str>, ScanError> + 'input>>,
}
impl<'input, I, T> ParserStack<'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
#[must_use]
pub fn new() -> Self {
Self::with_options(Options::default())
}
#[must_use]
pub fn with_options(options: Options) -> Self {
Self {
options,
parsers: Vec::new(),
#[cfg(feature = "comments")]
pending_document_ends: Vec::new(),
peeked: None,
emitted_source_id: None,
stream_end_emitted: false,
include_resolver: None,
}
}
pub fn set_resolver(
&mut self,
mut resolver: impl FnMut(&str) -> Result<String, ScanError> + 'input,
) {
self.include_resolver = Some(Box::new(move |name| resolver(name).map(Cow::Owned)));
}
pub fn set_borrowed_resolver(
&mut self,
mut resolver: impl FnMut(&str) -> Result<&'input str, ScanError> + 'input,
) {
self.include_resolver = Some(Box::new(move |name| resolver(name).map(Cow::Borrowed)));
}
pub fn push_include(&mut self, include_str: &str) -> Result<(), ScanError> {
let resolved = match &mut self.include_resolver {
Some(resolver) => resolver(include_str),
None => {
return Err(self.contextualize_include_error(
ScanError::from_kind(
crate::scanner::Marker::new(0, 1, 0),
ErrorKind::MissingIncludeResolver,
),
include_str,
));
}
};
let content = match resolved {
Ok(content) => content,
Err(error) => return Err(self.contextualize_include_error(error, include_str)),
};
let inherited_anchor_offset = self.parsers.last().map(AnyParser::anchor_offset);
let (events, next_anchor_offset) = match content {
Cow::Borrowed(content) => {
let mut parser = Parser::new_from_str_with_options(content, self.options.clone());
if let Some(anchor_offset) = inherited_anchor_offset {
parser.set_anchor_offset(anchor_offset);
}
let mut events = Vec::new();
while let Some(event) = parser.next_event() {
match event {
Ok(event) => events.push(event),
Err(error) => {
return Err(self.contextualize_include_error(error, include_str));
}
}
}
(events, parser.anchor_offset())
}
Cow::Owned(content) => {
let mut parser =
Parser::new_from_iter_with_options(content.chars(), self.options.clone());
if let Some(anchor_offset) = inherited_anchor_offset {
parser.set_anchor_offset(anchor_offset);
}
let mut events = Vec::new();
while let Some(event) = parser.next_event() {
match event {
Ok(event) => events.push(event),
Err(error) => {
return Err(self.contextualize_include_error(error, include_str));
}
}
}
(events, parser.anchor_offset())
}
};
self.push_replay_parser(
ReplayParser::new(events, next_anchor_offset),
include_str.into(),
);
Ok(())
}
pub fn push_include_with_source_id(
&mut self,
include_str: &str,
source_id: SourceId,
) -> Result<(), Sourced<ScanError>> {
self.push_include(include_str).map_err(|value| Sourced {
source_id: Some(source_id),
value,
})?;
self.set_pushed_source_id(source_id);
Ok(())
}
fn set_pushed_source_id(&mut self, source_id: SourceId) {
if let Some(parser) = self.parsers.last_mut() {
parser.set_source_id(source_id);
}
}
fn contextualize_include_error(&self, error: ScanError, include_str: &str) -> ScanError {
let mut source_stack = self.stack();
source_stack.push(include_str.into());
error.with_source_stack(source_stack)
}
fn prepare_for_push(&mut self) {
if matches!(self.peeked, Some(Ok((Event::StreamEnd, _)))) {
self.peeked = None;
}
}
pub fn push_str_parser(&mut self, mut parser: Parser<'input, StrInput<'input>>, name: String) {
self.prepare_for_push();
if let Some(parent) = self.parsers.last() {
parser.set_anchor_offset(parent.anchor_offset());
}
self.parsers.push(AnyParser::String {
parser,
name,
source_id: None,
});
}
pub fn push_iter_parser(
&mut self,
mut parser: Parser<'static, BufferedInput<I>>,
name: String,
) {
self.prepare_for_push();
if let Some(parent) = self.parsers.last() {
parser.set_anchor_offset(parent.anchor_offset());
}
self.parsers.push(AnyParser::Iter {
parser,
name,
source_id: None,
});
}
pub fn push_custom_parser(&mut self, mut parser: Parser<'input, T>, name: String) {
self.prepare_for_push();
if let Some(parent) = self.parsers.last() {
parser.set_anchor_offset(parent.anchor_offset());
}
self.parsers.push(AnyParser::Custom {
parser,
primed: None,
anchor_floor: 0,
name,
source_id: None,
});
}
pub fn push_replay_parser(&mut self, mut parser: ReplayParser<'input>, name: String) {
self.prepare_for_push();
if let Some(parent) = self.parsers.last() {
let inherited = parent.anchor_offset();
parser.set_anchor_offset(parser.anchor_offset().max(inherited));
}
self.parsers.push(AnyParser::Replay {
parser,
name,
source_id: None,
});
}
pub fn push_custom_parser_with_current(
&mut self,
mut parser: Parser<'input, T>,
name: String,
current: (Event<'input>, Span),
) {
self.prepare_for_push();
let anchor_floor = self.current_anchor_offset();
parser.set_anchor_offset(parser.anchor_offset().max(anchor_floor));
self.parsers.push(AnyParser::Custom {
parser,
primed: Some(current),
anchor_floor,
name,
source_id: None,
});
}
pub fn push_str_parser_with_source_id(
&mut self,
parser: Parser<'input, StrInput<'input>>,
name: String,
source_id: SourceId,
) {
self.push_str_parser(parser, name);
self.set_pushed_source_id(source_id);
}
pub fn push_iter_parser_with_source_id(
&mut self,
parser: Parser<'static, BufferedInput<I>>,
name: String,
source_id: SourceId,
) {
self.push_iter_parser(parser, name);
self.set_pushed_source_id(source_id);
}
pub fn push_custom_parser_with_source_id(
&mut self,
parser: Parser<'input, T>,
name: String,
source_id: SourceId,
) {
self.push_custom_parser(parser, name);
self.set_pushed_source_id(source_id);
}
pub fn push_replay_parser_with_source_id(
&mut self,
parser: ReplayParser<'input>,
name: String,
source_id: SourceId,
) {
self.push_replay_parser(parser, name);
self.set_pushed_source_id(source_id);
}
pub fn push_custom_parser_with_current_and_source_id(
&mut self,
parser: Parser<'input, T>,
name: String,
current: (Event<'input>, Span),
source_id: SourceId,
) {
self.push_custom_parser_with_current(parser, name, current);
self.set_pushed_source_id(source_id);
}
#[must_use]
pub fn current_anchor_offset(&self) -> usize {
self.parsers.last().map_or(0, AnyParser::anchor_offset)
}
#[must_use]
pub fn depth(&self) -> usize {
self.parsers.len()
}
#[must_use]
pub fn source_names(&self) -> SourceNames<'_, 'input, I, T> {
SourceNames {
parsers: self.parsers.iter(),
}
}
#[must_use]
pub fn source_ids(&self) -> SourceIds<'_, 'input, I, T> {
SourceIds {
parsers: self.parsers.iter(),
}
}
#[must_use]
pub fn current_source_id(&self) -> Option<SourceId> {
self.parsers.last().and_then(AnyParser::source_id)
}
#[must_use]
pub fn stack(&self) -> Vec<String> {
self.source_names().map(String::from).collect()
}
pub fn next_sourced(&mut self) -> Option<Sourced<ParseResult<'input>>> {
let value = self.next_event()?;
Some(Sourced {
source_id: self.emitted_source_id,
value,
})
}
fn contextualize_error(&self, error: ScanError) -> ScanError {
if self.parsers.len() > 1 {
error.with_source_stack(self.stack())
} else {
error
}
}
fn propagate_anchor_offset_from_popped(&mut self, popped: &AnyParser<'input, I, T>) {
if let Some(parent) = self.parsers.last_mut() {
let next_offset = parent.anchor_offset().max(popped.anchor_offset());
parent.set_anchor_offset(next_offset);
}
}
#[track_caller]
fn pop_parser_and_propagate_anchor_offset(&mut self) {
#[cfg(feature = "comments")]
if self
.pending_document_ends
.last()
.is_some_and(|(depth, _)| *depth == self.parsers.len())
{
self.pending_document_ends.pop();
}
let popped = self.parsers.pop().unwrap();
self.propagate_anchor_offset_from_popped(&popped);
}
#[allow(clippy::too_many_lines)]
fn next_event_impl(&mut self) -> Result<(Event<'input>, Span), ScanError> {
loop {
let Some(any_parser) = self.parsers.last_mut() else {
self.emitted_source_id = None;
return Ok((
Event::StreamEnd,
Span::empty(crate::scanner::Marker::new(0, 1, 0)),
));
};
self.emitted_source_id = any_parser.source_id();
let res = any_parser.next_event();
#[cfg(feature = "comments")]
if let Some(&(depth, span)) = self.pending_document_ends.last() {
if depth == self.parsers.len()
&& matches!(&res, Some(Ok((event, _)))
if !matches!(event, Event::Comment { .. } | Event::StreamEnd))
{
let error = self.contextualize_error(ScanError::from_kind(
span.start,
ErrorKind::MultipleDocumentsUnsupported,
));
self.pop_parser_and_propagate_anchor_offset();
return Err(error);
}
}
match res {
Some(Ok((event @ Event::StreamEnd, span))) => {
if self.parsers.len() == 1 {
self.parsers.pop();
return Ok((event, span));
}
self.pop_parser_and_propagate_anchor_offset();
}
None => {
if self.parsers.len() == 1 {
self.parsers.pop();
return Ok((
Event::StreamEnd,
Span::empty(crate::scanner::Marker::new(0, 1, 0)),
));
}
self.pop_parser_and_propagate_anchor_offset();
}
Some(Err(e)) => {
let e = self.contextualize_error(e);
self.pop_parser_and_propagate_anchor_offset();
return e.into_result();
}
Some(Ok((event @ Event::DocumentEnd { .. }, span))) => {
if self.parsers.len() == 1 {
return Ok((event, span));
}
#[cfg(feature = "comments")]
{
self.pending_document_ends.push((self.parsers.len(), span));
}
#[cfg(not(feature = "comments"))]
{
let next = self.parsers.last_mut().unwrap().next_event();
match next {
Some(Ok((Event::StreamEnd, _))) | None => {
self.pop_parser_and_propagate_anchor_offset();
}
Some(Err(error)) => {
let error = self.contextualize_error(error);
self.pop_parser_and_propagate_anchor_offset();
return Err(error);
}
Some(Ok(_)) => {
let error = self.contextualize_error(ScanError::from_kind(
span.start,
ErrorKind::MultipleDocumentsUnsupported,
));
self.pop_parser_and_propagate_anchor_offset();
return Err(error);
}
}
}
}
Some(Ok(event)) => {
#[cfg(feature = "comments")]
if !self.options.emit_comments && matches!(event.0, Event::Comment { .. }) {
continue;
}
if self.parsers.len() > 1
&& matches!(event.0, Event::StreamStart | Event::DocumentStart { .. })
{
continue;
}
return Ok(event);
}
}
}
}
}
impl<'input, I, T> Default for ParserStack<'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
fn default() -> Self {
Self::new()
}
}
impl<'input, I, T> ParserTrait<'input> for ParserStack<'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
fn peek(&mut self) -> Option<Result<&(Event<'input>, Span), ScanError>> {
if self.stream_end_emitted {
return None;
}
if self.peeked.is_none() {
self.peeked = Some(self.next_event_impl());
}
Some(self.peeked.as_ref()?.as_ref().map_err(Clone::clone))
}
fn next_event(&mut self) -> Option<ParseResult<'input>> {
if self.stream_end_emitted {
return None;
}
let result = self.peeked.take().unwrap_or_else(|| self.next_event_impl());
self.stream_end_emitted = matches!(result, Err(_) | Ok((Event::StreamEnd, _)));
Some(result)
}
fn load<R: SpannedEventReceiver<'input>>(
&mut self,
recv: &mut R,
multi: bool,
) -> Result<(), ScanError> {
while let Some(res) = self.next_event() {
let (ev, span) = res?;
let is_doc_end = matches!(ev, Event::DocumentEnd { .. });
let is_stream_end = matches!(ev, Event::StreamEnd);
recv.on_event(ev, span);
if is_stream_end {
break;
}
if !multi && is_doc_end {
break;
}
}
Ok(())
}
}
impl<'input, I, T> Iterator for ParserStack<'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
type Item = Result<(Event<'input>, Span), ScanError>;
fn next(&mut self) -> Option<Self::Item> {
self.next_event()
}
}
impl<'input, I, T> core::iter::FusedIterator for ParserStack<'input, I, T>
where
I: Iterator<Item = char>,
T: BorrowedInput<'input>,
{
}