use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;
use core::ops::Range;
use crate::engine::{ParseResult, ParserSession, StdParseDriver};
use crate::error::{ParseError, Recovery};
use crate::node::{BuildId, NodeBuildError, NodeKind, NodeRef, StagedChildren};
use crate::recompose::{
core_source_instruction, Recompose, RecomposeContext, Recomposer, TreeRecomposer,
};
use crate::scopes::ScopeStack;
use crate::source::{Source, SourceSpan, TextContent};
use crate::spec::ArgumentSpec;
use crate::state::{AllLangFeatures, Lang, ParsingState, StateData};
use crate::token::{
CommandRule, CommandRules, CommentRule, CommentRules, ForbiddenCharsRules, GroupRule,
GroupRules, ParagraphRules, RelaxedLang, ScriptedReader, ScriptedTokenization,
SpecialsRules, TokenEdge, TokenKind, TokenReader, TokenRules, WhitespaceRules,
};
use super::{
ConstructParser, ImplementationError, ImplementationErrorKind, NodesParser,
OptionalGroupArgumentParser, ParseContext, StopCause, StopSpec, TokenStopKind, UnclosedGroup,
UnterminatedVerbatim, VerbatimArgumentParser,
};
#[derive(Debug, Clone, Copy)]
pub(crate) struct TiledScriptedLang;
impl Lang for TiledScriptedLang {
type Features = AllLangFeatures;
type GroupTypeId = u32;
type CallableTypeId = u32;
type ModeId = ();
type StateExt = ();
type Event = ();
type SessionExt = ();
type SourceOrigin = Option<String>;
type Tokenization = ScriptedTokenization;
type NodeExts = ();
type InvocationSyntax = ();
type Driver = StdParseDriver;
fn make_node_ext(
_kind: &NodeKind<Self>,
_span: &SourceSpan<Self::SourceOrigin>,
_state: &Arc<ParsingState<Self>>,
_children: StagedChildren<'_, Self>,
) -> Result<(), NodeBuildError> {
Ok(())
}
}
const _: () = assert!(!RelaxedLang::OBEYS_SPAN_TILING);
const _: () = assert!(TiledScriptedLang::OBEYS_SPAN_TILING);
const GT_BRACE: u32 = 0;
const GT_BRACKET: u32 = 1;
fn script_rules<L>() -> TokenRules<L>
where
L: Lang<Features = AllLangFeatures, GroupTypeId = u32>,
{
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() }),
Arc::new(GroupRule {
group_type: GT_BRACKET,
open: "[".into(),
close: "]".into(),
}),
],
temporary: Vec::new(),
expecting_close: None,
},
commands: CommandRules {
enabled: true,
rules: vec![Arc::new(CommandRule {
escape_char: '\\',
name_chars: "abcdefghijklmnopqrstuvwxyz".into(),
})],
},
comments: CommentRules {
enabled: true,
rules: vec![Arc::new(CommentRule { start: "%".into() })],
},
specials: SpecialsRules { enabled: true },
forbidden_chars: ForbiddenCharsRules { chars: "".into() },
}
}
fn script_state<L>() -> Arc<ParsingState<L>>
where
L: Lang<Features = AllLangFeatures, GroupTypeId = u32, ModeId = (), StateExt = ()>,
{
Arc::new(ParsingState::new(StateData {
rules: script_rules(),
scopes: ScopeStack::new(),
mode: (),
ext: (),
}))
}
fn source(content: &str) -> Arc<Source> {
Arc::new(Source::new(content))
}
type Segment<'s> = (&'s Arc<Source>, Range<usize>);
struct Parsed<L: Lang> {
result: ParseResult<L>,
stop: StopCause<L>,
}
impl<L: Lang> Parsed<L> {
fn roots(&self) -> Vec<NodeRef<'_, L>> {
self.result.tree.root().children().iter().collect()
}
}
trait ScriptedTestLang:
Lang<
SourceOrigin = Option<String>,
Tokenization = ScriptedTokenization,
Driver = StdParseDriver,
Features = AllLangFeatures,
GroupTypeId = u32,
ModeId = (),
StateExt = (),
InvocationSyntax = (),
>
{
}
impl ScriptedTestLang for RelaxedLang {}
impl ScriptedTestLang for TiledScriptedLang {}
fn run_nodes<L: ScriptedTestLang>(
segments: &[Segment<'_>],
recovery: Recovery,
stop: StopSpec<'_, L>,
) -> Result<Parsed<L>, ParseError> {
let state = script_state::<L>();
let (result, stop) = with_scripted_parse(&state, segments, recovery, |cx| {
let begin = cx.tokens.position_here();
let mut parser = NodesParser::new(stop);
let (outcome, delta) = parser.parse(cx)?;
assert!(delta.is_none(), "a nodes parser reports no pass-through delta");
let end = cx.tokens.position_here();
let root_span = cx.source_span_within(&begin, &end)?;
Ok((outcome.nodes, root_span, outcome.stop))
})?;
Ok(Parsed { result, stop })
}
fn expect_error<L: Lang>(run: Result<Parsed<L>, ParseError>) -> ParseError {
match run {
Ok(_) => panic!("expected the machinery to reject the stream, but a tree was built"),
Err(error) => error,
}
}
fn with_scripted_parse<L: ScriptedTestLang, S>(
state: &Arc<ParsingState<L>>,
segments: &[Segment<'_>],
recovery: Recovery,
parse: impl FnOnce(
&mut ParseContext<'_, '_, L>,
) -> Result<(Vec<BuildId>, SourceSpan<L::SourceOrigin>, S), ParseError>,
) -> Result<(ParseResult<L>, S), ParseError> {
let mut reader = ScriptedReader::<L>::new(segments, state);
let mut session = ParserSession::new();
let driver = StdParseDriver::new(recovery, ());
let (nodes, root_span, extra) = {
let mut cx = ParseContext::new(&mut reader, Arc::clone(state), &mut session, &driver);
parse(&mut cx)?
};
let kind = NodeKind::list();
let ext = L::make_node_ext(
&kind,
&root_span,
state,
session.builder.staged_children(&nodes),
)
.expect("mint the root's node ext");
let root = session
.builder
.add(kind, root_span, Arc::clone(state), nodes, ext, ())
.expect("stage the root list");
let result = session.finish(root).expect("freeze the tree");
crate::node::validate_tree(&result.tree).expect("the all-trees law holds");
crate::node::check_tree_invariants(&result.tree);
Ok((result, extra))
}
fn implementation_detail(error: &ParseError) -> String {
error
.data()
.downcast_ref::<ImplementationError>()
.expect("an ImplementationError condition")
.detail
.clone()
}
fn implementation_kind(error: &ParseError) -> ImplementationErrorKind {
error
.data()
.downcast_ref::<ImplementationError>()
.expect("an ImplementationError condition")
.kind
}
fn chars_content<'t, L: Lang>(node: &NodeRef<'t, L>) -> &'t TextContent {
match node.kind() {
NodeKind::Chars { content } => content,
other => panic!("expected a chars node, found {other:?}"),
}
}
fn assert_owned_chars<L: Lang>(node: &NodeRef<'_, L>, text: &str) {
match chars_content(node) {
TextContent::Owned(owned) => assert_eq!(&owned[..], text),
other => panic!("expected owned chars content, found {other:?}"),
}
assert_eq!(node.chars(), Some(text));
}
fn assert_spanned_chars<L: Lang>(node: &NodeRef<'_, L>, text: &str) {
match chars_content(node) {
TextContent::Spanned(_) => {}
other => panic!("expected span-backed chars content, found {other:?}"),
}
assert_eq!(node.chars(), Some(text));
}
struct CoreSource;
impl<L: Lang, A> Recomposer<L, A> for CoreSource {
type State = ();
type Piece = String;
type Error = String;
fn recompose_node(
&mut self,
node: NodeRef<'_, L, A>,
_state: &(),
_cx: &mut RecomposeContext<'_, L, A>,
) -> Result<Recompose<String, ()>, String> {
core_source_instruction(node).ok_or_else(|| String::from("a callable node"))
}
}
fn recompose<L: Lang>(parsed: &Parsed<L>) -> String {
TreeRecomposer::new(&mut CoreSource)
.recompose(&parsed.result.tree, ())
.expect("the fold runs")
}
fn splice_sources() -> (Arc<Source>, Arc<Source>) {
(source("a\\foo b"), source("xyz"))
}
#[test]
fn a_chars_run_across_a_seam_is_one_node_owning_the_text_it_read() {
let (a, b) = splice_sources();
let parsed: Parsed<RelaxedLang> =
run_nodes(&[(&a, 0..1), (&b, 0..3), (&a, 5..7)], Recovery::Strict, StopSpec::none())
.expect("the parse runs");
let roots = parsed.roots();
assert_eq!(roots.len(), 1);
assert_owned_chars(&roots[0], "axyz b");
assert!(Arc::ptr_eq(roots[0].span().source(), &a));
assert_eq!(roots[0].span().range(), 0..7);
assert_eq!(roots[0].span().content(), "a\\foo b");
assert!(parsed.result.diagnostics.is_empty());
assert_eq!(parsed.stop, StopCause::EndOfInput);
}
#[test]
fn a_tiled_language_rejects_a_chars_run_across_a_seam() {
let (a, b) = splice_sources();
let error = expect_error(run_nodes::<TiledScriptedLang>(
&[(&a, 0..1), (&b, 0..3), (&a, 5..7)],
Recovery::Strict,
StopSpec::none(),
));
assert_eq!(implementation_kind(&error), ImplementationErrorKind::IncoherentPositions);
}
#[test]
fn recomposing_a_run_across_a_seam_emits_the_text_as_stored() {
let (a, b) = splice_sources();
let parsed: Parsed<RelaxedLang> =
run_nodes(&[(&a, 0..1), (&b, 0..3), (&a, 5..7)], Recovery::Strict, StopSpec::none())
.expect("the parse runs");
assert_eq!(recompose(&parsed), "axyz b");
}
#[test]
fn a_run_ending_at_a_seam_is_owned_and_a_tiled_language_rejects_it() {
let a = source("a");
let b = source("{b}");
let parsed: Parsed<RelaxedLang> =
run_nodes(&[(&a, 0..1), (&b, 0..3)], Recovery::Strict, StopSpec::none())
.expect("the parse runs");
let roots = parsed.roots();
assert_eq!(roots.len(), 2);
assert_owned_chars(&roots[0], "a");
assert!(Arc::ptr_eq(roots[0].span().source(), &a));
assert_eq!(roots[0].span().range(), 0..1);
assert!(roots[1].is_group());
assert_eq!(roots[1].group_delimiters(), Some(("{", "}")));
let error = expect_error(run_nodes::<TiledScriptedLang>(
&[(&a, 0..1), (&b, 0..3)],
Recovery::Strict,
StopSpec::none(),
));
assert_eq!(implementation_kind(&error), ImplementationErrorKind::IncoherentPositions);
}
#[test]
fn a_group_spanning_a_seam_records_the_delimiter_it_cannot_span() {
let a = source("{a");
let b = source("b}");
let parsed: Parsed<RelaxedLang> =
run_nodes(&[(&a, 0..2), (&b, 0..2)], Recovery::Strict, StopSpec::none())
.expect("the parse runs");
let roots = parsed.roots();
assert_eq!(roots.len(), 1);
let group = &roots[0];
assert!(group.is_group());
assert!(Arc::ptr_eq(group.span().source(), &a));
assert_eq!(group.span().range(), 0..2);
let data = group.group().expect("a group node");
match &data.open {
TextContent::Spanned(span) => assert_eq!(span.range(), 0..1),
other => panic!("the open delimiter lies in the node's own source: {other:?}"),
}
match &data.close {
TextContent::Owned(text) => assert_eq!(&text[..], "}"),
other => panic!("the close delimiter comes from another source: {other:?}"),
}
assert_eq!(group.group_delimiters(), Some(("{", "}")));
let children: Vec<_> = group.children().iter().collect();
assert_eq!(children.len(), 1);
assert_owned_chars(&children[0], "ab");
assert_eq!(recompose(&parsed), "{ab}");
}
#[test]
fn a_chars_run_across_a_hole_in_one_source_is_one_owned_node() {
let a = source("a\\foob");
let parsed: Parsed<RelaxedLang> =
run_nodes(&[(&a, 0..1), (&a, 5..6)], Recovery::Strict, StopSpec::none())
.expect("the parse runs");
let roots = parsed.roots();
assert_eq!(roots.len(), 1);
assert_owned_chars(&roots[0], "ab");
assert!(Arc::ptr_eq(roots[0].span().source(), &a));
assert_eq!(roots[0].span().range(), 0..6);
assert_eq!(roots[0].span().content(), "a\\foob");
let error = expect_error(run_nodes::<TiledScriptedLang>(
&[(&a, 0..1), (&a, 5..6)],
Recovery::Strict,
StopSpec::none(),
));
assert_eq!(implementation_kind(&error), ImplementationErrorKind::IncoherentPositions);
}
#[test]
fn an_unconsumed_stop_token_at_a_seam_is_peeked_again_where_it_stands() {
let a = source("ab");
let b = source("cd");
let stops_at_c = |token: &_, tokens: &dyn TokenReader<'_, RelaxedLang>| {
Ok(matches!(tokens.token_kind(token), TokenKind::Char('c')))
};
let state = script_state::<RelaxedLang>();
let (result, stop_span) = with_scripted_parse::<RelaxedLang, SourceSpan<Option<String>>>(
&state,
&[(&a, 0..2), (&b, 0..2)],
Recovery::Strict,
|cx| {
let begin = cx.tokens.position_here();
let mut parser = NodesParser::new(StopSpec::at_token(
TokenStopKind::Predicate(&stops_at_c),
false,
));
let (outcome, _) = parser.parse(cx)?;
let StopCause::TokenCondition { span, after } = &outcome.stop else {
panic!("expected a token-condition stop, got {:?}", outcome.stop);
};
let (span, after) = (span.clone(), *after);
let here = cx.tokens.position_here();
let again = cx.tokens.peek(&cx.state).expect("the token is peekable again");
assert!(matches!(cx.tokens.token_kind(&again), TokenKind::Char('c')));
assert_eq!(cx.tokens.position_at(&again, TokenEdge::StartBeforePreSpace), here);
assert_eq!(
cx.tokens
.source_span_between(&again, TokenEdge::StartBeforePreSpace, TokenEdge::Start)
.content(),
""
);
assert_eq!(cx.tokens.position_at(&again, TokenEdge::EndPastPostSpace), after);
let root_span = cx.source_span_within(&begin, &here)?;
Ok((outcome.nodes, root_span, span))
},
)
.expect("the parse runs");
assert!(Arc::ptr_eq(stop_span.source(), &b));
assert_eq!(stop_span.range(), 0..1);
let parsed = Parsed { result, stop: StopCause::EndOfInput };
let roots = parsed.roots();
assert_eq!(roots.len(), 1);
assert_owned_chars(&roots[0], "ab");
assert!(Arc::ptr_eq(roots[0].span().source(), &a));
assert_eq!(roots[0].span().range(), 0..2);
}
fn bracket_rule<L>(state: &Arc<ParsingState<L>>) -> Arc<GroupRule<L>>
where
L: Lang<Features = AllLangFeatures, GroupTypeId = u32>,
{
Arc::clone(
state
.rules()
.groups
.rules
.iter()
.find(|rule| &*rule.open == "[")
.expect("the bracket rule is in the seed"),
)
}
#[test]
fn an_optional_argument_probe_matches_across_a_seam() {
let a = source("\\cmd");
let b = source("[x]z");
let state = script_state::<RelaxedLang>();
let rule = bracket_rule(&state);
let spec = ArgumentSpec::new(OptionalGroupArgumentParser::new(rule), "opt");
let (result, ()) = with_scripted_parse::<RelaxedLang, ()>(
&state,
&[(&a, 0..4), (&b, 0..4)],
Recovery::Strict,
|cx| {
let state = Arc::clone(&cx.state);
let trigger = cx.probe_token(&state)?.expect("the trigger token");
assert!(matches!(
cx.tokens.token_kind(&trigger),
TokenKind::Command { name: "cmd", .. }
));
cx.tokens.move_to(&trigger, TokenEdge::EndPastPostSpace);
let begin = cx.tokens.position_here();
let parsed = spec
.parser
.parse_argument(cx, &spec)?
.expect("the optional argument is present");
let end = cx.tokens.position_here();
let span = cx.source_span_within(&begin, &end)?;
Ok((parsed.nodes, span, ()))
},
)
.expect("the parse runs");
let parsed = Parsed { result, stop: StopCause::EndOfInput };
let roots = parsed.roots();
assert_eq!(roots.len(), 1);
assert_eq!(roots[0].group_delimiters(), Some(("[", "]")));
let content: Vec<_> = roots[0].children().iter().collect();
assert_eq!(content.len(), 1);
assert_owned_chars(&content[0], "x");
assert_eq!(recompose(&parsed), "[x]");
}
#[test]
fn an_optional_argument_probe_that_fails_rewinds_across_a_seam() {
let a = source("\\cmd%c");
let b = source("y");
let state = script_state::<RelaxedLang>();
let rule = bracket_rule(&state);
let spec = ArgumentSpec::new(OptionalGroupArgumentParser::new(rule), "opt");
let segments: [Segment<'_>; 2] = [(&a, 0..6), (&b, 0..1)];
let mut reader = ScriptedReader::<RelaxedLang>::new(&segments, &state);
let mut session = ParserSession::new();
let driver = StdParseDriver::new(Recovery::Strict, ());
let mut cx = ParseContext::new(&mut reader, Arc::clone(&state), &mut session, &driver);
let trigger = cx.tokens.peek(&cx.state).expect("the trigger");
cx.tokens.move_to(&trigger, TokenEdge::EndPastPostSpace);
let before = cx.tokens.position_here();
let absent = spec.parser.parse_argument(&mut cx, &spec).expect("the probe runs");
assert!(absent.is_none(), "no bracket follows, so the argument is absent");
assert_eq!(cx.tokens.position_here(), before, "the probe rewound to where it started");
let again = cx.tokens.peek(&cx.state).expect("the comment is peekable again");
assert!(matches!(
cx.tokens.token_kind(&again),
TokenKind::Comment { start_delim: "%", content: "c" }
));
assert!(Arc::ptr_eq(cx.tokens.source_span_of(&again).source(), &a));
}
#[test]
fn a_comment_and_a_paragraph_break_in_another_source_become_nodes() {
let a = source("a");
let b = source("%note\n\nb");
let parsed: Parsed<RelaxedLang> =
run_nodes(&[(&a, 0..1), (&b, 0..8)], Recovery::Strict, StopSpec::none())
.expect("the parse runs");
let roots = parsed.roots();
assert_eq!(roots.len(), 4, "{:?}", roots.iter().map(|n| n.summary()).collect::<Vec<_>>());
assert_owned_chars(&roots[0], "a");
assert!(Arc::ptr_eq(roots[0].span().source(), &a));
let comment = roots[1].comment().expect("a comment node");
assert!(Arc::ptr_eq(roots[1].span().source(), &b));
assert_eq!(roots[1].span().range(), 0..5);
for part in [&comment.start, &comment.content, &comment.post_space] {
assert!(
matches!(part, TextContent::Spanned(_)),
"the comment's parts lie in the node's own source: {part:?}"
);
}
assert_eq!(comment.start.resolve(roots[1].source()), "%");
assert_eq!(comment.content.resolve(roots[1].source()), "note");
assert_eq!(comment.post_space.resolve(roots[1].source()), "");
assert_spanned_chars(&roots[2], "\n\n");
assert_eq!(roots[2].span().range(), 5..7);
assert_owned_chars(&roots[3], "b");
assert!(Arc::ptr_eq(roots[3].span().source(), &b));
assert_eq!(roots[3].span().range(), 7..8);
assert_eq!(recompose(&parsed), "a%note\n\nb");
assert!(!Arc::ptr_eq(roots[0].span().source(), roots[1].span().source()));
}
fn parse_with_broken_seams<L: ScriptedTestLang>() -> ParseError {
let a = source("a");
let b = source("b");
let state = script_state::<L>();
let segments: [Segment<'_>; 2] = [(&a, 0..1), (&b, 0..1)];
let mut reader = ScriptedReader::<L>::broken_at_seams(&segments, &state);
let mut session = ParserSession::new();
let driver = StdParseDriver::new(Recovery::Strict, ());
let mut cx = ParseContext::new(&mut reader, Arc::clone(&state), &mut session, &driver);
let mut parser = NodesParser::new(StopSpec::<L>::none());
parser.parse(&mut cx).expect_err("the broken reader is rejected")
}
#[test]
fn a_token_not_starting_where_the_stream_stood_is_an_implementation_error() {
assert_eq!(
implementation_detail(&parse_with_broken_seams::<RelaxedLang>()),
implementation_detail(&parse_with_broken_seams::<TiledScriptedLang>()),
);
assert_eq!(
implementation_kind(&parse_with_broken_seams::<TiledScriptedLang>()),
ImplementationErrorKind::TokenPositionMismatch,
);
}
#[test]
fn a_diagnostic_in_a_synthesized_source_renders_the_provenance_chain() {
let a = source("x\\expandme");
let expansion: Arc<Source> = Arc::new(Source::synthesized(
"{y",
"macro expansion",
SourceSpan::new(&a, 1..10),
));
let parsed: Parsed<RelaxedLang> = run_nodes(
&[(&a, 0..1), (&expansion, 0..2)],
Recovery::Tolerant,
StopSpec::none(),
)
.expect("tolerant parsing keeps going");
assert_eq!(parsed.result.diagnostics.len(), 1);
let diagnostic = parsed.result.diagnostics.iter().next().unwrap();
assert!(diagnostic.data().is::<UnclosedGroup>(), "unexpected diagnostic: {diagnostic:?}");
assert!(Arc::ptr_eq(diagnostic.span().source(), &expansion));
let report = parsed.result.diagnostics.render_all();
assert!(
report.contains("macro expansion"),
"the provenance chain is missing from the report:\n{report}"
);
}
fn raw_script_state<L>() -> Arc<ParsingState<L>>
where
L: Lang<Features = AllLangFeatures, GroupTypeId = u32, ModeId = (), StateExt = ()>,
{
let mut rules = script_rules::<L>();
rules.groups.enabled = false;
rules.groups.rules = Vec::new();
rules.commands.enabled = false;
rules.comments.enabled = false;
rules.paragraphs.enabled = false;
rules.groups.expecting_close = Some(Arc::new(GroupRule {
group_type: GT_BRACE,
open: "{".into(),
close: "}".into(),
}));
Arc::new(ParsingState::new(StateData {
rules,
scopes: ScopeStack::new(),
mode: (),
ext: (),
}))
}
fn run_verbatim_argument(
segments: &[Segment<'_>],
recovery: Recovery,
root_span: SourceSpan<Option<String>>,
) -> ParseResult<RelaxedLang> {
let state = raw_script_state::<RelaxedLang>();
let mut reader = ScriptedReader::<RelaxedLang>::new(segments, &state);
let mut session = ParserSession::new();
let driver = StdParseDriver::new(recovery, ());
let spec = ArgumentSpec::new(VerbatimArgumentParser::new(GT_BRACE), "verb");
let nodes = {
let mut cx = ParseContext::new(&mut reader, Arc::clone(&state), &mut session, &driver);
spec.parser
.parse_argument(&mut cx, &spec)
.expect("the verbatim argument parses")
.expect("the argument is present")
.nodes
};
let root = session
.builder
.add(NodeKind::list(), root_span, Arc::clone(&state), nodes, (), ())
.expect("stage the root list");
let result = session.finish(root).expect("freeze the tree");
crate::node::validate_tree(&result.tree).expect("the all-trees law holds");
crate::node::check_tree_invariants(&result.tree);
result
}
#[test]
fn verbatim_content_starting_at_a_seam_is_staged_as_the_text_it_read() {
let a = source("{zzz }");
let b = source("ab");
let result = run_verbatim_argument(
&[(&a, 0..1), (&b, 0..2), (&a, 4..7)],
Recovery::Strict,
SourceSpan::new(&a, 0..7),
);
let group = result.tree.root().child(0).expect("the verbatim group");
assert_eq!(group.group_delimiters(), Some(("{", "}")));
assert!(Arc::ptr_eq(group.span().source(), &a));
assert_eq!(group.span().range(), 0..7);
let content: Vec<_> = group.children().iter().collect();
assert_eq!(content.len(), 1);
assert_owned_chars(&content[0], "ab ");
assert!(Arc::ptr_eq(content[0].span().source(), &b));
assert_eq!(content[0].span().range(), 0..2);
assert_eq!(content[0].span().content(), "ab");
}
#[test]
fn verbatim_content_running_to_end_of_stream_keeps_the_whitespace_before_it() {
let a = source("{zzz ");
let b = source("ab");
let result = run_verbatim_argument(
&[(&a, 0..1), (&b, 0..2), (&a, 4..6)],
Recovery::Tolerant,
SourceSpan::new(&a, 0..6),
);
assert_eq!(result.diagnostics.len(), 1);
let diagnostic = result.diagnostics.iter().next().unwrap();
assert_eq!(
diagnostic.data().downcast_ref::<UnterminatedVerbatim>().map(|c| c.close.as_str()),
Some("}")
);
let group = result.tree.root().child(0).expect("the verbatim group");
assert_eq!(group.group_delimiters(), Some(("{", "")));
assert!(Arc::ptr_eq(group.span().source(), &a));
assert_eq!(group.span().range(), 0..6);
let content: Vec<_> = group.children().iter().collect();
assert_eq!(content.len(), 1);
assert_owned_chars(&content[0], "ab ");
assert!(Arc::ptr_eq(content[0].span().source(), &b));
assert_eq!(content[0].span().range(), 0..2);
}