-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathexec.rs
More file actions
3563 lines (3141 loc) · 118 KB
/
exec.rs
File metadata and controls
3563 lines (3141 loc) · 118 KB
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
// 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.
//! Execution engine for EndBASIC programs.
use crate::ast::*;
use crate::bytecode::*;
use crate::compiler;
use crate::reader::LineCol;
use crate::syms::{Callable, Symbol, SymbolKey, Symbols};
use crate::value;
use crate::value::double_to_integer;
use async_channel::{Receiver, Sender, TryRecvError};
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::rc::Rc;
/// Execution errors.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// Compilation error during execution.
#[error("{0}")]
CompilerError(#[from] compiler::Error),
/// Evaluation error during execution.
#[error("{0}: {1}")]
EvalError(LineCol, String),
/// Any other error not representable by other values.
#[error("{0}: {1}")]
InternalError(LineCol, String),
/// I/O error during execution.
#[error("{0}: {1}")]
IoError(LineCol, io::Error),
/// Syntax error.
#[error("{0}: {1}")]
SyntaxError(LineCol, String),
}
impl Error {
/// Annotates a value computation error with a position.
fn from_value_error(e: value::Error, pos: LineCol) -> Self {
Self::EvalError(pos, e.message)
}
/// Returns true if this type of error can be caught by `ON ERROR`.
fn is_catchable(&self) -> bool {
match self {
Error::CompilerError(_) => false,
Error::EvalError(..) => true,
Error::InternalError(..) => true,
Error::IoError(..) => true,
Error::SyntaxError(..) => true,
}
}
}
/// Result for execution return values.
pub type Result<T> = std::result::Result<T, Error>;
/// Instantiates a new `Err(Error::SyntaxError(...))` from a message. Syntactic sugar.
fn new_syntax_error<T, S: Into<String>>(pos: LineCol, message: S) -> Result<T> {
Err(Error::SyntaxError(pos, message.into()))
}
/// Signals that can be delivered to the machine.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Signal {
/// Asks the machine to stop execution of the currently-running program.
Break,
}
/// Request to exit the VM execution loop to execute a native command or function.
#[derive(Clone, Debug, Eq, PartialEq)]
struct UpcallData {
/// Index of the upcall to execute.
index: usize,
/// Name of the callable to execute.
name: SymbolKey,
/// Expected type of the value returned by the callable (if a function).
return_type: Option<ExprType>,
/// Position of the invocation.
pos: LineCol,
/// Number of arguments to extract from the stack for the invocation.
nargs: usize,
}
/// Describes how the machine stopped execution while it was running a portion of a script.
///
/// This is different from `StopReason` which represents "user-visible" stop conditions. Instead,
/// the stop conditions represented by this enum are "internal". The bytecode interpreter may have
/// to exit from its inner loop to perform "expensive" operations, which are all still handled here.
///
/// One reason for the entries in this enum, such as `CheckStop` and `Upcall`, is to keep the tight
/// inner loop of the bytecode interpreter sync. Early benchmarks showed a 25% performance
/// improvement just by removing async from the loop and pushing the infrequent async awaits to an
/// outer loop.
enum InternalStopReason {
/// Execution terminated because the bytecode reached a point in the instructions where an
/// interruption, if any, should be processed.
CheckStop,
/// Execution terminated because the machine reached the end of the input.
Eof,
/// Execution terminated because the machine was asked to terminate with `END`.
Exited(u8),
/// Execution terminated because the bytecode requires the caller to issue a builtin function
/// or command call.
Upcall(UpcallData),
}
/// Describes how the machine stopped execution while it was running a script via `exec()`.
#[derive(Clone, Debug, Eq, PartialEq)]
#[must_use]
pub enum StopReason {
/// Execution terminated because the machine reached the end of the input.
Eof,
/// Execution terminated because the machine was asked to terminate with `END`.
Exited(u8),
/// Execution terminated because the machine received a break signal.
Break,
}
impl StopReason {
/// Converts the stop reason into a process exit code.
pub fn as_exit_code(&self) -> i32 {
match self {
StopReason::Eof => 0,
StopReason::Exited(i) => *i as i32,
StopReason::Break => {
// This mimics the behavior of typical Unix shells, which translate a signal to a
// numerical exit code, but this is not accurate. First, because a CTRL+C sequence
// should be exposed as a SIGINT signal to whichever process is waiting for us, and
// second because this is not meaningful on Windows. But for now this will do.
const SIGINT: i32 = 2;
128 + SIGINT
}
}
}
}
/// Trait for objects that maintain state that can be reset to defaults.
pub trait Clearable {
/// Resets any state held by the object to default values. `syms` contain the symbols of the
/// machine before they are cleared, in case some state is held in them too.
fn reset_state(&self, syms: &mut Symbols);
}
/// Type of the function used by the execution loop to yield execution.
pub type YieldNowFn = Box<dyn Fn() -> Pin<Box<dyn Future<Output = ()> + 'static>>>;
/// Tags used in the value stack to identify the type of their corresponding value.
pub enum ValueTag {
/// Represents that there is no next value to consume. Can only appear for command invocations.
Missing = 0,
/// Represents that the next value to consume is a boolean.
Boolean = 1,
/// Represents that the next value to consume is a double.
Double = 2,
/// Represents that the next value to consume is an integer
Integer = 3,
/// Represents that the next value to consume is a string.
Text = 4,
}
impl From<ExprType> for ValueTag {
fn from(value: ExprType) -> Self {
match value {
ExprType::Boolean => ValueTag::Boolean,
ExprType::Double => ValueTag::Double,
ExprType::Integer => ValueTag::Integer,
ExprType::Text => ValueTag::Text,
}
}
}
/// Representation of the runtime stack.
#[derive(Default)]
struct Stack {
values: Vec<(Value, LineCol)>,
}
#[cfg(test)]
impl<V: Into<Vec<(Value, LineCol)>>> From<V> for Stack {
fn from(values: V) -> Self {
Self { values: values.into() }
}
}
impl Stack {
/// Discards the given number of elements from the top of the stack.
fn discard(&mut self, n: usize) {
self.values.truncate(self.values.len() - n)
}
/// Returns the number of elements in the stack.
fn len(&mut self) -> usize {
self.values.len()
}
/// Pops the top of the stack.
fn pop(&mut self) -> Option<(Value, LineCol)> {
self.values.pop()
}
/// Pushes a new value onto the stack.
fn push(&mut self, value: (Value, LineCol)) {
self.values.push(value)
}
/// Pops the top of the stack as a boolean value.
fn pop_boolean(&mut self) -> bool {
self.pop_boolean_with_pos().0
}
/// Pops the top of the stack as a boolean value.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
fn pop_boolean_with_pos(&mut self) -> (bool, LineCol) {
match self.values.pop() {
Some((Value::Boolean(b), pos)) => (b, pos),
Some((_, _)) => panic!("Type mismatch"),
_ => panic!("Not enough arguments to pop"),
}
}
/// Pushes a boolean onto the stack.
fn push_boolean(&mut self, b: bool, pos: LineCol) {
self.values.push((Value::Boolean(b), pos));
}
/// Pops the top of the stack as a double value.
#[allow(unused)]
fn pop_double(&mut self) -> f64 {
self.pop_double_with_pos().0
}
/// Pops the top of the stack as a double value.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
fn pop_double_with_pos(&mut self) -> (f64, LineCol) {
match self.values.pop() {
Some((Value::Double(d), pos)) => (d, pos),
Some((_, _)) => panic!("Type mismatch"),
_ => panic!("Not enough arguments to pop"),
}
}
/// Pushes a double onto the stack.
fn push_double(&mut self, d: f64, pos: LineCol) {
self.values.push((Value::Double(d), pos));
}
/// Pops the top of the stack as an integer value.
fn pop_integer(&mut self) -> i32 {
self.pop_integer_with_pos().0
}
/// Pops the top of the stack as an integer value.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
fn pop_integer_with_pos(&mut self) -> (i32, LineCol) {
match self.values.pop() {
Some((Value::Integer(i), pos)) => (i, pos),
Some((_, _)) => panic!("Type mismatch"),
_ => panic!("Not enough arguments to pop"),
}
}
/// Pushes an integer onto the stack.
fn push_integer(&mut self, i: i32, pos: LineCol) {
self.values.push((Value::Integer(i), pos));
}
/// Pops the top of the stack as a string value.
#[allow(unused)]
fn pop_string(&mut self) -> String {
self.pop_string_with_pos().0
}
/// Pops the top of the stack as a string value.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
fn pop_string_with_pos(&mut self) -> (String, LineCol) {
match self.values.pop() {
Some((Value::Text(s), pos)) => (s, pos),
Some((_, _)) => panic!("Type mismatch"),
_ => panic!("Not enough arguments to pop"),
}
}
/// Pushes a string onto the stack.
fn push_string(&mut self, s: String, pos: LineCol) {
self.values.push((Value::Text(s), pos));
}
/// Pops the top of the stack as a variable reference.
#[allow(unused)]
fn pop_varref(&mut self) -> (String, ExprType) {
let (name, etype, _pos) = self.pop_varref_with_pos();
(name, etype)
}
/// Pops the top of the stack as a variable reference.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
fn pop_varref_with_pos(&mut self) -> (String, ExprType, LineCol) {
match self.values.pop() {
Some((Value::VarRef(name, etype), pos)) => (name, etype, pos),
Some((_, _)) => panic!("Type mismatch"),
_ => panic!("Not enough arguments to pop"),
}
}
/// Pushes a variable reference onto the stack.
fn push_varref(&mut self, name: String, etype: ExprType, pos: LineCol) {
self.values.push((Value::VarRef(name, etype), pos));
}
/// Peeks into the top of the stack.
fn top(&self) -> Option<&(Value, LineCol)> {
self.values.last()
}
}
/// Provides controlled access to the parameters passed to a callable.
pub struct Scope<'s> {
stack: &'s mut Stack,
nargs: usize,
fref_pos: LineCol,
}
impl Drop for Scope<'_> {
fn drop(&mut self) {
self.stack.discard(self.nargs);
}
}
impl<'s> Scope<'s> {
/// Creates a new scope that wraps `nargs` arguments at the top of `stack`.
fn new(stack: &'s mut Stack, nargs: usize, fref_pos: LineCol) -> Self {
debug_assert!(nargs <= stack.len());
Self { stack, nargs, fref_pos }
}
/// Removes all remaining arguments from the stack tracked by this scope.
fn drain(&mut self) {
self.stack.discard(self.nargs);
self.nargs = 0;
}
/// Annotates an I/O error with the position of the callable that generated it.
pub fn io_error(&self, e: io::Error) -> Error {
Error::IoError(self.fref_pos, e)
}
/// Creates an internal error with the position of the callable that generated it.
pub fn internal_error<S: Into<String>>(&self, msg: S) -> Error {
Error::InternalError(self.fref_pos, msg.into())
}
/// Returns the number of arguments that can still be consumed.
pub fn nargs(&self) -> usize {
self.nargs
}
/// Pops the top of the stack as a boolean value.
pub fn pop_boolean(&mut self) -> bool {
self.pop_boolean_with_pos().0
}
/// Pops the top of the stack as a boolean value.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
pub fn pop_boolean_with_pos(&mut self) -> (bool, LineCol) {
debug_assert!(self.nargs > 0, "Not enough arguments in scope");
self.nargs -= 1;
self.stack.pop_boolean_with_pos()
}
/// Pops the top of the stack as a double value.
pub fn pop_double(&mut self) -> f64 {
self.pop_double_with_pos().0
}
/// Pops the top of the stack as a double value.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
pub fn pop_double_with_pos(&mut self) -> (f64, LineCol) {
debug_assert!(self.nargs > 0, "Not enough arguments in scope");
self.nargs -= 1;
self.stack.pop_double_with_pos()
}
/// Pops the top of the stack as an integer value.
pub fn pop_integer(&mut self) -> i32 {
self.pop_integer_with_pos().0
}
/// Pops the top of the stack as an integer value.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
pub fn pop_integer_with_pos(&mut self) -> (i32, LineCol) {
debug_assert!(self.nargs > 0, "Not enough arguments in scope");
self.nargs -= 1;
self.stack.pop_integer_with_pos()
}
/// Pops the top of the stack as a separator tag.
pub fn pop_sep_tag(&mut self) -> ArgSep {
const END_I32: i32 = ArgSep::End as i32;
const SHORT_I32: i32 = ArgSep::Short as i32;
const LONG_I32: i32 = ArgSep::Long as i32;
const AS_I32: i32 = ArgSep::As as i32;
match self.pop_integer() {
END_I32 => ArgSep::End,
SHORT_I32 => ArgSep::Short,
LONG_I32 => ArgSep::Long,
AS_I32 => ArgSep::As,
_ => unreachable!(),
}
}
/// Pops the top of the stack as a string value.
pub fn pop_string(&mut self) -> String {
self.pop_string_with_pos().0
}
/// Pops the top of the stack as a string value.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
pub fn pop_string_with_pos(&mut self) -> (String, LineCol) {
debug_assert!(self.nargs > 0, "Not enough arguments in scope");
self.nargs -= 1;
self.stack.pop_string_with_pos()
}
/// Pops the top of the stack as a value tag.
pub fn pop_value_tag(&mut self) -> ValueTag {
const MISSING_I32: i32 = ValueTag::Missing as i32;
const BOOLEAN_I32: i32 = ValueTag::Boolean as i32;
const DOUBLE_I32: i32 = ValueTag::Double as i32;
const INTEGER_I32: i32 = ValueTag::Integer as i32;
const TEXT_I32: i32 = ValueTag::Text as i32;
match self.pop_integer() {
MISSING_I32 => ValueTag::Missing,
BOOLEAN_I32 => ValueTag::Boolean,
DOUBLE_I32 => ValueTag::Double,
INTEGER_I32 => ValueTag::Integer,
TEXT_I32 => ValueTag::Text,
_ => unreachable!(),
}
}
/// Pops the top of the stack as a variable reference.
pub fn pop_varref(&mut self) -> (String, ExprType) {
let (name, etype, _pos) = self.pop_varref_with_pos();
(name, etype)
}
/// Pops the top of the stack as a variable reference.
//
// TODO(jmmv): Remove this variant once the stack values do not carry position
// information any longer.
pub fn pop_varref_with_pos(&mut self) -> (String, ExprType, LineCol) {
debug_assert!(self.nargs > 0, "Not enough arguments in scope");
self.nargs -= 1;
self.stack.pop_varref_with_pos()
}
/// Sets the return value of this function to `value`.
pub fn return_any(mut self, value: Value) -> Result<()> {
self.drain();
self.stack.push((value, self.fref_pos));
Ok(())
}
/// Sets the return value of this function to the boolean `value`.
pub fn return_boolean(mut self, value: bool) -> Result<()> {
self.drain();
self.stack.push((Value::Boolean(value), self.fref_pos));
Ok(())
}
/// Sets the return value of this function to the double `value`.
pub fn return_double(mut self, value: f64) -> Result<()> {
self.drain();
self.stack.push((Value::Double(value), self.fref_pos));
Ok(())
}
/// Sets the return value of this function to the integer `value`.
pub fn return_integer(mut self, value: i32) -> Result<()> {
self.drain();
self.stack.push((Value::Integer(value), self.fref_pos));
Ok(())
}
/// Sets the return value of this function to the string `value`.
pub fn return_string<S: Into<String>>(mut self, value: S) -> Result<()> {
self.drain();
self.stack.push((Value::Text(value.into()), self.fref_pos));
Ok(())
}
}
/// Machine state for the execution of an individual chunk of code.
struct Context {
pc: Address,
addr_stack: Vec<Address>,
value_stack: Stack,
err_handler: ErrorHandlerISpan,
}
impl Default for Context {
fn default() -> Self {
Self {
pc: 0,
addr_stack: vec![],
value_stack: Stack::default(),
err_handler: ErrorHandlerISpan::None,
}
}
}
/// Executes an EndBASIC program and tracks its state.
pub struct Machine {
symbols: Symbols,
clearables: Vec<Box<dyn Clearable>>,
yield_now_fn: Option<YieldNowFn>,
signals_chan: (Sender<Signal>, Receiver<Signal>),
last_error: Option<String>,
data: Vec<Option<Value>>,
}
impl Default for Machine {
fn default() -> Self {
Self::with_signals_chan_and_yield_now_fn(async_channel::unbounded(), None)
}
}
impl Machine {
/// Constructs a new empty machine with the given signals communication channel.
pub fn with_signals_chan(signals: (Sender<Signal>, Receiver<Signal>)) -> Self {
Self::with_signals_chan_and_yield_now_fn(signals, None)
}
/// Constructs a new empty machine with the given signals communication channel and yielding
/// function.
pub fn with_signals_chan_and_yield_now_fn(
signals: (Sender<Signal>, Receiver<Signal>),
yield_now_fn: Option<YieldNowFn>,
) -> Self {
Self {
symbols: Symbols::default(),
clearables: vec![],
yield_now_fn,
signals_chan: signals,
last_error: None,
data: vec![],
}
}
/// Registers the given clearable.
///
/// In the common case, functions and commands hold a reference to the out-of-machine state
/// they interact with. This state is invisible from here, but we may need to have access
/// to it to reset it as part of the `clear` operation. In those cases, such state must be
/// registered via this hook.
pub fn add_clearable(&mut self, clearable: Box<dyn Clearable>) {
self.clearables.push(clearable);
}
/// Registers the given builtin callable, which must not yet be registered.
pub fn add_callable(&mut self, callable: Rc<dyn Callable>) {
self.symbols.add_callable(callable)
}
/// Obtains a channel via which to send signals to the machine during execution.
pub fn get_signals_tx(&self) -> Sender<Signal> {
self.signals_chan.0.clone()
}
/// Resets the state of the machine by clearing all variable.
pub fn clear(&mut self) {
for clearable in self.clearables.as_slice() {
clearable.reset_state(&mut self.symbols);
}
self.symbols.clear();
self.last_error = None;
}
/// Returns the last execution error.
pub fn last_error(&self) -> Option<&str> {
self.last_error.as_deref()
}
/// Obtains immutable access to the data values available during the *current* execution.
pub fn get_data(&self) -> &[Option<Value>] {
&self.data
}
/// Obtains immutable access to the state of the symbols.
pub fn get_symbols(&self) -> &Symbols {
&self.symbols
}
/// Obtains mutable access to the state of the symbols.
pub fn get_mut_symbols(&mut self) -> &mut Symbols {
&mut self.symbols
}
/// Returns true if execution should stop because we have hit a stop condition.
async fn should_stop(&mut self) -> bool {
if let Some(yield_now) = self.yield_now_fn.as_ref() {
(yield_now)().await;
}
match self.signals_chan.1.try_recv() {
Ok(Signal::Break) => true,
Err(TryRecvError::Empty) => false,
Err(TryRecvError::Closed) => panic!("Channel unexpectedly closed"),
}
}
/// Handles an array assignment.
fn assign_array(
&mut self,
context: &mut Context,
key: &SymbolKey,
vref_pos: LineCol,
nargs: usize,
) -> Result<()> {
let mut ds = Vec::with_capacity(nargs);
for _ in 0..nargs {
let i = context.value_stack.pop_integer();
ds.push(i);
}
let (value, _pos) = context.value_stack.pop().unwrap();
match self.symbols.load_mut(key) {
Some(Symbol::Array(array)) => {
array.assign(&ds, value).map_err(|e| Error::from_value_error(e, vref_pos))?;
Ok(())
}
_ => unreachable!("Array existence and type checking has been done at compile time"),
}
}
/// Handles a builtin call.
async fn builtin_call(
&mut self,
context: &mut Context,
callable: Rc<dyn Callable>,
bref_pos: LineCol,
nargs: usize,
) -> Result<()> {
let metadata = callable.metadata();
debug_assert!(!metadata.is_function());
let scope = Scope::new(&mut context.value_stack, nargs, bref_pos);
callable.exec(scope, self).await
}
/// Handles an array definition. The array must not yet exist, and the name may not overlap
/// function or variable names.
fn dim_array(&mut self, context: &mut Context, span: &DimArrayISpan) -> Result<()> {
let mut ds = Vec::with_capacity(span.dimensions);
for _ in 0..span.dimensions {
let (i, pos) = context.value_stack.pop_integer_with_pos();
if i <= 0 {
return new_syntax_error(pos, "Dimensions in DIM array must be positive");
}
ds.push(i as usize);
}
if span.shared {
self.symbols.dim_shared_array(span.name.clone(), span.subtype, ds);
} else {
self.symbols.dim_array(span.name.clone(), span.subtype, ds);
}
Ok(())
}
/// Consumes any pending signals so that they don't interfere with an upcoming execution.
pub fn drain_signals(&mut self) {
while self.signals_chan.1.try_recv().is_ok() {
// Do nothing.
}
}
/// Tells the machine to stop execution at the next statement boundary.
fn end(&mut self, context: &mut Context, has_code: bool) -> Result<InternalStopReason> {
let code = if has_code {
let (code, code_pos) = context.value_stack.pop_integer_with_pos();
if code < 0 {
return new_syntax_error(
code_pos,
"Exit code must be a positive integer".to_owned(),
);
}
if code >= 128 {
return new_syntax_error(
code_pos,
"Exit code cannot be larger than 127".to_owned(),
);
}
code as u8
} else {
0
};
Ok(InternalStopReason::Exited(code))
}
/// Handles a unary logical operator that cannot fail.
fn exec_logical_op1<F: Fn(bool) -> bool>(context: &mut Context, op: F, pos: LineCol) {
let rhs = context.value_stack.pop_boolean();
context.value_stack.push_boolean(op(rhs), pos);
}
/// Handles a binary logical operator that cannot fail.
fn exec_logical_op2<F: Fn(bool, bool) -> bool>(context: &mut Context, op: F, pos: LineCol) {
let rhs = context.value_stack.pop_boolean();
let lhs = context.value_stack.pop_boolean();
context.value_stack.push_boolean(op(lhs, rhs), pos);
}
/// Handles a unary bitwise operator that cannot fail.
fn exec_bitwise_op1<F: Fn(i32) -> i32>(context: &mut Context, op: F, pos: LineCol) {
let rhs = context.value_stack.pop_integer();
context.value_stack.push_integer(op(rhs), pos);
}
/// Handles a binary bitwise operator that cannot fail.
fn exec_bitwise_op2<F: Fn(i32, i32) -> i32>(context: &mut Context, op: F, pos: LineCol) {
let rhs = context.value_stack.pop_integer();
let lhs = context.value_stack.pop_integer();
context.value_stack.push_integer(op(lhs, rhs), pos);
}
/// Handles a binary bitwise operator that can fail.
fn exec_bitwise_op2_err<F: Fn(i32, i32) -> value::Result<i32>>(
context: &mut Context,
op: F,
pos: LineCol,
) -> Result<()> {
let rhs = context.value_stack.pop_integer();
let lhs = context.value_stack.pop_integer();
let result = op(lhs, rhs).map_err(|e| Error::from_value_error(e, pos))?;
context.value_stack.push_integer(result, pos);
Ok(())
}
/// Handles a binary equality operator for booleans that cannot fail.
fn exec_equality_boolean_op2<F: Fn(bool, bool) -> bool>(
context: &mut Context,
op: F,
pos: LineCol,
) {
let rhs = context.value_stack.pop_boolean();
let lhs = context.value_stack.pop_boolean();
context.value_stack.push_boolean(op(lhs, rhs), pos);
}
/// Handles a binary equality operator for doubles that cannot fail.
fn exec_equality_double_op2<F: Fn(f64, f64) -> bool>(
context: &mut Context,
op: F,
pos: LineCol,
) {
let rhs = context.value_stack.pop_double();
let lhs = context.value_stack.pop_double();
context.value_stack.push_boolean(op(lhs, rhs), pos);
}
/// Handles a binary equality operator for integers that cannot fail.
fn exec_equality_integer_op2<F: Fn(i32, i32) -> bool>(
context: &mut Context,
op: F,
pos: LineCol,
) {
let rhs = context.value_stack.pop_integer();
let lhs = context.value_stack.pop_integer();
context.value_stack.push_boolean(op(lhs, rhs), pos);
}
/// Handles a binary equality operator for strings that cannot fail.
fn exec_equality_string_op2<F: Fn(&str, &str) -> bool>(
context: &mut Context,
op: F,
pos: LineCol,
) {
let rhs = context.value_stack.pop_string();
let lhs = context.value_stack.pop_string();
context.value_stack.push_boolean(op(&lhs, &rhs), pos);
}
/// Handles a unary arithmetic operator for doubles that cannot fail.
fn exec_arithmetic_double_op1<F: Fn(f64) -> f64>(context: &mut Context, op: F, pos: LineCol) {
let rhs = context.value_stack.pop_double();
context.value_stack.push_double(op(rhs), pos);
}
/// Handles a binary arithmetic operator for doubles that cannot fail.
fn exec_arithmetic_double_op2<F: Fn(f64, f64) -> f64>(
context: &mut Context,
op: F,
pos: LineCol,
) {
let rhs = context.value_stack.pop_double();
let lhs = context.value_stack.pop_double();
context.value_stack.push_double(op(lhs, rhs), pos);
}
/// Handles a unary arithmetic operator for doubles that can fail.
fn exec_arithmetic_integer_op1<F: Fn(i32) -> value::Result<i32>>(
context: &mut Context,
op: F,
pos: LineCol,
) -> Result<()> {
let rhs = context.value_stack.pop_integer();
let result = op(rhs).map_err(|e| Error::from_value_error(e, pos))?;
context.value_stack.push_integer(result, pos);
Ok(())
}
/// Handles a binary arithmetic operator for doubles that can fail.
fn exec_arithmetic_integer_op2<F: Fn(i32, i32) -> value::Result<i32>>(
context: &mut Context,
op: F,
pos: LineCol,
) -> Result<()> {
let rhs = context.value_stack.pop_integer();
let lhs = context.value_stack.pop_integer();
let result = op(lhs, rhs).map_err(|e| Error::from_value_error(e, pos))?;
context.value_stack.push_integer(result, pos);
Ok(())
}
/// Handles a binary arithmetic operator for doubles that cannot fail.
fn exec_arithmetic_string_op2<F: Fn(&str, &str) -> String>(
context: &mut Context,
op: F,
pos: LineCol,
) {
let rhs = context.value_stack.pop_string();
let lhs = context.value_stack.pop_string();
context.value_stack.push_string(op(&lhs, &rhs), pos);
}
/// Evaluates the subscripts of an array reference.
fn get_array_args(&self, context: &mut Context, nargs: usize) -> Result<Vec<i32>> {
let mut subscripts = Vec::with_capacity(nargs);
for _ in 0..nargs {
let i = context.value_stack.pop_integer();
subscripts.push(i);
}
Ok(subscripts)
}
/// Evaluates a function call specified by `fref` and arguments `args` on the function `f`.
async fn do_function_call(
&mut self,
context: &mut Context,
return_type: ExprType,
fref_pos: LineCol,
nargs: usize,
f: Rc<dyn Callable>,
) -> Result<()> {
let metadata = f.metadata();
debug_assert_eq!(return_type, metadata.return_type().unwrap());
let scope = Scope::new(&mut context.value_stack, nargs, fref_pos);
f.exec(scope, self).await?;
if cfg!(debug_assertions) {
match context.value_stack.top() {
Some((value, _pos)) => {
debug_assert_eq!(
return_type,
value.as_exprtype(),
"Value returned by function is incompatible with its type definition",
)
}
None => unreachable!("Functions must return one value"),
}
}
Ok(())
}
/// Handles an array reference.
fn array_ref(
&mut self,
context: &mut Context,
key: &SymbolKey,
vref_pos: LineCol,
nargs: usize,
) -> Result<()> {
let subscripts = self.get_array_args(context, nargs)?;
match self.symbols.load(key) {
Some(Symbol::Array(array)) => {
let value = array
.index(&subscripts)
.cloned()
.map_err(|e| Error::from_value_error(e, vref_pos))?;
context.value_stack.push((value, vref_pos));
Ok(())
}
Some(_) => unreachable!("Array type checking has been done at compile time"),
None => Err(Error::EvalError(vref_pos, format!("{} is not defined", key))),
}
}
/// Handles a function call.
async fn function_call(
&mut self,
context: &mut Context,
callable: Rc<dyn Callable>,
name: &SymbolKey,
return_type: ExprType,
fref_pos: LineCol,
nargs: usize,
) -> Result<()> {
if !callable.metadata().is_function() {
return Err(Error::EvalError(
fref_pos,
format!("{} is not an array nor a function", callable.metadata().name()),
));
}
if callable.metadata().is_argless() {
self.argless_function_call(context, name, return_type, fref_pos, callable).await
} else {
self.do_function_call(context, return_type, fref_pos, nargs, callable).await
}
}
/// Evaluates a call to an argless function.
async fn argless_function_call(
&mut self,
context: &mut Context,
fname: &SymbolKey,
ftype: ExprType,
fpos: LineCol,
f: Rc<dyn Callable>,
) -> Result<()> {
let scope = Scope::new(&mut context.value_stack, 0, fpos);
f.exec(scope, self).await?;
if cfg!(debug_assertions) {
match context.value_stack.top() {
Some((value, _pos)) => {
let fref_checker = VarRef::new(fname.to_string(), Some(ftype));
debug_assert!(
fref_checker.accepts(value.as_exprtype()),
"Value returned by function is incompatible with its type definition",
)
}
None => unreachable!("Functions must return one value"),
}
}
Ok(())
}