shulkerscript 0.1.0

Shulkerscript language implementation with compiler
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
432
433
434
435
436
437
438
439
440
441
442
443
//! Syntax tree nodes for conditions.

#![allow(clippy::missing_errors_doc)]

use std::{cmp::Ordering, collections::VecDeque};

use enum_as_inner::EnumAsInner;
use getset::Getters;

use crate::{
    base::{
        self,
        source_file::{SourceElement, Span},
        Handler, VoidHandler,
    },
    lexical::{
        token::{Punctuation, StringLiteral, Token},
        token_stream::Delimiter,
    },
    syntax::{
        error::{Error, ParseResult, SyntaxKind, UnexpectedSyntax},
        parser::{Parser, Reading},
    },
};

/// Condition that is viewed as a single entity during precedence parsing.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// PrimaryCondition:
///     UnaryCondition
///     | ParenthesizedCondition
///     | StringLiteral
/// ```
#[allow(missing_docs)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EnumAsInner)]
pub enum PrimaryCondition {
    Unary(UnaryCondition),
    Parenthesized(ParenthesizedCondition),
    StringLiteral(StringLiteral),
}

impl SourceElement for PrimaryCondition {
    fn span(&self) -> Span {
        match self {
            Self::Unary(unary) => unary.span(),
            Self::Parenthesized(parenthesized) => parenthesized.span(),
            Self::StringLiteral(literal) => literal.span(),
        }
    }
}

/// Condition that is composed of two conditions and a binary operator.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// BinaryCondition:
///     Condition ConditionalBinaryOperator Condition
///     ;
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
pub struct BinaryCondition {
    /// The left operand of the binary condition.
    #[get = "pub"]
    left_operand: Box<Condition>,
    /// The operator of the binary condition.
    #[get = "pub"]
    operator: ConditionalBinaryOperator,
    /// The right operand of the binary condition.
    #[get = "pub"]
    right_operand: Box<Condition>,
}

impl SourceElement for BinaryCondition {
    fn span(&self) -> Span {
        self.left_operand
            .span()
            .join(&self.right_operand.span())
            .unwrap()
    }
}

impl BinaryCondition {
    /// Dissolves the binary condition into its components
    #[must_use]
    pub fn dissolve(self) -> (Condition, ConditionalBinaryOperator, Condition) {
        (*self.left_operand, self.operator, *self.right_operand)
    }
}

/// Operator that is used to combine two conditions.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// ConditionalBinaryOperator:
///     '&&'
///     | '||'
///     ;
/// ```
#[allow(missing_docs)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EnumAsInner)]
pub enum ConditionalBinaryOperator {
    LogicalAnd(Punctuation, Punctuation),
    LogicalOr(Punctuation, Punctuation),
}

impl ConditionalBinaryOperator {
    /// Gets the precedence of the operator (the higher the number, the first it will be evaluated)
    ///
    /// The least operator has precedence 1.
    #[must_use]
    pub fn get_precedence(&self) -> u8 {
        match self {
            Self::LogicalOr(..) => 1,
            Self::LogicalAnd(..) => 2,
        }
    }
}

impl SourceElement for ConditionalBinaryOperator {
    fn span(&self) -> Span {
        match self {
            Self::LogicalAnd(a, b) | Self::LogicalOr(a, b) => a
                .span
                .join(&b.span)
                .expect("Invalid tokens for ConditionalBinaryOperator"),
        }
    }
}

/// Condition that is enclosed in parentheses.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// ParenthesizedCondition:
///    '(' Condition ')';
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
pub struct ParenthesizedCondition {
    /// The opening parenthesis.
    #[get = "pub"]
    pub open_paren: Punctuation,
    /// The condition within the parenthesis.
    #[get = "pub"]
    pub condition: Box<Condition>,
    /// The closing parenthesis.
    #[get = "pub"]
    pub close_paren: Punctuation,
}

impl ParenthesizedCondition {
    /// Dissolves the parenthesized condition into its components
    #[must_use]
    pub fn dissolve(self) -> (Punctuation, Condition, Punctuation) {
        (self.open_paren, *self.condition, self.close_paren)
    }
}

impl SourceElement for ParenthesizedCondition {
    fn span(&self) -> Span {
        self.open_paren
            .span()
            .join(&self.close_paren.span())
            .expect("The span of the parenthesis is invalid.")
    }
}

/// Operator that is used to prefix a condition.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// ConditionalPrefixOperator: '!';
/// ```
#[allow(missing_docs)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EnumAsInner)]
pub enum ConditionalPrefixOperator {
    LogicalNot(Punctuation),
}

impl SourceElement for ConditionalPrefixOperator {
    fn span(&self) -> Span {
        match self {
            Self::LogicalNot(token) => token.span.clone(),
        }
    }
}

/// Condition that is prefixed by an operator.
///
/// Syntax Synopsis:
///
/// ```ebnf
/// UnaryCondition:
///     ConditionalPrefixOperator PrimaryCondition
///     ;
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
pub struct UnaryCondition {
    /// The operator of the prefix.
    #[get = "pub"]
    operator: ConditionalPrefixOperator,
    /// The operand of the prefix.
    #[get = "pub"]
    operand: Box<PrimaryCondition>,
}

impl SourceElement for UnaryCondition {
    fn span(&self) -> Span {
        self.operator.span().join(&self.operand.span()).unwrap()
    }
}
impl UnaryCondition {
    /// Dissolves the conditional prefix into its components
    #[must_use]
    pub fn dissolve(self) -> (ConditionalPrefixOperator, PrimaryCondition) {
        (self.operator, *self.operand)
    }
}

/// Represents a condition in the syntax tree.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// Condition:
///     PrimaryCondition
///     | BinaryCondition
///     ;
/// ```
#[allow(missing_docs)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, EnumAsInner)]
pub enum Condition {
    Primary(PrimaryCondition),
    Binary(BinaryCondition),
}

impl SourceElement for Condition {
    fn span(&self) -> Span {
        match self {
            Self::Primary(primary) => primary.span(),
            Self::Binary(binary) => binary.span(),
        }
    }
}

impl<'a> Parser<'a> {
    /// Parses a [`Condition`].
    ///
    /// # Precedence of the operators
    /// 1. `!`
    /// 2. `&&`
    /// 3. `||`
    pub fn parse_condition(
        &mut self,
        handler: &impl Handler<base::Error>,
    ) -> ParseResult<Condition> {
        let mut lhs = Condition::Primary(self.parse_primary_condition(handler)?);
        let mut expressions = VecDeque::new();

        // Parses a list of binary operators and expressions
        while let Ok(binary_operator) = self.try_parse_conditional_binary_operator() {
            expressions.push_back((
                binary_operator,
                Some(Condition::Primary(self.parse_primary_condition(handler)?)),
            ));
        }

        let mut candidate_index = 0;
        let mut current_precedence;

        while !expressions.is_empty() {
            // reset precedence
            current_precedence = 0;

            for (index, (binary_op, _)) in expressions.iter().enumerate() {
                let new_precedence = binary_op.get_precedence();
                match new_precedence.cmp(&current_precedence) {
                    // Clear the candidate indices and set the current precedence to the
                    // precedence of the current binary operator.
                    Ordering::Greater => {
                        current_precedence = new_precedence;
                        candidate_index = index;
                    }

                    Ordering::Less | Ordering::Equal => (),
                }
            }

            // ASSUMPTION: The assignments have 1 precedence and are right associative.
            assert!(current_precedence > 0);

            if candidate_index == 0 {
                let (binary_op, rhs) = expressions.pop_front().expect("No binary operator found");

                // fold the first expression
                lhs = Condition::Binary(BinaryCondition {
                    left_operand: Box::new(lhs),
                    operator: binary_op,
                    right_operand: Box::new(rhs.unwrap()),
                });
            } else {
                let (binary_op, rhs) = expressions
                    .remove(candidate_index)
                    .expect("No binary operator found");

                // fold the expression at candidate_index
                expressions[candidate_index - 1].1 = Some(Condition::Binary(BinaryCondition {
                    left_operand: Box::new(expressions[candidate_index - 1].1.take().unwrap()),
                    operator: binary_op,
                    right_operand: Box::new(rhs.unwrap()),
                }));
            }
        }

        Ok(lhs)
    }

    /// Parses a [`PrimaryCondition`].
    pub fn parse_primary_condition(
        &mut self,
        handler: &impl Handler<base::Error>,
    ) -> ParseResult<PrimaryCondition> {
        match self.stop_at_significant() {
            // prefixed expression
            Reading::Atomic(Token::Punctuation(punc)) if punc.punctuation == '!' => {
                // eat prefix operator
                self.forward();

                let operator = match punc.punctuation {
                    '!' => ConditionalPrefixOperator::LogicalNot(punc),
                    _ => unreachable!(),
                };

                let operand = Box::new(self.parse_primary_condition(handler)?);

                Ok(PrimaryCondition::Unary(UnaryCondition {
                    operator,
                    operand,
                }))
            }

            // string literal
            Reading::Atomic(Token::StringLiteral(literal)) => {
                self.forward();
                Ok(PrimaryCondition::StringLiteral(literal))
            }

            // parenthesized condition
            Reading::IntoDelimited(punc) if punc.punctuation == '(' => self
                .parse_parenthesized_condition(handler)
                .map(PrimaryCondition::Parenthesized),

            unexpected => {
                // make progress
                self.forward();

                let err = Error::UnexpectedSyntax(UnexpectedSyntax {
                    expected: SyntaxKind::Either(&[
                        SyntaxKind::Punctuation('!'),
                        SyntaxKind::StringLiteral,
                        SyntaxKind::Punctuation('('),
                    ]),
                    found: unexpected.into_token(),
                });
                handler.receive(err.clone());

                Err(err)
            }
        }
    }

    /// Parses a [`ParenthesizedCondition`].
    pub fn parse_parenthesized_condition(
        &mut self,
        handler: &impl Handler<base::Error>,
    ) -> ParseResult<ParenthesizedCondition> {
        let token_tree = self.step_into(
            Delimiter::Parenthesis,
            |parser| {
                let cond = parser.parse_condition(handler)?;
                parser.stop_at_significant();
                Ok(cond)
            },
            handler,
        )?;

        Ok(ParenthesizedCondition {
            open_paren: token_tree.open,
            condition: Box::new(token_tree.tree?),
            close_paren: token_tree.close,
        })
    }

    fn try_parse_conditional_binary_operator(&mut self) -> ParseResult<ConditionalBinaryOperator> {
        self.try_parse(|parser| match parser.next_significant_token() {
            Reading::Atomic(token) => match token.clone() {
                Token::Punctuation(punc) => match punc.punctuation {
                    '&' => {
                        let b = parser.parse_punctuation('&', false, &VoidHandler)?;
                        Ok(ConditionalBinaryOperator::LogicalAnd(punc, b))
                    }
                    '|' => {
                        let b = parser.parse_punctuation('|', false, &VoidHandler)?;
                        Ok(ConditionalBinaryOperator::LogicalOr(punc, b))
                    }
                    _ => Err(Error::UnexpectedSyntax(UnexpectedSyntax {
                        expected: SyntaxKind::Either(&[
                            SyntaxKind::Punctuation('&'),
                            SyntaxKind::Punctuation('|'),
                        ]),
                        found: Some(token),
                    })),
                },
                unexpected => Err(Error::UnexpectedSyntax(UnexpectedSyntax {
                    expected: SyntaxKind::Either(&[
                        SyntaxKind::Punctuation('&'),
                        SyntaxKind::Punctuation('|'),
                    ]),
                    found: Some(unexpected),
                })),
            },
            unexpected => Err(Error::UnexpectedSyntax(UnexpectedSyntax {
                expected: SyntaxKind::Either(&[
                    SyntaxKind::Punctuation('&'),
                    SyntaxKind::Punctuation('|'),
                ]),
                found: unexpected.into_token(),
            })),
        })
    }
}