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
// EndBASIC
// Copyright 2021 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.

//! Array-related functions for EndBASIC.

use async_trait::async_trait;
use endbasic_core::ast::{ArgSep, ExprType, VarRef};
use endbasic_core::compiler::{
    ArgSepSyntax, RequiredRefSyntax, RequiredValueSyntax, SingularArgSyntax,
};
use endbasic_core::exec::{Machine, Scope};
use endbasic_core::syms::{
    Array, CallError, CallResult, Callable, CallableMetadata, CallableMetadataBuilder, Symbol,
    Symbols,
};
use std::borrow::Cow;
use std::rc::Rc;

/// Category description for all symbols provided by this module.
const CATEGORY: &str = "Array functions";

/// Extracts the array reference and the dimension number from the list of arguments passed to
/// either `LBOUND` or `UBOUND`.
#[allow(clippy::needless_lifetimes)]
fn parse_bound_args<'a>(
    scope: &mut Scope<'_>,
    symbols: &'a Symbols,
) -> Result<(&'a Array, usize), CallError> {
    let (arrayname, arraytype, arraypos) = scope.pop_varref_with_pos();

    let arrayref = VarRef::new(arrayname.to_string(), Some(arraytype));
    let array = match symbols
        .get(&arrayref)
        .map_err(|e| CallError::ArgumentError(arraypos, format!("{}", e)))?
    {
        Some(Symbol::Array(array)) => array,
        _ => unreachable!(),
    };

    if scope.nargs() == 1 {
        let (i, pos) = scope.pop_integer_with_pos();

        if i < 0 {
            return Err(CallError::ArgumentError(pos, format!("Dimension {} must be positive", i)));
        }
        let i = i as usize;

        if i > array.dimensions().len() {
            return Err(CallError::ArgumentError(
                pos,
                format!(
                    "Array {} has only {} dimensions but asked for {}",
                    arrayname,
                    array.dimensions().len(),
                    i,
                ),
            ));
        }
        Ok((array, i))
    } else {
        debug_assert_eq!(0, scope.nargs());

        if array.dimensions().len() > 1 {
            return Err(CallError::ArgumentError(
                arraypos,
                "Requires a dimension for multidimensional arrays".to_owned(),
            ));
        }

        Ok((array, 1))
    }
}

/// The `LBOUND` function.
pub struct LboundFunction {
    metadata: CallableMetadata,
}

impl LboundFunction {
    /// Creates a new instance of the function.
    pub fn new() -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("LBOUND")
                .with_return_type(ExprType::Integer)
                .with_syntax(&[
                    (
                        &[SingularArgSyntax::RequiredRef(
                            RequiredRefSyntax {
                                name: Cow::Borrowed("array"),
                                require_array: true,
                                define_undefined: false,
                            },
                            ArgSepSyntax::End,
                        )],
                        None,
                    ),
                    (
                        &[
                            SingularArgSyntax::RequiredRef(
                                RequiredRefSyntax {
                                    name: Cow::Borrowed("array"),
                                    require_array: true,
                                    define_undefined: false,
                                },
                                ArgSepSyntax::Exactly(ArgSep::Long),
                            ),
                            SingularArgSyntax::RequiredValue(
                                RequiredValueSyntax {
                                    name: Cow::Borrowed("dimension"),
                                    vtype: ExprType::Integer,
                                },
                                ArgSepSyntax::End,
                            ),
                        ],
                        None,
                    ),
                ])
                .with_category(CATEGORY)
                .with_description(
                    "Returns the lower bound for the given dimension of the array.
The lower bound is the smallest available subscript that can be provided to array indexing \
operations.
For one-dimensional arrays, the dimension% is optional.  For multi-dimensional arrays, the \
dimension% is a 1-indexed integer.",
                )
                .build(),
        })
    }
}

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

    async fn exec(&self, mut scope: Scope<'_>, machine: &mut Machine) -> CallResult {
        let (_array, _dim) = parse_bound_args(&mut scope, machine.get_symbols())?;
        scope.return_integer(0)
    }
}

/// The `UBOUND` function.
pub struct UboundFunction {
    metadata: CallableMetadata,
}

impl UboundFunction {
    /// Creates a new instance of the function.
    pub fn new() -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("UBOUND")
                .with_return_type(ExprType::Integer)
                .with_syntax(&[
                    (
                        &[SingularArgSyntax::RequiredRef(
                            RequiredRefSyntax {
                                name: Cow::Borrowed("array"),
                                require_array: true,
                                define_undefined: false,
                            },
                            ArgSepSyntax::End,
                        )],
                        None,
                    ),
                    (
                        &[
                            SingularArgSyntax::RequiredRef(
                                RequiredRefSyntax {
                                    name: Cow::Borrowed("array"),
                                    require_array: true,
                                    define_undefined: false,
                                },
                                ArgSepSyntax::Exactly(ArgSep::Long),
                            ),
                            SingularArgSyntax::RequiredValue(
                                RequiredValueSyntax {
                                    name: Cow::Borrowed("dimension"),
                                    vtype: ExprType::Integer,
                                },
                                ArgSepSyntax::End,
                            ),
                        ],
                        None,
                    ),
                ])
                .with_category(CATEGORY)
                .with_description(
                    "Returns the upper bound for the given dimension of the array.
The upper bound is the largest available subscript that can be provided to array indexing \
operations.
For one-dimensional arrays, the dimension% is optional.  For multi-dimensional arrays, the \
dimension% is a 1-indexed integer.",
                )
                .build(),
        })
    }
}

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

    async fn exec(&self, mut scope: Scope<'_>, machine: &mut Machine) -> CallResult {
        let (array, dim) = parse_bound_args(&mut scope, machine.get_symbols())?;
        scope.return_integer((array.dimensions()[dim - 1] - 1) as i32)
    }
}

/// Adds all symbols provided by this module to the given `machine`.
pub fn add_all(machine: &mut Machine) {
    machine.add_callable(LboundFunction::new());
    machine.add_callable(UboundFunction::new());
}

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

    /// Validates error handling of `LBOUND` and `UBOUND` as given in `func`.
    fn do_bound_errors_test(func: &str) {
        Tester::default()
            .run(&format!("DIM x(2): result = {}()", func))
            .expect_compilation_err(format!(
                "1:20: In call to {}: expected <array> | <array, dimension%>",
                func
            ))
            .check();

        Tester::default()
            .run(&format!("DIM x(2): result = {}(x, 1, 2)", func))
            .expect_compilation_err(format!(
                "1:20: In call to {}: expected <array> | <array, dimension%>",
                func
            ))
            .check();

        Tester::default()
            .run(&format!("DIM x(2): result = {}(x, -1)", func))
            .expect_err(format!("1:20: In call to {}: 1:30: Dimension -1 must be positive", func))
            .expect_array("x", ExprType::Integer, &[2], vec![])
            .check();

        Tester::default()
            .run(&format!("DIM x(2): result = {}(x, TRUE)", func))
            .expect_compilation_err(format!(
                "1:20: In call to {}: 1:30: BOOLEAN is not a number",
                func
            ))
            .check();

        Tester::default()
            .run(&format!("i = 0: result = {}(i)", func))
            .expect_compilation_err(format!(
                "1:17: In call to {}: 1:24: i is not an array reference",
                func
            ))
            .check();

        Tester::default()
            .run(&format!("result = {}(3)", func))
            .expect_compilation_err(format!(
                "1:10: In call to {}: 1:17: Requires an array reference, not a value",
                func
            ))
            .check();

        Tester::default()
            .run(&format!("i = 0: result = {}(i)", func))
            .expect_compilation_err(format!(
                "1:17: In call to {}: 1:24: i is not an array reference",
                func
            ))
            .check();

        Tester::default()
            .run(&format!("DIM i(3) AS BOOLEAN: result = {}(i$)", func))
            .expect_compilation_err(format!(
                "1:31: In call to {}: 1:38: Incompatible type annotation in i$ reference",
                func
            ))
            .check();

        Tester::default()
            .run(&format!("result = {}(x)", func))
            .expect_compilation_err(format!("1:10: In call to {}: 1:17: Undefined array x", func))
            .check();

        Tester::default()
            .run(&format!("DIM x(2, 3, 4): result = {}(x)", func))
            .expect_err(format!(
                "1:26: In call to {}: 1:33: Requires a dimension for multidimensional arrays",
                func
            ))
            .expect_array("x", ExprType::Integer, &[2, 3, 4], vec![])
            .check();

        Tester::default()
            .run(&format!("DIM x(2, 3, 4): result = {}(x, 5)", func))
            .expect_err(format!(
                "1:26: In call to {}: 1:36: Array X has only 3 dimensions but asked for 5",
                func
            ))
            .expect_array("x", ExprType::Integer, &[2, 3, 4], vec![])
            .check();
    }

    #[test]
    fn test_lbound_ok() {
        Tester::default()
            .run("DIM x(10): result = LBOUND(x)")
            .expect_var("result", 0i32)
            .expect_array("x", ExprType::Integer, &[10], vec![])
            .check();

        Tester::default()
            .run("DIM x(10, 20): result = LBOUND(x, 1)")
            .expect_var("result", 0i32)
            .expect_array("x", ExprType::Integer, &[10, 20], vec![])
            .check();

        Tester::default()
            .run("DIM x(10, 20): result = LBOUND(x, 2.1)")
            .expect_var("result", 0i32)
            .expect_array("x", ExprType::Integer, &[10, 20], vec![])
            .check();
    }

    #[test]
    fn test_lbound_errors() {
        do_bound_errors_test("LBOUND");
    }

    #[test]
    fn test_ubound_ok() {
        Tester::default()
            .run("DIM x(10): result = UBOUND(x)")
            .expect_var("result", 9i32)
            .expect_array("x", ExprType::Integer, &[10], vec![])
            .check();

        Tester::default()
            .run("DIM x(10, 20): result = UBOUND(x, 1)")
            .expect_var("result", 9i32)
            .expect_array("x", ExprType::Integer, &[10, 20], vec![])
            .check();

        Tester::default()
            .run("DIM x(10, 20): result = UBOUND(x, 2.1)")
            .expect_var("result", 19i32)
            .expect_array("x", ExprType::Integer, &[10, 20], vec![])
            .check();
    }

    #[test]
    fn test_ubound_errors() {
        do_bound_errors_test("UBOUND");
    }

    #[test]
    fn test_bound_integration() {
        Tester::default()
            .run("DIM x(5): FOR i = LBOUND(x) TO UBOUND(x): x(i) = i * 2: NEXT")
            .expect_var("i", 5i32)
            .expect_array_simple(
                "x",
                ExprType::Integer,
                vec![0i32.into(), 2i32.into(), 4i32.into(), 6i32.into(), 8i32.into()],
            )
            .check();
    }
}