Skip to main content

einvoice_xpath/
print.rs

1//! Printing syntax trees back to XPath text.
2//!
3//! The printer writes the canonical form: explicit axes except `child::` (omitted), `@` and
4//! `..`; `//` written out as `/descendant-or-self::node()/`; string literals in double
5//! quotes; parentheses only where the grammar needs them, plus around `instance of` (whose
6//! sequence type would otherwise swallow a following `*` or `+`) and around the lone `/`
7//! (which would otherwise take a following `*` or name as its first step) unless they stand
8//! alone or before a closing bracket. Parsing the output gives back the same tree.
9
10use std::fmt::{self, Display, Formatter, Write};
11
12use crate::ast::{
13    ArithmeticOp, Avt, AvtPart, Axis, AxisStep, Binding, CompareKind, ComparisonOp, Expr, ItemType,
14    KindTest, Literal, NameOrWildcard, NameTest, NodeTest, Occurrence, PathExpr, PathStart,
15    PathStep, Pattern, PatternAlternative, PatternAnchor, PatternAxis, PatternLink, PatternStep,
16    Quantifier, SequenceType, SingleType, Step,
17};
18
19/// Binding strength of each expression form, loosest first.
20mod prec {
21    pub(super) const SEQUENCE: u8 = 0;
22    pub(super) const SINGLE: u8 = 1;
23    pub(super) const OR: u8 = 2;
24    pub(super) const AND: u8 = 3;
25    pub(super) const COMPARISON: u8 = 4;
26    pub(super) const RANGE: u8 = 5;
27    pub(super) const ADDITIVE: u8 = 6;
28    pub(super) const MULTIPLICATIVE: u8 = 7;
29    pub(super) const UNION: u8 = 8;
30    pub(super) const INSTANCE_OF: u8 = 10;
31    pub(super) const CASTABLE: u8 = 12;
32    pub(super) const CAST: u8 = 13;
33    pub(super) const UNARY: u8 = 14;
34    pub(super) const PATH: u8 = 15;
35    pub(super) const FILTER: u8 = 16;
36    pub(super) const PRIMARY: u8 = 17;
37}
38
39fn precedence(expr: &Expr) -> u8 {
40    match expr {
41        Expr::Sequence(items) if !items.is_empty() => prec::SEQUENCE,
42        Expr::If { .. } | Expr::For { .. } | Expr::Quantified { .. } => prec::SINGLE,
43        Expr::Or(..) => prec::OR,
44        Expr::And(..) => prec::AND,
45        Expr::Comparison { .. } => prec::COMPARISON,
46        Expr::Range(..) => prec::RANGE,
47        Expr::Arithmetic {
48            op: ArithmeticOp::Add | ArithmeticOp::Subtract,
49            ..
50        } => prec::ADDITIVE,
51        Expr::Arithmetic { .. } => prec::MULTIPLICATIVE,
52        Expr::Union(..) => prec::UNION,
53        // Parenthesized everywhere but where a delimiter follows, see the module
54        // documentation.
55        Expr::InstanceOf { .. } => prec::SEQUENCE,
56        Expr::Castable { .. } => prec::CASTABLE,
57        Expr::Cast { .. } => prec::CAST,
58        Expr::Negate(_) => prec::UNARY,
59        Expr::Path(PathExpr { steps, .. }) if steps.is_empty() => prec::SEQUENCE,
60        Expr::Path(_) => prec::PATH,
61        Expr::Filter { .. } => prec::FILTER,
62        Expr::Literal(_)
63        | Expr::VarRef(_)
64        | Expr::ContextItem
65        | Expr::FunctionCall { .. }
66        | Expr::Sequence(_) => prec::PRIMARY,
67    }
68}
69
70struct Printer<'a, 'b> {
71    f: &'a mut Formatter<'b>,
72}
73
74impl Printer<'_, '_> {
75    /// Writes `expr`, in parentheses if it binds more loosely than `min`.
76    fn expr(&mut self, expr: &Expr, min: u8) -> fmt::Result {
77        if precedence(expr) < min {
78            self.f.write_char('(')?;
79            self.bare(expr)?;
80            self.f.write_char(')')
81        } else {
82            self.bare(expr)
83        }
84    }
85
86    fn binary(
87        &mut self,
88        lhs: &Expr,
89        op: &str,
90        rhs: &Expr,
91        lhs_min: u8,
92        rhs_min: u8,
93    ) -> fmt::Result {
94        self.expr(lhs, lhs_min)?;
95        write!(self.f, " {op} ")?;
96        self.expr(rhs, rhs_min)
97    }
98
99    fn bare(&mut self, expr: &Expr) -> fmt::Result {
100        match expr {
101            Expr::Literal(literal) => self.literal(literal),
102            Expr::VarRef(name) => write!(self.f, "${name}"),
103            Expr::ContextItem => self.f.write_char('.'),
104            Expr::FunctionCall { name, args } => {
105                write!(self.f, "{name}(")?;
106                self.list(args, prec::SINGLE)?;
107                self.f.write_char(')')
108            }
109            Expr::Sequence(items) if items.is_empty() => self.f.write_str("()"),
110            Expr::Sequence(items) => self.list(items, prec::SINGLE),
111            Expr::Filter { base, predicates } => {
112                self.expr(base, prec::PRIMARY)?;
113                self.predicates(predicates)
114            }
115            Expr::Path(path) => self.path(path),
116            Expr::Negate(operand) => {
117                self.f.write_char('-')?;
118                self.expr(operand, prec::UNARY)
119            }
120            Expr::Castable { operand, target } => {
121                self.expr(operand, prec::CAST)?;
122                write!(self.f, " castable as {target}")
123            }
124            Expr::Cast { operand, target } => {
125                self.expr(operand, prec::UNARY)?;
126                write!(self.f, " cast as {target}")
127            }
128            Expr::InstanceOf { operand, target } => {
129                self.expr(operand, prec::CASTABLE)?;
130                write!(self.f, " instance of {target}")
131            }
132            Expr::Union(lhs, rhs) => self.binary(lhs, "|", rhs, prec::UNION, prec::INSTANCE_OF),
133            Expr::Arithmetic { op, lhs, rhs } => {
134                let (text, level) = match op {
135                    ArithmeticOp::Add => ("+", prec::ADDITIVE),
136                    ArithmeticOp::Subtract => ("-", prec::ADDITIVE),
137                    ArithmeticOp::Multiply => ("*", prec::MULTIPLICATIVE),
138                    ArithmeticOp::Divide => ("div", prec::MULTIPLICATIVE),
139                    ArithmeticOp::IntegerDivide => ("idiv", prec::MULTIPLICATIVE),
140                    ArithmeticOp::Modulo => ("mod", prec::MULTIPLICATIVE),
141                };
142                self.binary(lhs, text, rhs, level, level + 1)
143            }
144            Expr::Range(lhs, rhs) => self.binary(lhs, "to", rhs, prec::ADDITIVE, prec::ADDITIVE),
145            Expr::Comparison { op, lhs, rhs } => {
146                self.binary(lhs, comparison_text(*op), rhs, prec::RANGE, prec::RANGE)
147            }
148            Expr::And(lhs, rhs) => self.binary(lhs, "and", rhs, prec::AND, prec::COMPARISON),
149            Expr::Or(lhs, rhs) => self.binary(lhs, "or", rhs, prec::OR, prec::AND),
150            Expr::If {
151                condition,
152                then,
153                otherwise,
154            } => {
155                self.f.write_str("if (")?;
156                self.expr(condition, prec::SEQUENCE)?;
157                self.f.write_str(") then ")?;
158                self.expr(then, prec::SINGLE)?;
159                self.f.write_str(" else ")?;
160                self.expr(otherwise, prec::SINGLE)
161            }
162            Expr::For { bindings, body } => {
163                self.f.write_str("for ")?;
164                self.bindings(bindings)?;
165                self.f.write_str(" return ")?;
166                self.expr(body, prec::SINGLE)
167            }
168            Expr::Quantified {
169                quantifier,
170                bindings,
171                satisfies,
172            } => {
173                self.f.write_str(match quantifier {
174                    Quantifier::Some => "some ",
175                    Quantifier::Every => "every ",
176                })?;
177                self.bindings(bindings)?;
178                self.f.write_str(" satisfies ")?;
179                self.expr(satisfies, prec::SINGLE)
180            }
181        }
182    }
183
184    fn list(&mut self, items: &[Expr], min: u8) -> fmt::Result {
185        for (i, item) in items.iter().enumerate() {
186            if i > 0 {
187                self.f.write_str(", ")?;
188            }
189            self.expr(item, min)?;
190        }
191        Ok(())
192    }
193
194    fn bindings(&mut self, bindings: &[Binding]) -> fmt::Result {
195        for (i, binding) in bindings.iter().enumerate() {
196            if i > 0 {
197                self.f.write_str(", ")?;
198            }
199            write!(self.f, "${} in ", binding.variable)?;
200            self.expr(&binding.sequence, prec::SINGLE)?;
201        }
202        Ok(())
203    }
204
205    fn literal(&mut self, literal: &Literal) -> fmt::Result {
206        match literal {
207            Literal::String(s) => {
208                self.f.write_char('"')?;
209                self.f.write_str(&s.replace('"', "\"\""))?;
210                self.f.write_char('"')
211            }
212            Literal::Integer(n) | Literal::Decimal(n) | Literal::Double(n) => self.f.write_str(n),
213        }
214    }
215
216    fn predicates(&mut self, predicates: &[Expr]) -> fmt::Result {
217        for predicate in predicates {
218            self.f.write_char('[')?;
219            self.expr(predicate, prec::SEQUENCE)?;
220            self.f.write_char(']')?;
221        }
222        Ok(())
223    }
224
225    fn path(&mut self, path: &PathExpr) -> fmt::Result {
226        if path.start == PathStart::Root {
227            self.f.write_char('/')?;
228        }
229        for (i, step) in path.steps.iter().enumerate() {
230            if i > 0 {
231                self.f.write_char('/')?;
232            }
233            match step {
234                Step::Axis(step) => self.axis_step(step)?,
235                Step::Expr(expr) => self.expr(expr, prec::FILTER)?,
236            }
237        }
238        Ok(())
239    }
240
241    fn axis_step(&mut self, step: &AxisStep) -> fmt::Result {
242        let is_attribute_test = matches!(step.test, NodeTest::Kind(KindTest::Attribute(_)));
243        match (step.axis, &step.test) {
244            (Axis::Parent, NodeTest::Kind(KindTest::AnyKind)) => self.f.write_str("..")?,
245            (Axis::Child, test) if !is_attribute_test => write!(self.f, "{test}")?,
246            (Axis::Attribute, test) => write!(self.f, "@{test}")?,
247            (axis, test) => write!(self.f, "{}::{test}", axis.name())?,
248        }
249        self.predicates(&step.predicates)
250    }
251}
252
253fn comparison_text(op: ComparisonOp) -> &'static str {
254    match op {
255        ComparisonOp::General(kind) => match kind {
256            CompareKind::Eq => "=",
257            CompareKind::Ne => "!=",
258            CompareKind::Lt => "<",
259            CompareKind::Le => "<=",
260            CompareKind::Gt => ">",
261            CompareKind::Ge => ">=",
262        },
263        ComparisonOp::Value(kind) => match kind {
264            CompareKind::Eq => "eq",
265            CompareKind::Ne => "ne",
266            CompareKind::Lt => "lt",
267            CompareKind::Le => "le",
268            CompareKind::Gt => "gt",
269            CompareKind::Ge => "ge",
270        },
271    }
272}
273
274impl Display for Expr {
275    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
276        Printer { f }.expr(self, prec::SEQUENCE)
277    }
278}
279
280impl Display for NodeTest {
281    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
282        match self {
283            Self::Name(NameTest::Name(name)) => write!(f, "{name}"),
284            Self::Name(NameTest::Any) => f.write_char('*'),
285            Self::Name(NameTest::AnyLocal { prefix, .. }) => write!(f, "{prefix}:*"),
286            Self::Name(NameTest::AnyNamespace { local }) => write!(f, "*:{local}"),
287            Self::Kind(kind) => write!(f, "{kind}"),
288        }
289    }
290}
291
292impl Display for KindTest {
293    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
294        let (name, arg) = match self {
295            Self::AnyKind => ("node", None),
296            Self::Text => ("text", None),
297            Self::Comment => ("comment", None),
298            Self::ProcessingInstruction => ("processing-instruction", None),
299            Self::Element(arg) => ("element", arg.as_ref()),
300            Self::Attribute(arg) => ("attribute", arg.as_ref()),
301        };
302        match arg {
303            None => write!(f, "{name}()"),
304            Some(NameOrWildcard::Wildcard) => write!(f, "{name}(*)"),
305            Some(NameOrWildcard::Name(qname)) => write!(f, "{name}({qname})"),
306        }
307    }
308}
309
310impl Display for SequenceType {
311    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
312        match &self.item {
313            ItemType::Atomic(atomic) => write!(f, "{}", atomic.name)?,
314            ItemType::Kind(kind) => write!(f, "{kind}")?,
315        }
316        f.write_str(match self.occurrence {
317            Occurrence::One => "",
318            Occurrence::ZeroOrOne => "?",
319            Occurrence::ZeroOrMore => "*",
320            Occurrence::OneOrMore => "+",
321        })
322    }
323}
324
325impl Display for SingleType {
326    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
327        write!(
328            f,
329            "{}{}",
330            self.atomic.name,
331            if self.allows_empty { "?" } else { "" }
332        )
333    }
334}
335
336impl Display for Pattern {
337    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
338        for (i, alternative) in self.alternatives.iter().enumerate() {
339            if i > 0 {
340                f.write_str(" | ")?;
341            }
342            write!(f, "{alternative}")?;
343        }
344        Ok(())
345    }
346}
347
348impl Display for PatternAlternative {
349    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
350        match self {
351            Self::DocumentRoot => f.write_char('/'),
352            Self::RootFunction => f.write_str("root()"),
353            Self::Path(path) => {
354                f.write_str(match path.anchor {
355                    PatternAnchor::Relative => "",
356                    PatternAnchor::Root => "/",
357                    PatternAnchor::RootDescendant => "//",
358                })?;
359                write!(f, "{}", path.first)?;
360                for (link, step) in &path.rest {
361                    f.write_str(match link {
362                        PatternLink::Child => "/",
363                        PatternLink::Descendant => "//",
364                    })?;
365                    write!(f, "{step}")?;
366                }
367                Ok(())
368            }
369        }
370    }
371}
372
373impl Display for PathStep {
374    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
375        match self {
376            Self::Axis(step) => write!(f, "{step}"),
377            Self::Parenthesized { inner, predicates } => {
378                write!(f, "({inner})")?;
379                Printer { f }.predicates(predicates)
380            }
381        }
382    }
383}
384
385impl Display for PatternStep {
386    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
387        let is_attribute_test = matches!(self.test, NodeTest::Kind(KindTest::Attribute(_)));
388        match self.axis {
389            PatternAxis::Attribute => write!(f, "@{}", self.test)?,
390            PatternAxis::Child if is_attribute_test => write!(f, "child::{}", self.test)?,
391            PatternAxis::Child => write!(f, "{}", self.test)?,
392        }
393        Printer { f }.predicates(&self.predicates)
394    }
395}
396
397impl Display for Avt {
398    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
399        for part in &self.parts {
400            match part {
401                AvtPart::Text(text) => f.write_str(&text.replace('{', "{{").replace('}', "}}"))?,
402                AvtPart::Expr(expr) => write!(f, "{{{expr}}}")?,
403            }
404        }
405        Ok(())
406    }
407}