pipa-js 0.1.3

A fast, minimal ES2023 JavaScript runtime built in Rust.
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
use crate::object::JSObject;
use crate::runtime::atom::AtomTable;
use crate::runtime::context::JSContext;
use crate::util::FxHashMap;
use crate::value::JSValue;
use std::cell::RefCell;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModuleState {
    Unlinked,
    Linking,
    Linked,
    Evaluating,
    Evaluated,
    Errored,
}

#[derive(Clone)]
pub struct ModuleExport {
    pub name: String,
    pub value: JSValue,
    pub mutable: bool,
}

#[derive(Clone)]
pub struct ModuleImport {
    pub module_specifier: String,
    pub import_name: String,
    pub local_name: String,
}

pub struct Module {
    pub specifier: String,
    pub state: ModuleState,
    pub exports: FxHashMap<String, ModuleExport>,
    pub imports: Vec<ModuleImport>,
    pub namespace_object: Option<usize>,
    pub source: String,
    pub import_meta_object: Option<usize>,
    pub error: Option<String>,
}

impl Module {
    pub fn new(specifier: String, source: String) -> Self {
        Module {
            specifier,
            state: ModuleState::Unlinked,
            exports: FxHashMap::default(),
            imports: Vec::new(),
            namespace_object: None,
            source,
            import_meta_object: None,
            error: None,
        }
    }

    pub fn add_export(&mut self, name: String, value: JSValue, mutable: bool) {
        self.exports.insert(
            name.clone(),
            ModuleExport {
                name,
                value,
                mutable,
            },
        );
    }

    pub fn add_import(
        &mut self,
        module_specifier: String,
        import_name: String,
        local_name: String,
    ) {
        self.imports.push(ModuleImport {
            module_specifier,
            import_name,
            local_name,
        });
    }

    pub fn get_export(&self, name: &str) -> Option<&ModuleExport> {
        self.exports.get(name)
    }

    pub fn get_export_mut(&mut self, name: &str) -> Option<&mut ModuleExport> {
        self.exports.get_mut(name)
    }

    pub fn get_export_value(&self, name: &str) -> JSValue {
        self.exports
            .get(name)
            .map(|e| e.value.clone())
            .unwrap_or(JSValue::undefined())
    }

    pub fn set_export_value(&mut self, name: &str, value: JSValue) {
        if let Some(export) = self.exports.get_mut(name) {
            export.value = value;
        }
    }

    pub fn create_namespace_object(&mut self, atom_table: &mut AtomTable) -> usize {
        let mut ns_obj = JSObject::new();
        for (name, export) in &self.exports {
            let atom = atom_table.intern(name);
            ns_obj.set(atom, export.value.clone());
        }
        let ptr = Box::into_raw(Box::new(ns_obj)) as usize;
        self.namespace_object = Some(ptr);
        ptr
    }

    pub fn get_or_create_namespace_object(&mut self, atom_table: &mut AtomTable) -> usize {
        if let Some(ptr) = self.namespace_object {
            ptr
        } else {
            self.create_namespace_object(atom_table)
        }
    }

    pub fn has_dependencies(&self) -> bool {
        !self.imports.is_empty()
    }

    pub fn get_dependencies(&self) -> Vec<String> {
        self.imports
            .iter()
            .map(|imp| imp.module_specifier.clone())
            .filter(|s| !s.is_empty())
            .collect()
    }
}

pub struct ModuleRegistry {
    modules: FxHashMap<String, RefCell<Module>>,
    resolving: Vec<String>,
}

impl ModuleRegistry {
    pub fn new() -> Self {
        ModuleRegistry {
            modules: FxHashMap::default(),
            resolving: Vec::new(),
        }
    }

    pub fn register(&mut self, module: Module) {
        self.modules
            .insert(module.specifier.clone(), RefCell::new(module));
    }

    pub fn get(&self, specifier: &str) -> Option<&RefCell<Module>> {
        self.modules.get(specifier)
    }

    pub fn get_mut(&mut self, specifier: &str) -> Option<&mut RefCell<Module>> {
        self.modules.get_mut(specifier)
    }

    pub fn has(&self, specifier: &str) -> bool {
        self.modules.contains_key(specifier)
    }

    pub fn begin_resolve(&mut self, specifier: &str) -> bool {
        if self.resolving.contains(&specifier.to_string()) {
            return false;
        }
        self.resolving.push(specifier.to_string());
        true
    }

    pub fn end_resolve(&mut self, specifier: &str) {
        self.resolving.retain(|s| s != specifier);
    }

    pub fn is_resolving(&self, specifier: &str) -> bool {
        self.resolving.contains(&specifier.to_string())
    }

    pub fn is_state(&self, specifier: &str, state: ModuleState) -> bool {
        self.modules
            .get(specifier)
            .map(|m| m.borrow().state == state)
            .unwrap_or(false)
    }

    pub fn set_state(&mut self, specifier: &str, state: ModuleState) {
        if let Some(m) = self.modules.get(specifier) {
            m.borrow_mut().state = state;
        }
    }

    pub fn get_all_specifiers(&self) -> Vec<String> {
        self.modules.keys().cloned().collect()
    }
}

impl Default for ModuleRegistry {
    fn default() -> Self {
        Self::new()
    }
}

pub fn resolve_specifier(specifier: &str, base_path: &str) -> String {
    if specifier.starts_with("./") || specifier.starts_with("../") {
        let base = std::path::Path::new(base_path);
        let base_dir = base.parent().unwrap_or(std::path::Path::new("."));
        let resolved = base_dir.join(specifier);
        let canonical = std::fs::canonicalize(&resolved).unwrap_or(resolved);
        canonical.to_string_lossy().to_string()
    } else if specifier.starts_with('/') {
        specifier.to_string()
    } else {
        let path = std::path::Path::new(".").join(specifier);
        let canonical = std::fs::canonicalize(&path).unwrap_or(path);
        canonical.to_string_lossy().to_string()
    }
}

pub fn load_module_source(specifier: &str) -> Result<String, String> {
    let path = if specifier.ends_with(".js") || specifier.ends_with(".mjs") {
        specifier.to_string()
    } else {
        format!("{}.js", specifier)
    };

    std::fs::read_to_string(&path).map_err(|e| format!("Failed to load module '{}': {}", path, e))
}

pub fn load_and_evaluate_module(ctx: &mut JSContext, specifier: &str) -> Result<usize, String> {
    use crate::compiler::ast::BlockStatement;
    use crate::compiler::codegen::CodeGenerator;
    use crate::compiler::parser::Parser;
    use crate::compiler::peephole;
    use crate::runtime::vm::VM;

    let resolved = if specifier.starts_with("./")
        || specifier.starts_with("../")
        || specifier.starts_with('/')
    {
        if let Some(current) = ctx.get_current_module() {
            resolve_specifier(specifier, current)
        } else {
            let cwd = std::env::current_dir()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_else(|_| ".".to_string());
            resolve_specifier(specifier, &cwd)
        }
    } else {
        specifier.to_string()
    };

    let already_evaluated = {
        let registry = ctx.runtime().module_registry();
        registry
            .get(&resolved)
            .map(|m| m.borrow().state == ModuleState::Evaluated)
            .unwrap_or(false)
    };

    if already_evaluated {
        let atom_table_ptr = ctx.atom_table_mut() as *mut _;
        let ns_ptr = unsafe {
            let registry = ctx.runtime_mut().module_registry_mut();
            let module_cell = registry.get_mut(&resolved);
            if let Some(module_cell) = module_cell {
                module_cell
                    .borrow_mut()
                    .get_or_create_namespace_object(&mut *atom_table_ptr)
            } else {
                return Err(format!("Module {} not found", resolved));
            }
        };
        return Ok(ns_ptr);
    }

    let is_manually_registered = {
        let registry = ctx.runtime().module_registry();
        registry
            .get(&resolved)
            .map(|m| {
                let module = m.borrow();
                !module.exports.is_empty()
            })
            .unwrap_or(false)
    };

    if is_manually_registered {
        {
            let registry = ctx.runtime_mut().module_registry_mut();
            if let Some(module_cell) = registry.get_mut(&resolved) {
                module_cell.borrow_mut().state = ModuleState::Evaluated;
            }
        }
        let atom_table_ptr = ctx.atom_table_mut() as *mut _;
        let ns_ptr = unsafe {
            let registry = ctx.runtime_mut().module_registry_mut();
            let module_cell = registry.get_mut(&resolved);
            if let Some(module_cell) = module_cell {
                module_cell
                    .borrow_mut()
                    .get_or_create_namespace_object(&mut *atom_table_ptr)
            } else {
                return Err(format!("Module {} not found", resolved));
            }
        };
        return Ok(ns_ptr);
    }

    {
        let registry = ctx.runtime().module_registry();
        if !registry.has(&resolved) {
            let source = load_module_source(&resolved)?;
            let module = Module::new(resolved.clone(), source);
            ctx.runtime_mut().module_registry_mut().register(module);
        }
    }

    let source = {
        let registry = ctx.runtime().module_registry();
        if let Some(module_cell) = registry.get(&resolved) {
            module_cell.borrow().source.clone()
        } else {
            return Err(format!("Module {} not found after registration", resolved));
        }
    };

    let dependencies: Vec<String> = {
        let registry = ctx.runtime().module_registry();
        if let Some(module_cell) = registry.get(&resolved) {
            module_cell.borrow().get_dependencies()
        } else {
            Vec::new()
        }
    };

    {
        let registry = ctx.runtime_mut().module_registry_mut();
        if let Some(module_cell) = registry.get_mut(&resolved) {
            module_cell.borrow_mut().state = ModuleState::Evaluating;
        }
    }

    for dep_specifier in &dependencies {
        let resolved_dep = if dep_specifier.starts_with("./") || dep_specifier.starts_with("../") {
            resolve_specifier(dep_specifier, &resolved)
        } else {
            dep_specifier.clone()
        };
        load_and_evaluate_module(ctx, &resolved_dep)?;
    }

    let old_module = ctx.get_current_module().map(|s| s.to_string());
    ctx.set_current_module(Some(resolved.clone()));

    let rb = {
        let ast = Parser::new(&source).parse()?;
        let opt_level = ctx.get_compiler_opt_level();
        let mut codegen = CodeGenerator::with_opt_level(opt_level);
        let block = BlockStatement {
            body: ast.body,
            lines: ast.lines,
        };
        let (mut rb, _) = codegen.compile_script(&block, ctx)?;
        peephole::optimize_with_level(&mut rb, opt_level);
        rb
    };

    let result = {
        let mut vm = VM::new();
        vm.execute(ctx, &rb)
    };

    ctx.set_current_module(old_module);

    match result {
        Ok(_) => {
            {
                let registry = ctx.runtime_mut().module_registry_mut();
                if let Some(module_cell) = registry.get_mut(&resolved) {
                    module_cell.borrow_mut().state = ModuleState::Evaluated;
                }
            }
            let ns_ptr = {
                let atom_table_ptr = ctx.atom_table_mut() as *mut _;
                let registry = ctx.runtime_mut().module_registry_mut();
                if let Some(module_cell) = registry.get_mut(&resolved) {
                    unsafe {
                        module_cell
                            .borrow_mut()
                            .get_or_create_namespace_object(&mut *atom_table_ptr)
                    }
                } else {
                    return Err(format!("Module {} not found after evaluation", resolved));
                }
            };
            Ok(ns_ptr)
        }
        Err(e) => {
            {
                let registry = ctx.runtime_mut().module_registry_mut();
                if let Some(module_cell) = registry.get_mut(&resolved) {
                    let mut module = module_cell.borrow_mut();
                    module.state = ModuleState::Errored;
                    module.error = Some(e.clone());
                }
            }
            Err(e)
        }
    }
}