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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
// -*- 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::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use tree_sitter::CaptureQuantifier;
use tree_sitter::Language;
use tree_sitter::Query;

use crate::parser::Range;
use crate::Identifier;
use crate::Location;

/// A graph DSL file
#[derive(Debug)]
pub struct File {
    pub language: Language,
    /// The expected global variables used in this file
    pub globals: Vec<Global>,
    /// The scoped variables that are inherited by child nodes
    pub inherited_variables: HashSet<Identifier>,
    /// The combined query of all stanzas in the file
    pub query: Option<Query>,
    /// The list of stanzas in the file
    pub stanzas: Vec<Stanza>,
    /// Attribute shorthands defined in the file
    pub shorthands: AttributeShorthands,
}

impl File {
    pub fn new(language: Language) -> File {
        File {
            language,
            globals: Vec::new(),
            inherited_variables: HashSet::new(),
            query: None,
            stanzas: Vec::new(),
            shorthands: AttributeShorthands::new(),
        }
    }
}

/// A global variable
#[derive(Debug, Eq, PartialEq)]
pub struct Global {
    /// The name of the global variable
    pub name: Identifier,
    /// The quantifier of the global variable
    pub quantifier: CaptureQuantifier,
    /// Default value
    pub default: Option<String>,
    pub location: Location,
}

/// 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>,
    /// Capture index of the full match in the stanza query
    pub full_match_stanza_capture_index: usize,
    /// Capture index of the full match in the file query
    pub full_match_file_capture_index: usize,
    pub range: Range,
}

/// 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),
    // If
    If(If),
    // ForIn
    ForIn(ForIn),
}

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

/// 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 std::fmt::Display for AddEdgeAttribute {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "attr ({} -> {})", self.source, self.sink)?;
        for attr in &self.attributes {
            write!(f, " {}", attr)?;
        }
        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 std::fmt::Display for AddGraphNodeAttribute {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "attr ({})", self.node)?;
        for attr in &self.attributes {
            write!(f, " {}", attr)?;
        }
        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 std::fmt::Display for Assign {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "set {} = {} at {}",
            self.variable, self.value, self.location,
        )
    }
}

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

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

/// 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 std::fmt::Display for CreateEdge {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "edge {} -> {} at {}",
            self.source, self.sink, 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 std::fmt::Display for CreateGraphNode {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "node {} at {}", self.node, 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 std::fmt::Display for DeclareImmutable {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "let {} = {} at {}",
            self.variable, self.value, 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 std::fmt::Display for DeclareMutable {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "var {} = {} at {}",
            self.variable, self.value, 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 std::fmt::Display for Print {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "print")?;
        for val in &self.values {
            write!(f, " {},", val)?;
        }
        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 std::fmt::Display for Scan {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "scan {} {{ ... }} at {}", self.value, 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 std::fmt::Display for ScanArm {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?} {{ ... }}", self.regex.as_str())
    }
}

/// A `cond` conditional statement that selects the first branch with a matching condition
#[derive(Debug, Eq, PartialEq)]
pub struct If {
    pub arms: Vec<IfArm>,
    pub location: Location,
}

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

impl std::fmt::Display for If {
    fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
        let mut first = true;
        for arm in &self.arms {
            if first {
                first = false;
                write!(f, "if {} {{ ... }}", DisplayConditions(&arm.conditions))?;
            } else {
                if !arm.conditions.is_empty() {
                    write!(f, " elif {} {{ ... }}", DisplayConditions(&arm.conditions))?;
                } else {
                    write!(f, " else {{ ... }}")?;
                }
            }
        }
        write!(f, " at {}", self.location)
    }
}

/// One arm of a `cond` statement
#[derive(Debug, PartialEq, Eq)]
pub struct IfArm {
    pub conditions: Vec<Condition>,
    pub statements: Vec<Statement>,
    pub location: Location,
}

struct DisplayConditions<'a>(&'a Vec<Condition>);

#[derive(Debug, PartialEq, Eq)]
pub enum Condition {
    Some {
        value: Expression,
        location: Location,
    },
    None {
        value: Expression,
        location: Location,
    },
    Bool {
        value: Expression,
        location: Location,
    },
}

impl std::fmt::Display for DisplayConditions<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
        let mut first = true;
        for condition in self.0.iter() {
            if first {
                first = false;
                write!(f, "{}", condition)?;
            } else {
                write!(f, ", {}", condition)?;
            }
        }
        Ok(())
    }
}

impl std::fmt::Display for Condition {
    fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
        match self {
            Condition::Some { value, .. } => {
                write!(f, "some {}", value)
            }
            Condition::None { value, .. } => {
                write!(f, "none {}", value)
            }
            Condition::Bool { value, .. } => {
                write!(f, "{}", value)
            }
        }
    }
}

/// A `for in` statement
#[derive(Debug, Eq, PartialEq)]
pub struct ForIn {
    pub variable: UnscopedVariable,
    pub value: Expression,
    pub statements: Vec<Statement>,
    pub location: Location,
}

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

impl std::fmt::Display for ForIn {
    fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "for {} in {} {{ ... }} at {}",
            self.variable, self.value, self.location,
        )
    }
}

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

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

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

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

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

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

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

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

/// 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),
    // Literals
    ListLiteral(ListLiteral),
    SetLiteral(SetLiteral),
    // Comprehensions
    ListComprehension(ListComprehension),
    SetComprehension(SetComprehension),
    // Syntax nodes
    Capture(Capture),
    // Variables
    Variable(Variable),
    // Functions
    Call(Call),
    // Regular expression
    RegexCapture(RegexCapture),
}

impl std::fmt::Display for Expression {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::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),
            Expression::StringConstant(expr) => expr.fmt(f),
            Expression::ListLiteral(expr) => expr.fmt(f),
            Expression::SetLiteral(expr) => expr.fmt(f),
            Expression::ListComprehension(expr) => expr.fmt(f),
            Expression::SetComprehension(expr) => expr.fmt(f),
            Expression::Capture(expr) => expr.fmt(f),
            Expression::Variable(expr) => expr.fmt(f),
            Expression::Call(expr) => expr.fmt(f),
            Expression::RegexCapture(expr) => expr.fmt(f),
        }
    }
}

/// 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 std::fmt::Display for Call {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "({}", self.function)?;
        for arg in &self.parameters {
            write!(f, " {}", arg)?;
        }
        write!(f, ")")
    }
}

/// A capture expression that references a syntax node
#[derive(Debug, Eq, PartialEq)]
pub struct Capture {
    /// The name of the capture
    pub name: Identifier,
    /// The suffix of the capture
    pub quantifier: CaptureQuantifier,
    /// Capture index in the merged file query
    pub file_capture_index: usize,
    /// Capture index in the stanza query
    pub stanza_capture_index: usize,
    pub location: Location,
}

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

impl std::fmt::Display for Capture {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "@{}", self.name)
    }
}

/// 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 std::fmt::Display for IntegerConstant {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.value)
    }
}

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

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

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

/// An list comprehension
#[derive(Debug, Eq, PartialEq)]
pub struct ListComprehension {
    pub element: Box<Expression>,
    pub variable: UnscopedVariable,
    pub value: Box<Expression>,
    pub location: Location,
}

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

impl std::fmt::Display for ListComprehension {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "[ {} for {} in {} ]",
            self.element, self.variable, self.value
        )
    }
}

/// 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 std::fmt::Display for RegexCapture {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "${}", self.match_index)
    }
}

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

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

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

/// An set comprehension
#[derive(Debug, Eq, PartialEq)]
pub struct SetComprehension {
    pub element: Box<Expression>,
    pub variable: UnscopedVariable,
    pub value: Box<Expression>,
    pub location: Location,
}

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

impl std::fmt::Display for SetComprehension {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{{ {} for {} in {} }}",
            self.element, self.variable, self.value
        )
    }
}

/// 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 std::fmt::Display for StringConstant {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self.value)
    }
}

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

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

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

/// Attribute shorthands
#[derive(Debug, Eq, PartialEq)]
pub struct AttributeShorthands(HashMap<Identifier, AttributeShorthand>);

impl AttributeShorthands {
    pub fn new() -> Self {
        Self(HashMap::new())
    }

    pub fn get(&self, name: &Identifier) -> Option<&AttributeShorthand> {
        self.0.get(name)
    }

    pub fn add(&mut self, shorthand: AttributeShorthand) {
        self.0.insert(shorthand.name.clone(), shorthand);
    }

    pub fn iter(&self) -> impl Iterator<Item = &AttributeShorthand> {
        self.0.values()
    }

    pub fn into_iter(self) -> impl Iterator<Item = AttributeShorthand> {
        self.0.into_values()
    }
}

/// An attribute shorthand
#[derive(Debug, Eq, PartialEq)]
pub struct AttributeShorthand {
    pub name: Identifier,
    pub variable: UnscopedVariable,
    pub attributes: Vec<Attribute>,
    pub location: Location,
}

impl std::fmt::Display for AttributeShorthand {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "attribute {} = {} =>", self.name, self.variable,)?;
        for attr in &self.attributes {
            write!(f, " {}", attr)?;
        }
        write!(f, " at {}", self.location)
    }
}