inauguration 0.2.0

.in language and general compiler CLI (Core IR, hybrid SIL, staging, plugins)
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
//! Simple stack-based bytecode IR and emitter.
//!
//! Bytecode is a minimal intermediate representation that SIL can lower to,
//! enabling code generation without external compilers or complex backends.

use crate::core_ir::{FloatVal, ModuleIdentityReport};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CmpOp {
    Eq,
    Ne,
    Lt,
    Gt,
    Le,
    Ge,
}

/// Runtime value on the stack.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Value {
    Int(i64),
    Float(FloatVal),
    Bool(bool),
    String(String),
    Struct {
        name: String,
        fields: Vec<(String, Value)>,
    },
    Array(Vec<Value>),
    Nil,
}

impl Value {
    pub fn to_int(&self) -> i64 {
        match self {
            Value::Int(n) => *n,
            Value::Float(FloatVal(f)) => *f as i64,
            Value::Bool(b) => {
                if *b {
                    1
                } else {
                    0
                }
            }
            Value::String(_) => 0,
            Value::Struct { .. } => 0,
            Value::Array(_) => 0,
            Value::Nil => 0,
        }
    }

    pub fn to_bool(&self) -> bool {
        match self {
            Value::Int(n) => *n != 0,
            Value::Float(FloatVal(f)) => *f != 0.0,
            Value::Bool(b) => *b,
            Value::String(s) => !s.is_empty(),
            Value::Struct { .. } => true,
            Value::Array(values) => !values.is_empty(),
            Value::Nil => false,
        }
    }

    pub fn to_float(&self) -> f64 {
        match self {
            Value::Float(FloatVal(f)) => *f,
            Value::Int(n) => *n as f64,
            Value::Bool(b) => {
                if *b {
                    1.0
                } else {
                    0.0
                }
            }
            Value::String(_) => 0.0,
            Value::Struct { .. } => 0.0,
            Value::Array(_) => 0.0,
            Value::Nil => 0.0,
        }
    }

    pub fn to_string_display(&self) -> String {
        match self {
            Value::Int(n) => n.to_string(),
            Value::Float(FloatVal(f)) => f.to_string(),
            Value::Bool(b) => b.to_string(),
            Value::String(s) => s.clone(),
            Value::Struct { name, .. } => name.clone(),
            Value::Array(values) => format!("[{}]", values.len()),
            Value::Nil => "nil".to_string(),
        }
    }
}

/// Bytecode instructions (stack-based).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Instruction {
    /// Load integer constant onto stack
    LoadInt(i64),
    /// Load float constant onto stack
    LoadFloat(FloatVal),
    /// Load string constant onto stack
    LoadString(String),
    /// Load boolean constant onto stack
    LoadBool(bool),
    /// Load nil
    LoadNil,
    /// Call built-in function (name, arg count)
    CallBuiltin(String, usize),
    /// Call user-defined function (name, arg count)
    CallFunction(String, usize),
    /// Return from function
    Return,
    /// Binary operation: pop 2 values, apply op, push result
    BinOp(String),
    /// Float binary operations
    FAdd,
    FSub,
    FMul,
    FDiv,
    FCmp(CmpOp),
    /// Unary operation: pop 1 value, apply op, push result
    UnOp(String),
    StructInit(String, Vec<String>),
    FieldAccess(String),
    ArrayInit(usize),
    IndexAccess,
    IndexSet(usize),
    /// Jump to label
    Jump(String),
    /// Jump if top of stack is false (pop value)
    JumpIfFalse(String),
    /// Jump if top of stack is true (pop value)
    JumpIfTrue(String),
    /// Label (no-op, marks position)
    Label(String),
    /// Pop from stack
    Pop,
    /// Duplicate top of stack
    Dup,
    /// Store in local (slot index)
    Store(usize),
    /// Load from local (slot index)
    Load(usize),
    /// Enter try region (catch label name)
    TryEnter(String),
    /// Exit innermost try region
    TryEnd,
}

/// A function in bytecode form.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BytecodeFunction {
    pub name: String,
    pub instructions: Vec<Instruction>,
    pub local_count: usize,
}

/// A complete bytecode module.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BytecodeModule {
    pub functions: Vec<BytecodeFunction>,
    pub entry_point: String,
    pub identity: Option<ModuleIdentityReport>,
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub package_exports:
        std::collections::BTreeMap<String, crate::package_runtime::PackageExportRuntime>,
}

impl BytecodeModule {
    pub fn new(entry_point: String) -> Self {
        BytecodeModule {
            functions: Vec::new(),
            entry_point,
            identity: None,
            package_exports: std::collections::BTreeMap::new(),
        }
    }

    pub fn add_function(&mut self, func: BytecodeFunction) {
        self.functions.push(func);
    }

    pub fn find_function(&self, name: &str) -> Option<&BytecodeFunction> {
        self.functions.iter().find(|f| f.name == name)
    }
}

/// Emit textual bytecode assembly (.bca format).
pub fn module_to_text(module: &BytecodeModule) -> String {
    let mut out = String::new();
    out.push_str(&format!(
        "; Bytecode module (entry: {})\n",
        module.entry_point
    ));
    if let Some(identity) = &module.identity
        && let Ok(encoded) = serde_json::to_string(identity)
    {
        out.push_str(&format!("; module_identity: {encoded}\n"));
    }
    if !module.package_exports.is_empty()
        && let Ok(encoded) = serde_json::to_string(&module.package_exports)
    {
        out.push_str(&format!("; package_exports: {encoded}\n"));
    }
    out.push_str("; ---\n\n");

    for func in &module.functions {
        out.push_str(&format!("function @{}:\n", func.name));
        out.push_str(&format!("  locals: {}\n", func.local_count));
        for inst in &func.instructions {
            out.push_str(&format!("  {}\n", instruction_to_text(inst)));
        }
        out.push('\n');
    }

    out
}

fn instruction_to_text(inst: &Instruction) -> String {
    match inst {
        Instruction::LoadInt(n) => format!("load_int {}", n),
        Instruction::LoadFloat(f) => format!("load_float {}", f.0),
        Instruction::LoadString(s) => format!("load_string {:?}", s),
        Instruction::LoadBool(b) => format!("load_bool {}", b),
        Instruction::LoadNil => "load_nil".to_string(),
        Instruction::CallBuiltin(name, argc) => format!("call_builtin {} {}", name, argc),
        Instruction::CallFunction(name, argc) => format!("call {} {}", name, argc),
        Instruction::Return => "return".to_string(),
        Instruction::BinOp(op) => format!("binop {}", op),
        Instruction::FAdd => "fadd".to_string(),
        Instruction::FSub => "fsub".to_string(),
        Instruction::FMul => "fmul".to_string(),
        Instruction::FDiv => "fdiv".to_string(),
        Instruction::FCmp(op) => format!("fcmp {:?}", op),
        Instruction::UnOp(op) => format!("unop {}", op),
        Instruction::StructInit(name, fields) => {
            format!("struct_init {} {}", name, fields.join(","))
        }
        Instruction::FieldAccess(name) => format!("field {}", name),
        Instruction::ArrayInit(len) => format!("array_init {}", len),
        Instruction::IndexAccess => "index".to_string(),
        Instruction::IndexSet(slot) => format!("index_set {}", slot),
        Instruction::Jump(label) => format!("jmp {}", label),
        Instruction::JumpIfFalse(label) => format!("jmpf {}", label),
        Instruction::JumpIfTrue(label) => format!("jmpt {}", label),
        Instruction::Label(label) => format!("{}:", label),
        Instruction::Pop => "pop".to_string(),
        Instruction::Dup => "dup".to_string(),
        Instruction::Store(slot) => format!("store {}", slot),
        Instruction::Load(slot) => format!("load {}", slot),
        Instruction::TryEnter(label) => format!("try_enter {}", label),
        Instruction::TryEnd => "try_end".to_string(),
    }
}

/// Parse textual bytecode assembly (.bca) back to module.
pub fn text_to_module(text: &str) -> Result<BytecodeModule, String> {
    let mut functions = Vec::new();
    let mut current_func: Option<BytecodeFunction> = None;
    let mut entry_point = "main".to_string();
    let mut identity = None;
    let mut package_exports = std::collections::BTreeMap::new();

    for line in text.lines() {
        let trimmed = line.trim();

        // Skip comments and empty lines
        if trimmed.is_empty() || trimmed.starts_with(';') {
            if trimmed.starts_with("; entry:") {
                entry_point = trimmed
                    .strip_prefix("; entry:")
                    .unwrap_or("main")
                    .trim()
                    .to_string();
            } else if let Some(rest) = trimmed.strip_prefix("; Bytecode module (entry:") {
                entry_point = rest.trim_end_matches(')').trim().to_string();
            } else if let Some(rest) = trimmed.strip_prefix("; module_identity:") {
                identity = parse_module_identity_line(rest.trim());
            } else if let Some(rest) = trimmed.strip_prefix("; package_exports:")
                && let Ok(parsed) = serde_json::from_str::<
                    std::collections::BTreeMap<
                        String,
                        crate::package_runtime::PackageExportRuntime,
                    >,
                >(rest.trim())
            {
                package_exports = parsed;
            }
            continue;
        }

        // Function header
        if trimmed.starts_with("function @") {
            if let Some(func) = current_func {
                functions.push(func);
            }
            let name = trimmed
                .strip_prefix("function @")
                .unwrap_or("")
                .trim_end_matches(':')
                .to_string();
            current_func = Some(BytecodeFunction {
                name,
                instructions: Vec::new(),
                local_count: 0,
            });
            continue;
        }

        // Parse locals declaration
        if trimmed.starts_with("locals:") {
            if let Some(ref mut func) = current_func
                && let Ok(n) = trimmed
                    .strip_prefix("locals:")
                    .unwrap_or("0")
                    .trim()
                    .parse::<usize>()
            {
                func.local_count = n;
            }
            continue;
        }

        // Parse instruction
        if let Some(ref mut func) = current_func
            && let Ok(inst) = parse_instruction(trimmed)
        {
            func.instructions.push(inst);
        }
    }

    if let Some(func) = current_func {
        functions.push(func);
    }

    Ok(BytecodeModule {
        functions,
        entry_point,
        identity,
        package_exports,
    })
}

fn parse_module_identity_line(line: &str) -> Option<ModuleIdentityReport> {
    if let Ok(identity) = serde_json::from_str(line) {
        return Some(identity);
    }
    let mut requested = None;
    let mut effective = None;
    let mut package = None;
    let mut module = None;
    for part in line.split_whitespace() {
        if let Some(value) = part.strip_prefix("requested=") {
            requested = Some(value.to_string());
        } else if let Some(value) = part.strip_prefix("effective=") {
            effective = Some(value.to_string());
        } else if let Some(value) = part.strip_prefix("package=") {
            if value != "none" {
                package = Some(value.to_string());
            }
        } else if let Some(value) = part.strip_prefix("module=")
            && value != "none"
        {
            module = Some(value.to_string());
        }
    }
    Some(ModuleIdentityReport {
        package,
        module,
        requested_module_id: requested?,
        effective_module_id: effective?,
    })
}

fn parse_instruction(line: &str) -> Result<Instruction, String> {
    if let Some(raw) = line.strip_prefix("load_string").map(str::trim) {
        return Ok(Instruction::LoadString(parse_quoted_payload(raw)?));
    }

    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.is_empty() {
        return Err("empty instruction".to_string());
    }

    match parts[0] {
        "load_int" => {
            let n = parts
                .get(1)
                .and_then(|s| s.parse::<i64>().ok())
                .ok_or("parse error")?;
            Ok(Instruction::LoadInt(n))
        }
        "load_float" => {
            let f = parts
                .get(1)
                .and_then(|s| s.parse::<f64>().ok())
                .ok_or("parse error")?;
            Ok(Instruction::LoadFloat(FloatVal(f)))
        }
        "load_bool" => {
            let b = parts
                .get(1)
                .and_then(|s| s.parse::<bool>().ok())
                .ok_or("parse error")?;
            Ok(Instruction::LoadBool(b))
        }
        "load_nil" => Ok(Instruction::LoadNil),
        "call_builtin" => {
            let name = parts.get(1).ok_or("parse error")?.to_string();
            let argc = parts
                .get(2)
                .and_then(|s| s.parse::<usize>().ok())
                .ok_or("parse error")?;
            Ok(Instruction::CallBuiltin(name, argc))
        }
        "call" => {
            let name = parts.get(1).ok_or("parse error")?.to_string();
            let argc = parts
                .get(2)
                .and_then(|s| s.parse::<usize>().ok())
                .ok_or("parse error")?;
            Ok(Instruction::CallFunction(name, argc))
        }
        "return" => Ok(Instruction::Return),
        "fadd" => Ok(Instruction::FAdd),
        "fsub" => Ok(Instruction::FSub),
        "fmul" => Ok(Instruction::FMul),
        "fdiv" => Ok(Instruction::FDiv),
        "fcmp" => {
            let op_str = parts.get(1).ok_or("parse error")?;
            let op = match *op_str {
                "Eq" => CmpOp::Eq,
                "Ne" => CmpOp::Ne,
                "Lt" => CmpOp::Lt,
                "Gt" => CmpOp::Gt,
                "Le" => CmpOp::Le,
                "Ge" => CmpOp::Ge,
                _ => return Err(format!("unknown cmp op: {}", op_str)),
            };
            Ok(Instruction::FCmp(op))
        }
        "binop" => {
            let op = parts.get(1).ok_or("parse error")?.to_string();
            Ok(Instruction::BinOp(op))
        }
        "unop" => {
            let op = parts.get(1).ok_or("parse error")?.to_string();
            Ok(Instruction::UnOp(op))
        }
        "struct_init" => {
            let name = parts.get(1).ok_or("parse error")?.to_string();
            let fields = parts
                .get(2)
                .map(|raw| {
                    raw.split(',')
                        .filter(|field| !field.is_empty())
                        .map(str::to_string)
                        .collect()
                })
                .unwrap_or_default();
            Ok(Instruction::StructInit(name, fields))
        }
        "field" => {
            let name = parts.get(1).ok_or("parse error")?.to_string();
            Ok(Instruction::FieldAccess(name))
        }
        "array_init" => {
            let len = parts
                .get(1)
                .and_then(|s| s.parse::<usize>().ok())
                .ok_or("parse error")?;
            Ok(Instruction::ArrayInit(len))
        }
        "index" => Ok(Instruction::IndexAccess),
        "index_set" => {
            let slot = parts
                .get(1)
                .and_then(|s| s.parse::<usize>().ok())
                .ok_or("parse error")?;
            Ok(Instruction::IndexSet(slot))
        }
        "jmp" => {
            let label = parts.get(1).ok_or("parse error")?.to_string();
            Ok(Instruction::Jump(label))
        }
        "jmpf" => {
            let label = parts.get(1).ok_or("parse error")?.to_string();
            Ok(Instruction::JumpIfFalse(label))
        }
        "jmpt" => {
            let label = parts.get(1).ok_or("parse error")?.to_string();
            Ok(Instruction::JumpIfTrue(label))
        }
        "pop" => Ok(Instruction::Pop),
        "dup" => Ok(Instruction::Dup),
        "store" => {
            let slot = parts
                .get(1)
                .and_then(|s| s.parse::<usize>().ok())
                .ok_or("parse error")?;
            Ok(Instruction::Store(slot))
        }
        "load" => {
            let slot = parts
                .get(1)
                .and_then(|s| s.parse::<usize>().ok())
                .ok_or("parse error")?;
            Ok(Instruction::Load(slot))
        }
        "try_enter" => {
            let label = parts.get(1).ok_or("parse error")?.to_string();
            Ok(Instruction::TryEnter(label))
        }
        "try_end" => Ok(Instruction::TryEnd),
        s if s.ends_with(':') => {
            let label = s.trim_end_matches(':').to_string();
            Ok(Instruction::Label(label))
        }
        _ => Err(format!("unknown instruction: {}", parts[0])),
    }
}

fn parse_quoted_payload(raw: &str) -> Result<String, String> {
    let payload = raw.trim();
    if !payload.starts_with('"') || !payload.ends_with('"') || payload.len() < 2 {
        return Err("parse error".to_string());
    }
    let mut out = String::new();
    let mut chars = payload[1..payload.len() - 1].chars();
    while let Some(ch) = chars.next() {
        if ch != '\\' {
            out.push(ch);
            continue;
        }
        let escaped = chars.next().ok_or("parse error")?;
        match escaped {
            '"' => out.push('"'),
            '\\' => out.push('\\'),
            'n' => out.push('\n'),
            'r' => out.push('\r'),
            't' => out.push('\t'),
            other => {
                out.push('\\');
                out.push(other);
            }
        }
    }
    Ok(out)
}

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

    #[test]
    fn bytecode_value_conversions() {
        assert_eq!(Value::Int(5).to_int(), 5);
        assert_eq!(Value::Bool(true).to_int(), 1);
        assert!(Value::Bool(true).to_bool());
        assert!(!Value::Int(0).to_bool());
    }

    #[test]
    fn module_to_text_roundtrip() {
        let mut module = BytecodeModule::new("main".to_string());
        let func = BytecodeFunction {
            name: "main".to_string(),
            instructions: vec![
                Instruction::LoadInt(42),
                Instruction::CallBuiltin("print".to_string(), 1),
                Instruction::Return,
            ],
            local_count: 0,
        };
        module.add_function(func);

        let text = module_to_text(&module);
        assert!(text.contains("function @main"));
        assert!(text.contains("load_int 42"));
        assert!(text.contains("call_builtin print 1"));

        let parsed = text_to_module(&text).unwrap();
        assert_eq!(parsed.entry_point, "main");
    }

    #[test]
    fn module_identity_text_roundtrip_preserves_literal_none() {
        let mut module = BytecodeModule::new("main".to_string());
        module.identity = Some(ModuleIdentityReport {
            package: Some("none".to_string()),
            module: Some("none.main".to_string()),
            requested_module_id: "App".to_string(),
            effective_module_id: "none.main".to_string(),
        });

        let parsed = text_to_module(&module_to_text(&module)).unwrap();
        let identity = parsed.identity.expect("module identity");
        assert_eq!(identity.package.as_deref(), Some("none"));
        assert_eq!(identity.module.as_deref(), Some("none.main"));
        assert_eq!(identity.requested_module_id, "App");
        assert_eq!(identity.effective_module_id, "none.main");
    }

    #[test]
    fn parse_instruction_works() {
        let inst = parse_instruction("load_int 123").unwrap();
        assert_eq!(inst, Instruction::LoadInt(123));

        let inst = parse_instruction("call foo 2").unwrap();
        assert_eq!(inst, Instruction::CallFunction("foo".to_string(), 2));

        let inst = parse_instruction("struct_init Point x,y").unwrap();
        assert_eq!(
            inst,
            Instruction::StructInit("Point".to_string(), vec!["x".to_string(), "y".to_string()])
        );

        let inst = parse_instruction("field y").unwrap();
        assert_eq!(inst, Instruction::FieldAccess("y".to_string()));
    }
}