reifydb-rql 0.4.6

ReifyDB Query Language (RQL) parser and AST
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

use reifydb_transaction::transaction::Transaction;
use reifydb_type::fragment::Fragment;

use crate::{
	Result,
	ast::ast::{
		Ast, AstBlock, AstCall, AstCallFunction, AstDefFunction, AstFor, AstIf, AstLet, AstLiteral,
		AstLiteralNone, AstLoop, AstMatch, AstMatchArm, AstReturn, AstStatement, AstWhile,
		LetValue as AstLetValue,
	},
	bump::{BumpBox, BumpFragment, BumpVec},
	convert_data_type_with_constraints,
	expression::{
		AliasExpression, AndExpression, ColumnExpression, EqExpression, Expression, ExpressionCompiler,
		IdentExpression, IsVariantExpression,
	},
	plan::logical::{
		Compiler, ConditionalNode, DeclareNode, ElseIfBranch, ForNode, LetValue, LogicalPlan, LoopNode,
		MapNode, WhileNode,
		function::{CallFunctionNode, DefineFunctionNode, FunctionParameter, ReturnNode},
	},
	token::token::{Literal, Token, TokenKind},
};

impl<'bump> Compiler<'bump> {
	pub(crate) fn compile_let(&self, ast: AstLet<'bump>, tx: &mut Transaction<'_>) -> Result<LogicalPlan<'bump>> {
		let value = match ast.value {
			AstLetValue::Expression(expr) => {
				let inner = BumpBox::into_inner(expr);
				// Detect LET $x = [] → empty Frame
				if matches!(&inner, Ast::List(list) if list.len() == 0) {
					LetValue::EmptyFrame
				} else if matches!(&inner, Ast::Closure(_)) {
					// Closures require statement-level compilation (not expression-level)
					let Ast::Closure(closure_node) = inner else {
						unreachable!()
					};
					let closure_plan = self.compile_closure(closure_node, tx)?;
					let mut plans = BumpVec::new_in(self.bump);
					plans.push(closure_plan);
					LetValue::Statement(plans)
				} else {
					LetValue::Expression(ExpressionCompiler::compile(inner)?)
				}
			}
			AstLetValue::Statement(statement) => {
				let plan = self.compile(statement, tx)?;
				LetValue::Statement(plan)
			}
		};

		Ok(LogicalPlan::Declare(DeclareNode {
			name: BumpFragment::internal(self.bump, ast.name.text()),
			value,
		}))
	}

	/// Produce a MAP { value: none } plan node.
	fn none_as_map(&self) -> Result<LogicalPlan<'bump>> {
		let none_literal = Ast::Literal(AstLiteral::None(AstLiteralNone(Token {
			kind: TokenKind::Literal(Literal::None),
			fragment: BumpFragment::internal(self.bump, "none"),
		})));
		self.compile_scalar_as_map(none_literal)
	}

	pub(crate) fn compile_if(&self, ast: AstIf<'bump>, tx: &mut Transaction<'_>) -> Result<LogicalPlan<'bump>> {
		// Compile the condition expression
		let condition = ExpressionCompiler::compile(BumpBox::into_inner(ast.condition))?;

		// Compile the then branch from block
		let then_branch = BumpBox::new_in(self.compile_block_single(ast.then_block, tx)?, self.bump);

		// Compile else if branches
		let mut else_ifs = Vec::new();
		for else_if in ast.else_ifs {
			let condition = ExpressionCompiler::compile(BumpBox::into_inner(else_if.condition))?;
			let then_branch =
				BumpBox::new_in(self.compile_block_single(else_if.then_block, tx)?, self.bump);

			else_ifs.push(ElseIfBranch {
				condition,
				then_branch,
			});
		}

		// Compile optional else branch
		let else_branch = if let Some(else_block) = ast.else_block {
			Some(BumpBox::new_in(self.compile_block_single(else_block, tx)?, self.bump))
		} else {
			Some(BumpBox::new_in(self.none_as_map()?, self.bump))
		};

		Ok(LogicalPlan::Conditional(ConditionalNode {
			condition,
			then_branch,
			else_ifs,
			else_branch,
		}))
	}

	pub(crate) fn compile_match(
		&self,
		ast: AstMatch<'bump>,
		_tx: &mut Transaction<'_>,
	) -> Result<LogicalPlan<'bump>> {
		let fragment = ast.token.fragment.to_owned();

		// Compile subject expression (if present)
		let subject = match ast.subject {
			Some(s) => Some(ExpressionCompiler::compile(BumpBox::into_inner(s))?),
			None => None,
		};

		// Extract the subject column name for field rewriting (if subject is a simple column)
		let subject_col_name = subject.as_ref().and_then(|s| match s {
			Expression::Column(ColumnExpression(col)) => Some(col.name.text().to_string()),
			_ => None,
		});

		// Build list of (condition, LogicalPlan) pairs + optional else
		let mut branches: Vec<(Expression, LogicalPlan<'bump>)> = Vec::new();
		let mut else_plan: Option<LogicalPlan<'bump>> = None;

		for arm in ast.arms {
			match arm {
				AstMatchArm::Else {
					result,
				} => {
					else_plan = Some(self.compile_scalar_as_map(BumpBox::into_inner(result))?);
				}
				AstMatchArm::Value {
					pattern,
					guard,
					result,
				} => {
					let subject_expr = subject.clone().expect("Value arm requires a MATCH subject");
					let pattern_expr = ExpressionCompiler::compile(BumpBox::into_inner(pattern))?;

					let mut condition = Expression::Equal(EqExpression {
						left: Box::new(subject_expr),
						right: Box::new(pattern_expr),
						fragment: fragment.clone(),
					});

					if let Some(guard) = guard {
						let guard_expr =
							ExpressionCompiler::compile(BumpBox::into_inner(guard))?;
						condition = Expression::And(AndExpression {
							left: Box::new(condition),
							right: Box::new(guard_expr),
							fragment: fragment.clone(),
						});
					}

					let result_plan = self.compile_scalar_as_map(BumpBox::into_inner(result))?;
					branches.push((condition, result_plan));
				}
				AstMatchArm::IsVariant {
					namespace,
					sumtype_name,
					variant_name,
					destructure,
					guard,
					result,
				} => {
					let subject_expr = subject.clone().expect("IS arm requires a MATCH subject");

					// Build field bindings for rewriting
					let bindings: Vec<(String, String)> = match (&destructure, &subject_col_name) {
						(Some(destr), Some(col_name)) => {
							let variant_lower = variant_name.text().to_lowercase();
							destr.fields
								.iter()
								.map(|f| {
									let field_name = f.text().to_string();
									let physical = format!(
										"{}_{}_{}",
										col_name,
										variant_lower,
										field_name.to_lowercase()
									);
									(field_name, physical)
								})
								.collect()
						}
						_ => vec![],
					};

					let mut condition = Expression::IsVariant(IsVariantExpression {
						expression: Box::new(subject_expr),
						namespace: namespace.map(|n| n.to_owned()),
						sumtype_name: sumtype_name.to_owned(),
						variant_name: variant_name.to_owned(),
						tag: None,
						fragment: fragment.clone(),
					});

					if let Some(guard) = guard {
						let mut guard_expr =
							ExpressionCompiler::compile(BumpBox::into_inner(guard))?;
						ExpressionCompiler::rewrite_field_refs(&mut guard_expr, &bindings);
						condition = Expression::And(AndExpression {
							left: Box::new(condition),
							right: Box::new(guard_expr),
							fragment: fragment.clone(),
						});
					}

					// Compile result, rewrite field refs, then wrap in MapNode
					let mut result_expr = ExpressionCompiler::compile(BumpBox::into_inner(result))?;
					ExpressionCompiler::rewrite_field_refs(&mut result_expr, &bindings);

					let alias_expr = AliasExpression {
						alias: IdentExpression(Fragment::internal("value")),
						expression: Box::new(result_expr),
						fragment: fragment.clone(),
					};
					let result_plan = LogicalPlan::Map(MapNode {
						map: vec![Expression::Alias(alias_expr)],
						rql: String::new(),
					});

					branches.push((condition, result_plan));
				}
				AstMatchArm::Variant {
					variant_name,
					destructure,
					guard,
					result,
				} => {
					let subject_expr =
						subject.clone().expect("Variant arm requires a MATCH subject");

					// Build field bindings for rewriting
					let bindings: Vec<(String, String)> = match (&destructure, &subject_col_name) {
						(Some(destr), Some(col_name)) => {
							let variant_lower = variant_name.text().to_lowercase();
							destr.fields
								.iter()
								.map(|f| {
									let field_name = f.text().to_string();
									let physical = format!(
										"{}_{}_{}",
										col_name,
										variant_lower,
										field_name.to_lowercase()
									);
									(field_name, physical)
								})
								.collect()
						}
						_ => vec![],
					};

					let mut condition = Expression::IsVariant(IsVariantExpression {
						expression: Box::new(subject_expr),
						namespace: None,
						sumtype_name: variant_name.to_owned(),
						variant_name: variant_name.to_owned(),
						tag: None,
						fragment: fragment.clone(),
					});

					if let Some(guard) = guard {
						let mut guard_expr =
							ExpressionCompiler::compile(BumpBox::into_inner(guard))?;
						ExpressionCompiler::rewrite_field_refs(&mut guard_expr, &bindings);
						condition = Expression::And(AndExpression {
							left: Box::new(condition),
							right: Box::new(guard_expr),
							fragment: fragment.clone(),
						});
					}

					// Compile result, rewrite field refs, then wrap in MapNode
					let mut result_expr = ExpressionCompiler::compile(BumpBox::into_inner(result))?;
					ExpressionCompiler::rewrite_field_refs(&mut result_expr, &bindings);

					let alias_expr = AliasExpression {
						alias: IdentExpression(Fragment::internal("value")),
						expression: Box::new(result_expr),
						fragment: fragment.clone(),
					};
					let result_plan = LogicalPlan::Map(MapNode {
						map: vec![Expression::Alias(alias_expr)],
						rql: String::new(),
					});

					branches.push((condition, result_plan));
				}
				AstMatchArm::Condition {
					condition,
					guard,
					result,
				} => {
					let mut cond = ExpressionCompiler::compile(BumpBox::into_inner(condition))?;

					if let Some(guard) = guard {
						let guard_expr =
							ExpressionCompiler::compile(BumpBox::into_inner(guard))?;
						cond = Expression::And(AndExpression {
							left: Box::new(cond),
							right: Box::new(guard_expr),
							fragment: fragment.clone(),
						});
					}

					let result_plan = self.compile_scalar_as_map(BumpBox::into_inner(result))?;
					branches.push((cond, result_plan));
				}
			}
		}

		// Assemble into ConditionalNode
		if branches.is_empty() {
			return match else_plan {
				Some(plan) => Ok(plan),
				None => self.none_as_map(),
			};
		}

		let (first_cond, first_then) = branches.remove(0);

		let else_ifs: Vec<ElseIfBranch<'bump>> = branches
			.into_iter()
			.map(|(cond, plan)| ElseIfBranch {
				condition: cond,
				then_branch: BumpBox::new_in(plan, self.bump),
			})
			.collect();

		let else_branch = match else_plan {
			Some(plan) => Some(BumpBox::new_in(plan, self.bump)),
			None => Some(BumpBox::new_in(self.none_as_map()?, self.bump)),
		};

		Ok(LogicalPlan::Conditional(ConditionalNode {
			condition: first_cond,
			then_branch: BumpBox::new_in(first_then, self.bump),
			else_ifs,
			else_branch,
		}))
	}

	/// Compile a block as a single logical plan node.
	/// Takes the first expression from the first statement.
	fn compile_block_single(&self, block: AstBlock<'bump>, tx: &mut Transaction<'_>) -> Result<LogicalPlan<'bump>> {
		if let Some(first_stmt) = block.statements.into_iter().next() {
			if let Some(first_node) = first_stmt.nodes.into_iter().next() {
				return self.compile_single(first_node, tx);
			}
		}
		// Empty block → none wrapped in MAP
		self.none_as_map()
	}

	/// Compile all statements in a block into a Vec<BumpVec<LogicalPlan>>
	pub(crate) fn compile_block(
		&self,
		block: AstBlock<'bump>,
		tx: &mut Transaction<'_>,
	) -> Result<Vec<BumpVec<'bump, LogicalPlan<'bump>>>> {
		let mut result = Vec::new();
		for stmt in block.statements {
			let plans = self.compile(stmt, tx)?;
			result.push(plans);
		}
		Ok(result)
	}

	pub(crate) fn compile_loop(&self, ast: AstLoop<'bump>, tx: &mut Transaction<'_>) -> Result<LogicalPlan<'bump>> {
		let body = self.compile_block(ast.body, tx)?;
		Ok(LogicalPlan::Loop(LoopNode {
			body,
		}))
	}

	pub(crate) fn compile_while(
		&self,
		ast: AstWhile<'bump>,
		tx: &mut Transaction<'_>,
	) -> Result<LogicalPlan<'bump>> {
		let condition = ExpressionCompiler::compile(BumpBox::into_inner(ast.condition))?;
		let body = self.compile_block(ast.body, tx)?;
		Ok(LogicalPlan::While(WhileNode {
			condition,
			body,
		}))
	}

	pub(crate) fn compile_for(&self, ast: AstFor<'bump>, tx: &mut Transaction<'_>) -> Result<LogicalPlan<'bump>> {
		let variable_name = {
			let text = ast.variable.token.fragment.text();
			let clean = if text.starts_with('$') {
				&text[1..]
			} else {
				text
			};
			BumpFragment::internal(self.bump, clean)
		};
		let iterable_ast = BumpBox::into_inner(ast.iterable);
		let iterable_stmt = AstStatement {
			nodes: vec![iterable_ast],
			has_pipes: false,
			is_output: false,
		};
		let iterable = self.compile(iterable_stmt, tx)?;
		let body = self.compile_block(ast.body, tx)?;
		Ok(LogicalPlan::For(ForNode {
			variable_name,
			iterable,
			body,
		}))
	}

	/// Compile a function definition
	pub(crate) fn compile_def_function(
		&self,
		ast: AstDefFunction<'bump>,
		tx: &mut Transaction<'_>,
	) -> Result<LogicalPlan<'bump>> {
		// Convert function name
		let name = ast.name.token.fragment;

		// Convert parameters
		let mut parameters = Vec::new();
		for param in ast.parameters {
			let param_name = param.variable.token.fragment;
			let type_constraint = if let Some(ref ty) = param.type_annotation {
				Some(convert_data_type_with_constraints(ty)?)
			} else {
				None
			};
			parameters.push(FunctionParameter {
				name: param_name,
				type_constraint,
			});
		}

		// Convert optional return type
		let return_type = if let Some(ref ty) = ast.return_type {
			Some(convert_data_type_with_constraints(ty)?)
		} else {
			None
		};

		// Compile the body
		let body = self.compile_block(ast.body, tx)?;

		Ok(LogicalPlan::DefineFunction(DefineFunctionNode {
			name,
			parameters,
			return_type,
			body,
		}))
	}

	/// Compile a return statement
	pub(crate) fn compile_return(&self, ast: AstReturn<'bump>) -> Result<LogicalPlan<'bump>> {
		let value = if let Some(expr) = ast.value {
			Some(ExpressionCompiler::compile(BumpBox::into_inner(expr))?)
		} else {
			None
		};

		Ok(LogicalPlan::Return(ReturnNode {
			value,
		}))
	}

	/// Compile a function call (potentially user-defined)
	pub(crate) fn compile_call_function(&self, ast: AstCallFunction<'bump>) -> Result<LogicalPlan<'bump>> {
		let name = if ast.function.namespaces.is_empty() {
			ast.function.name
		} else {
			let first_ns = &ast.function.namespaces[0];
			let mut qualified = String::new();
			for ns in &ast.function.namespaces {
				qualified.push_str(ns.text());
				qualified.push_str("::");
			}
			qualified.push_str(ast.function.name.text());
			let qualified_text = self.bump.alloc_str(&qualified);
			match first_ns {
				BumpFragment::Statement {
					offset,
					line,
					column,
					..
				} => BumpFragment::Statement {
					text: qualified_text,
					offset: *offset,
					source_end: ast.function.name.source_end(),
					line: *line,
					column: *column,
				},
				_ => BumpFragment::internal(self.bump, &qualified),
			}
		};

		// Compile arguments as expressions
		let mut arguments = Vec::new();
		for arg in ast.arguments.nodes {
			arguments.push(ExpressionCompiler::compile(arg)?);
		}

		Ok(LogicalPlan::CallFunction(CallFunctionNode {
			name,
			arguments,
			is_procedure_call: false,
		}))
	}

	/// Compile a CALL statement (e.g., `CALL procedure_name(args)` or `CALL ns::proc(args)`)
	/// This compiles to the same CallFunction logical plan node, so the VM
	/// will resolve it against DEF functions, catalog procedures, or built-in functions.
	pub(crate) fn compile_call(&self, ast: AstCall<'bump>) -> Result<LogicalPlan<'bump>> {
		// Build qualified name: join namespaces with '::' for catalog lookup
		let name = if ast.function.namespaces.is_empty() {
			ast.function.name
		} else {
			let first_ns = &ast.function.namespaces[0];
			let mut qualified = String::new();
			for ns in &ast.function.namespaces {
				qualified.push_str(ns.text());
				qualified.push_str("::");
			}
			qualified.push_str(ast.function.name.text());
			let qualified_text = self.bump.alloc_str(&qualified);
			match first_ns {
				BumpFragment::Statement {
					offset,
					line,
					column,
					..
				} => BumpFragment::Statement {
					text: qualified_text,
					offset: *offset,
					source_end: ast.function.name.source_end(),
					line: *line,
					column: *column,
				},
				_ => BumpFragment::internal(self.bump, &qualified),
			}
		};

		// Compile arguments as expressions
		let mut arguments = Vec::new();
		for arg in ast.arguments.nodes {
			arguments.push(ExpressionCompiler::compile(arg)?);
		}

		Ok(LogicalPlan::CallFunction(CallFunctionNode {
			name,
			arguments,
			is_procedure_call: true,
		}))
	}
}