microcad-lang-parse 0.5.0

µcad language syntax lexer and parser
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
// Copyright © 2026 The µcad authors <info@microcad.xyz>
// SPDX-License-Identifier: AGPL-3.0-or-later

use crate::ast;
use crate::ast::Span;
use std::num::ParseIntError;

/// An operator for binary operators, together with a span
#[derive(Debug, PartialEq)]
pub struct BinaryOperator {
    /// The source span for the operator
    pub span: Span,
    /// The type of the operator
    pub operation: BinaryOperatorType,
}

/// The type of the operator for binary operations
#[derive(Debug, PartialEq, Clone)]
#[allow(missing_docs)]
pub enum BinaryOperatorType {
    Add,
    Subtract,
    Multiply,
    Divide,
    Union,
    Intersect,
    PowerXor,
    GreaterThan,
    LessThan,
    GreaterEqual,
    LessEqual,
    Equal,
    Near,
    NotEqual,
    And,
    Or,
    Xor,
}

impl BinaryOperatorType {
    /// Get the symbolic representation for the operator
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Add => "+",
            Self::Subtract => "-",
            Self::Multiply => "*",
            Self::Divide => "/",
            Self::Union => "|",
            Self::Intersect => "&",
            Self::PowerXor => "^",
            Self::GreaterThan => ">",
            Self::LessThan => "<",
            Self::GreaterEqual => "",
            Self::LessEqual => "",
            Self::Equal => "==",
            Self::Near => "~",
            Self::NotEqual => "!=",
            Self::And => "&",
            Self::Or => "|",
            Self::Xor => "^",
        }
    }
}

/// An operator for unary operators, together with a span
#[derive(Debug, PartialEq)]
pub struct UnaryOperator {
    /// The source span for the unary operator
    pub span: Span,
    /// The type of the unary operator
    pub operation: UnaryOperatorType,
}

/// The type of the operator for unary operations
#[derive(Debug, PartialEq, Clone)]
#[allow(missing_docs)]
pub enum UnaryOperatorType {
    Minus,
    Plus,
    Not,
}

impl UnaryOperatorType {
    /// Get the symbolic representation for the operator
    pub fn as_str(&self) -> &'static str {
        match self {
            UnaryOperatorType::Minus => "-",
            UnaryOperatorType::Plus => "+",
            UnaryOperatorType::Not => "!",
        }
    }
}

/// Any expression.
#[derive(Debug, PartialEq)]
pub enum Expression {
    /// A literal: `42mm`
    Literal(ast::Literal),
    /// Something in `()` brackets: `(42mm)`
    Bracketed(Box<Expression>, Span),
    /// A tuple: `(a = 1, b = 23)`
    Tuple(TupleExpression),
    /// A range expression: `[1..4]`
    ArrayRange(ArrayRangeExpression),
    /// A list expression: `[1, 2, 3]`
    ArrayList(ArrayListExpression),
    /// A format string: `"We have {n} items"`
    String(FormatString),
    /// A qualified name: `foo::bar::baz`
    QualifiedName(QualifiedName),
    /// A marker expression: `@input`
    Marker(ast::Identifier),
    /// A binary operation: `1 + 3`
    BinaryOperation(BinaryOperation),
    /// A unary operation: `-2`
    UnaryOperation(UnaryOperation),
    /// A body expression containing statements: `{ ... }`
    Body(ast::Body),
    /// A call: `call::me(1, 2, 3)`
    Call(Call),
    /// Accessing an element: `.foo`, `.rotate()`, `#attr`, `[1]`
    ElementAccess(ElementAccess),
    /// An if expression: `if a == b { ... } else { ... }`
    If(If),
    /// Any occurred during parsing
    Error(Span),
}

impl Expression {
    /// Get the source span for the identifier
    pub fn span(&self) -> Span {
        match self {
            Expression::Literal(ex) => ex.span.clone(),
            Expression::Bracketed(_, span) => span.clone(),
            Expression::Tuple(ex) => ex.span.clone(),
            Expression::ArrayRange(ex) => ex.span.clone(),
            Expression::ArrayList(ex) => ex.span.clone(),
            Expression::String(ex) => ex.span.clone(),
            Expression::QualifiedName(ex) => ex.span.clone(),
            Expression::Marker(ex) => ex.span.clone(),
            Expression::BinaryOperation(ex) => ex.span.clone(),
            Expression::UnaryOperation(ex) => ex.span.clone(),
            Expression::Body(ex) => ex.span.clone(),
            Expression::Call(ex) => ex.span.clone(),
            Expression::ElementAccess(ex) => ex.span.clone(),
            Expression::If(ex) => ex.span.clone(),
            Expression::Error(span) => span.clone(),
        }
    }

    /// Can this expression also be used as a statement, without extra semicolon
    pub fn is_also_statement(&self) -> bool {
        matches!(self, Expression::Body(_) | Expression::If(_))
    }
}

/// A string containing a format expression
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct FormatString {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub parts: Vec<StringPart>,
}

/// A part of a [`FormatString`]
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub enum StringPart {
    Char(StringCharacter),
    Content(ast::StringLiteral),
    Expression(StringExpression),
}

/// A single character that is part of a [`FormatString`]
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct StringCharacter {
    pub span: Span,
    pub character: char,
}

/// A format expression that is part of a [`FormatString`]
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct StringExpression {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub expression: Box<Expression>,
    pub specification: Box<StringFormatSpecification>,
}

/// The format specification for a [`StringExpression`], specifying the width and precision for number formatting
///
/// All parts of the specification are optional
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct StringFormatSpecification {
    pub span: Span,
    pub precision: Option<Result<u32, (ParseIntError, Span)>>,
    pub width: Option<Result<u32, (ParseIntError, Span)>>,
}

impl StringFormatSpecification {
    /// Check if an part of the specification is specified
    pub fn is_some(&self) -> bool {
        self.precision.is_some() || self.width.is_some()
    }
}

/// An item that is part of a tuple expression
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct TupleItem {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub name: Option<ast::Identifier>,
    pub value: Expression,
}

impl ast::Dummy for TupleItem {
    fn dummy(span: Span) -> Self {
        Self {
            span: span.clone(),
            extras: ast::ItemExtras::default(),
            name: None,
            value: Expression::Error(span),
        }
    }
}

/// A tuple expression, a fixed size set of items that don't need to be the same type
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct TupleExpression {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub values: Vec<TupleItem>,
}

/// An array range, containing all values from the start value (inclusive) till then end value (exclusive)
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct ArrayRangeExpression {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub start: Box<ArrayItem>,
    pub end: Box<ArrayItem>,
    pub unit: Option<ast::Unit>,
}

/// An array specified as a list of items
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct ArrayListExpression {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub items: Vec<ArrayItem>,
    pub unit: Option<ast::Unit>,
}

/// An item that can be part of an array expression
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct ArrayItem {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub expression: Expression,
}

/// A qualified name, containing one or more [`Identifier`]s separated by `::`
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct QualifiedName {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub parts: Vec<ast::Identifier>,
}

/// A binary operation
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct BinaryOperation {
    pub span: Span,
    pub lhs: Box<Expression>,
    pub operation: BinaryOperator,
    pub rhs: Box<Expression>,
}

/// A unary operation
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct UnaryOperation {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub operation: UnaryOperator,
    pub rhs: Box<Expression>,
}

/// A function call
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct Call {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub name: QualifiedName,
    pub arguments: ArgumentList,
}

/// An expression that access an element from another expression.
///
/// Either accessing an array or tuple item, accessing an attribute of a value or a method call.
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct ElementAccess {
    pub span: Span,
    pub value: Box<Expression>,
    pub element_chain: Vec<Element>,
}

/// The possible element access types
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub enum ElementInner {
    Attribute(ast::Identifier),
    Tuple(ast::Identifier),
    Method(Call),
    ArrayElement(Box<Expression>),
}

#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct Element {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub inner: ElementInner,
}

#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct Body {
    pub span: Span,
    pub statements: ast::StatementList,
}

/// An if expression, can be used as either a statement or expression
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct If {
    pub span: Span,
    pub if_span: Span,
    pub extras: ast::ItemExtras,
    pub condition: Box<Expression>,
    pub body: Body,
    pub next_if_span: Option<Span>,
    pub next_if: Option<Box<If>>,
    pub else_span: Option<Span>,
    pub else_body: Option<Body>,
}

/// A list of arguments to a function call
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct ArgumentList {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub arguments: Vec<Argument>,
}

impl ast::Dummy for ArgumentList {
    fn dummy(span: Span) -> Self {
        Self {
            span,
            extras: ast::ItemExtras::default(),
            arguments: Vec::new(),
        }
    }
}

/// A function argument that is part of an [`ArgumentList`]
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub enum Argument {
    Unnamed(UnnamedArgument),
    Named(NamedArgument),
}

impl Argument {
    /// The name of the argument, if specified
    pub fn name(&self) -> Option<&ast::Identifier> {
        match self {
            Argument::Unnamed(_) => None,
            Argument::Named(arg) => Some(&arg.name),
        }
    }

    /// The value of the argument
    pub fn value(&self) -> &Expression {
        match self {
            Argument::Unnamed(arg) => &arg.value,
            Argument::Named(arg) => &arg.value,
        }
    }

    /// The span of the argument
    pub fn span(&self) -> &Span {
        match self {
            Argument::Unnamed(arg) => &arg.span,
            Argument::Named(arg) => &arg.span,
        }
    }
}

/// An argument without specified name
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct UnnamedArgument {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub value: Expression,
}

/// An argument with a specified name
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub struct NamedArgument {
    pub span: Span,
    pub extras: ast::ItemExtras,
    pub name: ast::Identifier,
    pub value: Expression,
}