use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;
use crate::node::{ArgumentExt, ContentNodes, GroupData, NodeKind};
use crate::source::{SourceSpan, TextContent};
use crate::spec::{ArgumentParser, ArgumentSpec, ParsedArgumentNodes};
use crate::state::{Lang, ParsingState};
use crate::token::{Token, TokenEdge, TokenKind};
use super::argument_parsers::{
marker_scan_state_delta, parse_expression_node, scan_argument_noise, stage_pre_space,
};
use super::{node_text_content, ConstructParserResult, FromInvocation, ParseContext};
pub struct EmbellishmentsArgumentParser {
markers: Vec<Box<str>>,
}
impl EmbellishmentsArgumentParser {
pub fn new(
markers: impl IntoIterator<Item = impl Into<Box<str>>>,
) -> EmbellishmentsArgumentParser {
EmbellishmentsArgumentParser {
markers: markers.into_iter().map(Into::into).collect(),
}
}
}
impl<L: Lang> ArgumentParser<L> for EmbellishmentsArgumentParser
where
ArgumentExt<L>: Default,
L::InvocationSyntax: FromInvocation<L>,
{
fn parse_argument(
&self,
cx: &mut ParseContext<'_, '_, L>,
_spec: &ArgumentSpec<L>,
) -> ConstructParserResult<L, Option<ParsedArgumentNodes<L>>> {
if self.markers.is_empty() {
return Err(cx.implementation_error(
"EmbellishmentsArgumentParser::new needs at least one marker",
cx.here(),
));
}
if self.markers.iter().any(|marker| marker.is_empty()) {
return Err(cx.implementation_error(
"EmbellishmentsArgumentParser::new needs non-empty markers",
cx.here(),
));
}
let scan_state = cx.derive_state(&marker_scan_state_delta())?;
let mut nodes = Vec::new();
let mut used = alloc::vec![false; self.markers.len()];
let mut content_start: Option<u32> = None;
loop {
let noise = scan_argument_noise(cx)?;
if noise.next.is_none() {
noise.rewind(cx);
break;
}
let Some(MarkerMatch { index: marker_index, first, span: marker_span }) =
self.scan_marker(cx, &scan_state, &used)?
else {
noise.rewind(cx);
break;
};
let mut wrapper_children = Vec::new();
let state = Arc::clone(&cx.state);
let expression = match cx.probe_token(&state)? {
Some(token) => parse_expression_node(cx, &token, &mut wrapper_children)?,
None => None,
};
if expression.is_none() {
cx.tokens.move_to_position(&noise.start);
break;
}
let span = match L::OBEYS_SPAN_TILING {
true => {
let child_span = wrapper_children
.last()
.and_then(|last| cx.staged_nodes().get(*last))
.map(|child| child.span().clone())
.filter(|child| {
child.same_source(&marker_span)
&& child.end() >= marker_span.end()
});
match child_span {
Some(child) => SourceSpan::new(
marker_span.source(),
marker_span.start()..child.end(),
),
None => marker_span.clone(),
}
}
false => cx.source_span_within(
&cx.tokens.position_at(&first, TokenEdge::Start),
&cx.tokens.position_here(),
)?,
};
let data = GroupData::untyped(
node_text_content(&marker_span, &span),
TextContent::empty(),
);
let wrapper = cx
.stage_node(
NodeKind::group(data),
span.clone(),
Arc::clone(&cx.state),
wrapper_children,
)
.map_err(|error| cx.staging_error(error, span))?;
used[marker_index] = true;
nodes.extend(noise.nodes);
stage_pre_space(cx, &mut nodes, &first)?;
if content_start.is_none() {
content_start = Some(nodes.len() as u32);
}
nodes.push(wrapper);
if used.iter().all(|used| *used) {
break; }
}
match content_start {
Some(start) => {
let end = nodes.len() as u32;
Ok(Some(ParsedArgumentNodes::new(
nodes,
ContentNodes::InRegion(start..end),
Default::default(),
)))
}
None => Ok(None),
}
}
fn can_match_empty(&self) -> bool {
true
}
}
struct MarkerMatch<L: Lang> {
index: usize,
first: Token<L>,
span: SourceSpan<L::SourceOrigin>,
}
impl EmbellishmentsArgumentParser {
fn scan_marker<'s, L: Lang>(
&self,
cx: &mut ParseContext<'_, 's, L>,
scan_state: &Arc<ParsingState<L>>,
used: &[bool],
) -> ConstructParserResult<L, Option<MarkerMatch<L>>> {
let Some(first) = cx.probe_token(scan_state)? else {
return Ok(None);
};
let TokenKind::Char(first_char) = cx.tokens.token_kind(&first) else {
return Ok(None);
};
let available = |candidate: &str| {
self.markers
.iter()
.enumerate()
.filter(|(index, _)| !used[*index])
.find(|(_, marker)| &***marker == candidate)
.map(|(index, _)| index)
};
let prefixes_any = |candidate: &str| {
self.markers
.iter()
.enumerate()
.any(|(index, marker)| !used[index] && marker.starts_with(candidate))
};
let mut run = String::new();
run.push(first_char);
if !prefixes_any(&run) {
return Ok(None);
}
cx.tokens.move_to(&first, TokenEdge::EndPastPostSpace);
let mut best: Option<(usize, Token<L>)> =
available(&run).map(|index| (index, first.clone()));
loop {
let Some(token) = cx.probe_token(scan_state)? else { break };
let TokenKind::Char(c) = cx.tokens.token_kind(&token) else { break };
if cx.tokens.position_at(&token, TokenEdge::StartBeforePreSpace)
!= cx.tokens.position_at(&token, TokenEdge::Start)
{
break;
}
run.push(c);
if !prefixes_any(&run) {
break;
}
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
if let Some(index) = available(&run) {
best = Some((index, token.clone()));
}
}
let Some((index, last)) = best else { return Ok(None) };
cx.tokens.move_to(&last, TokenEdge::EndPastPostSpace);
let span = cx.source_span_within(
&cx.tokens.position_at(&first, TokenEdge::Start),
&cx.tokens.position_at(&last, TokenEdge::EndPastPostSpace),
)?;
Ok(Some(MarkerMatch { index, first, span }))
}
}
impl fmt::Debug for EmbellishmentsArgumentParser {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EmbellishmentsArgumentParser")
.field("markers", &self.markers)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::engine::Language;
use crate::latexlike::{CallableType, Latexlike, MacroSpec, SpecialsSpec};
use crate::extract::{content_as_chars, split_embellishments_drop_annotations};
use crate::node::{check_tree_invariants, NodeRef};
use crate::scopes::Package;
use crate::state::ParsingState;
use crate::error::{DiagnosticInfo, Recovery};
use crate::latexlike::LatexlikeDriver;
use alloc::string::ToString;
use alloc::vec;
fn language_with_specials(markers: &[&str], specials: &[&str]) -> Language<Latexlike> {
let parser = EmbellishmentsArgumentParser::new(markers.iter().copied());
let mut package = Package::new("embellishment-tests");
package.insert(
CallableType::Macro,
"m",
Arc::new(MacroSpec::new(vec![Arc::new(ArgumentSpec::new_unnamed(Arc::new(parser)))])),
);
package.insert(CallableType::Macro, "alpha", Arc::new(MacroSpec::new(vec![])));
for trigger in specials {
package.insert_specials(
CallableType::Specials,
*trigger,
Arc::new(SpecialsSpec::new(vec![])),
);
}
Language::new(
LatexlikeDriver::new(Recovery::Strict),
ParsingState::lang_initial_with_packages([package]).expect("seed state"),
)
}
fn language(markers: &[&str]) -> Language<Latexlike> {
language_with_specials(markers, &[])
}
fn parse_with_specials(
markers: &[&str],
specials: &[&str],
input: &str,
) -> crate::engine::ParseResult<Latexlike> {
let result = language_with_specials(markers, specials).parse(input).unwrap();
check_tree_invariants(&result.tree);
assert!(
result.diagnostics.is_empty(),
"unexpected diagnostics: {:?}",
result.diagnostics
);
result
}
fn parse(markers: &[&str], input: &str) -> crate::engine::ParseResult<Latexlike> {
parse_with_specials(markers, &[], input)
}
fn keys(m: NodeRef<'_, Latexlike>) -> Vec<alloc::string::String> {
split_embellishments_drop_annotations(m.argument_content_nodes(0).expect("provided"))
.unwrap()
.iter()
.map(|entry| entry.key().to_string())
.collect()
}
#[test]
fn multi_char_markers_take_the_longest_available_match() {
let result = parse(&["a", "ab"], r"\m ab{x}a{y}!");
let m = result.tree.root().child(0).unwrap();
assert_eq!(keys(m), ["ab", "a"]);
let fields = split_embellishments_drop_annotations(m.argument_content_nodes(0).unwrap()).unwrap();
assert_eq!(
content_as_chars(fields.get("ab").unwrap().value_content().unwrap()).unwrap(),
"x"
);
assert_eq!(
content_as_chars(fields.get("a").unwrap().value_content().unwrap()).unwrap(),
"y"
);
assert_eq!(result.tree.root().child(1).unwrap().chars(), Some("!"));
}
#[test]
fn a_longer_candidate_that_never_completes_falls_back_to_the_shorter_match() {
let result = parse(&["a", "abc"], r"\m ab{x}");
let m = result.tree.root().child(0).unwrap();
assert_eq!(keys(m), ["a"]);
let fields = split_embellishments_drop_annotations(m.argument_content_nodes(0).unwrap()).unwrap();
assert_eq!(
content_as_chars(fields.get("a").unwrap().value().unwrap()).unwrap(),
"b"
);
assert!(result.tree.root().child(1).unwrap().is_group());
}
#[test]
fn multi_char_markers_must_be_contiguous() {
let result = parse(&["ab"], r"\m a b{x}");
let m = result.tree.root().child(0).unwrap();
assert!(!m.arguments().unwrap().get(0).unwrap().is_provided());
assert_eq!(result.tree.root().child(1).unwrap().chars(), Some("a b"));
}
#[test]
fn the_expression_takes_every_expression_form() {
let result = parse(&["^"], r"\m^\alpha rest");
let m = result.tree.root().child(0).unwrap();
let wrapper = m.argument_content_nodes(0).unwrap().first().unwrap();
assert_eq!(wrapper.group_delimiters(), Some(("^", "")));
assert!(wrapper.child(0).unwrap().is_callable());
let result = parse(&["^"], r"\m^2 rest");
let m = result.tree.root().child(0).unwrap();
let wrapper = m.argument_content_nodes(0).unwrap().first().unwrap();
assert_eq!(wrapper.child(0).unwrap().chars(), Some("2"));
assert_eq!(result.tree.root().child(1).unwrap().chars(), Some(" rest"));
}
#[test]
fn markers_are_matched_raw_ahead_of_specials_and_the_expression_is_not() {
let result = parse_with_specials(&["`", "^", "_"], &["`"], "\\m`{x}^{a`b} `!");
let m = result.tree.root().child(0).unwrap();
assert_eq!(keys(m), ["`", "^"]);
let content: Vec<_> = m.argument_content_nodes(0).unwrap().iter().collect();
assert_eq!(content[0].group_delimiters(), Some(("`", "")));
let sup_value = content[1].child(0).unwrap();
assert_eq!(sup_value.child(0).unwrap().chars(), Some("a"));
assert_eq!(sup_value.child(1).unwrap().specials_name(), Some("`"));
assert_eq!(sup_value.child(2).unwrap().chars(), Some("b"));
let root = result.tree.root();
assert!((0..root.child_count())
.any(|i| root.child(i).unwrap().specials_name() == Some("`")));
let result = parse_with_specials(&["!`"], &["`"], "\\m!`{x}");
assert_eq!(keys(result.tree.root().child(0).unwrap()), ["!`"]);
}
#[test]
fn an_empty_marker_list_is_an_implementation_error() {
let err = language(&[]).parse(r"\m x").unwrap_err();
assert_eq!(err.identifier(), super::super::ImplementationError::IDENTIFIER);
}
#[test]
fn an_empty_marker_is_an_implementation_error() {
let err = language(&["^", ""]).parse(r"\m^2").unwrap_err();
assert_eq!(err.identifier(), super::super::ImplementationError::IDENTIFIER);
}
}