endbasic-core 0.4.0

The EndBASIC programming language - core
Documentation
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
// EndBASIC
// Copyright 2020 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.

//! Console representation and manipulation.

use crate::ast::{ArgSep, Expr, Value, VarType};
use crate::eval::{CallableMetadata, CallableMetadataBuilder};
use crate::exec::{self, BuiltinCommand, Machine};
use async_trait::async_trait;
use std::cell::RefCell;
use std::io;
use std::rc::Rc;

/// Decoded key presses as returned by the console.
#[derive(Clone, Debug)]
pub enum Key {
    /// The cursor down key.
    ArrowDown,

    /// The cursor left key.
    ArrowLeft,

    /// The cursor right key.
    ArrowRight,

    /// The cursor up key.
    ArrowUp,

    /// Deletes the previous character.
    Backspace,

    /// Accepts the current line.
    CarriageReturn,

    /// A printable character.
    Char(char),

    /// Indicates a request for termination (e.g. `Ctrl-D`).
    Eof,

    /// The escape key.
    Escape,

    /// Indicates a request for interrupt (e.g. `Ctrl-C`).
    // TODO(jmmv): This (and maybe Eof too) should probably be represented as a more generic
    // Control(char) value so that we can represent other control sequences and allow the logic in
    // here to determine what to do with each.
    Interrupt,

    /// Accepts the current line.
    NewLine,

    /// An unknown character or sequence. The text describes what went wrong.
    Unknown(String),
}

/// Indicates what part of the console to clear on a `Console::clear()` call.
#[derive(Debug, Eq, PartialEq)]
pub enum ClearType {
    /// Clears the whole console and moves the cursor to the top left corner.
    All,

    /// Clears only the current line without moving the cursor.
    CurrentLine,

    /// Clears from the cursor position to the end of the line without moving the cursor.
    UntilNewLine,
}

/// Represents a position in the console.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Position {
    /// The row number, starting from zero.
    pub row: usize,

    /// The column number, starting from zero.
    pub column: usize,
}

impl std::ops::Sub for Position {
    type Output = Self;

    fn sub(self, other: Self) -> Self::Output {
        Position { row: self.row - other.row, column: self.column - other.column }
    }
}

/// Hooks to implement the commands that manipulate the console.
#[async_trait(?Send)]
pub trait Console {
    /// Clears the part of the console given by `how`.
    fn clear(&mut self, how: ClearType) -> io::Result<()>;

    /// Sets the console's foreground and background colors to `fg` and `bg`.
    ///
    /// If any of the colors is `None`, the color is left unchanged.
    fn color(&mut self, fg: Option<u8>, bg: Option<u8>) -> io::Result<()>;

    /// Enters the alternate console.
    // TODO(jmmv): This API leads to misuse as callers can forget to leave the alternate console.
    fn enter_alt(&mut self) -> io::Result<()>;

    /// Hides the cursor.
    // TODO(jmmv): This API leads to misuse as callers can forget to show the cursor again.
    fn hide_cursor(&mut self) -> io::Result<()>;

    /// Returns true if the console is attached to an interactive terminal.  This controls whether
    /// reading a line echoes back user input, for example.
    fn is_interactive(&self) -> bool;

    /// Leaves the alternate console.
    fn leave_alt(&mut self) -> io::Result<()>;

    /// Moves the cursor to the given position, which must be within the screen.
    fn locate(&mut self, pos: Position) -> io::Result<()>;

    /// Moves the cursor within the line.  Positive values move right, negative values move left.
    fn move_within_line(&mut self, off: i16) -> io::Result<()>;

    /// Writes `text` to the console, followed by a newline or CRLF pair depending on the needs of
    /// the console to advance a line.
    // TODO(jmmv): Remove this in favor of write?
    fn print(&mut self, text: &str) -> io::Result<()>;

    /// Waits for and returns the next key press.
    async fn read_key(&mut self) -> io::Result<Key>;

    /// Shows the cursor.
    fn show_cursor(&mut self) -> io::Result<()>;

    /// Queries the size of the console.
    ///
    /// The returned position represents the first row and column that lay *outside* of the console.
    fn size(&self) -> io::Result<Position>;

    /// Writes the raw `bytes` into the console.
    fn write(&mut self, bytes: &[u8]) -> io::Result<()>;
}

/// Reads a line of text interactively from the console, using the given `prompt` and pre-filling
/// the input with `previous`.
async fn read_line_interactive(
    console: &mut dyn Console,
    prompt: &str,
    previous: &str,
) -> io::Result<String> {
    let mut line = String::from(previous);
    console.clear(ClearType::UntilNewLine)?;
    if !prompt.is_empty() || !line.is_empty() {
        console.write(format!("{}{}", prompt, line).as_bytes())?;
    }

    let width = {
        // Assumes that the prompt was printed at column 0.  If that was not the case, line length
        // calculation does not work.
        let console_size = console.size()?;
        console_size.column - prompt.len()
    };

    // Insertion position *within* the line, without accounting for the prompt.
    let mut pos = line.len();

    loop {
        match console.read_key().await? {
            Key::ArrowUp | Key::ArrowDown => {
                // TODO(jmmv): Implement history tracking.
            }

            Key::ArrowLeft => {
                if pos > 0 {
                    console.move_within_line(-1)?;
                    pos -= 1;
                }
            }

            Key::ArrowRight => {
                if pos < line.len() {
                    console.move_within_line(1)?;
                    pos += 1;
                }
            }

            Key::Backspace => {
                if pos > 0 {
                    console.hide_cursor()?;
                    console.move_within_line(-1)?;
                    console.write(line[pos..].as_bytes())?;
                    console.write(&[b' '])?;
                    console.move_within_line(-((line.len() - pos) as i16 + 1))?;
                    console.show_cursor()?;
                    line.remove(pos - 1);
                    pos -= 1;
                }
            }

            Key::CarriageReturn => {
                // TODO(jmmv): This is here because the integration tests may be checked out with
                // CRLF line endings on Windows, which means we'd see two characters to end a line
                // instead of one.  Not sure if we should do this or if instead we should ensure
                // the golden data we feed to the tests has single-character line endings.
                if cfg!(not(target_os = "windows")) {
                    console.write(&[b'\r', b'\n'])?;
                    break;
                }
            }

            Key::Char(ch) => {
                debug_assert!(line.len() < width);
                if line.len() == width - 1 {
                    // TODO(jmmv): Implement support for lines that exceed the width of the input
                    // field (the width of the screen).
                    continue;
                }

                if pos < line.len() {
                    console.hide_cursor()?;
                    console.write(&[ch as u8])?;
                    console.write(line[pos..].as_bytes())?;
                    console.move_within_line(-((line.len() - pos) as i16))?;
                    console.show_cursor()?;
                } else {
                    console.write(&[ch as u8])?;
                }
                line.insert(pos, ch);
                pos += 1;
            }

            Key::Eof => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "EOF")),

            Key::Escape => {
                // Intentionally ignored.
            }

            Key::Interrupt => return Err(io::Error::new(io::ErrorKind::Interrupted, "Ctrl+C")),

            Key::NewLine => {
                console.write(&[b'\r', b'\n'])?;
                break;
            }

            // TODO(jmmv): Should do something smarter with unknown keys.
            Key::Unknown(_) => (),
        }
    }
    Ok(line)
}

/// Reads a line of text interactively from the console, which is not expected to be a TTY.
async fn read_line_raw(console: &mut dyn Console) -> io::Result<String> {
    let mut line = String::new();
    loop {
        match console.read_key().await? {
            Key::ArrowUp | Key::ArrowDown | Key::ArrowLeft | Key::ArrowRight => (),
            Key::Backspace => {
                if !line.is_empty() {
                    line.pop();
                }
            }
            Key::CarriageReturn => {
                // TODO(jmmv): This is here because the integration tests may be checked out with
                // CRLF line endings on Windows, which means we'd see two characters to end a line
                // instead of one.  Not sure if we should do this or if instead we should ensure
                // the golden data we feed to the tests has single-character line endings.
                if cfg!(not(target_os = "windows")) {
                    break;
                }
            }
            Key::Char(ch) => line.push(ch),
            Key::Escape => (),
            Key::Eof => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "EOF")),
            Key::Interrupt => return Err(io::Error::new(io::ErrorKind::Interrupted, "Ctrl+C")),
            Key::NewLine => break,
            Key::Unknown(bad_input) => line += &bad_input,
        }
    }
    Ok(line)
}

/// Reads a line from the console.  If the console is interactive, this does fancy line editing and
/// uses the given `prompt` and pre-fills the input with `previous`.
pub async fn read_line(
    console: &mut dyn Console,
    prompt: &str,
    previous: &str,
) -> io::Result<String> {
    if console.is_interactive() {
        read_line_interactive(console, prompt, previous).await
    } else {
        read_line_raw(console).await
    }
}

/// The `CLS` command.
pub struct ClsCommand {
    metadata: CallableMetadata,
    console: Rc<RefCell<dyn Console>>,
}

impl ClsCommand {
    /// Creates a new `CLS` command that clears the `console`.
    pub fn new(console: Rc<RefCell<dyn Console>>) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("CLS", VarType::Void)
                .with_syntax("")
                .with_category("Console manipulation")
                .with_description("Clears the screen.")
                .build(),
            console,
        })
    }
}

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

    async fn exec(
        &self,
        args: &[(Option<Expr>, ArgSep)],
        _machine: &mut Machine,
    ) -> exec::Result<()> {
        if !args.is_empty() {
            return exec::new_usage_error("CLS takes no arguments");
        }
        self.console.borrow_mut().clear(ClearType::All)?;
        Ok(())
    }
}

/// The `COLOR` command.
pub struct ColorCommand {
    metadata: CallableMetadata,
    console: Rc<RefCell<dyn Console>>,
}

impl ColorCommand {
    /// Creates a new `COLOR` command that changes the color of the `console`.
    pub fn new(console: Rc<RefCell<dyn Console>>) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("COLOR", VarType::Void)
                .with_syntax("[fg%][, [bg%]]")
                .with_category("Console manipulation")
                .with_description(
                    "Sets the foreground and background colors.
Color numbers are given as ANSI numbers and can be between 0 and 255.  If a color number is not \
specified, then the color is reset to the console's default.  The console default does not \
necessarily match any other color specifiable in the 0 to 255 range, as it might be transparent.",
                )
                .build(),
            console,
        })
    }
}

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

    async fn exec(
        &self,
        args: &[(Option<Expr>, ArgSep)],
        machine: &mut Machine,
    ) -> exec::Result<()> {
        let (fg_expr, bg_expr): (&Option<Expr>, &Option<Expr>) = match args {
            [] => (&None, &None),
            [(fg, ArgSep::End)] => (fg, &None),
            [(fg, ArgSep::Long), (bg, ArgSep::End)] => (fg, bg),
            _ => {
                return exec::new_usage_error(
                    "COLOR takes at most two arguments separated by a comma",
                )
            }
        };

        fn get_color(e: &Option<Expr>, machine: &Machine) -> exec::Result<Option<u8>> {
            match e {
                Some(e) => match e.eval(machine.get_vars(), machine.get_functions())? {
                    Value::Integer(i) if i >= 0 && i <= std::u8::MAX as i32 => Ok(Some(i as u8)),
                    Value::Integer(_) => exec::new_usage_error("Color out of range"),
                    _ => exec::new_usage_error("Color must be an integer"),
                },
                None => Ok(None),
            }
        }

        let fg = get_color(fg_expr, machine)?;
        let bg = get_color(bg_expr, machine)?;

        self.console.borrow_mut().color(fg, bg)?;
        Ok(())
    }
}

/// The `INPUT` command.
pub struct InputCommand {
    metadata: CallableMetadata,
    console: Rc<RefCell<dyn Console>>,
}

impl InputCommand {
    /// Creates a new `INPUT` command that uses `console` to gather user input.
    pub fn new(console: Rc<RefCell<dyn Console>>) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("INPUT", VarType::Void)
                .with_syntax("[\"prompt\"] <;|,> variableref")
                .with_category("Console manipulation")
                .with_description(
                    "Obtains user input from the console.
The first expression to this function must be empty or evaluate to a string, and specifies \
the prompt to print.  If this first argument is followed by the short `;` separator, the \
prompt is extended with a question mark.
The second expression to this function must be a bare variable reference and indicates the \
variable to update with the obtained input.",
                )
                .build(),
            console,
        })
    }
}

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

    async fn exec(
        &self,
        args: &[(Option<Expr>, ArgSep)],
        machine: &mut Machine,
    ) -> exec::Result<()> {
        if args.len() != 2 {
            return exec::new_usage_error("INPUT requires two arguments");
        }

        let mut prompt = match &args[0].0 {
            Some(e) => match e.eval(machine.get_vars(), machine.get_functions())? {
                Value::Text(t) => t,
                _ => return exec::new_usage_error("INPUT prompt must be a string"),
            },
            None => "".to_owned(),
        };
        if let ArgSep::Short = args[0].1 {
            prompt += "? ";
        }

        let vref = match &args[1].0 {
            Some(Expr::Symbol(vref)) => vref,
            _ => return exec::new_usage_error("INPUT requires a variable reference"),
        };

        let mut console = self.console.borrow_mut();
        let mut previous_answer = String::new();
        loop {
            match read_line(&mut *console, &prompt, &previous_answer).await {
                Ok(answer) => match Value::parse_as(vref.ref_type(), answer.trim_end()) {
                    Ok(value) => {
                        machine.get_mut_vars().set(vref, value)?;
                        return Ok(());
                    }
                    Err(e) => {
                        console.print(&format!("Retry input: {}", e))?;
                        previous_answer = answer;
                    }
                },
                Err(e) if e.kind() == io::ErrorKind::InvalidData => {
                    console.print(&format!("Retry input: {}", e))?
                }
                Err(e) => return Err(e.into()),
            }
        }
    }
}

/// The `LOCATE` command.
pub struct LocateCommand {
    metadata: CallableMetadata,
    console: Rc<RefCell<dyn Console>>,
}

impl LocateCommand {
    /// Creates a new `LOCATE` command that moves the cursor of the `console`.
    pub fn new(console: Rc<RefCell<dyn Console>>) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("LOCATE", VarType::Void)
                .with_syntax("row%, column%")
                .with_category("Console manipulation")
                .with_description("Moves the cursor to the given position.")
                .build(),
            console,
        })
    }
}

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

    async fn exec(
        &self,
        args: &[(Option<Expr>, ArgSep)],
        machine: &mut Machine,
    ) -> exec::Result<()> {
        if args.len() != 2 {
            return exec::new_usage_error("LOCATE takes two arguments");
        }
        let (row_arg, column_arg) = (&args[0], &args[1]);
        if row_arg.1 != ArgSep::Long {
            return exec::new_usage_error("LOCATE expects arguments separated by a comma");
        }
        debug_assert!(column_arg.1 == ArgSep::End);

        let row = match &row_arg.0 {
            Some(arg) => match arg.eval(machine.get_vars(), machine.get_functions())? {
                Value::Integer(i) => {
                    if i < 0 {
                        return exec::new_usage_error("Row cannot be negative");
                    }
                    i as usize
                }
                _ => return exec::new_usage_error("Row must be an integer"),
            },
            None => return exec::new_usage_error("Row cannot be empty"),
        };

        let column = match &column_arg.0 {
            Some(arg) => match arg.eval(machine.get_vars(), machine.get_functions())? {
                Value::Integer(i) => {
                    if i < 0 {
                        return exec::new_usage_error("Column cannot be negative");
                    }
                    i as usize
                }
                _ => return exec::new_usage_error("Column must be an integer"),
            },
            None => return exec::new_usage_error("Column cannot be empty"),
        };

        self.console.borrow_mut().locate(Position { row, column })?;
        Ok(())
    }
}

/// The `PRINT` command.
pub struct PrintCommand {
    metadata: CallableMetadata,
    console: Rc<RefCell<dyn Console>>,
}

impl PrintCommand {
    /// Creates a new `PRINT` command that writes to `console`.
    pub fn new(console: Rc<RefCell<dyn Console>>) -> Rc<Self> {
        Rc::from(Self {
            metadata: CallableMetadataBuilder::new("PRINT", VarType::Void)
                .with_syntax("[expr1 [<;|,> .. exprN]]")
                .with_category("Console manipulation")
                .with_description(
                    "Prints a message to the console.
The expressions given as arguments are all evaluated and converted to strings.  Arguments \
separated by the short `;` separator are concatenated with a single space, while arguments \
separated by the long `,` separator are concatenated with a tab character.",
                )
                .build(),
            console,
        })
    }
}

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

    async fn exec(
        &self,
        args: &[(Option<Expr>, ArgSep)],
        machine: &mut Machine,
    ) -> exec::Result<()> {
        let mut text = String::new();
        for arg in args.iter() {
            if let Some(expr) = arg.0.as_ref() {
                text += &expr.eval(machine.get_vars(), machine.get_functions())?.to_string();
            }
            match arg.1 {
                ArgSep::End => break,
                ArgSep::Short => text += " ",
                ArgSep::Long => text += "\t",
            }
        }
        self.console.borrow_mut().print(&text)?;
        Ok(())
    }
}

/// Adds all console-related commands for the given `console` to the `machine`.
pub fn all_commands(console: Rc<RefCell<dyn Console>>) -> Vec<Rc<dyn BuiltinCommand>> {
    vec![
        ClsCommand::new(console.clone()),
        ColorCommand::new(console.clone()),
        InputCommand::new(console.clone()),
        LocateCommand::new(console.clone()),
        PrintCommand::new(console),
    ]
}

#[cfg(test)]
pub(crate) mod testutils {
    use super::*;
    use std::collections::VecDeque;
    use std::io;

    /// A captured command or messages sent to the mock console.
    #[derive(Debug, Eq, PartialEq)]
    pub(crate) enum CapturedOut {
        Clear(ClearType),
        Color(Option<u8>, Option<u8>),
        EnterAlt,
        HideCursor,
        LeaveAlt,
        Locate(Position),
        MoveWithinLine(i16),
        Print(String),
        ShowCursor,
        Write(Vec<u8>),
    }

    /// A console that supplies golden input and captures all output.
    pub(crate) struct MockConsole {
        /// Sequence of keys to yield on `read_key` calls.
        golden_in: VecDeque<Key>,

        /// Sequence of all messages printed.
        captured_out: Vec<CapturedOut>,

        /// The size of the mock console.
        size: Position,
    }

    impl MockConsole {
        /// Obtains a reference to the captured output.
        pub(crate) fn captured_out(&self) -> &[CapturedOut] {
            self.captured_out.as_slice()
        }
    }

    impl Drop for MockConsole {
        fn drop(&mut self) {
            assert!(
                self.golden_in.is_empty(),
                "Not all golden input chars were consumed; {} left",
                self.golden_in.len()
            );
        }
    }

    #[async_trait(?Send)]
    impl Console for MockConsole {
        fn clear(&mut self, how: ClearType) -> io::Result<()> {
            self.captured_out.push(CapturedOut::Clear(how));
            Ok(())
        }

        fn color(&mut self, fg: Option<u8>, bg: Option<u8>) -> io::Result<()> {
            self.captured_out.push(CapturedOut::Color(fg, bg));
            Ok(())
        }

        fn enter_alt(&mut self) -> io::Result<()> {
            self.captured_out.push(CapturedOut::EnterAlt);
            Ok(())
        }

        fn hide_cursor(&mut self) -> io::Result<()> {
            self.captured_out.push(CapturedOut::HideCursor);
            Ok(())
        }

        fn is_interactive(&self) -> bool {
            false
        }

        fn leave_alt(&mut self) -> io::Result<()> {
            self.captured_out.push(CapturedOut::LeaveAlt);
            Ok(())
        }

        fn locate(&mut self, pos: Position) -> io::Result<()> {
            self.captured_out.push(CapturedOut::Locate(pos));
            Ok(())
        }

        fn move_within_line(&mut self, off: i16) -> io::Result<()> {
            self.captured_out.push(CapturedOut::MoveWithinLine(off));
            Ok(())
        }

        fn print(&mut self, text: &str) -> io::Result<()> {
            self.captured_out.push(CapturedOut::Print(text.to_owned()));
            Ok(())
        }

        async fn read_key(&mut self) -> io::Result<Key> {
            match self.golden_in.pop_front() {
                Some(ch) => Ok(ch),
                None => Ok(Key::Eof),
            }
        }

        fn show_cursor(&mut self) -> io::Result<()> {
            self.captured_out.push(CapturedOut::ShowCursor);
            Ok(())
        }

        fn size(&self) -> io::Result<Position> {
            Ok(self.size)
        }

        fn write(&mut self, bytes: &[u8]) -> io::Result<()> {
            self.captured_out.push(CapturedOut::Write(bytes.to_owned()));
            Ok(())
        }
    }

    /// Builder pattern for a `MockConsole`.
    pub(crate) struct MockConsoleBuilder {
        golden_in: VecDeque<Key>,
        size: Position,
    }

    impl MockConsoleBuilder {
        /// Creates a new console builder, with no golden input and an infinite size.
        pub(crate) fn new() -> Self {
            Self {
                golden_in: VecDeque::new(),
                size: Position { row: usize::MAX, column: usize::MAX },
            }
        }

        /// Adds a bunch of characters as golden input keys.
        ///
        /// Note that some escape characters within `s` are interpreted and added as their
        /// corresponding `Key`s for simplicity.
        pub(crate) fn add_input_chars(mut self, s: &str) -> Self {
            for ch in s.chars() {
                match ch {
                    '\n' => self.golden_in.push_back(Key::NewLine),
                    '\r' => self.golden_in.push_back(Key::CarriageReturn),
                    ch => self.golden_in.push_back(Key::Char(ch)),
                }
            }
            self
        }

        /// Adds a bunch of keys as golden input.
        pub(crate) fn add_input_keys(mut self, keys: &[Key]) -> Self {
            self.golden_in.extend(keys.iter().cloned());
            self
        }

        /// Sets the size of the mock console.
        pub(crate) fn with_size(mut self, size: Position) -> Self {
            self.size = size;
            self
        }

        /// Builds a `MockConsole` instance as configured in the builder.
        pub(crate) fn build(self) -> MockConsole {
            MockConsole { golden_in: self.golden_in, captured_out: vec![], size: self.size }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::testutils::*;
    use super::*;
    use crate::exec::MachineBuilder;
    use futures_lite::future::block_on;

    /// Builder pattern to construct a test for `read_line_interactive`.
    #[must_use]
    struct ReadLineInteractiveTest {
        keys: Vec<Key>,
        prompt: &'static str,
        previous: &'static str,
        exp_line: &'static str,
        exp_output: Vec<CapturedOut>,
    }

    impl ReadLineInteractiveTest {
        /// Constructs a new test that feeds no input to the function, with no prompt or previous
        /// text, and expects an empty return line and no changes to the console.
        fn new() -> Self {
            Self {
                keys: vec![],
                prompt: "",
                previous: "",
                exp_line: "",
                exp_output: vec![CapturedOut::Clear(ClearType::UntilNewLine)],
            }
        }

        /// Adds `key` to the golden input.
        fn add_key(mut self, key: Key) -> Self {
            self.keys.push(key);
            self
        }

        /// Adds a bunch of `chars` as individual key presses to the golden input.
        fn add_key_chars(mut self, chars: &'static str) -> Self {
            for ch in chars.chars() {
                self.keys.push(Key::Char(ch));
            }
            self
        }

        /// Adds a single state change to the expected output.
        fn add_output(mut self, output: CapturedOut) -> Self {
            self.exp_output.push(output);
            self
        }

        /// Adds a bunch of `bytes` as separate console writes to the expected output.
        fn add_output_bytes(mut self, bytes: &'static [u8]) -> Self {
            if bytes.is_empty() {
                self.exp_output.push(CapturedOut::Write(vec![]))
            } else {
                for b in bytes.iter() {
                    self.exp_output.push(CapturedOut::Write(vec![*b]))
                }
            }
            self
        }

        /// Sets the expected resulting line for the test.
        fn set_line(mut self, line: &'static str) -> Self {
            self.exp_line = line;
            self
        }

        /// Sets the prompt to use for the test.
        fn set_prompt(mut self, prompt: &'static str) -> Self {
            self.prompt = prompt;
            self
        }

        /// Sets the previous text to use for the test.
        fn set_previous(mut self, previous: &'static str) -> Self {
            self.previous = previous;
            self
        }

        /// Adds a final return key to the golden input, a newline to the expected output, and
        /// executes the test.
        fn accept(mut self) {
            self.keys.push(Key::NewLine);
            self.exp_output.push(CapturedOut::Write(vec![b'\r', b'\n']));

            let mut console = MockConsoleBuilder::new()
                .add_input_keys(&self.keys)
                .with_size(Position { row: 5, column: 15 })
                .build();
            let line =
                block_on(read_line_interactive(&mut console, self.prompt, self.previous)).unwrap();
            assert_eq!(self.exp_line, &line);
            assert_eq!(self.exp_output.as_slice(), console.captured_out());
        }
    }

    #[test]
    fn test_read_line_interactive_empty() {
        ReadLineInteractiveTest::new().accept();
        ReadLineInteractiveTest::new().add_key(Key::Backspace).accept();
        ReadLineInteractiveTest::new().add_key(Key::ArrowLeft).accept();
        ReadLineInteractiveTest::new().add_key(Key::ArrowRight).accept();
    }

    #[test]
    fn test_read_line_with_prompt() {
        ReadLineInteractiveTest::new()
            .set_prompt("Ready> ")
            .add_output(CapturedOut::Write(b"Ready> ".to_vec()))
            // -
            .add_key_chars("hello")
            .add_output_bytes(b"hello")
            // -
            .set_line("hello")
            .accept();

        ReadLineInteractiveTest::new()
            .set_prompt("Cannot delete")
            .add_output(CapturedOut::Write(b"Cannot delete".to_vec()))
            // -
            .add_key(Key::Backspace)
            .accept();
    }

    #[test]
    fn test_read_line_interactive_trailing_input() {
        ReadLineInteractiveTest::new()
            .add_key_chars("hello")
            .add_output_bytes(b"hello")
            // -
            .set_line("hello")
            .accept();

        ReadLineInteractiveTest::new()
            .set_previous("123")
            .add_output(CapturedOut::Write(b"123".to_vec()))
            // -
            .add_key_chars("hello")
            .add_output_bytes(b"hello")
            // -
            .set_line("123hello")
            .accept();
    }

    #[test]
    fn test_read_line_interactive_middle_input() {
        ReadLineInteractiveTest::new()
            .add_key_chars("some text")
            .add_output_bytes(b"some text")
            // -
            .add_key(Key::ArrowLeft)
            .add_output(CapturedOut::MoveWithinLine(-1))
            // -
            .add_key(Key::ArrowLeft)
            .add_output(CapturedOut::MoveWithinLine(-1))
            // -
            .add_key(Key::ArrowLeft)
            .add_output(CapturedOut::MoveWithinLine(-1))
            // -
            .add_key(Key::ArrowRight)
            .add_output(CapturedOut::MoveWithinLine(1))
            // -
            .add_key_chars(" ")
            .add_output(CapturedOut::HideCursor)
            .add_output_bytes(b" ")
            .add_output(CapturedOut::Write(b"xt".to_vec()))
            .add_output(CapturedOut::MoveWithinLine(-2))
            .add_output(CapturedOut::ShowCursor)
            // -
            .add_key_chars(".")
            .add_output(CapturedOut::HideCursor)
            .add_output_bytes(b".")
            .add_output(CapturedOut::Write(b"xt".to_vec()))
            .add_output(CapturedOut::MoveWithinLine(-2))
            .add_output(CapturedOut::ShowCursor)
            // -
            .set_line("some te .xt")
            .accept();
    }

    #[test]
    fn test_read_line_interactive_trailing_backspace() {
        ReadLineInteractiveTest::new()
            .add_key_chars("bar")
            .add_output_bytes(b"bar")
            // -
            .add_key(Key::Backspace)
            .add_output(CapturedOut::HideCursor)
            .add_output(CapturedOut::MoveWithinLine(-1))
            .add_output_bytes(b"")
            .add_output_bytes(b" ")
            .add_output(CapturedOut::MoveWithinLine(-1))
            .add_output(CapturedOut::ShowCursor)
            // -
            .add_key_chars("zar")
            .add_output_bytes(b"zar")
            // -
            .set_line("bazar")
            .accept();
    }

    #[test]
    fn test_read_line_interactive_middle_backspace() {
        ReadLineInteractiveTest::new()
            .add_key_chars("has a tYpo")
            .add_output_bytes(b"has a tYpo")
            // -
            .add_key(Key::ArrowLeft)
            .add_output(CapturedOut::MoveWithinLine(-1))
            // -
            .add_key(Key::ArrowLeft)
            .add_output(CapturedOut::MoveWithinLine(-1))
            // -
            .add_key(Key::Backspace)
            .add_output(CapturedOut::HideCursor)
            .add_output(CapturedOut::MoveWithinLine(-1))
            .add_output(CapturedOut::Write(b"po".to_vec()))
            .add_output_bytes(b" ")
            .add_output(CapturedOut::MoveWithinLine(-3))
            .add_output(CapturedOut::ShowCursor)
            // -
            .add_key_chars("y")
            .add_output(CapturedOut::HideCursor)
            .add_output_bytes(b"y")
            .add_output(CapturedOut::Write(b"po".to_vec()))
            .add_output(CapturedOut::MoveWithinLine(-2))
            .add_output(CapturedOut::ShowCursor)
            // -
            .set_line("has a typo")
            .accept();
    }

    #[test]
    fn test_read_line_interactive_test_move_bounds() {
        ReadLineInteractiveTest::new()
            .set_previous("12")
            .add_output(CapturedOut::Write(b"12".to_vec()))
            // -
            .add_key(Key::ArrowLeft)
            .add_output(CapturedOut::MoveWithinLine(-1))
            // -
            .add_key(Key::ArrowLeft)
            .add_output(CapturedOut::MoveWithinLine(-1))
            // -
            .add_key(Key::ArrowLeft)
            .add_key(Key::ArrowLeft)
            .add_key(Key::ArrowLeft)
            .add_key(Key::ArrowLeft)
            // -
            .add_key(Key::ArrowRight)
            .add_output(CapturedOut::MoveWithinLine(1))
            // -
            .add_key(Key::ArrowRight)
            .add_output(CapturedOut::MoveWithinLine(1))
            // -
            .add_key(Key::ArrowRight)
            .add_key(Key::ArrowRight)
            // -
            .add_key_chars("3")
            .add_output_bytes(b"3")
            // -
            .set_line("123")
            .accept();
    }

    #[test]
    fn test_read_line_interactive_horizontal_scrolling_not_implemented() {
        ReadLineInteractiveTest::new()
            .add_key_chars("1234567890123456789")
            .add_output_bytes(b"12345678901234")
            // -
            .set_line("12345678901234")
            .accept();

        ReadLineInteractiveTest::new()
            .add_key_chars("1234567890123456789")
            .add_output_bytes(b"12345678901234")
            // -
            .add_key(Key::ArrowLeft)
            .add_output(CapturedOut::MoveWithinLine(-1))
            // -
            .add_key(Key::ArrowLeft)
            .add_output(CapturedOut::MoveWithinLine(-1))
            // -
            .add_key_chars("these will all be ignored")
            // -
            .set_line("12345678901234")
            .accept();

        ReadLineInteractiveTest::new()
            .set_prompt("12345")
            .set_previous("67890")
            .add_output(CapturedOut::Write(b"1234567890".to_vec()))
            // -
            .add_key_chars("1234567890")
            .add_output_bytes(b"1234")
            // -
            .set_line("678901234")
            .accept();
    }

    #[test]
    fn test_read_line_interactive_history_not_implemented() {
        ReadLineInteractiveTest::new().add_key(Key::ArrowUp).accept();
        ReadLineInteractiveTest::new().add_key(Key::ArrowDown).accept();
    }

    #[test]
    fn test_read_line_ignored_keys() {
        ReadLineInteractiveTest::new()
            .add_key_chars("not ")
            .add_output_bytes(b"not ")
            // -
            .add_key(Key::Escape)
            // -
            .add_key_chars("affected")
            .add_output_bytes(b"affected")
            // -
            .set_line("not affected")
            .accept();
    }

    /// Runs the `input` code on a new machine and verifies its output.
    ///
    /// `golden_in` is a sequence of keys to feed to the commands that request console input.
    ///
    /// `expected_out` is a sequence of expected commands or messages.
    fn do_control_ok_test(input: &str, golden_in: &'static str, expected_out: &[CapturedOut]) {
        let console =
            Rc::from(RefCell::from(MockConsoleBuilder::new().add_input_chars(golden_in).build()));
        let mut machine =
            MachineBuilder::default().add_commands(all_commands(console.clone())).build();
        block_on(machine.exec(&mut input.as_bytes())).expect("Execution failed");
        assert_eq!(expected_out, console.borrow().captured_out());
    }

    /// Same as `do_control_ok_test` but with `expected_out` being just a sequence of expected
    /// `PRINT` calls.
    fn do_ok_test(input: &str, golden_in: &'static str, expected_out: &'static [&'static str]) {
        let expected_out: Vec<CapturedOut> =
            expected_out.iter().map(|x| CapturedOut::Print((*x).to_owned())).collect();
        do_control_ok_test(input, golden_in, &expected_out)
    }

    /// Runs the `input` code on a new machine and verifies that it fails with `expected_err`.
    ///
    /// Given that the code has side-effects until it fails, this follows the same process as
    /// `do_ok_test` regarding `golden_in` and `expected_out`.
    fn do_error_test(
        input: &str,
        golden_in: &'static str,
        expected_out: &'static [&'static str],
        expected_err: &str,
    ) {
        let console =
            Rc::from(RefCell::from(MockConsoleBuilder::new().add_input_chars(golden_in).build()));
        let mut machine =
            MachineBuilder::default().add_commands(all_commands(console.clone())).build();
        assert_eq!(
            expected_err,
            format!(
                "{}",
                block_on(machine.exec(&mut input.as_bytes())).expect_err("Execution did not fail")
            )
        );
        let expected_out: Vec<CapturedOut> =
            expected_out.iter().map(|x| CapturedOut::Print((*x).to_owned())).collect();
        assert_eq!(expected_out, console.borrow().captured_out());
    }

    /// Runs the `input` code on a new machine and verifies that it fails with `expected_err`.
    ///
    /// This is a syntactic wrapper over `do_error_test` to simplify those tests that are not
    /// expected to request any input nor generate any output.
    fn do_simple_error_test(input: &str, expected_err: &str) {
        do_error_test(input, "", &[], expected_err);
    }

    #[test]
    fn test_cls_ok() {
        do_control_ok_test("CLS", "", &[CapturedOut::Clear(ClearType::All)]);
    }

    #[test]
    fn test_cls_errors() {
        do_simple_error_test("CLS 1", "CLS takes no arguments");
    }

    #[test]
    fn test_color_ok() {
        do_control_ok_test("COLOR", "", &[CapturedOut::Color(None, None)]);
        do_control_ok_test("COLOR ,", "", &[CapturedOut::Color(None, None)]);
        do_control_ok_test("COLOR 1", "", &[CapturedOut::Color(Some(1), None)]);
        do_control_ok_test("COLOR 1,", "", &[CapturedOut::Color(Some(1), None)]);
        do_control_ok_test("COLOR , 1", "", &[CapturedOut::Color(None, Some(1))]);
        do_control_ok_test("COLOR 10, 5", "", &[CapturedOut::Color(Some(10), Some(5))]);
        do_control_ok_test("COLOR 0, 0", "", &[CapturedOut::Color(Some(0), Some(0))]);
        do_control_ok_test("COLOR 255, 255", "", &[CapturedOut::Color(Some(255), Some(255))]);
    }

    #[test]
    fn test_color_errors() {
        do_simple_error_test(
            "COLOR 1, 2, 3",
            "COLOR takes at most two arguments separated by a comma",
        );

        do_simple_error_test("COLOR 1000, 0", "Color out of range");
        do_simple_error_test("COLOR 0, 1000", "Color out of range");

        do_simple_error_test("COLOR TRUE, 0", "Color must be an integer");
        do_simple_error_test("COLOR 0, TRUE", "Color must be an integer");
    }

    #[test]
    fn test_input_ok() {
        do_ok_test("INPUT ; foo\nPRINT foo", "9\n", &["9"]);
        do_ok_test("INPUT ; foo\nPRINT foo", "-9\n", &["-9"]);
        do_ok_test("INPUT , bar?\nPRINT bar", "true\n", &["TRUE"]);
        do_ok_test("INPUT ; foo$\nPRINT foo", "\n", &[""]);
        do_ok_test(
            "INPUT \"With question mark\"; a$\nPRINT a$",
            "some long text\n",
            &["some long text"],
        );
        do_ok_test(
            "prompt$ = \"Indirectly without question mark\"\nINPUT prompt$, b\nPRINT b * 2",
            "42\n",
            &["84"],
        );
    }

    #[test]
    fn test_input_retry() {
        do_ok_test("INPUT ; b?", "\ntrue\n", &["Retry input: Invalid boolean literal "]);
        do_ok_test("INPUT ; b?", "0\ntrue\n", &["Retry input: Invalid boolean literal 0"]);
        do_ok_test("a = 3\nINPUT ; a", "\n7\n", &["Retry input: Invalid integer literal "]);
        do_ok_test("a = 3\nINPUT ; a", "x\n7\n", &["Retry input: Invalid integer literal x"]);
    }

    #[test]
    fn test_input_errors() {
        do_simple_error_test("INPUT", "INPUT requires two arguments");
        do_simple_error_test("INPUT ; ,", "INPUT requires two arguments");
        do_simple_error_test("INPUT ;", "INPUT requires a variable reference");
        do_simple_error_test("INPUT 3 ; a", "INPUT prompt must be a string");
        do_simple_error_test("INPUT ; a + 1", "INPUT requires a variable reference");
        do_simple_error_test("INPUT \"a\" + TRUE; b?", "Cannot add Text(\"a\") and Boolean(true)");
    }

    #[test]
    fn test_locate_ok() {
        do_control_ok_test(
            "LOCATE 0, 0",
            "",
            &[CapturedOut::Locate(Position { row: 0, column: 0 })],
        );
        do_control_ok_test(
            "LOCATE 1000, 2000",
            "",
            &[CapturedOut::Locate(Position { row: 1000, column: 2000 })],
        );
    }

    #[test]
    fn test_locate_errors() {
        do_simple_error_test("LOCATE", "LOCATE takes two arguments");
        do_simple_error_test("LOCATE 1", "LOCATE takes two arguments");
        do_simple_error_test("LOCATE 1, 2, 3", "LOCATE takes two arguments");
        do_simple_error_test("LOCATE 1; 2", "LOCATE expects arguments separated by a comma");

        do_simple_error_test("LOCATE -1, 2", "Row cannot be negative");
        do_simple_error_test("LOCATE TRUE, 2", "Row must be an integer");
        do_simple_error_test("LOCATE , 2", "Row cannot be empty");

        do_simple_error_test("LOCATE 1, -2", "Column cannot be negative");
        do_simple_error_test("LOCATE 1, TRUE", "Column must be an integer");
        do_simple_error_test("LOCATE 1,", "Column cannot be empty");
    }

    #[test]
    fn test_print_ok() {
        do_ok_test("PRINT", "", &[""]);
        do_ok_test("PRINT ;", "", &[" "]);
        do_ok_test("PRINT ,", "", &["\t"]);
        do_ok_test("PRINT ;,;,", "", &[" \t \t"]);

        do_ok_test("PRINT 3", "", &["3"]);
        do_ok_test("PRINT 3 = 5", "", &["FALSE"]);
        do_ok_test("PRINT true;123;\"foo bar\"", "", &["TRUE 123 foo bar"]);
        do_ok_test("PRINT 6,1;3,5", "", &["6\t1 3\t5"]);

        do_ok_test(
            "word = \"foo\"\nPRINT word, word\nPRINT word + \"s\"",
            "",
            &["foo\tfoo", "foos"],
        );
    }

    #[test]
    fn test_print_errors() {
        // Ensure type errors from `Expr` and `Value` bubble up.
        do_simple_error_test("PRINT a b", "Unexpected value in expression");
        do_simple_error_test("PRINT 3 + TRUE", "Cannot add Integer(3) and Boolean(true)");
    }
}