Skip to main content

vibe/
decompiler.rs

1//! Bi-directional Poetic Decompiler for VibeScript (Zero-Heap friendly).
2//!
3//! Decompiles `vibe-bc-0.1` bytecode chunks and parsed AST structures into clean,
4//! formatted, human-readable VibeScript source code. Supports round-trip AST formatting,
5//! expression precedence reconstruction, and block indentation.
6
7use crate::ast::*;
8use crate::bytecode::op::{Chunk, Const, Op};
9use std::fmt::Write;
10
11/// Formatting options for the decompiler.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct DecompileOptions {
14    /// Spaces per indentation level (default: 4).
15    pub indent_spaces: usize,
16    /// Whether to emit explicit step budgets.
17    pub emit_budgets: bool,
18    /// Whether to emit type annotations where known.
19    pub emit_types: bool,
20}
21
22impl Default for DecompileOptions {
23    fn default() -> Self {
24        Self {
25            indent_spaces: 4,
26            emit_budgets: true,
27            emit_types: true,
28        }
29    }
30}
31
32/// Decompile an entire `Program` AST back into formatted VibeScript source.
33pub fn decompile_program(program: &Program, opts: &DecompileOptions) -> String {
34    let mut out = String::with_capacity(1024);
35
36    for loc in &program.locales {
37        let _ = writeln!(out, "locale {};", loc.code);
38    }
39    if !program.locales.is_empty() {
40        out.push('\n');
41    }
42
43    // Module declaration
44    if let Some(module) = &program.module {
45        match &module.name {
46            Name::Ident(id) => {
47                let _ = writeln!(out, "module {id};\n");
48            }
49            Name::Iri(iri) => {
50                let _ = writeln!(out, "module <{iri}>;\n");
51            }
52        }
53    }
54
55    // Prefixes
56    for prefix in &program.prefixes {
57        let _ = writeln!(out, "prefix {}: <{}>;", prefix.prefix, prefix.iri);
58    }
59    if !program.prefixes.is_empty() {
60        out.push('\n');
61    }
62
63    // Imports
64    for import in &program.imports {
65        if let Some(alias) = &import.alias {
66            let _ = writeln!(out, "import \"{}\" as {};", import.path, alias);
67        } else {
68            let _ = writeln!(out, "import \"{}\";", import.path);
69        }
70    }
71    if !program.imports.is_empty() {
72        out.push('\n');
73    }
74
75    // Capability requires
76    for req in &program.requires {
77        let _ = writeln!(out, "requires [ capability(\"{}\") ];", req.id);
78    }
79    if !program.requires.is_empty() {
80        out.push('\n');
81    }
82
83    // Items
84    for (i, item) in program.items.iter().enumerate() {
85        if i > 0 {
86            out.push('\n');
87        }
88        decompile_item(&mut out, item, 0, opts);
89    }
90
91    out
92}
93
94/// Decompile a single AST Item.
95pub fn decompile_item(out: &mut String, item: &Item, indent: usize, opts: &DecompileOptions) {
96    let pad = " ".repeat(indent * opts.indent_spaces);
97    match item {
98        Item::Const(cd) => {
99            let _ = write!(out, "{pad}const {}", cd.name);
100            if let Some(ty) = &cd.ty {
101                if opts.emit_types {
102                    let _ = write!(out, ": {}", decompile_type_expr(ty));
103                }
104            }
105            out.push_str(" = ");
106            decompile_expr(out, &cd.value);
107            out.push_str(";\n");
108        }
109        Item::Function(fd) => {
110            let effect_str = match fd.effect {
111                Some(EffectClass::Pure) => "pure ",
112                Some(EffectClass::Hot) => "hot ",
113                Some(EffectClass::Cold) => "cold ",
114                Some(EffectClass::Async) => "async ",
115                Some(EffectClass::External) => "effect ",
116                None => "",
117            };
118            let async_str = if fd.is_async && fd.effect != Some(EffectClass::Async) {
119                "async "
120            } else {
121                ""
122            };
123            let _ = write!(out, "{pad}{effect_str}{async_str}fn {}(", fd.name);
124            for (j, p) in fd.params.iter().enumerate() {
125                if j > 0 {
126                    out.push_str(", ");
127                }
128                out.push_str(&p.name);
129                if opts.emit_types {
130                    let _ = write!(out, ": {}", decompile_type_expr(&p.ty));
131                }
132            }
133            out.push(')');
134
135            if opts.emit_budgets && !fd.budget.is_empty() {
136                out.push_str(" budget(");
137                for (k, b) in fd.budget.iter().enumerate() {
138                    if k > 0 {
139                        out.push_str(", ");
140                    }
141                    let _ = write!(out, "{}: ", b.name);
142                    decompile_expr(out, &b.value);
143                }
144                out.push(')');
145            }
146
147            if let Some(ret) = &fd.ret {
148                if opts.emit_types {
149                    let _ = write!(out, " -> {}", decompile_type_expr(ret));
150                }
151            }
152
153            out.push(' ');
154            decompile_block(out, &fd.body, indent, opts);
155            out.push('\n');
156        }
157        Item::Hook(hd) => {
158            let _ = write!(out, "{pad}on {} (", hd.path.join("."));
159            for (j, p) in hd.params.iter().enumerate() {
160                if j > 0 {
161                    out.push_str(", ");
162                }
163                out.push_str(&p.name);
164                if opts.emit_types {
165                    let _ = write!(out, ": {}", decompile_type_expr(&p.ty));
166                }
167            }
168            out.push_str(") ");
169            decompile_block(out, &hd.body, indent, opts);
170            out.push('\n');
171        }
172        Item::Statement(stmt) => {
173            let _ = write!(out, "{pad}");
174            decompile_stmt(out, stmt, indent, opts);
175            out.push('\n');
176        }
177        Item::Enum(ed) => {
178            let _ = writeln!(out, "{pad}enum {} {{", ed.name);
179            for variant in &ed.variants {
180                let vpad = " ".repeat((indent + 1) * opts.indent_spaces);
181                if variant.payload.is_empty() {
182                    let _ = writeln!(out, "{vpad}{},", variant.name);
183                } else {
184                    let _ = write!(out, "{vpad}{}(", variant.name);
185                    for (k, p) in variant.payload.iter().enumerate() {
186                        if k > 0 {
187                            out.push_str(", ");
188                        }
189                        out.push_str(&decompile_type_expr(p));
190                    }
191                    out.push_str("),\n");
192                }
193            }
194            let _ = writeln!(out, "{pad}}}");
195        }
196        Item::Law(ld) => {
197            let _ = writeln!(out, "{pad}law {} {{", ld.name);
198            let bpad = " ".repeat((indent + 1) * opts.indent_spaces);
199            let _ = write!(out, "{bpad}when: ");
200            decompile_expr(out, &ld.condition);
201            let _ = write!(out, " => ");
202            decompile_expr(out, &ld.consequence);
203            let _ = writeln!(out, ";\n{pad}}}");
204        }
205        Item::Material(md) => {
206            let _ = writeln!(out, "{pad}material {} {{", md.name);
207            let _ = writeln!(out, "{pad}}}");
208        }
209        Item::Field(fld) => {
210            let _ = writeln!(
211                out,
212                "{pad}field {}: {} {{",
213                fld.name,
214                decompile_type_expr(&fld.ty)
215            );
216            let _ = writeln!(out, "{pad}}}");
217        }
218        Item::Cell(cd) => {
219            let effect_str = match cd.effect {
220                Some(EffectClass::Pure) => "pure ",
221                Some(EffectClass::Hot) => "hot ",
222                Some(EffectClass::Cold) => "cold ",
223                Some(EffectClass::Async) => "async ",
224                Some(EffectClass::External) => "effect ",
225                None => "",
226            };
227            let _ = write!(out, "{pad}{effect_str}cell {}", cd.name);
228            if !cd.params.is_empty() {
229                out.push('(');
230                for (j, p) in cd.params.iter().enumerate() {
231                    if j > 0 {
232                        out.push_str(", ");
233                    }
234                    out.push_str(&p.name);
235                    if opts.emit_types {
236                        let _ = write!(out, ": {}", decompile_type_expr(&p.ty));
237                    }
238                }
239                out.push(')');
240            }
241            if let Some(w) = &cd.when {
242                out.push_str(" when ");
243                decompile_expr(out, w);
244            }
245            out.push_str(" := ");
246            decompile_expr(out, &cd.expr);
247            out.push_str(";\n");
248        }
249        Item::Present(pd) => {
250            let _ = writeln!(out, "{pad}present {} {{", pd.name);
251            for prop in &pd.properties {
252                let _ = write!(out, "{pad}  {}: ", prop.name);
253                decompile_expr(out, &prop.value);
254                out.push('\n');
255            }
256            let _ = writeln!(out, "{pad}}}");
257        }
258        Item::Bind(b) => {
259            let _ = write!(out, "{pad}bind ");
260            decompile_expr(out, &b.left);
261            out.push_str(" <-> ");
262            decompile_expr(out, &b.right);
263            if let Some((lo, hi)) = &b.clamp {
264                out.push_str(" using Clamp[");
265                decompile_expr(out, lo);
266                out.push_str(", ");
267                decompile_expr(out, hi);
268                out.push(']');
269            }
270            out.push_str(" resolve ");
271            out.push_str(match b.resolve {
272                crate::ast::BindResolve::Latest => "latest",
273                crate::ast::BindResolve::Left => "left",
274                crate::ast::BindResolve::Right => "right",
275            });
276            out.push_str(";\n");
277        }
278    }
279}
280
281/// Decompile a statement block.
282pub fn decompile_block(out: &mut String, block: &Block, indent: usize, opts: &DecompileOptions) {
283    if block.stmts.is_empty() {
284        out.push_str("{}");
285        return;
286    }
287    out.push_str("{\n");
288    for stmt in &block.stmts {
289        let pad = " ".repeat((indent + 1) * opts.indent_spaces);
290        out.push_str(&pad);
291        decompile_stmt(out, stmt, indent + 1, opts);
292        out.push('\n');
293    }
294    let pad = " ".repeat(indent * opts.indent_spaces);
295    let _ = write!(out, "{pad}}}");
296}
297
298/// Decompile a single statement.
299pub fn decompile_stmt(out: &mut String, stmt: &Stmt, indent: usize, opts: &DecompileOptions) {
300    match stmt {
301        Stmt::Let {
302            mutable,
303            name,
304            ty,
305            value,
306            ..
307        } => {
308            if *mutable {
309                out.push_str("mut ");
310            } else {
311                out.push_str("let ");
312            }
313            out.push_str(name);
314            if let Some(t) = ty {
315                if opts.emit_types {
316                    let _ = write!(out, ": {}", decompile_type_expr(t));
317                }
318            }
319            if let Some(val) = value {
320                out.push_str(" = ");
321                decompile_expr(out, val);
322            }
323            out.push(';');
324        }
325        Stmt::LetPat {
326            mutable,
327            pattern,
328            ty,
329            value,
330            ..
331        } => {
332            if *mutable {
333                out.push_str("mut ");
334            } else {
335                out.push_str("let ");
336            }
337            decompile_pattern(out, pattern);
338            if let Some(t) = ty {
339                if opts.emit_types {
340                    let _ = write!(out, ": {}", decompile_type_expr(t));
341                }
342            }
343            out.push_str(" = ");
344            decompile_expr(out, value);
345            out.push(';');
346        }
347        Stmt::Assign { target, value, .. } => {
348            decompile_expr(out, target);
349            out.push_str(" = ");
350            decompile_expr(out, value);
351            out.push(';');
352        }
353        Stmt::If {
354            cond,
355            then_block,
356            else_block,
357            ..
358        } => {
359            out.push_str("if ");
360            decompile_expr(out, cond);
361            out.push(' ');
362            decompile_block(out, then_block, indent, opts);
363            if let Some(else_branch) = else_block {
364                out.push_str(" else ");
365                match else_branch.as_ref() {
366                    Stmt::If { .. } => {
367                        decompile_stmt(out, else_branch.as_ref(), indent, opts);
368                    }
369                    Stmt::Block(b) => {
370                        decompile_block(out, b, indent, opts);
371                    }
372                    other => {
373                        decompile_stmt(out, other, indent, opts);
374                    }
375                }
376            }
377        }
378        Stmt::For {
379            name, iter, body, ..
380        } => {
381            let _ = write!(out, "for {name} in ");
382            decompile_expr(out, iter);
383            out.push(' ');
384            decompile_block(out, body, indent, opts);
385        }
386        Stmt::While { cond, body, .. } => {
387            out.push_str("while ");
388            decompile_expr(out, cond);
389            out.push(' ');
390            decompile_block(out, body, indent, opts);
391        }
392        Stmt::Match {
393            scrutinee, arms, ..
394        } => {
395            out.push_str("match ");
396            decompile_expr(out, scrutinee);
397            out.push_str(" {\n");
398            let arm_pad = " ".repeat((indent + 1) * opts.indent_spaces);
399            for arm in arms {
400                out.push_str(&arm_pad);
401                decompile_pattern(out, &arm.pattern);
402                out.push_str(" => ");
403                match &arm.body {
404                    ArmBody::Expr(e) => {
405                        decompile_expr(out, e);
406                        out.push_str(",\n");
407                    }
408                    ArmBody::Block(b) => {
409                        decompile_block(out, b, indent + 1, opts);
410                        out.push('\n');
411                    }
412                }
413            }
414            let pad = " ".repeat(indent * opts.indent_spaces);
415            let _ = write!(out, "{pad}}}");
416        }
417        Stmt::Return { value, .. } => {
418            out.push_str("return");
419            if let Some(e) = value {
420                out.push(' ');
421                decompile_expr(out, e);
422            }
423            out.push(';');
424        }
425        Stmt::Yield { value, .. } => {
426            out.push_str("yield");
427            if let Some(e) = value {
428                out.push(' ');
429                decompile_expr(out, e);
430            }
431            out.push(';');
432        }
433        Stmt::Transaction { args, body, .. } => {
434            out.push_str("transaction (");
435            for (j, a) in args.iter().enumerate() {
436                if j > 0 {
437                    out.push_str(", ");
438                }
439                let _ = write!(out, "{}: ", a.name);
440                decompile_expr(out, &a.value);
441            }
442            out.push_str(") ");
443            decompile_block(out, body, indent, opts);
444        }
445        Stmt::Effect { expr, .. } => {
446            out.push_str("effect ");
447            decompile_expr(out, expr);
448            out.push(';');
449        }
450        Stmt::Expr { expr, .. } => {
451            // A statement that begins with `if` would be re-parsed as a
452            // statement-form conditional, so parenthesise it.
453            if starts_with_conditional(expr) {
454                out.push('(');
455                decompile_expr(out, expr);
456                out.push(')');
457            } else {
458                decompile_expr(out, expr);
459            }
460            out.push(';');
461        }
462        Stmt::Block(b) => {
463            decompile_block(out, b, indent, opts);
464        }
465    }
466}
467
468/// Postfix operators may not follow an unparenthesised conditional expression.
469fn decompile_postfix_recv(out: &mut String, recv: &Expr) {
470    if matches!(recv.kind, ExprKind::IfElse { .. }) {
471        out.push('(');
472        decompile_expr(out, recv);
473        out.push(')');
474    } else {
475        decompile_expr(out, recv);
476    }
477}
478
479/// True when the emitted text of `expr` would begin with the `if` keyword.
480fn starts_with_conditional(expr: &Expr) -> bool {
481    match &expr.kind {
482        ExprKind::IfElse { .. } => true,
483        ExprKind::Binary { left, .. } => starts_with_conditional(left),
484        ExprKind::Pipe { left, .. } => starts_with_conditional(left),
485        ExprKind::Tween { from, .. } => starts_with_conditional(from),
486        // Postfix receivers that are conditionals are parenthesised already.
487        ExprKind::Member { recv, .. }
488        | ExprKind::Index { recv, .. }
489        | ExprKind::Try(recv)
490        | ExprKind::Call { callee: recv, .. } => {
491            !matches!(recv.kind, ExprKind::IfElse { .. }) && starts_with_conditional(recv)
492        }
493        _ => false,
494    }
495}
496
497/// Decompile an expression.
498pub fn decompile_expr(out: &mut String, expr: &Expr) {
499    match &expr.kind {
500        ExprKind::Literal(lit) => match lit {
501            Literal::Null => out.push_str("null"),
502            Literal::Bool(b) => {
503                let _ = write!(out, "{b}");
504            }
505            Literal::Int(i) => {
506                let _ = write!(out, "{i}");
507            }
508            Literal::UInt(u) => {
509                let _ = write!(out, "{u}");
510            }
511            Literal::Float(bits) => {
512                let f = f64::from_bits(*bits);
513                let _ = write!(out, "{f}");
514            }
515            Literal::Quantity { value, unit } => {
516                let f = f64::from_bits(*value);
517                let _ = write!(out, "{f}{unit}");
518            }
519            Literal::String(s) => {
520                let _ = write!(out, "\"{}\"", s.replace('"', "\\\""));
521            }
522            Literal::Color(c) => {
523                let _ = write!(out, "#{:02x}{:02x}{:02x}", c.r, c.g, c.b);
524            }
525        },
526        ExprKind::Ident(id) => out.push_str(id),
527        ExprKind::QueryVar(qv) => {
528            let _ = write!(out, "?{qv}");
529        }
530        ExprKind::Iri(iri) => {
531            let _ = write!(out, "<{iri}>");
532        }
533        ExprKind::Prefixed(p, n) => {
534            let _ = write!(out, "{p}:{n}");
535        }
536        ExprKind::Blank(b) => {
537            let _ = write!(out, "_:{b}");
538        }
539        ExprKind::Unary { op, expr: inner } => {
540            let op_str = match op {
541                UnOp::Not => "!",
542                UnOp::Neg => "-",
543                UnOp::Plus => "+",
544            };
545            out.push_str(op_str);
546            decompile_expr(out, inner);
547        }
548        ExprKind::Binary { op, left, right } => {
549            decompile_expr(out, left);
550            let op_str = match op {
551                BinOp::Or => " || ",
552                BinOp::And => " && ",
553                BinOp::Eq => " == ",
554                BinOp::Ne => " != ",
555                BinOp::Lt => " < ",
556                BinOp::Le => " <= ",
557                BinOp::Gt => " > ",
558                BinOp::Ge => " >= ",
559                BinOp::Add => " + ",
560                BinOp::Sub => " - ",
561                BinOp::Mul => " * ",
562                BinOp::Div => " / ",
563                BinOp::Rem => " % ",
564            };
565            out.push_str(op_str);
566            decompile_expr(out, right);
567        }
568        ExprKind::Await(inner) => {
569            out.push_str("await ");
570            decompile_expr(out, inner);
571        }
572        ExprKind::Member { recv, name } => {
573            decompile_postfix_recv(out, recv);
574            let _ = write!(out, ".{name}");
575        }
576        ExprKind::Call { callee, args } => {
577            decompile_postfix_recv(out, callee);
578            out.push('(');
579            for (j, a) in args.iter().enumerate() {
580                if j > 0 {
581                    out.push_str(", ");
582                }
583                match a {
584                    Arg::Pos(e) => decompile_expr(out, e),
585                    Arg::Named(na) => {
586                        let _ = write!(out, "{}: ", na.name);
587                        decompile_expr(out, &na.value);
588                    }
589                }
590            }
591            out.push(')');
592        }
593        ExprKind::Index { recv, index } => {
594            decompile_postfix_recv(out, recv);
595            out.push('[');
596            decompile_expr(out, index);
597            out.push(']');
598        }
599        ExprKind::Try(inner) => {
600            decompile_postfix_recv(out, inner);
601            out.push('?');
602        }
603        ExprKind::IfElse {
604            cond,
605            then_value,
606            else_value,
607        } => {
608            out.push_str("if ");
609            if matches!(cond.kind, ExprKind::IfElse { .. } | ExprKind::Record(_)) {
610                out.push('(');
611                decompile_expr(out, cond);
612                out.push(')');
613            } else {
614                decompile_expr(out, cond);
615            }
616            out.push_str(" { ");
617            decompile_expr(out, then_value);
618            out.push_str(" } else ");
619            if matches!(else_value.kind, ExprKind::IfElse { .. }) {
620                decompile_expr(out, else_value);
621            } else {
622                out.push_str("{ ");
623                decompile_expr(out, else_value);
624                out.push_str(" }");
625            }
626        }
627        ExprKind::List(items) => {
628            out.push('[');
629            for (j, it) in items.iter().enumerate() {
630                if j > 0 {
631                    out.push_str(", ");
632                }
633                decompile_expr(out, it);
634            }
635            out.push(']');
636        }
637        ExprKind::Record(entries) => {
638            out.push_str("{ ");
639            for (j, entry) in entries.iter().enumerate() {
640                if j > 0 {
641                    out.push_str(", ");
642                }
643                let _ = write!(out, "{}: ", entry.name);
644                decompile_expr(out, &entry.value);
645            }
646            out.push_str(" }");
647        }
648        ExprKind::Triple {
649            subject,
650            predicate,
651            object,
652        } => {
653            out.push_str("<< ");
654            decompile_expr(out, subject);
655            out.push(' ');
656            decompile_expr(out, predicate);
657            out.push(' ');
658            decompile_expr(out, object);
659            out.push_str(" >>");
660        }
661        ExprKind::Reified {
662            subject,
663            predicate,
664            object,
665            reifier,
666        } => {
667            out.push_str("<< ");
668            decompile_expr(out, subject);
669            out.push(' ');
670            decompile_expr(out, predicate);
671            out.push(' ');
672            decompile_expr(out, object);
673            out.push_str(" ~ ");
674            decompile_expr(out, reifier);
675            out.push_str(" >>");
676        }
677        ExprKind::Pipe { left, right } => {
678            decompile_expr(out, left);
679            out.push_str(" |> ");
680            decompile_expr(out, right);
681        }
682        ExprKind::GraphQuery {
683            is_ask, pattern, ..
684        } => {
685            if *is_ask {
686                out.push_str("graph? { ");
687            } else {
688                out.push_str("graph { ");
689            }
690            out.push_str(pattern);
691            out.push_str(" }");
692        }
693        ExprKind::ModalLogic {
694            modality,
695            args,
696            body,
697        } => {
698            let name = match modality {
699                ModalKind::DeonticObligate => "obligate",
700                ModalKind::DeonticPermit => "permit",
701                ModalKind::DeonticForbid => "forbid",
702                ModalKind::EpistemicKnows => "knows",
703                ModalKind::EpistemicBelieves => "believes",
704                ModalKind::Paraconsistent => "paraconsistent",
705                ModalKind::LtlGlobally => "always",
706                ModalKind::LtlFinally => "eventually",
707                ModalKind::LtlUntil => "until",
708                ModalKind::DlSubsumes => "subsumes",
709                ModalKind::N3Defeasible => "defeasible_rule",
710            };
711            out.push_str(name);
712            if !args.is_empty() {
713                out.push('(');
714                for (i, a) in args.iter().enumerate() {
715                    if i > 0 {
716                        out.push_str(", ");
717                    }
718                    decompile_expr(out, a);
719                }
720                out.push(')');
721            }
722            if let Some(b) = body {
723                out.push_str(" { ");
724                decompile_expr(out, b);
725                out.push_str(" }");
726            }
727        }
728        ExprKind::Interpolate(parts) => {
729            out.push_str("f\"");
730            for p in parts {
731                if let ExprKind::Literal(Literal::String(s)) = &p.kind {
732                    out.push_str(s);
733                } else {
734                    out.push('{');
735                    decompile_expr(out, p);
736                    out.push('}');
737                }
738            }
739            out.push('"');
740        }
741        ExprKind::Lambda { params, body } => {
742            out.push('|');
743            for (i, p) in params.iter().enumerate() {
744                if i > 0 {
745                    out.push_str(", ");
746                }
747                out.push_str(p);
748            }
749            out.push_str("| ");
750            decompile_expr(out, body);
751        }
752        ExprKind::Tween {
753            from,
754            to,
755            over,
756            ease,
757            spring,
758        } => {
759            decompile_expr(out, from);
760            out.push_str(" ~ ");
761            decompile_expr(out, to);
762            out.push_str(" over ");
763            decompile_expr(out, over);
764            if let Some(e) = ease {
765                out.push_str(" ease ");
766                out.push_str(e);
767            }
768            if let Some(args) = spring {
769                out.push_str(" spring(");
770                for (i, a) in args.iter().enumerate() {
771                    if i > 0 {
772                        out.push_str(", ");
773                    }
774                    let _ = write!(out, "{}: ", a.name);
775                    decompile_expr(out, &a.value);
776                }
777                out.push(')');
778            }
779        }
780    }
781}
782
783/// Decompile a pattern.
784pub fn decompile_pattern(out: &mut String, pat: &Pattern) {
785    match pat {
786        Pattern::Wildcard => out.push('_'),
787        Pattern::Ident(id) => out.push_str(id),
788        Pattern::Literal(lit) => match lit {
789            Literal::Null => out.push_str("null"),
790            Literal::Bool(b) => {
791                let _ = write!(out, "{b}");
792            }
793            Literal::Int(i) => {
794                let _ = write!(out, "{i}");
795            }
796            Literal::UInt(u) => {
797                let _ = write!(out, "{u}");
798            }
799            Literal::Float(bits) => {
800                let f = f64::from_bits(*bits);
801                let _ = write!(out, "{f}");
802            }
803            Literal::Quantity { value, unit } => {
804                let f = f64::from_bits(*value);
805                let _ = write!(out, "{f}{unit}");
806            }
807            Literal::String(s) => {
808                let _ = write!(out, "\"{s}\"");
809            }
810            Literal::Color(c) => {
811                let _ = write!(out, "#{:02x}{:02x}{:02x}", c.r, c.g, c.b);
812            }
813        },
814        Pattern::Ok(inner) => {
815            out.push_str("Ok(");
816            decompile_pattern(out, inner);
817            out.push(')');
818        }
819        Pattern::Err(inner) => {
820            out.push_str("Err(");
821            decompile_pattern(out, inner);
822            out.push(')');
823        }
824        Pattern::Some(inner) => {
825            out.push_str("Some(");
826            decompile_pattern(out, inner);
827            out.push(')');
828        }
829        Pattern::None => out.push_str("None"),
830        Pattern::Record(fields) => {
831            out.push_str("{ ");
832            for (j, (k, p)) in fields.iter().enumerate() {
833                if j > 0 {
834                    out.push_str(", ");
835                }
836                if let Pattern::Ident(id) = p {
837                    if id == k {
838                        out.push_str(k);
839                        continue;
840                    }
841                }
842                out.push_str(k);
843                out.push_str(": ");
844                decompile_pattern(out, p);
845            }
846            out.push_str(" }");
847        }
848        Pattern::List(elements) => {
849            out.push('[');
850            for (j, p) in elements.iter().enumerate() {
851                if j > 0 {
852                    out.push_str(", ");
853                }
854                decompile_pattern(out, p);
855            }
856            out.push(']');
857        }
858        Pattern::Constructor { name, args } => {
859            out.push_str(name);
860            out.push('(');
861            for (j, p) in args.iter().enumerate() {
862                if j > 0 {
863                    out.push_str(", ");
864                }
865                decompile_pattern(out, p);
866            }
867            out.push(')');
868        }
869        Pattern::Variant {
870            enum_name,
871            variant_name,
872            args,
873        } => {
874            let _ = write!(out, "{enum_name}.{variant_name}");
875            if !args.is_empty() {
876                out.push('(');
877                for (j, a) in args.iter().enumerate() {
878                    if j > 0 {
879                        out.push_str(", ");
880                    }
881                    decompile_pattern(out, a);
882                }
883                out.push(')');
884            }
885        }
886    }
887}
888
889/// Decompile a type expression.
890pub fn decompile_type_expr(ty: &TypeExpr) -> String {
891    if ty.args.is_empty() {
892        ty.name.clone()
893    } else {
894        let mut s = ty.name.clone();
895        s.push('<');
896        for (j, a) in ty.args.iter().enumerate() {
897            if j > 0 {
898                s.push_str(", ");
899            }
900            s.push_str(&decompile_type_expr(a));
901        }
902        s.push('>');
903        s
904    }
905}
906
907/// Decompile a raw Bytecode Chunk into symbolic disassembly.
908pub fn decompile_chunk(chunk: &Chunk) -> String {
909    let mut out = String::with_capacity(1024);
910
911    // Constants Pool
912    writeln!(out, "; ── Constants (count: {}) ──", chunk.constants.len()).unwrap();
913    for (i, c) in chunk.constants.iter().enumerate() {
914        match c {
915            Const::String(s) => writeln!(out, "  [{i}] String(\"{s}\")").unwrap(),
916            Const::Iri(iri) => writeln!(out, "  [{i}] Iri(<{iri}>)").unwrap(),
917        }
918    }
919
920    // Function Metadata
921    if !chunk.functions.is_empty() {
922        writeln!(
923            out,
924            "\n; ── Functions (count: {}) ──",
925            chunk.functions.len()
926        )
927        .unwrap();
928        for (i, f) in chunk.functions.iter().enumerate() {
929            writeln!(
930                out,
931                "  [{i}] fn {} (params: {}, locals: {}, offset: {:#x}, budget: {})",
932                f.name, f.param_count, f.local_count, f.code_offset, f.budget_steps
933            )
934            .unwrap();
935        }
936    }
937
938    // Disassembled Bytecode
939    writeln!(out, "\n; ── Bytecode (size: {} bytes) ──", chunk.code.len()).unwrap();
940    let mut pc = 0;
941    while pc < chunk.code.len() {
942        let op_byte = chunk.code[pc];
943        let op = match Op::from_byte(op_byte) {
944            Some(o) => format!("{o:?}"),
945            None => format!("UNKNOWN({op_byte:#04x})"),
946        };
947        writeln!(out, "  {pc:#06x}: {op}").unwrap();
948        pc += 1;
949    }
950
951    out
952}
953
954#[cfg(test)]
955mod tests {
956    use super::*;
957    use crate::parse::parse_program;
958
959    #[test]
960    fn decompile_roundtrip_function() {
961        let src = "pure fn add(x: i64, y: i64) budget(steps: 100) -> i64 {\n    return x + y;\n}\n";
962        let prog = parse_program(src).expect("parse");
963        let decomp = decompile_program(&prog, &DecompileOptions::default());
964        assert!(decomp.contains("pure fn add(x: i64, y: i64)"));
965        assert!(decomp.contains("return x + y;"));
966    }
967
968    #[test]
969    fn decompile_roundtrip_const() {
970        let src = "const PI: f64 = 3.14159;\n";
971        let prog = parse_program(src).expect("parse");
972        let decomp = decompile_program(&prog, &DecompileOptions::default());
973        assert!(decomp.contains("const PI: f64 = 3.14159;"));
974    }
975}