-
Notifications
You must be signed in to change notification settings - Fork 137
/
declaration.go
2001 lines (1686 loc) Β· 46.2 KB
/
declaration.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 Dapper Labs, Inc.
*
* 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 parser
import (
"encoding/hex"
"fmt"
"strconv"
"strings"
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/cadence/runtime/errors"
"github.com/onflow/cadence/runtime/parser/lexer"
)
func parseDeclarations(p *parser, endTokenType lexer.TokenType) (declarations []ast.Declaration, err error) {
for {
_, docString := p.parseTrivia(triviaOptions{
skipNewlines: true,
parseDocStrings: true,
})
switch p.current.Type {
case lexer.TokenSemicolon:
// Skip the semicolon
p.next()
continue
case endTokenType, lexer.TokenEOF:
return
default:
var declaration ast.Declaration
declaration, err = parseDeclaration(p, docString)
if err != nil {
return
}
if declaration == nil {
return
}
declarations = append(declarations, declaration)
}
}
}
func parseDeclaration(p *parser, docString string) (ast.Declaration, error) {
var access ast.Access = ast.AccessNotSpecified
var accessPos *ast.Position
purity := ast.FunctionPurityUnspecified
var purityPos *ast.Position
var staticPos *ast.Position
var nativePos *ast.Position
staticModifierEnabled := p.config.StaticModifierEnabled
nativeModifierEnabled := p.config.NativeModifierEnabled
for {
p.skipSpaceAndComments()
switch p.current.Type {
case lexer.TokenPragma:
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for pragma")
}
err := rejectAllModifiers(p, access, accessPos, staticPos, nativePos, common.DeclarationKindPragma)
if err != nil {
return nil, err
}
return parsePragmaDeclaration(p)
case lexer.TokenIdentifier:
switch string(p.currentTokenSource()) {
case KeywordLet, KeywordVar:
err := rejectStaticAndNativeModifiers(p, staticPos, nativePos, common.DeclarationKindVariable)
if err != nil {
return nil, err
}
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for variable")
}
return parseVariableDeclaration(p, access, accessPos, docString)
case KeywordFun:
return parseFunctionDeclaration(
p,
false,
access,
accessPos,
purity,
purityPos,
staticPos,
nativePos,
docString,
)
case KeywordImport:
err := rejectStaticAndNativeModifiers(p, staticPos, nativePos, common.DeclarationKindImport)
if err != nil {
return nil, err
}
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for import")
}
return parseImportDeclaration(p)
case KeywordEvent:
err := rejectStaticAndNativeModifiers(p, staticPos, nativePos, common.DeclarationKindEvent)
if err != nil {
return nil, err
}
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for event")
}
return parseEventDeclaration(p, access, accessPos, docString)
case KeywordStruct:
err := rejectStaticAndNativeModifiers(p, staticPos, nativePos, common.DeclarationKindStructure)
if err != nil {
return nil, err
}
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for struct")
}
return parseCompositeOrInterfaceDeclaration(p, access, accessPos, docString)
case KeywordResource:
err := rejectStaticAndNativeModifiers(p, staticPos, nativePos, common.DeclarationKindResource)
if err != nil {
return nil, err
}
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for resource")
}
return parseCompositeOrInterfaceDeclaration(p, access, accessPos, docString)
case KeywordEntitlement:
err := rejectStaticAndNativeModifiers(p, staticPos, nativePos, common.DeclarationKindEntitlement)
if err != nil {
return nil, err
}
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for entitlement")
}
return parseEntitlementOrMappingDeclaration(p, access, accessPos, docString)
case KeywordAttachment:
err := rejectStaticAndNativeModifiers(p, staticPos, nativePos, common.DeclarationKindAttachment)
if err != nil {
return nil, err
}
return parseAttachmentDeclaration(p, access, accessPos, docString)
case KeywordContract:
err := rejectStaticAndNativeModifiers(p, staticPos, nativePos, common.DeclarationKindContract)
if err != nil {
return nil, err
}
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for contract")
}
return parseCompositeOrInterfaceDeclaration(p, access, accessPos, docString)
case KeywordEnum:
err := rejectStaticAndNativeModifiers(p, staticPos, nativePos, common.DeclarationKindEnum)
if err != nil {
return nil, err
}
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for enum")
}
return parseCompositeOrInterfaceDeclaration(p, access, accessPos, docString)
case KeywordTransaction:
err := rejectAllModifiers(p, access, accessPos, staticPos, nativePos, common.DeclarationKindTransaction)
if err != nil {
return nil, err
}
if purity != ast.FunctionPurityUnspecified {
return nil, NewSyntaxError(*purityPos, "invalid view modifier for transaction")
}
return parseTransactionDeclaration(p, docString)
case KeywordView:
if purity != ast.FunctionPurityUnspecified {
p.report(p.syntaxError("invalid second view modifier"))
}
pos := p.current.StartPos
purityPos = &pos
purity = parsePurityAnnotation(p)
continue
case KeywordPub:
err := handlePub(p)
if err != nil {
return nil, err
}
continue
case KeywordPriv:
handlePriv(p)
continue
case KeywordAccess:
if access != ast.AccessNotSpecified {
return nil, p.syntaxError("invalid second access modifier")
}
if staticModifierEnabled && staticPos != nil {
return nil, p.syntaxError("invalid access modifier after static modifier")
}
if nativeModifierEnabled && nativePos != nil {
return nil, p.syntaxError("invalid access modifier after native modifier")
}
pos := p.current.StartPos
accessPos = &pos
var err error
access, err = parseAccess(p)
if err != nil {
return nil, err
}
continue
case KeywordStatic:
if !staticModifierEnabled {
break
}
if staticPos != nil {
return nil, p.syntaxError("invalid second static modifier")
}
if nativeModifierEnabled && nativePos != nil {
return nil, p.syntaxError("invalid static modifier after native modifier")
}
pos := p.current.StartPos
staticPos = &pos
p.next()
continue
case KeywordNative:
if !nativeModifierEnabled {
break
}
if nativePos != nil {
return nil, p.syntaxError("invalid second native modifier")
}
pos := p.current.StartPos
nativePos = &pos
p.next()
continue
}
}
return nil, nil
}
}
func handlePriv(p *parser) {
p.report(p.syntaxErrorWithSuggestedFix(
"`priv` is no longer a valid access keyword",
"`access(self)`",
))
p.next()
}
func handlePub(p *parser) error {
pubToken := p.current
p.nextSemanticToken()
// Try to parse `(set)` if given
if !p.current.Is(lexer.TokenParenOpen) {
p.report(NewSyntaxErrorWithSuggestedReplacement(
pubToken.Range,
"`pub` is no longer a valid access keyword",
"`access(all)`",
))
return nil
}
// Skip the opening paren
p.nextSemanticToken()
const keywordSet = "set"
if !p.current.Is(lexer.TokenIdentifier) {
return p.syntaxError(
"expected keyword %q, got %s",
keywordSet,
p.current.Type,
)
}
keyword := p.currentTokenSource()
if string(keyword) != keywordSet {
return p.syntaxError(
"expected keyword %q, got %q",
keywordSet,
keyword,
)
}
// Skip the `set` keyword
p.nextSemanticToken()
_, err := p.mustOne(lexer.TokenParenClose)
if err != nil {
return err
}
p.report(NewSyntaxError(
pubToken.StartPos,
"`pub(set)` is no longer a valid access keyword",
))
return nil
}
var enumeratedAccessModifierKeywords = common.EnumerateWords(
[]string{
strconv.Quote(KeywordAll),
strconv.Quote(KeywordAccount),
strconv.Quote(KeywordContract),
strconv.Quote(KeywordSelf),
},
"or",
)
func rejectAccessKeywords(p *parser, produceNominalType func() (*ast.NominalType, error)) (*ast.NominalType, error) {
nominalType, err := produceNominalType()
if err != nil {
return nil, err
}
switch nominalType.Identifier.Identifier {
case KeywordAll, KeywordAccess, KeywordAccount, KeywordSelf:
return nil, p.syntaxError("unexpected non-nominal type: %s", nominalType)
}
return nominalType, nil
}
func parseEntitlementList(p *parser) (ast.EntitlementSet, error) {
firstTy, err := rejectAccessKeywords(p, func() (*ast.NominalType, error) {
return parseNominalType(p, lowestBindingPower)
})
if err != nil {
return nil, err
}
p.skipSpaceAndComments()
entitlements := []*ast.NominalType{firstTy}
var separator lexer.TokenType
switch p.current.Type {
case lexer.TokenComma, lexer.TokenVerticalBar:
separator = p.current.Type
p.nextSemanticToken()
case lexer.TokenParenClose:
// it is impossible to disambiguate at parsing time between an access that is a single
// conjunctive entitlement, a single disjunctive entitlement, and the name of an entitlement mapping.
// Luckily, however, the former two are just equivalent, and the latter we can disambiguate in the type checker.
return ast.NewConjunctiveEntitlementSet(entitlements), nil
default:
return nil, p.syntaxError(
"unexpected entitlement separator %s",
p.current.Type.String(),
)
}
remainingEntitlements, _, err := parseNominalTypes(p, lexer.TokenParenClose, separator)
if err != nil {
return nil, err
}
for _, entitlement := range remainingEntitlements {
switch entitlement.Identifier.Identifier {
case KeywordAll, KeywordAccess, KeywordAccount, KeywordSelf:
return nil, p.syntaxError("unexpected non-nominal type: %s", entitlement)
}
entitlements = append(entitlements, entitlement)
}
var entitlementSet ast.EntitlementSet
if separator == lexer.TokenComma {
entitlementSet = ast.NewConjunctiveEntitlementSet(entitlements)
} else {
entitlementSet = ast.NewDisjunctiveEntitlementSet(entitlements)
}
return entitlementSet, nil
}
// parseAccess parses an access modifier
//
// access
// : 'access(self)'
// | 'access(all)' ( '(' 'set' ')' )?
// | 'access' '(' ( 'self' | 'contract' | 'account' | 'all' | entitlementList ) ')'
func parseAccess(p *parser) (ast.Access, error) {
switch string(p.currentTokenSource()) {
case KeywordAccess:
// Skip the `access` keyword
p.nextSemanticToken()
_, err := p.mustOne(lexer.TokenParenOpen)
if err != nil {
return ast.AccessNotSpecified, err
}
p.skipSpaceAndComments()
if !p.current.Is(lexer.TokenIdentifier) {
return ast.AccessNotSpecified, p.syntaxError(
"expected keyword %s, got %s",
enumeratedAccessModifierKeywords,
p.current.Type,
)
}
var access ast.Access
keyword := p.currentTokenSource()
switch string(keyword) {
case KeywordAll:
access = ast.AccessAll
// Skip the keyword
p.nextSemanticToken()
case KeywordAccount:
access = ast.AccessAccount
// Skip the keyword
p.nextSemanticToken()
case KeywordContract:
access = ast.AccessContract
// Skip the keyword
p.nextSemanticToken()
case KeywordSelf:
access = ast.AccessSelf
// Skip the keyword
p.nextSemanticToken()
case KeywordMapping:
keywordPos := p.current.StartPos
// Skip the keyword
p.nextSemanticToken()
entitlementMapName, err := parseNominalType(p, lowestBindingPower)
if err != nil {
return ast.AccessNotSpecified, err
}
access = ast.NewMappedAccess(entitlementMapName, keywordPos)
p.skipSpaceAndComments()
default:
entitlements, err := parseEntitlementList(p)
if err != nil {
return ast.AccessNotSpecified, err
}
access = ast.NewEntitlementAccess(entitlements)
}
_, err = p.mustOne(lexer.TokenParenClose)
if err != nil {
return ast.AccessNotSpecified, err
}
return access, nil
default:
return ast.AccessNotSpecified, errors.NewUnreachableError()
}
}
// parseVariableDeclaration parses a variable declaration.
//
// variableKind : 'var' | 'let'
//
// variableDeclaration :
// variableKind identifier ( ':' typeAnnotation )?
// transfer expression
// ( transfer expression )?
func parseVariableDeclaration(
p *parser,
access ast.Access,
accessPos *ast.Position,
docString string,
) (*ast.VariableDeclaration, error) {
startPos := p.current.StartPos
if accessPos != nil {
startPos = *accessPos
}
isLet := string(p.currentTokenSource()) == KeywordLet
// Skip the `let` or `var` keyword
p.nextSemanticToken()
identifier, err := p.nonReservedIdentifier("after start of variable declaration")
if err != nil {
return nil, err
}
// Skip the identifier
p.nextSemanticToken()
var typeAnnotation *ast.TypeAnnotation
if p.current.Is(lexer.TokenColon) {
// Skip the colon
p.nextSemanticToken()
typeAnnotation, err = parseTypeAnnotation(p)
if err != nil {
return nil, err
}
}
p.skipSpaceAndComments()
transfer := parseTransfer(p)
if transfer == nil {
return nil, p.syntaxError("expected transfer")
}
value, err := parseExpression(p, lowestBindingPower)
if err != nil {
return nil, err
}
p.skipSpaceAndComments()
secondTransfer := parseTransfer(p)
var secondValue ast.Expression
if secondTransfer != nil {
secondValue, err = parseExpression(p, lowestBindingPower)
if err != nil {
return nil, err
}
}
variableDeclaration := ast.NewVariableDeclaration(
p.memoryGauge,
access,
isLet,
identifier,
typeAnnotation,
value,
transfer,
startPos,
secondTransfer,
secondValue,
docString,
)
castingExpression, leftIsCasting := value.(*ast.CastingExpression)
if leftIsCasting {
castingExpression.ParentVariableDeclaration = variableDeclaration
}
return variableDeclaration, nil
}
// parseTransfer parses a transfer.
//
// transfer : '=' | '<-' | '<-!'
func parseTransfer(p *parser) *ast.Transfer {
var operation ast.TransferOperation
switch p.current.Type {
case lexer.TokenEqual:
operation = ast.TransferOperationCopy
case lexer.TokenLeftArrow:
operation = ast.TransferOperationMove
case lexer.TokenLeftArrowExclamation:
operation = ast.TransferOperationMoveForced
}
if operation == ast.TransferOperationUnknown {
return nil
}
pos := p.current.StartPos
p.next()
return ast.NewTransfer(
p.memoryGauge,
operation,
pos,
)
}
func parsePragmaDeclaration(p *parser) (*ast.PragmaDeclaration, error) {
startPos := p.current.StartPosition()
p.next()
expr, err := parseExpression(p, lowestBindingPower)
if err != nil {
return nil, err
}
return ast.NewPragmaDeclaration(
p.memoryGauge,
expr,
ast.NewRange(
p.memoryGauge,
startPos,
expr.EndPosition(p.memoryGauge),
),
), nil
}
// parseImportDeclaration parses an import declaration
//
// importDeclaration :
// 'import'
// ( identifier (',' identifier)* 'from' )?
// ( string | hexadecimalLiteral | identifier )
func parseImportDeclaration(p *parser) (*ast.ImportDeclaration, error) {
startPosition := p.current.StartPos
var identifiers []ast.Identifier
var location common.Location
var locationPos ast.Position
var endPos ast.Position
parseStringOrAddressLocation := func() {
locationPos = p.current.StartPos
endPos = p.current.EndPos
switch p.current.Type {
case lexer.TokenString:
literal := p.currentTokenSource()
parsedString := parseStringLiteral(p, literal)
location = common.NewStringLocation(p.memoryGauge, parsedString)
case lexer.TokenHexadecimalIntegerLiteral:
location = parseHexadecimalLocation(p)
default:
panic(errors.NewUnreachableError())
}
// Skip the location
p.next()
}
setIdentifierLocation := func(identifier ast.Identifier) {
location = common.IdentifierLocation(identifier.Identifier)
locationPos = identifier.Pos
endPos = identifier.EndPosition(p.memoryGauge)
}
parseLocation := func() error {
switch p.current.Type {
case lexer.TokenString, lexer.TokenHexadecimalIntegerLiteral:
parseStringOrAddressLocation()
case lexer.TokenIdentifier:
identifier := p.tokenToIdentifier(p.current)
setIdentifierLocation(identifier)
p.next()
default:
return p.syntaxError(
"unexpected token in import declaration: got %s, expected string, address, or identifier",
p.current.Type,
)
}
return nil
}
parseMoreIdentifiers := func() error {
expectCommaOrFrom := false
atEnd := false
for !atEnd {
p.nextSemanticToken()
switch p.current.Type {
case lexer.TokenComma:
if !expectCommaOrFrom {
return p.syntaxError(
"expected %s or keyword %q, got %s",
lexer.TokenIdentifier,
KeywordFrom,
p.current.Type,
)
}
expectCommaOrFrom = false
case lexer.TokenIdentifier:
keyword := p.currentTokenSource()
if string(keyword) == KeywordFrom {
if expectCommaOrFrom {
atEnd = true
// Skip the `from` keyword
p.nextSemanticToken()
err := parseLocation()
if err != nil {
return err
}
break
}
if !isNextTokenCommaOrFrom(p) {
return p.syntaxError(
"expected %s, got keyword %q",
lexer.TokenIdentifier,
keyword,
)
}
// If the next token is either comma or 'from' token, then fall through
// and process the current 'from' token as an identifier.
}
identifier := p.tokenToIdentifier(p.current)
identifiers = append(identifiers, identifier)
expectCommaOrFrom = true
case lexer.TokenEOF:
return p.syntaxError(
"unexpected end in import declaration: expected %s or %s",
lexer.TokenIdentifier,
lexer.TokenComma,
)
default:
return p.syntaxError(
"unexpected token in import declaration: got %s, expected keyword %q or %s",
p.current.Type,
KeywordFrom,
lexer.TokenComma,
)
}
}
return nil
}
maybeParseFromIdentifier := func(identifier ast.Identifier) error {
// The current identifier is maybe the `from` keyword,
// in which case the given (previous) identifier was
// an imported identifier and not the import location.
//
// If it is not the `from` keyword,
// the given (previous) identifier is the import location.
if string(p.currentTokenSource()) == KeywordFrom {
identifiers = append(identifiers, identifier)
// Skip the `from` keyword
p.nextSemanticToken()
err := parseLocation()
if err != nil {
return err
}
} else {
setIdentifierLocation(identifier)
}
return nil
}
// Skip the `import` keyword
p.nextSemanticToken()
switch p.current.Type {
case lexer.TokenString, lexer.TokenHexadecimalIntegerLiteral:
parseStringOrAddressLocation()
case lexer.TokenIdentifier:
identifier := p.tokenToIdentifier(p.current)
// Skip the identifier
p.nextSemanticToken()
switch p.current.Type {
case lexer.TokenComma:
// The previous identifier is an imported identifier,
// not the import location
identifiers = append(identifiers, identifier)
err := parseMoreIdentifiers()
if err != nil {
return nil, err
}
case lexer.TokenIdentifier:
err := maybeParseFromIdentifier(identifier)
if err != nil {
return nil, err
}
case lexer.TokenEOF:
// The previous identifier is the identifier location
setIdentifierLocation(identifier)
default:
return nil, p.syntaxError(
"unexpected token in import declaration: got %s, expected keyword %q or %s",
p.current.Type,
KeywordFrom,
lexer.TokenComma,
)
}
case lexer.TokenEOF:
return nil, p.syntaxError("unexpected end in import declaration: expected string, address, or identifier")
default:
return nil, p.syntaxError(
"unexpected token in import declaration: got %s, expected string, address, or identifier",
p.current.Type,
)
}
return ast.NewImportDeclaration(
p.memoryGauge,
identifiers,
location,
ast.NewRange(
p.memoryGauge,
startPosition,
endPos,
),
locationPos,
), nil
}
// isNextTokenCommaOrFrom check whether the token to follow is a comma or a from token.
func isNextTokenCommaOrFrom(p *parser) bool {
current := p.current
cursor := p.tokens.Cursor()
defer func() {
p.current = current
p.tokens.Revert(cursor)
}()
// skip the current token
p.nextSemanticToken()
// Lookahead the next token
switch p.current.Type {
case lexer.TokenIdentifier:
return string(p.currentTokenSource()) == KeywordFrom
case lexer.TokenComma:
return true
}
return false
}
func parseHexadecimalLocation(p *parser) common.AddressLocation {
// TODO: improve
literal := string(p.currentTokenSource())
bytes := []byte(strings.ReplaceAll(literal[2:], "_", ""))
length := len(bytes)
if length%2 == 1 {
bytes = append([]byte{'0'}, bytes...)
length++
}
rawAddress := make([]byte, hex.DecodedLen(length))
_, err := hex.Decode(rawAddress, bytes)
if err != nil {
// unreachable, hex literal should always be valid
panic(errors.NewUnexpectedErrorFromCause(err))
}
address, err := common.BytesToAddress(rawAddress)
if err != nil {
// Any returned error is a syntax error. e.g: Address too large error.
p.reportSyntaxError(err.Error())
}
return common.NewAddressLocation(p.memoryGauge, address, "")
}
// parseEventDeclaration parses an event declaration.
//
// eventDeclaration : 'event' identifier parameterList
func parseEventDeclaration(
p *parser,
access ast.Access,
accessPos *ast.Position,
docString string,
) (*ast.CompositeDeclaration, error) {
startPos := p.current.StartPos
if accessPos != nil {
startPos = *accessPos
}
// Skip the `event` keyword
p.nextSemanticToken()
identifier, err := p.nonReservedIdentifier("after start of event declaration")
if err != nil {
return nil, err
}
// Skip the identifier
p.next()
// if this is a `ResourceDestroyed` event (i.e., a default event declaration), parse default arguments
parseDefaultArguments := ast.IsResourceDestructionDefaultEvent(identifier.Identifier)
parameterList, err := parseParameterList(p, parseDefaultArguments)
if err != nil {
return nil, err
}
initializer := ast.NewSpecialFunctionDeclaration(
p.memoryGauge,
common.DeclarationKindInitializer,
ast.NewFunctionDeclaration(
p.memoryGauge,
ast.AccessNotSpecified,
ast.FunctionPurityUnspecified,
false,
false,
ast.NewEmptyIdentifier(p.memoryGauge, ast.EmptyPosition),
nil,
parameterList,
nil,
nil,
parameterList.StartPos,
"",
),
)
members := ast.NewMembers(
p.memoryGauge,
[]ast.Declaration{
initializer,
},
)
return ast.NewCompositeDeclaration(
p.memoryGauge,
access,
common.CompositeKindEvent,
identifier,
nil,
members,
docString,
ast.NewRange(
p.memoryGauge,
startPos,
parameterList.EndPos,
),
), nil
}
// parseCompositeKind parses a composite kind.
//
// compositeKind : 'struct' | 'resource' | 'contract' | 'enum'
func parseCompositeKind(p *parser) common.CompositeKind {
if p.current.Is(lexer.TokenIdentifier) {
switch string(p.currentTokenSource()) {
case KeywordStruct: