forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathidl_parser.py
executable file
·1251 lines (1080 loc) · 40 KB
/
idl_parser.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/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parser for Web IDL."""
#
# IDL Parser
#
# The parser is uses the PLY yacc library to build a set of parsing rules based
# on Web IDL.
#
# Web IDL, and Web IDL grammar can be found at:
# http://heycam.github.io/webidl/
# PLY can be found at:
# http://www.dabeaz.com/ply/
#
# The parser generates a tree by recursively matching sets of items against
# defined patterns. When a match is made, that set of items is reduced
# to a new item. The new item can provide a match for parent patterns.
# In this way an AST is built (reduced) depth first.
#
#
# Disable check for line length and Member as Function due to how grammar rules
# are defined with PLY
#
# pylint: disable=R0201
# pylint: disable=C0301
import os.path
import sys
import time
from idl_lexer import IDLLexer
from idl_node import IDLAttribute
from idl_node import IDLNode
SRC_DIR = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
sys.path.insert(0, os.path.join(SRC_DIR, 'third_party'))
from ply import lex
from ply import yacc
#
# ERROR_REMAP
#
# Maps the standard error formula into a more friendly error message.
#
ERROR_REMAP = {
'Unexpected ")" after "(".' : 'Empty argument list.',
'Unexpected ")" after ",".' : 'Missing argument.',
'Unexpected "}" after ",".' : 'Trailing comma in block.',
'Unexpected "}" after "{".' : 'Unexpected empty block.',
'Unexpected comment after "}".' : 'Unexpected trailing comment.',
'Unexpected "{" after keyword "enum".' : 'Enum missing name.',
'Unexpected "{" after keyword "struct".' : 'Struct missing name.',
'Unexpected "{" after keyword "interface".' : 'Interface missing name.',
}
def Boolean(val):
"""Convert to strict boolean type."""
if val:
return True
return False
def ListFromConcat(*items):
"""Generate list by concatenating inputs"""
itemsout = []
for item in items:
if item is None:
continue
if type(item) is not type([]):
itemsout.append(item)
else:
itemsout.extend(item)
return itemsout
def ExpandProduction(p):
if type(p) == list:
return '[' + ', '.join([ExpandProduction(x) for x in p]) + ']'
if type(p) == IDLNode:
return 'Node:' + str(p)
if type(p) == IDLAttribute:
return 'Attr:' + str(p)
if type(p) == str:
return 'str:' + p
return '%s:%s' % (p.__class__.__name__, str(p))
# TokenTypeName
#
# Generate a string which has the type and value of the token.
#
def TokenTypeName(t):
if t.type == 'SYMBOL':
return 'symbol %s' % t.value
if t.type in ['HEX', 'INT', 'OCT', 'FLOAT']:
return 'value %s' % t.value
if t.type == 'string' :
return 'string "%s"' % t.value
if t.type == 'SPECIAL_COMMENT':
return 'comment'
if t.type == t.value:
return '"%s"' % t.value
if t.type == ',':
return 'Comma'
if t.type == 'identifier':
return 'identifier "%s"' % t.value
return 'keyword "%s"' % t.value
# TODO(bashi): Consider moving this out of idl_parser.
def ExtractSpecialComment(comment):
if not comment.startswith('/**'):
raise ValueError('Special comment must start with /**')
if not comment.endswith('*/'):
raise ValueError('Special comment must end with */')
# Remove comment markers
lines = []
for line in comment[2:-2].split('\n'):
# Remove characters until start marker for this line '*' if found
# otherwise it will be blank.
offs = line.find('*')
if offs >= 0:
line = line[offs + 1:].rstrip()
else:
# TODO(bashi): We may want to keep |line| as is.
line = ''
lines.append(line)
return '\n'.join(lines)
#
# IDL Parser
#
# The Parser inherits the from the Lexer to provide PLY with the tokenizing
# definitions. Parsing patterns are encoded as functions where p_<name> is
# is called any time a patern matching the function documentation is found.
# Paterns are expressed in the form of:
# """ <new item> : <item> ....
# | <item> ...."""
#
# Where new item is the result of a match against one or more sets of items
# separated by the "|".
#
# The function is called with an object 'p' where p[0] is the output object
# and p[n] is the set of inputs for positive values of 'n'. Len(p) can be
# used to distinguish between multiple item sets in the pattern.
#
# The rules can look cryptic at first, but there are a few standard
# transforms from the CST to AST. With these in mind, the actions should
# be reasonably legible.
#
# * Ignore production
# Discard this branch. Primarily used when one alternative is empty.
#
# Sample code:
# if len(p) > 1:
# p[0] = ...
# # Note no assignment if len(p) == 1
#
# * Eliminate singleton production
# Discard this node in the CST, pass the next level down up the tree.
# Used to ignore productions only necessary for parsing, but not needed
# in the AST.
#
# Sample code:
# p[0] = p[1]
#
# * Build node
# The key type of rule. In this parser, produces object of class IDLNode.
# There are several helper functions:
# * BuildProduction: actually builds an IDLNode, based on a production.
# * BuildAttribute: builds an IDLAttribute, which is a temporary
# object to hold a name-value pair, which is then
# set as a Property of the IDLNode when the IDLNode
# is built.
# * BuildNamed: Same as BuildProduction, and sets the 'NAME' property.
# * BuildTrue: BuildAttribute with value True, for flags.
#
# Sample code:
# # Build node of type NodeType, with value p[1], and children.
# p[0] = self.BuildProduction('NodeType', p, 1, children)
#
# # Build named node of type NodeType, with name and value p[1].
# # (children optional)
# p[0] = self.BuildNamed('NodeType', p, 1)
#
# # Make a list
# # Used if one node has several children.
# children = ListFromConcat(p[2], p[3])
# p[0] = self.BuildProduction('NodeType', p, 1, children)
#
# # Also used to collapse the right-associative tree
# # produced by parsing a list back into a single list.
# """Foos : Foo Foos
# |"""
# if len(p) > 1:
# p[0] = ListFromConcat(p[1], p[2])
#
# # Add children.
# # Primarily used to add attributes, produced via BuildTrue.
# # p_StaticAttribute
# """StaticAttribute : STATIC Attribute"""
# p[2].AddChildren(self.BuildTrue('STATIC'))
# p[0] = p[2]
#
# For more details on parsing refer to the PLY documentation at
# http://www.dabeaz.com/ply/
#
# The parser is based on the Web IDL standard. See:
# http://heycam.github.io/webidl/#idl-grammar
#
# Productions with a fractional component in the comment denote additions to
# the Web IDL spec, such as allowing string list in extended attributes.
class IDLParser(object):
def p_Definitions(self, p):
"""Definitions : ExtendedAttributeList Definition Definitions
| """
if len(p) > 1:
p[2].AddChildren(p[1])
p[0] = ListFromConcat(p[2], p[3])
def p_Definition(self, p):
"""Definition : CallbackOrInterface
| Partial
| Dictionary
| Enum
| Typedef
| ImplementsStatement"""
p[0] = p[1]
# Error recovery for definition
def p_DefinitionError(self, p):
"""Definition : error ';'"""
p[0] = self.BuildError(p, 'Definition')
def p_CallbackOrInterface(self, p):
"""CallbackOrInterface : CALLBACK CallbackRestOrInterface
| Interface"""
if len(p) > 2:
p[2].AddChildren(self.BuildTrue('CALLBACK'))
p[0] = p[2]
else:
p[0] = p[1]
def p_CallbackRestOrInterface(self, p):
"""CallbackRestOrInterface : CallbackRest
| Interface"""
p[0] = p[1]
def p_Interface(self, p):
"""Interface : INTERFACE identifier Inheritance '{' InterfaceMembers '}' ';'"""
p[0] = self.BuildNamed('Interface', p, 2, ListFromConcat(p[3], p[5]))
# Error recovery for interface.
def p_InterfaceError(self, p):
"""Interface : INTERFACE identifier Inheritance '{' error"""
p[0] = self.BuildError(p, 'Interface')
def p_Partial(self, p):
"""Partial : PARTIAL PartialDefinition"""
p[2].AddChildren(self.BuildTrue('Partial'))
p[0] = p[2]
# Error recovery for Partial
def p_PartialError(self, p):
"""Partial : PARTIAL error"""
p[0] = self.BuildError(p, 'Partial')
def p_PartialDefinition(self, p):
"""PartialDefinition : PartialDictionary
| PartialInterface"""
p[0] = p[1]
def p_PartialInterface(self, p):
"""PartialInterface : INTERFACE identifier '{' InterfaceMembers '}' ';'"""
p[0] = self.BuildNamed('Interface', p, 2, p[4])
def p_InterfaceMembers(self, p):
"""InterfaceMembers : ExtendedAttributeList InterfaceMember InterfaceMembers
|"""
if len(p) > 1:
p[2].AddChildren(p[1])
p[0] = ListFromConcat(p[2], p[3])
# Error recovery for InterfaceMembers
def p_InterfaceMembersError(self, p):
"""InterfaceMembers : error"""
p[0] = self.BuildError(p, 'InterfaceMembers')
# Removed unsupported: Serializer
def p_InterfaceMember(self, p):
"""InterfaceMember : Const
| Operation
| Serializer
| Stringifier
| StaticMember
| Iterable
| ReadonlyMember
| ReadWriteAttribute
| ReadWriteMaplike
| ReadWriteSetlike"""
p[0] = p[1]
def p_Dictionary(self, p):
"""Dictionary : DICTIONARY identifier Inheritance '{' DictionaryMembers '}' ';'"""
p[0] = self.BuildNamed('Dictionary', p, 2, ListFromConcat(p[3], p[5]))
# Error recovery for regular Dictionary
def p_DictionaryError(self, p):
"""Dictionary : DICTIONARY error ';'"""
p[0] = self.BuildError(p, 'Dictionary')
# Error recovery for regular Dictionary
# (for errors inside dictionary definition)
def p_DictionaryError2(self, p):
"""Dictionary : DICTIONARY identifier Inheritance '{' error"""
p[0] = self.BuildError(p, 'Dictionary')
def p_DictionaryMembers(self, p):
"""DictionaryMembers : ExtendedAttributeList DictionaryMember DictionaryMembers
|"""
if len(p) > 1:
p[2].AddChildren(p[1])
p[0] = ListFromConcat(p[2], p[3])
# Error recovery for DictionaryMembers
def p_DictionaryMembersError(self, p):
"""DictionaryMembers : ExtendedAttributeList error"""
p[0] = self.BuildError(p, 'DictionaryMembers')
def p_DictionaryMember(self, p):
"""DictionaryMember : Required Type identifier Default ';'"""
p[0] = self.BuildNamed('Key', p, 3, ListFromConcat(p[1], p[2], p[4]))
def p_Required(self, p):
"""Required : REQUIRED
|"""
if len(p) > 1:
p[0] = self.BuildTrue('REQUIRED')
def p_PartialDictionary(self, p):
"""PartialDictionary : DICTIONARY identifier '{' DictionaryMembers '}' ';'"""
partial = self.BuildTrue('Partial')
p[0] = self.BuildNamed('Dictionary', p, 2, ListFromConcat(p[4], partial))
# Error recovery for Partial Dictionary
def p_PartialDictionaryError(self, p):
"""PartialDictionary : DICTIONARY error ';'"""
p[0] = self.BuildError(p, 'PartialDictionary')
def p_Default(self, p):
"""Default : '=' DefaultValue
|"""
if len(p) > 1:
p[0] = self.BuildProduction('Default', p, 2, p[2])
def p_DefaultValue(self, p):
"""DefaultValue : ConstValue
| string
| '[' ']'"""
if len(p) == 3:
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'sequence'),
self.BuildAttribute('VALUE', '[]'))
elif type(p[1]) == str:
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'DOMString'),
self.BuildAttribute('NAME', p[1]))
else:
p[0] = p[1]
def p_Inheritance(self, p):
"""Inheritance : ':' identifier
|"""
if len(p) > 1:
p[0] = self.BuildNamed('Inherit', p, 2)
def p_Enum(self, p):
"""Enum : ENUM identifier '{' EnumValueList '}' ';'"""
p[0] = self.BuildNamed('Enum', p, 2, p[4])
# Error recovery for Enums
def p_EnumError(self, p):
"""Enum : ENUM error ';'"""
p[0] = self.BuildError(p, 'Enum')
def p_EnumValueList(self, p):
"""EnumValueList : ExtendedAttributeList string EnumValueListComma"""
enum = self.BuildNamed('EnumItem', p, 2, p[1])
p[0] = ListFromConcat(enum, p[3])
def p_EnumValueListComma(self, p):
"""EnumValueListComma : ',' EnumValueListString
|"""
if len(p) > 1:
p[0] = p[2]
def p_EnumValueListString(self, p):
"""EnumValueListString : ExtendedAttributeList string EnumValueListComma
|"""
if len(p) > 1:
enum = self.BuildNamed('EnumItem', p, 2, p[1])
p[0] = ListFromConcat(enum, p[3])
def p_CallbackRest(self, p):
"""CallbackRest : identifier '=' ReturnType '(' ArgumentList ')' ';'"""
arguments = self.BuildProduction('Arguments', p, 4, p[5])
p[0] = self.BuildNamed('Callback', p, 1, ListFromConcat(p[3], arguments))
def p_Typedef(self, p):
"""Typedef : TYPEDEF ExtendedAttributeList Type identifier ';'"""
p[0] = self.BuildNamed('Typedef', p, 4, ListFromConcat(p[2], p[3]))
# Error recovery for Typedefs
def p_TypedefError(self, p):
"""Typedef : TYPEDEF error ';'"""
p[0] = self.BuildError(p, 'Typedef')
def p_ImplementsStatement(self, p):
"""ImplementsStatement : identifier IMPLEMENTS identifier ';'"""
name = self.BuildAttribute('REFERENCE', p[3])
p[0] = self.BuildNamed('Implements', p, 1, name)
def p_Const(self, p):
"""Const : CONST ConstType identifier '=' ConstValue ';'"""
value = self.BuildProduction('Value', p, 5, p[5])
p[0] = self.BuildNamed('Const', p, 3, ListFromConcat(p[2], value))
def p_ConstValue(self, p):
"""ConstValue : BooleanLiteral
| FloatLiteral
| integer
| null"""
if type(p[1]) == str:
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'integer'),
self.BuildAttribute('NAME', p[1]))
else:
p[0] = p[1]
# Add definition for NULL
def p_null(self, p):
"""null : NULL"""
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'NULL'),
self.BuildAttribute('NAME', 'NULL'))
def p_BooleanLiteral(self, p):
"""BooleanLiteral : TRUE
| FALSE"""
value = self.BuildAttribute('VALUE', Boolean(p[1] == 'true'))
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'boolean'), value)
def p_FloatLiteral(self, p):
"""FloatLiteral : float
| '-' INFINITY
| INFINITY
| NAN """
if len(p) > 2:
val = '-Infinity'
else:
val = p[1]
p[0] = ListFromConcat(self.BuildAttribute('TYPE', 'float'),
self.BuildAttribute('VALUE', val))
def p_Serializer(self, p):
"""Serializer : SERIALIZER SerializerRest"""
p[0] = self.BuildProduction('Serializer', p, 1, p[2])
# TODO(jl): This adds ReturnType and ';', missing from the spec's grammar.
# https://www.w3.org/Bugs/Public/show_bug.cgi?id=20361
def p_SerializerRest(self, p):
"""SerializerRest : ReturnType OperationRest
| '=' SerializationPattern ';'
| ';'"""
if len(p) == 3:
p[2].AddChildren(p[1])
p[0] = p[2]
elif len(p) == 4:
p[0] = p[2]
def p_SerializationPattern(self, p):
"""SerializationPattern : '{' SerializationPatternMap '}'
| '[' SerializationPatternList ']'
| identifier"""
if len(p) > 2:
p[0] = p[2]
else:
p[0] = self.BuildAttribute('ATTRIBUTE', p[1])
# TODO(jl): This adds the "ATTRIBUTE" and "INHERIT ',' ATTRIBUTE" variants,
# missing from the spec's grammar.
# https://www.w3.org/Bugs/Public/show_bug.cgi?id=20361
def p_SerializationPatternMap(self, p):
"""SerializationPatternMap : GETTER
| ATTRIBUTE
| INHERIT ',' ATTRIBUTE
| INHERIT Identifiers
| identifier Identifiers
|"""
p[0] = self.BuildProduction('Map', p, 0)
if len(p) == 4:
p[0].AddChildren(self.BuildTrue('INHERIT'))
p[0].AddChildren(self.BuildTrue('ATTRIBUTE'))
elif len(p) > 1:
if p[1] == 'getter':
p[0].AddChildren(self.BuildTrue('GETTER'))
elif p[1] == 'attribute':
p[0].AddChildren(self.BuildTrue('ATTRIBUTE'))
else:
if p[1] == 'inherit':
p[0].AddChildren(self.BuildTrue('INHERIT'))
attributes = p[2]
else:
attributes = ListFromConcat(p[1], p[2])
p[0].AddChildren(self.BuildAttribute('ATTRIBUTES', attributes))
def p_SerializationPatternList(self, p):
"""SerializationPatternList : GETTER
| identifier Identifiers
|"""
p[0] = self.BuildProduction('List', p, 0)
if len(p) > 1:
if p[1] == 'getter':
p[0].AddChildren(self.BuildTrue('GETTER'))
else:
attributes = ListFromConcat(p[1], p[2])
p[0].AddChildren(self.BuildAttribute('ATTRIBUTES', attributes))
def p_Stringifier(self, p):
"""Stringifier : STRINGIFIER StringifierRest"""
p[0] = self.BuildProduction('Stringifier', p, 1, p[2])
def p_StringifierRest(self, p):
"""StringifierRest : ReadOnly AttributeRest
| ReturnType OperationRest
| ';'"""
if len(p) == 3:
p[2].AddChildren(p[1])
p[0] = p[2]
def p_StaticMember(self, p):
"""StaticMember : STATIC StaticMemberRest"""
p[2].AddChildren(self.BuildTrue('STATIC'))
p[0] = p[2]
def p_StaticMemberRest(self, p):
"""StaticMemberRest : ReadOnly AttributeRest
| ReturnType OperationRest"""
if len(p) == 2:
p[0] = p[1]
else:
p[2].AddChildren(p[1])
p[0] = p[2]
def p_ReadonlyMember(self, p):
"""ReadonlyMember : READONLY ReadonlyMemberRest"""
p[2].AddChildren(self.BuildTrue('READONLY'))
p[0] = p[2]
def p_ReadonlyMemberRest(self, p):
"""ReadonlyMemberRest : AttributeRest
| MaplikeRest
| SetlikeRest"""
p[0] = p[1]
def p_ReadWriteAttribute(self, p):
"""ReadWriteAttribute : INHERIT ReadOnly AttributeRest
| AttributeRest"""
if len(p) > 2:
inherit = self.BuildTrue('INHERIT')
p[3].AddChildren(ListFromConcat(inherit, p[2]))
p[0] = p[3]
else:
p[0] = p[1]
def p_AttributeRest(self, p):
"""AttributeRest : ATTRIBUTE Type AttributeName ';'"""
p[0] = self.BuildNamed('Attribute', p, 3, p[2])
def p_AttributeName(self, p):
"""AttributeName : AttributeNameKeyword
| identifier"""
p[0] = p[1]
def p_AttributeNameKeyword(self, p):
"""AttributeNameKeyword : REQUIRED"""
p[0] = p[1]
def p_ReadOnly(self, p):
"""ReadOnly : READONLY
|"""
if len(p) > 1:
p[0] = self.BuildTrue('READONLY')
def p_Operation(self, p):
"""Operation : ReturnType OperationRest
| SpecialOperation"""
if len(p) == 3:
p[2].AddChildren(p[1])
p[0] = p[2]
else:
p[0] = p[1]
def p_SpecialOperation(self, p):
"""SpecialOperation : Special Specials ReturnType OperationRest"""
p[4].AddChildren(ListFromConcat(p[1], p[2], p[3]))
p[0] = p[4]
def p_Specials(self, p):
"""Specials : Special Specials
| """
if len(p) > 1:
p[0] = ListFromConcat(p[1], p[2])
def p_Special(self, p):
"""Special : GETTER
| SETTER
| CREATOR
| DELETER
| LEGACYCALLER"""
p[0] = self.BuildTrue(p[1].upper())
def p_OperationRest(self, p):
"""OperationRest : OptionalIdentifier '(' ArgumentList ')' ';'"""
arguments = self.BuildProduction('Arguments', p, 2, p[3])
p[0] = self.BuildNamed('Operation', p, 1, arguments)
def p_OptionalIdentifier(self, p):
"""OptionalIdentifier : identifier
|"""
if len(p) > 1:
p[0] = p[1]
else:
p[0] = '_unnamed_'
def p_ArgumentList(self, p):
"""ArgumentList : Argument Arguments
|"""
if len(p) > 1:
p[0] = ListFromConcat(p[1], p[2])
# ArgumentList error recovery
def p_ArgumentListError(self, p):
"""ArgumentList : error """
p[0] = self.BuildError(p, 'ArgumentList')
def p_Arguments(self, p):
"""Arguments : ',' Argument Arguments
|"""
if len(p) > 1:
p[0] = ListFromConcat(p[2], p[3])
# Arguments error recovery
def p_ArgumentsError(self, p):
"""Arguments : ',' error"""
p[0] = self.BuildError(p, 'Arguments')
def p_Argument(self, p):
"""Argument : ExtendedAttributeList OptionalOrRequiredArgument"""
p[2].AddChildren(p[1])
p[0] = p[2]
def p_OptionalOrRequiredArgument(self, p):
"""OptionalOrRequiredArgument : OPTIONAL Type ArgumentName Default
| Type Ellipsis ArgumentName"""
if len(p) > 4:
arg = self.BuildNamed('Argument', p, 3, ListFromConcat(p[2], p[4]))
arg.AddChildren(self.BuildTrue('OPTIONAL'))
else:
arg = self.BuildNamed('Argument', p, 3, ListFromConcat(p[1], p[2]))
p[0] = arg
def p_ArgumentName(self, p):
"""ArgumentName : ArgumentNameKeyword
| identifier"""
p[0] = p[1]
def p_Ellipsis(self, p):
"""Ellipsis : ELLIPSIS
|"""
if len(p) > 1:
p[0] = self.BuildNamed('Argument', p, 1)
p[0].AddChildren(self.BuildTrue('ELLIPSIS'))
def p_Iterable(self, p):
"""Iterable : ITERABLE '<' Type OptionalType '>' ';'"""
childlist = ListFromConcat(p[3], p[4])
p[0] = self.BuildProduction('Iterable', p, 2, childlist)
def p_OptionalType(self, p):
"""OptionalType : ',' Type
|"""
if len(p) > 1:
p[0] = p[2]
def p_ReadWriteMaplike(self, p):
"""ReadWriteMaplike : MaplikeRest"""
p[0] = p[1]
def p_ReadWriteSetlike(self, p):
"""ReadWriteSetlike : SetlikeRest"""
p[0] = p[1]
def p_MaplikeRest(self, p):
"""MaplikeRest : MAPLIKE '<' Type ',' Type '>' ';'"""
childlist = ListFromConcat(p[3], p[5])
p[0] = self.BuildProduction('Maplike', p, 2, childlist)
def p_SetlikeRest(self, p):
"""SetlikeRest : SETLIKE '<' Type '>' ';'"""
p[0] = self.BuildProduction('Setlike', p, 2, p[3])
# This rule has custom additions (i.e. SpecialComments).
def p_ExtendedAttributeList(self, p):
"""ExtendedAttributeList : SpecialComments '[' ExtendedAttribute ExtendedAttributes ']'
| '[' ExtendedAttribute ExtendedAttributes ']'
| SpecialComments
| """
if len(p) > 5:
items = ListFromConcat(p[3], p[4])
attribs = self.BuildProduction('ExtAttributes', p, 2, items)
p[0] = ListFromConcat(p[1], attribs)
elif len(p) > 4:
items = ListFromConcat(p[2], p[3])
p[0] = self.BuildProduction('ExtAttributes', p, 1, items)
elif len(p) > 1:
p[0] = p[1]
# Error recovery for ExtendedAttributeList
def p_ExtendedAttributeListError(self, p):
"""ExtendedAttributeList : '[' ExtendedAttribute ',' error"""
p[0] = self.BuildError(p, 'ExtendedAttributeList')
def p_ExtendedAttributes(self, p):
"""ExtendedAttributes : ',' ExtendedAttribute ExtendedAttributes
|"""
if len(p) > 1:
p[0] = ListFromConcat(p[2], p[3])
# https://heycam.github.io/webidl/#idl-extended-attributes
# The ExtendedAttribute symbol in Web IDL grammar is very flexible but we
# only support following patterns:
# [ identifier ]
# [ identifier ( ArgumentList ) ]
# [ identifier = identifier ]
# [ identifier = ( IdentifierList ) ]
# [ identifier = identifier ( ArgumentList ) ]
# [ identifier = ( StringList ) ]
# The first five patterns are specified in the Web IDL spec and the last
# pattern is Blink's custom extension to support [ReflectOnly].
def p_ExtendedAttribute(self, p):
"""ExtendedAttribute : ExtendedAttributeNoArgs
| ExtendedAttributeArgList
| ExtendedAttributeIdent
| ExtendedAttributeIdentList
| ExtendedAttributeNamedArgList
| ExtendedAttributeStringLiteral
| ExtendedAttributeStringLiteralList"""
p[0] = p[1]
def p_ArgumentNameKeyword(self, p):
"""ArgumentNameKeyword : ATTRIBUTE
| CALLBACK
| CONST
| CREATOR
| DELETER
| DICTIONARY
| ENUM
| GETTER
| IMPLEMENTS
| INHERIT
| LEGACYCALLER
| PARTIAL
| SERIALIZER
| SETTER
| STATIC
| STRINGIFIER
| TYPEDEF
| UNRESTRICTED"""
p[0] = p[1]
def p_Type(self, p):
"""Type : SingleType
| UnionType TypeSuffix"""
if len(p) == 2:
p[0] = self.BuildProduction('Type', p, 1, p[1])
else:
p[0] = self.BuildProduction('Type', p, 1, ListFromConcat(p[1], p[2]))
def p_SingleType(self, p):
"""SingleType : NonAnyType
| ANY TypeSuffixStartingWithArray"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = ListFromConcat(self.BuildProduction('Any', p, 1), p[2])
def p_UnionType(self, p):
"""UnionType : '(' UnionMemberType OR UnionMemberType UnionMemberTypes ')'"""
members = ListFromConcat(p[2], p[4], p[5])
p[0] = self.BuildProduction('UnionType', p, 1, members)
def p_UnionMemberType(self, p):
"""UnionMemberType : NonAnyType
| UnionType TypeSuffix
| ANY '[' ']' TypeSuffix"""
if len(p) == 2:
p[0] = self.BuildProduction('Type', p, 1, p[1])
elif len(p) == 3:
p[0] = self.BuildProduction('Type', p, 1, ListFromConcat(p[1], p[2]))
else:
any_node = ListFromConcat(self.BuildProduction('Any', p, 1), p[4])
p[0] = self.BuildProduction('Type', p, 1, any_node)
def p_UnionMemberTypes(self, p):
"""UnionMemberTypes : OR UnionMemberType UnionMemberTypes
|"""
if len(p) > 2:
p[0] = ListFromConcat(p[2], p[3])
# Moved BYTESTRING, DOMSTRING, OBJECT, DATE, REGEXP to PrimitiveType
# Moving all built-in types into PrimitiveType makes it easier to
# differentiate between them and 'identifier', since p[1] would be a string in
# both cases.
def p_NonAnyType(self, p):
"""NonAnyType : PrimitiveType TypeSuffix
| PromiseType Null
| identifier TypeSuffix
| SEQUENCE '<' Type '>' Null
| FROZENARRAY '<' Type '>' Null
| RecordType Null"""
if len(p) == 3:
if type(p[1]) == str:
typeref = self.BuildNamed('Typeref', p, 1)
else:
typeref = p[1]
p[0] = ListFromConcat(typeref, p[2])
if len(p) == 6:
cls = 'Sequence' if p[1] == 'sequence' else 'FrozenArray'
p[0] = self.BuildProduction(cls, p, 1, ListFromConcat(p[3], p[5]))
def p_ConstType(self, p):
"""ConstType : PrimitiveType Null
| identifier Null"""
if type(p[1]) == str:
p[0] = self.BuildNamed('Typeref', p, 1, p[2])
else:
p[1].AddChildren(p[2])
p[0] = p[1]
# Added StringType, OBJECT, DATE, REGEXP
def p_PrimitiveType(self, p):
"""PrimitiveType : UnsignedIntegerType
| UnrestrictedFloatType
| StringType
| BOOLEAN
| BYTE
| OCTET
| OBJECT
| DATE
| REGEXP"""
if type(p[1]) == str:
p[0] = self.BuildNamed('PrimitiveType', p, 1)
else:
p[0] = p[1]
def p_UnrestrictedFloatType(self, p):
"""UnrestrictedFloatType : UNRESTRICTED FloatType
| FloatType"""
if len(p) == 2:
typeref = self.BuildNamed('PrimitiveType', p, 1)
else:
typeref = self.BuildNamed('PrimitiveType', p, 2)
typeref.AddChildren(self.BuildTrue('UNRESTRICTED'))
p[0] = typeref
def p_FloatType(self, p):
"""FloatType : FLOAT
| DOUBLE"""
p[0] = p[1]
def p_UnsignedIntegerType(self, p):
"""UnsignedIntegerType : UNSIGNED IntegerType
| IntegerType"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = 'unsigned ' + p[2]
def p_IntegerType(self, p):
"""IntegerType : SHORT
| LONG OptionalLong"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = p[1] + p[2]
def p_OptionalLong(self, p):
"""OptionalLong : LONG
| """
if len(p) > 1:
p[0] = ' ' + p[1]
else:
p[0] = ''
# Add unqualified Promise
def p_PromiseType(self, p):
"""PromiseType : PROMISE '<' ReturnType '>'
| PROMISE"""
if len(p) == 2:
# Promise without resolution type is not specified in the Web IDL spec.
# As it is used in some specs and in the blink implementation,
# we allow that here.
resolution_type = self.BuildProduction('Type', p, 1,
self.BuildProduction('Any', p, 1))
p[0] = self.BuildNamed('Promise', p, 1, resolution_type)
else:
p[0] = self.BuildNamed('Promise', p, 1, p[3])
# Add support for sized array
def p_TypeSuffix(self, p):
"""TypeSuffix : '[' integer ']' TypeSuffix
| '[' ']' TypeSuffix
| '?' TypeSuffixStartingWithArray
| """
if len(p) == 5:
p[0] = self.BuildNamed('Array', p, 2, p[4])
if len(p) == 4:
p[0] = self.BuildProduction('Array', p, 1, p[3])
if len(p) == 3:
p[0] = ListFromConcat(self.BuildTrue('NULLABLE'), p[2])
def p_TypeSuffixStartingWithArray(self, p):
"""TypeSuffixStartingWithArray : '[' ']' TypeSuffix
| """
if len(p) > 1:
p[0] = self.BuildProduction('Array', p, 0, p[3])
def p_Null(self, p):
"""Null : '?'
|"""
if len(p) > 1:
p[0] = self.BuildTrue('NULLABLE')
def p_ReturnType(self, p):
"""ReturnType : Type
| VOID"""
if p[1] == 'void':
p[0] = self.BuildProduction('Type', p, 1)
p[0].AddChildren(self.BuildNamed('PrimitiveType', p, 1))
else:
p[0] = p[1]
def p_IdentifierList(self, p):
"""IdentifierList : identifier Identifiers"""
p[0] = ListFromConcat(p[1], p[2])
def p_Identifiers(self, p):
"""Identifiers : ',' identifier Identifiers
|"""
if len(p) > 1:
p[0] = ListFromConcat(p[2], p[3])
def p_ExtendedAttributeNoArgs(self, p):
"""ExtendedAttributeNoArgs : identifier"""
p[0] = self.BuildNamed('ExtAttribute', p, 1)
def p_ExtendedAttributeArgList(self, p):
"""ExtendedAttributeArgList : identifier '(' ArgumentList ')'"""
arguments = self.BuildProduction('Arguments', p, 2, p[3])
p[0] = self.BuildNamed('ExtAttribute', p, 1, arguments)
def p_ExtendedAttributeIdent(self, p):
"""ExtendedAttributeIdent : identifier '=' identifier"""
value = self.BuildAttribute('VALUE', p[3])
p[0] = self.BuildNamed('ExtAttribute', p, 1, value)
def p_ExtendedAttributeIdentList(self, p):
"""ExtendedAttributeIdentList : identifier '=' '(' IdentifierList ')'"""
value = self.BuildAttribute('VALUE', p[4])
p[0] = self.BuildNamed('ExtAttribute', p, 1, value)
def p_ExtendedAttributeNamedArgList(self, p):
"""ExtendedAttributeNamedArgList : identifier '=' identifier '(' ArgumentList ')'"""
args = self.BuildProduction('Arguments', p, 4, p[5])
value = self.BuildNamed('Call', p, 3, args)
p[0] = self.BuildNamed('ExtAttribute', p, 1, value)
# Blink extension: Add support for string literal Extended Attribute values
def p_ExtendedAttributeStringLiteral(self, p):
"""ExtendedAttributeStringLiteral : identifier '=' StringLiteral"""
def UnwrapString(ls):