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
#![feature(assert_matches)]
#![feature(specialization)]
#![feature(exact_size_is_empty)]
#![feature(exclusive_range_pattern)]
#![feature(let_chains)]
#![feature(box_patterns)]
#![feature(box_into_inner)]
#![feature(string_extend_from_within)]
#![recursion_limit = "256"]
#![feature(map_try_insert)]
#![feature(get_mut_unchecked)]
#![feature(stmt_expr_attributes)]


/// Implementation of various behvior for the tokens of cpclib_tokens
pub mod implementation;

/// All the stuff to parse z80 code.
pub mod parser;

/// Production of the bytecodes from the tokens.
pub mod assembler;

pub mod disass;

pub mod preamble;

pub mod error;

mod crunchers;

pub mod progress;

#[cfg(feature = "basm")]
pub mod basm_utils;

use std::fmt::Debug;
use std::io::Write;
use std::sync::{Arc, RwLock};

use cpclib_disc::amsdos::*;
use cpclib_sna::Snapshot;
use preamble::function::FunctionBuilder;
use preamble::processed_token::ProcessedToken;
use preamble::*;

use self::listing_output::ListingOutput;

/// Configuration of the assembler. By default the assembler is case sensitive and has no symbol
#[derive(Debug, Clone)]
pub struct AssemblingOptions {
    /// Set to true to consider that the assembler pay attention to the case of the labels
    case_sensitive: bool,
    /// Contains some symbols that could be used during assembling
    symbols: cpclib_tokens::symbols::SymbolsTable,
    output_builder: Option<Arc<RwLock<ListingOutput>>>,
    /// The snapshot may be prefiled with a dedicated snapshot
    snapshot_model: Option<Snapshot>
}

impl Default for AssemblingOptions {
    fn default() -> Self {
        Self {
            case_sensitive: true,
            symbols: cpclib_tokens::symbols::SymbolsTable::default(),
            output_builder: None,
            snapshot_model: None
        }
    }
}

#[allow(missing_docs)]
impl AssemblingOptions {
    pub fn new_case_sensitive() -> Self {
        Self::default()
    }

    pub fn new_case_insensitive() -> Self {
        let mut options = Self::new_case_sensitive();
        options.case_sensitive = false;
        options
    }

    /// Creation an option object with the given symbol table
    pub fn new_with_table(symbols: &cpclib_tokens::symbols::SymbolsTable) -> Self {
        let mut options = Self::default();
        options.set_symbols(symbols);
        options
    }

    /// Specify if the assembler must be case sensitive or not
    pub fn set_case_sensitive(&mut self, val: bool) -> &mut Self {
        self.case_sensitive = val;
        self
    }

    pub fn set_snapshot_model(&mut self, mut sna: Snapshot) -> &mut Self {
        sna.unwrap_memory_chunks();
        self.snapshot_model = Some(sna);
        self
    }

    /// Specify a symbol table to copy
    pub fn set_symbols(&mut self, val: &cpclib_tokens::symbols::SymbolsTable) -> &mut Self {
        self.symbols = val.clone();
        self
    }

    pub fn symbols(&self) -> &cpclib_tokens::symbols::SymbolsTable {
        &self.symbols
    }

    pub fn symbols_mut(&mut self) -> &mut cpclib_tokens::symbols::SymbolsTable {
        &mut self.symbols
    }

    pub fn case_sensitive(&self) -> bool {
        self.case_sensitive
    }

    pub fn snapshot_model(&self) -> Option<&Snapshot> {
        self.snapshot_model.as_ref()
    }

    pub fn write_listing_output<W: 'static + Write + Send + Sync>(
        &mut self,
        writer: W
    ) -> &mut Self {
        self.output_builder = Some(Arc::new(RwLock::new(ListingOutput::new(writer))));
        self.output_builder
            .as_mut()
            .map(|b| b.write().unwrap().on());
        self
    }
}

/// Assemble a piece of code and returns the associated list of bytes.
pub fn assemble(code: &str) -> Result<Vec<u8>, AssemblerError> {
    let options = EnvOptions::default();
    // let options = AssemblingOptions::new_with_table(table);
    assemble_with_options(code, options).map(|(bytes, _symbols)| bytes)
}

/// Assemble a piece of code and returns the associates liste of bytes as well as the generated reference table.
pub fn assemble_with_options(
    code: &str,
    options: EnvOptions
) -> Result<(Vec<u8>, cpclib_tokens::symbols::SymbolsTable), AssemblerError> {
    let builder = options.parse_options().clone().context_builder();
    let tokens = parser::parse_z80_with_context_builder(code, builder)?;
    assemble_tokens_with_options(&tokens, options)
}

/// Assemble the predifined list of tokens
pub fn assemble_tokens_with_options<
    'tokens,
    T: 'static + Visited + ToSimpleToken + Clone + ListingElement + Sync + MayHaveSpan
>(
    tokens: &'tokens [T],
    options: EnvOptions
) -> Result<(Vec<u8>, cpclib_tokens::symbols::SymbolsTable), AssemblerError>
where
    <T as cpclib_tokens::ListingElement>::Expr: ExprEvaluationExt,
    <<T as cpclib_tokens::ListingElement>::TestKind as cpclib_tokens::TestKindElement>::Expr:
        implementation::expression::ExprEvaluationExt,
    ProcessedToken<'tokens, T>: FunctionBuilder
{
    let (_tok, env) = assembler::visit_tokens_all_passes_with_options(tokens, options)
        .map_err(|(_, _, e)| AssemblerError::AlreadyRenderedError(e.to_string()))?;
    Ok((env.produced_bytes(), env.symbols().as_ref().clone()))
}

/// Build the code and store it inside a file supposed to be injected in a dsk
/// XXX probably crash if filename is not coherent
/// //
pub fn assemble_to_amsdos_file(
    code: &str,
    amsdos_filename: &str
) -> Result<AmsdosFile, AssemblerError> {
    let amsdos_filename = AmsdosFileName::try_from(amsdos_filename)?;

    let tokens = parser::parse_z80_str(code)?;
    let options = EnvOptions::default();

    let (_, env) = assembler::visit_tokens_all_passes_with_options(&tokens, options)
        .map_err(|(_, _, e)| AssemblerError::AlreadyRenderedError(e.to_string()))?;

    Ok(AmsdosFile::binary_file_from_buffer(
        &amsdos_filename,
        env.loading_address().unwrap() as u16,
        env.execution_address().unwrap() as u16,
        &env.produced_bytes()
    )?)
}

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

    #[test]
    fn simple_test_assemble() {
        let code = "
		org 0
		db 1, 2
		db 3, 4
		";

        let bytes = assemble(code).unwrap_or_else(|e| panic!("Unable to assemble {}: {}", code, e));
        assert_eq!(bytes.len(), 4);
        assert_eq!(bytes, vec![1, 2, 3, 4]);
    }

    #[test]
    fn located_test_assemble() {
        let code = "
		org 0x100
		db 1, 2
		db 3, 4
		";

        let bytes = assemble(code).unwrap_or_else(|e| panic!("Unable to assemble {}: {}", code, e));
        assert_eq!(bytes, vec![1, 2, 3, 4]);
    }

    #[test]
    fn case_verification() {
        let code = "
		ld hl, TruC
Truc
		";

        let options = AssemblingOptions::new_case_sensitive();
        let options = EnvOptions::from(options);
        println!("{:?}", assemble_with_options(code, options.clone()));
        assert!(assemble_with_options(code, options).is_err());

        let options = AssemblingOptions::new_case_insensitive();
        let options = EnvOptions::from(options);
        println!("{:?}", assemble_with_options(code, options.clone()));
        assert!(assemble_with_options(code, options).is_ok());
    }

    #[test]
    fn test_size() {
        let mut env = Default::default();
        dbg!(assemble_call_jr_or_jp(
            Mnemonic::Jp,
            None,
            &DataAccess::Expression(Expr::Value(0)),
            &mut env
        )
        .unwrap());
        assert_eq!(
            Token::OpCode(
                Mnemonic::Jp,
                None,
                Some(DataAccess::Expression(Expr::Value(0))),
                None
            )
            .number_of_bytes(),
            Ok(3)
        );

        assert_eq!(
            Token::OpCode(
                Mnemonic::Jr,
                None,
                Some(DataAccess::Expression(Expr::Value(0))),
                None
            )
            .number_of_bytes(),
            Ok(2)
        );

        assert_eq!(
            Token::OpCode(
                Mnemonic::Jr,
                Some(DataAccess::FlagTest(FlagTest::NC)),
                Some(DataAccess::Expression(Expr::Value(0))),
                None
            )
            .number_of_bytes(),
            Ok(2)
        );

        assert_eq!(
            Token::OpCode(
                Mnemonic::Push,
                Some(DataAccess::Register16(Register16::De)),
                None,
                None
            )
            .number_of_bytes(),
            Ok(1)
        );

        assert_eq!(
            Token::OpCode(
                Mnemonic::Dec,
                Some(DataAccess::Register8(Register8::A)),
                None,
                None
            )
            .number_of_bytes(),
            Ok(1)
        );
    }

    #[test]
    fn test_listing() {
        let mut listing = Listing::from_str("   nop").expect("unable to assemble");
        assert_eq!(listing.estimated_duration().unwrap(), 1);
        listing.set_duration(100);
        assert_eq!(listing.estimated_duration().unwrap(), 100);
    }

    fn code_test(code: &'static str) {
        let asm_options = AssemblingOptions::new_case_insensitive();
        let env_options = EnvOptions::new(ParserOptions::default(), asm_options);
        let res = assemble_with_options(code, env_options);
        res.unwrap();
    }

    /// Test stolen to rasm
    #[test]
    fn rasm_pagetag1() {
        let code = "  
        bankset 0
        org #5000
label1
        bankset 1
        org #9000
label2
        bankset 2
        assert {page}label1==0xC0
        assert {page}label2==0xC6 
        assert {pageset}label1==#C0
        assert {pageset}label2==#C2
        assert $ == 0x0000
        assert $$ == 0x0000
        nop";
        code_test(code);
    }
    // /// This test currently does not pass
    // #[test]
    // fn rasm_pagetag2() {
    // let code = "
    // bankset 0
    // call maroutine
    //
    // bank 4
    // org #C000
    // autreroutine
    // nop
    // ret
    //
    // bank 5
    // org #8000
    // maroutine
    // ldir
    // ret
    //
    // bankset 2
    // org #9000
    // troize
    // nop
    // assert {page}maroutine==#7FC5
    // assert {pageset}maroutine==#7FC2
    // assert {page}autreroutine==#7FC4
    // assert {pageset}autreroutine==#7FC2
    // assert {page}troize==#7FCE
    // assert {pageset}troize==#7FCA";
    // rasm_test(code);
    //
    // }
    // #define AUTOTEST_PAGETAG3	"buildsna:bank 2:assert {bank}$==2:assert {page}$==0x7FC0:assert {pageset}$==#7FC0:" \
    // "bankset 1:org #4000:assert {bank}$==5:assert {page}$==0x7FC5:assert {pageset}$==#7FC2"

    #[test]
    fn test_duration() {
        let listing = Listing::from_str(
            "
            pop de      ; 3
        "
        )
        .expect("Unable to assemble this code");
        println!("{}", listing.to_string());
        assert_eq!(listing.estimated_duration().unwrap(), 3);

        let listing = Listing::from_str(
            "
            inc l       ; 1
        "
        )
        .expect("Unable to assemble this code");
        println!("{}", listing.to_string());
        assert_eq!(listing.estimated_duration().unwrap(), 1);

        let listing = Listing::from_str(
            "
            ld (hl), e  ; 2
        "
        )
        .expect("Unable to assemble this code");
        println!("{}", listing.to_string());
        assert_eq!(listing.estimated_duration().unwrap(), 2);

        let listing = Listing::from_str(
            "
            ld (hl), d  ; 2
        "
        )
        .expect("Unable to assemble this code");
        println!("{}", listing.to_string());
        assert_eq!(listing.estimated_duration().unwrap(), 2);

        let listing = Listing::from_str(
            "
            pop de      ; 3
            inc l       ; 1
            ld (hl), e  ; 2
            inc l       ; 1
            ld (hl), d  ; 2
        "
        )
        .expect("Unable to assemble this code");
        println!("{}", listing.to_string());
        assert_eq!(listing.estimated_duration().unwrap(), (3 + 1 + 2 + 1 + 2));
    }

    #[test]
    fn test_real1() {
        let code = "    RUN 0x50, 0xc0";
        code_test(code);

        let code = r"    if {bank}$ == 0
            RUN 0x50, 0xc0
        endif
        ";
        code_test(code);
    }
}