-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.rs
More file actions
712 lines (647 loc) · 31 KB
/
Copy pathcompiler.rs
File metadata and controls
712 lines (647 loc) · 31 KB
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
use crate::ir::{Ir, Params, PrimOp, Quoted};
use std::collections::BTreeMap;
use std::fmt;
/// The fpga-lisp target's hard limits, checked before any assembly is
/// emitted (docs/abi.md / isa-contract.my). Both are silent-corruption
/// risks if left unchecked: extra call args past MAX_ARGS are never even
/// evaluated (compile_generic_call only compiles args[..MAX_ARGS]), and an
/// out-of-range literal truncates into LOADI's 16-bit immediate.
const MAX_CALL_ARGS: usize = 8;
const MAX_LOADI_MAGNITUDE: i64 = 0xFFFF;
/// Errors caught before emission by validating the IR against fpga-lisp's
/// target limits -- see docs/abi.md and isa-contract.my.
#[derive(Debug, Clone)]
pub enum CompileError {
/// A call site passes more arguments than the target's fixed register
/// bank (R1..R3, R5..R9) can carry.
TooManyArguments { found: usize, max: usize },
/// An integer literal doesn't fit LOADI's 16-bit immediate (negatives
/// are emitted via `LOADI 0; SUB` of the same-magnitude positive).
IntegerOutOfRange { value: i64, max_magnitude: i64 },
/// Contract 2.2 buffers have no fpga-lisp descriptor/BRAM ABI yet.
UnsupportedNumericBuffer,
/// A symbol-table-aware emission would exceed the 16-bit LOADSYM field.
SymbolTableOverflow,
/// An IR variant that is semantically supported by CML but lacks an fpga-lisp emission path.
UnsupportedVariant(&'static str),
}
impl fmt::Display for CompileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CompileError::TooManyArguments { found, max } => write!(
f,
"Arity: call has {found} arguments, but the fpga-lisp target supports at most {max}"
),
CompileError::IntegerOutOfRange {
value,
max_magnitude,
} => write!(
f,
"NumericOverflow: integer literal {value} exceeds the fpga-lisp target's LOADI range (magnitude > {max_magnitude})"
),
CompileError::UnsupportedNumericBuffer => {
write!(f, "Unsupported: typed numeric buffer for FPGA target")
}
CompileError::SymbolTableOverflow => {
write!(
f,
"NumericOverflow: symbol table overflow (max {})",
MAX_LOADI_MAGNITUDE
)
}
CompileError::UnsupportedVariant(variant) => {
write!(f, "Unsupported: IR variant for FPGA target: {variant}")
}
}
}
}
impl std::error::Error for CompileError {}
fn validate_ir(ir: &Ir) -> Result<(), CompileError> {
match ir {
Ir::Int(n) => validate_int(*n),
Ir::Float(_) => Err(CompileError::UnsupportedVariant("Float")),
Ir::Rational(_, _) => Err(CompileError::UnsupportedVariant("Rational")),
Ir::String(_) => Err(CompileError::UnsupportedVariant("String")),
Ir::Buffer(_) => Err(CompileError::UnsupportedNumericBuffer),
Ir::Nil | Ir::True | Ir::Var(_) => Ok(()),
Ir::Builtin(_) => Err(CompileError::UnsupportedVariant("Builtin")),
Ir::Quote(q) => validate_quoted(q),
Ir::Lambda { body, .. } => validate_ir(body),
Ir::App { func, args } => {
if args.len() > MAX_CALL_ARGS {
return Err(CompileError::TooManyArguments {
found: args.len(),
max: MAX_CALL_ARGS,
});
}
validate_ir(func)?;
args.iter().try_for_each(validate_ir)
}
Ir::Cond { branches } => branches.iter().try_for_each(|(test, body)| {
validate_ir(test)?;
validate_ir(body)
}),
Ir::Let { bindings, body } => {
bindings
.iter()
.try_for_each(|(_, value)| validate_ir(value))?;
validate_ir(body)
}
Ir::Def { value, .. } => validate_ir(value),
Ir::Prim { args, .. } => args.iter().try_for_each(validate_ir),
Ir::TailSelfCall { .. } => Err(CompileError::UnsupportedVariant("TailSelfCall")),
}
}
fn validate_int(n: i64) -> Result<(), CompileError> {
if n.unsigned_abs() > MAX_LOADI_MAGNITUDE as u64 {
return Err(CompileError::IntegerOutOfRange {
value: n,
max_magnitude: MAX_LOADI_MAGNITUDE,
});
}
Ok(())
}
fn validate_quoted(q: &Quoted) -> Result<(), CompileError> {
match q {
Quoted::Int(n) => validate_int(*n),
Quoted::List(items) => items.iter().try_for_each(validate_quoted),
Quoted::DottedList(items, tail) => {
items.iter().try_for_each(validate_quoted)?;
validate_quoted(tail)
}
Quoted::Str(_) | Quoted::Sym { .. } | Quoted::Nil => Ok(()),
Quoted::Float(_) => Err(CompileError::UnsupportedVariant("Quoted::Float")),
Quoted::Rational(_, _) => Err(CompileError::UnsupportedVariant("Quoted::Rational")),
}
}
pub struct Compiler {
output: Vec<String>,
label_counter: usize,
used_lookup: bool,
used_equal: bool,
}
/// FPGA-ready assembly plus the per-program symbol table required to turn
/// `LOADSYM Rn NAME` into the ISA's numeric tagged-symbol immediate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompiledAssembly {
pub assembly: String,
pub symbols: Vec<(u16, String)>,
}
impl Compiler {
pub fn new() -> Self {
Compiler {
output: Vec::new(),
label_counter: 0,
used_lookup: false,
used_equal: false,
}
}
fn next_label(&mut self, prefix: &str) -> String {
self.label_counter += 1;
format!("{}_{}", prefix, self.label_counter)
}
// --- Register preservation helpers (see docs/abi.md) -------------
//
// No register allocator exists here; every compile_* function
// hardcodes its own scratch registers. These three helpers are the
// only mechanism this codebase has for protecting a value across a
// nested compile_* call that might clobber it as scratch.
fn push(&mut self, reg: &str) {
self.emit(&format!("CONS R11 {} R11", reg));
}
fn pop(&mut self, reg: &str) {
self.emit(&format!("CAR {} R11", reg));
self.emit("CDR R11 R11");
}
/// Runs `body`, having pushed `reg`'s current value onto R11 first and
/// popped it back after -- protects `reg` across any compile_* call
/// inside `body` that might use it as scratch (docs/abi.md's "one rule
/// that matters"), regardless of that call's own target_reg.
fn preserve_across(&mut self, reg: &str, body: impl FnOnce(&mut Self)) {
self.push(reg);
body(self);
self.pop(reg);
}
/// Emits a protected `CALL R14 <label>` for a subroutine (cml_lookup,
/// cml_equal) that itself returns via `RET R14` -- preserves the
/// *caller's* pending return address (already sitting in R14) across
/// the nested call, since `CALL` unconditionally overwrites R14 with
/// its own return address on real hardware (see docs/abi.md). Without
/// this, a subroutine call from inside a function body silently
/// destroys that function's own eventual `RET R14` target.
fn call_subroutine(&mut self, label: &str) {
self.preserve_across("R14", |c| {
let ret_label = c.next_label("call_ret");
c.emit(&format!("LOADI R14 {}", ret_label));
c.emit(&format!("CALL R14 {}", label));
c.emit(&format!("{}:", ret_label));
});
}
pub fn compile(&mut self, program: &[Ir]) -> Result<String, CompileError> {
program.iter().try_for_each(validate_ir)?;
// Initialize R4 (ENV) and R11 (Stack) to NIL at program start
self.emit("LOADI R13 0");
self.emit("LOADI R12 1");
self.emit("EQ R4 R12 R13"); // R4 = NIL
self.emit("MOV R11 R4"); // R11 = NIL
for ir in program {
self.compile_expr(ir, "R15");
}
self.emit("HALT");
if self.used_lookup {
self.emit_cml_lookup();
}
if self.used_equal {
self.emit_cml_equal();
}
Ok(self.output.join("\n"))
}
/// Compile and intern symbolic LOADSYM operands deterministically for one
/// program. The legacy `compile` API remains name-oriented for readable
/// diagnostics; this additive API is the direct CML -> fpga-lisp bridge.
pub fn compile_with_symbols(
&mut self,
program: &[Ir],
) -> Result<CompiledAssembly, CompileError> {
let named = self.compile(program)?;
let mut ids = BTreeMap::<String, u16>::new();
let mut next_id: u32 = 900;
let mut lines = Vec::new();
for line in named.lines() {
let mut parts = line.splitn(3, char::is_whitespace);
let opcode = parts.next().unwrap_or_default();
let register = parts.next();
let operand = parts.next();
if opcode == "LOADSYM" {
if let (Some(register), Some(operand)) = (register, operand) {
let id = if let Ok(existing) = operand.parse::<u16>() {
existing
} else {
let entry = ids.entry(operand.to_string()).or_insert_with(|| {
let assigned = u16::try_from(next_id).unwrap_or(u16::MAX);
next_id = next_id.saturating_add(1);
assigned
});
if next_id > u32::from(u16::MAX) + 1 {
return Err(CompileError::SymbolTableOverflow);
}
*entry
};
lines.push(format!("LOADSYM {register} {id}"));
continue;
}
}
lines.push(line.to_string());
}
let symbols = ids.into_iter().map(|(name, id)| (id, name)).collect();
Ok(CompiledAssembly {
assembly: lines.join("\n"),
symbols,
})
}
fn compile_expr(&mut self, ir: &Ir, target_reg: &str) {
match ir {
Ir::Int(n) => {
self.emit_integer_literal(*n, target_reg);
}
Ir::Float(_) => unreachable!("Float rejected by validate_ir"),
Ir::Rational(_, _) => unreachable!("Rational rejected by validate_ir"),
Ir::String(_) => unreachable!("String rejected by validate_ir"),
Ir::Buffer(_) => unreachable!("Buffer rejected by validate_ir"),
Ir::Nil => {
self.emit("LOADI R13 0");
self.emit("LOADI R12 1");
self.emit(&format!("EQ {} R12 R13", target_reg));
}
Ir::True => {
self.emit(&format!("LOADI {} 0", target_reg));
self.emit(&format!("ATOM {} {}", target_reg, target_reg));
}
Ir::Var(s) => {
self.used_lookup = true;
self.emit(&format!("; LOOKUP {}", s));
self.emit(&format!("LOADSYM R12 {}", s));
self.emit("MOV R13 R4");
self.call_subroutine("cml_lookup");
self.emit(&format!("MOV {} R15", target_reg));
}
Ir::Builtin(_) => unreachable!("Builtin rejected by validate_ir"),
Ir::Quote(q) => self.compile_quoted(q, target_reg),
Ir::Lambda { params, body } => self.compile_lambda(params, body, target_reg),
Ir::App { func, args } => self.compile_generic_call(func, args, target_reg),
Ir::Cond { branches } => self.compile_cond(branches, target_reg),
Ir::Let { bindings, body } => self.compile_let(bindings, body, target_reg),
Ir::Def { name, value } => self.compile_def(name, value, target_reg),
Ir::Prim { op, args } => self.compile_prim(*op, args, target_reg),
Ir::TailSelfCall { .. } => unreachable!("TailSelfCall rejected by validate_ir"),
}
}
fn compile_prim(&mut self, op: PrimOp, args: &[Ir], target_reg: &str) {
match op {
PrimOp::Cons => {
// args[1] may itself be a two-arg primitive call, which
// also hardcodes R1 as scratch -- preserve R1 across
// evaluating args[1] so it can't clobber the
// already-computed first operand (docs/abi.md).
self.compile_expr(&args[0], "R1");
self.preserve_across("R1", |c| c.compile_expr(&args[1], "R2"));
self.emit(&format!("CONS {} R1 R2", target_reg));
}
PrimOp::Car => {
self.compile_expr(&args[0], "R1");
self.emit(&format!("CAR {} R1", target_reg));
}
PrimOp::Cdr => {
self.compile_expr(&args[0], "R1");
self.emit(&format!("CDR {} R1", target_reg));
}
PrimOp::Eq => {
self.compile_expr(&args[0], "R1");
self.preserve_across("R1", |c| c.compile_expr(&args[1], "R2"));
self.emit(&format!("EQ {} R1 R2", target_reg));
}
PrimOp::Atom => {
self.compile_expr(&args[0], "R1");
self.emit(&format!("ATOM {} R1", target_reg));
}
PrimOp::EqualP => {
self.compile_expr(&args[0], "R1");
self.preserve_across("R1", |c| c.compile_expr(&args[1], "R2"));
self.used_equal = true;
// cml_equal returns via RET R14 like cml_lookup, so it
// needs the same call_subroutine protection -- this used
// to be a bare `CALL R14 cml_equal` with no R14 save,
// silently destroying whatever function this equal? call
// was nested inside's own eventual `RET R14` target.
self.call_subroutine("cml_equal");
self.emit(&format!("MOV {} R15", target_reg));
}
PrimOp::Add => {
self.compile_expr(&args[0], "R1");
self.preserve_across("R1", |c| c.compile_expr(&args[1], "R2"));
self.emit(&format!("ADD {} R1 R2", target_reg));
}
PrimOp::Sub => {
self.compile_expr(&args[0], "R1");
self.preserve_across("R1", |c| c.compile_expr(&args[1], "R2"));
self.emit(&format!("SUB {} R1 R2", target_reg));
}
}
}
fn compile_generic_call(&mut self, func: &Ir, args: &[Ir], target_reg: &str) {
self.emit("; CALL START");
// 1. Evaluate arguments (support up to 8 args mapped to R1..R3, R5..R9)
let arg_regs = ["R1", "R2", "R3", "R5", "R6", "R7", "R8", "R9"];
let bound_arg_count = args.len().min(arg_regs.len());
// Push each argument onto the R11 stack immediately after computing
// it, before compiling the next one. A primitive call used as an
// argument expression (+, cdr, eq, cons, equal?, ...) always
// hardcodes R1/R2/R3 as scratch, regardless of its own target_reg --
// so without this, evaluating argument i+1 could silently clobber
// argument i's already-computed value still sitting in arg_regs[i]
// (e.g. `(f (cdr values) (+ acc 1))`: `(+ acc 1)` clobbers R1, which
// `(cdr values)` had just written its result into).
// Пушимо кожен аргумент на стек R11 одразу після обчислення, до
// компіляції наступного -- інакше примітив-аргумент (напр. `+`)
// тихо затирає R1..R3 попереднього вже обчисленого аргументу.
for (i, arg) in args.iter().enumerate() {
if i < arg_regs.len() {
self.compile_expr(arg, arg_regs[i]);
self.push(arg_regs[i]);
}
}
// 2. Evaluate the closure expression (into R15) while every computed
// argument sits safely on the stack -- this also protects them from
// cml_lookup's own R0/R1/R2 scratch use when func_expr is a symbol.
self.compile_expr(func, "R15");
// 3. Pop the arguments back off, in reverse push order.
for reg in arg_regs.iter().take(bound_arg_count).rev() {
self.pop(reg);
}
// R0 carries the complete evaluated argument list. Fixed-arity
// lambdas keep using the fast argument registers; dotted and bare
// parameter lists take their rest value from this structural form.
// R0 несе повний список аргументів для variadic lambda.
// R0 traegt die vollstaendige Argumentliste fuer variadische Lambdas.
self.emit("LOADI R13 0");
self.emit("LOADI R12 1");
self.emit("EQ R0 R12 R13"); // R0 = NIL
for reg in arg_regs.iter().take(args.len()).rev() {
self.emit(&format!("CONS R0 {} R0", reg));
}
// Save ENV (R4) and Link Register (R14), jump into the closure body
// (RET, not CALL: the target is a runtime label pointer in a
// register, and RET's hardware form doesn't auto-link R14 the way
// CALL does -- see docs/abi.md), then restore both on return.
self.push("R4");
self.push("R14");
// Closure is (LABEL_PTR . CAPTURED_ENV)
let ret_label = self.next_label("call_ret");
self.emit("CAR R10 R15"); // Extract LABEL_PTR to R10
self.emit("CDR R4 R15"); // Extract CAPTURED_ENV to R4 (current ENV register)
self.emit(&format!("LOADI R14 {}", ret_label)); // Return address
self.emit("RET R10"); // Indirect jump to lambda body
self.emit(&format!("{}:", ret_label));
self.pop("R14");
self.pop("R4");
self.emit(&format!("MOV {} R15", target_reg)); // Lambda returns in R15 by convention
self.emit("; CALL END");
}
// (def name value) binds `name` in the current environment (R4) via the
// fpga-lisp letrec pattern proven in M28/M29: extend R4 with a
// placeholder pair (name . NIL) *before* compiling `value`, so a lambda
// captures the extended frame and can look itself up by name; then
// SETCDR-backpatch the placeholder's cdr to the compiled value. This is
// the only mutation permitted after CONS allocates a cell (see fpga-lisp
// M26). Only self-recursion is supported this way -- two mutually
// recursive defs where the first calls the second before the second is
// defined would need two-pass forward declaration, not implemented.
// (def name value) прив'язує `name` у поточному середовищі (R4) через
// letrec-патерн fpga-lisp (M28/M29): розширюємо R4 placeholder-парою
// ДО компіляції value, потім SETCDR-бекпатчимо її cdr на скомпільоване
// значення.
fn compile_def(&mut self, name: &str, value: &Ir, target_reg: &str) {
self.emit("; DEF START");
self.emit("LOADI R13 0");
self.emit("LOADI R12 1");
self.emit("EQ R9 R12 R13"); // R9 = NIL
self.emit(&format!("LOADSYM R12 {}", name));
self.emit("CONS R13 R12 R9"); // R13 = ph_pair = (NAME . NIL)
self.emit("CONS R4 R13 R4"); // env = (ph_pair . env) -- captured by `value` if it's a lambda
self.emit("CONS R11 R13 R11"); // save ph_pair pointer across compiling `value`
self.compile_expr(value, target_reg);
self.emit("CAR R13 R11"); // restore ph_pair pointer
self.emit("CDR R11 R11");
self.emit(&format!("SETCDR R12 R13 {}", target_reg)); // backpatch: ph_pair.cdr = value
self.emit("; DEF END");
}
// `let` is a derived Lisp form, not an FPGA primitive. Lower
// (let ((name value) ...) body) to ((lambda (name ...) body) value ...).
// `let` — похідна форма Lisp, а не примітив FPGA.
// `let` ist eine abgeleitete Lisp-Form, keine FPGA-Primitive.
fn compile_let(&mut self, bindings: &[(String, Ir)], body: &Ir, target_reg: &str) {
let params = Params::Fixed(bindings.iter().map(|(name, _)| name.clone()).collect());
let values: Vec<Ir> = bindings.iter().map(|(_, value)| value.clone()).collect();
let lambda = Ir::Lambda {
params,
body: Box::new(body.clone()),
};
self.compile_generic_call(&lambda, &values, target_reg);
}
fn compile_quoted(&mut self, q: &Quoted, target_reg: &str) {
match q {
Quoted::Int(n) => self.emit_integer_literal(*n, target_reg),
Quoted::Str(s) => self.emit(&format!("LOADSYM {} {}", target_reg, s)),
// fpga-lisp keys its symbol/label table on the uppercased form,
// exactly as before cml#13 -- unaffected by that fix, which is
// scoped to backends that need my-lisp's own exact spelling.
Quoted::Sym { uppercased, .. } => {
self.emit(&format!("LOADSYM {} {}", target_reg, uppercased))
}
Quoted::Nil => {
self.emit("LOADI R13 0");
self.emit("LOADI R12 1");
self.emit(&format!("EQ {} R12 R13", target_reg));
}
Quoted::List(list) => {
self.emit("LOADI R13 0");
self.emit("LOADI R12 1");
self.emit(&format!("EQ {} R12 R13", target_reg));
for item in list.iter().rev() {
self.emit(&format!("CONS R11 {} R11", target_reg)); // Push accumulated list tail
self.compile_quoted(item, target_reg); // Evaluate item into target_reg
self.emit("CAR R12 R11"); // Pop list tail into R12
self.emit("CDR R11 R11");
self.emit(&format!("CONS {} {} R12", target_reg, target_reg)); // target_reg = cons(item, tail)
}
}
Quoted::DottedList(list, tail) => {
self.compile_quoted(tail, target_reg);
for item in list.iter().rev() {
self.emit(&format!("CONS R11 {} R11", target_reg)); // Push accumulated list tail
self.compile_quoted(item, target_reg); // Evaluate item into target_reg
self.emit("CAR R12 R11"); // Pop list tail into R12
self.emit("CDR R11 R11");
self.emit(&format!("CONS {} {} R12", target_reg, target_reg)); // target_reg = cons(item, tail)
}
}
Quoted::Float(_) => unreachable!("Quoted::Float rejected by validate_quoted"),
Quoted::Rational(_, _) => unreachable!("Quoted::Rational rejected by validate_quoted"),
}
}
fn compile_cond(&mut self, branches: &[(Ir, Ir)], target_reg: &str) {
let end_label = self.next_label("cond_end");
for (test, body) in branches {
let next_label = self.next_label("cond_next");
self.compile_expr(test, "R1");
// fpga-lisp's JF treats 0 as falsy, but my-lisp requires 0 to be truthy.
// We generate a strict NIL check by creating NIL and comparing against it twice.
// R9 is scratch here, not R4: R4 is the ENV register, and this NIL-check
// runs unconditionally for every branch (even ones not taken), so clobbering
// R4 here destroyed the environment before a taken branch's body could look
// up any variable or recursive call in it -- the actual cause of self-recursive
// `def` failing with RESULT_ERROR:Type (env lookups saw an empty/NIL env).
self.emit("LOADI R2 0");
self.emit("LOADI R3 1");
self.emit("EQ R9 R2 R3"); // R9 = NIL
self.emit("EQ R2 R1 R9"); // R2 = TRUE if R1 was NIL, else NIL
self.emit("EQ R3 R2 R9"); // R3 = TRUE if R1 was NOT NIL, else NIL
self.emit(&format!("JF R3 {}", next_label));
self.compile_expr(body, target_reg);
self.emit(&format!("JMP {}", end_label));
self.emit(&format!("{}:", next_label));
}
self.emit(&format!("{}:", end_label));
}
fn compile_lambda(&mut self, params: &Params, body: &Ir, target_reg: &str) {
let lambda_label = self.next_label("lambda_body");
let skip_label = self.next_label("lambda_skip");
self.emit("; LAMBDA START");
self.emit(&format!("LOADI R15 {}", lambda_label));
self.emit(&format!("CONS {} R15 R4", target_reg)); // Closure = (LABEL_PTR . ENV)
self.emit(&format!("JMP {}", skip_label));
self.emit(&format!("{}:", lambda_label));
// Lambda Body
// We must bind parameters (up to 3 mapped from R1, R2, R3)
// We bind parameters mapped from R1..R3, R5..R9
let arg_regs = ["R1", "R2", "R3", "R5", "R6", "R7", "R8", "R9"];
match params {
Params::Fixed(names) => {
for (i, name) in names.iter().enumerate() {
if i < arg_regs.len() {
self.emit(&format!("LOADSYM R12 {}", name));
self.emit(&format!("CONS R13 R12 {}", arg_regs[i])); // (param_sym . arg_val)
self.emit("CONS R4 R13 R4"); // env = (pair . env)
}
}
}
Params::Variadic { fixed, rest } => {
// Normal params
for (i, name) in fixed.iter().enumerate() {
if i < arg_regs.len() {
self.emit(&format!("LOADSYM R12 {}", name));
self.emit(&format!("CONS R13 R12 {}", arg_regs[i])); // (param_sym . arg_val)
self.emit("CONS R4 R13 R4"); // env = (pair . env)
}
}
// Variable arity tail: bind rest of args into a list
self.emit("MOV R10 R0");
for _ in 0..fixed.len() {
self.emit("CDR R10 R10");
}
self.emit(&format!("LOADSYM R12 {}", rest));
self.emit("CONS R13 R12 R10"); // (param_sym . rest_args_list)
self.emit("CONS R4 R13 R4"); // env = (pair . env)
}
Params::AllRest(rest) => {
self.emit(&format!("LOADSYM R12 {}", rest));
self.emit("CONS R13 R12 R0");
self.emit("CONS R4 R13 R4");
}
}
self.compile_expr(body, "R15"); // Return value in R15
// Note: Caller saved return address in R14
self.emit("RET R14");
self.emit(&format!("{}:", skip_label));
self.emit("; LAMBDA END");
}
fn emit_cml_lookup(&mut self) {
self.emit("");
self.emit("cml_lookup:");
self.emit("; input: R12 = target symbol ID");
self.emit("; input: R13 = environment list");
self.emit("; output: R15 = value");
self.emit("CAR R0 R13");
self.emit("CAR R1 R0");
self.emit("EQ R2 R1 R12");
self.emit("JF R2 cml_lookup_next");
self.emit("CDR R15 R0");
self.emit("RET R14");
self.emit("cml_lookup_next:");
self.emit("CDR R13 R13");
self.emit("JMP cml_lookup");
}
// Structural equality without letrec/recursion: an explicit worklist of
// (a . b) pairs pushed onto the shared stack register R11, drained
// iteratively. Type mismatches stop pushing new work but keep draining
// so R11 always returns balanced to its caller.
// Структурна рівність без letrec/рекурсії: явний worklist пар (a . b)
// на спільному регістрі-стеку R11.
// Strukturelle Gleichheit ohne letrec/Rekursion: explizite Arbeitsliste
// von (a . b)-Paaren auf dem gemeinsamen Stapelregister R11.
fn emit_cml_equal(&mut self) {
self.emit("");
self.emit("cml_equal:");
self.emit("; input: R1 = a, R2 = b");
self.emit("; output: R15 = TRUE/NIL");
self.emit("CONS R12 R1 R2");
self.emit("CONS R11 R12 R11"); // push initial (a . b)
self.emit("LOADI R15 0");
self.emit("ATOM R15 R15"); // R15 = TRUE (running result)
self.emit("cml_equal_loop:");
self.emit("LOADI R9 0");
self.emit("LOADI R8 1");
self.emit("EQ R7 R8 R9"); // R7 = NIL
self.emit("EQ R6 R11 R7"); // R6 = TRUE if worklist empty
self.emit("JF R6 cml_equal_pop");
self.emit("JMP cml_equal_done");
self.emit("cml_equal_pop:");
self.emit("CAR R12 R11"); // top pair
self.emit("CDR R11 R11"); // pop
self.emit("CAR R1 R12");
self.emit("CDR R2 R12");
self.emit("ATOM R5 R1");
self.emit("ATOM R6 R2");
self.emit("JF R5 cml_equal_a_not_atom");
self.emit("JF R6 cml_equal_mismatch"); // a atom, b cons
self.emit("EQ R7 R1 R2");
self.emit("JF R7 cml_equal_setfail");
self.emit("JMP cml_equal_loop");
self.emit("cml_equal_a_not_atom:");
self.emit("JF R6 cml_equal_both_cons"); // a cons, b atom -> mismatch below
self.emit("JMP cml_equal_mismatch");
self.emit("cml_equal_both_cons:");
self.emit("CAR R7 R1");
self.emit("CAR R8 R2");
self.emit("CONS R9 R7 R8");
self.emit("CONS R11 R9 R11"); // push (car a . car b)
self.emit("CDR R7 R1");
self.emit("CDR R8 R2");
self.emit("CONS R9 R7 R8");
self.emit("CONS R11 R9 R11"); // push (cdr a . cdr b)
self.emit("JMP cml_equal_loop");
self.emit("cml_equal_mismatch:");
self.emit("cml_equal_setfail:");
self.emit("LOADI R13 0");
self.emit("LOADI R12 1");
self.emit("EQ R15 R12 R13"); // R15 = NIL, keep draining
self.emit("JMP cml_equal_loop");
self.emit("cml_equal_done:");
self.emit("RET R14");
}
// fpga-lisp's assembler encodes LOADI's immediate as a bare 16-bit
// field (`imm & 0xFFFF`), with no sign extension into the fixnum
// value's wider field -- `LOADI R2 -1` loads 0xFFFF (65535), not the
// register-width two's-complement -1. Negative literals must instead
// be built with a real ALU op (SUB is register-register, no immediate
// truncation) so the tagged word downstream ops see is the hardware's
// actual negative representation. R13 is this codebase's established
// disposable scratch register (see the NIL/TRUE-construction idiom
// used throughout).
// Асемблер fpga-lisp кодує LOADI-immediate як голе 16-бітне поле, без
// sign extension -- `LOADI R2 -1` завантажує 0xFFFF, не справжнє
// two's-complement -1. Від'ємні літерали будуємо через SUB (rr-опція,
// без обрізання immediate).
fn emit_integer_literal(&mut self, n: i64, target_reg: &str) {
if n >= 0 {
self.emit(&format!("LOADI {} {}", target_reg, n));
} else {
self.emit(&format!("LOADI {} 0", target_reg));
self.emit(&format!("LOADI R13 {}", -n));
self.emit(&format!("SUB {} {} R13", target_reg, target_reg));
}
}
fn emit(&mut self, instr: &str) {
self.output.push(instr.to_string());
}
}