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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
mod statements;
mod store;
mod values;
use anyhow::Context as _;
use log::{debug, trace};
use std::collections::HashMap;
use tree_sitter::CaptureQuantifier::One;
use tree_sitter::QueryCursor;
use tree_sitter::QueryMatch;
use tree_sitter::Tree;
use crate::ast;
use crate::execution::query_capture_value;
use crate::execution::ExecutionError;
use crate::functions::Functions;
use crate::graph;
use crate::graph::Graph;
use crate::variables::Globals;
use crate::variables::VariableMap;
use crate::variables::Variables;
use crate::Identifier;
use statements::*;
use store::*;
use values::*;
impl ast::File {
pub fn execute_lazy<'tree>(
&self,
tree: &'tree Tree,
source: &'tree str,
functions: &mut Functions,
globals: &Globals,
) -> Result<Graph<'tree>, ExecutionError> {
let mut graph = Graph::new();
self.execute_lazy_into(&mut graph, tree, source, functions, globals)?;
Ok(graph)
}
pub fn execute_lazy_into<'tree>(
&self,
graph: &mut Graph<'tree>,
tree: &'tree Tree,
source: &'tree str,
functions: &mut Functions,
globals: &Globals,
) -> Result<(), ExecutionError> {
if tree.root_node().has_error() {
return Err(ExecutionError::ParseTreeHasErrors);
}
let mut locals = VariableMap::new();
let mut cursor = QueryCursor::new();
let mut store = LazyStore::new();
let mut scoped_store = LazyScopedVariables::new();
let mut lazy_graph = Vec::new();
let mut function_parameters = Vec::new();
let mut prev_element_debug_info = HashMap::new();
let query = &self.query.as_ref().unwrap();
let matches = cursor.matches(query, tree.root_node(), source.as_bytes());
for mat in matches {
let stanza = &self.stanzas[mat.pattern_index];
stanza.execute_lazy(
source,
&mat,
graph,
functions,
globals,
&mut locals,
&mut store,
&mut scoped_store,
&mut lazy_graph,
&mut function_parameters,
&mut prev_element_debug_info,
)?;
}
for graph_stmt in &lazy_graph {
graph_stmt
.evaluate(&mut EvaluationContext {
source,
graph,
functions,
store: &mut store,
scoped_store: &mut scoped_store,
function_parameters: &mut function_parameters,
prev_element_debug_info: &mut prev_element_debug_info,
})
.with_context(|| format!("Executing {}", graph_stmt))?;
}
Ok(())
}
}
struct ExecutionContext<'a, 'g, 'tree> {
source: &'tree str,
graph: &'a mut Graph<'tree>,
functions: &'a mut Functions,
globals: &'a Globals<'g>,
locals: &'a mut dyn Variables<LazyValue>,
current_regex_captures: &'a Vec<String>,
mat: &'a QueryMatch<'a, 'tree>,
store: &'a mut LazyStore,
scoped_store: &'a mut LazyScopedVariables,
lazy_graph: &'a mut Vec<LazyStatement>,
function_parameters: &'a mut Vec<graph::Value>,
prev_element_debug_info: &'a mut HashMap<GraphElementKey, DebugInfo>,
}
pub(self) struct EvaluationContext<'a, 'tree> {
pub source: &'tree str,
pub graph: &'a mut Graph<'tree>,
pub functions: &'a mut Functions,
pub store: &'a LazyStore,
pub scoped_store: &'a LazyScopedVariables,
pub function_parameters: &'a mut Vec<graph::Value>,
pub prev_element_debug_info: &'a mut HashMap<GraphElementKey, DebugInfo>,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub(super) enum GraphElementKey {
NodeAttribute(graph::GraphNodeRef, Identifier),
Edge(graph::GraphNodeRef, graph::GraphNodeRef),
EdgeAttribute(graph::GraphNodeRef, graph::GraphNodeRef, Identifier),
}
impl ast::Stanza {
fn execute_lazy<'l, 'g, 'q, 'tree>(
&self,
source: &'tree str,
mat: &QueryMatch<'_, 'tree>,
graph: &mut Graph<'tree>,
functions: &mut Functions,
globals: &Globals<'g>,
locals: &mut VariableMap<'l, LazyValue>,
store: &mut LazyStore,
scoped_store: &mut LazyScopedVariables,
lazy_graph: &mut Vec<LazyStatement>,
function_parameters: &mut Vec<graph::Value>,
prev_element_debug_info: &mut HashMap<GraphElementKey, DebugInfo>,
) -> Result<(), ExecutionError> {
let current_regex_captures = vec![];
locals.clear();
let mut exec = ExecutionContext {
source,
graph,
functions,
globals,
locals,
current_regex_captures: ¤t_regex_captures,
mat,
store,
scoped_store,
lazy_graph,
function_parameters,
prev_element_debug_info,
};
let node = query_capture_value(self.full_match_file_capture_index, One, &mat, exec.graph);
debug!("match {} at {}", node, self.location);
trace!("{{");
for statement in &self.statements {
statement
.execute_lazy(&mut exec)
.with_context(|| format!("Executing {}", statement))?;
}
trace!("}}");
Ok(())
}
}
impl ast::Statement {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
match self {
Self::DeclareImmutable(statement) => statement.execute_lazy(exec),
Self::DeclareMutable(statement) => statement.execute_lazy(exec),
Self::Assign(statement) => statement.execute_lazy(exec),
Self::CreateGraphNode(statement) => statement.execute_lazy(exec),
Self::AddGraphNodeAttribute(statement) => statement.execute_lazy(exec),
Self::CreateEdge(statement) => statement.execute_lazy(exec),
Self::AddEdgeAttribute(statement) => statement.execute_lazy(exec),
Self::Scan(statement) => statement.execute_lazy(exec),
Self::Print(statement) => statement.execute_lazy(exec),
Self::If(statement) => statement.execute_lazy(exec),
Self::ForIn(statement) => statement.execute_lazy(exec),
}
}
}
impl ast::DeclareImmutable {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let value = self.value.evaluate_lazy(exec)?;
self.variable.add_lazy(exec, value, false)
}
}
impl ast::DeclareMutable {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let value = self.value.evaluate_lazy(exec)?;
self.variable.add_lazy(exec, value, true)
}
}
impl ast::Assign {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let value = self.value.evaluate_lazy(exec)?;
self.variable.set_lazy(exec, value)
}
}
impl ast::CreateGraphNode {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let graph_node = exec.graph.add_graph_node();
self.node.add_lazy(exec, graph_node.into(), false)
}
}
impl ast::AddGraphNodeAttribute {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let node = self.node.evaluate_lazy(exec)?;
let mut attributes = Vec::new();
for attribute in &self.attributes {
attributes.push(attribute.evaluate_lazy(exec)?);
}
let stmt = LazyAddGraphNodeAttribute::new(node, attributes, self.location.into());
exec.lazy_graph.push(stmt.into());
Ok(())
}
}
impl ast::CreateEdge {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let source = self.source.evaluate_lazy(exec)?;
let sink = self.sink.evaluate_lazy(exec)?;
let stmt = LazyCreateEdge::new(source, sink, self.location.into());
exec.lazy_graph.push(stmt.into());
Ok(())
}
}
impl ast::AddEdgeAttribute {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let source = self.source.evaluate_lazy(exec)?;
let sink = self.sink.evaluate_lazy(exec)?;
let mut attributes = Vec::new();
for attribute in &self.attributes {
attributes.push(attribute.evaluate_lazy(exec)?);
}
let stmt = LazyAddEdgeAttribute::new(source, sink, attributes, self.location.into());
exec.lazy_graph.push(stmt.into());
Ok(())
}
}
impl ast::Scan {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let match_string = self.value.evaluate_eager(exec)?.into_string()?;
let mut i = 0;
let mut matches = Vec::new();
while i < match_string.len() {
matches.clear();
for (index, arm) in self.arms.iter().enumerate() {
let captures = arm.regex.captures(&match_string[i..]);
if let Some(captures) = captures {
if captures.get(0).unwrap().range().is_empty() {
return Err(ExecutionError::EmptyRegexCapture(format!(
"for regular expression /{}/",
arm.regex
)));
}
matches.push((captures, index));
}
}
if matches.is_empty() {
return Ok(());
}
matches.sort_by_key(|(captures, index)| {
let range = captures.get(0).unwrap().range();
(range.start, *index)
});
let (regex_captures, block_index) = &matches[0];
let arm = &self.arms[*block_index];
let mut current_regex_captures = Vec::new();
for regex_capture in regex_captures.iter() {
current_regex_captures
.push(regex_capture.map(|m| m.as_str()).unwrap_or("").to_string());
}
let mut arm_locals = VariableMap::new_child(exec.locals);
let mut arm_exec = ExecutionContext {
source: exec.source,
graph: exec.graph,
functions: exec.functions,
globals: exec.globals,
locals: &mut arm_locals,
current_regex_captures: ¤t_regex_captures,
mat: exec.mat,
store: exec.store,
scoped_store: exec.scoped_store,
lazy_graph: exec.lazy_graph,
function_parameters: exec.function_parameters,
prev_element_debug_info: exec.prev_element_debug_info,
};
for statement in &arm.statements {
statement
.execute_lazy(&mut arm_exec)
.with_context(|| format!("Executing {}", statement))
.with_context(|| {
format!(
"Matching {} with arm \"{}\" {{ ... }}",
match_string, arm.regex,
)
})?;
}
i += regex_captures.get(0).unwrap().range().end;
}
Ok(())
}
}
impl ast::Print {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let mut arguments = Vec::new();
for value in &self.values {
let argument = if let ast::Expression::StringConstant(expr) = value {
LazyPrintArgument::Text(expr.value.clone())
} else {
LazyPrintArgument::Value(value.evaluate_lazy(exec)?)
};
arguments.push(argument);
}
let stmt = LazyPrint::new(arguments, self.location.into());
exec.lazy_graph.push(stmt.into());
Ok(())
}
}
impl ast::If {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
for arm in &self.arms {
let mut result = true;
for condition in &arm.conditions {
result &= condition.test_eager(exec)?;
}
if result {
let mut arm_locals = VariableMap::new_child(exec.locals);
let mut arm_exec = ExecutionContext {
source: exec.source,
graph: exec.graph,
functions: exec.functions,
globals: exec.globals,
locals: &mut arm_locals,
current_regex_captures: exec.current_regex_captures,
mat: exec.mat,
store: exec.store,
scoped_store: exec.scoped_store,
lazy_graph: exec.lazy_graph,
function_parameters: exec.function_parameters,
prev_element_debug_info: exec.prev_element_debug_info,
};
for stmt in &arm.statements {
stmt.execute_lazy(&mut arm_exec)?;
}
break;
}
}
Ok(())
}
}
impl ast::Condition {
fn test_eager(&self, exec: &mut ExecutionContext) -> Result<bool, ExecutionError> {
match self {
Self::Some { value, .. } => Ok(!value.evaluate_eager(exec)?.is_null()),
Self::None { value, .. } => Ok(value.evaluate_eager(exec)?.is_null()),
Self::Bool { value, .. } => Ok(value.evaluate_eager(exec)?.into_boolean()?),
}
}
}
impl ast::ForIn {
fn execute_lazy(&self, exec: &mut ExecutionContext) -> Result<(), ExecutionError> {
let values = self.value.evaluate_eager(exec)?.into_list()?;
let mut loop_locals = VariableMap::new_child(exec.locals);
for value in values {
loop_locals.clear();
let mut loop_exec = ExecutionContext {
source: exec.source,
graph: exec.graph,
functions: exec.functions,
globals: exec.globals,
locals: &mut loop_locals,
current_regex_captures: exec.current_regex_captures,
mat: exec.mat,
store: exec.store,
scoped_store: exec.scoped_store,
lazy_graph: exec.lazy_graph,
function_parameters: exec.function_parameters,
prev_element_debug_info: exec.prev_element_debug_info,
};
self.variable
.add_lazy(&mut loop_exec, value.into(), false)?;
for stmt in &self.statements {
stmt.execute_lazy(&mut loop_exec)?;
}
}
Ok(())
}
}
impl ast::Expression {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
match self {
Self::FalseLiteral => Ok(false.into()),
Self::NullLiteral => Ok(graph::Value::Null.into()),
Self::TrueLiteral => Ok(true.into()),
Self::IntegerConstant(expr) => expr.evaluate_lazy(exec),
Self::StringConstant(expr) => expr.evaluate_lazy(exec),
Self::List(expr) => expr.evaluate_lazy(exec),
Self::Set(expr) => expr.evaluate_lazy(exec),
Self::Capture(expr) => expr.evaluate_lazy(exec),
Self::Variable(expr) => expr.evaluate_lazy(exec),
Self::Call(expr) => expr.evaluate_lazy(exec),
Self::RegexCapture(expr) => expr.evaluate_lazy(exec),
}
}
fn evaluate_eager(&self, exec: &mut ExecutionContext) -> Result<graph::Value, ExecutionError> {
self.evaluate_lazy(exec)?.evaluate(&mut EvaluationContext {
source: exec.source,
graph: exec.graph,
functions: exec.functions,
store: exec.store,
scoped_store: exec.scoped_store,
function_parameters: exec.function_parameters,
prev_element_debug_info: exec.prev_element_debug_info,
})
}
}
impl ast::IntegerConstant {
fn evaluate_lazy(&self, _exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
Ok(self.value.into())
}
}
impl ast::StringConstant {
fn evaluate_lazy(&self, _exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
Ok(self.value.clone().into())
}
}
impl ast::ListComprehension {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
let mut elements = Vec::new();
for element in &self.elements {
elements.push(element.evaluate_lazy(exec)?);
}
Ok(elements.into())
}
}
impl ast::SetComprehension {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
let mut elements = Vec::new();
for element in &self.elements {
elements.push(element.evaluate_lazy(exec)?);
}
Ok(LazySet::new(elements).into())
}
}
impl ast::Capture {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
Ok(query_capture_value(
self.file_capture_index,
self.quantifier,
exec.mat,
exec.graph,
)
.into())
}
}
impl ast::Call {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
let mut parameters = Vec::new();
for parameter in &self.parameters {
parameters.push(parameter.evaluate_lazy(exec)?);
}
Ok(LazyCall::new(self.function.clone(), parameters).into())
}
}
impl ast::RegexCapture {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
let value = exec.current_regex_captures[self.match_index].clone();
Ok(value.into())
}
}
impl ast::Variable {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
match self {
Self::Scoped(variable) => variable.evaluate_lazy(exec),
Self::Unscoped(variable) => variable.evaluate_lazy(exec),
}
}
}
impl ast::Variable {
fn add_lazy(
&self,
exec: &mut ExecutionContext,
value: LazyValue,
mutable: bool,
) -> Result<(), ExecutionError> {
match self {
Self::Scoped(variable) => variable.add_lazy(exec, value, mutable),
Self::Unscoped(variable) => variable.add_lazy(exec, value, mutable),
}
}
fn set_lazy(
&self,
exec: &mut ExecutionContext,
value: LazyValue,
) -> Result<(), ExecutionError> {
match self {
Self::Scoped(variable) => variable.set_lazy(exec, value),
Self::Unscoped(variable) => variable.set_lazy(exec, value),
}
}
}
impl ast::ScopedVariable {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
let scope = self.scope.evaluate_lazy(exec)?;
let value = LazyScopedVariable::new(scope, self.name.clone());
Ok(value.into())
}
fn add_lazy(
&self,
exec: &mut ExecutionContext,
value: LazyValue,
mutable: bool,
) -> Result<(), ExecutionError> {
if mutable {
return Err(ExecutionError::CannotDefineMutableScopedVariable(format!(
"{}",
self
)));
}
let scope = self.scope.evaluate_lazy(exec)?;
let variable = exec.store.add(value, self.location.into());
exec.scoped_store.add(
scope,
self.name.clone(),
variable.into(),
self.location.into(),
)
}
fn set_lazy(
&self,
_exec: &mut ExecutionContext,
_value: LazyValue,
) -> Result<(), ExecutionError> {
Err(ExecutionError::CannotAssignScopedVariable(format!(
"{}",
self
)))
}
}
impl ast::UnscopedVariable {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyValue, ExecutionError> {
if let Some(value) = exec.globals.get(&self.name) {
Some(value.clone().into())
} else {
exec.locals.get(&self.name).map(|value| value.clone())
}
.ok_or_else(|| ExecutionError::UndefinedVariable(format!("{}", self)))
}
}
impl ast::UnscopedVariable {
fn add_lazy(
&self,
exec: &mut ExecutionContext,
value: LazyValue,
mutable: bool,
) -> Result<(), ExecutionError> {
if exec.globals.get(&self.name).is_some() {
return Err(ExecutionError::DuplicateVariable(format!(
" global {}",
self
)));
}
let value = exec.store.add(value, self.location.into());
exec.locals
.add(self.name.clone(), value.into(), mutable)
.map_err(|_| ExecutionError::DuplicateVariable(format!(" local {}", self)))
}
fn set_lazy(
&self,
exec: &mut ExecutionContext,
value: LazyValue,
) -> Result<(), ExecutionError> {
if exec.globals.get(&self.name).is_some() {
return Err(ExecutionError::CannotAssignImmutableVariable(format!(
" global {}",
self
)));
}
let value = exec.store.add(value, self.location.into());
exec.locals
.set(self.name.clone(), value.into())
.map_err(|_| {
if exec.locals.get(&self.name).is_some() {
ExecutionError::CannotAssignImmutableVariable(format!("{}", self))
} else {
ExecutionError::UndefinedVariable(format!("{}", self))
}
})
}
}
impl ast::Attribute {
fn evaluate_lazy(&self, exec: &mut ExecutionContext) -> Result<LazyAttribute, ExecutionError> {
let value = self.value.evaluate_lazy(exec)?;
let attribute = LazyAttribute::new(self.name.clone(), value);
Ok(attribute)
}
}