-
Notifications
You must be signed in to change notification settings - Fork 7
/
parser.jc
1701 lines (1690 loc) · 53.6 KB
/
parser.jc
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 "System.jc"
import "ctobj.jc"
import "util.jc"
import System.Algorithm.*
import System.Console.*
import Util.*
import Ctobj.*
//////////////////////////////////////
//tokenization
module CharSet
auto charset(string e)
ok=new u32[8]
for i=0:7
ok[i]=0
inv=0
s=0
if e[0]=='^':
inv=1;s++
for(;s<e.n;s++)
if s+1<e.n&&e[s+1]=='-':
for(i=u32(u8(e[s]));i<=u32(u8(e[s+2]));i++)
ok[i>>5]|=(1u<<int(i&31u));
s+=2
else
ok[e[s]>>5]|=(1u<<int(u32(u8(e[s]))&31u));
if inv:
for i=0:7
ok[i]=~ok[i]
return ok
digits=charset("0-9")
digdot=charset("0-9.")
hexdigit=charset("0-9a-fA-F")
idhead=charset("_A-Za-z\200-\377")
idbody=charset("_0-9A-Za-z\200-\377")
spaces=charset("\r\t ")
spaces_newline=charset("\r\n\t ")
newlines=charset("\r\n")
inline has(u32[] ok,int c)
return !(c&0xffffff00)&&((ok[c>>5]>>(c&31))&1u);
TOK_TYPE=0x20000000
TOK_TYPE_MASK=-TOK_TYPE
TOK_CONST=1*TOK_TYPE
TOK_ID=2*TOK_TYPE
TOK_STRING=3*TOK_TYPE
TOK_EOF=4*TOK_TYPE
TOK_AA=int('e')
TOK_OO=int('f')
TOK_ADD_EQ=int('i')
TOK_SUB_EQ=int('j')
TOK_MUL_EQ=int('k')
TOK_DIV_EQ=int('l')
TOK_ADD_ADD=int('m')
TOK_SUB_SUB=int('n')
////////////////
TOK_MOD_EQ=int('o')
TOK_OR_EQ=int('p')
TOK_AND_EQ=int('q')
TOK_XOR_EQ=int('r')
TOK_LSHIFT_EQ=int('s')
TOK_RSHIFT_EQ=int('t')
g_sta_tr0=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,-1,-1,4,10,-1,3,-1,4,5,-1,6,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,9,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]
struct TToken
int tok
int epos0,epos1
auto tokenize(iptr ptr_start,int g_ignore_indents)
//we want feed to be zero-terminated
//merge all files to one big vector, add zeroes, and pass in the starting location
feed=g_feed
ptr=ptr_start
inline skipchars(u32[] cs)
while ptr<feed.n
ch=int(u8(feed[ptr]))
if !CharSet.has(cs,ch):return
ptr++
inline parseOperator()
ptr0=ptr
state=int(g_sta_tr0[int(feed[ptr])]);ptr++
switch state{
default:
ptr=ptr0
return
case 1:
ch=int(feed[ptr]);ptr++
if ch==']':return
ptr=ptr0
return
case 2:
return;
case 3:
//operator() should be allowed
ch=int(feed[ptr]);ptr++
if ch==')':return
ptr=ptr0
return
case 4:
ch=int(feed[ptr]);ptr++
if ch=='=':return
ptr--;return;
case 5:
ch=int(feed[ptr]);ptr++
if ch=='+':return
if ch=='=':return
ptr--;return;
case 6:
ch=int(feed[ptr]);ptr++
if ch=='-':return
if ch=='=':return
ptr--;return;
case 7:
ch=int(feed[ptr]);ptr++
if ch=='<':{state=4;break}
if ch=='=':return
ptr--;return;
case 8:
ch=int(feed[ptr]);ptr++
if ch=='=':return
if ch=='>':{state=4;break}
ptr--;return;
case 9:
ch=int(feed[ptr]);ptr++
if ch=='=':return
ptr--;return;
case 10:
ch=int(feed[ptr]);ptr++
if ch=='&':return
if ch=='=':return
ptr--;return;
case 11:
ch=int(feed[ptr]);ptr++
if ch=='=':return
if ch=='|':return
ptr--;return;
}
assert(state==4)
ch=int(feed[ptr]);ptr++
if ch=='=':return
ptr--;
return;
//////////////////////////
struct TBracket
int ch
iptr pos
inds=new int[]
brastk=new TBracket[]
toks=new TToken[]
ignore_indents=g_ignore_indents
last_significant_newline_position=-1L
last_line_comment_position=-1L
inline left_bracket(int ch0)
brastk.push(TBracket(){ch:ch0,pos:ptr})
if ch0=='{':
ignore_indents=g_ignore_indents
if !ignore_indents:
if inds.n:
ind0=inds.back()
else
ind0=0
inds.push(ind0|0x80000000)
else
ignore_indents=1
inline pop_indents()
//add } accordingly
//ignore the last dedent
while inds.n&&!(inds.back()&0x80000000)
if !(inds.back()&0x40000000):
toks.push(TToken(){tok:int('}'),epos0:int(ptr),epos1:int(ptr)})
inds.pop()
if inds.n:
inds.pop()
auto right_bracket(int ch0)
matcher=int(ch0==')'?'(':(ch0=='}'?'{':(ch0==']'?'[':'{')))
errored=0
err_pos=0
estr=string.NULL
while brastk.n&&brastk.back().ch!=matcher:
//compensate for the unmatching bracket
if !errored:
if ch0==0:
//EOF
error(ETYPE_ERROR,ptr,ptr,"the opening '@1' is not properly closed".Replace(["@1",string(char(brastk.back().ch))]))
else
error(ETYPE_ERROR,ptr,ptr+1,"the opening '@1' doesn't match the closing '@2'".Replace(["@1",string(char(brastk.back().ch)),"@2",string(char(ch0))]))
err_pos=int(brastk.back().pos)
estr=new string
errored=1
ch_poped=brastk.back().ch
matcher_ch_poped=char(ch_poped=='('?')':(ch_poped=='{'?'}':']'))
estr.push(matcher_ch_poped)
toks.push(TToken(){'tok':int(matcher_ch_poped),'epos0':int(ptr),'epos1':int(ptr)+1})
brastk.pop()
if ch_poped=='{'&&!g_ignore_indents:
pop_indents()
if errored:
if brastk.n:
epos_pop_to=brastk.back().pos+1
else
epos_pop_to=ptr_start
error(ETYPE_NOTE,ptr,ptr,"inserting '@1'".Replace(["@1",estr]))
if brastk.n:
error(ETYPE_NOTE,err_pos,err_pos+1,"the opening '@1' was here".Replace(["@1",string(char(brastk.back().ch))]))
else
error(ETYPE_NOTE,err_pos,err_pos+1,"the opening bracket was not found")
//error(ETYPE_NOTE,epos_pop_to,epos_pop_to,FormatAsText("automatically matching dangling opening brackets until here"))
if brastk.n:
ch_poped=brastk.back().ch
brastk.pop()
if ch_poped=='{'&&!g_ignore_indents:
pop_indents()
else
if !errored&&ch0:
error(ETYPE_ERROR,ptr,ptr+1,"the closing '@1' does not close any opening bracket".Replace(["@1",string(char(ch0))]))
return 0
if brastk.n&&brastk.back().ch!='{':
ignore_indents=1
else
ignore_indents=g_ignore_indents
return 1
for(;;)
skipchars(ignore_indents?CharSet.spaces_newline:CharSet.spaces)
ch=int(feed[ptr])
//numbers
if CharSet.has(CharSet.digits,ch):
//get the string representation
efeed0=ptr
efeed0_real=ptr
skipchars(CharSet.digits)
ch=int(feed[ptr])
isfloat=0
ishex=0
if ch=='x':
ptr++;ch=int(feed[ptr])
efeed0=ptr
skipchars(CharSet.hexdigit)
ishex=1
ch=int(feed[ptr])
else
if ch=='.':
isfloat=1;
ptr++;
skipchars(CharSet.digdot);
ch=int(feed[ptr])
if ch=='e'||ch=='E':
isfloat=1;
ptr++;ch=int(feed[ptr])
if ch=='-':
ptr++
skipchars(CharSet.digits)
ch=int(feed[ptr])
if isfloat:
if ch=='f':
val=i64(__float_as_int(feed[efeed0:ptr-1].ConvertToAsBinary(char).as(float)))
cid=getid_const(const_type(CTYPE_FLOAT,32),val)
ptr++
else
val=__double_as_longlong(feed[efeed0:ptr-1].ConvertToAsBinary(char).as(double))
cid=getid_const(const_type(CTYPE_FLOAT,64),val)
else
if ishex:
val=feed[efeed0:ptr-1].ConvertToAsBinary(char).asHex(i64)
else
val=feed[efeed0:ptr-1].ConvertToAsBinary(char).as(i64)
//actually parse the number, as double
t=const_type(CTYPE_INT,32)
if ch=='u'||ch=='U':
ptr++
ch=int(feed[ptr])
t=(t&~CTYPE_MASK)|CTYPE_UINT
if ch=='L':
ptr++
ch=int(feed[ptr])
if ch=='L':
ptr++
ch=int(feed[ptr])
t=const_type(t&CTYPE_MASK,64)
else
t=const_type(t&CTYPE_MASK,Util.bitSize())
if ch=='u'||ch=='U':
ptr++
ch=int(feed[ptr])
t=(t&~CTYPE_MASK)|CTYPE_UINT
val_represented=val
if t==const_type(CTYPE_UINT,32):
val_represented=i64(u32(val_represented))
else if t==const_type(CTYPE_INT,32):
val_represented=i64(u32(val_represented))
if val_represented!=val:
if (val_represented^val)!=0xFFFFFFFF00000000LL||!ishex:
//we ignore sign-only difference for hex values
error(ETYPE_WARNING,efeed0_real,ptr,"the number '"+cite_raw(efeed0_real,ptr)+"' has been clamped to value "+string(val_represented))
cid=getid_const(t,val)
toks.push(TToken(){'tok':TOK_CONST+cid,'epos0':int(efeed0),'epos1':int(ptr)})
continue
//id
if CharSet.has(CharSet.idhead,ch):
s=ptr
ptr++
skipchars(CharSet.idbody)
if ptr-s>=8&&cite_raw(ptr-8,ptr)=="operator":
//operator state machine
parseOperator()
id=getid(cite_raw(s,ptr))
toks.push(TToken(){'tok':TOK_ID+id,'epos0':int(s),'epos1':int(ptr)})
continue
ch0=ch
epos0_ch0=ptr
ptr++;ch=int(feed[ptr])
//is_at_str=0
if !ch0:break
switch ch0{
default:
break;//nothing
case '[','(','{':
left_bracket(ch0)
break;
case ')',']','}':
if !right_bracket(ch0):
//we shouldn't put it in
continue
break;
case '=':
if(ch=='=')
ptr++
ch0=TOK_EQ;
break;
case '+':
if(ch=='='){ptr++;ch0=TOK_ADD_EQ;}else
if(ch=='+'){ptr++;ch0=TOK_ADD_ADD;}
break
case '-':
if(ch=='='){ptr++;ch0=TOK_SUB_EQ;}else
if(ch=='-'){ptr++;ch0=TOK_SUB_SUB;}
break
case '*':
if(ch=='='){ptr++;ch0=TOK_MUL_EQ;}
break
case '<':
if(ch=='='){ptr++;ch0=TOK_LE;}else
if(ch=='<')
ptr++;ch0=TOK_LL;
if feed[ptr]==u8('='):
ptr++;ch0=TOK_LSHIFT_EQ;
break;
case '>':
if(ch=='='){ptr++;ch0=TOK_GE;}else\
if(ch=='>')
ptr++;ch0=TOK_GG;
if feed[ptr]==u8('='):
ptr++;ch0=TOK_RSHIFT_EQ;
break;
case '!':{if(ch=='='){ptr++;ch0=TOK_NE;}break;}
case '&':
if(ch=='&'){ptr++;ch0=TOK_AA;}
if(ch=='='){ptr++;ch0=TOK_AND_EQ;}
break;
case '|':
if(ch=='|'){ptr++;ch0=TOK_OO;}
if(ch=='='){ptr++;ch0=TOK_OR_EQ;}
break;
case '%':
if(ch=='='){ptr++;ch0=TOK_MOD_EQ;}
break
case '^':
if(ch=='='){ptr++;ch0=TOK_XOR_EQ;}
break
//indent stuff
case '\\':
//line-escape
if(ch=='\n'||ch=='\r')
skipchars(CharSet.newlines)
continue
break;
case '\n':
//just a normal space when gettext AND no indent
assert(!ignore_indents)
epos0=ptr
app=0
ind=0
for(ind=0;;)
ch=int(feed[ptr]);
if !CharSet.has(CharSet.spaces_newline,ch):break
ptr++
if ch=='\r':
//nothing
else if ch=='\n':
ind=0;app=0
else
if ch=='\t':{app|=1}else app|=2;
ind++;
if app==3:
app=7
error(ETYPE_ERROR,int(epos0),ptr,"space and tab can't be mixed in indentation")
if !feed[ptr]:
ind=0
if int(feed[ptr])=='}':
//auto-pop to 0x80000000 during the latter }
//pop_indents()
continue
else
ind0=(inds.n?(inds.back()&0x3fffffff):0)
if ind0!=ind:
if ind0<ind:
if inds.n&&(inds.back()&0x80000000)&&toks.back().tok==int('{'):
//ignore the first indent immediately following a {
inds.push(ind|0x40000000)
last_significant_newline_position=toks.n
continue
inds.push(ind)
ch0=int('{')
else
//don't pop past the {
while inds.n&&(inds.back()&0xbfffffff)>ind:
inds.pop();
toks.push(TToken(){'tok':int('}'),'epos0':int(ptr),'epos1':int(ptr)})
if !inds.n:
if ind:
error(ETYPE_ERROR,epos0_ch0,ptr,FormatAsText("indentation mismatch - this line is indented less than the first line in the file"))
else if (inds.back()&0x3fffffff)!=ind:
//indentation mismatch
error(ETYPE_ERROR,epos0_ch0,ptr,FormatAsText("indentation mismatch - @1 expected but @2 provided").Replace(["@1",string(inds.back()),"@2",string(ind)]))
last_significant_newline_position=toks.n
continue
else
ch0=int(';')
last_significant_newline_position=toks.n
if toks.n:
ch_lastline=toks.back().tok
if ch_lastline==int(';')||ch_lastline==int(',')||ch_lastline==int('{'):
continue
if toks.n==last_line_comment_position:
//line comments shouldn't generate ;, but they should generate {}
continue
last_significant_newline_position=toks.n+1
break
//char/string literal
case '"','\'':
//is_python_str=0
//if ch==ch0:
// if ptr<feed.n-1&&(int)feed[ptr+1]==(int)ch0:
// //python string
// is_python_str=1
// ptr+=2
efeed0=ptr
c0=ch0
isrecover=0
str=new string
for(;;)
c=int(feed[ptr]);ptr++
if c==0:
if isrecover:
ptr--
break
ptr--
error(ETYPE_ERROR,int(efeed0),ptr,"this string is not properly enclosed")
ptr=efeed0
isrecover=1
str.clear()
continue
if c=='\\'://&&!is_at_str:
ch=int(feed[ptr])
if ch=='\r'||ch=='\n':
ptr++;ch=int(feed[ptr])
if ch=='\r'||ch=='\n':
ptr++;ch=int(feed[ptr])
continue
c=ch;ptr++;
switch c{
case 'n':
c=int('\n');break;
case 'r':
c=int('\r');break;
case 't':
c=int('\t');break;
case 'b':
c=int('\b');break;
case 'e':
c=27;
break;
case 'x','u':
chu=0
for j=0:(c=='u'?3:1)
chj=int(feed[ptr])
if chj:ptr++
si=((chj-'0')&0x1f)
if si>=0x10:si-=7
chu=chu*16+(si&0xf)
if c=='x':
str.push(char(chu))
else
if chu>=2048:
str.push(char(((chu>>12)&0xf)+0xe0))
str.push(char(0x80+((chu>>6)&63)))
str.push(char(0x80+(chu&63)))
else if chu>=128:
str.push(char((chu>>6)+0xc0))
str.push(char(0x80+(chu&63)))
else
str.push(char(chu))
continue
default:
if CharSet.has(CharSet.digits,c):
ptr--
s=ptr
skipchars(CharSet.digits)
c=0
for(;s!=ptr;s++)
si=int(feed[s])
c=c*8+(si-'0')
break
}
else
if c==c0:
//if is_python_str:
// if ptr<=feed.n-2&&feed[ptr]==c0&&feed[ptr+1]==c0:
// ptr+=2
// break
// else
// goto goodchar0
break;
if isrecover&&(c=='\r'||c=='\n'):break
//:goodchar0
str.push(char(c))
if ch0=='\''&&str.n==1:
//char
toks.push(TToken(){'tok':TOK_CONST+getid_const(const_type(CTYPE_INT,8),i64(str[0])),'epos0':int(efeed0)-1,'epos1':int(ptr)})
else
toks.push(TToken(){'tok':TOK_STRING+getid(str),'epos0':int(efeed0)-1,'epos1':int(ptr)})
continue
//comments
case '/':
if(ch=='='){ptr++;ch0=TOK_DIV_EQ;break;}
if ch=='/':
ptr++
for(;;)
ch=int(feed[ptr])
if ch==0||ch=='\n':break
ptr++
if last_significant_newline_position==toks.n:
last_line_comment_position=toks.n
continue
if ch=='*':{
ptr++
auto c=0;
for(;;)
ch=int(feed[ptr])
if ch==0:break
ptr++
if ch=='/'&&c=='*':break;
c=ch;
continue
}
break;
}
toks.push(TToken(){'tok':ch0,'epos0':int(epos0_ch0),'epos1':int(ptr)})
//////////////////
while brastk.n:
right_bracket(0)
pop_indents()
toks.push(TToken(){'tok':TOK_EOF,'epos0':int(ptr),'epos1':int(ptr)})
return toks
auto dumpToken(int tok)
assert(tok!='\n')
switch(tok&TOK_TYPE_MASK){
case TOK_CONST:
val=Util.g_const_values[tok&~TOK_TYPE_MASK]
return dumpConst(val)
case TOK_ID:
return new(getIdString(tok&~TOK_TYPE_MASK))
case TOK_STRING:
s0=getIdString(tok&~TOK_TYPE_MASK)
return "\""+genString(s0)+"\""
}
switch tok{
case 0:return "<EOF>"
case TOK_EQ:return "=="
case TOK_NE:return "!="
case TOK_LE:return "<="
case TOK_GE:return ">="
case TOK_AA:return "&&"
case TOK_OO:return "||"
case TOK_LL:return "<<"
case TOK_GG:return ">>"
case TOK_ADD_EQ:return "+="
case TOK_SUB_EQ:return "-="
case TOK_MUL_EQ:return "*="
case TOK_DIV_EQ:return "/="
case TOK_ADD_ADD:return "++"
case TOK_SUB_SUB:return "--"
case TOK_MOD_EQ:return "%="
case TOK_OR_EQ:return "|="
case TOK_AND_EQ:return "&="
case TOK_XOR_EQ:return "^="
case TOK_LSHIFT_EQ:return "<<="
case TOK_RSHIFT_EQ:return ">>="
}
return string(char(tok))
auto dumpTokenArray(TToken[] toks)
ret=new string
ind=0
foreach toki in toks
s2=dumpToken(toki.tok)
if ret.n&&s2.n&&CharSet.has(CharSet.idbody,int(u8(s2[0]))):
if CharSet.has(CharSet.idbody,int(u8(ret.back()))):
ret.push(' ')
else if ret.back()=='}':
ret.push('\n')
for j=0:ind-1
ret.push(' ')
if toki.tok=='}':
if ind>0:ind--
if ret.n&&ret.back()==' '&&ret[ret.n-2]==' ':
ret.pop()
ret.pop()
else
ret.push('\n')
for j=0:ind-1
ret.push(' ')
ret.push(s2)
if toki.tok=='{'||toki.tok==';':
if toki.tok=='{':
ind++
ret.push('\n')
for j=0:ind-1
ret.push(' ')
return ret
auto test_tokenizer()
//Write(dumpTokenArray(tokenize(loadSourceFile("test\\ttokenizer.spap"),0)))
Write(dumpTokenArray(tokenize(loadSourceFile(getid("test\\tparser.spap")),0)))
//////////////////////////////////////
//canonical form parser, always returns a statement list
struct TOperator
int id,id2
int priority
g_operators=new TOperator[128]
g_inited=0
auto initParser()
if g_inited:return
g_inited=1
/////////////////////
g_operators[TOK_EQ]=TOperator(){'id':getid("operator"+dumpToken(TOK_EQ)),'priority':60}
g_operators[TOK_NE]=TOperator(){'id':getid("operator"+dumpToken(TOK_NE)),'priority':60}
g_operators[TOK_LE]=TOperator(){'id':getid("operator"+dumpToken(TOK_LE)),'priority':60}
g_operators[TOK_GE]=TOperator(){'id':getid("operator"+dumpToken(TOK_GE)),'priority':60}
g_operators[TOK_AA]=TOperator(){'id':getid("operator"+dumpToken(TOK_AA)),'priority':70}
g_operators[TOK_OO]=TOperator(){'id':getid("operator"+dumpToken(TOK_OO)),'priority':75}
g_operators[TOK_LL]=TOperator(){'id':getid("operator"+dumpToken(TOK_LL)),'priority':52}
g_operators[TOK_GG]=TOperator(){'id':getid("operator"+dumpToken(TOK_GG)),'priority':52}
s="operator"+dumpToken(TOK_ADD_EQ);g_operators[TOK_ADD_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
s="operator"+dumpToken(TOK_SUB_EQ);g_operators[TOK_SUB_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
s="operator"+dumpToken(TOK_MUL_EQ);g_operators[TOK_MUL_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
s="operator"+dumpToken(TOK_DIV_EQ);g_operators[TOK_DIV_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
s="operator"+dumpToken(TOK_MOD_EQ);g_operators[TOK_MOD_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
s="operator"+dumpToken(TOK_OR_EQ);g_operators[TOK_OR_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
s="operator"+dumpToken(TOK_AND_EQ);g_operators[TOK_AND_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
s="operator"+dumpToken(TOK_XOR_EQ);g_operators[TOK_XOR_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
s="operator"+dumpToken(TOK_LSHIFT_EQ);g_operators[TOK_LSHIFT_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
s="operator"+dumpToken(TOK_RSHIFT_EQ);g_operators[TOK_RSHIFT_EQ]=TOperator(){'id':getid(s),'id2':getid(s[:s.n-2]),'priority':LEVEL_ASSIGNMENT}
g_operators[TOK_ADD_ADD]=TOperator(){'id':getid("operator"+dumpToken(TOK_ADD_ADD)),'priority':LEVEL_POSTFIX}
g_operators[TOK_SUB_SUB]=TOperator(){'id':getid("operator"+dumpToken(TOK_SUB_SUB)),'priority':LEVEL_POSTFIX}
g_operators[(int('+'))]=TOperator(){'id':getid("operator+"),'priority':50}
g_operators[(int('-'))]=TOperator(){'id':getid("operator-"),'priority':50}
g_operators[(int('*'))]=TOperator(){'id':getid("operator*"),'priority':40}
g_operators[(int('/'))]=TOperator(){'id':getid("operator/"),'priority':40}
g_operators[(int('%'))]=TOperator(){'id':getid("operator%"),'priority':40}
g_operators[(int('&'))]=TOperator(){'id':getid("operator&"),'priority':54}
g_operators[(int('|'))]=TOperator(){'id':getid("operator|"),'priority':56}
g_operators[(int('^'))]=TOperator(){'id':getid("operator^"),'priority':55}
g_operators[(int('['))]=TOperator(){'id':getid("operator[]"),'priority':LEVEL_POSTFIX}
g_operators[(int('~'))]=TOperator(){'id':getid("operator~"),'priority':LEVEL_PREFIX}
g_operators[(int('!'))]=TOperator(){'id':getid("operator!"),'priority':LEVEL_PREFIX}
g_operators[(int('<'))]=TOperator(){'id':getid("operator<"),'priority':60}
g_operators[(int('>'))]=TOperator(){'id':getid("operator>"),'priority':60}
g_operators[(int('?'))]=TOperator(){'id':getid("__select"),'priority':LEVEL_SELECT}
g_operators[(int('='))]=TOperator(){'id':g_id_store,'priority':LEVEL_ASSIGNMENT}
g_system_unit_path=System.Env.GetExecutablePath()+"../../units/"
auto scanForSystemUnit(int id_namespace)
s0=getIdString(id_namespace)
s=new string
foreach ch0 in s0
ch=int(u8(ch0))
if ch>='A'&&ch<='Z':
if s.n&&(s.back()>='a'&&s.back()<='z'||s.back()>='A'&&s.back()<='Z'):
s.push('-')
s.push(char(ch+0x20))
else
s.push(ch0)
fn=g_system_unit_path+s+".jc"
if System.IO.FileExists(fn):
return getid(fn)
return 0
auto addSourceFile(int id_fn0)
id_fn=getid(System.Env.NormalizeFileName(getIdString(id_fn0)))
if !g_parsed_files[id_fn]:
g_parsed_files[id_fn]=1
g_files_to_parse.push(id_fn)
return id_fn
auto parseC0(int id_fn_current,TToken[] toks)
if !toks.n:return expriptr(0)
if g_enable_dump:
Writeln('============raw tokens')
Writeln(dumpTokenArray(toks))
initParser()
fn=getIdString(id_fn_current)
fn=fn.Replace(["\\","/"])
sunit_name_default=new string
need_to_capitalize=0
p_slash=fn.LastIndexOf('/')
if p_slash>=0:
fn=fn[p_slash+1:]
p_last_dot=fn.LastIndexOf('.')
if p_last_dot>=0:
fn=fn[:p_last_dot-1]
foreach ch,I in fn
chi=int(ch)
if g_c_id_allowed[chi]:
if chi>='A'&&ch<='Z':
chi+=0x20
if chi>='a'&&ch<='z':
if need_to_capitalize:
chi-=0x20
need_to_capitalize=0
else
need_to_capitalize=(chi!='_')
sunit_name_default.push(char(chi))
else
need_to_capitalize=1
if sunit_name_default[0]>='0'&&sunit_name_default[0]<='9':
sunit_name_default="_"+sunit_name_default
//sunit_name_default=sunit_name_default.ToLower()
if sunit_name_default[0]>='a'&&sunit_name_default[0]<='z':
sunit_name_default[0]-=i8(0x20)
id_unit=getid(sunit_name_default)
//even keyworded statements could use function syntax
//we should parse it into the code structures here
ptr=0L
g_current_function_ccnv=0
inline peek()
return toks[ptr].tok
//the inlines were a bit excessive...
auto wantid()
auto tok=peek()
if ((tok&TOK_TYPE_MASK)==TOK_ID)
ptr++
return tok&~TOK_TYPE_MASK
else
return 0
auto want(int tok)
if peek()==tok:
ptr++
return 1
else
return 0
auto eof()
return peek()==TOK_EOF
//////////////////////////////////
auto parseMap(PExpression pe0,int epos0)
as_member_setter=new PExpression[]
vtemp=gettempid(0)
if !pe0:
as_tuple_maker=new PExpression[]
as_member_setter.push(exprstr(g_id_tuple))
as_member_setter.push(0)
else
as_member_setter.push(call(g_id_store,fillepos(exprvar(vtemp),readPool(pe0+1),readPool(pe0+2)),pe0))
while !want(int('}'))&&!eof()
auto tok=peek()
ep0_id=toks[ptr].epos0
ep1_id=toks[ptr].epos1
if ((tok&TOK_TYPE_MASK)==TOK_ID)
id_name=(tok&~TOK_TYPE_MASK)
ptr++
else if ((tok&TOK_TYPE_MASK)==TOK_STRING)
id_name=(tok&~TOK_TYPE_MASK)
ptr++
else
id_name=0
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"a member name is expected")
if !want(int(':'))
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"':' is expected")
pe_value=expr(LEVEL_MAX)
if id_name&&pe_value:
if !pe0:as_tuple_maker.push(exprstr(id_name))
ep1_value=toks[ptr-1].epos1
as_member_setter.push(fillepos(call(g_id_store,fillepos(call(g_id_dot,exprvar(vtemp),exprstr(id_name)),ep0_id,ep1_id),pe_value),ep0_id,ep1_value))
if peek()!='}'&&!want(int(',')):
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"',' is expected")
epos1=toks[max(ptr-1,0L)].epos1
if !pe0:
as_member_setter[1]=call(g_id_store,exprvar(vtemp),vcall(g_id_tuple,as_tuple_maker))
as_member_setter.push(exprvar(vtemp))
pe_map=fillepos(vcall(g_id_block,as_member_setter),epos0,epos1)
return pe_map
auto parseTuple(PExpression pe0,int epos0)
as_member_setter=new PExpression[]
as_tuple_maker=new PExpression[]
as_member_setter.push(exprstr(g_id_tuple))
as_member_setter.push(0)
vtemp=gettempid(0)
n=0
id=getTupleId(n)
as_tuple_maker.push(exprstr(id))
as_member_setter.push(call(g_id_store,call(g_id_dot,exprvar(vtemp),exprstr(id)),pe0))
n++
while want(int(','))
if peek()==int(')'):break
pe_value=expr(LEVEL_MAX)
id=getTupleId(n)
as_tuple_maker.push(exprstr(id))
as_member_setter.push(call(g_id_store,call(g_id_dot,exprvar(vtemp),exprstr(id)),pe_value))
n++
if !want(int(')')):
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"')' is expected")
epos1=toks[ptr-1].epos1
as_member_setter[1]=call(g_id_store,exprvar(vtemp),vcall(g_id_tuple,as_tuple_maker))
as_member_setter.push(exprvar(vtemp))
pe_tuple=fillepos(vcall(g_id_block,as_member_setter),epos0,epos1)
return pe_tuple
//////////////////////////////////
auto parseFunction(int id0)
//function
epos0=toks[ptr-1].epos0
ccnv=id0
//ptr0=ptr
id_name=wantid()
pe=0
es_args=[exprstr(ccnv)]
if !want(int('('))
//error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos1,"( expected after function")
//ptr=ptr0
//pe=expr(LEVEL_MAX)
//no parameter
else
while !want(int(')'))&&!eof():
ptr_bk=ptr
//class / struct cannot take params
if ((toks[ptr].tok&TOK_TYPE_MASK)==TOK_ID&&ptr+1<toks.n&&(toks[ptr+1].tok==','||toks[ptr+1].tok==')'))||(id0==g_id_class||id0==g_id_struct):
pe_type=exprstr(id0==g_id_class||id0==g_id_struct?g_id_const:g_id_auto)
id_param=wantid()
else if toks[ptr].tok==TOK_ID+g_id_auto||toks[ptr].tok==TOK_ID+g_id_const:
pe_type=exprstr(wantid())
id_param=wantid()
else
pe_type=expr(LEVEL_MAX)
id_param=wantid()
if !id_param:
id_param=g_empty_id
epos0_id_param=toks[ptr].epos0
epos1_id_param=toks[ptr].epos0
else
epos0_id_param=toks[ptr-1].epos0
epos1_id_param=toks[ptr-1].epos1
if !want(int(','))&&!peek()==int(')'):
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"unknown things after function parameter")
es_args.push(pe_type)
es_args.push(fillepos(exprstr(id_param),epos0_id_param,epos1_id_param))
if ptr<=ptr_bk:
//error...
if toks[ptr].tok!=TOK_EOF:ptr++
if peek()==int('{')||id0==g_id_class||id0==g_id_struct:
bk=g_current_function_ccnv
g_current_function_ccnv=id0
pe_fbody=statement()
g_current_function_ccnv=bk
epos1=toks[ptr-1].epos1
if id0==g_id_class||id0==g_id_struct:
pe_fbody=call(g_id_block,
fillepos(call(g_id_store,exprvar(g_id_this),call(g_id_get_lambda_context,expriptr(0)),expriptr(0)),epos0,epos1),
pe_fbody,
fillepos(call(g_id_store,exprvar(g_id_return),exprvar(g_id_this),expriptr(0)),epos0,epos1))
es_args.push(pe_fbody)
id_call=g_id_function
else
id_call=g_id_function_type
//the 'auto' guys are actually types!
for i=1:2:es_args.n-2
if readPool(es_args[i])==EFLAG_STRING+g_id_auto:
assert(isExpr(es_args[i+1],EFLAG_STRING))
es_args[i]=exprvar(readPool(es_args[i+1])&~EFLAG_MASK)
writePool(es_args[i+1],EFLAG_STRING+g_empty_id)
if want(int(':')):
//return type
es_args.push(expr(LEVEL_PREFIX))
else
es_args.push(expriptr(0))
epos1=toks[ptr-1].epos1
pe=fillepos(vcall(id_call,es_args),epos0,epos1)
if id_name:
pe=fillepos(call(g_id_store,exprvar(id_name),pe,expriptr(0)),epos0,epos1)
return pe
//////////////////////////////////
auto parseForeach()
vars=new int[]
for(;;)
id_var=wantid()
if !id_var:break
vars.push(id_var)
if !want(int(',')):break
if vars.n==1&&want(int('=')):
//intslice for
pe_a=expr(LEVEL_MAX)
if !want(int(':')):
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"':' expected here")
vars=int[].NULL
pe_container=expriptr(0)
else
pe_b=expr(LEVEL_MAX)
if want(int(':')):
pe_c=expr(LEVEL_MAX)
else
pe_c=pe_b
pe_b=expriptr(1)
pe_container=call(g_id_int_range,pe_a,pe_b,pe_c)
else
if !want(TOK_ID+g_id_in):
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"'in' expected after 'for var'")
vars=int[].NULL
pe_container=expriptr(0)
else
pe_container=expr(LEVEL_MAX)
return (vars,pe_container)
auto parseMetaList(int epos0,PExpression pe_body0)
(vars,pe_container)=parseForeach()
if !vars:
return expriptr(0)
pe_body=call(g_id_block,indcall([exprvar(g_id_map_callback),pe_body0]))
got_if=0
if want(TOK_ID+g_id_if):
pecond=expr(LEVEL_SELECT)
pe_body=call(g_id_block,call(g_id_if,pecond,pe_body,expriptr(0),expriptr(0)))
got_if=1
/////////////
//create the map part
as=new PExpression[]
as.push(exprstr(g_id_inline_loopbody))
as.push(exprstr(g_id_auto))
as.push(exprstr(g_id_map_callback))
foreach id_var in vars
as.push(exprstr(g_id_auto))
as.push(exprstr(id_var))
as.push(pe_body)
pe_inline_body=vcall(g_id_function,as)
epos1=toks[ptr].epos1
if !want(int(']')):
epos1=toks[ptr].epos0
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos1,"'[' - ']' mismatch: need a ']' here")
return expriptr(0)
id_reduce_op=g_id_reduce_
es=new int[]
es.push(pe_container)
es.push(pe_inline_body)
es.push(expriptr(got_if))
if want(int('.')):
id_op_body=wantid()
if !id_op_body:
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"identifier expected after [].")
return expriptr(0)
id_reduce_op=catid(id_reduce_op,id_op_body)
if id_op_body!=g_id_n:
if !want(int('(')):
error(ETYPE_ERROR,toks[ptr-1].epos0,toks[ptr-1].epos1,"you cannot access members of a [... for ...] list directly")
return expriptr(0)
while !want(int(')'))&&!eof():
pe=expr(LEVEL_SELECT)
if !want(int(','))&&peek()!=int(')'):
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"this function parameter expression has terminated prematurely.")
continue
es.push(pe)
return fillepos(vcall(id_reduce_op,es),epos0,epos1)
auto atom()
auto lex=peek()
if (lex&TOK_TYPE_MASK)==TOK_CONST:
ret=fillepos(exprcns(lex&~TOK_TYPE_MASK),toks[ptr].epos0,toks[ptr].epos1)
ptr++
return ret
else if (lex&TOK_TYPE_MASK)==TOK_STRING:
ret=fillepos(exprstr(lex&~TOK_TYPE_MASK),toks[ptr].epos0,toks[ptr].epos1)
ptr++
return ret
else if (lex&TOK_TYPE_MASK)==TOK_ID:
id0=wantid()
if id0==g_id_function||id0==g_id_inline||id0==g_id_inline_loopbody||id0==g_id_class||id0==g_id_struct:
return parseFunction(id0)
else if id0==g_id_module:
epos0=toks[ptr-1].epos0
id_namespace=wantid()
if !id_namespace:
error(ETYPE_ERROR,toks[ptr].epos0,toks[ptr].epos0,"module must be followed by a name")
return expriptr(0)
pe_codeblock=statement()
//pe_codeblock=call(g_id_block,
// call(g_id_store,exprvar(g_id_this),call(g_id_get_lambda_context,expriptr(0)),expriptr(0)),
// pe_codeblock,