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
//! 0x01 Control operations (branch, thread, future, message, configuration)
//! * `0x0101` [jump]:`address`
//! * `0x0102` [call]:`address`
//! * `0x0103` return ([call_return])
//! * `0x0104` [goto] `direct:32`
//! * `0x0105` [gosub] `direct:32`
//! * `0x0108` loop:`counter_init` ([loop_init])
//! * `0x0109` [next] `direct:32`
//! * `0x010A` [goto_if]:`CMP` `direct:32`
//! * `0x010B` [gosub_if]:`CMP` `direct:32`
//! * TODO-0.2.0 `0x010C` goto_check:`checked` `direct:32`
//! * TODO-0.2.0 `0x010D` gosub_check:`checked` `direct:32`
//! * TODO-0.2.0 0x010E skip_if:`CMP`
//! * TODO-0.2.0 0x010F skip_check:`checked`
//! * `0x01FF` [halt]
//!
//!
//! * TODO 0x0170 FORK $target :
//!     invoke [Cpu] which `JUMP`s to `$target` with a new context instance,
//!     while the current [Cpu] continues with the next instruction.
//! * TODO 0x0180 PROMISE ?
//! * TODO 0x0181 RESOLVE ?
//! * TODO 0x0188 PRODUCE ?
//! * TODO 0x0187 CONSUME ?
//! * TODO ... MESSAGES
//! * TODO 0x01F0 CHANGE FREQUENCY
//!

use std::collections::HashMap;

use osiris_data::data::identification::Address;
use osiris_process::compare::Compare;
use osiris_process::operation::error::{OperationError, OperationResult};
use osiris_process::operation::{Operation, OperationSet};
use osiris_process::operation::scheme::{ArgumentScheme, ArgumentType, InstructionScheme, OperationId};
use osiris_process::processor::Cpu;

pub const SET_MASK: u16 = 0x0100;

/// 0x0101
pub const JUMP: OperationId = OperationId::new(SET_MASK | 0x01);

/// 0x0102
pub const CALL: OperationId = OperationId::new(SET_MASK | 0x02);

/// 0x0103
pub const CALL_RETURN: OperationId = OperationId::new(SET_MASK | 0x03);

/// 0x0104
pub const GOTO: OperationId = OperationId::new(SET_MASK | 0x04);

/// 0x0105
pub const GOSUB: OperationId = OperationId::new(SET_MASK | 0x05);

/// 0x0108
pub const LOOP: OperationId = OperationId::new(SET_MASK | 0x08);

/// 0x0109
pub const NEXT: OperationId = OperationId::new(SET_MASK | 0x09);

/// 0x010A
pub const GOTO_IF: OperationId = OperationId::new(SET_MASK | 0x0A);

/// 0x010B
pub const GOSUB_IF: OperationId = OperationId::new(SET_MASK | 0x0B);

/// 0x01FF
pub const HALT: OperationId = OperationId::new(SET_MASK | 0xFF);

fn _jump(cpu: &mut Cpu, address: Address) -> OperationResult<()> {
    match cpu.point_instruction(address) {
        Ok(_) => Ok(()),
        Err(err) => Err(OperationError::MemoryError(err)),
    }
}

fn _goto(cpu: &mut Cpu, current: Address, target: u32) -> OperationResult<()> {
    _jump(cpu, Address::new(0xFFFFFFFF_00000000 & current.to_u64() | target as u64))
}

/// # `0x0101` [jump]:`address`
///
/// ## Target
///  - The register containing the target address in memory.
///
/// ## Arguments
///  - None.
///
/// ## Operation
///  - `current = r:target`
///
/// ## Errors
///  - [OperationError::InvalidArgumentType] if the provided argument is not an [ArgumentScheme::NoArgument],
///  - [OperationError::MemoryError] if a memory error occurs.
pub fn jump(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    scheme.argument.get_no_argument()?;
    _jump(cpu, Address::from_word(cpu.bank_get(scheme.target)))
}

/// # `0x0102` [call]:`address`
///
/// ## Target
///  - The register containing the target address in memory.
///
/// ## Arguments
///  - None.
///
/// ## Operation
///  - `push:current`
///  - `jump:target`
///
/// ## Errors
///  - [OperationError::InvalidArgumentType] if the provided argument is not an [ArgumentScheme::NoArgument],
///  - [OperationError::MemoryError] if a memory error occurs.
pub fn call(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    cpu.stack_push(cpu.state.current.to_word());
    jump(cpu, scheme)
}

/// * `0x0103` return ([call_return])
///
/// ## Target
///  - None
///
/// ## Arguments
///  - None.
///
/// ## Operation
///  - `current = pop`
///
/// ## Errors
///  - [OperationError::InvalidArgumentType] if the provided argument is not an [ArgumentScheme::NoArgument],
///  - [OperationError::CannotReturnFromEmptyStack] if the stack is empty,
///  - [OperationError::MemoryError] if a memory error occurs.
pub fn call_return(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    scheme.argument.get_no_argument()?;
    match cpu.stack_pop() {
        None => { Err(OperationError::CannotReturnFromEmptyStack) }
        Some(addr) => {
            let result = _jump(cpu, Address::from_word(addr));
            cpu.state.current.increment();
            result
        }
    }
}

/// # `0x0104` [goto] `direct:32`
///
/// Performs a short jump (offset is 32 bits long).
///
/// ## Target
///  - None.
///
/// ## Arguments
///  - direct:**32**
///
/// ## Operation
///  - `current = (current.top) | direct`
///
/// ## Errors
///  - [OperationError::InvalidArgumentType] if the provided argument is not an [ArgumentType::OneU32],
///  - [OperationError::MemoryError] if a memory error occurs.
pub fn goto(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    let target = scheme.argument.get_one_u32()?;
    _goto(cpu, cpu.state.current, target)
}

/// # `0x0105` [gosub] `direct:32`
///
/// Performs a short call (offset is 32 bits long).
///
/// ## Target
///  - None.
///
/// ## Arguments
///  - direct:**32**
///
/// ## Operation
///  - `current = direct`
///
/// ## Errors
///  - [OperationError::InvalidArgumentType] if the provided argument is not an [ArgumentType::OneU32],
///  - [OperationError::MemoryError] if a memory error occurs.
pub fn gosub(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    cpu.stack_push(cpu.state.current.to_word());
    goto(cpu, scheme)
}


/// * `0x0108` loop:`counter_init` ([loop_init])
///
/// ## Target
///  - The register holding the initial value
///
/// ## Arguments
///  - None.
///
/// ## Operation
///  - `counter = r:target`
///
/// ## Errors
///  - [OperationError::InvalidArgumentType] if the provided argument is not an [ArgumentScheme::NoArgument],
pub fn loop_init(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    scheme.argument.get_no_argument()?;
    cpu.state.operation.counter = cpu.bank_get(scheme.target);
    cpu.debug("for", format!("{:016x}", cpu.state.operation.counter.to_u64()), "⚙️".to_string());
    Ok(())
}


/// * `0x0109` [next] `direct:32`
///
/// ## Target
///  - None.
///
/// ## Arguments
///  - direct:**32**
///
/// ## Operation
///  - `counter -= 1`
///  - `if counter >= 0 : current = direct`
///
/// ## Errors
///  - [OperationError::InvalidArgumentType] if the provided argument is not an [ArgumentType::OneU32],
pub fn next(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    cpu.decrease_loop_counter();
    if cpu.state.operation.counter.to_u64() > 0 {
        goto(cpu, scheme)?;
    }
    Ok(())
}

fn fn_if(state: i64, operator: u16) -> OperationResult<bool> {
    let cmp_op = Compare::from(operator);
    match cmp_op {
        None => Err(OperationError::Panic(format!("Invalid argument for comparison : {}", operator)))?,
        Some(op) => Ok(op.is(state))
    }
}


/// # `0x010A` [goto_if]:`CMP` `direct:32`
///
/// Jumps to a target address if the last comparison corresponds the selected operator.
///
/// ## Target
///  - CMP : LT / LE / NE / EQ / GE / GT
///           <   <=   !=   ==   >=   >
///
/// ## Arguments
///  - The address to jump to.
pub fn goto_if(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    let target = scheme.argument.get_one_u32()?;
    let state = cpu.state.operation.compare;
    if fn_if(state, scheme.target.to_u16())? {
        _goto(cpu, cpu.state.current, target)
    } else { Ok(()) }
}

/// # `0x010B` [gosub_if]:`CMP` `direct:32`
///
/// Calls a procedure stored at the given address if the last comparison corresponds the selected operator.
///
/// ## Target
///  - CMP : LT / LE / NE / EQ / GE / GT
///           <   <=   !=   ==   >=   >
///
/// ## Arguments
///  - The address to jump to.
pub fn gosub_if(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    cpu.stack_push(cpu.state.current.to_word());
    goto_if(cpu, scheme)
}

/// * `0x01FF` [halt]
///
/// ## Target
///  - None.
///
/// ## Arguments
///  - None.
///
/// ## Operation
///  - `HALT_FLAG = true`
///
/// ## Errors
///  - [OperationError::InvalidArgumentType] if the provided argument is not an [ArgumentScheme::NoArgument],
pub fn halt(cpu: &mut Cpu, scheme: InstructionScheme) -> OperationResult<()> {
    scheme.argument.get_no_argument()?;
    cpu.halt();
    Ok(())
}

/// Returns control operations.
///
/// ## Operations
///
/// * `0x0101` [jump]:`address`
/// * `0x0102` [call]:`address`
/// * `0x0103` return ([call_return])
/// * `0x0104` [goto] `direct:32`
/// * `0x0105` [gosub] `direct:32`
/// * `0x0108` loop:`counter_init` ([loop_init])
/// * `0x0109` [next] `direct:32`
/// * `0x010A` [goto_if]:`CMP` `direct:32`
/// * `0x010B` [gosub_if]:`CMP` `direct:32`
/// * `0x01FF` [halt]
pub fn operation_set() -> OperationSet {
    let mut set: OperationSet = HashMap::new();
    set.insert(
        JUMP,
        Operation::new(JUMP, "jump".to_string(), true, ArgumentType::NoArgument, jump),
    );
    set.insert(
        CALL,
        Operation::new(CALL, "call".to_string(), true, ArgumentType::NoArgument, call),
    );
    set.insert(
        CALL_RETURN,
        Operation::new(CALL_RETURN, "return".to_string(), false, ArgumentType::NoArgument, call_return),
    );
    set.insert(
        GOTO,
        Operation::new(GOTO, "goto".to_string(), false, ArgumentType::OneU32, goto),
    );
    set.insert(
        GOSUB,
        Operation::new(GOSUB, "gosub".to_string(), false, ArgumentType::OneU32, gosub),
    );
    set.insert(
        LOOP,
        Operation::new(LOOP, "loop".to_string(), true, ArgumentType::NoArgument, loop_init),
    );
    set.insert(
        NEXT,
        Operation::new(NEXT, "next".to_string(), false, ArgumentType::OneU32, next),
    );
    set.insert(
        GOTO_IF,
        Operation::new(GOTO_IF, "goto-if".to_string(), true, ArgumentType::OneU32, goto_if),
    );
    set.insert(
        GOSUB_IF,
        Operation::new(GOSUB_IF, "gosub-if".to_string(), true, ArgumentType::OneU32, gosub_if),
    );
    set.insert(
        HALT,
        Operation::new(HALT, "halt".to_string(), false, ArgumentType::NoArgument, halt),
    );
    set
}