Skip to main content

latexml_core/definition/
conditional.rs

1//! Conditionals Control sequence definitions.
2//! These represent the control sequences for conditionals, as well as
3//! `\else`, `\or` and `\fi`.
4
5use std::{borrow::Cow, cell::RefCell, fmt, rc::Rc};
6
7use libxml::tree::Node;
8
9// use crate::common::numeric_ops::NumericOps;
10use crate::Digested;
11use crate::{
12  common::{
13    error::{emit_warn, *},
14    locator::Locator,
15    object::Object,
16  },
17  definition::{BeforeDigestClosure, ConditionalClosure, Definition, DigestionClosure},
18  document::Document,
19  gullet,
20  parameter::Parameters,
21  pin,
22  state::*,
23  token::*,
24  tokens::Tokens,
25  whatsit::Whatsit,
26};
27
28// Conditional control sequences; Expandable
29//   Expand enough to determine true/false, then maybe skip
30//   record a flag somewhere so that \else or \fi is recognized
31//   (otherwise, they should signal an error)
32
33/// classify the standard pieces of a conditional
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum ConditionalType {
36  /// \if
37  If,
38  /// \unless
39  Unless,
40  /// \else
41  Else,
42  /// \or
43  Or,
44  /// \fi
45  Fi,
46  /// fallback?
47  Unknown,
48}
49
50impl From<&str> for ConditionalType {
51  fn from(cs: &str) -> Self {
52    use self::ConditionalType::*;
53    match cs {
54      "\\if" => If,
55      "\\unless" => Unless,
56      "\\else" => Else,
57      "\\or" => Or,
58      "\\fi" => Fi,
59      _ => If,
60    }
61  }
62}
63
64/// configurations for a conditional.
65#[derive(Default)]
66pub struct ConditionalOptions {
67  /// scope to install in state
68  pub scope:   Option<Scope>,
69  /// is this definition locked?
70  pub locked:  Option<bool>,
71  /// skipper, currently only used for \ifcase.
72  // TODO: implement this?
73  pub skipper: Option<bool>,
74}
75
76/// A Conditional definition; Expandable.
77#[derive(Clone)]
78pub struct Conditional {
79  /// the command sequence
80  pub cs:               Token,
81  /// list of parameters, if any
82  pub paramlist:        Option<Parameters>,
83  /// a test closure, if implemented in a binding
84  pub test:             Option<ConditionalClosure>,
85  /// the kind of piece in the syntax (if,else,fi...)
86  pub conditional_type: ConditionalType,
87  /// a skipper for \ifcase
88  pub skipper:          Option<bool>,
89  pub origin:           crate::definition::origin::DefinitionOrigin,
90}
91impl Default for Conditional {
92  fn default() -> Self {
93    Conditional {
94      cs:               T_CS!("Conditional"),
95      paramlist:        None,
96      test:             None,
97      conditional_type: ConditionalType::Unknown,
98      skipper:          None,
99      origin:           crate::definition::origin::current_origin(),
100    }
101  }
102}
103impl PartialEq for Conditional {
104  fn eq(&self, other: &Conditional) -> bool { self.cs == other.cs }
105}
106
107impl fmt::Display for Conditional {
108  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.cs) }
109}
110impl Object for Conditional {
111  fn is_expandable(&self) -> bool { true }
112  fn stringify(&self) -> String { self.stringify_type("Conditional") }
113}
114impl Definition for Conditional {
115  // sub new {
116  //   my ($class, $cs, $parameters, $test, %traits) = @_;
117  //   my $source = $state->getStomach->getGullet->getMouth;
118  //   return bless { cs => $cs, parameters => $parameters, test => $test,
119  //     locator      => "from " . $source->getLocator(-1),
120  //     isExpandable => 1,
121  //     %traits }, $class; }
122
123  // Note that although conditionals are Expandable,
124  // they are NOT defined as macros, so they don't need to handle doInvocation,
125  fn invoke(&self, _once_only: bool) -> Result<Tokens> {
126    // A real conditional must have condition_type set
127    use self::ConditionalType::*;
128    match self.conditional_type {
129      If | Unless => self.invoke_conditional(),
130      Else | Or => self.invoke_else(),
131      Fi => self.invoke_fi(),
132      _ => {
133        // Diagnostic-only path: format the current CS name, or "\\?" if the
134        // current-token register is empty. Never panic here — we are
135        // already in error-emission territory.
136        let cur = get_current_token()
137          .map(|t| t.stringify())
138          .unwrap_or_else(|| String::from("\\?"));
139        let message = s!("Unknown conditional control sequence {}", cur);
140        Error!("unexpected", self.cs, message);
141        Ok(Tokens!())
142      },
143    }
144  }
145
146  fn get_parameters(&self) -> Option<&Parameters> { self.paramlist.as_ref() }
147  fn get_cs(&self) -> Cow<'_, Token> { Cow::Borrowed(&self.cs) }
148  fn get_cs_name(&self) -> Cow<'_, str> { Cow::Owned(self.cs.with_cs_name(ToString::to_string)) }
149  fn get_alias(&self) -> Option<&String> { None }
150  fn get_test(&self) -> Option<&ConditionalClosure> { self.test.as_ref() }
151  fn get_conditional_type(&self) -> Option<ConditionalType> { Some(self.conditional_type) }
152  // Not implemented for expandable
153  fn invoke_primitive(&self) -> Result<Vec<Digested>> {
154    // Conditionals are expandable, not primitive — this shouldn't be called
155    Ok(Vec::new())
156  }
157  fn before_digest(&self) -> Option<&Vec<BeforeDigestClosure>> { None }
158  fn after_digest(&self) -> Option<&Vec<DigestionClosure>> { None }
159  fn do_absorption(&self, _document: &mut Document, _whatsit: &Whatsit) -> Result<Vec<Node>> {
160    fatal!(
161      Definition,
162      Unexpected,
163      "do_absorption on Conditional should never be called!"
164    );
165  }
166}
167
168/// A Frame of data for the currently active conditional, stored in State
169#[derive(Debug, Clone, PartialEq)]
170pub struct IfFrame {
171  /// the token which started the conditional
172  pub token:   Token,
173  /// source location of the conditional start
174  pub start:   Locator,
175  /// flag: currently parsing the test
176  pub parsing: bool,
177  /// flag: already seen an else at this level
178  pub elses:   bool,
179  /// in nested conditionals, give each an id
180  pub ifid:    i64,
181}
182
183impl Conditional {
184  fn invoke_conditional(&self) -> Result<Tokens> {
185    // Hot path: fires on every \if/\ifx/\ifnum/…. Perl assigns `if_count`
186    // 'global' (Conditional.pm:62) and keeps `$LaTeXML::IF_LIMIT` as a plain
187    // global; both live as typed `State` fields here (`State::if_count`),
188    // so a conditional pays no value-table lookup or global-assignment
189    // undo-frame walk.
190    let ifid = next_if_id();
191    // Perl: if ($LaTeXML::IF_LIMIT and $ifid > $LaTeXML::IF_LIMIT) { Fatal(...) }
192    let if_limit = if_limit();
193    if if_limit > 0 && ifid > if_limit {
194      Fatal!(
195        Timeout,
196        IfLimit,
197        s!("Conditional limit of {} exceeded, infinite loop?", if_limit)
198      );
199    }
200    let if_frame = Rc::new(RefCell::new(IfFrame {
201      token: get_current_token().unwrap(),
202      start: gullet::get_locator(),
203      parsing: true,
204      elses: false,
205      ifid,
206    }));
207    // (Perl's `local $LaTeXML::IFFRAME`, Conditional.pm:66: the frame goes however the conditional ends, an `Err` too)
208    let _if_frame_guard = local_ifframe_guard(Some(Rc::clone(&if_frame)));
209    push_if_frame(Rc::clone(&if_frame));
210    let args = self.read_arguments()?;
211
212    get_ifframe().unwrap().borrow_mut().parsing = false;
213    // `tracingcommands` is normally unset; defer the state probe to
214    // the path that would actually read it. Conditional::invoke fires
215    // on every \if/\ifx/\ifnum/…, so avoiding a mandatory state
216    // lookup per conditional is a measurable win.
217    if let Some(ref test) = self.test {
218      if (test)(args)? {
219        // true branch: do nothing, tokens follow naturally
220      } else {
221        // (an `Err` of the skip propagates, Perl's `die`, Conditional.pm:81; 1510.04725)
222        let to = self.skip_conditional_body(-1)?;
223        if lookup_bool_sym(pin!("tracingcommands")) {
224          Debug!("{{false}} [skipped to {:?}]\n", to);
225        }
226      }
227    } else {
228      // If there's no test, it must be the Special Case, \ifcase
229      // Note: num == 0 takes the 1st branch, no need to skip
230      // num < 0 should skip all \or & end up on the \else
231      let num = args.first().map(|a| a.value_of()).unwrap_or(0);
232      if num != 0 {
233        self.skip_conditional_body(num)?;
234        //       print STDERR "{$num} [skipped to " . ToString($to) . "]\n" if $tracing;
235      }
236    }
237    Ok(Tokens!())
238  }
239
240  // =====================================================================
241  // Support for conditionals:
242  //
243  // Skipping for conditionals
244  //   0 : skip to \fi
245  //  -1 : skip to \else, if any, or \fi
246  //   n : skip to n-th \or, if any, or \else, if any, or \fi.
247  //
248  // NOTE that there are 2 kinds of "nested" ifs.
249  //  \if's inside the body of either the true or false branch
250  // are easily skipped by tracking a level of if nesting and skipping over the
251  // same number of \fi as you find \if.
252  //  \if's that get expanded while evaluating the test clause itself
253  // are considerably trickier. There's a frame on the if-stack for this \if
254  // that's above the one we're currently processing; typically the \else & \fi
255  // may still remain, but we need to either evaluate them a normal
256  // if we're continuing to follow the true branch, or skip oever them if
257  // we're trying to find the \else for the false branch.
258  // The danger is mistaking the \else that's associated with the test clause's \if
259  // and taking it for the \else that we're skipping to!
260  // Canonical example:
261  //   \if\ifx AA XY junk \else blah \fi True \else False \fi
262  // The inner \ifx should expand to "XY junk", since A==A
263  // Return the token we've skipped to, and the frame that this applies to.
264  fn skip_conditional_body(&self, nskips: i64) -> Result<Tokens> {
265    let mut level = 1;
266    let mut n_ors = 0;
267    // NOTE: Open-coded manipulation of if_stack!
268    // [we're only reading tokens & looking up, so state::shouldn't change behind our backs]
269    loop {
270      let (t, cond_type) = match gullet::read_next_conditional()? {
271        Some((tok, typ)) => (Tokens!(tok), Some(typ)),
272        None => (Tokens!(), None),
273      };
274      match cond_type {
275        None => break,
276        Some(ConditionalType::If) => level += 1, //  Found a \ifxx of some sort
277        Some(ConditionalType::Fi) => {
278          // Found a \fi
279          if let Some(stack_frame) = pop_if_frame() {
280            if !is_local_frame(&stack_frame) {
281              // But is it for a condition nested in the test clause?
282              // then DO pop that conditional's frame; it's DONE!
283            } else {
284              level -= 1;
285              if level == 0 {
286                // otherwise, if no more nesting, we're done.
287                // Done with this frame, keep it removed
288                return Ok(t); // AND Return the finishing token.
289              }
290              push_if_frame(stack_frame);
291            }
292          }
293        },
294        Some(other_type) => {
295          if level > 1 {
296            // Ignore: \else,\or nested in the body.
297          } else if other_type == ConditionalType::Or {
298            n_ors += 1;
299            if n_ors == nskips {
300              return Ok(t);
301            }
302          } else if other_type == ConditionalType::Else && nskips != 0 {
303            // Found \else and we're looking for one?
304            // Make sure this \else is NOT for a nested \if that is part of the test clause!
305            if let Some(stack_frame) = top_if_frame()
306              && is_local_frame(&stack_frame)
307            {
308              // No need to actually call elseHandler, but note that we've seen an \else!
309              stack_frame.borrow_mut().elses = true;
310              return Ok(t);
311            }
312          }
313        },
314      };
315    }
316    Error!(
317      "expected",
318      "\\fi",
319      self,
320      s!(
321        "Missing \\fi or \\else, conditional fell off end. Conditional started at {}",
322        get_ifframe().map_or_else(String::new, |frame| frame.borrow().start.to_string())
323      )
324    );
325    Ok(Tokens!())
326  }
327
328  fn invoke_else(&self) -> Result<Tokens> {
329    let stack_frame_opt = top_if_frame();
330    let local_token = get_current_token().unwrap();
331    if local_token.with_str(|s| s == "\\else") && stack_frame_opt.is_none() {
332      let stack_len = if_stack_depth();
333      emit_warn(
334        "unexpected",
335        "else",
336        &format!("\\else encountered with no active if-frame (stack_len={stack_len})"),
337      );
338    }
339    if let Some(stack_frame) = stack_frame_opt {
340      if stack_frame.borrow().parsing {
341        // Defer expanding the \else if we're still parsing the test
342        Ok(Tokens!(T_RELAX!(), local_token))
343      } else if stack_frame.borrow().elses {
344        // Already seen an \else's at this level?
345        let message = s!(
346          "Extra {} already saw \\else for {:?} [{:?}] at {:?}",
347          local_token.stringify(),
348          stack_frame.borrow().token,
349          stack_frame.borrow().ifid,
350          stack_frame.borrow().start
351        );
352        let local_token_str = local_token.to_string();
353        Error!("unexpected", local_token_str, message);
354        Ok(Tokens!())
355      } else {
356        let _if_frame_guard = local_ifframe_guard(Some(Rc::clone(&stack_frame)));
357        self.skip_conditional_body(0)?;
358        //     print STDERR '{' . ToString($LaTeXML::CURRENT_TOKEN) . '}'
359        //       . " [for " . ToString($$LaTeXML::IFFRAME{token}) . " #" .
360        // $$LaTeXML::IFFRAME{ifid}       . " skipping to " . ToString($t) . "]\n"
361        //       if $state->lookupValue('tracingcommands');
362        Ok(Tokens!())
363      }
364    } else {
365      // No if stack entry ?
366      let message = s!(
367        "Didn't expect a {:?} since we seem not to be in a conditional",
368        local_token.stringify()
369      );
370      let local_token_str = local_token.to_string();
371      Error!("unexpected", local_token_str, message);
372      Ok(Tokens!())
373    }
374  }
375
376  fn invoke_fi(&self) -> Result<Tokens> {
377    let stack_frame_opt = top_if_frame();
378    if let Some(stack_frame) = stack_frame_opt {
379      if stack_frame.borrow().parsing {
380        // Defer expanding the \else if we're still parsing the test
381        Ok(Tokens!(T_RELAX!(), get_current_token().unwrap()))
382      } else {
383        // "expand" by removing the stack entry for this level
384        set_ifframe(Some(stack_frame));
385        pop_if_frame(); // Done with this frame
386
387        //     print STDERR '{' . ToString($LaTeXML::CURRENT_TOKEN) . '}'
388        // . " [for " . Stringify($$LaTeXML::IFFRAME{token}) . " #" . $$LaTeXML::IFFRAME{ifid} .
389        // "]\n"       if $state->lookupValue('tracingcommands');
390        expire_ifframe();
391        Ok(Tokens!())
392      }
393    } else {
394      let cur = get_current_token()
395        .map(|t| t.stringify())
396        .unwrap_or_else(|| String::from("\\?"));
397      let message = s!(
398        "Didn't expect a {:?} since we seem not to be in a conditional",
399        cur
400      );
401      Error!("unexpected", "fi", message);
402      Ok(Tokens!())
403    }
404  }
405}
406
407/// Current depth of the active conditional stack (`if_stack`).
408pub fn if_stack_depth() -> usize { crate::state::if_stack_depth() }
409
410/// Whether `frame` is the conditional being processed (Perl compares the frames
411/// themselves, `$frame eq $LaTeXML::IFFRAME`).
412fn is_local_frame(frame: &Rc<RefCell<IfFrame>>) -> bool {
413  get_ifframe().is_some_and(|local| Rc::ptr_eq(frame, &local))
414}
415
416#[cfg(test)]
417mod tests {
418  use super::*;
419
420  #[test]
421  fn conditional_type_from_str_known_variants() {
422    assert_eq!(ConditionalType::from("\\if"), ConditionalType::If);
423    assert_eq!(ConditionalType::from("\\unless"), ConditionalType::Unless);
424    assert_eq!(ConditionalType::from("\\else"), ConditionalType::Else);
425    assert_eq!(ConditionalType::from("\\or"), ConditionalType::Or);
426    assert_eq!(ConditionalType::from("\\fi"), ConditionalType::Fi);
427  }
428
429  #[test]
430  fn conditional_type_from_str_unknown_falls_back_to_if() {
431    // The match's default arm is `_ => If`, not Unknown — that's a
432    // surprising but documented behavior in the source. Lock it in.
433    assert_eq!(ConditionalType::from("\\foo"), ConditionalType::If);
434    assert_eq!(ConditionalType::from(""), ConditionalType::If);
435  }
436
437  #[test]
438  fn conditional_type_equality() {
439    assert_eq!(ConditionalType::If, ConditionalType::If);
440    assert_ne!(ConditionalType::If, ConditionalType::Else);
441  }
442
443  #[test]
444  fn conditional_default_fields() {
445    let c = Conditional::default();
446    assert!(c.paramlist.is_none());
447    assert!(c.test.is_none());
448    assert_eq!(c.conditional_type, ConditionalType::Unknown);
449    assert!(c.skipper.is_none());
450  }
451
452  #[test]
453  fn conditional_partial_eq_by_cs() {
454    // PartialEq ignores conditional_type, skipper etc., compares by cs.
455    let a = Conditional::default();
456    let b = Conditional::default();
457    assert!(a == b, "defaults have same cs");
458  }
459
460  #[test]
461  fn conditional_is_expandable() {
462    let c = Conditional::default();
463    assert!(c.is_expandable());
464    // Conditionals are NOT definitions (they're expandable machinery).
465    // Actually the default Object::is_definition returns false; the
466    // trait default applies here.
467  }
468
469  #[test]
470  fn conditional_display_is_cs_text() {
471    let c = Conditional::default();
472    let s = format!("{c}");
473    assert_eq!(s, "Conditional");
474  }
475
476  #[test]
477  fn conditional_get_parameters_none_by_default() {
478    let c = Conditional::default();
479    assert!(c.get_parameters().is_none());
480  }
481
482  /// A conditional left by an `Err` (here a read budget's, which a title-page check or a rehearsal catches and goes
483  /// on) takes its if-frame with it, as Perl's `local $LaTeXML::IFFRAME` (Conditional.pm:66) unwinds on `die`: a frame
484  /// left behind keeps `open_conditional_count()` above zero, and the fragment-yield seam never yields again.
485  #[test]
486  fn an_err_inside_a_conditional_takes_its_if_frame_with_it() {
487    use crate::{
488      common::local_assignments::{
489        expire_current_token, initialize_localized, local_current_token, open_conditional_count,
490      },
491      gullet::{read_budget, reading_from_mouth, unread},
492      mouth::Mouth,
493    };
494    let conditional = |cs: &str, conditional_type, test: Option<ConditionalClosure>| Conditional {
495      cs: T_CS!(cs),
496      test,
497      conditional_type,
498      ..Conditional::default()
499    };
500    let body = || Tokens::new(vec![T_LETTER!("a"); 10]);
501    let read_budget_failed = |defn: &Conditional, cs: &str| -> bool {
502      local_current_token(T_CS!(cs));
503      let result = reading_from_mouth(Mouth::default(), || {
504        unread(body());
505        let _budget = read_budget(3);
506        defn.invoke(false)
507      });
508      expire_current_token();
509      matches!(result.unwrap_err().category, ErrorCategory::ReadBudget)
510    };
511    initialize_localized();
512    // `\iffalse` breaching the budget while it skips its false branch
513    let iffalse = conditional(
514      "\\iffalse",
515      ConditionalType::If,
516      Some(Rc::new(|_| Ok(false))),
517    );
518    assert!(read_budget_failed(&iffalse, "\\iffalse"));
519    assert_eq!(open_conditional_count(), 0, "the skip's Err");
520    // a test whose own read fails (`\ifnum` reading its number)
521    let failing = conditional(
522      "\\ifnum",
523      ConditionalType::If,
524      Some(Rc::new(|_| {
525        loop {
526          gullet::read_token()?;
527        }
528      })),
529    );
530    assert!(read_budget_failed(&failing, "\\ifnum"));
531    assert_eq!(open_conditional_count(), 0, "the test's Err");
532    // `\else` of a true branch breaching the budget while it skips to `\fi`
533    let frame = Rc::new(RefCell::new(IfFrame {
534      token:   T_CS!("\\iftrue"),
535      start:   Locator::default(),
536      parsing: false,
537      elses:   false,
538      ifid:    1,
539    }));
540    push_if_frame(Rc::clone(&frame));
541    let else_ = conditional("\\else", ConditionalType::Else, None);
542    assert!(read_budget_failed(&else_, "\\else"));
543    assert_eq!(open_conditional_count(), 0, "the else's skip's Err");
544    pop_if_frame();
545  }
546
547  #[test]
548  fn conditional_options_default_all_none() {
549    let o = ConditionalOptions::default();
550    assert!(o.scope.is_none());
551    assert!(o.locked.is_none());
552    assert!(o.skipper.is_none());
553  }
554}