aiscript-vm 0.2.0

AIScript programming language interpreter
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
use std::collections::HashMap;
use std::fmt::Display;

use aiscript_arena::Collect;
use aiscript_directive::Validator;
use indexmap::IndexMap;

use crate::object::{FunctionType, ListKind};
use crate::{Value, string::InternedString};
use crate::{lexer::Token, ty::PrimitiveType};

mod pretty;

/// Use u16 to represent the chunk id
/// It is enough for a program to assign id for each function chunk.
pub type ChunkId = u16;

#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
pub enum Mutability {
    #[default]
    Mutable,
    Immutable,
}

#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Visibility {
    #[default]
    Private, // Default visibility
    Public, // Accessible from other modules
            // Could add more in future like:
            // Protected,  // Only accessible to child classes
            // Package,    // Only accessible within the same package/directory
}

#[derive(Debug, Clone, Copy, Default)]
pub enum Literal<'gc> {
    Number(f64),
    String(InternedString<'gc>),
    Boolean(bool),
    #[default]
    Nil,
}

impl Display for Literal<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Literal::Number(n) => write!(f, "{n}"),
            Literal::String(s) => write!(f, "\"{s}\""),
            Literal::Boolean(b) => write!(f, "{b}"),
            Literal::Nil => write!(f, "nil"),
        }
    }
}

#[derive(Debug)]
pub struct EnumDecl<'gc> {
    pub name: Token<'gc>,
    pub variants: Vec<EnumVariant<'gc>>,
    pub methods: Vec<Stmt<'gc>>,
    pub visibility: Visibility,
    pub line: u32,
}

#[derive(Debug, Clone)]
pub struct EnumVariant<'gc> {
    pub name: Token<'gc>,
    // Default is Literal::Nil
    pub value: Literal<'gc>,
}

#[derive(Debug)]
pub struct FunctionDecl<'gc> {
    pub name: Token<'gc>,
    pub mangled_name: String,
    pub doc: Option<Token<'gc>>,
    pub params: IndexMap<Token<'gc>, ParameterDecl<'gc>>,
    pub return_type: Option<Token<'gc>>,
    pub error_types: Vec<Token<'gc>>,
    pub body: Vec<Stmt<'gc>>,
    pub fn_type: FunctionType,
    pub visibility: Visibility,
    pub line: u32,
}

#[derive(Debug)]
pub struct VariableDecl<'gc> {
    pub name: Token<'gc>,
    pub initializer: Option<Expr<'gc>>,
    pub visibility: Visibility,
    pub line: u32,
}

pub struct ClassFieldDecl<'gc> {
    pub name: Token<'gc>,
    pub type_hint: Token<'gc>,
    pub default_value: Option<Expr<'gc>>,
    pub validators: Vec<Box<dyn Validator>>,
    pub line: u32,
}

#[derive(Debug)]
pub struct ClassDecl<'gc> {
    pub name: Token<'gc>,
    pub superclass: Option<Expr<'gc>>,
    // pub fields: Vec<ClassFieldDecl<'gc>>,
    pub methods: Vec<Stmt<'gc>>,
    pub visibility: Visibility,
    pub line: u32,
}

#[derive(Debug)]
pub struct AgentDecl<'gc> {
    pub name: Token<'gc>,
    pub mangled_name: String,
    pub fields: HashMap<&'gc str, Expr<'gc>>,
    pub tools: Vec<Stmt<'gc>>,
    pub visibility: Visibility,
    pub line: u32,
}

pub struct ParameterDecl<'gc> {
    pub name: Token<'gc>,
    pub type_hint: Option<Token<'gc>>,
    pub default_value: Option<Expr<'gc>>,
    pub validators: Vec<Box<dyn Validator>>,
}

impl std::fmt::Debug for ParameterDecl<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Parameter")
            .field("name", &self.name)
            .field("type_hint", &self.type_hint)
            .field("default_value", &self.default_value)
            .field("validators", &self.validators.len())
            .finish()
    }
}

impl<'gc> ParameterDecl<'gc> {
    pub fn new(name: Token<'gc>) -> Self {
        Self {
            name,
            type_hint: None,
            default_value: None,
            validators: Vec::new(),
        }
    }
}

// Define a new enum to represent parts of an f-string
#[derive(Debug)]
pub enum FStringPart<'gc> {
    // A literal string part (the text outside of curly braces)
    StringLiteral(InternedString<'gc>),
    // An expression to be evaluated and converted to a string (the code inside curly braces)
    Expression(Box<Expr<'gc>>),
}

#[derive(Debug)]
pub struct ErrorHandler<'gc> {
    pub error_var: Token<'gc>,
    pub handler_body: Vec<Stmt<'gc>>,
    pub propagate: bool, // Whether to use ? operator
}

#[derive(Debug, Clone, Collect)]
#[collect(require_static)]
pub struct FnDef {
    pub chunk_id: ChunkId,
    pub doc: String,
    pub params: IndexMap<String, PrimitiveType>,
}

impl FnDef {
    pub fn new(
        chunk_id: ChunkId,
        doc: &Option<Token>,
        params: IndexMap<String, PrimitiveType>,
    ) -> Self {
        FnDef {
            chunk_id,
            doc: doc.map(|t| t.lexeme.to_owned()).unwrap_or_default(),
            params,
        }
    }
}

#[derive(Debug)]
pub enum ObjectProperty<'gc> {
    // Regular property with literal name
    Literal {
        key: Token<'gc>,
        value: Box<Expr<'gc>>,
    },
    // Computed property name
    Computed {
        key_expr: Box<Expr<'gc>>,
        value: Box<Expr<'gc>>,
    },
}

#[derive(Debug)]
pub struct MatchArm<'gc> {
    pub patterns: Vec<MatchPattern<'gc>>,
    pub body: Box<Expr<'gc>>,
    // Optional if guard
    pub guard: Option<Box<Expr<'gc>>>,
    pub line: u32,
}

#[derive(Debug)]
pub enum MatchPattern<'gc> {
    EnumVariant {
        enum_name: Token<'gc>,
        variant: Token<'gc>,
    },
    Literal {
        value: Literal<'gc>,
    },
    Variable {
        name: Token<'gc>,
    },
    Range {
        start: Option<Box<Expr<'gc>>>,
        end: Option<Box<Expr<'gc>>>,
        inclusive: bool,
    },
    Wildcard,
}

impl MatchPattern<'_> {
    pub fn is_variable_pattern(&self) -> bool {
        matches!(self, Self::Variable { .. })
    }
}

#[derive(Debug)]
pub enum Expr<'gc> {
    EnvLookup {
        expr: Box<Expr<'gc>>,
        line: u32,
    },
    Object {
        properties: Vec<ObjectProperty<'gc>>,
        line: u32,
    },
    EnumVariant {
        enum_name: Token<'gc>,
        variant: Token<'gc>,
        line: u32,
    },
    // syntax: [Enum::Variant] to get the value
    EvaluateVariant {
        expr: Box<Expr<'gc>>,
        line: u32,
    },
    Binary {
        left: Box<Expr<'gc>>,
        operator: Token<'gc>,
        right: Box<Expr<'gc>>,
        line: u32,
    },
    Grouping {
        expression: Box<Expr<'gc>>,
        line: u32,
    },
    List {
        elements: Vec<Expr<'gc>>,
        kind: ListKind,
        line: u32,
    },
    Literal {
        value: Literal<'gc>,
        line: u32,
    },
    FString {
        // A vector of either literal string parts or expressions to be interpolated
        parts: Vec<FStringPart<'gc>>,
        line: u32,
    },
    Unary {
        operator: Token<'gc>,
        right: Box<Expr<'gc>>,
        line: u32,
    },
    Variable {
        name: Token<'gc>,
        line: u32,
    },
    Index {
        object: Box<Expr<'gc>>,
        key: Box<Expr<'gc>>,
        value: Option<Box<Expr<'gc>>>,
        line: u32,
    },
    Assign {
        name: Token<'gc>,
        value: Box<Expr<'gc>>,
        line: u32,
    },
    And {
        left: Box<Expr<'gc>>,
        right: Box<Expr<'gc>>,
        line: u32,
    },
    Or {
        left: Box<Expr<'gc>>,
        right: Box<Expr<'gc>>,
        line: u32,
    },
    Lambda {
        params: Vec<Token<'gc>>,
        body: Box<Expr<'gc>>,
        line: u32,
    },
    Block {
        statements: Vec<Stmt<'gc>>,
        line: u32,
    },
    Call {
        callee: Box<Expr<'gc>>,
        is_constructor: bool,
        arguments: Vec<Expr<'gc>>,
        keyword_args: HashMap<String, Expr<'gc>>,
        error_handler: Option<ErrorHandler<'gc>>,
        line: u32,
    },
    Invoke {
        object: Box<Expr<'gc>>,
        method: Token<'gc>,
        arguments: Vec<Expr<'gc>>,
        keyword_args: HashMap<String, Expr<'gc>>,
        error_handler: Option<ErrorHandler<'gc>>,
        line: u32,
    },
    Match {
        expr: Box<Expr<'gc>>,
        arms: Vec<MatchArm<'gc>>,
        line: u32,
    },
    InlineIf {
        condition: Box<Expr<'gc>>,
        then_branch: Box<Expr<'gc>>,
        else_branch: Box<Expr<'gc>>,
        line: u32,
    },
    Get {
        object: Box<Expr<'gc>>,
        name: Token<'gc>,
        line: u32,
    },
    Set {
        object: Box<Expr<'gc>>,
        name: Token<'gc>,
        value: Box<Expr<'gc>>,
        line: u32,
    },
    Self_ {
        line: u32,
    },
    Super {
        method: Token<'gc>,
        line: u32,
    },
    SuperInvoke {
        method: Token<'gc>,
        arguments: Vec<Expr<'gc>>,
        keyword_args: HashMap<String, Expr<'gc>>,
        line: u32,
    },
    Prompt {
        expression: Box<Expr<'gc>>,
        line: u32,
    },
}

impl Expr<'_> {
    pub fn line(&self) -> u32 {
        match self {
            Self::EnvLookup { line, .. }
            | Self::Object { line, .. }
            | Self::EnumVariant { line, .. }
            | Self::EvaluateVariant { line, .. }
            | Self::Binary { line, .. }
            | Self::Grouping { line, .. }
            | Self::List { line, .. }
            | Self::Literal { line, .. }
            | Self::FString { line, .. }
            | Self::Unary { line, .. }
            | Self::Variable { line, .. }
            | Self::Index { line, .. }
            | Self::Match { line, .. }
            | Self::InlineIf { line, .. }
            | Self::Assign { line, .. }
            | Self::And { line, .. }
            | Self::Or { line, .. }
            | Self::Lambda { line, .. }
            | Self::Block { line, .. }
            | Self::Call { line, .. }
            | Self::Invoke { line, .. }
            | Self::Get { line, .. }
            | Self::Set { line, .. }
            | Self::Self_ { line, .. }
            | Self::Super { line, .. }
            | Self::SuperInvoke { line, .. }
            | Self::Prompt { line, .. } => *line,
        }
    }
}

#[derive(Debug)]
pub enum Stmt<'gc> {
    Use {
        path: Token<'gc>,
        line: u32,
    },
    Enum(EnumDecl<'gc>),
    Expression {
        expression: Expr<'gc>,
        line: u32,
    },
    Let(VariableDecl<'gc>),
    Const {
        name: Token<'gc>,
        initializer: Expr<'gc>,
        visibility: Visibility,
        line: u32,
    },
    Block {
        statements: Vec<Stmt<'gc>>,
        line: u32,
    },
    Break {
        line: u32,
    },
    Continue {
        line: u32,
    },
    If {
        condition: Expr<'gc>,
        then_branch: Box<Stmt<'gc>>,
        else_branch: Option<Box<Stmt<'gc>>>,
        line: u32,
    },
    Loop {
        initializer: Option<Box<Stmt<'gc>>>,
        condition: Expr<'gc>,
        increment: Option<Expr<'gc>>,
        body: Box<Stmt<'gc>>,
        line: u32,
    },
    Function(FunctionDecl<'gc>),
    Raise {
        error: Expr<'gc>,
        line: u32,
    },
    Return {
        value: Option<Expr<'gc>>,
        line: u32,
    },
    // Block return just provides the block's value
    BlockReturn {
        value: Expr<'gc>,
        line: u32,
    },
    Class(ClassDecl<'gc>),
    Agent(AgentDecl<'gc>),
}

impl Stmt<'_> {
    pub fn line(&self) -> u32 {
        match self {
            Self::Use { line, .. }
            | Self::Enum(EnumDecl { line, .. })
            | Self::Expression { line, .. }
            | Self::Let(VariableDecl { line, .. })
            | Self::Const { line, .. }
            | Self::Break { line, .. }
            | Self::Continue { line, .. }
            | Self::Block { line, .. }
            | Self::If { line, .. }
            | Self::Loop { line, .. }
            | Self::Function(FunctionDecl { line, .. })
            | Self::Raise { line, .. }
            | Self::Return { line, .. }
            | Self::BlockReturn { line, .. }
            | Self::Class(ClassDecl { line, .. })
            | Self::Agent(AgentDecl { line, .. }) => *line,
        }
    }
}

// Implement PartialEq manually to handle float comparison
impl PartialEq for Literal<'_> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Literal::Number(a), Literal::Number(b)) => (a - b).abs() < f64::EPSILON,
            (Literal::String(a), Literal::String(b)) => a == b,
            (Literal::Boolean(a), Literal::Boolean(b)) => a == b,
            (Literal::Nil, Literal::Nil) => true,
            _ => false,
        }
    }
}

// Implement Eq after ensuring PartialEq handles float comparison correctly
impl Eq for Literal<'_> {}

// Implement Hash to match our Eq implementation
impl std::hash::Hash for Literal<'_> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            Literal::Number(n) => {
                // Hash the bits of the float to be consistent with our Eq implementation
                n.to_bits().hash(state);
            }
            Literal::String(s) => s.hash(state),
            Literal::Boolean(b) => b.hash(state),
            Literal::Nil => 0.hash(state),
        }
    }
}

#[derive(Debug)]
pub struct Program<'gc> {
    pub statements: Vec<Stmt<'gc>>,
}

impl Program<'_> {
    pub fn new() -> Self {
        Self {
            statements: Vec::new(),
        }
    }
}

impl<'gc> From<Literal<'gc>> for Value<'gc> {
    fn from(value: Literal<'gc>) -> Self {
        match value {
            Literal::Number(value) => Value::Number(value),
            Literal::String(value) => Value::String(value),
            Literal::Boolean(value) => Value::Boolean(value),
            Literal::Nil => Value::Nil,
        }
    }
}

impl<'gc> From<Box<Expr<'gc>>> for Expr<'gc> {
    fn from(value: Box<Expr<'gc>>) -> Self {
        *value
    }
}

impl<'gc> From<Box<Stmt<'gc>>> for Stmt<'gc> {
    fn from(value: Box<Stmt<'gc>>) -> Self {
        *value
    }
}