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
// EndBASIC
// Copyright 2022 Julio Merino
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations
// under the License.

//! Commands to interact with the data provided by `DATA` statements.

use async_trait::async_trait;
use endbasic_core::ast::{ArgSep, BuiltinCallSpan, Expr, Value, VarType};
use endbasic_core::exec::{Clearable, Machine};
use endbasic_core::syms::{
    CallError, CallableMetadata, CallableMetadataBuilder, Command, CommandResult,
};
use std::cell::RefCell;
use std::rc::Rc;

/// Category description for all symbols provided by this module.
pub(crate) const CATEGORY: &str = "Data management";

struct ClearableIndex(Rc<RefCell<usize>>);

impl Clearable for ClearableIndex {
    fn reset_state(&self, _syms: &mut endbasic_core::syms::Symbols) {
        *self.0.borrow_mut() = 0;
    }
}

/// The `READ` command.
pub struct ReadCommand {
    metadata: CallableMetadata,
    index: Rc<RefCell<usize>>,
}

impl ReadCommand {
    /// Creates a new `READ` command.
    pub fn new(index: Rc<RefCell<usize>>) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("READ", VarType::Void)
                .with_syntax("vref1 [, .., vrefN]")
                .with_category(CATEGORY)
                .with_description(
                    "Extracts data values from DATA statements.
DATA statements can appear anywhere in the program and they register data values into an array of \
values.  READ is then used to extract values from this array into the provided variables in the \
order in which they were defined.  In other words: READ maintains an internal index into the data \
array that gets incremented by the number of provided variables every time it is executed.
The variable references in the vref1..vrefN list must match the types or be compatible with the \
values in the corresponding position of the data array.  Empty values in the data array can be \
specified by DATA, and those are converted into the default values for the relevant types: \
booleans are false, numbers are 0, and strings are empty.
Attempting to extract more values than are defined by DATA results in an \"out of data\" error.
The index that READ uses to extract DATA values can be reset by RESTORE and, more generally, by \
CLEAR.",
                )
                .build(),
            index,
        })
    }
}

#[async_trait(?Send)]
impl Command for ReadCommand {
    fn metadata(&self) -> &CallableMetadata {
        &self.metadata
    }

    async fn exec(&self, span: &BuiltinCallSpan, machine: &mut Machine) -> CommandResult {
        if span.args.is_empty() {
            return Err(CallError::SyntaxError);
        }

        let mut index = self.index.borrow_mut();

        for arg in &span.args {
            match (arg.expr.as_ref(), arg.sep) {
                (Some(Expr::Symbol(symspan)), sep) if sep == ArgSep::Long || sep == ArgSep::End => {
                    let datum = {
                        let data = machine.get_data();
                        debug_assert!(*index <= data.len());
                        if *index == data.len() {
                            return Err(CallError::InternalError(
                                symspan.pos,
                                format!("Out of data reading into {}", symspan.vref),
                            ));
                        }

                        match (&symspan.vref.ref_type(), &data[*index]) {
                            (_, Some(datum)) => datum.clone(),
                            (VarType::Auto, None) => {
                                match machine
                                    .get_symbols()
                                    .get_var(&symspan.vref)
                                    .map(Value::as_vartype)
                                {
                                    Ok(VarType::Auto) => panic!(),
                                    Ok(VarType::Boolean) => Value::Boolean(false),
                                    Ok(VarType::Double) => Value::Double(0.0),
                                    Ok(VarType::Integer) => Value::Integer(0),
                                    Ok(VarType::Text) => Value::Text("".to_owned()),
                                    Ok(VarType::Void) => panic!(),
                                    Err(_) => Value::Integer(0),
                                }
                            }
                            (VarType::Boolean, None) => Value::Boolean(false),
                            (VarType::Double, None) => Value::Double(0.0),
                            (VarType::Integer, None) => Value::Integer(0),
                            (VarType::Text, None) => Value::Text("".to_owned()),
                            (VarType::Void, None) => panic!(),
                        }
                    };
                    *index += 1;

                    machine
                        .get_mut_symbols()
                        .set_var(&symspan.vref, datum)
                        .map_err(|e| CallError::ArgumentError(symspan.pos, format!("{}", e)))?;
                }
                _ => return Err(CallError::SyntaxError),
            }
        }

        Ok(())
    }
}

/// The `RESTORE` command.
pub struct RestoreCommand {
    metadata: CallableMetadata,
    index: Rc<RefCell<usize>>,
}

impl RestoreCommand {
    /// Creates a new `RESTORE` command.
    pub fn new(index: Rc<RefCell<usize>>) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("RESTORE", VarType::Void)
                .with_syntax("")
                .with_category(CATEGORY)
                .with_description(
                    "Resets the index of the data element to be returned.
This allows READ to re-return the same elements that were previously extracted from the array of \
values defined by DATA.",
                )
                .build(),
            index,
        })
    }
}

#[async_trait(?Send)]
impl Command for RestoreCommand {
    fn metadata(&self) -> &CallableMetadata {
        &self.metadata
    }

    async fn exec(&self, span: &BuiltinCallSpan, _machine: &mut Machine) -> CommandResult {
        if !span.args.is_empty() {
            return Err(CallError::SyntaxError);
        }
        *self.index.borrow_mut() = 0;
        Ok(())
    }
}

/// Instantiates all symbols in this module and adds them to the `machine`.
pub fn add_all(machine: &mut Machine) {
    let index = Rc::from(RefCell::from(0));
    machine.add_clearable(Box::from(ClearableIndex(index.clone())));
    machine.add_command(ReadCommand::new(index.clone()));
    machine.add_command(RestoreCommand::new(index));
}

#[cfg(test)]
mod tests {
    use crate::testutils::*;
    use endbasic_core::ast::Value;

    #[test]
    fn test_read_simple() {
        Tester::default()
            .run(
                r#"
            READ i: PRINT i
            READ i: PRINT i
            DATA 3, 5, -7
            READ i: PRINT i
            "#,
            )
            .expect_prints([" 3", " 5", "-7"])
            .expect_var("I", Value::Integer(-7))
            .check();
    }

    #[test]
    fn test_read_multiple() {
        Tester::default()
            .run(
                r#"
            READ i, j, k, i
            DATA 3, 5, 7, 6
            "#,
            )
            .expect_var("I", Value::Integer(6))
            .expect_var("J", Value::Integer(5))
            .expect_var("K", Value::Integer(7))
            .check();
    }

    #[test]
    fn test_read_types() {
        Tester::default()
            .run(r#"DATA TRUE, 1.2, -5, "foo bar": READ b, d, i, s"#)
            .expect_var("b", Value::Boolean(true))
            .expect_var("d", Value::Double(1.2))
            .expect_var("i", Value::Integer(-5))
            .expect_var("s", Value::Text("foo bar".to_owned()))
            .check();
    }

    #[test]
    fn test_read_defaults_with_annotations() {
        Tester::default()
            .run(r#"DATA , , , ,: READ a, b?, d#, i%, s$"#)
            .expect_var("a", Value::Integer(0))
            .expect_var("b", Value::Boolean(false))
            .expect_var("d", Value::Double(0.0))
            .expect_var("i", Value::Integer(0))
            .expect_var("s", Value::Text("".to_owned()))
            .check();
    }

    #[test]
    fn test_read_defaults_without_annotations() {
        Tester::default()
            .run(
                r#"
            DIM b AS BOOLEAN
            DIM d AS DOUBLE
            DIM i AS INTEGER
            DIM s AS STRING
            DATA , , , ,
            READ a, b, d, i, s
            "#,
            )
            .expect_var("a", Value::Integer(0))
            .expect_var("b", Value::Boolean(false))
            .expect_var("d", Value::Double(0.0))
            .expect_var("i", Value::Integer(0))
            .expect_var("s", Value::Text("".to_owned()))
            .check();
    }

    #[test]
    fn test_read_double_to_integer() {
        Tester::default().run(r#"DATA 5.6: READ i%"#).expect_var("i", Value::Integer(6)).check();
    }

    #[test]
    fn test_read_integer_to_double() {
        Tester::default().run(r#"DATA 5: READ d#"#).expect_var("d", Value::Double(5.0)).check();
    }

    #[test]
    fn test_read_out_of_data() {
        Tester::default()
            .run(r#"DATA 5: READ i: READ j"#)
            .expect_err("1:17: In call to READ: 1:22: Out of data reading into j")
            .expect_var("I", Value::Integer(5))
            .check();
    }

    #[test]
    fn test_read_clear_on_run() {
        Tester::default()
            .set_program(None, "DATA 1: READ i: PRINT i")
            .run(r#"RUN: RUN"#)
            .expect_clear()
            .expect_prints([" 1"])
            .expect_clear()
            .expect_prints([" 1"])
            .expect_var("I", Value::Integer(1))
            .expect_program(None as Option<String>, "DATA 1: READ i: PRINT i")
            .check();
    }

    #[test]
    fn test_read_index_remains_out_of_bounds() {
        let mut t = Tester::default();
        t.run(r#"DATA 1: READ i, j"#)
            .expect_var("i", Value::Integer(1))
            .expect_err("1:9: In call to READ: 1:17: Out of data reading into j")
            .check();

        // This represents a second invocation in the REPL, which in principle should work to avoid
        // surprises but currently doesn't due to the fact that we maintain the index outside of the
        // machine and `machine.exec()` cannot clear it upfront.  Note how the read into `i` picks
        // up the second value, not the first one, because the `DATA` is only [1, 2], NOT [1, 1, 2],
        // but the index is still 1, not 0.  This is kind of intentional though, because adding
        // extra hooks into `machine.exec()` just for this single use case seems overkill.
        t.run(r#"DATA 1, 2: READ i, j"#)
            .expect_var("i", Value::Integer(2))
            .expect_err("1:12: In call to READ: 1:20: Out of data reading into j")
            .check();

        // Running `CLEAR` explicitly should resolve the issue described above and give us the
        // expected behavior.
        t.run(r#"CLEAR"#).expect_clear().check();
        t.run(r#"DATA 1, 2: READ i, j"#)
            .expect_clear()
            .expect_var("i", Value::Integer(1))
            .expect_var("j", Value::Integer(2))
            .check();
    }

    #[test]
    fn test_read_errors() {
        check_stmt_err("1:1: In call to READ: expected vref1 [, .., vrefN]", "READ");
        check_stmt_err("1:1: In call to READ: expected vref1 [, .., vrefN]", "READ i; j");

        check_stmt_err(
            "1:13: In call to READ: 1:18: Cannot assign value of type BOOLEAN to variable of type INTEGER",
            "DATA FALSE: READ s%");
    }

    #[test]
    fn test_restore_nothing() {
        Tester::default().run("RESTORE").check();
    }

    #[test]
    fn test_restore_before_read() {
        Tester::default()
            .run(
                r#"
            DATA 3, 5, 7
            RESTORE
            READ i: PRINT i
            READ i: PRINT i
            "#,
            )
            .expect_prints([" 3", " 5"])
            .expect_var("I", Value::Integer(5))
            .check();
    }

    #[test]
    fn test_restore_after_read() {
        Tester::default()
            .run(
                r#"
            DATA 3, -5, 7
            READ i: PRINT i
            READ i: PRINT i
            RESTORE
            READ i: PRINT i
            "#,
            )
            .expect_prints([" 3", "-5", " 3"])
            .expect_var("I", Value::Integer(3))
            .check();
    }

    #[test]
    fn test_restore_errors() {
        check_stmt_err("1:1: In call to RESTORE: expected no arguments", "RESTORE 123");
    }
}