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
pub mod parser;
pub mod tokens;
use std::fmt::{self};
use cpclib_common::nom::error::convert_error;
use cpclib_common::nom::{self};
use cpclib_sna::Snapshot;
use failure::Fail;
use parser::parse_basic_program;
use tokens::BasicToken;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BasicProgramLineIdx {
Index(usize),
Number(u16)
}
#[derive(Debug, Fail, PartialEq, Clone)]
#[allow(missing_docs)]
pub enum BasicError {
#[fail(display = "Line does not exist: {:?}", idx)]
UnknownLine { idx: BasicProgramLineIdx },
#[fail(display = "{}", msg)]
ParseError { msg: String },
#[fail(display = "Exponent Overflow")]
ExponentOverflow
}
#[derive(Debug, Clone)]
pub struct BasicLine {
line_number: u16,
tokens: Vec<BasicToken>,
forced_length: Option<u16>
}
impl fmt::Display for BasicLine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ", self.line_number)?;
for token in self.tokens().iter() {
write!(f, "{}", token)?;
}
Ok(())
}
}
#[allow(missing_docs)]
impl BasicLine {
pub fn line_number(&self) -> u16 {
self.line_number
}
pub fn new(line_number: u16, tokens: &[BasicToken]) -> Self {
Self {
line_number,
tokens: tokens.to_vec(),
forced_length: None
}
}
pub fn add_length(&mut self, length: u16) {
let current = self.forced_length();
self.set_length(current + length);
}
pub fn set_length(&mut self, length: u16) {
self.forced_length = Some(length);
}
pub fn forced_length(&self) -> u16 {
match self.forced_length {
Some(val) => val,
None => (self.real_length() + 2 + 2 + 1)
}
}
pub fn real_length(&self) -> u16 {
self.tokens_as_bytes().len() as _
}
pub fn len(&self) -> usize {
self.tokens().len()
}
pub fn is_empty(&self) -> bool {
self.tokens().is_empty()
}
pub fn tokens_as_bytes(&self) -> Vec<u8> {
self.tokens
.iter()
.flat_map(BasicToken::as_bytes)
.collect::<Vec<u8>>()
}
pub fn as_bytes(&self) -> Vec<u8> {
let size = self.forced_length();
let mut content = vec![
(size % 256) as u8,
(size / 256) as u8,
(self.line_number % 256) as u8,
(self.line_number / 256) as u8,
];
content.extend_from_slice(&self.tokens_as_bytes());
content.push(0);
content
}
pub fn tokens(&self) -> &[BasicToken] {
&self.tokens
}
}
#[derive(Debug, Clone)]
pub struct BasicProgram {
lines: Vec<BasicLine>
}
impl fmt::Display for BasicProgram {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for line in &self.lines {
writeln!(f, "{}", line)?;
}
Ok(())
}
}
#[allow(missing_docs)]
impl BasicProgram {
pub fn new(lines: Vec<BasicLine>) -> Self {
Self { lines }
}
pub fn parse<S: AsRef<str>>(code: S) -> Result<Self, BasicError> {
let input = code.as_ref().into();
match parse_basic_program(input) {
Ok((res, prog)) => {
if res.trim().is_empty() {
Ok(prog)
}
else {
Err(BasicError::ParseError {
msg: format!("Basic content has not been totally parsed: `{}`", res)
})
}
}
Err(nom::Err::Error(e) | nom::Err::Failure(e)) => {
Err(BasicError::ParseError {
msg: format!(
"Error while parsing the Basic content: {}",
convert_error(input, e)
)
})
}
_ => unreachable!()
}
}
pub fn add_line(&mut self, line: BasicLine) {
self.lines.push(line);
}
pub fn get_line_mut(&mut self, idx: BasicProgramLineIdx) -> Option<&mut BasicLine> {
match self.line_idx_as_valid_index(idx) {
Ok(BasicProgramLineIdx::Index(index)) => self.lines.get_mut(index),
_ => None
}
}
pub fn get_line(&mut self, idx: BasicProgramLineIdx) -> Option<&BasicLine> {
match self.line_idx_as_valid_index(idx) {
Ok(BasicProgramLineIdx::Index(index)) => self.lines.get(index),
_ => None
}
}
pub fn is_first_line(&self, idx: BasicProgramLineIdx) -> bool {
match self.line_idx_as_valid_index(idx) {
Ok(BasicProgramLineIdx::Index(0)) => true,
_ => false
}
}
pub fn previous_idx(&self, idx: BasicProgramLineIdx) -> Option<BasicProgramLineIdx> {
match self.line_idx_as_valid_index(idx) {
Ok(BasicProgramLineIdx::Index(index)) => {
if index == 0 {
None
}
else {
Some(BasicProgramLineIdx::Index(index - 1))
}
}
Err(_e) => None,
_ => unreachable!()
}
}
pub fn has_line(&self, idx: BasicProgramLineIdx) -> bool {
self.line_idx_as_valid_index(idx).is_ok()
}
fn line_idx_as_valid_index(
&self,
idx: BasicProgramLineIdx
) -> Result<BasicProgramLineIdx, BasicError> {
match &idx {
BasicProgramLineIdx::Index(index) => {
if self.lines.len() <= *index {
Err(BasicError::UnknownLine { idx })
}
else {
Ok(idx)
}
}
BasicProgramLineIdx::Number(number) => {
match self.get_index_of_line_number(*number) {
Some(index) => Ok(BasicProgramLineIdx::Index(index)),
None => Err(BasicError::UnknownLine { idx })
}
}
}
}
fn get_index_of_line_number(&self, number: u16) -> Option<usize> {
self.lines
.iter()
.enumerate()
.filter_map(move |(index, line)| {
if line.line_number == number {
Some(index)
}
else {
None
}
})
.collect::<Vec<_>>()
.first()
.cloned()
}
pub fn hide_line(&mut self, idx: BasicProgramLineIdx) -> Result<(), BasicError> {
if !self.has_line(idx) {
Err(BasicError::UnknownLine { idx })
}
else if self.is_first_line(idx) {
self.lines[0].line_number = 0;
Ok(())
}
else {
match self.previous_idx(idx) {
Some(previous_idx) => {
let current_length = self.get_line(idx).unwrap().real_length();
self.get_line_mut(previous_idx)
.unwrap()
.add_length(current_length + 1 + 2 + 2);
self.get_line_mut(idx).unwrap().set_length(0);
Ok(())
}
None => Err(BasicError::UnknownLine { idx })
}
}
}
pub fn hide_lines(&mut self, lines: &[u16]) -> Result<(), BasicError> {
match lines.len() {
0 => Ok(()),
1 => self.hide_line(BasicProgramLineIdx::Number(lines[0])),
_ => unimplemented!("The current version is only able to hide one line. I can still implement multiline version if needed")
}
}
pub fn as_bytes(&self) -> Vec<u8> {
let mut bytes = self
.lines
.iter()
.flat_map(BasicLine::as_bytes)
.collect::<Vec<u8>>();
bytes.resize(bytes.len() + 3, 0);
bytes
}
pub fn as_sna(&self) -> Result<Snapshot, String> {
let bytes = self.as_bytes();
let mut sna = Snapshot::new_6128()?;
sna.unwrap_memory_chunks();
sna.add_data(&bytes, 0x170)
.map_err(|e| format!("{:?}", e))?;
Ok(sna)
}
}
#[allow(clippy::let_unit_value)]
#[allow(clippy::shadow_unrelated)]
#[cfg(test)]
pub mod test {
use super::*;
#[test]
fn parse_complete() {
let code = "10 call &0: call &0\n";
BasicProgram::parse(code).expect("Unable to produce basic tokens");
let code1 = "10 call &0: call &0";
BasicProgram::parse(code1).expect("Unable to produce basic tokens");
let code2 = "10 ' blabla bla\n20 ' blab bla bal\n30 call &180";
BasicProgram::parse(code2).expect("Unable to produce basic tokens");
}
#[test]
fn parse_correct() {
let code = "10 CALL &1234";
let prog = BasicProgram::parse(code).unwrap();
let bytes = prog.as_bytes();
let expected = [10, 0, 10, 0, 131, 32, 28, 0x34, 0x12, 0, 0, 0, 0];
assert_eq!(&bytes, &expected);
let code = "10 CALL &1234\n20 CALL &1234";
let prog = BasicProgram::parse(code).unwrap();
let bytes = prog.as_bytes();
let expected = [
10, 0, 10, 0, 131, 32, 28, 0x34, 0x12, 0, 10, 0, 20, 0, 131, 32, 28, 0x34, 0x12, 0, 0,
0, 0
];
assert_eq!(&bytes, &expected);
}
#[test]
fn hide1() {
let code = "10 CALL &1234";
let mut prog = BasicProgram::parse(code).unwrap();
prog.hide_line(BasicProgramLineIdx::Number(10)).unwrap();
let bytes = prog.as_bytes();
let expected = vec![10, 0, 0, 0, 131, 32, 28, 0x34, 0x12, 0, 0, 0, 0];
assert_eq!(bytes, expected);
}
#[test]
fn indices() {
let code = "10 CALL &1234\n20 CALL &1234";
let prog = BasicProgram::parse(code).unwrap();
assert_eq!(
Ok(BasicProgramLineIdx::Index(0)),
prog.line_idx_as_valid_index(BasicProgramLineIdx::Index(0))
);
assert_eq!(
Ok(BasicProgramLineIdx::Index(1)),
prog.line_idx_as_valid_index(BasicProgramLineIdx::Index(1))
);
assert_eq!(
Err(BasicError::UnknownLine {
idx: BasicProgramLineIdx::Index(2)
}),
prog.line_idx_as_valid_index(BasicProgramLineIdx::Index(2))
);
assert_eq!(
Some(BasicProgramLineIdx::Index(0)),
prog.previous_idx(BasicProgramLineIdx::Index(1))
);
assert_eq!(None, prog.previous_idx(BasicProgramLineIdx::Index(0)));
assert!(prog.has_line(BasicProgramLineIdx::Number(10)));
assert!(prog.has_line(BasicProgramLineIdx::Number(20)));
assert!(!prog.has_line(BasicProgramLineIdx::Number(30)));
assert!(prog.has_line(BasicProgramLineIdx::Index(0)));
assert!(prog.has_line(BasicProgramLineIdx::Index(1)));
assert!(!prog.has_line(BasicProgramLineIdx::Index(2)));
}
#[test]
fn hide2() {
let code = "10 CALL &1234\n20 CALL &1234";
let mut prog = BasicProgram::parse(code).unwrap();
assert!(prog.has_line(BasicProgramLineIdx::Number(20)));
prog.hide_line(BasicProgramLineIdx::Number(20)).unwrap();
let bytes = prog.as_bytes();
let expected = vec![
20, 0, 10, 0, 131, 32, 28, 0x34, 0x12, 0, 00, 0, 20, 0, 131, 32, 28, 0x34, 0x12, 0, 0,
0, 0,
];
assert_eq!(bytes, expected);
}
}