uxn-tal 0.7.1

uxntal:// protocol | a Rust library for assembling TAL (Tal Assembly Language) files into UXN ROM files
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
/// # UXN TAL Assembler
///
/// A Rust library for assembling TAL (Tal Assembly Language) files into UXN ROM files.
///
/// This library provides functionality to parse TAL source code and generate bytecode
/// compatible with the UXN virtual machine.
///
/// ## Basic Assembly Example
///
/// ```rust
/// use uxn_tal::{Assembler, AssemblerError};
///
/// fn main() -> Result<(), AssemblerError> {
///     let tal_source = r#"
///         |0100 @reset
///             #48 #65 #6c #6c #6f #20 #57 #6f #72 #6c #64 #21 #0a
///             #18 DEO
///         BRK
///     "#;
///     
///     let mut assembler = Assembler::new();
///     let rom = assembler.assemble(tal_source, None)?;
///     
///     // Save the ROM to a file
///     std::fs::write("hello.rom", rom)?;
///     
///     Ok(())
/// }
/// ```
///
/// ## Protocol URL Parsing with Git Support
///
/// The library provides enhanced URL parsing that automatically handles git repository URLs.
/// You can use either the familiar `ProtocolParser::parse` or the explicit `parse_uxntal_url` function:
///
/// ```rust
/// use uxn_tal::{ProtocolParser, parse_uxntal_url};
///
/// // Option 1: Standard API with automatic git support
/// let result = ProtocolParser::parse("uxntal://git@github.com:user/repo/tree/main/file.tal");
///
/// // Option 2: Explicit enhanced parsing (same result)
/// let result = parse_uxntal_url("uxntal://git@github.com:user/repo/tree/main/file.tal");
///
/// if let Some(repo_ref) = &result.repo_ref {
///     println!("Repository: {}/{}", repo_ref.owner, repo_ref.repo);
///     println!("Branch: {}", repo_ref.branch);
///     println!("File: {}", repo_ref.path);
/// }
/// ```
type AssembleDirectoryResult = (
    std::path::PathBuf,
    std::path::PathBuf,
    Option<std::path::PathBuf>,
    usize,
);
pub use util::{RealRomCache, RealRomEntryResolver};
// Re-export get_or_write_cached_rom and hash_url for downstream crates
pub use uxn_tal_common::{get_or_write_cached_rom, hash_url};
pub mod assembler;
pub mod bkend;
pub mod bkend_buxn;
pub mod bkend_drif;
pub mod bkend_uxn;
pub mod bkend_uxn38;
pub mod chocolatal;
pub mod debug;
pub mod devicemap;
pub mod dis_uxndis;
pub mod error;
pub mod hexrev;
pub mod lexer;
pub mod opcode_table;
pub mod opcodes;
pub mod parser;
pub mod rom;
pub mod runes;
pub mod wsl;
pub use assembler::Assembler;
pub use error::AssemblerError;
pub mod fetch;
pub mod paths;
pub mod util;
pub use fetch::parse_uxntal_url;
pub use fetch::resolver::resolve_entry_from_url;
pub mod probe_runtime;
pub mod probe_tal;
pub mod protocol_parser;

pub use uxn_tal_defined::*;
// Shadow the base ProtocolParser with our enhanced version that includes git support
pub use protocol_parser::ProtocolParser;

pub fn assemble(source: &str) -> Result<Vec<u8>, AssemblerError> {
    let mut a = Assembler::new();
    a.assemble(source, None)
}

pub fn assemble_with_path(source: &str, path: &str) -> Result<Vec<u8>, AssemblerError> {
    let mut a = Assembler::new();
    a.assemble(source, Some(path.to_string()))
}

/// Convenience function to assemble a TAL file directly from a file path
pub fn assemble_file<P: AsRef<std::path::Path>>(input_path: P) -> Result<Vec<u8>, AssemblerError> {
    let source = std::fs::read_to_string(&input_path)?;
    let mut assembler = Assembler::new();
    let path_str = input_path.as_ref().to_string_lossy().into_owned();
    assembler.assemble(&source, Some(path_str))
}

/// Convenience function to assemble a TAL file and save the ROM to a file
pub fn assemble_file_to_rom<P: AsRef<std::path::Path>, Q: AsRef<std::path::Path>>(
    input_path: P,
    output_path: Q,
) -> Result<usize, AssemblerError> {
    let rom = assemble_file(input_path)?;
    std::fs::write(&output_path, &rom)?;
    Ok(rom.len())
}

/// Convenience function to assemble a TAL file and save ROM with same name but .rom extension
pub fn assemble_file_auto<P: AsRef<std::path::Path>>(
    input_path: P,
) -> Result<(std::path::PathBuf, usize), AssemblerError> {
    let input_path = input_path.as_ref();
    let output_path = input_path.with_extension("rom");
    let size = assemble_file_to_rom(input_path, &output_path)?;
    Ok((output_path, size))
}

/// Convenience function to assemble a TAL file and generate both ROM and symbol files
pub fn assemble_file_with_symbols<P: AsRef<std::path::Path>>(
    input_path: P,
) -> Result<(std::path::PathBuf, std::path::PathBuf, usize), AssemblerError> {
    let input_path = input_path.as_ref();
    let source = std::fs::read_to_string(input_path)?;
    let mut assembler = Assembler::new();
    let path_str = input_path.to_string_lossy().into_owned();
    let rom = assembler.assemble(&source, Some(path_str))?;

    // Save ROM file
    let rom_path = input_path.with_extension("rom");
    std::fs::write(&rom_path, &rom)?;

    // Save symbol file
    let sym_path = input_path.with_extension("sym");
    let symbols = assembler.generate_symbol_file();
    std::fs::write(&sym_path, &symbols)?;

    Ok((rom_path, sym_path, rom.len()))
}

/// Convenience function to batch process TAL files in a directory
pub fn assemble_directory<P: AsRef<std::path::Path>>(
    dir_path: P,
    generate_symbols: bool,
) -> Result<Vec<AssembleDirectoryResult>, AssemblerError> {
    let dir_path = dir_path.as_ref();
    let mut results = Vec::new();

    for entry in std::fs::read_dir(dir_path)? {
        let entry = entry?;
        let path = entry.path();

        if path.extension().and_then(|s| s.to_str()) == Some("tal") {
            if generate_symbols {
                let (rom_path, sym_path, size) = assemble_file_with_symbols(&path)?;
                results.push((path, rom_path, Some(sym_path), size));
            } else {
                let (rom_path, size) = assemble_file_auto(&path)?;
                results.push((path, rom_path, None, size));
            }
        }
    }

    Ok(results)
}

pub fn assemble_with_rust_interface_module(
    source: &str,
    module_name: &str,
) -> Result<(Vec<u8>, String), AssemblerError> {
    let mut a = Assembler::new();
    let rom = a.assemble(source, None)?;
    let module = generate_rust_interface_module(&a, module_name);
    Ok((rom, module))
}

pub fn generate_rust_interface_module(
    assembler: &crate::assembler::Assembler,
    module_name: &str,
) -> String {
    let mut out = String::new();
    out.push_str("#![allow(clippy::module_inception)]\n");
    out.push_str(&format!("pub mod {} {{\n", module_name));
    out.push_str("    #![allow(non_upper_case_globals)]\n");
    out.push_str("    // Auto-generated: label address & size constants\n");
    // Address and size constants
    for name in &assembler.symbol_order {
        if let Some(sym) = assembler.symbols.get(name) {
            let id = {
                let mut s: String = name
                    .chars()
                    .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
                    .collect();
                if s.chars()
                    .next()
                    .map(|c| c.is_ascii_digit())
                    .unwrap_or(false)
                {
                    s.insert(0, '_');
                }
                s.to_ascii_uppercase()
            };
            out.push_str(&format!(
                "    pub const _c{}: usize = 0x{:04X};\n",
                id, sym.address
            ));
            // Compute size
            let next_addr = assembler
                .symbol_order
                .iter()
                .skip_while(|n| *n != name)
                .skip(1)
                .filter_map(|n| assembler.symbols.get(n))
                .map(|s| s.address)
                .find(|&a| a > sym.address)
                .unwrap_or(assembler.effective_length as u16);
            let size = next_addr.saturating_sub(sym.address);
            out.push_str(&format!(
                "    pub const _c{}_SIZE: usize = 0x{:04X};\n",
                id, size
            ));
        }
    }
    // Helper function to get a slice for a label
    out.push_str(
        r#"
    /// Returns a slice of RAM for a label by name (address, size)
    pub fn get_slice<'a>(ram: &'a [u8], label: &str) -> Option<&'a [u8]> {
        match label {
"#,
    );
    for name in &assembler.symbol_order {
        if let Some(_sym) = assembler.symbols.get(name) {
            let id = {
                let mut s: String = name
                    .chars()
                    .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
                    .collect();
                if s.chars()
                    .next()
                    .map(|c| c.is_ascii_digit())
                    .unwrap_or(false)
                {
                    s.insert(0, '_');
                }
                s.to_ascii_uppercase()
            };
            out.push_str(&format!(
                "            \"{name}\" => Some(&ram[_c{}.._c{}+_c{}_SIZE]),\n",
                id, id, id
            ));
        }
    }
    out.push_str(
        r#"            _ => None,
        }
    }
"#,
    );
    out.push_str("}\n");
    out
}

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

    #[test]
    fn test_simple_assembly() {
        let source = r#"
            |0100
            #42 #43 ADD BRK
        "#;

        let mut assembler = Assembler::new();
        let rom = assembler.assemble(source, None).expect("Assembly failed");

        // Should contain: LIT 0x42, LIT 0x43, ADD, BRK (6 bytes total)
        // ROM trimming removes the 256-byte padding
        assert_eq!(rom.len(), 6);
        assert_eq!(rom[0], 0x80); // LIT
        assert_eq!(rom[1], 0x42); // literal byte
        assert_eq!(rom[2], 0x80); // LIT
        assert_eq!(rom[3], 0x43); // literal byte
        assert_eq!(rom[4], 0x18); // ADD opcode
    }

    #[test]
    fn test_label_reference() {
        let source = r#"
            |0100 @start
            ;data LDA2
            BRK
            @data #1234
        "#;

        let mut assembler = Assembler::new();
        let rom = assembler
            .assemble(source, Some("(test_label_reference)".to_string()))
            .expect("Assembly failed");

        // Should have label reference resolved to correct address
        // ROM is trimmed, so no 256-byte padding
        assert!(rom.len() > 4);
        // ;data should generate LIT2 + 16-bit address
        assert_eq!(rom[0], 0xa0); // LIT2
                                  // Address of @data will be 0x100 + offset (where offset = 5 for the LIT2 + address + LDA2 + BRK)
        let expected_addr = 0x0105_u16;
        assert_eq!(rom[1], (expected_addr >> 8) as u8); // High byte
        assert_eq!(rom[2], (expected_addr & 0xff) as u8); // Low byte
    }

    fn _test_instruction_modes() {
        let source = r#"
            |0100
            ADD     ( base instruction )
            ADD2    ( short mode )
            ADDr    ( return mode )
            ADDk    ( keep mode )
            ADD2rk  ( all modes )
            BRK
        "#;

        let mut assembler = Assembler::new();
        // ROM is trimmed, so we check from index 0
        let rom = assembler
            .assemble(source, Some("(test_instruction_modes)".to_string()))
            .expect("Assembly failed");
        assert_eq!(rom[1], 0x18 | 0x20); // ADD2 (short mode)
        assert_eq!(rom[2], 0x18 | 0x40); // ADDr (return mode)
        assert_eq!(rom[3], 0x18 | 0x80); // ADDk (keep mode)
        assert_eq!(rom[4], 0x18 | 0x20 | 0x40 | 0x80); // ADD2rk (all modes)
        assert_eq!(rom[5], 0x00); // BRK
    }

    #[test]
    fn test_hex_literals() {
        let source = r#"
            #12 #3456 #ab #cdef
        "#;

        let mut assembler = Assembler::new();
        let rom = assembler
            .assemble(source, Some("(test_hex_literals1)".to_string()))
            .expect("Assembly failed");

        // ROM is trimmed, literals become LIT + byte or LIT2 + short
        // #12 -> LIT 0x12
        assert_eq!(rom[0], 0x80); // LIT
        assert_eq!(rom[1], 0x12); // byte
        assert_eq!(rom[2], 0xa0); // LIT2
        assert_eq!(rom[3], 0x34); // high byte
        assert_eq!(rom[4], 0x56); // low byte
                                  // #ab -> LIT 0xab
        assert_eq!(rom[5], 0x80); // LIT
        assert_eq!(rom[6], 0xab); // byte
                                  // #cdef -> LIT2 0xcdef
        assert_eq!(rom[7], 0xa0); // LIT2
        assert_eq!(rom[8], 0xcd); // high byte
        assert_eq!(rom[9], 0xef); // low byte
    }

    #[test]
    fn test_character_literals() {
        let source = r#"
            |0100
            'A 'B 'C
        "#;

        let mut assembler = Assembler::new();
        let rom = assembler.assemble(source, None).expect("Assembly failed");

        // Character literals become raw bytes (no LIT opcode)
        assert_eq!(rom[0], b'A');
        assert_eq!(rom[1], b'B');
        assert_eq!(rom[2], b'C');
    }

    #[test]
    fn test_raw_strings() {
        let source = r#"
            |0100
            "Hello"
        "#;

        let mut assembler = Assembler::new();
        let rom = assembler.assemble(source, None).expect("Assembly failed");

        // Raw strings become raw bytes (ROM is trimmed)
        assert_eq!(&rom[0..5], b"Hello");
    }

    #[test]
    #[ignore = "reason: not sure why it fails, tbd"]
    fn test_undefined_label_error() {
        let source = r#"
            |0100
            ;undefined-label LDA2
        "#;

        let mut assembler = Assembler::new();
        let result = assembler.assemble(source, None);

        assert!(matches!(result, Err(AssemblerError::UndefinedLabel { .. })));
    }

    #[test]
    #[ignore = "reason: not sure why it fails, tbd"]
    fn test_duplicate_label_error() {
        let source = r#"
            |0100 @label
            @label
        "#;

        let mut assembler = Assembler::new();
        let result = assembler.assemble(source, Some("(test_duplicate_label_error)".to_owned()));

        assert!(matches!(result, Err(AssemblerError::DuplicateLabel { .. })));
    }

    #[test]
    #[ignore = "reason: not sure why it fails, tbd"]
    fn test_unknown_opcode_error() {
        let source = r#"
            |0100
            UNKNOWN
        "#;

        let mut assembler = Assembler::new();
        let result = assembler.assemble(source, None);

        assert!(matches!(result, Err(AssemblerError::UnknownOpcode { .. })));
    }

    #[test]
    fn test_skip_directive() {
        let source = r#"
            |0100
            #12
            $04
            #34
        "#;

        let mut assembler = Assembler::new();
        let data = assembler
            .assemble(source, Some("(test_skip_directive)".to_string()))
            .unwrap();

        // Should have: LIT 12, 4 zero bytes, LIT 34
        // Starting at position 0 (after trimming padding)
        assert_eq!(data[0], 0x80); // LIT
        assert_eq!(data[1], 0x12); // Value
        let _rom = assembler
            .assemble(source, Some("(test_hex_literals)".to_string()))
            .expect("Assembly failed");
        assert_eq!(data[3], 0x00); // Skip byte 2
        assert_eq!(data[4], 0x00); // Skip byte 3
        assert_eq!(data[5], 0x00); // Skip byte 4
        assert_eq!(data[6], 0x80); // LIT
        assert_eq!(data[7], 0x34); // Value
    }

    #[test]
    fn test_device_access() {
        let source = r#"
            |00 @System &r $2
            |0100 @main
                #ff .System/r DEO
        "#;

        let mut assembler = Assembler::new();
        let data = assembler
            .assemble(source, Some("(test_device_access)".to_string()))
            .unwrap();

        // Should generate: LIT ff, LIT 00 (System/r address), DEO
        assert_eq!(data.len(), 5);
        assert_eq!(data[0], 0x80); // LIT
        assert_eq!(data[1], 0xff); // Value
        assert_eq!(data[2], 0x80); // LIT (for device address)
        assert_eq!(data[3], 0x00); // System/r address
        assert_eq!(data[4], 0x17); // DEO opcode
    }

    #[test]
    fn test_macros() {
        let source = r#"
            %DOUBLE { DUP ADD }
            |0100 @main
                #05 DOUBLE
        "#;

        let mut assembler = Assembler::new();
        let data = assembler
            .assemble(source, Some("(test_macros)".to_string()))
            .unwrap();

        // Should generate: LIT 05, DUP, ADD
        assert_eq!(data.len(), 4);
        assert_eq!(data[0], 0x80); // LIT
        assert_eq!(data[1], 0x05); // Value
        assert_eq!(data[2], 0x06); // DUP opcode
        assert_eq!(data[3], 0x18); // ADD opcode
    }

    #[test]
    fn test_inline_assembly() {
        let source = r#"
            |0100 @main
                [ #05 DUP ADD ]
        "#;

        let mut assembler = Assembler::new();
        let data = assembler
            .assemble(source, Some("(test_inline_assembly)".to_string()))
            .unwrap();

        // Should generate: LIT 05, DUP, ADD
        assert_eq!(data.len(), 4);
        assert_eq!(data[0], 0x80); // LIT
        assert_eq!(data[1], 0x05); // Value
        assert_eq!(data[2], 0x06); // DUP opcode
        assert_eq!(data[3], 0x18); // ADD opcode
    }

    #[test]
    fn test_complete_tal_features() {
        let source = r#"
            |0100 @main
                #41 #18 DEO
                BRK
        "#;

        let mut assembler = Assembler::new();
        let result = assembler.assemble(source, Some("(test_complete_tal_features)".to_string()));
        if let Err(ref e) = result {
            println!("Assembly error: {}", e);
        }
        assert!(result.is_ok(), "Complete TAL assembly should succeed");

        let data = result.unwrap();
        assert!(data.len() == 6, "Should generate some ROM data");

        // Verify it starts with our expected instructions
        assert_eq!(data[0], 0x80); // LIT
        assert_eq!(data[1], 0x41); // Value 'A'
        assert_eq!(data[2], 0x80); // LIT
        assert_eq!(data[3], 0x18); // #18
        assert_eq!(data[4], 0x17); // DEO
    }
}

#[test]
fn test_tal_strings_error() {
    use crate::Assembler;
    // TAL/UXN string equivalence to Python:
    // guide = "TYPE \"HELP\" FOR INFO \x7f "
    // bytes_free = " BYTES FREE\n"
    let source = r#"&guide "TYPE 20 ""HELP" 20 "FOR 20 "INFO 20 7f 20 $1 &bytes-free 20 "BYTES 20 "FREE 0a $1"#;

    // Assemble using Assembler struct to get label offsets
    let mut assembler = Assembler::new();
    let _ = assembler
        .assemble(source, None)
        .expect("Assembly should succeed");

    // Get label offsets
    let guide_offset = assembler.symbols["guide"].address as usize - 0x0100;
    let bytes_free_offset = assembler.symbols["bytes-free"].address as usize - 0x0100;

    // Get ROM bytes
    let rom = assembler.rom.data();

    // Expected bytes for guide and bytes_free
    let expected_guide: &[u8] = b"TYPE \"HELP\" FOR INFO \x7f ";
    let expected_bytes_free: &[u8] = b" BYTES FREE\n";

    assert_eq!(
        &rom[guide_offset..guide_offset + expected_guide.len()],
        expected_guide
    );
    assert_eq!(
        &rom[bytes_free_offset..bytes_free_offset + expected_bytes_free.len()],
        expected_bytes_free
    );
}