biujs 0.1.0-alpha.0

A lightweight, embeddable JavaScript engine with ES6 support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
use std::{
    collections::{BTreeMap, HashMap},
    fmt,
    sync::Arc,
};

pub const MIN_REQUIRED_REGISTER: usize = 3;

#[derive(Debug, Clone)]
pub struct Module {
    pub name: Option<String>,
    pub constants: Vec<Constant>,
    pub symtab: HashMap<FunctionId, usize>,
    /// Declared name and parameter count of every bytecode function, keyed by
    /// function id. Function objects expose these as `name` / `length`.
    pub func_info: HashMap<u32, (String, usize)>,
    /// Ids of the functions declared as `function*`. A call to one of these
    /// creates a generator object instead of pushing a frame.
    pub generators: std::collections::HashSet<u32>,
    /// Ids of constructors declared in a class with an `extends` clause. Their
    /// `this` is uninitialized until `super()` runs.
    pub derived_ctors: std::collections::HashSet<u32>,
    pub instructions: Vec<Bytecode>,
    pub debug_instructions: BTreeMap<usize, crate::compiler::ir::Instruction>,
}

impl Module {
    pub fn new(
        name: impl Into<Option<String>>,
        constants: Vec<Constant>,
        symtab: HashMap<FunctionId, usize>,
        func_info: HashMap<u32, (String, usize)>,
        generators: std::collections::HashSet<u32>,
        derived_ctors: std::collections::HashSet<u32>,
        instructions: Vec<Bytecode>,
    ) -> Self {
        Self {
            name: name.into(),
            constants,
            symtab,
            func_info,
            generators,
            derived_ctors,
            instructions,
            debug_instructions: BTreeMap::new(),
        }
    }
}

impl fmt::Display for Module {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Module")?;
        if let Some(name) = &self.name {
            write!(f, " {name}")?;
        }
        writeln!(f)?;

        writeln!(f, "=== constants ===")?;
        for (i, constant) in self.constants.iter().enumerate() {
            writeln!(f, "{i}\t: {constant}")?;
        }

        writeln!(f, "=== symtab ===")?;
        for (function_id, &index) in &self.symtab {
            writeln!(f, "{function_id}: {index}")?;
        }

        writeln!(f, "=== instructions ===")?;
        for (i, instruction) in self.instructions.iter().enumerate() {
            write!(f, "{i}\t: {instruction}")?;
            if let Some(debug_instruction) = self.debug_instructions.get(&i) {
                writeln!(f, "\t;{debug_instruction:<16}")?;
            } else {
                writeln!(f)?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Bytecode {
    pub opcode: Opcode,
    pub operands: [Operand; 3],
}

impl Bytecode {
    pub fn empty(opcode: Opcode) -> Self {
        Self {
            opcode,
            operands: [Operand::Immd(0); 3],
        }
    }

    pub fn single(opcode: Opcode, operand: Operand) -> Self {
        Self {
            opcode,
            operands: [operand, Operand::Immd(0), Operand::Immd(0)],
        }
    }

    pub fn double(opcode: Opcode, dst: Operand, src: Operand) -> Self {
        Self {
            opcode,
            operands: [dst, src, Operand::Immd(0)],
        }
    }

    pub fn triple(opcode: Opcode, dst: Operand, src1: Operand, src2: Operand) -> Self {
        Self {
            opcode,
            operands: [dst, src1, src2],
        }
    }
}

impl fmt::Display for Bytecode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.opcode)?;
        if let Some((last, operands)) = self.operands.split_last() {
            for operand in operands {
                write!(f, " {operand},")?;
            }
            write!(f, " {last}")?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
pub enum Opcode {
    /// load_const dst, const_id
    LoadConst,
    /// load_env dst, name
    LoadEnv,
    /// halt
    Halt,
    /// push src
    Push,
    /// pop dst
    Pop,
    /// pushc offset
    PushC,
    /// popc dst
    PopC,
    /// addc offset
    AddC,
    /// subc offset
    SubC,
    /// movc
    MovC,
    /// call func_id
    Call,
    /// call_ex callable
    CallEx,
    /// call_native callable args_count
    CallNative,
    /// ret value
    Ret,
    /// mov dst, src
    Mov,
    /// jump offset
    Jump,
    /// br_if cond, true_offset, false_offset
    BrIf,
    /// not dst, src
    Not,
    /// bitnot dst, src (bitwise NOT ~)
    BitNot,
    /// bitand dst, src1, src2 (bitwise AND &)
    BitAnd,
    /// bitor dst, src1, src2 (bitwise OR |)
    BitOr,
    /// bitxor dst, src1, src2 (bitwise XOR ^)
    BitXor,
    /// shl dst, src1, src2 (left shift <<)
    Shl,
    /// shr dst, src1, src2 (sign-propagating right shift >>)
    Shr,
    /// ushr dst, src1, src2 (unsigned right shift >>>)
    UShr,
    /// neg dst, src
    Neg,
    /// addx dst, src1, src2 (object addition)
    Addx,
    /// subx dst, src1, src2 (object subtraction)
    Subx,
    /// mulx dst, src1, src2 (object multiplication)
    Mulx,
    /// divx dst, src1, src2 (object division)
    Divx,
    /// remx dst, src1, src2 (object remainder)
    Remx,
    /// pow dst, src1, src2 (exponentiation `**`)
    Pow,
    /// and dst, src1, src2
    And,
    /// or dst, src1, src2
    Or,
    /// less dst, src1, src2
    Less,
    /// less_equal dst, src1, src2
    LessEqual,
    /// greater dst, src1, src2
    Greater,
    /// greater_equal dst, src1, src2
    GreaterEqual,
    /// equal dst, src1, src2
    Equal,
    /// not_equal dst, src1, src2
    NotEqual,
    /// strict_equal dst, src1, src2 (JS ===)
    StrictEqual,
    /// strict_not_equal dst, src1, src2 (JS !==)
    StrictNotEqual,
    /// typeof dst, src
    TypeOf,
    /// typeof_env dst, name — `typeof x` for an unresolvable-at-compile-time
    /// name: yields "undefined" instead of throwing ReferenceError.
    TypeOfEnv,
    /// instanceof dst, src1, src2
    InstanceOf,
    /// in dst, src1, src2
    In,
    /// make_iter dst, src
    MakeIter,
    /// iter_next dst, has_next, src
    IterNext,
    /// make_array dst
    MakeArray,
    /// array_push dst, src
    ArrayPush,
    /// array_push_spread dst, src — append every element of `src` to `array`
    ArrayPushSpread,
    /// make_object dst
    MakeObject,
    /// index_get dst, obj, idx
    IndexGet,
    /// index_set obj, idx, value
    IndexSet,
    /// prop_get dst, obj, prop
    PropGet,
    /// prop_set obj, prop, value
    PropSet,
    /// prop_delete dst, obj, prop
    PropDelete,
    /// index_delete dst, obj, idx
    IndexDelete,
    /// store_env name, value — assign into the global environment
    StoreEnv,
    /// call_method dst, obj, method
    CallMethod,
    /// try catch_offset, finally_offset (SEH: register handler at offset)
    Try,
    /// end_try (SEH: unregister handler)
    EndTry,
    /// throw src (SEH: throw exception)
    ThrowExc,
    /// load_exception dst (SEH: load caught exception)
    LoadException,
    /// resume_exception (SEH: re-throw pending exception after finally)
    ResumeExc,
    /// delayed_jump target, seh_depth (execute finally blocks then jump)
    DelayedJump,
    /// create_closure dst, func_id
    CreateClosure,
    /// new dst, constructor
    New,
    /// load_this dst
    LoadThis,
    /// load_new_target dst — `new.target` of the current frame (undefined for a
    /// plain call)
    LoadNewTarget,
    /// load_current_function dst — the function object whose body is running
    /// (used by `super` to find the [[HomeObject]] recorded at class definition)
    LoadCurrentFunction,
    /// make_func_obj dst, func_id
    MakeFuncObj,
    /// make_arrow_func_obj dst, func_id, captured_this
    MakeArrowFuncObj,
    /// closure_var name, value — push a captured variable for the next MakeArrowFuncObj
    ClosureVar,
    /// arguments dst — materialise the current frame's `arguments` object
    Arguments,
    /// iter_close iter — signal early exit to a protocol iterator
    IterClose,
    /// Suspend the enclosing generator: record the yielded value, hand the
    /// current frame to [`crate::vm::VM::generator_resume`] and stop the
    /// nested execution loop (the VM jumps past the last instruction, which is
    /// what terminates a nested `step` loop).
    Yield,
    /// to_string dst, src — ES ToString (objects via ToPrimitive("string"))
    ToString,
    /// to_number dst, src — ES ToNumber (objects via ToPrimitive("number"))
    ToNumber,
    /// make_rest dst, from_index — collect arguments[from_index..] into an array
    MakeRest,
    /// call_spread result, callee, this, args — call with args taken from an array
    CallSpread,
    /// call_super_spread callee, this, args — `super(...)`: like CallSpread but
    /// the callee frame inherits the caller's `new.target`
    CallSuperSpread,
    /// new_spread dst, ctor, args — construct with args taken from an array
    NewSpread,
}

impl fmt::Display for Opcode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Opcode::Jump => write!(f, "br"),
            Opcode::BrIf => write!(f, "br_if"),
            Opcode::Halt => write!(f, "halt"),
            Opcode::Push => write!(f, "push"),
            Opcode::Pop => write!(f, "pop"),
            Opcode::PushC => write!(f, "pushc"),
            Opcode::PopC => write!(f, "popc"),
            Opcode::MovC => write!(f, "movc"),
            Opcode::AddC => write!(f, "addc"),
            Opcode::SubC => write!(f, "subc"),
            Opcode::Call => write!(f, "call"),
            Opcode::CallEx => write!(f, "call_ex"),
            Opcode::CallNative => write!(f, "call_native"),
            Opcode::Ret => write!(f, "ret"),
            Opcode::LoadConst => write!(f, "load_const"),
            Opcode::LoadEnv => write!(f, "load_env"),
            Opcode::Mov => write!(f, "mov"),
            Opcode::Not => write!(f, "not"),
            Opcode::BitNot => write!(f, "bitnot"),
            Opcode::BitAnd => write!(f, "bitand"),
            Opcode::BitOr => write!(f, "bitor"),
            Opcode::BitXor => write!(f, "bitxor"),
            Opcode::Shl => write!(f, "shl"),
            Opcode::Shr => write!(f, "shr"),
            Opcode::UShr => write!(f, "ushr"),
            Opcode::Neg => write!(f, "neg"),
            Opcode::Addx => write!(f, "addx"),
            Opcode::Subx => write!(f, "subx"),
            Opcode::Mulx => write!(f, "mulx"),
            Opcode::Divx => write!(f, "divx"),
            Opcode::Remx => write!(f, "remx"),
            Opcode::Pow => write!(f, "pow"),
            Opcode::And => write!(f, "and"),
            Opcode::Or => write!(f, "or"),
            Opcode::Less => write!(f, "lt"),
            Opcode::LessEqual => write!(f, "lte"),
            Opcode::Greater => write!(f, "gt"),
            Opcode::GreaterEqual => write!(f, "gte"),
            Opcode::Equal => write!(f, "eq"),
            Opcode::NotEqual => write!(f, "ne"),
            Opcode::StrictEqual => write!(f, "seq"),
            Opcode::StrictNotEqual => write!(f, "sne"),
            Opcode::TypeOf => write!(f, "typeof"),
            Opcode::TypeOfEnv => write!(f, "typeof_env"),
            Opcode::InstanceOf => write!(f, "instanceof"),
            Opcode::In => write!(f, "in"),
            Opcode::MakeIter => write!(f, "make_iter"),
            Opcode::IterNext => write!(f, "iter_next"),
            Opcode::MakeArray => write!(f, "make_array"),
            Opcode::ArrayPush => write!(f, "array_push"),
            Opcode::ArrayPushSpread => write!(f, "array_push_spread"),
            Opcode::MakeObject => write!(f, "make_object"),
            Opcode::IndexGet => write!(f, "index_get"),
            Opcode::IndexSet => write!(f, "index_set"),
            Opcode::PropGet => write!(f, "prop_get"),
            Opcode::PropSet => write!(f, "prop_set"),
            Opcode::PropDelete => write!(f, "prop_delete"),
            Opcode::IndexDelete => write!(f, "index_delete"),
            Opcode::StoreEnv => write!(f, "store_env"),
            Opcode::CallMethod => write!(f, "call_method"),
            Opcode::Try => write!(f, "try"),
            Opcode::EndTry => write!(f, "end_try"),
            Opcode::ThrowExc => write!(f, "throw"),
            Opcode::LoadException => write!(f, "load_exception"),
            Opcode::ResumeExc => write!(f, "resume_exception"),
            Opcode::DelayedJump => write!(f, "delayed_jump"),
            Opcode::CreateClosure => write!(f, "create_closure"),
            Opcode::New => write!(f, "new"),
            Opcode::LoadThis => write!(f, "load_this"),
            Opcode::LoadNewTarget => write!(f, "load_new_target"),
            Opcode::LoadCurrentFunction => write!(f, "load_current_function"),
            Opcode::MakeFuncObj => write!(f, "make_func_obj"),
            Opcode::MakeArrowFuncObj => write!(f, "make_arrow_func_obj"),
            Opcode::ClosureVar => write!(f, "closure_var"),
            Opcode::Arguments => write!(f, "arguments"),
            Opcode::IterClose => write!(f, "iter_close"),
            Opcode::Yield => write!(f, "yield"),
            Opcode::ToString => write!(f, "to_string"),
            Opcode::ToNumber => write!(f, "to_number"),
            Opcode::MakeRest => write!(f, "make_rest"),
            Opcode::CallSpread => write!(f, "call_spread"),
            Opcode::CallSuperSpread => write!(f, "call_super_spread"),
            Opcode::NewSpread => write!(f, "new_spread"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Hash)]
pub enum Operand {
    Primitive(Primitive),
    Register(Register),
    Stack(isize),
    Immd(isize),
    Symbol(u32),
}

impl Operand {
    pub fn new_immd(immd: isize) -> Self {
        Self::Immd(immd)
    }

    pub fn new_primitive(primitive: Primitive) -> Self {
        Self::Primitive(primitive)
    }

    pub fn new_register(reg: Register) -> Self {
        Self::Register(reg)
    }

    pub fn new_stack(offset: isize) -> Self {
        Self::Stack(offset)
    }

    pub fn new_symbol(id: u32) -> Self {
        Self::Symbol(id)
    }

    pub fn as_immd(&self) -> isize {
        match self {
            Operand::Immd(immd) => *immd,
            _ => panic!("{self:?} not an immediate"),
        }
    }
}

impl fmt::Display for Operand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Operand::Primitive(primitive) => write!(f, "{primitive}"),
            Operand::Register(reg) => write!(f, "{reg}"),
            Operand::Stack(offset) => write!(f, "[rbp{offset:+}]"),
            Operand::Immd(immd) => write!(f, "{immd}"),
            Operand::Symbol(id) => write!(f, "sym_{id}"),
        }
    }
}

impl From<Register> for Operand {
    fn from(reg: Register) -> Self {
        Operand::Register(reg)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Hash)]
pub enum Register {
    R0 = 0,
    R1,
    R2,
    R3,
    R4,
    R5,
    R6,
    R7,
    R8,
    R9,
    R10,
    R11,
    R12,
    R13,
    R14,
    R15,
    /// Stack pointer
    Rsp,
    /// Base pointer
    Rbp,
    /// Return value
    Rv,
}

impl Register {
    pub fn as_usize(&self) -> usize {
        *self as usize
    }

    pub fn general() -> [Register; 16] {
        [
            Register::R0,
            Register::R1,
            Register::R2,
            Register::R3,
            Register::R4,
            Register::R5,
            Register::R6,
            Register::R7,
            Register::R8,
            Register::R9,
            Register::R10,
            Register::R11,
            Register::R12,
            Register::R13,
            Register::R14,
            Register::R15,
        ]
    }

    pub fn small_general() -> [Register; 4] {
        [Register::R0, Register::R1, Register::R2, Register::R3]
    }

    pub fn all() -> [Register; 19] {
        [
            Register::R0,
            Register::R1,
            Register::R2,
            Register::R3,
            Register::R4,
            Register::R5,
            Register::R6,
            Register::R7,
            Register::R8,
            Register::R9,
            Register::R10,
            Register::R11,
            Register::R12,
            Register::R13,
            Register::R14,
            Register::R15,
            Register::Rsp,
            Register::Rbp,
            Register::Rv,
        ]
    }
}

impl fmt::Display for Register {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Register::R0 => write!(f, "r0"),
            Register::R1 => write!(f, "r1"),
            Register::R2 => write!(f, "r2"),
            Register::R3 => write!(f, "r3"),
            Register::R4 => write!(f, "r4"),
            Register::R5 => write!(f, "r5"),
            Register::R6 => write!(f, "r6"),
            Register::R7 => write!(f, "r7"),
            Register::R8 => write!(f, "r8"),
            Register::R9 => write!(f, "r9"),
            Register::R10 => write!(f, "r10"),
            Register::R11 => write!(f, "r11"),
            Register::R12 => write!(f, "r12"),
            Register::R13 => write!(f, "r13"),
            Register::R14 => write!(f, "r14"),
            Register::R15 => write!(f, "r15"),
            Register::Rsp => write!(f, "rsp"),
            Register::Rbp => write!(f, "rbp"),
            Register::Rv => write!(f, "rv"),
        }
    }
}

#[derive(Default, Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum Primitive {
    #[default]
    Null,
    Undefined,
    Boolean(bool),
    Integer(i64),
    Float(f64),
}

impl fmt::Display for Primitive {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Primitive::Null => write!(f, "null"),
            Primitive::Undefined => write!(f, "undefined"),
            Primitive::Boolean(b) => write!(f, "{b}"),
            Primitive::Integer(i) => write!(f, "{i}"),
            Primitive::Float(ff) => write!(f, "{ff}"),
        }
    }
}

impl From<bool> for Primitive {
    fn from(value: bool) -> Self {
        Primitive::Boolean(value)
    }
}

impl From<i64> for Primitive {
    fn from(value: i64) -> Self {
        Primitive::Integer(value)
    }
}

impl From<f64> for Primitive {
    fn from(value: f64) -> Self {
        Primitive::Float(value)
    }
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash)]
pub enum Constant {
    String(Arc<String>),
}

impl From<&str> for Constant {
    fn from(value: &str) -> Self {
        Constant::String(Arc::new(value.to_string()))
    }
}

impl From<String> for Constant {
    fn from(value: String) -> Self {
        Constant::String(Arc::new(value.to_string()))
    }
}

impl fmt::Display for Constant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Constant::String(s) => write!(f, "\"{s}\""),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct ConstantId(u32);

impl ConstantId {
    pub fn new(id: u32) -> Self {
        Self(id)
    }

    pub fn as_usize(&self) -> usize {
        self.0 as usize
    }

    pub fn as_isize(&self) -> isize {
        self.0 as isize
    }
}

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct FunctionId(u32);

impl FunctionId {
    pub fn new(id: u32) -> Self {
        Self(id)
    }

    pub fn as_usize(&self) -> usize {
        self.0 as usize
    }

    pub fn as_isize(&self) -> isize {
        self.0 as isize
    }
}

impl fmt::Display for FunctionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ──────────────────────── Operand ────────────────────────

    #[test]
    fn test_operand_immd() {
        let op = Operand::new_immd(42);
        assert_eq!(op.as_immd(), 42);
    }

    #[test]
    fn test_operand_register() {
        let op = Operand::new_register(Register::R0);
        match op {
            Operand::Register(reg) => assert_eq!(reg, Register::R0),
            _ => panic!("expected Register"),
        }
    }

    #[test]
    fn test_operand_primitive() {
        let op = Operand::new_primitive(Primitive::Null);
        match op {
            Operand::Primitive(p) => assert_eq!(p, Primitive::Null),
            _ => panic!("expected Primitive"),
        }
    }

    #[test]
    fn test_operand_stack() {
        let op = Operand::new_stack(-8);
        match op {
            Operand::Stack(offset) => assert_eq!(offset, -8),
            _ => panic!("expected Stack"),
        }
    }

    #[test]
    fn test_operand_symbol() {
        let op = Operand::new_symbol(5);
        match op {
            Operand::Symbol(id) => assert_eq!(id, 5),
            _ => panic!("expected Symbol"),
        }
    }

    #[test]
    fn test_operand_display() {
        assert_eq!(format!("{}", Operand::new_immd(42)), "42");
        assert_eq!(format!("{}", Operand::new_register(Register::R0)), "r0");
        assert_eq!(
            format!("{}", Operand::new_primitive(Primitive::Null)),
            "null"
        );
        assert_eq!(format!("{}", Operand::new_stack(-8)), "[rbp-8]");
        assert_eq!(format!("{}", Operand::new_symbol(5)), "sym_5");
    }

    // ──────────────────────── Register ────────────────────────

    #[test]
    fn test_register_as_usize() {
        assert_eq!(Register::R0.as_usize(), 0);
        assert_eq!(Register::R15.as_usize(), 15);
        assert_eq!(Register::Rsp.as_usize(), 16);
        assert_eq!(Register::Rbp.as_usize(), 17);
        assert_eq!(Register::Rv.as_usize(), 18);
    }

    #[test]
    fn test_register_general() {
        let regs = Register::general();
        assert_eq!(regs.len(), 16);
        assert_eq!(regs[0], Register::R0);
        assert_eq!(regs[15], Register::R15);
    }

    #[test]
    fn test_register_small_general() {
        let regs = Register::small_general();
        assert_eq!(regs.len(), 4);
        assert_eq!(regs[0], Register::R0);
        assert_eq!(regs[3], Register::R3);
    }

    #[test]
    fn test_register_all() {
        let regs = Register::all();
        assert_eq!(regs.len(), 19);
        assert_eq!(regs[0], Register::R0);
        assert_eq!(regs[16], Register::Rsp);
        assert_eq!(regs[17], Register::Rbp);
        assert_eq!(regs[18], Register::Rv);
    }

    #[test]
    fn test_register_display() {
        assert_eq!(format!("{}", Register::R0), "r0");
        assert_eq!(format!("{}", Register::R15), "r15");
        assert_eq!(format!("{}", Register::Rsp), "rsp");
        assert_eq!(format!("{}", Register::Rbp), "rbp");
        assert_eq!(format!("{}", Register::Rv), "rv");
    }

    // ──────────────────────── Primitive ────────────────────────

    #[test]
    fn test_primitive_default() {
        assert_eq!(Primitive::default(), Primitive::Null);
    }

    #[test]
    fn test_primitive_display() {
        assert_eq!(format!("{}", Primitive::Null), "null");
        assert_eq!(format!("{}", Primitive::Undefined), "undefined");
        assert_eq!(format!("{}", Primitive::Boolean(true)), "true");
        assert_eq!(format!("{}", Primitive::Boolean(false)), "false");
        assert_eq!(format!("{}", Primitive::Integer(42)), "42");
        assert_eq!(format!("{}", Primitive::Float(3.14)), "3.14");
    }

    #[test]
    fn test_primitive_from_bool() {
        assert_eq!(Primitive::from(true), Primitive::Boolean(true));
        assert_eq!(Primitive::from(false), Primitive::Boolean(false));
    }

    #[test]
    fn test_primitive_from_i64() {
        assert_eq!(Primitive::from(42i64), Primitive::Integer(42));
        assert_eq!(Primitive::from(-1i64), Primitive::Integer(-1));
    }

    #[test]
    fn test_primitive_from_f64() {
        assert_eq!(Primitive::from(3.14f64), Primitive::Float(3.14));
        assert_eq!(Primitive::from(0.0f64), Primitive::Float(0.0));
    }

    // ──────────────────────── Bytecode ────────────────────────

    #[test]
    fn test_bytecode_empty() {
        let inst = Bytecode::empty(Opcode::Halt);
        assert!(matches!(inst.opcode, Opcode::Halt));
        for op in &inst.operands {
            assert!(matches!(op, Operand::Immd(0)));
        }
    }

    #[test]
    fn test_bytecode_single() {
        let inst = Bytecode::single(Opcode::Push, Operand::Register(Register::R0));
        assert!(matches!(inst.opcode, Opcode::Push));
        assert!(matches!(inst.operands[0], Operand::Register(Register::R0)));
        assert!(matches!(inst.operands[1], Operand::Immd(0)));
        assert!(matches!(inst.operands[2], Operand::Immd(0)));
    }

    #[test]
    fn test_bytecode_double() {
        let inst = Bytecode::double(
            Opcode::Mov,
            Operand::Register(Register::R0),
            Operand::Register(Register::R1),
        );
        assert!(matches!(inst.opcode, Opcode::Mov));
        assert!(matches!(inst.operands[0], Operand::Register(Register::R0)));
        assert!(matches!(inst.operands[1], Operand::Register(Register::R1)));
        assert!(matches!(inst.operands[2], Operand::Immd(0)));
    }

    #[test]
    fn test_bytecode_triple() {
        let inst = Bytecode::triple(
            Opcode::Addx,
            Operand::Register(Register::R0),
            Operand::Register(Register::R1),
            Operand::Register(Register::R2),
        );
        assert!(matches!(inst.opcode, Opcode::Addx));
        assert!(matches!(inst.operands[0], Operand::Register(Register::R0)));
        assert!(matches!(inst.operands[1], Operand::Register(Register::R1)));
        assert!(matches!(inst.operands[2], Operand::Register(Register::R2)));
    }

    #[test]
    fn test_bytecode_display() {
        let inst = Bytecode::triple(
            Opcode::Addx,
            Operand::Register(Register::R0),
            Operand::Register(Register::R1),
            Operand::Register(Register::R2),
        );
        assert_eq!(format!("{}", inst), "addx r0, r1, r2");
    }

    // ──────────────────────── Constant ────────────────────────

    #[test]
    fn test_constant_from_str() {
        let c: Constant = "hello".into();
        match &c {
            Constant::String(s) => assert_eq!(s.as_ref(), "hello"),
        }
    }

    #[test]
    fn test_constant_from_string() {
        let c: Constant = "world".to_string().into();
        match &c {
            Constant::String(s) => assert_eq!(s.as_ref(), "world"),
        }
    }

    #[test]
    fn test_constant_display() {
        let c: Constant = "hello".into();
        assert_eq!(format!("{}", c), "\"hello\"");
    }

    // ──────────────────────── FunctionId ────────────────────────

    #[test]
    fn test_function_id() {
        let fid = FunctionId::new(42);
        assert_eq!(fid.as_usize(), 42);
        assert_eq!(fid.as_isize(), 42);
        assert_eq!(format!("{}", fid), "42");
    }

    // ──────────────────────── Module ────────────────────────

    #[test]
    fn test_module_new() {
        let module = Module::new(
            Some("test".to_string()),
            vec![],
            HashMap::new(),
            HashMap::new(),
            std::collections::HashSet::new(),
            std::collections::HashSet::new(),
            vec![],
        );
        assert_eq!(module.name, Some("test".to_string()));
        assert!(module.constants.is_empty());
        assert!(module.symtab.is_empty());
        assert!(module.instructions.is_empty());
    }

    #[test]
    fn test_module_display() {
        let module = Module::new(
            Some("main".to_string()),
            vec![Constant::from("hello")],
            HashMap::new(),
            HashMap::new(),
            std::collections::HashSet::new(),
            std::collections::HashSet::new(),
            vec![Bytecode::empty(Opcode::Halt)],
        );
        let display = format!("{}", module);
        assert!(display.contains("Module main"));
        assert!(display.contains("\"hello\""));
        assert!(display.contains("halt"));
    }
}