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
//! # chipi
//!
//! Generate instruction decoders and disassemblers from `.chipi` files.
//!
//! Write your CPU instruction encoding in a simple DSL, and chipi generates
//! the Rust decoder and formatting code for you.
//!
//! ## Usage
//!
//! Add to `Cargo.toml`:
//!
//! ```toml
//! [build-dependencies]
//! chipi = "0.5.3"
//! ```
//!
//! Create `build.rs`:
//!
//! ```ignore
//! use std::env;
//! use std::path::PathBuf;
//!
//! fn main() {
//! let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
//! chipi::generate("cpu.chipi", out_dir.join("cpu.rs").to_str().unwrap())
//! .expect("failed to generate decoder");
//! println!("cargo:rerun-if-changed=cpu.chipi");
//! }
//! ```
//!
//! Use the generated decoder:
//!
//! ```ignore
//! mod cpu {
//! include!(concat!(env!("OUT_DIR"), "/cpu.rs"));
//! }
//!
//! // decode() always takes &[u8] and returns (instruction, bytes_consumed)
//! match cpu::CpuInstruction::decode(&data[offset..]) {
//! Some((instr, bytes)) => {
//! println!("{}", instr);
//! offset += bytes;
//! }
//! None => println!("invalid instruction"),
//! }
//! ```
//!
//! ## Example .chipi file
//!
//! ```text
//! decoder Cpu {
//! width = 32
//! bit_order = msb0
//! endian = big
//! }
//!
//! type simm16 = i32 { sign_extend(16) }
//! type simm24 = i32 { sign_extend(24), shift_left(2) }
//!
//! bx [0:5]=010010 li:simm24[6:29] aa:bool[30] lk:bool[31]
//! | "b{lk ? l}{aa ? a} {li:#x}"
//!
//! addi [0:5]=001110 rd:u8[6:10] ra:u8[11:15] simm:simm16[16:31]
//! | ra == 0: "li {rd}, {simm}"
//! | "addi {rd}, {ra}, {simm}"
//! ```
//!
//! ## Syntax
//!
//! ### Decoder block
//!
//! ```text
//! decoder Name {
//! width = 32 # 8, 16, or 32 bits
//! bit_order = msb0 # msb0 or lsb0
//! endian = big # big or little (default: big)
//! max_units = 4 # optional: safety guard (validates bit ranges)
//! }
//! ```
//!
//! #### Variable-Length Instructions
//!
//! chipi automatically generates variable-length decoders when you use bit positions
//! beyond `width-1`. Simply reference subsequent units in your bit ranges:
//!
//! ```text
//! decoder Dsp {
//! width = 16
//! bit_order = msb0
//! endian = big
//! max_units = 2 # Optional safety check: ensures bits don't exceed 32 (width * max_units)
//! }
//!
//! nop [0:15]=0000000000000000 # 1 unit (16 bits)
//! lri [0:10]=00000010000 rd:u5[11:15] imm:u16[16:31] # 2 units (32 bits)
//! ```
//!
//! The generated `decode` always has the signature:
//! `pub fn decode(data: &[u8]) -> Option<(Self, usize)>`
//!
//! It accepts raw bytes and returns the decoded instruction along with the
//! number of bytes consumed.
//!
//! ### Instructions
//!
//! Each instruction is one line with a name, fixed bit patterns, and fields:
//!
//! ```text
//! add [0:5]=011111 rd:u8[6:10] ra:u8[11:15]
//! ```
//!
//! Fixed bits use `[range]=pattern`. Fields use `name:type[range]`.
//!
//! #### Wildcard Bits
//!
//! Use `?` in bit patterns for bits that can be any value:
//!
//! ```text
//! # Match when bits [15:8] are 0x8c, bits [7:0] can be anything
//! clr15 [15:0]=10001100????????
//! | "CLR15"
//!
//! # Mix wildcards with specific bits
//! nop [7:4]=0000 [3:0]=????
//! | "nop"
//! ```
//!
//! Wildcard bits are excluded from the matching mask, so instructions match
//! regardless of the values in those positions. This is useful for reserved or
//! architecturally undefined bits.
//!
//! #### Overlapping Patterns
//!
//! chipi supports overlapping instruction patterns where one pattern is a subset of another.
//! More specific patterns (with more fixed bits) are checked first:
//!
//! ```text
//! # Generic instruction - matches 0x1X (any value in bits 4-7)
//! load [0:3]=0001 reg:u4[4:7]
//! | "load r{reg}"
//!
//! # Specific instruction - matches only 0x1F
//! load_max [0:3]=0001 [4:7]=1111
//! | "load rmax"
//! ```
//!
//! The decoder will check `load_max` first (all bits fixed), then fall back to `load`
//! (bits 4-7 are wildcards). This works across all units in variable-length decoders.
//!
//! ### Types
//!
//! Builtin types:
//! * `bool` (converts bit to true/false)
//! * `u1` to `u7` (maps to u8)
//! * `u8`, `u16`, `u32`
//! * `i8`, `i16`, `i32`
//!
//! Custom types:
//!
//! ```text
//! type simm = i32 { sign_extend(16) }
//! type reg = u8 as Register
//! ```
//!
//! Available transformations:
//! * `sign_extend(n)` - sign extend from n bits
//! * `zero_extend(n)` - zero extend from n bits
//! * `shift_left(n)` - shift left by n bits
//!
//! Display format hints (controls how the field is printed in format strings):
//! * `display(signed_hex)` - signed hex: `0x1A`, `-0x1A`, `0`
//! * `display(hex)` - unsigned hex: `0x1A`, `0`
//!
//! ### Imports
//!
//! Import Rust types to wrap extracted values:
//!
//! ```text
//! import crate::cpu::Register
//! import std::num::Wrapping
//! ```
//!
//! ### Format lines
//!
//! Format lines follow an instruction and define its disassembly output:
//!
//! ```text
//! bx [0:5]=010010 li:simm24[6:29] aa:bool[30] lk:bool[31]
//! | "b{lk ? l}{aa ? a} {li:#x}"
//! ```
//!
//! Features:
//! * `{field}` - insert field value, with optional format spec: `{field:#x}`
//! * `{field ? text}` - emit `text` if nonzero, `{field ? yes : no}` for else
//! * `{a + b * 4}` - inline arithmetic (`+`, `-`, `*`, `/`, `%`)
//! * `{-field}` - unary negation
//! * `{map_name(arg)}` - call a map lookup
//! * `{rotate_right(val, amt)}` - builtin functions
//! * Guards: `| ra == 0: "li {rd}, {simm}"` - conditional format selection
//! * Guard arithmetic: `| sh == 32 - mb : "srwi ..."` - arithmetic in guard operands
//!
//! ### Maps
//!
//! Lookup tables for use in format strings:
//!
//! ```text
//! map spr_name(spr) {
//! 1 => "xer"
//! 8 => "lr"
//! 9 => "ctr"
//! _ => "???"
//! }
//! ```
//!
//! ### Formatting trait
//!
//! chipi generates a `{Name}Format` trait with one method per instruction.
//! Default implementations come from format lines. Override selectively:
//!
//! ```ignore
//! struct MyFormat;
//! impl cpu::CpuFormat for MyFormat {
//! fn fmt_bx(li: i32, aa: bool, lk: bool,
//! f: &mut std::fmt::Formatter) -> std::fmt::Result {
//! write!(f, "BRANCH {:#x}", li)
//! }
//! }
//!
//! println!("{}", instr.display::<MyFormat>());
//! ```
//!
//! ## Emulator LUT
//!
//! chipi can generate a function-pointer **lookup table** for emulator dispatch.
//! Each opcode is routed directly to a handler function via static `[Handler; N]`
//! arrays derived from the same decision tree.
//!
//! ### build.rs
//!
//! Use [`LutBuilder`] to configure and emit both the LUT and the handler stubs:
//!
//! ```ignore
//! use std::env;
//! use std::path::PathBuf;
//!
//! fn main() {
//! let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
//! let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
//! let spec = "cpu.chipi";
//!
//! let builder = chipi::LutBuilder::new(spec)
//! .handler_mod("crate::cpu::interpreter")
//! .ctx_type("crate::Cpu");
//!
//! // Regenerated every build, stays in sync with the spec
//! builder
//! .build_lut(out_dir.join("cpu_lut.rs").to_str().unwrap())
//! .expect("failed to generate LUT");
//!
//! // Written once, hand-edits are never overwritten
//! let stubs = manifest.join("src/cpu/interpreter.rs");
//! if !stubs.exists() {
//! builder.build_stubs(stubs.to_str().unwrap())
//! .expect("failed to generate stubs");
//! }
//!
//! println!("cargo:rerun-if-changed={spec}");
//! }
//! ```
//!
//! ### Include and dispatch
//!
//! ```ignore
//! // src/cpu.rs
//! #[allow(dead_code, non_upper_case_globals)]
//! pub mod lut {
//! include!(concat!(env!("OUT_DIR"), "/cpu_lut.rs"));
//! }
//!
//! // fetch-decode-execute
//! let opcode = mem.read_u32(cpu.pc);
//! cpu.pc = cpu.pc.wrapping_add(4);
//! crate::cpu::lut::dispatch(&mut ctx, opcode);
//! ```
//!
//! ### Handler stubs
//!
//! On the first build, `build_stubs` writes `src/cpu/interpreter.rs` with
//! `todo!()` bodies. Replace each `todo!()` as you go; the file is never
//! regenerated so hand-edits are safe.
//!
//! The second parameter type is derived from the spec's `width`:
//! `u8` (8-bit), `u16` (16-bit), or `u32` (32-bit).
//!
//! ```ignore
//! pub fn addi(_ctx: &mut crate::Cpu, _opcode: u32) { todo!("addi") }
//! pub fn lwz(_ctx: &mut crate::Cpu, _opcode: u32) { todo!("lwz") }
//! // ... one fn per instruction
//! ```
//!
//! ### Grouped handlers with const generics
//!
//! Use `.group()` to fold multiple instructions into one handler via a
//! `const OP: u32` generic parameter. Each LUT entry is a separate
//! monomorphization.
//!
//! Provide `.lut_mod()` so that generated stubs can `use` the `OP_*` constants:
//!
//! ```ignore
//! chipi::LutBuilder::new("cpu.chipi")
//! .handler_mod("crate::cpu::interpreter")
//! .ctx_type("crate::Cpu")
//! .lut_mod("crate::cpu::lut")
//! .group("alu", ["addi", "addis", "ori", "oris"])
//! .build_lut(out_dir.join("cpu_lut.rs").to_str().unwrap())?;
//! ```
//!
//! ### Custom instruction wrapper type
//!
//! Use `.instr_type()` to replace the raw integer with a richer type.
//! chipi uses it in the generated `Handler` alias and all stub signatures.
//! `.raw_expr()` tells chipi how to extract the underlying integer for table
//! indexing; it defaults to `"instr.0"` for newtype wrappers.
//!
//! ```ignore
//! chipi::LutBuilder::new("cpu.chipi")
//! .handler_mod("crate::cpu::interpreter")
//! .ctx_type("crate::Cpu")
//! .instr_type("crate::cpu::Instruction") // struct Instruction(pub u32)
//! // .raw_expr("instr.0") // default for newtype wrappers
//! .build_lut(out_dir.join("cpu_lut.rs").to_str().unwrap())?;
//! ```
//!
//! Generated `Handler` type and stub signature:
//! ```ignore
//! pub type Handler = fn(&mut crate::Cpu, crate::cpu::Instruction);
//!
//! pub fn addi(_ctx: &mut crate::Cpu, _instr: crate::cpu::Instruction) { todo!("addi") }
//! ```
//!
//! ## Instruction Type Generation
//!
//! chipi can auto-generate the instruction newtype with field accessor methods,
//! eliminating the need to hand-write bit extraction code. This is useful in
//! cases where a thin wrapper for decoding is prefered (e.g. emulation).
//!
//! ### build.rs
//!
//! Add `.build_instr_type()` to your `LutBuilder` chain:
//!
//! ```ignore
//! chipi::LutBuilder::new("cpu.chipi")
//! .instr_type("crate::cpu::Instruction")
//! .build_instr_type(out_dir.join("instruction.rs").to_str().unwrap())?;
//! ```
//!
//! ### Generated output
//!
//! Creates a newtype with `#[inline]` accessor methods for every unique field:
//!
//! ```ignore
//! pub struct Instruction(pub u32);
//!
//! #[rustfmt::skip]
//! impl Instruction {
//! #[inline] pub fn rd(&self) -> u8 { ((self.0 >> 21) & 0x1f) as u8 }
//! #[inline] pub fn ra(&self) -> u8 { ((self.0 >> 16) & 0x1f) as u8 }
//! #[inline] pub fn simm(&self) -> i32 { ((((self.0 >> 0) & 0xffff) as i32) << 16) >> 16 }
//! #[inline] pub fn rc(&self) -> bool { (self.0 & 0x1) != 0 }
//! // ... one accessor per unique field across all instructions
//! }
//! ```
//!
//! ### Usage
//!
//! Include the generated file and optionally add custom methods:
//!
//! ```ignore
//! // src/cpu/semantics.rs
//! include!(concat!(env!("OUT_DIR"), "/instruction.rs"));
//!
//! // Add custom accessors not derivable from the spec
//! impl Instruction {
//! /// SPR field with swapped halves (PowerPC)
//! pub fn spr_decoded(&self) -> u32 {
//! let raw = self.spr();
//! (raw >> 5) | ((raw & 0x1f) << 5)
//! }
//! }
//! ```
//!
//! ### Conflict handling
//!
//! Fields with the same name but different bit ranges across instructions generate
//! separate accessors with bit range suffixes (e.g., `d_15_0()` and `d_11_0()`).
//! You can add convenience aliases in a separate `impl` block if needed.
//!
//! ## API
//!
//! ```ignore
//! // Parse and generate decoder from file
//! chipi::generate("cpu.chipi", "out.rs")?;
//!
//! // Generate decoder from source string
//! let code = chipi::generate_from_str(source, "cpu.chipi")?;
//!
//! // Step-by-step
//! let def = chipi::parse("cpu.chipi")?;
//! chipi::emit(&def, "out.rs")?;
//!
//! // Emulator LUT, simple
//! // (instr type auto-derived from spec width: u8 / u16 / u32)
//! chipi::generate_lut("cpu.chipi", "out/lut.rs", "crate::interp", "crate::Cpu")?;
//! chipi::generate_stubs("cpu.chipi", "src/interp.rs", "crate::Cpu")?; // once only
//!
//! // Instruction type generation
//! chipi::generate_instr_type("cpu.chipi", "out/instruction.rs", "Instruction")?;
//!
//! // Emulator LUT, full control via LutBuilder
//! chipi::LutBuilder::new("cpu.chipi")
//! .handler_mod("crate::cpu::interpreter")
//! .ctx_type("crate::Cpu")
//! .lut_mod("crate::cpu::lut") // needed when using groups
//! .group("alu", ["addi", "addis"]) // const-generic shared handler
//! .instr_type("crate::cpu::Instruction") // optional wrapper type
//! .build_lut("out/lut.rs")?
//! .build_instr_type("out/instruction.rs")?; // generate instruction type
//! ```
use HashMap;
use fs;
use Path;
use Errors;
use DecoderDef;
/// Parse a `.chipi` file from a file path and return the decoder definition.
///
/// # Errors
///
/// Returns an error if the file cannot be read or parsed.
///
/// # Example
///
/// ```ignore
/// let def = chipi::parse("thumb.chipi")?;
/// ```
/// Parse source text directly without reading from a file.
///
/// # Arguments
///
/// * `source`: `.chipi` source code
/// * `filename`: name used in error messages
/// Validate a parsed definition and write generated Rust code to a file.
///
/// # Errors
///
/// Returns validation or I/O errors.
/// Full pipeline: parse a `.chipi` file and generate a Rust decoder.
///
/// # Example
///
/// ```ignore
/// chipi::generate("thumb.chipi", "thumb_decoder.rs")?;
/// ```
/// Generate a function-pointer LUT from a `.chipi` spec file.
///
/// Produces a Rust source file containing:
/// - `pub type Handler = fn(&mut Ctx, u32)`
/// - Static dispatch tables (`_T0`, `_T1`, ...) indexed by opcode bit ranges
/// - `pub fn dispatch(ctx: &mut Ctx, opcode: u32)`
///
/// `handler_mod` is the module path where handler functions live, e.g.
/// `"crate::cpu::interpreter"`Each instruction `foo` in the spec must have
/// a corresponding `pub fn foo(ctx: &mut Ctx, opcode: u32)` there.
///
/// `ctx_type` is the mutable context passed to every handler, e.g.
/// `"crate::gekko::Gekko"`.
///
/// # Example (build.rs)
///
/// ```ignore
/// chipi::generate_lut(
/// "cpu.chipi",
/// out_dir.join("cpu_lut.rs").to_str().unwrap(),
/// "crate::cpu::interpreter",
/// "crate::Cpu",
/// )?;
/// ```
/// Generate handler stub functions for every instruction in a `.chipi` spec.
///
/// Each stub has the form:
/// ```rust,ignore
/// pub fn twi(_ctx: &mut Ctx, _opcode: u32) { todo!("twi") }
/// ```
///
/// Intended to be run **once** to bootstrap an interpreter module. After that,
/// replace `todo!()` bodies with real implementations as you go.
/// Generate an instruction newtype with field accessor methods from a `.chipi` spec.
///
/// Collects all unique fields across all instructions and generates a
/// `pub struct Name(pub u32)` with one `#[inline]` accessor method per field.
///
/// Fields with the same name but conflicting definitions (different bit ranges
/// or types) generate separate accessors with bit range suffixes (e.g., `d_15_0`
/// and `d_11_0`).
///
/// # Example
///
/// ```ignore
/// chipi::generate_instr_type("cpu.chipi", "out/instruction.rs", "Instruction")?;
/// ```
///
/// Then in your code:
///
/// ```ignore
/// mod cpu {
/// include!(concat!(env!("OUT_DIR"), "/instruction.rs"));
/// }
/// ```
/// Builder for generating a function-pointer LUT and handler stubs,
/// with optional grouping of instructions under shared const-generic handlers.
///
/// Use this when you want multiple instructions to share one handler function
/// via a `const OP: u32` generic parameter. See the crate documentation for
/// the full pattern.
///
/// # Example (build.rs)
///
/// ```ignore
/// chipi::LutBuilder::new("cpu.chipi")
/// .handler_mod("crate::cpu::interpreter")
/// .ctx_type("crate::Cpu")
/// .lut_mod("crate::cpu::lut")
/// .group("alu", ["addi", "addis", "ori", "oris"])
/// .group("mem", ["lwz", "stw", "lbz", "stb"])
/// .build_lut(out_dir.join("cpu_lut.rs").to_str().unwrap())?;
///
/// if !stubs.exists() {
/// chipi::LutBuilder::new("cpu.chipi")
/// .ctx_type("crate::Cpu")
/// .lut_mod("crate::cpu::lut")
/// .group("alu", ["addi", "addis", "ori", "oris"])
/// .group("mem", ["lwz", "stw", "lbz", "stb"])
/// .build_stubs(stubs.to_str().unwrap())?;
/// }
/// ```
/// Parse, validate, and generate code from source text. Returns the
/// generated Rust code as a `String`.
///
/// # Errors
///
/// Returns parse or validation errors.