-
Notifications
You must be signed in to change notification settings - Fork 2
/
EcsParserGrammar.les
2259 lines (2100 loc) · 89.1 KB
/
EcsParserGrammar.les
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
//
// Enhanced C# parser: this is designed to accept a superset of C# 6 (Enhanced C#).
// If this spews an error when given a valid C# file, it's a bug. File a bug report.
//
// EC# is more permisive than plain C#; it not only adds new syntax, but it
// liberalizes the existing syntax rules (e.g. "try Foo(); catch Bar();" is
// accepted in EC#) and it also accepts a lot of code that is not directly valid in
// C# (e.g. "struct X { Y(); }"). Such invalid code is allowed by the parser in
// case a macro might transform it later into something that makes more sense.
//
#importMacros LeMP.Prelude.Les;
#ecs;
import System;
import System.Collections.Generic;
import System.Linq;
import System.Text;
import System.Diagnostics;
import Loyc;
import Loyc.Syntax;
import Loyc.Syntax.Les;
import Loyc.Syntax.Lexing;
import Loyc.Collections;
import Loyc.Collections.Impl;
namespace Loyc.Ecs.Parser
{
using TT = TokenType;
using S = CodeSymbols;
using EP = EcsPrecedence;
// 0162=Unreachable code detected; 0642=Possibly mistaken empty statement
#rawText "\n\t#pragma warning disable 162, 642\n\t";
@[partial] class EcsParser
{
@[LL(2), Verbosity(1), AddCsLineDirectives(@false)]
LLLPG parser(laType(TokenType), terminalType(Token), matchType(int),
allowSwitch(@true), setType(HashSet!int), castLA(@false));
alias("(" = TT.LParen);
alias(")" = TT.RParen);
alias("[" = TT.LBrack);
alias("]" = TT.RBrack);
alias("{" = TT.LBrace);
alias("}" = TT.RBrace);
alias("." = TT.Dot);
alias("->" = TT.PtrArrow);
alias("::" = TT.ColonColon);
alias("?." = TT.NullDot);
alias("=" = TT.Set);
alias("??=" = TT.CompoundSet);
alias(":" = TT.Colon);
alias("@" = TT.At);
alias("``" = TT.BQString);
alias("\\" = TT.Backslash);
alias("*" = TT.Mul);
alias("/,%" = TT.DivMod);
alias("**" = TT.Power);
alias("+" = TT.Add);
alias("-" = TT.Sub);
alias("++,--" = TT.IncDec);
alias("&&" = TT.And);
alias("||,^^" = TT.OrXor);
alias("!" = TT.Not);
alias("&" = TT.AndBits);
alias("^" = TT.XorBits);
alias("|" = TT.OrBits);
alias("~" = TT.NotBits);
alias("==,!=" = TT.EqNeq);
alias("<" = TT.LT);
alias(">" = TT.GT);
alias("<=,>=" = TT.LEGE);
alias(".." = TT.DotDot);
alias("?" = TT.QuestionMark);
alias("??" = TT.NullCoalesce);
alias("=:" = TT.QuickBind);
alias(":=" = TT.QuickBindSet);
alias("==>" = TT.Forward);
alias("$" = TT.Substitute);
alias("=>" = TT.LambdaArrow);
alias("," = TT.Comma);
alias(";" = TT.Semicolon);
// Used to resolve the constructor ambiguity, in which "Foo()" could be a
// constructor declaration or a method call. _spaceName is the name of the
// current space, or #fn (S.Fn) when inside a method or constructor.
_spaceName::Symbol;
// Inside a LINQ expression, certain ContextualKeywords are to be treated
// as actual keywords. This flag enables that behavior.
_insideLinqExpr::bool;
// Used to detect a specific ContextualKeyword; `@` renders it not-a-keyword
fn Is(li::int, value::Symbol)::bool
{
var lt = LT(li);
return lt.Value == value && SourceFile.Text.TryGet(lt.StartIndex, '\0') != '@';
};
// A potential LINQ keyword that, it turns out, can be treated as an identifier
// because we are not in the context of a LINQ expression.
@[private] rule LinqKeywordAsId()::Token @{
&!{_insideLinqExpr} result:TT.LinqKeyword
};
// ---------------------------------------------------------------------
// -- Type names and complex identifiers -------------------------------
// ---------------------------------------------------------------------
// The complex identifier in EC# is a subset of the language of expressions,
// and data types are a superset of the language of complex identifiers.
// Complex identifiers can appear in the following contexts:
// - Space names: namespace Foo.Bar<$T> {...}
// (and yes, I want to support template parameters on namespaces someday)
// - Method/property names: bool global::System.IEquatable<T>.Equals(T other)
// Data types can appear in the following contexts:
// - Fields and properties: int* x { get; set; }
// - Methods declarations: int[] f(Foo<T>[,][] x);
// - Certain pseudo-functions: typeof(Foo<T[]>)
// Note that complex identifiers can contain substitution expressions,
// which, in turn, can contain expressions of any complexity, e.g.
// Foo<$(x*y(++z))>. Of course, complex identifiers also appear within
// normal expressions, but the expression grammar doesn't use the
// main "ComplexId" rule, instead it's handled somewhat separately.
// LLLPG is unaware of this overload, but when I write DataType(),
// it unwittingly invokes it.
@[public] fn DataType(afterAsOrIs::bool = false)::LNode {
brack::opt!Token;
var type = DataType(afterAsOrIs, out brack);
if (brack != null) {
Error("A type name cannot include [array dimensions]. The square brackets should be empty.");
};
return type;
};
@[recognizer(fn Scan_DataType(afterAsOrIs::bool = false))]
rule DataType(afterAsOrIs::bool, out majorDimension::opt!Token)::LNode @{
result:ComplexId()
TypeSuffixOpt(afterAsOrIs, out majorDimension, ref result)
};
// Complex identifier in non-declaration context, e.g. Foo.Bar or Foo<x, y>
@[FullLLk] // http://loyc-etc.blogspot.ca/2013/12/bogus-ambiguity-warnings-in-lllpg.html
token ComplexId(declContext::bool = false)::LNode @{ // Part of DataType
result:IdWithOptionalTypeParams(declContext)
[ // There can be only a single "externAlias::" prefix in a complex Id, with no type params.
{if (result.Calls(S.Of)) {Error("Type parameters cannot appear before '::' in a declaration or type name");};}
op:="::" rhs:=IdWithOptionalTypeParams(declContext)
{result = F.Call(S.ColonColon, result, rhs, result.Range.StartIndex, rhs.Range.EndIndex, op.StartIndex, op.EndIndex, NodeStyle.Operator);}
]?
[ op:="." rhs:=IdWithOptionalTypeParams(declContext)
{result = F.Dot(result, rhs, result.Range.StartIndex, rhs.Range.EndIndex, op.StartIndex, op.EndIndex, NodeStyle.Operator);}
]*
};
@[FullLLk]
token IdWithOptionalTypeParams(declarationContext::bool)::LNode @{
result:IdAtom [TParams(declarationContext, ref result)]?
};
// identifier, $identifier, $(expr), operator+ (or another operator name), or a primitive type (int, string)
rule IdAtom::LNode @{
{r::LNode;}
( t:="$" e:=Atom {e=AutoRemoveParens(e);}
{r = F.Call(S.Substitute, e, t.StartIndex, e.Range.EndIndex, t.StartIndex, t.EndIndex, NodeStyle.Operator);}
| op:=TT.Operator t:=AnyOperator
{r = F.Attr(_triviaUseOperatorKeyword, F.Id(t.Value -> Symbol, op.StartIndex, t.EndIndex));}
| t:=(TT.Id|TT.ContextualKeyword|TT.TypeKeyword)
{r = F.Id(t);}
| t:=LinqKeywordAsId
{r = F.Id(t);}
//| error {Error("Expected an identifier"); r = MissingHere();}
) {return r;}
};
@[#static] fn AutoRemoveParens(node::LNode)::LNode
{
i::int = node.Attrs.IndexWithName(S.TriviaInParens);
if (i > -1) {
return node.WithAttrs(node.Attrs.RemoveAt(i));
};
return node;
};
// List of type parameters. `declContext` specifies that type parameters can
// have [normal attributes] and in/out variance attrbutes.
@[recognizer(fn Scan_TParams(declContext::bool))]
rule TParams(declContext::bool, ref r::LNode)
@{
{list::VList!LNode = (new VList!LNode(r));}
{endIndex::int;}
( op:"<" [list+=TParamDeclOrDataType(declContext)
("," list+=TParamDeclOrDataType(declContext))*]? end:=">" {endIndex = end.EndIndex;}
| op:"." t:="[" end:="]" {list = AppendExprsInside(t, list); endIndex = end.EndIndex;} // Nemerle style
| op:"!" t:="(" end:=")" {list = AppendExprsInside(t, list); endIndex = end.EndIndex;} // D & LES style
| op:"!" list+=IdWithOptionalTypeParams(declContext) {endIndex = list.Last.Range.EndIndex;}
)
{
start::int = r.Range.StartIndex;
r = F.Call(S.Of, list, start, endIndex, op.StartIndex, op.EndIndex, NodeStyle.Operator);
}
};
@[recognizer(fn Scan_TParamDeclOrDataType(declarationContext::bool))]
rule TParamDeclOrDataType(declarationContext::bool)::LNode @{
{attrs::VList!LNode = default(VList!LNode); startIndex::int = GetTextPosition(InputPosition);}
( result:DataType(false)
/ &{declarationContext}
NormalAttributes(ref attrs)
TParamAttributeKeywords(ref attrs)
result:IdAtom
)
{$result = $result.WithAttrs(attrs);}
};
// This is the same as ComplexId except that it is used in declaration
// locations such as the name of a class. The difference is that the
// type parameters can have [normal attributes] and in/out variance
// attrbutes. This matcher also helps match properties and therefore
// optionally allows names ending in 'this', such as 'IList<T>.this'
fn ComplexNameDecl()::LNode { _::bool; return ComplexNameDecl(false, out _); };
@[FullLLk, recognizer(fn Scan_ComplexNameDecl(thisAllowed::bool = false))]
token ComplexNameDecl(thisAllowed::bool, out hasThis::bool)::LNode @{
result:ComplexId(declContext: true) {hasThis = false;}
[ op:="." ComplexThisDecl(thisAllowed) {hasThis = true;}
{result = F.Dot(result, $ComplexThisDecl, result.Range.StartIndex, $ComplexThisDecl.Range.EndIndex, op.StartIndex, op.EndIndex, NodeStyle.Operator);}
]?
};
// The matcher for method and property names is similar to ComplexNameDecl but
// can allow 'this' if it's a property, and 'operator true' if it's a method.
@[recognizer(fn Scan_MethodOrPropertyName(thisAllowed::bool))]
token MethodOrPropertyName(thisAllowed::bool, out hasThis::bool)::LNode @{
result:ComplexNameDecl(thisAllowed, out hasThis)
| result:ComplexThisDecl(thisAllowed) {hasThis = true;}
| TT.Operator &{@["Expected 'true' or 'false'"] LT($LI).Value `is` bool} tf:TT.Literal
{ $result = F.Attr(_triviaUseOperatorKeyword, F.Literal(tf)); hasThis = false; }
};
// `this` with optional <type arguments>
token ComplexThisDecl(allowed::bool)::LNode @{
{if (!allowed) {Error("'this' is not allowed in this location.");};}
t:=TT.This {$result = F.Id(t);}
TParams(true, ref result)?
};
count::int; // hack allows Scan_TypeSuffixOpt() to compile
@[recognizer(fn Scan_TypeSuffixOpt(afterAsOrIs::bool))]
token TypeSuffixOpt(afterAsOrIs::bool, out dimensionBrack::opt!Token, ref e::LNode)::bool
@{
{count::int; result::bool = false;}
{dimensionBrack = null;}
greedy
( // in "x as Foo ? ..." it could be challenging to figure out whether
// "?" is part of type Foo or not. Some tests with the standard C#
// compiler seem to suggest that checking the next token will suffice,
// because standard C# rejects potentially valid code such as
// "x as Foo? - y", saying "Syntax error, ':' expected" at the end.
// This seems not to be a precedence issue; although "/" has higher
// precedence than "as", the C# compiler can parse "x as Foo? / y"
// (meaning (x as Foo?) / y) or "x as Foo + y" but fails to parse
// "x as Foo? + y". I believe this is because "+" can be a prefix
// operator. It also fails to parse "x as Foo?*" with a syntax error,
// not a semantic error, and for "x as Foo? * x" it again says
// "':' expected".
//
// Note: C# 7 introduces "x is Foo y" syntax, but "x is Foo? y" is
// illegal, just like "x as Foo? y" ("Syntax error, ':' expected")
//
// Examples (usually there is more than one syntax error, but the message
// "':' expected" indicates how the parser sees the situation):
// x as Foo ? y // Syntax error, ':' expected
// x as Foo? / y // Parsed OK
// x as Foo? % y // Parsed OK
// x as Foo? < y // Parsed OK
// x as Foo? ?? y // Parsed OK
// x as Foo ?? y // Parsed OK (?? is null coalesce operator)
// x as Foo? + y // Syntax error, ':' expected
// x as Foo? - y // Syntax error, ':' expected
// x as Foo? * -y // Syntax error, ':' expected
// x as Foo? ! y // Syntax error, ':' expected
// (x as Foo?++) // Invalid expression term ')'
// x as Foo?.Value // Parsed OK
// x as Foo?[y] // Parsed OK (whoa - looks like C# 6 introduced an ambiguity here with the `?[]` operator!)
// x as Foo ? (y) : z // Parsed OK
// x as Foo?(y) // Syntax error, ':' expected
t:="?" (&!{@[Local]afterAsOrIs} | &!(TT.Id | TT.ContextualKeyword | TT.TypeKeyword | TT.Literal
| TT.New | "(" | "{" | "+" | "-" | "*" | "&" | "!" | "~"
| "==>" | "++,--" | "$" | "@" | LinqKeywordAsId))
{e = F.Of(F.Id(t), e, e.Range.StartIndex, t.EndIndex); result=true;}
| // Standard C# fails to parse "x as Foo * y", which suggests I can
// unconditionally accept "*" as a pointer marker.
t:="*" {e = F.Of(F.Id(t), e, e.Range.StartIndex, t.EndIndex); result=true;}
| t:="**" {
var ptr = F.Id(S._Pointer, t.StartIndex, t.EndIndex);
e = F.Of(ptr, F.Of(ptr, e, e.Range.StartIndex, t.EndIndex - 1), e.Range.StartIndex, t.EndIndex);
result=true;
}
| // int[][,] means "array of (two-dimensional array of int)", so we
// must process array adornments in reverse order.
{var dims = InternalList!(Pair!(int,int)).Empty;}
{rb::Token;}
( &{@[Local] (count=CountDims(LT($LI), true)) > 0} lb:="[" rb="]" {dims.Add(Pair.Create(count, rb.EndIndex));})
(greedy(&{@[Local] (count=CountDims(LT($LI), false)) > 0} "[" rb="]" {dims.Add(Pair.Create(count, rb.EndIndex));}))*
{
if CountDims(lb, false) <= 0 {
dimensionBrack = lb;
};
for (i::int = dims.Count - 1; i >= 0; i--) {
e = F.Of(F.Id(S.GetArrayKeyword(dims[i].A)), e, e.Range.StartIndex, dims[i].B);
};
result = true;
}
)*
{return result;}
};
// ---------------------------------------------------------------------
// -- Expressions ------------------------------------------------------
// ---------------------------------------------------------------------
// Parsing EC# expressions is very tricky. Here are some of the things
// that make it difficult, especially in an LL(k) parser:
//
// 1. Parenthesis: is it a cast or a normal expression?
// (A<B,C>)y is a cast
// (A<B,C>)-y is NOT a cast
// (A<B,C>)(-y) is a cast
// (A<B,C>)(as B) is NOT a cast (well, the second part is)
// x(A<B,C>)(-y) is NOT a cast
// -(A<B,C>)(-y) is a cast
// $(A<B,C>)(-y) is NOT a cast
// (A<B,C>){y} is a cast
// (A<B,C>)[y] is NOT a cast
// (A<B,C>)++(y) is NOT a cast (it's post-increment and call)
// (A<B> C)(-y) is NOT a cast
// ([] A<B,C>)(y) is NOT a cast (empty attr list defeats cast)
// (int)*y is a cast
// (A<B,C>)*y is NOT a cast
// (A<B,C>)&y is NOT a cast
// (A+B==C)y is nonsensical
// x(A<B,C>)y is nonsensical
// 2. In-expr var declarations: is "(A<B,C>D)" a variable declaration?
// (A<B,C>D) => D.Foo() // variable declaration
// (A<B,C>D) = Foo() // variable declaration
// (f1, f2) = (A<B,C>D) // tuple
// Foo(A<B,C>D) // method with two arguments
// void Foo(A<B,C>D) // variable declaration at statement level
// Foo(A<B,C>D) // variable declaration at statement level if 'Foo' is the space name
// // (i.e. when 'Foo' is a constructor)
// 3. Less-than: is it a generics list or an operator? Need unlimited lookahead.
// (A<B,C) // less-than operator
// (A<B,C>) // generics list
// (A<B,C>D) // context-dependent
// 4. Brackets. Is "Foo[]" a data type, or an indexer with no args?
// (Foo[]) x; // data type: #of(@`'[]`, Foo)
// (Foo[]).x; // indexer: @`'[]`(Foo)
// 5. Does "?" make a nullable type or a conditional operator?
// Foo<B> ? x = null; // nullable type
// Foo<B> ? x = null : y; // conditional operator
/// Below lowest precedence
@[#public, #static, #readonly] StartExpr::Precedence = (new Precedence(-100));
// Types of expressions:
// - identifier
// - (parenthesized expr)
// - (tuple,)
// - ++prefix_operators
// - suffix_operators++
// - infix + operators, including x => y
// - the ? conditional : operator
// - generic<arguments>, generic!arguments, generic.[arguments]
// - (old_style) casts
// - call_style(->casts)
// - method_calls(with, arguments)
// - typeof(and other pseudofunctions)
// - indexers[with, indexes]
// - new Object()
// - { code in braces; new scope }
// - #{ code in braces; old scope }
// - delegate(...) {...}
// - from x in expr... (LINQ)
// Atom is: Id, TypeKeyword, $Atom, .Atom, new ..., (ExprStart), {Stmts},
@[LL(3)]
rule Atom::LNode @{
{r::LNode;}
( t:=("$"|".") e:=Atom {e=AutoRemoveParens(e);}
{r = F.Call(t.Value -> Symbol, e, t.StartIndex, e.Range.EndIndex, t.StartIndex, t.EndIndex);}
| op:=TT.Operator t:=AnyOperator
{r = F.Attr(_triviaUseOperatorKeyword, F.Id(t.Value -> Symbol, op.StartIndex, t.EndIndex));}
| t:=(TT.Id | TT.ContextualKeyword | TT.TypeKeyword | TT.This | TT.Base)
{r = F.Id(t);}
| t:=LinqKeywordAsId
{r = F.Id(t);}
| t:=TT.Literal
{r = F.Literal(t);}
| r=ExprInParensAuto // (...)
| r=NewExpr // new ...
| r=BracedBlock // {...}
| r=TokenLiteral
| t:=(TT.Checked | TT.Unchecked)
args:="(" rp:=")"
{r = F.Call(t.Value -> Symbol, ExprListInside(args), t.StartIndex, rp.EndIndex, t.StartIndex, t.EndIndex);}
| t:=(TT.Typeof | TT.Default | TT.Sizeof)
args:="(" rp:=")"
{r = F.Call(t.Value -> Symbol, TypeInside(args), t.StartIndex, rp.EndIndex, t.StartIndex, t.EndIndex);}
| t:=TT.Delegate args:="(" ")" block:="{" rb:="}"
{r = F.Call(S.Lambda, F.List(ExprListInside(args, false, true)), F.Braces(StmtListInside(block), block.StartIndex, rb.EndIndex),
t.StartIndex, rb.EndIndex, t.StartIndex, t.EndIndex, NodeStyle.OldStyle);}
| t:=TT.Is r=IsPattern(F.Missing, t)
| error
greedy[ (~(","|";")) ]*
{r = Error("'{0}': Expected an expression: (parentheses), {{braces}}, identifier, literal, or $substitution.", CurrentTokenText());}
/*hack: avoid long analysis-time bug*/ (_ =>{})
) {return r;}
};
token AnyOperator::Token // operators allowed after the "operator" keyword
@{
// Create synthetic token for >> or <<
&{LT($LI).EndIndex == LT($LI+1).StartIndex}
( op:="<" "<" {$result = (new Token(TT.Operator -> int, op.StartIndex, op.Length+1, S.Shl));}
| op:=">" ">" {$result = (new Token(TT.Operator -> int, op.StartIndex, op.Length+1, S.Shr));} )
/ result:
( "." | "->" | "::" | "?." | "=" | "??=" | ":" | "@"
| "``" | "\\" | "*" | "/,%" | "**" | "+" | "-" | "++,--"
| "&&" | "||,^^" | "!" | "&" | "^" | "|" | "~" | "==,!="
| "<" | ">" | "<=,>=" | ".." | "?" | "??" | "=:" | ":="
| "$" | "=>" | "==>" )
};
token NewExpr::LNode @{
{
majorDimension::opt!Token = null;
endIndex::int;
var list = VList!LNode.Empty;
}
op:=TT.New
( // new [] { ... } <=> #new(@`[]`(), ...)
&{(count=CountDims(LT($LI), false)) > 0}
lb:="[" rb:="]"
{var type = F.Id(S.GetArrayKeyword(count), lb.StartIndex, rb.EndIndex);}
lb="{" rb="}"
{
list.Add(LNode.Call(type, type.Range));
AppendInitializersInside(lb, ref list);
endIndex = rb.EndIndex;
}
| // new { ... } <=> #new(@``, ...)
lb:="{" rb:="}"
{
list.Add(F.Missing);
AppendInitializersInside(lb, ref list);
endIndex = rb.EndIndex;
}
| // new Type(...) <=> #new(Type(...))
// new Type(...) { ... } <=> #new(Type(...), ...)
// new Type { ... } <=> #new(Type(), ...)
// new Type[10] { ... } <=> #new(#of(@`[]`, Type)(10), ...)
// new Type[10][] <=> #new(#of(@`[]`, #of(@`'[]`, Type))(10))
type:=DataType(false, out majorDimension)
( // new Type(...) <=> #new(Type(...))
// new Type(...) { ... } <=> #new(Type(...), ...)
lp:="(" rp:=")"
{
if (majorDimension != null) {
Error("Syntax error: unexpected constructor argument list (...)");
};
list.Add(F.Call(type, ExprListInside(lp), type.Range.StartIndex, rp.EndIndex));
endIndex = rp.EndIndex;
}
( lb:="{" rb:="}"
{
AppendInitializersInside(lb, ref list);
endIndex = rb.EndIndex;
}
)?
/ // new Type { ... } <=> #new(Type(), ...)
// new Type[10] { ... } <=> #new(#of(@`[]`, Type)(10), ...)
// new Type[10][] <=> #new(#of(@`[]`, #of(@`[]`, Type))(10))
{var(lb::Token = op, rb::Token = op); haveBraces::bool = false;}
( lb="{" rb="}" {haveBraces = true;} )?
{
if (majorDimension != null) {
list.Add(LNode.Call(type, ExprListInside(majorDimension.Value), type.Range))
} else {
list.Add(LNode.Call(type, type.Range));
};
if (haveBraces) {
AppendInitializersInside(lb, ref list);
endIndex = rb.EndIndex;
} else {
endIndex = type.Range.EndIndex;
};
if (!haveBraces && majorDimension == null) {
if IsArrayType(type) {
Error("Syntax error: missing array size expression")
} else {
Error("Syntax error: expected constructor argument list (...) or initializers {...}");
};
};
}
)
)
{return F.Call(S.New, list, op.StartIndex, endIndex, op.StartIndex, op.EndIndex);}
};
fn TypeInside(args::Token)::LNode
{
if (!Down(args)) (return F.Id(S.Missing, args.EndIndex, args.EndIndex));
var type = DataType();
Match(EOF -> int);
return Up(type);
};
@[private] rule ExprInParensAuto::LNode @{
// This gate is used to avoid a slug that quadruples analysis time elsewhere in the grammar
"(" ")" =>
( &(ExprInParens(true) ("="|"=>"))
r:=ExprInParens(true) {return r;}
/ r:=ExprInParens(false) {return r;}
)
};
@[private] rule TokenLiteral()::LNode @{
at:"@" ( L:"[" R:"]" | L:"{" R:"}" )
{return F.Literal($L.Children, $at.StartIndex, $R.EndIndex);}
};
@[FullLLk, private]
rule AtomOrTypeParamExpr()::LNode @{
&( IdWithOptionalTypeParams(false) (~(TT.Id|TT.ContextualKeyword|TT.LinqKeyword)|EOF) ) result:IdWithOptionalTypeParams(false)
/ result:Atom
};
@[private] rule PrimaryExpr()::LNode @{
e:=AtomOrTypeParamExpr
FinishPrimaryExpr(ref e)
(
op:="?." rhs:=PrimaryExpr {e = F.Call(op, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex, NodeStyle.Operator);}
)?
{return e;}
};
@[private] rule FinishPrimaryExpr(ref e::LNode) @{
greedy
( op:=("."|"->"|"::"|"=:")
rhs:=AtomOrTypeParamExpr {e = F.Call(op.Value -> Symbol, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex, op.StartIndex, op.EndIndex, NodeStyle.Operator);}
/ // x(-> Foo), x(as Foo), x(using Foo)
e=PrimaryExpr_NewStyleCast(e)
/ lp:="(" rp:=")" {e = F.Call(e, ExprListInside(lp), e.Range.StartIndex, rp.EndIndex);}
| lb:="[" rb:="]" {var list = (new VList!LNode() { e });}
{e = F.Call(S.IndexBracks, AppendExprsInside(lb, list), e.Range.StartIndex, rb.EndIndex, lb.StartIndex, lb.EndIndex);}
| // Tentative tree structure - there is an undesirable inconsistency between ?. and ?[].
// Specifically, `a.b?.c.d` parses as `(a.b)?.(c.d)` so that the
// null-dot macro can manipulate the `.d` on the end; it would be
// harder to generate the outut of `a.b != null ? a.b.c.d : null` if
// it came in as `((a.b)?.c).d`. Likewise if there were a macro for
// `?[]`, it would morph `a.b?[c].d` into `a.b != null ? a.b[c].d : null`
// so it seems like we want a ternary operator, such that `a.b?[c].d`
// is parsed as @`?[]`(a.b, #(c), d) so we can deal with the `.d`.
// However, this doesn't really work, because it wouldn't naturally
// accept an input like `a.b?[c](d)`. So... argh. For now I'll parse
// 1. `a.b?[c].d` as ``@`?[]`(a.b, #(c)).d``
// 2. `a.b?[c](d)` as ``@`?[]`(a.b, #(c))(d)``
// This is the easiest way to parse it, anyhow. And I'll leave `?.`
// as-is, even though it works differently than `?[]`.
t:="?" lb:="[" rb:="]"
{e = F.Call(S.NullIndexBracks, e, F.List(ExprListInside(lb)), e.Range.StartIndex, rb.EndIndex, t.StartIndex, lb.EndIndex);}
| // Post-inc or post-dec
t:="++,--" {e = F.Call(t.Value == S.PreInc ? S.PostInc : S.PostDec, e, e.Range.StartIndex, t.EndIndex, t.StartIndex, t.EndIndex);}
| bb:=BracedBlockOrTokenLiteral
{ if (!e.IsCall || e.BaseStyle == NodeStyle.Operator) {
e = F.Call(e, bb, e.Range.StartIndex, bb.Range.EndIndex)
} else {
e = e.WithArgs(e.Args.Add(bb)).WithRange(e.Range.StartIndex, bb.Range.EndIndex);
};
}
)*
};
@[private] rule PrimaryExpr_NewStyleCast(e::LNode)::LNode @{
&{@[Hoist] Down($LI) && Up(LA0 == TT.As || LA0 == TT.Using || LA0 == TT.PtrArrow)}
lp:="(" rp:=")"
(=>
{Down(lp);}
{kind::Symbol;}
{var attrs = VList!LNode.Empty;}
( op:"->" {kind = S.Cast;}
| op:TT.As {kind = S.As;}
| op:TT.Using {kind = S.UsingCast;})
NormalAttributes(ref attrs)
AttributeKeywords(ref attrs)
type:=DataType EOF
{
type = type.PlusAttrs(attrs);
return Up(SetAlternateStyle(SetOperatorStyle(
F.Call(kind, e, type, e.Range.StartIndex, rp.EndIndex, op.StartIndex, op.EndIndex))));
}
)
};
// Prefix expressions, atoms, and high-precedence expressions like f(x) and List<T>
@[LL(3)] // to distinguish (cast) expr from (parens)
@[private] rule PrefixExpr::LNode
@{ op:=("+"|"-"|"!"|"~"|"++,--"|"*"|"&"|".."|"==>") e:=PrefixExpr
{return SetOperatorStyle(F.Call(op, e, op.StartIndex, e.Range.EndIndex));}
| op:="**"
e:=PrefixExpr
{return F.Call(S._Dereference, F.Call(S._Dereference, e,
op.StartIndex+1, e.Range.EndIndex, op.StartIndex+1, op.EndIndex, NodeStyle.Operator),
op.StartIndex, e.Range.EndIndex, op.StartIndex, op.StartIndex+1, NodeStyle.Operator);}
| // C-style cast
&{@[Hoist] Down($LI) && Up(Scan_DataType() && LA0 == EOF)}
lp:="(" ")"
&!("+"|"-"|"*"|"&"|"."|TT.BQString | ("++,--" "(") | &{_insideLinqExpr} TT.LinqKeyword)
e:=PrefixExpr
{Down(lp); return SetOperatorStyle(F.Call(S.Cast, e, Up(DataType()), lp.StartIndex, e.Range.EndIndex, lp.StartIndex, lp.EndIndex));}
/ e:=KeywordOrPrimaryExpr {return e;}
};
@[LL(2), private]
rule KeywordOrPrimaryExpr::LNode
@{ // C# 5 await
&{@[Hoist] Is($LI, @@await)} op:=TT.ContextualKeyword e:=PrefixExpr
{return SetOperatorStyle(F.Call(@@await, e, op.StartIndex, e.Range.EndIndex, op.StartIndex, op.EndIndex));}
/ e:=KeywordStmtAsExpr
{return e;}
/ e:=LinqQueryExpression
{return e;}
/ e:=PrimaryExpr
{return e;}
};
rule KeywordStmtAsExpr::LNode @{
{var startIndex = LT0.StartIndex;}
( result:ReturnBreakContinueThrow(startIndex)
| result:GotoCaseStmt(startIndex)
/ result:GotoStmt(startIndex)
| result:SwitchStmt(startIndex)
)
};
fn SetOperatorStyle(node::LNode)::LNode
{
return node.SetBaseStyle(NodeStyle.Operator);
};
fn SetAlternateStyle(node::LNode)::LNode
{
node.Style |= NodeStyle.Alternate;
return node;
};
// This rule handles all lower precedence levels, from ** down to assignment
// (=). This rule uses the "precedence floor" concept, documented in
// Loyc.Syntax.Precedence, to handle different precedence levels. The
// traditional approach is to define a separate rule for every precedence
// level. By collapsing many precedence levels into a single rule, there are
// two benefits:
// (1) shorter code.
// (2) potentially better performance: using a separate rule per precedence
// level causes a new stack frame and prediction step to be created for
// each level, regardless of the operators present in the actual
// expression being parsed. For example, to parse the simple expression
// "Hello" the traditional way requires 20 rules and therefore 20 stack
// frames if there are 20 precedence levels. On the other hand, the
// "precedence floor" approach requires an extra precedence check, so
// it may be slower when there are few levels. Note: EC# has 22
// precedence levels, and this method handles the lower 18 of them.
//
// The higher levels of the EC# expression parser do not use this trick
// because the higher precedence levels have some complications, such as
// C-style casts and <type arguments>, that I prefer to deal with
// separately.
@[private] rule SubExpr(context::Precedence)::LNode @{
{Debug.Assert(context.CanParse(EP.Prefix));}
{prec::Precedence;}
e:=PrefixExpr
greedy
( // Infix operator
&{@[Local] context.CanParse(prec=InfixPrecedenceOf($LA))}
op:=( "**"|"*"|"/,%"|"+"|"-"|"~"|".."|"<"|">"|"<=,>="|"==,!="
| "&"|"|"|"^"|"&&"|"||,^^"|"??"|"="|"??="|"=>"|TT.BQString|TT.In )
rhs:=SubExpr(prec)
{e = F.Call(op.Value -> Symbol, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex, op.StartIndex, op.EndIndex, NodeStyle.Operator);}
| // is-test or a more complex is-expr
&{@[Local] context.CanParse(prec=EP.Compare)}
op:=TT.Is
e=IsPattern(e, op)
// 'as' or 'using' cast (special case: #usingCast instead of #using)
| &{@[Local] context.CanParse(prec=EP.Compare)}
op:=(TT.As | TT.Using)
rhs:=DataType(true)
{e = F.Call(op.Type() == TT.Using ? S.UsingCast : S.As, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex, op.StartIndex, op.EndIndex);}
| // Shift operators (two LT or GT in a row)
&{@[Local] context.CanParse(EP.Shift)}
&{LT($LI).EndIndex == LT($LI+1).StartIndex}
( op:="<" "<" rhs:=SubExpr(EP.Shift)
{e = F.Call(S.Shl, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex, op.StartIndex, op.EndIndex + 1, NodeStyle.Operator);}
| op:=">" ">" rhs:=SubExpr(EP.Shift)
{e = F.Call(S.Shr, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex, op.StartIndex, op.EndIndex + 1, NodeStyle.Operator);}
)
| // Conditional operator
&{@[Local] context.CanParse(EP.IfElse)}
op:="?" then:=SubExpr(StartExpr) ":" else:=SubExpr(EP.IfElse)
{e = F.Call(S.QuestionMark, LNode.List(e, then, @else), e.Range.StartIndex, else.Range.EndIndex,
op.StartIndex, op.EndIndex, NodeStyle.Operator);}
)*
{return e;}
};
@[recognizer(fn Scan_IsPattern())]
@[private] token IsPattern(lhs::LNode, isTok::Token)::LNode // 'token' is used to avoid long analysis in LLLPG
@{
{argList::VList!LNode = (new VList!LNode(lhs));}
target:=DataType(true)
// C# 7 allows you to declare a variable as part of "is" expression
[targetName:=IdAtom {target = F.Call(S.Var, target, targetName, target.Range.StartIndex, targetName.Range.EndIndex);}]?
{argList.Add(target);}
// EC# allows an argument list for recursive deconstruction
[ "(" ")" {argList.Add(F.List(ExprListInside($"(", allowUnassignedVarDecl: true), $"(".StartIndex, $")".EndIndex));} ]?
{return F.Call(isTok, argList, lhs.Range.StartIndex, argList.Last.Range.EndIndex);}
};
// An expression that can start with attributes [...], attribute keywords
// (out, ref, public, etc.), a named argument (a: expr) and/or a variable
// declaration (Foo? x = null).
@[FullLLk, public] rule ExprStart(allowUnassignedVarDecl::bool)::LNode @{
// Detect "keyword argument" expression
{argName::Token = default(Token);}
(argName=(TT.Id|TT.ContextualKeyword)|argName=LinqKeywordAsId) colon:=":"
result:ExprStartNNP(allowUnassignedVarDecl)
{result = F.Call(S.NamedArg, F.Id(argName), result, argName.StartIndex, result.Range.EndIndex, colon.StartIndex, colon.EndIndex, NodeStyle.Operator);}
/ result:ExprStartNNP(allowUnassignedVarDecl)
};
// ExprStart with No Named Parameter allowed
@[public] rule ExprStartNNP(allowUnassignedVarDecl::bool)::LNode @{
{var attrs = VList!LNode.Empty;}
hasList:=NormalAttributes(ref attrs)
AttributeKeywords(ref attrs)
(SubExpr => {
// Unassigned var decl is allowed when attributes are present (e.g. out)
if (!attrs.IsEmpty || hasList) { allowUnassignedVarDecl = true; };
// PEG-style parse: try one thing, then the other.
expr::LNode;
var(result::TentativeResult, _::TentativeResult);
if (allowUnassignedVarDecl) {
expr = TentativeVarDecl(attrs, out result, allowUnassignedVarDecl)
?? TentativeExpr(attrs, out result);
} else {
expr = TentativeExpr(attrs, out result);
// If parsing as expression succeeds but it's an assignment with
// > on the RHS, try parsing as a var decl too (consider `List<Foo>x=0`)
if expr == null || (expr.Calls(S.Assign, 2) && expr.Args[0].Calls(S.GT, 2)) {
InputPosition = result.OldPosition;
expr = TentativeVarDecl(attrs, out _, allowUnassignedVarDecl);
};
};
expr ??= Apply(result);
return expr;
})
};
// Helper functions for parsing normal expressions and var-decl expressions
// TODO: upgrade to use newer LeMP macros that are easier to understand
unroll ((TentativeFunction; TentativeCode) `in` (
(TentativeExpr; #splice(
result.Result = SubExpr(StartExpr).PlusAttrs(attrs);
// A var decl like "A B" looks like an expression followed by
// an identifier. To cede victory to VarDeclExpr, detect that
// the expression didn't end properly and emit an error.
if LA0 != EOF && LA0 != TT.Semicolon && LA0 != TT.Comma && !(LA0 == TT.LinqKeyword && _insideLinqExpr) {
failed = @true;
};
));
(TentativeVarDecl; #splice(
_::int;
var cat = DetectStatementCategoryAndAddWordAttributes(out _, ref attrs, DetectionMode.Expr);
if (cat != StmtCat.MethodOrPropOrVar) {
failed = @true;
result.Result = F.Missing;
} else {
hasInitializer::bool;
result.Result = VarDeclExpr(out hasInitializer, attrs);
if (!hasInitializer && !allowUnassigned) {
Error(-1, "An unassigned variable declaration is not allowed in this context");
};
};
));
)) {
// Parses an expression (TentativeExpr) or variable declaration (TentativeVarDecl).
// Returns the parsed node on success or null if outer-level parse error(s)
// occurred; the out param result is never null, and in case of success it
// is the same as the return value. Error handling is tricky... we fail if
// there are errors at the current level, not if there are errors in
// parenthesized subexpressions.
fn TentativeFunction(attrs::VList!LNode, out result::TentativeResult, allowUnassigned::bool = false)::LNode
{
result = (new TentativeResult(InputPosition));
var oldState = _tentative;
_tentative = (new TentativeState(@true));
{
on_finally { _tentative = oldState; };
failed::bool = false;
TentativeCode; // sets the result variable
result.Errors = _tentative.DeferredErrors;
result.InputPosition = InputPosition;
if failed || _tentative.LocalErrorCount != 0 {
// error(s) occurred.
InputPosition = result.OldPosition;
return @null;
};
};
return Apply(result); // must Apply after finally block
};
};
fn Apply(result::TentativeResult)::LNode
{
InputPosition = result.InputPosition;
if result.Errors != null {
result.Errors.WriteListTo(CurrentSink(false));
};
return result.Result;
};
@[private] rule VarDeclExpr(out hasInitializer::bool, VList<LNode> attrs)::LNode @{
[ t:=TT.This {attrs.Add(F.Id(t));} ]?
pair:=VarDeclStart
{var(type::LNode = pair.Item1, name::LNode = pair.Item2);}
( // A property is allowed whereever an initialized variable is
// allowed, to make possible `Constructor(public int Prop {get;}) {}`
result:RestOfPropertyDefinition(type.Range.StartIndex, type, name, true)
{hasInitializer = true;}
/ nameAndInit:=VarInitializerOpt(name, IsArrayType(type))
{
hasInitializer = (nameAndInit != name);
var typeStart = type.Range.StartIndex;
var start = attrs.IsEmpty ? typeStart : attrs[0].Range.StartIndex;
$result = F.Call(S.Var, type, nameAndInit,
start, nameAndInit.Range.EndIndex, typeStart, typeStart);
hasInitializer = @true;
}
)
{$result = $result.PlusAttrs(attrs);}
};
@[private] rule VarDeclStart::Pair!(LNode, LNode) @{
e:=DataType
id:=IdAtom
{MaybeRecognizeVarAsKeyword(ref e);}
{return Pair.Create(e, id);}
};
@[#static, #readonly] _var::Symbol = GSymbol.Get("var");
@[private] fn MaybeRecognizeVarAsKeyword(ref type::LNode)
{
// Recognize "var" (but not @var) as a contextual keyword.
rng::SourceRange;
name::Symbol = type.Name;
if (name == _var) && type.IsId
&& (rng=type.Range).Source.Text.TryGet(rng.StartIndex, '\0') != '@' {
type = type.WithName(S.Missing);
};
};
@[private] rule ExprInParens(allowUnassignedVarDecl::bool)::LNode
@{
lp:="(" rp:=")"
{
// Note: we invoke ExprInParensOrTuple inside an action, hiding the
// invocation from LLLPG, to avoid creating a recognizer for Expr.
if (!Down(lp)) { return F.Call(S.Tuple, lp.StartIndex, rp.EndIndex, lp.StartIndex, lp.EndIndex); };
return Up(InParens_ExprOrTuple(allowUnassignedVarDecl, lp.StartIndex, rp.EndIndex));
}
};
// Called inside parens by ExprInParens
rule InParens_ExprOrTuple(allowUnassignedVarDecl::bool, startIndex::int, endIndex::int)::LNode @
{ // We're parsing a token tree so EOF could represent ")" or "]" or "}"
EOF =>
{return F.Tuple(VList!LNode.Empty, startIndex, endIndex);}
/ {var hasAttrList = LA0 == TT.LBrack;}
e:=ExprStart(allowUnassignedVarDecl)
{var list = (new VList!LNode() { e });}
nongreedy[
"," list+=ExprStart(allowUnassignedVarDecl)
]*
{isTuple::bool = list.Count > 1;}
["," {isTuple = true;}]? EOF
{
if isTuple {
return F.Tuple(list, startIndex, endIndex);
} else {
return hasAttrList ? e : F.InParens(e, startIndex, endIndex);
};
}
};
@[private] rule BracedBlockOrTokenLiteral(spaceName::Symbol = @null, target::Symbol = @null, startIndex::int = -1)::LNode
@{ result:BracedBlock(spaceName, target, startIndex)
| result:TokenLiteral
};
@[private] rule BracedBlock(spaceName::Symbol = @null, target::Symbol = @null, startIndex::int = -1)::LNode
@{
{ var oldSpace = _spaceName;
_spaceName = spaceName ?? oldSpace;
}
"{" "}"
{ if (startIndex == -1) { startIndex = $"{".StartIndex; };
var stmts = StmtListInside($"{");
_spaceName = oldSpace;
return F.Call(target ?? S.Braces, stmts,
startIndex, $"}".EndIndex, $"{".StartIndex, $"{".EndIndex, NodeStyle.Statement);
}
};
// ---------------------------------------------------------------------
// -- Attributes -------------------------------------------------------
// ---------------------------------------------------------------------
@[recognizer(fn Scan_NormalAttributes())]
token NormalAttributes(ref attrs::VList!LNode)::bool @{
( &!{Down($LI) && Up(Try_Scan_AsmOrModLabel(0))}
t:="[" "]"
{
$result = true;
if (Down(t)) {
AttributeContents(ref attrs);
Up();
};
}
)*
};
token AttributeContents(ref attrs::VList!LNode) @{
{attrTarget::Token = default(Token);}
( attrTarget=(TT.Id|TT.ContextualKeyword|TT.LinqKeyword|TT.Return) ":"
{newAttrs::VList!LNode = (new VList!LNode());}
ExprList(ref newAttrs, allowTrailingComma: true, allowUnassignedVarDecl: true)
{
var attrTargetId = F.Id(attrTarget);
for (i::int = 0; i < newAttrs.Count; i++) {
var attr = newAttrs[i];
if (!IsNamedArg(attr)) {
attr = SetOperatorStyle(F.Call(S.NamedArg, attrTargetId, attr,
i == 0 ? attrTarget.StartIndex : attr.Range.StartIndex, attr.Range.EndIndex));
} else {
Error(attrTargetId = attrs[i].Args[0], "Syntax error: only one attribute target is allowed");
};
attrs.Add(attr);
};
}
/ ExprList(ref attrs, allowTrailingComma: true, allowUnassignedVarDecl: true)
)
};
fn IsNamedArg(node::LNode)::bool { return node.Calls(S.NamedArg, 2) && node.BaseStyle == NodeStyle.Operator; };
token AttributeKeywords(ref attrs::VList!LNode) @{
[ t:=TT.AttrKeyword
{attrs.Add(F.Id(t));}
]*
};
@[recognizer(fn Scan_TParamAttributeKeywords())]
token TParamAttributeKeywords(ref attrs::VList!LNode) @{
[ t:=(TT.AttrKeyword|TT.In)
{attrs.Add(F.Id(t));}
]*
};
// =====================================================================
// == LINQ =============================================================
// =====================================================================
@[public] rule LinqQueryExpression::LNode @{
{
startIndex::int = LT0.StartIndex;
_insideLinqExpr = true;
on_finally { _insideLinqExpr = false; };
var parts = LNode.List();
}
parts+=LinqFromClause
QueryBody(ref parts)
{return F.Call(S.Linq, parts, startIndex, parts.Last.Range.EndIndex, startIndex, startIndex);}
};
@[private] rule LinqFromClause::LNode @{
&{@[Hoist] Is($LI, @@from)} kw:=TT.LinqKeyword
((TT.Id|TT.ContextualKeyword|"$") =>)
e:=Var_In_Expr
{return F.Call(S.From, e, kw.StartIndex, e.Range.EndIndex, kw.StartIndex, kw.EndIndex);}
};