use alloc::boxed::Box;
use alloc::format;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;
use crate::engine::ParseDriver;
use crate::error::DiagnosticInfo;
use crate::node::{ArgumentExt, ContentNodes};
use crate::spec::{ArgumentParser, ArgumentSpec, CallableSpec, ParsedArgumentNodes};
use crate::state::Lang;
use crate::token::{TokenEdge, TokenKind};
use super::argument_parsers::{scan_argument_noise, stage_pre_space};
use super::{ConstructParserResult, FromInvocation, Invocation, invocation_frame, ParseContext};
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
id = "core.arguments.repeated-tack-on-field",
message = "information field ‘{escape_char}{name}’ cannot be specified more than once"
)]
pub struct RepeatedTackOnField {
pub name: String,
pub escape_char: char,
}
struct TackOnField<L: Lang> {
name: Box<str>,
spec: Arc<dyn CallableSpec<L>>,
repeatable: bool,
}
pub struct TackOnFieldsArgumentParser<L: Lang> {
callable_type: L::CallableTypeId,
fields: Vec<TackOnField<L>>,
}
impl<L: Lang> TackOnFieldsArgumentParser<L> {
pub fn new(callable_type: L::CallableTypeId) -> TackOnFieldsArgumentParser<L> {
TackOnFieldsArgumentParser { callable_type, fields: Vec::new() }
}
pub fn with_field(
self,
name: impl Into<Box<str>>,
spec: Arc<dyn CallableSpec<L>>,
) -> Self {
self.field(name.into(), spec, false)
}
pub fn with_repeatable_field(
self,
name: impl Into<Box<str>>,
spec: Arc<dyn CallableSpec<L>>,
) -> Self {
self.field(name.into(), spec, true)
}
fn field(mut self, name: Box<str>, spec: Arc<dyn CallableSpec<L>>, repeatable: bool) -> Self {
self.fields.push(TackOnField { name, spec, repeatable });
self
}
}
impl<L: Lang> ArgumentParser<L> for TackOnFieldsArgumentParser<L>
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 let Some(duplicate) = self.fields.iter().enumerate().find_map(|(i, field)| {
self.fields[..i]
.iter()
.any(|earlier| earlier.name == field.name)
.then_some(&*field.name)
}) {
return Err(cx.implementation_error(
format!(
"TackOnFieldsArgumentParser field names must be distinct \
(duplicate registration of ‘{duplicate}’)"
),
cx.here(),
));
}
let mut nodes = Vec::new();
let mut seen = alloc::vec![false; self.fields.len()];
let mut content_start: Option<u32> = None;
loop {
let noise = scan_argument_noise(cx)?;
let Some(token) = noise.next.clone() else {
noise.rewind(cx);
break;
};
let kind = cx.tokens.token_kind(&token);
let TokenKind::Command { name, escape_char } = kind else {
noise.rewind(cx);
break;
};
let Some(index) = self.fields.iter().position(|field| &*field.name == name)
else {
noise.rewind(cx);
break;
};
let field = &self.fields[index];
if seen[index] && !field.repeatable {
let span = cx.tokens.source_span_of(&token);
cx.recover(
RepeatedTackOnField::new(String::from(name), escape_char),
span,
)?;
}
seen[index] = true;
nodes.extend(noise.nodes);
stage_pre_space(cx, &mut nodes, &token)?;
let invocation = Invocation {
callable_type: self.callable_type,
name,
spec: &field.spec,
token: &token,
};
let frame = invocation_frame(cx, &invocation);
cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
let driver = cx.driver;
let mut parser = driver
.make_invocation_parser(invocation)
.map_err(|error| cx.attach_hook_frames(error))?;
let result = cx.parse_construct(&mut *parser, None, Some(frame));
drop(parser);
let (id, _delta) = result?;
if content_start.is_none() {
content_start = Some(nodes.len() as u32);
}
nodes.push(id);
}
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
}
}
impl<L: Lang> fmt::Debug for TackOnFieldsArgumentParser<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut fields = f.debug_struct("TackOnFieldsArgumentParser");
fields.field("callable_type", &self.callable_type);
for field in &self.fields {
fields.field(
if field.repeatable { "repeatable_field" } else { "field" },
&field.name,
);
}
fields.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constructs::CharsGroupArgumentParser;
use crate::engine::Language;
use crate::error::Recovery;
use crate::latexlike::{
argument_specs, CallableType, GroupType, Latexlike, LatexlikeDriver, MacroSpec,
};
use crate::extract::{content_as_chars, split_tack_on_fields_drop_annotations};
use crate::node::{check_tree_invariants, NodeRef};
use crate::scopes::Package;
use crate::state::ParsingState;
use alloc::vec;
use alloc::vec::Vec;
fn label_spec() -> Arc<dyn CallableSpec<Latexlike>> {
Arc::new(MacroSpec::new(vec![Arc::new(ArgumentSpec::new_unnamed(Arc::new(
CharsGroupArgumentParser::new(GroupType::Content),
)))]))
}
fn language(
tack_on: TackOnFieldsArgumentParser<Latexlike>,
recovery: Recovery,
) -> Language<Latexlike> {
let mut arguments = argument_specs(["m"]).unwrap();
arguments.push(Arc::new(ArgumentSpec::new_unnamed(Arc::new(tack_on))));
let mut package = Package::new("tack-on-tests");
package.insert(CallableType::Macro, "section", Arc::new(MacroSpec::new(arguments)));
Language::new(
LatexlikeDriver::new(recovery),
ParsingState::lang_initial_with_packages([package]).expect("seed state"),
)
}
fn repeatable_label() -> TackOnFieldsArgumentParser<Latexlike> {
TackOnFieldsArgumentParser::new(CallableType::Macro)
.with_repeatable_field("label", label_spec())
}
fn parse_ok(
tack_on: TackOnFieldsArgumentParser<Latexlike>,
input: &str,
) -> crate::engine::ParseResult<Latexlike> {
let result = language(tack_on, Recovery::Strict).parse(input).unwrap();
check_tree_invariants(&result.tree);
assert!(
result.diagnostics.is_empty(),
"unexpected diagnostics: {:?}",
result.diagnostics
);
result
}
fn section_node(result: &crate::engine::ParseResult<Latexlike>) -> NodeRef<'_, Latexlike> {
let node = result.tree.root().child(0).expect("the section node");
assert_eq!(node.macro_name(), Some("section"));
node
}
#[test]
fn trailing_fields_attach_to_the_invocation_node() {
let result = parse_ok(repeatable_label(), r"\section{One} \label{sec:one} after");
let section = section_node(&result);
assert_eq!(section.span().range(), 0..29);
let argument = section.arguments().unwrap().get(1).unwrap();
assert!(argument.is_provided());
let region: Vec<_> = section.argument_nodes(1).unwrap().iter().collect();
assert_eq!(region.len(), 2);
assert_eq!(region[0].chars(), Some(" "));
let content: Vec<_> = section.argument_content_nodes(1).unwrap().iter().collect();
assert_eq!(content.len(), 1);
let label = content[0];
assert!(label.is_callable());
assert_eq!(label.name(), Some("label"));
assert_eq!(label.callable_type(), Some(CallableType::Macro));
assert_eq!(
content_as_chars(label.argument_content_nodes(0).unwrap()).unwrap(),
"sec:one"
);
assert_eq!(result.tree.root().child(1).unwrap().chars(), Some(" after"));
}
#[test]
fn a_nested_tack_on_field_chain_is_counted_by_the_descent_guard() {
use crate::constructs::DescentLimitExceeded;
use crate::engine::StdDescentGuardInit;
use crate::error::DiagnosticInfo as _;
use alloc::string::String;
let mut spec: Arc<dyn CallableSpec<Latexlike>> =
Arc::new(MacroSpec::new(Vec::new()));
for _ in 0..40 {
let tack = TackOnFieldsArgumentParser::new(CallableType::Macro)
.with_field("f", Arc::clone(&spec));
spec = Arc::new(MacroSpec::new(vec![Arc::new(ArgumentSpec::new_unnamed(
Arc::new(tack),
))]));
}
let mut package = Package::new("tack-chain");
package.insert(CallableType::Macro, "start", spec);
let language: Language<Latexlike> = Language::new(
LatexlikeDriver::new(Recovery::Strict),
ParsingState::lang_initial_with_packages([package]).expect("seed state"),
)
.with_descent_guard_init(StdDescentGuardInit::depth_limit(20));
assert!(language.parse(r"\start \f \f \f x").is_ok());
let mut chain = String::from(r"\start");
for _ in 0..40 {
chain.push_str(r" \f");
}
chain.push_str(" x");
let err = language.parse(chain).unwrap_err();
assert_eq!(err.identifier(), DescentLimitExceeded::IDENTIFIER);
}
#[test]
fn field_commands_are_not_language_commands() {
let result = language(repeatable_label(), Recovery::Tolerant)
.parse(r"\label{a}")
.unwrap();
assert_eq!(result.diagnostics.len(), 1);
assert!(
result.diagnostics.iter().next().unwrap().message().contains("cannot resolve"),
"{}",
result.diagnostics.iter().next().unwrap().message()
);
}
#[test]
fn repeatable_fields_absorb_every_occurrence() {
let result = parse_ok(repeatable_label(), r"\section{A}\label{x}\label{y}z");
let section = section_node(&result);
let content: Vec<_> = section.argument_content_nodes(1).unwrap().iter().collect();
assert_eq!(content.len(), 2);
let fields = split_tack_on_fields_drop_annotations(section.argument_content_nodes(1).unwrap()).unwrap();
assert_eq!(fields.len(), 2);
let keys: Vec<_> = fields.iter().map(|entry| entry.key().to_string()).collect();
assert_eq!(keys, ["label", "label"]);
assert_eq!(
content_as_chars(fields.get("label").unwrap().value().unwrap()).unwrap(),
"y"
);
let combined = fields.get_combined_with("label", ",").unwrap().unwrap();
assert_eq!(content_as_chars(combined.root().children()).unwrap(), "x,y");
assert_eq!(result.tree.root().child(1).unwrap().chars(), Some("z"));
}
#[test]
fn non_repeatable_duplicates_are_diagnosed_and_kept() {
let once = || {
TackOnFieldsArgumentParser::new(CallableType::Macro)
.with_field("label", label_spec())
};
let err =
language(once(), Recovery::Strict).parse(r"\section{A}\label{x}\label{y}").unwrap_err();
assert!(
err.to_string().contains("cannot be specified more than once"),
"{err}"
);
let result =
language(once(), Recovery::Tolerant).parse(r"\section{A}\label{x}\label{y}").unwrap();
check_tree_invariants(&result.tree);
assert_eq!(result.diagnostics.len(), 1);
let diagnostic = result.diagnostics.iter().next().unwrap();
assert_eq!(diagnostic.identifier(), RepeatedTackOnField::IDENTIFIER);
let condition = diagnostic.data().downcast_ref::<RepeatedTackOnField>().unwrap();
assert_eq!(condition.name, "label");
assert_eq!(condition.escape_char, '\\');
let section = section_node(&result);
let content: Vec<_> = section.argument_content_nodes(1).unwrap().iter().collect();
assert_eq!(content.len(), 2);
}
#[test]
fn noise_between_fields_keeps_the_association() {
let result = parse_ok(repeatable_label(), "\\section{A} % note\n\\label{x}!");
let section = section_node(&result);
let region: Vec<_> = section.argument_nodes(1).unwrap().iter().collect();
assert!(region.iter().any(|node| node.comment().is_some()));
let fields = split_tack_on_fields_drop_annotations(section.argument_content_nodes(1).unwrap()).unwrap();
assert_eq!(
content_as_chars(fields.get("label").unwrap().value().unwrap()).unwrap(),
"x"
);
assert_eq!(result.tree.root().child(1).unwrap().chars(), Some("!"));
}
#[test]
fn absorption_stops_at_anything_else_silently() {
let result = parse_ok(repeatable_label(), r"\section{A} text");
let section = section_node(&result);
assert_eq!(section.span().range(), 0..11);
assert!(!section.arguments().unwrap().get(1).unwrap().is_provided());
assert_eq!(result.tree.root().child(1).unwrap().chars(), Some(" text"));
}
#[test]
fn zero_argument_fields_record_no_value() {
let tack_on = TackOnFieldsArgumentParser::new(CallableType::Macro)
.with_repeatable_field("label", label_spec())
.with_field("nonumber", Arc::new(MacroSpec::new(vec![])));
let result = parse_ok(tack_on, r"\section{A}\nonumber\label{x}");
let section = section_node(&result);
let fields = split_tack_on_fields_drop_annotations(section.argument_content_nodes(1).unwrap()).unwrap();
assert_eq!(fields.len(), 2);
assert!(fields.get("nonumber").unwrap().value().is_none());
assert_eq!(
content_as_chars(fields.get("label").unwrap().value().unwrap()).unwrap(),
"x"
);
}
#[test]
fn duplicate_field_names_are_an_implementation_error() {
let tack_on = TackOnFieldsArgumentParser::new(CallableType::Macro)
.with_field("label", label_spec())
.with_repeatable_field("label", label_spec());
let err = language(tack_on, Recovery::Tolerant)
.parse(r"\section{A}\label{x}")
.unwrap_err();
assert_eq!(
err.identifier(),
crate::constructs::ImplementationError::IDENTIFIER
);
}
}