-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathInternal.y
1957 lines (1705 loc) · 95.3 KB
/
Internal.y
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
{
{-|
Module : Language.Rust.Parser.Internal
Description : Rust parser
Copyright : (c) Alec Theriault, 2017-2018
License : BSD-style
Maintainer : alec.theriault@gmail.com
Stability : experimental
Portability : GHC
The parsers in this file are all re-exported to 'Language.Rust.Parser' via the 'Parse' class. The
parsers are based off of:
* primarily the reference @rustc@ [implementation][0]
* some documentation on [rust-lang][2]
* drawing a couple ideas from a slightly outdated [ANTLR grammar][1]
To get information about transition states and such, run
> happy --info=happyinfo.txt -o /dev/null src/Language/Rust/Parser/Internal.y
[0]: https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/parser.rs
[1]: https://github.com/rust-lang/rust/blob/master/src/grammar/parser-lalr.y
[2]: https://doc.rust-lang.org/grammar.html
-}
{-# OPTIONS_HADDOCK hide, not-home #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}
module Language.Rust.Parser.Internal (
-- * Parsers
parseAttr,
parseBlock,
parseExpr,
parseGenerics,
parseImplItem,
parseItem,
parseLifetimeDef,
parseLit,
parsePat,
parseSourceFile,
parseStmt,
parseTokenStream,
parseTraitItem,
parseTt,
parseTy,
parseTyParam,
parseWhereClause,
) where
import Language.Rust.Syntax
import Language.Rust.Data.Ident ( Ident(..), mkIdent )
import Language.Rust.Data.Position
import Language.Rust.Parser.Lexer ( lexNonSpace, lexShebangLine )
import Language.Rust.Parser.ParseMonad ( pushToken, getPosition, P, parseError )
import Language.Rust.Parser.Literals ( translateLit )
import Language.Rust.Parser.Reversed
import Data.Foldable ( toList )
import Data.List ( (\\), isSubsequenceOf, sort )
import Data.Semigroup ( (<>) )
import Text.Read ( readMaybe )
import Data.List.NonEmpty ( NonEmpty(..), (<|) )
import qualified Data.List.NonEmpty as N
}
-- in order to document the parsers, we have to alias them
%name parseLit lit
%name parseAttr export_attribute
%name parseTy ty
%name parsePat pat
%name parseStmt stmt
%name parseExpr expr
%name parseItem mod_item
%name parseSourceFileContents source_file
%name parseBlock export_block
%name parseImplItem impl_item
%name parseTraitItem trait_item
%name parseTt token_tree
%name parseTokenStream token_stream
%name parseTyParam ty_param
%name parseLifetimeDef lifetime_def
%name parseWhereClause where_clause
%name parseGenerics generics
%tokentype { Spanned Token }
%lexer { lexNonSpace >>= } { Spanned Eof _ }
%monad { P } { >>= } { return }
%errorhandlertype explist
%error { expParseError }
%expect 0
%token
-- Expression-operator symbols.
'=' { Spanned Equal _ }
'<' { Spanned Less _ }
'>' { Spanned Greater _ }
'!' { Spanned Exclamation _ }
'~' { Spanned Tilde _ }
'+' { Spanned Plus _ }
'-' { Spanned Minus _ }
'*' { Spanned Star _ }
'/' { Spanned Slash _ }
'%' { Spanned Percent _ }
'^' { Spanned Caret _ }
'&' { Spanned Ampersand _ }
'|' { Spanned Pipe _ }
-- Structural symbols.
'@' { Spanned At _ }
'...' { Spanned DotDotDot _ }
'..=' { Spanned DotDotEqual _ }
'..' { Spanned DotDot _ }
'.' { Spanned Dot _ }
',' { Spanned Comma _ }
';' { Spanned Semicolon _ }
'::' { Spanned ModSep _ }
':' { Spanned Colon _ }
'->' { Spanned RArrow _ }
'<-' { Spanned LArrow _ }
'=>' { Spanned FatArrow _ }
'#' { Spanned Pound _ }
'$' { Spanned Dollar _ }
'?' { Spanned Question _ }
'#!' { Spanned Shebang _ }
'||' { Spanned PipePipe _ }
'&&' { Spanned AmpersandAmpersand _ }
'>=' { Spanned GreaterEqual _ }
'>>=' { Spanned GreaterGreaterEqual _ }
'<<' { Spanned LessLess _ }
'>>' { Spanned GreaterGreater _ }
'==' { Spanned EqualEqual _ }
'!=' { Spanned NotEqual _ }
'<=' { Spanned LessEqual _ }
'<<=' { Spanned LessLessEqual _ }
'-=' { Spanned MinusEqual _ }
'&=' { Spanned AmpersandEqual _ }
'|=' { Spanned PipeEqual _ }
'+=' { Spanned PlusEqual _ }
'*=' { Spanned StarEqual _ }
'/=' { Spanned SlashEqual _ }
'^=' { Spanned CaretEqual _ }
'%=' { Spanned PercentEqual _ }
'(' { Spanned (OpenDelim Paren) _ }
'[' { Spanned (OpenDelim Bracket) _ }
'{' { Spanned (OpenDelim Brace) _ }
')' { Spanned (CloseDelim Paren) _ }
']' { Spanned (CloseDelim Bracket) _ }
'}' { Spanned (CloseDelim Brace) _ }
-- Literals.
byte { Spanned (LiteralTok ByteTok{} _) _ }
char { Spanned (LiteralTok CharTok{} _) _ }
int { Spanned (LiteralTok IntegerTok{} _) _ }
float { Spanned (LiteralTok FloatTok{} _) _ }
str { Spanned (LiteralTok StrTok{} _) _ }
byteStr { Spanned (LiteralTok ByteStrTok{} _) _ }
rawStr { Spanned (LiteralTok StrRawTok{} _) _ }
rawByteStr { Spanned (LiteralTok ByteStrRawTok{} _) _ }
-- Strict keywords used in the language
as { Spanned (IdentTok "as") _ }
box { Spanned (IdentTok "box") _ }
break { Spanned (IdentTok "break") _ }
const { Spanned (IdentTok "const") _ }
continue { Spanned (IdentTok "continue") _ }
crate { Spanned (IdentTok "crate") _ }
else { Spanned (IdentTok "else") _ }
enum { Spanned (IdentTok "enum") _ }
extern { Spanned (IdentTok "extern") _ }
false { Spanned (IdentTok "false") _ }
fn { Spanned (IdentTok "fn") _ }
for { Spanned (IdentTok "for") _ }
if { Spanned (IdentTok "if") _ }
impl { Spanned (IdentTok "impl") _ }
in { Spanned (IdentTok "in") _ }
let { Spanned (IdentTok "let") _ }
loop { Spanned (IdentTok "loop") _ }
match { Spanned (IdentTok "match") _ }
mod { Spanned (IdentTok "mod") _ }
move { Spanned (IdentTok "move") _ }
mut { Spanned (IdentTok "mut") _ }
pub { Spanned (IdentTok "pub") _ }
ref { Spanned (IdentTok "ref") _ }
return { Spanned (IdentTok "return") _ }
Self { Spanned (IdentTok "Self") _ }
self { Spanned (IdentTok "self") _ }
static { Spanned (IdentTok "static") _ }
struct { Spanned (IdentTok "struct") _ }
super { Spanned (IdentTok "super") _ }
trait { Spanned (IdentTok "trait") _ }
true { Spanned (IdentTok "true") _ }
type { Spanned (IdentTok "type") _ }
unsafe { Spanned (IdentTok "unsafe") _ }
use { Spanned (IdentTok "use") _ }
where { Spanned (IdentTok "where") _ }
while { Spanned (IdentTok "while") _ }
do { Spanned (IdentTok "do") _ }
-- Keywords reserved for future use
abstract { Spanned (IdentTok "abstract") _ }
alignof { Spanned (IdentTok "alignof") _ }
become { Spanned (IdentTok "become") _ }
final { Spanned (IdentTok "final") _ }
macro { Spanned (IdentTok "macro") _ }
offsetof { Spanned (IdentTok "offsetof") _ }
override { Spanned (IdentTok "override") _ }
priv { Spanned (IdentTok "priv") _ }
proc { Spanned (IdentTok "proc") _ }
pure { Spanned (IdentTok "pure") _ }
sizeof { Spanned (IdentTok "sizeof") _ }
typeof { Spanned (IdentTok "typeof") _ }
unsized { Spanned (IdentTok "unsized") _ }
virtual { Spanned (IdentTok "virtual") _ }
-- Weak keywords, have special meaning only in specific contexts.
default { Spanned (IdentTok "default") _ }
union { Spanned (IdentTok "union") _ }
catch { Spanned (IdentTok "catch") _ }
auto { Spanned (IdentTok "auto") _ }
yield { Spanned (IdentTok "yield") _ }
dyn { Spanned (IdentTok "dyn") _ }
-- Comments
outerDoc { Spanned (Doc _ Outer _) _ }
innerDoc { Spanned (Doc _ Inner _) _ }
-- Identifiers.
'_' { Spanned (IdentTok "_") _ }
IDENT { Spanned IdentTok{} _ }
-- Lifetimes.
LIFETIME { Spanned (LifetimeTok _) _ }
-- Interpolated
ntItem { Spanned (Interpolated (NtItem $$)) _ }
ntBlock { Spanned (Interpolated (NtBlock $$)) _ }
ntStmt { Spanned (Interpolated (NtStmt $$)) _ }
ntPat { Spanned (Interpolated (NtPat $$)) _ }
ntExpr { Spanned (Interpolated (NtExpr $$)) _ }
ntTy { Spanned (Interpolated (NtTy $$)) _ }
ntIdent { Spanned (Interpolated (NtIdent _)) _ }
ntPath { Spanned (Interpolated (NtPath $$)) _ }
ntTT { Spanned (Interpolated (NtTT $$)) _ }
ntArm { Spanned (Interpolated (NtArm $$)) _ }
ntImplItem { Spanned (Interpolated (NtImplItem $$)) _ }
ntTraitItem { Spanned (Interpolated (NtTraitItem $$)) _ }
ntGenerics { Spanned (Interpolated (NtGenerics $$)) _ }
ntWhereClause { Spanned (Interpolated (NtWhereClause $$)) _ }
ntArg { Spanned (Interpolated (NtArg $$)) _ }
ntLit { Spanned (Interpolated (NtLit $$)) _ }
-- 'SEG' needs to be lower than '::' for path segments
%nonassoc SEG
-- 'mut' needs to be lower precedence than 'IDENT' so that in 'pat', something like "&mut x"
-- associates the "mut" to a refence pattern and not to the identifier pattern "x".
--
-- 'DEF' is for the empty case of 'def', which needs to _not_ be taken when there is a 'default'
-- token available.
--
-- 'EQ' is for differentiating the 'where ty' from 'where ty = ty' case in where clause
-- predicates, since the former needs to _not_ be taken when there is a '=' token available.
--
-- '::' is so that the remainder of mod paths in attributes are not gobbled as just raw tokens
%nonassoc mut DEF EQ '::'
-- These are all identifiers of sorts ('union' and 'default' are "weak" keywords)
%nonassoc IDENT ntIdent default union catch self Self super auto dyn crate
-- These are all very low precedence unary operators
%nonassoc box return yield break continue for IMPLTRAIT LAMBDA
-- 'static' needs to have higher precedenc than 'LAMBDA' so that statements starting in static get
-- considered as static items, and not a static lambda
%nonassoc static
-- These are the usual arithmetic precedences. 'UNARY' is introduced here for '*', '!', '-', '&'
%right '=' '>>=' '<<=' '-=' '+=' '*=' '/=' '^=' '|=' '&=' '%='
%right '<-'
%nonassoc SINGLERNG
%nonassoc INFIXRNG
%nonassoc POSTFIXRNG
%nonassoc PREFIXRNG
%nonassoc '..' '...' '..='
%left '||'
%left '&&'
%left '==' '!=' '<' '>' '<=' '>='
%left '|'
%left '^'
%left '&'
%left '<<' '>>'
%left '+' '-'
%left '*' '/' '%'
%nonassoc ':' as
%nonassoc UNARY
-- These are all generated precedence tokens.
--
-- * 'FIELD' for field access expressions (which bind less tightly than '.' for method calls)
-- * 'VIS' for adjusting the precedence of 'pub' compared to other visbility modifiers (see 'vis')
-- * 'PATH' boosts the precedences of paths in types and expressions
-- * 'WHERE' is for non-empty where clauses
--
%nonassoc FIELD VIS PATH WHERE NOSEMI
-- These are postfix operators.
%nonassoc '?' '.'
-- Delimiters have the highest precedence. 'ntBlock' counts as a delimiter since it always starts
-- and ends with '{' and '}'
%nonassoc '{' ntBlock '[' '(' '!' ';'
%%
-- Unwraps the IdentTok into just an Ident
-- For questionable reasons of backwards compatibility, 'union', 'default', and 'catch' can be used
-- as identifiers, even if they are also keywords. They are "contextual" keywords.
--
-- Union's RFC: https://github.com/rust-lang/rfcs/blob/master/text/1444-union.md
ident :: { Spanned Ident }
: ntIdent { fmap (\(Interpolated (NtIdent i)) -> i) $1 }
| union { toIdent $1 }
| default { toIdent $1 }
| catch { toIdent $1 }
| auto { toIdent $1 }
| dyn { toIdent $1 }
| IDENT { toIdent $1 }
-- This should precede any '>' token which could be absorbed in a '>>', '>=', or '>>=' token. Its
-- purpose is to check if the lookahead token starts with '>' but contains more that. If that is
-- the case, it pushes two tokens, the first of which is '>'. We exploit the %% feature of threaded
-- lexers to discard what would have been the troublesome '>>', '>=', or '>>=' token.
gt :: { () }
: {- empty -} {%% \(Spanned tok s) ->
let s' = nudge 1 0 s; s'' = nudge 0 (-1) s in
case tok of
GreaterGreater -> pushToken (Spanned Greater s') *> pushToken (Spanned Greater s'')
GreaterEqual -> pushToken (Spanned Equal s') *> pushToken (Spanned Greater s'')
GreaterGreaterEqual -> pushToken (Spanned GreaterEqual s') *> pushToken (Spanned Greater s'')
_ -> pushToken (Spanned tok s)
}
-- This should precede any '|' token which could be absorbed in a '||' token. This works in the same
-- way as 'gt'.
pipe :: { () }
: {- empty -} {%% \(Spanned tok s) ->
let s' = nudge 1 0 s; s'' = nudge 0 (-1) s in
case tok of
PipePipe -> pushToken (Spanned Pipe s') *> pushToken (Spanned Pipe s'')
_ -> pushToken (Spanned tok s)
}
-------------
-- Utility --
-------------
-- | One or more occurences of 'p'
some(p) :: { Reversed NonEmpty p }
: some(p) p { let Reversed xs = $1 in Reversed ($2 <| xs) }
| p { [$1] }
-- | Zero or more occurences of 'p'
many(p) :: { [ p ] }
: some(p) { toList $1 }
| {- empty -} { [] }
-- | One or more occurences of 'p', seperated by 'sep'
sep_by1(p,sep) :: { Reversed NonEmpty p }
: sep_by1(p,sep) sep p { let Reversed xs = $1 in Reversed ($3 <| xs) }
| p { [$1] }
-- | Zero or more occurrences of 'p', separated by 'sep'
sep_by(p,sep) :: { [ p ] }
: sep_by1(p,sep) { toList $1 }
| {- empty -} { [] }
-- | One or more occurrences of 'p', seperated by 'sep', optionally ending in 'sep'
sep_by1T(p,sep) :: { Reversed NonEmpty p }
: sep_by1(p,sep) sep { $1 }
| sep_by1(p,sep) { $1 }
-- | Zero or more occurences of 'p', seperated by 'sep', optionally ending in 'sep' (only if there
-- is at least one 'p')
sep_byT(p,sep) :: { [ p ] }
: sep_by1T(p,sep) { toList $1 }
| {- empty -} { [] }
--------------------------
-- Whole file
--------------------------
-- shebang is dealt with at the top level, outside Happy/Alex
source_file :: { ([Attribute Span],[Item Span]) }
: inner_attrs many(mod_item) { (toList $1, $2) }
| many(mod_item) { ([], $1) }
--------------------------
-- Attributes
--------------------------
outer_attribute :: { Attribute Span }
: '#' '[' mod_path token_stream ']' { Attribute Outer $3 $4 ($1 # $>) }
| outerDoc { let Spanned (Doc str _ l) x = $1 in SugaredDoc Outer l str x }
inner_attribute :: { Attribute Span }
: '#' '!' '[' mod_path token_stream ']' { Attribute Inner $4 $5 ($1 # $>) }
| '#!' '[' mod_path token_stream ']' { Attribute Inner $3 $4 ($1 # $>) }
| innerDoc { let Spanned (Doc str _ l) x = $1 in SugaredDoc Inner l str x }
-- TODO: for some precedence related reason, using 'some' here doesn't work
inner_attrs :: { Reversed NonEmpty (Attribute Span) }
: inner_attrs inner_attribute { let Reversed xs = $1 in Reversed ($2 <| xs) }
| inner_attribute { [$1] }
--------------
-- Literals --
--------------
lit :: { Lit Span }
: ntLit { $1 }
| byte { lit $1 }
| char { lit $1 }
| int { lit $1 }
| float { lit $1 }
| true { lit $1 }
| false { lit $1 }
| string { $1 }
string :: { Lit Span }
: str { lit $1 }
| rawStr { lit $1 }
| byteStr { lit $1 }
| rawByteStr { lit $1 }
-----------
-- Paths --
-----------
-- parse_qualified_path(PathStyle::Type)
-- qual_path :: Spanned (NonEmpty (Ident, PathParameters Span)) -> P (Spanned (QSelf Span, Path Span))
qual_path(segs) :: { Spanned (QSelf Span, Path Span) }
: '<' qual_path_suf(segs) { let Spanned x _ = $2 in Spanned x ($1 # $2) }
| lt_ty_qual_path as ty_path '>' '::' segs {
let Path g segsTy x = $3 in
Spanned (QSelf (unspan $1) (length segsTy), Path g (segsTy <> toList $6) x) ($1 # $>)
}
-- Basically a qualified path, but ignoring the very first '<' token
qual_path_suf(segs) :: { Spanned (QSelf Span, Path Span) }
: ty '>' '::' segs { Spanned (QSelf $1 0, Path False (toList $4) (spanOf $4)) ($1 # $>) }
| ty as ty_path '>' '::' segs {
let Path g segsTy x = $3 in
Spanned (QSelf $1 (length segsTy), Path g (segsTy <> toList $6) x) ($1 # $>)
}
-- Usually qual_path_suf is for... type paths! This consumes these but with a starting '<<' token.
-- The underlying type has the right 'Span' (it doesn't include the very first '<', while the
-- 'Spanned' wrapper does)
lt_ty_qual_path :: { Spanned (Ty Span) }
: '<<' qual_path_suf(path_segments_without_colons)
{ let (qself,path) = unspan $2 in Spanned (PathTy (Just qself) path (nudge 1 0 ($1 # $2))) ($1 # $2) }
-- parse_generic_args() but with the '<' '>'
generic_values :: { Spanned ([Lifetime Span], [Ty Span], [(Ident, Ty Span)]) }
: '<' sep_by1(lifetime,',') ',' sep_by1(ty,',') ',' sep_by1T(binding,',') gt '>'
{ Spanned (toList $2, toList $4, toList $6) ($1 # $>) }
| '<' sep_by1(lifetime,',') ',' sep_by1T(ty,',') gt '>'
{ Spanned (toList $2, toList $4, [] ) ($1 # $>) }
| '<' sep_by1(lifetime,',') ',' sep_by1T(binding,',') gt '>'
{ Spanned (toList $2, [], toList $4) ($1 # $>) }
| '<' sep_by1T(lifetime,',') gt '>'
{ Spanned (toList $2, [], [] ) ($1 # $>) }
| '<' sep_by1(ty,',') ',' sep_by1T(binding,',') gt '>'
{ Spanned ([], toList $2, toList $4) ($1 # $>) }
| '<' sep_by1T(ty,',') gt '>'
{ Spanned ([], toList $2, [] ) ($1 # $>) }
| '<' sep_by1T(binding,',') gt '>'
{ Spanned ([], [], toList $2) ($1 # $>) }
| '<' gt '>'
{ Spanned ([], [], [] ) ($1 # $>) }
| lt_ty_qual_path ',' sep_by1(ty,',') ',' sep_by1T(binding,',') gt '>'
{ Spanned ([], unspan $1 : toList $3, toList $5) ($1 # $>) }
| lt_ty_qual_path ',' sep_by1T(ty,',') gt '>'
{ Spanned ([], unspan $1 : toList $3, [] ) ($1 # $>) }
| lt_ty_qual_path ',' sep_by1T(binding,',') gt '>'
{ Spanned ([], [unspan $1],toList $3) ($1 # $>) }
| lt_ty_qual_path gt '>'
{ Spanned ([], [unspan $1],[] ) ($1 # $>) }
binding :: { (Ident, Ty Span) }
: ident '=' ty { (unspan $1, $3) }
-- Type related:
-- parse_path(PathStyle::Type)
ty_path :: { Path Span }
: ntPath { $1 }
| path_segments_without_colons { Path False $1 (spanOf $1) }
| '::' path_segments_without_colons { Path True $2 ($1 # $2) }
ty_qual_path :: { Spanned (QSelf Span, Path Span) }
: qual_path(path_segments_without_colons) { $1 }
-- parse_path_segments_without_colons()
path_segments_without_colons :: { [PathSegment Span] }
: sep_by1(path_segment_without_colons, '::') %prec SEG { toList $1 }
-- No corresponding function - see path_segments_without_colons
path_segment_without_colons :: { PathSegment Span }
: self_or_ident path_parameter { PathSegment (unspan $1) $2 ($1 # $>) }
path_parameter :: { Maybe (PathParameters Span) }
: generic_values { let (lts, tys, bds) = unspan $1
in Just (AngleBracketed lts tys bds (spanOf $1)) }
| '(' sep_byT(ty,',') ')' { Just (Parenthesized $2 Nothing ($1 # $>)) }
| '(' sep_byT(ty,',') ')' '->' ty_no_plus { Just (Parenthesized $2 (Just $>) ($1 # $>)) }
| {- empty -} %prec IDENT { Nothing }
-- Expression related:
-- parse_path(PathStyle::Expr)
expr_path :: { Path Span }
: ntPath { $1 }
| path_segments_with_colons { Path False (toList $1) (spanOf $1) }
| '::' path_segments_with_colons { Path True (toList $2) ($1 # $2) }
expr_qual_path :: { Spanned (QSelf Span, Path Span) }
: qual_path(path_segments_with_colons) { $1 }
-- parse_path_segments_with_colons()
path_segments_with_colons :: { Reversed NonEmpty (PathSegment Span) }
: self_or_ident
{ [PathSegment (unspan $1) Nothing (spanOf $1)] }
| path_segments_with_colons '::' self_or_ident
{ $1 <> [PathSegment (unspan $3) Nothing (spanOf $3)] }
| path_segments_with_colons '::' generic_values
{%
case (unsnoc $1, unspan $3) of
((rst, PathSegment i Nothing x), (lts, tys, bds)) ->
let seg = PathSegment i (Just (AngleBracketed lts tys bds (spanOf $3))) (x # $3)
in pure $ snoc rst seg
_ -> fail "invalid path segment in expression path"
}
-- Mod related:
-- parse_path(PathStyle::Mod)
--
-- TODO: This is O(n^2) in the segment length! I haven't been able to make the grammar work out in
-- order to refactor this nicely
mod_path :: { Path Span }
: ntPath { $1 }
| self_or_ident { Path False [PathSegment (unspan $1) Nothing (spanOf $1)] (spanOf $1) }
| '::' self_or_ident { Path True [PathSegment (unspan $2) Nothing (spanOf $2)] ($1 # $>) }
| mod_path '::' self_or_ident {
let Path g segs _ = $1 in
Path g (segs <> [PathSegment (unspan $3) Nothing (spanOf $3) ]) ($1 # $3)
}
self_or_ident :: { Spanned Ident }
: ident { $1 }
| crate { Spanned "crate" (spanOf $1) }
| self { Spanned "self" (spanOf $1) }
| Self { Spanned "Self" (spanOf $1) }
| super { Spanned "super" (spanOf $1) }
-----------
-- Types --
-----------
lifetime :: { Lifetime Span }
: LIFETIME { let Spanned (LifetimeTok (Ident l _ _)) s = $1 in Lifetime l s }
-- parse_trait_ref()
trait_ref :: { TraitRef Span }
: ty_path { TraitRef $1 }
-- parse_ty()
-- See https://github.com/rust-lang/rfcs/blob/master/text/0438-precedence-of-plus.md
-- All types, including trait types with plus
ty :: { Ty Span }
: ty_no_plus { $1 }
| poly_trait_ref_mod_bound '+' sep_by1T(ty_param_bound_mod,'+') { TraitObject ($1 <| toNonEmpty $3) ($1 # $3) }
-- parse_ty_no_plus()
ty_no_plus :: { Ty Span }
: ntTy { $1 }
| no_for_ty { $1 }
| for_ty_no_plus { $1 }
-- All types not starting with a '(' or '<'
ty_prim :: { Ty Span }
: no_for_ty_prim { $1 }
| for_ty_no_plus { $1 }
| poly_trait_ref_mod_bound '+' sep_by1T(ty_param_bound_mod,'+') { TraitObject ($1 <| toNonEmpty $3) ($1 # $3) }
-- All (non-sum) types not starting with a 'for'
no_for_ty :: { Ty Span }
: no_for_ty_prim { $1 }
| '(' ')' { TupTy [] ($1 # $2) }
| '(' ty ')' { ParenTy $2 ($1 # $3) }
| '(' ty ',' ')' { TupTy [$2] ($1 # $4) }
| '(' ty ',' sep_by1T(ty,',') ')' { TupTy ($2 : toList $4) ($1 # $5) }
| ty_qual_path { PathTy (Just (fst (unspan $1))) (snd (unspan $1)) (spanOf $1) }
-- All (non-sum) types not starting with a 'for', '(', or '<'
no_for_ty_prim :: { Ty Span }
: '_' { Infer (spanOf $1) }
| '!' { Never (spanOf $1) }
| '[' ty ']' { Slice $2 ($1 # $3) }
| '*' ty_no_plus { Ptr Immutable $2 ($1 # $2) }
| '*' const ty_no_plus { Ptr Immutable $3 ($1 # $3) }
| '*' mut ty_no_plus { Ptr Mutable $3 ($1 # $3) }
| '&' ty_no_plus { Rptr Nothing Immutable $2 ($1 # $>) }
| '&' lifetime ty_no_plus { Rptr (Just $2) Immutable $3 ($1 # $>) }
| '&' mut ty_no_plus { Rptr Nothing Mutable $3 ($1 # $>) }
| '&' lifetime mut ty_no_plus { Rptr (Just $2) Mutable $4 ($1 # $>) }
| '&&' ty_no_plus { Rptr Nothing Immutable (Rptr Nothing Immutable $2 (nudge 1 0 ($1 # $>))) ($1 # $>) }
| '&&' lifetime ty_no_plus { Rptr Nothing Immutable (Rptr (Just $2) Immutable $3 (nudge 1 0 ($1 # $>))) ($1 # $>) }
| '&&' mut ty_no_plus { Rptr Nothing Immutable (Rptr Nothing Mutable $3 (nudge 1 0 ($1 # $>))) ($1 # $>) }
| '&&' lifetime mut ty_no_plus { Rptr Nothing Immutable (Rptr (Just $2) Mutable $4 (nudge 1 0 ($1 # $>))) ($1 # $>) }
| ty_path %prec PATH { PathTy Nothing $1 ($1 # $>) }
| ty_mac { MacTy $1 ($1 # $>) }
| unsafe extern abi fn fn_decl(arg_general) { BareFn Unsafe $3 [] $> ($1 # $>) }
| unsafe fn fn_decl(arg_general) { BareFn Unsafe Rust [] $> ($1 # $>) }
| extern abi fn fn_decl(arg_general) { BareFn Normal $2 [] $> ($1 # $>) }
| fn fn_decl(arg_general) { BareFn Normal Rust [] $> ($1 # $>) }
| typeof '(' expr ')' { Typeof $3 ($1 # $>) }
| '[' ty ';' expr ']' { Array $2 $4 ($1 # $>) }
| '?' trait_ref { TraitObject [TraitTyParamBound (PolyTraitRef [] $2 (spanOf $2)) Maybe ($1 # $2)] ($1 # $2) }
| '?' for_lts trait_ref { TraitObject [TraitTyParamBound (PolyTraitRef (unspan $2) $3 ($2 # $3)) Maybe ($1 # $3)] ($1 # $3) }
| impl sep_by1(ty_param_bound_mod,'+') %prec IMPLTRAIT { ImplTrait (toNonEmpty $2) ($1 # $2) }
| dyn sep_by1(ty_param_bound_mod,'+') %prec IMPLTRAIT { TraitObject (toNonEmpty $2) ($1 # $2) }
-- All (non-sum) types starting with a 'for'
for_ty_no_plus :: { Ty Span }
: for_lts unsafe extern abi fn fn_decl(arg_general) { BareFn Unsafe $4 (unspan $1) $> ($1 # $>) }
| for_lts unsafe fn fn_decl(arg_general) { BareFn Unsafe Rust (unspan $1) $> ($1 # $>) }
| for_lts extern abi fn fn_decl(arg_general) { BareFn Normal $3 (unspan $1) $> ($1 # $>) }
| for_lts fn fn_decl(arg_general) { BareFn Normal Rust (unspan $1) $> ($1 # $>) }
| for_lts trait_ref {
let poly = PolyTraitRef (unspan $1) $2 ($1 # $2) in
TraitObject [TraitTyParamBound poly None ($1 # $2)] ($1 # $2)
}
-- An optional lifetime followed by an optional mutability
lifetime_mut :: { (Maybe (Lifetime Span), Mutability) }
: lifetime mut { (Just $1, Mutable) }
| lifetime { (Just $1, Immutable) }
| mut { (Nothing, Mutable) }
| {- empty -} { (Nothing, Immutable) }
-- The argument list and return type in a function
fn_decl(arg) :: { FnDecl Span }
: '(' sep_by1(arg,',') ',' '...' ')' ret_ty { FnDecl (toList $2) $> True ($1 # $5 # $6) }
| '(' sep_byT(arg,',') ')' ret_ty { FnDecl $2 $> False ($1 # $3 # $4) }
-- Like 'fn_decl', but also accepting a self argument
fn_decl_with_self_general :: { FnDecl Span }
: '(' arg_self_general ',' sep_byT(arg_general,',') ')' ret_ty { FnDecl ($2 : $4) $> False ($1 # $5 # $6) }
| '(' arg_self_general ')' ret_ty { FnDecl [$2] $> False ($1 # $3 # $4) }
| '(' ')' ret_ty { FnDecl [] $> False ($1 # $2 # $3) }
-- Like 'fn_decl', but also accepting a self argument
fn_decl_with_self_named :: { FnDecl Span }
: '(' arg_self_named ',' sep_by1(arg_named,',') ',' ')' ret_ty { FnDecl ($2 : toList $4) $> False ($1 # $6 # $7) }
| '(' arg_self_named ',' sep_by1(arg_named,',') ')' ret_ty { FnDecl ($2 : toList $4) $> False ($1 # $5 # $6) }
| '(' arg_self_named ',' ')' ret_ty { FnDecl [$2] $> False ($1 # $3 # $4) }
| '(' arg_self_named ')' ret_ty { FnDecl [$2] $> False ($1 # $3 # $4) }
| fn_decl(arg_named) { $1 }
-- parse_ty_param_bounds(BoundParsingMode::Bare) == sep_by1(ty_param_bound,'+')
ty_param_bound :: { TyParamBound Span }
: lifetime { RegionTyParamBound $1 (spanOf $1) }
| poly_trait_ref { TraitTyParamBound $1 None (spanOf $1) }
| '(' poly_trait_ref ')' { TraitTyParamBound $2 None ($1 # $3) }
poly_trait_ref_mod_bound :: { TyParamBound Span }
: poly_trait_ref { TraitTyParamBound $1 None (spanOf $1) }
| '?' poly_trait_ref { TraitTyParamBound $2 Maybe ($1 # $2) }
-- parse_ty_param_bounds(BoundParsingMode::Modified) == sep_by1(ty_param_bound_mod,'+')
ty_param_bound_mod :: { TyParamBound Span }
: ty_param_bound { $1 }
| '?' poly_trait_ref { TraitTyParamBound $2 Maybe ($1 # $2) }
-- Sort of like parse_opt_abi() -- currently doesn't handle raw string ABI
abi :: { Abi }
: str {% case unspan $1 of
LiteralTok (StrTok "cdecl") Nothing -> pure Cdecl
LiteralTok (StrTok "stdcall") Nothing -> pure Stdcall
LiteralTok (StrTok "fastcall") Nothing -> pure Fastcall
LiteralTok (StrTok "vectorcall") Nothing -> pure Vectorcall
LiteralTok (StrTok "aapcs") Nothing -> pure Aapcs
LiteralTok (StrTok "win64") Nothing -> pure Win64
LiteralTok (StrTok "sysv64") Nothing -> pure SysV64
LiteralTok (StrTok "ptx-kernel") Nothing -> pure PtxKernel
LiteralTok (StrTok "msp430-interrupt") Nothing -> pure Msp430Interrupt
LiteralTok (StrTok "x86-interrupt") Nothing -> pure X86Interrupt
LiteralTok (StrTok "Rust") Nothing -> pure Rust
LiteralTok (StrTok "C") Nothing -> pure C
LiteralTok (StrTok "system") Nothing -> pure System
LiteralTok (StrTok "rust-intrinsic") Nothing -> pure RustIntrinsic
LiteralTok (StrTok "rust-call") Nothing -> pure RustCall
LiteralTok (StrTok "platform-intrinsic") Nothing -> pure PlatformIntrinsic
LiteralTok (StrTok "unadjusted") Nothing -> pure Unadjusted
_ -> parseError $1 {- "invalid ABI" -}
}
| {- empty -} { C }
-- parse_ret_ty
ret_ty :: { Maybe (Ty Span) }
: '->' ty_no_plus { Just $2 }
| {- empty -} { Nothing }
-- parse_poly_trait_ref()
poly_trait_ref :: { PolyTraitRef Span }
: trait_ref { PolyTraitRef [] $1 (spanOf $1) }
| for_lts trait_ref { PolyTraitRef (unspan $1) $2 ($1 # $2) }
-- parse_for_lts()
-- Unlike the Rust libsyntax version, this _requires_ the 'for'
for_lts :: { Spanned [LifetimeDef Span] }
: for '<' sep_byT(lifetime_def,',') '>' { Spanned $3 ($1 # $>) }
-- Definition of a lifetime: attributes can come before the lifetime, and a list of bounding
-- lifetimes can come after the lifetime.
lifetime_def :: { LifetimeDef Span }
: many(outer_attribute) lifetime ':' sep_by1T(lifetime,'+') { LifetimeDef $1 $2 (toList $4) ($1 # $2 # $>) }
| many(outer_attribute) lifetime { LifetimeDef $1 $2 [] ($1 # $2 # $>) }
---------------
-- Arguments --
---------------
-- Argument (requires a name / pattern, ie. @parse_arg_general(true)@)
arg_named :: { Arg Span }
: ntArg { $1 }
| pat ':' ty { Arg (Just $1) $3 ($1 # $3) }
-- Argument (does not require a name / pattern, ie. @parse_arg_general(false)@)
--
-- Remark: not all patterns are accepted (as per <https://github.com/rust-lang/rust/issues/35203>)
-- The details for which patterns _should_ be accepted fall into @is_named_argument()@.
arg_general :: { Arg Span }
: ntArg { $1 }
| ty { Arg Nothing $1 (spanOf $1) }
| '_' ':' ty { Arg (Just (WildP (spanOf $1))) $3 ($1 # $3) }
| ident ':' ty { Arg (Just (IdentP (ByValue Immutable) (unspan $1) Nothing (spanOf $1))) $3 ($1 # $3) }
| mut ident ':' ty { Arg (Just (IdentP (ByValue Mutable) (unspan $2) Nothing (spanOf $2))) $4 ($1 # $4) }
| '&' '_' ':' ty { Arg (Just (RefP (WildP (spanOf $2)) Immutable ($1 # $2))) $4 ($1 # $4) }
| '&' ident ':' ty { Arg (Just (RefP (IdentP (ByValue Immutable) (unspan $2) Nothing (spanOf $2)) Immutable ($1 # $2))) $4 ($1 # $4) }
| '&&' '_' ':' ty { Arg (Just (RefP (RefP (WildP (spanOf $2)) Immutable (nudge 1 0 ($1 # $2))) Immutable ($1 # $2))) $4 ($1 # $4) }
| '&&' ident ':' ty { Arg (Just (RefP (RefP (IdentP (ByValue Immutable) (unspan $2) Nothing (spanOf $2)) Immutable (nudge 1 0 ($1 # $2))) Immutable ($1 # $2))) $4 ($1 # $4) }
-- Self argument (only allowed in trait function signatures)
arg_self_general :: { Arg Span }
: mut self { SelfValue Mutable ($1 # $>) }
| self ':' ty { SelfExplicit $3 Immutable ($1 # $>) }
| mut self ':' ty { SelfExplicit $4 Mutable ($1 # $>) }
| arg_general {
case $1 of
Arg Nothing (PathTy Nothing (Path False [PathSegment "self" Nothing _] _) _) x -> SelfValue Immutable x
Arg Nothing (Rptr l m (PathTy Nothing (Path False [PathSegment "self" Nothing _] _) _) _) x -> SelfRegion l m x
_ -> $1
}
-- Self argument (only allowed in impl function signatures)
arg_self_named :: { Arg Span }
: self { SelfValue Immutable ($1 # $>) }
| mut self { SelfValue Mutable ($1 # $>) }
| '&' self { SelfRegion Nothing Immutable ($1 # $>) }
| '&' lifetime self { SelfRegion (Just $2) Immutable ($1 # $>) }
| '&' mut self { SelfRegion Nothing Mutable ($1 # $>) }
| '&' lifetime mut self { SelfRegion (Just $2) Mutable ($1 # $>) }
| self ':' ty { SelfExplicit $3 Immutable ($1 # $>) }
| mut self ':' ty { SelfExplicit $4 Mutable ($1 # $>) }
-- Lambda expression argument
lambda_arg :: { Arg Span }
: ntArg { $1 }
| pat ':' ty { Arg (Just $1) $3 ($1 # $3) }
| pat { Arg (Just $1) (Infer mempty) (spanOf $1) }
--------------
-- Patterns --
--------------
-- There is a funky trick going on here around 'IdentP'. When there is a binding mode (ie a 'mut' or
-- 'ref') or an '@' pattern, everything is fine, but otherwise there is no difference between an
-- expression variable path and a pattern. To deal with this, we intercept expression paths with
-- only one segment, no path parameters, and not global and turn them into identifier patterns.
pat :: { Pat Span }
: ntPat { $1 }
| '_' { WildP (spanOf $1) }
| '&' mut pat { RefP $3 Mutable ($1 # $3) }
| '&' pat { RefP $2 Immutable ($1 # $2) }
| '&&' mut pat { RefP (RefP $3 Mutable (nudge 1 0 ($1 # $3))) Immutable ($1 # $3) }
| '&&' pat { RefP (RefP $2 Immutable (nudge 1 0 ($1 # $2))) Immutable ($1 # $2) }
| lit_expr { LitP $1 (spanOf $1) }
| '-' lit_expr { LitP (Unary [] Neg $2 ($1 # $2)) ($1 # $2) }
| box pat { BoxP $2 ($1 # $2) }
| binding_mode1 ident '@' pat { IdentP (unspan $1) (unspan $2) (Just $4) ($1 # $>) }
| binding_mode1 ident { IdentP (unspan $1) (unspan $2) Nothing ($1 # $>) }
| ident '@' pat { IdentP (ByValue Immutable) (unspan $1) (Just $3) ($1 # $>) }
| expr_path {
case $1 of
Path False [PathSegment i Nothing _] _ -> IdentP (ByValue Immutable) i Nothing (spanOf $1)
_ -> PathP Nothing $1 (spanOf $1)
}
| expr_qual_path { PathP (Just (fst (unspan $1))) (snd (unspan $1)) ($1 # $>) }
| lit_or_path '...' lit_or_path { RangeP $1 $3 ($1 # $>) }
| lit_or_path '..=' lit_or_path { RangeP $1 $3 ($1 # $>) }
| expr_path '{' '..' '}' { StructP $1 [] True ($1 # $>) }
| expr_path '{' pat_fields '}' { let (fs,b) = $3 in StructP $1 fs b ($1 # $>) }
| expr_path '(' pat_tup ')' { let (ps,m,_) = $3 in TupleStructP $1 ps m ($1 # $>) }
| expr_mac { MacP $1 (spanOf $1) }
| '[' pat_slice ']' { let (b,s,a) = $2 in SliceP b s a ($1 # $3) }
| '(' pat_tup ')' {%
case $2 of
([p], Nothing, False) -> parseError (CloseDelim Paren)
(ps,m,t) -> pure (TupleP ps m ($1 # $3))
}
-- The first element is the spans, the second the position of '..', and the third if there is a
-- trailing comma
pat_tup :: { ([Pat Span], Maybe Int, Bool) }
: sep_by1(pat,',') ',' '..' ',' sep_by1(pat,',') { (toList ($1 <> $5), Just (length $1), False) }
| sep_by1(pat,',') ',' '..' ',' sep_by1(pat,',') ',' { (toList ($1 <> $5), Just (length $1), True) }
| sep_by1(pat,',') ',' '..' { (toList $1, Just (length $1), False) }
| sep_by1(pat,',') { (toList $1, Nothing, False) }
| sep_by1(pat,',') ',' { (toList $1, Nothing, True) }
| '..' ',' sep_by1(pat,',') { (toList $3, Just 0, False) }
| '..' ',' sep_by1(pat,',') ',' { (toList $3, Just 0, True) }
| '..' { ([], Just 0, False) }
| {- empty -} { ([], Nothing, False) }
-- The first element is the patterns at the beginning of the slice, the second the optional binding
-- for the middle slice ('Nothing' if there is no '..' and 'Just (WildP mempty) is there is one, but
-- unlabelled), and the third is the patterns at the end of the slice.
pat_slice :: { ([Pat Span], Maybe (Pat Span), [Pat Span]) }
: sep_by1(pat,',') ',' '..' ',' sep_by1T(pat,',') { (toList $1, Just (WildP mempty), toList $5) }
| sep_by1(pat,',') ',' '..' { (toList $1, Just (WildP mempty), []) }
| sep_by1(pat,',') '..' ',' sep_by1T(pat,',') { let (xs, x) = unsnoc $1 in (toList xs, Just x, toList $4) }
| sep_by1(pat,',') '..' { let (xs, x) = unsnoc $1 in (toList xs, Just x, []) }
| sep_by1T(pat,',') { (toList $1, Nothing, []) }
| '..' ',' sep_by1T(pat,',') { ([], Just (WildP mempty), toList $3) }
| '..' { ([], Just (WildP mempty), []) }
| {- empty -} { ([], Nothing, []) }
-- Endpoints of range patterns
lit_or_path :: { Expr Span }
: expr_path { PathExpr [] Nothing $1 (spanOf $1) }
| expr_qual_path { PathExpr [] (Just (fst (unspan $1))) (snd (unspan $1)) (spanOf $1) }
| '-' lit_expr { Unary [] Neg $2 ($1 # $2) }
| lit_expr { $1 }
-- Used in patterns for tuple and expression patterns
pat_fields :: { ([FieldPat Span], Bool) }
: sep_byT(pat_field,',') { ($1, False) }
| sep_by1(pat_field,',') ',' '..' { (toList $1, True) }
pat_field :: { FieldPat Span }
: binding_mode ident
{ FieldPat Nothing (IdentP (unspan $1) (unspan $2) Nothing (spanOf $2)) ($1 # $2) }
| box binding_mode ident
{ FieldPat Nothing (BoxP (IdentP (unspan $2) (unspan $3) Nothing ($2 # $3)) ($1 # $3)) ($1 # $3) }
| binding_mode ident ':' pat
{ FieldPat (Just (unspan $2)) $4 ($1 # $2 # $4) }
-- Used prefixing IdentP patterns (not empty - that is a seperate pattern case)
binding_mode1 :: { Spanned BindingMode }
: ref mut { Spanned (ByRef Mutable) ($1 # $2) }
| ref { Spanned (ByRef Immutable) (spanOf $1) }
| mut { Spanned (ByValue Mutable) (spanOf $1) }
-- Used for patterns for fields (includes the empty case)
binding_mode :: { Spanned BindingMode }
: binding_mode1 { $1 }
| {- empty -} { Spanned (ByValue Immutable) mempty }
-----------------
-- Expressions --
-----------------
-- Expressions are a pain to parse. The Rust language places "restrictions" preventing certain
-- specific expressions from being valid in a certain context. Elsewhere in the parser, it will turn
-- on or off these restrictions. Unfortunately, that doesn't work well at all in a grammar, so we
-- have to define production rules for every combination of restrications used. Parametrized
-- productions make this a bit easier by letting us factor out the core expressions used everywhere.
-- Generalized expressions, parametrized by
--
-- * 'lhs' - expressions allowed on the left extremity of the term
-- * 'rhs' - expressions allowed on the right extremity of the term
-- * 'rhs2' - expressions allowed on the right extremity following '..'/'.../..='
--
-- Precedences are handled by Happy (right at the end of the token section)
gen_expression(lhs,rhs,rhs2) :: { Expr Span }
-- immediate expressions
: ntExpr { $1 }
| lit_expr { $1 }
| '[' sep_byT(expr,',') ']' { Vec [] $2 ($1 # $>) }
| '[' inner_attrs sep_byT(expr,',') ']' { Vec (toList $2) $3 ($1 # $>) }
| '[' expr ';' expr ']' { Repeat [] $2 $4 ($1 # $>) }
| expr_mac { MacExpr [] $1 (spanOf $1) }
| expr_path %prec PATH { PathExpr [] Nothing $1 (spanOf $1) }
| expr_qual_path { PathExpr [] (Just (fst (unspan $1))) (snd (unspan $1)) (spanOf $1) }
-- unary expressions
| '*' rhs %prec UNARY { Unary [] Deref $2 ($1 # $>) }
| '!' rhs %prec UNARY { Unary [] Not $2 ($1 # $>) }
| '-' rhs %prec UNARY { Unary [] Neg $2 ($1 # $>) }
| '&' rhs %prec UNARY { AddrOf [] Immutable $2 ($1 # $>) }
| '&' mut rhs %prec UNARY { AddrOf [] Mutable $3 ($1 # $>) }
| '&&' rhs %prec UNARY { AddrOf [] Immutable (AddrOf [] Immutable $2 (nudge 1 0 ($1 # $2))) ($1 # $2) }
| '&&' mut rhs %prec UNARY { AddrOf [] Immutable (AddrOf [] Mutable $3 (nudge 1 0 ($1 # $3))) ($1 # $3) }
| box rhs %prec UNARY { Box [] $2 ($1 # $>) }
-- left-recursive
| left_gen_expression(lhs,rhs,rhs2) { $1 }
-- range expressions
| '..' rhs2 %prec PREFIXRNG { Range [] Nothing (Just $2) HalfOpen ($1 # $2) }
| '...' rhs2 %prec PREFIXRNG { Range [] Nothing (Just $2) Closed ($1 # $2) }
| '..=' rhs2 %prec PREFIXRNG { Range [] Nothing (Just $2) Closed ($1 # $2) }
| '..' %prec SINGLERNG { Range [] Nothing Nothing HalfOpen (spanOf $1) }
| '..=' %prec SINGLERNG { Range [] Nothing Nothing Closed (spanOf $1) }
-- low precedence prefix expressions
| return { Ret [] Nothing (spanOf $1) }
| return rhs { Ret [] (Just $2) ($1 # $2) }
| yield { Yield [] Nothing (spanOf $1) }
| yield rhs { Yield [] (Just $2) ($1 # $2) }
| continue { Continue [] Nothing (spanOf $1) }
| continue label { Continue [] (Just $2) ($1 # $2) }
| break { Break [] Nothing Nothing (spanOf $1) }
| break rhs { Break [] Nothing (Just $2) ($1 # $2) }
| break label { Break [] (Just $2) Nothing ($1 # $2) }
| break label rhs %prec break { Break [] (Just $2) (Just $3) ($1 # $3) }
-- lambda expressions
| static move lambda_args rhs %prec LAMBDA
{ Closure [] Immovable Value (FnDecl (unspan $3) Nothing False (spanOf $3)) $> ($1 # $>) }
| move lambda_args rhs %prec LAMBDA
{ Closure [] Movable Value (FnDecl (unspan $2) Nothing False (spanOf $2)) $> ($1 # $>) }
| static lambda_args rhs %prec LAMBDA
{ Closure [] Immovable Ref (FnDecl (unspan $2) Nothing False (spanOf $2)) $> ($1 # $>) }
| lambda_args rhs %prec LAMBDA
{ Closure [] Movable Ref (FnDecl (unspan $1) Nothing False (spanOf $1)) $> ($1 # $>) }
-- Variant of 'gen_expression' which only constructs expressions starting with another expression.
left_gen_expression(lhs,rhs,rhs2) :: { Expr Span }
: postfix_blockexpr(lhs) { $1 }
| lhs '[' expr ']' { Index [] $1 $3 ($1 # $>) }
| lhs '(' sep_byT(expr,',') ')' { Call [] $1 $3 ($1 # $>) }
-- unary expressions
| lhs ':' ty_no_plus { TypeAscription [] $1 $3 ($1 # $>) }
| lhs as ty_no_plus { Cast [] $1 $3 ($1 # $>) }
-- binary expressions
| lhs '*' rhs { Binary [] MulOp $1 $3 ($1 # $>) }
| lhs '/' rhs { Binary [] DivOp $1 $3 ($1 # $>) }
| lhs '%' rhs { Binary [] RemOp $1 $3 ($1 # $>) }
| lhs '+' rhs { Binary [] AddOp $1 $3 ($1 # $>) }
| lhs '-' rhs { Binary [] SubOp $1 $3 ($1 # $>) }
| lhs '<<' rhs { Binary [] ShlOp $1 $3 ($1 # $>) }
| lhs '>>' rhs { Binary [] ShrOp $1 $3 ($1 # $>) }
| lhs '&' rhs { Binary [] BitAndOp $1 $3 ($1 # $>) }
| lhs '^' rhs { Binary [] BitXorOp $1 $3 ($1 # $>) }
| lhs '|' rhs { Binary [] BitOrOp $1 $3 ($1 # $>) }
| lhs '==' rhs { Binary [] EqOp $1 $3 ($1 # $>) }
| lhs '!=' rhs { Binary [] NeOp $1 $3 ($1 # $>) }
| lhs '<' rhs { Binary [] LtOp $1 $3 ($1 # $>) }
| lhs '>' rhs { Binary [] GtOp $1 $3 ($1 # $>) }
| lhs '<=' rhs { Binary [] LeOp $1 $3 ($1 # $>) }
| lhs '>=' rhs { Binary [] GeOp $1 $3 ($1 # $>) }
| lhs '&&' rhs { Binary [] AndOp $1 $3 ($1 # $>) }
| lhs '||' rhs { Binary [] OrOp $1 $3 ($1 # $>) }
-- range expressions
| lhs '..' %prec POSTFIXRNG { Range [] (Just $1) Nothing HalfOpen ($1 # $>) }
| lhs '...' %prec POSTFIXRNG { Range [] (Just $1) Nothing Closed ($1 # $>) }
| lhs '..=' %prec POSTFIXRNG { Range [] (Just $1) Nothing Closed ($1 # $>) }