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
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
//! Syntax tree nodes for declarations.

#![allow(missing_docs)]

use getset::Getters;

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

use super::{statement::Block, ConnectedList, DelimitedList};

/// Represents a declaration in the syntax tree.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// Declaration:
///    Function
///    | Import
///   ;
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Declaration {
    Function(Function),
    Import(Import),
    Tag(Tag),
}

impl SourceElement for Declaration {
    fn span(&self) -> Span {
        match self {
            Self::Function(function) => function.span(),
            Self::Import(import) => import.span(),
            Self::Tag(tag) => tag.span(),
        }
    }
}
/// Represents an Annotation with optional value.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// Annotation:
///     '#[' Identifier ('=' StringLiteral)? ']'
///     ;
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
pub struct Annotation {
    #[get = "pub"]
    pound_sign: Punctuation,
    #[get = "pub"]
    open_bracket: Punctuation,
    #[get = "pub"]
    identifier: Identifier,
    #[get = "pub"]
    value: Option<(Punctuation, StringLiteral)>,
    #[get = "pub"]
    close_bracket: Punctuation,
}

impl Annotation {
    /// Dissolves the [`Annotation`] into its components.
    #[must_use]
    pub fn dissolve(
        self,
    ) -> (
        Punctuation,
        Punctuation,
        Identifier,
        Option<(Punctuation, StringLiteral)>,
        Punctuation,
    ) {
        (
            self.pound_sign,
            self.open_bracket,
            self.identifier,
            self.value,
            self.close_bracket,
        )
    }
}
impl SourceElement for Annotation {
    fn span(&self) -> Span {
        self.pound_sign
            .span
            .join(&self.close_bracket.span())
            .unwrap()
    }
}

/// Represents a function declaration in the syntax tree.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// Function:
///     Annotation* 'pub'? 'fn' Identifier '(' ParameterList? ')' Block
///     ;
///
/// ParameterList:
///     Identifier (',' Identifier)* ','?  
///     ;
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
pub struct Function {
    #[get = "pub"]
    public_keyword: Option<Keyword>,
    #[get = "pub"]
    annotations: Vec<Annotation>,
    #[get = "pub"]
    function_keyword: Keyword,
    #[get = "pub"]
    identifier: Identifier,
    #[get = "pub"]
    open_paren: Punctuation,
    #[get = "pub"]
    parameters: Option<ConnectedList<Identifier, Punctuation>>,
    #[get = "pub"]
    close_paren: Punctuation,
    #[get = "pub"]
    block: Block,
}

impl Function {
    /// Dissolves the [`Function`] into its components.
    #[must_use]
    #[allow(clippy::type_complexity)]
    pub fn dissolve(
        self,
    ) -> (
        Option<Keyword>,
        Vec<Annotation>,
        Keyword,
        Identifier,
        Punctuation,
        Option<ConnectedList<Identifier, Punctuation>>,
        Punctuation,
        Block,
    ) {
        (
            self.public_keyword,
            self.annotations,
            self.function_keyword,
            self.identifier,
            self.open_paren,
            self.parameters,
            self.close_paren,
            self.block,
        )
    }

    /// Returns `true` if the function is public.
    #[must_use]
    pub fn is_public(&self) -> bool {
        self.public_keyword.is_some()
    }
}

impl SourceElement for Function {
    fn span(&self) -> Span {
        self.public_keyword
            .as_ref()
            .map_or_else(|| self.function_keyword.span(), SourceElement::span)
            .join(&self.block.span())
            .unwrap()
    }
}

/// Represents an import declaration in the syntax tree.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// Import:
///     'from' StringLiteral 'import' ('*' | Identifier (',' Identifier)*) ';'
///     ;
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
pub struct Import {
    #[get = "pub"]
    from_keyword: Keyword,
    #[get = "pub"]
    module: StringLiteral,
    #[get = "pub"]
    import_keyword: Keyword,
    #[get = "pub"]
    items: ImportItems,
    #[get = "pub"]
    semicolon: Punctuation,
}

/// Items to import.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ImportItems {
    All(Punctuation),
    Named(ConnectedList<Identifier, Punctuation>),
}

impl Import {
    /// Dissolves the [`Import`] into its components.
    #[must_use]
    pub fn dissolve(self) -> (Keyword, StringLiteral, Keyword, ImportItems, Punctuation) {
        (
            self.from_keyword,
            self.module,
            self.import_keyword,
            self.items,
            self.semicolon,
        )
    }
}

impl SourceElement for Import {
    fn span(&self) -> Span {
        self.from_keyword
            .span()
            .join(&self.semicolon.span())
            .unwrap()
    }
}

/// Represents a tag declaration in the syntax tree.
///
/// Syntax Synopsis:
///
/// ``` ebnf
/// TagDeclaration:
///     'tag' StringLiteral ('of' StringLiteral)? 'replace'? '[' (StringLiteral (',' StringLiteral)*)? ']'
///     ;
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Getters)]
pub struct Tag {
    #[get = "pub"]
    tag_keyword: Keyword,
    #[get = "pub"]
    name: StringLiteral,
    #[get = "pub"]
    of_type: Option<(Keyword, StringLiteral)>,
    #[get = "pub"]
    replace: Option<Keyword>,
    #[get = "pub"]
    entries: DelimitedList<StringLiteral>,
}

impl Tag {
    #[must_use]
    #[allow(clippy::type_complexity)]
    pub fn dissolve(
        self,
    ) -> (
        Keyword,
        StringLiteral,
        Option<(Keyword, StringLiteral)>,
        Option<Keyword>,
        DelimitedList<StringLiteral>,
    ) {
        (
            self.tag_keyword,
            self.name,
            self.of_type,
            self.replace,
            self.entries,
        )
    }

    #[cfg(feature = "shulkerbox")]
    #[must_use]
    pub fn tag_type(&self) -> shulkerbox::datapack::tag::TagType {
        use shulkerbox::datapack::tag::TagType;

        self.of_type
            .as_ref()
            .map_or(TagType::Function, |(_, tag_type)| {
                match tag_type.str_content().as_ref() {
                    "function" => TagType::Function,
                    "block" => TagType::Block,
                    "entity_type" => TagType::Entity,
                    "fluid" => TagType::Fluid,
                    "game_event" => TagType::GameEvent,
                    "item" => TagType::Item,
                    other => TagType::Other(other.to_string()),
                }
            })
    }
}

impl SourceElement for Tag {
    fn span(&self) -> Span {
        self.tag_keyword
            .span()
            .join(&self.entries.close.span)
            .unwrap()
    }
}

impl<'a> Parser<'a> {
    /// Parses an annotation.
    ///
    /// # Errors
    /// - if the parser position is not at an annotation.
    /// - if the parsing of the annotation fails
    pub fn parse_annotation(
        &mut self,
        handler: &impl Handler<base::Error>,
    ) -> ParseResult<Annotation> {
        match self.stop_at_significant() {
            Reading::Atomic(Token::Punctuation(punctuation)) if punctuation.punctuation == '#' => {
                // eat the pound sign
                self.forward();

                // step into the brackets
                let content = self.step_into(
                    Delimiter::Bracket,
                    |parser| {
                        let identifier = parser.parse_identifier(handler)?;

                        let value = match parser.stop_at_significant() {
                            Reading::Atomic(Token::Punctuation(punc))
                                if punc.punctuation == '=' =>
                            {
                                // eat the equals sign
                                parser.forward();

                                // parse the string literal
                                let string_literal = parser.parse_string_literal(handler)?;

                                Some((punc, string_literal))
                            }
                            _ => None,
                        };

                        Ok((identifier, value))
                    },
                    handler,
                )?;

                let (identifier, value) = content.tree?;

                Ok(Annotation {
                    pound_sign: punctuation,
                    open_bracket: content.open,
                    identifier,
                    value,
                    close_bracket: content.close,
                })
            }
            unexpected => {
                let err = Error::UnexpectedSyntax(UnexpectedSyntax {
                    expected: SyntaxKind::Punctuation('#'),
                    found: unexpected.into_token(),
                });
                handler.receive(err.clone());
                Err(err)
            }
        }
    }

    #[tracing::instrument(level = "trace", skip_all)]
    pub fn parse_declaration(
        &mut self,
        handler: &impl Handler<base::Error>,
    ) -> ParseResult<Declaration> {
        match self.stop_at_significant() {
            Reading::Atomic(Token::Keyword(function_keyword))
                if function_keyword.keyword == KeywordKind::Function =>
            {
                let function = self.parse_function(handler)?;

                tracing::trace!("Parsed function '{:?}'", function.identifier.span.str());

                Ok(Declaration::Function(function))
            }

            Reading::Atomic(Token::Keyword(pub_keyword))
                if pub_keyword.keyword == KeywordKind::Pub =>
            {
                let function = self.parse_function(handler)?;

                tracing::trace!("Parsed function '{:?}'", function.identifier.span.str());

                Ok(Declaration::Function(function))
            }

            // parse annotations
            Reading::Atomic(Token::Punctuation(punctuation)) if punctuation.punctuation == '#' => {
                // parse the annotation
                let mut annotations = Vec::new();

                while let Ok(annotation) =
                    self.try_parse(|parser| parser.parse_annotation(&VoidHandler))
                {
                    annotations.push(annotation);
                }

                self.parse_function(handler).map(|mut function| {
                    function.annotations.extend(annotations);
                    Declaration::Function(function)
                })
            }

            Reading::Atomic(Token::Keyword(from_keyword))
                if from_keyword.keyword == KeywordKind::From =>
            {
                // eat the from keyword
                self.forward();

                // parse the module
                let module = self.parse_string_literal(handler)?;

                let import_keyword = self.parse_keyword(KeywordKind::Import, handler)?;

                // TODO: re-enable when the asterisk is supported
                let items = // match self.stop_at_significant() {
                    // Reading::Atomic(Token::Punctuation(punc)) if punc.punctuation == '*' => {
                        // eat the asterisk
                        // self.forward();

                        // ImportItems::All(punc)
                    // }
                    // _ => 
                    self.try_parse(|parser| parser

                        .parse_connected_list(
                            ',',
                            |parser| parser.parse_identifier(&VoidHandler),
                            handler,
                        )
                        .map(ImportItems::Named)) // ,
                // }
                ;

                if let Ok(items) = items {
                    let semicolon = self.parse_punctuation(';', true, handler)?;

                    tracing::trace!("Parsed import from '{:?}'", module.str_content());

                    Ok(Declaration::Import(Import {
                        from_keyword,
                        module,
                        import_keyword,
                        items,
                        semicolon,
                    }))
                } else {
                    let err = Error::UnexpectedSyntax(UnexpectedSyntax {
                        expected: SyntaxKind::Punctuation('*'),
                        found: self.stop_at_significant().into_token(),
                    });
                    handler.receive(err.clone());

                    Err(err)
                }
            }

            Reading::Atomic(Token::Keyword(tag_keyword))
                if tag_keyword.keyword == KeywordKind::Tag =>
            {
                // eat the tag keyword
                self.forward();

                // parse the name
                let name = self.parse_string_literal(handler)?;

                let of_type = self
                    .try_parse(|parser| {
                        let of_keyword = parser.parse_keyword(KeywordKind::Of, &VoidHandler)?;
                        let of_type = parser.parse_string_literal(handler)?;

                        Ok((of_keyword, of_type))
                    })
                    .ok();

                let replace = self
                    .try_parse(|parser| parser.parse_keyword(KeywordKind::Replace, &VoidHandler))
                    .ok();

                let entries = self.parse_enclosed_list(
                    Delimiter::Bracket,
                    ',',
                    |parser| parser.parse_string_literal(handler),
                    handler,
                )?;

                Ok(Declaration::Tag(Tag {
                    tag_keyword,
                    name,
                    of_type,
                    replace,
                    entries,
                }))
            }

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

                let err = Error::UnexpectedSyntax(UnexpectedSyntax {
                    expected: SyntaxKind::Declaration,
                    found: unexpected.into_token(),
                });
                handler.receive(err.clone());

                Err(err)
            }
        }
    }

    /// Parses a function.
    ///
    /// # Errors
    /// - if the parser is not at a function (not at annotation).
    /// - if the parsing of the function fails.
    pub fn parse_function(&mut self, handler: &impl Handler<base::Error>) -> ParseResult<Function> {
        let pub_keyword =
            self.try_parse(|parser| parser.parse_keyword(KeywordKind::Pub, &VoidHandler));

        match self.stop_at_significant() {
            Reading::Atomic(Token::Keyword(function_keyword))
                if function_keyword.keyword == KeywordKind::Function =>
            {
                // eat the function keyword
                self.forward();

                // parse the identifier
                let identifier = self.parse_identifier(handler)?;
                let delimited_tree = self.parse_enclosed_list(
                    Delimiter::Parenthesis,
                    ',',
                    |parser: &mut Parser<'_>| parser.parse_identifier(handler),
                    handler,
                )?;

                // parse the block
                let block = self.parse_block(handler)?;

                Ok(Function {
                    public_keyword: pub_keyword.ok(),
                    annotations: Vec::new(),
                    function_keyword,
                    identifier,
                    open_paren: delimited_tree.open,
                    parameters: delimited_tree.list,
                    close_paren: delimited_tree.close,
                    block,
                })
            }
            unexpected => {
                let err = Error::UnexpectedSyntax(UnexpectedSyntax {
                    expected: SyntaxKind::Keyword(KeywordKind::Function),
                    found: unexpected.into_token(),
                });
                handler.receive(err.clone());
                Err(err)
            }
        }
    }
}