-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSection.py
4033 lines (3365 loc) · 151 KB
/
Section.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
# ecmaspeak-py/Section.py:
# Identify "sections" in the spec, and ascertain their 'kind'.
#
# Copyright (C) 2018 J. Michael Dyck <[email protected]>
import re, string, time, pdb, types
import shared
from shared import stderr, msg_at_node, msg_at_posn, spec
from HTML import HNode
import Pseudocode
import function_preambles as fpr
import intrinsics
from intrinsics import get_pdn, S_Property, S_InternalSlot
from algos import ensure_alg, AlgParam, AlgHeader, AlgDefn, write_header_info, check_alg_consistency
import records
from NodeGrammar import NodeGrammar
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def make_and_check_sections():
stderr("make_and_check_sections ...")
fpr.oh_inc_f = shared.open_for_output('oh_warnings')
spec.root_section = _make_section_tree(spec.doc_node)
_set_section_identification_r(spec.root_section, None)
t_start = time.time()
prev_top_level_num = ''
for section in spec.root_section.each_descendant_that_is_a_section():
# "progress bar"
top_level_num = section.section_num.split('.')[0]
if top_level_num != prev_top_level_num:
stderr(f" {top_level_num}", end='', flush=True)
prev_top_level_num = top_level_num
_set_section_kind(section)
stderr()
t_end = time.time()
stderr(f"analyzing sections took {t_end-t_start:.2f} seconds")
Pseudocode.check_emu_alg_coverage()
Pseudocode.check_emu_eqn_coverage()
Pseudocode.report_all_parsers()
fpr.oh_inc_f.close()
fpr.note_unused_rules()
_print_section_kinds()
_print_unused_ispl()
_print_intrinsic_facts()
_check_aoids()
_check_section_order()
write_header_info()
check_alg_consistency()
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def _make_section_tree(doc_node):
# We traverse the spec's doc-tree to find all the sections.
# Each section is a pre-existing HNode --
# mainly every <emu-clause>, but also every <emu-annex>,
# one <emu-intro>, and the <body> element.
#
# Each HNode is already connected to its HNode children,
# but we connect each section to its children in a different way.
# Thus, we establish an alternative tree by which to traverse the document.
# (The <body> node becomes the root of the section-tree.)
# Set section attributes:
# .section_level
# .is_root_section
# .block_children
# .numless_children
# .section_children
# .heading_child
# .bcen_{list,str,set}
assert doc_node.element_name == '#DOC'
_make_section_tree_r(doc_node, 0)
return doc_node
def _make_section_tree_r(section, section_level):
section.section_level = section_level
section.is_root_section = (section_level == 0)
assert not section.inline_child_element_names
# if section.inline_child_element_names:
# msg_at_node(
# section,
# "'section' node contains inline items"
# )
section.block_children = []
section.numless_children = []
section.section_children = []
for child in section.children:
if child.is_whitespace():
pass
elif child.element_name == '#COMMENT':
pass
elif child.is_a_section():
section.section_children.append(child)
elif child.element_name == 'h2':
numless = Numless( child.inner_source_text() )
section.numless_children.append(numless)
elif section.numless_children:
section.numless_children[-1].block_children.append(child)
else:
section.block_children.append(child)
if section.is_root_section:
section.heading_child = None
else:
h1 = section.block_children.pop(0)
assert h1.element_name == 'h1'
section.heading_child = h1
if (
len(section.block_children) == 0
and
len(section.numless_children) == 0
and
len(section.section_children) == 0
):
msg_at_node(
section,
"section is empty!"
)
_set_bcen_attributes(section)
for child in section.section_children:
_make_section_tree_r(child, section_level+1)
# -------------
class Numless:
# A numberless part of a section. Starts with an h2.
def __init__(self, title):
self.title = title
self.block_children = []
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def _set_section_identification_r(section, section_num):
# Set section attributes:
# .section_num
# .section_id
# .section_title
section.section_num = section_num
if section.is_root_section:
section.section_id = None
section.section_title = None
clause_counter = 0
annex_counter = 0
for child in section.section_children:
if child.element_name == 'emu-intro':
sn = '0'
elif child.element_name == 'emu-clause':
clause_counter += 1
sn = str(clause_counter)
elif child.element_name == 'emu-annex':
sn = string.ascii_uppercase[annex_counter]
annex_counter += 1
else:
assert 0, child.element_name
_set_section_identification_r(child, sn)
else:
section.section_id = section.attrs['id']
section.section_title = section.heading_child.inner_source_text()
child_clause_counter = 0
for child in section.section_children:
child_clause_counter += 1
sn = section_num + '.' + str(child_clause_counter)
_set_section_identification_r(child, sn)
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def _set_section_kind(section):
# Set section attributes:
# .section_kind
# .section_title
# .alg_headers
section.has_structured_header = False
section.alg_headers = []
r = (
_handle_root_section(section)
or
_handle_early_errors_section(section)
or
_handle_sdo_section(section)
or
_handle_oddball_op_section(section)
or
_handle_other_op_section(section)
or
_handle_function_section(section)
or
_handle_changes_section(section)
or
_handle_other_section(section)
)
assert r
check_id(section)
extract_intrinsic_info(section)
ensure_every_emu_alg_in_section_is_parsed(section)
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def ensure_every_emu_alg_in_section_is_parsed(section):
# Ensure that we've parsed every <emu-alg>
# for which this is the closet-containing section.
# (Eventually, these should be reached by 'normal' means.)
for bc in section.block_children:
for emu_alg in bc.each_descendant_named('emu-alg'):
if hasattr(emu_alg, '_syntax_tree'):
# already done
continue
if spec.text.startswith(
(
'\n 1. Top-level step',
# 5.2 Algorithm Conventions
# This is just showing the format of algorithms,
# so it's not meant to be parsable.
'\n 1. Otherwise, let ',
# 7.1.12.1 NumberToString
# The is unparsable because the grammar doesn't
# allow an "Otherwise" without a preceding "If",
# and I don't want to warp the grammar to allow it.
),
emu_alg.inner_start_posn,
emu_alg.inner_end_posn
):
# unparsable, so don't try
emu_alg._syntax_tree = None
continue
# print('\n!', section.section_num, section.section_title)
Pseudocode.parse(emu_alg)
# Most of these are involved in the definition of shorthands,
# which I don't handle well.
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def _handle_root_section(section):
if section.is_root_section:
return True
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def _handle_early_errors_section(section):
if section.section_title != 'Static Semantics: Early Errors':
return False
section.section_kind = 'early_errors'
alg_header = AlgHeader_make(
section = section,
species = 'op: discriminated by syntax: early error',
name = 'Early Errors',
params = [],
node_at_end_of_header = section.heading_child,
)
patterns = [
(
# 89 cases, the vast majority
['emu-grammar', 'ul'],
lambda emu_grammar, ul: (emu_grammar, None, ul)
),
(
# 1 case (13.2.5.1 Static Semantics: Early Errors)
# sec-object-initializer-static-semantics-early-errors
# Extra <p> constrains application of subsequent 2 emu-grammar+ul pairs.
[
('p', '.+ the following Early Error rules .+ not applied .+'),
'emu-grammar',
'ul',
'emu-note',
'emu-grammar',
'ul',
],
lambda p, emu_grammar1, ul1, emu_note, emu_grammar2, ul2: [
(emu_grammar1, p, ul1),
(emu_grammar2, p, ul2),
]
),
(
# 1 case (B.1.4.1 "Static Semantics: Early Errors")
[ ('p', 'The semantics of <emu-xref href="#[^"]+"></emu-xref> is extended as follows:') ],
None
),
(
# 1 case (B.1.4.1 "Static Semantics: Early Errors")
[ ('p', 'Additionally, the rules for the following productions are modified with the addition of the <ins>highlighted</ins> text:') ],
None
),
(
# 18 cases
['emu-note'],
None
),
]
bodies = scan_section(section, patterns)
for body in bodies:
assert isinstance(body, tuple)
(emu_grammar, p, ul) = body
EarlyErrorAlgDefn(alg_header, emu_grammar, ul, p)
return True
# ------------------------------------------------------------------------------
class EarlyErrorAlgDefn(AlgDefn):
# An early error block consists of:
# - an <emu-grammar> element (containing 1 or more productions),
# - a <ul> element (containing 1 or more "It is a Syntax Error" items), and
# - rarely, a <p> element that constrains the applicability of the rules.
def __init__(self, alg_header, emu_grammar, ul, kludgey_p):
assert (
alg_header is None
# only for Annex B, because we want to syntax-check the rules,
# but not add them to the alg_header
or
isinstance(alg_header, AlgHeader)
)
assert (
isinstance(emu_grammar, HNode)
and
emu_grammar.element_name == 'emu-grammar'
)
assert (
isinstance(ul, HNode)
and
ul.element_name == 'ul'
)
assert kludgey_p is None or (
isinstance(kludgey_p, HNode)
and
kludgey_p.element_name == 'p'
)
self.parent_header = alg_header
self.emu_grammar = emu_grammar
self.ul = ul
self.kludgey_p = kludgey_p
# ----
self.emu_grammars = [emu_grammar]
self.lis = []
self.anodes = []
for li in ul.children:
if li.element_name == '#LITERAL':
assert li.source_text().isspace()
elif li.element_name == 'li':
self.lis.append(li)
tree = Pseudocode.parse(li, 'early_error')
if tree is None:
ee_rule = None
else:
assert tree.prod.lhs_s == '{EARLY_ERROR_RULE}'
[ee_rule] = tree.children
assert ee_rule.prod.lhs_s == '{EE_RULE}'
self.anodes.append(ee_rule)
else:
assert 0, li.element_name
# ----
if alg_header: alg_header.u_defns.append(self)
def get_puk_set(self):
return self.emu_grammar.puk_set
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def _handle_sdo_section(section):
# Since the merge of PR #2271,
# almost all SDO sections are identified by `type="sdo"`.
if section.attrs.get('type') == 'sdo':
if section.section_title == 'Runtime Semantics: Evaluation':
# These don't have a <dl class="header">,
# and so don't fit my idea of a structured header.
section.section_kind = 'syntax_directed_operation'
alg_header = AlgHeader_make(
section = section,
species = 'op: discriminated by syntax: steps',
name = 'Evaluation',
params = [],
node_at_end_of_header = section.heading_child
)
else:
alg_header = _handle_structured_header(section)
if alg_header is None: return True
else:
# But there are various clauses that don't get `type="sdo"`
# that we neverthless want to mark as SDO sections...
# A clause that only *partially* defines an SDO:
if section.section_title in [
'Runtime Semantics: MV',
'Static Semantics: MV',
]:
sdo_name = re.sub('.*: ', '', section.section_title)
# An Annex B clause that extends the semantics of a main-body SDO:
elif section.section_title in [
'Static Semantics: IsCharacterClass',
'Static Semantics: CharacterValue',
]:
# B.1.2.3
# B.1.2.4
sdo_name = re.sub('.*: ', '', section.section_title)
else:
# Anything else isn't an SDO section.
return False
section.section_kind = 'syntax_directed_operation'
params = []
return_nature_node = None
alg_header = AlgHeader_make(
section = section,
species = 'op: discriminated by syntax: steps',
name = sdo_name,
params = params,
node_at_end_of_header = section.heading_child,
return_nature_node = return_nature_node,
)
# ------------------------------------------------------------------------------
if 'ul' in section.bcen_set:
# The rules are given in one or more <ul> elements.
handle_inline_sdo_section_body(section, alg_header)
else:
patterns = [
(
# ~900 cases, the vast majority.
['emu-grammar', 'emu-alg'],
lambda emu_grammar, emu_alg: (emu_grammar, emu_alg)
),
(
# 3 cases
[
('p', r'Every grammar production alternative in this specification which is not listed below implicitly has the following default definition of \w+:'),
'emu-alg'
],
lambda p, emu_alg: (None, emu_alg)
),
(
# 2 cases in Annex B
[
('p', 'The semantics of <emu-xref [^<>]+></emu-xref> is extended as follows:'),
'emu-grammar',
'emu-alg'
],
lambda p, emu_grammar, emu_alg: (emu_grammar, emu_alg)
),
(
# 90 cases
['emu-note'],
None
),
(
# 2 cases:
#
# 13.5.3.1
# Evaluation of |UnaryExpression : `typeof` UnaryExpression|
# ends with "Return a String according to <reference to emu-table>."
# and then the emu-alg is followed by an emu-table.
#
# 22.2.1.4
# CharacterValue of |CharacterEscape :: ControlEscape| is
# "Return the code point value according to Table 59."
# and then the emu-alg is followed by an emu-table.
#
['emu-table'],
None
),
(
# 6 cases. They're basically Notes.
['p'],
None
),
]
bodies = scan_section(section, patterns)
for body in bodies:
(emu_grammar, emu_alg) = body
UsualSdoAlgDefn(alg_header, emu_grammar, emu_alg)
return True
class UsualSdoAlgDefn(AlgDefn):
def __init__(self, alg_header, emu_grammar, emu_alg):
assert isinstance(alg_header, AlgHeader)
assert (
emu_grammar is None
# and self.parent_header.name in ops_with_implicit_defns
or
isinstance(emu_grammar, HNode) and emu_grammar.element_name == 'emu-grammar'
)
assert isinstance(emu_alg, HNode) and emu_alg.element_name == 'emu-alg'
self.parent_header = alg_header
self.emu_grammar = emu_grammar
self.emu_alg = emu_alg
anode = Pseudocode.parse(emu_alg)
assert anode is None or anode.prod.lhs_s == '{EMU_ALG_BODY}'
self.emu_grammars = [emu_grammar]
self.anodes = [anode]
alg_header.u_defns.append(self)
def get_puk_set(self):
if self.emu_grammar is None:
puk = ('*default*', '', '')
puk_set = set([puk])
else:
puk_set = self.emu_grammar.puk_set
if not puk_set:
stderr(f"! sdo_coverage may be broken because no puk_set for {self.emu_grammar.source_text()}")
return puk_set
# ------------------------------------------------------------------------------
def handle_inline_sdo_section_body(section, alg_header):
for bc in section.block_children:
if bc.element_name == 'ul':
# Each <li> in the <ul> is an "inline SDO".
for ul_child in bc.children:
if ul_child.is_whitespace(): continue
assert ul_child.element_name == 'li'
InlineSdoAlgDefn(alg_header, ul_child)
elif bc.element_name == 'emu-table':
# "String Single Character Escape Sequences" in 12.8.4.1 "Static Semantics: SV"
# This table has info that is necessary for executing one of the SV rules,
# but we'll deal with it some other time?
pass
elif bc.element_name in ['p', 'emu-note']:
# In practice, in this context, a <p> is basically a Note.
pass
else:
assert 0, bc.element_name
class InlineSdoAlgDefn(AlgDefn):
def __init__(self, alg_header, li):
assert isinstance(alg_header, AlgHeader)
assert isinstance(li, HNode) and li.element_name == 'li'
self.parent_header = alg_header
self.li = li
self.emu_grammars = [* li.each_child_named('emu-grammar')]
assert len(self.emu_grammars) > 0
INLINE_SDO_RULE = Pseudocode.parse(li, 'inline_sdo')
if INLINE_SDO_RULE is None:
rule_expr_anode = None
else:
assert INLINE_SDO_RULE.prod.lhs_s == '{INLINE_SDO_RULE}'
[ISDO_RULE] = INLINE_SDO_RULE.children
assert str(ISDO_RULE.prod) == '{ISDO_RULE} : The {cap_word} {OF_PRODUCTIONS} is {EXPR}.'
[cap_word, of_productions, rule_expr_anode] = ISDO_RULE.children
[rule_sdo_name] = cap_word.children
assert rule_sdo_name == alg_header.name
emu_grammar_anodes = of_productions.children
assert len(self.emu_grammars) == len(emu_grammar_anodes)
for (emu_grammar_hnode, emu_grammar_anode) in zip(self.emu_grammars, emu_grammar_anodes):
emu_grammar_anode._hnode = emu_grammar_hnode
assert rule_expr_anode.prod.lhs_s == '{EXPR}'
self.anodes = [rule_expr_anode]
alg_header.u_defns.append(self)
def get_puk_set(self):
result = set()
for emu_grammar in self.emu_grammars:
result |= emu_grammar.puk_set
return result
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def _handle_oddball_op_section(section):
# This function handles a few specific cases where even though section doesn't have
# - a `type` attribute, or
# - a structured header, or
# - a preamble with standardized wording,
# we still want to treat it like an op.
if section.section_id in [
'sec-object-environment-records-createimmutablebinding-n-s',
'sec-module-environment-records-deletebinding-n',
]:
# The clause exists only to tell us that the concrete method is never used.
p = section.block_children[0]
assert p.element_name == 'p'
mo = re.fullmatch(
r'The (\w+) concrete method of (an? (\w+ Environment Record)) is never used within this specification.',
p.inner_source_text()
)
# Note that the start of this sentence looks like the start of a standardized preamble,
# so we have to detect these cases before _handle_other_op_section's call
# to _handle_header_with_std_preamble.
# There's roughly two approaches:
# - Create the thing, but make the body of it be (effectively) "Assert: False."
# - Don't create the thing. (So if there *is* an attempt to use it, the lookup will fail.)
# Let's try the latter.
# I.e., don't create anything, but return True to indicate that we've handled this section.
section.section_kind = 'env_rec_method_unused'
# Actually, if there's an attempt to invoke DeleteBinding on a module ER,
# and the module ER schema doesn't have anything for that method,
# the lookup *won't* fail, it will propagate up to the declarative ER schema,
# which *does* have a definition for that method, which might succeed.
# So we'd fail to detect that an unexpected thing had occurred.
# So we do want *something* in the schema to 'trap' the invocation.
(method_name, for_phrase, discriminator) = mo.groups()
# This is a bit kludgey.
# I could use _handle_header_with_std_preamble,
# but I'd have to tweak it somewhat, and I don't feel like it.
# Could maybe even leave these cases to _handle_other_op_section.
params = {
'CreateImmutableBinding': [
AlgParam('_N_', '', 'a String'),
AlgParam('_S_', '', 'a Boolean'),
],
'DeleteBinding': [
AlgParam('_N_', '', 'a String'),
],
}[method_name]
alg_header = AlgHeader_make(
section = section,
species = 'op: discriminated by type: env rec',
name = method_name,
params = params,
node_at_end_of_header = p,
for_phrase = for_phrase,
)
rs = spec.RecordSchema_for_name_[discriminator.title()]
rs.add_method_defn(records.MethodDefn(alg_header, None))
return True
# ----
if section.section_id == 'sec-weakref-execution':
# 9.10.3
op_name = 'WeakRef emptying thing'
assert section.block_children[0].source_text().startswith(
"<p>At any time, if a set of objects and/or symbols _S_ is not live,"
)
params = [ AlgParam('_S_', '', 'a List of Objects and/or Symbols') ]
elif section.section_title in [
'Valid Chosen Reads',
'Coherent Reads',
'Tear Free Reads',
]:
# 29.7.*
op_name = section.section_title
assert section.block_children[0].source_text().startswith(
"<p>A candidate execution _execution_ has "
)
params = [ AlgParam('_execution_', '', 'an execution') ]
elif section.section_title in [
'Races',
'Data Races',
]:
# 29.8, 29.9
op_name = section.section_title
assert section.block_children[0].source_text().startswith(
"<p>For an execution _execution_ and events _E_ and _D_ that are contained in SharedDataBlockEventSet(_execution_)"
)
params = [
AlgParam('_execution_', '', 'an execution'),
AlgParam('_E_' , '', 'an event in SharedDataBlockEventSet(_execution_)'),
AlgParam('_D_' , '', 'an event in SharedDataBlockEventSet(_execution_)'),
]
else:
return False
# --------------------------------------------
section.section_kind = 'abstract_operation'
fpr.oh_warn()
fpr.oh_warn(f"In {section.section_num} {section.section_title} ({section.section_id}),")
fpr.oh_warn(f"there is a non-standard preamble")
alg_header = AlgHeader_make(
section = section,
species = 'op: singular',
name = op_name,
params = params,
node_at_end_of_header = section.heading_child,
)
emu_alg = section.block_children[1]
assert emu_alg.element_name == 'emu-alg'
SimpleAlgDefn(alg_header, emu_alg)
return True
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def _handle_other_op_section(section):
section_type = section.attrs.get('type')
if section_type == 'sdo':
assert 0 # Would have been handled already
return False
elif section_type is not None:
# type="sdo" has been around for a while,
# but all the other type="..." attributes were introduced in PR #545.
# So we can assume that this section has a structured header?
# (Or might authors add a `type` attribute but use an old-style header?)
alg_header = _handle_structured_header(section)
if alg_header is None: return True
elif (alg_header := _handle_header_with_std_preamble(section)):
pass
else:
return False
# --------------------------------------------------------------------------
op_species = alg_header.species
op_name = alg_header.name
n_emu_algs = section.bcen_list.count('emu-alg')
if n_emu_algs == 0:
emu_alg = None
elif n_emu_algs == 1:
emu_alg_posn = section.bcen_list.index('emu-alg')
emu_alg = section.block_children[emu_alg_posn]
assert emu_alg.element_name == 'emu-alg'
else:
assert 0, n_emu_algs
if emu_alg is None and 'emu-table' in section.bcen_set:
assert section.bcen_str == 'emu-table' # it turns out
[emu_table] = section.block_children
handle_op_table(emu_table, alg_header)
elif section.section_kind in [
'host-defined_abstract_operation',
'implementation-defined_abstract_operation',
]:
if emu_alg is None:
# That's what we'd expect.
# Typically, there's a <ul> containing
# requirements that the implementation must conform to.
pass
else:
# 3 cases:
# - 9.5.2 HostMakeJobCallback
# - 9.5.3 HostCallJobCallback
# - 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob
# In the first two, the <emu-alg> is a default implementation,
# which is actually required for non-browsers.
# In the last, the <emu-alg> is the steps of an Abstract Closure
# that defines the job to be scheduled.
#
# TODO: Handle these better.
SimpleAlgDefn(alg_header, emu_alg)
elif emu_alg is None:
assert 0, (section.section_num, section.section_title)
else:
# The emu-alg is the 'body' of
# (this definition of) the operation named by the section_title.
if alg_header.for_phrase is None:
SimpleAlgDefn(alg_header, emu_alg)
else:
# type-discriminated operation
mo = re.fullmatch(r'an? (.+?)( _\w+_)?', alg_header.for_phrase)
type_str = mo.group(1)
TypeDirectedAlgDefn(alg_header, type_str, emu_alg)
if section.section_kind.endswith('_rec_method'):
assert len(alg_header.u_defns) == 1
[alg_defn] = alg_header.u_defns
rs = spec.RecordSchema_for_name_[type_str.title()]
rs.add_method_defn(records.MethodDefn(alg_header, alg_defn))
# -----------------------------------------
if section.section_id == 'sec-maybesimplecasefolding':
ensure_alg('op: singular', 'scf')
return True
class SimpleAlgDefn(AlgDefn):
def __init__(self, alg_header, emu_alg):
assert isinstance(alg_header, AlgHeader)
assert isinstance(emu_alg, HNode) and emu_alg.element_name == 'emu-alg'
self.parent_header = alg_header
self.emu_alg = emu_alg
anode = Pseudocode.parse(emu_alg, None)
assert anode is None or anode.prod.lhs_s == '{EMU_ALG_BODY}'
self.anodes = [anode]
alg_header.u_defns.append(self)
class TypeDirectedAlgDefn(AlgDefn):
def __init__(self, alg_header, type_str, emu_alg):
assert isinstance(alg_header, AlgHeader)
assert isinstance(type_str, str)
assert isinstance(emu_alg, HNode) and emu_alg.element_name == 'emu-alg'
self.parent_header = alg_header
self.type_str = type_str
self.emu_alg = emu_alg
anode = Pseudocode.parse(emu_alg)
assert anode is None or anode.prod.lhs_s == '{EMU_ALG_BODY}'
self.anodes = [anode]
alg_header.u_defns.append(self)
# ------------------------------------------------------------------------------
def handle_op_table(emu_table, alg_header):
# The op is defined by a table that splits on argument type.
# I.e., each row has two cells:
# - The first cell is the name of an ES language type.
# - The second cell is a little algorithm,
# but it's generally not marked as an emu-alg.
assert emu_table.element_name == 'emu-table'
(_, table, _) = emu_table.children
assert table.element_name == 'table'
for tr in table.each_child_named('tr'):
(_, a, _, b, _) = tr.children
if a.element_name == 'th' and b.element_name == 'th':
assert a.inner_source_text().strip() == 'Argument Type'
assert b.inner_source_text().strip() == 'Result'
continue
TabularAlgDefn(alg_header, tr)
class TabularAlgDefn(AlgDefn):
def __init__(self, alg_header, tr):
assert isinstance(alg_header, AlgHeader)
assert isinstance(tr, HNode) and tr.element_name == 'tr'
self.parent_header = alg_header
self.tr = tr
(_, type_td, _, result_td, _) = tr.children
assert type_td.element_name == 'td'
assert result_td.element_name == 'td'
self.type_str = type_td.inner_source_text().strip()
x = ' '.join(c.element_name for c in result_td.children)
if x == '#LITERAL p #LITERAL emu-alg #LITERAL':
(_, p, _, emu_alg, _) = result_td.children
assert p.source_text() == '<p>Apply the following steps:</p>'
anode = Pseudocode.parse(emu_alg)
assert anode is None or anode.prod.lhs_s == '{EMU_ALG_BODY}'
elif x in [
'#LITERAL',
'#LITERAL emu-xref #LITERAL',
'#LITERAL sub #LITERAL',
'#LITERAL sub #LITERAL sub #LITERAL',
'#LITERAL emu-note #LITERAL',
# ToBoolean: row for 'Object' has a NOTE re [[IsHTMLDDA]]
'#LITERAL p #LITERAL p #LITERAL',
]:
anode = Pseudocode.parse(result_td, 'one_line_alg')
assert anode is None or anode.prod.lhs_s == '{ONE_LINE_ALG}'
else:
assert 0, x
self.anodes = [anode]
alg_header.u_defns.append(self)
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
other_op_species_for_section_kind_ = {
'syntax_directed_operation' : 'op: discriminated by syntax: steps',
'env_rec_method' : 'op: discriminated by type: env rec',
'module_rec_method' : 'op: discriminated by type: module rec',
'internal_method' : 'op: discriminated by type: object',
'abstract_operation' : 'op: singular',
'numeric_method' : 'op: singular: numeric method',
'host-defined_abstract_operation' : 'op: singular: host-defined',
'implementation-defined_abstract_operation': 'op: singular: implementation-defined',
}
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def _handle_structured_header(section):
section.has_structured_header = True
dl = section.block_children.pop(0)
assert dl.element_name == 'dl'
assert dl.attrs.get('class') == 'header'
section.dl_child = dl
_set_bcen_attributes(section)
section_type = section.attrs.get('type')
if section_type == 'concrete method':
if section.parent.parent.section_id == 'sec-the-environment-record-type-hierarchy':
section.section_kind = 'env_rec_method'
elif section.parent.parent.section_id == 'sec-module-semantics':
section.section_kind = 'module_rec_method'
else:
assert 0, section.section_id
else:
section.section_kind = {
'abstract operation': 'abstract_operation',
'numeric method' : 'numeric_method',
'internal method' : 'internal_method',
'sdo' : 'syntax_directed_operation',
'host-defined abstract operation' : 'host-defined_abstract_operation',
'implementation-defined abstract operation': 'implementation-defined_abstract_operation',
}[section_type]
# --------------------------------------------
h1 = section.heading_child