use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
use core::mem;
use crate::error::{DiagnosticInfo, ParseError, ToDiagnosticValue};
use crate::node::{BuildId, NodeKind, StagedNodeView};
use crate::source::{SourceSpan, TextContent};
use crate::engine::{CommandResolution, ParseDriver};
use crate::state::{FeaturePresence, Lang, LangFeatures, ParsingState, ParsingStateDelta};
use crate::token::{StreamPosition, Token, TokenEdge, TokenKind, TokenReader};
use super::child_state::{ChildStateSpec, GroupChildState, InvocationChildState};
use super::{
ImplementationErrorKind,
comment_node_kind, push_pre_space_text, push_token_text, ConstructParser,
ConstructParserResult, FromInvocation, Invocation, invocation_frame, ParseContext,
};
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.specs.unresolvable-command")]
pub struct UnresolvableCommand {
pub name: String,
pub escape_char: char,
pub detail: Option<String>,
}
impl fmt::Display for UnresolvableCommand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Unknown command ‘{}{}’", self.escape_char, self.name)?;
if let Some(detail) = &self.detail {
write!(f, ": {detail}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.specs.command-resolution-failed")]
pub struct CommandResolutionFailed {
pub name: String,
pub escape_char: char,
pub detail: Option<String>,
}
impl fmt::Display for CommandResolutionFailed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Failed to resolve command ‘{}{}’",
self.escape_char, self.name
)?;
if let Some(detail) = &self.detail {
write!(f, ": {detail}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
id = "core.arguments.expression-callable-requires-content",
message = "‘{callable}’ may not be used alone as an argument: it requires \
arguments or a body"
)]
pub struct ExpressionCallableRequiresContent {
pub callable: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.recovery.unusable-recovery-token")]
pub struct UnusableRecoveryToken {
pub spelling: String,
pub kind: UnusableRecoveryTokenKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToDiagnosticValue)]
#[non_exhaustive]
pub enum UnusableRecoveryTokenKind {
Command,
Specials,
GroupOpen,
}
impl fmt::Display for UnusableRecoveryToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
UnusableRecoveryTokenKind::Command => write!(
f,
"Misconfigured token reader: the recovery placeholder ‘{}’ of a \
tokenization error may not be a command",
self.spelling
),
UnusableRecoveryTokenKind::Specials => write!(
f,
"Misconfigured token reader: the recovery placeholder ‘{}’ of a \
tokenization error may not be a specials token",
self.spelling
),
UnusableRecoveryTokenKind::GroupOpen => write!(
f,
"Misconfigured token reader: the recovery placeholder ‘{}’ of a \
tokenization error may not be an opening delimiter",
self.spelling
),
}
}
}
pub enum TokenStopKind<'p, L: Lang> {
Command {
name: &'p str,
},
GroupClose {
group_type: L::GroupTypeId,
close: &'p str,
},
ParagraphBreak,
#[allow(clippy::type_complexity)]
Predicate(
&'p dyn Fn(
&Token<L>,
&dyn TokenReader<'_, L>,
) -> Result<bool, ParseError<L::SourceOrigin>>,
),
}
pub struct TokenStopCondition<'p, L: Lang> {
pub kind: TokenStopKind<'p, L>,
pub consume: bool,
}
pub struct StopSpec<'p, L: Lang> {
pub token: Option<TokenStopCondition<'p, L>>,
#[allow(clippy::type_complexity)]
pub node: Option<
&'p mut dyn FnMut(
usize,
StagedNodeView<'_, L>,
) -> Result<bool, ParseError<L::SourceOrigin>>,
>,
}
impl<'p, L: Lang> StopSpec<'p, L> {
pub fn none() -> StopSpec<'p, L> {
StopSpec { token: None, node: None }
}
pub fn at_token(kind: TokenStopKind<'p, L>, consume: bool) -> StopSpec<'p, L> {
StopSpec { token: Some(TokenStopCondition { kind, consume }), node: None }
}
}
impl<L: Lang> Default for StopSpec<'_, L> {
fn default() -> Self {
StopSpec::none()
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
id = "core.groups.stray-group-close",
message = "Unmatched closing delimiter ‘{delim}’: no group is open"
)]
pub struct StrayGroupClose {
pub delim: String,
}
pub enum StopCause<L: Lang> {
TokenCondition {
span: SourceSpan<L::SourceOrigin>,
after: StreamPosition<L>,
},
NodeCondition,
EndOfInput,
UnexpectedGroupClose {
span: SourceSpan<L::SourceOrigin>,
after: StreamPosition<L>,
},
}
impl<L: Lang> fmt::Debug for StopCause<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StopCause::TokenCondition { span, after } => f
.debug_struct("TokenCondition")
.field("span", span)
.field("after", after)
.finish(),
StopCause::NodeCondition => f.write_str("NodeCondition"),
StopCause::EndOfInput => f.write_str("EndOfInput"),
StopCause::UnexpectedGroupClose { span, after } => f
.debug_struct("UnexpectedGroupClose")
.field("span", span)
.field("after", after)
.finish(),
}
}
}
impl<L: Lang> Clone for StopCause<L> {
fn clone(&self) -> Self {
match self {
StopCause::TokenCondition { span, after } => StopCause::TokenCondition {
span: span.clone(),
after: after.clone(),
},
StopCause::NodeCondition => StopCause::NodeCondition,
StopCause::EndOfInput => StopCause::EndOfInput,
StopCause::UnexpectedGroupClose { span, after } => {
StopCause::UnexpectedGroupClose {
span: span.clone(),
after: after.clone(),
}
}
}
}
}
impl<L: Lang> PartialEq for StopCause<L> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
StopCause::TokenCondition { span, after },
StopCause::TokenCondition { span: other_span, after: other_after },
) => span == other_span && after == other_after,
(StopCause::NodeCondition, StopCause::NodeCondition) => true,
(StopCause::EndOfInput, StopCause::EndOfInput) => true,
(
StopCause::UnexpectedGroupClose { span, after },
StopCause::UnexpectedGroupClose { span: other_span, after: other_after },
) => span == other_span && after == other_after,
_ => false,
}
}
}
impl<L: Lang> Eq for StopCause<L> {}
pub struct NodesOutcome<L: Lang> {
pub nodes: Vec<BuildId>,
pub stop: StopCause<L>,
pub state: Arc<ParsingState<L>>,
pub after_effects: Option<Box<ParsingStateDelta<L>>>,
}
impl<L: Lang> fmt::Debug for NodesOutcome<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NodesOutcome")
.field("nodes", &self.nodes)
.field("stop", &self.stop)
.field("state", &self.state)
.field("after_effects", &self.after_effects)
.finish()
}
}
impl<L: Lang> Clone for NodesOutcome<L> {
fn clone(&self) -> Self {
NodesOutcome {
nodes: self.nodes.clone(),
stop: self.stop.clone(),
state: Arc::clone(&self.state),
after_effects: self.after_effects.clone(),
}
}
}
pub struct NodesParser<'p, L: Lang> {
stop: StopSpec<'p, L>,
child_states: ChildStateSpec<'p, L>,
nodes: Vec<BuildId>,
run: Option<PendingRun<L>>,
after_effects: Option<Box<ParsingStateDelta<L>>>,
}
struct PendingRun<L: Lang> {
start: StreamPosition<L>,
end: StreamPosition<L>,
text: Option<String>,
}
impl<L: Lang> fmt::Debug for PendingRun<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PendingRun")
.field("start", &self.start)
.field("end", &self.end)
.field("text", &self.text)
.finish()
}
}
fn chars_run_node<L: Lang>(
cx: &ParseContext<'_, '_, L>,
run: PendingRun<L>,
) -> ConstructParserResult<L, (NodeKind<L>, SourceSpan<L::SourceOrigin>)> {
let span = cx.source_span_within(&run.start, &run.end)?;
let content = match run.text {
Some(text) => TextContent::Owned(text.into()),
None => TextContent::Spanned(span.span()),
};
Ok((NodeKind::chars(content), span))
}
impl<'p, L: Lang> NodesParser<'p, L> {
pub fn new(stop: StopSpec<'p, L>) -> NodesParser<'p, L> {
NodesParser {
stop,
child_states: ChildStateSpec::inherit(),
nodes: Vec::new(),
run: None,
after_effects: None,
}
}
pub fn with_child_states(mut self, child_states: ChildStateSpec<'p, L>) -> Self {
self.child_states = child_states;
self
}
fn take_pre_space(
&mut self,
cx: &ParseContext<'_, '_, L>,
token: &Token<L>,
) -> Result<(), String> {
let start = cx.tokens.position_at(token, TokenEdge::StartBeforePreSpace);
let end = cx.tokens.position_at(token, TokenEdge::Start);
if start == end {
return Ok(());
}
let mut text = (!L::OBEYS_SPAN_TILING).then(String::new);
push_pre_space_text(&mut text, cx, token);
self.extend_run_to(start, end, text)
}
fn extend_run(
&mut self,
cx: &ParseContext<'_, '_, L>,
token: &Token<L>,
c: char,
) -> Result<(), String> {
let start = cx.tokens.position_at(token, TokenEdge::StartBeforePreSpace);
let end = cx.tokens.position_at(token, TokenEdge::EndPastPostSpace);
let mut text = (!L::OBEYS_SPAN_TILING).then(String::new);
push_token_text(&mut text, cx, token, c.encode_utf8(&mut [0u8; 4]));
self.extend_run_to(start, end, text)
}
fn extend_run_to(
&mut self,
start: StreamPosition<L>,
end: StreamPosition<L>,
text: Option<String>,
) -> Result<(), String> {
match &mut self.run {
Some(run) => {
if run.end != start {
return Err(alloc::format!(
"Inconsistent token reader: the token peeked at {:?} begins at \
{:?}; a peeked token, including its pre-space, must begin at \
the position of the peek",
run.end,
start
));
}
run.end = end;
if let (Some(accumulated), Some(text)) = (&mut run.text, text) {
accumulated.push_str(&text);
}
}
None => self.run = Some(PendingRun { start, end, text }),
}
Ok(())
}
fn flush(&mut self, cx: &mut ParseContext<'_, '_, L>) -> ConstructParserResult<L, bool> {
match self.run.take() {
Some(run) => {
let (kind, span) = chars_run_node(cx, run)?;
self.stage_node(cx, kind, span)
}
None => Ok(false),
}
}
fn flush_through(
&mut self,
cx: &mut ParseContext<'_, '_, L>,
token: &Token<L>,
) -> ConstructParserResult<L, bool> {
self.take_pre_space(cx, token).map_err(|detail| {
let span = cx.tokens.source_span_between(
token,
TokenEdge::StartBeforePreSpace,
TokenEdge::Start,
);
cx.implementation_error_with_kind(
ImplementationErrorKind::TokenPositionMismatch,
detail,
span,
)
})?;
self.flush(cx)
}
fn flush_for_token_stop(
&mut self,
cx: &mut ParseContext<'_, '_, L>,
token: &Token<L>,
) -> ConstructParserResult<L, ()> {
self.take_pre_space(cx, token).map_err(|detail| {
let span = cx.tokens.source_span_between(
token,
TokenEdge::StartBeforePreSpace,
TokenEdge::Start,
);
cx.implementation_error_with_kind(
ImplementationErrorKind::TokenPositionMismatch,
detail,
span,
)
})?;
if let Some(run) = self.run.take() {
let (kind, span) = chars_run_node(cx, run)?;
self.stage(cx, kind, span)?;
}
Ok(())
}
fn stage(
&mut self,
cx: &mut ParseContext<'_, '_, L>,
kind: NodeKind<L>,
span: SourceSpan<L::SourceOrigin>,
) -> ConstructParserResult<L, BuildId> {
let id = cx
.stage_node(kind, span.clone(), Arc::clone(&cx.state), vec![])
.map_err(|error| cx.staging_error(error, span))?;
self.nodes.push(id);
Ok(id)
}
fn stage_node(
&mut self,
cx: &mut ParseContext<'_, '_, L>,
kind: NodeKind<L>,
span: SourceSpan<L::SourceOrigin>,
) -> ConstructParserResult<L, bool> {
let id = self.stage(cx, kind, span)?;
self.test_node_stop(cx, id)
}
fn test_node_stop(
&mut self,
cx: &mut ParseContext<'_, '_, L>,
id: BuildId,
) -> ConstructParserResult<L, bool> {
let Some(condition) = &mut self.stop.node else {
return Ok(false);
};
let staged = cx.staged_nodes();
let Some(view) = staged.get(id) else {
return Ok(false);
};
condition(self.nodes.len(), view).map_err(|error| cx.attach_hook_frames(error))
}
fn token_stop(
&self,
state: &ParsingState<L>,
token: &Token<L>,
token_kind: TokenKind<'_, L>,
tokens: &dyn TokenReader<'_, L>,
) -> Result<Option<bool>, ParseError<L::SourceOrigin>> {
let Some(cond) = self.stop.token.as_ref() else {
return Ok(None);
};
let matches = match &cond.kind {
TokenStopKind::Command { name } => {
matches!(token_kind, TokenKind::Command { name: n, .. } if n == *name)
}
TokenStopKind::GroupClose { group_type, close } => match token_kind {
TokenKind::GroupClose { delim } => {
delim == *close && group_close_type(state, delim) == Some(*group_type)
}
_ => false,
},
TokenStopKind::ParagraphBreak => {
matches!(token_kind, TokenKind::ParagraphBreak)
}
TokenStopKind::Predicate(predicate) => predicate(token, tokens)?,
};
Ok(matches.then_some(cond.consume))
}
fn recover_as_chars<'s>(
&mut self,
cx: &mut ParseContext<'_, 's, L>,
token: &Token<L>,
recovered: bool,
condition: impl DiagnosticInfo,
) -> ConstructParserResult<L, bool> {
if self.flush_through(cx, token)? {
if !recovered {
cx.tokens.move_to(token, TokenEdge::Start);
}
return Ok(true);
}
let span = cx.tokens.source_span_of(token);
cx.recover(condition, span.clone())?;
if !recovered {
cx.tokens.move_to(token, TokenEdge::EndPastPostSpace);
}
self.stage_node(cx, NodeKind::chars(span.span()), span)
}
fn dispatch_invocation<'s>(
&mut self,
cx: &mut ParseContext<'_, 's, L>,
invocation: Invocation<'_, L>,
) -> ConstructParserResult<L, bool>
where
L::InvocationSyntax: FromInvocation<L>,
{
let base = match &self.child_states.invocation {
InvocationChildState::Inherit => Arc::clone(&cx.state),
InvocationChildState::Fixed(state) => Arc::clone(state),
InvocationChildState::Compute(compute) => compute(&cx.state, &invocation)
.map_err(|error| cx.attach_hook_frames(error))?,
};
let frame = invocation_frame(cx, &invocation);
cx.tokens.move_to(invocation.token, TokenEdge::EndPastPostSpace);
let driver = cx.driver;
let result = cx.with_frame(frame, |cx| {
let mut parser = driver
.make_invocation_parser(invocation)
.map_err(|error| cx.attach_hook_frames(error))?;
let result = cx.parse_construct(&mut *parser, Some(base), None);
drop(parser);
result
});
let (id, delta) = result?;
self.nodes.push(id);
if let Some(delta) = delta {
cx.state = cx.derive_state_recording(&delta, &mut self.after_effects)?;
}
self.test_node_stop(cx, id)
}
fn outcome(&mut self, state: &Arc<ParsingState<L>>, stop: StopCause<L>) -> NodesOutcome<L> {
NodesOutcome {
nodes: mem::take(&mut self.nodes),
stop,
state: Arc::clone(state),
after_effects: self.after_effects.take().filter(|delta| !delta.is_empty()),
}
}
}
impl<L: Lang> ConstructParser<L> for NodesParser<'_, L>
where
L::InvocationSyntax: FromInvocation<L>,
{
type Output = NodesOutcome<L>;
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, L>,
) -> ConstructParserResult<L, (NodesOutcome<L>, Option<Box<ParsingStateDelta<L>>>)> {
let mut last_position: Option<StreamPosition<L>> = None;
loop {
let position = cx.tokens.position_here();
if last_position.as_ref() == Some(&position) {
return Err(cx.implementation_error_with_kind(
ImplementationErrorKind::StalledTokenReader,
alloc::format!(
"Inconsistent token reader: the stream position did not advance \
past the token read at {position:?}; every token other than \
‘EndOfStream’ must advance the stream position"
),
cx.here(),
));
}
last_position = Some(position);
let (token, recovered) = match cx.tokens.peek(&cx.state) {
Ok(token) => (token, false),
Err(error) => {
let kind = error.kind().clone();
let span = error.span().clone();
match error.into_recovery() {
None => {
return Err(ParseError::from_token_error(kind, span)
.with_frames(cx.session.snapshot_frames()))
}
Some(recovery) => {
cx.recover_boxed(kind.clone().into_condition(), span.clone())?;
let before = cx.tokens.position_here();
cx.tokens.move_to_position(&recovery.resume);
if cx.tokens.position_here() == before {
return Err(ParseError::from_token_error(kind, span)
.with_frames(cx.session.snapshot_frames()));
}
(recovery.token, true)
}
}
}
};
let kind = cx.tokens.token_kind(&token);
if !recovered {
if let Some(consume) = self
.token_stop(&cx.state, &token, kind, &*cx.tokens)
.map_err(|error| cx.attach_hook_frames(error))?
{
self.flush_for_token_stop(cx, &token)?;
let span = cx.tokens.source_span_of(&token);
let after = cx.tokens.position_at(&token, TokenEdge::EndPastPostSpace);
if consume {
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
} else {
cx.tokens.move_to(&token, TokenEdge::Start);
}
return Ok((
self.outcome(&cx.state, StopCause::TokenCondition { span, after }),
None,
));
}
}
match kind {
TokenKind::Char(c) => {
self.extend_run(cx, &token, c).map_err(|detail| {
let span = cx.tokens.source_span_of(&token);
cx.implementation_error_with_kind(
ImplementationErrorKind::TokenPositionMismatch,
detail,
span,
)
})?;
if !recovered {
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
}
}
TokenKind::EndOfStream => {
let fired = self.flush_through(cx, &token)?;
if !recovered {
cx.tokens.move_to(&token, TokenEdge::Start);
}
let cause =
if fired { StopCause::NodeCondition } else { StopCause::EndOfInput };
return Ok((self.outcome(&cx.state, cause), None));
}
TokenKind::GroupClose { .. } => {
let fired = self.flush_through(cx, &token)?;
if !recovered {
cx.tokens.move_to(&token, TokenEdge::Start);
}
let cause = if fired {
StopCause::NodeCondition
} else {
StopCause::UnexpectedGroupClose {
span: cx.tokens.source_span_of(&token),
after: cx
.tokens
.position_at(&token, TokenEdge::EndPastPostSpace),
}
};
return Ok((self.outcome(&cx.state, cause), None));
}
TokenKind::ParagraphBreak => {
if !<L::Features as LangFeatures>::Paragraphs::PRESENT {
return Err(cx.implementation_error_with_kind(
ImplementationErrorKind::UnexpectedToken,
"Invalid ‘ParagraphBreak’ token returned by the token reader: \
the language declares the paragraphs feature absent",
cx.tokens.source_span_of(&token),
));
}
if self.flush_through(cx, &token)? {
if !recovered {
cx.tokens.move_to(&token, TokenEdge::Start);
}
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
let span = cx.tokens.source_span_of(&token);
let kind = cx.driver.make_paragraph_break_node(&cx.state, &span);
if !recovered {
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
}
if self.stage_node(cx, kind, span)? {
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
}
TokenKind::Comment { .. } => {
if !<L::Features as LangFeatures>::Comments::PRESENT {
return Err(cx.implementation_error_with_kind(
ImplementationErrorKind::UnexpectedToken,
"Invalid ‘Comment’ token returned by the token reader: \
the language declares the comments feature absent",
cx.tokens.source_span_of(&token),
));
}
if self.flush_through(cx, &token)? {
if !recovered {
cx.tokens.move_to(&token, TokenEdge::Start);
}
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
let (kind, span) = comment_node_kind(cx, &token);
if !recovered {
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
}
if self.stage_node(cx, kind, span)? {
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
}
TokenKind::Command { name, escape_char } => {
if !<L::Features as LangFeatures>::Commands::PRESENT {
return Err(cx.implementation_error_with_kind(
ImplementationErrorKind::UnexpectedToken,
"Invalid ‘Command’ token returned by the token reader: \
the language declares the commands feature absent",
cx.tokens.source_span_of(&token),
));
}
if recovered {
let condition = UnusableRecoveryToken::new(
alloc::format!("{escape_char}{name}"),
UnusableRecoveryTokenKind::Command,
);
if self.recover_as_chars(cx, &token, recovered, condition)? {
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
continue;
}
let resolved = cx
.driver
.resolve_command(&cx.state, &token, &*cx.tokens)
.map_err(|error| cx.attach_hook_frames(error))?;
match resolved {
CommandResolution::Resolved(resolved) => {
if self.flush_through(cx, &token)? {
cx.tokens.move_to(&token, TokenEdge::Start);
return Ok((
self.outcome(&cx.state, StopCause::NodeCondition),
None,
));
}
let invocation = Invocation {
callable_type: resolved.callable_type,
name,
spec: &resolved.spec,
token: &token,
};
if self.dispatch_invocation(cx, invocation)? {
return Ok((
self.outcome(&cx.state, StopCause::NodeCondition),
None,
));
}
}
CommandResolution::Unresolved { detail } => {
let condition =
UnresolvableCommand::new(name, escape_char, detail);
if self.recover_as_chars(cx, &token, recovered, condition)? {
return Ok((
self.outcome(&cx.state, StopCause::NodeCondition),
None,
));
}
}
CommandResolution::Failed { detail } => {
let condition =
CommandResolutionFailed::new(name, escape_char, detail);
if self.recover_as_chars(cx, &token, recovered, condition)? {
return Ok((
self.outcome(&cx.state, StopCause::NodeCondition),
None,
));
}
}
}
}
TokenKind::Specials { callable_type, name, spec } => {
if !<L::Features as LangFeatures>::Specials::PRESENT {
return Err(cx.implementation_error_with_kind(
ImplementationErrorKind::UnexpectedToken,
"Invalid ‘Specials’ token returned by the token reader: \
the language declares the specials feature absent",
cx.tokens.source_span_of(&token),
));
}
if recovered {
let condition = UnusableRecoveryToken::new(
name,
UnusableRecoveryTokenKind::Specials,
);
if self.recover_as_chars(cx, &token, recovered, condition)? {
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
continue;
}
if self.flush_through(cx, &token)? {
cx.tokens.move_to(&token, TokenEdge::Start);
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
let invocation =
Invocation { callable_type, name, spec, token: &token };
if self.dispatch_invocation(cx, invocation)? {
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
}
TokenKind::GroupOpen { delim, rule } => {
if !<L::Features as LangFeatures>::Groups::PRESENT {
return Err(cx.implementation_error_with_kind(
ImplementationErrorKind::UnexpectedToken,
"Invalid ‘GroupOpen’ token returned by the token reader: \
the language declares the groups feature absent",
cx.tokens.source_span_of(&token),
));
}
if recovered {
let condition = UnusableRecoveryToken::new(
delim,
UnusableRecoveryTokenKind::GroupOpen,
);
if self.recover_as_chars(cx, &token, recovered, condition)? {
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
continue;
}
if self.flush_through(cx, &token)? {
cx.tokens.move_to(&token, TokenEdge::Start);
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
let base = match &self.child_states.group {
GroupChildState::Inherit => Arc::clone(&cx.state),
GroupChildState::Fixed(state) => Arc::clone(state),
GroupChildState::Compute(compute) => {
compute(&cx.state, &token, &*cx.tokens)
.map_err(|error| cx.attach_hook_frames(error))?
}
};
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
let (id, delta) = cx.parse_group(
base,
&token,
Arc::clone(rule),
ChildStateSpec::inherit(),
None,
)?;
self.nodes.push(id);
if let Some(delta) = delta {
cx.state = cx.derive_state_recording(&delta, &mut self.after_effects)?;
}
if self.test_node_stop(cx, id)? {
return Ok((self.outcome(&cx.state, StopCause::NodeCondition), None));
}
}
}
}
}
}
fn group_close_type<L: Lang>(state: &ParsingState<L>, delim: &str) -> Option<L::GroupTypeId> {
if let Some(rule) = state.rules().expecting_group_close() {
if rule.close == delim {
return Some(rule.group_type);
}
}
state
.prefix_table() .and_then(|table| table.match_at(delim))
.filter(|entry| entry.delim() == delim)
.and_then(|entry| entry.close())
.map(|rule| rule.group_type)
}
impl<L: Lang> fmt::Debug for TokenStopKind<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TokenStopKind::Command { name } => {
f.debug_struct("Command").field("name", name).finish()
}
TokenStopKind::GroupClose { group_type, close } => f
.debug_struct("GroupClose")
.field("group_type", group_type)
.field("close", close)
.finish(),
TokenStopKind::ParagraphBreak => write!(f, "ParagraphBreak"),
TokenStopKind::Predicate(_) => write!(f, "Predicate(..)"),
}
}
}
impl<L: Lang> fmt::Debug for TokenStopCondition<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TokenStopCondition")
.field("kind", &self.kind)
.field("consume", &self.consume)
.finish()
}
}
impl<L: Lang> fmt::Debug for StopSpec<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StopSpec")
.field("token", &self.token)
.field("node", &self.node.as_ref().map(|_| "FnMut(..)"))
.finish()
}
}
impl<L: Lang> fmt::Debug for NodesParser<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NodesParser")
.field("stop", &self.stop)
.field("nodes", &self.nodes.len())
.field("run", &self.run)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::source::Span;
use crate::constructs::tests::{relaxed_driver, RelaxedStdLang, RELAXED_MACRO};
use crate::engine::{
resolve_command_in_scopes, ParseResult, ParserSession, ScopesCommandResolver,
StdParseDriver,
};
use crate::error::Recovery;
use crate::scopes::{
CallableQuery, CallableSyntax, Package, ProviderError, ScopeStack, SpecsProvider,
};
use crate::node::GroupData;
use crate::source::{Source, SourcePos, TextContent};
use crate::spec::{ArgumentSpec, CallableSpec, StdCallableSpec};
use super::super::argument_parsers::{GroupArgumentParser, MarkerArgumentParser};
use super::super::{InvocationChildState, StdInvocationParser};
use crate::state::{
CommentOverrides, NodeExtTypes, TrivialLang, StateData, TokenRulesOverrides,
};
use crate::token::{
CommandRule, CommandRules, CommentRule, CommentRules, ForbiddenCharsRules, GroupRule,
GroupRules, ParagraphRules, SpecialsMatch, SpecialsRules, SpecialsScanError,
StdStreamPosition, StdToken, StdTokenReader, TokenEdge, TokenError,
TokenErrorKind, TokenKind, TokenListReader, TokenReader,
TokenRecovery, TokenResult, TokenRules, Tokenization, TriggerChars, WhitespaceRules,
};
use alloc::boxed::Box;
use alloc::string::ToString;
const GT_BRACE: u32 = 0;
const GT_MATH: u32 = 1;
const CT_MACRO: u32 = 10;
const CT_SPECIALS: u32 = 11;
#[derive(Debug, Clone, Copy)]
struct TestLang;
impl TrivialLang for TestLang {}
fn resolve_macro_in_scopes<L: Lang<CallableTypeId = u32>>(
state: &ParsingState<L>,
token: &Token<L>,
tokens: &dyn TokenReader<'_, L>,
) -> Result<CommandResolution<L>, ParseError<L::SourceOrigin>> {
Ok(resolve_command_in_scopes(state, token, tokens, CT_MACRO))
}
trait TestDriver {
fn with_recovery(recovery: Recovery) -> Self;
}
impl TestDriver for StdParseDriver {
fn with_recovery(recovery: Recovery) -> Self {
StdParseDriver::new(recovery, ())
}
}
#[derive(Debug, Clone, Copy)]
struct CmdLang;
impl Lang for CmdLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = CmdDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct CmdDriver {
recovery: Recovery,
}
impl TestDriver for CmdDriver {
fn with_recovery(recovery: Recovery) -> Self {
CmdDriver { recovery }
}
}
impl ParseDriver<CmdLang> for CmdDriver {
fn recovery(&self) -> Recovery {
self.recovery
}
fn resolve_command(
&self,
state: &ParsingState<CmdLang>,
token: &StdToken<CmdLang>,
tokens: &dyn TokenReader<'_, CmdLang>,
) -> Result<CommandResolution<CmdLang>, ParseError> {
resolve_macro_in_scopes(state, token, tokens)
}
}
#[derive(Debug, Clone, Copy)]
struct TildeLang;
impl Lang for TildeLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = crate::engine::StdParseDriver;
fn scan_specials(
_state: &ParsingState<Self>,
content: &str,
pos: usize,
) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
if content[pos..].starts_with('~') {
Ok(Some(SpecialsMatch {
end: pos + 1,
callable_type: CT_SPECIALS,
spec: Arc::new(StdCallableSpec::default()),
}))
} else {
Ok(None)
}
}
fn specials_trigger_chars(_data: &StateData<Self>) -> TriggerChars {
TriggerChars::Only("~".into())
}
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
fn macro_library<L: Lang<CallableTypeId = u32> + 'static>(names: &[&str]) -> Arc<Package<L>> {
let mut lib = Package::new("test-macros");
let spec: Arc<dyn CallableSpec<L>> = Arc::new(StdCallableSpec::default());
for name in names {
lib.insert(CT_MACRO, *name, Arc::clone(&spec));
}
Arc::new(lib)
}
fn state_with_macros(names: &[&str]) -> Arc<ParsingState<CmdLang>> {
let mut scopes = ScopeStack::new();
scopes.push(macro_library(names));
Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }))
}
fn math_rule<L: Lang<GroupTypeId = u32>>() -> Arc<GroupRule<L>> {
Arc::new(GroupRule { group_type: GT_MATH, open: "$".into(), close: "$".into() })
}
fn rules<L: Lang<GroupTypeId = u32, Features = crate::state::AllLangFeatures>>(
) -> TokenRules<L> {
TokenRules {
whitespace: WhitespaceRules { enabled: true, chars: " \t\n".into() },
paragraphs: ParagraphRules { enabled: true },
groups: GroupRules {
enabled: true,
rules: vec![Arc::new(GroupRule {
group_type: GT_BRACE,
open: "{".into(),
close: "}".into(),
})],
temporary: Vec::new(),
expecting_close: None,
},
commands: CommandRules {
enabled: true,
rules: vec![Arc::new(CommandRule {
escape_char: '\\',
name_chars: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".into(),
})],
},
comments: CommentRules {
enabled: true,
rules: vec![Arc::new(CommentRule { start: "%".into() })],
},
specials: SpecialsRules { enabled: true },
forbidden_chars: ForbiddenCharsRules { chars: "".into() },
}
}
fn state_with<L: Lang<GroupTypeId = u32, StateExt = ()>>(
rules: TokenRules<L>,
) -> Arc<ParsingState<L>> {
Arc::new(ParsingState::new(StateData {
rules,
scopes: ScopeStack::new(),
mode: Default::default(),
ext: (),
}))
}
fn state() -> Arc<ParsingState<TestLang>> {
state_with(rules())
}
struct Parsed<L: Lang> {
result: ParseResult<L>,
stop: StopCause<L>,
pos: usize,
position: StreamPosition<L>,
}
fn stop_shape<L: Lang>(stop: &StopCause<L>) -> String {
match stop {
StopCause::TokenCondition { span, .. } => {
alloc::format!("token {:?}", span.range())
}
StopCause::UnexpectedGroupClose { span, .. } => {
alloc::format!("close {:?}", span.range())
}
StopCause::NodeCondition => String::from("node"),
StopCause::EndOfInput => String::from("end of input"),
}
}
impl<L: Lang> fmt::Debug for Parsed<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Parsed")
.field("shapes", &shapes(&self.result))
.field("stop", &self.stop)
.field("pos", &self.pos)
.field("position", &self.position)
.finish()
}
}
fn try_run<'s, L: Lang<SourceOrigin = Option<String>>>(
source: &'s Arc<Source>,
tokens: &mut dyn TokenReader<'s, L>,
state: &Arc<ParsingState<L>>,
recovery: Recovery,
stop: StopSpec<'_, L>,
) -> Result<Parsed<L>, ParseError>
where
L::Driver: TestDriver,
L::InvocationSyntax: FromInvocation<L>,
{
try_run_with(source, tokens, state, recovery, stop, ChildStateSpec::inherit())
}
fn try_run_with<'s, 'p, L: Lang<SourceOrigin = Option<String>>>(
source: &'s Arc<Source>,
tokens: &mut dyn TokenReader<'s, L>,
state: &Arc<ParsingState<L>>,
recovery: Recovery,
stop: StopSpec<'p, L>,
child_states: ChildStateSpec<'p, L>,
) -> Result<Parsed<L>, ParseError>
where
L::Driver: TestDriver,
L::InvocationSyntax: FromInvocation<L>,
{
let mut session = ParserSession::new();
let driver = L::Driver::with_recovery(recovery);
let mut cx =
ParseContext::new(tokens, Arc::clone(state), &mut session, &driver);
let mut parser = NodesParser::new(stop).with_child_states(child_states);
let (outcome, delta) = parser.parse(&mut cx)?;
assert!(delta.is_none(), "NodesParser returns no pass-through delta");
let position = cx.tokens.position_here();
let pos = cx.here().start();
let root_span = {
let staged = session.builder.staged_nodes();
match (outcome.nodes.first(), outcome.nodes.last()) {
(Some(&first), Some(&last)) => Span::new(
staged.get(first).unwrap().span().start(),
staged.get(last).unwrap().span().end(),
),
_ => Span::empty(0),
}
};
let root = {
let kind = NodeKind::list();
let span = SourceSpan::new(source, root_span);
let ext = L::make_node_ext(
&kind,
&span,
state,
session.builder.staged_children(&outcome.nodes),
)
.expect("mint node ext");
session.builder.add(kind, span, Arc::clone(state), outcome.nodes, ext, ()).unwrap()
};
let result = session.finish(root).unwrap();
crate::node::check_tree_invariants(&result.tree);
Ok(Parsed { result, stop: outcome.stop, pos, position })
}
fn scan<L>(source: &Arc<Source>, state: &Arc<ParsingState<L>>) -> Vec<Token<L>>
where
L: Lang<SourceOrigin = Option<String>>,
L::Tokenization:
Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
{
let mut reader = StdTokenReader::new(source);
let mut tokens = Vec::new();
loop {
let token = TokenReader::next(&mut reader, state).expect("clean scan");
let reader_ref: &dyn TokenReader<'_, L> = &reader;
let done = matches!(reader_ref.token_kind(&token), TokenKind::EndOfStream);
tokens.push(token);
if done {
break;
}
}
tokens
}
fn run_both<'p, L>(
content: &str,
state: &Arc<ParsingState<L>>,
recovery: Recovery,
stop_std: StopSpec<'p, L>,
stop_list: StopSpec<'p, L>,
) -> Parsed<L>
where
L: Lang<SourceOrigin = Option<String>>,
L::Tokenization:
Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
L::Driver: TestDriver,
L::InvocationSyntax: FromInvocation<L>,
{
run_both_with(content, state, recovery, stop_std, stop_list, ChildStateSpec::inherit())
}
fn run_both_with<'p, L>(
content: &str,
state: &Arc<ParsingState<L>>,
recovery: Recovery,
stop_std: StopSpec<'p, L>,
stop_list: StopSpec<'p, L>,
child_states: ChildStateSpec<'p, L>,
) -> Parsed<L>
where
L: Lang<SourceOrigin = Option<String>>,
L::Tokenization:
Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
L::Driver: TestDriver,
L::InvocationSyntax: FromInvocation<L>,
{
let source: Arc<Source> = Arc::new(Source::new(content));
let mut std_reader = StdTokenReader::new(&source);
let a = try_run_with(
&source,
&mut std_reader,
state,
recovery,
stop_std,
child_states.clone(),
)
.expect("std reader");
let mut list_reader = TokenListReader::new(&source, scan(&source, state));
let b =
try_run_with(&source, &mut list_reader, state, recovery, stop_list, child_states)
.expect("list reader");
assert_eq!(shapes(&a.result), shapes(&b.result), "readers disagree on {:?}", content);
assert_eq!(a.stop, b.stop, "stop causes disagree on {:?}", content);
assert_eq!(a.pos, b.pos, "positions disagree on {:?}", content);
assert_eq!(a.result.diagnostics.len(), b.result.diagnostics.len());
a
}
fn shapes<L: Lang>(result: &ParseResult<L>) -> Vec<String> {
result
.tree
.root()
.children()
.iter().map(|node| {
let span = format!("{}..{}", node.span().start(), node.span().end());
match node.kind() {
NodeKind::Chars { .. } => {
format!("chars {} {:?}", span, node.chars().unwrap())
}
NodeKind::Comment(_) => {
let data = node.comment().unwrap();
format!(
"comment {} start={:?} content={:?} post={:?}",
span,
data.start.resolve(node.source()),
data.content.resolve(node.source()),
data.post_space.resolve(node.source())
)
}
NodeKind::Group(_) => format!("group {}", span),
NodeKind::Callable(_) => format!("callable {}", span),
NodeKind::List => format!("list {}", span),
}
})
.collect()
}
fn assert_partition<L: Lang>(result: &ParseResult<L>, interior: core::ops::Range<usize>) {
let mut pos = interior.start;
for child in result.tree.root().children() {
assert_eq!(child.span().start(), pos, "gap before a sibling: {:?}", shapes(result));
pos = child.span().end();
}
assert_eq!(pos, interior.end, "siblings fall short: {:?}", shapes(result));
}
#[test]
fn empty_input_is_an_empty_list() {
let st = state();
let parsed = run_both("", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_eq!(parsed.result.tree.root().child_count(), 0);
assert_eq!(parsed.pos, 0);
assert!(parsed.result.diagnostics.is_empty());
}
#[test]
fn chars_accumulate_into_one_maximal_node() {
let st = state();
let parsed =
run_both("ab cd", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["chars 0..5 \"ab cd\""]);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_eq!(parsed.pos, 5);
assert_partition(&parsed.result, 0..5);
}
#[test]
fn leading_and_trailing_whitespace_joins_the_run() {
let st = state();
let parsed =
run_both(" ab ", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["chars 0..6 \" ab \""]);
assert_eq!(parsed.pos, 6);
assert_partition(&parsed.result, 0..6);
}
#[test]
fn whitespace_only_input_is_a_whitespace_chars_node() {
let st = state();
let parsed = run_both(" ", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["chars 0..2 \" \""]);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_partition(&parsed.result, 0..2);
}
#[test]
fn paragraph_break_gets_its_own_node_runs_do_not_merge_across() {
let st = state();
let parsed =
run_both("a \n \n b", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"a \"", "chars 2..5 \"\\n \\n\"", "chars 5..7 \" b\""]
);
assert_partition(&parsed.result, 0..7);
}
#[test]
fn paragraph_break_node_comes_from_the_driver_hook() {
#[derive(Debug, Clone, Copy)]
struct MarkLang;
impl Lang for MarkLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = MarkDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct MarkDriver {
recovery: Recovery,
}
impl TestDriver for MarkDriver {
fn with_recovery(recovery: Recovery) -> Self {
MarkDriver { recovery }
}
}
impl ParseDriver<MarkLang> for MarkDriver {
fn recovery(&self) -> Recovery {
self.recovery
}
fn make_paragraph_break_node(
&self,
_state: &ParsingState<MarkLang>,
_break_span: &SourceSpan,
) -> NodeKind<MarkLang> {
NodeKind::chars("¶") }
}
let st = state_with(rules::<MarkLang>());
let parsed =
run_both("a\n\nb", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..1 \"a\"", "chars 1..3 \"¶\"", "chars 3..4 \"b\""]
);
let break_node = parsed.result.tree.root().child(1).unwrap();
assert!(matches!(
break_node.kind(),
NodeKind::Chars { content: TextContent::Owned(_), .. }
));
assert_partition(&parsed.result, 0..4);
}
#[test]
fn comment_node_records_start_content_and_post_space() {
let st = state();
let parsed = run_both(
"x % note\n y",
&st,
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
);
assert_eq!(
shapes(&parsed.result),
[
"chars 0..2 \"x \"",
"comment 2..11 start=\"%\" content=\" note\" post=\"\\n \"",
"chars 11..12 \"y\"",
]
);
assert_partition(&parsed.result, 0..12);
}
#[test]
fn comment_bordering_a_paragraph_break_has_empty_post_space() {
let st = state();
let parsed =
run_both("x %n\n\ny", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
[
"chars 0..2 \"x \"",
"comment 2..4 start=\"%\" content=\"n\" post=\"\"",
"chars 4..6 \"\\n\\n\"",
"chars 6..7 \"y\"",
]
);
assert_partition(&parsed.result, 0..7);
}
#[test]
fn comment_at_end_of_input() {
let st = state();
let parsed =
run_both("x %n", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"x \"", "comment 2..4 start=\"%\" content=\"n\" post=\"\""]
);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_partition(&parsed.result, 0..4);
}
#[test]
fn stop_at_command_leaves_the_token_peekable_with_pre_space_housed() {
let st = state();
let content = "ab \\end rest";
let parsed = run_both(
content,
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
);
assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
assert_eq!(stop_shape(&parsed.stop), "token 3..8");
assert_eq!(parsed.pos, 3);
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
TokenReader::<'_, TestLang>::move_to_position(&mut reader, &parsed.position);
let token: StdToken<TestLang> = TokenReader::peek(&mut reader, &st).unwrap();
let reader: &dyn TokenReader<'_, TestLang> = &reader;
assert!(matches!(
reader.token_kind(&token),
TokenKind::Command { name: "end", .. }
));
assert!(reader
.source_span_between(&token, TokenEdge::StartBeforePreSpace, TokenEdge::Start)
.is_empty());
}
#[test]
fn the_stop_causes_after_position_skips_the_unconsumed_token() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("ab}c"));
let mut reader = StdTokenReader::new(&source);
let parsed: Parsed<TestLang> =
try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap();
let StopCause::UnexpectedGroupClose { span, after } = parsed.stop else {
panic!("expected an unexpected group close");
};
assert_eq!(span.range(), 2..3);
assert_eq!(span.content(), "}");
assert_eq!(parsed.pos, 2);
TokenReader::<'_, TestLang>::move_to_position(&mut reader, &after);
let token: StdToken<TestLang> = TokenReader::peek(&mut reader, &st).unwrap();
let reader_ref: &dyn TokenReader<'_, TestLang> = &reader;
assert!(matches!(reader_ref.token_kind(&token), TokenKind::Char('c')));
}
#[test]
fn lone_pre_space_before_a_stop_token_becomes_a_whitespace_node() {
let st = state();
let parsed = run_both(
" \\end",
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
);
assert_eq!(shapes(&parsed.result), ["chars 0..1 \" \""]);
assert_eq!(stop_shape(&parsed.stop), "token 1..5");
assert_eq!(parsed.pos, 1);
}
#[test]
fn stop_at_group_close_produced_by_the_delimiter_table() {
let st = state();
let parsed = run_both(
"ab}c",
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
);
assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
assert_eq!(stop_shape(&parsed.stop), "token 2..3");
assert_eq!(parsed.pos, 2);
}
#[test]
fn stop_at_group_close_produced_by_the_expected_close() {
let mut r = rules::<TestLang>();
r.groups.rules.push(math_rule());
r.groups.expecting_close = Some(math_rule());
let st = state_with(r);
let parsed = run_both(
"a b$c",
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_MATH, close: "$" }, false),
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_MATH, close: "$" }, false),
);
assert_eq!(shapes(&parsed.result), ["chars 0..3 \"a b\""]);
assert_eq!(stop_shape(&parsed.stop), "token 3..4");
assert_eq!(parsed.pos, 3);
}
#[test]
fn group_close_of_a_different_delimiter_is_unexpected() {
let mut r = rules::<TestLang>();
r.groups.rules.push(math_rule());
r.groups.expecting_close = Some(math_rule());
let st = state_with(r);
let parsed = run_both(
"ab}c",
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_MATH, close: "$" }, false),
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_MATH, close: "$" }, false),
);
assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
assert_eq!(stop_shape(&parsed.stop), "close 2..3");
assert_eq!(parsed.pos, 2);
assert!(parsed.result.diagnostics.is_empty());
}
#[test]
fn group_close_of_a_shared_class_but_different_delimiter_is_unexpected() {
let mut r = rules::<TestLang>();
r.groups.rules.push(Arc::new(GroupRule {
group_type: GT_BRACE,
open: "[".into(),
close: "]".into(),
}));
let st = state_with(r);
let parsed = run_both(
"ab]c",
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
);
assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
assert_eq!(stop_shape(&parsed.stop), "close 2..3");
assert_eq!(parsed.pos, 2);
assert!(parsed.result.diagnostics.is_empty());
}
#[test]
fn group_close_reclassified_to_another_class_is_unexpected() {
let mut r = rules::<TestLang>();
r.groups.expecting_close = Some(Arc::new(GroupRule {
group_type: GT_MATH,
open: "{".into(),
close: "}".into(),
}));
let st = state_with(r);
let parsed = run_both(
"ab}c",
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, false),
);
assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
assert_eq!(stop_shape(&parsed.stop), "close 2..3");
assert_eq!(parsed.pos, 2);
assert!(parsed.result.diagnostics.is_empty());
}
#[test]
fn group_close_without_any_stop_condition_is_unexpected() {
let st = state();
let parsed =
run_both("ab}c", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
assert_eq!(stop_shape(&parsed.stop), "close 2..3");
assert_eq!(parsed.pos, 2);
assert!(parsed.result.diagnostics.is_empty());
}
#[test]
fn stop_at_paragraph_break() {
let st = state();
let parsed = run_both(
"ab\n\ncd",
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::ParagraphBreak, false),
StopSpec::at_token(TokenStopKind::ParagraphBreak, false),
);
assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
assert_eq!(stop_shape(&parsed.stop), "token 2..4");
assert_eq!(parsed.pos, 2);
}
#[test]
fn stop_at_a_token_predicate() {
let st = state();
let predicate = |token: &StdToken<TestLang>,
tokens: &dyn TokenReader<'_, TestLang>| {
Ok(matches!(tokens.token_kind(token), TokenKind::Comment { .. }))
};
let parsed = run_both(
"ab %c\nd",
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::Predicate(&predicate), false),
StopSpec::at_token(TokenStopKind::Predicate(&predicate), false),
);
assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
assert_eq!(stop_shape(&parsed.stop), "token 3..6");
assert_eq!(parsed.pos, 3);
}
#[test]
fn a_failing_stop_predicate_aborts_under_any_policy() {
let st = state();
let failing = |_: &StdToken<TestLang>,
_: &dyn TokenReader<'_, TestLang>|
-> Result<bool, ParseError> {
let scratch: Arc<Source> = Arc::new(Source::new(""));
Err(ParseError::new(
crate::error::HookFailed::new("stop table unavailable", None),
SourceSpan::new(&scratch, 0..0),
))
};
let content = "ab";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let mut session: ParserSession<TestLang> = ParserSession::new();
let driver: StdParseDriver = StdParseDriver::new(Recovery::Tolerant, ());
let mut cx = ParseContext::new(
&mut reader,
Arc::clone(&st),
&mut session,
&driver);
let mut parser = NodesParser::new(StopSpec::at_token(
TokenStopKind::Predicate(&failing),
false,
));
let frame = crate::engine::Frame {
title: crate::engine::FrameTitle::Static("test descent"),
span: SourceSpan::new(&source, 0..0),
};
let error = cx.with_frame(frame, |cx| parser.parse(cx)).unwrap_err();
assert_eq!(error.identifier(), "core.hooks.hook-failed");
assert_eq!(
error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
Some("stop table unavailable")
);
assert_eq!(error.frames().len(), 1);
assert_eq!(error.frames()[0].title(), "test descent");
}
#[test]
fn consume_flag_swallows_a_command_stop_token_with_its_post_space() {
let st = state();
let content = "ab \\end rest";
let parsed = run_both(
content,
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::Command { name: "end" }, true),
StopSpec::at_token(TokenStopKind::Command { name: "end" }, true),
);
assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
assert_eq!(stop_shape(&parsed.stop), "token 3..8");
assert_eq!(parsed.pos, 8);
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
TokenReader::<'_, TestLang>::move_to_position(&mut reader, &parsed.position);
let token: StdToken<TestLang> = TokenReader::peek(&mut reader, &st).unwrap();
let reader: &dyn TokenReader<'_, TestLang> = &reader;
assert!(matches!(reader.token_kind(&token), TokenKind::Char('r')));
assert!(reader
.source_span_between(&token, TokenEdge::StartBeforePreSpace, TokenEdge::Start)
.is_empty());
}
#[test]
fn consume_flag_swallows_a_group_close_stop_token() {
let st = state();
let parsed = run_both(
"ab} c",
&st,
Recovery::Strict,
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, true),
StopSpec::at_token(TokenStopKind::GroupClose { group_type: GT_BRACE, close: "}" }, true),
);
assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
assert_eq!(stop_shape(&parsed.stop), "token 2..3");
assert_eq!(parsed.pos, 3);
}
#[test]
fn node_condition_stops_after_a_flushed_chars_node() {
let st = state();
let mut c1 = |count: usize, _: StagedNodeView<'_, TestLang>| Ok(count >= 1);
let mut c2 = |count: usize, _: StagedNodeView<'_, TestLang>| Ok(count >= 1);
let parsed = run_both(
"ab %c\nde",
&st,
Recovery::Strict,
StopSpec { token: None, node: Some(&mut c1) },
StopSpec { token: None, node: Some(&mut c2) },
);
assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
assert_eq!(parsed.stop, StopCause::NodeCondition);
assert_eq!(parsed.pos, 3);
assert_partition(&parsed.result, 0..3);
}
#[test]
fn node_condition_stops_after_a_directly_staged_node() {
let st = state();
let mut c1 = |count: usize, view: StagedNodeView<'_, TestLang>| {
Ok(count >= 1 && matches!(view.kind(), NodeKind::Comment { .. }))
};
let mut c2 = |count: usize, view: StagedNodeView<'_, TestLang>| {
Ok(count >= 1 && matches!(view.kind(), NodeKind::Comment { .. }))
};
let parsed = run_both(
"%c\nab",
&st,
Recovery::Strict,
StopSpec { token: None, node: Some(&mut c1) },
StopSpec { token: None, node: Some(&mut c2) },
);
assert_eq!(
shapes(&parsed.result),
["comment 0..3 start=\"%\" content=\"c\" post=\"\\n\""]
);
assert_eq!(parsed.stop, StopCause::NodeCondition);
assert_eq!(parsed.pos, 3);
}
#[test]
fn node_condition_on_the_trailing_whitespace_node_wins_over_end_of_input() {
let st = state();
let mut c1 = |count: usize, _: StagedNodeView<'_, TestLang>| Ok(count >= 1);
let mut c2 = |count: usize, _: StagedNodeView<'_, TestLang>| Ok(count >= 1);
let parsed = run_both(
"ab",
&st,
Recovery::Strict,
StopSpec { token: None, node: Some(&mut c1) },
StopSpec { token: None, node: Some(&mut c2) },
);
assert_eq!(shapes(&parsed.result), ["chars 0..2 \"ab\""]);
assert_eq!(parsed.stop, StopCause::NodeCondition);
}
#[test]
fn a_failing_node_stop_condition_aborts_under_any_policy() {
let st = state();
let mut failing =
|_: usize, _: StagedNodeView<'_, TestLang>| -> Result<bool, ParseError> {
let scratch: Arc<Source> = Arc::new(Source::new(""));
Err(ParseError::new(
crate::error::HookFailed::new("node table unavailable", None),
SourceSpan::new(&scratch, 0..0),
))
};
let content = "ab";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let mut session: ParserSession<TestLang> = ParserSession::new();
let driver: StdParseDriver = StdParseDriver::new(Recovery::Tolerant, ());
let mut cx = ParseContext::new(
&mut reader,
Arc::clone(&st),
&mut session,
&driver);
let mut parser =
NodesParser::new(StopSpec { token: None, node: Some(&mut failing) });
let frame = crate::engine::Frame {
title: crate::engine::FrameTitle::Static("test descent"),
span: SourceSpan::new(&source, 0..0),
};
let error = cx.with_frame(frame, |cx| parser.parse(cx)).unwrap_err();
assert_eq!(error.identifier(), "core.hooks.hook-failed");
assert_eq!(error.frames().len(), 1);
assert_eq!(error.frames()[0].title(), "test descent");
}
#[test]
fn token_stop_flush_does_not_consult_the_node_condition() {
let st = state();
let mut calls_std = 0usize;
let mut calls_list = 0usize;
let mut c1 = |_: usize, _: StagedNodeView<'_, TestLang>| {
calls_std += 1;
Ok(true)
};
let mut c2 = |_: usize, _: StagedNodeView<'_, TestLang>| {
calls_list += 1;
Ok(true)
};
let parsed = run_both(
"ab \\end rest",
&st,
Recovery::Strict,
StopSpec {
token: Some(TokenStopCondition {
kind: TokenStopKind::Command { name: "end" },
consume: true,
}),
node: Some(&mut c1),
},
StopSpec {
token: Some(TokenStopCondition {
kind: TokenStopKind::Command { name: "end" },
consume: true,
}),
node: Some(&mut c2),
},
);
assert_eq!(shapes(&parsed.result), ["chars 0..3 \"ab \""]);
assert_eq!(stop_shape(&parsed.stop), "token 3..8");
assert_eq!(parsed.pos, 8);
assert_eq!(calls_std, 0, "the token-stop flush consulted the node condition");
assert_eq!(calls_list, 0, "the token-stop flush consulted the node condition");
}
#[test]
fn forbidden_char_tolerant_adopts_the_recovery_token() {
let mut r = rules::<TestLang>();
r.forbidden_chars.chars = "#".into();
let st = state_with(r);
let source: Arc<Source> = Arc::new(Source::new("ab#cd"));
let mut reader = StdTokenReader::new(&source);
let parsed =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
assert_eq!(shapes(&parsed.result), ["chars 0..5 \"ab#cd\""]);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
assert_eq!(
diagnostic.data().downcast_ref::<crate::token::ForbiddenChar>().map(|c| c.ch),
Some('#')
);
assert_eq!(diagnostic.span().range(), 2..3);
assert_partition(&parsed.result, 0..5);
}
#[test]
fn forbidden_char_strict_aborts() {
let mut r = rules::<TestLang>();
r.forbidden_chars.chars = "#".into();
let st = state_with(r);
let source: Arc<Source> = Arc::new(Source::new("ab#cd"));
let mut reader = StdTokenReader::new(&source);
let err =
try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap_err();
assert_eq!(err.identifier(), crate::token::ForbiddenChar::IDENTIFIER);
assert_eq!(
err.data().downcast_ref::<crate::token::ForbiddenChar>().map(|c| c.ch),
Some('#')
);
assert_eq!(err.span().range(), 2..3);
}
#[derive(Debug, Clone, Copy)]
enum PlaceholderKind {
Command,
Specials,
GroupOpen,
}
struct PlaceholderReader<'s> {
inner: StdTokenReader<'s>,
at: usize,
kind: PlaceholderKind,
}
impl<'s> PlaceholderReader<'s> {
fn inner(&self) -> &dyn TokenReader<'s, TestLang> {
&self.inner
}
fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, TestLang> {
&mut self.inner
}
}
impl<'s> TokenReader<'s, TestLang> for PlaceholderReader<'s> {
fn peek(
&mut self,
state: &Arc<ParsingState<TestLang>>,
) -> TokenResult<TestLang, StdToken<TestLang>> {
let here = self.inner().position_here();
if here.offset() != self.at {
return self.inner_mut().peek(state);
}
let span = Span::new(self.at, self.at + 1);
let token = match self.kind {
PlaceholderKind::Command => StdToken::command(
'\\',
Span::new(self.at, self.at + 2),
Span::empty(self.at),
Span::empty(self.at + 2),
),
PlaceholderKind::Specials => {
let spec: Arc<dyn CallableSpec<TestLang>> =
Arc::new(StdCallableSpec::default());
StdToken::specials(CT_SPECIALS, spec, span, Span::empty(self.at))
}
PlaceholderKind::GroupOpen => StdToken::group_open(
Arc::new(GroupRule {
group_type: GT_BRACE,
open: "{".into(),
close: "}".into(),
}),
span,
Span::empty(self.at),
),
};
let resume = self.inner().position_at(&token, TokenEdge::EndPastPostSpace);
Err(TokenError::new(
TokenErrorKind::ForbiddenChar(crate::token::ForbiddenChar::new('#')),
SourceSpan::new(self.inner.source(), span),
Some(TokenRecovery { token, resume }),
))
}
fn move_to(&mut self, tok: &StdToken<TestLang>, edge: TokenEdge) {
self.inner_mut().move_to(tok, edge);
}
fn move_to_position(&mut self, at: &StdStreamPosition) {
self.inner_mut().move_to_position(at);
}
fn token_kind<'t>(&self, tok: &'t StdToken<TestLang>) -> TokenKind<'t, TestLang>
where
's: 't,
{
self.inner().token_kind(tok)
}
fn source_span_between(
&self,
tok: &StdToken<TestLang>,
a: TokenEdge,
b: TokenEdge,
) -> SourceSpan {
self.inner().source_span_between(tok, a, b)
}
fn position_here(&self) -> StdStreamPosition {
self.inner().position_here()
}
fn position_at(&self, tok: &StdToken<TestLang>, edge: TokenEdge) -> StdStreamPosition {
self.inner().position_at(tok, edge)
}
fn source_position_at(&self, at: &StdStreamPosition) -> SourcePos {
self.inner().source_position_at(at)
}
fn source_span_within(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> Option<SourceSpan> {
self.inner().source_span_within(begin, end)
}
fn source_span_describing(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> SourceSpan {
self.inner().source_span_describing(begin, end)
}
}
fn unusable_placeholder<L: Lang>(result: &ParseResult<L>) -> UnusableRecoveryToken {
let diagnostics: Vec<_> = result.diagnostics.iter().collect();
assert_eq!(diagnostics.len(), 2, "{diagnostics:?}");
assert_eq!(diagnostics[0].identifier(), crate::token::ForbiddenChar::IDENTIFIER);
assert_eq!(diagnostics[1].identifier(), UnusableRecoveryToken::IDENTIFIER);
diagnostics[1]
.data()
.downcast_ref::<UnusableRecoveryToken>()
.expect("the unusable-placeholder condition")
.clone()
}
#[test]
fn a_specials_placeholder_is_unusable_and_recovers_as_chars() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("ab~cd"));
let mut reader = PlaceholderReader {
inner: StdTokenReader::new(&source),
at: 2,
kind: PlaceholderKind::Specials,
};
let parsed =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"ab\"", "chars 2..3 \"~\"", "chars 3..5 \"cd\""]
);
assert_eq!(parsed.stop, StopCause::EndOfInput);
let condition = unusable_placeholder(&parsed.result);
assert_eq!(condition.kind, UnusableRecoveryTokenKind::Specials);
assert_eq!(condition.spelling, "~");
assert_partition(&parsed.result, 0..5);
}
#[test]
fn a_group_open_placeholder_is_unusable_and_recovers_as_chars() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("ab{cd"));
let mut reader = PlaceholderReader {
inner: StdTokenReader::new(&source),
at: 2,
kind: PlaceholderKind::GroupOpen,
};
let parsed =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"ab\"", "chars 2..3 \"{\"", "chars 3..5 \"cd\""]
);
assert_eq!(parsed.stop, StopCause::EndOfInput);
let condition = unusable_placeholder(&parsed.result);
assert_eq!(condition.kind, UnusableRecoveryTokenKind::GroupOpen);
assert_eq!(condition.spelling, "{");
assert_partition(&parsed.result, 0..5);
}
#[test]
fn a_command_placeholder_is_unusable_and_recovers_as_chars() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("ab\\cd"));
let mut reader = PlaceholderReader {
inner: StdTokenReader::new(&source),
at: 2,
kind: PlaceholderKind::Command,
};
let parsed =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"ab\"", "chars 2..4 \"\\\\c\"", "chars 4..5 \"d\""]
);
assert_eq!(parsed.stop, StopCause::EndOfInput);
let condition = unusable_placeholder(&parsed.result);
assert_eq!(condition.kind, UnusableRecoveryTokenKind::Command);
assert_eq!(condition.spelling, "\\c");
assert_partition(&parsed.result, 0..5);
}
#[test]
fn a_specials_placeholder_aborts_under_strict_recovery() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("ab~cd"));
let mut reader = PlaceholderReader {
inner: StdTokenReader::new(&source),
at: 2,
kind: PlaceholderKind::Specials,
};
let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
.unwrap_err();
assert_eq!(err.identifier(), crate::token::ForbiddenChar::IDENTIFIER);
assert_eq!(err.span().range(), 2..3);
}
struct StuckRecoveryReader<'s> {
inner: StdTokenReader<'s>,
}
impl<'s> StuckRecoveryReader<'s> {
fn inner(&self) -> &dyn TokenReader<'s, TestLang> {
&self.inner
}
fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, TestLang> {
&mut self.inner
}
}
impl<'s> TokenReader<'s, TestLang> for StuckRecoveryReader<'s> {
fn peek(
&mut self,
_state: &Arc<ParsingState<TestLang>>,
) -> TokenResult<TestLang, StdToken<TestLang>> {
let here = self.inner().position_here();
let pos = here.offset();
let span = Span::new(pos, pos + 1);
Err(TokenError::new(
TokenErrorKind::ForbiddenChar(crate::token::ForbiddenChar::new('#')),
SourceSpan::new(self.inner.source(), span),
Some(TokenRecovery {
token: StdToken::char('#', span, Span::empty(pos)),
resume: here, }),
))
}
fn move_to(&mut self, tok: &StdToken<TestLang>, edge: TokenEdge) {
self.inner_mut().move_to(tok, edge);
}
fn move_to_position(&mut self, at: &StdStreamPosition) {
self.inner_mut().move_to_position(at);
}
fn token_kind<'t>(&self, tok: &'t StdToken<TestLang>) -> TokenKind<'t, TestLang>
where
's: 't,
{
self.inner().token_kind(tok)
}
fn source_span_between(
&self,
tok: &StdToken<TestLang>,
a: TokenEdge,
b: TokenEdge,
) -> SourceSpan {
self.inner().source_span_between(tok, a, b)
}
fn position_here(&self) -> StdStreamPosition {
self.inner().position_here()
}
fn position_at(&self, tok: &StdToken<TestLang>, edge: TokenEdge) -> StdStreamPosition {
self.inner().position_at(tok, edge)
}
fn source_position_at(&self, at: &StdStreamPosition) -> SourcePos {
self.inner().source_position_at(at)
}
fn source_span_within(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> Option<SourceSpan> {
self.inner().source_span_within(begin, end)
}
fn source_span_describing(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> SourceSpan {
self.inner().source_span_describing(begin, end)
}
}
#[test]
fn non_advancing_token_recovery_aborts_instead_of_spinning() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("ab"));
let mut reader = StuckRecoveryReader { inner: StdTokenReader::new(&source) };
let err = try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
.expect_err("a non-advancing resume position must abort the parse");
assert_eq!(err.identifier(), crate::token::ForbiddenChar::IDENTIFIER);
assert_eq!(
err.data().downcast_ref::<crate::token::ForbiddenChar>().map(|c| c.ch),
Some('#')
);
assert_eq!(err.span().range(), 0..1);
}
struct NonAdvancingTokenReader<'s> {
inner: StdTokenReader<'s>,
}
impl<'s> NonAdvancingTokenReader<'s> {
fn inner(&self) -> &dyn TokenReader<'s, TestLang> {
&self.inner
}
fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, TestLang> {
&mut self.inner
}
}
impl<'s> TokenReader<'s, TestLang> for NonAdvancingTokenReader<'s> {
fn peek(
&mut self,
_state: &Arc<ParsingState<TestLang>>,
) -> TokenResult<TestLang, StdToken<TestLang>> {
let pos = self.inner().position_here().offset();
Ok(StdToken::char('x', Span::empty(pos), Span::empty(pos)))
}
fn move_to(&mut self, tok: &StdToken<TestLang>, edge: TokenEdge) {
self.inner_mut().move_to(tok, edge);
}
fn move_to_position(&mut self, at: &StdStreamPosition) {
self.inner_mut().move_to_position(at);
}
fn token_kind<'t>(&self, tok: &'t StdToken<TestLang>) -> TokenKind<'t, TestLang>
where
's: 't,
{
self.inner().token_kind(tok)
}
fn source_span_between(
&self,
tok: &StdToken<TestLang>,
a: TokenEdge,
b: TokenEdge,
) -> SourceSpan {
self.inner().source_span_between(tok, a, b)
}
fn position_here(&self) -> StdStreamPosition {
self.inner().position_here()
}
fn position_at(&self, tok: &StdToken<TestLang>, edge: TokenEdge) -> StdStreamPosition {
self.inner().position_at(tok, edge)
}
fn source_position_at(&self, at: &StdStreamPosition) -> SourcePos {
self.inner().source_position_at(at)
}
fn source_span_within(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> Option<SourceSpan> {
self.inner().source_span_within(begin, end)
}
fn source_span_describing(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> SourceSpan {
self.inner().source_span_describing(begin, end)
}
}
#[test]
fn a_token_that_does_not_advance_the_stream_is_an_implementation_error() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("ab"));
let mut reader = NonAdvancingTokenReader { inner: StdTokenReader::new(&source) };
let error = try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
.expect_err("a token that does not advance the stream must abort the parse");
let condition = error
.data()
.downcast_ref::<crate::constructs::ImplementationError>()
.expect("an ImplementationError condition");
assert_eq!(condition.kind, ImplementationErrorKind::StalledTokenReader);
assert_eq!(error.span().range(), 0..0);
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "taboolang.token.taboo-char",
message = "the character ‘{ch}’ is taboo here",
no_constructor
)]
struct TabooChar {
ch: char,
}
#[derive(Debug, Clone, Copy)]
struct TabooLang;
impl Lang for TabooLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = crate::engine::StdParseDriver;
fn scan_specials(
_state: &ParsingState<Self>,
content: &str,
pos: usize,
) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
if content[pos..].starts_with('!') {
Err(SpecialsScanError {
kind: TokenErrorKind::Custom(Box::new(TabooChar { ch: '!' })),
span: Span::new(pos, pos + 1),
})
} else {
Ok(None)
}
}
fn specials_trigger_chars(_data: &StateData<Self>) -> TriggerChars {
TriggerChars::Only("!".into())
}
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
struct TabooReader<'s> {
inner: StdTokenReader<'s>,
}
impl<'s> TabooReader<'s> {
fn inner(&self) -> &dyn TokenReader<'s, TabooLang> {
&self.inner
}
fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, TabooLang> {
&mut self.inner
}
}
impl<'s> TokenReader<'s, TabooLang> for TabooReader<'s> {
fn peek(
&mut self,
state: &Arc<ParsingState<TabooLang>>,
) -> TokenResult<TabooLang, StdToken<TabooLang>> {
let pos = TokenReader::<TabooLang>::position_here(&self.inner).offset();
if self.inner.content()[pos..].starts_with('!') {
let span = Span::new(pos, pos + 1);
return Err(TokenError::new(
TokenErrorKind::Custom(Box::new(TabooChar { ch: '!' })),
SourceSpan::new(self.inner.source(), span),
Some(TokenRecovery {
token: StdToken::char('!', span, Span::empty(pos)),
resume: StdStreamPosition::at(span.end()),
}),
));
}
TokenReader::peek(&mut self.inner, state)
}
fn move_to(&mut self, tok: &StdToken<TabooLang>, edge: TokenEdge) {
self.inner_mut().move_to(tok, edge);
}
fn move_to_position(&mut self, at: &StdStreamPosition) {
self.inner_mut().move_to_position(at);
}
fn token_kind<'t>(&self, tok: &'t StdToken<TabooLang>) -> TokenKind<'t, TabooLang>
where
's: 't,
{
self.inner().token_kind(tok)
}
fn source_span_between(
&self,
tok: &StdToken<TabooLang>,
a: TokenEdge,
b: TokenEdge,
) -> SourceSpan {
self.inner().source_span_between(tok, a, b)
}
fn position_here(&self) -> StdStreamPosition {
self.inner().position_here()
}
fn position_at(&self, tok: &StdToken<TabooLang>, edge: TokenEdge) -> StdStreamPosition {
self.inner().position_at(tok, edge)
}
fn source_position_at(&self, at: &StdStreamPosition) -> SourcePos {
self.inner().source_position_at(at)
}
fn source_span_within(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> Option<SourceSpan> {
self.inner().source_span_within(begin, end)
}
fn source_span_describing(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> SourceSpan {
self.inner().source_span_describing(begin, end)
}
}
#[test]
fn custom_token_condition_flows_through_the_lift_unwrapped() {
let st = state_with(rules::<TabooLang>());
for recovery in [Recovery::Tolerant, Recovery::Strict] {
let source: Arc<Source> = Arc::new(Source::new("a!b"));
let mut reader = StdTokenReader::new(&source);
let err = try_run(&source, &mut reader, &st, recovery, StopSpec::none())
.expect_err("a specials scan error carries no recovery");
assert_eq!(err.identifier(), TabooChar::IDENTIFIER);
assert!(err.data().downcast_ref::<TabooChar>().is_some());
}
let source: Arc<Source> = Arc::new(Source::new("a!b"));
let mut reader = TabooReader { inner: StdTokenReader::new(&source) };
let parsed =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
assert_eq!(shapes(&parsed.result), ["chars 0..3 \"a!b\""]);
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
assert_eq!(diagnostic.identifier(), TabooChar::IDENTIFIER);
assert_eq!(
diagnostic.data().downcast_ref::<TabooChar>(),
Some(&TabooChar { ch: '!' })
);
let source: Arc<Source> = Arc::new(Source::new("a!b"));
let mut reader = TabooReader { inner: StdTokenReader::new(&source) };
let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
.unwrap_err();
assert_eq!(err.identifier(), TabooChar::IDENTIFIER);
assert!(err.data().downcast_ref::<TabooChar>().is_some());
}
#[test]
fn escape_at_end_of_input_tolerant_recovers_and_repositions() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("ab \\"));
let mut reader = StdTokenReader::new(&source);
let parsed =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none()).unwrap();
assert_eq!(shapes(&parsed.result), ["chars 0..4 \"ab \\\\\""]);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_eq!(parsed.pos, 4);
assert_eq!(parsed.result.diagnostics.len(), 1);
assert_partition(&parsed.result, 0..4);
}
#[test]
fn escape_at_end_of_input_strict_aborts() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("ab \\"));
let mut reader = StdTokenReader::new(&source);
let err =
try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap_err();
assert_eq!(err.identifier(), crate::token::EndOfStreamAfterEscape::IDENTIFIER);
assert_eq!(
err.data()
.downcast_ref::<crate::token::EndOfStreamAfterEscape>()
.map(|c| c.escape_char),
Some('\\')
);
}
#[test]
fn unresolved_command_recovers_as_a_chars_fallback() {
let st = state();
let parsed =
run_both("a \\foo b", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"a \"", "chars 2..8 \"\\\\foo \"", "chars 8..9 \"b\""]
);
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
let condition = diagnostic.data().downcast_ref::<UnresolvableCommand>().unwrap();
assert_eq!(condition.name, "foo");
assert_eq!(condition.escape_char, '\\');
assert!(condition.detail.is_some());
assert_eq!(diagnostic.span().range(), 2..8);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_partition(&parsed.result, 0..9);
}
#[test]
fn diagnostics_inside_a_group_carry_the_group_frame() {
let st = state();
let parsed =
run_both("{\\foo", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
assert_eq!(parsed.result.diagnostics.len(), 2);
let unresolvable = parsed
.result
.diagnostics
.with_identifier(UnresolvableCommand::IDENTIFIER)
.next()
.unwrap();
assert_eq!(unresolvable.frames().len(), 1);
assert_eq!(unresolvable.frames()[0].span().range(), 0..1);
assert!(unresolvable.render().contains(unresolvable.frames()[0].title()));
let unclosed = parsed
.result
.diagnostics
.with_identifier(super::super::UnclosedGroup::IDENTIFIER)
.next()
.unwrap();
assert!(unclosed.frames().is_empty());
}
#[test]
fn unresolved_command_strict_aborts() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("a \\foo b"));
let mut reader = StdTokenReader::new(&source);
let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
.unwrap_err();
let condition = err.data().downcast_ref::<UnresolvableCommand>().unwrap();
assert_eq!(condition.name, "foo");
assert!(condition.detail.is_some());
assert_eq!(err.span().range(), 2..8);
}
#[test]
fn library_miss_takes_the_unresolvable_command_recovery() {
let st = state_with_macros(&[]);
let parsed =
run_both("a \\foo b", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"a \"", "chars 2..7 \"\\\\foo \"", "chars 7..8 \"b\""]
);
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
let condition = diagnostic.data().downcast_ref::<UnresolvableCommand>().unwrap();
assert_eq!(condition.name, "foo");
let detail = condition.detail.as_deref().expect("a miss detail");
assert!(detail.contains("test-macros"), "the searched provider is named: {detail}");
assert_partition(&parsed.result, 0..8);
}
#[test]
fn provider_failure_takes_the_command_resolution_failed_recovery() {
#[derive(Debug)]
struct BrokenProvider;
impl crate::serialize::SerializableObject<CmdLang> for BrokenProvider {}
impl SpecsProvider<CmdLang> for BrokenProvider {
fn name(&self) -> &str {
"broken"
}
fn retrieve_spec(
&self,
_query: &CallableQuery<'_, CmdLang>,
_state: &ParsingState<CmdLang>,
) -> Result<Option<Arc<dyn CallableSpec<CmdLang>>>, ProviderError> {
Err(ProviderError::Failed("provider is down".into()))
}
}
let mut scopes = ScopeStack::new();
scopes.push(Arc::new(BrokenProvider));
let st = Arc::new(ParsingState::new(StateData {
rules: rules(),
scopes,
mode: (),
ext: (),
}));
let parsed = run_both(
"a \\foo b",
&st,
Recovery::Tolerant,
StopSpec::none(),
StopSpec::none(),
);
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"a \"", "chars 2..7 \"\\\\foo \"", "chars 7..8 \"b\""]
);
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
assert_eq!(diagnostic.identifier(), CommandResolutionFailed::IDENTIFIER);
let condition = diagnostic.data().downcast_ref::<CommandResolutionFailed>().unwrap();
assert_eq!(condition.name, "foo");
let detail = condition.detail.as_deref().expect("a failure detail");
assert!(
detail.contains("broken") && detail.contains("provider is down"),
"unexpected detail: {detail}"
);
}
#[derive(Debug, Clone, Copy)]
struct HintLang;
impl Lang for HintLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = HintDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct HintDriver {
recovery: Recovery,
}
impl TestDriver for HintDriver {
fn with_recovery(recovery: Recovery) -> Self {
HintDriver { recovery }
}
}
impl ParseDriver<HintLang> for HintDriver {
fn recovery(&self) -> Recovery {
self.recovery
}
fn resolve_command(
&self,
_state: &ParsingState<HintLang>,
_token: &StdToken<HintLang>,
_tokens: &dyn TokenReader<'_, HintLang>,
) -> Result<CommandResolution<HintLang>, ParseError> {
Ok(CommandResolution::Unresolved {
detail: Some("load the {amsmath} library for this command".into()),
})
}
}
#[test]
fn resolver_supplied_detail_rides_the_diagnostic() {
let st = state_with(rules::<HintLang>());
let parsed =
run_both("a \\foo b", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
let condition = diagnostic.data().downcast_ref::<UnresolvableCommand>().unwrap();
assert_eq!(condition.name, "foo");
assert_eq!(
condition.detail.as_deref(),
Some("load the {amsmath} library for this command")
);
}
#[derive(Debug, Clone, Copy)]
struct AbortLang;
impl Lang for AbortLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = AbortDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct AbortDriver {
recovery: Recovery,
}
impl ParseDriver<AbortLang> for AbortDriver {
fn recovery(&self) -> Recovery {
self.recovery
}
fn resolve_command(
&self,
_state: &ParsingState<AbortLang>,
_token: &StdToken<AbortLang>,
_tokens: &dyn TokenReader<'_, AbortLang>,
) -> Result<CommandResolution<AbortLang>, ParseError> {
let source: Arc<Source> = Arc::new(Source::new(""));
Err(ParseError::new(
crate::error::HookFailed::new("resolver backend is down", None),
SourceSpan::new(&source, 0..0),
))
}
}
impl TestDriver for AbortDriver {
fn with_recovery(recovery: Recovery) -> Self {
AbortDriver { recovery }
}
}
#[test]
fn a_failing_resolve_command_aborts_under_any_policy() {
let st = state_with(rules::<AbortLang>());
let content = "a {\\foo} b";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let error =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
.unwrap_err();
assert_eq!(error.identifier(), "core.hooks.hook-failed");
assert_eq!(
error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
Some("resolver backend is down")
);
assert_eq!(error.frames().len(), 1);
assert_eq!(error.frames()[0].span().range(), 2..3);
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "refinelang.commands.not-available",
message = "command ‘\\{name}’ is not available: this language defines no commands",
no_constructor
)]
struct CommandsNotAvailable {
name: String,
}
#[derive(Debug, Clone, Copy)]
struct RefineLang;
impl Lang for RefineLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = RefineDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct RefineDriver {
recovery: Recovery,
}
impl TestDriver for RefineDriver {
fn with_recovery(recovery: Recovery) -> Self {
RefineDriver { recovery }
}
}
impl ParseDriver<RefineLang> for RefineDriver {
fn recovery(&self) -> Recovery {
self.recovery
}
fn refine_diagnostic(
&self,
data: alloc::boxed::Box<dyn crate::error::DiagnosticData>,
_state: &ParsingState<RefineLang>,
) -> alloc::boxed::Box<dyn crate::error::DiagnosticData> {
match data.downcast_ref::<UnresolvableCommand>() {
Some(condition) => alloc::boxed::Box::new(CommandsNotAvailable {
name: condition.name.clone(),
}),
None => data,
}
}
}
#[test]
fn refine_diagnostic_replaces_the_condition_in_the_funnel() {
let st = state_with(rules::<RefineLang>());
let parsed = run_both(
"a \\foo b",
&st,
Recovery::Tolerant,
StopSpec::none(),
StopSpec::none(),
);
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
assert_eq!(diagnostic.identifier(), CommandsNotAvailable::IDENTIFIER);
assert_eq!(
diagnostic.data().downcast_ref::<CommandsNotAvailable>().unwrap().name,
"foo"
);
assert!(diagnostic.message().contains("is not available"));
let source: Arc<Source> = Arc::new(Source::new("a \\foo b"));
let mut reader = StdTokenReader::new(&source);
let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
.unwrap_err();
assert_eq!(err.identifier(), CommandsNotAvailable::IDENTIFIER);
}
#[test]
fn zero_arg_macro_end_to_end() {
let st = state_with_macros(&["foo"]);
let parsed =
run_both("ab \\foo cd", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..3 \"ab \"", "callable 3..8", "chars 8..10 \"cd\""]
);
let node = parsed.result.tree.root().child(1).unwrap();
assert_eq!(node.callable_type(), Some(CT_MACRO));
assert_eq!(node.name(), Some("foo"));
let data = node.callable().unwrap();
assert!(data.arguments.is_empty() && data.slots.is_empty());
let expected = st
.scopes()
.retrieve_spec(
&CallableQuery::new(
CT_MACRO,
"foo",
CallableSyntax::Command { escape_char: '\\' },
),
&st,
)
.unwrap()
.unwrap();
assert!(Arc::ptr_eq(&data.spec, &expected));
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert!(parsed.result.diagnostics.is_empty());
assert_partition(&parsed.result, 0..10);
}
#[test]
fn macro_post_space_is_the_trigger_tokens_own_and_nothing_more() {
let st = state_with_macros(&["foo", "&"]);
let parsed =
run_both("\\foo bar", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["callable 0..5", "chars 5..8 \"bar\""]);
assert_partition(&parsed.result, 0..8);
let parsed =
run_both("\\& b", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["callable 0..2", "chars 2..4 \" b\""]);
assert_partition(&parsed.result, 0..4);
}
#[test]
fn macro_post_space_stops_at_a_paragraph_break() {
let st = state_with_macros(&["foo"]);
let parsed = run_both(
"\\foo \n\nb",
&st,
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
);
assert_eq!(
shapes(&parsed.result),
["callable 0..5", "chars 5..7 \"\\n\\n\"", "chars 7..8 \"b\""]
);
assert_partition(&parsed.result, 0..8);
}
#[test]
fn specials_dispatch_through_the_resolution_riding_on_the_token() {
let st = state_with(rules::<TildeLang>());
let parsed =
run_both("a~b", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..1 \"a\"", "callable 1..2", "chars 2..3 \"b\""]
);
let node = parsed.result.tree.root().child(1).unwrap();
assert_eq!(node.callable_type(), Some(CT_SPECIALS));
assert_eq!(node.name(), Some("~"));
assert!(parsed.result.diagnostics.is_empty());
assert_partition(&parsed.result, 0..3);
}
#[test]
fn invocation_inside_a_group_dispatches_at_that_level() {
let st = state_with_macros(&["foo"]);
let parsed =
run_both("{\\foo x}", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["group 0..8"]);
let group = parsed.result.tree.root().child(0).unwrap();
assert_eq!(group.child_count(), 2);
assert_eq!(group.child(0).unwrap().name(), Some("foo"));
assert_eq!(group.child(1).unwrap().chars(), Some("x"));
assert_partition(&parsed.result, 0..8);
}
#[test]
fn invocation_delta_defines_later_siblings() {
#[derive(Debug)]
struct DefSpec;
impl crate::serialize::SerializableObject<CmdLang> for DefSpec {}
impl CallableSpec<CmdLang> for DefSpec {
fn make_invocation_parser<'a>(
&'a self,
invocation: Invocation<'a, CmdLang>,
) -> Result<Box<dyn ConstructParser<CmdLang, Output = BuildId> + 'a>, ParseError>
{
Ok(Box::new(DefParser { inner: StdInvocationParser::new(invocation) }))
}
}
struct DefParser<'a> {
inner: StdInvocationParser<'a, CmdLang>,
}
impl ConstructParser<CmdLang> for DefParser<'_> {
type Output = BuildId;
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, CmdLang>,
) -> ConstructParserResult<
CmdLang,
(BuildId, Option<Box<ParsingStateDelta<CmdLang>>>),
> {
let (id, _) = self.inner.parse(cx)?;
let delta =
ParsingStateDelta::new().push_provider(macro_library(&["late"]));
Ok((id, Some(Box::new(delta))))
}
}
let mut lib: Package<CmdLang> = Package::new("cmds");
lib.insert(CT_MACRO, "def", Arc::new(DefSpec));
let mut scopes = ScopeStack::new();
scopes.push(Arc::new(lib));
let st: Arc<ParsingState<CmdLang>> =
Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));
let parsed = run_both(
"\\def \\late x",
&st,
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
);
assert_eq!(
shapes(&parsed.result),
["callable 0..5", "callable 5..11", "chars 11..12 \"x\""]
);
let def = parsed.result.tree.root().child(0).unwrap();
let late = parsed.result.tree.root().child(1).unwrap();
assert_eq!(def.name(), Some("def"));
assert_eq!(late.name(), Some("late"));
assert!(Arc::ptr_eq(def.parsing_state(), &st));
assert!(!Arc::ptr_eq(late.parsing_state(), &st));
assert!(parsed.result.diagnostics.is_empty());
assert_partition(&parsed.result, 0..12);
let st = state_with_macros(&[]);
let parsed = run_both(
"\\late x",
&st,
Recovery::Tolerant,
StopSpec::none(),
StopSpec::none(),
);
assert_eq!(parsed.result.diagnostics.len(), 1);
}
#[test]
fn takeover_parser_reads_raw_tokens_stages_custom_shape_and_returns_a_delta() {
#[derive(Debug)]
struct TakeSpec;
impl crate::serialize::SerializableObject<CmdLang> for TakeSpec {}
impl CallableSpec<CmdLang> for TakeSpec {
fn make_invocation_parser<'a>(
&'a self,
invocation: Invocation<'a, CmdLang>,
) -> Result<Box<dyn ConstructParser<CmdLang, Output = BuildId> + 'a>, ParseError>
{
Ok(Box::new(TakeParser { invocation }))
}
}
struct TakeParser<'a> {
invocation: Invocation<'a, CmdLang>,
}
impl ConstructParser<CmdLang> for TakeParser<'_> {
type Output = BuildId;
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, CmdLang>,
) -> ConstructParserResult<
CmdLang,
(BuildId, Option<Box<ParsingStateDelta<CmdLang>>>),
> {
let open_span = cx.tokens.source_span_of(self.invocation.token);
let content_start = cx.tokens.position_here();
let (content_end, close_span, end) = loop {
let token = cx.tokens.peek(&cx.state).expect("clean test content");
let at = cx.tokens.position_at(&token, TokenEdge::Start);
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
match cx.tokens.token_kind(&token) {
TokenKind::Char('!') => {
break (
at,
cx.tokens.source_span_of(&token),
cx.tokens.position_here(),
)
}
TokenKind::EndOfStream => {
panic!("test content has a marker")
}
_ => {}
}
};
let content = cx.source_span_within(&content_start, &content_end)?;
let child = cx.stage_node(
NodeKind::chars(content.span()),
content,
Arc::clone(&cx.state),
vec![],
).unwrap();
let span = cx.source_span_within(
&cx.tokens.position_at(self.invocation.token, TokenEdge::Start),
&end,
)?;
let delimiter =
|at: &SourceSpan| super::super::node_text_content(at, &span);
let data: GroupData<CmdLang> =
GroupData::untyped(delimiter(&open_span), delimiter(&close_span));
let id = cx.stage_node(
NodeKind::group(data),
span,
Arc::clone(&cx.state),
vec![child],
).unwrap();
let delta = ParsingStateDelta::new().rules(TokenRulesOverrides {
comments: CommentOverrides::disable(),
..TokenRulesOverrides::default()
});
Ok((id, Some(Box::new(delta))))
}
}
let mut lib: Package<CmdLang> = Package::new("cmds");
lib.insert(CT_MACRO, "take", Arc::new(TakeSpec));
let mut scopes = ScopeStack::new();
scopes.push(Arc::new(lib));
let st: Arc<ParsingState<CmdLang>> =
Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));
let content = "\\take a{b! %c";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let parsed =
try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap();
assert_eq!(
shapes(&parsed.result),
["group 0..10", "chars 10..13 \" %c\""]
);
let take = parsed.result.tree.root().child(0).unwrap();
assert_eq!(take.group_type(), None); assert_eq!(take.group_delimiters(), Some(("\\take ", "!")));
assert_eq!(take.child(0).unwrap().chars(), Some("a{b"));
assert!(parsed.result.diagnostics.is_empty());
assert_partition(&parsed.result, 0..13);
}
#[test]
fn make_node_ext_mints_through_the_dispatch_loop() {
struct ExtBundle;
impl NodeExtTypes for ExtBundle {
type NodeExt = Option<Box<str>>; type ArgumentExt = ();
type SlotExt = ();
}
#[derive(Debug, Clone, Copy)]
struct ExtLang;
#[derive(Debug, Clone, Copy)]
struct ExtDriver {
recovery: Recovery,
}
impl TestDriver for ExtDriver {
fn with_recovery(recovery: Recovery) -> Self {
ExtDriver { recovery }
}
}
impl ParseDriver<ExtLang> for ExtDriver {
fn recovery(&self) -> Recovery {
self.recovery
}
fn resolve_command(
&self,
state: &ParsingState<ExtLang>,
token: &StdToken<ExtLang>,
tokens: &dyn TokenReader<'_, ExtLang>,
) -> Result<CommandResolution<ExtLang>, ParseError> {
resolve_macro_in_scopes(state, token, tokens)
}
}
impl Lang for ExtLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ExtBundle;
type InvocationSyntax = ();
type Driver = ExtDriver;
fn make_node_ext(
kind: &NodeKind<Self>,
_span: &SourceSpan<Self::SourceOrigin>,
_state: &Arc<ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<Option<Box<str>>, crate::node::NodeBuildError> {
let NodeKind::Callable(data) = kind else { return Ok(None) };
let spec = (&*data.spec as &dyn core::any::Any)
.downcast_ref::<StdCallableSpec<ExtLang>>()
.expect("the test library registers StdCallableSpec");
Ok(Some(format!("{}#{}", data.name, spec.arguments.len()).into_boxed_str()))
}
}
let mut scopes = ScopeStack::new();
scopes.push(macro_library::<ExtLang>(&["foo"]));
let st: Arc<ParsingState<ExtLang>> =
Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));
let parsed =
run_both("\\foo x", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
let node = parsed.result.tree.root().child(0).unwrap();
assert_eq!(node.ext().as_deref(), Some("foo#0"));
assert_eq!(*parsed.result.tree.root().child(1).unwrap().ext(), None);
}
#[test]
fn invocation_child_state_policy_fixed_and_compute() {
let st = state_with_macros(&["foo"]);
let other = Arc::new(st.derived(&ParsingStateDelta::new()).unwrap());
let parsed = run_both_with(
"\\foo x",
&st,
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
ChildStateSpec {
group: GroupChildState::Inherit,
invocation: InvocationChildState::Fixed(Arc::clone(&other)),
},
);
let node = parsed.result.tree.root().child(0).unwrap();
assert!(Arc::ptr_eq(node.parsing_state(), &other));
let sibling = parsed.result.tree.root().child(1).unwrap();
assert!(Arc::ptr_eq(sibling.parsing_state(), &st));
let compute = |state: &Arc<ParsingState<CmdLang>>,
invocation: &Invocation<'_, CmdLang>|
-> Result<Arc<ParsingState<CmdLang>>, ParseError> {
assert_eq!(invocation.name, "foo");
assert_eq!(invocation.callable_type, CT_MACRO);
Ok(Arc::clone(state))
};
let parsed = run_both_with(
"\\foo x",
&st,
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
ChildStateSpec {
group: GroupChildState::Inherit,
invocation: InvocationChildState::Compute(&compute),
},
);
let node = parsed.result.tree.root().child(0).unwrap();
assert!(Arc::ptr_eq(node.parsing_state(), &st));
}
#[test]
fn group_round_trips_with_exact_spans_and_delimiters() {
let st = state();
let parsed =
run_both("a {b} c", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"a \"", "group 2..5", "chars 5..7 \" c\""]
);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert!(parsed.result.diagnostics.is_empty());
let group = parsed.result.tree.root().child(1).unwrap();
assert_eq!(group.group_type(), Some(GT_BRACE));
assert_eq!(group.group_delimiters(), Some(("{", "}")));
assert_eq!(group.child_count(), 1);
assert_eq!(group.child(0).unwrap().chars(), Some("b"));
assert_partition(&parsed.result, 0..7);
}
#[test]
fn nested_groups_with_exact_spans() {
let st = state();
let parsed =
run_both("{a{b}c}", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["group 0..7"]);
let outer = parsed.result.tree.root().child(0).unwrap();
assert_eq!(outer.child_count(), 3);
assert_eq!(outer.child(0).unwrap().chars(), Some("a"));
let inner = outer.child(1).unwrap();
assert!(inner.is_group());
assert_eq!(inner.span().range(), 2..5);
assert_eq!(inner.child(0).unwrap().chars(), Some("b"));
assert_eq!(outer.child(2).unwrap().chars(), Some("c"));
}
#[test]
fn empty_group_has_no_children() {
let st = state();
let parsed =
run_both("x{}y", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..1 \"x\"", "group 1..3", "chars 3..4 \"y\""]
);
let group = parsed.result.tree.root().child(1).unwrap();
assert_eq!(group.child_count(), 0);
assert_eq!(group.group_delimiters(), Some(("{", "}")));
}
#[test]
fn paragraph_break_inside_a_group_stays_inside() {
let st = state();
let parsed =
run_both("{a\n\nb}", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["group 0..6"]);
let group = parsed.result.tree.root().child(0).unwrap();
assert_eq!(group.child_count(), 3); assert_eq!(group.child(1).unwrap().chars(), Some("\n\n"));
}
#[test]
fn ambiguous_dollar_group_closes_via_the_derived_expected_close() {
let mut r = rules::<TestLang>();
r.groups.rules.push(math_rule());
let st = state_with(r);
let source: Arc<Source> = Arc::new(Source::new("a $x$ b"));
let mut reader = StdTokenReader::new(&source);
let parsed =
try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap();
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"a \"", "group 2..5", "chars 5..7 \" b\""]
);
let group = parsed.result.tree.root().child(1).unwrap();
assert_eq!(group.group_type(), Some(GT_MATH));
assert_eq!(group.group_delimiters(), Some(("$", "$")));
assert_eq!(group.child(0).unwrap().chars(), Some("x"));
}
#[test]
fn node_condition_counts_a_group_as_one_node() {
let st = state();
let mut c1 = |count: usize, view: StagedNodeView<'_, TestLang>| {
Ok(count >= 1 && matches!(view.kind(), NodeKind::Group(_)))
};
let mut c2 = |count: usize, view: StagedNodeView<'_, TestLang>| {
Ok(count >= 1 && matches!(view.kind(), NodeKind::Group(_)))
};
let parsed = run_both(
"{a}b",
&st,
Recovery::Strict,
StopSpec { token: None, node: Some(&mut c1) },
StopSpec { token: None, node: Some(&mut c2) },
);
assert_eq!(shapes(&parsed.result), ["group 0..3"]);
assert_eq!(parsed.stop, StopCause::NodeCondition);
assert_eq!(parsed.pos, 3);
}
#[test]
fn stop_conditions_are_not_consulted_inside_a_group() {
let st = state();
let parsed = run_both(
"a{\\end}b",
&st,
Recovery::Tolerant,
StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
StopSpec::at_token(TokenStopKind::Command { name: "end" }, false),
);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_eq!(parsed.result.diagnostics.len(), 1);
let group = parsed.result.tree.root().child(1).unwrap();
assert_eq!(group.child(0).unwrap().chars(), Some("\\end"));
}
#[test]
fn unclosed_group_at_end_of_input_recovers_with_an_empty_close() {
let st = state();
let parsed =
run_both("a {bc", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["chars 0..2 \"a \"", "group 2..5"]);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_eq!(parsed.pos, 5);
let group = parsed.result.tree.root().child(1).unwrap();
assert_eq!(group.group_delimiters(), Some(("{", "")));
assert_eq!(group.child(0).unwrap().chars(), Some("bc"));
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
let condition = diagnostic.data().downcast_ref::<super::super::UnclosedGroup>().unwrap();
assert_eq!(condition.expected_close, "}");
assert_eq!(condition.found, super::super::UnclosedGroupFound::EndOfInput);
assert_eq!(diagnostic.span().range(), 2..3);
}
#[test]
fn unclosed_group_strict_aborts() {
let st = state();
let source: Arc<Source> = Arc::new(Source::new("a {bc"));
let mut reader = StdTokenReader::new(&source);
let err = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
.unwrap_err();
let condition = err.data().downcast_ref::<super::super::UnclosedGroup>().unwrap();
assert_eq!(condition.expected_close, "}");
assert_eq!(condition.found, super::super::UnclosedGroupFound::EndOfInput);
assert_eq!(err.span().range(), 2..3);
}
#[test]
fn mismatched_close_inside_a_group_unwinds_without_consuming() {
let mut r = rules::<TestLang>();
r.groups.rules.push(Arc::new(GroupRule {
group_type: GT_BRACE,
open: "[".into(),
close: "]".into(),
}));
let st = state_with(r);
let parsed =
run_both("{a]}", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
assert_eq!(shapes(&parsed.result), ["group 0..2"]);
let group = parsed.result.tree.root().child(0).unwrap();
assert_eq!(group.group_delimiters(), Some(("{", "")));
assert_eq!(group.child(0).unwrap().chars(), Some("a"));
assert_eq!(stop_shape(&parsed.stop), "close 2..3");
assert_eq!(parsed.pos, 2);
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
let condition = diagnostic.data().downcast_ref::<super::super::UnclosedGroup>().unwrap();
assert_eq!(condition.expected_close, "}");
assert_eq!(condition.found, super::super::UnclosedGroupFound::StrayClose);
assert_eq!(diagnostic.span().range(), 2..3);
}
#[test]
fn mismatched_close_inside_a_group_strict_aborts() {
let mut r = rules::<TestLang>();
r.groups.rules.push(Arc::new(GroupRule {
group_type: GT_BRACE,
open: "[".into(),
close: "]".into(),
}));
let st = state_with(r);
let source: Arc<Source> = Arc::new(Source::new("{a]}"));
let mut reader = StdTokenReader::new(&source);
let err =
try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none()).unwrap_err();
let condition = err.data().downcast_ref::<super::super::UnclosedGroup>().unwrap();
assert_eq!(condition.expected_close, "}");
assert_eq!(condition.found, super::super::UnclosedGroupFound::StrayClose);
assert_eq!(err.span().range(), 2..3);
}
#[test]
fn root_driver_skips_a_stray_close_and_continues() {
#[derive(Debug, Clone, DiagnosticInfo)]
#[diagnostic(
id = "test.root-driver.stray-group-close",
message = "unexpected closing ‘{delim}’",
no_constructor
)]
struct StrayGroupClose {
delim: String,
}
let content = "a}b";
let source: Arc<Source> = Arc::new(Source::new(content));
let st = state();
let mut reader = StdTokenReader::new(&source);
let mut session: ParserSession<TestLang> = ParserSession::new();
let driver = StdParseDriver::new(Recovery::Tolerant, ());
let mut nodes = Vec::new();
let stop = loop {
let mut cx = ParseContext::new(
&mut reader,
Arc::clone(&st),
&mut session,
&driver);
let mut parser = NodesParser::new(StopSpec::none());
let (outcome, _) = parser.parse(&mut cx).unwrap();
nodes.extend(outcome.nodes);
match outcome.stop {
StopCause::UnexpectedGroupClose { span, after } => {
session
.recover(
Recovery::Tolerant,
Box::new(StrayGroupClose { delim: "}".into() }),
span,
)
.unwrap();
<dyn TokenReader<'_, TestLang>>::move_to_position(&mut reader, &after);
}
other => break other,
}
};
assert_eq!(stop, StopCause::EndOfInput);
let root = session.builder.add(
NodeKind::list(),
SourceSpan::entire(&source),
Arc::clone(&st),
nodes, (), (),
).unwrap();
let result = session.finish(root).unwrap();
let texts: Vec<_> = result
.tree
.root()
.children()
.iter().map(|c| c.chars().unwrap().to_string())
.collect();
assert_eq!(texts, ["a", "b"]);
assert_eq!(result.diagnostics.len(), 1);
}
#[test]
fn child_state_fixed_reverts_group_interiors_to_the_outer_state() {
let full = state();
let restricted = Arc::new(full.derived(&ParsingStateDelta::new().rules(
TokenRulesOverrides { comments: CommentOverrides::disable(), ..Default::default() },
)).unwrap());
let content = "%x{%y\n}z";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let plain =
try_run(&source, &mut reader, &restricted, Recovery::Strict, StopSpec::none())
.unwrap();
let group = plain.result.tree.root().child(1).unwrap();
assert!(group.children().iter().all(|c| c.is_chars()));
let policy = ChildStateSpec {
group: GroupChildState::Fixed(Arc::clone(&full)),
invocation: InvocationChildState::Inherit,
};
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let parsed = try_run_with(&source,
&mut reader,
&restricted,
Recovery::Strict,
StopSpec::none(),
policy,
)
.unwrap();
assert_eq!(
shapes(&parsed.result),
["chars 0..2 \"%x\"", "group 2..7", "chars 7..8 \"z\""]
);
let group = parsed.result.tree.root().child(1).unwrap();
assert_eq!(group.child_count(), 1);
let comment = group.child(0).unwrap();
assert_eq!(
comment.comment().map(|data| data.content.resolve(comment.source())),
Some("y")
);
assert!(Arc::ptr_eq(group.parsing_state(), &full));
}
#[test]
fn child_state_compute_selects_by_the_open_token() {
const GT_OPT: u32 = 2;
let mut r = rules::<TestLang>();
r.groups.rules.push(Arc::new(GroupRule {
group_type: GT_OPT,
open: "[".into(),
close: "]".into(),
}));
let full = state_with(r);
let no_comments = Arc::new(full.derived(&ParsingStateDelta::new().rules(
TokenRulesOverrides { comments: CommentOverrides::disable(), ..Default::default() },
)).unwrap());
let compute = |state: &Arc<ParsingState<TestLang>>,
token: &StdToken<TestLang>,
tokens: &dyn TokenReader<'_, TestLang>| {
Ok(match tokens.token_kind(token) {
TokenKind::GroupOpen { rule, .. } if rule.group_type == GT_OPT => {
Arc::clone(&no_comments)
}
_ => Arc::clone(state), })
};
let policy = ChildStateSpec {
group: GroupChildState::Compute(&compute),
invocation: InvocationChildState::Inherit,
};
let content = "{%a\n}[%b\n]";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let parsed = try_run_with(&source,
&mut reader,
&full,
Recovery::Strict,
StopSpec::none(),
policy,
)
.unwrap();
let braces = parsed.result.tree.root().child(0).unwrap();
assert_eq!(braces.child_count(), 1);
let comment = braces.child(0).unwrap();
assert_eq!(
comment.comment().map(|data| data.content.resolve(comment.source())),
Some("a")
);
assert!(Arc::ptr_eq(braces.parsing_state(), &full)); let brackets = parsed.result.tree.root().child(1).unwrap();
assert_eq!(brackets.group_type(), Some(GT_OPT));
assert_eq!(brackets.child_count(), 1);
assert_eq!(brackets.child(0).unwrap().chars(), Some("%b\n"));
assert!(Arc::ptr_eq(brackets.parsing_state(), &no_comments));
}
#[test]
fn a_failing_child_state_compute_aborts_under_any_policy() {
let full = state_with(rules::<TestLang>());
let compute = |state: &Arc<ParsingState<TestLang>>,
_token: &StdToken<TestLang>,
_tokens: &dyn TokenReader<'_, TestLang>| {
let delta = ParsingStateDelta::new()
.scope_op(crate::scopes::ScopeOp::Unload { name: "no-such-provider".into() });
match state.derived(&delta) {
Ok(state) => Ok(Arc::new(state)),
Err(error) => {
let scratch: Arc<Source> = Arc::new(Source::new(""));
Err(ParseError::new(
crate::error::HookFailed::new(error.to_string(), None)
.with_cause(error),
SourceSpan::new(&scratch, 0..0),
))
}
}
};
let policy = ChildStateSpec {
group: GroupChildState::Compute(&compute),
invocation: InvocationChildState::Inherit,
};
let content = "{a}";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let error = try_run_with(&source,
&mut reader,
&full,
Recovery::Tolerant,
StopSpec::none(),
policy,
)
.unwrap_err();
assert_eq!(error.identifier(), "core.hooks.hook-failed");
let condition =
error.data().downcast_ref::<crate::error::HookFailed>().unwrap();
let cause: &(dyn core::error::Error + 'static) = &**condition.cause.as_ref().unwrap();
let derive_error = cause
.downcast_ref::<crate::state::DeriveError<TestLang>>()
.expect("the cause is the DeriveError");
assert!(derive_error.finalize_error.is_none());
assert_eq!(derive_error.failures.len(), 1);
assert!(matches!(
&derive_error.failures[0],
crate::scopes::ScopeOpError::UnknownProvider { name } if &**name == "no-such-provider"
));
assert_eq!(error.frames().len(), 0);
}
#[test]
fn sibling_group_interiors_share_one_memoized_state() {
let st = state();
let parsed =
run_both("{a}{b}", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
let root = parsed.result.tree.root();
let g1 = root.child(0).unwrap();
let g2 = root.child(1).unwrap();
assert!(Arc::ptr_eq(g1.parsing_state(), &st));
assert!(Arc::ptr_eq(g2.parsing_state(), &st));
let a = g1.child(0).unwrap();
let b = g2.child(0).unwrap();
assert!(Arc::ptr_eq(a.parsing_state(), b.parsing_state()));
assert!(!Arc::ptr_eq(a.parsing_state(), &st));
assert_eq!(
a.parsing_state()
.rules()
.expecting_group_close()
.map(|rule| rule.close.as_str()),
Some("}")
);
}
#[test]
fn observe_transition_fires_per_descent_finalize_once_per_derivation() {
use core::sync::atomic::{AtomicUsize, Ordering};
static FINALIZE_RUNS: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug, Default)]
struct Counts {
observed: usize,
}
#[derive(Debug, Clone, Copy)]
struct CountLang;
impl Lang for CountLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = Counts;
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = CountDriver;
fn finalize_transition(
_new: &mut StateData<Self>,
_prev: &ParsingState<Self>,
_events: &[()],
) -> Result<(), crate::state::FinalizeError> {
FINALIZE_RUNS.fetch_add(1, Ordering::Relaxed);
Ok(())
}
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct CountDriver;
impl ParseDriver<CountLang> for CountDriver {
fn observe_transition(
&self,
ext: &mut Counts,
_diagnostics: &mut crate::error::Diagnostics,
_prev: &ParsingState<CountLang>,
_new: &ParsingState<CountLang>,
_delta: &ParsingStateDelta<CountLang>,
) -> Result<(), ParseError> {
ext.observed += 1;
Ok(())
}
}
let content = "{a}{b}";
let source: Arc<Source> = Arc::new(Source::new(content));
let st = state_with(rules::<CountLang>());
let mut reader = StdTokenReader::new(&source);
let mut session: ParserSession<CountLang> = ParserSession::new();
let driver = CountDriver;
let mut cx = ParseContext::new(
&mut reader,
Arc::clone(&st),
&mut session,
&driver);
let mut parser = NodesParser::new(StopSpec::none());
let (outcome, _) = parser.parse(&mut cx).unwrap();
assert!(matches!(outcome.stop, StopCause::EndOfInput));
assert_eq!(session.ext.observed, 2);
assert_eq!(FINALIZE_RUNS.load(Ordering::Relaxed), 1);
}
#[derive(Debug, Default)]
struct Seen {
transitions: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "testlang.observe.transition-observed",
message = "a state transition was observed",
no_constructor
)]
struct TransitionObserved;
#[test]
fn observe_transition_diagnostics_sink_records_without_aborting() {
#[derive(Debug, Clone, Copy)]
struct SinkLang;
impl Lang for SinkLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = Seen;
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = SinkDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct SinkDriver;
impl TestDriver for SinkDriver {
fn with_recovery(_recovery: Recovery) -> Self {
SinkDriver }
}
impl ParseDriver<SinkLang> for SinkDriver {
fn observe_transition(
&self,
ext: &mut Seen,
diagnostics: &mut crate::error::Diagnostics,
_prev: &ParsingState<SinkLang>,
_new: &ParsingState<SinkLang>,
_delta: &ParsingStateDelta<SinkLang>,
) -> Result<(), ParseError> {
ext.transitions += 1;
let scratch: Arc<Source> = Arc::new(Source::new(""));
diagnostics.push(crate::error::Diagnostic::error(
TransitionObserved,
SourceSpan::new(&scratch, 0..0),
));
Ok(())
}
}
let st = state_with(rules::<SinkLang>());
let content = "{a}";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let parsed =
try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
.expect("the sink records; it never aborts");
assert_eq!(parsed.result.diagnostics.len(), 1);
let recorded = parsed.result.diagnostics.iter().next().unwrap();
assert_eq!(recorded.severity(), crate::error::Severity::Error);
assert_eq!(recorded.identifier(), "testlang.observe.transition-observed");
assert_eq!(shapes(&parsed.result), ["group 0..3"]);
}
#[test]
fn a_failing_observe_transition_aborts_under_any_policy() {
#[derive(Debug, Clone, Copy)]
struct FailObserveLang;
impl Lang for FailObserveLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = Seen;
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = FailObserveDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct FailObserveDriver;
impl TestDriver for FailObserveDriver {
fn with_recovery(_recovery: Recovery) -> Self {
FailObserveDriver }
}
impl ParseDriver<FailObserveLang> for FailObserveDriver {
fn recovery(&self) -> Recovery {
Recovery::Tolerant
}
fn observe_transition(
&self,
ext: &mut Seen,
_diagnostics: &mut crate::error::Diagnostics,
_prev: &ParsingState<FailObserveLang>,
_new: &ParsingState<FailObserveLang>,
_delta: &ParsingStateDelta<FailObserveLang>,
) -> Result<(), ParseError> {
ext.transitions += 1;
if ext.transitions < 2 {
return Ok(());
}
let scratch: Arc<Source> = Arc::new(Source::new(""));
Err(ParseError::new(
crate::error::HookFailed::new("observer backend gone", None),
SourceSpan::new(&scratch, 0..0),
))
}
}
let st = state_with(rules::<FailObserveLang>());
let content = "{{a}}";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let error =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
.unwrap_err();
assert_eq!(error.identifier(), "core.hooks.hook-failed");
assert_eq!(
error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
Some("observer backend gone")
);
assert!(!error.frames().is_empty());
}
#[test]
fn mixed_content_with_groups_partitions_exactly() {
let st = state();
let content = "ab {cd %e\nf} g\n\nh";
let parsed =
run_both(content, &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
[
"chars 0..3 \"ab \"",
"group 3..12",
"chars 12..14 \" g\"",
"chars 14..16 \"\\n\\n\"",
"chars 16..17 \"h\"",
]
);
let group = parsed.result.tree.root().child(1).unwrap();
assert_eq!(group.child_count(), 3);
assert_eq!(group.child(0).unwrap().chars(), Some("cd "));
let comment = group.child(1).unwrap();
assert_eq!(
comment.comment().map(|data| data.content.resolve(comment.source())),
Some("e")
);
assert_eq!(group.child(2).unwrap().chars(), Some("f"));
assert_partition(&parsed.result, 0..content.len());
}
#[test]
fn mixed_content_shapes_and_partition() {
let st = state();
let content = "ab %c\nd\n\n e \\foo f";
let parsed =
run_both(content, &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
[
"chars 0..3 \"ab \"",
"comment 3..6 start=\"%\" content=\"c\" post=\"\\n\"",
"chars 6..7 \"d\"",
"chars 7..9 \"\\n\\n\"",
"chars 9..12 \" e \"",
"chars 12..17 \"\\\\foo \"",
"chars 17..18 \"f\"",
]
);
assert_eq!(parsed.stop, StopCause::EndOfInput);
assert_eq!(parsed.result.diagnostics.len(), 1);
assert_partition(&parsed.result, 0..content.len());
}
#[test]
fn custom_driver_intercepts_every_factory_and_math_groups_enter_math_mode() {
use core::sync::atomic::{AtomicUsize, Ordering};
use super::super::GroupParser;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
enum Mode {
#[default]
Text,
Math,
}
#[derive(Debug, Clone, Copy)]
struct DriveLang;
impl Lang for DriveLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = Mode;
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = DriveDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Default)]
struct DriveDriver {
nodes_parsers: AtomicUsize,
group_parsers: AtomicUsize,
invocation_parsers: AtomicUsize,
}
impl ParseDriver<DriveLang> for DriveDriver {
fn resolve_command(
&self,
state: &ParsingState<DriveLang>,
token: &StdToken<DriveLang>,
tokens: &dyn TokenReader<'_, DriveLang>,
) -> Result<CommandResolution<DriveLang>, ParseError> {
resolve_macro_in_scopes(state, token, tokens)
}
fn group_interior_delta(
&self,
_base: &ParsingState<DriveLang>,
rule: &Arc<GroupRule<DriveLang>>,
) -> Option<ParsingStateDelta<DriveLang>> {
(rule.group_type == GT_MATH)
.then(|| ParsingStateDelta::new().mode(Mode::Math))
}
fn make_nodes_parser<'p>(
&'p self,
stop: StopSpec<'p, DriveLang>,
child_states: ChildStateSpec<'p, DriveLang>,
) -> Result<
Box<dyn ConstructParser<DriveLang, Output = NodesOutcome<DriveLang>> + 'p>,
ParseError,
> {
self.nodes_parsers.fetch_add(1, Ordering::Relaxed);
Ok(Box::new(NodesParser::new(stop).with_child_states(child_states)))
}
fn make_group_parser<'p>(
&'p self,
open: &StdToken<DriveLang>,
rule: Arc<GroupRule<DriveLang>>,
child_states: ChildStateSpec<'p, DriveLang>,
) -> Result<Box<dyn ConstructParser<DriveLang, Output = BuildId> + 'p>, ParseError>
{
self.group_parsers.fetch_add(1, Ordering::Relaxed);
Ok(Box::new(
GroupParser::new(open.clone(), rule).with_child_states(child_states),
))
}
fn make_invocation_parser<'a>(
&'a self,
invocation: Invocation<'a, DriveLang>,
) -> Result<Box<dyn ConstructParser<DriveLang, Output = BuildId> + 'a>, ParseError>
{
self.invocation_parsers.fetch_add(1, Ordering::Relaxed);
let spec = invocation.spec;
spec.make_invocation_parser(invocation)
}
}
let content = "{a}$m$\\m {y}";
let mut rules = rules::<DriveLang>();
rules.groups.rules.push(math_rule());
let mut scopes = ScopeStack::new();
scopes.push(macro_library::<DriveLang>(&["m"]));
let st = Arc::new(ParsingState::new(StateData {
rules,
scopes,
mode: Mode::Text,
ext: (),
}));
let st = Arc::new(st.derived(&ParsingStateDelta::new()).unwrap()); let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let mut session: ParserSession<DriveLang> = ParserSession::new();
let driver = DriveDriver::default();
let mut cx = ParseContext::new(
&mut reader,
Arc::clone(&st),
&mut session,
&driver);
let (outcome, delta) = cx
.parse_nodes(Arc::clone(&st), StopSpec::none(), ChildStateSpec::inherit())
.unwrap();
assert!(delta.is_none());
assert!(matches!(outcome.stop, StopCause::EndOfInput));
let root = session
.builder
.add(
NodeKind::list(),
SourceSpan::new(&source, 0..content.len()),
Arc::clone(&st),
outcome.nodes, (), (),
)
.unwrap();
let result = session.finish(root).unwrap();
crate::node::check_tree_invariants(&result.tree);
assert!(result.diagnostics.is_empty());
assert_eq!(
shapes(&result),
["group 0..3", "group 3..6", "callable 6..9", "group 9..12"]
);
assert_eq!(driver.nodes_parsers.load(Ordering::Relaxed), 4);
assert_eq!(driver.group_parsers.load(Ordering::Relaxed), 3);
assert_eq!(driver.invocation_parsers.load(Ordering::Relaxed), 1);
let math_child = result.tree.root().child(1).unwrap().child(0).unwrap();
assert_eq!(math_child.chars(), Some("m"));
assert_eq!(math_child.parsing_state().mode(), Mode::Math);
let brace_child = result.tree.root().child(0).unwrap().child(0).unwrap();
assert_eq!(brace_child.chars(), Some("a"));
assert_eq!(brace_child.parsing_state().mode(), Mode::Text);
let after = result.tree.root().child(3).unwrap().child(0).unwrap();
assert_eq!(after.chars(), Some("y"));
assert_eq!(after.parsing_state().mode(), Mode::Text);
}
#[test]
fn a_group_leaks_the_after_effects_its_hook_keeps() {
use core::sync::atomic::{AtomicUsize, Ordering};
use super::super::{GroupAfterEffectsFn, GroupParser};
use crate::scopes::{Scope, ScopeOp};
use crate::state::{FeaturePresence, LangFeatures};
const GLOBAL: &str = "global";
const LOCAL: &str = "local";
#[derive(Debug, Clone, Copy)]
struct GdefLang;
impl Lang for GdefLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = GdefDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug)]
struct DefiningSpec {
delta: ParsingStateDelta<GdefLang>,
}
impl crate::serialize::SerializableObject<GdefLang> for DefiningSpec {}
impl CallableSpec<GdefLang> for DefiningSpec {
fn make_invocation_parser<'a>(
&'a self,
invocation: Invocation<'a, GdefLang>,
) -> Result<Box<dyn ConstructParser<GdefLang, Output = BuildId> + 'a>, ParseError>
{
Ok(Box::new(DefiningParser {
inner: StdInvocationParser::new(invocation),
delta: &self.delta,
}))
}
}
struct DefiningParser<'a> {
inner: StdInvocationParser<'a, GdefLang>,
delta: &'a ParsingStateDelta<GdefLang>,
}
impl ConstructParser<GdefLang> for DefiningParser<'_> {
type Output = BuildId;
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, GdefLang>,
) -> ConstructParserResult<
GdefLang,
(BuildId, Option<Box<ParsingStateDelta<GdefLang>>>),
> {
let (id, _) = self.inner.parse(cx)?;
Ok((id, Some(Box::new(self.delta.clone()))))
}
}
fn defining(scope: &str, name: &str) -> ParsingStateDelta<GdefLang> {
ParsingStateDelta::new().scope_op(ScopeOp::Define {
scope: scope.into(),
callable_type: CT_MACRO,
name: name.into(),
spec: Arc::new(StdCallableSpec::default()),
})
}
fn defined(state: &ParsingState<GdefLang>, name: &str) -> bool {
let query =
CallableQuery::new(CT_MACRO, name, CallableSyntax::Command { escape_char: '\\' });
state.scopes().retrieve_spec(&query, state).unwrap().is_some()
}
#[allow(clippy::type_complexity)]
type Hook = Box<
dyn Fn(
&Arc<GroupRule<GdefLang>>,
&Arc<ParsingState<GdefLang>>,
&Arc<ParsingState<GdefLang>>,
Option<Box<ParsingStateDelta<GdefLang>>>,
) -> Result<Option<Box<ParsingStateDelta<GdefLang>>>, ParseError>
+ Send
+ Sync,
>;
struct GdefDriver {
hook: Option<Hook>,
calls: Arc<AtomicUsize>,
}
impl fmt::Debug for GdefDriver {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("GdefDriver").finish_non_exhaustive()
}
}
impl GdefDriver {
fn new(leak: bool) -> GdefDriver {
let calls = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&calls);
let hook: Hook = Box::new(move |rule, initial, exit, record| {
counter.fetch_add(1, Ordering::Relaxed);
assert_eq!(rule.group_type, GT_BRACE);
assert!(!defined(initial, "g") && !defined(initial, "d"));
let Some(record) = record else {
assert!(Arc::ptr_eq(initial, exit));
return Ok(None);
};
let ops = <<GdefLang as Lang>::Features as LangFeatures>::Scopes::store_get(
&record.scope_ops,
)
.expect("the lang declares the scopes feature present");
let kept: Vec<ScopeOp<GdefLang>> = ops
.iter()
.filter(|op| matches!(op, ScopeOp::Define { scope, .. } if &**scope == GLOBAL))
.cloned()
.collect();
if kept.is_empty() {
return Ok(None);
}
let mut escaping = ParsingStateDelta::new();
for op in kept {
escaping = escaping.scope_op(op);
}
Ok(Some(Box::new(escaping)))
});
GdefDriver { hook: leak.then_some(hook), calls }
}
}
impl ParseDriver<GdefLang> for GdefDriver {
fn make_token_reader<'s>(
&'s self,
source: &'s alloc::sync::Arc<crate::source::Source>,
) -> alloc::boxed::Box<dyn crate::token::TokenReader<'s, GdefLang> + 's> {
alloc::boxed::Box::new(crate::token::StdTokenReader::new(source))
}
fn recovery(&self) -> Recovery {
Recovery::Tolerant
}
fn resolve_command(
&self,
state: &ParsingState<GdefLang>,
token: &StdToken<GdefLang>,
tokens: &dyn TokenReader<'_, GdefLang>,
) -> Result<CommandResolution<GdefLang>, ParseError> {
resolve_macro_in_scopes(state, token, tokens)
}
fn make_group_parser<'p>(
&'p self,
open: &StdToken<GdefLang>,
rule: Arc<GroupRule<GdefLang>>,
child_states: ChildStateSpec<'p, GdefLang>,
) -> Result<Box<dyn ConstructParser<GdefLang, Output = BuildId> + 'p>, ParseError>
{
Ok(match &self.hook {
None => Box::new(
GroupParser::new(open.clone(), rule).with_child_states(child_states),
),
Some(hook) => {
let hook: GroupAfterEffectsFn<'p, GdefLang> = &**hook;
Box::new(
GroupParser::new_with_after_effects(open.clone(), rule, hook)
.with_child_states(child_states),
)
}
})
}
}
fn run(
content: &str,
driver: &GdefDriver,
) -> (ParseResult<GdefLang>, Arc<ParsingState<GdefLang>>) {
let mut scopes = ScopeStack::new();
let mut base: Scope<GdefLang> = Scope::new("base");
base.insert(CT_MACRO, "gdef", Arc::new(DefiningSpec { delta: defining(GLOBAL, "g") }));
base.insert(CT_MACRO, "def", Arc::new(DefiningSpec { delta: defining(LOCAL, "d") }));
scopes.push(Arc::new(base));
scopes.push(Arc::new(Scope::<GdefLang>::new(GLOBAL)));
let st = Arc::new(ParsingState::new(StateData {
rules: rules(),
scopes,
mode: (),
ext: (),
}));
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let mut session: ParserSession<GdefLang> = ParserSession::new();
let mut cx =
ParseContext::new(&mut reader, Arc::clone(&st), &mut session, driver);
let (outcome, delta) = cx
.parse_nodes(Arc::clone(&st), StopSpec::none(), ChildStateSpec::inherit())
.unwrap();
assert!(delta.is_none());
let exit = Arc::clone(&outcome.state);
let root = session
.builder
.add(
NodeKind::list(),
SourceSpan::new(&source, 0..content.len()),
Arc::clone(&st),
outcome.nodes,
(),
(),
)
.unwrap();
(session.finish(root).unwrap(), exit)
}
let driver = GdefDriver::new(true);
let (result, exit) = run("{\\gdef\\def\\g\\d}\\g\\d", &driver);
crate::node::check_tree_invariants(&result.tree);
assert_eq!(driver.calls.load(Ordering::Relaxed), 1);
let root = result.tree.root();
assert_eq!(root.child(0).unwrap().child_count(), 4);
assert_eq!(root.child(1).unwrap().name(), Some("g"));
assert_eq!(root.child(2).unwrap().chars(), Some("\\d"));
assert_eq!(result.diagnostics.len(), 1);
assert!(defined(&exit, "g"));
assert!(!defined(&exit, "d"));
let driver = GdefDriver::new(true);
let (result, exit) = run("{{\\gdef}}\\g", &driver);
crate::node::check_tree_invariants(&result.tree);
assert_eq!(driver.calls.load(Ordering::Relaxed), 2);
assert_eq!(result.tree.root().child(1).unwrap().name(), Some("g"));
assert!(result.diagnostics.is_empty());
assert!(defined(&exit, "g"));
let driver = GdefDriver::new(false);
let (result, exit) = run("{\\gdef\\def}\\g\\d", &driver);
crate::node::check_tree_invariants(&result.tree);
assert_eq!(driver.calls.load(Ordering::Relaxed), 0);
assert_eq!(result.diagnostics.len(), 2);
assert!(!defined(&exit, "g"));
assert!(!defined(&exit, "d"));
}
#[test]
fn a_failing_invocation_parser_factory_aborts_under_any_policy() {
#[derive(Debug)]
struct BrokenFactorySpec;
impl crate::serialize::SerializableObject<CmdLang> for BrokenFactorySpec {}
impl CallableSpec<CmdLang> for BrokenFactorySpec {
fn make_invocation_parser<'a>(
&'a self,
_invocation: Invocation<'a, CmdLang>,
) -> Result<Box<dyn ConstructParser<CmdLang, Output = BuildId> + 'a>, ParseError>
{
let scratch: Arc<Source> = Arc::new(Source::new(""));
Err(ParseError::new(
crate::error::HookFailed::new("parser backend unavailable", None),
SourceSpan::new(&scratch, 0..0),
))
}
}
let mut lib = Package::new("broken");
lib.insert(CT_MACRO, "fail", BrokenFactorySpec);
let mut scopes = ScopeStack::new();
scopes.push(Arc::new(lib));
let st: Arc<ParsingState<CmdLang>> =
Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));
let content = "a {\\fail} b";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let error =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
.unwrap_err();
assert_eq!(error.identifier(), "core.hooks.hook-failed");
assert_eq!(
error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
Some("parser backend unavailable")
);
assert_eq!(error.frames().len(), 2);
assert_eq!(error.frames()[0].span().range(), 3..8);
assert_eq!(error.frames()[1].span().range(), 2..3);
assert_eq!(
error.frames()[0].title(),
BrokenFactorySpec.stack_frame_title(crate::spec::FrameRole::Invocation, "\\fail")
);
}
#[test]
fn a_failing_nodes_parser_factory_aborts_under_any_policy() {
#[derive(Debug, Clone, Copy)]
struct BrokenLang;
impl Lang for BrokenLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = BrokenDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct BrokenDriver;
impl TestDriver for BrokenDriver {
fn with_recovery(_recovery: Recovery) -> Self {
BrokenDriver }
}
impl ParseDriver<BrokenLang> for BrokenDriver {
fn recovery(&self) -> Recovery {
Recovery::Tolerant
}
fn make_nodes_parser<'p>(
&'p self,
_stop: StopSpec<'p, BrokenLang>,
_child_states: ChildStateSpec<'p, BrokenLang>,
) -> Result<
Box<dyn ConstructParser<BrokenLang, Output = NodesOutcome<BrokenLang>> + 'p>,
ParseError,
> {
let scratch: Arc<Source> = Arc::new(Source::new(""));
Err(ParseError::new(
crate::error::HookFailed::new("content-loop backend unavailable", None),
SourceSpan::new(&scratch, 0..0),
))
}
}
let st = state_with(rules::<BrokenLang>());
let content = "{a}";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let error =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
.unwrap_err();
assert_eq!(error.identifier(), "core.hooks.hook-failed");
assert_eq!(error.frames().len(), 1);
assert_eq!(error.frames()[0].span().range(), 0..1);
}
#[test]
fn a_failing_make_node_ext_aborts_as_a_hook_failure() {
#[derive(Debug, Clone, Copy)]
struct MintFailLang;
impl Lang for MintFailLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = StdParseDriver;
fn make_node_ext(
kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
if matches!(kind, NodeKind::Chars { .. }) {
return Err(crate::node::NodeBuildError::ExtMintFailed {
detail: "ext backend unavailable".into(),
});
}
Ok(())
}
}
let st = state_with(rules::<MintFailLang>());
let content = "{a}";
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = StdTokenReader::new(&source);
let error =
try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
.unwrap_err();
assert_eq!(error.identifier(), "core.hooks.hook-failed");
assert_eq!(
error.data().downcast_ref::<crate::error::HookFailed>().map(|c| c.detail.as_str()),
Some("ext backend unavailable")
);
assert_eq!(error.frames().len(), 1);
assert_eq!(error.frames()[0].span().range(), 0..1);
}
#[test]
fn error_callable_spec_diagnoses_and_recovers_as_chars() {
use crate::scopes::{CallableDefinedAsError, ErrorCallableSpec};
let mut package: Package<CmdLang> = Package::new("cmds");
package.insert(
CT_MACRO,
"gone",
Arc::new(ErrorCallableSpec::with_detail("removed upstream"))
as Arc<dyn CallableSpec<CmdLang>>,
);
let mut scopes = ScopeStack::new();
scopes.push(Arc::new(package));
let st: Arc<ParsingState<CmdLang>> =
Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));
let parsed =
run_both("a\\gone b", &st, Recovery::Tolerant, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
["chars 0..1 \"a\"", "chars 1..7 \"\\\\gone \"", "chars 7..8 \"b\""]
);
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
let condition =
diagnostic.data().downcast_ref::<CallableDefinedAsError>().unwrap();
assert_eq!(condition.name, "gone");
assert_eq!(condition.detail.as_deref(), Some("removed upstream"));
assert_partition(&parsed.result, 0..8);
let source: Arc<Source> = Arc::new(Source::new("a\\gone b"));
let mut reader = StdTokenReader::new(&source);
let error =
try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
.unwrap_err();
assert_eq!(error.data().identifier(), CallableDefinedAsError::IDENTIFIER);
}
#[derive(Debug, Clone, Copy)]
struct FailingMathLang;
impl Lang for FailingMathLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = FailingMathDriver;
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
struct FailingMathDriver {
recovery: Recovery,
}
impl TestDriver for FailingMathDriver {
fn with_recovery(recovery: Recovery) -> Self {
FailingMathDriver { recovery }
}
}
impl ParseDriver<FailingMathLang> for FailingMathDriver {
fn recovery(&self) -> Recovery {
self.recovery
}
fn group_interior_delta(
&self,
_base: &ParsingState<FailingMathLang>,
rule: &Arc<GroupRule<FailingMathLang>>,
) -> Option<ParsingStateDelta<FailingMathLang>> {
use crate::scopes::ScopeOp;
(rule.group_type == GT_MATH).then(|| {
ParsingStateDelta::new().scope_op(ScopeOp::Unload { name: "absent".into() })
})
}
}
#[test]
fn descent_scope_op_failure_recovers_tolerantly_and_aborts_strictly() {
use crate::constructs::ScopeOpFailed;
let mut math_rules = rules::<FailingMathLang>();
math_rules.groups.rules.push(math_rule());
let st = state_with(math_rules);
let source: Arc<Source> = Arc::new(Source::new("a$m$b"));
let mut reader = StdTokenReader::new(&source);
let parsed = try_run(&source, &mut reader, &st, Recovery::Tolerant, StopSpec::none())
.expect("tolerant parse continues");
assert_eq!(
shapes(&parsed.result),
["chars 0..1 \"a\"", "group 1..4", "chars 4..5 \"b\""]
);
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
let detail = &diagnostic.data().downcast_ref::<ScopeOpFailed>().unwrap().detail;
assert_eq!(
*detail,
crate::scopes::ScopeOpError::UnknownProvider { name: "absent".into() }.to_string()
);
assert_partition(&parsed.result, 0..5);
let source: Arc<Source> = Arc::new(Source::new("a$m$b"));
let mut reader = StdTokenReader::new(&source);
let error = try_run(&source, &mut reader, &st, Recovery::Strict, StopSpec::none())
.unwrap_err();
assert_eq!(error.data().identifier(), ScopeOpFailed::IDENTIFIER);
}
#[derive(Debug, Clone, Copy)]
struct StackSpecialsLang;
impl Lang for StackSpecialsLang {
type Features = crate::state::AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = crate::token::StdTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = crate::engine::StdParseDriver;
fn scan_specials(
state: &ParsingState<Self>,
content: &str,
pos: usize,
) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
state.scopes().scan_specials(state, content, pos)
}
fn specials_trigger_chars(data: &StateData<Self>) -> TriggerChars {
data.scopes.specials_trigger_chars()
}
fn make_node_ext(
_kind: &crate::node::NodeKind<Self>,
_span: &crate::source::SourceSpan<Self::SourceOrigin>,
_state: &alloc::sync::Arc<crate::state::ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
#[test]
fn package_specials_resolve_through_the_stack_fold_end_to_end() {
let inner_short: Arc<dyn CallableSpec<StackSpecialsLang>> =
Arc::new(StdCallableSpec::default());
let outer_short: Arc<dyn CallableSpec<StackSpecialsLang>> =
Arc::new(StdCallableSpec::default());
let outer_long: Arc<dyn CallableSpec<StackSpecialsLang>> =
Arc::new(StdCallableSpec::default());
let mut inner: Package<StackSpecialsLang> = Package::new("inner");
inner.insert_specials(CT_SPECIALS, "--", Arc::clone(&inner_short));
let mut outer: Package<StackSpecialsLang> = Package::new("outer");
outer.insert_specials(CT_SPECIALS, "--", Arc::clone(&outer_short));
outer.insert_specials(CT_SPECIALS, "---", Arc::clone(&outer_long));
let mut scopes = ScopeStack::new();
scopes.push(Arc::new(outer));
scopes.push(Arc::new(inner));
let st: Arc<ParsingState<StackSpecialsLang>> =
Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }));
let parsed =
run_both("x---y--z", &st, Recovery::Strict, StopSpec::none(), StopSpec::none());
assert_eq!(
shapes(&parsed.result),
[
"chars 0..1 \"x\"",
"callable 1..4",
"chars 4..5 \"y\"",
"callable 5..7",
"chars 7..8 \"z\""
]
);
let long = parsed.result.tree.root().child(1).unwrap();
assert_eq!(long.name(), Some("---"));
assert_eq!(long.callable_type(), Some(CT_SPECIALS));
assert!(Arc::ptr_eq(&long.callable().unwrap().spec, &outer_long));
let short = parsed.result.tree.root().child(3).unwrap();
assert_eq!(short.name(), Some("--"));
assert!(Arc::ptr_eq(&short.callable().unwrap().spec, &inner_short));
assert!(parsed.result.diagnostics.is_empty());
assert_partition(&parsed.result, 0..8);
}
impl TestDriver for StdParseDriver<ScopesCommandResolver<RelaxedStdLang>> {
fn with_recovery(recovery: Recovery) -> Self {
relaxed_driver(recovery)
}
}
const _: () = assert!(CT_MACRO == RELAXED_MACRO);
fn span_tiling_macros<L>() -> Arc<Package<L>>
where
L: crate::state::LangHasGroups<CallableTypeId = u32, GroupTypeId = u32> + 'static,
crate::node::ArgumentExt<L>: Default,
L::InvocationSyntax: FromInvocation<L>,
{
let mut lib = Package::new("span-tiling-macros");
lib.insert(CT_MACRO, "foo", Arc::new(StdCallableSpec::default()));
lib.insert(
CT_MACRO,
"arg",
Arc::new(StdCallableSpec::new([ArgumentSpec::new_unnamed(Arc::new(
GroupArgumentParser::new(GT_BRACE),
))])),
);
lib.insert(
CT_MACRO,
"opt",
Arc::new(StdCallableSpec::new([ArgumentSpec::new_unnamed(Arc::new(
MarkerArgumentParser::new("**"),
))])),
);
Arc::new(lib)
}
fn span_tiling_state<L>() -> Arc<ParsingState<L>>
where
L: crate::state::LangHasGroups<
CallableTypeId = u32,
GroupTypeId = u32,
Features = crate::state::AllLangFeatures,
ModeId = (),
StateExt = (),
> + 'static,
crate::node::ArgumentExt<L>: Default,
L::InvocationSyntax: FromInvocation<L>,
{
let mut scopes = ScopeStack::new();
scopes.push(span_tiling_macros::<L>());
Arc::new(ParsingState::new(StateData { rules: rules(), scopes, mode: (), ext: () }))
}
fn chars_representations<L: Lang>(result: &ParseResult<L>) -> Vec<&'static str> {
result
.tree
.iter_storage_order()
.filter_map(|node| match node.kind() {
NodeKind::Chars { content: TextContent::Spanned(_), .. } => Some("spanned"),
NodeKind::Chars { content: TextContent::Owned(_), .. } => Some("owned"),
_ => None,
})
.collect()
}
const SPAN_TILING_INPUT: &str = "a b{c d}%note\n\ne \\foo f \\arg{g} h";
#[test]
fn a_language_that_does_not_obey_span_tiling_parses_the_same_tree() {
let tiled = run_both::<CmdLang>(
SPAN_TILING_INPUT,
&span_tiling_state(),
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
);
let relaxed = run_both::<RelaxedStdLang>(
SPAN_TILING_INPUT,
&span_tiling_state(),
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
);
assert_eq!(shapes(&tiled.result), shapes(&relaxed.result));
assert_eq!(
shapes(&relaxed.result),
[
"chars 0..3 \"a b\"",
"group 3..8",
"comment 8..13 start=\"%\" content=\"note\" post=\"\"",
"chars 13..15 \"\\n\\n\"",
"chars 15..17 \"e \"",
"callable 17..22",
"chars 22..24 \"f \"",
"callable 24..31",
"chars 31..33 \" h\"",
]
);
assert_eq!(
tiled.result.tree.node_count(),
relaxed.result.tree.node_count(),
"the two trees differ in node count"
);
assert!(chars_representations(&tiled.result).iter().all(|it| *it == "spanned"));
assert_eq!(
chars_representations(&relaxed.result),
["owned", "spanned", "owned", "owned", "owned", "owned", "owned"]
);
crate::node::validate_tree(&tiled.result.tree).expect("the all-trees law holds");
crate::node::validate_tree(&relaxed.result.tree).expect("the all-trees law holds");
}
#[test]
fn a_relaxed_chars_run_owns_the_text_the_reader_answered() {
let parsed = run_both::<RelaxedStdLang>(
" hi there ",
&span_tiling_state(),
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
);
let node = parsed.result.tree.root().child(0).unwrap();
assert_eq!(node.chars(), Some(" hi there "));
assert!(matches!(
node.kind(),
NodeKind::Chars { content: TextContent::Owned(_), .. }
));
assert_eq!(node.span().range(), 0..11);
}
struct SlippingReader<'s, L: Lang> {
inner: StdTokenReader<'s>,
lang: core::marker::PhantomData<L>,
}
impl<'s, L> SlippingReader<'s, L>
where
L: Lang<SourceOrigin = Option<String>>,
L::Tokenization:
Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
{
fn new(source: &'s Arc<Source>) -> SlippingReader<'s, L> {
SlippingReader {
inner: StdTokenReader::new(source),
lang: core::marker::PhantomData,
}
}
fn inner(&self) -> &dyn TokenReader<'s, L> {
&self.inner
}
fn inner_mut(&mut self) -> &mut dyn TokenReader<'s, L> {
&mut self.inner
}
}
impl<'s, L> TokenReader<'s, L> for SlippingReader<'s, L>
where
L: Lang<SourceOrigin = Option<String>>,
L::Tokenization:
Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
{
fn peek(
&mut self,
state: &Arc<ParsingState<L>>,
) -> TokenResult<L, StdToken<L>> {
TokenReader::peek(&mut self.inner, state)
}
fn move_to(&mut self, tok: &StdToken<L>, edge: TokenEdge) {
self.inner_mut().move_to(tok, edge);
}
fn move_to_position(&mut self, at: &StdStreamPosition) {
self.inner_mut().move_to_position(at);
}
fn token_kind<'t>(&self, tok: &'t StdToken<L>) -> TokenKind<'t, L>
where
's: 't,
{
self.inner().token_kind(tok)
}
fn source_span_between(
&self,
tok: &StdToken<L>,
a: TokenEdge,
b: TokenEdge,
) -> SourceSpan {
self.inner().source_span_between(tok, a, b)
}
fn position_here(&self) -> StdStreamPosition {
self.inner().position_here()
}
fn position_at(&self, tok: &StdToken<L>, edge: TokenEdge) -> StdStreamPosition {
let at = self.inner().position_at(tok, edge);
match edge {
TokenEdge::StartBeforePreSpace => StdStreamPosition::at(at.offset() + 1),
_ => at,
}
}
fn source_position_at(&self, at: &StdStreamPosition) -> SourcePos {
self.inner().source_position_at(at)
}
fn source_span_within(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> Option<SourceSpan> {
self.inner().source_span_within(begin, end)
}
fn source_span_describing(
&self,
begin: &StdStreamPosition,
end: &StdStreamPosition,
) -> SourceSpan {
self.inner().source_span_describing(begin, end)
}
}
#[test]
fn a_token_not_starting_where_it_was_peeked_is_an_implementation_error() {
fn detail_of(error: &ParseError) -> String {
error
.data()
.downcast_ref::<crate::constructs::ImplementationError>()
.expect("an ImplementationError condition")
.detail
.to_string()
}
let source: Arc<Source> = Arc::new(Source::new("ab"));
let mut tiled = SlippingReader::<CmdLang>::new(&source);
let error = try_run(
&source,
&mut tiled,
&span_tiling_state::<CmdLang>(),
Recovery::Strict,
StopSpec::none(),
)
.expect_err("the reader breaks clause 7");
assert_eq!(
error
.data()
.downcast_ref::<crate::constructs::ImplementationError>()
.expect("an ImplementationError condition")
.kind,
ImplementationErrorKind::TokenPositionMismatch,
);
let detail = detail_of(&error);
let span = error.span().range();
let mut relaxed = SlippingReader::<RelaxedStdLang>::new(&source);
let error = try_run(
&source,
&mut relaxed,
&span_tiling_state::<RelaxedStdLang>(),
Recovery::Strict,
StopSpec::none(),
)
.expect_err("the reader breaks clause 7 whatever the language declares");
assert_eq!(detail_of(&error), detail);
assert_eq!(error.span().range(), span);
}
#[test]
fn a_marker_argument_owns_its_text_where_the_language_does_not_obey_span_tiling() {
fn marker_node<L: Lang>(result: &ParseResult<L>) -> crate::node::NodeRef<'_, L> {
let call = result.tree.root().child(0).expect("the callable");
let region: Vec<_> =
call.argument_nodes(0).expect("provided argument").iter().collect();
*region.last().expect("the marker node ends the region")
}
let tiled = run_both::<CmdLang>(
"\\opt** x",
&span_tiling_state(),
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
);
let relaxed = run_both::<RelaxedStdLang>(
"\\opt** x",
&span_tiling_state(),
Recovery::Strict,
StopSpec::none(),
StopSpec::none(),
);
assert_eq!(shapes(&tiled.result), shapes(&relaxed.result));
let tiled_marker = marker_node(&tiled.result);
assert_eq!(tiled_marker.chars(), Some("**"));
assert!(matches!(
tiled_marker.kind(),
NodeKind::Chars { content: TextContent::Spanned(_), .. }
));
let relaxed_marker = marker_node(&relaxed.result);
assert_eq!(relaxed_marker.chars(), Some("**"));
assert!(
matches!(
relaxed_marker.kind(),
NodeKind::Chars { content: TextContent::Owned(_), .. }
),
"a relaxed parse records the marker as text, got {:?}",
relaxed_marker.kind()
);
assert_eq!(tiled_marker.span().range(), relaxed_marker.span().range());
}
}