forked from rhaiscript/rhai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.rs
3983 lines (3534 loc) · 155 KB
/
parser.rs
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
//! Main module defining the lexer and parser.
use crate::api::options::LangOptions;
use crate::ast::{
ASTFlags, BinaryExpr, CaseBlocksList, Expr, FlowControl, FnCallExpr, FnCallHashes, Ident,
OpAssignment, RangeCase, ScriptFuncDef, Stmt, StmtBlock, StmtBlockContainer,
SwitchCasesCollection,
};
use crate::engine::{Precedence, OP_CONTAINS, OP_NOT};
use crate::eval::{Caches, GlobalRuntimeState};
use crate::func::{hashing::get_hasher, StraightHashMap};
use crate::tokenizer::{
is_reserved_keyword_or_symbol, is_valid_function_name, is_valid_identifier, Token, TokenStream,
TokenizerControl,
};
use crate::types::dynamic::{AccessMode, Union};
use crate::{
calc_fn_hash, Dynamic, Engine, EvalAltResult, EvalContext, ExclusiveRange, FnArgsVec,
ImmutableString, InclusiveRange, LexError, ParseError, Position, Scope, Shared, SmartString,
StaticVec, ThinVec, VarDefInfo, AST, PERR,
};
use bitflags::bitflags;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
convert::TryFrom,
fmt,
hash::{Hash, Hasher},
num::{NonZeroU8, NonZeroUsize},
};
pub type ParseResult<T> = Result<T, ParseError>;
#[cfg(not(feature = "no_function"))]
type FnLib = StraightHashMap<Shared<ScriptFuncDef>>;
/// Invalid variable name that acts as a search barrier in a [`Scope`].
const SCOPE_SEARCH_BARRIER_MARKER: &str = "$ BARRIER $";
impl PERR {
/// Make a [`ParseError`] using the current type and position.
#[cold]
#[inline(never)]
fn into_err(self, pos: Position) -> ParseError {
ParseError(self.into(), pos)
}
}
/// _(internals)_ A type that encapsulates the current state of the parser.
/// Exported under the `internals` feature only.
pub struct ParseState<'a, 't, 'f> {
/// Stream of input tokens.
pub input: &'t mut TokenStream<'a>,
/// Tokenizer control interface.
pub tokenizer_control: TokenizerControl,
/// Script-defined functions.
#[cfg(not(feature = "no_function"))]
pub lib: &'f mut FnLib,
/// Controls whether parsing of an expression should stop given the next token.
pub expr_filter: fn(&Token) -> bool,
/// External [scope][Scope] with constants.
pub external_constants: Option<&'a Scope<'a>>,
/// Global runtime state.
pub global: Option<Box<GlobalRuntimeState>>,
/// Encapsulates a local stack with variable names to simulate an actual runtime scope.
pub stack: Scope<'a>,
/// Size of the local variables stack upon entry of the current block scope.
pub frame_pointer: usize,
/// Tracks a list of external variables (variables that are not explicitly declared in the scope).
#[cfg(not(feature = "no_closure"))]
pub external_vars: ThinVec<Ident>,
/// An indicator that, when set to `false`, disables variable capturing into externals one
/// single time up until the nearest consumed Identifier token.
///
/// If set to `false` the next call to [`access_var`][ParseState::access_var] will not capture
/// the variable.
///
/// All consequent calls to [`access_var`][ParseState::access_var] will not be affected.
pub allow_capture: bool,
/// Encapsulates a local stack with imported [module][crate::Module] names.
#[cfg(not(feature = "no_module"))]
pub imports: ThinVec<ImmutableString>,
/// List of globally-imported [module][crate::Module] names.
#[cfg(not(feature = "no_module"))]
pub global_imports: ThinVec<ImmutableString>,
/// Unused dummy field.
#[cfg(feature = "no_function")]
pub dummy: &'f (),
}
impl fmt::Debug for ParseState<'_, '_, '_> {
#[cold]
#[inline(never)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut f = f.debug_struct("ParseState");
f.field("tokenizer_control", &self.tokenizer_control)
.field("external_constants_scope", &self.external_constants)
.field("global", &self.global)
.field("stack", &self.stack)
.field("frame_pointer", &self.frame_pointer);
#[cfg(not(feature = "no_closure"))]
f.field("external_vars", &self.external_vars)
.field("allow_capture", &self.allow_capture);
#[cfg(not(feature = "no_module"))]
f.field("imports", &self.imports)
.field("global_imports", &self.global_imports);
f.finish()
}
}
impl<'a, 't, 'f> ParseState<'a, 't, 'f> {
/// Create a new [`ParseState`].
#[inline]
#[must_use]
pub fn new(
external_constants: Option<&'a Scope>,
input: &'t mut TokenStream<'a>,
tokenizer_control: TokenizerControl,
#[cfg(not(feature = "no_function"))] lib: &'f mut FnLib,
#[cfg(feature = "no_function")] dummy: &'f (),
) -> Self {
Self {
input,
tokenizer_control,
#[cfg(not(feature = "no_function"))]
lib,
#[cfg(feature = "no_function")]
dummy,
expr_filter: |_| true,
#[cfg(not(feature = "no_closure"))]
external_vars: ThinVec::new(),
allow_capture: true,
external_constants,
global: None,
stack: Scope::new(),
frame_pointer: 0,
#[cfg(not(feature = "no_module"))]
imports: ThinVec::new(),
#[cfg(not(feature = "no_module"))]
global_imports: ThinVec::new(),
}
}
/// Find explicitly declared variable by name in the [`ParseState`], searching in reverse order.
///
/// The first return value is the offset to be deducted from `ParseState::stack::len()`,
/// i.e. the top element of [`ParseState`]'s variables stack is offset 1.
///
/// If the variable is not present in the scope, the first return value is zero.
///
/// The second return value indicates whether the barrier has been hit before finding the variable.
#[must_use]
pub fn find_var(&self, name: &str) -> (usize, bool) {
let mut hit_barrier = false;
let index = self
.stack
.iter_rev_inner()
.position(|(n, ..)| {
if n == SCOPE_SEARCH_BARRIER_MARKER {
// Do not go beyond the barrier
hit_barrier = true;
false
} else {
n == name
}
})
.map_or(0, |i| i + 1);
(index, hit_barrier)
}
/// Find a module by name in the [`ParseState`], searching in reverse.
///
/// Returns the offset to be deducted from `Stack::len`,
/// i.e. the top element of the [`ParseState`] is offset 1.
///
/// Returns [`None`] when the variable name is not found in the [`ParseState`].
///
/// # Panics
///
/// Panics when called under `no_module`.
#[cfg(not(feature = "no_module"))]
#[must_use]
pub fn find_module(&self, name: &str) -> Option<NonZeroUsize> {
self.imports
.iter()
.rev()
.rposition(|n| n == name)
.and_then(|i| NonZeroUsize::new(i + 1))
}
}
bitflags! {
/// Bit-flags containing all status for [`ParseSettings`].
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
pub struct ParseSettingFlags: u8 {
/// Is the construct being parsed located at global level?
const GLOBAL_LEVEL = 0b0000_0001;
/// Is the construct being parsed located inside a function definition?
const FN_SCOPE = 0b0000_0010;
/// Is the construct being parsed located inside a closure definition?
const CLOSURE_SCOPE = 0b0000_0100;
/// Is the construct being parsed located inside a breakable loop?
const BREAKABLE = 0b0000_1000;
/// Disallow statements in blocks?
const DISALLOW_STATEMENTS_IN_BLOCKS = 0b0001_0000;
/// Disallow unquoted map properties?
const DISALLOW_UNQUOTED_MAP_PROPERTIES = 0b0010_0000;
}
}
bitflags! {
/// Bit-flags containing all status for parsing property/indexing/namespace chains.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
struct ChainingFlags: u8 {
/// Is the construct being parsed a property?
const PROPERTY = 0b0000_0001;
/// Disallow namespaces?
const DISALLOW_NAMESPACES = 0b0000_0010;
}
}
/// A type that encapsulates all the settings for a particular parsing function.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct ParseSettings {
/// Flags.
pub flags: ParseSettingFlags,
/// Language options in effect (overrides Engine options).
pub options: LangOptions,
/// Current expression nesting level.
pub level: usize,
/// Current position.
pub pos: Position,
/// Maximum levels of expression nesting (0 for unlimited).
#[cfg(not(feature = "unchecked"))]
pub max_expr_depth: usize,
}
impl ParseSettings {
/// Is a particular flag on?
#[inline(always)]
#[must_use]
pub const fn has_flag(&self, flag: ParseSettingFlags) -> bool {
self.flags.intersects(flag)
}
/// Is a particular language option on?
#[inline(always)]
#[must_use]
pub const fn has_option(&self, option: LangOptions) -> bool {
self.options.intersects(option)
}
/// Create a new `ParseSettings` with one higher expression level.
#[inline]
pub fn level_up(&self) -> ParseResult<Self> {
#[cfg(not(feature = "unchecked"))]
if self.max_expr_depth > 0 && self.level >= self.max_expr_depth {
return Err(PERR::ExprTooDeep.into_err(self.pos));
}
Ok(Self {
level: self.level + 1,
..*self
})
}
/// Create a new `ParseSettings` with one higher expression level.
#[inline]
pub fn level_up_with_position(&self, pos: Position) -> ParseResult<Self> {
let mut x = self.level_up()?;
x.pos = pos;
Ok(x)
}
}
/// Make an anonymous function.
#[cfg(not(feature = "no_function"))]
#[inline]
#[must_use]
pub fn make_anonymous_fn(hash: u64) -> crate::Identifier {
use std::fmt::Write;
let mut buf = crate::Identifier::new_const();
write!(&mut buf, "{}{hash:016x}", crate::engine::FN_ANONYMOUS).unwrap();
buf
}
/// Is this function an anonymous function?
#[cfg(not(feature = "no_function"))]
#[inline(always)]
#[must_use]
pub fn is_anonymous_fn(fn_name: &str) -> bool {
fn_name.starts_with(crate::engine::FN_ANONYMOUS)
}
impl Expr {
/// Raise an error if the expression can never yield a boolean value.
fn ensure_bool_expr(self) -> ParseResult<Self> {
let type_name = match self {
Self::Unit(..) => "()",
Self::DynamicConstant(ref v, ..) if !v.is_bool() => v.type_name(),
Self::IntegerConstant(..) => "a number",
#[cfg(not(feature = "no_float"))]
Self::FloatConstant(..) => "a floating-point number",
Self::CharConstant(..) => "a character",
Self::StringConstant(..) => "a string",
Self::InterpolatedString(..) => "a string",
Self::Array(..) => "an array",
Self::Map(..) => "an object map",
_ => return Ok(self),
};
Err(
PERR::MismatchedType("a boolean expression".into(), type_name.into())
.into_err(self.start_position()),
)
}
/// Raise an error if the expression can never yield an iterable value.
fn ensure_iterable(self) -> ParseResult<Self> {
let type_name = match self {
Self::Unit(..) => "()",
Self::BoolConstant(..) => "a boolean",
Self::IntegerConstant(..) => "a number",
#[cfg(not(feature = "no_float"))]
Self::FloatConstant(..) => "a floating-point number",
Self::CharConstant(..) => "a character",
Self::Map(..) => "an object map",
_ => return Ok(self),
};
Err(
PERR::MismatchedType("an iterable value".into(), type_name.into())
.into_err(self.start_position()),
)
}
}
/// Make sure that the next expression is not a statement expression (i.e. wrapped in `{}`).
fn ensure_not_statement_expr(
input: &mut TokenStream,
type_name: &(impl ToString + ?Sized),
) -> ParseResult<()> {
match input.peek().unwrap() {
(Token::LeftBrace, pos) => Err(PERR::ExprExpected(type_name.to_string()).into_err(*pos)),
_ => Ok(()),
}
}
/// Make sure that the next expression is not a mis-typed assignment (i.e. `a = b` instead of `a == b`).
fn ensure_not_assignment(input: &mut TokenStream) -> ParseResult<()> {
match input.peek().unwrap() {
(token @ Token::Equals, pos) => Err(LexError::ImproperSymbol(
token.literal_syntax().into(),
"Possibly a typo of '=='?".into(),
)
.into_err(*pos)),
_ => Ok(()),
}
}
/// Consume a particular [token][Token], checking that it is the expected one.
///
/// # Panics
///
/// Panics if the next token is not the expected one, or either tokens is not a literal symbol.
#[inline(always)]
fn eat_token(input: &mut TokenStream, expected_token: &Token) -> Position {
let (t, pos) = input.next().unwrap();
debug_assert_eq!(
&t,
expected_token,
"{} expected but gets {} at {}",
expected_token.literal_syntax(),
t.literal_syntax(),
pos,
);
pos
}
/// Match a particular [token][Token], consuming it if matched.
#[inline]
fn match_token(input: &mut TokenStream, token: &Token) -> (bool, Position) {
let (t, pos) = input.peek().unwrap();
if t == token {
(true, eat_token(input, token))
} else {
(false, *pos)
}
}
/// Process a block comment such that it indents properly relative to the start token.
#[cfg(not(feature = "no_function"))]
#[cfg(feature = "metadata")]
#[inline]
fn unindent_block_comment(comment: String, pos: usize) -> String {
if pos == 0 || !comment.contains('\n') {
return comment;
}
// Note, use `trim_start_matches` instead of `trim` because `trim` will remove even multi-byte
// Unicode spaces, which may cause the minimum offset to end up inside that multi-byte space
// character. Therefore, be conservative and only remove ASCII spaces.
let offset = comment
.lines()
.skip(1)
.map(|s| s.len() - s.trim_start_matches(' ').len())
.min()
.unwrap_or(pos)
.min(pos);
if offset == 0 {
return comment;
}
comment
.lines()
.enumerate()
.map(|(i, s)| if i > 0 { &s[offset..] } else { s })
.collect::<Vec<_>>()
.join("\n")
}
/// Parse a variable name.
fn parse_var_name(input: &mut TokenStream) -> ParseResult<(SmartString, Position)> {
match input.next().unwrap() {
// Variable name
(Token::Identifier(s), pos) => Ok((*s, pos)),
// Reserved keyword
(Token::Reserved(s), pos) if is_valid_identifier(&s) => {
Err(PERR::Reserved(s.to_string()).into_err(pos))
}
// Bad identifier
(Token::LexError(err), pos) => Err(err.into_err(pos)),
// Not a variable name
(.., pos) => Err(PERR::VariableExpected.into_err(pos)),
}
}
/// Optimize the structure of a chained expression where the root expression is another chained expression.
///
/// # Panics
///
/// Panics if the expression is not a combo chain.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
fn optimize_combo_chain(expr: &mut Expr) {
#[allow(clippy::type_complexity)]
let (mut x, x_options, x_pos, mut root, mut root_options, root_pos, make_sub, make_root): (
_,
_,
_,
_,
_,
_,
fn(_, _, _) -> Expr,
fn(_, _, _) -> Expr,
) = match expr.take() {
#[cfg(not(feature = "no_index"))]
Expr::Index(mut x, opt, pos) => match x.lhs.take() {
Expr::Index(x2, opt2, pos2) => (x, opt, pos, x2, opt2, pos2, Expr::Index, Expr::Index),
#[cfg(not(feature = "no_object"))]
Expr::Dot(x2, opt2, pos2) => (x, opt, pos, x2, opt2, pos2, Expr::Index, Expr::Dot),
_ => unreachable!("combo chain expected"),
},
#[cfg(not(feature = "no_object"))]
Expr::Dot(mut x, opt, pos) => match x.lhs.take() {
#[cfg(not(feature = "no_index"))]
Expr::Index(x2, opt2, pos2) => (x, opt, pos, x2, opt2, pos2, Expr::Dot, Expr::Index),
Expr::Dot(x2, opt2, pos2) => (x, opt, pos, x2, opt2, pos2, Expr::Dot, Expr::Dot),
_ => unreachable!("combo chain expected"),
},
_ => unreachable!("combo chain expected"),
};
// Rewrite the chains like this:
//
// Source: ( x[y].prop_a )[z].prop_b
// ^ ^
// parentheses that generated the combo chain
//
// From: Index( Index( x, Dot(y, prop_a) ), Dot(z, prop_b) )
// ^ ^ ^
// x root tail
//
// To: Index( x, Dot(y, Index(prop_a, Dot(z, prop_b) ) ) )
//
// Equivalent to: x[y].prop_a[z].prop_b
// Find the end of the root chain.
let mut tail = root.as_mut();
let mut tail_options = &mut root_options;
while !tail_options.intersects(ASTFlags::BREAK) {
match tail.rhs {
Expr::Index(ref mut x, ref mut options2, ..) => {
tail = x.as_mut();
tail_options = options2;
}
#[cfg(not(feature = "no_object"))]
Expr::Dot(ref mut x, ref mut options2, ..) => {
tail = x.as_mut();
tail_options = options2;
}
_ => break,
}
}
// Since we attach the outer chain to the root chain, we no longer terminate at the end of the
// root chain, so remove the ASTFlags::BREAK flag.
tail_options.remove(ASTFlags::BREAK);
x.lhs = tail.rhs.take(); // remove tail and insert it into head of outer chain
tail.rhs = make_sub(x, x_options, x_pos); // attach outer chain to tail
*expr = make_root(root, root_options, root_pos);
}
impl Engine {
/// Find explicitly declared variable by name in the [`ParseState`], searching in reverse order.
///
/// If the variable is not present in the scope adds it to the list of external variables.
///
/// The return value is the offset to be deducted from `ParseState::stack::len()`,
/// i.e. the top element of [`ParseState`]'s variables stack is offset 1.
///
/// # Return value: `(index, is_func_name)`
///
/// * `index`: [`None`] when the variable name is not found in the `stack`,
/// otherwise the index value.
///
/// * `is_func_name`: `true` if the variable is actually the name of a function
/// (in which case it will be converted into a function pointer).
#[must_use]
fn access_var(
&self,
state: &mut ParseState,
name: &str,
_pos: Position,
) -> (Option<NonZeroUsize>, bool) {
let (index, hit_barrier) = state.find_var(name);
#[cfg(not(feature = "no_function"))]
let is_func_name = state.lib.values().any(|f| f.name == name);
#[cfg(feature = "no_function")]
let is_func_name = false;
#[cfg(not(feature = "no_closure"))]
if state.allow_capture {
if !is_func_name && index == 0 && !state.external_vars.iter().any(|v| v.name == name) {
let name = self.get_interned_string(name);
state.external_vars.push(Ident { name, pos: _pos });
}
} else {
state.allow_capture = true;
}
let index = (!hit_barrier).then(|| NonZeroUsize::new(index)).flatten();
(index, is_func_name)
}
/// Convert a [`Variable`][Expr::Variable] into a [`Property`][Expr::Property].
/// All other variants are untouched.
#[cfg(not(feature = "no_object"))]
#[inline]
#[must_use]
fn convert_expr_into_property(&self, expr: Expr) -> Expr {
match expr {
#[cfg(not(feature = "no_module"))]
Expr::Variable(x, ..) if !x.2.is_empty() => unreachable!("qualified property"),
Expr::Variable(x, .., pos) => {
let ident = x.1.clone();
let getter = self.get_interned_getter(&ident);
let hash_get = calc_fn_hash(None, &getter, 1);
let setter = self.get_interned_setter(&ident);
let hash_set = calc_fn_hash(None, &setter, 2);
Expr::Property(
Box::new(((getter, hash_get), (setter, hash_set), ident)),
pos,
)
}
_ => expr,
}
}
/// Parse a function call.
fn parse_fn_call(
&self,
state: &mut ParseState,
settings: ParseSettings,
id: ImmutableString,
no_args: bool,
capture_parent_scope: bool,
#[cfg(not(feature = "no_module"))] mut namespace: crate::ast::Namespace,
) -> ParseResult<Expr> {
let (token, token_pos) = if no_args {
&(Token::RightParen, Position::NONE)
} else {
state.input.peek().unwrap()
};
let mut args = FnArgsVec::new();
match token {
// id( <EOF>
Token::EOF => {
return Err(PERR::MissingToken(
Token::RightParen.into(),
format!("to close the arguments list of this function call '{id}'"),
)
.into_err(*token_pos))
}
// id( <error>
Token::LexError(err) => return Err(err.clone().into_err(*token_pos)),
// id()
Token::RightParen => {
if !no_args {
eat_token(state.input, &Token::RightParen);
}
#[cfg(not(feature = "no_module"))]
let hash = if namespace.is_empty() {
calc_fn_hash(None, &id, 0)
} else {
let root = namespace.root();
let index = state.find_module(root);
let is_global = false;
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_module"))]
let is_global = is_global || root == crate::engine::KEYWORD_GLOBAL;
if settings.has_option(LangOptions::STRICT_VAR)
&& index.is_none()
&& !is_global
&& !state.global_imports.iter().any(|m| m == root)
&& !self.global_sub_modules.contains_key(root)
{
return Err(
PERR::ModuleUndefined(root.into()).into_err(namespace.position())
);
}
namespace.index = index;
calc_fn_hash(namespace.path.iter().map(Ident::as_str), &id, 0)
};
#[cfg(feature = "no_module")]
let hash = calc_fn_hash(None, &id, 0);
let hashes = if is_valid_function_name(&id) {
FnCallHashes::from_hash(hash)
} else {
FnCallHashes::from_native_only(hash)
};
args.shrink_to_fit();
return Ok(FnCallExpr {
name: self.get_interned_string(id),
capture_parent_scope,
op_token: None,
#[cfg(not(feature = "no_module"))]
namespace,
hashes,
args,
}
.into_fn_call_expr(settings.pos));
}
// id...
_ => (),
}
let settings = settings.level_up()?;
loop {
match state.input.peek().unwrap() {
// id(...args, ) - handle trailing comma
(Token::RightParen, ..) => (),
_ => args.push(self.parse_expr(state, settings)?),
}
match state.input.peek().unwrap() {
// id(...args)
(Token::RightParen, ..) => {
eat_token(state.input, &Token::RightParen);
#[cfg(not(feature = "no_module"))]
let hash = if namespace.is_empty() {
calc_fn_hash(None, &id, args.len())
} else {
let root = namespace.root();
let index = state.find_module(root);
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_module"))]
let is_global = root == crate::engine::KEYWORD_GLOBAL;
#[cfg(any(feature = "no_function", feature = "no_module"))]
let is_global = false;
if settings.has_option(LangOptions::STRICT_VAR)
&& index.is_none()
&& !is_global
&& !state.global_imports.iter().any(|m| m == root)
&& !self.global_sub_modules.contains_key(root)
{
return Err(
PERR::ModuleUndefined(root.into()).into_err(namespace.position())
);
}
namespace.index = index;
calc_fn_hash(namespace.path.iter().map(Ident::as_str), &id, args.len())
};
#[cfg(feature = "no_module")]
let hash = calc_fn_hash(None, &id, args.len());
let hashes = if is_valid_function_name(&id) {
FnCallHashes::from_hash(hash)
} else {
FnCallHashes::from_native_only(hash)
};
args.shrink_to_fit();
return Ok(FnCallExpr {
name: self.get_interned_string(id),
capture_parent_scope,
op_token: None,
#[cfg(not(feature = "no_module"))]
namespace,
hashes,
args,
}
.into_fn_call_expr(settings.pos));
}
// id(...args,
(Token::Comma, ..) => {
eat_token(state.input, &Token::Comma);
}
// id(...args <EOF>
(Token::EOF, pos) => {
return Err(PERR::MissingToken(
Token::RightParen.into(),
format!("to close the arguments list of this function call '{id}'"),
)
.into_err(*pos))
}
// id(...args <error>
(Token::LexError(err), pos) => return Err(err.clone().into_err(*pos)),
// id(...args ???
(.., pos) => {
return Err(PERR::MissingToken(
Token::Comma.into(),
format!("to separate the arguments to function call '{id}'"),
)
.into_err(*pos))
}
}
}
}
/// Parse an indexing chain.
/// Indexing binds to the right, so this call parses all possible levels of indexing following in the input.
#[cfg(not(feature = "no_index"))]
fn parse_index_chain(
&self,
state: &mut ParseState,
mut settings: ParseSettings,
lhs: Expr,
options: ASTFlags,
check_types: bool,
) -> ParseResult<Expr> {
fn check_argument_types(lhs: &Expr, idx_expr: &Expr) -> Result<(), ParseError> {
// Check types of indexing that cannot be overridden
// - arrays, maps, strings, bit-fields
match *lhs {
Expr::Map(..) => match *idx_expr {
// lhs[int]
Expr::IntegerConstant(..) => Err(PERR::MalformedIndexExpr(
"Object map expects string index, not a number".into(),
)
.into_err(idx_expr.start_position())),
// lhs[string]
Expr::StringConstant(..) | Expr::InterpolatedString(..) => Ok(()),
// lhs[float]
#[cfg(not(feature = "no_float"))]
Expr::FloatConstant(..) => Err(PERR::MalformedIndexExpr(
"Object map expects string index, not a float".into(),
)
.into_err(idx_expr.start_position())),
// lhs[char]
Expr::CharConstant(..) => Err(PERR::MalformedIndexExpr(
"Object map expects string index, not a character".into(),
)
.into_err(idx_expr.start_position())),
// lhs[()]
Expr::Unit(..) => Err(PERR::MalformedIndexExpr(
"Object map expects string index, not ()".into(),
)
.into_err(idx_expr.start_position())),
// lhs[??? && ???], lhs[??? || ???], lhs[true], lhs[false]
Expr::And(..) | Expr::Or(..) | Expr::BoolConstant(..) => {
Err(PERR::MalformedIndexExpr(
"Object map expects string index, not a boolean".into(),
)
.into_err(idx_expr.start_position()))
}
_ => Ok(()),
},
Expr::IntegerConstant(..)
| Expr::Array(..)
| Expr::StringConstant(..)
| Expr::InterpolatedString(..) => match *idx_expr {
// lhs[int]
Expr::IntegerConstant(..) => Ok(()),
// lhs[string]
Expr::StringConstant(..) | Expr::InterpolatedString(..) => {
Err(PERR::MalformedIndexExpr(
"Array, string or bit-field expects numeric index, not a string".into(),
)
.into_err(idx_expr.start_position()))
}
// lhs[float]
#[cfg(not(feature = "no_float"))]
Expr::FloatConstant(..) => Err(PERR::MalformedIndexExpr(
"Array, string or bit-field expects integer index, not a float".into(),
)
.into_err(idx_expr.start_position())),
// lhs[char]
Expr::CharConstant(..) => Err(PERR::MalformedIndexExpr(
"Array, string or bit-field expects integer index, not a character".into(),
)
.into_err(idx_expr.start_position())),
// lhs[()]
Expr::Unit(..) => Err(PERR::MalformedIndexExpr(
"Array, string or bit-field expects integer index, not ()".into(),
)
.into_err(idx_expr.start_position())),
// lhs[??? && ???], lhs[??? || ???], lhs[true], lhs[false]
Expr::And(..) | Expr::Or(..) | Expr::BoolConstant(..) => {
Err(PERR::MalformedIndexExpr(
"Array, string or bit-field expects integer index, not a boolean"
.into(),
)
.into_err(idx_expr.start_position()))
}
_ => Ok(()),
},
_ => Ok(()),
}
}
let idx_expr = self.parse_expr(state, settings.level_up()?)?;
if check_types {
check_argument_types(&lhs, &idx_expr)?;
}
// Check if there is a closing bracket
match state.input.peek().unwrap() {
(Token::RightBracket, ..) => {
eat_token(state.input, &Token::RightBracket);
// Any more indexing following?
match state.input.peek().unwrap() {
// If another indexing level, right-bind it
(Token::LeftBracket | Token::QuestionBracket, ..) => {
let (token, pos) = state.input.next().unwrap();
let prev_pos = settings.pos;
settings.pos = pos;
let settings = settings.level_up()?;
// Recursively parse the indexing chain, right-binding each
let options = match token {
Token::LeftBracket => ASTFlags::empty(),
Token::QuestionBracket => ASTFlags::NEGATED,
_ => unreachable!("`[` or `?[`"),
};
let idx_expr =
self.parse_index_chain(state, settings, idx_expr, options, false)?;
// Indexing binds to right
Ok(Expr::Index(
BinaryExpr { lhs, rhs: idx_expr }.into(),
options,
prev_pos,
))
}
// Otherwise terminate the indexing chain
_ => Ok(Expr::Index(
BinaryExpr { lhs, rhs: idx_expr }.into(),
options | ASTFlags::BREAK,
settings.pos,
)),
}
}
(Token::LexError(err), pos) => Err(err.clone().into_err(*pos)),
(.., pos) => Err(PERR::MissingToken(
Token::RightBracket.into(),
"for a matching [ in this index expression".into(),
)
.into_err(*pos)),
}
}
/// Parse an array literal.
#[cfg(not(feature = "no_index"))]
fn parse_array_literal(
&self,
state: &mut ParseState,
mut settings: ParseSettings,
) -> ParseResult<Expr> {
// [ ...
settings.pos = eat_token(state.input, &Token::LeftBracket);
let mut array = ThinVec::new();
loop {
const MISSING_RBRACKET: &str = "to end this array literal";
#[cfg(not(feature = "unchecked"))]
if self.max_array_size() > 0 && array.len() >= self.max_array_size() {
return Err(PERR::LiteralTooLarge(
"Size of array literal".into(),
self.max_array_size(),
)
.into_err(state.input.peek().unwrap().1));
}
match state.input.peek().unwrap() {
(Token::RightBracket, ..) => {
eat_token(state.input, &Token::RightBracket);
break;
}
(Token::EOF, pos) => {
return Err(PERR::MissingToken(
Token::RightBracket.into(),
MISSING_RBRACKET.into(),
)
.into_err(*pos))
}
_ => array.push(self.parse_expr(state, settings.level_up()?)?),
}
match state.input.peek().unwrap() {
(Token::Comma, ..) => {
eat_token(state.input, &Token::Comma);
}
(Token::RightBracket, ..) => (),
(Token::EOF, pos) => {
return Err(PERR::MissingToken(
Token::RightBracket.into(),
MISSING_RBRACKET.into(),
)
.into_err(*pos))
}
(Token::LexError(err), pos) => return Err(err.clone().into_err(*pos)),
(.., pos) => {
return Err(PERR::MissingToken(
Token::Comma.into(),
"to separate the items of this array literal".into(),
)
.into_err(*pos))
}
};
}
array.shrink_to_fit();
Ok(Expr::Array(array, settings.pos))
}
/// Parse a map literal.
#[cfg(not(feature = "no_object"))]
fn parse_map_literal(
&self,
state: &mut ParseState,
mut settings: ParseSettings,
) -> ParseResult<Expr> {
// #{ ...
settings.pos = eat_token(state.input, &Token::MapStart);
let mut map = StaticVec::<(Ident, Expr)>::new();
let mut template = std::collections::BTreeMap::<crate::Identifier, crate::Dynamic>::new();
loop {
const MISSING_RBRACE: &str = "to end this object map literal";
match state.input.peek().unwrap() {
(Token::RightBrace, ..) => {
eat_token(state.input, &Token::RightBrace);