use crate::{ expanded::{ExpandedTokenStream, FrontendEventKind}, math_expr::MathInfixFractionKind, source::{SourceLocation, SourceOrigin}, }; #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum MathScope { Display, Inline, Environment(String), } impl MathScope { pub fn from_start_event(kind: &FrontendEventKind) -> Option { match kind { FrontendEventKind::DisplayMathStart => Some(Self::Display), FrontendEventKind::InlineMathStart => Some(Self::Inline), FrontendEventKind::BeginEnvironment { name, .. } if is_display_math_environment(name) => { Some(Self::Environment(name.clone())) } _ => None, } } pub fn from_end_event(kind: &FrontendEventKind) -> Option { match kind { FrontendEventKind::DisplayMathEnd(_) => Some(Self::Display), FrontendEventKind::InlineMathEnd(_) => Some(Self::Inline), FrontendEventKind::EndEnvironment { name, .. } if is_display_math_environment(name) => { Some(Self::Environment(name.clone())) } _ => None, } } fn is_display(&self) -> bool { !matches!(self, Self::Inline) } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum TeXMode { Vertical, Horizontal, InlineMath, DisplayMath, } pub struct TeXModeState { mode: TeXMode, math_scope: Option, math_opened_at: Option, } impl Default for TeXModeState { fn default() -> Self { Self { mode: TeXMode::Vertical, math_scope: None, math_opened_at: None, } } } impl TeXModeState { pub fn enter_math(&mut self, scope: MathScope, location: SourceLocation) { self.mode = if scope.is_display() { TeXMode::DisplayMath } else { TeXMode::InlineMath }; self.math_scope = Some(scope); self.math_opened_at = Some(location); } pub fn leave_math(&mut self) { self.mode = match self.mode { TeXMode::InlineMath => TeXMode::Horizontal, TeXMode::DisplayMath => TeXMode::Vertical, TeXMode::Vertical | TeXMode::Horizontal => self.mode, }; self.math_scope = None; self.math_opened_at = None; } pub fn is_math(&self) -> bool { matches!(self.mode, TeXMode::InlineMath | TeXMode::DisplayMath) } pub fn is_display_math(&self) -> bool { self.mode == TeXMode::DisplayMath } pub fn math_scope(&self) -> Option<&MathScope> { self.math_scope.as_ref() } pub fn math_opened_at(&self) -> Option<&SourceLocation> { self.math_opened_at.as_ref() } } pub fn is_display_math_environment(environment: &str) -> bool { matches!( environment, "equation" | "equation*" | "align" | "align*" | "alignat" | "alignat*" | "flalign" | "flalign*" | "eqnarray" | "eqnarray*" | "gather" | "gather*" | "multline" | "multline*" | "displaymath" ) } type Delimiter = MathScope; pub fn validate_math_delimiters(source: &ExpandedTokenStream) -> Result<(), String> { use FrontendEventKind as Event; let mut mode = TeXModeState::default(); let mut active_math: Option<(Vec, Vec)> = None; for event in &source.events { if mode.is_math() { let (left_delimiters, fraction_scopes) = active_math .as_mut() .expect("active math mode has its delimiter validation state"); if Delimiter::from_end_event(&event.kind).as_ref() == mode.math_scope() { if let Some(location) = left_delimiters.last() { return Err(math_delimiter_error( location, "missing `\\right` for this `\\left`", )); } mode.leave_math(); active_math = None; continue; } if Delimiter::from_end_event(&event.kind).is_some() { return Err(math_delimiter_error( mode.math_opened_at().unwrap_or(&event.location), "the math-mode closing delimiter does not match its opening delimiter", )); } if Delimiter::from_start_event(&event.kind).is_some() { return Err(math_delimiter_error( &event.location, "math mode cannot be started inside math mode", )); } if matches!(event.kind, Event::ParagraphBreak) { return Err(math_delimiter_error( &event.location, "`\\par` is not allowed in math mode", )); } if matches!(event.kind, Event::VerticalGlue(_)) { return Err(math_delimiter_error( &event.location, "vertical glue is not allowed in math mode", )); } if matches!(event.kind, Event::EquationTag(_)) && !mode.is_display_math() { return Err(math_delimiter_error( &event.location, "`\\tag` must appear inside display math", )); } match &event.kind { Event::MathDelimiterStart { .. } => { left_delimiters.push(event.location.clone()); fraction_scopes.push(0); } Event::MathDelimiterMiddle { .. } if left_delimiters.is_empty() => { return Err(math_delimiter_error( &event.location, "`\\middle` must appear between `\\left` and `\\right`", )); } Event::MathDelimiterEnd { .. } if left_delimiters.is_empty() => { return Err(math_delimiter_error( &event.location, "`\\right` has no matching `\\left`", )); } Event::MathDelimiterEnd { .. } => { left_delimiters.pop(); if fraction_scopes.len() > 1 { fraction_scopes.pop(); } } Event::MathManualDelimiter { .. } => {} Event::MathUnicodeDelimiter { .. } => {} _ => {} } match &event.kind { Event::MathInfixFraction(..) => { let count = fraction_scopes .last_mut() .expect("math scope always has a fraction counter"); *count += 1; if *count > 1 { return Err(math_delimiter_error( &event.location, "Ambiguous; you need another `{` and `}`", )); } } Event::GroupStart | Event::MathFractionStart { .. } | Event::MathRootStart { .. } | Event::MathAccentStart { .. } | Event::MathFontStart(_) | Event::MathOperatorStart | Event::MathClassStart(_) => fraction_scopes.push(0), Event::GroupEnd | Event::MathFractionEnd | Event::MathRootEnd | Event::MathAccentEnd | Event::MathFontEnd | Event::MathOperatorEnd | Event::MathClassEnd => { if fraction_scopes.len() > 1 { fraction_scopes.pop(); } } Event::MathFractionSeparator | Event::MathRootSeparator => { *fraction_scopes .last_mut() .expect("math scope always has a fraction counter") = 0; } Event::MathCell | Event::RowBreak => { *fraction_scopes .last_mut() .expect("math scope always has a fraction counter") = 0; } Event::MathChoiceStart => fraction_scopes.push(0), Event::MathChoiceBranch(_) => { *fraction_scopes .last_mut() .expect("math scope always has a fraction counter") = 0; } Event::MathChoiceEnd => { if fraction_scopes.len() > 1 { fraction_scopes.pop(); } } _ => {} } continue; } if Delimiter::from_end_event(&event.kind).is_some() { return Err(math_delimiter_error( &event.location, "math-mode closing delimiter has no matching opening delimiter", )); } if let Some(scope) = Delimiter::from_start_event(&event.kind) { mode.enter_math(scope, event.location.clone()); active_math = Some((Vec::new(), vec![0])); continue; } let message = match &event.kind { Event::MathDelimiterStart { .. } => Some("`\\left` must appear inside math mode"), Event::MathDelimiterMiddle { .. } => { Some("`\\middle` must appear between `\\left` and `\\right`") } Event::MathDelimiterEnd { .. } => Some("`\\right` has no matching `\\left`"), Event::MathInfixFraction(kind, _) => Some(match kind { MathInfixFractionKind::Over => "`\\over` must appear inside math mode", MathInfixFractionKind::Atop => "`\\atop` must appear inside math mode", MathInfixFractionKind::Choose(_) => "`\\choose` must appear inside math mode", MathInfixFractionKind::Above(_) => "`\\above` must appear inside math mode", MathInfixFractionKind::OverWithDelims(_) => { "`\\overwithdelims` must appear inside math mode" } MathInfixFractionKind::AtopWithDelims(_) => { "`\\atopwithdelims` must appear inside math mode" } MathInfixFractionKind::AboveWithDelims { .. } => { "`\\abovewithdelims` must appear inside math mode" } }), Event::MathManualDelimiter { .. } => { Some("manual delimiter size commands must appear inside math mode") } Event::MathCharacter { .. } | Event::MathUnicodeCharacter { .. } => { Some("math characters must appear inside math mode") } Event::MathUnicodeDelimiter { .. } => { Some("Unicode math delimiters must appear inside math mode") } Event::MathStyleChange(_) => Some("math style commands must appear inside math mode"), Event::MathChoiceStart | Event::MathChoiceBranch(_) | Event::MathChoiceEnd => { Some("\\mathchoice must appear inside math mode") } Event::EquationTag(_) => Some("`\\tag` must appear inside display math"), _ => None, }; if let Some(message) = message { return Err(math_delimiter_error(&event.location, message)); } } if let Some((left_delimiters, _)) = active_math && let Some(location) = left_delimiters.last() { return Err(math_delimiter_error( location, "missing `\\right` for this `\\left`", )); } if let Some(location) = mode.math_opened_at() { return Err(math_delimiter_error( location, "math mode has no matching closing delimiter", )); } Ok(()) } pub fn math_delimiter_error(location: &SourceLocation, message: &str) -> String { let origin = match &location.origin { SourceOrigin::File(path) => path.display().to_string(), SourceOrigin::Terminal => "".to_string(), }; format!("{origin}:{}:{}: {message}", location.line, location.column) }