Skip to main content

latexml_core/common/
glue.rs

1use std::{cmp::Ordering, fmt, sync::LazyLock};
2
3use regex::Regex;
4
5use super::dimension::fixedformat;
6use crate::{
7  Object,
8  common::{
9    dimension::attribute_format,
10    error::Result,
11    numeric_ops::{EPSILON, NumericOps, fixpoint, fixpoint_unit, kround},
12  },
13  definition::register::{RegisterType, RegisterValue},
14  digested::Digested,
15  state::*,
16  tokens::Tokens,
17};
18
19/// Positively silly enum, but it solves all kinds of issues with the Glue struct
20/// most importantly allows us to keep deriving the Copy trait, and avoids storing
21/// strings in Glue objects
22#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
23pub enum FillCode {
24  Fil,
25  Fill,
26  Filll,
27}
28
29impl fmt::Display for FillCode {
30  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.to_str()) }
31}
32
33impl FillCode {
34  pub fn new(index: usize) -> Option<FillCode> {
35    match index {
36      1 => Some(FillCode::Fil),
37      2 => Some(FillCode::Fill),
38      3 => Some(FillCode::Filll),
39      _ => None,
40    }
41  }
42  pub fn from(ftype: &str) -> Option<FillCode> {
43    match ftype {
44      "fil" => Some(FillCode::Fil),
45      "fill" => Some(FillCode::Fill),
46      "filll" => Some(FillCode::Filll),
47      _ => None,
48    }
49  }
50  pub fn to_str(&self) -> &'static str {
51    match self {
52      FillCode::Fil => "fil",
53      FillCode::Fill => "fill",
54      FillCode::Filll => "filll",
55    }
56  }
57}
58
59// Note: Regexes are not first-level objects in Rust, and neither are Strings
60//       yet we would like to have some efficient
61macro_rules! num_re_str {
62  () => {
63    r"\d*\.?\d*"
64  };
65}
66macro_rules! unit_re_str {
67  () => {
68    r"[a-zA-Z][a-zA-Z]"
69  };
70}
71macro_rules! fill_re_str {
72  () => {
73    r"fil|fill|filll|[a-zA-Z][a-zA-Z]"
74  };
75}
76
77macro_rules! plus_re_str {
78  () => {
79    concat!(r"\s+plus\s*(", num_re_str!(), ")(", fill_re_str!(), r")")
80  };
81}
82macro_rules! minus_re_str {
83  () => {
84    concat!(r"\s+minus\s*(", num_re_str!(), r")(", fill_re_str!(), r")")
85  };
86}
87
88static GLUE_RE_STR: &str = concat!(
89  r"^(\+?\-?",
90  num_re_str!(),
91  r")(",
92  unit_re_str!(),
93  r")(",
94  plus_re_str!(),
95  r")?(",
96  minus_re_str!(),
97  r")?$"
98);
99
100static _NUM_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(num_re_str!()).unwrap());
101static UNIT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(unit_re_str!()).unwrap());
102static _FILL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(fill_re_str!()).unwrap());
103static _PLUS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(plus_re_str!()).unwrap());
104static _MINUS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(minus_re_str!()).unwrap());
105static GLUE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(GLUE_RE_STR).unwrap());
106
107/// Whether `spec` is a form Perl's `Glue($spec)`/`MuGlue($spec)` reads (Glue.pm `new`): `$GLUE_re`, or a bare
108/// number of sp; any other string Perl Warns "Missing Glue specification" and reads as 0.
109pub fn is_glue_spec(spec: &str) -> bool {
110  GLUE_RE.is_match(spec) || (!UNIT_RE.is_match(spec) && spec.parse::<f64>().is_ok())
111}
112
113#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
114pub struct Glue {
115  pub skip:  i64,
116  pub plus:  Option<i64>,
117  pub pfill: Option<FillCode>,
118  pub minus: Option<i64>,
119  pub mfill: Option<FillCode>,
120}
121
122impl NumericOps for Glue {
123  fn value_of(self) -> i64 { self.skip }
124  fn register_type(&self) -> RegisterType { RegisterType::Glue }
125  // identity, used to type cast in runtime
126  fn into_glue_type(self) -> Glue { self }
127  fn add<T: NumericOps>(self, other: T) -> Self
128  where Self: Sized {
129    if other.register_type() != RegisterType::Glue {
130      Glue {
131        skip:  self.skip + other.value_of(),
132        plus:  self.plus,
133        pfill: self.pfill,
134        minus: self.minus,
135        mfill: self.mfill,
136      }
137    } else {
138      // Both glues, add
139      self.add_glue(other.into_glue_type())
140    }
141  }
142  fn new(skip: i64) -> Self {
143    Glue {
144      skip,
145      plus: None,
146      pfill: None,
147      minus: None,
148      mfill: None,
149    }
150  }
151  fn new_f64(number: f64) -> Self {
152    let (skip, plus, pfill, minus, mfill) = new_setup(number, None, None, None, None);
153    Glue {
154      skip,
155      plus,
156      pfill,
157      minus,
158      mfill,
159    }
160  }
161  // Perl Glue.pm: multiply scales skip, plus, AND minus components
162  fn multiply<T: NumericOps>(self, other: T) -> Self
163  where Self: Sized {
164    let factor = other.value_f64();
165    Glue {
166      skip:  (self.skip as f64 * factor) as i64,
167      plus:  self.plus.map(|p| (p as f64 * factor) as i64),
168      pfill: self.pfill,
169      minus: self.minus.map(|m| (m as f64 * factor) as i64),
170      mfill: self.mfill,
171    }
172  }
173  // Perl Glue.pm: divide scales skip, plus, AND minus components
174  fn divide<T: NumericOps>(self, other: T) -> Self
175  where Self: Sized {
176    let mut divisor = other.value_f64();
177    if divisor == 0.0 {
178      divisor = EPSILON;
179    }
180    Glue {
181      skip:  (self.skip as f64 / divisor).trunc() as i64,
182      plus:  self.plus.map(|p| (p as f64 / divisor).trunc() as i64),
183      pfill: self.pfill,
184      minus: self.minus.map(|m| (m as f64 / divisor).trunc() as i64),
185      mfill: self.mfill,
186    }
187  }
188  fn subtract<T: NumericOps>(self, other: T) -> Self
189  where Self: Sized {
190    if other.register_type() != RegisterType::Glue {
191      Glue {
192        skip:  self.skip - other.value_of(),
193        plus:  self.plus,
194        pfill: self.pfill,
195        minus: self.minus,
196        mfill: self.mfill,
197      }
198    } else {
199      let other_glue = other.into_glue_type();
200      self.add_glue(Glue {
201        skip:  -other_glue.skip,
202        plus:  other_glue.plus.map(|p| -p),
203        pfill: other_glue.pfill,
204        minus: other_glue.minus.map(|m| -m),
205        mfill: other_glue.mfill,
206      })
207    }
208  }
209  // Negate all components (skip, plus, minus)
210  fn negate(self) -> Self {
211    Glue {
212      skip:  -self.skip,
213      plus:  self.plus.map(|p| -p),
214      pfill: self.pfill,
215      minus: self.minus.map(|m| -m),
216      mfill: self.mfill,
217    }
218  }
219  fn smaller<T: NumericOps>(self, other: T) -> Self
220  where Self: Sized {
221    let other_val = other.value_of();
222    if self.skip <= other_val {
223      self
224    } else {
225      Self::new(other_val)
226    }
227  }
228  fn larger<T: NumericOps>(self, other: T) -> Self
229  where Self: Sized {
230    let other_val = other.value_of();
231    if self.skip >= other_val {
232      self
233    } else {
234      Self::new(other_val)
235    }
236  }
237}
238
239pub fn glue_string(
240  skip: i64,
241  plus_opt: Option<i64>,
242  pfill_opt: Option<FillCode>,
243  minus_opt: Option<i64>,
244  mfill_opt: Option<FillCode>,
245  unit: &str,
246) -> String {
247  // ??? TODO: There seems to be some messy confusion about the types of the
248  // pieces of glue/dimensions -- are we consistently using i64 or f64?
249  let mut string = fixedformat(skip, Some(unit));
250  if let Some(plus) = plus_opt
251    && plus != 0
252  {
253    string.push_str(" plus ");
254    let p_fill = if let Some(fill) = pfill_opt {
255      fill.to_str()
256    } else {
257      unit
258    };
259    string.push_str(&fixedformat(plus, Some(p_fill)))
260  }
261  if let Some(minus) = minus_opt
262    && minus != 0
263  {
264    string.push_str(" minus ");
265    let p_fill = if let Some(fill) = mfill_opt {
266      fill.to_str()
267    } else {
268      unit
269    };
270    string.push_str(&fixedformat(minus, Some(p_fill)))
271  }
272  string
273}
274
275impl fmt::Display for Glue {
276  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
277    let string = glue_string(
278      self.skip, self.plus, self.pfill, self.minus, self.mfill, "pt",
279    );
280    write!(f, "{string}")
281  }
282}
283impl Object for Glue {
284  /// Perl `Common/Number.pm` `revert` (inherited by Glue): `ExplodeText($self->toString)`.
285  /// The default (no tokens) reverted `\hspace{10pt}` to a bare `\hskip`. A
286  /// glue ending in a `fil` unit takes a space after it, which ends the unit
287  /// (tex.web ยง454 reads further `l`s): `$x\hspace{\stretch{1}}l$` reverted to
288  /// `\hskip 0.0pt plus 1.0filll`, which swallows the `l`.
289  fn revert(&self) -> Result<Tokens> {
290    let string = self.to_string();
291    let mut tokens = ExplodeText!(&string);
292    if string.ends_with("fil") || string.ends_with("fill") || string.ends_with("filll") {
293      tokens.push(crate::token::Token::new(" ", crate::token::Catcode::SPACE));
294    }
295    Ok(Tokens::new(tokens))
296  }
297  fn be_digested(self) -> Result<Digested> { Ok(RegisterValue::Glue(self).into()) }
298}
299
300pub fn new_setup(
301  skip: f64,
302  plus: Option<f64>,
303  pfill: Option<FillCode>,
304  minus: Option<f64>,
305  mfill: Option<FillCode>,
306) -> (
307  i64,
308  Option<i64>,
309  Option<FillCode>,
310  Option<i64>,
311  Option<FillCode>,
312) {
313  // See comment in Dimension for why kround rather than int
314  (
315    kround(skip),
316    plus.map(kround),
317    pfill,
318    minus.map(kround),
319    mfill,
320  )
321}
322
323pub fn spec_setup(
324  spec: &str,
325  plus: Option<f64>,
326  mut pfill: Option<FillCode>,
327  minus: Option<f64>,
328  mut mfill: Option<FillCode>,
329  unit: &str,
330) -> (
331  i64,
332  Option<i64>,
333  Option<FillCode>,
334  Option<i64>,
335  Option<FillCode>,
336) {
337  if !UNIT_RE.is_match(spec) {
338    // If no units, expect fixedpoint values
339    let skip: f64 = spec.parse::<f64>().unwrap_or_default();
340    new_setup(skip, plus, pfill, minus, mfill)
341  } else {
342    let is_mu = unit == "mu";
343    if plus.is_some() || pfill.is_some() || minus.is_some() || mfill.is_some() {
344      let msg = s!(
345        "You should not create {} with both units and stretch",
346        if is_mu { "MuGlue" } else { "Glue" }
347      );
348      Warn!("unexpected", "fill", msg);
349    }
350
351    if let Some(cs) = GLUE_RE.captures(spec) {
352      let (f, unit, p, punit, m, munit) = (
353        cs.get(1)
354          .map(|v| v.as_str().parse::<f64>().unwrap_or_default())
355          .unwrap_or_default(),
356        cs.get(2).map_or("", |m| m.as_str()),
357        cs.get(4)
358          .map(|v| v.as_str().parse::<f64>().unwrap_or_default())
359          .unwrap_or_default(),
360        cs.get(5).map_or("", |m| m.as_str()),
361        cs.get(7)
362          .map(|v| v.as_str().parse::<f64>().unwrap_or_default())
363          .unwrap_or_default(),
364        cs.get(8).map_or("", |m| m.as_str()),
365      );
366      let skip = if unit.is_empty() {
367        f.trunc() as i64
368      } else if is_mu {
369        if unit != "mu" {
370          Warn!("unexpected", unit, "Assumed mu");
371        }
372        fixpoint(f, None) // in mu
373      } else {
374        {
375          let (num, den) = convert_unit_ratio(unit);
376          fixpoint_unit(f, num, den)
377        }
378      };
379
380      let plus = if punit.is_empty() {
381        None // Some(0.0) ?
382      // ? punit = "0";
383      } else if let Some(code) = FillCode::from(punit) {
384        pfill = Some(code);
385        Some(fixpoint(p, None))
386      } else if is_mu {
387        pfill = None;
388        if punit != "mu" {
389          Warn!("unexpected", punit, "Assumed mu");
390        }
391        Some(fixpoint(p, None))
392      } else {
393        pfill = None; // ? 0
394        Some({
395          let (num, den) = convert_unit_ratio(punit);
396          fixpoint_unit(p, num, den)
397        })
398      };
399
400      let minus = if munit.is_empty() {
401        None // ? Some(0.0);
402      // munit = 0;
403      } else if let Some(code) = FillCode::from(munit) {
404        mfill = Some(code);
405        Some(fixpoint(m, None))
406      } else if is_mu {
407        mfill = None; // 0
408        if munit != "mu" {
409          Warn!("unexpected", munit, "Assumed mu");
410        }
411        Some(fixpoint(m, None))
412      } else {
413        mfill = None; // 0
414        Some({
415          let (num, den) = convert_unit_ratio(munit);
416          fixpoint_unit(m, num, den)
417        })
418      };
419
420      (skip, plus, pfill, minus, mfill)
421    } else {
422      let msg = s!(
423        "Missing {} specification assuming 0pt",
424        if is_mu { "MuGlue" } else { "Glue" }
425      );
426      Warn!("unexpected", spec, msg);
427      (0, None, None, None, None)
428    }
429  }
430}
431
432impl Glue {
433  pub fn new_full(
434    skip: i64,
435    plus: Option<i64>,
436    pfill: Option<FillCode>,
437    minus: Option<i64>,
438    mfill: Option<FillCode>,
439  ) -> Self {
440    Glue {
441      skip,
442      plus,
443      pfill,
444      minus,
445      mfill,
446    }
447  }
448  pub fn new_full_f64(
449    skip: f64,
450    plus: Option<f64>,
451    pfill: Option<FillCode>,
452    minus: Option<f64>,
453    mfill: Option<FillCode>,
454  ) -> Self {
455    let (skip, plus, pfill, minus, mfill) = new_setup(skip, plus, pfill, minus, mfill);
456    Glue {
457      skip,
458      plus,
459      pfill,
460      minus,
461      mfill,
462    }
463  }
464  pub fn new_spec(
465    spec: &str,
466    plus: Option<f64>,
467    pfill: Option<FillCode>,
468    minus: Option<f64>,
469    mfill: Option<FillCode>,
470  ) -> Self {
471    let (skip, plus, pfill, minus, mfill) = spec_setup(spec, plus, pfill, minus, mfill, "pt");
472    Glue {
473      skip,
474      plus,
475      pfill,
476      minus,
477      mfill,
478    }
479  }
480
481  pub fn add_glue(self, other: Glue) -> Glue {
482    // (pts, p, pf, m, mf) = @$self;
483    // if (ref $other eq 'LaTeXML::Common::Glue') {
484    // my ($pts2, $p2, $pf2, $m2, $mf2) = @$other;
485    let skip = self.skip + other.skip;
486    let mut plus = self.plus;
487    let mut minus = self.minus;
488    let mut pfill = self.pfill;
489    let mut mfill = self.mfill;
490
491    match self.pfill.cmp(&other.pfill) {
492      Ordering::Equal => {
493        if let Some(oplus) = other.plus {
494          plus = match plus {
495            Some(splus) => Some(splus + oplus),
496            None => Some(oplus),
497          };
498        }
499      },
500      Ordering::Less => {
501        plus = other.plus;
502        pfill = other.pfill;
503      },
504      _ => {},
505    };
506    match self.mfill.cmp(&other.mfill) {
507      Ordering::Equal => {
508        if let Some(ominus) = other.minus {
509          minus = match minus {
510            Some(sminus) => Some(sminus + ominus),
511            None => Some(ominus),
512          };
513        }
514      },
515      Ordering::Less => {
516        minus = other.minus;
517        mfill = other.mfill;
518      },
519      _ => {},
520    };
521
522    Glue {
523      skip,
524      plus,
525      pfill,
526      minus,
527      mfill,
528    }
529    // else {
530    // return (ref $self)->new($pts + $other->valueOf, $p, $pf, $m, $mf); }
531  }
532
533  pub fn to_attribute(&self) -> String {
534    let u = "pt";
535    let mut string = attribute_format(self.skip, Some(u));
536    if let Some(plus) = self.plus
537      && plus != 0
538    {
539      string.push_str(" plus ");
540      let fill_u = if let Some(pfill) = self.pfill {
541        pfill.to_str()
542      } else {
543        u
544      };
545      string.push_str(&attribute_format(plus, Some(fill_u)));
546    }
547    if let Some(minus) = self.minus
548      && minus != 0
549    {
550      string.push_str(" minus ");
551      let mfill_u = if let Some(mfill) = self.mfill {
552        mfill.to_str()
553      } else {
554        u
555      };
556      string.push_str(&attribute_format(minus, Some(mfill_u)));
557    }
558    string
559  }
560}
561
562#[cfg(test)]
563mod tests {
564  use super::*;
565
566  #[test]
567  fn fillcode_new_from_index() {
568    assert_eq!(FillCode::new(1), Some(FillCode::Fil));
569    assert_eq!(FillCode::new(2), Some(FillCode::Fill));
570    assert_eq!(FillCode::new(3), Some(FillCode::Filll));
571    assert_eq!(FillCode::new(0), None);
572    assert_eq!(FillCode::new(4), None);
573    assert_eq!(FillCode::new(100), None);
574  }
575
576  #[test]
577  fn fillcode_from_str_case_sensitive() {
578    assert_eq!(FillCode::from("fil"), Some(FillCode::Fil));
579    assert_eq!(FillCode::from("fill"), Some(FillCode::Fill));
580    assert_eq!(FillCode::from("filll"), Some(FillCode::Filll));
581    // Case-sensitive: uppercase is rejected.
582    assert_eq!(FillCode::from("FIL"), None);
583    assert_eq!(FillCode::from("Fil"), None);
584    assert_eq!(FillCode::from(""), None);
585    assert_eq!(FillCode::from("other"), None);
586  }
587
588  #[test]
589  fn fillcode_to_str_roundtrip() {
590    // from(to_str(c)) == c for all variants.
591    for code in [FillCode::Fil, FillCode::Fill, FillCode::Filll] {
592      let s = code.to_str();
593      assert_eq!(
594        FillCode::from(s),
595        Some(code),
596        "roundtrip broke at {code:?} via {s:?}"
597      );
598    }
599  }
600
601  #[test]
602  fn fillcode_display_matches_to_str() {
603    assert_eq!(format!("{}", FillCode::Fil), "fil");
604    assert_eq!(format!("{}", FillCode::Fill), "fill");
605    assert_eq!(format!("{}", FillCode::Filll), "filll");
606  }
607
608  #[test]
609  fn fillcode_ord_fil_lt_fill_lt_filll() {
610    // Derived Ord follows variant declaration order.
611    assert!(FillCode::Fil < FillCode::Fill);
612    assert!(FillCode::Fill < FillCode::Filll);
613  }
614
615  #[test]
616  fn glue_default_is_zero_skip_no_stretch() {
617    let g = Glue::default();
618    assert_eq!(g.skip, 0);
619    assert_eq!(g.plus, None);
620    assert_eq!(g.minus, None);
621    assert_eq!(g.pfill, None);
622    assert_eq!(g.mfill, None);
623  }
624
625  #[test]
626  fn glue_new_builds_skip_only() {
627    let g = <Glue as NumericOps>::new(65536);
628    assert_eq!(g.skip, 65536);
629    assert_eq!(g.plus, None);
630    assert_eq!(g.minus, None);
631  }
632
633  #[test]
634  fn glue_value_of_returns_skip() {
635    let g = Glue {
636      skip:  1234,
637      plus:  Some(10),
638      pfill: None,
639      minus: None,
640      mfill: None,
641    };
642    assert_eq!(
643      g.value_of(),
644      1234,
645      "value_of returns the skip, not the stretch"
646    );
647  }
648}