-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterp.rs
1275 lines (1085 loc) · 40.3 KB
/
interp.rs
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! TODO!
use super::mem_mapped::{MemMapped, MemMappedSpecial /*, BSP, PSR*/, MCR};
use lc3_isa::{
Addr, Instruction,
Reg::{self, *},
Word, ACCESS_CONTROL_VIOLATION_EXCEPTION_VECTOR, ILLEGAL_OPCODE_EXCEPTION_VECTOR,
INTERRUPT_VECTOR_TABLE_START_ADDR, MEM_MAPPED_START_ADDR,
PRIVILEGE_MODE_VIOLATION_EXCEPTION_VECTOR, TRAP_VECTOR_TABLE_START_ADDR,
USER_PROGRAM_START_ADDR,
};
use lc3_traits::control::metadata::{Identifier, ProgramMetadata, Version, version_from_crate};
use lc3_traits::control::load::{PageIndex, PAGE_SIZE_IN_WORDS};
use lc3_traits::control::control::MAX_CALL_STACK_DEPTH;
use lc3_traits::peripherals::{gpio::GpioPinArr, timers::TimerArr};
use lc3_traits::{memory::Memory, peripherals::Peripherals};
use lc3_traits::peripherals::{gpio::Gpio, input::Input, output::Output, timers::Timers};
use lc3_traits::error::Error;
use crate::mem_mapped::Interrupt;
use core::any::TypeId;
use core::convert::TryInto;
use core::marker::PhantomData;
use core::ops::{Index, IndexMut};
use core::sync::atomic::AtomicBool;
use core::ops::{Deref, DerefMut};
use core::cell::Cell;
// TODO: Break up this file!
// TODO: name?
pub trait InstructionInterpreterPeripheralAccess<'a>:
InstructionInterpreter + Deref + DerefMut
where
<Self as Deref>::Target: Peripherals<'a>,
{
fn get_peripherals(&self) -> &<Self as Deref>::Target {
self.deref()
}
fn get_peripherals_mut(&mut self) -> &mut <Self as Deref>::Target {
self.deref_mut()
}
fn get_device_reg<M: MemMapped>(&self) -> Result<M, Acv> {
M::from(self)
}
fn set_device_reg<M: MemMapped>(&mut self, value: Word) -> WriteAttempt {
M::set(self, value)
}
fn update_device_reg<M: MemMapped>(&mut self, func: impl FnOnce(M) -> Word) -> WriteAttempt {
M::update(self, func)
}
fn get_special_reg<M: MemMappedSpecial>(&self) -> M {
M::from_special(self)
}
fn set_special_reg<M: MemMappedSpecial>(&mut self, value: Word) {
M::set_special(self, value)
}
fn update_special_reg<M: MemMappedSpecial>(&mut self, func: impl FnOnce(M) -> Word) {
M::update(self, func).unwrap()
}
fn reset_peripherals(&mut self) {
use lc3_traits::peripherals::gpio::{GPIO_PINS, GpioState};
use lc3_traits::peripherals::adc::{Adc, ADC_PINS, AdcState};
use lc3_traits::peripherals::pwm::{Pwm, PWM_PINS, PwmState};
use lc3_traits::peripherals::timers::{TIMERS, TimerMode, TimerState};
use lc3_traits::peripherals::clock::Clock;
// TODO: do something with errors here?
for pin in GPIO_PINS.iter() {
let _ = Gpio::set_state(self.get_peripherals_mut(), *pin, GpioState::Disabled);
Gpio::reset_interrupt_flag(self.get_peripherals_mut(), *pin);
}
for pin in ADC_PINS.iter() {
let _ = Adc::set_state(self.get_peripherals_mut(), *pin, AdcState::Disabled);
}
for pin in PWM_PINS.iter() {
Pwm::set_state(self.get_peripherals_mut(), *pin, PwmState::Disabled);
Pwm::set_duty_cycle(self.get_peripherals_mut(), *pin, 0);
}
for id in TIMERS.iter() {
Timers::set_mode(self.get_peripherals_mut(), *id, TimerMode::SingleShot);
Timers::set_state(self.get_peripherals_mut(), *id, TimerState::Disabled);
Timers::reset_interrupt_flag(self.get_peripherals_mut(), *id);
}
Clock::set_milliseconds(self.get_peripherals_mut(), 0);
Input::reset_interrupt_flag(self.get_peripherals_mut());
Output::reset_interrupt_flag(self.get_peripherals_mut());
}
}
pub trait InstructionInterpreter:
Index<Reg, Output = Word> + IndexMut<Reg, Output = Word> + Sized
{
const ID: Identifier = Identifier::new_from_str_that_crashes_on_invalid_inputs("Insn");
const VER: Version = Version::empty()
.pre_from_str_that_crashes_on_invalid_inputs("????");
fn step(&mut self) -> MachineState;
fn set_pc(&mut self, addr: Addr);
fn get_pc(&self) -> Addr;
// Checked access:
fn set_word(&mut self, addr: Addr, word: Word) -> WriteAttempt;
fn get_word(&self, addr: Addr) -> ReadAttempt;
fn set_word_unchecked(&mut self, addr: Addr, word: Word);
fn get_word_unchecked(&self, addr: Addr) -> Word;
fn set_word_force_memory_backed(&mut self, addr: Addr, word: Word);
fn get_word_force_memory_backed(&self, addr: Addr) -> Word;
fn get_register(&self, reg: Reg) -> Word { self[reg] }
fn set_register(&mut self, reg: Reg, word: Word) { self[reg] = word; }
fn get_machine_state(&self) -> MachineState;
fn reset(&mut self);
fn halt(&mut self); // TODO: have the MCR set this, etc.
fn set_error(&self, err: Error);
fn get_error(&self) -> Option<Error>;
fn get_call_stack(&self) -> [Option<(Addr, ProcessorMode)>; MAX_CALL_STACK_DEPTH];
fn get_call_stack_depth(&self) -> u64;
// Taken straight from Memory:
fn commit_page(&mut self, page_idx: PageIndex, page: &[Word; PAGE_SIZE_IN_WORDS as usize]);
fn get_program_metadata(&self) -> ProgramMetadata;
fn set_program_metadata(&mut self, metadata: ProgramMetadata);
// Until TypeId::of is a const function, this can't be an associated const:
fn type_id() -> TypeId { core::any::TypeId::of::<Instruction>() }
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Acv;
pub type ReadAttempt = Result<Word, Acv>;
pub type WriteAttempt = Result<(), Acv>;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum MachineState {
Running,
Halted,
}
impl MachineState {
const fn new() -> Self {
MachineState::Halted
}
}
impl Default for MachineState {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub struct PeripheralInterruptFlags {
gpio: GpioPinArr<AtomicBool>, // No payload; just tell us if a rising edge has happened
// adc: AdcPinArr<bool>, // We're not going to have Adc Interrupts
// pwm: PwmPinArr<bool>, // No Pwm Interrupts
timers: TimerArr<AtomicBool>, // No payload; timers don't actually expose counts anyways
// clock: bool, // No Clock Interrupt
input: AtomicBool, // No payload; check KBDR for the current character
output: AtomicBool, // Technically this has an interrupt, but I have no idea why; UPDATE: it interrupts when it's ready to accept more data
// display: bool, // Unless we're exposing vsync/hsync or something, this doesn't need an interrupt
}
impl PeripheralInterruptFlags {
pub const fn new() -> Self {
macro_rules! b {
() => {
AtomicBool::new(false)
};
}
// TODO: make this less gross..
Self {
gpio: GpioPinArr([b!(), b!(), b!(), b!(), b!(), b!(), b!(), b!()]),
timers: TimerArr([b!(), b!()]),
input: AtomicBool::new(false),
output: AtomicBool::new(false),
}
}
}
impl Default for PeripheralInterruptFlags {
fn default() -> Self {
Self::new()
}
}
// TODO: Either find a `core` replacement for this or pull it out into a `util`
// mod or something.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone)]
pub enum OwnedOrRef<'a, T> {
Owned(T),
Ref(&'a T),
}
impl<T: Default> Default for OwnedOrRef<'_, T> {
fn default() -> Self {
Self::Owned(Default::default())
}
}
impl<T> Deref for OwnedOrRef<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
use OwnedOrRef::*;
match self {
Owned(inner) => inner,
Ref(inner) => inner,
}
}
}
// impl<T> DerefMut for OwnedOrRef<'_, T> {
// fn deref_mut(&mut self) -> &mut Self::Target {
// use OwnedOrRef::*;
// match self {
// Owned(inner) => inner,
// Ref(inner) => inner,
// }
// }
// }
#[derive(Debug)]
pub struct CallStack {
stack: [Option<(Addr, ProcessorMode)>; MAX_CALL_STACK_DEPTH],
depth: u64,
}
impl CallStack {
pub const fn new() -> Self {
Self {
stack: [None; MAX_CALL_STACK_DEPTH],
depth: 0,
}
}
// Push subroutine address to call stack if stack is not full
// Always increments depth
// -> true if pushed, false otherwise
pub fn push(&mut self, subroutine: Addr, in_user_mode: bool) -> bool {
let mut success = false;
// Check if stack is not full
if self.depth < MAX_CALL_STACK_DEPTH as u64 {
let processor_mode = if in_user_mode {ProcessorMode::User} else {ProcessorMode::Supervisor};
self.stack[self.depth as usize] = Some((subroutine, processor_mode));
success = true;
}
// Increment depth
self.depth = match self.depth.checked_add(1) {
Some(val) => val,
None => panic!("Overflowed depth of call stack!"),
};
success
}
// Pop subroutine address off of call stack if top of stack matches current depth
// Always decrements depth
// -> true if popped, false otherwise
pub fn pop(&mut self) -> bool {
let mut success = false;
// Decrement depth, saturates at 0 (unsigned)
self.depth = self.depth.saturating_sub(1);
// Check if depth exceeds max saved addrs
if self.depth < MAX_CALL_STACK_DEPTH as u64 {
self.stack[self.depth as usize] = None;
success = true;
}
success
}
}
// #[derive(Debug, Default, Clone)] // TODO: Clone
#[derive(Debug)]
pub struct Interpreter<'per, M: Memory, P: Peripherals<'per>> {
memory: M,
peripherals: P,
// flags: OwnedOrRef<'a, PeripheralInterruptFlags>,
flags: PhantomData<OwnedOrRef<'per, PeripheralInterruptFlags>>,
regs: [Word; Reg::NUM_REGS],
pc: Word, //TODO: what should the default for this be
state: MachineState,
error: Cell<Option<Error>>,
call_stack: CallStack,
}
impl<'a, M: Memory + Default, P: Peripherals<'a>> Default for Interpreter<'a, M, P> {
fn default() -> Self {
InterpreterBuilder::new()
.with_defaults()
.build()
}
}
#[derive(Debug)]
pub struct Set;
#[derive(Debug)]
pub struct NotSet;
#[derive(Debug)]
struct InterpreterBuilderData<'a, M: Memory, P>
where
P: Peripherals<'a>,
{
memory: Option<M>,
peripherals: Option<P>,
flags: Option<OwnedOrRef<'a, PeripheralInterruptFlags>>,
regs: Option<[Word; Reg::NUM_REGS]>,
pc: Option<Word>,
state: Option<MachineState>,
}
#[derive(Debug)]
pub struct InterpreterBuilder<
'a,
M: Memory,
P,
Mem = NotSet,
Perip = NotSet,
Flags = NotSet,
Regs = NotSet,
Pc = NotSet,
State = NotSet,
> where
P: Peripherals<'a>,
{
data: InterpreterBuilderData<'a, M, P>,
_mem: PhantomData<&'a Mem>,
_perip: PhantomData<&'a Perip>,
_flags: PhantomData<&'a Flags>,
_regs: PhantomData<&'a Regs>,
_pc: PhantomData<&'a Pc>,
_state: PhantomData<&'a State>,
}
impl<'a, M: Memory, P, Mem, Perip, Flags, Regs, Pc, State>
InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, State>
where
P: Peripherals<'a>,
{
fn with_data(data: InterpreterBuilderData<'a, M, P>) -> Self {
Self {
data,
_mem: PhantomData,
_perip: PhantomData,
_flags: PhantomData,
_regs: PhantomData,
_pc: PhantomData,
_state: PhantomData,
}
}
}
impl<'a, M: Memory, P> InterpreterBuilder<'a, M, P, NotSet, NotSet, NotSet, NotSet, NotSet, NotSet>
where
P: Peripherals<'a>,
{
pub fn new() -> Self {
Self {
data: InterpreterBuilderData {
memory: None,
peripherals: None,
flags: None,
regs: None,
pc: None,
state: None,
},
_mem: PhantomData,
_perip: PhantomData,
_flags: PhantomData,
_regs: PhantomData,
_pc: PhantomData,
_state: PhantomData,
}
}
}
impl<'a, M: Memory + Default, P, Mem, Perip, Flags, Regs, Pc, State>
InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, State>
where
P: Peripherals<'a>,
{
pub fn with_defaults(self) -> InterpreterBuilder<'a, M, P, Set, Set, Set, Set, Set, Set> {
InterpreterBuilder::with_data(InterpreterBuilderData {
memory: Some(Default::default()),
peripherals: Some(Default::default()),
flags: Some(Default::default()),
regs: Some(Default::default()),
pc: Some(Default::default()),
state: Some(Default::default()),
})
}
}
// impl<'a, M: Memory, P, Perip, Flags, Regs, Pc, State> InterpreterBuilder<'a, M, P, NotSet, Perip, Flags, Regs, Pc, State>
impl<'a, M: Memory, P, Mem, Perip, Flags, Regs, Pc, State>
InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, State>
where
P: Peripherals<'a>,
{
pub fn with_memory(
self,
memory: M,
) -> InterpreterBuilder<'a, M, P, Set, Perip, Flags, Regs, Pc, State> {
InterpreterBuilder::with_data(InterpreterBuilderData {
memory: Some(memory),
..self.data
})
}
}
// impl<'a, M: Memory + Default, P, Perip, Flags, Regs, Pc, State> InterpreterBuilder<'a, M, P, NotSet, Perip, Flags, Regs, Pc, State>
impl<'a, M: Memory + Default, P, Mem, Perip, Flags, Regs, Pc, State>
InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, State>
where
P: Peripherals<'a>,
{
pub fn with_default_memory(
self,
) -> InterpreterBuilder<'a, M, P, Set, Perip, Flags, Regs, Pc, State> {
self.with_memory(Default::default())
}
}
// impl<'a, M: Memory, P, Mem, Flags, Regs, Pc, State> InterpreterBuilder<'a, M, P, Mem, NotSet, Flags, Regs, Pc, State>
impl<'a, M: Memory, P, Mem, Perip, Flags, Regs, Pc, State>
InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, State>
where
P: Peripherals<'a>,
{
pub fn with_peripherals(
self,
peripherals: P,
) -> InterpreterBuilder<'a, M, P, Mem, Set, Flags, Regs, Pc, State> {
InterpreterBuilder::with_data(InterpreterBuilderData {
peripherals: Some(peripherals),
..self.data
})
}
pub fn with_default_peripherals(
self,
) -> InterpreterBuilder<'a, M, P, Mem, Set, Flags, Regs, Pc, State> {
self.with_peripherals(Default::default())
}
}
// impl<'a, M: Memory, P, Mem, Perip, Regs, Pc, State> InterpreterBuilder<'a, M, P, Mem, Perip, NotSet, Regs, Pc, State>
impl<'a, M: Memory, P, Mem, Perip, Flags, Regs, Pc, State>
InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, State>
where
P: Peripherals<'a>,
{
pub fn with_interrupt_flags_by_ref(
self,
flags: &'a PeripheralInterruptFlags,
) -> InterpreterBuilder<'a, M, P, Mem, Perip, Set, Regs, Pc, State> {
InterpreterBuilder::with_data(InterpreterBuilderData {
flags: Some(OwnedOrRef::Ref(&flags)),
..self.data
})
}
pub fn with_owned_interrupt_flags(
self,
flags: PeripheralInterruptFlags,
) -> InterpreterBuilder<'a, M, P, Mem, Perip, Set, Regs, Pc, State> {
InterpreterBuilder::with_data(InterpreterBuilderData {
flags: Some(OwnedOrRef::Owned(flags)),
..self.data
})
}
pub fn with_default_interrupt_flags(
self,
) -> InterpreterBuilder<'a, M, P, Mem, Perip, Set, Regs, Pc, State> {
self.with_owned_interrupt_flags(Default::default())
}
}
// TODO: do we want to allow people to set the starting register values?
// impl<'a, M: Memory, P, Mem, Perip, Flags, Pc, State> InterpreterBuilder<'a, M, P, Mem, Perip, Flags, NotSet, Pc, State>
impl<'a, M: Memory, P, Mem, Perip, Flags, Regs, Pc, State>
InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, State>
where
P: Peripherals<'a>,
{
pub fn with_regs(
self,
regs: [Word; Reg::NUM_REGS],
) -> InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Set, Pc, State> {
InterpreterBuilder::with_data(InterpreterBuilderData {
regs: Some(regs),
..self.data
})
}
pub fn with_default_regs(
self,
) -> InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Set, Pc, State> {
self.with_regs(Default::default())
}
}
// TODO: do we want to allow people to set the starting pc?
// impl<'a, M: Memory, P, Mem, Perip, Flags, Regs, State> InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, NotSet, State>
impl<'a, M: Memory, P, Mem, Perip, Flags, Regs, Pc, State>
InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, State>
where
P: Peripherals<'a>,
{
pub fn with_pc(
self,
pc: Word,
) -> InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Set, State> {
InterpreterBuilder::with_data(InterpreterBuilderData {
pc: Some(pc),
..self.data
})
}
pub fn with_default_pc(
self,
) -> InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Set, State> {
self.with_pc(Default::default())
}
}
// TODO: do we want to allow people to set the starting machine state?
// impl<'a, M: Memory, P, Mem, Perip, Flags, Regs, Pc> InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, NotSet>
impl<'a, M: Memory, P, Mem, Perip, Flags, Regs, Pc, State>
InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, State>
where
P: Peripherals<'a>,
{
pub fn with_state(
self,
state: MachineState,
) -> InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, Set> {
InterpreterBuilder::with_data(InterpreterBuilderData {
state: Some(state),
..self.data
})
}
pub fn with_default_state(
self,
) -> InterpreterBuilder<'a, M, P, Mem, Perip, Flags, Regs, Pc, Set> {
self.with_state(Default::default())
}
}
impl<'a, M: Memory, P> InterpreterBuilder<'a, M, P, Set, Set, Set, Set, Set, Set>
where
P: Peripherals<'a>,
{
pub fn build(self) -> Interpreter<'a, M, P> {
Interpreter::new(
self.data.memory.unwrap(),
self.data.peripherals.unwrap(),
self.data.flags.unwrap(),
self.data.regs.unwrap(),
self.data.pc.unwrap(),
self.data.state.unwrap(),
)
}
}
impl<'a, M: Memory, P: Peripherals<'a>> Interpreter<'a, M, P> {
pub fn new(
memory: M,
peripherals: P,
flags: OwnedOrRef<'a, PeripheralInterruptFlags>,
regs: [Word; Reg::NUM_REGS],
pc: Word,
state: MachineState,
) -> Self {
// TODO: propagate flags to the peripherals!
// TODO: maybe eventually don't even hold flags; just pass it along
let mut interp = Self {
memory,
peripherals,
flags: PhantomData,
regs,
pc,
state,
error: Cell::new(None),
call_stack: CallStack::new(),
};
// TODO: we can't call this.
// This is a problem; we need to drop the `flags` field from `Interpreter` and
// make the builder ensure that flags (that live long enough) are actually
// passed in.
//
// Or rather we can have the flags field be of type
// `&'a PeripheralInterruptFlags`; the Default impl can use Box::leak to provide
// this.
//
// interp.init(&interp.flags);
// For now, the following workaround:
if let OwnedOrRef::Ref(r) = flags {
interp.init(r);
} else {
// warn!("unsupported, sorry!");
// TODO: let's just do this instead of using OwnedOrRef.
// at some point we should just strip out all of the OwnedOrRef stuff.
static INTERNAL_INACCESSIBLE_PERIPHERAL_FLAGS: PeripheralInterruptFlags = PeripheralInterruptFlags::new();
interp.init(&INTERNAL_INACCESSIBLE_PERIPHERAL_FLAGS);
}
interp.reset(); // TODO: remove pc/regs options from the interpreter builder
interp
}
}
impl<'a, M: Memory, P: Peripherals<'a>> Index<Reg> for Interpreter<'a, M, P> {
type Output = Word;
fn index(&self, reg: Reg) -> &Self::Output {
&self.regs[TryInto::<usize>::try_into(Into::<u8>::into(reg)).unwrap()]
}
}
impl<'a, M: Memory, P: Peripherals<'a>> IndexMut<Reg> for Interpreter<'a, M, P> {
fn index_mut(&mut self, reg: Reg) -> &mut Self::Output {
&mut self.regs[TryInto::<usize>::try_into(Into::<u8>::into(reg)).unwrap()]
}
}
impl<'a, M: Memory, P: Peripherals<'a>> Deref for Interpreter<'a, M, P> {
type Target = P;
fn deref(&self) -> &Self::Target {
&self.peripherals
}
}
impl<'a, M: Memory, P: Peripherals<'a>> DerefMut for Interpreter<'a, M, P> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.peripherals
}
}
impl<'a, M: Memory, P: Peripherals<'a>> InstructionInterpreterPeripheralAccess<'a>
for Interpreter<'a, M, P>
{ }
impl<'a, M: Memory, P: Peripherals<'a>> Interpreter<'a, M, P> {
pub fn init(&mut self, flags: &'a PeripheralInterruptFlags) {
Gpio::<'a>::register_interrupt_flags(&mut self.peripherals, &flags.gpio);
Timers::<'a>::register_interrupt_flags(&mut self.peripherals, &flags.timers);
Input::<'a>::register_interrupt_flag(&mut self.peripherals, &flags.input);
Output::<'a>::register_interrupt_flag(&mut self.peripherals, &flags.output);
}
}
impl<'a, M: Memory, P: Peripherals<'a>> Interpreter<'a, M, P> {
fn set_cc(&mut self, word: Word) {
<PSR as MemMapped>::from(self).unwrap().set_cc(self, word)
}
fn get_cc(&self) -> (bool, bool, bool) {
self.get_special_reg::<PSR>().get_cc()
}
fn push(&mut self, word: Word) -> WriteAttempt {
// This function will *only ever push onto the system stack*:
// TODO: report an error if it's in the I/O region somehow? it's not possible in regular use but it happened to me anyways (when getting the OS not to switch to user mode)
if self[R6] <= lc3_isa::OS_START_ADDR {
self.set_error(SystemStackOverflow);
self.halt();
return Err(Acv); // TODO: Kind of an ACV, but not really?
}
self[R6] -= 1;
self.set_word(self[R6], word)
}
// Take notice! This will not modify R6 if the read fails!
// TODO: Is this correct?
fn pop(&mut self) -> ReadAttempt {
let word = self.get_word(self[R6])?;
self[R6] += 1;
Ok(word)
}
// TODO: Swap result out
fn push_state(&mut self, saved_psr: Word) -> WriteAttempt {
// Push the saved PSR and then the PC so that the PC gets popped first.
// (Popping the PSR first could trigger an ACV)
self.push(saved_psr)
.and_then(|()| self.push(self.get_pc()))
}
fn restore_state(&mut self) -> Result<(), Acv> {
// Update call stack on return
self.pop_call_stack();
// Restore the PC and then the PSR.
self.pop()
.map(|w| self.set_pc(w))
.and_then(|()| self.pop().map(|w| self.set_special_reg::<PSR>(w)))
}
// Infallible since BSP is 'special'.
fn swap_stacks(&mut self) {
let (sp, bsp) = (self[R6], *self.get_special_reg::<BSP>());
BSP::set_special(self, sp);
self[R6] = bsp;
}
// TODO: execution event = exception, interrupt, or a trap
// find a better name
fn prep_for_execution_event(&mut self) {
let mut psr = self.get_special_reg::<PSR>();
// Need to save a temporary copy of the PSR before switching to supervisor mode
let saved_psr: Word = *self.get_special_reg::<PSR>();
// If we're in user mode..
if psr.in_user_mode() {
// ..switch to supervisor mode..
psr.to_privileged_mode(self);
// ..and switch the stacks:
self.swap_stacks();
} else {
// We're assuming if PSR[15] is in supervisor mode, R6 is already
// the supervisor stack pointer and BSR has the user stack pointer.
}
// We're in privileged mode now so this should only error if we've
// overflowed our stack.
if let Err(Acv) = self.push_state(saved_psr) {
debug_assert_eq!(self.state, MachineState::Halted);
return;
}
// self.get_special_reg::<PSR>().set_priority(self, 3);
}
fn handle_trap(&mut self, trap_vec: u8) {
self.prep_for_execution_event();
// Go to the trap routine:
// (this should also not panic)
self.pc = self
.get_word(TRAP_VECTOR_TABLE_START_ADDR | (Into::<Word>::into(trap_vec)))
.unwrap();
self.push_call_stack(self.pc, self.get_special_reg::<PSR>().in_user_mode());
}
// TODO: find a word that generalizes exception and trap...
// since that's what this handles
fn handle_exception(&mut self, ex_vec: u8) {
self.prep_for_execution_event();
// Go to the exception routine:
// (this should also not panic)
self.pc = self
.get_word(INTERRUPT_VECTOR_TABLE_START_ADDR | (Into::<Word>::into(ex_vec)))
.unwrap();
self.push_call_stack(self.pc, self.get_special_reg::<PSR>().in_user_mode());
}
fn handle_interrupt(&mut self, int_vec: u8, priority: u8) -> bool {
// TODO: check that the ordering here is right
// Make sure that the priority is high enough to interrupt:
if self.get_special_reg::<PSR>().get_priority() > priority {
// Gotta wait.
return false;
}
// Haven't executed instruction at PC-1, so must store PC-1 on stack, not PC
self.pc -= 1;
self.handle_exception(int_vec);
self.set_cc(0);
self.get_special_reg::<PSR>().set_priority(self, priority);
true
// self.prep_for_execution_event();
// // Go to the interrupt routine:
// // (this should also not panic)
// self.pc = self
// .get_word(INTERRUPT_VECTOR_TABLE_START_ADDR | (Into::<Word>::into(int_vec)))
// .unwrap();
// true
}
fn check_interrupts(&mut self) -> bool {
macro_rules! assert_in_priority_order {
($dev1: ty, $dev2: ty, $($rest:ty),*) => {
sa::const_assert!(<$dev1>::PRIORITY >= <$dev2>::PRIORITY);
assert_in_priority_order!($dev2, $($rest),*);
};
($dev1: ty, $dev2: ty) => {
sa::const_assert!(<$dev1>::PRIORITY >= <$dev2>::PRIORITY);
}
}
macro_rules! int_devices {
($($dev:ty),* $(,)?) => {
let cur_priority: u8 = self.get_special_reg::<PSR>().get_priority();
$(
if <$dev>::PRIORITY <= cur_priority { return false; }
else if <$dev as Interrupt>::interrupt(self) {
<$dev as Interrupt>::reset_interrupt_flag(self);
return self.handle_interrupt(<$dev>::INT_VEC, <$dev>::PRIORITY);
}
)*
assert_in_priority_order!($($dev),*);
}
}
int_devices!(
KBSR, DSR, G0CR, G1CR, G2CR, G3CR, G4CR, G5CR, G6CR, G7CR, T0CR, T1CR
);
false
}
fn is_acv(&self, addr: Word) -> bool {
// TODO: is `PSR::from_special(self).in_user_mode()` clearer?
if self.get_special_reg::<PSR>().in_user_mode() {
(addr < USER_PROGRAM_START_ADDR) | (addr >= MEM_MAPPED_START_ADDR)
} else {
false
}
}
fn instruction_step_inner(&mut self, insn: Instruction) -> Result<(), Acv> {
use Instruction::*;
macro_rules! i {
(PC <- $expr:expr) => {
self.set_pc($expr);
};
(mem[$addr:expr] <- $expr:expr) => {
self.set_word($addr, $expr)?;
};
($dr:ident <- $expr:expr) => {
self[$dr] = $expr;
if insn.sets_condition_codes() {
self.set_cc(self[$dr]);
}
};
}
macro_rules! I {
(PC <- $($rest:tt)*) => {{
_insn_inner_gen!($);
#[allow(unused_mut)]
let mut pc: Addr;
_insn_inner!(pc | $($rest)*);
i!(PC <- pc);
}};
([S+] PC <- $($rest:tt)*) => {{
_insn_inner_gen!($);
#[allow(unused_mut)]
let mut pc: Addr;
_insn_inner!(pc | $($rest)*);
i!(PC <- pc);
self.push_call_stack(pc, self.get_special_reg::<PSR>().in_user_mode());
}};
([S-] PC <- $($rest:tt)*) => {{
_insn_inner_gen!($);
#[allow(unused_mut)]
let mut pc: Addr;
_insn_inner!(pc | $($rest)*);
i!(PC <- pc);
self.pop_call_stack();
}};
(mem[$($addr:tt)*] <- $($word:tt)*) => {{
_insn_inner_gen!($);
#[allow(unused_mut)]
let mut addr: Addr;
#[allow(unused_mut)]
let mut word: Word;
_insn_inner!(addr | $($addr)*);
_insn_inner!(word | $($word)*);
self.set_word(addr, word)?
}};
($dr:ident <- $($rest:tt)*) => {{
_insn_inner_gen!($);
#[allow(unused_mut)]
let mut word: Word;
_insn_inner!(word | $($rest)*);
i!($dr <- word);
}};
}
macro_rules! _insn_inner_gen {
($d:tt) => {
macro_rules! _insn_inner {
($d nom:ident | R[$d reg:expr] $d ($d rest:tt)*) => { $d nom = self[$d reg]; _insn_inner!($d nom | $d ($d rest)*) };
($d nom:ident | PC $d ($d rest:tt)*) => { $d nom = self.get_pc(); _insn_inner!($d nom | $d ($d rest)*) };
($d nom:ident | mem[$d ($d addr:tt)*] $d ($d rest:tt)*) => {
$d nom = self.get_word({
let mut _addr_mem: Addr;
_insn_inner!(_addr_mem | $d ($d addr)*);
_addr_mem
}/* as Word*/)?;
_insn_inner!($d nom | $d ($d rest)*)
};
($d nom:ident | + $d ($d rest:tt)*) => {
$d nom = $d nom.wrapping_add(
{
let mut _rhs_add;
_insn_inner!(_rhs_add | $d ($d rest)*);
_rhs_add
} as Word);
};
($d nom:ident | & $d ($d rest:tt)*) => {
$d nom = $d nom & {
let mut _rhs_and;
_insn_inner!(_rhs_and | $d ($d rest)*);
_rhs_and
} as Word;
};
($d nom:ident | ! $d ($d rest:tt)*) => {
$d nom = ! {
let mut _rhs_not: Word;
_insn_inner!(_rhs_not | $d ($d rest)*);
_rhs_not
} /*as Word*/;
};
($d nom:ident | $d ident:ident $d ($d rest:tt)*) => {
$d nom = $d ident; _insn_inner!($d nom | $d ($d rest)*)
};
($d nom:ident | ) => {};
}
}
}
match insn {
AddReg { dr, sr1, sr2 } => I!(dr <- R[sr1] + R[sr2]),
AddImm { dr, sr1, imm5 } => I!(dr <- R[sr1] + imm5),
AndReg { dr, sr1, sr2 } => I!(dr <- R[sr1] & R[sr2]),
AndImm { dr, sr1, imm5 } => I!(dr <- R[sr1] & imm5),
Br { n, z, p, offset9 } => {
let (cc_n, cc_z, cc_p) = self.get_cc();
if n && cc_n || z && cc_z || p && cc_p {