vbscript 0.2.3

Rust VBScript 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
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
645
646
647
648
649
650
651
652
653
use crate::lexer::TokenKind;
use std::fmt;
use std::fmt::{Display, Formatter};

/*

From https://www.vbsedit.com/html/9233ea93-1f8d-4ac5-9ad9-d27ecff00da4.asp

Dim varname[([subscripts])][, varname[([subscripts])]] . . .

ReDim [Preserve] varname(subscripts) [, varname(subscripts)] . . .

Set objectvar = {objectexpression | New classname | Nothing}
' or
Set object.eventname = GetRef(procname)

Do [{While | Until} condition]
   [statements]
   [Exit Do]
   [statements]
Loop               ' or use this syntax
Do
   [statements]
   [Exit Do]
   [statements]
Loop [{While | Until} condition]

For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next

For Each element In group
   [statements]
   [Exit For]
   [statements]
Next [element]

While condition
   [statements]
Wend

If condition Then statements [Else elsestatements ]
' Or, you can use the block form syntax:
If condition Then
   [statements]
[ElseIf condition-n Then
   [elseifstatements]] . . .
[Else
   [elsestatements]]
End If

Select Case testexpression
   [Case expressionlist-n
      [statements-n]] . . .
   [Case Else
      [elsestatements-n]]
End Select

[Call] name [argumentlist]



With object
      statements
End With

[Public [Default] | Private] Sub name [(arglist)]
   [statements]
   [Exit Sub]
   [statements]
End Sub

[Public [Default] | Private] Function name [(arglist)]
   [statements]
   [name = expression]
   [Exit Function]
   [statements]
   [name = expression]
End Function

Class name
      statements
End Class

[Public | Private] Property Let name ([arglist,] value)
   [statements]
   [Exit Property]
   [statements]
End Property

[Public | Private] Property Set name([arglist,] reference)
   [statements]
   [Exit Property]
   [statements]
End Property

[Public [Default] | Private] Property Get name [(arglist)]
   [statements]
   [[Set] name = expression]
   [Exit Property]
   [statements]
   [[Set] name = expression]
End Property

*/

#[derive(Debug, Clone, PartialEq)]
pub struct IdentPart {
    pub name: String,
    // there might be multiple array indices/function calls
    // eg a(1,2)(2)
    pub array_indices: Vec<Vec<Option<Expr>>>,
}

impl IdentPart {
    pub fn ident(name: impl Into<String>) -> Self {
        IdentPart {
            name: name.into(),
            array_indices: Vec::new(),
        }
    }
}

impl Display for IdentPart {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)?;
        fmt_indices(f, &self.array_indices)?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum IdentBase {
    /// When used in a `with` statement, eg `.property`
    Partial(IdentPart),
    /// When used as a standalone identifier, eg `variable`
    Complete(IdentPart),
    Me {
        array_indices: Vec<Vec<Option<Expr>>>,
    },
}

fn fmt_indices(f: &mut Formatter, array_indices: &Vec<Vec<Option<Expr>>>) -> fmt::Result {
    for indices in array_indices {
        write!(f, "(")?;
        for (i, index) in indices.iter().enumerate() {
            match index {
                Some(index) => write!(f, "{index}")?,
                None => write!(f, "")?,
            }
            if i < indices.len() - 1 {
                write!(f, ", ")?;
            }
        }
        write!(f, ")")?;
    }
    Ok(())
}

impl IdentBase {
    pub fn ident(name: impl Into<String>) -> Self {
        IdentBase::Complete(IdentPart::ident(name))
    }

    pub fn partial(name: impl Into<String>) -> Self {
        IdentBase::Partial(IdentPart::ident(name))
    }

    pub fn me() -> Self {
        IdentBase::Me {
            array_indices: Vec::new(),
        }
    }

    pub fn array_indices(&self) -> &Vec<Vec<Option<Expr>>> {
        match &self {
            IdentBase::Complete(part) => &part.array_indices,
            IdentBase::Partial(part) => &part.array_indices,
            IdentBase::Me { array_indices } => array_indices,
        }
    }

    pub fn set_array_indices(&mut self, array_indices: Vec<Vec<Option<Expr>>>) {
        match self {
            IdentBase::Complete(part) => part.array_indices = array_indices,
            IdentBase::Partial(part) => part.array_indices = array_indices,
            IdentBase::Me {
                array_indices: me_array_indices,
            } => *me_array_indices = array_indices,
        }
    }
}

impl Display for IdentBase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IdentBase::Partial(part) => write!(f, ".{part}"),
            IdentBase::Complete(part) => write!(f, "{part}"),
            IdentBase::Me { array_indices } => {
                write!(f, "Me")?;
                fmt_indices(f, array_indices)?;
                Ok(())
            }
        }
    }
}

/// An identifier with optional property accesses
/// eg `a.b.c`, `a.b(1).c`, `a.b(1)(2).c` or `a.b(1,2).c(3)`
///
/// Contains a restricted expression that does not allow all operators.
#[derive(Debug, Clone, PartialEq)]
pub struct FullIdent(pub Box<Expr>);

impl FullIdent {
    pub fn ident(name: impl Into<String>) -> Self {
        FullIdent(Box::new(Expr::ident(name)))
    }

    pub fn new(expr: Expr) -> Self {
        FullIdent(Box::new(expr))
    }
}

impl Display for FullIdent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    Literal(Lit),
    Ident(String),
    /// An identifier, identifier with array access, sub or function call
    /// This grammar is ambiguous, so will need to be resolved at runtime
    /// TODO we can probably make a different type for
    ///   * Ident without array access or SubCall without args
    ///   * Ident with array access or FnCall with args or
    ///   * FnCall without args
    ///   * SubCall with args
    IdentFnSubCall(FullIdent),
    // FnCall {
    //     fn_name: FullIdent,
    //     args: Vec<Expr>,
    // },
    // SubCall {
    //     fn_name: String,
    //     args: Vec<Expr>,
    // },
    PrefixOp {
        op: TokenKind,
        expr: Box<Expr>,
    },
    InfixOp {
        op: TokenKind,
        lhs: Box<Expr>,
        rhs: Box<Expr>,
    },
    // PostfixOp {
    //     op: TokenKind,
    //     expr: Box<Expr>,
    // }
    New(String),
    FnApplication {
        callee: Box<Expr>,
        args: Vec<Option<Expr>>,
    },
    WithScoped,
    MemberExpression {
        base: Box<Expr>,
        property: String,
    },
}

impl Expr {
    pub fn ident2(name: impl Into<String>) -> Self {
        Expr::IdentFnSubCall(FullIdent::ident(name))
    }

    pub fn ident(name: impl Into<String>) -> Self {
        Expr::Ident(name.into())
    }

    pub fn int(i: isize) -> Self {
        Expr::Literal(Lit::Int(i.to_string()))
    }

    pub fn int_str(i: impl Into<String>) -> Self {
        Expr::Literal(Lit::Int(i.into()))
    }

    pub fn bool(b: bool) -> Self {
        Expr::Literal(Lit::Bool(b))
    }

    pub fn str(s: impl Into<String>) -> Self {
        Expr::Literal(Lit::Str(s.into()))
    }

    pub fn new(name: impl Into<String>) -> Self {
        Expr::New(name.into())
    }

    pub fn member(base: Expr, property: impl Into<String>) -> Self {
        Expr::MemberExpression {
            base: Box::new(base),
            property: property.into(),
        }
    }

    pub fn fn_application(callee: Expr, args: Vec<Expr>) -> Self {
        let args = args.into_iter().map(Some).collect();
        Expr::FnApplication {
            callee: Box::new(callee),
            args,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Lit {
    /// Integral literal, can be negative, can be very large and at runtime seen as Double with loss of precision
    Int(String),
    /// Floating point literal, can be negative, at runtime seen as Float or Double
    Float(f64),
    Str(String),
    Bool(bool),
    DateTime(String),
    Nothing,
    Empty,
    Null,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ErrorClause {
    ResumeNext,
    Goto0,
}

#[derive(Debug, Clone, PartialEq)]
pub enum SetRhs {
    Expr(Box<Expr>),
    Nothing,
}

impl SetRhs {
    pub fn ident(name: impl Into<String>) -> Self {
        SetRhs::Expr(Box::new(Expr::ident(name)))
    }
    pub fn expr(expr: Expr) -> Self {
        SetRhs::Expr(Box::new(expr))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum DoLoopCondition {
    While(Box<Expr>),
    Until(Box<Expr>),
}

#[derive(Debug, Clone, PartialEq)]
pub enum DoLoopCheck {
    Pre(DoLoopCondition),
    Post(DoLoopCondition),
    None,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Case {
    pub tests: Vec<Expr>,
    pub body: Vec<Stmt>,
}

// Statements
// https://learn.microsoft.com/en-us/previous-versions/7aw9cadb(v=vs.85)
#[derive(Debug, Clone, PartialEq)]
pub enum Stmt {
    Dim {
        vars: Vec<(String, Vec<Expr>)>,
    },
    ReDim {
        preserve: bool,
        var_bounds: Vec<(String, Vec<Expr>)>,
    },
    Const(Vec<(String, Lit)>),
    Set {
        var: FullIdent,
        rhs: SetRhs,
    },
    Assignment {
        full_ident: FullIdent,
        value: Box<Expr>,
    },
    IfStmt {
        condition: Box<Expr>,
        body: Vec<Stmt>,
        elseif_statements: Vec<(Box<Expr>, Vec<Stmt>)>,
        else_stmt: Option<Vec<Stmt>>,
    },
    WhileStmt {
        condition: Box<Expr>,
        body: Vec<Stmt>,
    },
    ForStmt {
        counter: String,
        start: Box<Expr>,
        end: Box<Expr>,
        step: Option<Box<Expr>>,
        body: Vec<Stmt>,
    },
    ForEachStmt {
        element: String,
        group: Box<Expr>,
        body: Vec<Stmt>,
    },
    DoLoop {
        check: DoLoopCheck,
        body: Vec<Stmt>,
    },
    // https://learn.microsoft.com/en-us/previous-versions/6ef9w614(v=vs.85)
    SelectCase {
        test_expr: Box<Expr>,
        cases: Vec<Case>,
        else_stmt: Option<Vec<Stmt>>,
    },
    SubCall {
        fn_name: FullIdent,
        /// Empty arguments are allowed, eg 'MySub 1,,2'
        args: Vec<Option<Expr>>,
    },
    /// Call statement
    /// You are not required to use the Call keyword when calling a procedure. However,
    /// if you use the Call keyword to call a procedure that requires arguments, argumentlist
    /// must be enclosed in parentheses. If you omit the Call keyword, you also must omit
    /// the parentheses around argumentlist. If you use either Call syntax to call any intrinsic
    /// or user-defined function, the function's return value is discarded.
    Call(FullIdent),
    With {
        object: FullIdent,
        body: Vec<Stmt>,
    },
    // https://learn.microsoft.com/en-us/previous-versions//tt223ahx(v=vs.85)
    // There are restrictions as to where these can be defined
    // TODO apply these restrictions, also to function
    // You can't define a Sub procedure inside any other procedure (e.g. Function, Sub or Property Get).
    Sub {
        visibility: Visibility,
        name: String,
        // TODO handle ByVal and ByRef
        parameters: Vec<Argument>,
        body: Vec<Stmt>,
    },
    // https://learn.microsoft.com/en-us/previous-versions//x7hbf8fa(v=vs.85)
    Function {
        visibility: Visibility,
        name: String,
        parameters: Vec<Argument>,
        body: Vec<Stmt>,
    },
    ExitDo,
    ExitFor,
    ExitFunction,
    ExitProperty,
    ExitSub,
    OnError {
        error_clause: ErrorClause,
    },
}

// Byval and ByRef
// https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/argument-passing-mechanisms
#[derive(Debug, Clone, PartialEq)]
pub enum Argument {
    ByVal(String),
    ByRef(String),
}

#[derive(Debug, Clone, PartialEq)]
pub enum PropertyVisibility {
    Public { default: bool },
    Private,
}

#[derive(Debug, Clone, PartialEq)]
pub enum PropertyType {
    Let,
    Set,
    Get,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ArgumentType {
    ByVal,
    ByRef,
}

#[derive(Debug, Clone, PartialEq)]
pub struct MemberAccess {
    pub visibility: PropertyVisibility,
    pub name: String,
    pub property_type: PropertyType,
    pub args: Vec<(String, ArgumentType)>,
    pub body: Vec<Stmt>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Visibility {
    Default,
    Public,
    Private,
}

#[derive(Debug, Clone, PartialEq)]
pub struct MemberDefinitions {
    pub visibility: Visibility,
    pub properties: Vec<(String, Option<Vec<usize>>)>,
}

pub type ClassDim = Vec<(String, Option<Vec<usize>>)>;

#[derive(Debug, Clone, PartialEq)]
pub enum Item {
    // https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/scripting-articles/bw9t3484%28v%3Dvs.84%29
    OptionExplicit,
    // https://learn.microsoft.com/en-us/previous-versions//4ah5852c(v=vs.85)
    Class {
        name: String,
        members: Vec<MemberDefinitions>,
        dims: Vec<ClassDim>,
        member_accessors: Vec<MemberAccess>,
        methods: Vec<Stmt>, // expect only functions and subs
    },
    /// This is a script-level const that has visibility
    /// Consts in procedures are handled by Stmt::Const
    Const {
        visibility: Visibility,
        values: Vec<(String, Lit)>,
    },
    /// This is a script-level variable that has visibility
    /// e.g. `Public a, b, c` or `Private a, b, c`
    /// note: `Public a()` is a dynamic array and not the same as `Public a`
    /// https://stackoverflow.com/a/23911728/42198
    Variable {
        visibility: Visibility,
        vars: Vec<(String, Option<Vec<usize>>)>,
    },
    Statement(Stmt),
}

impl Stmt {
    pub fn dim(var_name: impl Into<String>) -> Self {
        Stmt::Dim {
            vars: vec![(var_name.into(), Vec::new())],
        }
    }

    pub fn const_(var_name: impl Into<String>, value: Lit) -> Self {
        Stmt::Const(vec![(var_name.into(), value)])
    }

    pub fn assignment(ident: FullIdent, value: Expr) -> Self {
        Stmt::Assignment {
            full_ident: ident,
            value: Box::new(value),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Type {
    pub name: String,
    pub generics: Vec<Type>,
}

impl fmt::Display for Expr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Expr::Literal(lit) => write!(f, "{lit}"),
            Expr::Ident(ident) => write!(f, "{ident}"),
            Expr::WithScoped => write!(f, "."),
            Expr::IdentFnSubCall(ident) => {
                write!(f, "{ident}")
            }
            // Expr::FnCall { fn_name, args } => {
            //     write!(f, "{}(", fn_name)?;
            //     for arg in args {
            //         write!(f, "{},", arg)?;
            //     }
            //     write!(f, ")")
            // }
            // Expr::SubCall { fn_name, args } => {
            //     write!(f, "{}", fn_name)?;
            //     for arg in args {
            //         write!(f, "{},", arg)?;
            //     }
            //     write!(f, "")
            // }
            Expr::PrefixOp { op, expr } => write!(f, "({op} {expr})"),
            Expr::InfixOp { op, lhs, rhs } => write!(f, "({lhs} {op} {rhs})"),
            // Expr::PostfixOp { op, expr } =>
            //     write!(f, "({} {})", expr, op),
            Expr::New(name) => write!(f, "New {name}"),
            Expr::FnApplication { callee, args } => {
                write!(f, "{callee}(")?;
                let len = args.len();
                for (i, arg) in args.iter().enumerate() {
                    if let Some(arg) = arg {
                        write!(f, "{arg}")?;
                    }
                    if i != len - 1 {
                        write!(f, ", ")?;
                    }
                }
                write!(f, ")")
            }
            Expr::MemberExpression { base, property } => write!(f, "{base}.{property}"),
        }
    }
}

impl fmt::Display for Lit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Lit::Int(i) => write!(f, "{i}"),
            Lit::Float(fl) => write!(f, "{fl}"),
            Lit::Str(s) => write!(f, r#""{}""#, s.replace('"', "\"\"")),
            Lit::DateTime(dt) => write!(f, "#{dt}#"),
            Lit::Bool(b) => {
                if *b {
                    write!(f, "True")
                } else {
                    write!(f, "False")
                }
            }
            Lit::Nothing => write!(f, "Nothing"),
            Lit::Empty => write!(f, "Empty"),
            Lit::Null => write!(f, "Null"),
        }
    }
}

impl Lit {
    pub fn str(s: impl Into<String>) -> Self {
        Lit::Str(s.into())
    }

    pub fn int(i: isize) -> Self {
        Lit::Int(i.to_string())
    }
}