polycomp 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Cargo.toml +25 -0
- package/bin/native/polycomp.exe +0 -0
- package/bin/polycomp.js +25 -0
- package/js/frontend.js +1061 -0
- package/js/index.cjs +245 -0
- package/js/index.d.ts +2 -0
- package/js/index.mjs +19 -0
- package/js/polycomp-vm.mjs +1047 -0
- package/package.json +41 -5
- package/src/ast.rs +329 -0
- package/src/bundle.rs +3307 -0
- package/src/diagnostics.rs +276 -0
- package/src/interpreter.rs +1565 -0
- package/src/ir.rs +272 -0
- package/src/jit.rs +1151 -0
- package/src/lib.rs +11 -0
- package/src/lowering.rs +1157 -0
- package/src/main.rs +655 -0
- package/src/optimizer.rs +660 -0
- package/src/parser.rs +4755 -0
- package/src/resolver.rs +722 -0
- package/src/runtime.rs +1104 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1565 @@
|
|
|
1
|
+
use crate::ast::Language;
|
|
2
|
+
use crate::bundle::IrBundle;
|
|
3
|
+
use crate::diagnostics::PolyError;
|
|
4
|
+
use crate::ir::*;
|
|
5
|
+
use crate::jit::{is_jit_eligible, JitAbiVal, JitCallbacks, JitEngine};
|
|
6
|
+
use crate::lowering::{lower_function, lower_top_level};
|
|
7
|
+
use crate::optimizer::optimize_function;
|
|
8
|
+
use crate::resolver::{ModuleResolver, StaticCheckReport};
|
|
9
|
+
use crate::runtime::{
|
|
10
|
+
eval_builtin, make_heap, ClassInstance, GcStats, MemoryHeap, MemoryMode, StrHandle,
|
|
11
|
+
Value,
|
|
12
|
+
};
|
|
13
|
+
use rustc_hash::{FxHashMap, FxHashSet};
|
|
14
|
+
use std::path::{Path, PathBuf};
|
|
15
|
+
|
|
16
|
+
#[derive(Debug, Clone)]
|
|
17
|
+
pub struct RunConfig {
|
|
18
|
+
pub memory_mode: MemoryMode,
|
|
19
|
+
pub enable_jit: bool,
|
|
20
|
+
pub jit_threshold: u32,
|
|
21
|
+
pub trace_imports: bool,
|
|
22
|
+
pub capture_stdout: bool,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
impl Default for RunConfig {
|
|
26
|
+
fn default() -> Self {
|
|
27
|
+
Self {
|
|
28
|
+
memory_mode: MemoryMode::TracingGc,
|
|
29
|
+
enable_jit: true,
|
|
30
|
+
jit_threshold: 1,
|
|
31
|
+
trace_imports: false,
|
|
32
|
+
capture_stdout: false,
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
#[derive(Debug, Clone, Default)]
|
|
38
|
+
pub struct RunStats {
|
|
39
|
+
pub modules_parsed: usize,
|
|
40
|
+
pub parsed_paths: Vec<PathBuf>,
|
|
41
|
+
pub functions_lowered: usize,
|
|
42
|
+
pub functions_jit_compiled: usize,
|
|
43
|
+
pub jit_invocations: usize,
|
|
44
|
+
pub vm_invocations: usize,
|
|
45
|
+
pub call_sites_resolved: usize,
|
|
46
|
+
pub gc_stats: GcStats,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
pub struct RunOutcome {
|
|
50
|
+
pub return_value: Value,
|
|
51
|
+
pub formatted_return: String,
|
|
52
|
+
pub stdout: String,
|
|
53
|
+
pub stats: RunStats,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#[derive(Debug, Clone, Copy)]
|
|
57
|
+
struct ExceptionHandler {
|
|
58
|
+
catch_bb: BasicBlockId,
|
|
59
|
+
err_reg: Register,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
pub struct VmEngine {
|
|
63
|
+
pub resolver: ModuleResolver,
|
|
64
|
+
pub heap: Box<dyn MemoryHeap>,
|
|
65
|
+
pub jit: Option<JitEngine>,
|
|
66
|
+
pub config: RunConfig,
|
|
67
|
+
pub functions: Vec<IrFunction>,
|
|
68
|
+
pub fn_map: FxHashMap<(usize, String), FnId>,
|
|
69
|
+
pub call_sites: Vec<CallSite>,
|
|
70
|
+
pub call_counts: Vec<u32>,
|
|
71
|
+
pub top_level_ran: FxHashSet<usize>,
|
|
72
|
+
pub active_roots: Vec<Vec<Value>>,
|
|
73
|
+
pub stdout_sink: Option<String>,
|
|
74
|
+
pub stats: RunStats,
|
|
75
|
+
pub last_error: Option<PolyError>,
|
|
76
|
+
pub last_trap_code: Option<u32>,
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
impl VmEngine {
|
|
80
|
+
pub fn new(config: RunConfig) -> Result<Self, PolyError> {
|
|
81
|
+
let heap = make_heap(config.memory_mode);
|
|
82
|
+
let jit = if config.enable_jit {
|
|
83
|
+
Some(JitEngine::new(JitCallbacks {
|
|
84
|
+
call_site: rt_call_site,
|
|
85
|
+
call_fn: rt_call_fn,
|
|
86
|
+
call_builtin: rt_call_builtin,
|
|
87
|
+
set_trap: rt_set_trap,
|
|
88
|
+
})?)
|
|
89
|
+
} else {
|
|
90
|
+
None
|
|
91
|
+
};
|
|
92
|
+
let stdout_sink = if config.capture_stdout {
|
|
93
|
+
Some(String::new())
|
|
94
|
+
} else {
|
|
95
|
+
None
|
|
96
|
+
};
|
|
97
|
+
Ok(Self {
|
|
98
|
+
resolver: ModuleResolver::new(config.trace_imports),
|
|
99
|
+
heap,
|
|
100
|
+
jit,
|
|
101
|
+
config,
|
|
102
|
+
functions: Vec::new(),
|
|
103
|
+
fn_map: FxHashMap::default(),
|
|
104
|
+
call_sites: Vec::new(),
|
|
105
|
+
call_counts: Vec::new(),
|
|
106
|
+
top_level_ran: FxHashSet::default(),
|
|
107
|
+
active_roots: Vec::new(),
|
|
108
|
+
stdout_sink,
|
|
109
|
+
stats: RunStats::default(),
|
|
110
|
+
last_error: None,
|
|
111
|
+
last_trap_code: None,
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
pub fn run_entry(
|
|
116
|
+
&mut self,
|
|
117
|
+
entry_path: &Path,
|
|
118
|
+
entry_fn: &str,
|
|
119
|
+
args: &[Value],
|
|
120
|
+
) -> Result<RunOutcome, PolyError> {
|
|
121
|
+
let entry_mod_id = self.resolver.load_module(entry_path)?;
|
|
122
|
+
self.run_module_top_level_if_needed(entry_mod_id)?;
|
|
123
|
+
|
|
124
|
+
let actual_entry = self
|
|
125
|
+
.resolver
|
|
126
|
+
.resolve_entry_fn_name(entry_mod_id, entry_fn)
|
|
127
|
+
.unwrap_or_else(|| entry_fn.to_string());
|
|
128
|
+
|
|
129
|
+
let fn_id = self.ensure_function_compiled(entry_mod_id, &actual_entry)?;
|
|
130
|
+
let ret = self.invoke_fn(fn_id, args)?;
|
|
131
|
+
|
|
132
|
+
self.stats.modules_parsed = self.resolver.stats.modules_parsed;
|
|
133
|
+
self.stats.parsed_paths = self.resolver.stats.parsed_paths.clone();
|
|
134
|
+
self.stats.gc_stats = self.heap.stats();
|
|
135
|
+
|
|
136
|
+
let formatted_return = ret.format(&*self.heap);
|
|
137
|
+
let stdout = self.stdout_sink.take().unwrap_or_default();
|
|
138
|
+
|
|
139
|
+
Ok(RunOutcome {
|
|
140
|
+
return_value: ret,
|
|
141
|
+
formatted_return,
|
|
142
|
+
stdout,
|
|
143
|
+
stats: self.stats.clone(),
|
|
144
|
+
})
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
pub fn run_inline_source(
|
|
148
|
+
&mut self,
|
|
149
|
+
virtual_path: &Path,
|
|
150
|
+
lang: Language,
|
|
151
|
+
source: String,
|
|
152
|
+
entry_fn: &str,
|
|
153
|
+
args: &[Value],
|
|
154
|
+
) -> Result<RunOutcome, PolyError> {
|
|
155
|
+
let entry_mod_id = self
|
|
156
|
+
.resolver
|
|
157
|
+
.load_source_in_memory(virtual_path, lang, source)?;
|
|
158
|
+
self.run_module_top_level_if_needed(entry_mod_id)?;
|
|
159
|
+
|
|
160
|
+
let actual_entry = self
|
|
161
|
+
.resolver
|
|
162
|
+
.resolve_entry_fn_name(entry_mod_id, entry_fn)
|
|
163
|
+
.unwrap_or_else(|| entry_fn.to_string());
|
|
164
|
+
|
|
165
|
+
let fn_id = self.ensure_function_compiled(entry_mod_id, &actual_entry)?;
|
|
166
|
+
let ret = self.invoke_fn(fn_id, args)?;
|
|
167
|
+
|
|
168
|
+
self.stats.modules_parsed = self.resolver.stats.modules_parsed;
|
|
169
|
+
self.stats.parsed_paths = self.resolver.stats.parsed_paths.clone();
|
|
170
|
+
self.stats.gc_stats = self.heap.stats();
|
|
171
|
+
|
|
172
|
+
let formatted_return = ret.format(&*self.heap);
|
|
173
|
+
let stdout = self.stdout_sink.take().unwrap_or_default();
|
|
174
|
+
|
|
175
|
+
Ok(RunOutcome {
|
|
176
|
+
return_value: ret,
|
|
177
|
+
formatted_return,
|
|
178
|
+
stdout,
|
|
179
|
+
stats: self.stats.clone(),
|
|
180
|
+
})
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
pub fn dump_reachable_ir(
|
|
184
|
+
&mut self,
|
|
185
|
+
entry_path: &Path,
|
|
186
|
+
entry_fn: &str,
|
|
187
|
+
) -> Result<Vec<IrFunction>, PolyError> {
|
|
188
|
+
let entry_mod_id = self.resolver.load_module(entry_path)?;
|
|
189
|
+
let reachable = self
|
|
190
|
+
.resolver
|
|
191
|
+
.check_reachable_from_entry(entry_mod_id, entry_fn)?;
|
|
192
|
+
let mut out = Vec::new();
|
|
193
|
+
for (mod_id, fname) in reachable {
|
|
194
|
+
let fn_id = self.ensure_function_compiled(mod_id, &fname)?;
|
|
195
|
+
out.push(self.functions[fn_id.0 as usize].clone());
|
|
196
|
+
}
|
|
197
|
+
Ok(out)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
pub fn compile_to_bundle(
|
|
201
|
+
&mut self,
|
|
202
|
+
entry_path: &Path,
|
|
203
|
+
entry_fn: &str,
|
|
204
|
+
) -> Result<IrBundle, PolyError> {
|
|
205
|
+
let entry_mod_id = self.resolver.load_module(entry_path)?;
|
|
206
|
+
self.compile_loaded_module(entry_mod_id, entry_fn)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
pub fn compile_inline_to_bundle(
|
|
210
|
+
&mut self,
|
|
211
|
+
virtual_path: &Path,
|
|
212
|
+
lang: Language,
|
|
213
|
+
source: String,
|
|
214
|
+
entry_fn: &str,
|
|
215
|
+
) -> Result<IrBundle, PolyError> {
|
|
216
|
+
let entry_mod_id = self
|
|
217
|
+
.resolver
|
|
218
|
+
.load_source_in_memory(virtual_path, lang, source)?;
|
|
219
|
+
self.compile_loaded_module(entry_mod_id, entry_fn)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
fn compile_loaded_module(
|
|
223
|
+
&mut self,
|
|
224
|
+
entry_mod_id: usize,
|
|
225
|
+
entry_fn: &str,
|
|
226
|
+
) -> Result<IrBundle, PolyError> {
|
|
227
|
+
let reachable = self
|
|
228
|
+
.resolver
|
|
229
|
+
.check_reachable_from_entry(entry_mod_id, entry_fn)?;
|
|
230
|
+
|
|
231
|
+
let mut init_fns = Vec::new();
|
|
232
|
+
let mut seen_mods = FxHashSet::default();
|
|
233
|
+
for &(mod_id, _) in &reachable {
|
|
234
|
+
if seen_mods.insert(mod_id) {
|
|
235
|
+
let m = self.resolver.get_module(mod_id);
|
|
236
|
+
if !m.ast.top_level.is_empty() {
|
|
237
|
+
let stmts = m.ast.top_level.clone();
|
|
238
|
+
let bindings = m.bindings.clone();
|
|
239
|
+
let fn_idx_map = m.function_index.clone();
|
|
240
|
+
let mod_name = m
|
|
241
|
+
.path
|
|
242
|
+
.file_stem()
|
|
243
|
+
.and_then(|s| s.to_str())
|
|
244
|
+
.unwrap_or("module")
|
|
245
|
+
.to_string();
|
|
246
|
+
let fn_id = FnId(self.functions.len() as u32);
|
|
247
|
+
let mut ir_fn = lower_top_level(
|
|
248
|
+
fn_id,
|
|
249
|
+
mod_id,
|
|
250
|
+
format!("{mod_name}::__top_level"),
|
|
251
|
+
&stmts,
|
|
252
|
+
&bindings,
|
|
253
|
+
&fn_idx_map,
|
|
254
|
+
&mut self.call_sites,
|
|
255
|
+
)?;
|
|
256
|
+
optimize_function(&mut ir_fn);
|
|
257
|
+
self.functions.push(ir_fn);
|
|
258
|
+
self.call_counts.push(0);
|
|
259
|
+
self.stats.functions_lowered += 1;
|
|
260
|
+
init_fns.push(fn_id);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
let mut exports = Vec::new();
|
|
266
|
+
for (mod_id, fname) in &reachable {
|
|
267
|
+
let fn_id = self.ensure_function_compiled(*mod_id, fname)?;
|
|
268
|
+
let mod_stem = self
|
|
269
|
+
.resolver
|
|
270
|
+
.get_module(*mod_id)
|
|
271
|
+
.path
|
|
272
|
+
.file_stem()
|
|
273
|
+
.and_then(|s| s.to_str())
|
|
274
|
+
.unwrap_or("module")
|
|
275
|
+
.to_string();
|
|
276
|
+
exports.push((format!("{mod_stem}::{fname}"), fn_id));
|
|
277
|
+
if *mod_id == entry_mod_id {
|
|
278
|
+
exports.push((fname.clone(), fn_id));
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
let actual_entry = self
|
|
283
|
+
.resolver
|
|
284
|
+
.resolve_entry_fn_name(entry_mod_id, entry_fn)
|
|
285
|
+
.unwrap_or_else(|| entry_fn.to_string());
|
|
286
|
+
let entry_fn_id = self.ensure_function_compiled(entry_mod_id, &actual_entry)?;
|
|
287
|
+
|
|
288
|
+
let mut idx = 0usize;
|
|
289
|
+
while idx < self.functions.len() {
|
|
290
|
+
let block_count = self.functions[idx].blocks.len();
|
|
291
|
+
for b in 0..block_count {
|
|
292
|
+
let instr_count = self.functions[idx].blocks[b].instructions.len();
|
|
293
|
+
for j in 0..instr_count {
|
|
294
|
+
let instr = self.functions[idx].blocks[b].instructions[j].clone();
|
|
295
|
+
match instr {
|
|
296
|
+
IrInstruction::CallLazy(dst, site_id, args) => {
|
|
297
|
+
let target_id = self.resolve_call_site(site_id)?;
|
|
298
|
+
self.functions[idx].blocks[b].instructions[j] =
|
|
299
|
+
IrInstruction::CallFn(dst, target_id, args);
|
|
300
|
+
}
|
|
301
|
+
IrInstruction::ResolveFn(dst, site_id) => {
|
|
302
|
+
let target_id = self.resolve_call_site(site_id)?;
|
|
303
|
+
self.functions[idx].blocks[b].instructions[j] =
|
|
304
|
+
IrInstruction::LoadFnRef(dst, target_id);
|
|
305
|
+
}
|
|
306
|
+
_ => {}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
optimize_function(&mut self.functions[idx]);
|
|
311
|
+
idx += 1;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
Ok(IrBundle {
|
|
315
|
+
entry_fn: entry_fn_id,
|
|
316
|
+
entry_name: entry_fn.to_string(),
|
|
317
|
+
init_fns,
|
|
318
|
+
exports,
|
|
319
|
+
functions: self.functions.clone(),
|
|
320
|
+
})
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
pub fn run_bundle(
|
|
324
|
+
&mut self,
|
|
325
|
+
bundle: IrBundle,
|
|
326
|
+
entry_override: Option<&str>,
|
|
327
|
+
args: &[Value],
|
|
328
|
+
) -> Result<RunOutcome, PolyError> {
|
|
329
|
+
self.functions = bundle.functions;
|
|
330
|
+
self.call_counts = vec![0; self.functions.len()];
|
|
331
|
+
self.fn_map.clear();
|
|
332
|
+
self.call_sites.clear();
|
|
333
|
+
|
|
334
|
+
for init_id in bundle.init_fns {
|
|
335
|
+
let _ = self.invoke_fn(init_id, &[])?;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
let target_fn_id = if let Some(name) = entry_override {
|
|
339
|
+
if name == bundle.entry_name {
|
|
340
|
+
bundle.entry_fn
|
|
341
|
+
} else if let Some((_, id)) = bundle.exports.iter().find(|(n, _)| n == name) {
|
|
342
|
+
*id
|
|
343
|
+
} else {
|
|
344
|
+
return Err(PolyError::msg(
|
|
345
|
+
"E0501",
|
|
346
|
+
format!("function '{name}' not found in IR bundle"),
|
|
347
|
+
));
|
|
348
|
+
}
|
|
349
|
+
} else {
|
|
350
|
+
bundle.entry_fn
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
let ret = self.invoke_fn(target_fn_id, args)?;
|
|
354
|
+
self.stats.modules_parsed = 0;
|
|
355
|
+
self.stats.gc_stats = self.heap.stats();
|
|
356
|
+
|
|
357
|
+
let formatted_return = ret.format(&*self.heap);
|
|
358
|
+
let stdout = self.stdout_sink.take().unwrap_or_default();
|
|
359
|
+
|
|
360
|
+
Ok(RunOutcome {
|
|
361
|
+
return_value: ret,
|
|
362
|
+
formatted_return,
|
|
363
|
+
stdout,
|
|
364
|
+
stats: self.stats.clone(),
|
|
365
|
+
})
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
fn run_module_top_level_if_needed(&mut self, module_id: usize) -> Result<(), PolyError> {
|
|
369
|
+
if !self.top_level_ran.insert(module_id) {
|
|
370
|
+
return Ok(());
|
|
371
|
+
}
|
|
372
|
+
let m = self.resolver.get_module(module_id);
|
|
373
|
+
if m.ast.top_level.is_empty() {
|
|
374
|
+
return Ok(());
|
|
375
|
+
}
|
|
376
|
+
let stmts = m.ast.top_level.clone();
|
|
377
|
+
let bindings = m.bindings.clone();
|
|
378
|
+
let fn_idx_map = m.function_index.clone();
|
|
379
|
+
let mod_name = m
|
|
380
|
+
.path
|
|
381
|
+
.file_stem()
|
|
382
|
+
.and_then(|s| s.to_str())
|
|
383
|
+
.unwrap_or("module")
|
|
384
|
+
.to_string();
|
|
385
|
+
|
|
386
|
+
let fn_id = FnId(self.functions.len() as u32);
|
|
387
|
+
let mut ir_fn = lower_top_level(
|
|
388
|
+
fn_id,
|
|
389
|
+
module_id,
|
|
390
|
+
format!("{mod_name}::__top_level"),
|
|
391
|
+
&stmts,
|
|
392
|
+
&bindings,
|
|
393
|
+
&fn_idx_map,
|
|
394
|
+
&mut self.call_sites,
|
|
395
|
+
)?;
|
|
396
|
+
optimize_function(&mut ir_fn);
|
|
397
|
+
self.functions.push(ir_fn);
|
|
398
|
+
self.call_counts.push(0);
|
|
399
|
+
self.stats.functions_lowered += 1;
|
|
400
|
+
let _ = self.invoke_fn(fn_id, &[])?;
|
|
401
|
+
Ok(())
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
pub fn ensure_function_compiled(
|
|
405
|
+
&mut self,
|
|
406
|
+
module_id: usize,
|
|
407
|
+
fn_name: &str,
|
|
408
|
+
) -> Result<FnId, PolyError> {
|
|
409
|
+
if let Some(&id) = self.fn_map.get(&(module_id, fn_name.to_string())) {
|
|
410
|
+
return Ok(id);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
let m = self.resolver.get_module(module_id);
|
|
414
|
+
let decl_idx = *m.function_index.get(fn_name).ok_or_else(|| {
|
|
415
|
+
PolyError::msg(
|
|
416
|
+
"E0501",
|
|
417
|
+
format!(
|
|
418
|
+
"function '{}' not found in '{}'",
|
|
419
|
+
fn_name,
|
|
420
|
+
m.path.display()
|
|
421
|
+
),
|
|
422
|
+
)
|
|
423
|
+
})?;
|
|
424
|
+
let decl = m.ast.functions[decl_idx].clone();
|
|
425
|
+
let bindings = m.bindings.clone();
|
|
426
|
+
let local_fn_names = m.function_index.clone();
|
|
427
|
+
let mod_stem = m
|
|
428
|
+
.path
|
|
429
|
+
.file_stem()
|
|
430
|
+
.and_then(|s| s.to_str())
|
|
431
|
+
.unwrap_or("module")
|
|
432
|
+
.to_string();
|
|
433
|
+
|
|
434
|
+
let fn_id = FnId(self.functions.len() as u32);
|
|
435
|
+
let mut ir_fn = lower_function(
|
|
436
|
+
fn_id,
|
|
437
|
+
module_id,
|
|
438
|
+
format!("{mod_stem}::{fn_name}"),
|
|
439
|
+
&decl,
|
|
440
|
+
&bindings,
|
|
441
|
+
&local_fn_names,
|
|
442
|
+
&mut self.call_sites,
|
|
443
|
+
)?;
|
|
444
|
+
optimize_function(&mut ir_fn);
|
|
445
|
+
|
|
446
|
+
self.functions.push(ir_fn);
|
|
447
|
+
self.call_counts.push(0);
|
|
448
|
+
self.fn_map.insert((module_id, fn_name.to_string()), fn_id);
|
|
449
|
+
self.stats.functions_lowered += 1;
|
|
450
|
+
Ok(fn_id)
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
pub fn resolve_call_site(&mut self, site_id: CallSiteId) -> Result<FnId, PolyError> {
|
|
454
|
+
if let Some(id) = self.call_sites[site_id.0 as usize].resolved_fn {
|
|
455
|
+
return Ok(id);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
let site = self.call_sites[site_id.0 as usize].clone();
|
|
459
|
+
let (target_mod, target_fn) = match site.target {
|
|
460
|
+
LazyTarget::SelfModule { module_id, symbol } => (module_id, symbol),
|
|
461
|
+
LazyTarget::ModuleMember { module_id, member } => (module_id, member),
|
|
462
|
+
LazyTarget::Direct {
|
|
463
|
+
from_module,
|
|
464
|
+
symbol,
|
|
465
|
+
} => {
|
|
466
|
+
if let Some((ns, member)) = symbol.split_once("::") {
|
|
467
|
+
self.resolver
|
|
468
|
+
.resolve_member_function_lazy(from_module, ns, member, site.span)?
|
|
469
|
+
} else {
|
|
470
|
+
self.resolver
|
|
471
|
+
.resolve_symbol_lazy(from_module, &symbol, site.span)?
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
self.run_module_top_level_if_needed(target_mod)?;
|
|
477
|
+
let fn_id = self.ensure_function_compiled(target_mod, &target_fn)?;
|
|
478
|
+
self.call_sites[site_id.0 as usize].resolved_fn = Some(fn_id);
|
|
479
|
+
self.stats.call_sites_resolved += 1;
|
|
480
|
+
Ok(fn_id)
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
pub fn invoke_fn(&mut self, fn_id: FnId, args: &[Value]) -> Result<Value, PolyError> {
|
|
484
|
+
let idx = fn_id.0 as usize;
|
|
485
|
+
self.call_counts[idx] += 1;
|
|
486
|
+
let count = self.call_counts[idx];
|
|
487
|
+
|
|
488
|
+
if self.config.enable_jit && count >= self.config.jit_threshold {
|
|
489
|
+
let already_compiled = self.jit.as_ref().and_then(|j| j.get(fn_id)).is_some();
|
|
490
|
+
if !already_compiled && is_jit_eligible(&self.functions[idx]) {
|
|
491
|
+
let ir_clone = self.functions[idx].clone();
|
|
492
|
+
let heap_ptr: *mut dyn MemoryHeap = &mut *self.heap;
|
|
493
|
+
if let Some(jit) = self.jit.as_mut() {
|
|
494
|
+
let compiled = jit.compile_function(&ir_clone, |s| {
|
|
495
|
+
let h = unsafe { &mut *heap_ptr };
|
|
496
|
+
h.alloc_string(s.to_string()).0
|
|
497
|
+
});
|
|
498
|
+
match compiled {
|
|
499
|
+
Ok(_) => self.stats.functions_jit_compiled += 1,
|
|
500
|
+
Err(e) if self.config.trace_imports => {
|
|
501
|
+
eprintln!("[polycomp:jit] skip {}: {e}", ir_clone.qualified_name);
|
|
502
|
+
}
|
|
503
|
+
Err(_) => {}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
if let Some(entry) = self.jit.as_ref().and_then(|j| j.get(fn_id)).cloned() {
|
|
509
|
+
return self.invoke_jit(&entry, args);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
self.invoke_vm(fn_id, args)
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
fn invoke_jit(
|
|
517
|
+
&mut self,
|
|
518
|
+
entry: &crate::jit::JitEntry,
|
|
519
|
+
args: &[Value],
|
|
520
|
+
) -> Result<Value, PolyError> {
|
|
521
|
+
self.stats.jit_invocations += 1;
|
|
522
|
+
let expected = entry.param_types.len();
|
|
523
|
+
if args.len() != expected {
|
|
524
|
+
return Err(PolyError::msg(
|
|
525
|
+
"E0502",
|
|
526
|
+
format!("expected {expected} arguments, got {}", args.len()),
|
|
527
|
+
));
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
let mut raw_args = Vec::with_capacity(expected);
|
|
531
|
+
for (i, &pty) in entry.param_types.iter().enumerate() {
|
|
532
|
+
let raw = match (pty, args[i]) {
|
|
533
|
+
(IrType::I64, Value::Int(v)) => v as u64,
|
|
534
|
+
(IrType::I64, Value::Float(f)) => (f as i64) as u64,
|
|
535
|
+
(IrType::I64, Value::Bool(b)) => u64::from(b),
|
|
536
|
+
(IrType::F64, Value::Float(f)) => f.to_bits(),
|
|
537
|
+
(IrType::F64, Value::Int(v)) => (v as f64).to_bits(),
|
|
538
|
+
(IrType::Bool, v) => u64::from(v.is_truthy(&*self.heap)),
|
|
539
|
+
(IrType::Str, Value::Str(h)) => u64::from(h.0),
|
|
540
|
+
_ => {
|
|
541
|
+
return Err(PolyError::msg(
|
|
542
|
+
"E0503",
|
|
543
|
+
format!(
|
|
544
|
+
"incompatible argument #{} type '{}' for JIT function expecting {:?}",
|
|
545
|
+
i + 1,
|
|
546
|
+
args[i].type_name(),
|
|
547
|
+
pty
|
|
548
|
+
),
|
|
549
|
+
));
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
raw_args.push(raw);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
let mut raw_out: u64 = 0;
|
|
556
|
+
let tramp = entry.trampoline;
|
|
557
|
+
let ret_ty = entry.return_type;
|
|
558
|
+
let vm_ptr = self as *mut VmEngine as *mut u8;
|
|
559
|
+
let status = unsafe { tramp(vm_ptr, raw_args.as_ptr(), &mut raw_out) };
|
|
560
|
+
|
|
561
|
+
if status != 0 {
|
|
562
|
+
if let Some(err) = self.last_error.take() {
|
|
563
|
+
return Err(err);
|
|
564
|
+
}
|
|
565
|
+
if let Some(code) = self.last_trap_code.take()
|
|
566
|
+
&& code == 1
|
|
567
|
+
{
|
|
568
|
+
return Err(PolyError::msg("E0504", "division or modulo by zero"));
|
|
569
|
+
}
|
|
570
|
+
return Err(PolyError::msg("E0505", "JIT runtime trap"));
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
let val = match ret_ty {
|
|
574
|
+
IrType::Void => Value::Nil,
|
|
575
|
+
IrType::I64 => Value::Int(raw_out as i64),
|
|
576
|
+
IrType::F64 => Value::Float(f64::from_bits(raw_out)),
|
|
577
|
+
IrType::Bool => Value::Bool(raw_out != 0),
|
|
578
|
+
IrType::Str => Value::Str(StrHandle(raw_out as u32)),
|
|
579
|
+
IrType::Dynamic => Value::Nil,
|
|
580
|
+
};
|
|
581
|
+
Ok(val)
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
fn invoke_vm(&mut self, fn_id: FnId, args: &[Value]) -> Result<Value, PolyError> {
|
|
585
|
+
self.stats.vm_invocations += 1;
|
|
586
|
+
let func = self.functions[fn_id.0 as usize].clone();
|
|
587
|
+
|
|
588
|
+
if args.len() != func.params.len() {
|
|
589
|
+
return Err(PolyError::msg(
|
|
590
|
+
"E0502",
|
|
591
|
+
format!(
|
|
592
|
+
"function '{}' expects {} arguments, got {}",
|
|
593
|
+
func.qualified_name,
|
|
594
|
+
func.params.len(),
|
|
595
|
+
args.len()
|
|
596
|
+
),
|
|
597
|
+
));
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
let frame_idx = self.active_roots.len();
|
|
601
|
+
let mut regs = vec![Value::Nil; func.register_types.len()];
|
|
602
|
+
for (i, (reg, pty)) in func.params.iter().enumerate() {
|
|
603
|
+
regs[reg.0] = cast_value(args[i], *pty, &mut *self.heap)?;
|
|
604
|
+
}
|
|
605
|
+
self.active_roots.push(regs);
|
|
606
|
+
|
|
607
|
+
let result = self.exec_blocks(&func, frame_idx);
|
|
608
|
+
self.active_roots.pop();
|
|
609
|
+
|
|
610
|
+
if self.heap.mode() == MemoryMode::TracingGc {
|
|
611
|
+
let mut roots = Vec::new();
|
|
612
|
+
for frame in &self.active_roots {
|
|
613
|
+
roots.extend(frame.iter().copied());
|
|
614
|
+
}
|
|
615
|
+
if let Ok(ret_v) = &result {
|
|
616
|
+
roots.push(*ret_v);
|
|
617
|
+
}
|
|
618
|
+
self.heap.maybe_collect(&roots);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
result
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
fn exec_blocks(&mut self, func: &IrFunction, frame: usize) -> Result<Value, PolyError> {
|
|
625
|
+
let mut bb_idx = 0usize;
|
|
626
|
+
let mut ip = 0usize;
|
|
627
|
+
let mut try_stack: Vec<ExceptionHandler> = Vec::new();
|
|
628
|
+
|
|
629
|
+
while bb_idx < func.blocks.len() {
|
|
630
|
+
let bb = &func.blocks[bb_idx];
|
|
631
|
+
if ip >= bb.instructions.len() {
|
|
632
|
+
break;
|
|
633
|
+
}
|
|
634
|
+
match &bb.instructions[ip] {
|
|
635
|
+
IrInstruction::LoadConst(dst, c) => {
|
|
636
|
+
let v = match c {
|
|
637
|
+
Constant::Nil => Value::Nil,
|
|
638
|
+
Constant::Bool(b) => Value::Bool(*b),
|
|
639
|
+
Constant::Int(i) => Value::Int(*i),
|
|
640
|
+
Constant::Float(f) => Value::Float(*f),
|
|
641
|
+
Constant::String(s) => Value::Str(self.heap.alloc_string(s.clone())),
|
|
642
|
+
Constant::Regex { pattern, flags } => {
|
|
643
|
+
let h = self.heap.alloc_regex(pattern, flags)?;
|
|
644
|
+
Value::Regex(h)
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
self.active_roots[frame][dst.0] = v;
|
|
648
|
+
ip += 1;
|
|
649
|
+
}
|
|
650
|
+
IrInstruction::Move(dst, src) => {
|
|
651
|
+
let v = self.active_roots[frame][src.0];
|
|
652
|
+
self.active_roots[frame][dst.0] = v;
|
|
653
|
+
ip += 1;
|
|
654
|
+
}
|
|
655
|
+
IrInstruction::Cast(dst, ty, src) => {
|
|
656
|
+
let v = self.active_roots[frame][src.0];
|
|
657
|
+
let cv = cast_value(v, *ty, &mut *self.heap)?;
|
|
658
|
+
self.active_roots[frame][dst.0] = cv;
|
|
659
|
+
ip += 1;
|
|
660
|
+
}
|
|
661
|
+
IrInstruction::UnaryOp(op, dst, src) => {
|
|
662
|
+
let v = self.active_roots[frame][src.0];
|
|
663
|
+
let res = eval_unary(*op, v, &*self.heap)?;
|
|
664
|
+
self.active_roots[frame][dst.0] = res;
|
|
665
|
+
ip += 1;
|
|
666
|
+
}
|
|
667
|
+
IrInstruction::BinOp(op, dst, l, r) => {
|
|
668
|
+
let lv = self.active_roots[frame][l.0];
|
|
669
|
+
let rv = self.active_roots[frame][r.0];
|
|
670
|
+
match eval_binop(*op, lv, rv, &mut *self.heap) {
|
|
671
|
+
Ok(res) => {
|
|
672
|
+
self.active_roots[frame][dst.0] = res;
|
|
673
|
+
ip += 1;
|
|
674
|
+
}
|
|
675
|
+
Err(e) => {
|
|
676
|
+
if let Some(h) = try_stack.pop() {
|
|
677
|
+
let s = self.heap.alloc_string(e.to_string());
|
|
678
|
+
self.active_roots[frame][h.err_reg.0] = Value::Str(s);
|
|
679
|
+
bb_idx = h.catch_bb.0;
|
|
680
|
+
ip = 0;
|
|
681
|
+
} else {
|
|
682
|
+
return Err(e);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
IrInstruction::CallLazy(dst, site_id, arg_regs) => {
|
|
688
|
+
let args: Vec<Value> = arg_regs
|
|
689
|
+
.iter()
|
|
690
|
+
.map(|r| self.active_roots[frame][r.0])
|
|
691
|
+
.collect();
|
|
692
|
+
let target_id = self.resolve_call_site(*site_id)?;
|
|
693
|
+
match self.invoke_fn(target_id, &args) {
|
|
694
|
+
Ok(ret) => {
|
|
695
|
+
self.active_roots[frame][dst.0] = ret;
|
|
696
|
+
ip += 1;
|
|
697
|
+
}
|
|
698
|
+
Err(e) => {
|
|
699
|
+
if let Some(h) = try_stack.pop() {
|
|
700
|
+
let s = self.heap.alloc_string(e.to_string());
|
|
701
|
+
self.active_roots[frame][h.err_reg.0] = Value::Str(s);
|
|
702
|
+
bb_idx = h.catch_bb.0;
|
|
703
|
+
ip = 0;
|
|
704
|
+
} else {
|
|
705
|
+
return Err(e);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
IrInstruction::CallFn(dst, target_id, arg_regs) => {
|
|
711
|
+
let args: Vec<Value> = arg_regs
|
|
712
|
+
.iter()
|
|
713
|
+
.map(|r| self.active_roots[frame][r.0])
|
|
714
|
+
.collect();
|
|
715
|
+
match self.invoke_fn(*target_id, &args) {
|
|
716
|
+
Ok(ret) => {
|
|
717
|
+
self.active_roots[frame][dst.0] = ret;
|
|
718
|
+
ip += 1;
|
|
719
|
+
}
|
|
720
|
+
Err(e) => {
|
|
721
|
+
if let Some(h) = try_stack.pop() {
|
|
722
|
+
let s = self.heap.alloc_string(e.to_string());
|
|
723
|
+
self.active_roots[frame][h.err_reg.0] = Value::Str(s);
|
|
724
|
+
bb_idx = h.catch_bb.0;
|
|
725
|
+
ip = 0;
|
|
726
|
+
} else {
|
|
727
|
+
return Err(e);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
IrInstruction::CallIndirect(dst, fn_reg, arg_regs) => {
|
|
733
|
+
let callee = self.active_roots[frame][fn_reg.0];
|
|
734
|
+
let Value::FunctionRef(target_id) = callee else {
|
|
735
|
+
return Err(PolyError::msg(
|
|
736
|
+
"E0506",
|
|
737
|
+
format!(
|
|
738
|
+
"attempted to call non-function value of type {}",
|
|
739
|
+
callee.type_name()
|
|
740
|
+
),
|
|
741
|
+
));
|
|
742
|
+
};
|
|
743
|
+
let args: Vec<Value> = arg_regs
|
|
744
|
+
.iter()
|
|
745
|
+
.map(|r| self.active_roots[frame][r.0])
|
|
746
|
+
.collect();
|
|
747
|
+
match self.invoke_fn(target_id, &args) {
|
|
748
|
+
Ok(ret) => {
|
|
749
|
+
self.active_roots[frame][dst.0] = ret;
|
|
750
|
+
ip += 1;
|
|
751
|
+
}
|
|
752
|
+
Err(e) => {
|
|
753
|
+
if let Some(h) = try_stack.pop() {
|
|
754
|
+
let s = self.heap.alloc_string(e.to_string());
|
|
755
|
+
self.active_roots[frame][h.err_reg.0] = Value::Str(s);
|
|
756
|
+
bb_idx = h.catch_bb.0;
|
|
757
|
+
ip = 0;
|
|
758
|
+
} else {
|
|
759
|
+
return Err(e);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
IrInstruction::CallMethod(dst, obj_reg, method_name, arg_regs) => {
|
|
765
|
+
let obj = self.active_roots[frame][obj_reg.0];
|
|
766
|
+
let args: Vec<Value> = arg_regs
|
|
767
|
+
.iter()
|
|
768
|
+
.map(|r| self.active_roots[frame][r.0])
|
|
769
|
+
.collect();
|
|
770
|
+
let ret = self.eval_method_call(obj, method_name, &args)?;
|
|
771
|
+
self.active_roots[frame][dst.0] = ret;
|
|
772
|
+
ip += 1;
|
|
773
|
+
}
|
|
774
|
+
IrInstruction::CallBuiltin(dst, builtin, arg_regs) => {
|
|
775
|
+
let args: Vec<Value> = arg_regs
|
|
776
|
+
.iter()
|
|
777
|
+
.map(|r| self.active_roots[frame][r.0])
|
|
778
|
+
.collect();
|
|
779
|
+
match eval_builtin(*builtin, &args, &mut *self.heap, &mut self.stdout_sink) {
|
|
780
|
+
Ok(ret) => {
|
|
781
|
+
self.active_roots[frame][dst.0] = ret;
|
|
782
|
+
ip += 1;
|
|
783
|
+
}
|
|
784
|
+
Err(e) => {
|
|
785
|
+
if let Some(h) = try_stack.pop() {
|
|
786
|
+
let s = self.heap.alloc_string(e.to_string());
|
|
787
|
+
self.active_roots[frame][h.err_reg.0] = Value::Str(s);
|
|
788
|
+
bb_idx = h.catch_bb.0;
|
|
789
|
+
ip = 0;
|
|
790
|
+
} else {
|
|
791
|
+
return Err(e);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
IrInstruction::ResolveFn(dst, site_id) => {
|
|
797
|
+
let target_id = self.resolve_call_site(*site_id)?;
|
|
798
|
+
self.active_roots[frame][dst.0] = Value::FunctionRef(target_id);
|
|
799
|
+
ip += 1;
|
|
800
|
+
}
|
|
801
|
+
IrInstruction::LoadFnRef(dst, fn_id) => {
|
|
802
|
+
self.active_roots[frame][dst.0] = Value::FunctionRef(*fn_id);
|
|
803
|
+
ip += 1;
|
|
804
|
+
}
|
|
805
|
+
IrInstruction::Return(opt_r) => {
|
|
806
|
+
let val = opt_r
|
|
807
|
+
.map(|r| self.active_roots[frame][r.0])
|
|
808
|
+
.unwrap_or(Value::Nil);
|
|
809
|
+
return Ok(val);
|
|
810
|
+
}
|
|
811
|
+
IrInstruction::BranchIf(cond, t_bb, f_bb) => {
|
|
812
|
+
let cv = self.active_roots[frame][cond.0];
|
|
813
|
+
bb_idx = if cv.is_truthy(&*self.heap) {
|
|
814
|
+
t_bb.0
|
|
815
|
+
} else {
|
|
816
|
+
f_bb.0
|
|
817
|
+
};
|
|
818
|
+
ip = 0;
|
|
819
|
+
}
|
|
820
|
+
IrInstruction::Jump(target) => {
|
|
821
|
+
bb_idx = target.0;
|
|
822
|
+
ip = 0;
|
|
823
|
+
}
|
|
824
|
+
IrInstruction::TryBegin(catch_bb, err_reg) => {
|
|
825
|
+
try_stack.push(ExceptionHandler {
|
|
826
|
+
catch_bb: *catch_bb,
|
|
827
|
+
err_reg: *err_reg,
|
|
828
|
+
});
|
|
829
|
+
ip += 1;
|
|
830
|
+
}
|
|
831
|
+
IrInstruction::TryEnd => {
|
|
832
|
+
let _ = try_stack.pop();
|
|
833
|
+
ip += 1;
|
|
834
|
+
}
|
|
835
|
+
IrInstruction::Throw(r) => {
|
|
836
|
+
let err_val = self.active_roots[frame][r.0];
|
|
837
|
+
if let Some(h) = try_stack.pop() {
|
|
838
|
+
self.active_roots[frame][h.err_reg.0] = err_val;
|
|
839
|
+
bb_idx = h.catch_bb.0;
|
|
840
|
+
ip = 0;
|
|
841
|
+
} else {
|
|
842
|
+
let msg = err_val.format(&*self.heap);
|
|
843
|
+
return Err(PolyError::msg("E0520", format!("uncaught exception: {msg}")));
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
IrInstruction::CreateArray(dst, item_regs) => {
|
|
847
|
+
let items: Vec<Value> = item_regs
|
|
848
|
+
.iter()
|
|
849
|
+
.map(|r| self.active_roots[frame][r.0])
|
|
850
|
+
.collect();
|
|
851
|
+
let h = self.heap.alloc_array(items);
|
|
852
|
+
self.active_roots[frame][dst.0] = Value::Array(h);
|
|
853
|
+
ip += 1;
|
|
854
|
+
}
|
|
855
|
+
IrInstruction::GetIndex(dst, obj_reg, idx_reg) => {
|
|
856
|
+
let obj = self.active_roots[frame][obj_reg.0];
|
|
857
|
+
let idx_val = self.active_roots[frame][idx_reg.0];
|
|
858
|
+
let Value::Int(idx_i) = idx_val else {
|
|
859
|
+
return Err(PolyError::msg("E0507", "index must be an integer"));
|
|
860
|
+
};
|
|
861
|
+
let val = match obj {
|
|
862
|
+
Value::Array(h) => {
|
|
863
|
+
let arr = self
|
|
864
|
+
.heap
|
|
865
|
+
.get_array(h)
|
|
866
|
+
.ok_or_else(|| PolyError::msg("E0508", "dangling array handle"))?;
|
|
867
|
+
let i = usize::try_from(idx_i)
|
|
868
|
+
.ok()
|
|
869
|
+
.filter(|&i| i < arr.len())
|
|
870
|
+
.ok_or_else(|| {
|
|
871
|
+
PolyError::msg(
|
|
872
|
+
"E0509",
|
|
873
|
+
format!(
|
|
874
|
+
"array index {idx_i} out of bounds (len {})",
|
|
875
|
+
arr.len()
|
|
876
|
+
),
|
|
877
|
+
)
|
|
878
|
+
})?;
|
|
879
|
+
arr[i]
|
|
880
|
+
}
|
|
881
|
+
Value::RawBuffer(h) => {
|
|
882
|
+
let buf = self
|
|
883
|
+
.heap
|
|
884
|
+
.buffer_slice(h)
|
|
885
|
+
.ok_or_else(|| PolyError::msg("E0508", "dangling buffer handle"))?;
|
|
886
|
+
let i = usize::try_from(idx_i)
|
|
887
|
+
.ok()
|
|
888
|
+
.filter(|&i| i < buf.len())
|
|
889
|
+
.ok_or_else(|| {
|
|
890
|
+
PolyError::msg("E0509", "buffer index out of bounds")
|
|
891
|
+
})?;
|
|
892
|
+
Value::Int(i64::from(buf[i]))
|
|
893
|
+
}
|
|
894
|
+
Value::Str(h) => {
|
|
895
|
+
let s = self
|
|
896
|
+
.heap
|
|
897
|
+
.get_string(h)
|
|
898
|
+
.ok_or_else(|| PolyError::msg("E0508", "dangling string handle"))?;
|
|
899
|
+
let ch = usize::try_from(idx_i)
|
|
900
|
+
.ok()
|
|
901
|
+
.and_then(|i| s.chars().nth(i))
|
|
902
|
+
.ok_or_else(|| {
|
|
903
|
+
PolyError::msg("E0509", "string index out of bounds")
|
|
904
|
+
})?;
|
|
905
|
+
Value::Str(self.heap.alloc_string(ch.to_string()))
|
|
906
|
+
}
|
|
907
|
+
other => {
|
|
908
|
+
return Err(PolyError::msg(
|
|
909
|
+
"E0510",
|
|
910
|
+
format!("cannot index type {}", other.type_name()),
|
|
911
|
+
));
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
self.active_roots[frame][dst.0] = val;
|
|
915
|
+
ip += 1;
|
|
916
|
+
}
|
|
917
|
+
IrInstruction::SetIndex(obj_reg, idx_reg, val_reg) => {
|
|
918
|
+
let obj = self.active_roots[frame][obj_reg.0];
|
|
919
|
+
let idx_val = self.active_roots[frame][idx_reg.0];
|
|
920
|
+
let val = self.active_roots[frame][val_reg.0];
|
|
921
|
+
let Value::Int(idx_i) = idx_val else {
|
|
922
|
+
return Err(PolyError::msg("E0507", "index must be an integer"));
|
|
923
|
+
};
|
|
924
|
+
match obj {
|
|
925
|
+
Value::Array(h) => {
|
|
926
|
+
let arr = self
|
|
927
|
+
.heap
|
|
928
|
+
.get_array_mut(h)
|
|
929
|
+
.ok_or_else(|| PolyError::msg("E0508", "dangling array handle"))?;
|
|
930
|
+
let i = usize::try_from(idx_i)
|
|
931
|
+
.ok()
|
|
932
|
+
.filter(|&i| i < arr.len())
|
|
933
|
+
.ok_or_else(|| {
|
|
934
|
+
PolyError::msg("E0509", "array index out of bounds")
|
|
935
|
+
})?;
|
|
936
|
+
arr[i] = val;
|
|
937
|
+
}
|
|
938
|
+
Value::RawBuffer(h) => {
|
|
939
|
+
let Value::Int(byte) = val else {
|
|
940
|
+
return Err(PolyError::msg(
|
|
941
|
+
"E0510",
|
|
942
|
+
"buffer element must be an integer byte",
|
|
943
|
+
));
|
|
944
|
+
};
|
|
945
|
+
let buf = self
|
|
946
|
+
.heap
|
|
947
|
+
.buffer_slice_mut(h)
|
|
948
|
+
.ok_or_else(|| PolyError::msg("E0508", "dangling buffer handle"))?;
|
|
949
|
+
let i = usize::try_from(idx_i)
|
|
950
|
+
.ok()
|
|
951
|
+
.filter(|&i| i < buf.len())
|
|
952
|
+
.ok_or_else(|| {
|
|
953
|
+
PolyError::msg("E0509", "buffer index out of bounds")
|
|
954
|
+
})?;
|
|
955
|
+
buf[i] = (byte & 0xff) as u8;
|
|
956
|
+
}
|
|
957
|
+
other => {
|
|
958
|
+
return Err(PolyError::msg(
|
|
959
|
+
"E0510",
|
|
960
|
+
format!("cannot index-assign type {}", other.type_name()),
|
|
961
|
+
));
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
ip += 1;
|
|
965
|
+
}
|
|
966
|
+
IrInstruction::CreateObject(dst, class_name) => {
|
|
967
|
+
let h = self.heap.alloc_object(ClassInstance {
|
|
968
|
+
class_name: class_name.clone(),
|
|
969
|
+
fields: FxHashMap::default(),
|
|
970
|
+
});
|
|
971
|
+
self.active_roots[frame][dst.0] = Value::Object(h);
|
|
972
|
+
ip += 1;
|
|
973
|
+
}
|
|
974
|
+
IrInstruction::SetField(obj_reg, field, val_reg) => {
|
|
975
|
+
let obj = self.active_roots[frame][obj_reg.0];
|
|
976
|
+
let val = self.active_roots[frame][val_reg.0];
|
|
977
|
+
let Value::Object(h) = obj else {
|
|
978
|
+
return Err(PolyError::msg(
|
|
979
|
+
"E0511",
|
|
980
|
+
format!("cannot set field '{field}' on {}", obj.type_name()),
|
|
981
|
+
));
|
|
982
|
+
};
|
|
983
|
+
let inst = self
|
|
984
|
+
.heap
|
|
985
|
+
.get_object_mut(h)
|
|
986
|
+
.ok_or_else(|| PolyError::msg("E0508", "dangling object handle"))?;
|
|
987
|
+
inst.fields.insert(field.clone(), val);
|
|
988
|
+
ip += 1;
|
|
989
|
+
}
|
|
990
|
+
IrInstruction::GetField(dst, obj_reg, field) => {
|
|
991
|
+
let obj = self.active_roots[frame][obj_reg.0];
|
|
992
|
+
let val = match obj {
|
|
993
|
+
Value::Object(h) => {
|
|
994
|
+
let inst = self
|
|
995
|
+
.heap
|
|
996
|
+
.get_object(h)
|
|
997
|
+
.ok_or_else(|| PolyError::msg("E0508", "dangling object handle"))?;
|
|
998
|
+
inst.fields.get(field).copied().unwrap_or(Value::Nil)
|
|
999
|
+
}
|
|
1000
|
+
Value::Str(h) => {
|
|
1001
|
+
let s = self.heap.get_string(h).unwrap_or("");
|
|
1002
|
+
if field == "length" || field == "Length" {
|
|
1003
|
+
Value::Int(s.len() as i64)
|
|
1004
|
+
} else {
|
|
1005
|
+
Value::Nil
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
Value::Array(h) => {
|
|
1009
|
+
let a = self.heap.get_array(h).unwrap_or(&[]);
|
|
1010
|
+
if field == "length" || field == "Length" || field == "Count" {
|
|
1011
|
+
Value::Int(a.len() as i64)
|
|
1012
|
+
} else {
|
|
1013
|
+
Value::Nil
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
_ => Value::Nil,
|
|
1017
|
+
};
|
|
1018
|
+
self.active_roots[frame][dst.0] = val;
|
|
1019
|
+
ip += 1;
|
|
1020
|
+
}
|
|
1021
|
+
IrInstruction::AllocBuffer(dst, size_reg) => {
|
|
1022
|
+
let Value::Int(sz) = self.active_roots[frame][size_reg.0] else {
|
|
1023
|
+
return Err(PolyError::msg("E0512", "buffer size must be integer"));
|
|
1024
|
+
};
|
|
1025
|
+
if sz < 0 {
|
|
1026
|
+
return Err(PolyError::msg("E0512", "negative buffer size"));
|
|
1027
|
+
}
|
|
1028
|
+
let h = self.heap.alloc_buffer(sz as usize);
|
|
1029
|
+
self.active_roots[frame][dst.0] = Value::RawBuffer(h);
|
|
1030
|
+
ip += 1;
|
|
1031
|
+
}
|
|
1032
|
+
IrInstruction::StoreByte(buf_r, off_r, val_r) => {
|
|
1033
|
+
let _ = eval_builtin(
|
|
1034
|
+
BuiltinId::WriteU8,
|
|
1035
|
+
&[
|
|
1036
|
+
self.active_roots[frame][buf_r.0],
|
|
1037
|
+
self.active_roots[frame][off_r.0],
|
|
1038
|
+
self.active_roots[frame][val_r.0],
|
|
1039
|
+
],
|
|
1040
|
+
&mut *self.heap,
|
|
1041
|
+
&mut self.stdout_sink,
|
|
1042
|
+
)?;
|
|
1043
|
+
ip += 1;
|
|
1044
|
+
}
|
|
1045
|
+
IrInstruction::LoadByte(dst, buf_r, off_r) => {
|
|
1046
|
+
let v = eval_builtin(
|
|
1047
|
+
BuiltinId::ReadU8,
|
|
1048
|
+
&[
|
|
1049
|
+
self.active_roots[frame][buf_r.0],
|
|
1050
|
+
self.active_roots[frame][off_r.0],
|
|
1051
|
+
],
|
|
1052
|
+
&mut *self.heap,
|
|
1053
|
+
&mut self.stdout_sink,
|
|
1054
|
+
)?;
|
|
1055
|
+
self.active_roots[frame][dst.0] = v;
|
|
1056
|
+
ip += 1;
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
Ok(Value::Nil)
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
fn eval_method_call(
|
|
1065
|
+
&mut self,
|
|
1066
|
+
obj: Value,
|
|
1067
|
+
method: &str,
|
|
1068
|
+
args: &[Value],
|
|
1069
|
+
) -> Result<Value, PolyError> {
|
|
1070
|
+
match obj {
|
|
1071
|
+
Value::Regex(h) => match method {
|
|
1072
|
+
"test" | "Match" | "IsMatch" => {
|
|
1073
|
+
let mut b_args = vec![Value::Regex(h)];
|
|
1074
|
+
b_args.extend_from_slice(args);
|
|
1075
|
+
eval_builtin(
|
|
1076
|
+
BuiltinId::RegexTest,
|
|
1077
|
+
&b_args,
|
|
1078
|
+
&mut *self.heap,
|
|
1079
|
+
&mut self.stdout_sink,
|
|
1080
|
+
)
|
|
1081
|
+
}
|
|
1082
|
+
"exec" | "match" => {
|
|
1083
|
+
let mut b_args = vec![Value::Regex(h)];
|
|
1084
|
+
b_args.extend_from_slice(args);
|
|
1085
|
+
eval_builtin(
|
|
1086
|
+
BuiltinId::RegexMatch,
|
|
1087
|
+
&b_args,
|
|
1088
|
+
&mut *self.heap,
|
|
1089
|
+
&mut self.stdout_sink,
|
|
1090
|
+
)
|
|
1091
|
+
}
|
|
1092
|
+
"replace" | "Replace" | "ReplaceAll" => {
|
|
1093
|
+
let mut b_args = vec![Value::Regex(h)];
|
|
1094
|
+
b_args.extend_from_slice(args);
|
|
1095
|
+
eval_builtin(
|
|
1096
|
+
BuiltinId::RegexReplace,
|
|
1097
|
+
&b_args,
|
|
1098
|
+
&mut *self.heap,
|
|
1099
|
+
&mut self.stdout_sink,
|
|
1100
|
+
)
|
|
1101
|
+
}
|
|
1102
|
+
"split" | "Split" => {
|
|
1103
|
+
let mut b_args = vec![Value::Regex(h)];
|
|
1104
|
+
b_args.extend_from_slice(args);
|
|
1105
|
+
eval_builtin(
|
|
1106
|
+
BuiltinId::RegexSplit,
|
|
1107
|
+
&b_args,
|
|
1108
|
+
&mut *self.heap,
|
|
1109
|
+
&mut self.stdout_sink,
|
|
1110
|
+
)
|
|
1111
|
+
}
|
|
1112
|
+
_ => Err(PolyError::msg(
|
|
1113
|
+
"E0521",
|
|
1114
|
+
format!("unknown regex method '{method}'"),
|
|
1115
|
+
)),
|
|
1116
|
+
},
|
|
1117
|
+
Value::Str(h) => match method {
|
|
1118
|
+
"contains" | "Contains" | "includes" => {
|
|
1119
|
+
let mut b_args = vec![Value::Str(h)];
|
|
1120
|
+
b_args.extend_from_slice(args);
|
|
1121
|
+
eval_builtin(
|
|
1122
|
+
BuiltinId::StrContains,
|
|
1123
|
+
&b_args,
|
|
1124
|
+
&mut *self.heap,
|
|
1125
|
+
&mut self.stdout_sink,
|
|
1126
|
+
)
|
|
1127
|
+
}
|
|
1128
|
+
"split" | "Split" => {
|
|
1129
|
+
let mut b_args = vec![Value::Str(h)];
|
|
1130
|
+
b_args.extend_from_slice(args);
|
|
1131
|
+
eval_builtin(
|
|
1132
|
+
BuiltinId::StrSplit,
|
|
1133
|
+
&b_args,
|
|
1134
|
+
&mut *self.heap,
|
|
1135
|
+
&mut self.stdout_sink,
|
|
1136
|
+
)
|
|
1137
|
+
}
|
|
1138
|
+
"trim" | "Trim" | "TrimSpace" => eval_builtin(
|
|
1139
|
+
BuiltinId::StrTrim,
|
|
1140
|
+
&[Value::Str(h)],
|
|
1141
|
+
&mut *self.heap,
|
|
1142
|
+
&mut self.stdout_sink,
|
|
1143
|
+
),
|
|
1144
|
+
"toUpperCase" | "ToUpper" | "upper" => eval_builtin(
|
|
1145
|
+
BuiltinId::StrUpper,
|
|
1146
|
+
&[Value::Str(h)],
|
|
1147
|
+
&mut *self.heap,
|
|
1148
|
+
&mut self.stdout_sink,
|
|
1149
|
+
),
|
|
1150
|
+
"toLowerCase" | "ToLower" | "lower" => eval_builtin(
|
|
1151
|
+
BuiltinId::StrLower,
|
|
1152
|
+
&[Value::Str(h)],
|
|
1153
|
+
&mut *self.heap,
|
|
1154
|
+
&mut self.stdout_sink,
|
|
1155
|
+
),
|
|
1156
|
+
"replace" | "Replace" | "replaceAll" | "ReplaceAll" => {
|
|
1157
|
+
if let Some(Value::Regex(_)) = args.first() {
|
|
1158
|
+
let mut b_args = vec![args[0], Value::Str(h)];
|
|
1159
|
+
if let Some(repl) = args.get(1) {
|
|
1160
|
+
b_args.push(*repl);
|
|
1161
|
+
}
|
|
1162
|
+
eval_builtin(
|
|
1163
|
+
BuiltinId::RegexReplace,
|
|
1164
|
+
&b_args,
|
|
1165
|
+
&mut *self.heap,
|
|
1166
|
+
&mut self.stdout_sink,
|
|
1167
|
+
)
|
|
1168
|
+
} else {
|
|
1169
|
+
let mut b_args = vec![Value::Str(h)];
|
|
1170
|
+
b_args.extend_from_slice(args);
|
|
1171
|
+
eval_builtin(
|
|
1172
|
+
BuiltinId::StrReplace,
|
|
1173
|
+
&b_args,
|
|
1174
|
+
&mut *self.heap,
|
|
1175
|
+
&mut self.stdout_sink,
|
|
1176
|
+
)
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
_ => Err(PolyError::msg(
|
|
1180
|
+
"E0521",
|
|
1181
|
+
format!("unknown string method '{method}'"),
|
|
1182
|
+
)),
|
|
1183
|
+
},
|
|
1184
|
+
Value::Array(h) => match method {
|
|
1185
|
+
"push" | "append" | "Add" => {
|
|
1186
|
+
let mut b_args = vec![Value::Array(h)];
|
|
1187
|
+
b_args.extend_from_slice(args);
|
|
1188
|
+
eval_builtin(
|
|
1189
|
+
BuiltinId::Push,
|
|
1190
|
+
&b_args,
|
|
1191
|
+
&mut *self.heap,
|
|
1192
|
+
&mut self.stdout_sink,
|
|
1193
|
+
)
|
|
1194
|
+
}
|
|
1195
|
+
"pop" => eval_builtin(
|
|
1196
|
+
BuiltinId::Pop,
|
|
1197
|
+
&[Value::Array(h)],
|
|
1198
|
+
&mut *self.heap,
|
|
1199
|
+
&mut self.stdout_sink,
|
|
1200
|
+
),
|
|
1201
|
+
_ => Err(PolyError::msg(
|
|
1202
|
+
"E0521",
|
|
1203
|
+
format!("unknown array method '{method}'"),
|
|
1204
|
+
)),
|
|
1205
|
+
},
|
|
1206
|
+
Value::Object(h) => {
|
|
1207
|
+
let inst = self
|
|
1208
|
+
.heap
|
|
1209
|
+
.get_object(h)
|
|
1210
|
+
.ok_or_else(|| PolyError::msg("E0508", "dangling object handle"))?;
|
|
1211
|
+
if let Some(&field_val) = inst.fields.get(method) {
|
|
1212
|
+
if let Value::FunctionRef(target_id) = field_val {
|
|
1213
|
+
let mut call_args = vec![obj];
|
|
1214
|
+
call_args.extend_from_slice(args);
|
|
1215
|
+
return self.invoke_fn(target_id, &call_args);
|
|
1216
|
+
}
|
|
1217
|
+
return Ok(field_val);
|
|
1218
|
+
}
|
|
1219
|
+
let scoped_name = format!("{}::{method}", inst.class_name);
|
|
1220
|
+
for (&(_, ref name), &target_id) in &self.fn_map {
|
|
1221
|
+
if name == &scoped_name {
|
|
1222
|
+
let mut call_args = vec![obj];
|
|
1223
|
+
call_args.extend_from_slice(args);
|
|
1224
|
+
return self.invoke_fn(target_id, &call_args);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
Err(PolyError::msg(
|
|
1228
|
+
"E0521",
|
|
1229
|
+
format!(
|
|
1230
|
+
"object of class '{}' has no method '{method}'",
|
|
1231
|
+
inst.class_name
|
|
1232
|
+
),
|
|
1233
|
+
))
|
|
1234
|
+
}
|
|
1235
|
+
other => Err(PolyError::msg(
|
|
1236
|
+
"E0521",
|
|
1237
|
+
format!("cannot call method '{method}' on {}", other.type_name()),
|
|
1238
|
+
)),
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
pub fn check_project(
|
|
1244
|
+
entry_path: &Path,
|
|
1245
|
+
entry_fn: &str,
|
|
1246
|
+
trace_imports: bool,
|
|
1247
|
+
) -> Result<StaticCheckReport, PolyError> {
|
|
1248
|
+
let mut resolver = ModuleResolver::new(trace_imports);
|
|
1249
|
+
let entry_mod = resolver.load_module(entry_path)?;
|
|
1250
|
+
let reachable = resolver.check_reachable_from_entry(entry_mod, entry_fn)?;
|
|
1251
|
+
Ok(StaticCheckReport {
|
|
1252
|
+
modules_parsed: resolver.stats.modules_parsed,
|
|
1253
|
+
reachable_functions: reachable.len(),
|
|
1254
|
+
parsed_paths: resolver.stats.parsed_paths,
|
|
1255
|
+
})
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
fn cast_value(val: Value, ty: IrType, heap: &mut dyn MemoryHeap) -> Result<Value, PolyError> {
|
|
1259
|
+
match ty {
|
|
1260
|
+
IrType::Dynamic | IrType::Void => Ok(val),
|
|
1261
|
+
IrType::Bool => Ok(Value::Bool(val.is_truthy(heap))),
|
|
1262
|
+
IrType::I64 => match val {
|
|
1263
|
+
Value::Int(i) => Ok(Value::Int(i)),
|
|
1264
|
+
Value::Float(f) => Ok(Value::Int(f as i64)),
|
|
1265
|
+
Value::Bool(b) => Ok(Value::Int(i64::from(b))),
|
|
1266
|
+
other => Err(PolyError::msg(
|
|
1267
|
+
"E0513",
|
|
1268
|
+
format!("cannot cast {} to int", other.type_name()),
|
|
1269
|
+
)),
|
|
1270
|
+
},
|
|
1271
|
+
IrType::F64 => match val {
|
|
1272
|
+
Value::Float(f) => Ok(Value::Float(f)),
|
|
1273
|
+
Value::Int(i) => Ok(Value::Float(i as f64)),
|
|
1274
|
+
Value::Bool(b) => Ok(Value::Float(if b { 1.0 } else { 0.0 })),
|
|
1275
|
+
other => Err(PolyError::msg(
|
|
1276
|
+
"E0513",
|
|
1277
|
+
format!("cannot cast {} to float", other.type_name()),
|
|
1278
|
+
)),
|
|
1279
|
+
},
|
|
1280
|
+
IrType::Str => match val {
|
|
1281
|
+
Value::Str(h) => Ok(Value::Str(h)),
|
|
1282
|
+
other => Ok(Value::Str(heap.alloc_string(other.format(heap)))),
|
|
1283
|
+
},
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
fn eval_unary(op: IrUnaryOp, v: Value, heap: &dyn MemoryHeap) -> Result<Value, PolyError> {
|
|
1288
|
+
match op {
|
|
1289
|
+
IrUnaryOp::Not => Ok(Value::Bool(!v.is_truthy(heap))),
|
|
1290
|
+
IrUnaryOp::Neg => match v {
|
|
1291
|
+
Value::Int(i) => Ok(Value::Int(i.wrapping_neg())),
|
|
1292
|
+
Value::Float(f) => Ok(Value::Float(-f)),
|
|
1293
|
+
other => Err(PolyError::msg(
|
|
1294
|
+
"E0514",
|
|
1295
|
+
format!("cannot negate {}", other.type_name()),
|
|
1296
|
+
)),
|
|
1297
|
+
},
|
|
1298
|
+
IrUnaryOp::BitNot => match v {
|
|
1299
|
+
Value::Int(i) => Ok(Value::Int(!i)),
|
|
1300
|
+
other => Err(PolyError::msg(
|
|
1301
|
+
"E0514",
|
|
1302
|
+
format!("cannot bitwise-not {}", other.type_name()),
|
|
1303
|
+
)),
|
|
1304
|
+
},
|
|
1305
|
+
IrUnaryOp::BitsToF64 => match v {
|
|
1306
|
+
Value::Int(i) => Ok(Value::Float(f64::from_bits(i as u64))),
|
|
1307
|
+
other => Err(PolyError::msg(
|
|
1308
|
+
"E0514",
|
|
1309
|
+
format!("cannot bitcast {} to float", other.type_name()),
|
|
1310
|
+
)),
|
|
1311
|
+
},
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
fn eval_binop(
|
|
1316
|
+
op: IrBinOp,
|
|
1317
|
+
l: Value,
|
|
1318
|
+
r: Value,
|
|
1319
|
+
heap: &mut dyn MemoryHeap,
|
|
1320
|
+
) -> Result<Value, PolyError> {
|
|
1321
|
+
if op == IrBinOp::Add && (matches!(l, Value::Str(_)) || matches!(r, Value::Str(_))) {
|
|
1322
|
+
let ls = l.format(heap);
|
|
1323
|
+
let rs = r.format(heap);
|
|
1324
|
+
return Ok(Value::Str(heap.alloc_string(format!("{ls}{rs}"))));
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
match (l, r) {
|
|
1328
|
+
(Value::Int(a), Value::Int(b)) => match op {
|
|
1329
|
+
IrBinOp::Add => Ok(Value::Int(a.wrapping_add(b))),
|
|
1330
|
+
IrBinOp::Sub => Ok(Value::Int(a.wrapping_sub(b))),
|
|
1331
|
+
IrBinOp::Mul => Ok(Value::Int(a.wrapping_mul(b))),
|
|
1332
|
+
IrBinOp::Div => {
|
|
1333
|
+
if b == 0 {
|
|
1334
|
+
return Err(PolyError::msg("E0504", "division by zero"));
|
|
1335
|
+
}
|
|
1336
|
+
Ok(Value::Int(a.wrapping_div(b)))
|
|
1337
|
+
}
|
|
1338
|
+
IrBinOp::FloorDiv => {
|
|
1339
|
+
if b == 0 {
|
|
1340
|
+
return Err(PolyError::msg("E0504", "division by zero"));
|
|
1341
|
+
}
|
|
1342
|
+
let mut q = a.wrapping_div(b);
|
|
1343
|
+
let rem = a.wrapping_rem(b);
|
|
1344
|
+
if rem != 0 && (a ^ b) < 0 {
|
|
1345
|
+
q = q.wrapping_sub(1);
|
|
1346
|
+
}
|
|
1347
|
+
Ok(Value::Int(q))
|
|
1348
|
+
}
|
|
1349
|
+
IrBinOp::Mod => {
|
|
1350
|
+
if b == 0 {
|
|
1351
|
+
return Err(PolyError::msg("E0504", "modulo by zero"));
|
|
1352
|
+
}
|
|
1353
|
+
Ok(Value::Int(a.wrapping_rem(b)))
|
|
1354
|
+
}
|
|
1355
|
+
IrBinOp::Pow => {
|
|
1356
|
+
if b >= 0 && b <= u32::MAX as i64 {
|
|
1357
|
+
Ok(Value::Int(a.wrapping_pow(b as u32)))
|
|
1358
|
+
} else {
|
|
1359
|
+
Ok(Value::Float((a as f64).powf(b as f64)))
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
IrBinOp::Eq => Ok(Value::Bool(a == b)),
|
|
1363
|
+
IrBinOp::Ne => Ok(Value::Bool(a != b)),
|
|
1364
|
+
IrBinOp::Lt => Ok(Value::Bool(a < b)),
|
|
1365
|
+
IrBinOp::Le => Ok(Value::Bool(a <= b)),
|
|
1366
|
+
IrBinOp::Gt => Ok(Value::Bool(a > b)),
|
|
1367
|
+
IrBinOp::Ge => Ok(Value::Bool(a >= b)),
|
|
1368
|
+
IrBinOp::BitAnd => Ok(Value::Int(a & b)),
|
|
1369
|
+
IrBinOp::BitOr => Ok(Value::Int(a | b)),
|
|
1370
|
+
IrBinOp::BitXor => Ok(Value::Int(a ^ b)),
|
|
1371
|
+
IrBinOp::Shl => Ok(Value::Int(a.wrapping_shl(b as u32))),
|
|
1372
|
+
IrBinOp::Shr => Ok(Value::Int(a.wrapping_shr(b as u32))),
|
|
1373
|
+
IrBinOp::And => Ok(Value::Bool(a != 0 && b != 0)),
|
|
1374
|
+
IrBinOp::Or => Ok(Value::Bool(a != 0 || b != 0)),
|
|
1375
|
+
},
|
|
1376
|
+
(Value::Float(a), Value::Float(b)) => eval_float_op(op, a, b),
|
|
1377
|
+
(Value::Int(a), Value::Float(b)) => eval_float_op(op, a as f64, b),
|
|
1378
|
+
(Value::Float(a), Value::Int(b)) => eval_float_op(op, a, b as f64),
|
|
1379
|
+
(Value::Bool(a), Value::Bool(b)) => match op {
|
|
1380
|
+
IrBinOp::Eq => Ok(Value::Bool(a == b)),
|
|
1381
|
+
IrBinOp::Ne => Ok(Value::Bool(a != b)),
|
|
1382
|
+
IrBinOp::And => Ok(Value::Bool(a && b)),
|
|
1383
|
+
IrBinOp::Or => Ok(Value::Bool(a || b)),
|
|
1384
|
+
_ => Err(PolyError::msg("E0515", "unsupported boolean operation")),
|
|
1385
|
+
},
|
|
1386
|
+
(Value::Str(a), Value::Str(b)) => {
|
|
1387
|
+
let sa = heap.get_string(a).unwrap_or("");
|
|
1388
|
+
let sb = heap.get_string(b).unwrap_or("");
|
|
1389
|
+
match op {
|
|
1390
|
+
IrBinOp::Eq => Ok(Value::Bool(sa == sb)),
|
|
1391
|
+
IrBinOp::Ne => Ok(Value::Bool(sa != sb)),
|
|
1392
|
+
IrBinOp::Lt => Ok(Value::Bool(sa < sb)),
|
|
1393
|
+
IrBinOp::Le => Ok(Value::Bool(sa <= sb)),
|
|
1394
|
+
IrBinOp::Gt => Ok(Value::Bool(sa > sb)),
|
|
1395
|
+
IrBinOp::Ge => Ok(Value::Bool(sa >= sb)),
|
|
1396
|
+
_ => Err(PolyError::msg("E0515", "unsupported string operation")),
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
(Value::Nil, Value::Nil) => match op {
|
|
1400
|
+
IrBinOp::Eq => Ok(Value::Bool(true)),
|
|
1401
|
+
IrBinOp::Ne => Ok(Value::Bool(false)),
|
|
1402
|
+
_ => Err(PolyError::msg("E0515", "unsupported nil operation")),
|
|
1403
|
+
},
|
|
1404
|
+
(a, b) => match op {
|
|
1405
|
+
IrBinOp::Eq => Ok(Value::Bool(a == b)),
|
|
1406
|
+
IrBinOp::Ne => Ok(Value::Bool(a != b)),
|
|
1407
|
+
_ => Err(PolyError::msg(
|
|
1408
|
+
"E0515",
|
|
1409
|
+
format!(
|
|
1410
|
+
"unsupported binary operation {:?} between {} and {}",
|
|
1411
|
+
op,
|
|
1412
|
+
a.type_name(),
|
|
1413
|
+
b.type_name()
|
|
1414
|
+
),
|
|
1415
|
+
)),
|
|
1416
|
+
},
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
fn eval_float_op(op: IrBinOp, a: f64, b: f64) -> Result<Value, PolyError> {
|
|
1421
|
+
match op {
|
|
1422
|
+
IrBinOp::Add => Ok(Value::Float(a + b)),
|
|
1423
|
+
IrBinOp::Sub => Ok(Value::Float(a - b)),
|
|
1424
|
+
IrBinOp::Mul => Ok(Value::Float(a * b)),
|
|
1425
|
+
IrBinOp::Div => Ok(Value::Float(a / b)),
|
|
1426
|
+
IrBinOp::FloorDiv => Ok(Value::Float((a / b).floor())),
|
|
1427
|
+
IrBinOp::Mod => Ok(Value::Float(a % b)),
|
|
1428
|
+
IrBinOp::Pow => Ok(Value::Float(a.powf(b))),
|
|
1429
|
+
IrBinOp::Eq => Ok(Value::Bool(a == b)),
|
|
1430
|
+
IrBinOp::Ne => Ok(Value::Bool(a != b)),
|
|
1431
|
+
IrBinOp::Lt => Ok(Value::Bool(a < b)),
|
|
1432
|
+
IrBinOp::Le => Ok(Value::Bool(a <= b)),
|
|
1433
|
+
IrBinOp::Gt => Ok(Value::Bool(a > b)),
|
|
1434
|
+
IrBinOp::Ge => Ok(Value::Bool(a >= b)),
|
|
1435
|
+
IrBinOp::And => Ok(Value::Bool(a != 0.0 && b != 0.0)),
|
|
1436
|
+
IrBinOp::Or => Ok(Value::Bool(a != 0.0 || b != 0.0)),
|
|
1437
|
+
_ => Err(PolyError::msg("E0515", "unsupported float operation")),
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
unsafe extern "C" fn rt_call_site(
|
|
1442
|
+
rt_ctx: *mut u8,
|
|
1443
|
+
site_id: u32,
|
|
1444
|
+
args_ptr: *const JitAbiVal,
|
|
1445
|
+
args_len: usize,
|
|
1446
|
+
out_ptr: *mut JitAbiVal,
|
|
1447
|
+
) -> u8 {
|
|
1448
|
+
let vm = unsafe { &mut *(rt_ctx as *mut VmEngine) };
|
|
1449
|
+
let args = decode_abi_args(args_ptr, args_len);
|
|
1450
|
+
let res = vm
|
|
1451
|
+
.resolve_call_site(CallSiteId(site_id))
|
|
1452
|
+
.and_then(|fn_id| vm.invoke_fn(fn_id, &args));
|
|
1453
|
+
finish_abi_call(vm, res, out_ptr)
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
unsafe extern "C" fn rt_call_fn(
|
|
1457
|
+
rt_ctx: *mut u8,
|
|
1458
|
+
fn_id: u32,
|
|
1459
|
+
args_ptr: *const JitAbiVal,
|
|
1460
|
+
args_len: usize,
|
|
1461
|
+
out_ptr: *mut JitAbiVal,
|
|
1462
|
+
) -> u8 {
|
|
1463
|
+
let vm = unsafe { &mut *(rt_ctx as *mut VmEngine) };
|
|
1464
|
+
let args = decode_abi_args(args_ptr, args_len);
|
|
1465
|
+
let res = vm.invoke_fn(FnId(fn_id), &args);
|
|
1466
|
+
finish_abi_call(vm, res, out_ptr)
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
unsafe extern "C" fn rt_call_builtin(
|
|
1470
|
+
rt_ctx: *mut u8,
|
|
1471
|
+
builtin_discriminant: u32,
|
|
1472
|
+
args_ptr: *const JitAbiVal,
|
|
1473
|
+
args_len: usize,
|
|
1474
|
+
out_ptr: *mut JitAbiVal,
|
|
1475
|
+
) -> u8 {
|
|
1476
|
+
let vm = unsafe { &mut *(rt_ctx as *mut VmEngine) };
|
|
1477
|
+
let args = decode_abi_args(args_ptr, args_len);
|
|
1478
|
+
let res = match builtin_from_u32(builtin_discriminant) {
|
|
1479
|
+
Some(b) => eval_builtin(b, &args, &mut *vm.heap, &mut vm.stdout_sink),
|
|
1480
|
+
None => Err(PolyError::msg("E0516", "invalid builtin id from JIT")),
|
|
1481
|
+
};
|
|
1482
|
+
finish_abi_call(vm, res, out_ptr)
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
unsafe extern "C" fn rt_set_trap(rt_ctx: *mut u8, code: u32) {
|
|
1486
|
+
let vm = unsafe { &mut *(rt_ctx as *mut VmEngine) };
|
|
1487
|
+
vm.last_trap_code = Some(code);
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
fn decode_abi_args(ptr: *const JitAbiVal, len: usize) -> Vec<Value> {
|
|
1491
|
+
if len == 0 || ptr.is_null() {
|
|
1492
|
+
return Vec::new();
|
|
1493
|
+
}
|
|
1494
|
+
let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
|
|
1495
|
+
slice.iter().map(|a| a.to_value()).collect()
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
fn finish_abi_call(
|
|
1499
|
+
vm: &mut VmEngine,
|
|
1500
|
+
res: Result<Value, PolyError>,
|
|
1501
|
+
out_ptr: *mut JitAbiVal,
|
|
1502
|
+
) -> u8 {
|
|
1503
|
+
match res {
|
|
1504
|
+
Ok(val) => {
|
|
1505
|
+
if !out_ptr.is_null() {
|
|
1506
|
+
unsafe {
|
|
1507
|
+
*out_ptr = JitAbiVal::from_value(val);
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
0
|
|
1511
|
+
}
|
|
1512
|
+
Err(err) => {
|
|
1513
|
+
vm.last_error = Some(err);
|
|
1514
|
+
1
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
fn builtin_from_u32(v: u32) -> Option<BuiltinId> {
|
|
1520
|
+
match v {
|
|
1521
|
+
x if x == BuiltinId::Print as u32 => Some(BuiltinId::Print),
|
|
1522
|
+
x if x == BuiltinId::Println as u32 => Some(BuiltinId::Println),
|
|
1523
|
+
x if x == BuiltinId::Printf as u32 => Some(BuiltinId::Printf),
|
|
1524
|
+
x if x == BuiltinId::Sprintf as u32 => Some(BuiltinId::Sprintf),
|
|
1525
|
+
x if x == BuiltinId::Len as u32 => Some(BuiltinId::Len),
|
|
1526
|
+
x if x == BuiltinId::Str as u32 => Some(BuiltinId::Str),
|
|
1527
|
+
x if x == BuiltinId::Int as u32 => Some(BuiltinId::Int),
|
|
1528
|
+
x if x == BuiltinId::Float as u32 => Some(BuiltinId::Float),
|
|
1529
|
+
x if x == BuiltinId::Bool as u32 => Some(BuiltinId::Bool),
|
|
1530
|
+
x if x == BuiltinId::Abs as u32 => Some(BuiltinId::Abs),
|
|
1531
|
+
x if x == BuiltinId::Min as u32 => Some(BuiltinId::Min),
|
|
1532
|
+
x if x == BuiltinId::Max as u32 => Some(BuiltinId::Max),
|
|
1533
|
+
x if x == BuiltinId::Sqrt as u32 => Some(BuiltinId::Sqrt),
|
|
1534
|
+
x if x == BuiltinId::Pow as u32 => Some(BuiltinId::Pow),
|
|
1535
|
+
x if x == BuiltinId::Floor as u32 => Some(BuiltinId::Floor),
|
|
1536
|
+
x if x == BuiltinId::Ceil as u32 => Some(BuiltinId::Ceil),
|
|
1537
|
+
x if x == BuiltinId::Round as u32 => Some(BuiltinId::Round),
|
|
1538
|
+
x if x == BuiltinId::Sin as u32 => Some(BuiltinId::Sin),
|
|
1539
|
+
x if x == BuiltinId::Cos as u32 => Some(BuiltinId::Cos),
|
|
1540
|
+
x if x == BuiltinId::Log as u32 => Some(BuiltinId::Log),
|
|
1541
|
+
x if x == BuiltinId::Push as u32 => Some(BuiltinId::Push),
|
|
1542
|
+
x if x == BuiltinId::Pop as u32 => Some(BuiltinId::Pop),
|
|
1543
|
+
x if x == BuiltinId::TypeOf as u32 => Some(BuiltinId::TypeOf),
|
|
1544
|
+
x if x == BuiltinId::AllocBuf as u32 => Some(BuiltinId::AllocBuf),
|
|
1545
|
+
x if x == BuiltinId::ReadU8 as u32 => Some(BuiltinId::ReadU8),
|
|
1546
|
+
x if x == BuiltinId::WriteU8 as u32 => Some(BuiltinId::WriteU8),
|
|
1547
|
+
x if x == BuiltinId::BufLen as u32 => Some(BuiltinId::BufLen),
|
|
1548
|
+
x if x == BuiltinId::ClockMs as u32 => Some(BuiltinId::ClockMs),
|
|
1549
|
+
x if x == BuiltinId::Assert as u32 => Some(BuiltinId::Assert),
|
|
1550
|
+
x if x == BuiltinId::Range as u32 => Some(BuiltinId::Range),
|
|
1551
|
+
x if x == BuiltinId::RegexNew as u32 => Some(BuiltinId::RegexNew),
|
|
1552
|
+
x if x == BuiltinId::RegexTest as u32 => Some(BuiltinId::RegexTest),
|
|
1553
|
+
x if x == BuiltinId::RegexMatch as u32 => Some(BuiltinId::RegexMatch),
|
|
1554
|
+
x if x == BuiltinId::RegexFindAll as u32 => Some(BuiltinId::RegexFindAll),
|
|
1555
|
+
x if x == BuiltinId::RegexReplace as u32 => Some(BuiltinId::RegexReplace),
|
|
1556
|
+
x if x == BuiltinId::RegexSplit as u32 => Some(BuiltinId::RegexSplit),
|
|
1557
|
+
x if x == BuiltinId::StrContains as u32 => Some(BuiltinId::StrContains),
|
|
1558
|
+
x if x == BuiltinId::StrSplit as u32 => Some(BuiltinId::StrSplit),
|
|
1559
|
+
x if x == BuiltinId::StrTrim as u32 => Some(BuiltinId::StrTrim),
|
|
1560
|
+
x if x == BuiltinId::StrUpper as u32 => Some(BuiltinId::StrUpper),
|
|
1561
|
+
x if x == BuiltinId::StrLower as u32 => Some(BuiltinId::StrLower),
|
|
1562
|
+
x if x == BuiltinId::StrReplace as u32 => Some(BuiltinId::StrReplace),
|
|
1563
|
+
_ => None,
|
|
1564
|
+
}
|
|
1565
|
+
}
|