-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression.rs
More file actions
2162 lines (1948 loc) · 72 KB
/
expression.rs
File metadata and controls
2162 lines (1948 loc) · 72 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
use rusty_common::*;
use rusty_pc::and::{KeepLeftCombiner, VecCombiner};
use rusty_pc::*;
use rusty_variant::{MIN_INTEGER, MIN_LONG};
use crate::core::opt_second_expression::conditionally_opt_whitespace;
use crate::input::StringView;
use crate::pc_specific::*;
use crate::tokens::comma_ws;
use crate::{
BuiltInFunction, ExpressionType, FileHandle, HasExpressionType, Name, Operator, ParserError, TypeQualifier, UnaryOperator, VariableInfo
};
// TODO move traits and logic that is linter specific to linter (including CanCastTo from common)
#[derive(Clone, Debug, PartialEq)]
pub enum Expression {
SingleLiteral(f32),
DoubleLiteral(f64),
StringLiteral(String),
IntegerLiteral(i32),
LongLiteral(i64),
Variable(Name, VariableInfo),
/// During parsing, arrays are also parsed as function calls.
/// Only during linting can it be determined if it's an array or a function call.
FunctionCall(Name, Expressions),
/// Not a parser type, only at linting can we determine
/// if it's a FunctionCall or an ArrayElement
ArrayElement(
// the name of the array (unqualified only for user defined types)
Name,
// the array indices
Expressions,
// the type of the elements (shared refers to the array itself)
VariableInfo,
),
BuiltInFunctionCall(BuiltInFunction, Expressions),
BinaryExpression(
Operator,
Box<ExpressionPos>,
Box<ExpressionPos>,
ExpressionType,
),
UnaryExpression(UnaryOperator, Box<ExpressionPos>),
Parenthesis(Box<ExpressionPos>),
/// A property of a user defined type
///
/// The left side is the expression owning the element,
/// the right side is the element name.
///
/// Examples:
///
/// - A.B (A left, B right)
/// - A(1).B ( A(1) left, B right)
/// - A.B.C (A.B left, C right)
Property(Box<Self>, Name, ExpressionType),
}
pub type ExpressionPos = Positioned<Expression>;
pub type Expressions = Vec<ExpressionPos>;
impl From<f32> for Expression {
fn from(f: f32) -> Self {
Self::SingleLiteral(f)
}
}
impl From<f64> for Expression {
fn from(f: f64) -> Self {
Self::DoubleLiteral(f)
}
}
impl From<String> for Expression {
fn from(f: String) -> Self {
Self::StringLiteral(f)
}
}
impl From<&str> for Expression {
fn from(f: &str) -> Self {
f.to_string().into()
}
}
impl From<i32> for Expression {
fn from(f: i32) -> Self {
Self::IntegerLiteral(f)
}
}
impl From<i64> for Expression {
fn from(f: i64) -> Self {
Self::LongLiteral(f)
}
}
impl From<FileHandle> for Expression {
fn from(file_handle: FileHandle) -> Self {
Self::IntegerLiteral(file_handle.into())
}
}
impl Expression {
#[cfg(test)]
pub fn func(s: &str, args: Expressions) -> Self {
let name: Name = s.into();
Expression::FunctionCall(name, args)
}
fn unary_minus(child_pos: ExpressionPos) -> Self {
let Positioned {
element: child,
pos,
} = child_pos;
match child {
Self::SingleLiteral(n) => Self::SingleLiteral(-n),
Self::DoubleLiteral(n) => Self::DoubleLiteral(-n),
Self::IntegerLiteral(n) => {
if n <= MIN_INTEGER {
Self::LongLiteral(-n as i64)
} else {
Self::IntegerLiteral(-n)
}
}
Self::LongLiteral(n) => {
if n <= MIN_LONG {
Self::DoubleLiteral(-n as f64)
} else {
Self::LongLiteral(-n)
}
}
_ => Self::UnaryExpression(
UnaryOperator::Minus,
Box::new(child.simplify_unary_minus_literals().at_pos(pos)),
),
}
}
pub fn simplify_unary_minus_literals(self) -> Self {
match self {
Self::UnaryExpression(op, child) => {
let x: ExpressionPos = *child;
match op {
UnaryOperator::Minus => Self::unary_minus(x),
_ => Self::UnaryExpression(op, Self::simplify_unary_minus_pos(x)),
}
}
Self::BinaryExpression(op, left, right, old_expression_type) => Self::BinaryExpression(
op,
Self::simplify_unary_minus_pos(*left),
Self::simplify_unary_minus_pos(*right),
old_expression_type,
),
Self::Parenthesis(child) => Self::Parenthesis(Self::simplify_unary_minus_pos(*child)),
Self::FunctionCall(name, args) => Self::FunctionCall(
name,
args.into_iter()
.map(|a| a.map(|x| x.simplify_unary_minus_literals()))
.collect(),
),
_ => self,
}
}
fn simplify_unary_minus_pos(child: ExpressionPos) -> Box<ExpressionPos> {
let Positioned { element, pos } = child;
let simplified = element.simplify_unary_minus_literals();
Box::new(simplified.at_pos(pos))
}
/// Returns the name of this `Variable` or `Property` expression.
/// For properties, this is the concatenated name of all elements in the property path.
pub fn fold_name(&self) -> Option<Name> {
match self {
Self::Variable(n, _) => Some(n.clone()),
Self::Property(left_side, property_name, _) => match left_side.fold_name() {
Some(left_side_name) => left_side_name.try_concat_name(property_name.clone()),
_ => None,
},
_ => None,
}
}
pub fn left_most_name(&self) -> Option<&Name> {
match self {
Self::Variable(n, _) | Self::FunctionCall(n, _) | Self::ArrayElement(n, _, _) => {
Some(n)
}
Self::Property(left_side, _, _) => left_side.left_most_name(),
_ => None,
}
}
#[cfg(test)]
pub fn var_unresolved(s: &str) -> Self {
let name: Name = s.into();
Self::Variable(name, VariableInfo::unresolved())
}
// TODO #[cfg(test)] but used by rusty_linter too
pub fn var_resolved(s: &str) -> Self {
let name: Name = s.into();
let expression_type = name.expression_type();
Self::Variable(name, VariableInfo::new_local(expression_type))
}
// TODO #[cfg(test)] but used by rusty_linter too
pub fn var_user_defined(name: &str, type_name: &str) -> Self {
Self::Variable(
name.into(),
VariableInfo::new_local(ExpressionType::UserDefined(type_name.into())),
)
}
fn flip_multiply_plus(l_op: &Operator, r_op: &Operator) -> bool {
(l_op.is_multiply_or_divide() || *l_op == Operator::Modulo) && r_op.is_plus_or_minus()
}
fn flip_plus_minus(l_op: &Operator, r_op: &Operator) -> bool {
//
// A + B - C is parsed as
//
// +
// A -
// B C
//
// needs to flip into
//
// -
// + C
// A B
l_op.is_plus_or_minus() && r_op.is_plus_or_minus()
}
fn flip_multiply_divide(l_op: &Operator, r_op: &Operator) -> bool {
l_op.is_multiply_or_divide() && r_op.is_multiply_or_divide()
}
}
// TODO #[deprecated]
pub trait ExpressionPosTrait {
fn flip_binary(self) -> Self;
fn simplify_unary_minus_literals(self) -> Self;
fn apply_priority_order(self, right_side: Self, op: Operator, pos: Position) -> Self;
fn binary_expr(self, op: Operator, right_side: Self, pos: Position) -> Self;
fn apply_unary_priority_order(self, op: UnaryOperator, op_pos: Position) -> Self;
}
impl ExpressionPosTrait for ExpressionPos {
/// Flips a binary expression.
///
/// `A AND B OR C` would be parsed as `A AND (B OR C)` but needs to be `(A AND B) OR C`.
fn flip_binary(self) -> Self {
let Self { element, pos } = self;
if let Expression::BinaryExpression(l_op, l_left, l_right, _) = element {
let Self {
element: r_element,
pos: r_pos,
} = *l_right;
if let Expression::BinaryExpression(r_op, r_left, r_right, _) = r_element {
let new_left = l_left.binary_expr(l_op, *r_left, pos);
new_left.binary_expr(r_op, *r_right, r_pos)
} else {
panic!("should_flip_binary internal error")
}
} else {
panic!("should_flip_binary internal error")
}
}
fn simplify_unary_minus_literals(self) -> Self {
self.map(|x| x.simplify_unary_minus_literals())
}
fn apply_priority_order(self, right_side: Self, op: Operator, pos: Position) -> Self {
self.binary_expr(op, right_side, pos)
}
fn binary_expr(self, op: Operator, right_side: Self, pos: Position) -> Self {
let result = Expression::BinaryExpression(
op,
Box::new(self),
Box::new(right_side),
ExpressionType::Unresolved,
)
.at_pos(pos);
if result.should_flip_binary() {
result.flip_binary()
} else {
result
}
}
/// Applies the unary operator priority order.
///
/// `NOT A AND B` would be parsed as `NOT (A AND B)`, needs to flip into `(NOT A) AND B`
fn apply_unary_priority_order(self, op: UnaryOperator, op_pos: Position) -> Self {
if self.should_flip_unary(op) {
let Self { element, pos } = self;
match element {
Expression::BinaryExpression(r_op, r_left, r_right, _) => {
// apply the unary operator to the left of the binary expr
let new_left = Expression::UnaryExpression(op, r_left).at_pos(op_pos);
// and nest it as left inside a binary expr
new_left.binary_expr(r_op, *r_right, pos)
}
_ => panic!("should_flip_unary internal error"),
}
} else {
Expression::UnaryExpression(op, Box::new(self)).at_pos(op_pos)
}
}
}
impl HasExpressionType for Expression {
fn expression_type(&self) -> ExpressionType {
match self {
Self::SingleLiteral(_) => ExpressionType::BuiltIn(TypeQualifier::BangSingle),
Self::DoubleLiteral(_) => ExpressionType::BuiltIn(TypeQualifier::HashDouble),
Self::StringLiteral(_) => ExpressionType::BuiltIn(TypeQualifier::DollarString),
Self::IntegerLiteral(_) => ExpressionType::BuiltIn(TypeQualifier::PercentInteger),
Self::LongLiteral(_) => ExpressionType::BuiltIn(TypeQualifier::AmpersandLong),
Self::Variable(
_,
VariableInfo {
expression_type, ..
},
)
| Self::Property(_, _, expression_type)
| Self::BinaryExpression(_, _, _, expression_type) => expression_type.clone(),
Self::ArrayElement(
_,
args,
VariableInfo {
expression_type, ..
},
) => {
if args.is_empty() {
// this is the entire array
ExpressionType::Array(Box::new(expression_type.clone()))
} else {
// an element of the array
expression_type.clone()
}
}
Self::FunctionCall(name, _) => name.expression_type(),
Self::BuiltInFunctionCall(f, _) => ExpressionType::BuiltIn(f.into()),
Self::UnaryExpression(_, c) | Self::Parenthesis(c) => c.expression_type(),
}
}
}
impl HasExpressionType for ExpressionPos {
fn expression_type(&self) -> ExpressionType {
self.element.expression_type()
}
}
impl HasExpressionType for Box<ExpressionPos> {
fn expression_type(&self) -> ExpressionType {
self.as_ref().expression_type()
}
}
pub trait ExpressionTrait {
fn is_parenthesis(&self) -> bool;
fn should_flip_unary(&self, op: UnaryOperator) -> bool;
fn should_flip_binary(&self) -> bool;
fn is_by_ref(&self) -> bool;
}
impl ExpressionTrait for Expression {
fn is_parenthesis(&self) -> bool {
matches!(self, Self::Parenthesis(_))
}
fn should_flip_unary(&self, op: UnaryOperator) -> bool {
match self {
Self::BinaryExpression(r_op, _, _, _) => op == UnaryOperator::Minus || r_op.is_binary(),
_ => false,
}
}
fn should_flip_binary(&self) -> bool {
match self {
Self::BinaryExpression(l_op, _, l_right, _) => match &l_right.element {
Self::BinaryExpression(r_op, _, _, _) => {
l_op.is_arithmetic() && (r_op.is_relational() || r_op.is_binary())
|| l_op.is_relational() && r_op.is_binary()
|| *l_op == Operator::And && *r_op == Operator::Or
|| Self::flip_multiply_plus(l_op, r_op)
|| Self::flip_plus_minus(l_op, r_op)
|| Self::flip_multiply_divide(l_op, r_op)
}
_ => false,
},
_ => false,
}
}
fn is_by_ref(&self) -> bool {
matches!(
self,
Self::Variable(_, _) | Self::ArrayElement(_, _, _) | Self::Property(_, _, _)
)
}
}
impl ExpressionTrait for ExpressionPos {
// needed by parser
fn is_parenthesis(&self) -> bool {
self.element.is_parenthesis()
}
fn should_flip_unary(&self, op: UnaryOperator) -> bool {
self.element.should_flip_unary(op)
}
fn should_flip_binary(&self) -> bool {
self.element.should_flip_binary()
}
fn is_by_ref(&self) -> bool {
self.element.is_by_ref()
}
}
impl ExpressionTrait for Box<ExpressionPos> {
fn is_parenthesis(&self) -> bool {
self.as_ref().is_parenthesis()
}
fn should_flip_unary(&self, op: UnaryOperator) -> bool {
self.as_ref().should_flip_unary(op)
}
fn should_flip_binary(&self) -> bool {
self.as_ref().should_flip_binary()
}
fn is_by_ref(&self) -> bool {
self.as_ref().is_by_ref()
}
}
/// `( expr [, expr]* )`
pub fn in_parenthesis_csv_expressions_non_opt(
expectation: &str,
) -> impl Parser<StringView, Output = Expressions, Error = ParserError> + '_ {
in_parenthesis(csv_expressions_non_opt(expectation)).to_fatal()
}
/// Parses one or more expressions separated by comma.
/// FIXME Unlike csv_expressions, the first expression does not need a separator!
pub fn csv_expressions_non_opt(
expectation: &str,
) -> impl Parser<StringView, Output = Expressions, Error = ParserError> + use<'_> {
csv_non_opt(expression_pos_p(), expectation)
}
/// Parses one or more expressions separated by comma.
/// Trailing commas are not allowed.
/// Missing expressions are not allowed.
/// The first expression needs to be preceded by space or surrounded in parenthesis.
pub fn csv_expressions_first_guarded()
-> impl Parser<StringView, Output = Expressions, Error = ParserError> {
ws_expr_pos_p().map(|first| vec![first]).and(
comma_ws()
.and_keep_right(expression_pos_p().or_expected("expression after comma"))
.zero_or_more(),
VecCombiner,
)
}
pub fn expression_pos_p() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
lazy(eager_expression_pos_p)
}
/// Parses an expression that is either preceded by whitespace
/// or is a parenthesis expression.
///
/// ```text
/// <ws> <expr-not-in-parenthesis> |
/// <ws> <expr-in-parenthesis> |
/// <expr-in-parenthesis>
/// ```
pub fn ws_expr_pos_p() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
// ws* ( expr )
// ws+ expr
preceded_by_ws(expression_pos_p())
}
/// Parses an expression that is either followed by whitespace
/// or is a parenthesis expression.
///
/// The whitespace is mandatory after a non-parenthesis
/// expression.
///
/// ```text
/// <expr-not-in-parenthesis> <ws> |
/// <expr-in-parenthesis> <ws> |
/// <expr-in-parenthesis>
/// ```
pub fn expr_pos_ws_p() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
followed_by_ws(expression_pos_p())
}
/// Parses an expression that is either surrounded by whitespace
/// or is a parenthesis expression.
///
/// The whitespace is mandatory after a non-parenthesis
/// expression.
///
/// ```text
/// <ws> <expr-not-in-parenthesis> <ws> |
/// <ws> <expr-in-parenthesis> <ws> |
/// <expr-in-parenthesis>
/// ```
pub fn ws_expr_pos_ws_p() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
followed_by_ws(ws_expr_pos_p())
}
fn preceded_by_ws(
parser: impl Parser<StringView, Output = ExpressionPos, Error = ParserError>,
) -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
guard::parser().and_keep_right(parser)
}
fn followed_by_ws(
parser: impl Parser<StringView, Output = ExpressionPos, Error = ParserError>,
) -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
parser.then_with_in_context(
conditionally_opt_whitespace(),
|e| e.is_parenthesis(),
KeepLeftCombiner,
)
}
/// Parses an expression
fn eager_expression_pos_p() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError>
{
binary_expression::parser()
}
mod single_or_double_literal {
use rusty_pc::*;
use crate::input::StringView;
use crate::pc_specific::WithPos;
use crate::tokens::{digits, dot, pound};
use crate::{ParserError, *};
// single ::= <digits> . <digits>
// single ::= . <digits> (without leading zero)
// double ::= <digits> . <digits> "#"
// double ::= . <digits> "#"
// TODO support more qualifiers besides '#'
pub fn parser() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
// read integer digits optionally (might start with . e.g. `.123`)
digits()
.to_option()
// read dot and demand digits after decimal point
// if dot is missing, the parser returns an empty result
// the "deal breaker" is therefore the dot
.and_keep_left(dot())
// demand digits after decimal point
.and_tuple(digits().to_fatal())
// and parse optionally a type qualifier such as `#`
.and_tuple(pound().to_option())
// done parsing, flat map everything
.and_then(|((opt_integer_digits, frac_digits), opt_pound)| {
let left = opt_integer_digits
.map(|token| token.to_string())
.unwrap_or_else(|| "0".to_owned());
let s = format!("{}.{}", left, frac_digits.as_str());
if opt_pound.is_some() {
match s.parse::<f64>() {
Ok(f) => Ok(Expression::DoubleLiteral(f)),
Err(err) => Err(err.into()),
}
} else {
match s.parse::<f32>() {
Ok(f) => Ok(Expression::SingleLiteral(f)),
Err(err) => Err(err.into()),
}
}
})
.with_pos()
}
}
mod string_literal {
use rusty_pc::many::StringManyCombiner;
use rusty_pc::*;
use crate::input::StringView;
use crate::pc_specific::*;
use crate::tokens::{MatchMode, TokenType, any_symbol_of, any_token_of};
use crate::{ParserError, *};
pub fn parser() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
surround(
string_delimiter(),
inside_string(),
string_delimiter(),
SurroundMode::Mandatory,
)
.map(Expression::StringLiteral)
.with_pos()
}
fn string_delimiter() -> impl Parser<StringView, Output = Token, Error = ParserError> {
// TODO support ignoring token to avoid allocation
any_symbol_of!('"')
}
fn inside_string() -> impl Parser<StringView, Output = String, Error = ParserError> {
any_token_of!(
types = TokenType::Eol ;
symbols = '"' ;
mode = MatchMode::Exclude)
.many_allow_none(StringManyCombiner)
}
}
mod integer_or_long_literal {
use rusty_pc::*;
use rusty_variant::{BitVec, BitVecIntOrLong, MAX_INTEGER, MAX_LONG};
use crate::error::ParserError;
use crate::input::StringView;
use crate::pc_specific::WithPos;
use crate::tokens::{TokenType, any_token_of};
use crate::*;
// result ::= <digits> | <hex-digits> | <oct-digits>
pub fn parser() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
any_token_of!(
TokenType::Digits,
TokenType::HexDigits,
TokenType::OctDigits
)
.and_then(process_token)
.with_pos()
}
fn process_token(token: Token) -> Result<Expression, ParserError> {
match TokenType::from_token(&token) {
TokenType::Digits => process_dec(token),
TokenType::HexDigits => process_hex(token),
TokenType::OctDigits => process_oct(token),
_ => panic!("Should not have processed {}", token),
}
}
fn process_dec(token: Token) -> Result<Expression, ParserError> {
match token.to_string().parse::<u32>() {
Ok(u) => {
if u <= MAX_INTEGER as u32 {
Ok(Expression::IntegerLiteral(u as i32))
} else if u <= MAX_LONG as u32 {
Ok(Expression::LongLiteral(u as i64))
} else {
Ok(Expression::DoubleLiteral(u as f64))
}
}
Err(e) => Err(e.into()),
}
}
fn process_hex(token: Token) -> Result<Expression, ParserError> {
// token text is &HFFFF or &H-FFFF
let mut s: String = token.to_string();
// remove &
s.remove(0);
// remove H
s.remove(0);
if s.starts_with('-') {
Err(ParserError::Overflow)
} else {
let mut result: BitVec = BitVec::new();
for digit in s.chars().skip_while(|ch| *ch == '0') {
let hex = convert_hex_digit(digit);
result.push_hex(hex);
}
create_expression_from_bit_vec(result)
}
}
fn convert_hex_digit(ch: char) -> u8 {
if ch.is_ascii_digit() {
(ch as u8) - b'0'
} else if ('a'..='f').contains(&ch) {
(ch as u8) - b'a' + 10
} else if ('A'..='F').contains(&ch) {
(ch as u8) - b'A' + 10
} else {
panic!("Unexpected hex digit: {}", ch)
}
}
fn process_oct(token: Token) -> Result<Expression, ParserError> {
let mut s: String = token.to_string();
// remove &
s.remove(0);
// remove O
s.remove(0);
if s.starts_with('-') {
Err(ParserError::Overflow)
} else {
let mut result: BitVec = BitVec::new();
for digit in s.chars().skip_while(|ch| *ch == '0') {
let oct = convert_oct_digit(digit);
result.push_oct(oct);
}
create_expression_from_bit_vec(result)
}
}
fn convert_oct_digit(ch: char) -> u8 {
if ('0'..='7').contains(&ch) {
(ch as u8) - b'0'
} else {
panic!("Unexpected oct digit: {}", ch)
}
}
fn create_expression_from_bit_vec(bit_vec: BitVec) -> Result<Expression, ParserError> {
bit_vec
.convert_to_int_or_long_expr()
.map(|x| match x {
BitVecIntOrLong::Int(i) => Expression::IntegerLiteral(i),
BitVecIntOrLong::Long(l) => Expression::LongLiteral(l),
})
.map_err(|_| ParserError::Overflow)
}
}
// TODO consider nesting variable/function_call modules inside property as they are only used there
mod variable {
use std::collections::VecDeque;
use rusty_pc::*;
use crate::core::name::{name_as_tokens_p, token_to_type_qualifier};
use crate::input::StringView;
use crate::pc_specific::WithPos;
use crate::{ParserError, *};
// variable ::= <identifier-with-dots>
// | <identifier-with-dots> <type-qualifier>
// | <keyword> "$"
//
// must not be followed by parenthesis (solved by ordering of parsers)
//
// if <identifier-with-dots> contains dots, it might be converted to a property expression
pub fn parser() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
name_as_tokens_p().map(map_to_expr).with_pos()
}
fn map_to_expr(name_as_tokens: NameAsTokens) -> Expression {
if is_property_expr(&name_as_tokens) {
map_to_property(name_as_tokens)
} else {
Expression::Variable(name_as_tokens.into(), VariableInfo::unresolved())
}
}
fn is_property_expr(name_as_tokens: &NameAsTokens) -> bool {
let (name_token, _) = name_as_tokens;
let mut name_count = 1;
let mut last_was_dot = false;
// leading dot cannot happen
debug_assert!(!name_token.as_str().starts_with('.'));
for name in name_token.as_str().chars() {
if '.' == name {
if last_was_dot {
// two dots in a row
return false;
} else {
last_was_dot = true;
}
} else {
if last_was_dot {
name_count += 1;
last_was_dot = false;
}
}
}
// at least two names and no trailing dot
name_count > 1 && !last_was_dot
}
fn map_to_property(name_as_tokens: NameAsTokens) -> Expression {
let (name_token, opt_q_token) = name_as_tokens;
let mut property_names: VecDeque<String> = name_token
.as_str()
.split('.')
.map(|s| s.to_owned())
.collect();
let mut result = Expression::Variable(
Name::bare(BareName::new(property_names.pop_front().unwrap())),
VariableInfo::unresolved(),
);
while let Some(property_name) = property_names.pop_front() {
let is_last = property_names.is_empty();
let opt_q_next = if is_last {
opt_q_token.as_ref().map(token_to_type_qualifier)
} else {
None
};
result = Expression::Property(
Box::new(result),
Name::new(BareName::new(property_name), opt_q_next),
ExpressionType::Unresolved,
);
}
result
}
}
mod function_call_or_array_element {
use rusty_pc::*;
use crate::core::expression::expression_pos_p;
use crate::core::name::name_as_tokens_p;
use crate::input::StringView;
use crate::pc_specific::{WithPos, csv, in_parenthesis};
use crate::{ParserError, *};
// function_call ::= <function-name> "(" <expr>* ")"
// function-name ::= <identifier-with-dots>
// | <identifier-with-dots> <type-qualifier>
// | <keyword> "$"
//
// Cannot invoke function with empty parenthesis, even if they don't have arguments.
// However, it is allowed for arrays, so we parse it.
//
// A function can be qualified.
pub fn parser() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
name_as_tokens_p()
.and(
in_parenthesis(csv(expression_pos_p()).or_default()),
|name_as_tokens: NameAsTokens, arguments: Expressions| {
Expression::FunctionCall(name_as_tokens.into(), arguments)
},
)
.with_pos()
}
}
pub mod property {
use rusty_pc::and::TupleCombiner;
use rusty_pc::*;
use crate::core::name::{name_as_tokens_p, token_to_type_qualifier};
use crate::error::ParserError;
use crate::input::StringView;
use crate::pc_specific::OrExpected;
use crate::tokens::dot;
use crate::*;
// property ::= <expr> "." <property-name>
// property-name ::= <identifier-without-dot>
// | <identifier-without-dot> <type-qualifier>
//
// expr must not be qualified
pub fn parser() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
base_expr_pos_p()
.then_with_in_context(
ctx_dot_property(),
|first_expr_pos| is_qualified(&first_expr_pos.element),
TupleCombiner,
)
.and_then(|(first_expr_pos, properties)| {
// not possible to have properties for qualified first expr
// therefore either we don't have properties
// or if we do then the first expr is bare
debug_assert!(properties.is_none() || !is_qualified(&first_expr_pos.element));
match properties {
Some((property_name, opt_q_token)) => {
let text = property_name.as_str();
let mut it = text.split('.').peekable();
let mut result = first_expr_pos;
while let Some(name) = it.next() {
if name.is_empty() {
// detected something like X = Y(1).A..B
return Err(ParserError::expected("identifier").to_fatal());
}
let property_name = if it.peek().is_some() {
Name::bare(BareName::new(name.to_owned()))
} else {
Name::new(
BareName::new(name.to_owned()),
opt_q_token.as_ref().map(token_to_type_qualifier),
)
};
result = result.map(|prev_expr| {
Expression::Property(
Box::new(prev_expr),
property_name,
ExpressionType::Unresolved,
)
});
}
Ok(result)
}
None => Ok(first_expr_pos),
}
})
}
/// Parses an optional `.property` after the first expression was parsed.
/// The boolean context indicates whether the previously parsed expression
/// was qualified or not.
/// If it was qualified, we return Ok(None) without trying to parse,
/// because qualified names can't have properties.
fn ctx_dot_property()
-> impl Parser<StringView, bool, Output = Option<NameAsTokens>, Error = ParserError> {
ctx_parser()
.and_then(|was_first_expr_qualified| {
if was_first_expr_qualified {
// fine, don't parse anything further
// i.e. A$(1).Name won't attempt to parse the .Name part
Ok(None)
} else {
// it wasn't qualified, therefore let the dot_property continue
default_parse_error()
}
})
.or(dot_property().no_context())
}
fn dot_property() -> impl Parser<StringView, Output = Option<NameAsTokens>, Error = ParserError>
{
dot()
.and_keep_right(name_as_tokens_p().or_expected("property name after dot"))
.to_option()
}
/// Returns a name expression which could be a function call (array)
/// e.g. `A$(1)`,
/// or a variable e.g. `A.B.C$` (which can be Variable or Property).
/// can't use expression_pos_p because it will stack overflow
fn base_expr_pos_p() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
// order is important, variable matches anything that function_call_or_array_element matches
OrParser::new(vec![
Box::new(super::function_call_or_array_element::parser()),
Box::new(super::variable::parser()),
])
}
pub fn is_qualified(expr: &Expression) -> bool {
match expr {
Expression::Variable(name, _)
| Expression::FunctionCall(name, _)
| Expression::Property(_, name, _) => !name.is_bare(),
_ => {
panic!("Unexpected property type {:?}", expr)
}
}
}
}
mod built_in_function_call {
use rusty_pc::Parser;
use crate::built_ins::built_in_function_call_p;
use crate::input::StringView;
use crate::pc_specific::WithPos;
use crate::{ParserError, *};
pub fn parser() -> impl Parser<StringView, Output = ExpressionPos, Error = ParserError> {
built_in_function_call_p().with_pos()
}
}
mod binary_expression {
use rusty_common::Positioned;
use rusty_pc::and::TupleCombiner;