1use relate_ir::{ChronoOp, Expr, LabelExpr, MapProjectionItem, QuantifierKind, TypeExpr};
16use relate_model::identifier::parameter_reference;
17use relate_names::SmallName;
18
19pub fn expr_text(expr: &Expr) -> String {
24 match expr {
25 Expr::Null => "null".to_string(),
26 Expr::Bool(value) => value.to_string(),
27 Expr::Int(value) => value.to_string(),
28 Expr::Float(value) => value.to_string(),
29 Expr::String(value) => format!("'{value}'"),
30 Expr::Parameter(name) => parameter_reference(name.as_str()),
31 Expr::Variable(name) => name.to_string(),
32 Expr::Star => "*".to_string(),
33 Expr::CountStar => "count(*)".to_string(),
34 Expr::Property { expr, key, .. } => format!("{}.{key}", expr_text(expr)),
35 Expr::DynamicProperty { expr, key } => format!("{}[{}]", expr_text(expr), expr_text(key)),
36 Expr::Function {
37 name,
38 distinct,
39 args,
40 } => {
41 let args = args.iter().map(expr_text).collect::<Vec<_>>().join(", ");
42 let distinct = if *distinct { "DISTINCT " } else { "" };
43 format!("{name}({distinct}{args})")
44 }
45 Expr::Unary { op, expr } => {
46 let inner = expr_text(expr);
47 match op {
48 relate_ir::UnaryOp::IsNull => format!("{inner} IS NULL"),
50 relate_ir::UnaryOp::IsNotNull => format!("{inner} IS NOT NULL"),
51 relate_ir::UnaryOp::Not => format!("NOT {inner}"),
52 relate_ir::UnaryOp::Minus => format!("-{inner}"),
53 relate_ir::UnaryOp::Plus => format!("+{inner}"),
54 }
55 }
56 Expr::Binary { op, left, right } => {
57 format!("{} {} {}", expr_text(left), op.as_str(), expr_text(right))
58 }
59 Expr::List(items) => format!(
60 "[{}]",
61 items.iter().map(expr_text).collect::<Vec<_>>().join(", ")
62 ),
63 Expr::PathConstruct { elements } => format!(
64 "PATH [{}]",
65 elements
66 .iter()
67 .map(expr_text)
68 .collect::<Vec<_>>()
69 .join(", ")
70 ),
71 Expr::Map(pairs) => format!(
72 "{{{}}}",
73 pairs
74 .iter()
75 .map(|(key, value)| format!("{key}: {}", expr_text(value)))
76 .collect::<Vec<_>>()
77 .join(", ")
78 ),
79 Expr::Subscript { expr, index } => format!("{}[{}]", expr_text(expr), expr_text(index)),
80 Expr::Slice { expr, start, end } => format!(
81 "{}[{}..{}]",
82 expr_text(expr),
83 start.as_deref().map(expr_text).unwrap_or_default(),
84 end.as_deref().map(expr_text).unwrap_or_default()
85 ),
86 Expr::IsType {
87 expr,
88 type_expr,
89 negated,
90 } => format!(
91 "{} IS {}:: {}",
92 expr_text(expr),
93 not_prefix(*negated),
94 type_expr_text(type_expr)
95 ),
96 Expr::LabelPredicate {
97 expr, label_expr, ..
98 } => format!("{}:{}", expr_text(expr), label_expr_text(label_expr)),
99 Expr::IsNormalized {
100 expr,
101 form,
102 negated,
103 } => format!(
104 "{} IS {}{}NORMALIZED",
105 expr_text(expr),
106 not_prefix(*negated),
107 form.as_deref()
108 .map(|form| format!("{form} "))
109 .unwrap_or_default()
110 ),
111 Expr::ChronoCompare {
112 left,
113 op,
114 right,
115 negated,
116 } => format!(
117 "{} IS {}{} {}",
118 expr_text(left),
119 not_prefix(*negated),
120 chrono_op_text(*op),
121 expr_text(right)
122 ),
123 Expr::Case {
124 when_then,
125 else_expr,
126 } => {
127 let arms = when_then
128 .iter()
129 .map(|(when, then)| format!("WHEN {} THEN {}", expr_text(when), expr_text(then)))
130 .chain(
131 else_expr
132 .as_deref()
133 .map(|otherwise| format!("ELSE {}", expr_text(otherwise))),
134 )
135 .collect::<Vec<_>>()
136 .join(" ");
137 format!("CASE {arms} END")
138 }
139 Expr::ListComp {
140 ident,
141 list,
142 predicate,
143 projection,
144 } => format!(
145 "[{ident} IN {}{} | {}]",
146 expr_text(list),
147 predicate
148 .as_deref()
149 .map(|predicate| format!(" WHERE {}", expr_text(predicate)))
150 .unwrap_or_default(),
151 expr_text(projection)
152 ),
153 Expr::MapComp {
154 key_ident,
155 value_ident,
156 source,
157 predicate,
158 key_expr,
159 value_expr,
160 } => format!(
161 "map {{{}{value_ident} IN {}{} | {}: {}}}",
162 key_ident
163 .as_ref()
164 .map(|key_ident| format!("{key_ident}: "))
165 .unwrap_or_default(),
166 expr_text(source),
167 predicate
168 .as_deref()
169 .map(|predicate| format!(" WHERE {}", expr_text(predicate)))
170 .unwrap_or_default(),
171 expr_text(key_expr),
172 expr_text(value_expr)
173 ),
174 Expr::Quantifier {
175 kind,
176 ident,
177 list,
178 predicate,
179 } => format!(
180 "{}({ident} IN {} WHERE {})",
181 quantifier_text(*kind),
182 expr_text(list),
183 expr_text(predicate)
184 ),
185 Expr::Reduce {
186 accumulator,
187 initial,
188 ident,
189 list,
190 expression,
191 } => format!(
192 "reduce({accumulator} = {}, {ident} IN {} | {})",
193 expr_text(initial),
194 expr_text(list),
195 expr_text(expression)
196 ),
197 Expr::AllReduce {
198 accumulator,
199 initial,
200 ident,
201 list,
202 expression,
203 predicate,
204 } => format!(
205 "allReduce({accumulator} = {}, {ident} IN {} | {} WHERE {})",
206 expr_text(initial),
207 expr_text(list),
208 expr_text(expression),
209 expr_text(predicate)
210 ),
211 Expr::ExistsSubquery { .. } => "EXISTS { … }".to_string(),
212 Expr::CountSubquery { .. } => "COUNT { … }".to_string(),
213 Expr::CollectSubquery { .. } => "COLLECT { … }".to_string(),
214 Expr::PatternPred { .. } => "(pattern)".to_string(),
215 Expr::ShortestPath { all, .. } => {
216 if *all {
217 "allShortestPaths(…)".to_string()
218 } else {
219 "shortestPath(…)".to_string()
220 }
221 }
222 Expr::MapProjection { expr, items } => format!(
223 "{} {{{}}}",
224 expr_text(expr),
225 items
226 .iter()
227 .map(map_projection_item_text)
228 .collect::<Vec<_>>()
229 .join(", ")
230 ),
231 Expr::RuntimeValue(_) => "<value>".to_string(),
232 Expr::DistanceMetric(metric) => metric.name().to_string(),
233 }
234}
235
236pub(crate) fn graph_call_text(name: &SmallName, args: &[Expr]) -> String {
239 let inner = args
240 .iter()
241 .map(graph_expr_text)
242 .collect::<Vec<_>>()
243 .join(", ");
244 format!("{name}({inner})")
245}
246
247pub(crate) fn graph_expr_text(expr: &Expr) -> String {
252 match expr {
253 Expr::String(_) | Expr::Variable(_) | Expr::Parameter(_) | Expr::Property { .. } => {
254 expr_text(expr)
255 }
256 Expr::Function { name, args, .. } => graph_call_text(name, args),
257 _ => "<dynamic>".to_string(),
258 }
259}
260
261fn not_prefix(negated: bool) -> &'static str {
263 if negated {
264 "NOT "
265 } else {
266 ""
267 }
268}
269
270fn chrono_op_text(op: ChronoOp) -> &'static str {
271 match op {
272 ChronoOp::Before => "BEFORE",
273 ChronoOp::After => "AFTER",
274 ChronoOp::SameInstant => "SAME INSTANT",
275 ChronoOp::SameRepresentation => "SAME REPRESENTATION",
276 }
277}
278
279fn quantifier_text(kind: QuantifierKind) -> &'static str {
280 match kind {
281 QuantifierKind::All => "all",
282 QuantifierKind::Any => "any",
283 QuantifierKind::None => "none",
284 QuantifierKind::Single => "single",
285 }
286}
287
288fn map_projection_item_text(item: &MapProjectionItem) -> String {
289 match item {
290 MapProjectionItem::KeyValue { key, value } => format!("{key}: {}", expr_text(value)),
291 MapProjectionItem::Property { key } => format!(".{key}"),
292 MapProjectionItem::Variable { name } => name.to_string(),
293 MapProjectionItem::AllProperties => ".*".to_string(),
294 }
295}
296
297fn type_expr_text(type_expr: &TypeExpr) -> String {
300 let (base, not_null) = match type_expr {
301 TypeExpr::Predefined { kind, not_null } => (kind.as_str().to_string(), *not_null),
302 TypeExpr::List { element, not_null } => {
303 (format!("LIST<{}>", type_expr_text(element)), *not_null)
304 }
305 TypeExpr::PropertyValue { not_null } => ("[ANY] PROPERTY VALUE".to_string(), *not_null),
306 TypeExpr::Union(members) => (
307 members
308 .iter()
309 .map(type_expr_text)
310 .collect::<Vec<_>>()
311 .join(" | "),
312 false,
313 ),
314 TypeExpr::Vector {
315 coord,
316 dimension,
317 not_null,
318 } => {
319 let mut text = String::from("VECTOR");
320 if let Some(coord) = coord {
321 text.push('<');
322 text.push_str(coord);
323 text.push_str(" NOT NULL>");
324 }
325 if let Some(dimension) = dimension {
326 text.push('(');
327 text.push_str(&dimension.to_string());
328 text.push(')');
329 }
330 (text, *not_null)
331 }
332 };
333 if not_null {
334 format!("{base} NOT NULL")
335 } else {
336 base
337 }
338}
339
340fn label_expr_text(label_expr: &LabelExpr) -> String {
342 match label_expr {
343 LabelExpr::Label(label) => label.to_string(),
344 LabelExpr::Wildcard => "%".to_string(),
345 LabelExpr::Dynamic { expr, .. } => format!("$({})", expr_text(expr)),
346 LabelExpr::Not(inner) => format!("!{}", label_expr_text(inner)),
347 LabelExpr::And(items) => items
348 .iter()
349 .map(label_expr_text)
350 .collect::<Vec<_>>()
351 .join("&"),
352 LabelExpr::Or(items) => items
353 .iter()
354 .map(label_expr_text)
355 .collect::<Vec<_>>()
356 .join("|"),
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 use relate_ir::BinaryOp;
365
366 fn var(name: &str) -> Expr {
367 Expr::Variable(name.into())
368 }
369
370 #[test]
371 fn renders_the_common_projection_shapes() {
372 let expr = Expr::Binary {
373 op: BinaryOp::Add,
374 left: Box::new(var("n")),
375 right: Box::new(Expr::Int(1)),
376 };
377 assert_eq!(expr_text(&expr), "n + 1");
378 let expr = Expr::Function {
379 name: "collect".into(),
380 distinct: false,
381 args: vec![var("n")],
382 };
383 assert_eq!(expr_text(&expr), "collect(n)");
384 let expr = Expr::Property {
385 key_id: Default::default(),
386 expr: Box::new(var("n")),
387 key: "prop".into(),
388 };
389 assert_eq!(expr_text(&expr), "n.prop");
390 let expr = Expr::Parameter("p".into());
391 assert_eq!(expr_text(&expr), "$p");
392 let expr = Expr::String("s".into());
393 assert_eq!(expr_text(&expr), "'s'");
394 let expr = Expr::Unary {
397 op: relate_ir::UnaryOp::IsNull,
398 expr: Box::new(var("n")),
399 };
400 assert_eq!(expr_text(&expr), "n IS NULL");
401 let expr = Expr::Unary {
402 op: relate_ir::UnaryOp::IsNotNull,
403 expr: Box::new(var("n")),
404 };
405 assert_eq!(expr_text(&expr), "n IS NOT NULL");
406 let expr = Expr::Unary {
407 op: relate_ir::UnaryOp::Not,
408 expr: Box::new(var("n")),
409 };
410 assert_eq!(expr_text(&expr), "NOT n");
411 }
412
413 #[test]
416 fn renders_carried_modifiers_and_type_expressions() {
417 let is_type = Expr::IsType {
418 expr: Box::new(var("n")),
419 type_expr: TypeExpr::Predefined {
420 kind: relate_ir::PredefinedType::Integer,
421 not_null: true,
422 },
423 negated: true,
424 };
425 assert_eq!(expr_text(&is_type), "n IS NOT :: INTEGER NOT NULL");
426
427 let normalized = Expr::IsNormalized {
428 expr: Box::new(var("n")),
429 form: Some("NFC".to_string()),
430 negated: true,
431 };
432 assert_eq!(expr_text(&normalized), "n IS NOT NFC NORMALIZED");
433
434 let chrono = Expr::ChronoCompare {
435 left: Box::new(var("a")),
436 op: ChronoOp::SameRepresentation,
437 right: Box::new(var("b")),
438 negated: true,
439 };
440 assert_eq!(expr_text(&chrono), "a IS NOT SAME REPRESENTATION b");
441
442 let label = Expr::LabelPredicate {
443 expr: Box::new(var("n")),
444 label_expr: LabelExpr::And(vec![
445 LabelExpr::Label(SmallName::from_name("A")),
446 LabelExpr::Not(Box::new(LabelExpr::Label(SmallName::from_name("B")))),
447 ]),
448 strict: false,
449 };
450 assert_eq!(expr_text(&label), "n:A&!B");
451
452 let metric = Expr::DistanceMetric(relate_ir::VectorMetric::Cosine);
453 assert_eq!(expr_text(&metric), "COSINE");
454 }
455}