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
//! See: https://faqwiki.zxnet.co.uk/wiki/Z80#Differences_between_NMOS_and_CMOS_Z80s
#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};

use super::{Z80, any::Z80Any, CpuFlags};

/// A trait for implementing exceptions to the undocumented Z80 behaviour.
///
/// It's been [reported] that depending on the CPU technology (NMOS, CMOS) and the manufacturer (Zilog, NEC, other clones)
/// there are certain differences of undocumented behaviour and mainly affects the way the Flags' undocumented
/// bits 3 and 5 are being modified.
///
/// [reported]: https://faqwiki.zxnet.co.uk/wiki/Z80#Differences_between_NMOS_and_CMOS_Z80s
pub trait Flavour: Clone + Copy + Default + PartialEq + Eq {
    /// The value being actually put on the data bus while executing the undocumented instruction `OUT (C),(HL)`.
    const CONSTANT_OUT_DATA: u8;
    /// Should be `true` if the IFF2 is being reset early when accepting an interrupt, while an instruction
    /// is being executed, so `LD A,I` or `LD A,R` may report modified IFF2 value.
    const ACCEPTING_INT_RESETS_IFF2_EARLY: bool;
    /// Returns the string identifier of this flavour.
    fn tag() -> &'static str;
    /// The way MEMPTR is being updated for: `LD (nnnn),A`, `LD (BC),A`, `LD (DE),A` and `OUT (nn),A`
    /// is being controlled by this function. The current Accumulator value is being passed as `msb` and
    /// the lower 8-bits of the current destination address is being provided as `lsb`.
    /// The function should return the (MSB, LSB) value to set the MEMPTR with.
    fn memptr_mix(msb: u8, lsb: u8) -> (u8, u8);
    /// This method is being called each time before an instructions is being executed or an interrupt is being
    /// accepted, including NMI. It might modify some state and is being used together with [Flavour::flags_modified]
    /// and [Flavour::get_q] to prepare a value applied to bits 3 and 5 of the Flags for the SCF/CCF instructions.
    fn begin_instruction(&mut self);
    /// This method is being called each time an instructions modifies the Flags register.
    fn flags_modified(&mut self);
    /// Bits 3 and 5 of the returned value will be copied to the Flags register.
    fn get_q(&self, acc:u8, flags: CpuFlags) -> u8;
    /// Converts a [Z80] struct of this flavour into an [Z80Any] enum.
    fn cpu_into_any(cpu: Z80<Self>) -> Z80Any;
    /// Returns the contained [`Z80<Self>`][Z80] value, consuming the `cpu` value.
    ///
    /// # Panics
    /// Panics if the `cpu_any` value is not a variant corresponding to this `Flavour`.
    fn unwrap_cpu_any(cpu_any: Z80Any) -> Z80<Self>;
    /// Should reset the state. Called by [crate::Cpu::reset]. The default implementation resets the state to default.
    #[inline(always)]
    fn reset(&mut self) {
        *self = Default::default();
    }
}

/// The struct implements a [Flavour] that emulates the Zilog Z80 NMOS version.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(default, rename_all(serialize = "camelCase")))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NMOS {
    #[cfg_attr(feature = "serde", serde(alias = "flagsModified"))]
    flags_modified: bool,
    #[cfg_attr(feature = "serde", serde(alias = "lastFlagsModified"))]
    last_flags_modified: bool
}

/// The struct implements a [Flavour] that emulates the Zilog Z80 CMOS version.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(into = "NMOS", from = "NMOS"))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CMOS;

/// The struct implements a [Flavour] that (supposedly) emulates the KP1858BM1 or T34BM1 clones of the Z80.
///
/// It differs from the NMOS implementation in the way [Flavour::memptr_mix] works.
/// In this implementation the returned MSB is always 0.
/// The [Flavour::ACCEPTING_INT_RESETS_IFF2_EARLY] value is `false`.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(default, rename_all(serialize = "camelCase")))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BM1 {
    #[cfg_attr(feature = "serde", serde(alias = "flagsModified"))]
    flags_modified: bool,
    #[cfg_attr(feature = "serde", serde(alias = "lastFlagsModified"))]
    last_flags_modified: bool
}

impl Flavour for NMOS {
    const CONSTANT_OUT_DATA: u8 = 0;
    const ACCEPTING_INT_RESETS_IFF2_EARLY: bool = true;
    #[inline(always)]
    fn tag() -> &'static str {
        "NMOS"
    }
    #[inline(always)]
    fn memptr_mix(msb: u8, lsb: u8) -> (u8, u8) {
        (msb, lsb.wrapping_add(1))
    }
    #[inline(always)]
    fn begin_instruction(&mut self) {
        self.last_flags_modified = self.flags_modified;
        self.flags_modified = false;
    }
    #[inline(always)]
    fn flags_modified(&mut self) {
        self.flags_modified = true;
    }
    #[inline(always)]
    fn get_q(&self, acc: u8, flags: CpuFlags) -> u8 {
        if self.last_flags_modified {
            acc
        }
        else {
            acc | flags.bits()
        }
    }
    #[inline]
    fn cpu_into_any(cpu: Z80<Self>) -> Z80Any {
        Z80Any::NMOS(cpu)
    }

    fn unwrap_cpu_any(cpu_any: Z80Any) -> Z80<Self> {
        cpu_any.unwrap_nmos()
    }
}

impl Flavour for CMOS {
    const CONSTANT_OUT_DATA: u8 = u8::max_value();
    const ACCEPTING_INT_RESETS_IFF2_EARLY: bool = false;
    #[inline(always)]
    fn tag() -> &'static str {
        "CMOS"
    }
    #[inline(always)]
    fn memptr_mix(msb: u8, lsb: u8) -> (u8, u8) {
        (msb, lsb.wrapping_add(1))
    }
    #[inline(always)]
    fn begin_instruction(&mut self) {}
    #[inline(always)]
    fn flags_modified(&mut self) {}
    #[inline(always)]
    fn get_q(&self, acc: u8, _flags: CpuFlags) -> u8 { acc }
    #[inline]
    fn cpu_into_any(cpu: Z80<Self>) -> Z80Any {
        Z80Any::CMOS(cpu)
    }

    fn unwrap_cpu_any(cpu_any: Z80Any) -> Z80<Self> {
        cpu_any.unwrap_cmos()
    }
}

impl Flavour for BM1 {
    const CONSTANT_OUT_DATA: u8 = 0;
    const ACCEPTING_INT_RESETS_IFF2_EARLY: bool = false;
    #[inline(always)]
    fn tag() -> &'static str {
        "BM1"
    }
    #[inline(always)]
    fn memptr_mix(_msb: u8, lsb: u8) -> (u8, u8) {
        (0, lsb.wrapping_add(1))
    }
    #[inline(always)]
    fn begin_instruction(&mut self) {
        self.last_flags_modified = self.flags_modified;
        self.flags_modified = false;
    }
    #[inline(always)]
    fn flags_modified(&mut self) {
        self.flags_modified = true;
    }
    #[inline(always)]
    fn get_q(&self, acc: u8, flags: CpuFlags) -> u8 {
        if self.last_flags_modified {
            acc
        }
        else {
            acc | flags.bits()
        }
    }
    #[inline]
    fn cpu_into_any(cpu: Z80<Self>) -> Z80Any {
        Z80Any::BM1(cpu)
    }

    fn unwrap_cpu_any(cpu_any: Z80Any) -> Z80<Self> {
        cpu_any.unwrap_bm1()
    }
}

/// This conversion is lossy. When CMOS [Flavour] is converted back information is lost.
impl From<NMOS> for CMOS {
    fn from(_: NMOS) -> Self {
        CMOS
    }
}

impl From<CMOS> for NMOS {
    fn from(_: CMOS) -> Self {
        NMOS::default()
    }
}

/// This conversion is lossy. When CMOS [Flavour] is converted back information is lost.
impl From<BM1> for CMOS {
    fn from(_: BM1) -> Self {
        CMOS
    }
}

impl From<CMOS> for BM1 {
    fn from(_: CMOS) -> Self {
        BM1::default()
    }
}

impl From<NMOS> for BM1 {
    fn from(NMOS{flags_modified, last_flags_modified}: NMOS) -> Self {
        BM1 {flags_modified, last_flags_modified}
    }
}

impl From<BM1> for NMOS {
    fn from(BM1{flags_modified, last_flags_modified}: BM1) -> Self {
        NMOS {flags_modified, last_flags_modified}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::z80::Z80;

    #[test]
    fn flavour_conversion() {
        let cmos: Z80<CMOS> = Z80::<BM1>::default().into_flavour();
        let nmos = Z80::<NMOS>::from_flavour(cmos);
        let bm1 = nmos.into_flavour::<BM1>();
        assert_eq!(bm1, Z80::<BM1>::default());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn flavour_serde() {
        assert_eq!(NMOS::tag(), "NMOS");
        assert_eq!(CMOS::tag(), "CMOS");
        assert_eq!(BM1::tag(), "BM1");
        assert_eq!(serde_json::to_string(&NMOS::default()).unwrap(), r#"{"flagsModified":false,"lastFlagsModified":false}"#);
        assert_eq!(serde_json::to_string(&CMOS::default()).unwrap(), r#"{"flagsModified":false,"lastFlagsModified":false}"#);
        assert_eq!(serde_json::to_string(&BM1::default()).unwrap(), r#"{"flagsModified":false,"lastFlagsModified":false}"#);
        let flav: NMOS = serde_json::from_str(r#"{"flags_modified":false,"last_flags_modified":false}"#).unwrap();
        assert!(flav == NMOS::default());
        let flav: NMOS = serde_json::from_str(r#"{}"#).unwrap();
        assert!(flav == NMOS::default());
        let flav: NMOS = serde_json::from_str(r#"{"flagsModified":true,"lastFlagsModified":true}"#).unwrap();
        assert!(flav == NMOS { flags_modified: true, last_flags_modified: true});
        let flav: CMOS = serde_json::from_str(r#"{"flags_modified":false,"last_flags_modified":false}"#).unwrap();
        assert!(flav == CMOS::default());
        let flav: CMOS = serde_json::from_str(r#"{}"#).unwrap();
        assert!(flav == CMOS::default());
        let flav: CMOS = serde_json::from_str(r#"{"flagsModified":true,"lastFlagsModified":true}"#).unwrap();
        assert!(flav == CMOS);
        let flav: BM1 = serde_json::from_str(r#"{"flags_modified":false,"last_flags_modified":false}"#).unwrap();
        assert!(flav == BM1::default());
        let flav: BM1 = serde_json::from_str(r#"{}"#).unwrap();
        assert!(flav == BM1::default());
        let flav: BM1 = serde_json::from_str(r#"{"flagsModified":true,"lastFlagsModified":true}"#).unwrap();
        assert!(flav == BM1 { flags_modified: true, last_flags_modified: true});
    }
}