1use std::borrow::Cow;
34
35use libxml::tree::Node;
36use rustc_hash::FxHashMap as HashMap;
37use winnow::{
38 combinator::{alt, opt, peek, repeat},
39 error::{ContextError, ErrMode},
40 prelude::*,
41 token::{literal, one_of, take_while},
42};
43
44use crate::{
45 common::{
46 arena::SymHashMap,
47 error::{Error, Result},
48 font::Font,
49 store::Stored,
50 },
51 definition::FontDirective,
52 digested::Digested,
53 document::Document,
54};
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum FloatKind {
64 Single,
65 Double,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum Value {
73 Arg(usize),
75 Prop(String),
77 Func { name: String, args: Vec<FuncArg> },
80 Literal(String),
82}
83
84#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum FuncArg {
87 Value(Value),
88 Str(AttrValue),
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct AttrValue {
94 pub parts: Vec<AttrPart>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum AttrPart {
100 Literal(String),
101 Value(Value),
102 Conditional {
105 test: Value,
106 then_val: Value,
107 else_val: Value,
108 },
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum AttrPair {
115 KeyValue {
116 key: String,
117 value: AttrValue,
118 },
119 Conditional {
120 test: Value,
121 then_attrs: Vec<AttrPair>,
122 else_attrs: Vec<AttrPair>,
123 },
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
128pub enum ReplacementOp {
129 OpenElement {
132 qname: String,
133 attrs: Vec<AttrPair>,
134 float: Option<FloatKind>,
135 self_closing: bool,
136 },
137 CloseElement { qname: String },
139 ProcessingInstruction { qname: String, attrs: Vec<AttrPair> },
141 AbsorbValue { value: Value },
143 SetAttribute {
146 key: String,
147 value: AttrValue,
148 float: bool,
149 },
150 Text { text: String },
152 Conditional {
154 test: Value,
155 then_ops: Vec<ReplacementOp>,
156 else_ops: Vec<ReplacementOp>,
157 },
158}
159
160pub fn parse_replacement(template: &str) -> Result<Vec<ReplacementOp>> {
165 ops_with_float
166 .parse(template)
167 .map_err(|e| Error::from(format!("replacement template parse error: {e}")))
168}
169
170fn ops_with_float(input: &mut &str) -> ModalResult<Vec<ReplacementOp>> {
175 let float = opt(float_prefix).parse_next(input)?;
176 let mut ops: Vec<ReplacementOp> = repeat(0.., op).parse_next(input)?;
177 if let Some(fk) = float {
178 attach_float(&mut ops, fk);
179 }
180 Ok(ops)
181}
182
183fn attach_float(ops: &mut [ReplacementOp], fk: FloatKind) {
186 for o in ops.iter_mut() {
187 match o {
188 ReplacementOp::OpenElement { float, .. } => {
189 *float = Some(fk);
190 return;
191 },
192 ReplacementOp::SetAttribute { float, .. } => {
193 *float = true;
194 return;
195 },
196 _ => {},
197 }
198 }
199}
200
201fn float_prefix(input: &mut &str) -> ModalResult<FloatKind> {
203 let carets = take_while(1.., '^').parse_next(input)?;
204 ws(input)?;
205 Ok(if carets.chars().count() >= 2 {
206 FloatKind::Double
207 } else {
208 FloatKind::Single
209 })
210}
211
212fn op(input: &mut &str) -> ModalResult<ReplacementOp> {
216 alt((
217 conditional_op,
218 pi_op,
219 open_tag_op,
220 close_tag_op,
221 absorb_value_op,
222 attribute_op,
223 text_op,
224 ))
225 .parse_next(input)
226}
227
228fn conditional_op(input: &mut &str) -> ModalResult<ReplacementOp> {
229 peek((literal("?"), one_of(['#', '&']))).parse_next(input)?;
230 let (test, if_s, else_s) = parse_conditional_raw(input)?;
231 let then_ops = reparse_ops(&if_s)?;
232 let else_ops = reparse_ops(&else_s)?;
233 Ok(ReplacementOp::Conditional { test, then_ops, else_ops })
234}
235
236fn pi_op(input: &mut &str) -> ModalResult<ReplacementOp> {
237 ws(input)?;
238 literal("<?").parse_next(input)?;
239 let name = cut_err_(qname, input)?;
240 let attrs = avpairs(input)?;
241 ws(input)?;
242 cut_err_lit("?>", input)?;
243 Ok(ReplacementOp::ProcessingInstruction { qname: name, attrs })
244}
245
246fn open_tag_op(input: &mut &str) -> ModalResult<ReplacementOp> {
247 ws(input)?;
248 literal("<").parse_next(input)?;
249 let name = qname.parse_next(input)?;
251 let attrs = avpairs(input)?;
252 let self_closing = opt(literal("/")).parse_next(input)?.is_some();
253 cut_err_lit(">", input)?;
254 Ok(ReplacementOp::OpenElement {
255 qname: name,
256 attrs,
257 float: None,
258 self_closing,
259 })
260}
261
262fn close_tag_op(input: &mut &str) -> ModalResult<ReplacementOp> {
263 literal("</").parse_next(input)?;
265 let name = cut_err_(qname, input)?;
266 ws(input)?;
267 cut_err_lit(">", input)?;
268 Ok(ReplacementOp::CloseElement { qname: name })
269}
270
271fn absorb_value_op(input: &mut &str) -> ModalResult<ReplacementOp> {
272 peek(one_of(['#', '&'])).parse_next(input)?;
274 let value = content_value(input)?;
275 Ok(ReplacementOp::AbsorbValue { value })
276}
277
278fn attribute_op(input: &mut &str) -> ModalResult<ReplacementOp> {
279 let key = qname.parse_next(input)?;
281 if opt((ws_p, literal("="), ws_p)).parse_next(input)?.is_none() {
282 return Err(ErrMode::Backtrack(ContextError::new()));
284 }
285 let value = attr_string(input)?;
286 Ok(ReplacementOp::SetAttribute { key, value, float: false })
287}
288
289fn text_op(input: &mut &str) -> ModalResult<ReplacementOp> {
290 let raw = take_literal_run(input, "", true)?;
292 Ok(ReplacementOp::Text { text: unquote(&raw) })
293}
294
295fn parse_conditional_raw(input: &mut &str) -> ModalResult<(Value, String, String)> {
302 literal("?").parse_next(input)?;
303 let test = match content_value(input) {
304 Ok(v) => v,
305 Err(ErrMode::Backtrack(e)) => return Err(ErrMode::Cut(e)),
306 Err(e) => return Err(e),
307 };
308 match opt(bracketed).parse_next(input)? {
309 None => Ok((test, String::new(), String::new())),
310 Some(a) => {
311 let b = opt(bracketed).parse_next(input)?.unwrap_or_default();
312 Ok((test, a, b))
313 },
314 }
315}
316
317fn bracketed(input: &mut &str) -> ModalResult<String> {
322 let s: &str = input;
323 let mut level: i32 = 0;
324 let mut has_open = false;
325 let mut extracted = String::new();
326 let mut consumed = 0usize;
327 let mut closed = false;
328 for (i, c) in s.char_indices() {
329 match c {
330 ')' => {
331 level -= 1;
332 if level < 1 {
333 consumed = i + c.len_utf8();
334 closed = true;
335 break;
336 }
337 extracted.push(c);
338 },
339 '(' => {
340 has_open = true;
341 level += 1;
342 if level > 1 {
343 extracted.push(c);
344 }
345 },
346 other => {
347 if level > 0 {
348 extracted.push(other);
349 } else if !other.is_whitespace() {
350 break; }
352 },
353 }
354 }
355 if has_open && closed {
356 *input = &s[consumed..];
357 Ok(extracted)
358 } else {
359 Err(ErrMode::Backtrack(ContextError::new()))
360 }
361}
362
363fn content_value(input: &mut &str) -> ModalResult<Value> {
366 alt((func_value, arg_value, prop_value)).parse_next(input)
367}
368
369fn full_value(input: &mut &str, exclude: &str) -> ModalResult<Value> {
372 if let Some(v) = opt(content_value).parse_next(input)? {
373 return Ok(v);
374 }
375 let raw = take_literal_run(input, exclude, false)?;
376 Ok(Value::Literal(unquote(&raw)))
377}
378
379fn arg_value(input: &mut &str) -> ModalResult<Value> {
380 literal("#").parse_next(input)?;
381 let digits = take_while(1.., |c: char| c.is_ascii_digit()).parse_next(input)?;
382 let n: usize = digits
383 .parse()
384 .map_err(|_| ErrMode::Backtrack(ContextError::new()))?;
385 if !(1..=9).contains(&n) {
386 return Err(ErrMode::Cut(ContextError::new()));
387 }
388 Ok(Value::Arg(n))
389}
390
391fn prop_value(input: &mut &str) -> ModalResult<Value> {
392 literal("#").parse_next(input)?;
393 let name = take_while(1.., |c: char| c.is_alphanumeric() || c == '_' || c == '-')
394 .map(str::to_string)
395 .parse_next(input)?;
396 Ok(Value::Prop(name))
397}
398
399fn func_value(input: &mut &str) -> ModalResult<Value> {
400 literal("&").parse_next(input)?;
402 let name = take_while(0.., |c: char| c.is_alphanumeric() || c == '_' || c == ':')
403 .map(str::to_string)
404 .parse_next(input)?;
405 literal("(").parse_next(input)?; let mut args = Vec::new();
407 loop {
408 if probe(|i| (ws_p, literal(")")).void().parse_next(i), input) {
409 break;
410 }
411 ws(input)?;
412 let arg = if probe(|i| one_of(['\'', '"']).parse_next(i), input) {
413 FuncArg::Str(attr_string(input)?)
414 } else {
415 FuncArg::Value(full_value(input, ",)")?)
416 };
417 args.push(arg);
418 if opt((ws_p, literal(","), ws_p)).parse_next(input)?.is_none() {
419 break;
420 }
421 }
422 ws(input)?;
423 cut_err_lit(")", input)?;
424 Ok(Value::Func { name, args })
425}
426
427fn attr_string(input: &mut &str) -> ModalResult<AttrValue> {
431 ws(input)?;
432 let quote = match opt(one_of(['\'', '"'])).parse_next(input)? {
433 Some(q) => q,
434 None => {
435 if let Some(c) = input.chars().next() {
436 *input = &input[c.len_utf8()..];
437 }
438 return Ok(AttrValue { parts: Vec::new() });
439 },
440 };
441 let mut parts = Vec::new();
442 loop {
443 if input.is_empty() {
444 break;
445 }
446 if input.starts_with(quote) {
447 *input = &input[quote.len_utf8()..];
448 break;
449 }
450 if probe(
451 |i| (literal("?"), one_of(['#', '&'])).void().parse_next(i),
452 input,
453 ) {
454 let (test, if_s, else_s) = parse_conditional_raw(input)?;
455 let then_val = parse_single_value(&if_s)?;
456 let else_val = parse_single_value(&else_s)?;
457 parts.push(AttrPart::Conditional { test, then_val, else_val });
458 continue;
459 }
460 if probe(|i| one_of(['#', '&']).parse_next(i), input) {
461 parts.push(AttrPart::Value(content_value(input)?));
462 continue;
463 }
464 let raw = take_literal_run(input, "'\"", false)?;
465 parts.push(AttrPart::Literal(unquote(&raw)));
466 }
467 Ok(AttrValue { parts })
468}
469
470fn avpairs(input: &mut &str) -> ModalResult<Vec<AttrPair>> {
473 let mut pairs = Vec::new();
474 loop {
475 ws(input)?;
476 if let Some(c) = opt(avpair_conditional).parse_next(input)? {
477 pairs.push(c);
478 continue;
479 }
480 if let Some(kv) = opt(avpair_keyval).parse_next(input)? {
481 pairs.push(kv);
482 continue;
483 }
484 break;
485 }
486 Ok(pairs)
487}
488
489fn avpair_conditional(input: &mut &str) -> ModalResult<AttrPair> {
490 peek((literal("?"), one_of(['#', '&']))).parse_next(input)?;
491 let (test, if_s, else_s) = parse_conditional_raw(input)?;
492 Ok(AttrPair::Conditional {
493 test,
494 then_attrs: reparse_avpairs(&if_s),
495 else_attrs: reparse_avpairs(&else_s),
496 })
497}
498
499fn avpair_keyval(input: &mut &str) -> ModalResult<AttrPair> {
500 let key = qname.parse_next(input)?;
501 if opt((ws_p, literal("="), ws_p)).parse_next(input)?.is_none() {
502 return Err(ErrMode::Backtrack(ContextError::new()));
503 }
504 let value = attr_string(input)?;
505 Ok(AttrPair::KeyValue { key, value })
506}
507
508fn parse_single_value(s: &str) -> ModalResult<Value> {
512 if s.is_empty() {
513 return Ok(Value::Literal(String::new()));
514 }
515 let mut inp: &str = s;
516 full_value(&mut inp, "")
517}
518
519fn reparse_ops(s: &str) -> ModalResult<Vec<ReplacementOp>> {
522 ops_with_float
523 .parse(s)
524 .map_err(|_| ErrMode::Cut(ContextError::new()))
525}
526
527fn reparse_avpairs(s: &str) -> Vec<AttrPair> {
530 let mut inp: &str = s;
531 avpairs(&mut inp).unwrap_or_default()
532}
533
534fn qname(input: &mut &str) -> ModalResult<String> {
537 (one_of(is_qname_start), take_while(0.., is_qname_continue))
538 .take()
539 .map(str::to_string)
540 .parse_next(input)
541}
542
543fn is_qname_start(c: char) -> bool { c.is_alphabetic() || c == '_' || c == ':' }
544fn is_qname_continue(c: char) -> bool { c.is_alphanumeric() || matches!(c, '_' | ':' | '.' | '-') }
545
546fn ws(input: &mut &str) -> ModalResult<()> {
548 let _ = take_while(0.., |c: char| c.is_whitespace()).parse_next(input)?;
549 Ok(())
550}
551
552fn ws_p(input: &mut &str) -> ModalResult<()> { ws(input) }
554
555fn probe<O>(mut p: impl FnMut(&mut &str) -> ModalResult<O>, input: &str) -> bool {
559 let mut s: &str = input;
560 p(&mut s).is_ok()
561}
562
563fn cut_err_lit(lit: &'static str, input: &mut &str) -> ModalResult<()> {
565 match literal(lit).parse_next(input) {
566 Ok(_) => Ok(()),
567 Err(ErrMode::Backtrack(e)) => Err(ErrMode::Cut(e)),
568 Err(e) => Err(e),
569 }
570}
571
572fn cut_err_<O>(mut p: impl FnMut(&mut &str) -> ModalResult<O>, input: &mut &str) -> ModalResult<O> {
574 match p(input) {
575 Ok(o) => Ok(o),
576 Err(ErrMode::Backtrack(e)) => Err(ErrMode::Cut(e)),
577 Err(e) => Err(e),
578 }
579}
580
581fn take_literal_run(input: &mut &str, exclude: &str, exclude_lt: bool) -> ModalResult<String> {
586 let s: &str = input;
587 let mut pos = 0usize;
588 while pos < s.len() {
589 let rest = &s[pos..];
590 let c = rest.chars().next().unwrap();
591 if c == '&' {
592 if rest.starts_with("&") {
593 pos += 5;
594 continue;
595 }
596 break; }
598 if c == '\\' {
599 let after = &rest[1..];
600 let letters: usize = after
601 .chars()
602 .take_while(|ch| ch.is_ascii_alphabetic() || *ch == '@')
603 .map(char::len_utf8)
604 .sum();
605 if letters > 0 {
606 pos += 1 + letters; continue;
608 }
609 if let Some(nc) = after.chars().next() {
610 pos += 1 + nc.len_utf8(); continue;
612 }
613 break; }
615 if c == '#' || c == '?' {
616 break;
617 }
618 if exclude_lt && c == '<' {
619 break;
620 }
621 if exclude.contains(c) {
622 break;
623 }
624 pos += c.len_utf8();
625 }
626 if pos == 0 {
627 return Err(ErrMode::Backtrack(ContextError::new()));
628 }
629 let raw = s[..pos].to_string();
630 *input = &s[pos..];
631 Ok(raw)
632}
633
634pub fn unquote(text: &str) -> String {
639 const ESCAPED: &[char] = &['#', '?', '(', '&', ',', '<', '>', '\\', '%'];
640 let mut out = String::with_capacity(text.len());
641 let mut i = 0usize;
642 while i < text.len() {
643 let rest = &text[i..];
644 let c = rest.chars().next().unwrap();
645 if c == '\\'
646 && let Some(nc) = rest[1..].chars().next()
647 && ESCAPED.contains(&nc)
648 {
649 i += 1 + nc.len_utf8(); continue;
651 }
652 out.push(c);
653 i += c.len_utf8();
654 }
655 out.replace("##", "#").replace("&", "&")
656}
657
658pub fn slashify(text: &str) -> String { text.replace('\\', "\\\\") }
661
662pub fn apply_ops(
667 ops: &[ReplacementOp],
668 document: &mut Document,
669 args: &[Option<Digested>],
670 props: &SymHashMap<Stored>,
671) -> Result<()> {
672 let mut savenode: Option<Node> = None;
673 exec_ops(ops, document, args, props, &mut savenode)?;
674 if let Some(sn) = savenode {
675 document.set_node(&sn);
676 }
677 Ok(())
678}
679
680fn exec_ops(
681 ops: &[ReplacementOp],
682 document: &mut Document,
683 args: &[Option<Digested>],
684 props: &SymHashMap<Stored>,
685 savenode: &mut Option<Node>,
686) -> Result<()> {
687 let mut opened_here: Vec<&str> = Vec::new();
694 for op in ops {
695 match op {
696 ReplacementOp::OpenElement {
697 qname,
698 attrs,
699 float,
700 self_closing,
701 } => {
702 if let Some(fk) = float {
703 *savenode = document.float_to_element(qname, matches!(fk, FloatKind::Double))?;
704 }
705 if !*self_closing {
706 opened_here.push(qname.as_str());
707 }
708 let av = eval_avpairs(attrs, args, props)?;
709 if av.is_empty() {
710 document.open_element(qname, None, None)?;
711 } else {
712 let mut map: HashMap<String, String> = HashMap::default();
713 for (k, v) in av {
714 map.insert(k, v);
715 }
716 let this_font_opt: Option<Cow<Font>> = match props.get("font") {
717 Some(Stored::Font(f)) => Some(Cow::Borrowed(&**f)),
718 Some(Stored::FontDirective(FontDirective::Asset(fa))) => Some(Cow::Borrowed(&**fa)),
719 Some(Stored::FontDirective(FontDirective::Closure(code))) => {
720 Some(Cow::Owned(code(None)?))
721 },
722 _ => None,
723 };
724 if let Some(this_font) = this_font_opt {
725 document.open_element(qname, Some(map), Some(&this_font))?;
726 } else {
727 document.open_element(qname, Some(map), None)?;
728 }
729 }
730 if *self_closing {
731 document.close_element(qname)?;
732 }
733 },
734 ReplacementOp::CloseElement { qname } => {
735 if opened_here.contains(&qname.as_str()) {
736 document.close_element_if_open(qname)?;
737 } else {
738 document.close_element(qname)?;
739 }
740 },
741 ReplacementOp::ProcessingInstruction { qname, attrs } => {
742 let av = eval_avpairs(attrs, args, props)?;
743 if av.is_empty() {
744 document.insert_pi(qname, None)?;
745 } else {
746 let mut map: HashMap<String, String> = HashMap::default();
747 for (k, v) in av {
748 map.insert(k, v);
749 }
750 document.insert_pi(qname, Some(map))?;
751 }
752 },
753 ReplacementOp::AbsorbValue { value } => {
754 absorb_value(value, document, args, props)?;
755 },
756 ReplacementOp::SetAttribute { key, value, float } => {
757 let val_str = eval_attr_value(value, args, props)?;
758 if *float {
759 *savenode = document.float_to_attribute(key);
760 let mut node = document.get_node().clone();
761 document.set_attribute(&mut node, key, &val_str)?;
762 if let &mut Some(ref sn) = savenode {
763 document.set_node(sn);
764 }
765 } else {
766 let mut node = document.get_node().clone();
767 document.set_attribute(&mut node, key, &val_str)?;
768 }
769 },
770 ReplacementOp::Text { text } => {
771 document.absorb_string(text, props)?;
772 },
773 ReplacementOp::Conditional { test, then_ops, else_ops } => {
774 if eval_bool(test, args, props)? {
775 exec_ops(then_ops, document, args, props, savenode)?;
776 } else {
777 exec_ops(else_ops, document, args, props, savenode)?;
778 }
779 },
780 }
781 }
782 Ok(())
783}
784
785fn eval_avpairs(
788 attrs: &[AttrPair],
789 args: &[Option<Digested>],
790 props: &SymHashMap<Stored>,
791) -> Result<Vec<(String, String)>> {
792 let mut out = Vec::new();
793 for a in attrs {
794 match a {
795 AttrPair::KeyValue { key, value } => {
796 if key == "font" {
797 continue;
798 }
799 out.push((key.clone(), eval_attr_value(value, args, props)?));
800 },
801 AttrPair::Conditional { test, then_attrs, else_attrs } => {
802 let branch = if eval_bool(test, args, props)? {
803 then_attrs
804 } else {
805 else_attrs
806 };
807 out.extend(eval_avpairs(branch, args, props)?);
808 },
809 }
810 }
811 Ok(out)
812}
813
814fn eval_attr_value(
815 v: &AttrValue,
816 args: &[Option<Digested>],
817 props: &SymHashMap<Stored>,
818) -> Result<String> {
819 let mut s = String::new();
820 for part in &v.parts {
821 match part {
822 AttrPart::Literal(lit) => s.push_str(lit),
823 AttrPart::Value(val) => s.push_str(&value_to_attribute(val, args, props)?),
824 AttrPart::Conditional { test, then_val, else_val } => {
825 let chosen = if eval_bool(test, args, props)? {
826 then_val
827 } else {
828 else_val
829 };
830 s.push_str(&value_to_attribute(chosen, args, props)?);
831 },
832 }
833 }
834 Ok(s)
835}
836
837fn value_to_attribute(
841 v: &Value,
842 args: &[Option<Digested>],
843 props: &SymHashMap<Stored>,
844) -> Result<String> {
845 Ok(match v {
846 Value::Arg(n) => match args.get(n - 1) {
847 Some(Some(d)) => d.to_attribute(),
848 _ => String::new(),
849 },
850 Value::Prop(name) => match props.get(name) {
851 Some(stored) => stored.to_attribute(),
852 None => String::new(),
853 },
854 Value::Func { name, args: fargs } => call_func(name, fargs, args, props)?,
855 Value::Literal(lit) => lit.clone(),
856 })
857}
858
859fn absorb_value(
862 v: &Value,
863 document: &mut Document,
864 args: &[Option<Digested>],
865 props: &SymHashMap<Stored>,
866) -> Result<()> {
867 match v {
868 Value::Arg(n) => {
869 if let Some(Some(d)) = args.get(n - 1) {
870 document.absorb(d, None)?;
871 }
872 },
873 Value::Prop(name) => {
874 if let Some(stored) = props.get(name) {
875 let dig: Option<Digested> = stored.into();
876 if let Some(ref d) = dig {
877 document.absorb(d, None)?;
878 }
879 }
880 },
881 Value::Func { name, args: fargs } => {
882 let s = call_func(name, fargs, args, props)?;
883 if !s.is_empty() {
884 document.absorb_string(&s, props)?;
885 }
886 },
887 Value::Literal(_) => {}, }
889 Ok(())
890}
891
892fn eval_bool(v: &Value, args: &[Option<Digested>], props: &SymHashMap<Stored>) -> Result<bool> {
895 Ok(match v {
896 Value::Arg(n) => match args.get(n - 1) {
897 Some(Some(d)) => is_truthy(&d.to_string()),
898 _ => false,
899 },
900 Value::Prop(name) => match props.get(name) {
901 Some(stored) => is_truthy(&stored.to_string()),
902 None => false,
903 },
904 Value::Func { name, args: fargs } => is_truthy(&call_func(name, fargs, args, props)?),
905 Value::Literal(s) => is_truthy(s),
906 })
907}
908
909fn is_truthy(s: &str) -> bool { !s.is_empty() && s != "false" }
910
911fn call_func(
917 name: &str,
918 fargs: &[FuncArg],
919 args: &[Option<Digested>],
920 props: &SymHashMap<Stored>,
921) -> Result<String> {
922 let mut argv: Vec<String> = Vec::with_capacity(fargs.len());
923 for fa in fargs {
924 argv.push(match fa {
925 FuncArg::Value(v) => value_to_attribute(v, args, props)?,
926 FuncArg::Str(s) => eval_attr_value(s, args, props)?,
927 });
928 }
929 match name {
930 "ToString" => Ok(argv.join("")),
931 "GetKeyVal" => {
936 let kv = argv.first().map(String::as_str).unwrap_or("");
937 let key = argv.get(1).map(String::as_str).unwrap_or("");
938 Ok(
939 crate::keyval::split_keyval_source(kv)
940 .into_iter()
941 .find(|(k, _)| k == key)
942 .map(|(_, v)| v)
943 .unwrap_or_default(),
944 )
945 },
946 _ => Err(Error::from(format!(
947 "runtime template: function &{name}(…) is not in the whitelist"
948 ))),
949 }
950}
951
952#[cfg(test)]
955mod tests {
956 use super::*;
957
958 fn lit(s: &str) -> AttrValue {
959 AttrValue {
960 parts: vec![AttrPart::Literal(s.to_string())],
961 }
962 }
963 fn argval(n: usize) -> AttrValue {
964 AttrValue {
965 parts: vec![AttrPart::Value(Value::Arg(n))],
966 }
967 }
968
969 #[test]
970 fn plain_element_with_arg() {
971 let ops = parse_replacement("<ltx:emph>#1</ltx:emph>").unwrap();
972 assert_eq!(ops, vec![
973 ReplacementOp::OpenElement {
974 qname: "ltx:emph".into(),
975 attrs: vec![],
976 float: None,
977 self_closing: false,
978 },
979 ReplacementOp::AbsorbValue { value: Value::Arg(1) },
980 ReplacementOp::CloseElement { qname: "ltx:emph".into() },
981 ]);
982 }
983
984 #[test]
985 fn element_with_literal_attribute_and_arg() {
986 let ops = parse_replacement("<ltx:text class='ok'>#1</ltx:text>").unwrap();
987 assert_eq!(ops, vec![
988 ReplacementOp::OpenElement {
989 qname: "ltx:text".into(),
990 attrs: vec![AttrPair::KeyValue {
991 key: "class".into(),
992 value: lit("ok"),
993 }],
994 float: None,
995 self_closing: false,
996 },
997 ReplacementOp::AbsorbValue { value: Value::Arg(1) },
998 ReplacementOp::CloseElement { qname: "ltx:text".into() },
999 ]);
1000 }
1001
1002 #[test]
1003 fn attribute_value_interpolates_arg() {
1004 let ops = parse_replacement("<ltx:ref class='#2'>#1</ltx:ref>").unwrap();
1005 let ReplacementOp::OpenElement { attrs, .. } = &ops[0] else {
1006 panic!()
1007 };
1008 assert_eq!(attrs, &vec![AttrPair::KeyValue {
1009 key: "class".into(),
1010 value: argval(2),
1011 }]);
1012 }
1013
1014 #[test]
1015 fn self_closing_element() {
1016 let ops = parse_replacement("<ltx:break/>").unwrap();
1017 assert_eq!(ops, vec![ReplacementOp::OpenElement {
1018 qname: "ltx:break".into(),
1019 attrs: vec![],
1020 float: None,
1021 self_closing: true,
1022 }]);
1023 }
1024
1025 #[test]
1026 fn whitespace_before_tag_is_dropped_but_text_kept() {
1027 let ops = parse_replacement("<a>\n <b></b>\n </a>").unwrap();
1030 assert_eq!(ops, vec![
1031 ReplacementOp::OpenElement {
1032 qname: "a".into(),
1033 attrs: vec![],
1034 float: None,
1035 self_closing: false,
1036 },
1037 ReplacementOp::OpenElement {
1038 qname: "b".into(),
1039 attrs: vec![],
1040 float: None,
1041 self_closing: false,
1042 },
1043 ReplacementOp::CloseElement { qname: "b".into() },
1044 ReplacementOp::Text { text: "\n ".into() },
1045 ReplacementOp::CloseElement { qname: "a".into() },
1046 ]);
1047 }
1048
1049 #[test]
1050 fn footnote_corpus_specimen() {
1051 let ops = parse_replacement(
1053 "^<ltx:note role='footnote' ?#mark(mark='#mark')()>?#prenote(#prenote )()#2</ltx:note>",
1054 )
1055 .unwrap();
1056 assert_eq!(ops, vec![
1057 ReplacementOp::OpenElement {
1058 qname: "ltx:note".into(),
1059 attrs: vec![
1060 AttrPair::KeyValue {
1061 key: "role".into(),
1062 value: lit("footnote"),
1063 },
1064 AttrPair::Conditional {
1065 test: Value::Prop("mark".into()),
1066 then_attrs: vec![AttrPair::KeyValue {
1067 key: "mark".into(),
1068 value: AttrValue {
1069 parts: vec![AttrPart::Value(Value::Prop("mark".into()))],
1070 },
1071 }],
1072 else_attrs: vec![],
1073 },
1074 ],
1075 float: Some(FloatKind::Single),
1076 self_closing: false,
1077 },
1078 ReplacementOp::Conditional {
1079 test: Value::Prop("prenote".into()),
1080 then_ops: vec![
1081 ReplacementOp::AbsorbValue {
1082 value: Value::Prop("prenote".into()),
1083 },
1084 ReplacementOp::Text { text: " ".into() },
1085 ],
1086 else_ops: vec![],
1087 },
1088 ReplacementOp::AbsorbValue { value: Value::Arg(2) },
1089 ReplacementOp::CloseElement { qname: "ltx:note".into() },
1090 ]);
1091 }
1092
1093 #[test]
1094 fn pi_corpus_specimen() {
1095 let ops = parse_replacement("<?latexml class='#2' ?#1(options='#1')?>").unwrap();
1097 assert_eq!(ops, vec![ReplacementOp::ProcessingInstruction {
1098 qname: "latexml".into(),
1099 attrs: vec![
1100 AttrPair::KeyValue {
1101 key: "class".into(),
1102 value: argval(2),
1103 },
1104 AttrPair::Conditional {
1105 test: Value::Arg(1),
1106 then_attrs: vec![AttrPair::KeyValue {
1107 key: "options".into(),
1108 value: argval(1),
1109 }],
1110 else_attrs: vec![],
1111 },
1112 ],
1113 }]);
1114 }
1115
1116 #[test]
1117 fn float_double_caret() {
1118 let ops = parse_replacement("^^<ltx:x/>").unwrap();
1119 let ReplacementOp::OpenElement { float, .. } = &ops[0] else {
1120 panic!()
1121 };
1122 assert_eq!(float, &Some(FloatKind::Double));
1123 }
1124
1125 #[test]
1126 fn top_level_conditional_with_else() {
1127 let ops = parse_replacement("?#1(<a/>)(<b/>)").unwrap();
1128 assert_eq!(ops, vec![ReplacementOp::Conditional {
1129 test: Value::Arg(1),
1130 then_ops: vec![ReplacementOp::OpenElement {
1131 qname: "a".into(),
1132 attrs: vec![],
1133 float: None,
1134 self_closing: true,
1135 }],
1136 else_ops: vec![ReplacementOp::OpenElement {
1137 qname: "b".into(),
1138 attrs: vec![],
1139 float: None,
1140 self_closing: true,
1141 }],
1142 }]);
1143 }
1144
1145 #[test]
1146 fn prop_hole_at_content_and_arg_distinguished() {
1147 let ops = parse_replacement("#mark#2").unwrap();
1148 assert_eq!(ops, vec![
1149 ReplacementOp::AbsorbValue {
1150 value: Value::Prop("mark".into()),
1151 },
1152 ReplacementOp::AbsorbValue { value: Value::Arg(2) },
1153 ]);
1154 }
1155
1156 #[test]
1157 fn func_value_parses() {
1158 let ops = parse_replacement("<a x='&ToString(#1)'/>").unwrap();
1159 let ReplacementOp::OpenElement { attrs, .. } = &ops[0] else {
1160 panic!()
1161 };
1162 assert_eq!(attrs, &vec![AttrPair::KeyValue {
1163 key: "x".into(),
1164 value: AttrValue {
1165 parts: vec![AttrPart::Value(Value::Func {
1166 name: "ToString".into(),
1167 args: vec![FuncArg::Value(Value::Arg(1))],
1168 })],
1169 },
1170 }]);
1171 }
1172
1173 #[test]
1174 fn unquote_reproduces_original_quirks() {
1175 assert_eq!(unquote("a&b"), "a&b");
1176 assert_eq!(unquote(r"\#"), ""); assert_eq!(unquote(r"\textbf"), r"\textbf"); assert_eq!(unquote("a##b"), "a#b");
1179 }
1180
1181 #[test]
1182 fn empty_template_is_empty_oplist() {
1183 assert_eq!(parse_replacement("").unwrap(), vec![]);
1184 }
1185
1186 use crate::common::arena;
1195
1196 fn dig(s: &str) -> Digested { s.to_string().into() }
1197
1198 fn props_with(pairs: &[(&str, &str)]) -> SymHashMap<Stored> {
1199 let mut m = SymHashMap::default();
1200 for (k, v) in pairs {
1201 m.insert(k, Stored::String(arena::pin(v)));
1202 }
1203 m
1204 }
1205
1206 fn footnote_attrs() -> Vec<AttrPair> {
1208 let ops = parse_replacement(
1209 "^<ltx:note role='footnote' ?#mark(mark='#mark')()>?#prenote(#prenote )()#2</ltx:note>",
1210 )
1211 .unwrap();
1212 match &ops[0] {
1213 ReplacementOp::OpenElement { attrs, .. } => attrs.clone(),
1214 _ => panic!("expected OpenElement"),
1215 }
1216 }
1217
1218 #[test]
1219 fn footnote_conditional_attr_fires_when_prop_present() {
1220 let attrs = footnote_attrs();
1221 let props = props_with(&[("mark", "MK")]);
1222 let av = eval_avpairs(&attrs, &[], &props).unwrap();
1223 let mk = Stored::String(arena::pin("MK")).to_attribute();
1226 assert_eq!(av, vec![
1227 ("role".to_string(), "footnote".to_string()),
1228 ("mark".to_string(), mk)
1229 ]);
1230 }
1231
1232 #[test]
1233 fn footnote_conditional_attr_absent_when_prop_missing() {
1234 let attrs = footnote_attrs();
1235 let av = eval_avpairs(&attrs, &[], &SymHashMap::default()).unwrap();
1236 assert_eq!(av, vec![("role".to_string(), "footnote".to_string())]);
1237 }
1238
1239 #[test]
1240 fn footnote_prenote_condition_truth_test() {
1241 assert!(
1243 eval_bool(
1244 &Value::Prop("prenote".into()),
1245 &[],
1246 &props_with(&[("prenote", "P")])
1247 )
1248 .unwrap()
1249 );
1250 assert!(!eval_bool(&Value::Prop("prenote".into()), &[], &SymHashMap::default()).unwrap());
1251 assert!(
1252 !eval_bool(
1253 &Value::Prop("x".into()),
1254 &[],
1255 &props_with(&[("x", "false")])
1256 )
1257 .unwrap()
1258 );
1259 assert!(!eval_bool(&Value::Prop("x".into()), &[], &props_with(&[("x", "")])).unwrap());
1260 }
1261
1262 #[test]
1263 fn pi_attr_interpolation_uses_to_attribute_and_conditional() {
1264 let ops = parse_replacement("<?latexml class='#2' ?#1(options='#1')?>").unwrap();
1265 let ReplacementOp::ProcessingInstruction { attrs, .. } = &ops[0] else {
1266 panic!()
1267 };
1268
1269 let a1 = dig("opts");
1270 let a2 = dig("article");
1271 let args = vec![Some(a1.clone()), Some(a2.clone())];
1272 let av = eval_avpairs(attrs, &args, &SymHashMap::default()).unwrap();
1273 assert_eq!(av, vec![
1276 ("class".to_string(), a2.to_attribute()),
1277 ("options".to_string(), a1.to_attribute()),
1278 ]);
1279
1280 let av2 = eval_avpairs(attrs, &[None, Some(a2.clone())], &SymHashMap::default()).unwrap();
1282 assert_eq!(av2, vec![("class".to_string(), a2.to_attribute())]);
1283 }
1284
1285 #[test]
1286 fn font_attribute_key_is_dropped() {
1287 let ops = parse_replacement("<ltx:x font='ignored' class='keep'/>").unwrap();
1290 let ReplacementOp::OpenElement { attrs, .. } = &ops[0] else {
1291 panic!()
1292 };
1293 let av = eval_avpairs(attrs, &[], &SymHashMap::default()).unwrap();
1294 assert_eq!(av, vec![("class".to_string(), "keep".to_string())]);
1295 }
1296
1297 #[test]
1298 fn plain_text_only() {
1299 assert_eq!(parse_replacement("hello world").unwrap(), vec![
1300 ReplacementOp::Text { text: "hello world".into() }
1301 ]);
1302 }
1303}