-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathexpression.go
1818 lines (1516 loc) Β· 43.4 KB
/
expression.go
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
/*
* Cadence - The resource-oriented smart contract programming language
*
* Copyright Flow Foundation
*
* 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.
*/
package old_parser
import (
"math/big"
"strings"
"unicode/utf8"
"github.com/onflow/cadence/ast"
"github.com/onflow/cadence/common"
"github.com/onflow/cadence/errors"
"github.com/onflow/cadence/parser/lexer"
)
const exprBindingPowerGap = 10
const (
exprLeftBindingPowerTernary = exprBindingPowerGap * (iota + 2)
exprLeftBindingPowerLogicalOr
exprLeftBindingPowerLogicalAnd
exprLeftBindingPowerComparison
exprLeftBindingPowerNilCoalescing
exprLeftBindingPowerBitwiseOr
exprLeftBindingPowerBitwiseXor
exprLeftBindingPowerBitwiseAnd
exprLeftBindingPowerBitwiseShift
exprLeftBindingPowerAddition
exprLeftBindingPowerMultiplication
exprLeftBindingPowerCasting
exprLeftBindingPowerUnaryPrefix
exprLeftBindingPowerUnaryPostfix
exprLeftBindingPowerAccess
)
type infixExprFunc func(parser *parser, left, right ast.Expression) (ast.Expression, error)
type prefixExprFunc func(parser *parser, right ast.Expression, tokenRange ast.Range) (ast.Expression, error)
type postfixExprFunc func(parser *parser, left ast.Expression, tokenRange ast.Range) (ast.Expression, error)
type exprNullDenotationFunc func(parser *parser, token lexer.Token) (ast.Expression, error)
type exprMetaLeftDenotationFunc func(
p *parser,
rightBindingPower int,
left ast.Expression,
) (
result ast.Expression,
err error,
done bool,
)
type literalExpr struct {
nullDenotation exprNullDenotationFunc
tokenType lexer.TokenType
}
type infixExpr struct {
leftDenotation infixExprFunc
leftBindingPower int
tokenType lexer.TokenType
rightAssociative bool
}
type binaryExpr struct {
leftBindingPower int
operation ast.Operation
tokenType lexer.TokenType
rightAssociative bool
}
type prefixExpr struct {
nullDenotation prefixExprFunc
bindingPower int
tokenType lexer.TokenType
}
type unaryExpr struct {
tokenType lexer.TokenType
bindingPower int
operation ast.Operation
}
type postfixExpr struct {
leftDenotation postfixExprFunc
bindingPower int
tokenType lexer.TokenType
}
var exprNullDenotations = [lexer.TokenMax]exprNullDenotationFunc{}
type exprLeftDenotationFunc func(parser *parser, token lexer.Token, left ast.Expression) (ast.Expression, error)
var exprLeftBindingPowers = [lexer.TokenMax]int{}
var exprIdentifierLeftBindingPowers = map[string]int{}
var exprLeftDenotations = [lexer.TokenMax]exprLeftDenotationFunc{}
var exprMetaLeftDenotations = [lexer.TokenMax]exprMetaLeftDenotationFunc{}
func defineExpr(def any) {
switch def := def.(type) {
case infixExpr:
tokenType := def.tokenType
setExprLeftBindingPower(tokenType, def.leftBindingPower)
rightBindingPower := def.leftBindingPower
if def.rightAssociative {
rightBindingPower--
}
setExprLeftDenotation(
tokenType,
func(parser *parser, _ lexer.Token, left ast.Expression) (ast.Expression, error) {
right, err := parseExpression(parser, rightBindingPower)
if err != nil {
return nil, err
}
return def.leftDenotation(parser, left, right)
},
)
case binaryExpr:
defineExpr(infixExpr{
tokenType: def.tokenType,
leftBindingPower: def.leftBindingPower,
rightAssociative: def.rightAssociative,
leftDenotation: func(p *parser, left, right ast.Expression) (ast.Expression, error) {
return ast.NewBinaryExpression(
p.memoryGauge,
def.operation,
left,
right,
), nil
},
})
case literalExpr:
tokenType := def.tokenType
setExprNullDenotation(tokenType, def.nullDenotation)
case prefixExpr:
tokenType := def.tokenType
setExprNullDenotation(
tokenType,
func(parser *parser, token lexer.Token) (ast.Expression, error) {
right, err := parseExpression(parser, def.bindingPower)
if err != nil {
return nil, err
}
return def.nullDenotation(parser, right, token.Range)
},
)
case unaryExpr:
defineExpr(prefixExpr{
tokenType: def.tokenType,
bindingPower: def.bindingPower,
nullDenotation: func(p *parser, right ast.Expression, tokenRange ast.Range) (ast.Expression, error) {
return ast.NewUnaryExpression(
p.memoryGauge,
def.operation,
right,
tokenRange.StartPos,
), nil
},
})
case postfixExpr:
tokenType := def.tokenType
setExprLeftBindingPower(tokenType, def.bindingPower)
setExprLeftDenotation(
tokenType,
func(p *parser, token lexer.Token, left ast.Expression) (ast.Expression, error) {
return def.leftDenotation(p, left, token.Range)
},
)
default:
panic(errors.NewUnreachableError())
}
}
func setExprNullDenotation(tokenType lexer.TokenType, nullDenotation exprNullDenotationFunc) {
current := exprNullDenotations[tokenType]
if current != nil {
panic(errors.NewUnexpectedError(
"expression null denotation for token %s already exists",
tokenType,
))
}
exprNullDenotations[tokenType] = nullDenotation
}
func setExprLeftBindingPower(tokenType lexer.TokenType, power int) {
current := exprLeftBindingPowers[tokenType]
if current > power {
return
}
exprLeftBindingPowers[tokenType] = power
}
func setExprIdentifierLeftBindingPower(keyword string, power int) {
current := exprIdentifierLeftBindingPowers[keyword]
if current > power {
return
}
exprIdentifierLeftBindingPowers[keyword] = power
}
func setExprLeftDenotation(tokenType lexer.TokenType, leftDenotation exprLeftDenotationFunc) {
current := exprLeftDenotations[tokenType]
if current != nil {
panic(errors.NewUnexpectedError(
"expression left denotation for token %s already exists",
tokenType,
))
}
exprLeftDenotations[tokenType] = leftDenotation
}
func setExprMetaLeftDenotation(tokenType lexer.TokenType, metaLeftDenotation exprMetaLeftDenotationFunc) {
current := exprMetaLeftDenotations[tokenType]
if current != nil {
panic(errors.NewUnexpectedError(
"expression meta left denotation for token %s already exists",
tokenType,
))
}
exprMetaLeftDenotations[tokenType] = metaLeftDenotation
}
// init defines the binding power for operations.
func init() {
defineExpr(binaryExpr{
tokenType: lexer.TokenVerticalBarVerticalBar,
leftBindingPower: exprLeftBindingPowerLogicalOr,
operation: ast.OperationOr,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenAmpersandAmpersand,
leftBindingPower: exprLeftBindingPowerLogicalAnd,
operation: ast.OperationAnd,
})
defineLessThanOrTypeArgumentsExpression()
defineGreaterThanOrBitwiseRightShiftExpression()
defineExpr(binaryExpr{
tokenType: lexer.TokenLessEqual,
leftBindingPower: exprLeftBindingPowerComparison,
operation: ast.OperationLessEqual,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenGreaterEqual,
leftBindingPower: exprLeftBindingPowerComparison,
operation: ast.OperationGreaterEqual,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenEqualEqual,
leftBindingPower: exprLeftBindingPowerComparison,
operation: ast.OperationEqual,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenNotEqual,
leftBindingPower: exprLeftBindingPowerComparison,
operation: ast.OperationNotEqual,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenDoubleQuestionMark,
leftBindingPower: exprLeftBindingPowerNilCoalescing,
operation: ast.OperationNilCoalesce,
rightAssociative: true,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenVerticalBar,
leftBindingPower: exprLeftBindingPowerBitwiseOr,
operation: ast.OperationBitwiseOr,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenCaret,
leftBindingPower: exprLeftBindingPowerBitwiseXor,
operation: ast.OperationBitwiseXor,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenAmpersand,
leftBindingPower: exprLeftBindingPowerBitwiseAnd,
operation: ast.OperationBitwiseAnd,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenLessLess,
leftBindingPower: exprLeftBindingPowerBitwiseShift,
operation: ast.OperationBitwiseLeftShift,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenPlus,
leftBindingPower: exprLeftBindingPowerAddition,
operation: ast.OperationPlus,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenMinus,
leftBindingPower: exprLeftBindingPowerAddition,
operation: ast.OperationMinus,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenStar,
leftBindingPower: exprLeftBindingPowerMultiplication,
operation: ast.OperationMul,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenSlash,
leftBindingPower: exprLeftBindingPowerMultiplication,
operation: ast.OperationDiv,
})
defineExpr(binaryExpr{
tokenType: lexer.TokenPercent,
leftBindingPower: exprLeftBindingPowerMultiplication,
operation: ast.OperationMod,
})
defineIdentifierLeftDenotations()
defineExpr(literalExpr{
tokenType: lexer.TokenBinaryIntegerLiteral,
nullDenotation: func(p *parser, token lexer.Token) (ast.Expression, error) {
literal := p.tokenSource(token)
return parseIntegerLiteral(
p,
literal,
literal[2:],
common.IntegerLiteralKindBinary,
token.Range,
), nil
},
})
defineExpr(literalExpr{
tokenType: lexer.TokenOctalIntegerLiteral,
nullDenotation: func(p *parser, token lexer.Token) (ast.Expression, error) {
literal := p.tokenSource(token)
return parseIntegerLiteral(
p,
literal,
literal[2:],
common.IntegerLiteralKindOctal,
token.Range,
), nil
},
})
defineExpr(literalExpr{
tokenType: lexer.TokenDecimalIntegerLiteral,
nullDenotation: func(p *parser, token lexer.Token) (ast.Expression, error) {
literal := p.tokenSource(token)
return parseIntegerLiteral(
p,
literal,
literal,
common.IntegerLiteralKindDecimal,
token.Range,
), nil
},
})
defineExpr(literalExpr{
tokenType: lexer.TokenHexadecimalIntegerLiteral,
nullDenotation: func(p *parser, token lexer.Token) (ast.Expression, error) {
literal := p.tokenSource(token)
return parseIntegerLiteral(
p,
literal,
literal[2:],
common.IntegerLiteralKindHexadecimal,
token.Range,
), nil
},
})
defineExpr(literalExpr{
tokenType: lexer.TokenUnknownBaseIntegerLiteral,
nullDenotation: func(p *parser, token lexer.Token) (ast.Expression, error) {
literal := p.tokenSource(token)
return parseIntegerLiteral(
p,
literal,
literal[2:],
common.IntegerLiteralKindUnknown,
token.Range,
), nil
},
})
defineExpr(literalExpr{
tokenType: lexer.TokenFixedPointNumberLiteral,
nullDenotation: func(p *parser, token lexer.Token) (ast.Expression, error) {
literal := p.tokenSource(token)
return parseFixedPointLiteral(
p,
literal,
token.Range,
), nil
},
})
defineExpr(literalExpr{
tokenType: lexer.TokenString,
nullDenotation: func(p *parser, token lexer.Token) (ast.Expression, error) {
literal := p.tokenSource(token)
parsedString := parseStringLiteral(p, literal)
return ast.NewStringExpression(
p.memoryGauge,
parsedString,
token.Range,
), nil
},
})
defineExpr(prefixExpr{
tokenType: lexer.TokenMinus,
bindingPower: exprLeftBindingPowerUnaryPrefix,
nullDenotation: func(p *parser, right ast.Expression, tokenRange ast.Range) (ast.Expression, error) {
switch right := right.(type) {
case *ast.IntegerExpression:
if right.Value.Sign() > 0 {
if right.Value != nil {
right.Value.Neg(right.Value)
}
right.StartPos = tokenRange.StartPos
return right, nil
}
case *ast.FixedPointExpression:
if !right.Negative {
right.Negative = !right.Negative
right.StartPos = tokenRange.StartPos
return right, nil
}
}
return ast.NewUnaryExpression(
p.memoryGauge,
ast.OperationMinus,
right,
tokenRange.StartPos,
), nil
},
})
defineExpr(unaryExpr{
tokenType: lexer.TokenExclamationMark,
bindingPower: exprLeftBindingPowerUnaryPrefix,
operation: ast.OperationNegate,
})
defineExpr(unaryExpr{
tokenType: lexer.TokenLeftArrow,
bindingPower: exprLeftBindingPowerUnaryPrefix,
operation: ast.OperationMove,
})
defineExpr(postfixExpr{
tokenType: lexer.TokenExclamationMark,
bindingPower: exprLeftBindingPowerUnaryPostfix,
leftDenotation: func(p *parser, left ast.Expression, tokenRange ast.Range) (ast.Expression, error) {
return ast.NewForceExpression(
p.memoryGauge,
left,
tokenRange.EndPos,
), nil
},
})
defineNestedExpression()
defineInvocationExpression()
defineArrayExpression()
defineDictionaryExpression()
defineIndexExpression()
definePathExpression()
defineConditionalExpression()
defineReferenceExpression()
defineMemberExpression()
defineIdentifierExpression()
setExprNullDenotation(lexer.TokenEOF, func(parser *parser, token lexer.Token) (ast.Expression, error) {
return nil, NewSyntaxError(token.StartPos, "unexpected end of program")
})
}
func defineLessThanOrTypeArgumentsExpression() {
// The less token `<` does not have a single left binding power,
// but one depending on the tokens following it:
//
// Either an invocation with type arguments (zero or more, comma separated),
// followed by a closing greater token `>` and argument list;
// or a normal expression.
//
// lessThenOrTypeArguments : '<'
// ( ( ( typeAnnotation ( ',' )* )? '>' argumentList )
// | expression
// )
//
//
// Parse this ambiguity by first trying to parse type arguments
// and a closing greater token `>` and start of an argument list,
// i.e. the open paren token `(`.
//
// If that parse fails, the result expression must be a binary expression,
// and a normal expression must follow.
//
// In both cases, the right binding power must be checked,
// just like it is before a normal left denotation is applied.
const binaryExpressionLeftBindingPower = exprLeftBindingPowerComparison
const invocationExpressionLeftBindingPower = exprLeftBindingPowerAccess
setExprMetaLeftDenotation(
lexer.TokenLess,
func(p *parser, rightBindingPower int, left ast.Expression) (result ast.Expression, err error, done bool) {
var typeArguments []*ast.TypeAnnotation
// Start buffering before skipping the `<` token,
// so it can be replayed in case the right binding power
// was higher than the determined left binding power.
p.startBuffering()
p.startAmbiguity()
defer p.endAmbiguity()
// Skip the `<` token.
p.nextSemanticToken()
// First, try to parse zero or more comma-separated type
// arguments (type annotations), a closing greater token `>`,
// and the start of an argument list, i.e. the open paren token `(`.
//
// This parse may fail, in which case we just ignore the error,
// except for fatal errors.
var argumentsStartPos ast.Position
err = func() error {
defer func() {
err := recover()
// MemoryError should abort parsing
_, ok := err.(errors.MemoryError)
if ok {
panic(err)
}
}()
typeArguments, err = parseCommaSeparatedTypeAnnotations(p, lexer.TokenGreater)
if err != nil {
return err
}
_, err = p.mustOne(lexer.TokenGreater)
if err != nil {
return err
}
p.skipSpaceAndComments()
parenOpenToken, err := p.mustOne(lexer.TokenParenOpen)
if err != nil {
return err
}
argumentsStartPos = parenOpenToken.EndPos
return nil
}()
// `err` is nil means the expression is an invocation
if err == nil {
// The expression was determined to be an invocation.
// Still, it should have maybe not been parsed if the right binding power
// was higher. In that case, replay the buffered tokens and stop.
if rightBindingPower >= invocationExpressionLeftBindingPower {
err = p.replayBuffered()
if err != nil {
return nil, err, true
}
return left, nil, true
}
// The previous attempt to parse an invocation succeeded,
// accept the buffered tokens.
p.acceptBuffered()
arguments, endPos, err := parseArgumentListRemainder(p)
if err != nil {
return nil, err, true
}
invocationExpression := ast.NewInvocationExpression(
p.memoryGauge,
left,
typeArguments,
arguments,
argumentsStartPos,
endPos,
)
return invocationExpression, nil, false
} else {
// The previous attempt to parse an invocation failed,
// replay the buffered tokens.
err = p.replayBuffered()
if err != nil {
return nil, err, true
}
// The expression was determined to *not* be an invocation,
// so it must be a binary expression.
//
// Like for a normal left denotation,
// check if this left denotation applies.
if rightBindingPower >= binaryExpressionLeftBindingPower {
return left, nil, true
}
// Skip the `<` token.
// The token buffering started before this token,
// because it should have maybe not been parsed in the first place
// if the right binding power is higher.
p.nextSemanticToken()
right, err := parseExpression(p, binaryExpressionLeftBindingPower)
if err != nil {
return nil, err, true
}
binaryExpression := ast.NewBinaryExpression(
p.memoryGauge,
ast.OperationLess,
left,
right,
)
return binaryExpression, nil, false
}
})
}
// defineGreaterThanOrBitwiseRightShiftExpression parses
// the greater-than expression (operator `>`, e.g. `1 > 2`)
// and the bitwise right shift expression (operator `>>`, e.g. `1 >> 3`).
//
// The `>>` operator consists of two `>` tokens, instead of one dedicated `>>` token,
// because that would introduce a parsing problem for function calls/invocations
// which have a type argument, where the type argument is a type instantiation,
// for example, `f<T<U>>()`.
func defineGreaterThanOrBitwiseRightShiftExpression() {
setExprMetaLeftDenotation(
lexer.TokenGreater,
func(p *parser, rightBindingPower int, left ast.Expression) (result ast.Expression, err error, done bool) {
// If the right binding power is higher than any of the potential cases,
// then return early
if rightBindingPower >= exprLeftBindingPowerBitwiseShift &&
rightBindingPower >= exprLeftBindingPowerComparison {
return left, nil, true
}
// Perform a lookahead for '>'
current := p.current
cursor := p.tokens.Cursor()
// Skip the `>` token.
p.next()
// If another '>' token appears immediately,
// then the operator is actually a bitwise right shift operator
isBitwiseShift := p.current.Is(lexer.TokenGreater)
var operation ast.Operation
var nextRightBindingPower int
if isBitwiseShift {
operation = ast.OperationBitwiseRightShift
// The expression was determined to be a bitwise shift.
// Still, it should have maybe not been parsed if the right binding power
// was higher. In that case, replay the buffered tokens and stop.
if rightBindingPower >= exprLeftBindingPowerBitwiseShift {
p.current = current
p.tokens.Revert(cursor)
return left, nil, true
}
// The previous attempt to parse a bitwise right shift succeeded,
// accept the buffered tokens.
nextRightBindingPower = exprLeftBindingPowerBitwiseShift
} else {
operation = ast.OperationGreater
// The previous attempt to parse a bitwise right shift failed,
// replay the buffered tokens.
p.current = current
p.tokens.Revert(cursor)
// The expression was determined to *not* be a bitwise shift,
// so it must be a comparison expression.
//
// Like for a normal left denotation,
// check if this left denotation applies.
if rightBindingPower >= exprLeftBindingPowerComparison {
return left, nil, true
}
nextRightBindingPower = exprLeftBindingPowerComparison
}
p.nextSemanticToken()
right, err := parseExpression(p, nextRightBindingPower)
if err != nil {
return nil, err, true
}
binaryExpression := ast.NewBinaryExpression(
p.memoryGauge,
operation,
left,
right,
)
return binaryExpression, err, false
})
}
func defineIdentifierExpression() {
defineExpr(literalExpr{
tokenType: lexer.TokenIdentifier,
nullDenotation: func(p *parser, token lexer.Token) (ast.Expression, error) {
switch string(p.tokenSource(token)) {
case keywordTrue:
return ast.NewBoolExpression(p.memoryGauge, true, token.Range), nil
case keywordFalse:
return ast.NewBoolExpression(p.memoryGauge, false, token.Range), nil
case keywordNil:
return ast.NewNilExpression(p.memoryGauge, token.Range.StartPos), nil
case keywordCreate:
return parseCreateExpressionRemainder(p, token)
case keywordDestroy:
expression, err := parseExpression(p, lowestBindingPower)
if err != nil {
return nil, err
}
return ast.NewDestroyExpression(
p.memoryGauge,
expression,
token.Range.StartPos,
), nil
case keywordAttach:
return parseAttachExpressionRemainder(p, token)
case keywordFun:
return parseFunctionExpression(p, token)
default:
return ast.NewIdentifierExpression(
p.memoryGauge,
p.tokenToIdentifier(token),
), nil
}
},
})
}
func parseFunctionExpression(p *parser, token lexer.Token) (*ast.FunctionExpression, error) {
parameterList, returnTypeAnnotation, functionBlock, err :=
parseFunctionParameterListAndRest(p, false)
if err != nil {
return nil, err
}
return ast.NewFunctionExpression(
p.memoryGauge,
ast.FunctionPurityUnspecified,
parameterList,
returnTypeAnnotation,
functionBlock,
token.StartPos,
), nil
}
func defineIdentifierLeftDenotations() {
setExprIdentifierLeftBindingPower(keywordAs, exprLeftBindingPowerCasting)
setExprLeftDenotation(
lexer.TokenIdentifier,
func(parser *parser, t lexer.Token, left ast.Expression) (ast.Expression, error) {
// NOTE: switch statement with just one case instead of if,
// as this function is called for *any identifier left denotation ("postfix keyword"),
// not just for `as`, it might be extended with more cases (keywords) in the future
switch string(parser.tokenSource(t)) {
case keywordAs:
right, err := parseTypeAnnotation(parser)
if err != nil {
return nil, err
}
return ast.NewCastingExpression(
parser.memoryGauge,
left,
ast.OperationCast,
right,
nil,
), nil
default:
panic(errors.NewUnreachableError())
}
},
)
for _, tokenOperation := range []struct {
token lexer.TokenType
operation ast.Operation
}{
{
token: lexer.TokenAsExclamationMark,
operation: ast.OperationForceCast,
},
{
token: lexer.TokenAsQuestionMark,
operation: ast.OperationFailableCast,
},
} {
operation := tokenOperation.operation
tokenType := tokenOperation.token
// Rebind operation, so the closure captures to current iteration's value,
// i.e. the next iteration doesn't override `operation`
leftDenotation := (func(operation ast.Operation) exprLeftDenotationFunc {
return func(parser *parser, t lexer.Token, left ast.Expression) (ast.Expression, error) {
right, err := parseTypeAnnotation(parser)
if err != nil {
return nil, err
}
return ast.NewCastingExpression(
parser.memoryGauge,
left,
operation,
right,
nil,
), nil
}
})(operation)
setExprLeftBindingPower(tokenType, exprLeftBindingPowerCasting)
setExprLeftDenotation(tokenType, leftDenotation)
}
}
func parseCreateExpressionRemainder(p *parser, token lexer.Token) (*ast.CreateExpression, error) {
invocation, err := parseNominalTypeInvocationRemainder(p)
if err != nil {
return nil, err
}
return ast.NewCreateExpression(
p.memoryGauge,
invocation,
token.StartPos,
), nil
}
func parseAttachExpressionRemainder(p *parser, token lexer.Token) (*ast.AttachExpression, error) {
attachment, err := parseNominalTypeInvocationRemainder(p)
if err != nil {
return nil, err
}
p.skipSpaceAndComments()
if !p.isToken(p.current, lexer.TokenIdentifier, keywordTo) {
return nil, p.syntaxError(
"expected 'to', got %s",
p.current.Type,
)
}
// consume the `to` token
p.nextSemanticToken()
base, err := parseExpression(p, lowestBindingPower)
if err != nil {
return nil, err
}
return ast.NewAttachExpression(p.memoryGauge, base, attachment, token.StartPos), nil
}
// Invocation Expression Grammar:
//
// invocation : '(' ( argument ( ',' argument )* )? ')'
func defineInvocationExpression() {
setExprLeftBindingPower(lexer.TokenParenOpen, exprLeftBindingPowerAccess)
setExprLeftDenotation(
lexer.TokenParenOpen,
func(p *parser, token lexer.Token, left ast.Expression) (ast.Expression, error) {
arguments, endPos, err := parseArgumentListRemainder(p)
if err != nil {
return nil, err
}
return ast.NewInvocationExpression(
p.memoryGauge,
left,
nil,
arguments,
token.EndPos,
endPos,
), nil
},
)
}
func parseArgumentListRemainder(p *parser) (arguments []*ast.Argument, endPos ast.Position, err error) {
atEnd := false
expectArgument := true
for !atEnd {
p.skipSpaceAndComments()
switch p.current.Type {
case lexer.TokenComma:
if expectArgument {
return nil, ast.EmptyPosition, p.syntaxError(
"expected argument or end of argument list, got %s",
p.current.Type,
)
}
// Skip the comma