akar-parser 0.1.0

Cypher parser for the Akar embedded graph database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Expression parsing — arithmetic, boolean, string, list, map, case, function calls.

use super::Rule;
use super::dml::{parse_property_kv, parse_query_pairs};
use crate::ast::*;

/// Parse any expression rule to an AST node.
pub fn parse_expression(pair: pest::iterators::Pair<Rule>) -> Result<Expression, String> {
    // Handle compound binary expressions by collecting children
    let rule = pair.as_rule();
    let children: Vec<_> = pair.clone().into_inner().collect();

    // Handle CASE expression
    if rule == Rule::case_expr {
        return parse_case_expr(pair);
    }

    // Handle comparison_expr specially — it can have 1, 2, or 3 children depending
    // on which operator is used (IS NULL, IN, STARTS WITH, =, etc.)
    if rule == Rule::comparison_expr {
        if children.len() == 1 {
            return parse_expression(children[0].clone());
        }
        let left = parse_expression(children[0].clone())?;
        if children.len() == 2 {
            // Postfix/special operators (IS NULL, IN, STARTS WITH, ...)
            return parse_comparison_suffix(children[1].clone(), left);
        }
        if children.len() == 3 {
            // Standard comparison: left comparison_op right
            let op_str = children[1].as_str();
            let op = match op_str {
                "=" => BinaryOp::Equal,
                "<>" => BinaryOp::NotEqual,
                "<" => BinaryOp::LessThan,
                ">" => BinaryOp::GreaterThan,
                "<=" => BinaryOp::LessThanOrEqual,
                ">=" => BinaryOp::GreaterThanOrEqual,
                _ => return Err(format!("Unknown comparison_op: {}", op_str)),
            };
            let right = parse_expression(children[2].clone())?;
            return Ok(Expression::BinaryOp(op, Box::new(left), Box::new(right)));
        }
        return Err(format!("Unexpected comparison_expr with {} children", children.len()));
    }

    // Unwrap single-child wrappers (priority/precedence levels)
    if matches!(
        rule,
        Rule::expression
            | Rule::or_expr
            | Rule::xor_expr
            | Rule::and_expr
            | Rule::not_expr
            | Rule::additive_expr
            | Rule::multiplicative_expr
            | Rule::unary_expr
    ) {
        if children.len() == 1 {
            return parse_expression(children[0].clone());
        }
        if children.len() >= 3 {
            let mut result = parse_expression(children[0].clone())?;
            let mut i = 1;
            while i + 1 < children.len() {
                let op = match children[i].as_str() {
                    "OR" => BinaryOp::Or,
                    "XOR" => BinaryOp::Xor,
                    "AND" => BinaryOp::And,
                    "+" => BinaryOp::Add,
                    "-" => BinaryOp::Subtract,
                    "*" => BinaryOp::Multiply,
                    "/" => BinaryOp::Divide,
                    "%" => BinaryOp::Modulo,
                    _ => return Err(format!("Unknown op: {}", children[i].as_str())),
                };
                let right = parse_expression(children[i + 1].clone())?;
                result = Expression::BinaryOp(op, Box::new(result), Box::new(right));
                i += 2;
            }
            return Ok(result);
        }
    }

    // Handle unary NOT
    if rule == Rule::not_expr && children.len() == 2 {
        let inner = parse_expression(children[1].clone())?;
        return Ok(Expression::UnaryOp(UnaryOp::Not, Box::new(inner)));
    }

    match rule {
        Rule::primary => {
            // Handle function calls encoded by grammar as: variable ~ function_args?
            // e.g. nextval('seq') or COUNT(a)
            if children.len() == 2
                && children[0].as_rule() == Rule::variable
                && children[1].as_rule() == Rule::function_args
            {
                let name = children[0].as_str().to_string();
                let mut args = Vec::new();
                let args_text = children[1].as_str().replace(" ", "");
                for c in children[1].clone().into_inner() {
                    if c.as_rule() == Rule::expression {
                        args.push(parse_expression(c)?);
                    }
                }
                if args.is_empty() && args_text == "(*)" {
                    args.push(Expression::Star);
                }
                return Ok(Expression::FunctionCall(name, args));
            }
            parse_expression(children.into_iter().next().ok_or("Empty primary")?)
        }
        Rule::literal => parse_literal(children.into_iter().next().ok_or("Empty literal")?),
        Rule::string => Ok(Expression::Constant(Constant::String(unescape_string(pair.as_str())))),
        Rule::integer => {
            let v: i64 = pair.as_str().parse().map_err(|e| format!("Int: {e}"))?;
            Ok(Expression::Constant(Constant::Integer(v)))
        }
        Rule::float => {
            let v: f64 = pair.as_str().parse().map_err(|e| format!("Float: {e}"))?;
            Ok(Expression::Constant(Constant::Float(v)))
        }
        Rule::boolean_literal => Ok(Expression::Constant(Constant::Bool(
            pair.as_str().to_uppercase() == "TRUE",
        ))),
        Rule::null_literal => Ok(Expression::Constant(Constant::Null)),
        Rule::variable => Ok(Expression::Variable(pair.as_str().to_string())),
        Rule::parameter => {
            let name = pair.as_str().strip_prefix('$').unwrap_or(pair.as_str()).to_string();
            Ok(Expression::Parameter(name))
        }
        Rule::list_literal => {
            let items = children
                .into_iter()
                .filter(|c| c.as_rule() == Rule::expression)
                .map(parse_expression)
                .collect::<Result<Vec<_>, _>>()?;
            Ok(Expression::List(items))
        }
        Rule::map_literal => {
            let mut entries = Vec::new();
            for c in children {
                if c.as_rule() == Rule::property_key_value {
                    entries.push(parse_property_kv(c)?);
                }
            }
            Ok(Expression::Map(entries))
        }
        Rule::postfix_expr => {
            let mut children = pair.clone().into_inner();
            let mut result = parse_expression(children.next().ok_or("Empty postfix")?)?;
            for child in children {
                if child.as_rule() == Rule::property_access {
                    let prop = child.into_inner().next().unwrap().as_str().to_string();
                    result = Expression::PropertyAccess(Box::new(result), prop);
                }
            }
            Ok(result)
        }
        Rule::exists_subquery => {
            // EXISTS { MATCH ... }
            for c in children {
                if c.as_rule() == Rule::query_statement {
                    let query = parse_query_pairs(c)?;
                    return Ok(Expression::ExistsSubquery(Box::new(query)));
                }
            }
            Err("EXISTS subquery requires a query statement".into())
        }
        Rule::list_predicate => {
            // ANY(x IN list WHERE predicate), ALL/NONE/SINGLE
            // Parse tree has: variable, expression(list), expression(predicate)
            // Quantifier is extracted from the matched string prefix.
            let children: Vec<_> = pair.clone().into_inner().collect();
            if children.len() < 3 {
                return Err(format!("Invalid list predicate syntax: {} children", children.len()));
            }
            // Extract quantifier from the raw token: the first word of the pair
            let full_text = pair.as_str();
            let quantifier_str = full_text.split('(').next().unwrap_or("").to_uppercase();
            let quantifier = match quantifier_str.as_str() {
                "ANY" => Quantifier::Any,
                "ALL" => Quantifier::All,
                "NONE" => Quantifier::None,
                "SINGLE" => Quantifier::Single,
                _ => return Err(format!("Unknown quantifier: {}", quantifier_str)),
            };
            let var_name = children[0].as_str().to_string();
            let list = parse_expression(children[1].clone())?;
            let predicate = parse_expression(children[2].clone())?;
            Ok(Expression::ListPredicate {
                quantifier,
                list: Box::new(list),
                var_name,
                predicate: Box::new(predicate),
            })
        }
        Rule::lambda_expr => {
            let mut children = pair.clone().into_inner();
            let var_name = children.next().ok_or("Lambda missing variable")?.as_str().to_string();
            let body = parse_expression(children.next().ok_or("Lambda missing body")?)?;
            Ok(Expression::Lambda {
                var_name,
                body: Box::new(body),
            })
        }
        Rule::function_args => {
            // function_call can appear as child of postfix_expr
            // The parent variable is the function name
            // We detect this in the postfix chain handling
            if children.is_empty() {
                return Ok(Expression::Constant(Constant::Null));
            }
            // Extract function name from siblings in parent
            let name = pair.as_str().split('(').next().unwrap_or("").to_string();
            let args = children
                .into_iter()
                .filter(|c| c.as_rule() == Rule::expression)
                .map(parse_expression)
                .collect::<Result<Vec<_>, _>>()?;
            Ok(Expression::FunctionCall(name, args))
        }
        Rule::property_access => Err("property_access should be handled within postfix_expr".into()),
        _ => {
            // Try unwrapping single child
            if let Some(child) = children.into_iter().next() {
                parse_expression(child)
            } else {
                Err(format!("Cannot parse: {:?}", rule))
            }
        }
    }
}

/// Parse a comparison suffix operator node into an expression given the left-hand side.
pub fn parse_comparison_suffix(pair: pest::iterators::Pair<Rule>, left: Expression) -> Result<Expression, String> {
    /// Find the additive_expr child inside an operator rule.
    fn get_rhs(pair: pest::iterators::Pair<Rule>) -> Result<Expression, String> {
        let rhs_pair = pair
            .into_inner()
            .find(|p| p.as_rule() == Rule::additive_expr)
            .ok_or_else(|| "Operator missing right-hand expression".to_string())?;
        parse_expression(rhs_pair)
    }

    match pair.as_rule() {
        Rule::is_check_op => {
            let text = pair.as_str();
            if text.contains("NOT") {
                Ok(Expression::UnaryOp(UnaryOp::IsNotNull, Box::new(left)))
            } else {
                Ok(Expression::UnaryOp(UnaryOp::IsNull, Box::new(left)))
            }
        }
        Rule::in_op => {
            let right = get_rhs(pair)?;
            Ok(Expression::BinaryOp(BinaryOp::In, Box::new(left), Box::new(right)))
        }
        Rule::not_in_op => {
            let right = get_rhs(pair)?;
            Ok(Expression::BinaryOp(BinaryOp::NotIn, Box::new(left), Box::new(right)))
        }
        Rule::starts_with_op => {
            let right = get_rhs(pair)?;
            Ok(Expression::BinaryOp(
                BinaryOp::StartsWith,
                Box::new(left),
                Box::new(right),
            ))
        }
        Rule::not_starts_with_op => {
            let right = get_rhs(pair)?;
            let inner = Expression::BinaryOp(BinaryOp::StartsWith, Box::new(left), Box::new(right));
            Ok(Expression::UnaryOp(UnaryOp::Not, Box::new(inner)))
        }
        Rule::ends_with_op => {
            let right = get_rhs(pair)?;
            Ok(Expression::BinaryOp(
                BinaryOp::EndsWith,
                Box::new(left),
                Box::new(right),
            ))
        }
        Rule::not_ends_with_op => {
            let right = get_rhs(pair)?;
            let inner = Expression::BinaryOp(BinaryOp::EndsWith, Box::new(left), Box::new(right));
            Ok(Expression::UnaryOp(UnaryOp::Not, Box::new(inner)))
        }
        Rule::contains_op => {
            let right = get_rhs(pair)?;
            Ok(Expression::BinaryOp(
                BinaryOp::Contains,
                Box::new(left),
                Box::new(right),
            ))
        }
        Rule::not_contains_op => {
            let right = get_rhs(pair)?;
            let inner = Expression::BinaryOp(BinaryOp::Contains, Box::new(left), Box::new(right));
            Ok(Expression::UnaryOp(UnaryOp::Not, Box::new(inner)))
        }
        Rule::like_op => {
            let right = get_rhs(pair)?;
            Ok(Expression::BinaryOp(BinaryOp::Like, Box::new(left), Box::new(right)))
        }
        Rule::between_op => {
            let mut children = pair.into_inner();
            let lower_pair = children
                .find(|p| p.as_rule() == Rule::additive_expr)
                .ok_or_else(|| "BETWEEN missing lower bound expression".to_string())?;
            let upper_pair = children
                .find(|p| p.as_rule() == Rule::additive_expr)
                .ok_or_else(|| "BETWEEN missing upper bound expression".to_string())?;
            let lower_expr = parse_expression(lower_pair)?;
            let upper_expr = parse_expression(upper_pair)?;
            let ge = Expression::BinaryOp(
                BinaryOp::GreaterThanOrEqual,
                Box::new(left.clone()),
                Box::new(lower_expr),
            );
            let le = Expression::BinaryOp(BinaryOp::LessThanOrEqual, Box::new(left), Box::new(upper_expr));
            Ok(Expression::BinaryOp(BinaryOp::And, Box::new(ge), Box::new(le)))
        }
        r => Err(format!("Unknown comparison suffix: {:?}", r)),
    }
}

/// Parse a `CASE [subject] WHEN ... THEN ... [ELSE ...] END` expression.
pub fn parse_case_expr(pair: pest::iterators::Pair<Rule>) -> Result<Expression, String> {
    let mut subject: Option<Expression> = None;
    let mut alternatives: Vec<CaseAlternative> = Vec::new();
    let mut else_expr: Option<Expression> = None;

    for child in pair.into_inner() {
        match child.as_rule() {
            Rule::case_subject => {
                // case_subject wraps a single expression (with lookahead to skip WHEN)
                if let Some(expr_pair) = child.into_inner().next() {
                    subject = Some(parse_expression(expr_pair)?);
                }
            }
            Rule::case_when => {
                // case_when contains exactly two expression children: WHEN expr, THEN expr
                let mut exprs = child
                    .into_inner()
                    .filter(|p| p.as_rule() == Rule::expression)
                    .map(parse_expression)
                    .collect::<Result<Vec<_>, _>>()?;
                if exprs.len() < 2 {
                    return Err("CASE WHEN clause requires both WHEN and THEN expressions".into());
                }
                let then = exprs.remove(1);
                let when = exprs.remove(0);
                alternatives.push(CaseAlternative { when, then });
            }
            Rule::case_else => {
                if let Some(expr_pair) = child.into_inner().find(|p| p.as_rule() == Rule::expression) {
                    else_expr = Some(parse_expression(expr_pair)?);
                }
            }
            _ => {} // Skip "CASE", "END" keyword tokens
        }
    }

    if alternatives.is_empty() {
        return Err("CASE expression requires at least one WHEN clause".into());
    }

    Ok(Expression::Case(CaseExpr {
        subject: subject.map(Box::new),
        alternatives,
        else_expr: else_expr.map(Box::new),
    }))
}

/// Parse a literal value.
pub fn parse_literal(pair: pest::iterators::Pair<Rule>) -> Result<Expression, String> {
    match pair.as_rule() {
        Rule::string => Ok(Expression::Constant(Constant::String(unescape_string(pair.as_str())))),
        Rule::integer => {
            let s = pair.as_str();
            Ok(Expression::Constant(Constant::Integer(
                s.trim().parse().map_err(|e| format!("Int: {e} (for string '{s}')"))?,
            )))
        }
        Rule::float => {
            let s = pair.as_str();
            Ok(Expression::Constant(Constant::Float(
                s.trim().parse().map_err(|e| format!("Float: {e} (for string '{s}')"))?,
            )))
        }
        Rule::boolean_literal => Ok(Expression::Constant(Constant::Bool(
            pair.as_str().to_uppercase() == "TRUE",
        ))),
        Rule::null_literal => Ok(Expression::Constant(Constant::Null)),
        _ => Err(format!("Unknown literal: {:?}", pair.as_rule())),
    }
}

/// Unescape a string literal — handles \n, \t, \r, \\, \", \'.
pub fn unescape_string(s: &str) -> String {
    let s = s.trim_matches(|c| c == '"' || c == '\'');
    let mut r = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('n') => r.push('\n'),
                Some('t') => r.push('\t'),
                Some('r') => r.push('\r'),
                Some('\\') => r.push('\\'),
                Some('"') => r.push('"'),
                Some('\'') => r.push('\''),
                Some(o) => {
                    r.push('\\');
                    r.push(o);
                }
                None => r.push('\\'),
            }
        } else {
            r.push(c);
        }
    }
    r
}