Skip to main content

harn_kernel/
program.rs

1use std::collections::HashMap;
2use std::fmt;
3use std::sync::Arc;
4
5use harn_parser::TypeExpr;
6use serde::{Deserialize, Serialize};
7
8use crate::{BuiltinId, Op};
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11pub enum Constant {
12    Int(i64),
13    Float(f64),
14    String(String),
15    Bool(bool),
16    Nil,
17    Duration(i64),
18}
19
20impl fmt::Display for Constant {
21    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
22        match self {
23            Self::Int(value) => write!(formatter, "{value}"),
24            Self::Float(value) => write!(formatter, "{value}"),
25            Self::String(value) => write!(formatter, "\"{value}\""),
26            Self::Bool(value) => write!(formatter, "{value}"),
27            Self::Nil => formatter.write_str("nil"),
28            Self::Duration(value) => write!(formatter, "{value}ms"),
29        }
30    }
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct LocalSlotInfo {
35    pub name: String,
36    pub mutable: bool,
37    pub scope_depth: usize,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct ParamSlot {
42    pub name: String,
43    pub type_expr: Option<TypeExpr>,
44    pub has_default: bool,
45}
46
47impl ParamSlot {
48    pub fn from_typed_param(param: &harn_parser::TypedParam) -> Self {
49        Self::from_typed_param_with_type(param, param.type_expr.clone())
50    }
51
52    pub(crate) fn from_typed_param_with_type(
53        param: &harn_parser::TypedParam,
54        type_expr: Option<TypeExpr>,
55    ) -> Self {
56        Self {
57            name: param.name.clone(),
58            type_expr,
59            has_default: param.default_value.is_some(),
60        }
61    }
62
63    pub fn vec_from_typed(params: &[harn_parser::TypedParam]) -> Vec<Self> {
64        params.iter().map(Self::from_typed_param).collect()
65    }
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct CompiledFunction {
70    pub name: String,
71    pub type_params: Vec<String>,
72    pub nominal_type_names: Vec<String>,
73    pub params: Vec<ParamSlot>,
74    pub default_start: Option<usize>,
75    pub chunk: Arc<Chunk>,
76    pub is_generator: bool,
77    pub is_stream: bool,
78    pub has_rest_param: bool,
79    pub has_runtime_type_checks: bool,
80}
81
82impl CompiledFunction {
83    pub(crate) fn has_runtime_type_checks_for_params(params: &[ParamSlot]) -> bool {
84        params.iter().any(|param| param.type_expr.is_some())
85    }
86
87    pub fn param_names(&self) -> impl Iterator<Item = &str> {
88        self.params.iter().map(|param| param.name.as_str())
89    }
90
91    pub fn required_param_count(&self) -> usize {
92        self.default_start.unwrap_or(self.params.len())
93    }
94
95    pub fn declares_type_param(&self, name: &str) -> bool {
96        self.type_params.iter().any(|param| param == name)
97    }
98
99    pub fn has_nominal_type(&self, name: &str) -> bool {
100        self.nominal_type_names.iter().any(|ty| ty == name)
101    }
102}
103
104#[derive(Debug, Serialize, Deserialize)]
105pub struct Chunk {
106    pub code: Vec<u8>,
107    pub constants: Vec<Constant>,
108    #[serde(skip)]
109    constant_index: Option<HashMap<ConstantKey, u16>>,
110    pub lines: Vec<u32>,
111    pub columns: Vec<u32>,
112    pub source_file: Option<String>,
113    #[doc(hidden)]
114    pub current_col: u32,
115    pub functions: Vec<Arc<CompiledFunction>>,
116    #[doc(hidden)]
117    pub local_slots: Vec<LocalSlotInfo>,
118    #[doc(hidden)]
119    pub references_outer_names: bool,
120    #[cfg(debug_assertions)]
121    #[serde(skip)]
122    balance_depth: i32,
123    #[cfg(debug_assertions)]
124    #[serde(skip)]
125    balance_nonlinear: u32,
126}
127
128impl Clone for Chunk {
129    fn clone(&self) -> Self {
130        Self {
131            code: self.code.clone(),
132            constants: self.constants.clone(),
133            constant_index: self.constant_index.clone(),
134            lines: self.lines.clone(),
135            columns: self.columns.clone(),
136            source_file: self.source_file.clone(),
137            current_col: self.current_col,
138            functions: self.functions.clone(),
139            local_slots: self.local_slots.clone(),
140            references_outer_names: self.references_outer_names,
141            #[cfg(debug_assertions)]
142            balance_depth: self.balance_depth,
143            #[cfg(debug_assertions)]
144            balance_nonlinear: self.balance_nonlinear,
145        }
146    }
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Hash)]
150enum ConstantKey {
151    Int(i64),
152    Float(u64),
153    String(String),
154    Bool(bool),
155    Nil,
156    Duration(i64),
157}
158
159impl From<&Constant> for ConstantKey {
160    fn from(value: &Constant) -> Self {
161        match value {
162            Constant::Int(value) => Self::Int(*value),
163            Constant::Float(value) => Self::Float(value.to_bits()),
164            Constant::String(value) => Self::String(value.clone()),
165            Constant::Bool(value) => Self::Bool(*value),
166            Constant::Nil => Self::Nil,
167            Constant::Duration(value) => Self::Duration(*value),
168        }
169    }
170}
171
172#[cfg(debug_assertions)]
173#[derive(Clone, Copy)]
174pub(crate) struct BalanceProbe {
175    depth: i32,
176    nonlinear: u32,
177}
178
179impl Default for Chunk {
180    fn default() -> Self {
181        Self::new()
182    }
183}
184
185impl Chunk {
186    pub(crate) fn from_artifact_parts(
187        code: Vec<u8>,
188        constants: Vec<Constant>,
189        lines: Vec<u32>,
190        columns: Vec<u32>,
191        source_file: Option<String>,
192        functions: Vec<Arc<CompiledFunction>>,
193        local_slots: Vec<LocalSlotInfo>,
194        references_outer_names: bool,
195    ) -> Self {
196        Self {
197            code,
198            constants,
199            constant_index: None,
200            lines,
201            columns,
202            source_file,
203            current_col: 0,
204            functions,
205            local_slots,
206            references_outer_names,
207            #[cfg(debug_assertions)]
208            balance_depth: 0,
209            #[cfg(debug_assertions)]
210            balance_nonlinear: 0,
211        }
212    }
213
214    pub fn new() -> Self {
215        Self {
216            code: Vec::new(),
217            constants: Vec::new(),
218            constant_index: Some(HashMap::new()),
219            lines: Vec::new(),
220            columns: Vec::new(),
221            source_file: None,
222            current_col: 0,
223            functions: Vec::new(),
224            local_slots: Vec::new(),
225            references_outer_names: false,
226            #[cfg(debug_assertions)]
227            balance_depth: 0,
228            #[cfg(debug_assertions)]
229            balance_nonlinear: 0,
230        }
231    }
232
233    pub fn set_column(&mut self, column: u32) {
234        self.current_col = column;
235    }
236
237    pub fn add_constant(&mut self, constant: Constant) -> u16 {
238        let index = self.constant_index.get_or_insert_with(|| {
239            self.constants
240                .iter()
241                .enumerate()
242                .filter_map(|(index, value)| {
243                    u16::try_from(index)
244                        .ok()
245                        .map(|index| (ConstantKey::from(value), index))
246                })
247                .collect()
248        });
249        let key = ConstantKey::from(&constant);
250        if let Some(existing) = index.get(&key) {
251            return *existing;
252        }
253        let slot =
254            u16::try_from(self.constants.len()).expect("constant pool exceeded u16 operand space");
255        self.constants.push(constant);
256        index.insert(key, slot);
257        slot
258    }
259
260    pub fn emit(&mut self, op: Op, line: u32) {
261        self.note_balance(op, 0);
262        self.push_bytes(&[op as u8], line);
263        if reads_outer_name(op) {
264            self.references_outer_names = true;
265        }
266    }
267
268    pub fn emit_u16(&mut self, op: Op, value: u16, line: u32) {
269        self.note_balance(op, value);
270        self.push_bytes(&[op as u8, (value >> 8) as u8, value as u8], line);
271        if reads_outer_name(op) {
272            self.references_outer_names = true;
273        }
274    }
275
276    pub fn emit_u8(&mut self, op: Op, value: u8, line: u32) {
277        self.note_balance(op, u16::from(value));
278        self.push_bytes(&[op as u8, value], line);
279        if reads_outer_name(op) {
280            self.references_outer_names = true;
281        }
282    }
283
284    pub fn emit_call_builtin(&mut self, id: BuiltinId, name: u16, argc: u8, line: u32) {
285        self.note_balance(Op::CallBuiltin, u16::from(argc));
286        let mut bytes = vec![Op::CallBuiltin as u8];
287        bytes.extend_from_slice(&id.raw().to_be_bytes());
288        bytes.extend_from_slice(&name.to_be_bytes());
289        bytes.push(argc);
290        self.push_bytes(&bytes, line);
291        self.references_outer_names = true;
292    }
293
294    pub fn emit_call_builtin_spread(&mut self, id: BuiltinId, name: u16, line: u32) {
295        let mut bytes = vec![Op::CallBuiltinSpread as u8];
296        bytes.extend_from_slice(&id.raw().to_be_bytes());
297        bytes.extend_from_slice(&name.to_be_bytes());
298        self.push_bytes(&bytes, line);
299        self.references_outer_names = true;
300    }
301
302    pub fn emit_method_call(&mut self, name: u16, argc: u8, line: u32) {
303        self.emit_method_call_inner(Op::MethodCall, name, argc, line);
304    }
305
306    pub fn emit_method_call_opt(&mut self, name: u16, argc: u8, line: u32) {
307        self.emit_method_call_inner(Op::MethodCallOpt, name, argc, line);
308    }
309
310    fn emit_method_call_inner(&mut self, op: Op, name: u16, argc: u8, line: u32) {
311        self.note_balance(op, u16::from(argc));
312        self.push_bytes(&[op as u8, (name >> 8) as u8, name as u8, argc], line);
313    }
314
315    pub fn emit_set_local_slot_property(&mut self, property: u16, slot: u16, line: u32) {
316        self.note_balance(Op::SetLocalSlotProperty, 0);
317        self.push_bytes(
318            &[
319                Op::SetLocalSlotProperty as u8,
320                (property >> 8) as u8,
321                property as u8,
322                (slot >> 8) as u8,
323                slot as u8,
324            ],
325            line,
326        );
327    }
328
329    fn push_bytes(&mut self, bytes: &[u8], line: u32) {
330        self.code.extend_from_slice(bytes);
331        self.lines.extend(std::iter::repeat_n(line, bytes.len()));
332        self.columns
333            .extend(std::iter::repeat_n(self.current_col, bytes.len()));
334    }
335
336    pub fn current_offset(&self) -> usize {
337        self.code.len()
338    }
339
340    pub fn emit_jump(&mut self, op: Op, line: u32) -> usize {
341        self.note_balance(op, 0);
342        let patch = self.code.len() + 1;
343        self.push_bytes(&[op as u8, 0xff, 0xff], line);
344        patch
345    }
346
347    pub fn patch_jump(&mut self, patch: usize) {
348        self.patch_jump_to(patch, self.code.len());
349    }
350
351    pub fn patch_jump_to(&mut self, patch: usize, target: usize) {
352        // The compiler's final addressability guard turns this provisional
353        // truncation into a structured compile error before the image escapes.
354        let target = target as u16;
355        self.code[patch..patch + 2].copy_from_slice(&target.to_be_bytes());
356    }
357
358    pub fn read_u16(&self, position: usize) -> u16 {
359        u16::from_be_bytes([self.code[position], self.code[position + 1]])
360    }
361
362    pub(crate) fn add_local_slot(
363        &mut self,
364        name: String,
365        mutable: bool,
366        scope_depth: usize,
367    ) -> u16 {
368        let slot = u16::try_from(self.local_slots.len()).expect("local slot count exceeded u16");
369        self.local_slots.push(LocalSlotInfo {
370            name,
371            mutable,
372            scope_depth,
373        });
374        slot
375    }
376
377    #[cfg(debug_assertions)]
378    pub(crate) fn balance_probe(&self) -> BalanceProbe {
379        BalanceProbe {
380            depth: self.balance_depth,
381            nonlinear: self.balance_nonlinear,
382        }
383    }
384
385    #[cfg(debug_assertions)]
386    pub(crate) fn balance_delta_since(&self, probe: BalanceProbe) -> Option<i32> {
387        (self.balance_nonlinear == probe.nonlinear).then_some(self.balance_depth - probe.depth)
388    }
389
390    #[cfg(debug_assertions)]
391    fn note_balance(&mut self, op: Op, count: u16) {
392        match stack_delta(op, count) {
393            Some(delta) => self.balance_depth += delta,
394            None => self.balance_nonlinear += 1,
395        }
396    }
397
398    #[cfg(not(debug_assertions))]
399    fn note_balance(&mut self, _op: Op, _count: u16) {}
400
401    pub fn disassemble(&self, name: &str) -> String {
402        let mut output = format!("== {name} ==\n");
403        let mut ip = 0;
404        while let Some(byte) = self.code.get(ip).copied() {
405            let offset = ip;
406            let line = self.lines.get(ip).copied().unwrap_or(0);
407            let Some(op) = Op::from_byte(byte) else { break };
408            ip += 1;
409            let rendered = self.disassemble_instruction(op, &mut ip);
410            output.push_str(&format!("{offset:04} [{line:>4}] {rendered}\n"));
411        }
412        output
413    }
414
415    fn disassemble_instruction(&self, op: Op, ip: &mut usize) -> String {
416        let label = opcode_label(op.name());
417        let read_u16 = |position: usize| {
418            self.code
419                .get(position..position + 2)
420                .map(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]))
421        };
422        if matches!(
423            op,
424            Op::Constant
425                | Op::GetVar
426                | Op::DefLet
427                | Op::DefVar
428                | Op::DefCell
429                | Op::SetVar
430                | Op::GetProperty
431                | Op::GetPropertyOpt
432                | Op::SetProperty
433                | Op::Import
434        ) {
435            let Some(index) = read_u16(*ip) else {
436                return label;
437            };
438            *ip += 2;
439            return match self.constants.get(index as usize) {
440                Some(value) => format!("{label} {index:>4} ({value})"),
441                None => format!("{label} {index:>4}"),
442            };
443        }
444        if matches!(
445            op,
446            Op::GetLocalSlot
447                | Op::DefLocalSlot
448                | Op::SetLocalSlot
449                | Op::SetLocalSlotSubscript
450                | Op::ConcatAssignLocal
451        ) {
452            let Some(slot) = read_u16(*ip) else {
453                return label;
454            };
455            *ip += 2;
456            return match self.local_slots.get(slot as usize) {
457                Some(info) => format!("{label} {slot:>4} ({})", info.name),
458                None => format!("{label} {slot:>4}"),
459            };
460        }
461        if op == Op::SetLocalSlotProperty {
462            let Some(property) = read_u16(*ip) else {
463                return label;
464            };
465            let Some(slot) = read_u16(*ip + 2) else {
466                return label;
467            };
468            *ip += 4;
469            let property = self
470                .constants
471                .get(property as usize)
472                .map(ToString::to_string)
473                .unwrap_or_default();
474            return format!("{label} {slot:>4} {property}");
475        }
476        if matches!(op, Op::MethodCall | Op::MethodCallOpt) {
477            let Some(name) = read_u16(*ip) else {
478                return label;
479            };
480            let Some(argc) = self.code.get(*ip + 2).copied() else {
481                return label;
482            };
483            *ip += 3;
484            let name = self
485                .constants
486                .get(name as usize)
487                .map(ToString::to_string)
488                .unwrap_or_default();
489            return format!("{label} {argc:>4} ({name})");
490        }
491        if matches!(op, Op::Call | Op::TailCall) {
492            let Some(argc) = self.code.get(*ip).copied() else {
493                return label;
494            };
495            *ip += 1;
496            return format!("{label} {argc:>4}");
497        }
498        let width = instruction_len(op, &self.code[(*ip).saturating_sub(1)..]).unwrap_or(1);
499        if width == 3 {
500            let Some(value) = read_u16(*ip) else {
501                return label;
502            };
503            *ip += 2;
504            return format!("{label} {value:>4}");
505        }
506        if width > 1 {
507            *ip = (*ip).saturating_add(width - 1).min(self.code.len());
508        }
509        label
510    }
511}
512
513fn opcode_label(name: &str) -> String {
514    let mut output = String::new();
515    for (index, ch) in name.chars().enumerate() {
516        if index > 0 && ch.is_ascii_uppercase() {
517            output.push('_');
518        }
519        output.push(ch.to_ascii_uppercase());
520    }
521    output
522}
523
524fn reads_outer_name(op: Op) -> bool {
525    matches!(
526        op,
527        Op::GetVar
528            | Op::SetVar
529            | Op::Call
530            | Op::TailCall
531            | Op::Pipe
532            | Op::CheckType
533            | Op::CallSpread
534            | Op::CallBuiltin
535            | Op::CallBuiltinSpread
536    )
537}
538
539pub fn instruction_len(op: Op, _remaining: &[u8]) -> Option<usize> {
540    Some(op.instruction_len())
541}
542
543#[cfg(debug_assertions)]
544fn stack_delta(op: Op, count: u16) -> Option<i32> {
545    use Op::*;
546    let count = i32::from(count);
547    Some(match op {
548        Constant | Nil | True | False | RootHarness | GetVar | GetArgc | GetLocalSlot | Closure
549        | Dup => 1,
550        DefLet | DefVar | DefCell | SetVar | DefLocalSlot | SetLocalSlot | SetProperty
551        | SetLocalSlotProperty | ConcatAssignLocal | Pop => -1,
552        Negate | Not | GetProperty | GetPropertyOpt | CheckType | TryUnwrap | TryWrapOk | Swap
553        | PushScope | PopScope | PopIterator | PopHandler => 0,
554        Add | Sub | Mul | Div | Mod | Pow | AddInt | SubInt | MulInt | DivInt | ModInt
555        | AddFloat | SubFloat | MulFloat | DivFloat | ModFloat | Equal | NotEqual | Less
556        | Greater | LessEqual | GreaterEqual | EqualInt | NotEqualInt | LessInt | GreaterInt
557        | LessEqualInt | GreaterEqualInt | EqualFloat | NotEqualFloat | LessFloat
558        | GreaterFloat | LessEqualFloat | GreaterEqualFloat | EqualBool | NotEqualBool
559        | EqualString | NotEqualString | Contains | Subscript | SubscriptOpt => -1,
560        IterInit => -1,
561        Slice | SetSubscript | SetLocalSlotSubscript => -2,
562        BuildList | Concat | CallBuiltin => 1 - count,
563        BuildDict => 1 - 2 * count,
564        Call | MethodCall | MethodCallOpt => -count,
565        Jump | JumpIfFalse | JumpIfTrue | IterNext | Return | TailCall | Throw | TryCatchSetup
566        | Spawn | Pipe | Parallel | ParallelMap | ParallelMapStream | ParallelSettle
567        | SyncMutexEnter | SyncMutexEnterKeyed | TaskScopeEnter | TaskScopeExit | Import
568        | SelectiveImport | NamespaceImport | DeadlineSetup | DeadlineEnd | BuildEnum
569        | MatchEnum | Yield | CallSpread | CallBuiltinSpread | MethodCallSpread => return None,
570    })
571}