use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::ops::Range;
use crate::constructs::{
InvalidReferenceReason, InvalidSourceReferenceArgument, NodesParser, ParseContext, StopSpec,
};
use crate::engine::{ParseResult, ParserSession};
use crate::error::{DiagnosticInfo, ParseError, Recovery};
use crate::node::{NodeKind, NodeRef};
use crate::recompose::TreeRecomposer;
use crate::scopes::Package;
use crate::source::{MapResolver, Source, TextContent};
use crate::state::{Lang, ParsingState};
use crate::token::ScriptedReader;
use super::test_support::RelaxedScriptedLatexlike;
use super::{check_latexlike_tree_invariants, source_recomposer, CallableType, LatexlikeDriver};
fn source(content: &str) -> Arc<Source> {
Arc::new(Source::new(content))
}
type Segment<'s> = (&'s Arc<Source>, Range<usize>);
fn seed(
package: Package<RelaxedScriptedLatexlike>,
) -> Arc<ParsingState<RelaxedScriptedLatexlike>> {
Arc::new(ParsingState::lang_initial_with_packages([Arc::new(package)]).expect("seed state"))
}
fn run_script(
state: &Arc<ParsingState<RelaxedScriptedLatexlike>>,
segments: &[Segment<'_>],
recovery: Recovery,
) -> Result<ParseResult<RelaxedScriptedLatexlike>, ParseError> {
run_script_with(state, segments, LatexlikeDriver::new(recovery))
}
fn run_script_with(
state: &Arc<ParsingState<RelaxedScriptedLatexlike>>,
segments: &[Segment<'_>],
driver: LatexlikeDriver<RelaxedScriptedLatexlike>,
) -> Result<ParseResult<RelaxedScriptedLatexlike>, ParseError> {
let mut reader = ScriptedReader::<RelaxedScriptedLatexlike>::new(segments, state);
let mut session = ParserSession::new();
let (nodes, root_span) = {
let mut cx = ParseContext::new(&mut reader, Arc::clone(state), &mut session, &driver);
let begin = cx.tokens.position_here();
let mut parser = NodesParser::new(StopSpec::none());
let (outcome, delta) = crate::constructs::ConstructParser::parse(&mut parser, &mut 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)?;
(outcome.nodes, root_span)
};
let kind = NodeKind::list();
RelaxedScriptedLatexlike::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, (), ())
.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");
check_latexlike_tree_invariants(&result.tree);
Ok(result)
}
fn reemit(result: &ParseResult<RelaxedScriptedLatexlike>) -> String {
TreeRecomposer::new(&mut source_recomposer::<RelaxedScriptedLatexlike>())
.recompose(&result.tree, ())
.expect("the preset re-emits the tree")
}
fn body_nodes<'t>(
environment: NodeRef<'t, RelaxedScriptedLatexlike>,
) -> Vec<NodeRef<'t, RelaxedScriptedLatexlike>> {
environment
.body()
.expect("the environment has a body slot")
.iter()
.collect()
}
fn itemize_package() -> Package<RelaxedScriptedLatexlike> {
let mut package = Package::new("relaxed-scripted-envs");
package
.define_environment("itemize", core::iter::empty::<&str>())
.expect("no argument codes");
package
}
#[test]
fn an_environment_spanning_seams_is_built_and_reemitted_as_stored() {
let a = source("\\begin{itemize}\\end{itemize}");
let b = source("body");
let state = seed(itemize_package());
let result = run_script(&state, &[(&a, 0..15), (&b, 0..4), (&a, 15..28)], Recovery::Strict)
.expect("the parse runs");
assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
let root = result.tree.root();
assert_eq!(root.children().len(), 1);
let environment = root.child(0).expect("the environment node");
assert_eq!(environment.name(), Some("itemize"));
assert_eq!(environment.environment_name(), Some("itemize"));
assert!(Arc::ptr_eq(environment.span().source(), &a));
assert_eq!(environment.span().range(), 0..28);
let body = body_nodes(environment);
assert_eq!(body.len(), 1);
match body[0].kind() {
NodeKind::Chars { content: TextContent::Owned(text) } => assert_eq!(&text[..], "body"),
other => panic!("expected owned body content, found {other:?}"),
}
assert_eq!(body[0].chars(), Some("body"));
assert!(Arc::ptr_eq(body[0].span().source(), &b));
assert_eq!(body[0].span().range(), 0..4);
let side = |side: &super::StdEnvironmentSideSyntax<RelaxedScriptedLatexlike>| {
assert!(
matches!(side.command_word, TextContent::Spanned(_)),
"the command word lies in the node's own source: {:?}",
side.command_word
);
};
let syntax = environment_syntax(&environment);
side(&syntax.begin);
side(syntax.end.as_ref().expect("the terminator was consumed"));
assert_eq!(reemit(&result), "\\begin{itemize}body\\end{itemize}");
}
#[test]
fn an_environment_terminator_from_another_source_is_recorded_as_text() {
let a = source("\\begin{itemize}");
let b = source("body\\end{itemize}");
let state = seed(itemize_package());
let result = run_script(&state, &[(&a, 0..15), (&b, 0..17)], Recovery::Strict)
.expect("the parse runs");
assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
let environment = result.tree.root().child(0).expect("the environment node");
assert!(Arc::ptr_eq(environment.span().source(), &a));
assert_eq!(environment.span().range(), 0..15);
let syntax = environment_syntax(&environment);
let end = syntax.end.as_ref().expect("the terminator was consumed");
match &end.command_word {
TextContent::Owned(word) => assert_eq!(&word[..], "end"),
other => panic!("the terminator comes from another source: {other:?}"),
}
assert_eq!(reemit(&result), "\\begin{itemize}body\\end{itemize}");
}
#[test]
fn an_environment_name_read_across_a_seam_resolves_the_environment() {
let a = source("\\begin{}x\\end{itemize}");
let b = source("itemize");
let state = seed(itemize_package());
let result = run_script(&state, &[(&a, 0..7), (&b, 0..7), (&a, 7..22)], Recovery::Tolerant)
.expect("the parse runs");
assert!(
result.diagnostics.is_empty(),
"the lookup found the environment: {:?}",
result.diagnostics
);
let environment = result.tree.root().child(0).expect("the environment node");
assert_eq!(environment.name(), Some("itemize"));
let body = body_nodes(environment);
assert_eq!(body.len(), 1);
assert_eq!(body[0].chars(), Some("x"));
assert_eq!(reemit(&result), "\\begin{itemize}x\\end{itemize}");
}
fn environment_syntax<'t>(
node: &NodeRef<'t, RelaxedScriptedLatexlike>,
) -> &'t super::StdEnvironmentSyntax<RelaxedScriptedLatexlike> {
match &node.callable().expect("a callable node").invocation_syntax {
super::InvocationSyntaxData::Environment(env) => env,
other => panic!("expected an environment payload, found {other:?}"),
}
}
#[test]
fn a_macro_post_space_is_recorded_as_text_where_the_language_does_not_obey_tiling() {
let a = source("\\foo z");
let b = source("y");
let mut package = Package::new("relaxed-scripted-macros");
package.define_macro("foo", core::iter::empty::<&str>()).expect("no argument codes");
let state = seed(package);
let result = run_script(&state, &[(&b, 0..1), (&a, 0..6)], Recovery::Strict)
.expect("the parse runs");
assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
let root = result.tree.root();
let shapes: Vec<String> = root.children().iter().map(|node| node.summary()).collect();
assert_eq!(shapes, ["chars(y)", "Macro(foo)", "chars(z)"], "{shapes:?}");
let macro_node = root.child(1).expect("the macro node");
assert!(Arc::ptr_eq(macro_node.span().source(), &a));
assert_eq!(macro_node.span().range(), 0..5);
match ¯o_node.callable().expect("a callable node").invocation_syntax {
super::InvocationSyntaxData::Macro { escape_char, post_space } => {
assert_eq!(*escape_char, '\\');
match post_space {
TextContent::Owned(text) => assert_eq!(&text[..], " "),
other => panic!("expected owned post-space, found {other:?}"),
}
}
other => panic!("expected a macro payload, found {other:?}"),
}
assert_eq!(reemit(&result), "y\\foo z");
}
fn input_package() -> Package<RelaxedScriptedLatexlike> {
let mut package = Package::new("relaxed-scripted-inputs");
package.insert(
CallableType::Macro,
"input",
super::input_macro_spec::<RelaxedScriptedLatexlike>(false, super::BodyMarker::not_body()),
);
package
}
fn resolving_driver(content: &str) -> LatexlikeDriver<RelaxedScriptedLatexlike> {
let mut resolver = MapResolver::new();
resolver.insert("chap.tex", content);
LatexlikeDriver::new(Recovery::Tolerant)
.with_source_resolver(resolver.with_reference_as_origin())
}
#[test]
fn an_input_reference_read_across_seams_resolves() {
let a = source("\\input{}");
let b = source("chap.tex");
let state = seed(input_package());
let result = run_script_with(
&state,
&[(&a, 0..7), (&b, 0..8), (&a, 7..8)],
resolving_driver("included"),
)
.expect("the parse runs");
assert!(
result.diagnostics.is_empty(),
"the reference resolved: {:?}",
result.diagnostics
);
let input = result.tree.root().child(0).expect("the input node");
assert_eq!(input.name(), Some("input"));
let reference: Vec<_> = input
.argument_content_nodes_named("reference")
.expect("a named argument")
.expect("the argument is provided")
.iter()
.collect();
assert_eq!(reference.len(), 1);
match reference[0].kind() {
NodeKind::Chars { content: TextContent::Owned(text) } => {
assert_eq!(&text[..], "chap.tex")
}
other => panic!("expected owned reference content, found {other:?}"),
}
let slots = input.slots().expect("a callable node");
assert_eq!(slots.len(), 1, "the resolved source was attached");
assert_eq!(slots.get(0).expect("the attached slot").name(), Some("attached"));
}
#[test]
fn an_input_reference_that_is_not_plain_characters_is_an_invalid_reference_argument() {
let a = source("\\input{{chap.tex}}");
let state = seed(input_package());
let result = run_script_with(&state, &[(&a, 0..18)], resolving_driver("included"))
.expect("the parse runs");
let input = result.tree.root().child(0).expect("the input node");
assert_eq!(input.name(), Some("input"));
let reference: Vec<_> = input
.argument_content_nodes_named("reference")
.expect("a named argument")
.expect("the argument is provided")
.iter()
.collect();
assert_eq!(reference.len(), 1);
assert!(reference[0].is_group(), "the content is a group, not characters");
assert_eq!(result.diagnostics.len(), 1, "{:?}", result.diagnostics);
let diagnostic = result.diagnostics.iter().next().expect("the diagnostic");
assert_eq!(diagnostic.identifier(), InvalidSourceReferenceArgument::IDENTIFIER);
let condition = diagnostic
.data()
.downcast_ref::<InvalidSourceReferenceArgument>()
.expect("the condition type");
assert_eq!(condition.reason, InvalidReferenceReason::NotPlainCharacters);
assert_eq!(diagnostic.span().range(), 6..18);
assert!(Arc::ptr_eq(diagnostic.span().source(), &a));
assert!(
input.slots().expect("a callable node").is_empty(),
"no source is attached when the reference cannot be read"
);
}