trion 0.7.2

Trion is an assembler designed to be used with the Raspberry Pico (RP2040) microcontroller.
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
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
use core::fmt;
use core::num::NonZeroUsize;
use std::collections::HashMap;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::asm::constant::{Lookup, Realm};
use crate::asm::directive::DirectiveList;
use crate::asm::instr::InstructionSet;
use crate::asm::memory::map::{MemoryMap, PutError, Search};
use crate::text::{Positioned, PosNamed};
use crate::text::parse::{Argument, ElementValue, Parser, ParseErrorKind};

pub mod arcob;
pub mod constant;
pub mod directive;
pub mod instr;
pub mod memory;
pub mod simplify;

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ErrorLevel
{
	Trivial, Fatal,
}

impl ErrorLevel
{
	pub fn should_abort(self) -> bool
	{
		self >= Self::Fatal
	}
}

pub type TaskFn = dyn FnOnce(&mut Context) -> Result<(), ErrorLevel>;

pub struct Context<'l>
{
	path_stack: Vec<PathBuf>,
	curr_name: Arc<String>,
	instructions: &'l dyn InstructionSet,
	directives: &'l DirectiveList,
	output: MemoryMap,
	active: Segment,
	globals: HashMap<String, Option<i64>>,
	locals: Option<HashMap<String, Option<i64>>>,
	global_tasks: Vec<Box<TaskFn>>,
	local_tasks: Option<Vec<Box<TaskFn>>>,
	errors: Vec<Box<PosNamed<dyn Error>>>,
}

impl<'l> Context<'l>
{
	pub fn new(instructions: &'l dyn InstructionSet, directives: &'l DirectiveList) -> Self
	{
		Self
		{
			path_stack: Vec::new(),
			curr_name: Arc::new("<unknown>".to_owned()),
			instructions,
			directives,
			output: MemoryMap::new(),
			active: Segment::Inactive(Vec::new()),
			globals: HashMap::new(),
			locals: None,
			global_tasks: Vec::new(),
			local_tasks: None,
			errors: Vec::new(),
		}
	}
	
	pub fn has_curr_file(&self) -> bool
	{
		!self.path_stack.is_empty()
	}
	
	pub fn curr_file_path(&self) -> Option<&Path>
	{
		self.path_stack.last().map(PathBuf::as_path)
	}
	
	pub fn curr_file_name(&self) -> Arc<String>
	{
		self.curr_name.clone()
	}
	
	pub fn get_instruction_set(&self) -> &'l dyn InstructionSet
	{
		self.instructions
	}
	
	pub fn get_directives(&self) -> &'l DirectiveList
	{
		self.directives
	}
	
	pub fn output(&self) -> &MemoryMap
	{
		&self.output
	}
	
	pub fn output_mut(&mut self) -> &mut MemoryMap
	{
		&mut self.output
	}
	
	pub fn active(&self) -> Option<&ActiveSegment>
	{
		match self.active
		{
			Segment::Empty => unreachable!("empty segment wrapper"),
			Segment::Inactive(..) => None,
			Segment::Active(ref seg) => Some(seg),
		}
	}
	
	pub fn active_mut(&mut self) -> Option<&mut ActiveSegment>
	{
		match self.active
		{
			Segment::Empty => unreachable!("empty segment wrapper"),
			Segment::Inactive(..) => None,
			Segment::Active(ref mut seg) => Some(seg),
		}
	}
	
	pub fn curr_addr(&self) -> Option<u32>
	{
		self.active().map(ActiveSegment::curr_addr)
	}
	
	pub fn change_segment(&mut self, addr: u32) -> Result<bool, SegmentError>
	{
		match self.active
		{
			Segment::Empty => unreachable!("empty segment wrapper"),
			Segment::Active(ref seg) =>
			{
				if addr == seg.base_addr {return Ok(false);}
				self.close_segment()?;
			},
			Segment::Inactive(..) => (),
		}
		let next = self.output.find(addr, Search::Above).map(|r| r.get_first());
		if next.is_some_and(|n| n <= addr)
		{
			// `addr` is within the segment starting at `next` so this is occupied
			return Err(SegmentError::Occupied(addr));
		}
		self.active.make_active(addr, next);
		Ok(true)
	}
	
	pub fn close_segment(&mut self) -> Result<bool, SegmentError>
	{
		match self.active
		{
			Segment::Empty => unreachable!("empty segment wrapper"),
			Segment::Active(ref seg) =>
			{
				match self.output.put(seg.base_addr, seg.buffer.as_ref())
				{
					Ok(n) => assert_eq!(n, seg.buffer.len()),
					Err(e) => return Err(SegmentError::Write(e)),
				}
				self.active.make_inactive();
				Ok(true)
			},
			_ => Ok(false),
		}
	}
	
	pub fn get_constant(&self, name: &str, realm: Realm) -> Lookup
	{
		let constants = match realm
		{
			Realm::Global => &self.globals,
			Realm::Local =>
			{
				match self.locals
				{
					None => panic!("no local scope"),
					Some(ref l) => l,
				}
			},
		};
		match constants.get(name)
		{
			None => Lookup::NotFound,
			Some(None) => Lookup::Deferred,
			Some(&Some(v)) => Lookup::Found(v),
		}
	}
	
	pub fn insert_constant(&mut self, name: &str, value: i64, realm: Realm) -> Result<bool, ConstantError>
	{
		if self.instructions.is_register(name)
		{
			return Err(ConstantError::Reserved(name.to_owned()));
		}
		let constants = match realm
		{
			Realm::Global => &mut self.globals,
			Realm::Local =>
			{
				match self.locals
				{
					None => panic!("no local scope"),
					Some(ref mut l) => l,
				}
			},
		};
		match constants.get_mut(name)
		{
			None =>
			{
				constants.insert(name.to_owned(), Some(value));
				Ok(true)
			},
			Some(dst @ None) =>
			{
				*dst = Some(value);
				Ok(false)
			},
			Some(Some(..)) => Err(ConstantError::Duplicate{name: name.to_owned(), realm}),
		}
	}
	
	pub fn replace_constant(&mut self, name: &str, value: i64, realm: Realm) -> Result<Lookup, ConstantError>
	{
		if self.instructions.is_register(name)
		{
			return Err(ConstantError::Reserved(name.to_owned()));
		}
		let constants = match realm
		{
			Realm::Global => &mut self.globals,
			Realm::Local =>
			{
				match self.locals
				{
					None => panic!("no local scope"),
					Some(ref mut l) => l,
				}
			},
		};
		match constants.get_mut(name)
		{
			None =>
			{
				constants.insert(name.to_owned(), Some(value));
				Ok(Lookup::NotFound)
			},
			Some(dst @ None) =>
			{
				*dst = Some(value);
				Ok(Lookup::Deferred)
			},
			Some(Some(have)) =>
			{
				let prev = *have;
				*have = value;
				Ok(Lookup::Found(prev))
			},
		}
	}
	
	pub fn defer_constant(&mut self, name: &str, realm: Realm) -> Result<(), ConstantError>
	{
		if self.instructions.is_register(name)
		{
			return Err(ConstantError::Reserved(name.to_owned()));
		}
		let constants = match realm
		{
			Realm::Global => &mut self.globals,
			Realm::Local =>
			{
				match self.locals
				{
					None => panic!("no local scope"),
					Some(ref mut l) => l,
				}
			},
		};
		if constants.contains_key(name)
		{
			return Err(ConstantError::Duplicate{name: name.to_owned(), realm});
		}
		constants.insert(name.to_owned(), None);
		Ok(())
	}
	
	fn do_assemble<'s>(&'s mut self, data: &[u8]) -> Result<(), ErrorLevel>
	{
		for element in Parser::new(data)
		{
			let element = match element
			{
				Ok(el) => el,
				Err(e) =>
				{
					self.push_error(e.convert_fn(AsmErrorKind::Parse));
					return Err(ErrorLevel::Fatal);
				},
			};
			
			match element.value
			{
				ElementValue::Directive{name, args} =>
				{
					if let Err(e) = self.directives.process(self, Positioned{line: element.line, col: element.col, value: (name.as_ref(), args)})
					{
						return Err(e);
					}
				},
				ElementValue::Label(ref name) =>
				{
					let curr_addr = match self.active()
					{
						None =>
						{
							self.push_error(element.convert(AsmErrorKind::Inactive));
							return Err(ErrorLevel::Fatal);
						},
						Some(seg) => seg.curr_addr(),
					};
					if let Err(e) = self.insert_constant(name.as_ref(), i64::from(curr_addr), Realm::Local)
					{
						self.push_error(element.convert(e));
						return Err(ErrorLevel::Fatal);
					}
				},
				ElementValue::Instruction{name, args} =>
				{
					if self.active().is_none()
					{
						self.push_error(Positioned{line: element.line, col: element.line, value: AsmErrorKind::Inactive});
						return Err(ErrorLevel::Fatal);
					}
					if let Err(e) = self.assemble_instr(element.line, element.col, name.as_ref(), args)
					{
						return Err(e);
					}
				},
			}
		}
		Ok(())
	}
	
	pub fn assemble(&mut self, data: &[u8], path: PathBuf) -> (Result<(), ErrorLevel>, PathBuf)
	{
		let file_name = Arc::new(path.to_string_lossy().into_owned());
		self.path_stack.push(path);
		let count = NonZeroUsize::try_from(self.path_stack.len()).unwrap();
		let curr_name = core::mem::replace(&mut self.curr_name, file_name);
		let constants = core::mem::replace(&mut self.locals, Some(HashMap::new())).map(|c| core::mem::replace(&mut self.globals, c));
		let tasks = core::mem::replace(&mut self.local_tasks, Some(Vec::new())).map(|t| core::mem::replace(&mut self.global_tasks, t));
		let mut frame = PathFrame{ctx: self, count: Some(count), name: Some(curr_name), constants, tasks};
		let mut result = frame.ctx.do_assemble(data);
		if result != Err(ErrorLevel::Fatal)
		{
			let mut tasks = frame.ctx.local_tasks.replace(Vec::new()).unwrap();
			while !tasks.is_empty()
			{
				for task in tasks.drain(..)
				{
					if let Err(lvl) = task(&mut frame.ctx)
					{
						result = match result
						{
							Ok(()) => Err(lvl),
							Err(old_lvl) => Err(old_lvl.max(lvl)),
						};
						if lvl.should_abort() {break;}
					}
				}
				core::mem::swap(frame.ctx.local_tasks.as_mut().unwrap(), &mut tasks);
				if result.is_err_and(ErrorLevel::should_abort) {break;}
			}
		}
		(result, frame.into_inner())
	}
	
	pub fn assemble_instr(&mut self, line: u32, col: u32, name: &str, args: Vec<Argument>) -> Result<(), ErrorLevel>
	{
		self.instructions.assemble(self, line, col, name, args)
	}
	
	pub fn add_task(&mut self, task: Box<TaskFn>, realm: Realm)
	{
		let tasks = match realm
		{
			Realm::Global => &mut self.global_tasks,
			Realm::Local =>
			{
				match self.local_tasks
				{
					None => panic!("no local scope"),
					Some(ref mut l) => l,
				}
			},
		};
		tasks.push(task);
	}
	
	pub fn finalize(&mut self) -> bool
	{
		let mut abort = false;
		let mut tasks = core::mem::replace(&mut self.global_tasks, Vec::new());
		while !tasks.is_empty()
		{
			for task in tasks.drain(..)
			{
				if task(self).is_err_and(ErrorLevel::should_abort)
				{
					abort = true;
					break;
				}
			}
			core::mem::swap(&mut self.global_tasks, &mut tasks);
			if abort {break;}
		}
		!(abort || self.has_errored())
	}
	
	pub fn has_errored(&self) -> bool
	{
		!self.errors.is_empty()
	}
	
	pub fn get_errors(&self) -> &[Box<PosNamed<dyn Error>>]
	{
		self.errors.as_ref()
	}
	
	pub fn push_error<T: Error + 'static>(&mut self, error: Positioned<T>)
	{
		self.errors.push(Box::new(error.with_name(self.curr_file_name())));
	}
	
	pub fn push_error_in<T: Error + 'static>(&mut self, error: PosNamed<T>)
	{
		self.errors.push(Box::new(error));
	}
}

struct PathFrame<'l, 'c: 'l>
{
	ctx: &'l mut Context<'c>,
	count: Option<NonZeroUsize>,
	name: Option<Arc<String>>,
	constants: Option<HashMap<String, Option<i64>>>,
	tasks: Option<Vec<Box<TaskFn>>>,
}

impl<'l, 'c: 'l> PathFrame<'l, 'c>
{
	pub fn into_inner(mut self) -> PathBuf
	{
		let count = self.count.unwrap();
		assert_eq!(self.ctx.path_stack.len(), count.get());
		let buff = self.ctx.path_stack.pop().unwrap();
		self.ctx.curr_name = self.name.take().unwrap();
		self.ctx.locals = self.constants.take().map(|c| core::mem::replace(&mut self.ctx.globals, c));
		self.ctx.local_tasks = self.tasks.take().map(|t| core::mem::replace(&mut self.ctx.global_tasks, t));
		// this replaces drop as this call takes the value back out
		core::mem::forget(self);
		buff
	}
}

impl<'l, 'c: 'l> Drop for PathFrame<'l, 'c>
{
	fn drop(&mut self)
	{
		if let Some(count) = self.count
		{
			assert!(self.ctx.path_stack.len() == count.get());
			self.ctx.path_stack.pop();
			self.ctx.curr_name = self.name.take().unwrap();
			self.ctx.locals = self.constants.take().map(|c| core::mem::replace(&mut self.ctx.globals, c));
			self.ctx.local_tasks = self.tasks.take().map(|t| core::mem::replace(&mut self.ctx.global_tasks, t));
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SegmentError
{
	Write(PutError),
	Occupied(u32),
	Overflow{need: usize, have: usize},
}

impl fmt::Display for SegmentError
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
	{
		match self
		{
			Self::Write(..) => f.write_str("could not write segment"),
			Self::Occupied(addr) => write!(f, "address {addr:08X} is already occupied"),
			Self::Overflow{need, have} => write!(f, "segment overflow (need {need}, capacity {have})"),
		}
	}
}

impl Error for SegmentError
{
	fn source(&self) -> Option<&(dyn Error + 'static)>
	{
		match self
		{
			Self::Write(e) => Some(e),
			_ => None,
		}
	}
}

#[derive(Debug, Clone)]
enum Segment
{
	Empty,
	Inactive(Vec<u8>), // to avoid re-allocating
	Active(ActiveSegment),
}

impl Segment
{
	pub fn make_active(&mut self, addr: u32, next: Option<u32>)
	{
		let Segment::Inactive(buffer) = core::mem::replace(self, Segment::Empty) else {panic!("segment not inactive");};
		let max_len = match next
		{
			None => usize::try_from(u32::MAX - addr).unwrap_or(usize::MAX).saturating_add(1),
			Some(next) => usize::try_from(next - addr).unwrap_or(usize::MAX),
		};
		*self = Segment::Active(ActiveSegment{base_addr: addr, buffer, max_len})
	}
	
	pub fn make_inactive(&mut self)
	{
		let Segment::Active(mut seg) = core::mem::replace(self, Segment::Empty) else {panic!("segment not active");};
		seg.buffer.clear();
		*self = Segment::Inactive(seg.buffer);
	}
}

#[derive(Debug, Clone)]
pub struct ActiveSegment
{
	base_addr: u32,
	buffer: Vec<u8>,
	max_len: usize,
}

impl ActiveSegment
{
	pub fn base_addr(&self) -> u32
	{
		self.base_addr
	}
	
	pub fn curr_addr(&self) -> u32
	{
		// for segments that go up to the end of address space
		self.base_addr.saturating_add(self.buffer.len() as u32)
	}
	
	pub fn remaining(&self) -> usize
	{
		self.max_len - self.buffer.len()
	}
	
	pub fn has_remaining(&self, len: usize) -> bool
	{
		len <= self.remaining()
	}
	
	pub fn write(&mut self, data: &[u8]) -> Result<(), SegmentError>
	{
		if self.has_remaining(data.len())
		{
			self.buffer.extend_from_slice(data);
			Ok(())
		}
		else
		{
			Err(SegmentError::Overflow{need: data.len(), have: self.remaining()})
		}
	}
	
	pub fn write_at(&mut self, addr: u32, data: &[u8]) -> Result<(), SegmentError>
	{
		assert!(addr >= self.base_addr && addr <= self.curr_addr());
		// safe cast because `Self::curr_addr` uses the buffer's length (usize)
		let start = (addr - self.base_addr) as usize;
		if self.buffer.len() - start < data.len()
		{
			let overwrite = self.buffer.len() - start;
			if !self.has_remaining(overwrite)
			{
				return Err(SegmentError::Overflow{need: data.len() - overwrite, have: self.remaining()});
			}
			// mixed overwrite & append, truncate to simplify into only appending
			self.buffer.truncate(start);
			self.buffer.extend_from_slice(data);
		}
		else if start < self.buffer.len()
		{
			// all contained within the buffer, overwrite only
			self.buffer[start..start + data.len()].copy_from_slice(data);
		}
		else
		{
			// all appended to the buffer, no overwrite
			self.buffer.extend_from_slice(data);
		}
		Ok(())
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ConstantError
{
	Reserved(String),
	NotFound{name: String, realm: Realm},
	Duplicate{name: String, realm: Realm},
	Range{min: i64, max: i64, have: i64},
	Alignment{align: u32, have: i64},
}

impl fmt::Display for ConstantError
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
	{
		match *self
		{
			Self::Reserved(ref name) => write!(f, "reserved name {name:?}"),
			Self::NotFound{ref name, realm} => write!(f, "no such {realm} constant {name:?}"),
			Self::Duplicate{ref name, realm} => write!(f, "duplicate {realm} constant {name}"),
			Self::Range{min, max, have} => write!(f, "label out of range ({min} to {max}, got {have})"),
			Self::Alignment{align, have} => write!(f, "misaligned label (expect {align}, got {have})"),
		}
	}
}

impl Error for ConstantError {}

pub type AssembleError = Positioned<AsmErrorKind>;

#[derive(Debug)]
pub enum AsmErrorKind
{
	Parse(ParseErrorKind),
	Inactive,
}

impl fmt::Display for AsmErrorKind
{
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
	{
		match self
		{
			Self::Parse(..) => f.write_str("parsing failed"),
			Self::Inactive => f.write_str("no active segment"),
		}
	}
}

impl Error for AsmErrorKind
{
	fn source(&self) -> Option<&(dyn Error + 'static)>
	{
		match self
		{
			Self::Parse(e) => Some(e),
			_ => None,
		}
	}
}