Skip to main content

latexml_core/
keyval.rs

1//! Key-Value Definitions
2//!
3//! Provides an interface to define and access KeyVal definition.
4//! Used in conjunction with `KeyVals` to
5//!  fully implement KeyVal pairs.
6
7use std::{borrow::Cow, rc::Rc};
8
9use crate::{
10  binding::def::dialect::{def_conditional, def_macro},
11  common::{def_parser::parse_parameters, error::*, store::Stored},
12  definition::{
13    ExpansionBody, ExpansionClosure, argument::ArgWrap, conditional::ConditionalOptions,
14  },
15  mouth::tokenize,
16  parameter::Parameter,
17  state,
18  token::{Catcode, Token},
19  tokens::{TeXString, Tokens},
20};
21
22#[derive(Debug, Clone, PartialEq)]
23pub struct KeyVal {
24  // which KeyVals are we parsing and how do we behave?
25  prefix: String,
26  key:    String,
27  keyset: String,
28}
29
30impl Default for KeyVal {
31  fn default() -> Self {
32    KeyVal {
33      prefix: "KV".to_string(),
34      keyset: String::new(),
35      key:    String::new(),
36    }
37  }
38}
39
40impl KeyVal {
41  pub fn new(prefix: Option<String>, keyset: String, key: String) -> Self {
42    let prefix = prefix.unwrap_or_else(|| "KV".to_string());
43    KeyVal { prefix, key, keyset }
44  }
45
46  pub fn get_header(&self) -> String { s!("{}@{}@{}", self.prefix, self.keyset, self.key) }
47
48  //======================================================================
49  // Property access
50  //======================================================================
51
52  pub fn get_prop(&self, key: &str) -> Option<Stored> {
53    state::lookup_value(&s!("KEYVAL@{}@{}", key, self.get_header()))
54  }
55  pub fn get_default(&self) -> Option<Stored> { self.get_prop("default") }
56  pub fn get_type(&self) -> Option<Rc<Parameter>> {
57    // Read directly via with_value — avoids the Stored::clone that
58    // get_prop's lookup_value pays just so we can pattern-match on
59    // the Parameter variant and Rc::clone its body. Hot path during
60    // keyval parsing.
61    state::with_value(&s!("KEYVAL@type@{}", self.get_header()), |v| match v {
62      Some(Stored::Parameter(p)) => Some(Rc::clone(p)),
63      _ => None,
64    })
65  }
66}
67
68// semi-internals
69pub(crate) fn keyval_qname(prefix: &str, keyset: &str, key: &str) -> String {
70  let prefix = if prefix.is_empty() { "KV" } else { prefix };
71  // xkeyval.tex:83-88 `\XKV@makehd`: header = `<prefix>@` followed by
72  // `<family>@` ONLY when the family is non-empty, so an empty-family key
73  // (`\define@key[psset]{}{precode}`, pstricks.tex:808) is `\psset@precode`,
74  // never `\psset@@precode`. Perl KeyVal.pm:60-62 always doubles the `@`,
75  // which is why its `KeyVals->new` had to drop the empty family (KNOWN_PERL_ERRORS
76  // #212, DIVERGENCES #219); with the real rule the `@@` names stay free for
77  // pstricks' delimited helpers (`\psset@@dash`, `\psset@@ArrowInside`).
78  if keyset.is_empty() {
79    s!("{prefix}@{key}")
80  } else {
81    s!("{prefix}@{keyset}@{key}")
82  }
83}
84
85pub(crate) fn keyval_get(qname: &str, prop: &str) -> Option<Stored> {
86  state::lookup_value(&s!("KEYVAL@{prop}@{qname}"))
87}
88
89/// Using local assignments in the State to set keyvals, but that necessitates a
90/// cast of `ArgWrap`` to `State`` on set and `State` to `ArgWrap` on get.
91/// Certain values don't really work well with that, e.g. Stored::Bool ...
92/// The original Perl made no type casts, as there weren't any concrete types.
93pub(crate) fn keyval_set(qname: &str, prop: &str, value: Stored) {
94  state::assign_value(&s!("KEYVAL@{prop}@{qname}"), value, None);
95}
96
97/// check if a key-value pair is defined
98pub fn has_keyval(prefix: &str, keyset: &str, key: &str) -> bool {
99  let qname = keyval_qname(prefix, keyset, key);
100  state::with_value(&s!("KEYVAL@defined@{}", qname), |v| v.is_some())
101    || state::has_meaning(&T_CS!(s!("\\{qname}")))
102}
103
104/// disable a given key-val
105pub fn disable_keyval(prefix: &str, keyset: &str, key: &str) -> Result<()> {
106  let qname = keyval_qname(prefix, keyset, key);
107  keyval_set(&qname, "disabled", true.into());
108  // disable the key
109  define_ordinary(
110    &qname,
111    Some(ExpansionBody::Tokens(tokenize(TeXString::assembled(s!(
112      "\\PackageWarning{{keyval}}{{`{key}' has been disabled. }}"
113    ))))),
114  )
115}
116
117//======================================================================
118// Key Definition
119//======================================================================
120#[derive(Debug, Default, Clone)]
121/// Configuration fields for declaring a new KeyVal pattern
122pub struct KeyvalConfig<'a> {
123  pub prefix:      &'a str,
124  pub keyset:      &'a str,
125  pub key:         &'a str,
126  pub vtype:       &'a str,
127  pub default:     Option<&'a str>,
128  /// Token-form default, preferred over `default` when set: real xkeyval
129  /// stores the default's raw TOKENS (`\XKV@define@default`), while the
130  /// string path below re-tokenizes under the STANDARD cattable, splitting
131  /// internal names (`[\xskak@val@defaultid]` → `\xskak` + `@val@defaultid`
132  /// — xskak-keys.sty L25, the xskak/chessboard manuals' 1000-error csname
133  /// cascade). Perl shares the stringify bug (Package.pm DefKeyVal ToString).
134  pub default_tks: Option<Tokens>,
135  pub kind:        Option<&'a str>,
136  pub code:        Option<ExpansionBody>,
137  pub macroprefix: Option<&'a str>,
138  pub mismatch:    Option<ExpansionBody>,
139  pub normalize:   Option<bool>,
140  pub bin:         Option<Tokens>,
141  pub choices:     Vec<String>,
142}
143
144/// Register a keyval qname in the global registry for enumeration by \xkvview.
145fn register_keyval(qname: &str) {
146  use crate::common::arena;
147  let registry_key = "KEYVAL@registry";
148  // Borrow the registry via `with_value` to skip the outer Stored::clone
149  // (lookup_value clones the enum; we only need the inner Vec<SymStr>).
150  let mut registry: Vec<arena::SymStr> = state::with_value(registry_key, |v| match v {
151    Some(Stored::Strings(v)) => v.to_vec(),
152    _ => Vec::new(),
153  });
154  let sym = arena::pin(qname);
155  // avoid duplicates (re-definitions)
156  if !registry.contains(&sym) {
157    registry.push(sym);
158  }
159  state::assign_value(registry_key, Stored::Strings(registry.into()), None);
160}
161
162/// Metadata for a registered keyval, used by \xkvview.
163#[derive(Debug, Clone)]
164pub struct KeyvalMeta {
165  pub key:     String,
166  pub prefix:  String,
167  pub keyset:  String,
168  pub kind:    String,
169  pub default: String,
170}
171
172/// Enumerate all registered keyvals with their metadata (for \xkvview).
173pub fn enumerate_keyvals() -> Vec<KeyvalMeta> {
174  use crate::common::arena;
175  let registry_key = "KEYVAL@registry";
176  let registry = state::with_value(registry_key, |v| match v {
177    Some(Stored::Strings(v)) => v.to_vec(),
178    _ => Vec::new(),
179  });
180  if registry.is_empty() {
181    return Vec::new();
182  }
183  let mut result = Vec::new();
184  for sym in registry {
185    // Resolve the interned qname once via a closure — the five
186    // keyval_get calls below all take `&str`, so we hand each the same
187    // resolved borrow rather than allocating a per-key String.
188    let entry = arena::with(sym, |qname| {
189      let key = keyval_get(qname, "key_name")
190        .map(|s| s.to_string())
191        .unwrap_or_default();
192      let prefix = keyval_get(qname, "keyval_prefix")
193        .map(|s| s.to_string())
194        .unwrap_or_else(|| "KV".to_string());
195      let keyset = keyval_get(qname, "keyset")
196        .map(|s| s.to_string())
197        .unwrap_or_default();
198      let kind = keyval_get(qname, "kind")
199        .map(|s| s.to_string())
200        .unwrap_or_else(|| "ordinary".to_string());
201      let default = keyval_get(qname, "default")
202        .map(|s| s.to_string())
203        .unwrap_or_else(|| "[none]".to_string());
204      KeyvalMeta {
205        key,
206        prefix,
207        keyset,
208        kind,
209        default,
210      }
211    });
212    result.push(entry);
213  }
214  result
215}
216
217/// (Re-)defines this Key of kind 'kind'.
218///
219///Defines a keyword `key` used in keyval arguments for the set `keyset` and,
220///and if the option `code` is given, defines appropriate macros
221///when used with the `keyval` package (or extensions thereof).
222///
223///If `type` is given, it defines the type of value that must be supplied,
224///such as `Dimension`.  If `default` is given, that value will be used
225///when `key` is used without an equals and explicit value in a keyvals argument.
226///
227///A `scope` option can be given, which can be used to defined the key-value pair
228///globally instead of in the current scope.
229///
230///Several more `option`s can be given. These implement the behaviour of the
231///xkeyval package.
232///
233///The `prefix` parameter can be used to configure a custom prefix for
234///the macros to be defined. The `kind` parameter can be used to configure special types of xkeyval
235///pairs.
236///
237///The 'ordinary' kind behaves like a normal keyval parameter.
238///
239///The 'command' kind defines a command key, that when run stores the value of the
240///key in a special macro, which can be further specefied by the `macroprefix`
241///option.
242///
243///The 'choice' kind defines a choice key, which takes additional options
244///`choices` (to specify which choices are valid values), `mismatch` (to be run
245///if an invalid choice is made) and `bin` (see xkeyval documentation for
246///details).
247///
248///The 'boolean' kind defines a special choice key that takes possible values true and
249///false, and defines a new Conditional according to the assumed value. The name of
250///this conditional can be specified with the `macroprefix` option.
251///
252///The kind parameter only takes effect when `code` is given, otherwise only
253///meta-data is stored.
254pub fn define(options: KeyvalConfig) -> Result<()> {
255  let KeyvalConfig {
256    prefix,
257    keyset,
258    key,
259    vtype,
260    default,
261    default_tks,
262    kind,
263    code,
264    macroprefix,
265    mismatch,
266    normalize,
267    bin,
268    choices,
269  } = options;
270
271  let qname = keyval_qname(prefix, keyset, key);
272
273  // define that the key exists and is not disabled
274  keyval_set(&qname, "exists", true.into());
275  keyval_set(&qname, "disabled", false.into());
276  // store metadata for introspection (used by \xkvview)
277  // only register when xkvview tracking is enabled
278  if state::lookup_bool("XKVVIEW_TRACKING") {
279    // `assembled`: these four are bare identifiers (a key/keyset/prefix name),
280    // not markup — nothing to weld — but they arrive as borrowed `&str`.
281    let identifier = |s: &str| TeXString::assembled(s.to_string());
282    keyval_set(
283      &qname,
284      "kind",
285      Stored::Tokens(tokenize(identifier(kind.unwrap_or("ordinary")))),
286    );
287    keyval_set(
288      &qname,
289      "keyval_prefix",
290      Stored::Tokens(tokenize(identifier(prefix))),
291    );
292    keyval_set(
293      &qname,
294      "keyset",
295      Stored::Tokens(tokenize(identifier(keyset))),
296    );
297    keyval_set(
298      &qname,
299      "key_name",
300      Stored::Tokens(tokenize(identifier(key))),
301    );
302    register_keyval(&qname);
303  }
304  // set the type
305  let vtype = if vtype.is_empty() { "{}" } else { vtype };
306  let paramlist_opt = parse_parameters(
307    vtype,
308    &T_OTHER!(s!("KeyVal {key} in set {keyset} with prefix {prefix}")),
309    true,
310  )?;
311  match paramlist_opt {
312    None => {
313      Warn!(
314        "unexpected",
315        "keyval",
316        s!(
317          "No parameters in keyval {key} (in set {keyset} with prefix {prefix}) taking only first"
318        )
319      );
320    },
321    Some(paramlist) => {
322      if paramlist.get_num_args() != 1 {
323        Warn!(
324          "unexpected",
325          "keyval",
326          s!(
327            "Too many parameters in keyval {key} (in set {keyset} with prefix {prefix})\
328          taking only first"
329          )
330        );
331      }
332      keyval_set(&qname, "type", paramlist.take_parameters().remove(0).into());
333    },
334  };
335  // set the default
336  // Question: Why was $default converted ToString ???
337  let default_tokens = default_tks
338    .or_else(|| default.map(|default_str| tokenize(TeXString::assembled(default_str.to_string()))));
339  if let Some(default_tks) = default_tokens {
340    keyval_set(&qname, "default", Stored::Tokens(default_tks.clone()));
341    def_macro(
342      T_CS!(s!("\\{qname}@default")),
343      None,
344      ExpansionBody::Tokens(Tokens!(
345        T_CS!(s!("\\{qname}")),
346        T_BEGIN!(),
347        default_tks,
348        T_END!()
349      )),
350      None,
351    )?;
352  }
353
354  // figure out the kind of key-val parameter we are defining
355  let kind = kind.unwrap_or("ordinary");
356  match kind {
357    "ordinary" => define_ordinary(&qname, code)?,
358    "command" => {
359      // Perl #2777 (2026-03-27): macroprefix falls back to "cmd"+qname
360      // when undefined OR empty. The truthy check that existed pre-fix
361      // already treated empty-string as falsy; we match that semantics
362      // explicitly for Option<&str>.
363      let macroname = match macroprefix {
364        Some(mpfx) if !mpfx.is_empty() => s!("{mpfx}{key}"),
365        _ => s!("cmd{qname}"),
366      };
367      define_command(&qname, code, &macroname)?;
368    },
369    "choice" => define_choice(
370      &qname,
371      code,
372      mismatch,
373      choices,
374      normalize.unwrap_or(false),
375      bin,
376    )?,
377    "boolean" => define_boolean(
378      &qname,
379      code,
380      mismatch,
381      &if let Some(mpfx) = macroprefix {
382        Cow::Owned(s!("{mpfx}{key}"))
383      } else {
384        Cow::Borrowed(&qname)
385      },
386    )?,
387    _ => Warn!(
388      "unknown",
389      "undef",
390      s!(
391        "Unknown KeyVals kind {kind} should be one of 'ordinary', 'command', 'choice', 'boolean'. "
392      )
393    ),
394  };
395  Ok(())
396}
397
398/// Helper function to define state, neccesary for an ordinary key.
399fn define_ordinary(qname: &str, code_expansion: Option<ExpansionBody>) -> Result<()> {
400  let qname_cs = T_CS!(s!("\\{qname}"));
401  let plain_params = parse_parameters("{}", &qname_cs, true)?;
402  def_macro(qname_cs, plain_params, code_expansion, None)
403}
404
405/// Helper function to define state, neccesary for a command key.
406fn define_command(qname: &str, code: Option<ExpansionBody>, macroname: &str) -> Result<()> {
407  let qname_cs = T_CS!(s!("\\{qname}"));
408  let plain_params = parse_parameters("{}", &qname_cs, true)?;
409  let plainp = plain_params.clone();
410  let orig = s!("\\ltxml@orig@{qname}");
411  let macroname_cs = s!("\\{macroname}");
412  let closure: ExpansionClosure = Rc::new(move |value: Vec<ArgWrap>| {
413    def_macro(T_CS!(&orig), plainp.clone(), code.clone(), None)?;
414    let value_tks: Vec<Token> = value
415      .into_iter()
416      .flat_map(|v| {
417        v.owned_tokens()
418          .map(|inner| inner.unlist())
419          .unwrap_or_default()
420      })
421      .collect();
422    // Perl KeyVal.pm L131 emits `T_PARAM, $value` here (with the author's own
423    // "!?!??!" comment), so the key code's argument arrives as `#<value>` and
424    // the stray PARAM token reaches the stomach: `Error:misdefined:#` on every
425    // \define@cmdkey use, and `#1` in the code body never sees the value.
426    // Real xkeyval (xkeyval.tex `\XKV@define@cmdkey`) runs the code with `#1`
427    // = the bare value — KNOWN_PERL_ERRORS #1275; witness
428    // doc/latex/xkeymask/xkeymask.tex. Emit the bare value.
429    Ok(Tokens!(
430      T_CS!("\\def"),
431      T_CS!(&macroname_cs),
432      T_BEGIN!(),
433      value_tks.clone(),
434      T_END!(),
435      T_CS!(&orig),
436      T_BEGIN!(),
437      value_tks,
438      T_END!()
439    ))
440  });
441  def_macro(
442    qname_cs,
443    plain_params,
444    ExpansionBody::Closure(closure),
445    None,
446  )
447}
448
449/// Helper function to define state, neccesary for an choice key.
450fn define_choice(
451  qname: &str,
452  code_opt: Option<ExpansionBody>,
453  mismatch_opt: Option<ExpansionBody>,
454  choices: Vec<String>,
455  normalize: bool,
456  bin: Option<Tokens>,
457) -> Result<()> {
458  let (varmacro_opt, idxmacro_opt) = if let Some(bin_tks) = bin {
459    let mut bin_iter = bin_tks.unlist().into_iter();
460    (bin_iter.next(), bin_iter.next())
461  } else {
462    (None, None)
463  };
464  let qname_cs = T_CS!(s!("\\{qname}"));
465  let orig = T_CS!(s!("\\ltxml@orig@{qname}"));
466  let plain_params = parse_parameters("{}", &qname_cs, true)?;
467  let plain_params_main = plain_params.clone();
468  let closure: ExpansionClosure = Rc::new(move |mut values| {
469    // Store the normalized value (if applicable)
470    let value = values.remove(0).owned_tokens().unwrap_or_default();
471    let mut nvalue = value.to_string();
472    if normalize {
473      nvalue = nvalue.to_lowercase();
474    }
475    if let Some(varmacro) = varmacro_opt {
476      // xkeyval.tex `\XKV@checkchoice` leaves the chosen value in the bin
477      // macro with its ORIGINAL catcodes (`\lowercase` for the `*` form keeps
478      // them): letters stay catcode 11, so a later `\ifx`/`\in@` against a
479      // catcode-11 list matches (powerdot.cls:353-387 `\pd@pdifs@tup` on
480      // `\pd@cursetup`). `Explode!` made every letter catcode 12 — Perl
481      // KeyVal.pm:143 shares that (KNOWN_PERL_ERRORS #215, batch 56ar).
482      let body = if normalize {
483        Tokens::new(ExplodeText!(nvalue))
484      } else {
485        value.clone()
486      };
487      def_macro(varmacro, None, ExpansionBody::Tokens(body), None)?;
488    }
489    // iterate over the possible choices and store them
490    let mut valid = false;
491    for (index, choice_str) in choices.iter().enumerate() {
492      if (normalize && (choice_str.to_lowercase() == nvalue)) || *choice_str == nvalue {
493        valid = true;
494        if let Some(idxmacro) = idxmacro_opt {
495          def_macro(
496            idxmacro,
497            None,
498            ExpansionBody::Tokens(Tokens::new(Explode!(index))),
499            None,
500          )?;
501        }
502      }
503    }
504    // find a name for the original macro to store in
505    let mut tokens = Vec::new();
506    // if we have chosen a valid index, run $code
507    if valid {
508      if let Some(ref code) = code_opt {
509        def_macro(orig, plain_params.clone(), code.clone(), None)?;
510        tokens.push(orig);
511        tokens.push(T_BEGIN!());
512        tokens.extend(value.unlist());
513        tokens.push(T_END!());
514      }
515    } else if let Some(ref mismatch) = mismatch_opt {
516      // else run `mismatch
517      def_macro(orig, plain_params.clone(), mismatch.clone(), None)?;
518      tokens.push(orig);
519      tokens.push(T_BEGIN!());
520      tokens.extend(value.unlist());
521      tokens.push(T_END!());
522    }
523    Ok(Tokens::new(tokens))
524  });
525  def_macro(
526    qname_cs,
527    plain_params_main,
528    ExpansionBody::Closure(closure),
529    None,
530  )
531}
532
533/// Helper function to define state, neccesary for a boolean key.
534fn define_boolean(
535  qname: &str,
536  code_opt: Option<ExpansionBody>,
537  mismatch: Option<ExpansionBody>,
538  macroname: &str,
539) -> Result<()> {
540  def_conditional(
541    T_CS!(s!("\\if{macroname}")),
542    None,
543    None,
544    ConditionalOptions::default(),
545  )?; // We might need to $scope here
546  let orig = s!("\\ltxml@@rig@{qname}");
547  let orig_cs = T_CS!(orig);
548  let plain_params = parse_parameters("{}", &orig_cs, true)?;
549  let macroname_true = T_CS!(s!("\\{macroname}true"));
550  let macroname_false = T_CS!(s!("\\{macroname}false"));
551  let closure: ExpansionClosure = Rc::new(move |mut values: Vec<ArgWrap>| {
552    // set the conditional to true/false
553    let value = values.remove(0).owned_tokens().unwrap_or_default();
554    let value_str = value.to_string().to_lowercase();
555    let mut tokens = vec![];
556    // Toggle the conditional by invoking \XXXtrue or \XXXfalse
557    if value_str == "true" {
558      tokens.push(macroname_true);
559    } else {
560      tokens.push(macroname_false);
561    }
562    // Store and invoke the original macro if needed
563    if let Some(ref code) = code_opt {
564      def_macro(orig_cs, plain_params.clone(), code.clone(), None)?;
565      tokens.push(orig_cs);
566      tokens.push(T_BEGIN!());
567      tokens.extend(value.unlist());
568      tokens.push(T_END!());
569    }
570    Ok(Tokens::new(tokens))
571  });
572
573  define_choice(
574    qname,
575    Some(ExpansionBody::Closure(closure)),
576    mismatch,
577    vec!["true".to_string(), "false".to_string()],
578    true,
579    None,
580  )
581}
582
583#[cfg(test)]
584mod tests {
585  use super::*;
586
587  #[test]
588  fn keyval_default_fields() {
589    let kv = KeyVal::default();
590    assert_eq!(kv.prefix, "KV");
591    assert!(kv.keyset.is_empty());
592    assert!(kv.key.is_empty());
593  }
594
595  #[test]
596  fn keyval_new_custom_prefix() {
597    let kv = KeyVal::new(
598      Some("custom".to_string()),
599      "ks".to_string(),
600      "k".to_string(),
601    );
602    assert_eq!(kv.prefix, "custom");
603    assert_eq!(kv.keyset, "ks");
604    assert_eq!(kv.key, "k");
605  }
606
607  #[test]
608  fn keyval_new_default_prefix_on_none() {
609    // None prefix → default "KV".
610    let kv = KeyVal::new(None, "ks".to_string(), "k".to_string());
611    assert_eq!(kv.prefix, "KV");
612  }
613
614  #[test]
615  fn keyval_get_header_format() {
616    let kv = KeyVal::new(
617      Some("P".to_string()),
618      "set".to_string(),
619      "width".to_string(),
620    );
621    assert_eq!(kv.get_header(), "P@set@width");
622  }
623
624  #[test]
625  fn keyval_get_header_default_prefix() {
626    let kv = KeyVal::new(None, "tabular".to_string(), "vattach".to_string());
627    assert_eq!(kv.get_header(), "KV@tabular@vattach");
628  }
629
630  #[test]
631  fn keyval_equality_by_all_fields() {
632    let a = KeyVal::new(Some("P".to_string()), "ks".to_string(), "k".to_string());
633    let b = KeyVal::new(Some("P".to_string()), "ks".to_string(), "k".to_string());
634    let c = KeyVal::new(Some("P".to_string()), "ks".to_string(), "other".to_string());
635    assert_eq!(a, b);
636    assert_ne!(a, c);
637  }
638
639  #[test]
640  fn keyval_qname_normalizes_empty_prefix() {
641    // Empty prefix is substituted with "KV".
642    assert_eq!(keyval_qname("", "set", "k"), "KV@set@k");
643    assert_eq!(keyval_qname("P", "set", "k"), "P@set@k");
644    // The empty family takes xkeyval's `\XKV@makehd` shape (no doubled `@`).
645    assert_eq!(keyval_qname("psset", "", "precode"), "psset@precode");
646    assert_eq!(keyval_qname("", "", "k"), "KV@k");
647  }
648}
649
650// ── keyval TeX-source splitting (winnow) ─────────────────────────────────
651// The same `winnow` grammar family as the XML-replacement template parser
652// (binding/def/replacement.rs); used by the runtime-bindings GetKeyVal(s)
653// accessors over a dict's TeX-source form.
654
655/// Split a keyval dict's TeX-source form (`"k=v, k2={v, 2}"`) into
656/// `(key, value)` pairs: comma/equals splitting at brace depth 0 only, one
657/// level of outer braces stripped from values, whitespace trimmed, empty
658/// keys dropped (keyval semantics).
659pub fn split_keyval_source(kv: &str) -> Vec<(String, String)> {
660  split_keyval_items(kv)
661    .into_iter()
662    .map(|(k, v)| (k, v.unwrap_or_default()))
663    .collect()
664}
665
666/// [`split_keyval_source`], a value-less key (`k`, which takes keyval's default) told from an empty value (`k=`).
667pub fn split_keyval_items(kv: &str) -> Vec<(String, Option<String>)> {
668  use winnow::{
669    combinator::{opt, separated},
670    prelude::*,
671  };
672
673  /// One item: everything up to a depth-0 comma (consumed by the separator).
674  fn item(input: &mut &str) -> ModalResult<(String, Option<String>)> {
675    let mut depth = 0usize;
676    let mut split = None; // byte offset of the depth-0 `=`, if any
677    let mut end = input.len();
678    for (i, c) in input.char_indices() {
679      match c {
680        '{' => depth += 1,
681        '}' => depth = depth.saturating_sub(1),
682        '=' if depth == 0 && split.is_none() => split = Some(i),
683        ',' if depth == 0 => {
684          end = i;
685          break;
686        },
687        _ => {},
688      }
689    }
690    let (raw, rest) = input.split_at(end);
691    *input = rest;
692    let Some(eq) = split.filter(|s| *s < end) else {
693      return Ok((raw.trim().to_string(), None));
694    };
695    let v = raw[eq + 1..].trim();
696    let v = v
697      .strip_prefix('{')
698      .and_then(|s| s.strip_suffix('}'))
699      .unwrap_or(v);
700    Ok((raw[..eq].trim().to_string(), Some(v.to_string())))
701  }
702
703  let mut parser = (separated(0.., item, ","), opt(","));
704  let items: Vec<(String, Option<String>)> = match parser.parse(kv) {
705    Ok((items, _)) => items,
706    Err(_) => Vec::new(), // total parser: `item` consumes anything, so unreachable
707  };
708  items.into_iter().filter(|(k, _)| !k.is_empty()).collect()
709}
710
711#[cfg(test)]
712mod keyval_source_tests {
713  use super::split_keyval_source;
714
715  #[test]
716  fn splits_at_depth_zero_only() {
717    assert_eq!(split_keyval_source("lang=rust, size={1, 2}"), vec![
718      ("lang".to_string(), "rust".to_string()),
719      ("size".to_string(), "1, 2".to_string()),
720    ]);
721  }
722
723  #[test]
724  fn flag_keys_and_empties() {
725    assert_eq!(split_keyval_source("draft,, a=1 ,"), vec![
726      ("draft".to_string(), String::new()),
727      ("a".to_string(), "1".to_string()),
728    ]);
729  }
730
731  #[test]
732  fn braced_equals_is_not_a_split() {
733    assert_eq!(split_keyval_source("k={a=b}"), vec![(
734      "k".to_string(),
735      "a=b".to_string()
736    )]);
737  }
738
739  #[test]
740  fn empty_input() {
741    assert!(split_keyval_source("").is_empty());
742  }
743}