aver-lang 0.10.1

VM and transpiler for Aver, a statically-typed language designed for AI-assisted development
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
use std::collections::HashMap;

use crate::nan_value::NanValue;

use super::builtin::VmBuiltin;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct VmVariantCtor {
    pub(crate) type_id: u32,
    pub(crate) variant_id: u16,
    pub(crate) ctor_id: u32,
    pub(crate) field_count: u8,
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum VmSymbolKind {
    Function(u32),
    Builtin(VmBuiltin),
    Namespace,
    VariantCtor(VmVariantCtor),
    Wrapper(u8),
    Constant(NanValue),
}

#[derive(Debug, Clone)]
pub(crate) struct VmSymbolInfo {
    pub(crate) name: String,
    pub(crate) kind: Option<VmSymbolKind>,
    pub(crate) required_effects: Vec<u32>,
    members: HashMap<u32, NanValue>,
}

#[derive(Debug, Clone, Default)]
pub(crate) struct VmSymbolTable {
    symbols: Vec<VmSymbolInfo>,
    by_name: HashMap<String, u32>,
}

impl VmSymbolTable {
    #[inline]
    pub(crate) fn symbol_ref(symbol_id: u32) -> NanValue {
        NanValue::new_int_inline(symbol_id as i64)
    }

    pub(crate) fn intern_name(&mut self, name: &str) -> u32 {
        if let Some(&symbol_id) = self.by_name.get(name) {
            return symbol_id;
        }
        let symbol_id = self.symbols.len() as u32;
        self.symbols.push(VmSymbolInfo {
            name: name.to_string(),
            kind: None,
            required_effects: Vec::new(),
            members: HashMap::new(),
        });
        self.by_name.insert(name.to_string(), symbol_id);
        symbol_id
    }

    pub(crate) fn intern_namespace(&mut self, name: &str) -> u32 {
        let symbol_id = self.intern_name(name);
        let info = &mut self.symbols[symbol_id as usize];
        match info.kind {
            Some(VmSymbolKind::Namespace) => {}
            None => info.kind = Some(VmSymbolKind::Namespace),
            Some(other) => panic!("VM symbol '{}' already exists as {:?}", name, other),
        }
        symbol_id
    }

    pub(crate) fn intern_namespace_path(&mut self, path: &str) -> u32 {
        let mut current_id = None;
        let mut current_path = String::new();

        for segment in path.split('.') {
            if segment.is_empty() {
                continue;
            }
            if !current_path.is_empty() {
                current_path.push('.');
            }
            current_path.push_str(segment);

            let child_id = self.intern_namespace(&current_path);
            if let Some(parent_id) = current_id {
                let member_symbol_id = self.intern_name(segment);
                self.add_namespace_member_by_id(
                    parent_id,
                    member_symbol_id,
                    Self::symbol_ref(child_id),
                );
            }
            current_id = Some(child_id);
        }

        current_id.expect("intern_namespace_path() requires a non-empty path")
    }

    pub(crate) fn intern_function(&mut self, name: &str, fn_id: u32, effects: &[String]) -> u32 {
        let symbol_id = self.intern_name(name);
        let required_effects = self.intern_effects(effects.iter().map(String::as_str));
        let info = &mut self.symbols[symbol_id as usize];
        match &mut info.kind {
            Some(VmSymbolKind::Function(existing_fn_id)) => {
                *existing_fn_id = fn_id;
            }
            None => {
                info.kind = Some(VmSymbolKind::Function(fn_id));
            }
            Some(other) => panic!("VM symbol '{}' already exists as {:?}", name, other),
        }
        info.required_effects = required_effects;
        symbol_id
    }

    pub(crate) fn intern_builtin(&mut self, builtin: VmBuiltin) -> u32 {
        let symbol_id = self.intern_name(builtin.name());
        let required_effects = self.intern_effects(builtin.effects().iter().copied());
        let info = &mut self.symbols[symbol_id as usize];
        match info.kind {
            Some(VmSymbolKind::Builtin(existing)) => {
                debug_assert_eq!(existing, builtin);
            }
            None => {
                info.kind = Some(VmSymbolKind::Builtin(builtin));
            }
            Some(other) => panic!(
                "VM symbol '{}' already exists as {:?}",
                builtin.name(),
                other
            ),
        }
        info.required_effects = required_effects;
        symbol_id
    }

    pub(crate) fn intern_variant_ctor(&mut self, name: &str, ctor: VmVariantCtor) -> u32 {
        let symbol_id = self.intern_name(name);
        let info = &mut self.symbols[symbol_id as usize];
        match info.kind {
            Some(VmSymbolKind::VariantCtor(existing)) => {
                debug_assert_eq!(existing, ctor);
            }
            None => info.kind = Some(VmSymbolKind::VariantCtor(ctor)),
            Some(other) => panic!("VM symbol '{}' already exists as {:?}", name, other),
        }
        symbol_id
    }

    pub(crate) fn intern_wrapper(&mut self, name: &str, wrap_kind: u8) -> u32 {
        let symbol_id = self.intern_name(name);
        let info = &mut self.symbols[symbol_id as usize];
        match info.kind {
            Some(VmSymbolKind::Wrapper(existing)) => {
                debug_assert_eq!(existing, wrap_kind);
            }
            None => info.kind = Some(VmSymbolKind::Wrapper(wrap_kind)),
            Some(other) => panic!("VM symbol '{}' already exists as {:?}", name, other),
        }
        symbol_id
    }

    pub(crate) fn intern_constant(&mut self, name: &str, value: NanValue) -> u32 {
        let symbol_id = self.intern_name(name);
        let info = &mut self.symbols[symbol_id as usize];
        match info.kind {
            Some(VmSymbolKind::Constant(existing)) => {
                debug_assert_eq!(existing.bits(), value.bits());
            }
            None => info.kind = Some(VmSymbolKind::Constant(value)),
            Some(other) => panic!("VM symbol '{}' already exists as {:?}", name, other),
        }
        symbol_id
    }

    #[cfg(test)]
    pub(crate) fn add_namespace_member(
        &mut self,
        namespace: &str,
        member: &str,
        value: NanValue,
    ) -> u32 {
        let namespace_id = self.intern_namespace(namespace);
        let member_symbol_id = self.intern_name(member);
        self.add_namespace_member_by_id(namespace_id, member_symbol_id, value);
        member_symbol_id
    }

    pub(crate) fn add_namespace_member_by_id(
        &mut self,
        namespace_symbol_id: u32,
        member_symbol_id: u32,
        value: NanValue,
    ) {
        let info = &mut self.symbols[namespace_symbol_id as usize];
        match info.kind {
            Some(VmSymbolKind::Namespace) => {
                info.members.insert(member_symbol_id, value);
            }
            None => panic!("VM symbol '{}' is not registered as namespace", info.name),
            Some(other) => panic!("VM symbol '{}' is {:?}", info.name, other),
        }
    }

    pub(crate) fn find(&self, name: &str) -> Option<u32> {
        self.by_name.get(name).copied()
    }

    pub(crate) fn get(&self, symbol_id: u32) -> Option<&VmSymbolInfo> {
        self.symbols.get(symbol_id as usize)
    }

    pub(crate) fn resolve_function(&self, symbol_id: u32) -> Option<u32> {
        match self.get(symbol_id)?.kind {
            Some(VmSymbolKind::Function(fn_id)) => Some(fn_id),
            _ => None,
        }
    }

    pub(crate) fn resolve_builtin(&self, symbol_id: u32) -> Option<VmBuiltin> {
        match self.get(symbol_id)?.kind {
            Some(VmSymbolKind::Builtin(builtin)) => Some(builtin),
            _ => None,
        }
    }

    pub(crate) fn resolve_variant_ctor(&self, symbol_id: u32) -> Option<VmVariantCtor> {
        match self.get(symbol_id)?.kind {
            Some(VmSymbolKind::VariantCtor(ctor)) => Some(ctor),
            _ => None,
        }
    }

    pub(crate) fn resolve_wrapper(&self, symbol_id: u32) -> Option<u8> {
        match self.get(symbol_id)?.kind {
            Some(VmSymbolKind::Wrapper(kind)) => Some(kind),
            _ => None,
        }
    }

    pub(crate) fn resolve_constant(&self, symbol_id: u32) -> Option<NanValue> {
        match self.get(symbol_id)?.kind {
            Some(VmSymbolKind::Constant(value)) => Some(value),
            _ => None,
        }
    }

    pub(crate) fn is_namespace(&self, symbol_id: u32) -> bool {
        matches!(
            self.get(symbol_id).and_then(|info| info.kind),
            Some(VmSymbolKind::Namespace)
        )
    }

    pub(crate) fn resolve_member(
        &self,
        namespace_symbol_id: u32,
        member_symbol_id: u32,
    ) -> Option<NanValue> {
        self.get(namespace_symbol_id)?
            .members
            .get(&member_symbol_id)
            .copied()
    }

    pub(crate) fn resolve_symbol_ref(&self, value: NanValue) -> Option<u32> {
        let symbol_id = value.inline_int_value()?;
        (symbol_id >= 0)
            .then_some(symbol_id as u32)
            .filter(|&id| self.get(id).is_some_and(|info| info.kind.is_some()))
    }

    pub(crate) fn resolve_namespace_path(&self, path: &str) -> Option<u32> {
        if let Some(symbol_id) = self.find(path)
            && self.is_namespace(symbol_id)
        {
            return Some(symbol_id);
        }

        let mut segments = path.split('.');
        let first = segments.next()?;
        let mut current_id = self.find(first)?;
        if !self.is_namespace(current_id) {
            return None;
        }

        for segment in segments {
            let member_symbol_id = self.find(segment)?;
            let member = self.resolve_member(current_id, member_symbol_id)?;
            current_id = self.resolve_symbol_ref(member)?;
            if !self.is_namespace(current_id) {
                return None;
            }
        }

        Some(current_id)
    }

    #[cfg(test)]
    pub(crate) fn required_effects(&self, symbol_id: u32) -> Option<&[u32]> {
        Some(self.get(symbol_id)?.required_effects.as_slice())
    }

    fn intern_effects<'a>(&mut self, effects: impl IntoIterator<Item = &'a str>) -> Vec<u32> {
        effects
            .into_iter()
            .map(|name| self.intern_name(name))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::{VmSymbolKind, VmSymbolTable, VmVariantCtor};
    use crate::nan_value::NanValue;
    use crate::vm::builtin::VmBuiltin;

    #[test]
    fn symbol_table_interns_functions_and_builtins() {
        let mut table = VmSymbolTable::default();
        let fn_sym = table.intern_function("main", 7, &[]);
        let builtin_sym = table.intern_builtin(VmBuiltin::StringReplace);

        assert_eq!(table.find("main"), Some(fn_sym));
        assert_eq!(table.find("String.replace"), Some(builtin_sym));
        assert_eq!(table.resolve_function(fn_sym), Some(7));
        assert_eq!(
            table.resolve_builtin(builtin_sym),
            Some(VmBuiltin::StringReplace)
        );
        assert!(matches!(
            table.get(fn_sym).and_then(|info| info.kind),
            Some(VmSymbolKind::Function(7))
        ));
        assert_eq!(table.required_effects(fn_sym), Some([].as_slice()));
    }

    #[test]
    fn symbol_table_reuses_builtin_name_for_effect() {
        let mut table = VmSymbolTable::default();
        let effect_sym = table.intern_name("Console.print");
        let builtin_sym = table.intern_builtin(VmBuiltin::ConsolePrint);

        assert_eq!(effect_sym, builtin_sym);
        assert_eq!(
            table.required_effects(builtin_sym),
            Some([builtin_sym].as_slice())
        );
    }

    #[test]
    fn namespace_members_can_point_at_symbols_and_constants() {
        let mut table = VmSymbolTable::default();
        let ns = table.intern_namespace("Option");
        let some = table.intern_wrapper("Option.Some", 2);
        table.add_namespace_member("Option", "Some", VmSymbolTable::symbol_ref(some));
        table.add_namespace_member("Option", "None", NanValue::NONE);

        let some_member = table.find("Some").unwrap();
        let none_member = table.find("None").unwrap();

        assert_eq!(
            table.resolve_member(ns, some_member).map(NanValue::bits),
            Some(VmSymbolTable::symbol_ref(some).bits())
        );
        assert_eq!(
            table.resolve_member(ns, none_member).map(NanValue::bits),
            Some(NanValue::NONE.bits())
        );
    }

    #[test]
    fn variant_ctor_symbols_keep_ctor_metadata() {
        let mut table = VmSymbolTable::default();
        let ctor = VmVariantCtor {
            type_id: 4,
            variant_id: 2,
            ctor_id: 9,
            field_count: 0,
        };
        let symbol_id = table.intern_variant_ctor("Status.Done", ctor);

        assert_eq!(table.resolve_variant_ctor(symbol_id), Some(ctor));
    }

    #[test]
    fn symbol_table_builds_and_resolves_nested_namespace_paths() {
        let mut table = VmSymbolTable::default();
        let path = table.intern_namespace_path("Domain.Types");

        assert_eq!(table.find("Domain.Types"), Some(path));

        let domain = table.find("Domain").expect("missing Domain");
        let types = table.find("Types").expect("missing Types");
        assert_eq!(
            table
                .resolve_member(domain, types)
                .and_then(|value| table.resolve_symbol_ref(value)),
            Some(path)
        );
        assert_eq!(table.resolve_namespace_path("Domain.Types"), Some(path));
    }
}