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