corewars_sim/core/
modifier.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
//! Implementation details specific to opcode modifiers used during core simulation.

use corewars_core::load_file::{Instruction, Modifier, Offset};

use super::address;
use super::Core;

/// A helper struct to execute an instruction using the proper modifiers.
/// This struct maintains the "registers" used for evaluating instructions
pub(super) struct Executor<'a> {
    core: &'a mut Core,
    program_counter: Offset,
    a_value: Instruction,
    b_value: Instruction,
    a_ptr: Offset,
    b_ptr: Offset,
}

impl<'a> Executor<'a> {
    /// Build a new executor for the given program offset of the given [`Core`].
    pub fn new(core: &'a mut Core, program_counter: Offset) -> Self {
        let a_ptr = address::resolve_a_pointer(core, program_counter);

        // NOTE: the order of evaluation is significant here: we create the "register"
        // by cloning the A operand before evaluating the B pointer, and all further
        // operations must use the buffered A operand, in case the B pointer evaluation
        // modifies memory
        address::apply_a_pointer(core, program_counter, address::EvalTime::Pre);
        let a_value = core.get_offset(a_ptr).clone();
        address::apply_a_pointer(core, program_counter, address::EvalTime::Post);

        let b_ptr = address::resolve_b_pointer(core, program_counter);

        address::apply_b_pointer(core, program_counter, address::EvalTime::Pre);
        let b_value = core.get_offset(b_ptr).clone();
        address::apply_b_pointer(core, program_counter, address::EvalTime::Post);

        Self {
            core,
            program_counter,
            a_value,
            b_value,
            a_ptr,
            b_ptr,
        }
    }

    /// Getter for the resolved A pointer
    pub fn a_ptr(&self) -> Offset {
        self.a_ptr
    }

    /// Execute a given operation (`FieldOp`) on a given instruction. This is a convenience
    /// shortcut for [`run_on_instructions`](Self::run_on_instructions) without an `InstructionOp`.
    pub fn run_on_fields<FieldOp>(self, field_op: FieldOp)
    where
        FieldOp: FnMut(Offset, Offset) -> Option<Offset>,
    {
        self.run_on_instructions::<_, fn(_, _) -> _, _>(field_op, None);
    }

    /// Execute a given operation (`FieldOp`) on a given instruction.
    /// `field_op` and `instruction_op` are closures taking an `a` and `b`
    /// argument and returning the new value to set in the `b` instruction, if any.
    pub fn run_on_instructions<FieldOp, InstructionOp, OptionalInstructionOp>(
        self,
        mut field_op: FieldOp,
        instruction_op: OptionalInstructionOp,
    ) where
        FieldOp: FnMut(Offset, Offset) -> Option<Offset>,
        InstructionOp: FnMut(Instruction, Instruction) -> Option<Instruction>,
        OptionalInstructionOp: Into<Option<InstructionOp>>,
    {
        let instruction = self.core.get_offset(self.program_counter).clone();

        let a_value_a_offset = self.core.offset(self.a_value.a_field.unwrap_value());
        let a_value_b_offset = self.core.offset(self.a_value.b_field.unwrap_value());

        let b_value_a_offset = self.core.offset(self.b_value.a_field.unwrap_value());
        let b_value_b_offset = self.core.offset(self.b_value.b_field.unwrap_value());

        let b_target = self.core.get_offset_mut(self.b_ptr);

        match instruction.modifier {
            Modifier::A => {
                if let Some(res) = field_op(a_value_a_offset, b_value_a_offset) {
                    b_target.a_field.set_value(res);
                }
            }
            Modifier::B => {
                if let Some(res) = field_op(a_value_b_offset, b_value_b_offset) {
                    b_target.b_field.set_value(res);
                }
            }
            Modifier::AB => {
                if let Some(res) = field_op(a_value_a_offset, b_value_b_offset) {
                    b_target.b_field.set_value(res);
                }
            }
            Modifier::BA => {
                if let Some(res) = field_op(a_value_b_offset, b_value_a_offset) {
                    b_target.a_field.set_value(res);
                }
            }
            Modifier::F | Modifier::I => {
                if let Some(a_res) = field_op(a_value_a_offset, b_value_a_offset) {
                    b_target.a_field.set_value(a_res);
                }
                if let Some(b_res) = field_op(a_value_b_offset, b_value_b_offset) {
                    b_target.b_field.set_value(b_res);
                }

                if instruction.modifier == Modifier::I {
                    if let Some(mut instruction_op) = instruction_op.into() {
                        if let Some(res) = instruction_op(self.a_value, b_target.clone()) {
                            b_target.opcode = res.opcode;
                            b_target.modifier = res.modifier;
                        }
                    }
                }
            }
            Modifier::X => {
                if let Some(a_res) = field_op(a_value_b_offset, b_value_a_offset) {
                    b_target.a_field.set_value(a_res);
                }
                if let Some(b_res) = field_op(a_value_a_offset, b_value_b_offset) {
                    b_target.b_field.set_value(b_res);
                }
            }
        }
    }
}

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

    use super::super::tests::build_core;

    use corewars_core::load_file::{Field, Instruction, Opcode};

    use pretty_assertions::assert_eq;
    use test_case::test_case;

    #[test_case("a", 35, 6; "a")]
    #[test_case("b", 5, 46; "b")]
    #[test_case("ab", 5, 36; "ab")]
    #[test_case("ba", 45, 6; "ba")]
    #[test_case("f", 35, 46; "f")]
    #[test_case("x", 45, 36; "x")]
    fn field_modifier(modifier: &str, expected_a: i32, expected_b: i32) {
        use pretty_assertions::assert_eq;

        let mut core = build_core(&format!(
            "
            dat.{}  $1, $2
            dat     $3, $4
            sub.x   $5, $6
            ",
            modifier
        ));

        let zero = core.offset(0);
        let exec = Executor::new(&mut core, zero);

        exec.run_on_fields(|a, b| {
            // kinda hacky way to verify exact outputs but I guess it works...
            let string_ans = a.value().to_string() + &b.value().to_string();
            Some(zero + string_ans.parse::<i32>().unwrap())
        });

        assert_eq!(
            core.get(2),
            &Instruction {
                opcode: Opcode::Sub,
                modifier: Modifier::X,
                a_field: Field::direct(expected_a),
                b_field: Field::direct(expected_b),
            }
        );
    }

    #[test]
    fn instruction_modifier() {
        let mut core = build_core(
            "
            dat.i $1, $2
            add.f $3, $4
            sub.x $5, $6
            ",
        );

        let output = core.offset(0);
        let zero = core.offset(0);

        let exec = Executor::new(&mut core, zero);

        exec.run_on_instructions(
            |a, b| {
                let string_ans = a.value().to_string() + &b.value().to_string();
                Some(output + string_ans.parse::<i32>().unwrap())
            },
            |a: Instruction, b: Instruction| {
                assert_eq!(a.opcode, Opcode::Add);
                assert_eq!(b.opcode, Opcode::Sub);

                Some(Instruction {
                    opcode: Opcode::Nop,
                    modifier: Modifier::AB,
                    a_field: Field::direct(0),
                    b_field: Field::direct(0),
                })
            },
        );

        assert_eq!(
            core.get(2),
            &Instruction {
                opcode: Opcode::Nop,
                modifier: Modifier::AB,
                a_field: Field::direct(35),
                b_field: Field::direct(46),
            }
        );
    }
}