mod argument_parsers;
mod attached_source;
mod chars_group_parser;
mod child_state;
#[cfg(test)]
mod content_reader_tests;
mod embellishments_parser;
mod environment_parser;
mod group_parser;
mod invocation_parser;
mod nodes_parser;
mod root_parser;
#[cfg(test)]
mod span_tiling_tests;
mod tack_on_parser;
mod terminated_parser;
mod verbatim_parser;
pub use argument_parsers::{
marker_scan_state_delta, peek_adjacent_argument, scan_argument_noise, stage_pre_space,
ArgumentNoise, ExpectedExpressionArgument,
ExpressionParser, GroupArgumentParser, MarkerArgumentParser, MissingMandatoryArgument,
OptionalGroupArgumentParser,
};
pub use attached_source::{
AttachedSourceOutcome, InvalidReferenceReason, InvalidSourceReferenceArgument,
NoSourceResolver, UnresolvableSourceReference,
};
pub use chars_group_parser::CharsGroupArgumentParser;
pub use child_state::{ChildStateSpec, GroupChildState, InvocationChildState};
pub use embellishments_parser::EmbellishmentsArgumentParser;
pub use tack_on_parser::{RepeatedTackOnField, TackOnFieldsArgumentParser};
pub use environment_parser::{
read_rigid_name_group, EnvironmentBeginSyntaxData, EnvironmentBody,
EnvironmentBodyParser, EnvironmentTerminatorMismatch,
EnvironmentTerminatorSyntaxData, MalformedEnvironmentTerminator,
MissingEnvironmentTerminator, MissingTerminatorFound, NameGroup,
};
pub use group_parser::{
GroupAfterEffectsFn, GroupParser, UnclosedGroup, UnclosedGroupFound,
};
pub use invocation_parser::{parse_declared_arguments, StdInvocationParser};
pub use nodes_parser::{
CommandResolutionFailed, ExpressionCallableRequiresContent, NodesOutcome, NodesParser,
StopCause, StopSpec, StrayGroupClose, TokenStopCondition, TokenStopKind,
UnresolvableCommand, UnusableRecoveryToken, UnusableRecoveryTokenKind,
};
pub use root_parser::RootNodesParser;
pub use terminated_parser::{
ExpectedArgumentOpener, MissingArgumentTerminator, TerminatedArgumentParser,
};
pub use verbatim_parser::{
verbatim_state_delta, ExpectedVerbatimDelimiter, UnterminatedVerbatim,
VerbatimArgumentParser, VerbatimBodyParser, VerbatimBodyTerminator,
};
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use alloc::sync::Arc;
use core::fmt;
use crate::engine::{Frame, FrameTitle, ParseDriver, ParserSession, SessionDeriveError};
use crate::error::{Diagnostic, DiagnosticData, DiagnosticInfo, HookFailed, ParseError, Severity};
use crate::source::{SourceSpan, TextContent};
use crate::spec::{CallableSpec, FrameRole};
use crate::node::{
BuildId, CallableData, ContentNodes, NodeBuildError, NodeKind, NodeTree, NodeTreeBuilder,
ParsedArgument, ParsedArguments, ParsedSlots, StagedNodeView, StagedNodes,
};
use crate::state::{FeaturePresence, Lang, LangFeatures, ParsingState, ParsingStateDelta};
use crate::token::{GroupRule, StreamPosition, Token, TokenEdge, TokenReader};
pub(crate) fn invocation_frame<L: Lang>(
cx: &ParseContext<'_, '_, L>,
invocation: &Invocation<'_, L>,
) -> Frame<L> {
let token = invocation.token;
Frame {
title: FrameTitle::Callable {
spec: Arc::clone(invocation.spec),
role: FrameRole::Invocation,
name: cx.tokens.source_span_between(token, TokenEdge::Start, TokenEdge::End),
},
span: cx.tokens.source_span_of(token),
}
}
pub(crate) fn node_text_content<O: crate::source::SourceOrigin>(
fact: &SourceSpan<O>,
node_span: &SourceSpan<O>,
) -> TextContent {
match fact.same_source(node_span) {
true => TextContent::Spanned(fact.span()),
false => TextContent::Owned(fact.content().into()),
}
}
pub(crate) fn push_pre_space_text<L: Lang>(
text: &mut Option<String>,
cx: &ParseContext<'_, '_, L>,
token: &Token<L>,
) {
let Some(text) = text else { return };
text.push_str(
cx.tokens
.source_span_between(token, TokenEdge::StartBeforePreSpace, TokenEdge::Start)
.content(),
);
}
pub(crate) fn push_token_text<L: Lang>(
text: &mut Option<String>,
cx: &ParseContext<'_, '_, L>,
token: &Token<L>,
spelling: &str,
) {
push_pre_space_text(text, cx, token);
let Some(text) = text else { return };
text.push_str(spelling);
text.push_str(
cx.tokens
.source_span_between(token, TokenEdge::End, TokenEdge::EndPastPostSpace)
.content(),
);
}
pub(crate) fn comment_node_kind<L: Lang>(
cx: &ParseContext<'_, '_, L>,
token: &Token<L>,
) -> (NodeKind<L>, SourceSpan<L::SourceOrigin>) {
let span = cx.tokens.source_span_of(token);
let between = |a, b| cx.tokens.source_span_between(token, a, b);
let kind = NodeKind::comment(
node_text_content(&between(TokenEdge::Start, TokenEdge::ContentStart), &span),
node_text_content(&between(TokenEdge::ContentStart, TokenEdge::End), &span),
node_text_content(&between(TokenEdge::End, TokenEdge::EndPastPostSpace), &span),
);
(kind, span)
}
pub struct ParseContext<'a, 's, L: Lang> {
pub tokens: &'a mut dyn TokenReader<'s, L>,
pub state: Arc<ParsingState<L>>,
pub session: &'a mut ParserSession<L>,
pub driver: &'a L::Driver,
}
impl<'a, 's, L: Lang> ParseContext<'a, 's, L> {
pub fn new(
tokens: &'a mut dyn TokenReader<'s, L>,
state: Arc<ParsingState<L>>,
session: &'a mut ParserSession<L>,
driver: &'a L::Driver,
) -> ParseContext<'a, 's, L> {
ParseContext { tokens, state, session, driver }
}
pub fn here(&self) -> SourceSpan<L::SourceOrigin> {
SourceSpan::at(&self.tokens.source_position_at(&self.tokens.position_here()))
}
pub fn source_span_within(
&self,
begin: &StreamPosition<L>,
end: &StreamPosition<L>,
) -> ConstructParserResult<L, SourceSpan<L::SourceOrigin>> {
if !L::OBEYS_SPAN_TILING {
return Ok(self.tokens.source_span_describing(begin, end));
}
match self.tokens.source_span_within(begin, end) {
Some(span) => Ok(span),
None => Err(self.implementation_error(
format!(
"the positions {begin:?} and {end:?} do not delimit one range of \
one source (a span must run forward within a single source)"
),
self.here(),
)),
}
}
pub fn stage_node(
&mut self,
kind: NodeKind<L>,
span: SourceSpan<L::SourceOrigin>,
state: Arc<ParsingState<L>>,
children: Vec<BuildId>,
) -> Result<BuildId, NodeBuildError> {
let ext = L::make_node_ext(
&kind,
&span,
&state,
self.session.builder.staged_children(&children),
)?;
self.session.builder.add(kind, span, state, children, ext, ())
}
pub fn staged_nodes(&self) -> StagedNodes<'_, L> {
self.session.builder.staged_nodes()
}
pub fn content_as_tree(
&self,
region_nodes: &[BuildId],
content: &ContentNodes,
) -> Result<NodeTree<L, Option<BuildId>>, NodeBuildError> {
let (nodes, parent) = self.resolve_content_nodes(region_nodes, content)?;
let staged = self.staged_nodes();
let mut builder: NodeTreeBuilder<L, Option<BuildId>> = NodeTreeBuilder::new();
let mut children = Vec::with_capacity(nodes.len());
for id in nodes {
children.push(staged.copy_subtree_into(*id, &mut builder, &mut |view| {
Some(view.id())
})?);
}
let (span, state) = self.content_root_provenance(nodes, parent)?;
let kind = NodeKind::list();
let ext = L::make_node_ext(&kind, &span, &state, builder.staged_children(&children))?;
let root = builder.add(kind, span, state, children, ext, None)?;
builder.finish(root)
}
pub fn argument_content_as_tree(
&self,
argument: &ParsedArgument<L>,
children: &[BuildId],
) -> Result<Option<NodeTree<L, Option<BuildId>>>, NodeBuildError> {
let Some((region_nodes, content)) = self.argument_designation(argument, children)? else {
return Ok(None);
};
self.content_as_tree(region_nodes, content).map(Some)
}
pub fn content_as_plain_chars(
&self,
region_nodes: &[BuildId],
content: &ContentNodes,
) -> Result<String, PlainCharsError> {
let (nodes, _) = self.resolve_content_nodes(region_nodes, content)?;
let staged = self.staged_nodes();
let mut text = String::new();
for id in nodes {
let view =
staged.get(*id).ok_or(NodeBuildError::ChildNotStaged { child: *id })?;
match view.kind() {
NodeKind::Chars { content: chars, .. } => {
text.push_str(chars.resolve(view.span().source()))
}
_ => return Err(PlainCharsError::NotPlainCharacters { node: *id }),
}
}
Ok(text)
}
pub fn argument_content_as_plain_chars(
&self,
argument: &ParsedArgument<L>,
children: &[BuildId],
) -> Result<Option<String>, PlainCharsError> {
let Some((region_nodes, content)) = self.argument_designation(argument, children)? else {
return Ok(None);
};
self.content_as_plain_chars(region_nodes, content).map(Some)
}
fn argument_designation<'c>(
&self,
argument: &'c ParsedArgument<L>,
children: &'c [BuildId],
) -> Result<Option<(&'c [BuildId], &'c ContentNodes)>, NodeBuildError> {
let Some(region) = argument.region.as_ref() else {
return Ok(None);
};
let Some((offsets, content)) = region.staged() else {
return Err(NodeBuildError::RegionAlreadyResolved);
};
let region_nodes = children
.get(offsets.start as usize..offsets.end as usize)
.ok_or_else(|| NodeBuildError::RegionOutOfBounds {
region: offsets.clone(),
n_children: children.len() as u32,
})?;
Ok(Some((region_nodes, content)))
}
fn resolve_content_nodes<'c>(
&'c self,
region_nodes: &'c [BuildId],
content: &ContentNodes,
) -> Result<(&'c [BuildId], Option<StagedNodeView<'c, L>>), NodeBuildError> {
match content {
ContentNodes::InRegion(range) => {
let nodes = region_nodes
.get(range.start as usize..range.end as usize)
.ok_or_else(|| NodeBuildError::ContentOutOfBounds {
content: range.clone(),
available: region_nodes.len() as u32,
})?;
Ok((nodes, None))
}
ContentNodes::InChildrenOf(parent, range) => {
let view = self
.staged_nodes()
.get(*parent)
.ok_or(NodeBuildError::ContentParentNotStaged { parent: *parent })?;
let nodes = view
.children()
.get(range.start as usize..range.end as usize)
.ok_or_else(|| NodeBuildError::ContentOutOfBounds {
content: range.clone(),
available: view.children().len() as u32,
})?;
Ok((nodes, Some(view)))
}
}
}
#[allow(clippy::type_complexity)]
fn content_root_provenance(
&self,
nodes: &[BuildId],
parent: Option<StagedNodeView<'_, L>>,
) -> Result<(SourceSpan<L::SourceOrigin>, Arc<ParsingState<L>>), NodeBuildError> {
let staged = self.staged_nodes();
match (nodes.first(), nodes.last()) {
(Some(first), Some(last)) => {
let first =
staged.get(*first).ok_or(NodeBuildError::ChildNotStaged { child: *first })?;
let last =
staged.get(*last).ok_or(NodeBuildError::ChildNotStaged { child: *last })?;
let (from, to) = (first.span(), last.span());
let span = if from.same_source(to)
&& from.start() <= to.start()
&& from.end() <= to.end()
{
SourceSpan::new(from.source(), from.start()..to.end())
} else {
match parent {
Some(parent) => parent.span().clone(),
None => from.clone(),
}
};
Ok((span, first.parsing_state().clone()))
}
_ => match parent {
Some(parent) => Ok((parent.span().clone(), parent.parsing_state().clone())),
None => Ok((self.here(), Arc::clone(&self.state))),
},
}
}
pub fn stage_invocation(
&mut self,
invocation: &Invocation<'_, L>,
arguments: ParsedArguments<L>,
slots: ParsedSlots<L>,
children: Vec<BuildId>,
end: Option<&StreamPosition<L>>,
) -> ConstructParserResult<L, BuildId>
where
L::InvocationSyntax: FromInvocation<L>,
{
let token = invocation.token;
let trigger = self.tokens.source_span_of(token);
let trigger_start = self.tokens.position_at(token, TokenEdge::Start);
let span = match end {
Some(end) => self.invocation_span_within(&trigger, &trigger_start, end)?,
None if !L::OBEYS_SPAN_TILING => {
let here = self.tokens.position_here();
self.invocation_span_within(&trigger, &trigger_start, &here)?
}
None => {
let child_end = children
.last()
.and_then(|last| self.staged_nodes().get(*last))
.map(|child| child.span().clone())
.filter(|child| child.same_source(&trigger))
.map(|child| child.end());
match child_end {
Some(child_end) => {
if child_end < trigger.start() {
return Err(self.invalid_invocation_span(&trigger));
}
SourceSpan::new(trigger.source(), trigger.start()..child_end)
}
None => {
let here = self.tokens.position_here();
self.invocation_span_within(&trigger, &trigger_start, &here)?
}
}
}
};
let data = CallableData {
callable_type: invocation.callable_type,
name: invocation.name.into(),
spec: Arc::clone(invocation.spec),
arguments,
slots,
invocation_syntax: L::InvocationSyntax::from_invocation(invocation, &*self.tokens),
};
self.stage_node(
NodeKind::callable(data),
span.clone(),
Arc::clone(&self.state),
children,
)
.map_err(|error| self.staging_error(error, span))
}
fn invocation_span_within(
&self,
trigger: &SourceSpan<L::SourceOrigin>,
begin: &StreamPosition<L>,
end: &StreamPosition<L>,
) -> ConstructParserResult<L, SourceSpan<L::SourceOrigin>> {
if !L::OBEYS_SPAN_TILING {
return Ok(self.tokens.source_span_describing(begin, end));
}
match self.tokens.source_span_within(begin, end) {
Some(span) => Ok(span),
None => Err(self.invalid_invocation_span(trigger)),
}
}
fn invalid_invocation_span(
&self,
trigger: &SourceSpan<L::SourceOrigin>,
) -> ParseError<L::SourceOrigin> {
self.implementation_error(
"stage_invocation computed an invalid node span: the node's end must \
not precede the trigger's start and must lie in the trigger's own \
source — check the explicit end position or the staged children's \
spans",
trigger.clone(),
)
}
pub fn probe_token(
&mut self,
state: &Arc<ParsingState<L>>,
) -> ConstructParserResult<L, Option<Token<L>>> {
self.driver.probe_token(self.tokens, self.session, state)
}
#[allow(clippy::type_complexity)]
pub fn parse_construct<P>(
&mut self,
parser: &mut P,
state: Option<Arc<ParsingState<L>>>,
frame: Option<Frame<L>>,
) -> ConstructParserResult<L, (P::Output, Option<Box<ParsingStateDelta<L>>>)>
where
P: ConstructParser<L> + ?Sized,
{
let state = match state {
Some(state) => state,
None => Arc::clone(&self.state),
};
let framed = frame.is_some();
if let Some(frame) = frame {
self.session.push_frame(frame);
}
match self.session.enter_descent() {
Ok(None) => {}
Ok(Some(warning)) => {
let span = self.here();
let frames = self.session.snapshot_frames();
self.session.diagnostics.push(Diagnostic::from_parts(
Severity::Warning,
Box::new(DescentLimitApproaching::new(warning.detail)),
span,
frames,
));
}
Err(refusal) => {
let error = ParseError::new(
DescentLimitExceeded::new(refusal.detail),
self.here(),
)
.with_frames(self.session.snapshot_frames());
if framed {
self.session.pop_frame();
}
return Err(error);
}
}
let result = self.with_parsing_state(state, |cx| parser.parse(cx));
self.session.exit_descent();
if framed {
self.session.pop_frame();
}
result
}
pub fn with_parsing_state<R>(
&mut self,
state: Arc<ParsingState<L>>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.session.push_state(Arc::clone(&state));
let outer = core::mem::replace(&mut self.state, state);
let result = f(self);
self.state = outer;
self.session.pop_state();
result
}
pub fn recover(
&mut self,
condition: impl DiagnosticInfo,
span: SourceSpan<L::SourceOrigin>,
) -> Result<(), ParseError<L::SourceOrigin>> {
self.recover_boxed(Box::new(condition), span)
}
pub fn attach_hook_frames(
&self,
error: ParseError<L::SourceOrigin>,
) -> ParseError<L::SourceOrigin> {
if error.frames().is_empty() {
error.with_frames(self.session.snapshot_frames())
} else {
error
}
}
pub(crate) fn recover_boxed(
&mut self,
data: Box<dyn DiagnosticData>,
span: SourceSpan<L::SourceOrigin>,
) -> Result<(), ParseError<L::SourceOrigin>> {
self.driver.recover(self.session, &self.state, data, span)
}
pub fn derive_state(
&mut self,
delta: &ParsingStateDelta<L>,
) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
let base = Arc::clone(&self.state);
let effective;
let delta = if delta.events.is_empty() {
delta
} else {
effective = self.lower_state_events(delta)?;
&effective
};
self.commit_derivation(&base, delta)
}
pub(crate) fn derive_state_recording(
&mut self,
delta: &ParsingStateDelta<L>,
record: &mut Option<Box<ParsingStateDelta<L>>>,
) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
let base = Arc::clone(&self.state);
let effective;
let applied = if delta.events.is_empty() {
delta
} else {
effective = self.lower_state_events(delta)?;
&effective
};
let new = self.commit_derivation(&base, applied)?;
match record {
Some(record) => record.merge_from(applied.clone()),
None => *record = Some(Box::new(applied.clone())),
}
Ok(new)
}
fn commit_derivation(
&mut self,
base: &Arc<ParsingState<L>>,
applied: &ParsingStateDelta<L>,
) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
match self.session.derived_state(self.driver, base, applied) {
Ok(new) => Ok(new),
Err(SessionDeriveError::Derive(failure)) => {
self.recover_derive_failure(base, failure)
}
Err(SessionDeriveError::Observe(error)) => Err(self.attach_hook_frames(error)),
}
}
pub fn with_derived_state<R>(
&mut self,
delta: &ParsingStateDelta<L>,
f: impl FnOnce(&mut Self) -> R,
) -> ConstructParserResult<L, R> {
let state = self.derive_state(delta)?;
Ok(self.with_parsing_state(state, f))
}
fn lower_state_events(
&mut self,
delta: &ParsingStateDelta<L>,
) -> ConstructParserResult<L, ParsingStateDelta<L>> {
let lent = match self.session.state_stack().innermost() {
Some(innermost) => !Arc::ptr_eq(innermost, &self.state),
None => true,
};
if lent {
self.session.push_state(Arc::clone(&self.state));
}
let mut patches: Vec<ParsingStateDelta<L>> = Vec::new();
let mut kept_events: Vec<L::Event> = Vec::new();
let mut abort: Option<ParseError<L::SourceOrigin>> = None;
for event in &delta.events {
match self.driver.resolve_state_event(event, self.session.state_stack()) {
Ok(Some(patch)) => patches.push(patch),
Ok(None) => kept_events.push(event.clone()),
Err(error) => {
abort = Some(error);
break;
}
}
}
if lent {
self.session.pop_state();
}
if let Some(error) = abort {
return Err(self.attach_hook_frames(error));
}
let mut effective = ParsingStateDelta::new();
for patch in patches {
effective.rules.merge_from(patch.rules);
if let (Some(ops), Some(patch_ops)) = (
<L::Features as LangFeatures>::Scopes::store_get_mut(&mut effective.scope_ops),
<L::Features as LangFeatures>::Scopes::store_into_inner(patch.scope_ops),
) {
ops.extend(patch_ops);
}
if patch.mode.is_some() {
effective.mode = patch.mode;
}
if patch.ext.is_some() {
effective.ext = patch.ext;
}
effective.events.extend(patch.events);
}
effective.rules.merge_from(delta.rules.clone());
if let (Some(ops), Some(delta_ops)) = (
<L::Features as LangFeatures>::Scopes::store_get_mut(&mut effective.scope_ops),
<L::Features as LangFeatures>::Scopes::store_get(&delta.scope_ops),
) {
ops.extend(delta_ops.iter().cloned());
}
if delta.mode.is_some() {
effective.mode = delta.mode;
}
if delta.ext.is_some() {
effective.ext = delta.ext.clone();
}
effective.events.extend(kept_events);
Ok(effective)
}
pub fn group_interior_state(
&mut self,
rule: &Arc<GroupRule<L>>,
) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
let base = Arc::clone(&self.state);
match self.session.group_interior_state(self.driver, &base, rule) {
Ok(new) => Ok(new),
Err(SessionDeriveError::Derive(failure)) => {
self.recover_derive_failure(&base, failure)
}
Err(SessionDeriveError::Observe(error)) => Err(self.attach_hook_frames(error)),
}
}
fn recover_derive_failure(
&mut self,
base: &Arc<ParsingState<L>>,
failure: crate::state::DeriveError<L>,
) -> ConstructParserResult<L, Arc<ParsingState<L>>> {
let span = self.here();
let crate::state::DeriveError {
failures,
finalize_error,
recovered,
delta,
} = failure;
for failed_op in &failures {
self.recover(ScopeOpFailed::new(failed_op.to_string()), span.clone())?;
}
if let Some(finalize_error) = finalize_error {
return Err(self.implementation_error(finalize_error, span));
}
let recovered = Arc::new(recovered);
self.driver
.observe_transition(
&mut self.session.ext,
&mut self.session.diagnostics,
base,
&recovered,
&delta,
)
.map_err(|error| self.attach_hook_frames(error))?;
Ok(recovered)
}
#[allow(clippy::type_complexity)]
pub fn parse_nodes<'p>(
&mut self,
state: Arc<ParsingState<L>>,
stop: StopSpec<'p, L>,
child_states: ChildStateSpec<'p, L>,
) -> ConstructParserResult<L, (NodesOutcome<L>, Option<Box<ParsingStateDelta<L>>>)>
where
'a: 'p,
L::InvocationSyntax: FromInvocation<L>,
{
let driver = self.driver;
let mut parser = driver
.make_nodes_parser(stop, child_states)
.map_err(|error| self.attach_hook_frames(error))?;
self.parse_construct(&mut *parser, Some(state), None)
}
#[allow(clippy::type_complexity)]
pub fn parse_group<'p>(
&mut self,
base: Arc<ParsingState<L>>,
open: &Token<L>,
rule: Arc<GroupRule<L>>,
child_states: ChildStateSpec<'p, L>,
frame: Option<Frame<L>>,
) -> ConstructParserResult<L, (BuildId, Option<Box<ParsingStateDelta<L>>>)>
where
'a: 'p,
L::InvocationSyntax: FromInvocation<L>,
{
let driver = self.driver;
let mut parser = driver
.make_group_parser(open, rule, child_states)
.map_err(|error| self.attach_hook_frames(error))?;
self.parse_construct(&mut *parser, Some(base), frame)
}
pub fn with_frame<R>(&mut self, frame: Frame<L>, f: impl FnOnce(&mut Self) -> R) -> R {
self.session.push_frame(frame);
let result = f(self);
self.session.pop_frame();
result
}
pub fn implementation_error(
&self,
detail: impl fmt::Display,
span: SourceSpan<L::SourceOrigin>,
) -> ParseError<L::SourceOrigin> {
ParseError::new(ImplementationError::new(detail.to_string()), span)
.with_frames(self.session.snapshot_frames())
}
pub(crate) fn staging_error(
&self,
error: NodeBuildError,
span: SourceSpan<L::SourceOrigin>,
) -> ParseError<L::SourceOrigin> {
match error {
NodeBuildError::ExtMintFailed { detail } => {
ParseError::new(HookFailed::new(detail, None), span)
.with_frames(self.session.snapshot_frames())
}
other => self.implementation_error(other, span),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PlainCharsError {
NotPlainCharacters {
node: BuildId,
},
MalformedRecord(NodeBuildError),
}
impl From<NodeBuildError> for PlainCharsError {
fn from(error: NodeBuildError) -> PlainCharsError {
PlainCharsError::MalformedRecord(error)
}
}
impl fmt::Display for PlainCharsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PlainCharsError::NotPlainCharacters { node } => {
write!(f, "the content node {:?} is not plain characters", node)
}
PlainCharsError::MalformedRecord(error) => {
write!(f, "the staged content record does not resolve: {}", error)
}
}
}
}
impl core::error::Error for PlainCharsError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
PlainCharsError::NotPlainCharacters { .. } => None,
PlainCharsError::MalformedRecord(error) => Some(error),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
id = "core.constructs.implementation-error",
message = "implementation error (extension contract violation): {detail}"
)]
pub struct ImplementationError {
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
id = "core.specs.scope-op-failed",
message = "scope op failed: {detail}"
)]
pub struct ScopeOpFailed {
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
id = "core.constructs.descent-limit-exceeded",
message = "the input nests too deeply to parse: {detail}"
)]
pub struct DescentLimitExceeded {
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
id = "core.constructs.descent-limit-approaching",
message = "the input's nesting approaches the parsing depth limit: {detail}"
)]
pub struct DescentLimitApproaching {
pub detail: String,
}
impl<L: Lang> fmt::Debug for ParseContext<'_, '_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ParseContext")
.field("at", &self.here())
.field("state", &self.state)
.field("session", &self.session)
.finish()
}
}
pub type ConstructParserResult<L, T> = Result<T, ParseError<<L as Lang>::SourceOrigin>>;
pub trait ConstructParser<L: Lang> {
type Output;
#[allow(clippy::type_complexity)]
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, L>,
) -> ConstructParserResult<L, (Self::Output, Option<Box<ParsingStateDelta<L>>>)>;
}
pub struct Invocation<'a, L: Lang> {
pub callable_type: L::CallableTypeId,
pub name: &'a str,
pub spec: &'a Arc<dyn CallableSpec<L>>,
pub token: &'a Token<L>,
}
impl<L: Lang> fmt::Debug for Invocation<'_, L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Invocation")
.field("callable_type", &self.callable_type)
.field("name", &self.name)
.field("spec", &self.spec)
.field("token", &self.token)
.finish()
}
}
pub trait FromInvocation<L: Lang>: Sized {
fn from_invocation(
invocation: &Invocation<'_, L>,
tokens: &dyn TokenReader<'_, L>,
) -> Self;
}
impl<L: Lang> FromInvocation<L> for () {
fn from_invocation(_invocation: &Invocation<'_, L>, _tokens: &dyn TokenReader<'_, L>) {}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::source::{Source, Span};
use crate::engine::StdParseDriver;
use crate::error::Recovery;
use crate::scopes::ScopeStack;
use crate::state::{StateData, TrivialLang};
use crate::token::{
CommandRules, CommentRules, ForbiddenCharsRules, GroupRules, ParagraphRules,
SpecialsRules, TokenListReader, TokenRules, WhitespaceRules,
};
use alloc::vec;
#[derive(Debug, Clone, Copy)]
pub(crate) struct PlainLang;
impl TrivialLang for PlainLang {}
pub(crate) fn min_rules<L: Lang<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::new(),
temporary: Vec::new(),
expecting_close: None,
},
commands: CommandRules { enabled: true, rules: Vec::new() },
comments: CommentRules { enabled: true, rules: Vec::new() },
specials: SpecialsRules { enabled: true },
forbidden_chars: ForbiddenCharsRules { chars: "".into() },
}
}
pub(crate) fn state<L>() -> Arc<ParsingState<L>>
where
L: Lang<Features = crate::state::AllLangFeatures, StateExt = ()>,
L::ModeId: Default,
{
Arc::new(ParsingState::new(StateData {
rules: min_rules(),
scopes: ScopeStack::new(),
mode: Default::default(),
ext: (),
}))
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct TestCondition;
impl fmt::Display for TestCondition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "test condition")
}
}
impl crate::error::DiagnosticInfo for TestCondition {
const IDENTIFIER: &'static str = "test.constructs.test-condition";
}
#[derive(Default)]
struct StackProbeParser {
seen_state: Option<Arc<ParsingState<PlainLang>>>,
seen_depth: Option<usize>,
}
impl ConstructParser<PlainLang> for StackProbeParser {
type Output = ();
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, PlainLang>,
) -> ConstructParserResult<PlainLang, ((), Option<Box<ParsingStateDelta<PlainLang>>>)>
{
self.seen_state = Some(Arc::clone(&cx.state));
self.seen_depth = Some(cx.session.state_stack().len());
Ok(((), None))
}
}
struct RecoveringParser;
impl ConstructParser<PlainLang> for RecoveringParser {
type Output = ();
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, PlainLang>,
) -> ConstructParserResult<PlainLang, ((), Option<Box<ParsingStateDelta<PlainLang>>>)>
{
cx.recover(TestCondition, cx.here())?;
Ok(((), None))
}
}
fn with_std_context<R>(
content: &str,
f: impl FnOnce(&mut ParseContext<'_, '_, PlainLang>, &Arc<Source>) -> R,
) -> R {
let source: Arc<Source> = Arc::new(Source::new(content));
let mut reader = crate::token::StdTokenReader::new(&source);
let mut session = ParserSession::new();
let driver = StdParseDriver::new(Recovery::Strict, ());
let mut cx = ParseContext::new(
&mut reader,
state(),
&mut session,
&driver);
f(&mut cx, &source)
}
#[test]
fn here_is_the_empty_span_at_the_reader_position() {
with_std_context("abc", |cx, source| {
let at = cx.here();
assert_eq!(at.range(), 0..0);
assert!(Arc::ptr_eq(at.source(), source));
let token = cx.tokens.peek(&cx.state).unwrap();
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
assert_eq!(cx.here().range(), 1..1);
});
}
#[test]
fn source_span_within_spans_two_positions_and_lifts_an_incoherent_pair() {
with_std_context("abc", |cx, _source| {
let begin = cx.tokens.position_here();
let token = cx.tokens.peek(&cx.state).unwrap();
let end = cx.tokens.position_at(&token, TokenEdge::EndPastPostSpace);
assert_eq!(cx.source_span_within(&begin, &end).unwrap().range(), 0..1);
let error = cx.source_span_within(&end, &begin).unwrap_err();
let condition = error
.data()
.downcast_ref::<ImplementationError>()
.expect("an ImplementationError condition");
assert!(
condition.detail.contains("do not delimit one range of one source"),
"unexpected detail: {}",
condition.detail
);
});
}
const _: () = assert!(PlainLang::OBEYS_SPAN_TILING);
const _: () = assert!(<crate::latexlike::Latexlike as Lang>::OBEYS_SPAN_TILING);
#[derive(Debug, Clone, Copy)]
pub(crate) struct RelaxedStdLang;
impl Lang for RelaxedStdLang {
const OBEYS_SPAN_TILING: bool = false;
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<crate::engine::ScopesCommandResolver<RelaxedStdLang>>;
fn make_node_ext(
_kind: &NodeKind<Self>,
_span: &SourceSpan<Self::SourceOrigin>,
_state: &Arc<ParsingState<Self>>,
_children: crate::node::StagedChildren<'_, Self>,
) -> Result<(), crate::node::NodeBuildError> {
Ok(())
}
}
const _: () = assert!(!RelaxedStdLang::OBEYS_SPAN_TILING);
pub(crate) const RELAXED_MACRO: u32 = 10;
pub(crate) fn relaxed_driver(
recovery: Recovery,
) -> StdParseDriver<crate::engine::ScopesCommandResolver<RelaxedStdLang>> {
StdParseDriver::new(
recovery,
crate::engine::ScopesCommandResolver { command_type: RELAXED_MACRO },
)
}
#[test]
fn a_language_that_does_not_obey_span_tiling_parses_over_the_standard_reader() {
let mut rules = min_rules::<RelaxedStdLang>();
rules.groups.rules = vec![Arc::new(crate::token::GroupRule {
group_type: 0,
open: "{".into(),
close: "}".into(),
})];
let seed = Arc::new(ParsingState::new(StateData {
rules,
scopes: ScopeStack::new(),
mode: (),
ext: (),
}));
let language = crate::engine::Language::new(relaxed_driver(Recovery::Strict), seed);
let parsed = language.parse("a{b}c").expect("the parse runs");
let root = parsed.tree.root();
let kinds: Vec<_> = root
.children()
.iter()
.map(|child| match child.kind() {
NodeKind::Chars { .. } => "chars",
NodeKind::Group(_) => "group",
other => panic!("unexpected node kind: {other:?}"),
})
.collect();
assert_eq!(kinds, ["chars", "group", "chars"]);
crate::node::validate_tree(&parsed.tree).expect("the all-trees law holds");
}
#[test]
fn source_span_within_describes_the_stretch_when_the_language_does_not_obey_tiling() {
let source: Arc<Source> = Arc::new(Source::new("abc"));
let mut reader = crate::token::StdTokenReader::new(&source);
let mut session = ParserSession::new();
let driver = relaxed_driver(Recovery::Strict);
let cx = ParseContext::new(
&mut reader,
state::<RelaxedStdLang>(),
&mut session,
&driver);
let begin = cx.tokens.position_here();
let token = cx.tokens.peek(&cx.state).unwrap();
let end = cx.tokens.position_at(&token, TokenEdge::EndPastPostSpace);
assert_eq!(cx.source_span_within(&begin, &end).unwrap().range(), 0..1);
let described = cx
.source_span_within(&end, &begin)
.expect("no error under OBEYS_SPAN_TILING = false");
assert_eq!(described.range(), 1..1);
}
#[derive(Debug)]
struct TestSpec;
impl crate::serialize::SerializableObject<PlainLang> for TestSpec {}
impl CallableSpec<PlainLang> for TestSpec {}
fn stage_invocation_span(
content: &str,
trigger: usize,
end: EndUnderTest,
children: impl FnOnce(&mut ParseContext<'_, '_, PlainLang>) -> Vec<BuildId>,
) -> Result<core::ops::Range<usize>, ParseError> {
with_std_context(content, |cx, _source| {
let spec: Arc<dyn CallableSpec<PlainLang>> = Arc::new(TestSpec);
for _ in 0..trigger {
let skipped = cx.tokens.peek(&cx.state).unwrap();
cx.tokens.move_to(&skipped, TokenEdge::EndPastPostSpace);
}
let token = cx.tokens.peek(&cx.state).unwrap();
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
let children = children(cx);
let invocation = Invocation {
callable_type: 0u32,
name: "t",
spec: &spec,
token: &token,
};
let end = match end {
EndUnderTest::Standard => None,
EndUnderTest::Here => Some(cx.tokens.position_here()),
EndUnderTest::BeforeTheTrigger => {
Some(cx.tokens.position_at(&token, TokenEdge::StartBeforePreSpace))
}
};
let slots = match children.len() as u32 {
0 => ParsedSlots::empty(),
count => ParsedSlots::new(alloc::vec![crate::node::ParsedSlot::new(
crate::node::ChildRegion::new(
0..count,
crate::node::ContentNodes::InRegion(0..count),
),
"content",
crate::node::SlotRole::Content,
(),
)]),
};
let id = cx.stage_invocation(
&invocation,
ParsedArguments::empty(),
slots,
children,
end.as_ref(),
)?;
Ok(cx.staged_nodes().get(id).unwrap().span().range())
})
}
enum EndUnderTest {
Standard,
Here,
BeforeTheTrigger,
}
fn chars_child(
range: core::ops::Range<usize>,
) -> impl FnOnce(&mut ParseContext<'_, '_, PlainLang>) -> Vec<BuildId> {
move |cx| {
let here = cx.here();
let span = SourceSpan::new(here.source(), range.clone());
let id = cx
.stage_node(
NodeKind::chars(span.span()),
span,
Arc::clone(&cx.state),
Vec::new(),
)
.unwrap();
alloc::vec![id]
}
}
fn foreign_child(
range: core::ops::Range<usize>,
) -> impl FnOnce(&mut ParseContext<'_, '_, PlainLang>) -> Vec<BuildId> {
move |cx| {
let other: Arc<Source> = Arc::new(Source::new("elsewhere"));
let span = SourceSpan::new(&other, range.clone());
let id = cx
.stage_node(
NodeKind::chars(span.span()),
span,
Arc::clone(&cx.state),
Vec::new(),
)
.unwrap();
alloc::vec![id]
}
}
#[test]
fn stage_invocation_ends_at_the_explicit_position() {
let range = stage_invocation_span("abcd", 0, EndUnderTest::Here, |cx| {
for _ in 0..2 {
let token = cx.tokens.peek(&cx.state).unwrap();
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
}
Vec::new()
})
.unwrap();
assert_eq!(range, 0..3);
}
#[test]
fn stage_invocation_ends_at_the_last_child_under_the_standard_rule() {
let range = stage_invocation_span("abcd", 0, EndUnderTest::Standard, chars_child(1..3))
.unwrap();
assert_eq!(range, 0..3);
}
#[test]
fn stage_invocation_ends_at_the_reader_for_a_childless_shape() {
let range =
stage_invocation_span("abcd", 0, EndUnderTest::Standard, |_cx| Vec::new()).unwrap();
assert_eq!(range, 0..1);
}
#[test]
fn stage_invocation_ignores_a_last_child_staged_in_another_source() {
let range =
stage_invocation_span("abcd", 0, EndUnderTest::Standard, foreign_child(3..9))
.unwrap();
assert_eq!(range, 0..1);
}
#[test]
fn stage_invocation_reports_an_end_before_the_trigger_as_an_implementation_error() {
let error =
stage_invocation_span(" abcd", 0, EndUnderTest::BeforeTheTrigger, |_cx| Vec::new())
.unwrap_err();
assert_invalid_node_span(&error);
let error =
stage_invocation_span("abcd", 2, EndUnderTest::Standard, chars_child(0..1))
.unwrap_err();
assert_invalid_node_span(&error);
}
fn assert_invalid_node_span(error: &ParseError) {
let condition = error
.data()
.downcast_ref::<ImplementationError>()
.expect("an ImplementationError condition");
assert!(
condition.detail.contains("invalid node span"),
"unexpected detail: {}",
condition.detail
);
}
#[test]
fn parse_construct_state_none_matches_explicit_current_state_clone() {
let source: Arc<Source> = Arc::new(Source::new("xy"));
let st = state();
let mut reader: TokenListReader<'_, PlainLang> = TokenListReader::new(&source, vec![]);
let mut session = ParserSession::new();
let driver = StdParseDriver::new(Recovery::Tolerant, ());
let mut cx = ParseContext::new(
&mut reader,
Arc::clone(&st),
&mut session,
&driver);
let mut probe = StackProbeParser::default();
cx.parse_construct(&mut probe, None, None).unwrap();
assert!(Arc::ptr_eq(probe.seen_state.as_ref().unwrap(), &st));
let depth_under_none = probe.seen_depth.unwrap();
assert_eq!(depth_under_none, 1);
assert!(Arc::ptr_eq(&cx.state, &st), "outer state restored");
assert_eq!(cx.session.state_stack().len(), 0, "stack entry popped");
let mut probe = StackProbeParser::default();
let explicit = Arc::clone(&cx.state);
cx.parse_construct(&mut probe, Some(explicit), None).unwrap();
assert!(Arc::ptr_eq(probe.seen_state.as_ref().unwrap(), &st));
assert_eq!(probe.seen_depth.unwrap(), depth_under_none);
assert!(Arc::ptr_eq(&cx.state, &st), "outer state restored");
assert_eq!(cx.session.state_stack().len(), 0, "stack entry popped");
}
#[test]
fn parse_construct_frame_reaches_the_diagnostic_snapshot() {
let source: Arc<Source> = Arc::new(Source::new("xy"));
let st = state();
let mut reader: TokenListReader<'_, PlainLang> = TokenListReader::new(&source, vec![]);
let mut session = ParserSession::new();
let driver = StdParseDriver::new(Recovery::Tolerant, ());
let mut cx =
ParseContext::new(&mut reader, st, &mut session, &driver);
let frame = Frame {
title: FrameTitle::Static("construct frame"),
span: SourceSpan::new(&source, Span::new(0, 1)),
};
cx.parse_construct(&mut RecoveringParser, None, Some(frame)).unwrap();
assert!(cx.session.snapshot_frames().is_empty(), "frame popped on return");
let diagnostic = session.diagnostics.iter().next().unwrap();
assert_eq!(diagnostic.frames().len(), 1);
assert_eq!(diagnostic.frames()[0].title(), "construct frame");
assert_eq!(diagnostic.frames()[0].span().range(), 0..1);
}
#[test]
fn parse_construct_pops_the_frame_on_the_err_path() {
let source: Arc<Source> = Arc::new(Source::new("xy"));
let st = state();
let mut reader: TokenListReader<'_, PlainLang> = TokenListReader::new(&source, vec![]);
let mut session = ParserSession::new();
let driver = StdParseDriver::new(Recovery::Strict, ());
let mut cx =
ParseContext::new(&mut reader, st, &mut session, &driver);
let frame = Frame {
title: FrameTitle::Static("construct frame"),
span: SourceSpan::new(&source, Span::new(0, 1)),
};
let err =
cx.parse_construct(&mut RecoveringParser, None, Some(frame)).unwrap_err();
assert!(
cx.session.snapshot_frames().is_empty(),
"frame popped on the Err path"
);
assert_eq!(err.frames().len(), 1);
assert_eq!(err.frames()[0].title(), "construct frame");
}
#[test]
fn attach_hook_frames_adds_the_live_traceback_unless_present() {
let source: Arc<Source> = Arc::new(Source::new("xy"));
let st = state();
let mut reader: TokenListReader<'_, PlainLang> = TokenListReader::new(&source, vec![]);
let mut session = ParserSession::new();
let driver = StdParseDriver::new(Recovery::Strict, ());
let mut cx =
ParseContext::new(&mut reader, st, &mut session, &driver);
let frame = || Frame {
title: FrameTitle::Static("hook frame"),
span: SourceSpan::new(&source, Span::new(0, 1)),
};
let at = SourceSpan::new(&source, Span::new(1, 2));
let attached = cx.with_frame(frame(), |cx| {
cx.attach_hook_frames(ParseError::new(TestCondition, at.clone()))
});
assert_eq!(attached.frames().len(), 1);
assert_eq!(attached.frames()[0].title(), "hook frame");
assert_eq!(attached.span().range(), 1..2, "condition and span are the hook's own");
let preexisting = ParseError::new(TestCondition, at.clone())
.with_frames(vec![crate::error::TraceFrame::new("preexisting", at.clone())]);
let kept = cx.with_frame(frame(), |cx| cx.attach_hook_frames(preexisting));
assert_eq!(kept.frames().len(), 1);
assert_eq!(kept.frames()[0].title(), "preexisting");
}
#[test]
fn hot_path_result_payloads_stay_within_one_cache_line() {
use core::mem::size_of;
type Origin = Option<String>;
let parse_error = size_of::<ParseError<Origin>>();
let predicate = size_of::<Result<bool, ParseError<Origin>>>();
let compute =
size_of::<Result<Arc<ParsingState<PlainLang>>, ParseError<Origin>>>();
assert_eq!(
predicate, parse_error,
"Predicate/StopSpec::node Result outgrew the bare ParseError"
);
assert_eq!(
compute, parse_error,
"Compute-arm Result outgrew the bare ParseError"
);
assert!(parse_error <= 64, "ParseError outgrew one cache line: {parse_error} B");
}
}