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
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2021, tree-sitter authors.
// Licensed under either of Apache License, Version 2.0, or MIT license, at your option.
// Please see the LICENSE-APACHE or LICENSE-MIT files in this distribution for license details.
// ------------------------------------------------------------------------------------------------

//! Defines the AST structure of a graph DSL file

use regex::Regex;
use std::fmt;
use tree_sitter::Language;
use tree_sitter::Query;

use crate::Context;
use crate::DisplayWithContext;
use crate::Identifier;
use crate::Location;

/// A graph DSL file
#[derive(Debug)]
pub struct File {
    pub language: Language,
    /// The list of stanzas in the file
    pub stanzas: Vec<Stanza>,
}

impl File {
    pub fn new(language: Language) -> File {
        File {
            language,
            stanzas: Vec::new(),
        }
    }
}

/// One stanza within a file
#[derive(Debug)]
pub struct Stanza {
    /// The tree-sitter query for this stanza
    pub query: Query,
    /// The list of statements in the stanza
    pub statements: Vec<Statement>,
    pub location: Location,
}

/// A statement that can appear in a graph DSL stanza
#[derive(Debug, Eq, PartialEq)]
pub enum Statement {
    // Variables
    DeclareImmutable(DeclareImmutable),
    DeclareMutable(DeclareMutable),
    Assign(Assign),
    // Graph nodes
    CreateGraphNode(CreateGraphNode),
    AddGraphNodeAttribute(AddGraphNodeAttribute),
    // Edges
    CreateEdge(CreateEdge),
    AddEdgeAttribute(AddEdgeAttribute),
    // Regular expression
    Scan(Scan),
    // Debugging
    Print(Print),
}

impl DisplayWithContext for Statement {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        match self {
            Statement::DeclareImmutable(stmt) => stmt.fmt(f, ctx),
            Statement::DeclareMutable(stmt) => stmt.fmt(f, ctx),
            Statement::Assign(stmt) => stmt.fmt(f, ctx),
            Statement::CreateGraphNode(stmt) => stmt.fmt(f, ctx),
            Statement::AddGraphNodeAttribute(stmt) => stmt.fmt(f, ctx),
            Statement::CreateEdge(stmt) => stmt.fmt(f, ctx),
            Statement::AddEdgeAttribute(stmt) => stmt.fmt(f, ctx),
            Statement::Scan(stmt) => stmt.fmt(f, ctx),
            Statement::Print(stmt) => stmt.fmt(f, ctx),
        }
    }
}

/// An `attr` statement that adds an attribute to an edge
#[derive(Debug, Eq, PartialEq)]
pub struct AddEdgeAttribute {
    pub source: Expression,
    pub sink: Expression,
    pub attributes: Vec<Attribute>,
    pub location: Location,
}

impl From<AddEdgeAttribute> for Statement {
    fn from(statement: AddEdgeAttribute) -> Statement {
        Statement::AddEdgeAttribute(statement)
    }
}

impl DisplayWithContext for AddEdgeAttribute {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(
            f,
            "attr ({} -> {})",
            self.source.display_with(ctx),
            self.sink.display_with(ctx),
        )?;
        for attr in &self.attributes {
            write!(f, " {}", attr.display_with(ctx))?;
        }
        write!(f, " at {}", self.location)
    }
}

/// An `attr` statement that adds an attribute to a graph node
#[derive(Debug, Eq, PartialEq)]
pub struct AddGraphNodeAttribute {
    pub node: Expression,
    pub attributes: Vec<Attribute>,
    pub location: Location,
}

impl From<AddGraphNodeAttribute> for Statement {
    fn from(statement: AddGraphNodeAttribute) -> Statement {
        Statement::AddGraphNodeAttribute(statement)
    }
}

impl DisplayWithContext for AddGraphNodeAttribute {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(f, "attr ({})", self.node.display_with(ctx),)?;
        for attr in &self.attributes {
            write!(f, " {}", attr.display_with(ctx),)?;
        }
        write!(f, " at {}", self.location)
    }
}

/// A `set` statement that updates the value of a mutable variable
#[derive(Debug, Eq, PartialEq)]
pub struct Assign {
    pub variable: Variable,
    pub value: Expression,
    pub location: Location,
}

impl From<Assign> for Statement {
    fn from(statement: Assign) -> Statement {
        Statement::Assign(statement)
    }
}

impl DisplayWithContext for Assign {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(
            f,
            "set {} = {} at {}",
            self.variable.display_with(ctx),
            self.value.display_with(ctx),
            self.location,
        )
    }
}

/// The name and value of an attribute
#[derive(Debug, Eq, PartialEq)]
pub struct Attribute {
    pub name: Identifier,
    pub value: Expression,
}

impl DisplayWithContext for Attribute {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(
            f,
            "{} = {}",
            self.name.display_with(ctx),
            self.value.display_with(ctx),
        )
    }
}

/// An `edge` statement that creates a new edge
#[derive(Debug, Eq, PartialEq)]
pub struct CreateEdge {
    pub source: Expression,
    pub sink: Expression,
    pub location: Location,
}

impl From<CreateEdge> for Statement {
    fn from(statement: CreateEdge) -> Statement {
        Statement::CreateEdge(statement)
    }
}

impl DisplayWithContext for CreateEdge {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(
            f,
            "edge {} -> {} at {}",
            self.source.display_with(ctx),
            self.sink.display_with(ctx),
            self.location,
        )
    }
}

/// A `node` statement that creates a new graph node
#[derive(Debug, Eq, PartialEq)]
pub struct CreateGraphNode {
    pub node: Variable,
    pub location: Location,
}

impl From<CreateGraphNode> for Statement {
    fn from(statement: CreateGraphNode) -> Statement {
        Statement::CreateGraphNode(statement)
    }
}

impl DisplayWithContext for CreateGraphNode {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(
            f,
            "node {} at {}",
            self.node.display_with(ctx),
            self.location
        )
    }
}

/// A `let` statement that declares a new immutable variable
#[derive(Debug, Eq, PartialEq)]
pub struct DeclareImmutable {
    pub variable: Variable,
    pub value: Expression,
    pub location: Location,
}

impl From<DeclareImmutable> for Statement {
    fn from(statement: DeclareImmutable) -> Statement {
        Statement::DeclareImmutable(statement)
    }
}

impl DisplayWithContext for DeclareImmutable {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(
            f,
            "let {} = {} at {}",
            self.variable.display_with(ctx),
            self.value.display_with(ctx),
            self.location,
        )
    }
}

/// A `var` statement that declares a new mutable variable
#[derive(Debug, Eq, PartialEq)]
pub struct DeclareMutable {
    pub variable: Variable,
    pub value: Expression,
    pub location: Location,
}

impl From<DeclareMutable> for Statement {
    fn from(statement: DeclareMutable) -> Statement {
        Statement::DeclareMutable(statement)
    }
}

impl DisplayWithContext for DeclareMutable {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(
            f,
            "var {} = {} at {}",
            self.variable.display_with(ctx),
            self.value.display_with(ctx),
            self.location,
        )
    }
}

/// A `print` statement that prints out some debugging information
#[derive(Debug, Eq, PartialEq)]
pub struct Print {
    pub values: Vec<Expression>,
    pub location: Location,
}

impl From<Print> for Statement {
    fn from(statement: Print) -> Statement {
        Statement::Print(statement)
    }
}

impl DisplayWithContext for Print {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(f, "print")?;
        for val in &self.values {
            write!(f, " {},", val.display_with(ctx),)?;
        }
        write!(f, " at {}", self.location)
    }
}

/// A `scan` statement that matches regular expressions against a string
#[derive(Debug, Eq, PartialEq)]
pub struct Scan {
    pub value: Expression,
    pub arms: Vec<ScanArm>,
    pub location: Location,
}

impl From<Scan> for Statement {
    fn from(statement: Scan) -> Statement {
        Statement::Scan(statement)
    }
}

impl DisplayWithContext for Scan {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(
            f,
            "scan {} {{ ... }} at {}",
            self.value.display_with(ctx),
            self.location
        )
    }
}

/// One arm of a `scan` statement
#[derive(Debug)]
pub struct ScanArm {
    pub regex: Regex,
    pub statements: Vec<Statement>,
    pub location: Location,
}

impl Eq for ScanArm {}

impl PartialEq for ScanArm {
    fn eq(&self, other: &ScanArm) -> bool {
        self.regex.as_str() == other.regex.as_str() && self.statements == other.statements
    }
}

impl DisplayWithContext for ScanArm {
    fn fmt(&self, f: &mut fmt::Formatter, _ctx: &Context) -> fmt::Result {
        write!(f, "{:?} {{ ... }}", self.regex.as_str())
    }
}

/// A reference to a variable
#[derive(Debug, Eq, PartialEq)]
pub enum Variable {
    Scoped(ScopedVariable),
    Unscoped(UnscopedVariable),
}

impl DisplayWithContext for Variable {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        match self {
            Variable::Scoped(variable) => variable.fmt(f, ctx),
            Variable::Unscoped(variable) => variable.fmt(f, ctx),
        }
    }
}

/// A reference to a scoped variable
#[derive(Debug, Eq, PartialEq)]
pub struct ScopedVariable {
    pub scope: Box<Expression>,
    pub name: Identifier,
}

impl From<ScopedVariable> for Variable {
    fn from(variable: ScopedVariable) -> Variable {
        Variable::Scoped(variable)
    }
}

impl DisplayWithContext for ScopedVariable {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(
            f,
            "{}.{}",
            self.scope.display_with(ctx),
            self.name.display_with(ctx),
        )
    }
}

/// A reference to a global or local variable
#[derive(Debug, Eq, PartialEq)]
pub struct UnscopedVariable {
    pub name: Identifier,
}

impl From<UnscopedVariable> for Variable {
    fn from(variable: UnscopedVariable) -> Variable {
        Variable::Unscoped(variable)
    }
}

impl From<Identifier> for Variable {
    fn from(name: Identifier) -> Variable {
        UnscopedVariable { name }.into()
    }
}

impl DisplayWithContext for UnscopedVariable {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(f, "{}", self.name.display_with(ctx))
    }
}

/// An expression that can appear in a graph DSL file
#[derive(Debug, Eq, PartialEq)]
pub enum Expression {
    // Literals
    FalseLiteral,
    NullLiteral,
    TrueLiteral,
    // Constants
    IntegerConstant(IntegerConstant),
    StringConstant(StringConstant),
    // Comprehensions
    List(ListComprehension),
    Set(SetComprehension),
    // Syntax nodes
    Capture(Capture),
    // Variables
    Variable(Variable),
    // Functions
    Call(Call),
    // Regular expression
    RegexCapture(RegexCapture),
}

impl DisplayWithContext for Expression {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        match self {
            Expression::FalseLiteral => write!(f, "false"),
            Expression::NullLiteral => write!(f, "#null"),
            Expression::TrueLiteral => write!(f, "true"),
            Expression::IntegerConstant(expr) => expr.fmt(f, ctx),
            Expression::StringConstant(expr) => expr.fmt(f, ctx),
            Expression::List(expr) => expr.fmt(f, ctx),
            Expression::Set(expr) => expr.fmt(f, ctx),
            Expression::Capture(expr) => expr.fmt(f, ctx),
            Expression::Variable(expr) => expr.fmt(f, ctx),
            Expression::Call(expr) => expr.fmt(f, ctx),
            Expression::RegexCapture(expr) => expr.fmt(f, ctx),
        }
    }
}

/// A function call
#[derive(Debug, Eq, PartialEq)]
pub struct Call {
    pub function: Identifier,
    pub parameters: Vec<Expression>,
}

impl From<Call> for Expression {
    fn from(expr: Call) -> Expression {
        Expression::Call(expr)
    }
}

impl DisplayWithContext for Call {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(f, "({}", self.function.display_with(ctx))?;
        for arg in &self.parameters {
            write!(f, " {}", arg.display_with(ctx))?;
        }
        write!(f, ")")
    }
}

/// A capture expression that references a syntax node
#[derive(Debug, Eq, PartialEq)]
pub struct Capture {
    /// The index of this capture in the block's tree-sitter query
    pub index: usize,
    /// The name of the capture
    pub name: Identifier,
}

impl From<Capture> for Expression {
    fn from(expr: Capture) -> Expression {
        Expression::Capture(expr)
    }
}

impl DisplayWithContext for Capture {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(f, "{}", self.name.display_with(ctx))
    }
}

/// An integer constant
#[derive(Debug, Eq, PartialEq)]
pub struct IntegerConstant {
    pub value: u32,
}

impl From<IntegerConstant> for Expression {
    fn from(expr: IntegerConstant) -> Expression {
        Expression::IntegerConstant(expr)
    }
}

impl DisplayWithContext for IntegerConstant {
    fn fmt(&self, f: &mut fmt::Formatter, _ctx: &Context) -> fmt::Result {
        write!(f, "{}", self.value)
    }
}

/// An ordered list of values
#[derive(Debug, Eq, PartialEq)]
pub struct ListComprehension {
    pub elements: Vec<Expression>,
}

impl From<ListComprehension> for Expression {
    fn from(expr: ListComprehension) -> Expression {
        Expression::List(expr)
    }
}

impl DisplayWithContext for ListComprehension {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(f, "[")?;
        let mut first = true;
        for elem in &self.elements {
            if first {
                write!(f, "{}", elem.display_with(ctx))?;
                first = false;
            } else {
                write!(f, ", {}", elem.display_with(ctx))?;
            }
        }
        write!(f, "]")
    }
}

/// A reference to one of the regex captures in a `scan` statement
#[derive(Debug, Eq, PartialEq)]
pub struct RegexCapture {
    pub match_index: usize,
}

impl From<RegexCapture> for Expression {
    fn from(expr: RegexCapture) -> Expression {
        Expression::RegexCapture(expr)
    }
}

impl DisplayWithContext for RegexCapture {
    fn fmt(&self, f: &mut fmt::Formatter, _ctx: &Context) -> fmt::Result {
        write!(f, "${}", self.match_index)
    }
}

/// An unordered set of values
#[derive(Debug, Eq, PartialEq)]
pub struct SetComprehension {
    pub elements: Vec<Expression>,
}

impl From<SetComprehension> for Expression {
    fn from(expr: SetComprehension) -> Expression {
        Expression::Set(expr)
    }
}

impl DisplayWithContext for SetComprehension {
    fn fmt(&self, f: &mut fmt::Formatter, ctx: &Context) -> fmt::Result {
        write!(f, "{{")?;
        let mut first = true;
        for elem in &self.elements {
            if first {
                write!(f, "{}", elem.display_with(ctx))?;
                first = false;
            } else {
                write!(f, ", {}", elem.display_with(ctx))?;
            }
        }
        write!(f, "}}")
    }
}

/// A string constant
#[derive(Debug, Eq, PartialEq)]
pub struct StringConstant {
    pub value: String,
}

impl From<StringConstant> for Expression {
    fn from(expr: StringConstant) -> Expression {
        Expression::StringConstant(expr)
    }
}

impl DisplayWithContext for StringConstant {
    fn fmt(&self, f: &mut fmt::Formatter, _ctx: &Context) -> fmt::Result {
        write!(f, "{:?}", self.value)
    }
}

impl From<String> for Expression {
    fn from(value: String) -> Expression {
        Expression::StringConstant(StringConstant { value }.into())
    }
}

impl From<Identifier> for Expression {
    fn from(name: Identifier) -> Expression {
        Expression::Variable(UnscopedVariable { name }.into())
    }
}

impl From<ScopedVariable> for Expression {
    fn from(variable: ScopedVariable) -> Expression {
        Expression::Variable(variable.into())
    }
}