Skip to main content

latexml_core/
keyvals.rs

1use core::slice::Iter;
2use std::{borrow::Cow, fmt};
3
4use libxml::tree::Node;
5use rustc_hash::FxHashMap as HashMap;
6
7use super::keyval::{has_keyval, keyval_get, keyval_qname};
8use crate::{
9  BoxOps, Digested, NO_PROPERTIES,
10  binding::def::dialect::def_macro,
11  common::{
12    arena::{self, SymHashMap},
13    error::{emit_warn, *},
14    font::Font,
15    object::Object,
16    store::Stored,
17  },
18  definition::{ExpansionBody, argument::ArgWrap, expandable::ExpandableOptions},
19  document::Document,
20  gullet::{self, ExpansionLevel},
21  state::{self, Scope},
22  token::{Catcode, Token},
23  tokens::Tokens,
24};
25
26#[derive(Debug, Clone)]
27struct KVData {
28  key:            String,
29  value:          Option<ArgWrap>,
30  use_default:    bool,
31  primary_keyset: String,
32  keysets:        Vec<String>,
33  digested_value: Option<Digested>,
34}
35
36thread_local! {
37  /// The (prefix, key, keysets) of each unknown key reported in this conversion, each reported once.
38  static SEEN_MISSING: std::cell::RefCell<rustc_hash::FxHashSet<(String, String, String)>> =
39    std::cell::RefCell::default();
40}
41
42/// Forget the unknown keys reported: a conversion reports its own (`initialize_report`, as Perl's `$$state{status} = {}`
43/// per conversion, LaTeXML.pm:232), not only those a persistent worker's earlier paper did not (ST3).
44pub fn reset_unknown_keys_reported() { SEEN_MISSING.with_borrow_mut(|seen| seen.clear()); }
45
46#[allow(dead_code)] // TODO: remove when KeyVals is fully implemented
47#[derive(Debug, Clone)]
48pub struct KeyVals {
49  // which KeyVals are we parsing and how do we behave?
50  prefix:               String,
51  /// `keysets should be a list of keysets to find keys inside of.
52  /// It defaults to ["_anonymous_"] if empty.
53  keysets:              Vec<String>,
54  skip:                 Vec<String>,
55  set_all:              bool,
56  set_internals:        bool,
57  skip_missing:         SkipMissing,
58  was_digested:         bool,
59  hook_missing:         Option<Token>,
60  // all the internal representations
61  tuples:               Vec<KVData>,
62  cached_pairs:         Vec<(String, ArgWrap)>,
63  cached_hash:          HashMap<String, Vec<ArgWrap>>,
64  cached_hash_digested: HashMap<String, Vec<Digested>>,
65  /// The tokens each typed length value states (`width=0.48\textwidth`), in the order given, kept under
66  /// `parameter::KEEP_STATED_LENGTHS` ([`Self::stated_entry`]).
67  stated:               Vec<(String, Tokens)>,
68}
69
70impl Default for KeyVals {
71  fn default() -> Self {
72    KeyVals {
73      prefix:               "KV".to_string(),
74      keysets:              vec!["_anonymous_".to_string()],
75      skip:                 Vec::new(),
76      set_all:              false,
77      set_internals:        false,
78      skip_missing:         SkipMissing::None,
79      was_digested:         false,
80      hook_missing:         None,
81      tuples:               Vec::new(),
82      cached_pairs:         Vec::new(),
83      cached_hash:          HashMap::default(),
84      cached_hash_digested: HashMap::default(),
85      stated:               Vec::new(),
86    }
87  }
88}
89
90impl PartialEq for KeyVals {
91  fn eq(&self, _other: &KeyVals) -> bool {
92    false // TODO ?
93  }
94}
95
96impl fmt::Display for KeyVals {
97  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
98    let mut first = true;
99    for (key, value) in &self.cached_pairs {
100      if !first {
101        // Perl uses comma without space for KeyVals serialization
102        write!(f, ",")?;
103      }
104      write!(f, "{}={}", key, value)?;
105      first = false;
106    }
107    Ok(())
108  }
109}
110
111impl Object for KeyVals {
112  fn stringify(&self) -> String { self.to_string() }
113
114  fn be_digested(mut self) -> Result<Digested> {
115    if self.was_digested {
116      Info!(
117        "ignore",
118        "keyvals",
119        "Skipping digestion of \\setkeys as requested (did you digest a KeyVals twice?) "
120      );
121    } else {
122      crate::stomach::digest(self.set_keys_expansion())?;
123    }
124
125    // iterate over the tuples, digesting the values
126    for tuple in self.tuples.iter_mut() {
127      let KVData {
128        key,
129        value,
130        primary_keyset,
131        digested_value,
132        ..
133      } = tuple;
134      if digested_value.is_none() {
135        // avoid accidental repeats?
136        let keytype_opt = keyval_get(&keyval_qname(&self.prefix, primary_keyset, key), "type");
137        let v = if let Some(Stored::Parameter(keytype)) = keytype_opt {
138          match value.take() {
139            Some(v) => keytype.digest(v, None)?,
140            _ => None,
141          }
142        } else {
143          match value.take() {
144            Some(v) => Some(v.be_digested()?),
145            _ => None,
146          }
147        };
148        tuple.digested_value = v;
149      }
150    }
151    // TODO: DG: KeyVals digestion feels very iffy while porting it over to Rust.
152    // had to add an explicit "rebuild" to cache the digested values in the new
153    // "cached_hash_digested" It feels like the entire object should be reorganized to leverage
154    // a little more of the well-typed capabilities we have here.
155    self.rebuild(None);
156    self.was_digested = true;
157    Ok(self.into())
158  }
159}
160
161impl BoxOps for KeyVals {
162  fn with_properties<R, FnR>(&self, caller: FnR) -> R
163  where FnR: FnOnce(&SymHashMap<Stored>) -> R {
164    caller(NO_PROPERTIES)
165  }
166  fn get_string(&self) -> Result<Cow<'_, str>> { Ok(Cow::Owned(self.to_string())) }
167  fn set_property<T: Into<Stored>>(&mut self, _key: &str, _value: T) {
168    emit_warn(
169      "internal",
170      "keyvals",
171      "set_property on KeyVals not supported",
172    );
173  }
174  fn be_absorbed(&self, _document: &mut Document) -> Result<Vec<Node>> { Ok(Vec::new()) } // TODO
175  fn get_font(&self) -> Result<Option<std::rc::Rc<Font>>> { Ok(None) } // TODO
176  fn compute_size(
177    &self,
178    _options: SymHashMap<Stored>,
179  ) -> Result<(
180    crate::common::dimension::Dimension,
181    crate::common::dimension::Dimension,
182    crate::common::dimension::Dimension,
183  )> {
184    use crate::common::dimension::Dimension;
185    Ok((
186      Dimension::default(),
187      Dimension::default(),
188      Dimension::default(),
189    ))
190  }
191}
192#[derive(Debug, Clone, Default, PartialEq)]
193pub enum SkipMissing {
194  #[default]
195  /// throw errors
196  None,
197  /// silently ignore all missing keys
198  All,
199  /// store all missing keys under the provided token
200  Store(Token),
201}
202
203#[derive(Default)]
204pub struct KeyvalsConfig {
205  pub prefix:        Option<String>,
206  pub keysets:       Vec<String>,
207  pub set_all:       bool,
208  pub set_internals: bool,
209  pub skip:          Vec<String>,
210  pub skip_missing:  SkipMissing,
211  pub hook_missing:  Option<Token>,
212}
213
214impl KeyVals {
215  ///======================================================================
216  /// The KeyVals constructor
217  ///======================================================================
218  /// This defines the KeyVals data object that can appear in the datastream
219  /// along with tokens, boxes, etc.
220  /// Thus it has to be digestible, however we may not want to digest it more
221  /// than once.
222  ///**********************************************************************
223  pub fn new(options: KeyvalsConfig) -> Self {
224    // parse all the arguments
225    let KeyvalsConfig {
226      prefix,
227      mut keysets,
228      set_all,
229      set_internals,
230      skip,
231      skip_missing,
232      hook_missing,
233    } = options;
234    let prefix = prefix.unwrap_or_else(|| String::from("KV"));
235    // The EMPTY family is a family (xkeyval.tex:83-88): pst-xkey.tex:53-57
236    // accumulates `\pst@famlist` as ",pstricks", so every `\psset` searches
237    // "" (pstricks.tex:808-810 `precode`/`postcode`/`exchange`, pst-node.tex's
238    // `Xnodesep` family) before "pstricks". Perl KeyVals.pm:52 drops the empty
239    // entries (its `keyval_qname` doubled the `@` and collided with pstricks'
240    // delimited `\psset@@…` helpers; `keyval_qname` now uses xkeyval's header
241    // rule instead) — KNOWN_PERL_ERRORS #212, DIVERGENCES #219. Only an
242    // ABSENT list falls back to `_anonymous_`.
243    if keysets.is_empty() {
244      keysets = vec![String::from("_anonymous_")];
245    }
246    KeyVals {
247      prefix,
248      keysets,
249      skip,
250      set_all,
251      set_internals,
252      skip_missing,
253      hook_missing,
254      ..KeyVals::default()
255    }
256  }
257
258  //======================================================================
259  // Resolution to KeySets
260  //======================================================================
261
262  /// Return a list of the keysets in which this key is defined
263  fn resolve_keyval_for(&self, key: &str) -> Vec<String> {
264    let prefix = &self.prefix;
265    let allkeysets = &self.keysets;
266    let keysets: Vec<_> = self
267      .keysets
268      .iter()
269      .filter(|kset| has_keyval(prefix, kset, key))
270      .collect();
271    // throw an error (not really), unless we record the missing macros
272    // Since we're not as obsessive about declaring ALL keys, we'll soften the blow
273    if keysets.is_empty() {
274      if self.skip_missing == SkipMissing::None {
275        // Rate-limit: only emit Info the first time this (prefix, key,
276        // keysets) tuple fires. A large `tabular` with 700 rows can
277        // otherwise produce 700 identical "Encountered unknown KeyVals
278        // key 'vattach'" messages (arxiv 1709.05096), each allocating
279        // a formatted String + going through the log backend. Perl's
280        // Info() has an equivalent deduper in Error.pm via
281        // maxWarnings limits; our rate-limit is per (prefix,key,keysets)
282        // and unbounded in count, so the first occurrence is always
283        // visible but repeats are silently dropped.
284        let all_joined = allkeysets.join(",");
285        // (a speculative digestion's diagnostics go with it: what it sees is not seen, or the document's own Warning goes unsaid)
286        let is_new = SEEN_MISSING.with(|cell| {
287          let seen = (prefix.clone(), key.to_string(), all_joined.clone());
288          if gullet::in_speculative_digestion() {
289            !cell.borrow().contains(&seen)
290          } else {
291            cell.borrow_mut().insert(seen)
292          }
293        });
294        if is_new && !(prefix == "KV" && unknown_keyval_keys_ignored()) {
295          // Intentional divergence from Perl (KeyVals.pm L97 uses Info).
296          // An unknown KeyVal key in `\setkeys` (non-starred) is the
297          // package binding admitting it doesn't recognise an option
298          // the user actually requested — the key's effect (formatting,
299          // rendering options) is silently dropped. For siunitx
300          // specifically this cascades into broken `\SI{}` expansion,
301          // which leaves bare control sequences in math and produces
302          // duplicated xml:id (witness: 1410.8171). Promoted to Warn
303          // so each unique missing key surfaces as a status_code=1
304          // (`[warn]` in the canvas), and a binding gap can't ship
305          // green.
306          //
307          // EXCEPT for the 'Frontmatter' keyset (PR #2767): its design
308          // passes undeclared keys by construction (the engine's own
309          // \lx@add@date uses `name={...}`; class bindings pass through
310          // arbitrary attributes). Perl Infos there; mirror that level
311          // so frontmatter-bearing papers don't all turn status_code=1.
312          if all_joined == "Frontmatter" {
313            Info!(
314              "undefined",
315              "Encountered unknown KeyVals key",
316              s!("'{key}' with prefix '{prefix}' not defined in '{all_joined}'")
317            );
318          } else {
319            Warn!(
320              "undefined",
321              "Encountered unknown KeyVals key",
322              s!(
323                "'{key}' with prefix '{prefix}' not defined in '{all_joined}', were you perhaps using \\setkeys instead of \\setkeys*?"
324              )
325            );
326          }
327        }
328      }
329      return Vec::new();
330    }
331    // return either the first or all of the KeyVal objects
332    // TODO: SymStr would avoid the allocation.
333    if self.set_all {
334      keysets.into_iter().cloned().collect()
335    } else {
336      vec![keysets[0].clone()]
337    }
338  }
339
340  fn can_resolve_keyval_for(&self, key: &str) -> bool {
341    // iterate over the keysets
342    self
343      .keysets
344      .iter()
345      .any(|keyset| has_keyval(&self.prefix, keyset, key))
346  }
347
348  /// Return the 1st of the keysets, or the 1st one of the KeyVals itself
349  fn get_primary_keyval<'a>(&'a self, keysets: &'a [String]) -> &'a str {
350    match keysets.first() {
351      None => self.keysets[0].as_str(),
352      Some(kset) => kset.as_str(),
353    }
354  }
355
356  fn read_keyword_from(&self, close: Token) -> Result<(Tokens, Option<Token>)> {
357    // set of tokens we will expand
358    let mut tokens = Vec::new();
359    let delim = &[close, T_OTHER!(","), T_OTHER!("=")];
360    // skip leading spaces
361    gullet::skip_spaces()?;
362
363    let mut last_token = None;
364    // Real keyval reads each comma item as a delimited macro argument
365    // (keyval.sty `\KV@do#1,`, tex.web §392): the KEY is taken UNEXPANDED and
366    // a `{…}` inside it is opaque. Perl's readKeyWordFrom (KeyVals.pm:273-286)
367    // and this port expanded while scanning and ended the key at the first
368    // `}`/`,`/`=` — so an enumitem shortlabel macro, verifica.cls:245-252
369    // `\setlist[test]{\@risp,leftmargin=*}` with `\@risp` = `\fbox{…}`,
370    // was unfolded into its box code, cut at an inner `}`, and the tail of
371    // the option list plus the real closing `}` landed in the stream:
372    // "Attempt to close a group that switched to mode horizontal" ×3 per
373    // document (verifica example1-5). enumitem's shortlabel path receives
374    // the key `\@risp` itself, as real enumitem does. Guard:
375    // `perfect_kernel_batch54::keyval_key_is_brace_aware`.
376    let mut depth: usize = 0;
377    while let Some(token) = gullet::read_token()? {
378      // skip to the next iteration if we have a paragraph
379      if token == T_CS!("\\par") {
380        continue;
381      }
382      // A brace inside the key is part of it; only an END at depth 0 can be
383      // the closing delimiter.
384      match token.get_catcode() {
385        Catcode::BEGIN => {
386          depth += 1;
387          tokens.push(token);
388          continue;
389        },
390        Catcode::END if depth > 0 => {
391          depth -= 1;
392          tokens.push(token);
393          continue;
394        },
395        _ => {},
396      }
397      // if we have one of out delimiters (outside any group), we end
398      if delim.contains(&token) {
399        last_token = Some(token);
400        break;
401      }
402      tokens.push(token);
403    }
404    let mut tokens = Tokens::new(tokens);
405    // xkeyval.tex L140-146 `\XKV@ifcmd`: a key may be wrapped as
406    // `\savevalue{key}` / `\gsavevalue{key}`. Real xkeyval detects the leading
407    // command on the unexpanded key and strips it; here the wrapper macros
408    // (xkeyval_sty.rs) latch the pending-save flags and expand to the bare
409    // key, so only a key that STARTS with one of them is expanded.
410    if let Some(first) = tokens.unlist_ref().first()
411      && (*first == T_CS!("\\savevalue") || *first == T_CS!("\\gsavevalue"))
412    {
413      tokens = gullet::do_expand(tokens)?;
414    }
415    // return the tokens and the last token
416    Ok((tokens, last_token))
417  }
418
419  //======================================================================
420  // Public accessors of all the values
421  //======================================================================
422  // Note: The API of this need to be stable, as people may be using it
423
424  /// The tokens the last of `keys` given states as its length value (`width=0.48\textwidth`), where they were kept
425  /// (`parameter::KEEP_STATED_LENGTHS`), with the key that stated them (`width`, `totalheight`; the value they gave is
426  /// [`Self::get_value`]'s): a key given again replaces its value.
427  pub fn stated_entry(&self, keys: &[&str]) -> Option<(&str, &Tokens)> {
428    self
429      .stated
430      .iter()
431      .rev()
432      .find(|(key, _)| keys.contains(&key.as_str()))
433      .map(|(key, tokens)| (key.as_str(), tokens))
434  }
435
436  /// return the value of a given key. If multiple values are given, return the last one.
437  pub fn get_value(&self, key: &str) -> Option<&ArgWrap> {
438    // Since we (by default) accumulate lists of values when repeated,
439    // we need to provide the "common" thing: return the last value given.
440    match self.cached_hash.get(key) {
441      None => None,
442      Some(value) => value.last(),
443    }
444  }
445  /// return the digested value of a given key. If multiple values are given, return the last one.
446  /// This call does *not* digest the value, and will return None if called pre-digestion
447  pub fn get_value_digested(&self, key: &str) -> Option<&Digested> {
448    // Since we (by default) accumulate lists of values when repeated,
449    // we need to provide the "common" thing: return the last value given.
450    match self.cached_hash_digested.get(key) {
451      None => None,
452      Some(value) => value.last(),
453    }
454  }
455
456  /// return a list of values for a given key
457  pub fn get_values(&self, key: &str) -> Option<&Vec<ArgWrap>> { self.cached_hash.get(key) }
458  /// return the digested values of a given key, in the order given
459  pub fn get_values_digested(&self, key: &str) -> Option<&Vec<Digested>> {
460    self.cached_hash_digested.get(key)
461  }
462
463  /// return the set of key-value pairs
464  pub fn get_pairs(&self) -> Iter<'_, (String, ArgWrap)> { self.cached_pairs.iter() }
465  /// consume KeyVals and return a flat HashMap
466  pub fn as_flat_hash(self) -> HashMap<String, ArgWrap> {
467    let mut flat_hash = HashMap::default();
468    for (k, mut vec) in self.cached_hash {
469      if let Some(v) = vec.pop() {
470        flat_hash.insert(k, v);
471      }
472    }
473    flat_hash
474  }
475  /// consume KeyVals and return the cached HashMap of input values
476  pub fn as_hash(self) -> HashMap<String, Vec<ArgWrap>> { self.cached_hash }
477  /// consume KeyVals and return the cached HashMap of digested values
478  pub fn as_hash_digested(self) -> HashMap<String, Vec<Digested>> { self.cached_hash_digested }
479  /// returns a key => ToString(value)
480  pub fn get_hash(&self) -> HashMap<String, String> {
481    let mut hashed = HashMap::default();
482    for (k, v) in &self.cached_hash {
483      hashed.insert(
484        k.clone(),
485        v.iter()
486          .map(ToString::to_string)
487          .collect::<Vec<String>>()
488          .join(""),
489      );
490    }
491    hashed
492  }
493  /// returns a key => ToString(value)
494  pub fn get_hash_digested(&self) -> HashMap<String, String> {
495    let mut hashed = HashMap::default();
496    for (k, v) in &self.cached_hash_digested {
497      hashed.insert(
498        k.clone(),
499        v.iter()
500          .map(ToString::to_string)
501          .collect::<Vec<String>>()
502          .join(""),
503      );
504    }
505    hashed
506  }
507
508  // return a hash of key-value pairs
509  pub fn get_keyvals(&self) -> &HashMap<String, Vec<ArgWrap>> { &self.cached_hash }
510
511  // checks if the value for a given key exists
512  pub fn has_key(&self, key: &str) -> bool { self.cached_hash.contains_key(key) }
513
514  //======================================================================
515  // Value Related Reversion
516  //======================================================================
517  pub fn set_keys_expansion(&self) -> Tokens {
518    let skip_keys = &self.skip;
519    let set_internals = self.set_internals;
520    let prefix = &self.prefix;
521
522    // Handle skipMissing store token (xkeyval feature)
523    let rmmacro = match &self.skip_missing {
524      SkipMissing::Store(token) => Some(*token),
525      _ => None,
526    };
527    let hook_missing = self.hook_missing;
528
529    // Read the existing leftover list from rmmacro ONE STEP (its body), as
530    // xkeyval.tex L497 `\XKV@addtolist@o\XKV@rm\XKV@tempa` does. Perl
531    // (KeyVals.pm:345-346) fully `Expand`s it — but a leftover VALUE may name a
532    // macro that is only defined by the time its key code runs:
533    // chessboard.sty:1439 saves `trimarea=\board` at load time, and `\board`
534    // is `\edef`'d inside `\chessboard` (:1087) just before the leftovers are
535    // dispatched (:1110); every intermediate `\setkeys*` re-read `\XKV@rm`
536    // and raised "undefined \board" (chessboard-skakps). Perl never reaches
537    // this: its xkeyval stub stops at `\XKV@testopta`. Guard:
538    // `perfect_kernel_batch54::setrmkeys_keeps_leftover_values_unexpanded`.
539    let mut rmtokens: Vec<Token> = Vec::new();
540    if let Some(rm) = rmmacro
541      && let Ok(Some(defn)) = state::lookup_expandable(&rm, None)
542      && let Ok(body) = defn.invoke(true)
543    {
544      rmtokens = body.unlist();
545    }
546
547    let mut tokens: Vec<Token> = Vec::new();
548
549    // Define xkeyval internals if needed
550    if set_internals {
551      let keysets_joined = self.keysets.join(",");
552      let skip_joined = self.skip.join(",");
553      tokens.push(T_CS!("\\def"));
554      tokens.push(T_CS!("\\XKV@fams"));
555      tokens.push(T_BEGIN!());
556      tokens.extend(Explode!(keysets_joined));
557      tokens.push(T_END!());
558      tokens.push(T_CS!("\\def"));
559      tokens.push(T_CS!("\\XKV@na"));
560      tokens.push(T_BEGIN!());
561      tokens.extend(Explode!(skip_joined));
562      tokens.push(T_END!());
563    }
564
565    // Iterate over key-value pairs
566    for tuple in &self.tuples {
567      let KVData {
568        key,
569        value,
570        use_default,
571        primary_keyset,
572        keysets,
573        ..
574      } = tuple;
575
576      // Skip keys in the skip list
577      if skip_keys.iter().any(|s| s == key) {
578        continue;
579      }
580
581      // If no keysets resolved for this key
582      if keysets.is_empty() {
583        // Store in rmmacro if defined
584        if rmmacro.is_some()
585          && let Ok(rev) = self.revert_keyval(
586            key,
587            primary_keyset,
588            value.as_ref(),
589            *use_default,
590            rmtokens.is_empty(),
591          )
592        {
593          rmtokens.extend(rev);
594        }
595        // Call hookMissing if defined
596        if let Some(hm) = hook_missing
597          && let Ok(rev) =
598            self.revert_keyval(key, primary_keyset, value.as_ref(), *use_default, true)
599        {
600          tokens.push(hm);
601          tokens.push(T_BEGIN!());
602          tokens.extend(rev);
603          tokens.push(T_END!());
604        }
605        continue;
606      }
607
608      // Iterate over all valid keysets
609      for keyset in keysets {
610        let qname = keyval_qname(prefix, keyset, key);
611        if !has_keyval(prefix, keyset, key) {
612          Info!(
613            "undefined",
614            "Encountered unknown KeyVals key",
615            s!("'{key}' with prefix '{prefix}' not defined in '{keyset}'")
616          );
617        } else if matches!(keyval_get(&qname, "disabled"), Some(Stored::Bool(true))) {
618          Warn!("undefined", "keyval", s!("`{key}' has been disabled. "));
619        } else {
620          // Define xkeyval internals per-key if needed
621          if set_internals {
622            tokens.push(T_CS!("\\def"));
623            tokens.push(T_CS!("\\XKV@prefix"));
624            tokens.push(T_BEGIN!());
625            tokens.extend(Explode!(s!("{prefix}@")));
626            tokens.push(T_END!());
627            tokens.push(T_CS!("\\def"));
628            tokens.push(T_CS!("\\XKV@tfam"));
629            tokens.push(T_BEGIN!());
630            tokens.extend(Explode!(keyset));
631            tokens.push(T_END!());
632            tokens.push(T_CS!("\\def"));
633            tokens.push(T_CS!("\\XKV@header"));
634            tokens.push(T_BEGIN!());
635            // xkeyval.tex:83-88 `\XKV@makehd`: no `<family>@` segment for the
636            // empty family (same rule as `keyval_qname`).
637            tokens.extend(Explode!(if keyset.is_empty() {
638              s!("{prefix}@")
639            } else {
640              s!("{prefix}@{keyset}@")
641            }));
642            tokens.push(T_END!());
643            tokens.push(T_CS!("\\def"));
644            tokens.push(T_CS!("\\XKV@tkey"));
645            tokens.push(T_BEGIN!());
646            tokens.extend(Explode!(key));
647            tokens.push(T_END!());
648          }
649
650          // Perl: if ($useDefault) { push(@tokens, T_CS('\\' . $qname . '@default')); }
651          //       else { push(@tokens, T_CS('\\' . $qname), T_BEGIN, Revert($value), T_END); }
652          // Note: Perl unconditionally emits \qname@default for bare keys. In Rust, we guard
653          // with has_meaning to avoid undefined-CS errors when @default was never registered
654          // (e.g., xkeyval DeclareOptionX keys without default values).
655          if *use_default && state::has_meaning(&T_CS!(s!("\\{qname}@default"))) {
656            // Call the @default macro (bare key with registered default)
657            tokens.push(T_CS!(s!("\\{qname}@default")));
658          } else {
659            // Call the macro with the value (or empty if bare key without default)
660            tokens.push(T_CS!(s!("\\{qname}")));
661            tokens.push(T_BEGIN!());
662            if let Some(v) = value
663              && let Ok(reverted) = v.revert()
664            {
665              tokens.extend(reverted.unlist());
666            }
667            tokens.push(T_END!());
668          }
669
670          // Reset xkeyval internals per-key
671          if set_internals {
672            tokens.push(T_CS!("\\def"));
673            tokens.push(T_CS!("\\XKV@prefix"));
674            tokens.push(T_BEGIN!());
675            tokens.push(T_END!());
676            tokens.push(T_CS!("\\def"));
677            tokens.push(T_CS!("\\XKV@tfam"));
678            tokens.push(T_BEGIN!());
679            tokens.push(T_END!());
680            tokens.push(T_CS!("\\def"));
681            tokens.push(T_CS!("\\XKV@header"));
682            tokens.push(T_BEGIN!());
683            tokens.push(T_END!());
684            tokens.push(T_CS!("\\def"));
685            tokens.push(T_CS!("\\XKV@tkey"));
686            tokens.push(T_BEGIN!());
687            tokens.push(T_END!());
688          }
689        }
690      }
691    }
692
693    // Assign rmmacro with collected missing keys
694    if let Some(rm) = rmmacro {
695      tokens.push(T_CS!("\\def"));
696      tokens.push(rm);
697      tokens.push(T_BEGIN!());
698      tokens.extend(rmtokens);
699      tokens.push(T_END!());
700    }
701
702    // Reset all internals if applicable
703    if set_internals {
704      tokens.push(T_CS!("\\def"));
705      tokens.push(T_CS!("\\XKV@fams"));
706      tokens.push(T_BEGIN!());
707      tokens.push(T_END!());
708      tokens.push(T_CS!("\\def"));
709      tokens.push(T_CS!("\\XKV@na"));
710      tokens.push(T_BEGIN!());
711      tokens.push(T_END!());
712    }
713
714    Tokens::new(tokens)
715  }
716
717  pub fn revert(&self) -> Result<Tokens> {
718    let mut tokens = Vec::new();
719    // iterate over the key-value pairs
720    for tuple in &self.tuples {
721      let KVData {
722        key,
723        value,
724        use_default,
725        keysets: _,
726        primary_keyset,
727        digested_value,
728      } = tuple;
729      if !primary_keyset.is_empty() {
730        // Post-digestion `be_digested` has `take()`n the raw `value`, leaving
731        // the value only in `digested_value`; fall back to reverting that, so a
732        // reverted KeyVals keeps `key=value` instead of collapsing to a bare
733        // `key` (issue #627). Mirrors `rebuild`'s digested-value fallback.
734        // `strip_braces`: the digested value reverts with its own `{…}` wrapper,
735        // but `revert_keyval`/`rebrace` re-add braces only when the value has an
736        // outer comma — so strip one level first to match Perl's
737        // `rebrace(Revert($value))` (no braces for a plain value).
738        let digested_fallback = match (value, digested_value) {
739          (None, Some(dv)) => Some(ArgWrap::Tokens(dv.revert()?.strip_braces())),
740          _ => None,
741        };
742        let reverted = self.revert_keyval(
743          key,
744          primary_keyset,
745          value.as_ref().or(digested_fallback.as_ref()),
746          *use_default,
747          tokens.is_empty(),
748        )?;
749        tokens.extend(reverted);
750      }
751    }
752    // and return the list of tokens
753    Ok(Tokens::new(tokens))
754  }
755
756  fn revert_keyval(
757    &self,
758    key: &str,
759    keyset: &str,
760    value_opt: Option<&ArgWrap>,
761    use_default: bool,
762    is_first: bool,
763  ) -> Result<Vec<Token>> {
764    // get the key-value definition
765    let keytype_stored = keyval_get(&keyval_qname(&self.prefix, keyset, key), "type");
766    // define the tokens
767    let mut tokens = Vec::new();
768    // write comma and key, unless in the first iteration
769    if !is_first {
770      tokens.push(T_OTHER!(","));
771    }
772    tokens.extend(Explode!(key));
773    // write the default (if applicable)
774    if !use_default && let Some(value) = value_opt {
775      tokens.push(T_OTHER!("="));
776      let mut reverted_tokens = Vec::new();
777      if let Some(Stored::Parameter(keytype)) = keytype_stored {
778        // TODO: The types here are a little curious. The stored value must be cast back into
779        // Tokens if Parameter's revert works on Tokens. Or should that revert call work on
780        // ArgWrap?
781        if let Some(reverted) = keytype.revert(Some(value.revert()?))? {
782          reverted_tokens.extend(reverted.unlist());
783        }
784      } else {
785        reverted_tokens.extend(value.revert()?.unlist());
786      }
787      tokens.extend(self.rebrace(Tokens::new(reverted_tokens)).unlist());
788    }
789    Ok(tokens)
790  }
791
792  /// When reverting a KeyVals value, we may need to wrap in {}
793  /// eg. if a "," appears outside of any bracing
794  /// Other cases?
795  fn rebrace(&self, tokens: Tokens) -> Tokens {
796    let mut level: i32 = 0;
797    let mut needs_brace = tokens.is_empty();
798    for t in tokens.unlist_ref() {
799      let cc = t.get_catcode();
800      if cc == Catcode::BEGIN {
801        level += 1;
802      }
803      if cc == Catcode::END {
804        level -= 1;
805        // Note that '{ }} {' is still unbalanced
806        // even though the left and right braces match in count.
807        if level < 0 {
808          break;
809        }
810      } else if level <= 0 && cc == Catcode::OTHER && t.with_str(|s| s == ",") {
811        // Outer comma?
812        needs_brace = true;
813        break;
814      }
815    }
816    if needs_brace {
817      let mut wrapped = vec![T_BEGIN!()];
818      wrapped.extend(tokens.unlist());
819      wrapped.push(T_END!());
820      Tokens::new(wrapped)
821    } else {
822      tokens
823    }
824  }
825
826  //======================================================================
827  // Changing contained values
828  //======================================================================
829
830  pub fn add_value(
831    &mut self,
832    key: &str,
833    value_arg: ArgWrap,
834    use_default: bool,
835    no_rebuild: bool,
836  ) -> Result<()> {
837    // figure out the keyset(s) for the key to be added
838    let keysets = self.resolve_keyval_for(key);
839    let primary_keyset = self.get_primary_keyval(keysets.as_slice()).to_owned();
840
841    // and add the new tuple to the set of tuples
842    let value = if use_default {
843      match keyval_get(&keyval_qname(&self.prefix, &primary_keyset, key), "default") {
844        None => Some(ArgWrap::Tokens(Tokens!())), // bare key with no default: empty value
845        Some(v) => {
846          let arg: Result<ArgWrap> = v.into();
847          Some(arg?)
848        },
849      }
850    } else {
851      Some(value_arg)
852    };
853    self.tuples.push(KVData {
854      key: key.to_string(),
855      value,
856      use_default,
857      keysets,
858      primary_keyset,
859      digested_value: None,
860    });
861    // we now need to rebuild, unless we were asked not to
862    // TODO: Maybe only update the last element?
863    if !no_rebuild {
864      self.rebuild(None);
865    }
866    Ok(())
867  }
868
869  pub fn set_value(&mut self, key: &str, value: ArgWrap, use_default: bool) -> Result<()> {
870    // delete the existing values by skipping key
871    self.rebuild(Some(key));
872    // Perl: if (ref $value eq 'ARRAY') { foreach ... addValue(..., 1) } rebuild()
873    //       elsif (defined($value)) { addValue($key, $value, $useDefault) }
874    //       else { just delete (already done by rebuild above) }
875    match &value {
876      ArgWrap::None => {
877        // undef — just delete (already done by rebuild above)
878        Ok(())
879      },
880      _ => {
881        // single value — set normally
882        self.add_value(key, value, use_default, false)
883      },
884    }
885  }
886
887  fn rebuild(&mut self, skip_opt: Option<&str>) {
888    // the new data structures to create
889    let mut newtuples: Vec<KVData> = Vec::new();
890    let mut pairs = Vec::new();
891    let mut hash: HashMap<String, Vec<ArgWrap>> = HashMap::default();
892    let mut hash_digested: HashMap<String, Vec<Digested>> = HashMap::default();
893
894    for tuple in self.tuples.drain(..) {
895      // take all the elements we need from the stack
896      let KVData {
897        key,
898        value,
899        use_default,
900        primary_keyset,
901        keysets,
902        digested_value,
903      } = tuple;
904      // if we want to skip some values, we need to store new tuples
905      let key_str = key.as_str();
906      if let Some(skip) = skip_opt
907        && skip == key_str
908      {
909        continue;
910      }
911      if let Some(v) = value.as_ref() {
912        // push key / value into the pair
913        pairs.push((key.clone(), v.clone()));
914
915        // we always use Vec<ArgWrap> storage, just push the new value in
916        let entry = hash.entry(key.clone()).or_default();
917        entry.push(v.clone());
918      } else if let Some(ref dv) = digested_value {
919        // After digestion, value is taken but digested_value is set.
920        // Populate cached_pairs from the digested value (matching Perl's rebuild behavior).
921        let fallback = ArgWrap::Tokens(dv.revert().unwrap_or_default());
922        pairs.push((key.clone(), fallback.clone()));
923        let entry = hash.entry(key.clone()).or_default();
924        entry.push(fallback);
925      }
926      // if we have a digested value, push that in the Vec<Digested> hash storage
927      if let Some(ref dvalue) = digested_value {
928        let entry = hash_digested.entry(key.clone()).or_default();
929        entry.push(dvalue.clone());
930      }
931
932      // Record.
933      newtuples.push(KVData {
934        key,
935        value,
936        use_default,
937        primary_keyset,
938        keysets,
939        digested_value,
940      });
941    }
942    // store all of the values
943    self.cached_pairs = pairs;
944    self.cached_hash = hash;
945    self.cached_hash_digested = hash_digested;
946    self.tuples = newtuples;
947  }
948
949  //======================================================================
950  // parsing values from a gullet
951  //======================================================================
952
953  // A KeyVal argument MUST be delimited by either braces or brackets (if optional)
954  // This method reads the keyval pairs INCLUDING the delimiters, (rather than
955  // parsing after the fact), since some values may have special catcode needs.
956
957  /// xkeyval `\savekeys` membership: the save list for `<prefix>@<keyset>@`
958  /// lives in `\XKV@<prefix>@<keyset>@save` (xkeyval.tex L407-415, maintained
959  /// by the verbatim `\XKV@savekeys` port in xkeyval_sty.rs); entries are key
960  /// names, optionally wrapped as `\global{key}` for a global save. Returns
961  /// `Some(global)` when `key` is listed.
962  fn save_listed(&self, keyset: &str, key: &str) -> Option<bool> {
963    let cs = T_CS!(s!("\\XKV@{}", keyval_qname(&self.prefix, keyset, "save")));
964    state::lookup_meaning(&cs)?;
965    let body = gullet::do_expand(Tokens!(cs)).ok()?.to_string();
966    for entry in body.split(',') {
967      let e = entry.trim();
968      let (global, name) = match e.strip_prefix("\\global") {
969        Some(rest) => (true, rest),
970        None => (false, e),
971      };
972      let name = name
973        .trim()
974        .trim_start_matches('{')
975        .trim_end_matches('}')
976        .trim();
977      if name == key {
978        return Some(global);
979      }
980    }
981    None
982  }
983
984  /// xkeyval.tex L560-583 `\XKV@replacepointers`: splice every
985  /// `\usevalue{X}` in a value with the stored `\XKV@<header>X@value` body
986  /// (one macro level, re-scanned so a stored value may itself point on),
987  /// EAGERLY at `\setkeys` time under the key's own header. The key code
988  /// then receives the literal value, so a value it stores for later
989  /// (pmdraw.sty:1704-1706 `\renewcommand{\pmdraw@tikz}{#1}`, consumed inside
990  /// the tikzpicture at :1857-1860) never carries an unresolved pointer into
991  /// a context whose active `\setkeys` header differs — the lazy `\usevalue`
992  /// macro (xkeyval_sty.rs) produced 501 "no value recorded" errors on
993  /// pmdraw. A missing store errors and drops the pointer (L570-571); a
994  /// back-linking pointer cancels the replacement (L573-576).
995  fn replace_pointers(&self, keyset: &str, value: Tokens) -> Result<Tokens> {
996    let usevalue = T_CS!("\\usevalue");
997    if !value.unlist_ref().contains(&usevalue) {
998      return Ok(value);
999    }
1000    let mut toks: Vec<Token> = value.unlist();
1001    let mut out: Vec<Token> = Vec::with_capacity(toks.len());
1002    let mut seen: Vec<String> = Vec::new();
1003    let mut i = 0;
1004    while i < toks.len() {
1005      if toks[i] != usevalue {
1006        out.push(toks[i]);
1007        i += 1;
1008        continue;
1009      }
1010      // the pointer's key: a braced group or the single next token
1011      let mut j = i + 1;
1012      let key = if j < toks.len() && toks[j].get_catcode() == Catcode::BEGIN {
1013        let mut depth = 0;
1014        let mut inner = Vec::new();
1015        while j < toks.len() {
1016          match toks[j].get_catcode() {
1017            Catcode::BEGIN => depth += 1,
1018            Catcode::END => {
1019              depth -= 1;
1020              if depth == 0 {
1021                j += 1;
1022                break;
1023              }
1024            },
1025            _ => {},
1026          }
1027          if depth > 1 || toks[j].get_catcode() != Catcode::BEGIN {
1028            inner.push(toks[j]);
1029          }
1030          j += 1;
1031        }
1032        Tokens::new(inner).to_string()
1033      } else if j < toks.len() {
1034        j += 1;
1035        toks[j - 1].to_string()
1036      } else {
1037        String::new()
1038      };
1039      let key = key.trim().to_string();
1040      let cs = T_CS!(s!(
1041        "\\XKV@{}@value",
1042        keyval_qname(&self.prefix, keyset, &key)
1043      ));
1044      // xkeyval.tex L569 `\XKV@ifundefined` tests DEFINEDNESS, not the body:
1045      // a key saved with an empty value (pmdraw.sty:2191-2264 `tikz={}`,
1046      // `label node={}` …) is `\let` to an empty-bodied macro (L525-527) and
1047      // replaces to nothing. `Expandable::new` collapses an empty Tokens body
1048      // to `expansion = None`, so `get_expansion()` alone reads it as
1049      // unrecorded — pmdraw manual, 501 `no value recorded` errors + cap.
1050      let body = match state::lookup_definition(&cs) {
1051        Ok(Some(defn)) => Some(match defn.get_expansion() {
1052          Some(ExpansionBody::Tokens(body)) => body.clone(),
1053          _ => Tokens::new(Vec::new()),
1054        }),
1055        _ => None,
1056      };
1057      match body {
1058        None => {
1059          Error!(
1060            "undefined",
1061            "\\usevalue",
1062            s!("no value recorded for key `{key}'; ignored")
1063          );
1064          toks.drain(i..j);
1065        },
1066        Some(_) if seen.contains(&key) => {
1067          Error!(
1068            "unexpected",
1069            "\\usevalue",
1070            "back linking pointers; pointer replacement canceled"
1071          );
1072          toks.drain(i..j);
1073        },
1074        Some(body) => {
1075          seen.push(key);
1076          toks.splice(i..j, body.unlist());
1077        },
1078      }
1079    }
1080    Ok(Tokens::new(out))
1081  }
1082
1083  /// Store a saved key value as `\XKV@<prefix>@<keyset>@<key>@value`
1084  /// (xkeyval.tex L521-528).
1085  fn store_saved_value(&self, keyset: &str, key: &str, value: Tokens, global: bool) -> Result<()> {
1086    let cs = T_CS!(s!(
1087      "\\XKV@{}@value",
1088      keyval_qname(&self.prefix, keyset, key)
1089    ));
1090    let options = global.then(|| ExpandableOptions {
1091      scope: Some(Scope::Global),
1092      ..ExpandableOptions::default()
1093    });
1094    def_macro(cs, None, ExpansionBody::Tokens(value), options)
1095  }
1096
1097  pub fn read_from(&mut self, until: Token, silence_missing: bool) -> Result<()> {
1098    // if we want to force skip_missing keys, we set it up here
1099    let skip_missing = self.skip_missing.clone();
1100    let hook_missing = self.hook_missing;
1101    // if we want to silence all missing errors, store them in a hook
1102    if silence_missing {
1103      self.skip_missing = SkipMissing::All;
1104      self.hook_missing = None;
1105    }
1106
1107    // read the opening token and figure out where we are
1108    let startloc = gullet::get_locator();
1109    // set and read tokens
1110    let _open = gullet::read_token()?;
1111
1112    // xkeyval pointer system (\savevalue/\usevalue/\savekeys — xkeyval.tex
1113    // L405-436, L518-533, L560-583): record the active prefix/keysets so the
1114    // \usevalue closure (xkeyval_sty.rs) can resolve the
1115    // `\XKV@<header><key>@value` stores this read creates below.
1116    state::assign_value(
1117      "XKV@ptr@prefix",
1118      Stored::String(arena::pin(&self.prefix)),
1119      None,
1120    );
1121    state::assign_value(
1122      "XKV@ptr@keysets",
1123      Stored::String(arena::pin(self.keysets.join(","))),
1124      None,
1125    );
1126
1127    // the typed lengths' stated tokens kept (`stated_entry`)
1128    let mut stated: Vec<(String, Tokens)> = Vec::new();
1129    let punct_tks = Tokens!(T_OTHER!(","));
1130    let until_tks = Tokens!(until);
1131    // iterate over all the key-value pairs to read
1132    loop {
1133      // gobble leading spaces
1134      gullet::skip_spaces()?;
1135      if gullet::if_next(T_BEGIN!())? {
1136        // Protect against redundant {} wrapping
1137        gullet::read_token()?;
1138        gullet::unread(gullet::read_balanced(ExpansionLevel::Off, false, false)?.strip_braces());
1139        gullet::skip_spaces()?;
1140      }
1141      // Read a single keyword, get a delimiter and a set of keyword tokens
1142      let (ktoks, mut delim_opt) = self.read_keyword_from(until)?;
1143
1144      // if there was no delimiter at the end, we throw an error
1145      if delim_opt.is_none() {
1146        let message = s!(
1147          "Fell off end expecting {} while reading KeyVal key",
1148          until.stringify()
1149        );
1150        let message2 = s!("key started at {}", startloc.to_string());
1151        Error!("expected", until, message, message2);
1152      }
1153
1154      // turn the key tokens into a string and trim whitespace
1155      let key_str = ktoks.to_string();
1156      let key = key_str.trim();
1157
1158      // if we have a non-empty key
1159      if !key.is_empty() {
1160        let mut value = ArgWrap::None;
1161        // if we have an '=', we explcity assign a value
1162        let is_explicit = delim_opt == Some(T_OTHER!("="));
1163        if is_explicit {
1164          // setup the key-codes to properly read
1165          let resolved_kv = self.resolve_keyval_for(key);
1166          let keyset = self.get_primary_keyval(&resolved_kv);
1167          let keytype_opt = keyval_get(&keyval_qname(&self.prefix, keyset, key), "type");
1168          if let Some(Stored::Parameter(ref keytype)) = keytype_opt {
1169            keytype.setup_catcodes();
1170          }
1171          // read until comma
1172          let mut toks = Vec::new();
1173          loop {
1174            // TODO: The types are a bit unnatural here - we need the plural Tokens for read_match,
1175            //       but we expect the singular Token as a delimiter result, since we are matching
1176            // on a char separator
1177            delim_opt = gullet::read_match(&[&punct_tks, &until_tks])?.map(|tks| tks.into());
1178            if delim_opt.is_some() {
1179              break; // only until we hit a delim.
1180            }
1181            if let Some(tok) = gullet::read_token()? {
1182              // Copy next token to args
1183              toks.push(tok);
1184              if tok.get_catcode() == Catcode::BEGIN {
1185                let balanced_arg = gullet::read_balanced(ExpansionLevel::Off, false, false)?;
1186                if !balanced_arg.is_empty() {
1187                  toks.extend(balanced_arg.unlist());
1188                }
1189                toks.push(T_END!());
1190              }
1191            } else {
1192              break;
1193            }
1194          }
1195          // reparse (and expand) the tokens representing the value
1196          let mut raw_value_tks: Option<Tokens> = None;
1197          if !toks.is_empty() {
1198            // xkeyval.tex L525-528 saves the RAW value (pointers unresolved)
1199            // before L529 replaces the pointers for the key code.
1200            let raw_toks = Tokens::new(toks).strip_braces_n(2);
1201            raw_value_tks = Some(raw_toks.clone());
1202            let stripped_toks = self.replace_pointers(keyset, raw_toks)?;
1203            if !stripped_toks.is_empty() {
1204              if let Some(Stored::Parameter(ref keytype)) = keytype_opt {
1205                // a length's tokens as stated, where they are kept (`stated_entry`)
1206                if (keytype.name == crate::pin!("Dimension") || keytype.name == crate::pin!("Glue"))
1207                  && state::lookup_bool(crate::parameter::KEEP_STATED_LENGTHS)
1208                {
1209                  stated.push((key.to_string(), stripped_toks.clone()));
1210                }
1211                value = keytype.reparse(stripped_toks)?;
1212              } else {
1213                value = ArgWrap::Tokens(stripped_toks);
1214              }
1215            }
1216          }
1217          // An explicit `=` always assigns a value, even when it is empty
1218          // (`key=` or `key={}`): that is an EXPLICIT empty override, distinct
1219          // from a missing key. Keep it as empty Tokens rather than the
1220          // `ArgWrap::None` the value was initialised to — `None` is reserved
1221          // for a missing key and its Display is the literal string "None",
1222          // which leaks into consumers that stringify the value. Concretely, a
1223          // starred matrix with no alignment bracket emits `alignment=` (empty);
1224          // without this the keyval value was "None", so `\lx@gen@matrix@bindings`
1225          // saw `alignment="None"` instead of defaulting to "c", producing a
1226          // malformed column alignment that made a `\dots` cell swallow the next
1227          // `&` → "Stray alignment". Witness 1910.00678.
1228          if value.is_none() {
1229            value = ArgWrap::Tokens(Tokens!());
1230          }
1231          // and cleanup
1232          if let Some(Stored::Parameter(ref keydef)) = keytype_opt {
1233            keydef.revert_catcodes()?;
1234          }
1235          // xkeyval pointer system: `\savevalue{key}` latched the pending
1236          // flags while the key portion expanded (closure in xkeyval_sty.rs),
1237          // and a `\savekeys` list can mark the key persistently (entries may
1238          // be `\global{key}`). Mirror xkeyval.tex L521-528: store the value
1239          // as `\XKV@<prefix>@<keyset>@<key>@value` so raw packages can read
1240          // it back (chessboard.sty L1221-1229
1241          // `\boolean{\XKV@UFCB@locset@psset@value}`, xskak.sty L415).
1242          let pending_rkv = state::lookup_bool("XKV@ptr@rkv");
1243          let pending_sg = state::lookup_bool("XKV@ptr@sg");
1244          if pending_rkv || pending_sg {
1245            state::assign_value("XKV@ptr@rkv", Stored::from(false), None);
1246            state::assign_value("XKV@ptr@sg", Stored::from(false), None);
1247          }
1248          let save_global = if pending_rkv {
1249            Some(pending_sg)
1250          } else {
1251            self.save_listed(keyset, key)
1252          };
1253          if let Some(global) = save_global {
1254            let value_tks =
1255              raw_value_tks.unwrap_or_else(|| value.clone().owned_tokens().unwrap_or_default());
1256            self.store_saved_value(keyset, key, value_tks, global)?;
1257          }
1258        }
1259        // and store our value please
1260        if !silence_missing || self.can_resolve_keyval_for(key) {
1261          self.add_value(key, value, !is_explicit, false)?;
1262        }
1263      }
1264
1265      // we finish if we have the last element
1266      if delim_opt.as_ref() == Some(&until) {
1267        break;
1268      }
1269    }
1270
1271    self.stated.extend(stated);
1272    // rebuild and return nothing
1273    self.rebuild(None);
1274
1275    // restore all settings if we silenced the missing keys
1276    if silence_missing {
1277      self.skip_missing = skip_missing;
1278      self.hook_missing = hook_missing;
1279    }
1280    Ok(())
1281  }
1282
1283  /// TODO: This is an improvised method for switching KeyVals into Tokens, but losing all collected
1284  /// metadata.
1285  /// The long-term solution ought to be via a type system extension, where the
1286  /// arguments to our before-digest closures are a vector of a new type
1287  /// ReadValue ::= [Token, KeyVals, RegisterValue]       potentially?
1288  /// On the other hand, we can also put the
1289  /// extra effort of *postponing* the build of KV metadata until digestion,
1290  /// this way not losing any time reserializing metadata
1291  pub fn into_tokens(self) -> Result<Tokens> {
1292    let mut tks: Vec<Token> = Vec::new();
1293    for (k, v) in self.cached_pairs.into_iter() {
1294      tks.push(T_OTHER!(k));
1295      match v {
1296        ArgWrap::Tokens(vtks) => {
1297          let expanded = gullet::do_expand(vtks)?;
1298          let mut exp_str = expanded.to_string();
1299          if exp_str == "{}" {
1300            exp_str.clear();
1301          }
1302          tks.push(T_OTHER!(exp_str));
1303        },
1304        ArgWrap::Token(vtk) => tks.push(vtk),
1305        other => {
1306          emit_warn(
1307            "internal",
1308            "keyvals",
1309            &format!("Unexpected ArgWrap variant in KeyVals revert: {other:?}"),
1310          );
1311        },
1312      }
1313    }
1314    Ok(Tokens::new(tks))
1315  }
1316}
1317
1318impl From<KeyVals> for Result<Option<Digested>> {
1319  fn from(value: KeyVals) -> Result<Option<Digested>> {
1320    let tmp: Digested = value.into();
1321    tmp.into()
1322  }
1323}
1324
1325/// Whether keyval's unknown-key report has been switched off: keyval.sty raises it through `\KV@errx`
1326/// (keyval.sty:41-42, :60-65), which a package may redefine to do nothing for its own `\setkeys` — CoverPage.sty:128
1327/// `\def\KV@errx##1{\relax}` ("keyval: ignore unknown keys") for a BibTeX record's other fields. Then TeX reports
1328/// nothing, and neither does the native `\setkeys`. (keyval's default and `unknownkeyserror` raise an error; this
1329/// engine warns.)
1330fn unknown_keyval_keys_ignored() -> bool {
1331  match state::lookup_definition(&T_CS!("\\KV@errx")) {
1332    Ok(Some(defn)) => match defn.get_expansion() {
1333      Some(ExpansionBody::Tokens(body)) => body.unlist_ref().iter().all(|t| *t == T_CS!("\\relax")),
1334      _ => true,
1335    },
1336    _ => false,
1337  }
1338}
1339
1340#[cfg(test)]
1341mod tests {
1342  use super::*;
1343
1344  #[test]
1345  fn skip_missing_default_is_none() {
1346    let s = SkipMissing::default();
1347    assert_eq!(s, SkipMissing::None);
1348  }
1349
1350  #[test]
1351  fn skip_missing_variants_not_equal() {
1352    assert_ne!(SkipMissing::None, SkipMissing::All);
1353  }
1354
1355  #[test]
1356  fn keyvals_config_default_all_empty() {
1357    let c = KeyvalsConfig::default();
1358    assert!(c.prefix.is_none());
1359    assert!(c.keysets.is_empty());
1360    assert!(!c.set_all);
1361    assert!(!c.set_internals);
1362    assert!(c.skip.is_empty());
1363    assert_eq!(c.skip_missing, SkipMissing::None);
1364    assert!(c.hook_missing.is_none());
1365  }
1366
1367  #[test]
1368  fn keyvals_default_prefix_and_anonymous_keyset() {
1369    // Default KeyVals has prefix=KV, keysets=["_anonymous_"].
1370    let kv = KeyVals::default();
1371    assert_eq!(kv.prefix, "KV");
1372    assert_eq!(kv.keysets, vec!["_anonymous_".to_string()]);
1373    assert!(!kv.set_all);
1374    assert!(!kv.set_internals);
1375  }
1376
1377  #[test]
1378  fn keyvals_new_with_empty_keysets_defaults_to_anonymous() {
1379    let kv = KeyVals::new(KeyvalsConfig::default());
1380    assert_eq!(kv.keysets, vec!["_anonymous_".to_string()]);
1381  }
1382
1383  #[test]
1384  fn keyvals_new_with_custom_keysets_preserved() {
1385    let cfg = KeyvalsConfig {
1386      keysets: vec!["tabular".to_string(), "array".to_string()],
1387      ..KeyvalsConfig::default()
1388    };
1389    let kv = KeyVals::new(cfg);
1390    assert_eq!(kv.keysets.len(), 2);
1391    assert_eq!(kv.keysets[0], "tabular");
1392  }
1393
1394  #[test]
1395  fn keyvals_new_custom_prefix() {
1396    let cfg = KeyvalsConfig {
1397      prefix: Some("P".to_string()),
1398      ..KeyvalsConfig::default()
1399    };
1400    let kv = KeyVals::new(cfg);
1401    assert_eq!(kv.prefix, "P");
1402  }
1403
1404  #[test]
1405  fn keyvals_new_default_prefix_on_none() {
1406    let cfg = KeyvalsConfig {
1407      prefix: None,
1408      ..KeyvalsConfig::default()
1409    };
1410    let kv = KeyVals::new(cfg);
1411    assert_eq!(kv.prefix, "KV");
1412  }
1413
1414  #[test]
1415  fn keyvals_new_set_all_flag() {
1416    let cfg = KeyvalsConfig {
1417      set_all: true,
1418      ..KeyvalsConfig::default()
1419    };
1420    let kv = KeyVals::new(cfg);
1421    assert!(kv.set_all);
1422  }
1423
1424  #[test]
1425  fn keyvals_new_keeps_the_empty_family() {
1426    // `\pst@famlist` accumulates as ",pstricks" (pst-xkey.tex:53-57); xkeyval
1427    // searches the empty family first, and its key macros are `\psset@<key>`
1428    // (keyval_qname's header rule), so nothing collides with pstricks'
1429    // delimited `\psset@@…` helpers. Perl drops the entry (KPE #212).
1430    let cfg = KeyvalsConfig {
1431      keysets: vec!["".to_string(), "pstricks".to_string()],
1432      ..KeyvalsConfig::default()
1433    };
1434    let kv = KeyVals::new(cfg);
1435    assert_eq!(kv.keysets, vec!["".to_string(), "pstricks".to_string()]);
1436  }
1437
1438  #[test]
1439  fn keyvals_new_all_empty_keysets_stay_the_empty_family() {
1440    // Explicit empty entries are the empty family; only an ABSENT list
1441    // falls back to _anonymous_.
1442    let cfg = KeyvalsConfig {
1443      keysets: vec!["".to_string(), "".to_string()],
1444      ..KeyvalsConfig::default()
1445    };
1446    let kv = KeyVals::new(cfg);
1447    // An explicit empty family is xkeyval's empty family, not `_anonymous_`.
1448    assert_eq!(kv.keysets, vec!["".to_string(), "".to_string()]);
1449  }
1450}