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
//! Basic Ast components
use enumflags2::bitflags;
use itertools::Itertools;
use ustr::Ustr;
pub type Span = std::ops::Range<usize>;
#[derive(Clone, Debug)]
pub struct SymbolSpan {
    pub name: Ustr,
    pub span: Span,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Path {
    pub names: Vec<Ustr>,
    pub spans: Vec<Span>,
}

impl Path {
    pub fn append(&self, arg: &SymbolSpan) -> Path {
        let mut new = self.clone();
        new.names.push(arg.name);
        new.spans.push(arg.span.clone());
        new
    }
    pub fn len(&self) -> usize {
        self.names.len()
    }
    pub fn range(&self) -> Span {
        if !self.spans.is_empty() {
            self.spans[0].start..self.spans.last().unwrap().end
        } else {
            0..0
        }
    }
    pub fn segment(&self, offset: usize) -> usize {
        self.spans
            .iter()
            .take_while(|i| i.start < offset)
            .count()
            .saturating_sub(1)
    }
    pub fn to_string(&self) -> String {
        self.names.iter().map(|i| i.as_str()).join(".")
    }
    pub fn relative_path(&self) -> String {
        let mut path = self.names.iter().map(|i| i.as_str()).join("/");
        path.push_str(".uvl");
        path
    }
}

/// Type definitions for symbols
#[bitflags]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Type {
    String,
    Real,
    Vector,
    Attributes,
    Bool,
    Void,
    Namespace,
    Object,
}

#[derive(Clone, Debug)]
pub enum GroupMode {
    Or,
    Alternative,
    Optional,
    Mandatory,
    Cardinality(Cardinality),
}
#[derive(Clone, Debug)]
pub enum Cardinality {
    Range(usize, usize),
    Fixed,
}
#[derive(Clone, Debug)]
pub enum LanguageLevelMajor {
    Boolean,
    Arithmetic,
    Type,
}
#[derive(Clone, Debug, PartialEq)]
pub enum LanguageLevelArithmetic {
    Any,
    FeatureCardinality,
    Aggregate,
}
#[derive(Clone, Debug, PartialEq)]
pub enum LanguageLevelBoolean {
    Any,
    GroupCardinality,
}
#[derive(Clone, Debug, PartialEq)]
pub enum LanguageLevelType {
    Any,
    NumericConstraints,
    StringConstraints,
}
#[derive(Clone, Debug)]
pub enum LanguageLevel {
    Boolean(Vec<LanguageLevelBoolean>),
    Arithmetic(Vec<LanguageLevelArithmetic>),
    Type(Vec<LanguageLevelType>),
}

#[derive(Clone, Debug)]
pub struct LanguageLevelDecl {
    pub lang_lvl: LanguageLevel,
    pub span: Span,
}
#[derive(Clone, Debug)]
pub struct Feature {
    pub name: SymbolSpan,
    pub cardinality: Option<Cardinality>,
    pub ty: Type,
    pub duplicate: bool,
    pub first_cardinality_child: bool, // used to fix same name problem
}
#[derive(Clone, Debug)]
pub struct Import {
    pub path: Path,
    pub alias: Option<SymbolSpan>,
}
#[derive(Clone, Debug)]
pub struct Namespace {
    pub prefix: Path,
}
#[derive(Clone, Debug)]
pub struct Group {
    pub mode: GroupMode,
    pub span: Span,
}
#[derive(Clone, Debug)]
pub struct Reference {
    pub path: Path,
}
#[derive(Clone, Debug)]
pub struct Attribute {
    pub name: SymbolSpan,
    pub value: ValueDecl,
    pub depth: u32,
    pub duplicate: bool,
}
#[derive(Clone, Debug)]
pub struct Keyword {
    pub name: Ustr,
    pub span: Span,
}
#[derive(Clone, Debug)]
pub struct Dir {
    pub name: Ustr,
    pub depth: u32,
}

#[derive(Clone, Debug)]
pub enum Value {
    Void,
    Number(f64),
    String(String),
    Vector,
    Bool(bool),
    Attributes,
}

#[derive(Clone, Debug)]
pub struct ValueDecl {
    pub value: Value,
    pub span: Span,
}

impl Default for Value {
    fn default() -> Self {
        Value::Void
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NumericOP {
    Add,
    Sub,
    Div,
    Mul,
}

impl NumericOP {
    pub fn parse(op: &str) -> Option<Self> {
        match op {
            "+" => Some(NumericOP::Add),
            "-" => Some(NumericOP::Sub),
            "*" => Some(NumericOP::Mul),
            "/" => Some(NumericOP::Div),
            _ => None,
        }
    }
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LogicOP {
    And,
    Or,
    Implies,
    Equiv,
}

#[derive(Clone, Debug)]
pub enum AggregateOP {
    Avg,
    Sum,
}

#[derive(Clone, Debug)]
pub enum IntegerOP {
    Floor,
    Ceil,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EquationOP {
    Greater,
    Smaller,
    Equal,
}

#[derive(Clone, Debug)]
pub enum Constraint {
    Constant(bool),
    Equation {
        op: EquationOP,
        lhs: Box<ExprDecl>,
        rhs: Box<ExprDecl>,
    },
    Logic {
        op: LogicOP,
        lhs: Box<ConstraintDecl>,
        rhs: Box<ConstraintDecl>,
    },
    Ref(Symbol),
    Not(Box<ConstraintDecl>),
}

#[derive(Clone, Debug)]
pub struct ConstraintDecl {
    pub content: Constraint,
    pub span: Span,
}

#[derive(Clone, Debug)]
pub enum Expr {
    Number(f64),
    String(String),
    Ref(Symbol),
    Binary {
        op: NumericOP,
        rhs: Box<ExprDecl>,
        lhs: Box<ExprDecl>,
    },
    Aggregate {
        op: AggregateOP,
        context: Option<Symbol>,
        query: Path,
    },
    Integer {
        op: IntegerOP,
        n: Box<ExprDecl>,
    },
    Len(Box<ExprDecl>),
}
#[derive(Clone, Debug)]
pub struct ExprDecl {
    pub content: Expr,
    pub span: Span,
}
/// A symbol represents an entity in some uvl document
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, enum_kinds::EnumKind)]
#[enum_kind(SymbolKind, derive(Hash))]
pub enum Symbol {
    Keyword(usize),
    Feature(usize),
    Constraint(usize),
    Attribute(usize),
    Reference(usize),
    Group(usize),
    Import(usize),
    LangLvl(usize),
    Dir(usize),
    Root,
}
impl Symbol {
    pub fn offset(&self) -> usize {
        match self {
            Self::Feature(id)
            | Self::Constraint(id)
            | Self::Attribute(id)
            | Self::Reference(id)
            | Self::Group(id)
            | Self::LangLvl(id)
            | Self::Dir(id)
            | Self::Import(id) => *id,
            _ => panic!(),
        }
    }
}