-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPseudocode.py
2134 lines (1786 loc) · 81.2 KB
/
Pseudocode.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
#!/usr/bin/python3
# ecmaspeak-py/Pseudocode.py:
# Parse various flavors of ECMASpeak pseudocode.
#
# Copyright (C) 2018 J. Michael Dyck <[email protected]>
import sys, re, math, pdb, string, pprint
from collections import defaultdict
from HTML import HNode
from Pseudocode_Parser import Pseudocode_Parser, ANode
import emu_grammars
import shared
from shared import spec, stderr, msg_at_node
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def do_stuff_with_pseudocode():
check_step_references()
check_vars()
check_for_unbalanced_ifs()
check_value_descriptions()
analyze_static_dependencies()
check_the_sdo_name()
check_optional_parameters()
check_sdo_coverage()
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def check_step_references():
# This deals with the pseudocode in <emu-alg> elements,
# though in a fairly superficial way.
# (I.e., we don't need to have it parsed according to the emu-alg grammar.)
f_step_refs = shared.open_for_output('step_refs')
def put(*args): print(*args, file=f_step_refs)
curr_referring_section = None
for (referring_section, referring_line, refd_section, refd_line) in each_step_ref():
if referring_section != curr_referring_section:
put()
put('-' * 40)
put(referring_section.section_num)
put(referring_section.section_title)
curr_referring_section = referring_section
curr_referring_line = None
if referring_line != curr_referring_line:
# This does the 'wrong' thing in EvalDeclarationInstantiation,
# where there are two distinct referring lines with the exact same text
put()
put(' ' + referring_line)
curr_referring_line = referring_line
put()
if refd_section is referring_section:
put(f" (same section):")
else:
put(f" {refd_section.section_num} {refd_section.section_title}:")
put(f" {refd_line}")
f_step_refs.close()
# ------------------------------------------------------------------------------
def each_step_ref():
for mo in re.finditer(r'(?i)\bsteps* [0-9<]', spec.text):
st = mo.start()
referring_line = spec.text[spec.text.rindex('\n', 0, st)+1:spec.text.index('\n', st)].strip()
text_n = find_deepest_node_covering_posn(st)
assert text_n.parent.element_name in ['p', 'li', 'emu-alg', 'dd']
referring_section = text_n.closest_containing_section()
x = '<emu-xref href="#([-a-z0-9]+)"></emu-xref>'
patterns = [
fr'steps {x}, {x}, and {x}',
fr'steps {x}-{x}',
f'steps {x}\u2013{x}',
fr'steps {x} and {x}',
# kludgey for 13.15.2:
fr'step {x}, {x}, {x}, {x}, {x}',
fr'step {x}, {x}, {x}, {x}',
fr'step {x}',
]
for pattern in patterns:
mo = re.compile(pattern, re.IGNORECASE).match(spec.text, st)
if mo:
break
else:
assert 0, spec.text[st:st+200].replace('\n', '\\n')
step_ids = mo.groups()
for step_id in step_ids:
refd_emu_alg = spec.node_with_id_[step_id]
assert refd_emu_alg.element_name == 'emu-alg'
refd_section = refd_emu_alg.closest_containing_section()
mo = re.search(rf'.*id="{step_id}".*', refd_emu_alg.source_text())
assert mo
refd_line = mo.group(0).lstrip()
yield (referring_section, referring_line, refd_section, refd_line)
# ------------------------------------------------------------------------------
def find_deepest_node_covering_posn(posn):
def recurse(node):
assert node.start_posn <= posn <= node.end_posn
if node.children:
for child in node.children:
if child.start_posn <= posn <= child.end_posn:
return recurse(child)
else:
assert 0
else:
return node
return recurse(spec.doc_node)
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def create_all_parsers():
global pseudocode_parser
pseudocode_parser = Pseudocode_Parser('pseudocode')
def report_all_parsers():
pseudocode_parser.report()
def parse(hnode, what=None):
assert isinstance(hnode, HNode)
assert not hasattr(hnode, '_syntax_tree')
# In most case, we parse the element's inner text.
start_posn = hnode.inner_start_posn
end_posn = hnode.inner_end_posn
if hnode.element_name == 'emu-alg':
assert what is None
goal = 'EMU_ALG_BODY'
# # sneak this in...
# n_lines = spec.text.count('\n', start_posn, end_posn)
# if n_lines > 60:
# cc_section = hnode.closest_containing_section()
# print(f'\n emu-alg with {n_lines} lines in {cc_section.section_num} "{cc_section.section_title}"')
elif hnode.element_name == 'emu-eqn':
assert what is None
goal = 'EMU_EQN_DEF'
elif hnode.element_name == 'td':
if what == 'one_line_alg':
goal = 'ONE_LINE_ALG'
elif what == 'field_value_type':
goal = 'FIELD_VALUE_TYPE'
else:
assert 0, what
elif hnode.element_name == 'dd':
assert what is None
goal = 'FOR_PHRASE'
elif hnode.element_name == 'h1':
goal = 'H1_BODY'
elif hnode.element_name == 'li':
if what == 'early_error':
goal = 'EARLY_ERROR_RULE'
elif what == 'inline_sdo':
goal = 'INLINE_SDO_RULE'
else:
assert 0, what
else:
assert 0, hnode.element_name
tree = pseudocode_parser.parse_and_handle_errors(start_posn, end_posn, goal)
hnode._syntax_tree = tree
if tree is None:
cc_section = hnode.closest_containing_section()
if hasattr(cc_section, 'section_num'):
identification = f"{cc_section.section_num} {cc_section.section_title}"
else:
identification = f"{cc_section.element_name} id={cc_section.attrs['id']!r}"
stderr(f"\nFailed to parse <{hnode.element_name}> in {identification}")
# (Messes up the "progress bar")
return None
connect_anodes_to_hnodes(hnode, tree)
annotate_invocations(tree)
return tree
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def check_emu_eqn_coverage():
# Check that every <emu-eqn> that should have been parsed was parsed.
stderr("check_emu_eqn_coverage...")
for emu_eqn in spec.doc_node.each_descendant_named('emu-eqn'):
st = emu_eqn.inner_source_text()
if '=' not in st:
# 67 of these.
# The content is at best a formula or expression;
# it doesn't define anything.
# I suppose I could parse it for conformance to {EXPR},
# but to what end?
# Skip it.
assert not hasattr(emu_eqn, '_syntax_tree')
continue
if 'aoid' not in emu_eqn.attrs:
# There are a few of these:
# abs(_k_) < abs(_y_) and _x_-_k_ = _q_ × _y_
# floor(_x_) = _x_-(_x_ modulo 1)
# 60 × 60 × 24 × 1000 = 86,400,000
# MonthFromTime(0) = 0
# WeekDay(0) = 4
# _t_<sub>local</sub> = _t_
# _a_ =<sub>CF</sub> _b_
# _comparefn_(_a_, _b_) = 0
# They aren't definitions.
# Skip it.
assert not hasattr(emu_eqn, '_syntax_tree')
continue
assert emu_eqn.parent.element_name == 'emu-clause'
assert emu_eqn.parent.section_kind == 'catchall'
assert hasattr(emu_eqn, '_syntax_tree')
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def check_emu_alg_coverage():
stderr("check_emu_alg_coverage...")
for emu_alg in spec.doc_node.each_descendant_named('emu-alg'):
assert emu_alg.parent.element_name in ['emu-clause', 'emu-annex', 'emu-note', 'td', 'li']
# print(emu_alg.parent.element_name)
# 1758 emu-clause
# 56 emu-annex
# 4 emu-note
# 3 td
# 1 li
assert hasattr(emu_alg, '_syntax_tree')
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def connect_anodes_to_hnodes(base_hnode, base_anode):
pairs = [
('emu-grammar', '{h_emu_grammar}'),
('emu-alg', '{h_emu_alg}' ),
('figure', '{h_figure}' ),
('a', '{h_a}' ),
('pre', '{h_pre_code}' ),
# ('emu-xref', '{h_emu_xref}' ),
]
# We could include <emu-xref> and {h_emu_xref}, but
# - I don't think it'll be useful, and
# - there are cases
# FunctionDeclarationInstantiation ( _func_, _argumentsList_ )
# Runtime Semantics: GlobalDeclarationInstantiation ( _script_, _env_ )
# Runtime Semantics: EvalDeclarationInstantiation ( _body_, _varEnv_, _lexEnv_, _strict_ )
# NewPromiseCapability ( _C_ )
# where an <emu-xref> appears in a NOTE-step
# (base_hnode.element_name == 'emu-alg' and re.search('NOTE: .+ <emu-xref ', base_hnode.source_text())):
# it'll show up as a connectable hnode, but not as a connectable anode.
# ------------------------
connectable_hnode_names = [ hnode_name for (hnode_name, _) in pairs ]
connectable_hnodes = [
child
for child in base_hnode.children
if child.element_name in connectable_hnode_names
]
if base_hnode.element_name == 'li' and re.search('(?s)<p>.*<emu-grammar>', base_hnode.source_text()):
assert connectable_hnodes == []
(_, p, _) = base_hnode.children
assert p.element_name == 'p'
connectable_hnodes = [
child
for child in p.children
if child.element_name in connectable_hnode_names
]
# ------------------------
connectable_anode_names = [ anode_name for (_, anode_name) in pairs ]
connectable_anodes = [
anode
for anode in base_anode.each_descendant()
if anode.prod.lhs_s in connectable_anode_names
]
# ------------------------
assert len(connectable_anodes) == len(connectable_hnodes)
for (c_hnode, c_anode) in zip(connectable_hnodes, connectable_anodes):
assert (c_hnode.element_name, c_anode.prod.lhs_s) in pairs
c_anode._hnode = c_hnode
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def annotate_invocations(anode):
# For each node in `anode` that is an invocation of an operation,
# annotate it with info about the invocation.
for d in anode.each_descendant_or_self():
op_names = None
if d.prod.lhs_s == '{NAMED_OPERATION_INVOCATION}':
rhs = d.prod.rhs_s
if rhs == '{h_emu_meta_start}{NAMED_OPERATION_INVOCATION}{h_emu_meta_end}':
# This will be handled when `d` is set to the inner NOI.
pass
elif rhs in [
'{PREFIX_PAREN}',
'{PREFIX_PAREN} (see {h_emu_xref})',
]:
# This will be handled below, when `d` is set to the {PREFIX_PAREN}.
pass
elif rhs in [
'the {ISDO_NAME} of {PROD_REF}',
'{ISDO_NAME} of {PROD_REF}',
]:
isdo_name = d.children[0]
assert isdo_name.prod.rhs_s == '{cap_word}'
op_names = [isdo_name.source_text()]
args = [d.children[1]]
elif rhs in [
'the {cap_word} of {LOCAL_REF}',
'the {cap_word} of {LOCAL_REF} (see {h_emu_xref})',
'the {cap_word} of {LOCAL_REF} as defined in {h_emu_xref}',
'the {cap_word} of {LOCAL_REF} {WITH_ARGS}',
'{cap_word} of {LOCAL_REF}',
'{cap_word} of {LOCAL_REF} {WITH_ARGS}',
'the result of performing {cap_word} on {EX}',
]:
cap_word = d.children[0]
op_names = [cap_word.source_text()]
args = [d.children[1]]
if '{WITH_ARGS}' in rhs:
with_args = d.children[2]
assert with_args.prod.lhs_s == '{WITH_ARGS}'
if '{PASSING}' in with_args.prod.rhs_s:
args.extend(with_args.children[1:])
else:
args.extend(with_args.children)
elif rhs == 'the abstract operation named by {DOTTING} using the elements of {DOTTING} as its arguments':
op_names = [ 'ScriptEvaluationJob', 'TopLevelModuleEvaluationJob']
args = [d.children[1]] # XXX
else:
callee_name = {
"the CharSet returned by {h_emu_grammar}" : 'CompileToCharSet',
'{LOCAL_REF} Contains {G_SYM}' : 'Contains',
'{LOCAL_REF} Contains {var}' : 'Contains',
}[rhs]
op_names = [callee_name]
args = d.children # XXX incorrect for a few cases
elif d.prod.lhs_s == '{PREFIX_PAREN}':
assert d.prod.rhs_s in ['{OPN_BEFORE_PAREN}({EXLIST_OPT})', '{OPN_BEFORE_PAREN}({EXPR})']
[opn_before_paren, arg_list] = d.children
assert opn_before_paren.prod.lhs_s == '{OPN_BEFORE_PAREN}'
if opn_before_paren.prod.rhs_s == '{h_emu_meta_start}{OPN_BEFORE_PAREN}{h_emu_meta_end}':
(_, opn_before_paren, _) = opn_before_paren.children
if opn_before_paren.prod.rhs_s == '{SIMPLE_OPERATION_NAME}':
op_names = [opn_before_paren.source_text()]
elif opn_before_paren.prod.rhs_s == '{DOTTING}':
[dotting] = opn_before_paren.children
[lhs, dsbn] = dotting.children
op_name = dsbn.source_text()
# Usually, we are invoking an object's internal method.
# But the memory model has 2 record-fields that are invocable
# but not actually defined. (It's just weird.)
# It's simpler if we skip those cases.
if op_name in ['[[ModifyOp]]', '[[ReadsBytesFrom]]']:
op_names = []
else:
op_names = [op_name]
elif opn_before_paren.prod.rhs_s == '{var}.{cap_word}':
[var, cap_word] = opn_before_paren.children
op_names = [cap_word.source_text()]
elif opn_before_paren.prod.rhs_s == '{var}':
# can't do much
if opn_before_paren.source_text() == '_conversionOperation_':
# Should extract this from "The TypedArray Constructors" table
op_names = [
'ToInt8',
'ToUint8',
'ToUint8Clamp',
'ToInt16',
'ToUint16',
'ToInt32',
'ToUint32',
'ToBigInt64',
'ToBigUint64',
]
elif opn_before_paren.source_text() == '_operation_':
assert d.source_text() == '_operation_(_lNum_, _rNum_)'
# ApplyStringOrNumericBinaryOperator
op_names = [
'Number::exponentiate',
'BigInt::exponentiate',
'Number::multiply',
'BigInt::multiply',
'Number::divide',
'BigInt::divide',
'Number::remainder',
'BigInt::remainder',
'Number::add',
'BigInt::add',
'Number::subtract',
'BigInt::subtract',
'Number::leftShift',
'BigInt::leftShift',
'Number::signedRightShift',
'BigInt::signedRightShift',
'Number::unsignedRightShift',
'BigInt::unsignedRightShift',
'Number::bitwiseAND',
'BigInt::bitwiseAND',
'Number::bitwiseXOR',
'BigInt::bitwiseXOR',
'Number::bitwiseOR',
'BigInt::bitwiseOR',
]
else:
# mostly closures created+invoked in RegExp semantics
# print('>>>', opn_before_paren.source_text())
pass
else:
assert 0, opn_before_paren.prod.rhs_s
if arg_list.prod.lhs_s == '{EXLIST_OPT}':
args = exes_in_exlist_opt(arg_list)
elif arg_list.prod.lhs_s == '{EXPR}':
args = [arg_list]
else:
assert 0, arg_list.prod.lhs_s
elif str(d.prod) == '{CONDITION_1} : {var} and {var} are in a race in {var}':
op_names = ['Races']
args = [] # XXX
elif str(d.prod) == '{COMMAND} : Set fields of {var} with the values listed in {h_emu_xref}. {the_field_names_are_the_names_listed_etc}':
op_names = [ 'CreateBuiltinFunction', 'initializer for @@unscopables']
args = [] # XXX
elif str(d.prod) == '{COMMAND} : IfAbruptRejectPromise({var}, {var}).':
op_names = ['IfAbruptRejectPromise']
args = d.children[0:2]
elif str(d.prod) in [
'{COMMAND} : ReturnIfAbrupt({EX}).',
'{SMALL_COMMAND} : ReturnIfAbrupt({var})',
]:
op_names = ['ReturnIfAbrupt']
args = [d.children[0]]
if op_names is not None:
d._op_invocation = (op_names, args)
def exes_in_exlist_opt(exlist_opt):
assert exlist_opt.prod.lhs_s == '{EXLIST_OPT}'
if exlist_opt.prod.rhs_s == '{EPSILON}':
return []
elif exlist_opt.prod.rhs_s == '{EXLIST}':
[exlist] = exlist_opt.children
return exes_in_exlist(exlist)
elif exlist_opt.prod.rhs_s == '{var}':
return [exlist_opt.children[0]]
else:
assert 0, exlist_opt.prod.rhs_s
def exes_in_exlist(exlist):
exes = []
while True:
assert exlist.prod.lhs_s == '{EXLIST}'
if exlist.prod.rhs_s == '{EX}':
[ex] = exlist.children
exes.insert(0, ex)
break
elif exlist.prod.rhs_s == '{EXLIST}, {EX}':
[inner_exlist, ex] = exlist.children
exes.insert(0, ex)
exlist = inner_exlist
else:
assert 0
return exes
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def check_vars():
stderr('check_vars ...')
# Check algorithms for used-but-not-defined
# and defined-but-not-used.
#
# The approach here is fairly simplistic,
# not caring about scope or use-before-def
# or whether a var is defined on all possible paths
# that reach a particular use.
for (alg_name, alg_info) in (
sorted(spec.alg_info_['op'].items())
+
sorted(spec.alg_info_['bif'].items())
):
for alg_defn in alg_info.all_definitions():
for anode in alg_defn.anodes:
check_vars_in_anode(anode, alg_defn.parent_header)
def check_vars_in_anode(anode, alg_header):
# If an algorithm is incomplete in some way,
# it's pointless to check the vars in an algorithm.
# Detect those cases and do an early return.
#
# (This way of checking is fairly kludgey.)
if anode is None: return
s = anode.start_posn
preceding_text = shared.spec_text[s-100:s].replace('\n', r'\n')
if ' replaces-step=' in preceding_text:
# This is a chunk of pseudocode
# that replaces a step in some other algorithm.
# So it probably refers to vars that are defined there,
# and might define vars that are referenced only there.
return
if 'this method performs the following steps to prepare the Strings:' in preceding_text:
# String.prototype.localeCompare
# It's the start of an algorithm,
# so we'd expect unused vars.
# (Though not undefined vars, so we could just check for those.)
return
# -------------
class Thing:
def __init__(self):
self.defs = []
self.uses = []
self.okay_if_unused = False
things = defaultdict(Thing)
for param in alg_header.params:
if param.decl_node:
d = param.decl_node.children[0]
else:
d = None
d_thing = things[param.name]
d_thing.defs.append(d)
d_thing.okay_if_unused = alg_header.species.startswith('op: discriminated by')
# It's okay if some of the defns in a discriminated union
# don't use all the parameters
fp = alg_header.for_phrase_node
if fp and '{var}' in fp.prod.rhs_s:
d = fp.children[1]
d_thing = things[d.source_text()]
d_thing.defs.append(d)
d_thing.okay_if_unused = alg_header.species.startswith('op: discriminated by')
for d in anode.each_descendant_or_self():
if d.prod.lhs_s == '{var}':
d_thing = things[d.source_text()]
p = d.parent
pp = str(p.prod)
if pp == '{DEFVAR} : {var}':
d_thing.defs.append(d)
elif pp == '{EXPR} : a List whose elements are the elements of {var} ordered as if an Array of the same values had been sorted using {percent_word} using {LITERAL} as {var}' and d is p.children[3]:
# In ModuleNamespaceCreate,
# `_comparefn_` refers to a parameter of %Array.prototype.sort%,
# so it's neither a declaration nor a use.
pass
else:
d_thing.uses.append(d)
for (varname, thing) in sorted(things.items()):
if thing.defs and not thing.uses:
# Defined but not used
if thing.okay_if_unused:
pass
else:
msg_node = thing.defs[0]
if msg_node is None:
msg_node = anode
msg_at_node(
msg_node,
f"{varname} is not used in this algorithm"
)
if thing.uses and not thing.defs:
# Used but not defined
msg_at_node(
thing.uses[0],
f"{varname} is not defined in this algorithm"
)
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def check_for_unbalanced_ifs():
stderr('check_for_unbalanced_ifs ...')
# Check algorithms for 'unbalanced' If-commands:
# arms should either be all-indented or all-inline.
for (alg_name, alg_info) in (
sorted(spec.alg_info_['op'].items())
+
sorted(spec.alg_info_['bif'].items())
):
for alg_defn in alg_info.all_definitions():
for anode in alg_defn.anodes:
if anode is None: continue
for d in anode.each_descendant_or_self():
if d.prod.lhs_s == '{IF_OTHER}':
arms = [* each_if_arm(d)]
assert len(arms) > 0
arm_nts = set(
str(arm.prod.lhs_s)
for arm in arms
)
if len(arm_nts) == 1: continue
arm_nts_str = ' '.join(
str(arm.prod.lhs_s)
for arm in arms
)
msg_at_node(d, f"If-command has 'unbalanced' arms: {arm_nts_str}")
def each_if_arm(anode):
if anode.prod.lhs_s == '{IF_OTHER}':
assert anode.prod.rhs_s == '{IF_OPEN}{IF_TAIL}'
[if_open, if_tail] = anode.children
yield from each_if_arm(if_open)
yield from each_if_arm(if_tail)
elif anode.prod.lhs_s in ['{IF_OPEN}', '{ELSEIF_PART}']:
[condition, commands] = anode.children
assert commands.prod.lhs_s in ['{IND_COMMANDS}', '{SMALL_COMMAND}']
yield commands
elif anode.prod.lhs_s == '{IF_TAIL}':
if anode.prod.rhs_s == '{EPSILON}':
[] = anode.children
elif anode.prod.rhs_s == '{_NL_N} {ELSEIF_PART}{IF_TAIL}':
[elseif_part, if_tail] = anode.children
yield from each_if_arm(elseif_part)
yield from each_if_arm(if_tail)
elif anode.prod.rhs_s == '{_NL_N} {ELSE_PART}':
[else_part] = anode.children
yield from each_if_arm(else_part)
else:
assert 0, str(anode.prod)
elif anode.prod.lhs_s == '{ELSE_PART}':
commands = anode.children[-1]
assert commands.prod.lhs_s in ['{IND_COMMANDS}', '{SMALL_COMMAND}', '{COMMAND}']
yield commands
else:
assert 0, anode.prod_lhs_s
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def check_value_descriptions():
stderr('check_value_descriptions ...')
def visit(n):
if hasattr(n, '_syntax_tree'):
stree = n._syntax_tree
if stree is not None:
for anode in stree.each_descendant_or_self():
if anode.prod.lhs_s == '{VAL_DESC_DISJUNCTION}':
check_val_desc_disjunction(anode)
spec.doc_node.preorder_traversal(visit)
def check_val_desc_disjunction(val_desc_disjunction):
# Enforce on the rules set out in
# https://github.com/tc39/ecma262/pull/2972#issuecomment-1379579896
# and following.
assert val_desc_disjunction.prod.lhs_s == '{VAL_DESC_DISJUNCTION}'
sm_string = ''.join(
single_or_multi(val_desc)
for val_desc in val_desc_disjunction.children
)
# If a disjunction combines multi-valued terms (types)
# with single-valued terms (constants/literals),
# all the multis should come before all the singles.
if re.fullmatch(r'(M*)(S*)', sm_string):
pass
else:
msg_at_node(
val_desc_disjunction,
f"In a VAL_DESC_DISJUNCTION, the multi-valued terms should come before the single-valued terms, but here the terms are '{sm_string}'"
)
# -----------------
# And then there are rules about whether the disjunction
# should be preceded by 'either', 'one of', or nothing.
value_description = val_desc_disjunction.parent
assert value_description.prod.lhs_s == '{VALUE_DESCRIPTION}'
assert value_description.prod.rhs_s.endswith('{VAL_DESC_DISJUNCTION}')
prefix = value_description.prod.rhs_s.removesuffix('{VAL_DESC_DISJUNCTION}').rstrip()
# See https://github.com/tc39/ecma262/pull/2972#issuecomment-1372894434
gparent_prod = value_description.parent.prod
if str(gparent_prod) in [
'{CONDITION_1} : {EX} is {VALUE_DESCRIPTION}',
'{CONDITION_1} : {EX} is not {VALUE_DESCRIPTION}',
'{VAL_DESC} : a normal completion containing {VALUE_DESCRIPTION}',
'{VAL_DESC} : an Abstract Closure that takes {VAL_DESC} and {VAL_DESC} and returns {VALUE_DESCRIPTION}',
]:
# This is a 'prose' context.
# The prefix should be "one of" only in the case where
# there are 3+ disjuncts and all are single-valued.
# Otherwise, it should be "either".
preferred_prefix = 'one of' if re.fullmatch(r'SSS+', sm_string) else 'either'
elif (
gparent_prod.lhs_s in ['{H1_BODY}', '{PARAMETER_DECL}', '{FIELD_VALUE_TYPE}']
or
str(gparent_prod).startswith('{VAL_DESC} : a Record with fields')
or
str(gparent_prod) == '{VALUE_DESCRIPTION} : {VAL_DESC}, but not {VALUE_DESCRIPTION}'
):
# This is a 'declaration' context.
# It doesn't need a prefix, unless the result would be ambiguous.
vd0 = val_desc_disjunction.children[0]
if vd0.prod.rhs_s == 'a normal completion containing {VALUE_DESCRIPTION}':
# would be ambiguous without a prefix
preferred_prefix = 'either'
else:
preferred_prefix = ''
else:
assert 0, str(gparent_prod)
if prefix != preferred_prefix:
msg_at_node(
val_desc_disjunction,
f"this VAL_DESC_DISJUNCTION should be preceded by '{preferred_prefix}' rather than '{prefix}'"
)
# The other way to accomplish the discrimination
# between 'prose' contexts and 'declaration' contexts
# would be to change pseudocode.grammar, splitting {VALUE_DESCRIPTION}
# (into, say, {PROSE_VALUE_DESCRIPTION} and {DECL_VALUE_DESCRIPTION}),
# and changing each occurrence of {VALUE_DESCRIPTION} to one of those
# as appropriate.
# Then here, just look at val_desc_disjunction.parent.prod.lhs_s.
def single_or_multi(val_desc):
assert val_desc.prod.lhs_s == '{VAL_DESC}'
# Return 'M' if {val_desc} is a multi-valued description (type),
# or 'S' if it is a single-valued description (constant/literal).
r = val_desc.prod.rhs_s
if r.startswith(('a ', 'an ', 'an? ', 'any', 'some ')):
return 'M'
if r in [
'ECMAScript source text',
'source text',
'the Environment Record for a |Catch| clause',
'the execution context of a generator',
'the single code point {code_point_lit} or {code_point_lit}',
'the {nonterminal} of an? {nonterminal}',
]:
return 'M'
if r in [
'-1',
'{LITERAL_ISH}',
'{LITERAL}',
'{nonterminal}',
]:
return 'S'
assert 0, r
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def analyze_static_dependencies():
f_deps = shared.open_for_output('static_deps')
def put(*args):
print(*args, file=f_deps)
def put_names(header, names):
put()
put(header + ':')
if names:
for name in sorted(names):
put(f" {name}")
else:
put(" (none)")
# ----------------------------------------------------
# Find and print all the static dependencies:
for (alg_name, alg_info) in (
sorted(spec.alg_info_['op'].items())
+
sorted(spec.alg_info_['bif'].items())
):
for alg_defn in alg_info.all_definitions():
alg_defn.callees = set()
def recurse(anode):
for d in anode.each_descendant_or_self():
if hasattr(d, '_op_invocation'):
(callee_names, args) = d._op_invocation
for callee_name in callee_names:
alg_defn.callees.add(callee_name)
if callee_name in spec.alg_info_['op']:
spec.alg_info_['op'][callee_name].invocations.append(d)
else:
stderr(f"spec.alg_info_['op'] has no entry for {callee_name!r} ({alg_name} calls it in {alg_defn.parent_header.section.section_num})")
elif hasattr(d, '_hnode') and hasattr(d._hnode, '_syntax_tree'):
assert alg_name == 'Early Errors'
# "... and the following algorithm evaluates to *true*: ..."
recurse(d._hnode._syntax_tree)
for anode in alg_defn.anodes:
if anode: recurse(anode)
alg_info.callees.update(alg_defn.callees)
if alg_name == 'HostLoadImportedModule':
assert len(alg_info.all_definitions()) == 0
# There's just a list of requirements
# that the implementation must conform to.
# But one of those is that it has to invoke FinishLoadingImportedModule.
alg_info.callees.add('FinishLoadingImportedModule')
put()
put(alg_name)
put(f"[{alg_info.species}, {len(alg_info.all_definitions())} definitions]")
for callee in sorted(alg_info.callees):
put(' ', callee)
for callee_name in alg_info.callees:
if callee_name in spec.alg_info_['op']:
spec.alg_info_['op'][callee_name].callers.add(alg_name)
else:
stderr(f"spec.alg_info_['op'] has no entry for {callee_name!r} ({alg_name} calls it)")
# ----------------------------------------------------
# Starting at known "top-level" points,
# do a depth-first search of the dependency graph,
# marking which operations are "reached".
op_names_with_no_info = set()
def reach_op(op_name, level):
if op_name in op_names_with_no_info:
# No point in continuing.
return
# put(' '*level, op_name)
if op_name not in spec.alg_info_['op']:
op_names_with_no_info.add(op_name)
return
op_info = spec.alg_info_['op'][op_name]
if hasattr(op_info, '_reached'): return
op_info._reached = True
for callee_name in sorted(list(op_info.callees)):
reach_op(callee_name, level+1)
reach_op('Early Errors', 0)
if True: # PR #1597 has been merged
reach_op('InitializeHostDefinedRealm', 1)
# ScriptEvaluationJob, 1
reach_op('ParseScript', 2)
reach_op('ScriptEvaluation', 2)
# TopLevelModuleEvaluationJob, 1
reach_op('ParseModule', 2)
reach_op('Link', 2)
reach_op('Evaluate', 2)
else:
reach_op('RunJobs', 0)
# The spec doesn't invoke, but the host can:
reach_op('DetachArrayBuffer', 0)
# Memory Model
# put('Valid Executions')
# references things via bullet point prose
# put(' '*1, 'host-synchronizes-with')
reach_op('HostEventSet', 2)
reach_op('Valid Chosen Reads', 1)
reach_op('Coherent Reads', 1)
reach_op('Tear Free Reads', 1)
#
reach_op('Data Races', 0)
for (bif_name, bif_info) in sorted(spec.alg_info_['bif'].items()):
# put(bif_name)
for callee in sorted(bif_info.callees):
reach_op(callee, 1)
# --------------
# Print out dependency anomalies.
put()
put('X' * 40)
put_names(
'operations referenced but not declared',
op_names_with_no_info
)
put()
put('operations declared but not reached:')
for (op_name, op_info) in sorted(spec.alg_info_['op'].items()):
if not hasattr(op_info, '_reached'):
put(f" {op_name}")
# ===================================================================
# Static Semantics
put()
put('X' * 40)
op_names_labelled_ss = set()
op_names_labelled_rs = set()
op_names_not_labelled = set()
for section in spec.root_section.each_descendant_that_is_a_section():
if section.alg_headers == []: continue
op_name = section.alg_headers[0].name
if section.section_title.startswith('Static Semantics:'):
op_names_labelled_ss.add(op_name)
elif section.section_title.startswith('Runtime Semantics:'):
op_names_labelled_rs.add(op_name)
else:
op_names_not_labelled.add(op_name)
ss_and_rs = op_names_labelled_ss & op_names_labelled_rs
ss_and_un = op_names_labelled_ss & op_names_not_labelled
rs_and_un = op_names_labelled_rs & op_names_not_labelled
put_names(
"ops labelled both 'Static Semantics' and 'Runtime Semantics'",
ss_and_rs
)
put_names(
"ops labelled 'Static Semantics' and also unlabelled",
ss_and_un
)