use alloc::boxed::Box;
use alloc::string::ToString;
use alloc::sync::Arc;
use alloc::vec::Vec;
use crate::node::{BuildId, NodeKind};
use crate::source::SourceSpan;
use crate::state::{FeaturePresence, Lang, LangFeatures, ParsingStateDelta};
use super::{
ImplementationErrorKind,
ChildStateSpec, ConstructParser, ConstructParserResult, FromInvocation, ParseContext,
StopCause, StopSpec, StrayGroupClose,
};
#[derive(Debug, Default, Clone, Copy)]
pub struct RootNodesParser;
impl RootNodesParser {
pub fn new() -> RootNodesParser {
RootNodesParser
}
}
impl<L: Lang> ConstructParser<L> for RootNodesParser
where
L::InvocationSyntax: FromInvocation<L>,
{
type Output = BuildId;
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, L>,
) -> ConstructParserResult<L, (BuildId, Option<Box<ParsingStateDelta<L>>>)> {
let entry_state = Arc::clone(&cx.state);
let source = Arc::clone(cx.here().source());
let mut nodes = Vec::new();
loop {
let (outcome, _delta) = cx.parse_nodes(
Arc::clone(&cx.state),
StopSpec::none(),
ChildStateSpec::inherit(),
)?;
nodes.extend(outcome.nodes);
cx.state = outcome.state;
match outcome.stop {
StopCause::EndOfInput => break,
StopCause::UnexpectedGroupClose { span, after } => {
if !<L::Features as LangFeatures>::Groups::PRESENT {
return Err(cx.implementation_error_with_kind(
ImplementationErrorKind::UnexpectedToken,
"Invalid ‘GroupClose’ token returned by the token \
reader: the language declares the groups feature \
absent",
span,
));
}
let delim = span.content().to_string();
cx.recover(StrayGroupClose { delim }, span.clone())?;
cx.tokens.move_to_position(&after);
let id = cx
.stage_node(
NodeKind::chars(span.span()),
span.clone(),
Arc::clone(&cx.state),
Vec::new(),
)
.map_err(|error| cx.staging_error(error, span))?;
nodes.push(id);
}
StopCause::TokenCondition { span, .. } => {
return Err(cx.implementation_error_with_kind(
ImplementationErrorKind::InvalidStopCause,
"Invalid stop cause ‘TokenCondition’ returned by the \
nodes parser from ‘ParseDriver::make_nodes_parser’: \
the stop specification of the root sets no token condition",
span,
));
}
StopCause::NodeCondition => {
return Err(cx.implementation_error_with_kind(
ImplementationErrorKind::InvalidStopCause,
"Invalid stop cause ‘NodeCondition’ returned by the \
nodes parser from ‘ParseDriver::make_nodes_parser’: \
the stop specification of the root sets no node condition",
cx.here(),
));
}
}
}
let root = cx
.stage_node(NodeKind::list(), SourceSpan::entire(&source), entry_state, nodes)
.map_err(|error| {
let at = SourceSpan::at(&SourceSpan::entire(&source).start_pos());
cx.staging_error(error, at)
})?;
Ok((root, None))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::engine::{ParserSession, StdParseDriver};
use crate::error::Recovery;
use crate::node::check_tree_invariants;
use crate::source::Source;
use crate::state::{ParsingState, TrivialLang};
use crate::token::Tokenization;
#[derive(Debug, Clone, Copy)]
struct PlainLang;
impl TrivialLang for PlainLang {}
#[test]
fn driven_by_hand_it_stages_the_root_list_over_the_whole_source() {
let driver = StdParseDriver::new(Recovery::Strict, ());
let state = Arc::new(ParsingState::<PlainLang>::lang_initial().expect("seed state"));
let source = Arc::new(Source::new("hello"));
let mut reader = <crate::token::StdTokenization as Tokenization<PlainLang>>::make_token_reader(&source);
let mut session = ParserSession::new();
let mut cx = ParseContext::new(&mut *reader, Arc::clone(&state), &mut session, &driver);
let (root, delta) = RootNodesParser::new().parse(&mut cx).unwrap();
assert!(delta.is_none(), "the root has no caller to apply a delta");
let result = session.finish(root).unwrap();
check_tree_invariants(&result.tree);
assert_eq!(result.tree.root().span().range(), 0..5);
assert!(Arc::ptr_eq(result.tree.root().parsing_state(), &state));
assert_eq!(result.tree.root().child(0).unwrap().chars(), Some("hello"));
}
}