-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.py
1938 lines (1750 loc) · 48.5 KB
/
parse.py
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
import preprocess
import symbol_read
import string
from termcolor import colored
# a procedural program for parsing
# based on the EBNF rules in https://golang.org/ref/spec
#state variables
file = None
symbol = None
line_no = None
column_no = None
prev_isspace = False
#helper
def open_symbolic_file(filename):
global file
file = open(filename)
file = preprocess.preprocess(file)
file = symbol_read.read_symbols(file)
def read_one_symbol():
global symbol, line_no, column_no, prev_isspace
symbol, line_no, column_no, prev_isspace = next(file)
def output_error_and_halt():
#implement ouput error here
print("error")
print("symbol", symbol, "line_no", line_no, "column_no", column_no)
raise SystemExit
def main(filename):
try:
#main program
open_symbolic_file(filename)
read_one_symbol()
#call start symbol
nt_SourceFile()
#output if no error
print("=========================================")
with open(filename) as file:
for line in file:
print(line,end='')
print()
print("=========================================")
print("no error was found. file syntax is valid")
except SystemExit as e:
print("specifically in the file please see below")
print("=========================================")
if line_no!="last":
#output final error
with open(filename) as file:
l=1
for line in file:
c_no=1
for c in line:
if l==line_no and c_no >= column_no and c_no<column_no+len(symbol):
print(colored(c,'red'),end='')
elif (l==line_no and c_no > column_no) or (l>line_no):
print(colored(c,'grey'),end='')
else:
print(c,end='')
c_no=c_no+1
l=l+1
print('\033[0m')
else:
with open(filename) as file:
for line in file:
print(line,end='')
print()
print(colored('_','red'))
print("=========================================")
print("error! see above")
#GRAMMAR IMPLEMENTATION HERE
# | | | |
# v v v v
def accept(T):
global symbol
if T == symbol:
read_one_symbol()
else:
output_error_and_halt()
def acceptset(Ts):
global symbol
if symbol in Ts:
read_one_symbol()
else:
output_error_and_halt()
def acceptsemicolon():
#this is to abide to the specification's semicolon ignorance rule no. 2:
# To allow complex statements to occupy a single line, a semicolon may be omitted before a closing ")" or "}".
global symbol
if symbol==";":
read_one_symbol()
elif symbol!="}" and symbol != ")":
output_error_and_halt()
#all nonterminal symbols
#format: nt_<symbol_name>
# <newline> ::= /* the Unicode code point U+000A */
def nt_newline():
accept('\n')
# <unicode_char> ::= /* an arbitrary Unicode code point except newline */
def nt_unicode_char():
accept(symbol)
# <unicode_letter> ::= /* a Unicode code point classified as "Letter" */
def nt_unicode_letter():
if symbol in set(string.ascii_letters):
accept(symbol)
# <unicode_digit> ::= /* a Unicode code point classified as "Number, decimal digit" */
def nt_unicode_digit():
if symbol in set(string.digits):
accept(symbol)
# <letter> ::= unicode_letter | "_"
def nt_letter():
if symbol == "_":
accept("_")
elif symbol in set(string.ascii_letters):
accept(symbol)
else:
output_error_and_halt()
# <decimal_digit> ::= "0" … "9"
def nt_decimal_digit():
if symbol in set(string.digits):
accept(symbol)
# <octal_digit> ::= "0" … "7"
def nt_octal_digit():
if symbol in set(string.digits):
accept(symbol)
# <hex_digit> ::= "0" … "9" | "A" … "F" | "a" … "f"
def nt_hex_digit():
if symbol in set(string.digits):
accept(symbol)
elif symbol in set({"A","B","C","D","E","F","a","b","c","d","e","f"}):
accept(symbol)
import traceback
# <identifier> ::= letter { letter | unicode_digit }
def nt_identifier():
nt_letter()
while symbol in set(string.ascii_letters+string.digits+"_") and not prev_isspace:
if symbol in set(string.ascii_letters+"_"):
nt_letter()
elif symbol in set(string.digits):
nt_unicode_digit()
# <int_lit> ::= decimal_lit | octal_lit | hex_lit
def nt_int_lit():
if symbol in set(string.digits):
nt_decimal_lit()
if symbol in set(string.octdigits):
nt_octal_lit()
if symbol in set(string.hexdigits):
nt_hex_lit()
# <decimal_lit> ::= ( "1" … "9" ) { decimal_digit }
def nt_decimal_lit():
if symbol == '1':
accept('1')
elif symbol == '2':
accept('2')
elif symbol == '3':
accept('3')
elif symbol == '4':
accept('4')
elif symbol == '5':
accept('5')
elif symbol == '6':
accept('6')
elif symbol == '7':
accept('7')
elif symbol == '8':
accept('8')
elif symbol == '9':
accept('9')
else:
output_error_and_halt()
while symbol in set(string.digits):
nt_decimal_digit()
# <octal_lit> ::= "0" { octal_digit }
def nt_octal_lit():
accept("0")
while symbol in set(string.octdigits):
nt_octal_digit()
# <hex_lit> ::= "0" ( "x" | "X" ) hex_digit { hex_digit }
def nt_hex_lit():
accept("0")
if symbol == "x":
accept("x")
elif symbol == "X":
accept("X")
else:
output_error_and_halt()
nt_hex_digit()
while symbol in set(string.hexdigits):
nt_hex_digit()
# <float_lit> ::= decimals "." [ decimals ] [ exponent ] | decimals exponent | "." decimals [ exponent ]
def nt_float_lit():
if symbol == ".":
accept(".")
nt_decimals()
if symbol in set({"e","E"}):
nt_exponent()
else:
nt_decimals()
accept(".")
if symbol in set(string.digits):
nt_decimals()
if symbol in set({"e","E"}):
nt_exponent()
# <decimals> ::= decimal_digit { decimal_digit }
def nt_decimals():
nt_decimal_digit()
while symbol in set(string.digits):
nt_decimal_digit()
# <exponent> ::= ( "e" | "E" ) [ "+" | "-" ] decimals
def nt_exponent():
if symbol == "e":
accept("e")
elif symbol == "E":
accept("E")
else:
output_error_and_halt()
if symbol == "+":
accept("+")
elif symbol == "-":
accept("-")
nt_decimals()
# <imaginary_lit> ::= (decimals | float_lit) "i"
def nt_imaginary_lit():
if symbol in set(string.digits):
nt_decimals()
elif symbol == ".":
float_lit()
accept("i")
# <rune_lit> ::= " ' " ( unicode_value | byte_value ) " ' "
# <rune_lit> ::= " ' " ( unicode_value_or_byte_value ) " ' "
def nt_rune_lit():
accept("'")
nt_unicode_or_byte_value()
accept("'")
# <unicode_value> ::= unicode_char | little_u_value | big_u_value | escaped_char
def nt_unicode_value():
if symbol != "\\":
nt_unicode_char()
else:
accept("\\")
if symbol == "u":
nt_little_u_value()
elif symbol == "U":
nt_big_u_value()
else:
nt_escaped_char()
def nt_unicode_value_or_byte_value():
if symbol!='\\':
accept(symbol)
else:
accept("\\")
if symbol in {"a","b","f","n","r","t","v",'\\', "'", '"'}:
accept(symbol)
elif symbol=="x":
accept("x")
nt_hex_digit()
nt_hex_digit()
elif symbol=="u":
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
elif symbol=="U":
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
else:
nt_octal_digit()
nt_octal_digit()
nt_octal_digit()
def is_unicode_value(symbol):
return len(symbol)==1 and symbol!="\n"
# <byte_value> ::= octal_byte_value | hex_byte_value
def nt_byte_value():
if symbol == "x":
nt_hex_byte_value()
else:
nt_octal_byte_value()
# <octal_byte_value> ::= `\` octal_digit octal_digit octal_digit
def nt_octal_byte_value():
nt_octal_digit()
nt_octal_digit()
nt_octal_digit()
# <hex_byte_value> ::= `\` "x" hex_digit hex_digit
def nt_hex_byte_value():
accept("x")
nt_hex_digit()
nt_hex_digit()
# <little_u_value> ::= `\` "u" hex_digit hex_digit hex_digit hex_digit
def nt_little_u_value():
# accept('\\')
accept("u")
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
# <big_u_value> ::= `\` "U" hex_digit hex_digit hex_digit hex_digit hex_digit hex_digit hex_digit hex_digit
def nt_big_u_value():
# accept('\\')
accept("U")
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
nt_hex_digit()
# <escaped_char> ::= `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` )
def nt_escaped_char():
# accept('\\')
if symbol == "a":
accept("a")
elif symbol == "b":
accept("b")
elif symbol == "f":
accept("f")
elif symbol == "n":
accept("n")
elif symbol == "r":
accept("r")
elif symbol == "t":
accept("t")
elif symbol == "v":
accept("v")
elif symbol == "\\":
accept("\\")
elif symbol == "'":
accept("'")
elif symbol == '"':
accept('"')
# <string_lit> ::= raw_string_lit | interpreted_string_lit
def nt_string_lit():
if symbol == "`":
nt_raw_string_lit()
elif symbol == '"':
nt_interpreted_string_lit()
# <raw_string_lit> ::= "`" { unicode_char | newline } "`"
def nt_raw_string_lit():
accept("`")
while symbol!="`":
if symbol == "\n":
nt_newline()
else:
nt_unicode_char()
accept("`")
# <interpreted_string_lit> ::= `"` { unicode_value | byte_value } `"`
# THIS IS NOT LL(1)
# change to: <interpreted_string_lit> ::= `"` { unicode_or_byte_value } `"`
def nt_interpreted_string_lit():
accept('"')
while symbol != '"':
nt_unicode_or_byte_value()
accept('"')
# added a new rule:
# <unicode_or_byte_value> ::= unicode_char | "\\" ( little_u_value | big_u_value | escaped_char | byte_value )
def nt_unicode_or_byte_value():
if symbol!="\\":
nt_unicode_char()
else:
accept("\\")
if symbol=="u":
nt_little_u_value()
elif symbol=="U":
nt_big_u_value()
elif symbol in {"a", "b", "f", "n", "r","t", "v", "\\", "'", '"' }:
nt_escaped_char()
else:
nt_byte_value()
# <Type> ::= TypeName | TypeLit | "(" Type ")"
def nt_Type():
if symbol == "(":
accept("(")
nt_Type()
accept(")")
elif symbol in set({"[","struct","*","func","interface","map","chan","<-"}):
nt_TypeLit()
elif symbol in set(string.ascii_letters).union({"_"}):
nt_TypeName()
# <TypeName> ::= identifier | QualifiedIdent
# change to: <TypeName> ::= identifier [ "." identifier ]
def nt_TypeName():
if symbol in set(string.ascii_letters).union({"_"}):
nt_identifier()
if symbol==".":
accept(".")
nt_identifier()
# <TypeLit> ::= ArrayType | StructType | PointerType | FunctionType | InterfaceType | SliceType | MapType | ChannelType
def nt_TypeLit():
if symbol == "[":
nt_ArrayOrSliceType()
elif symbol == "struct":
nt_StructType()
elif symbol == "*":
nt_PointerType()
elif symbol == "func":
nt_FunctionType()
elif symbol == "interface":
nt_InterfaceType()
elif symbol == "map":
nt_MapType()
else:
nt_ChannelType()
# <ArrayOrSliceType> ::= "[" [ ArrayLength ] "]" ElementType
def nt_ArrayOrSliceType():
accept("[")
if symbol!="]":
nt_ArrayLength()
accept("]")
nt_ElementType()
# <ArrayType> ::= "[" ArrayLength "]" ElementType
def nt_ArrayType():
accept("[")
nt_ArrayLength()
accept("]")
nt_ElementType()
# <ArrayLength> ::= Expression
def nt_ArrayLength():
nt_Expression()
# <ElementType> ::= Type
def nt_ElementType():
nt_Type()
# <SliceType> ::= "[" "]" ElementType
def nt_SliceType():
accept("[]")
nt_ElementType()
# <StructType> ::= "struct" "{" { FieldDecl ";" } "}"
def nt_StructType():
accept("struct")
accept("{")
while symbol in set(string.ascii_letters).union({"_","*"}):
nt_FieldDecl()
acceptsemicolon()
accept("}")
# <FieldDecl> ::= (IdentifierList Type | EmbeddedField) [ Tag ]
def nt_FieldDecl():
if symbol in set(string.ascii_letters).union({"_"}):
nt_IdentifierList()
nt_Type()
elif symbol in set(string.ascii_letters).union({"_","*"}):
nt_EmbeddedField()
else:
output_error_and_halt()
if symbol in {"'",'"',"`"}:
nt_Tag()
# <EmbeddedField> ::= [ "*" ] TypeName
def nt_EmbeddedField():
if symbol == "*":
accept("*")
nt_TypeName()
# <Tag> ::= string_lit
def nt_Tag():
nt_string_lit()
# <PointerType> ::= "*" BaseType
def nt_PointerType():
accept("*")
nt_BaseType()
# <BaseType> ::= Type
def nt_BaseType():
nt_Type()
# <FunctionType> ::= "func" Signature
def nt_FunctionType():
accept("func")
nt_Signature()
# <Signature> ::= Parameters [ Result ]
def nt_Signature():
nt_Parameters()
if symbol in set(string.ascii_letters).union({"(","_"}).union({"[","struct","*","func","interface","map","chan","<-"}):
nt_Result()
# <Result> ::= Parameters | Type
def nt_Result():
if symbol == "(":
nt_Parameters()
elif symbol in set(string.ascii_letters).union({"(","_"}).union({"[","struct","*","func","interface","map","chan","<-"}):
nt_Type()
# <Parameters> ::= "(" [ ParameterList [ "," ] ] ")"
def nt_Parameters():
accept("(")
if symbol in set(string.ascii_letters).union({"(","_"}).union({"[","struct","*","func","interface","map","chan","<-"}):
nt_ParameterList()
if symbol == ",":
accept(",")
accept(")")
# <ParameterList> ::= ParameterDecl { "," ParameterDecl }
def nt_ParameterList():
nt_ParameterDecl()
while symbol == ",":
accept(",")
nt_ParameterDecl()
# <ParameterDecl> ::= [ IdentifierList ] [ "..." ] Type
def nt_ParameterDecl():
if symbol in set(string.ascii_letters).union({"_"}):
nt_IdentifierList()
if symbol == "...":
accept("...")
nt_Type()
# <InterfaceType> ::= "interface" "{" { MethodSpec ";" } "}"
def nt_InterfaceType():
accept("interface")
accept("{")
while symbol in set(string.ascii_letters).union({"_"}):
nt_MethodSpec()
acceptsemicolon()
accept("}")
# <MethodSpec> ::= MethodName Signature | InterfaceTypeName
def nt_MethodSpec():
if symbol in set(string.ascii_letters).union({"_"}):
nt_MethodName()
nt_Signature()
elif symbol in set(string.ascii_letters).union({"_"}):
nt_InterfaceTypeName()
# <MethodName> ::= identifier
def nt_MethodName():
nt_identifier()
# <InterfaceTypeName> ::= TypeName
def nt_InterfaceTypeName():
nt_TypeName()
# <MapType> ::= "map" "[" KeyType "]" ElementType
def nt_MapType():
accept("map")
accept("[")
nt_KeyType()
accept("]")
nt_ElementType()
# <KeyType> ::= Type
def nt_KeyType():
nt_Type()
# <ChannelType> ::= ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType
def nt_ChannelType():
if symbol == "chan":
accept("chan")
if symbol == "<-":
accept("<-")
elif symbol == "<-":
accept("<-")
accept("chan")
else:
output_error_and_halt()
nt_ElementType()
# <Block> ::= "{" StatementList "}"
def nt_Block():
accept("{")
nt_StatementList()
accept("}")
# <StatementList> ::= { Statement ";" }
def nt_StatementList():
while symbol in set(string.ascii_letters+'.').union({"_"}).union({"const", "type", "var","go","return","break","continue","goto","fallthrough","{","if","switch","select","for","defer"}).union(nt_unary_op_set).union(nt_literal_first_set).union({"("}):
nt_Statement()
acceptsemicolon()
# <Declaration> ::= ConstDecl | TypeDecl | VarDecl
def nt_Declaration():
if symbol == "const":
nt_ConstDecl()
elif symbol == "type":
nt_TypeDecl()
elif symbol == "var":
nt_VarDecl()
else:
output_error_and_halt()
# <TopLevelDecl> ::= Declaration | FunctionDecl | MethodDecl
# change to:
# <TopLevelDecl> ::= Declaration | "func" ( MethodDecl | FunctionDecl )
# MethodDecl and FunctionDecl is also changed
def nt_TopLevelDecl():
if symbol in set({"const", "type", "var"}):
nt_Declaration()
elif symbol == "func":
accept("func")
if symbol == "(":
nt_MethodDecl()
elif symbol in set(string.ascii_letters).union({"_","("}):
nt_FunctionDecl()
# <ConstDecl> ::= "const" ( ConstSpec | "(" { ConstSpec ";" } ")" )
def nt_ConstDecl():
accept("const")
if symbol in set(string.ascii_letters+"_").union({"_","("}):
if symbol == "(":
accept("(")
while symbol in set(string.ascii_letters+"_"):
nt_ConstSpec()
acceptsemicolon()
accept(")")
else:
nt_ConstSpec()
# <ConstSpec> ::= IdentifierList [ [ Type ] "=" ExpressionList ]
def nt_ConstSpec():
nt_IdentifierList()
if symbol in set(string.ascii_letters+"_=").union({"(","[","struct","*","func","interface","map","chan","<-"}):
if symbol in set(string.ascii_letters+"_").union({"(","[","struct","*","func","interface","map","chan","<-"}):
nt_Type()
accept("=")
nt_ExpressionList()
# <IdentifierList> ::= identifier { "," identifier }
def nt_IdentifierList():
nt_identifier()
while symbol == ",":
accept(",")
nt_identifier()
# <ExpressionList> ::= Expression { "," Expression }
def nt_ExpressionList(mightFollowBlock=False):
nt_Expression(mightFollowBlock)
while symbol == ",":
accept(",")
nt_Expression(mightFollowBlock)
# <TypeDecl> ::= "type" ( TypeSpec | "(" { TypeSpec ";" } ")" )
def nt_TypeDecl():
accept("type")
if symbol in set(string.ascii_letters).union({"_"}):
nt_TypeSpec()
elif symbol == "(":
accept("(")
while symbol in set(string.ascii_letters).union({"_"}):
nt_TypeSpec()
acceptsemicolon()
accept(")")
else:
output_error_and_halt()
# <TypeSpec> ::= AliasDecl | TypeDef
# change to:
# <TypeSpec> ::= identifier [ "=" ] Type
def nt_TypeSpec():
nt_identifier()
if symbol== "=":
accept("=")
nt_Type()
# <AliasDecl> ::= identifier "=" Type
def nt_AliasDecl():
nt_identifier()
accept("=")
nt_Type()
# <TypeDef> ::= identifier Type
def nt_TypeDef():
nt_identifier()
nt_Type()
# <VarDecl> ::= "var" ( VarSpec | "(" { VarSpec ";" } ")" )
def nt_VarDecl():
accept("var")
if symbol == "(":
accept("(")
while symbol in set(string.ascii_letters).union({"_"}):
nt_VarSpec()
acceptsemicolon()
accept(")")
elif symbol in set(string.ascii_letters).union({"_"}):
nt_VarSpec()
else:
output_error_and_halt()
# <VarSpec> ::= IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList )
def nt_VarSpec():
nt_IdentifierList()
if symbol == "=":
accept("=")
nt_ExpressionList()
elif symbol in set(string.ascii_letters).union({"_","(","[","struct","*","func","interface","map","chan","<-"}):
nt_Type()
if symbol == "=":
accept("=")
nt_ExpressionList()
else:
output_error_and_halt()
# <ShortVarDecl> ::= IdentifierList ":=" ExpressionList
def nt_ShortVarDecl():
nt_IdentifierList()
accept(":=")
nt_ExpressionList()
# <FunctionDecl> ::= "func" FunctionName Signature [ FunctionBody ]
# change to: <FunctionDecl> ::= "func" FunctionName Signature [ FunctionBody ]
def nt_FunctionDecl():
nt_FunctionName()
nt_Signature()
if symbol == "{":
nt_FunctionBody()
# <FunctionName> ::= identifier
def nt_FunctionName():
nt_identifier()
# <FunctionBody> ::= Block
def nt_FunctionBody():
nt_Block()
# <MethodDecl> ::= "func" Receiver MethodName Signature [ FunctionBody ]
# change to: <MethodDecl> ::= Receiver MethodName Signature [ FunctionBody ]
def nt_MethodDecl():
nt_Receiver()
nt_MethodName()
nt_Signature()
if symbol == "{":
nt_FunctionBody()
# <Receiver> ::= Parameters
def nt_Receiver():
nt_Parameters()
# <Operand> ::= Literal | OperandName | "(" Expression ")"
def Operand():
if symbol in set(string.ascii_letters+"_"):
nt_OperandName()
elif symbol == "(":
accept("(")
nt_Expression()
accept(")")
else:
nt_Literal()
nt_literal_first_set = set(string.digits+".'`"+'"').union({"struct","[","map","func"})
# <Literal> ::= BasicLit | CompositeLit | FunctionLit
def nt_Literal():
if symbol in set(string.digits+".'`"+'"'):
nt_BasicLit()
elif symbol in {"struct","[","map"}.union(set(string.ascii_letters+'_')):
nt_CompositeLit()
elif symbol == "func":
nt_FunctionLit()
else:
output_error_and_halt()
# <BasicLit> ::= int_lit | float_lit | imaginary_lit | rune_lit | string_lit
# change to: <BasicLit> ::= numeric_lit | rune_lit | string_lit
def nt_BasicLit():
if symbol in set(string.digits+"."):
nt_numeric_lit()
elif symbol=="'":
nt_rune_lit()
elif symbol in set('"`'):
nt_string_lit()
else:
output_error_and_halt()
# added rule: <numeric_lit> ::= decimal_lit [ "." [ decimals ] ] [ exponent ] |
# "0" ( ( "x" | "X" ) hex_digit { hex_digit } |
# { decimal_digit } [ "." [ decimals ] ] [ exponent ] |
# "." decimals [ exponent ]
# (we assume that octal_digit is included in decimal_digit, although it might output "malformed integer")
def nt_numeric_lit():
if symbol in set("123456789"):
nt_decimal_lit()
if symbol==".":
accept(".")
if symbol in set(string.digits):
nt_decimals()
if symbol in {"e","E"}:
nt_exponent()
elif symbol=="0":
accept("0")
if symbol in {"x","X"}:
acceptset({"x","X"})
nt_hex_digit()
while symbol in set(string.hexdigits):
nt_hex_digit()
elif symbol in set(string.digits+".eE"):
while symbol in set(string.digits):
nt_decimal_digit()
if symbol==".":
accept(".")
if symbol in set(string.digits):
nt_decimals()
if symbol in {"e","E"}:
nt_exponent()
elif symbol==".":
accept(".")
nt_decimals()
if symbol in {"e","E"}:
nt_exponent()
else:
output_error_and_halt()
if symbol=="i":
accept("i")
# <OperandName> ::= identifier | QualifiedIdent.
# NOT LL(1)
# change to: <OperandName> ::= identifier [ "." identifier]
def nt_OperandName():
nt_identifier()
if symbol==".":
accept(".")
nt_identifier()
# <QualifiedIdent> ::= PackageName "." identifier
def nt_QualifiedIdent():
nt_PackageName()
accept(".")
nt_identifier()
# <CompositeLit> ::= LiteralType LiteralValue
def nt_CompositeLit():
nt_LiteralType()
nt_LiteralValue()
# <LiteralType> ::= StructType | ArrayType | "[" "..." "]" ElementType | SliceType | MapType | TypeName
def nt_LiteralType():
if symbol=="struct":
nt_StructType()
elif symbol=="[": #ArrayType or "[" "..." "]" ElementType or SliceType
accept("[")
if symbol=="...":
accept("...")
accept("]")
nt_ElementType()
elif symbol=="]":
accept("]")
nt_ElementType()
else:
nt_ArrayLength()
accept("]")
nt_ElementType()
elif symbol=="map":
nt_MapType()
elif symbol in set(string.ascii_letters+'_'):
nt_TypeName()
# <LiteralValue> ::= "{" [ ElementList [ "," ] ] "}"
# <ElementList> ::= KeyedElement { "," KeyedElement }
# this one is implementation for both LiteralValue and ElementList
# <LiteralValue> ::= "{" [ KeyedElement { "," KeyedElement } "," ] "}"
def nt_LiteralValue():
accept("{")
if symbol != "}":
nt_KeyedElement()
while symbol ==",":
accept(",")
if symbol != "}":
nt_KeyedElement()
accept("}")
# <KeyedElement> ::= [ Key ":" ] Element
# Key and element is the same, so:
def nt_KeyedElement():
nt_Element() #also works with key
if symbol==":":
accept(":")
nt_Element()
# <Key> ::= FieldName | Expression | LiteralValue
# not LL(1)
# FieldName is also covered in Expression, so:
def nt_Key():
if symbol != "{":
nt_Expression()
else:
nt_LiteralValue()
# <FieldName> ::= identifier
def nt_FieldName():
nt_identifier()
# <Element> ::= Expression | LiteralValue
def nt_Element():
if symbol!="{":
nt_Expression()
else:
nt_LiteralValue()
# <FunctionLit> ::= "func" Signature FunctionBody
def nt_FunctionLit():
accept("func")
nt_Signature()
nt_FunctionBody()
# <PrimaryExpr> ::= Operand | Conversion | MethodExpr | PrimaryExpr Selector | PrimaryExpr Index | PrimaryExpr Slice | PrimaryExpr TypeAssertion | PrimaryExpr Arguments
# FOLLOW(Selector) contains "." which is in FIRST(Selector)
# <PrimaryExpr> ::= ( identifier | Literal | "(" Expression ")" ) { SelectorOrTypeAssertion | IndexOrSlice }
# Literal can be CompositeLit, which can be LiteralType LiteralValue
# LiteralType can be TypeName, which is identifier | QualifiedIdent
# CompositeLit is skipped for now
def nt_PrimaryExprFront(mightFollowBlock=False):
if symbol in set(string.ascii_letters + "_"):
nt_identifier()
if symbol=="{" and not mightFollowBlock:
nt_LiteralValue()
elif symbol in {"(","[","struct","*","interface","map","chan"}:
count_openparentheses = 0
while symbol=="(":
accept("(")
count_openparentheses += 1
if symbol in {"[","struct","*","interface","map","chan"}: #obviously Type or LiteralType
if symbol=="[":
nt_LiteralType()
else:
nt_Type()
if symbol=="{": #CompositeLit
isConversion=False
nt_LiteralValue()
else:
isConversion=True
elif symbol=="<-": #might be ChannelType, might be not
accept("<-")
if symbol=="chan":
accept("chan")
nt_ElementType()
isConversion = True
else:
isConversion = False
nt_Expression()
else:
isConversion = False
nt_Expression()
while count_openparentheses > 0:
accept(")")
count_openparentheses -= 1
if isConversion: # "(" Expression [ "," ] ")"
accept("(")
nt_Expression()
if symbol==",":
accept(",")
accept(")")
elif symbol=="func":
nt_FunctionLitOrFunctionTypeConversionOrFunctionTypeCompositeLit()