shelly-shell 0.5.0

A Rust based Unix style shell with a typed and structured language syntax.
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

use std::cell::Cell;

use crate::language::{ text::location::Location, data::{ value::Value, types::TypeId } };

#[derive(Debug)]
pub enum AstError
{
    ExpressionNotString(Location)
}


pub struct AstSymbol
{
    pub name: String
}


impl AstSymbol
{
    pub fn is_glob(&self) -> bool
    {
        self.name.contains(['*', '?', '['])
    }
}


pub struct AstLiteral
{
    pub value: Value
}


pub enum AstMathOperator
{
    Add,
    Subtract,
    Multiply,
    Divide,
    Modulo
}


pub enum AstBooleanOperator
{
    Equal,
    NotEqual,
    Less,
    LessEqual,
    Greater,
    GreaterEqual,
    And,
    Or
}


pub enum AstExpressionKind
{
    // Same-line `name ()`: the checker resolves the type/command ambiguity.
    SpacedEmptyCall(String),
    EnumVariant(String, String),
    StructConstructor(Box<AstStructConstructor>),
    Field(Box<AstExpression>, String, Option<usize>),
    Variable(AstSymbol),
    VariableSplat(AstSymbol),
    Array(Vec<AstExpression>),
    HashMap(Vec<(AstExpression, AstExpression)>),
    Range(Option<Box<AstExpression>>, Option<Box<AstExpression>>, bool),
    Index(Box<AstExpression>, Box<AstExpression>),
    Splat(Box<AstExpression>),
    Symbol(AstSymbol),
    Literal(AstLiteral),
    Grouped(Box<AstExpression>),
    // Preserve the referenced value without implicitly invoking it as an argument.
    ExecutableReference(Box<AstExpression>),
    Execute(Box<AstExecuteStatement>),
    Redirect(Box<AstExpression>, Vec<AstRedirection>),
    Pipeline(Box<AstPipeline>),
    TryExecute(Box<AstExpression>),
    MathExpression(AstMathOperator, Box<AstExpression>, Box<AstExpression>),
    BooleanExpression(AstBooleanOperator, Box<AstExpression>, Box<AstExpression>),
    BooleanNot(Box<AstExpression>),
    MathNegate(Box<AstExpression>),
    // The binding checker records explicit collection constraints for conversion lookup.
    TypeConversion(String, Box<AstExpression>, Option<TypeId>, Cell<Option<TypeId>>),
    IfExpression(Box<AstIfExpression>),
    MatchExpression(Box<AstMatchExpression>),
    AnonymousFunction(Box<AstFunctionStatement>)
}


pub enum AstStringFlag
{
    Interpolated(Vec<usize>),
    NonInterpolated,
}


pub struct AstExpression
{
    pub location: Location,
    pub kind: AstExpressionKind,
    pub string_flag: Option<AstStringFlag>
}


pub fn new_ast_variable(location: Location, name: String) -> AstExpression
{
    AstExpression
        {
            location: location.clone(),
            kind: AstExpressionKind::Variable(AstSymbol
                {
                    name
                }),
            string_flag:None
        }
}


pub fn new_ast_variable_splat(location: Location, name: String) -> AstExpression
{
    AstExpression
        {
            location: location.clone(),
            kind: AstExpressionKind::VariableSplat(AstSymbol
                {
                    name
                }),
            string_flag:None
        }
}


pub fn new_ast_symbol(location: Location, name: String,
                      string_flag: Option<AstStringFlag>) -> AstExpression
{
    AstExpression
        {
            location: location.clone(),
            kind: AstExpressionKind::Symbol(AstSymbol
                {
                    name
                }),
            string_flag
        }
}


pub fn new_ast_literal(location: Location,
                       value: Value,
                       string_flag: Option<AstStringFlag>) -> AstExpression
{
    AstExpression
        {
            location: location.clone(),
            kind: AstExpressionKind::Literal(AstLiteral
                {
                    value
                }),
            string_flag
        }
}


impl AstExpression
{
    pub fn uses_pipeline_input(&self) -> bool
    {
        match &self.kind
        {
            AstExpressionKind::Variable(item) | AstExpressionKind::VariableSplat(item) =>
                item.name == "$",
            AstExpressionKind::Execute(call) => call.executable.uses_pipeline_input()
                || call.arguments.iter().any(Self::uses_pipeline_input),
            AstExpressionKind::Array(items) => items.iter().any(Self::uses_pipeline_input),
            AstExpressionKind::HashMap(items) => items.iter().any(|(key, value)|
                key.uses_pipeline_input() || value.uses_pipeline_input()),
            AstExpressionKind::StructConstructor(item) => item.fields.iter()
                .any(|(_, _, value)| value.uses_pipeline_input()),
            AstExpressionKind::Index(a, b) | AstExpressionKind::MathExpression(_, a, b)
            | AstExpressionKind::BooleanExpression(_, a, b) =>
                a.uses_pipeline_input() || b.uses_pipeline_input(),
            AstExpressionKind::Field(inner, _, _) | AstExpressionKind::Splat(inner)
            | AstExpressionKind::Grouped(inner) | AstExpressionKind::ExecutableReference(inner)
            | AstExpressionKind::TryExecute(inner) | AstExpressionKind::MathNegate(inner)
            | AstExpressionKind::BooleanNot(inner)
            | AstExpressionKind::TypeConversion(_, inner, _, _) => inner.uses_pipeline_input(),
            AstExpressionKind::Range(start, end, _) => start.iter().chain(end.iter())
                .any(|value| value.uses_pipeline_input()),
            AstExpressionKind::Redirect(inner, redirects) => inner.uses_pipeline_input()
                || redirects.iter().any(|item| item.target.uses_pipeline_input()),
            AstExpressionKind::IfExpression(item) => item.branches.iter().any(|branch|
                branch.condition.uses_pipeline_input() || branch.body.uses_pipeline_input())
                || item.else_body.as_ref().is_some_and(AstBlockStatement::uses_pipeline_input),
            AstExpressionKind::MatchExpression(item) => item.value.uses_pipeline_input()
                || item.arms.iter().any(|arm|
                    arm.pattern.as_ref().is_some_and(Self::uses_pipeline_input)
                        || arm.body.uses_pipeline_input()),
            // A nested pipeline supplies its own input after its source expression.
            AstExpressionKind::Pipeline(item) => item.stages[0].uses_pipeline_input(),
            _ => false,
        }
    }

    pub fn resolve_as_text(&self) -> Result<String, AstError>
    {
        match &self.kind
        {
            AstExpressionKind::Symbol(symbol) => Ok(symbol.name.clone()),
            AstExpressionKind::EnumVariant(_, _) =>
                Err(AstError::ExpressionNotString(self.location.clone())),
            AstExpressionKind::Variable(variable) => Ok(variable.name.clone()),
            AstExpressionKind::VariableSplat(variable) => Ok(variable.name.clone()),
            AstExpressionKind::Literal(literal) => Ok(literal.value.as_text()),
            AstExpressionKind::Grouped(_)
            | AstExpressionKind::AnonymousFunction(_)
            | AstExpressionKind::Array(_)
            | AstExpressionKind::HashMap(_)
            | AstExpressionKind::Range(_, _, _)
            | AstExpressionKind::StructConstructor(_)
            | AstExpressionKind::SpacedEmptyCall(_)
            | AstExpressionKind::Field(_, _, _)
            | AstExpressionKind::Index(_, _)
            | AstExpressionKind::Splat(_)
            | AstExpressionKind::ExecutableReference(_)
            | AstExpressionKind::Execute(_)
            | AstExpressionKind::Redirect(_, _)
            | AstExpressionKind::Pipeline(_)
            | AstExpressionKind::TryExecute(_)
            | AstExpressionKind::MathExpression(_, _, _)
            | AstExpressionKind::BooleanExpression(_, _, _)
            | AstExpressionKind::BooleanNot(_)
            | AstExpressionKind::MathNegate(_)
            | AstExpressionKind::TypeConversion(_, _, _, _)
            | AstExpressionKind::IfExpression(_)
            | AstExpressionKind::MatchExpression(_) =>
                Err(AstError::ExpressionNotString(self.location.clone()))
        }
    }
}


#[derive(PartialEq, Eq)]
pub enum AstExportFlag
{
    Exported,
    NonExported,
}


pub struct AstLetStatement
{
    pub public: bool,
    pub location: Location,
    pub export_flag: AstExportFlag,
    pub identifier: String,
    pub annotation: Option<AstType>,
    pub type_id: Option<TypeId>,
    pub default_initialize: bool,
    pub expression: AstExpression
}


pub struct AstExecuteStatement
{
    // Only `pub visible` publishes a native/scripted reference through this call.
    pub public: bool,
    pub location: Location,
    pub executable: AstExpression,
    pub expand_path: bool,
    pub arguments: Vec<AstExpression>
}


#[derive(Clone, Copy)]
pub enum RedirectStream
{
    Output,
    Error,
    Both
}


pub struct AstRedirection
{
    pub location: Location,
    pub stream: RedirectStream,
    pub target: AstExpression
}


pub struct AstPipeBoundary
{
    pub location: Location,
    pub decode: Option<String>,
    // Resolved against registered formats and visible type names at the boundary.
    pub annotation: Option<String>,
    pub type_id: Option<TypeId>,
}


pub struct AstPipeline
{
    pub stages: Vec<AstExpression>,
    pub boundaries: Vec<AstPipeBoundary>,
}


pub struct AstSetStatement
{
    pub location: Location,
    pub identifier: String,
    pub indexes: Vec<AstAccess>,
    pub expression: AstExpression,
}


pub struct AstAliasArgument
{
    pub value: Value,
    pub expand_path: bool
}


pub struct AstAliasStatement
{
    pub public: bool,
    pub location: Location,
    pub alias: String,
    pub target: String,
    pub arguments: Vec<AstAliasArgument>
}


pub struct AstParameter
{
    pub location: Location,
    pub name: String,
    pub annotation: Option<AstType>,
    pub optional: bool,
    pub variadic: bool,
    pub type_id: Option<TypeId>
}


pub struct AstFunctionStatement
{
    pub public: bool,
    // Evaluated before registration; excluded functions never reach type checking.
    pub condition: Option<AstExpression>,
    pub location: Location,
    pub name: String,
    pub receiver: Option<String>,
    pub receiver_type: Option<TypeId>,
    pub parameters: Vec<AstParameter>,
    pub return_annotation: Option<AstType>,
    pub return_type: Option<TypeId>,
    pub body: AstTopLevel
}


pub struct AstReturnStatement
{
    pub location: Location,
    pub expression: Option<AstExpression>
}


pub fn new_ast_let_statement(location: Location,
                             export_flag: AstExportFlag,
                             identifier: String,
                             expression: AstExpression) -> Option<AstStatement>
{
    Some(AstStatement::LetStatement(Box::new(AstLetStatement
        {
            public: false,
            location,
            export_flag,
            identifier,
            annotation: None,
            type_id: None,
            default_initialize: false,
            expression,
        })))
}


pub fn new_ast_set_statement(location: Location,
                             identifier: String,
                             indexes: Vec<AstAccess>,
                             expression: AstExpression) -> Option<AstStatement>
{
    Some(AstStatement::SetStatement(Box::new(AstSetStatement
        {
            location,
            identifier,
            indexes,
            expression,
        })))
}


pub fn new_ast_execute_statement(location: Location,
                                 expand_path: bool,
                                 executable: AstExpression,
                                 arguments: Vec<AstExpression>) -> Option<AstStatement>
{
    Some(AstStatement::ExecuteStatement(Box::new(AstExecuteStatement
        {
            public: false,
            location,
            executable,
            expand_path,
            arguments,
        })))
}


pub fn new_ast_alias_statement(location: Location,
                               alias: String,
                               target: String,
                               arguments: Vec<AstAliasArgument>) -> Option<AstStatement>
{
    Some(AstStatement::AliasStatement(Box::new(AstAliasStatement
        {
            public: false,
            location,
            alias,
            target,
            arguments,
        })))
}


pub struct AstBlockStatement
{
    // An annotated block contributes statements to its parent instead of creating a scope.
    pub condition: Option<AstExpression>,
    pub location: Location,
    pub body: AstTopLevel
}


impl AstBlockStatement
{
    fn uses_pipeline_input(&self) -> bool
    {
        self.condition.as_ref().is_some_and(AstExpression::uses_pipeline_input)
            || self.body.iter().any(AstStatement::uses_pipeline_input)
    }
}


pub struct AstIfBranch
{
    pub condition: AstExpression,
    pub body: AstBlockStatement
}


pub struct AstIfExpression
{
    pub location: Location,
    pub branches: Vec<AstIfBranch>,
    pub else_body: Option<AstBlockStatement>
}


pub struct AstMatchArm
{
    // None denotes the bare wildcard, not a value expression.
    pub pattern: Option<AstExpression>,
    pub body: AstBlockStatement
}


pub struct AstMatchExpression
{
    pub location: Location,
    pub value: AstExpression,
    pub arms: Vec<AstMatchArm>
}


pub struct AstForStatement
{
    pub location: Location,
    pub bindings: Vec<String>,
    pub destructure: bool,
    pub iterable: AstExpression,
    pub body: AstBlockStatement
}


pub struct AstConditionalLoopStatement
{
    pub condition: AstExpression,
    pub body: AstBlockStatement,
    pub until: bool
}


pub enum AstType
{
    Function(Vec<AstType>, Box<AstType>),
    Named(String),
    Array(Box<AstType>),
    FixedArray(Vec<AstType>),
    Map(Box<AstType>, Box<AstType>),
    Union(Vec<AstType>),
    Optional(Box<AstType>)
}

pub struct AstFieldDeclaration
{
    pub name: String,
    pub annotation: AstType,
    pub optional: bool,
    pub location: Location
}

pub struct AstStructDeclaration
{
    pub public: bool,
    pub name: String,
    pub fields: Vec<AstFieldDeclaration>,
    pub location: Location
}

pub struct AstTypeDeclaration
{
    // Resolved default factory; explicit declarations with its name take precedence.
    pub conversion: Option<Box<AstFunctionStatement>>,
    pub public: bool,
    pub name: String,
    pub annotation: AstType,
    pub location: Location,
}

pub struct AstStructConstructor
{
    pub name: String,
    pub fields: Vec<(String, Location, AstExpression)>,
    pub type_id: Option<TypeId>,
    pub field_indexes: Vec<usize>
}

pub enum AstAccess
{
    Index(AstExpression),
    Field(String)
}


pub struct AstEnumDeclaration
{
    pub public: bool,
    pub location: Location,
    pub name: String,
    pub variants: Vec<(String, Location)>
}


pub struct AstImportStatement
{
    pub public: bool,
    pub location: Location,
    pub module: String,
    pub names: Vec<String>,
    pub condition: Option<AstExpression>,
    pub enabled: bool,
}


pub enum AstStatement
{
    ImportStatement(Box<AstImportStatement>),
    EnumDeclaration(Box<AstEnumDeclaration>),
    StructDeclaration(Box<AstStructDeclaration>),
    TypeDeclaration(Box<AstTypeDeclaration>),
    LetStatement(Box<AstLetStatement>),
    DiscardStatement(AstExpression),
    SetStatement(Box<AstSetStatement>),
    AliasStatement(Box<AstAliasStatement>),
    ExecuteStatement(Box<AstExecuteStatement>),
    ExpressionStatement(AstExpression),
    ReturnStatement(Box<AstReturnStatement>),
    FunctionDefinition(Box<AstFunctionStatement>),
    BlockStatement(Box<AstBlockStatement>),
    ForStatement(Box<AstForStatement>),
    LoopStatement(Box<AstBlockStatement>),
    ConditionalLoopStatement(Box<AstConditionalLoopStatement>),
    BreakStatement(Location),
    ContinueStatement(Location),
    NullStatement
}


pub type AstTopLevel = Vec<AstStatement>;


impl AstStatement
{
    fn uses_pipeline_input(&self) -> bool
    {
        match self
        {
            Self::LetStatement(item) => item.expression.uses_pipeline_input(),
            Self::SetStatement(item) => item.expression.uses_pipeline_input()
                || item.indexes.iter().any(|access| match access
                    { AstAccess::Index(value) => value.uses_pipeline_input(), _ => false }),
            Self::DiscardStatement(value) | Self::ExpressionStatement(value) =>
                value.uses_pipeline_input(),
            Self::ExecuteStatement(item) => item.executable.uses_pipeline_input()
                || item.arguments.iter().any(AstExpression::uses_pipeline_input),
            Self::ReturnStatement(item) => item.expression.as_ref()
                .is_some_and(AstExpression::uses_pipeline_input),
            Self::BlockStatement(item) | Self::LoopStatement(item) => item.uses_pipeline_input(),
            Self::ForStatement(item) => item.iterable.uses_pipeline_input()
                || item.body.uses_pipeline_input(),
            Self::ConditionalLoopStatement(item) => item.condition.uses_pipeline_input()
                || item.body.uses_pipeline_input(),
            _ => false,
        }
    }

    pub fn module_declaration(&self) -> Option<(&str, &Location, bool)>
    {
        Some(match self
            {
                Self::LetStatement(item) => (&item.identifier, &item.location, item.public),
                Self::FunctionDefinition(item) => (&item.name, &item.location, item.public),
                Self::StructDeclaration(item) => (&item.name, &item.location, item.public),
                Self::EnumDeclaration(item) => (&item.name, &item.location, item.public),
                Self::TypeDeclaration(item) => (&item.name, &item.location, item.public),
                Self::AliasStatement(item) => (&item.alias, &item.location, item.public),
                Self::ImportStatement(item) => (&item.module, &item.location, item.public),
                Self::ExecuteStatement(item) if item.public
                    => ("", &item.location, true),
                _ => return None,
            })
    }
}