-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpda_lua.py
More file actions
2040 lines (1698 loc) · 115 KB
/
Copy pathpda_lua.py
File metadata and controls
2040 lines (1698 loc) · 115 KB
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
# Copyright (c) 2020 Kevin Stevens
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import string
import pda
def bstr_to_set(b):
"""
Convert a byte string to a set of the length-1 bytes obejcts within it.
"""
return set(bytes([c]) for c in b)
def u8_complement(s):
"""
Return the set of all length-1 bytes objects not in s (which is of
type bytes, or set of length-1 bytes objects).
"""
return without(ALL, s)
def without(s, removals):
"""
Return the set of all length-1 bytes objects in s and not in removals
(both of which are either of type bytes, or set of length-1 bytes objects).
"""
if isinstance(s, bytes):
s = bstr_to_set(s)
elif isinstance(s, set):
s = set(s)
else:
raise TypeError(s)
if isinstance(removals, bytes):
removals = bstr_to_set(removals)
elif not isinstance(removals, set):
raise TypeError(removals)
for r in removals:
s.remove(r)
return s
# See lctype.h
ALL = bstr_to_set(bytes(range(0x100)))
IN_LISLALPHA = bstr_to_set(string.ascii_letters.encode('cp1252') + b'_')
NOT_LISLALPHA = u8_complement(IN_LISLALPHA)
IN_LISLALNUM = bstr_to_set(string.ascii_letters.encode('cp1252') + string.digits.encode('cp1252') + b'_')
NOT_LISLALNUM = u8_complement(IN_LISLALNUM)
IN_LISDIGIT = bstr_to_set(string.digits.encode('cp1252'))
NOT_LISDIGIT = u8_complement(IN_LISDIGIT)
IN_LISSPACE = bstr_to_set(string.whitespace.encode('cp1252'))
NOT_LISSPACE = u8_complement(IN_LISSPACE)
IN_LISPRINT = bstr_to_set(string.printable.encode('cp1252'))
NOT_LISPRINT = u8_complement(IN_LISPRINT)
IN_LISXDIGIT = bstr_to_set(string.hexdigits.encode('cp1252'))
NOT_LISXDIGIT = u8_complement(IN_LISXDIGIT)
# (Note: the Lua parser uses hardcoded Arabic numeral characters, like this)
DIGITS = bstr_to_set(b'0123456789')
ONLY_HEX_DIGITS = bstr_to_set(b'abcdefABCDEF')
HEX_DIGITS = DIGITS | ONLY_HEX_DIGITS
def _make_transitions():
"""
Create the transitions table for the Lua 2PDA
"""
transitions = {}
FAIL_TRANSITION = ('FAIL', 'stay', 'read', None)
KEYWORDS = [
'and', 'break', 'do', 'else', 'elseif', 'end',
'false', 'for', 'function', 'goto', 'if', 'in',
'local', 'nil', 'not', 'or', 'repeat', 'return',
'then', 'true', 'until', 'while']
CHECK_IF_ONLY_NAME_STACK_SYMBOLS = ['beginning',
'only_name',
'not_only_name']
####################################################################
####################################################################
################## Subsystem enter/exit functions ##################
####################################################################
####################################################################
# (These have to be defined first instead of with each subsystem
# because a few of the subsystems are mutually recursive, and thus
# need to be able to call each other's entrance functions)
def read_whitespace(start_state, minus_transition, *, required_stack_value=None):
"""
Read whitespace, including any comments. Remains on the current
state, except while reading comments.
Note that, when using this function on a state, you CANNOT also
add your own transition on "-" away from that state! Use
minus_transition instead.
- start_state: the state we start at
- minus_transition: transition to use upon reading a minus and
then landing on something that's not a minus. At this point,
minus has already been consumed, and we can't go back and
un-consume it.
- required_stack_value: this must be initially on top of the
stack for whitespace/comments to be recognized
When minus_transition is taken, the stack will be the same as
when whitespace reading began.
"""
this_stack_value = 'comment__' + start_state
# Skip any whitespace while on the start state
for c in IN_LISSPACE:
transitions[(start_state, c, required_stack_value)] = (start_state, 'right', 'read', None)
# Comment?
transitions[(start_state, b'-', required_stack_value)] = ('possible_comment_-', 'right', 'push', this_stack_value)
# If we're in "possible_comment_-", and read anything other than "-", transition to minus_transition
# (after popping this_stack_value off the stack)
for c in u8_complement(b'-'):
intermediate_state = 'possible_comment_-__' + start_state
transitions[('possible_comment_-', c, this_stack_value)] = (intermediate_state, 'stay', 'pop', None)
transitions[(intermediate_state, c, None)] = minus_transition
# If there is another "-", we'll pick it up in the general comment parser.
# End of a single-line comment -- return to original state
transitions[('comment_single_line', b'\r', this_stack_value)] = (start_state, 'right', 'pop', None)
transitions[('comment_single_line', b'\n', this_stack_value)] = (start_state, 'right', 'pop', None)
# End of a multi-line comment -- return to original state
transitions[('comment_multiline_end', b']', this_stack_value)] = (start_state, 'right', 'pop', None)
def read_name_or_keyword(start_state, name_transition, keyword_transition, *, required_stack_value=None):
"""
Read a "Name" from the Lua grammar, which is defined as follows:
(https://www.lua.org/manual/5.3/manual.html#3.1)
Names (also called identifiers) in Lua can be any string of
letters, digits, and underscores, not beginning with a digit
and not being a reserved word. Identifiers are used to name
variables, table fields, and labels.
If the name turns out to be a keyword, then it's not really a
name. But having a function that can check for both is useful.
- start_state: the state we start at
- name_transition: transition to use upon successfully reading a
name (defined as reading a non-alphanumeric character after
reading a full name which is not a keyword)
- keyword_transition: transition to use upon successfully
reading a keyword (defined as reading a non-alphanumeric
character after reading a full keyword)
- required_stack_value: this must be initially on top of the
stack for the name or keyword to be recognized
Note that, just before the keyword transition, the keyword
itself will be on the top of the stack. But just before the name
transition, there will be nothing extra on top of the stack.
"""
this_stack_value = 'name_or_keyword__' + start_state
# Enter subsystem
# Precondition: in start_state, with nothing on top of stack
# Postcondition: in "name_or_keyword" state, with this_stack_value on top of stack
for c in IN_LISLALPHA:
transitions[(start_state, c, required_stack_value)] = ('name_or_keyword', 'stay', 'push', this_stack_value)
# Exit subsystem (name)
# Precondition: in "name" state, with this_stack_value on top of stack
# Postcondition: taking name_transition, with nothing on top of stack
for c in NOT_LISLALNUM:
intermediate_state = 'name_from__' + start_state
transitions[('name', c, this_stack_value)] = (intermediate_state, 'stay', 'pop', None)
transitions[(intermediate_state, c, None)] = name_transition
# Exit subsystem (keyword)
# Precondition: in any of the "keyword_[keyword]" states, with this_stack_value on top of stack
# Postcondition: taking keyword_transition, with keyword on top of stack
for keyword in KEYWORDS:
intermediate_state = 'keyword_' + keyword + '_from__' + start_state
for c in NOT_LISLALNUM:
transitions[('keyword_' + keyword, c, this_stack_value)] = (intermediate_state, 'stay', 'replace', keyword)
transitions[(intermediate_state, c, None)] = keyword_transition
def read_name_list(start_state, name_transition, keyword_transition, *, required_stack_value=None):
"""
Read a name list.
- start_state: the state we start at
- name_transition: transition to use upon successfully reading
one or more names (defined as reading a non-alphanumeric
character other than "," after reading a full name which is
not a keyword)
- keyword_transition: transition to use upon successfully
reading a keyword (defined as reading a non-alphanumeric
character after reading a full keyword, which is the first
thing in the name list)
- required_stack_value: this must be initially on top of the
stack for the name or keyword to be recognized
Unlike read_name_or_keyword(), this function consumes trailing
whitespace after reading names. It has to, since you could have
a situation like
return a ,b ;end
and so it has to read all the whitespace following each name
to determine if the name list continues or not.
It does NOT consume leading whitespace.
Note: right now, you can't have a name list that's closed by a
minus sign, because comments complicates this and I don't think
it would ever be used anywhere. Implement that only if needed.
See docstring for read_name_or_keyword() for more details.
"""
this_stack_value = 'name_list__' + start_state
# Enter subsystem
# Precondition: in start_state, with nothing on top of stack
# Postcondition: in "name" state, with this_stack_value on top of stack
for c in ALL:
transitions[(start_state, c, required_stack_value)] = ('name_list_start', 'stay', 'push', this_stack_value)
# Exit subsystem (usual route)
# Precondition: in "name_list_exit_name" state, with this_stack_value on top of stack
# Postcondition: taking name_transition, with nothing on top of stack
for c in ALL:
intermediate_state = 'name_list_exit_name_from__' + start_state
transitions[('name_list_exit_name', c, this_stack_value)] = (intermediate_state, 'stay', 'pop', None)
transitions[(intermediate_state, c, None)] = name_transition
# Exit subsystem (keyword encountered)
# Precondition: in "name_list_exit_keyword" state, with keyword name above this_stack_value on top of stack
# Postcondition: taking keyword_transition, with the keyword on top of stack
for c in ALL:
for k in KEYWORDS:
intermediate_state_1 = f'name_list_exit_keyword__{k}'
intermediate_state_2 = f'name_list_exit_keyword__{k}__from__{start_state}'
intermediate_state_3 = f'name_list_exit_keyword_from__{start_state}'
# Pop the keyword off the stack, and put it in the state name instead
transitions[('name_list_exit_keyword', c, k)] = (intermediate_state_1, 'stay', 'pop', None)
# Pop the "this_stack_value" off the stack, and put it in the state name instead
transitions[(intermediate_state_1, c, this_stack_value)] = (intermediate_state_2, 'stay', 'pop', None)
# Push the keyword back onto the stack
transitions[(intermediate_state_2, c, None)] = (intermediate_state_3, 'stay', 'push', k)
# Take the actual final transition
transitions[(intermediate_state_3, c, None)] = keyword_transition
def read_lvalue_or_rvalue(start_state, already_read_name, transition, minus_transition, period_transition, colon_transition,
keyword_transition=FAIL_TRANSITION,
*, check_if_only_name=False, check_if_function_call=False):
"""
Read an L-value or R-value (corresponding to the "var" and
"prefixexp" Lua grammar rules). See "lvalue-rvalue-notes.txt".
This function leaves a stack symbol on top of the stack --
either "rvalue" or "lvalue_or_rvalue" -- which you can use to
deduce if what was read could be valid as an lvalue or would
only be valid as an rvalue.
- start_state: the state we start at
- already_read_name: True if a name has already been read, False
otherwise
- transition: transition to use upon encountering something that
implies the end of the thing
- minus_transition: transition to use upon reading a minus and
then landing on something that's not a minus. At this point,
minus has already been consumed, and we can't go back and
un-consume it. This is otherwise equivalent to the main exit
transition.
Note that trailing whitespace is NOT consumed in this case!
- period_transition: transition to use upon reading a period and
then landing on another period. At this point, period has
already been consumed, and we can't go back and un-consume it.
This is otherwise equivalent to the main exit transition.
Note that trailing whitespace is NOT consumed in this case!
- colon_transition: transition to use upon reading a colon and
then landing on something that's not a name. At this point,
colon has already been consumed, and we can't go back and
un-consume it. This is otherwise equivalent to the main exit
transition.
Note that trailing whitespace is NOT consumed in this case!
- keyword_transition: transition to use if the first thing that
is read is a keyword.
Note that trailing whitespace is NOT consumed in this case!
Also note that NO new symbols are left on the stack in this
case, except for the keyword itself.
- check_if_only_name: causes this function to leave an extra
element on the stack (only if exiting via "transition" or
"minus_transition"), which will be 'only_name' if the only
thing that was read was a single name, or 'not_only_name' if
the lvalue/rvalue was anything more. See below for where
exactly this will be placed on the stack.
- check_if_function_call: causes this function to leave an extra
element on the stack (only if exiting via "transition" or
"minus_transition"), which will be 'only_name' if the only
thing that was read was a single name, or 'not_only_name' if
the lvalue/rvalue was anything more. See below for where
exactly this will be placed on the stack.
The order in which stack symbols will be left on the stack
(top to bottom):
- "lvalue_or_rvalue" or "rvalue"
- "only_name" or "not_only_name" (optional -- only if
check_if_only_name is True)
- "function_call" or "not_function_call" (optional -- only if
check_if_function_call is True)
This function handles trailing whitespace automatically, except
for exit transitions that specify otherwise. It does NOT handle
leading whitespace.
"""
this_stack_value = 'lrvalue__' + start_state
entry_point = '2' if already_read_name else '1'
# Enter subsystem
# Precondition: in start_state, with nothing on top of stack
# Postcondition: in "lrvalue_start_1" or "lrvalue_start_2"
# state (depending on already_read_name), with
# this_stack_value on top of stack
for c in ALL:
transitions[(start_state, c, None)] = ('lrvalue_start_' + entry_point, 'stay', 'push', this_stack_value)
# Exit subsystem
# AND
# Exit subsystem (minus read)
# AND
# Exit subsystem (period read)
# Precondition: in "lrvalue[_-|_.]_exit" state, with
# the current state (as set by
# _lrvalue_set_stack_state_and_read_next_part()) on top of
# stack, followed by this_stack_value
# Postcondition: taking [minus_]transition, with the top of the
# stack looking like this (top to bottom):
# - "lvalue_or_rvalue" or "rvalue"
# - "only_name" or "not_only_name" (optional -- only if check_if_only_name is True)
# - "function_call" or "not_function_call" (optional -- only if check_if_function_call is True)
for mod, this_transition in [('', transition), ('_-', minus_transition), ('_.', period_transition), ('_:', colon_transition)]:
for exit_option_1 in ['lvalue_or_rvalue', 'rvalue']:
for exit_option_2 in ['only_name', 'not_only_name']:
for exit_option_3 in ['function_call', 'not_function_call']:
state_stack_value = exit_option_1 + '__' + exit_option_2 + '__' + exit_option_3
intermediate_state_1 = f'lrvalue_exit{mod}_with__' + state_stack_value
extra_intermediate_state = f'lrvalue_exit{mod}_from__' + this_stack_value + '__with__' + state_stack_value
to_push = []
if check_if_function_call:
to_push.append(exit_option_3)
if check_if_only_name:
to_push.append(exit_option_2)
to_push.append(exit_option_1)
for c in ALL:
# pop state_stack_value
transitions[(f'lrvalue{mod}_exit', c, state_stack_value)] = (intermediate_state_1, 'stay', 'pop', None)
current_intermediate_state = intermediate_state_1
next_intermediate_state_num = 1
action = 'replace' # replace the first time; push subsequent times
stack_value_to_check_against = this_stack_value # this_stack_value the first time; None subsequent times
for tp in to_push:
next_intermediate_state = extra_intermediate_state + '__' + str(next_intermediate_state_num)
transitions[(current_intermediate_state, c, stack_value_to_check_against)] = \
(next_intermediate_state, 'stay', action, tp)
# prepare for next iteration
action = 'push'
stack_value_to_check_against = None
current_intermediate_state = next_intermediate_state
next_intermediate_state_num += 1
transitions[(current_intermediate_state, c, None)] = this_transition
# Exit subsystem (keyword)
# Precondition: in "lrvalue_exit_keyword" state, with the
# keyword on top of stack, followed by this_stack_value
# Postcondition: taking keyword_transition, with keyword on top
# of stack
for keyword in KEYWORDS:
intermediate_state_1 = f'lrvalue_exit_keyword_with__' + keyword
intermediate_state_2 = f'lrvalue_exit_keyword_from__' + start_state + '__with__' + keyword
for c in ALL:
transitions[('lrvalue_exit', c, keyword)] = (intermediate_state_1, 'stay', 'pop', None)
transitions[(intermediate_state_1, c, this_stack_value)] = (intermediate_state_2, 'stay', 'replace', keyword)
transitions[(intermediate_state_2, c, None)] = keyword_transition
def _lrvalue_init_stack_state_and_read_next_part(start_state, characters_to_transition_on, right_or_stay,
lvalue_or_rvalue_vs_rvalue, only_name_vs_not_only_name, function_call_vs_not_function_call):
"""
Helper function for the LRvalue subsystem to initialize the
stack state to represent certain values, and then transition to
lrvalue_read_next_part
"""
stack_value = lvalue_or_rvalue_vs_rvalue + '__' + only_name_vs_not_only_name + '__' + function_call_vs_not_function_call
if isinstance(characters_to_transition_on, bytes):
characters_to_transition_on = bstr_to_set(characters_to_transition_on)
for c in characters_to_transition_on:
transitions[(start_state, c, None)] = ('lrvalue_read_next_part', right_or_stay, 'push', stack_value)
def _lrvalue_set_stack_state_and_read_next_part(start_state, characters_to_transition_on, right_or_stay,
lvalue_or_rvalue_vs_rvalue, only_name_vs_not_only_name, function_call_vs_not_function_call,
*, is_colon_version=False):
"""
Helper function for the LRvalue subsystem to change the stack
state to represent certain values, and then transition to
lrvalue_read_next_part
"""
target_state = 'lrvalue_read_next_part' + ('_:' if is_colon_version else '')
stack_value = lvalue_or_rvalue_vs_rvalue + '__' + only_name_vs_not_only_name + '__' + function_call_vs_not_function_call
if isinstance(characters_to_transition_on, bytes):
characters_to_transition_on = bstr_to_set(characters_to_transition_on)
for c in characters_to_transition_on:
transitions[(start_state, c, None)] = (target_state, right_or_stay, 'replace', stack_value)
def read_expression(start_state, transition,
end_transition=FAIL_TRANSITION, elseif_transition=FAIL_TRANSITION,
else_transition=FAIL_TRANSITION, until_transition=FAIL_TRANSITION,
semicolon_transition=FAIL_TRANSITION, rparen_transition=FAIL_TRANSITION,
equals_transition=FAIL_TRANSITION,
trailing_name_transition=FAIL_TRANSITION,
colon_transition=FAIL_TRANSITION,
*, required_stack_value=None, check_if_only_name=False):
"""
Read an expression.
- start_state: the state we start at
- transition: transition to use upon encountering something that
would seem to imply the end of the expression
- end_transition / elseif_transition / else_transition /
until_transition: transition to use if the expression is just
the specified keyword (used by return statements) Note that
trailing whitespace is NOT consumed in this case!
(But the keyword itself is.)
Requested output variables are NOT left on the stack.
- semicolon_transition: transition to use if ';' is the first
thing encountered (used by return statements)
Note that trailing whitespace is NOT consumed in this case!
(But the ';' is.)
Requested output variables are NOT left on the stack.
- rparen_transition: transition to use if ')' is the first
thing encountered (used by function calls)
Note that trailing whitespace is NOT consumed in this case!
(But the ')' is.)
Requested output variables are NOT left on the stack.
- equals_transition: transition to use if read_expression()
consumed an '=' in the hopes of it being the '==' binary
operator, but it turned out not to be.
Note that trailing whitespace is NOT consumed in this case!
Requested output variables ARE left on the stack.
- trailing_name_transition: transition to use if
read_expression() consumed a name in the hopes of it being
'and' or 'or', but it turned out not to be.
Note that trailing whitespace is NOT consumed in this case!
Requested output variables ARE left on the stack.
- colon_transition: transition to use if read_expression()
consumed a ':'' in the hopes of it being a ':'-style function
call, but it turned out not to be.
Note that trailing whitespace is NOT consumed in this case!
(But the ':' is.)
Requested output variables ARE left on the stack.
- required_stack_value: this must be initially on top of the
stack for the expression to be recognized
- check_if_only_name: causes this function to leave an extra
element on top of the stack (only if exiting via the primary
transition), which will be 'only_name' if the only thing that
was read was a single name, or 'not_only_name' if the
expression was anything else. (Accidentally reading an extra
'=' in the equals_transition does not count as "anything
else.")
DO NOT CALL read_whitespace() ON THE SAME STATE THAT YOU CALL
THIS FUNCTION ON!!! They conflict because they both check for
"-". This function handles leading and trailing whitespace
automatically (unless "end" or ";" or "=" is read, so you can
fail quickly)
"""
this_stack_value = 'expression__' + start_state
# Enter subsystem
# Precondition: in start_state, with nothing on top of stack
# Postcondition: in "expression" state, with 'beginning' (from
# CHECK_IF_ONLY_NAME_STACK_SYMBOLS) on top of stack, and
# this_stack_value just below it
for c in ALL:
transitions[(start_state, c, required_stack_value)] = ('expression_start', 'stay', 'push', this_stack_value)
transitions[('expression_start', c, None)] = ('expression', 'stay', 'push', 'beginning')
read_whitespace('expression_start',
('expression_start', 'stay', 'read', None))
# ^ "exp ::= - exp" is a valid grammar production, so if
# read_whitespace() consumes a '-', that's not a problem. We
# just have to go back to expression_start to read any further
# whitespace following the '-'.
# Exit subsystem (regularly, or "=" or name or ":" encountered)
# Precondition: in "expression_exit" state, with the current
# check_if_only_name state on top of stack, and
# this_stack_value just below it
# Postcondition: taking transition, with either nothing or the
# check_if_only_name state (depending on check_if_only_name)
# on top of stack
for type, this_transition in [('', transition),
('_=', equals_transition),
('_trailing_name', trailing_name_transition),
('_:', colon_transition)]:
for c in ALL:
for symb in CHECK_IF_ONLY_NAME_STACK_SYMBOLS:
# Pop stack symbol and put it in the state name
intermediate_state_1 = f'expression_exit{type}_with__' + symb
transitions[(f'expression_exit{type}', c, symb)] = (intermediate_state_1, 'stay', 'pop', None)
# Pop this_stack_value and either replace it with the
# stack symbol, or don't
intermediate_state_2 = f'expression_exit{type}_from__' + start_state
if check_if_only_name:
transitions[(intermediate_state_1, c, this_stack_value)] = (intermediate_state_2, 'stay', 'replace', symb)
else:
transitions[(intermediate_state_1, c, this_stack_value)] = (intermediate_state_2, 'stay', 'pop', None)
# Transition out using the transition provided to us
transitions[(intermediate_state_2, c, None)] = this_transition
# Exit subsystem ("end" / "elseif" / "else" / "until" / ";" / ")" encountered)
# Precondition: in "expression_exit_end" or "expression_exit_;"
# or "expression_exit_)" state, with the current
# check_if_only_name state on top of stack, and
# this_stack_value just below it
# Postcondition: taking appropriate transition, with nothing on
# top of stack
for k, special_transition in [('end', end_transition),
('elseif', elseif_transition),
('else', else_transition),
('until', until_transition),
(';', semicolon_transition),
(')', rparen_transition)]:
intermediate_state = 'expression_exit_' + k + '_from__' + start_state
for c in ALL:
transitions[(f'expression_exit_{k}', c, None)] = (f'expression_exit_{k}_1', 'stay', 'pop', None)
transitions[(f'expression_exit_{k}_1', c, this_stack_value)] = (intermediate_state, 'stay', 'pop', None)
transitions[(intermediate_state, c, None)] = special_transition
def read_expression_list(start_state, transition,
end_transition=FAIL_TRANSITION, elseif_transition=FAIL_TRANSITION,
else_transition=FAIL_TRANSITION, until_transition=FAIL_TRANSITION,
semicolon_transition=FAIL_TRANSITION, rparen_transition=FAIL_TRANSITION,
trailing_name_transition=FAIL_TRANSITION,
colon_transition=FAIL_TRANSITION,
*, required_stack_value=None):
"""
Read an expression list.
- start_state: the state we start at
- transition: transition to use upon encountering something that
would seem to imply the end of the expression list
- end_transition / elseif_transition / else_transition /
until_transition / semicolon_transition / rparen_transition /
trailing_name_transition / colon_transition: transition to use
if the last call to read_expression() exited via its
transition of the same name. For details, please see the
docstring for read_expression().
- required_stack_value: this must be initially on top of the
stack for the expression to be recognized
DO NOT CALL read_whitespace() ON THE SAME STATE THAT YOU CALL
THIS FUNCTION ON!!! They conflict because they both check for
"-". This function handles leading and trailing whitespace
automatically (unless "end" or ";" is read, so you can fail
quickly)
"""
this_stack_value = 'expression_list__' + start_state
# Enter subsystem
# Precondition: in start_state, with nothing on top of stack
# Postcondition: in "expression_list_start" state, with this_stack_value on top of stack
for c in ALL:
transitions[(start_state, c, required_stack_value)] = ('expression_list_start', 'stay', 'push', this_stack_value)
# Exit subsystem
# Precondition: in "expression_list_exit" state, with this_stack_value on top of stack
# Postcondition: taking transition, with nothing on top of stack
for c in ALL:
intermediate_state = 'expression_list_exit_from__' + start_state
transitions[('expression_list_exit', c, this_stack_value)] = (intermediate_state, 'stay', 'pop', None)
transitions[(intermediate_state, c, None)] = transition
# Exit subsystem ("end" / "elseif" / "else" / "until" / ";" / ")" / trailing-name encountered)
# Precondition: in "expression_list_exit_{keyword}" state, with this_stack_value on top of stack
# Postcondition: taking {keyword}_transition, with nothing on top of stack
for k, trans in [('end', end_transition),
('elseif', elseif_transition),
('else', else_transition),
('until', until_transition),
(';', semicolon_transition),
(')', rparen_transition),
('trailing_name', trailing_name_transition),
(':', colon_transition)]:
for c in ALL:
intermediate_state = f'expression_list_exit_{k}_from__' + start_state
transitions[('expression_list_exit_' + k, c, this_stack_value)] = (intermediate_state, 'stay', 'pop', None)
transitions[(intermediate_state, c, None)] = trans
####################################################################
####################################################################
################# Long strings / multiline comments ################
####################################################################
####################################################################
# These are similar enough to be worth parsing in the same way.
# Note: I don't believe it's possible in general to count "="s and
# compare them again in a PDA. So we hardcode it up to 10 ='s, and
# treat anything more than 10 as if it was 10.
EQUALS_TO_SUPPORT = 10 # supports 0 ='s through this number (inclusive)
# To enter this subsystem:
# - push something you can use to later return on the stack
# - transition to state "multiline_comment_or_long_string_start"
# BEFORE consuming the leading "["
# --OR--
# transition to state "multiline_comment_or_long_string_start_2"
# AFTER consuming the leading "["
# To exit:
# - make a transition from "multiline_comment_or_long_string_end" back
# to your own state, which consumes a ']', and checks for your
# stack value and pops it
# Note:
# Make sure to treat a failed closing "]" as the possible start of
# the real ending; that is, account for "code() --[===[ comment ]=]===] code()"
MCOLS = 'multiline_comment_or_long_string' # So I don't have to keep typing it
# Read initial '[', and push a '' onto the stack (representing
# the number of ='s read so far)
for c in ALL:
transitions[(f'{MCOLS}_start', c, None)] = (f'{MCOLS}_end_opening_fail', 'stay', 'read', None)
transitions[(f'{MCOLS}_start', b'[', None)] = (f'{MCOLS}_start_[', 'right', 'push', '')
# ALTERNATIVE ENTRY POINT
# Already past the initial '[', so now we should be on either a '['
# or a '='. Push a '' onto the stack (representing the number of ='s
# read so far)
for c in ALL:
transitions[(f'{MCOLS}_start_2', c, None)] = (f'{MCOLS}_end_opening_fail', 'stay', 'read', None)
transitions[(f'{MCOLS}_start_2', b'[', None)] = (f'{MCOLS}_start_[', 'stay', 'push', '')
transitions[(f'{MCOLS}_start_2', b'=', None)] = (f'{MCOLS}_start_[', 'stay', 'push', '')
# Read 1-N equals
for c in u8_complement(b'='):
transitions[(f'{MCOLS}_start_[', c, None)] = (f'{MCOLS}_end_opening_fail', 'stay', 'pop', None)
for i in range(1, EQUALS_TO_SUPPORT + 1):
transitions[(f'{MCOLS}_start_[', b'=', '=' * (i - 1))] = (f'{MCOLS}_start_[', 'right', 'replace', '=' * i)
# More than N equals are treated as if there were only N
transitions[(f'{MCOLS}_start_[', b'=', None)] = (f'{MCOLS}_start_[', 'right', 'read', None)
# Second opening '['
transitions[(f'{MCOLS}_start_[', b'[', None)] = (MCOLS, 'right', 'read', None)
# At this point we're in the MCOLS state, with the number of ='s we read
# on the stack (as one stack symbol).
# Skip over stuff
for c in ALL:
transitions[(MCOLS, c, None)] = (MCOLS, 'right', 'read', None)
# Detect start of possible ending
transitions[(MCOLS, b']', None)] = (f'{MCOLS}_possible_end', 'right', 'push', '')
# Detect failed possible endings via invalid characters
for c in u8_complement(b'=]'):
transitions[(f'{MCOLS}_possible_end', c, None)] = (MCOLS, 'right', 'pop', None)
# Count equals
for i in range(1, EQUALS_TO_SUPPORT + 1):
transitions[(f'{MCOLS}_possible_end', b'=', '=' * (i - 1))] = (f'{MCOLS}_possible_end', 'right', 'replace', '=' * i)
transitions[(f'{MCOLS}_possible_end', b'=', None)] = (f'{MCOLS}_possible_end', 'right', 'read', None)
# Upon reaching ']', check if the top two stack values are equal
transitions[(f'{MCOLS}_possible_end', b']', None)] = (f'{MCOLS}_possible_end_2', 'stay', 'read', None)
for i in range(EQUALS_TO_SUPPORT + 1):
transitions[(f'{MCOLS}_possible_end_2', b']', '=' * i)] = (f'{MCOLS}_possible_end_' + ('=' * i), 'stay', 'pop', None)
transitions[(f'{MCOLS}_possible_end_' + ('=' * i), b']', '=' * i)] = (f'{MCOLS}_end', 'stay', 'pop', None)
# If they're *not* equal, go back to _possible_end because we did just read
# another ']' that could be the start of the true ending
transitions[(f'{MCOLS}_possible_end_' + ('=' * i), b']', None)] = (f'{MCOLS}_possible_end', 'right', 'push', '')
####################################################################
####################################################################
####################### Whitespace / Comments ######################
####################################################################
####################################################################
# We pick up at state "possible_comment_-", where we read another "-", starting a comment
transitions[('possible_comment_-', b'-', None)] = ('comment_start', 'right', 'read', None)
# Comment! Is it the "--" form, or the "--[=*[" form?
for c in ALL:
transitions[('comment_start', c, None)] = ('comment_single_line', 'stay', 'read', None)
transitions[('comment_start', b'[', None)] = \
('multiline_comment_or_long_string_start', 'stay', 'push', 'multiline_comment')
# Single-line form: read until end of line, then go back to the whitespace state
# Note: newline characters are defined as '\n' and '\r'; see currIsNewline() in llex.c
for c in u8_complement(b'\r\n'):
transitions[('comment_single_line', c, None)] = ('comment_single_line', 'right', 'read', None)
# \r and \n will be consumed in read_whitespace()
# Multi-line form. Pop our 'multline_comment' stack symbol
# Final "]" will be consumed in read_whitespace()
transitions[('multiline_comment_or_long_string_end', b']', 'multiline_comment')] = \
('comment_multiline_end', 'stay', 'pop', None)
for c in ALL:
transitions[('multiline_comment_or_long_string_end_opening_fail', c, 'multiline_comment')] = \
('comment_single_line', 'stay', 'pop', None)
####################################################################
####################################################################
######################### Names / Keywords #########################
####################################################################
####################################################################
# We start in the 'name_or_keyword' state, having already verified
# that the first character is alphabetic (but still being positioned
# on that character).
# ======== "name" STATE ========
# Skip over alphanumeric characters while in the "name" state
for c in IN_LISLALNUM:
transitions[('name', c, None)] = ('name', 'right', 'read', None)
# (Exiting the state when a non-alphanum character is read is
# handled by read_name_or_keyword().)
# ======== "name_or_keyword" STATE ========
# If the first thing we read isn't the start of a keyword, go to the name state
for c in IN_LISLALNUM:
transitions[('name_or_keyword', c, None)] = ('name', 'stay', 'read', None)
# Now we'll replace some of those to look for actual keywords.
for keyword in KEYWORDS:
# If we have a partial keyword on the stack, but get literally
# anything other than what we're looking for, pop the
# in-progress keyword off the stack and go to the name state to
# handle it like a name
for c in ALL:
keyword_so_far = ''
for k in keyword:
keyword_so_far += k
transitions[('name_or_keyword', c, keyword_so_far)] = ('name', 'stay', 'pop', None)
for keyword in KEYWORDS:
# If we complete the full keyword and encounter something
# non-alphanumeric, go to the appropriate keyword state
for c in NOT_LISLALNUM:
transitions[('name_or_keyword', c, keyword)] = ('keyword_' + keyword, 'stay', 'pop', None)
# (read_name_or_keyword() takes it from here.)
# Actual primary sequence of transitions for the keyword
transitions[('name_or_keyword', keyword[0].encode('cp1252'), None)] = ('name_or_keyword', 'right', 'push', keyword[0])
keyword_so_far = keyword[0]
for c in keyword[1:]:
transitions[('name_or_keyword', c.encode('cp1252'), keyword_so_far)] = ('name_or_keyword', 'right', 'replace', keyword_so_far + c)
keyword_so_far += c
####################################################################
####################################################################
############################# Name List ############################
####################################################################
####################################################################
# Read a name
read_name_or_keyword('name_list_start',
('name_list_entry_end', 'stay', 'read', None), # (read an actual name)
('name_list_exit_keyword', 'stay', 'read', None)) # (read a keyword)
# If we read an actual name, either read a comma and read a second name,
# or go to the exit state
for c in ALL:
transitions[('name_list_entry_end', c, None)] = ('name_list_exit_name', 'stay', 'read', None)
read_whitespace('name_list_entry_end', FAIL_TRANSITION)
transitions[('name_list_entry_end', b',', None)] = ('name_list_start_2', 'right', 'read', None)
read_whitespace('name_list_start_2', FAIL_TRANSITION)
# Read another name (2nd, 3rd, 4th, etc)
# This time, we fail immediately if we discover a keyword
read_name_or_keyword('name_list_start_2',
('name_list_entry_end', 'stay', 'read', None), # (read an actual name)
FAIL_TRANSITION) # (read a keyword)
####################################################################
####################################################################
########################## Function Bodies #########################
####################################################################
####################################################################
# To enter this subsystem:
# - push something you can use to later return on the stack
# - transition to state "func_body_start"
# (whitespace will be taken care of for you)
# To exit:
# - make a transition from "func_body_end" back
# to your own state, which checks for your stack value and pops it
# (will be right after the "end" is parsed, so transition on all
# characters)
# Note about a requirement for the implementation below:
# Make sure to treat a failed closing "]" as the possible start of
# the real ending; that is, account for "code() --[===[ comment ]=]===] code()"
read_whitespace('func_body_start', FAIL_TRANSITION)
# Read a "(", and then whitespace
transitions[('func_body_start', b'(', None)] = ('parlist_start', 'right', 'read', None)
read_whitespace('parlist_start', FAIL_TRANSITION)
# Read a name, and then whitespace
read_name_or_keyword('parlist_start', ('parlist_after_name', 'stay', 'read', None), FAIL_TRANSITION)
read_whitespace('parlist_after_name', FAIL_TRANSITION)
# Read a comma, and then whitespace
transitions[('parlist_after_name', b',', None)] = ('parlist_after_comma', 'right', 'read', None)
read_whitespace('parlist_after_comma', FAIL_TRANSITION)
# We can read another name now, and then loop back
read_name_or_keyword('parlist_after_comma', ('parlist_after_name', 'stay', 'read', None), FAIL_TRANSITION)
# If we see a "." right after the opening "(" or after a comma, start trying to read a full "..."
transitions[('parlist_start', b'.', None)] = ('parlist_.', 'right', 'read', None)
transitions[('parlist_after_comma', b'.', None)] = ('parlist_.', 'right', 'read', None)
transitions[('parlist_.', b'.', None)] = ('parlist_..', 'right', 'read', None)
transitions[('parlist_..', b'.', None)] = ('parlist_...', 'right', 'read', None)
# (possibly followed by whitespace)
read_whitespace('parlist_...', FAIL_TRANSITION)
# If we see a ")" after the opening "(", a name, or the "...", start reading statements
transitions[('parlist_start', b')', None)] = ('statement', 'right', 'push', 'func_body')
transitions[('parlist_after_name', b')', None)] = ('statement', 'right', 'push', 'func_body')
transitions[('parlist_...', b')', None)] = ('statement', 'right', 'push', 'func_body')
# The rest is handled by the 'func_body': 'func_body_end' entry in
# STACK_VALUES_POPPED_BY_END_KEYWORD
####################################################################
####################################################################
####################### Short String Literals ######################
####################################################################
####################################################################
# To enter this subsystem:
# - push something you can use to later return on the stack
# - transition to state "short_string_start"
# To exit:
# - make a transition from "short_string_end" back
# to your own state, which checks for your stack value and pops it
#
# Leading/trailing whitespace is NOT handled here.
transitions[('short_string_start', b"'", None)] = ('short_string', 'right', 'push', "'")
transitions[('short_string_start', b'"', None)] = ('short_string', 'right', 'push', '"')
# Looking at llex.c, it seems that the only things that can cause a
# string to be malformed are:
# - unescaped newline (\n or \r)
# - malformed escape sequence
# - EOF
# Almost all characters should be read as normal
for c in u8_complement(b'\r\n\\'):
transitions[('short_string', c, None)] = ('short_string', 'right', 'read', None)
# Allow embedding the opposite quote character
transitions[('short_string', b'"', "'")] = ('short_string', 'right', 'read', None)
transitions[('short_string', b"'", '"')] = ('short_string', 'right', 'read', None)
# Detect start of an escape sequence
transitions[('short_string', b'\\', None)] = ('short_string_esc_seq', 'right', 'read', None)
# Easy single-character ones
for c in bstr_to_set(b'abfnrtv' b'\\' b'"' b"'" b'\n'):
transitions[('short_string_esc_seq', c, None)] = ('short_string', 'right', 'read', None)
# \z: skips all following whitespace characters including linebreaks.
# NOTE: that means IN_LISSPACE, not read_whitespace() (which would
# skip over Lua comments)
transitions[('short_string_esc_seq', b'z', None)] = ('short_string_esc_seq_z', 'right', 'read', None)
for c in IN_LISSPACE:
transitions[('short_string_esc_seq_z', c, None)] = ('short_string_esc_seq_z', 'right', 'read', None)
for c in NOT_LISSPACE:
transitions[('short_string_esc_seq_z', c, None)] = ('short_string', 'stay', 'read', None)
# \xXX: hexadecimal literal
transitions[('short_string_esc_seq', b'x', None)] = ('short_string_esc_seq_x', 'right', 'read', None)
for c in HEX_DIGITS:
transitions[('short_string_esc_seq_x', c, None)] = ('short_string_esc_seq_x_X', 'right', 'read', None)
transitions[('short_string_esc_seq_x_X', c, None)] = ('short_string', 'right', 'read', None)
# \d, \dd, \ddd: decimal literal
# This is tricky for two reasons:
# - This can be 1, 2 or 3 digits long
# - We have to detect and reject \256 and above
# Notes:
# - Lua reads \dddd as \ddd followed by a digit character
# If the first digit is 0 or 1, no overflow potential
for d in bstr_to_set(b'01'):
transitions[('short_string_esc_seq', d, None)] = ('short_string_esc_seq_01', 'right', 'read', None)
for d in DIGITS:
transitions[('short_string_esc_seq_01', d, None)] = ('short_string_esc_seq_01_*', 'right', 'read', None)
transitions[('short_string_esc_seq_01_*', d, None)] = ('short_string', 'right', 'read', None)
for c in u8_complement(DIGITS):
transitions[('short_string_esc_seq_01', c, None)] = ('short_string', 'stay', 'read', None)
transitions[('short_string_esc_seq_01_*', c, None)] = ('short_string', 'stay', 'read', None)
# If the first digit is 3-9, it will overflow iff the escape is 3 digits long
for d in bstr_to_set(b'3456789'):
transitions[('short_string_esc_seq', d, None)] = ('short_string_esc_seq_3-9', 'right', 'read', None)
for d in DIGITS:
transitions[('short_string_esc_seq_3-9', d, None)] = ('short_string_esc_seq_3-9_*', 'right', 'read', None)
for c in u8_complement(DIGITS):
transitions[('short_string_esc_seq_3-9', c, None)] = ('short_string', 'stay', 'read', None)
transitions[('short_string_esc_seq_3-9_*', c, None)] = ('short_string', 'stay', 'read', None)
# If the first digit is 2, it *might* overflow depending on the following digits,
# so separate it into "2_0-4", "2_5", and "2_6-9" categories
transitions[('short_string_esc_seq', b'2', None)] = ('short_string_esc_seq_2', 'right', 'read', None)
for d in bstr_to_set(b'01234'): # Second digit is 0-4: no overflow potential
transitions[('short_string_esc_seq_2', d, None)] = ('short_string_esc_seq_2_0-4', 'right', 'read', None)
transitions[('short_string_esc_seq_2', b'5', None)] = ('short_string_esc_seq_2_5', 'right', 'read', None)
for d in bstr_to_set(b'6789'): # Second digit is 6-9: will overflow iff escape is 3 digits long
transitions[('short_string_esc_seq_2', d, None)] = ('short_string_esc_seq_2_6-9', 'right', 'read', None)
for c in u8_complement(DIGITS):
transitions[('short_string_esc_seq_2', c, None)] = ('short_string', 'stay', 'read', None)
# Handle the easy "2_0-4" and "2_6-9" cases from above
for d in DIGITS:
transitions[('short_string_esc_seq_2_0-4', d, None)] = ('short_string', 'right', 'read', None)
for c in u8_complement(DIGITS):
transitions[('short_string_esc_seq_2_0-4', c, None)] = ('short_string', 'stay', 'read', None)
transitions[('short_string_esc_seq_2_6-9', c, None)] = ('short_string', 'stay', 'read', None)
# Handle the more complicated case where we have \25[something]
for d in bstr_to_set(b'012345'): # only valid digits to follow \25
transitions[('short_string_esc_seq_2_5', d, None)] = ('short_string', 'right', 'read', None)
for c in u8_complement(DIGITS):
transitions[('short_string_esc_seq_2_5', c, None)] = ('short_string', 'stay', 'read', None)
# \u{XXX}: Unicode literal
# Notes:
# - Values greater than 7FFFFFFF are forbidden
# - No limit to the total number of digits (e.g. "\u{0000000007FFFFFFF}" is fine)
# - Must have at least one digit (i.e. "\u{}" is invalid)
transitions[('short_string_esc_seq', b'u', None)] = ('short_string_esc_seq_u', 'right', 'read', None)
transitions[('short_string_esc_seq_u', b'{', None)] = ('short_string_esc_seq_u{', 'right', 'read', None)
# Step 1: skip over all leading zeros
transitions[('short_string_esc_seq_u{', b'0', None)] = ('short_string_esc_seq_u{_0', 'right', 'read', None)
transitions[('short_string_esc_seq_u{_0', b'0', None)] = ('short_string_esc_seq_u{_0', 'right', 'read', None)
# Step 2: differentiate based on initial character 1-7 vs 8-F