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
use std::fmt::{Debug, Display};
use std::io::Write;
use std::sync::{Arc, RwLock};

use cpclib_common::itertools::Itertools;
use cpclib_common::smallvec::SmallVec;
use cpclib_tokens::symbols::PhysicalAddress;
use cpclib_tokens::{ExprResult, Token};

use crate::preamble::{LocatedToken, MayHaveSpan};
/// Generate an output listing.
/// Can be useful to detect issues
pub struct ListingOutput {
    /// Writer that will contains the listing/
    /// The listing is produced line by line and not token per token
    writer: Box<dyn Write + Send + Sync>,
    /// Filename of the current line
    current_fname: Option<String>,
    activated: bool,

    /// Bytes collected at the current line
    current_line_bytes: SmallVec<[u8; 4]>,
    /// Complete source
    current_source: Option<&'static str>,
    /// Line number and line content.
    current_line_group: Option<(u32, String)>, // clone view of the line XXX avoid this clone

    current_first_address: u32,
    current_address_kind: AddressKind,
    current_physical_address: PhysicalAddress,
    crunched_section_counter: usize
}
#[derive(PartialEq)]
pub enum AddressKind {
    Address,
    CrunchedArea,
    Mixed,
    None
}

impl Display for AddressKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                AddressKind::Address => ' ',
                AddressKind::CrunchedArea => 'C',
                AddressKind::Mixed => 'M',
                AddressKind::None => 'N'
            }
        )
    }
}

impl Debug for ListingOutput {
    fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Ok(())
    }
}

impl ListingOutput {
    /// Build a new ListingOutput that will write everyting in writter
    pub fn new<W: 'static + Write + Send + Sync>(writer: W) -> Self {
        Self {
            writer: Box::new(writer),
            current_fname: None,
            activated: false,
            current_line_bytes: Default::default(),
            current_line_group: None,
            current_source: None,
            current_first_address: 0,
            current_address_kind: AddressKind::None,
            crunched_section_counter: 0,
            current_physical_address: PhysicalAddress::new(0, 0)
        }
    }

    fn bytes_per_line(&self) -> usize {
        8
    }

    /// Check if the token is for the same source
    fn token_is_on_same_source(&self, token: &LocatedToken) -> bool {
        match &self.current_source {
            Some(current_source) => {
                std::ptr::eq(token.context().source.as_ptr(), current_source.as_ptr())
            }
            None => false
        }
    }

    /// Check if the token is for the same line than the previous token
    fn token_is_on_same_line(&self, token: &LocatedToken) -> bool {
        match &self.current_line_group {
            Some((current_location, _current_line)) => {
                self.token_is_on_same_source(token)
                    && *current_location == token.span().location_line()
            }
            None => false
        }
    }

    fn extract_code(token: &LocatedToken) -> String {
        match token {
            LocatedToken::Standard {
                token: Token::Macro(..),
                span
            } => {
                // 		self.need_to_cut = true;
                span.fragment().to_string()
            }

            _ => {
                // 			self.need_to_cut = false;
                unsafe { std::str::from_utf8_unchecked(token.span().get_line_beginning()) }
                    .to_owned()
            }
        }
    }

    /// Add a token for the current line
    pub fn add_token(
        &mut self,
        token: &LocatedToken,
        bytes: &[u8],
        address: u32,
        address_kind: AddressKind,
        physical_address: PhysicalAddress
    ) {
        if !self.activated {
            return;
        }

        let fname_handling = self.manage_fname(token);

        if !self.token_is_on_same_line(token) {
            self.process_current_line(); // request a display

            // replace the objects of interest
            self.current_source = Some(token.context().source);

            // TODO manage differently for macros and so on
            // let current_line = current_line.split("\n").next().unwrap_or(current_line);
            self.current_line_group =
                Some((token.span().location_line(), Self::extract_code(token)));
            self.current_first_address = address;
            self.current_physical_address = physical_address;
            self.current_address_kind = AddressKind::None;
            self.manage_fname(token);
        }

        self.current_line_bytes.extend_from_slice(bytes);
        self.current_address_kind = if self.current_address_kind == AddressKind::None {
            address_kind
        }
        else if self.current_address_kind != address_kind {
            AddressKind::Mixed
        }
        else {
            address_kind
        };

        if let Some(line) = fname_handling {
            writeln!(self.writer, "{}", line).unwrap();
        }
    }

    pub fn process_current_line(&mut self) {
        // retrieve the line
        let (line_number, line) = match &self.current_line_group {
            Some((idx, line)) => (idx, line),
            None => return
        };

        // build the iterators over the line representation of source code and data
        let mut line_representation = line.split("\n");
        let data_representation = &self
            .current_line_bytes
            .iter()
            .chunks(self.bytes_per_line())
            .into_iter()
            .map(|c| c.map(|b| format!("{:02X}", b)).join(" "))
            .collect_vec();
        let mut data_representation = data_representation.iter();

        // TODO manage missing end of files/blocks if needed

        // draw all line
        let mut idx = 0;
        loop {
            let current_inner_line = line_representation.next();
            let current_inner_data = data_representation.next();

            if current_inner_data.is_none() && current_inner_line.is_none() {
                break;
            }

            let loc_representation = if current_inner_line.is_none() {
                "    ".to_owned()
            }
            else {
                format!("{:04X}", self.current_first_address)
            };

            // Physical address is only printed if it differs from the code address
            let offset = self.current_physical_address.offset_in_cpc();
            let phys_addr_representation =
                if current_inner_line.is_none() || offset == self.current_first_address {
                    "     ".to_owned()
                }
                else {
                    format!("{:05X}{}", offset, self.current_address_kind)
                };

            let line_nb_representation = if current_inner_line.is_none() {
                "    ".to_owned()
            }
            else {
                format!("{:4}", line_number + idx)
            };

            writeln!(
                self.writer,
                "{} {} {} {:bytes_width$} {} ",
                line_nb_representation,
                loc_representation,
                phys_addr_representation,
                current_inner_data.unwrap_or(&"".to_owned()),
                current_inner_line.unwrap_or(""),
                bytes_width = self.bytes_per_line() * 3
            )
            .unwrap();

            idx += 1;
        }

        // cleanup all the fields of the current line
        self.current_line_group = None;
        self.current_source = None;
        self.current_line_bytes.clear();
    }

    pub fn finish(&mut self) {
        self.process_current_line()
    }

    /// Print filename if needed
    pub fn manage_fname(&mut self, token: &LocatedToken) -> Option<String> {
        // 	dbg!(token);

        let ctx = &token.span().extra;
        let fname = ctx
            .filename()
            .map(|p| p.as_os_str().to_str().unwrap().to_string())
            .or_else(|| ctx.context_name().map(|s| s.to_owned()));

        match fname {
            Some(fname) => {
                let print = match self.current_fname.as_ref() {
                    Some(current_fname) => *current_fname != fname,
                    None => true
                };

                if print {
                    self.current_fname = Some(fname.clone());
                    Some(format!("Context: {}", fname))
                }
                else {
                    None
                }
            }
            None => None
        }
    }

    pub fn on(&mut self) {
        self.activated = true;
    }

    pub fn off(&mut self) {
        self.finish();
        self.activated = false;
    }

    pub fn enter_crunched_section(&mut self) {
        self.crunched_section_counter += 1;
    }

    pub fn leave_crunched_section(&mut self) {
        self.crunched_section_counter -= 1;
    }
}

/// This structure collects the necessary information to feed the output
#[derive(Clone)]
pub struct ListingOutputTrigger {
    /// the token read before collecting the bytes
    /// Because each token can have a different lifespan, we store them using a pointer
    pub(crate) token: Option<*const LocatedToken>,
    /// the bytes progressively collected
    pub(crate) bytes: Vec<u8>,
    pub(crate) start: u32,
    pub(crate) physical_address: PhysicalAddress,
    pub(crate) builder: Arc<RwLock<ListingOutput>>
}

unsafe impl Sync for ListingOutputTrigger {}

impl ListingOutputTrigger {
    pub fn write_byte(&mut self, b: u8) {
        self.bytes.push(b);
    }

    pub fn new_token(
        &mut self,
        new: *const LocatedToken,
        code: u32,
        kind: AddressKind,
        physical_address: PhysicalAddress
    ) {
        if let Some(token) = &self.token {
            self.builder.write().unwrap().add_token(
                unsafe { &**token },
                &self.bytes,
                self.start,
                kind,
                self.physical_address
            );
        }

        self.token.replace(new.clone()); // TODO remove that clone that is memory/time eager
        self.bytes.clear();
        self.start = code;
        self.physical_address = physical_address;
    }

    /// Override the address value by the expression result
    /// BUGGY when it is not a number ...
    pub fn replace_code_address(&mut self, address: ExprResult) {
        match address {
            ExprResult::Float(_f) => {}
            ExprResult::Value(v) => self.start = v as _,
            ExprResult::Char(v) => self.start = v as _,
            ExprResult::Bool(b) => self.start = if b { 1 } else { 0 },
            ExprResult::String(s) => self.start = s.len() as _,
            ExprResult::List(l) => self.start = l.len() as _,
            ExprResult::Matrix {
                width,
                height,
                content: _
            } => self.start = (width + height) as _
        }
    }

    pub fn replace_physical_address(&mut self, address: PhysicalAddress) {
        self.physical_address = address;
    }

    pub fn finish(&mut self) {
        if let Some(token) = &self.token {
            self.builder.write().unwrap().add_token(
                unsafe { &**token },
                &self.bytes,
                self.start,
                AddressKind::Address,
                self.physical_address
            );
        }
        self.builder.write().unwrap().finish();
    }

    pub fn on(&mut self) {
        self.builder.write().unwrap().on();
    }

    pub fn off(&mut self) {
        self.builder.write().unwrap().off();
    }

    pub fn enter_crunched_section(&mut self) {
        self.builder.write().unwrap().enter_crunched_section();
    }

    pub fn leave_crunched_section(&mut self) {
        self.builder.write().unwrap().leave_crunched_section();
    }
}