use std::fmt;
use std::sync::Arc;
use techy::core::constructs::{
ArgumentParser, ConstructParser, ConstructParserResult, EnvironmentBody, EnvironmentBodyParser,
OptionalGroupArgumentParser, ParseContext, ParsedArgumentNodes,
};
use techy::core::node::{BodySlotExt, BuildId, NodeKind, NodeRef, NodeSlice, StagedNodes};
use techy::core::specs::ArgumentSpec;
use techy::core::token::GroupRule;
use techy::core::ParsingStateDelta;
use techy::error::{DiagnosticInfo, DiagnosticValue, ToDiagnosticValue};
use techy::latexlike::{EnvironmentBehavior, EnvironmentInvocation, Mode};
use techy::source::{Source, SourceSpan};
use crate::lang::{Flm, FlmSpan};
use crate::lang::flm::FlmGroupType;
use crate::lang::origin::FlmOrigin;
use crate::lang::structural;
use crate::lang::mint::{
ArgDef, ArgStdKind, DefinitionShape, ElementDef, FlmArgumentParser, FlmBodyParser,
ScopedPackageDef, SyntaxDef, field_element,
is_field_named,
};
use crate::lang::text::is_blank_text;
use crate::model::aspects::ContentRef;
use crate::model::element::ElementSpec;
use crate::model::names::{FeatureName, Name};
use crate::stdlib::features::refs::{self, LabelUse};
pub const PACKAGE: &str = "flm.math.lines";
pub const LINEBREAK_COMMAND: &str = "\\";
pub const TAG_COMMAND: &str = "tag";
pub const NONUMBER_COMMAND: &str = "nonumber";
pub const SPACING_ARG: &str = "spacing";
pub const STAR_ARG: &str = "star";
pub const TEXT_ARG: &str = "text";
fn linebreak_syntax() -> SyntaxDef {
SyntaxDef::Macro { args: vec![ArgDef::named(SPACING_ARG, SpacingParser::new())] }
}
#[derive(Debug)]
struct SpacingParser(OptionalGroupArgumentParser<Flm>);
impl SpacingParser {
fn new() -> SpacingParser {
let brackets = Arc::new(GroupRule {
group_type: FlmGroupType::Content,
open: String::from("["),
close: String::from("]"),
});
SpacingParser(OptionalGroupArgumentParser::<Flm>::new(brackets).require_adjacent())
}
}
impl ArgumentParser<Flm> for SpacingParser {
fn parse_argument(
&self,
cx: &mut ParseContext<'_, '_, Flm>,
spec: &ArgumentSpec<Flm>,
) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
self.0.parse_argument(cx, spec)
}
fn can_match_empty(&self) -> bool {
self.0.can_match_empty()
}
}
impl FlmArgumentParser for SpacingParser {
fn identity(&self) -> Vec<u8> {
b"flm.math.lines.spacing".to_vec()
}
fn definition_shape(&self) -> DefinitionShape {
DefinitionShape::Value
}
fn description(&self) -> String {
String::from("an optional `[…]` group written directly after the command")
}
}
fn linebreak_def(owner: &FeatureName) -> ElementDef {
ElementDef::new(
owner.clone(),
[LINEBREAK_COMMAND],
linebreak_syntax(),
field_element(
"A `\\\\` inside a display-math environment: the end of an equation line, \
with the optional vertical spacing written after it.",
),
)
.modes([Mode::Math])
.docs("Ends an equation line; the optional argument is vertical spacing.")
}
fn tag_def(owner: &FeatureName) -> ElementDef {
ElementDef::new(
owner.clone(),
[TAG_COMMAND],
SyntaxDef::Macro {
args: vec![
ArgDef::named(STAR_ARG, ArgStdKind::Star)
.docs("A star: the text is shown as written, without parentheses."),
ArgDef::named(TEXT_ARG, ArgStdKind::Mandatory)
.mode(Mode::Text)
.docs("The tag's text, as ordinary document content."),
],
},
field_element(
"A `\\tag{…}` or `\\tag*{…}` inside a display-math environment: a custom tag \
for the equation line, replacing its number.",
),
)
.modes([Mode::Math])
.docs(
"Gives the line a custom tag in place of its number, shown in parentheses unless \
the command is starred. The text is read in text mode, so it is ordinary document \
content: a command inside it is read as a command, and a character an output \
format must escape is escaped.",
)
}
fn nonumber_def(owner: &FeatureName) -> ElementDef {
ElementDef::new(
owner.clone(),
[NONUMBER_COMMAND],
SyntaxDef::Macro { args: Vec::new() },
field_element(
"A `\\nonumber` inside a display-math environment: the equation line is not \
to be numbered.",
),
)
.modes([Mode::Math])
.docs("Marks the line as not numbered.")
}
fn label_def(owner: &FeatureName) -> ElementDef {
ElementDef::new(
owner.clone(),
[refs::LABEL_FIELD],
SyntaxDef::Macro {
args: vec![
ArgDef::named(refs::TARGET_ARG, ArgStdKind::CharsGroup)
.docs("The label, `type:label` (`eq:main`).")
.role(refs::DEFINED_LABEL_ARG_ROLE),
],
},
field_element(
"A `\\label{type:label}` inside a display-math environment: a label on the \
equation line it is written on.",
),
)
.modes([Mode::Math])
.docs("Attaches a label to the equation line it is written on.")
}
pub fn package(owner: impl Into<FeatureName>) -> ScopedPackageDef {
let owner = owner.into();
ScopedPackageDef {
owner: owner.clone(),
name: Name::from(PACKAGE),
elements: vec![
linebreak_def(&owner),
tag_def(&owner),
nonumber_def(&owner),
label_def(&owner),
],
docs: String::from(
"The commands of a display-math environment's body: `\\\\`, `\\label`, `\\tag` \
and `\\nonumber`.",
),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineCommand {
Label,
Tag,
}
impl LineCommand {
pub fn name(self) -> &'static str {
match self {
LineCommand::Label => "label",
LineCommand::Tag => "tag",
}
}
}
impl fmt::Display for LineCommand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl ToDiagnosticValue for LineCommand {
fn to_diagnostic_value(&self) -> DiagnosticValue {
DiagnosticValue::Str(String::from(self.name()))
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.math.label-without-number",
message = "`\\{command}` must not be written on a line marked `\\nonumber` or in a \
starred environment; line {line} (counting from 0) of the `{environment}` \
environment is such a line"
)]
pub struct LabelWithoutNumber {
pub environment: String,
pub line: usize,
pub command: LineCommand,
}
#[derive(Debug)]
pub struct LinesBehavior {
numbered: bool,
}
pub fn body_behavior(numbered: bool) -> LinesBehavior {
LinesBehavior { numbered }
}
impl FlmBodyParser for LinesBehavior {
fn identity(&self) -> Vec<u8> {
let mut out = b"flm.math.lines".to_vec();
out.push(u8::from(self.numbered));
out
}
fn description(&self) -> String {
String::from("equation lines separated by `\\\\`, checked as they are read")
}
}
impl EnvironmentBehavior<Flm> for LinesBehavior {
fn make_body_parser<'p>(
&'p self,
invocation: EnvironmentInvocation<'p, Flm>,
) -> Box<dyn ConstructParser<Flm, Output = EnvironmentBody<Flm>> + 'p> {
Box::new(LinesBodyParser { invocation, numbered: self.numbered })
}
}
struct LinesBodyParser<'p> {
invocation: EnvironmentInvocation<'p, Flm>,
numbered: bool,
}
impl ConstructParser<Flm> for LinesBodyParser<'_> {
type Output = EnvironmentBody<Flm>;
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, Flm>,
) -> ConstructParserResult<Flm, (EnvironmentBody<Flm>, Option<Box<ParsingStateDelta<Flm>>>)> {
let invocation = &self.invocation;
let mut inner = EnvironmentBodyParser::new(
invocation.trigger_span.clone(),
invocation.name,
invocation.end_command_name,
FlmGroupType::Content,
)
.with_invocation_name_span(invocation.name_span.clone());
let (body, delta) = inner.parse(cx)?;
let faults = match cx.staged_nodes().get(body.body) {
Some(list) => {
let staged = cx.staged_nodes();
line_faults(staged, list.children(), invocation.name, self.numbered)
}
None => {
return Err(cx.implementation_error(
"the body parser of a display-math environment returned an unstaged body",
invocation.trigger_span.clone(),
));
}
};
for (condition, span) in faults {
cx.recover(condition, span)?;
}
Ok((body, delta))
}
}
fn line_faults(
staged: StagedNodes<'_, Flm>,
children: &[BuildId],
environment: &str,
numbered: bool,
) -> Vec<(LabelWithoutNumber, FlmSpan)> {
let pieces = children.iter().filter_map(|id| {
let node = staged.get(*id)?;
let piece = piece_of(node.kind(), &node.ext().element, node.span().source());
Some((piece, node.span().clone()))
});
let mut faults = Vec::new();
for (line, segment) in split(pieces).into_iter().enumerate() {
let unnumbered = !numbered || segment.items.iter().any(|(piece, _)| *piece == Piece::NoNumber);
if unnumbered {
for (piece, span) in &segment.items {
let command = match piece {
Piece::Label => LineCommand::Label,
Piece::Tag => LineCommand::Tag,
_ => continue,
};
let condition =
LabelWithoutNumber { environment: String::from(environment), line, command };
faults.push((condition, span.clone()));
}
}
}
faults
}
pub(crate) fn empty_lines(node: &NodeRef<'_, Flm>) -> Vec<(usize, FlmSpan)> {
let Some(body) = node.body() else {
return Vec::new();
};
let pieces = body.iter().map(|child| {
let piece = piece_of(child.kind(), &child.ext().element, child.span().source());
(piece, child.span().clone())
});
let mut empty = Vec::new();
for (line, segment) in split(pieces).into_iter().enumerate() {
if segment.items.iter().any(|(piece, _)| *piece == Piece::Content) {
continue;
}
let commands: Vec<&FlmSpan> = segment
.items
.iter()
.filter(|(piece, _)| *piece != Piece::Blank)
.map(|(_, span)| span)
.collect();
let span = match (cover(&commands), &segment.linebreak) {
(Some(span), _) => span,
(None, Some(brk)) => brk.clone(),
(None, None) => body_span(node),
};
empty.push((line, span));
}
empty
}
fn body_span(node: &NodeRef<'_, Flm>) -> FlmSpan {
let wrapper = node.callable().and_then(|callable| {
let index = callable.slots.iter().position(|slot| slot.ext.is_body())?;
node.slot_content_parent(index)
});
if let Some(wrapper) = wrapper {
return wrapper.span().clone();
}
node.body().and_then(|body| body.span()).unwrap_or_else(|| node.span().clone())
}
fn cover(spans: &[&FlmSpan]) -> Option<FlmSpan> {
let first = spans.first()?;
let last = spans.last()?;
if first.same_source(last) {
Some(SourceSpan::new(first.source(), first.start()..last.end()))
} else {
Some((*first).clone())
}
}
fn written(nodes: &NodeSlice<'_, Flm>) -> String {
match nodes.source_text() {
Some(text) => text.to_string(),
None => nodes.iter().map(|node| node.span_content()).collect(),
}
}
#[derive(Debug, Clone)]
pub struct LineBreak<'t> {
pub node: NodeRef<'t, Flm>,
pub spacing: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Tag<'t> {
pub node: NodeRef<'t, Flm>,
pub content: Vec<NodeRef<'t, Flm>>,
pub star: bool,
}
impl Tag<'_> {
pub fn parenthesized(&self) -> bool {
!self.star
}
pub fn written(&self) -> String {
self.content.iter().map(|node| node.span_content()).collect()
}
pub fn content_ref(&self) -> Option<ContentRef> {
let region = self.node.argument_nodes_named(TEXT_ARG).ok()??;
let mut nodes = region.iter();
let first = nodes.next()?;
nodes.next().is_none().then(|| ContentRef::Node(first.id()))
}
}
#[derive(Debug, Clone, Default)]
pub struct EquationLine<'t> {
pub content: Vec<NodeRef<'t, Flm>>,
pub labels: Vec<LabelUse>,
pub tag: Option<Tag<'t>>,
pub nonumber: bool,
pub linebreak: Option<LineBreak<'t>>,
}
pub fn line_break<'t>(node: &NodeRef<'t, Flm>) -> Option<LineBreak<'t>> {
if !is_field_named(node, LINEBREAK_COMMAND) {
return None;
}
let provided = node
.arguments()
.and_then(|args| args.get_named(SPACING_ARG))
.is_some_and(|arg| arg.is_provided());
let spacing = provided.then(|| {
node.argument_content_nodes_named(SPACING_ARG)
.ok()
.flatten()
.map(|content| written(&content))
.unwrap_or_default()
});
Some(LineBreak { node: *node, spacing })
}
pub fn tag_of<'t>(node: &NodeRef<'t, Flm>) -> Option<Tag<'t>> {
if !is_field_named(node, TAG_COMMAND) {
return None;
}
let star = node
.arguments()
.and_then(|args| args.get_named(STAR_ARG))
.is_some_and(|arg| arg.is_provided());
let content = node
.argument_content_nodes_named(TEXT_ARG)
.ok()
.flatten()
.map(|content| content.iter().collect())
.unwrap_or_default();
Some(Tag { node: *node, content, star })
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Piece {
Break,
Label,
Tag,
NoNumber,
Blank,
Content,
}
fn piece_of(kind: &NodeKind<Flm>, element: &ElementSpec, source: &Source<FlmOrigin>) -> Piece {
let field = match kind {
NodeKind::Callable(data) if element.name == structural::FIELD => Some(&*data.name),
_ => None,
};
if let Some(name) = field {
if name == LINEBREAK_COMMAND {
return Piece::Break;
} else if name == refs::LABEL_FIELD {
return Piece::Label;
} else if name == TAG_COMMAND {
return Piece::Tag;
} else if name == NONUMBER_COMMAND {
return Piece::NoNumber;
}
}
if element.name.as_str() == structural::PARBREAK {
Piece::Blank
} else {
match kind {
NodeKind::Comment(_) => Piece::Blank,
NodeKind::Chars { content } if is_blank_text(content.resolve(source)) => Piece::Blank,
_ => Piece::Content,
}
}
}
struct Segment<T> {
items: Vec<(Piece, T)>,
linebreak: Option<T>,
}
impl<T> Default for Segment<T> {
fn default() -> Segment<T> {
Segment { items: Vec::new(), linebreak: None }
}
}
fn split<T>(pieces: impl IntoIterator<Item = (Piece, T)>) -> Vec<Segment<T>> {
let mut lines = Vec::new();
let mut line = Segment::default();
let mut ends_with_break = false;
for (piece, value) in pieces {
match piece {
Piece::Break => {
line.linebreak = Some(value);
lines.push(std::mem::take(&mut line));
ends_with_break = true;
}
Piece::Blank => line.items.push((piece, value)),
_ => {
ends_with_break = false;
line.items.push((piece, value));
}
}
}
if ends_with_break {
if let Some(last) = lines.last_mut() {
last.linebreak = None;
last.items.append(&mut line.items);
}
} else {
lines.push(line);
}
lines
}
pub fn equation_lines<'t>(node: &NodeRef<'t, Flm>) -> Vec<EquationLine<'t>> {
let Some(body) = node.body() else {
return Vec::new();
};
let pieces = body.iter().map(|child| {
let piece = piece_of(child.kind(), &child.ext().element, child.span().source());
(piece, child)
});
split(pieces)
.into_iter()
.map(|segment| {
let mut line = EquationLine::default();
for (piece, child) in segment.items {
match piece {
Piece::Label => {
if let Some(label) = refs::label_use(&child) {
line.labels.push(label);
}
}
Piece::Tag => line.tag = tag_of(&child),
Piece::NoNumber => line.nonumber = true,
Piece::Blank | Piece::Content => line.content.push(child),
Piece::Break => {}
}
}
line.linebreak = segment.linebreak.as_ref().and_then(line_break);
line
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lang::structural::FIELD;
#[test]
fn the_package_declares_the_four_commands_in_math_mode_only() {
let package = package("math");
assert_eq!(package.name, PACKAGE);
let names: Vec<Vec<String>> = package
.elements
.iter()
.map(|def| def.names.iter().map(|n| n.to_string()).collect())
.collect();
assert_eq!(names, [vec!["\\"], vec!["tag"], vec!["nonumber"], vec!["label"]]);
assert!(package.elements.iter().all(|def| def.modes == vec![Mode::Math]));
assert!(package.elements.iter().all(|def| def.owner == "math"));
}
#[test]
fn every_declaration_is_a_field_named_for_the_command() {
let package = package("math");
let fields: Vec<&str> = package
.elements
.iter()
.map(|def| {
assert_eq!(def.element.name, FIELD, "every line command is a field");
def.names[0].as_str()
})
.collect();
assert_eq!(fields, [LINEBREAK_COMMAND, TAG_COMMAND, NONUMBER_COMMAND, refs::LABEL_FIELD]);
}
#[test]
fn the_split_drops_a_final_break_and_opens_a_line_for_a_command_after_it() {
use Piece::*;
let pieces = |seq: &[Piece]| seq.iter().enumerate().map(|(i, p)| (*p, i)).collect::<Vec<_>>();
let lines = split(pieces(&[Content, Break, Blank]));
assert_eq!(lines.len(), 1);
assert_eq!(lines[0].items.iter().map(|(p, v)| (*p, *v)).collect::<Vec<_>>(), [(Content, 0), (Blank, 2)]);
assert!(lines[0].linebreak.is_none());
let lines = split(pieces(&[Content, Break, Blank, Label]));
assert_eq!(lines.len(), 2);
assert_eq!(lines[0].linebreak, Some(1));
assert_eq!(lines[1].items.iter().map(|(p, _)| *p).collect::<Vec<_>>(), [Blank, Label]);
assert!(lines[1].linebreak.is_none());
let lines = split(pieces(&[Break, Blank, Break, Blank]));
assert_eq!(lines.len(), 2);
assert_eq!(lines[0].linebreak, Some(0));
assert_eq!(lines[1].items.iter().map(|(p, v)| (*p, *v)).collect::<Vec<_>>(), [(Blank, 1), (Blank, 3)]);
assert!(lines[1].linebreak.is_none());
assert_eq!(split(pieces(&[])).len(), 1);
}
}