forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Codegen.py
11190 lines (9978 loc) · 475 KB
/
Codegen.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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# Common codegen classes.
import operator
import os
import re
import string
import math
import itertools
from WebIDL import BuiltinTypes, IDLBuiltinType, IDLNullValue, IDLSequenceType, IDLType, IDLAttribute
from Configuration import NoSuchDescriptorError, getTypesFromDescriptor, getTypesFromDictionary, getTypesFromCallback, Descriptor
AUTOGENERATED_WARNING_COMMENT = \
"/* THIS FILE IS AUTOGENERATED - DO NOT EDIT */\n\n"
ADDPROPERTY_HOOK_NAME = '_addProperty'
FINALIZE_HOOK_NAME = '_finalize'
TRACE_HOOK_NAME = '_trace'
CONSTRUCT_HOOK_NAME = '_constructor'
LEGACYCALLER_HOOK_NAME = '_legacycaller'
HASINSTANCE_HOOK_NAME = '_hasInstance'
NEWRESOLVE_HOOK_NAME = '_newResolve'
ENUMERATE_HOOK_NAME= '_enumerate'
ENUM_ENTRY_VARIABLE_NAME = 'strings'
def replaceFileIfChanged(filename, newContents):
"""
Read a copy of the old file, so that we don't touch it if it hasn't changed.
Returns True if the file was updated, false otherwise.
"""
oldFileContents = ""
try:
oldFile = open(filename, 'rb')
oldFileContents = ''.join(oldFile.readlines())
oldFile.close()
except:
pass
if newContents == oldFileContents:
return False
f = open(filename, 'wb')
f.write(newContents)
f.close()
return True
def toStringBool(arg):
return str(not not arg).lower()
def toBindingNamespace(arg):
return re.sub("((_workers)?$)", "Binding\\1", arg);
class CGThing():
"""
Abstract base class for things that spit out code.
"""
def __init__(self):
pass # Nothing for now
def declare(self):
"""Produce code for a header file."""
assert(False) # Override me!
def define(self):
"""Produce code for a cpp file."""
assert(False) # Override me!
def deps(self):
"""Produce the deps for a pp file"""
assert(False) # Override me!
class CGNativePropertyHooks(CGThing):
"""
Generate a NativePropertyHooks for a given descriptor
"""
def __init__(self, descriptor, properties):
CGThing.__init__(self)
self.descriptor = descriptor
self.properties = properties
def declare(self):
if self.descriptor.workers:
return ""
return """// We declare this as an array so that retrieving a pointer to this
// binding's property hooks only requires compile/link-time resolvable
// address arithmetic. Declaring it as a pointer instead would require
// doing a run-time load to fetch a pointer to this binding's property
// hooks. And then structures which embedded a pointer to this structure
// would require a run-time load for proper initialization, which would
// then induce static constructors. Lots of static constructors.
extern const NativePropertyHooks sNativePropertyHooks[];"""
def define(self):
if self.descriptor.workers:
return ""
if self.descriptor.concrete and self.descriptor.proxy:
resolveOwnProperty = "ResolveOwnProperty"
enumerateOwnProperties = "EnumerateOwnProperties"
elif self.descriptor.interface.getExtendedAttribute("NeedNewResolve"):
resolveOwnProperty = "ResolveOwnPropertyViaNewresolve"
enumerateOwnProperties = "EnumerateOwnPropertiesViaGetOwnPropertyNames"
else:
resolveOwnProperty = "nullptr"
enumerateOwnProperties = "nullptr"
if self.properties.hasNonChromeOnly():
regular = "&sNativeProperties"
else:
regular = "nullptr"
if self.properties.hasChromeOnly():
chrome = "&sChromeOnlyNativeProperties"
else:
chrome = "nullptr"
constructorID = "constructors::id::"
if self.descriptor.interface.hasInterfaceObject():
constructorID += self.descriptor.name
else:
constructorID += "_ID_Count"
prototypeID = "prototypes::id::"
if self.descriptor.interface.hasInterfacePrototypeObject():
prototypeID += self.descriptor.name
else:
prototypeID += "_ID_Count"
parent = self.descriptor.interface.parent
parentHooks = (toBindingNamespace(parent.identifier.name) + "::sNativePropertyHooks"
if parent else 'nullptr')
return CGWrapper(CGIndenter(CGList([CGGeneric(resolveOwnProperty),
CGGeneric(enumerateOwnProperties),
CGWrapper(CGList([CGGeneric(regular),
CGGeneric(chrome)],
", "),
pre="{ ", post=" }"),
CGGeneric(prototypeID),
CGGeneric(constructorID),
CGGeneric(parentHooks)],
",\n")),
pre="const NativePropertyHooks sNativePropertyHooks[] = { {\n",
post=("\n"
"} };\n")).define()
def NativePropertyHooks(descriptor):
return "&sWorkerNativePropertyHooks" if descriptor.workers else "sNativePropertyHooks"
def DOMClass(descriptor):
protoList = ['prototypes::id::' + proto for proto in descriptor.prototypeChain]
# Pad out the list to the right length with _ID_Count so we
# guarantee that all the lists are the same length. _ID_Count
# is never the ID of any prototype, so it's safe to use as
# padding.
protoList.extend(['prototypes::id::_ID_Count'] * (descriptor.config.maxProtoChainLength - len(protoList)))
prototypeChainString = ', '.join(protoList)
if descriptor.nativeOwnership == 'worker':
participant = "nullptr"
else:
participant = "GetCCParticipant<%s>::Get()" % descriptor.nativeType
getParentObject = "GetParentObject<%s>::Get" % descriptor.nativeType
return """{
{ %s },
IsBaseOf<nsISupports, %s >::value,
%s,
%s,
GetProtoObject,
%s
}""" % (prototypeChainString, descriptor.nativeType,
NativePropertyHooks(descriptor),
getParentObject,
participant)
class CGDOMJSClass(CGThing):
"""
Generate a DOMJSClass for a given descriptor
"""
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def declare(self):
return ""
def define(self):
traceHook = TRACE_HOOK_NAME if self.descriptor.customTrace else 'nullptr'
callHook = LEGACYCALLER_HOOK_NAME if self.descriptor.operations["LegacyCaller"] else 'nullptr'
classFlags = "JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(3)"
if self.descriptor.interface.getExtendedAttribute("NeedNewResolve"):
newResolveHook = "(JSResolveOp)" + NEWRESOLVE_HOOK_NAME
classFlags += " | JSCLASS_NEW_RESOLVE"
enumerateHook = ENUMERATE_HOOK_NAME
else:
newResolveHook = "JS_ResolveStub"
enumerateHook = "JS_EnumerateStub"
return """
static const DOMJSClass Class = {
{ "%s",
%s,
%s, /* addProperty */
JS_DeletePropertyStub, /* delProperty */
JS_PropertyStub, /* getProperty */
JS_StrictPropertyStub, /* setProperty */
%s, /* enumerate */
%s, /* resolve */
JS_ConvertStub,
%s, /* finalize */
nullptr, /* checkAccess */
%s, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
%s, /* trace */
JSCLASS_NO_INTERNAL_MEMBERS
},
%s
};
""" % (self.descriptor.interface.identifier.name,
classFlags,
ADDPROPERTY_HOOK_NAME if self.descriptor.concrete and not self.descriptor.nativeOwnership == 'worker' and self.descriptor.wrapperCache else 'JS_PropertyStub',
enumerateHook, newResolveHook, FINALIZE_HOOK_NAME, callHook, traceHook,
CGIndenter(CGGeneric(DOMClass(self.descriptor))).define())
def PrototypeIDAndDepth(descriptor):
prototypeID = "prototypes::id::"
if descriptor.interface.hasInterfacePrototypeObject():
prototypeID += descriptor.interface.identifier.name
if descriptor.workers:
prototypeID += "_workers"
depth = "PrototypeTraits<%s>::Depth" % prototypeID
else:
prototypeID += "_ID_Count"
depth = "0"
return (prototypeID, depth)
def UseHolderForUnforgeable(descriptor):
return (descriptor.concrete and
descriptor.proxy and
any(m for m in descriptor.interface.members if m.isAttr() and m.isUnforgeable()))
def CallOnUnforgeableHolder(descriptor, code, isXrayCheck=None):
"""
Generate the code to execute the code in "code" on an unforgeable holder if
needed. code should be a string containing the code to execute. If it
contains a ${holder} string parameter it will be replaced with the
unforgeable holder object.
If isXrayCheck is not None it should be a string that contains a statement
returning whether proxy is an Xray. If isXrayCheck is None the generated
code won't try to unwrap Xrays.
"""
code = string.Template(code).substitute({ "holder": "unforgeableHolder" })
if not isXrayCheck is None:
pre = """// Scope for 'global', 'ac' and 'unforgeableHolder'
{
JS::Rooted<JSObject*> global(cx);
Maybe<JSAutoCompartment> ac;
if (""" + isXrayCheck + """) {
global = js::GetGlobalForObjectCrossCompartment(js::UncheckedUnwrap(proxy));
ac.construct(cx, global);
} else {
global = js::GetGlobalForObjectCrossCompartment(proxy);
}"""
else:
pre = """// Scope for 'global' and 'unforgeableHolder'
{
JSObject* global = js::GetGlobalForObjectCrossCompartment(proxy);"""
return (pre + """
JS::Rooted<JSObject*> unforgeableHolder(cx, GetUnforgeableHolder(global, prototypes::id::%s));
""" + CGIndenter(CGGeneric(code)).define() + """
}
""") % descriptor.name
class CGPrototypeJSClass(CGThing):
def __init__(self, descriptor, properties):
CGThing.__init__(self)
self.descriptor = descriptor
self.properties = properties
def declare(self):
# We're purely for internal consumption
return ""
def define(self):
(prototypeID, depth) = PrototypeIDAndDepth(self.descriptor)
slotCount = "DOM_INTERFACE_PROTO_SLOTS_BASE"
if UseHolderForUnforgeable(self.descriptor):
slotCount += " + 1 /* slot for the JSObject holding the unforgeable properties */"
return """static DOMIfaceAndProtoJSClass PrototypeClass = {
{
"%sPrototype",
JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(%s),
JS_PropertyStub, /* addProperty */
JS_DeletePropertyStub, /* delProperty */
JS_PropertyStub, /* getProperty */
JS_StrictPropertyStub, /* setProperty */
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
nullptr, /* finalize */
nullptr, /* checkAccess */
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
nullptr, /* trace */
JSCLASS_NO_INTERNAL_MEMBERS
},
eInterfacePrototype,
%s,
"[object %sPrototype]",
%s,
%s
};
""" % (self.descriptor.interface.identifier.name, slotCount,
NativePropertyHooks(self.descriptor),
self.descriptor.interface.identifier.name,
prototypeID, depth)
def NeedsGeneratedHasInstance(descriptor):
return descriptor.hasXPConnectImpls or descriptor.interface.isConsequential()
class CGInterfaceObjectJSClass(CGThing):
def __init__(self, descriptor, properties):
CGThing.__init__(self)
self.descriptor = descriptor
self.properties = properties
def declare(self):
# We're purely for internal consumption
return ""
def define(self):
if self.descriptor.interface.ctor():
ctorname = CONSTRUCT_HOOK_NAME
else:
ctorname = "ThrowingConstructor"
if NeedsGeneratedHasInstance(self.descriptor):
hasinstance = HASINSTANCE_HOOK_NAME
elif self.descriptor.interface.hasInterfacePrototypeObject():
hasinstance = "InterfaceHasInstance"
else:
hasinstance = "nullptr"
(prototypeID, depth) = PrototypeIDAndDepth(self.descriptor)
slotCount = "DOM_INTERFACE_SLOTS_BASE"
if len(self.descriptor.interface.namedConstructors) > 0:
slotCount += (" + %i /* slots for the named constructors */" %
len(self.descriptor.interface.namedConstructors))
return """
static DOMIfaceAndProtoJSClass InterfaceObjectClass = {
{
"Function",
JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(%s),
JS_PropertyStub, /* addProperty */
JS_DeletePropertyStub, /* delProperty */
JS_PropertyStub, /* getProperty */
JS_StrictPropertyStub, /* setProperty */
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
nullptr, /* finalize */
nullptr, /* checkAccess */
%s, /* call */
%s, /* hasInstance */
%s, /* construct */
nullptr, /* trace */
JSCLASS_NO_INTERNAL_MEMBERS
},
eInterface,
%s,
"function %s() {\\n [native code]\\n}",
%s,
%s
};
""" % (slotCount, ctorname,
hasinstance, ctorname, NativePropertyHooks(self.descriptor),
self.descriptor.interface.identifier.name,
prototypeID, depth)
class CGList(CGThing):
"""
Generate code for a list of GCThings. Just concatenates them together, with
an optional joiner string. "\n" is a common joiner.
"""
def __init__(self, children, joiner=""):
CGThing.__init__(self)
# Make a copy of the kids into a list, because if someone passes in a
# generator we won't be able to both declare and define ourselves, or
# define ourselves more than once!
self.children = list(children)
self.joiner = joiner
def append(self, child):
self.children.append(child)
def prepend(self, child):
self.children.insert(0, child)
def extend(self, kids):
self.children.extend(kids)
def join(self, generator):
return self.joiner.join(filter(lambda s: len(s) > 0, (child for child in generator)))
def declare(self):
return self.join(child.declare() for child in self.children if child is not None)
def define(self):
return self.join(child.define() for child in self.children if child is not None)
def deps(self):
deps = set()
for child in self.children:
if child is None:
continue
deps = deps.union(child.deps())
return deps
class CGGeneric(CGThing):
"""
A class that spits out a fixed string into the codegen. Can spit out a
separate string for the declaration too.
"""
def __init__(self, define="", declare=""):
self.declareText = declare
self.defineText = define
def declare(self):
return self.declareText
def define(self):
return self.defineText
def deps(self):
return set()
# We'll want to insert the indent at the beginnings of lines, but we
# don't want to indent empty lines. So only indent lines that have a
# non-newline character on them.
lineStartDetector = re.compile("^(?=[^\n#])", re.MULTILINE)
class CGIndenter(CGThing):
"""
A class that takes another CGThing and generates code that indents that
CGThing by some number of spaces. The default indent is two spaces.
"""
def __init__(self, child, indentLevel=2, declareOnly=False):
CGThing.__init__(self)
self.child = child
self.indent = " " * indentLevel
self.declareOnly = declareOnly
def declare(self):
decl = self.child.declare()
if decl is not "":
return re.sub(lineStartDetector, self.indent, decl)
else:
return ""
def define(self):
defn = self.child.define()
if defn is not "" and not self.declareOnly:
return re.sub(lineStartDetector, self.indent, defn)
else:
return defn
class CGWrapper(CGThing):
"""
Generic CGThing that wraps other CGThings with pre and post text.
"""
def __init__(self, child, pre="", post="", declarePre=None,
declarePost=None, definePre=None, definePost=None,
declareOnly=False, defineOnly=False, reindent=False):
CGThing.__init__(self)
self.child = child
self.declarePre = declarePre or pre
self.declarePost = declarePost or post
self.definePre = definePre or pre
self.definePost = definePost or post
self.declareOnly = declareOnly
self.defineOnly = defineOnly
self.reindent = reindent
def declare(self):
if self.defineOnly:
return ''
decl = self.child.declare()
if self.reindent:
# We don't use lineStartDetector because we don't want to
# insert whitespace at the beginning of our _first_ line.
decl = stripTrailingWhitespace(
decl.replace("\n", "\n" + (" " * len(self.declarePre))))
return self.declarePre + decl + self.declarePost
def define(self):
if self.declareOnly:
return ''
defn = self.child.define()
if self.reindent:
# We don't use lineStartDetector because we don't want to
# insert whitespace at the beginning of our _first_ line.
defn = stripTrailingWhitespace(
defn.replace("\n", "\n" + (" " * len(self.definePre))))
return self.definePre + defn + self.definePost
def deps(self):
return self.child.deps()
class CGIfWrapper(CGWrapper):
def __init__(self, child, condition):
pre = CGWrapper(CGGeneric(condition), pre="if (", post=") {\n",
reindent=True)
CGWrapper.__init__(self, CGIndenter(child), pre=pre.define(),
post="\n}")
class CGIfElseWrapper(CGList):
def __init__(self, condition, ifTrue, ifFalse):
kids = [ CGIfWrapper(ifTrue, condition),
CGWrapper(CGIndenter(ifFalse), pre=" else {\n", post="\n}") ]
CGList.__init__(self, kids)
class CGTemplatedType(CGWrapper):
def __init__(self, templateName, child, isConst=False, isReference=False):
const = "const " if isConst else ""
pre = "%s%s<" % (const, templateName)
ref = "&" if isReference else ""
post = " >%s" % ref
CGWrapper.__init__(self, child, pre=pre, post=post)
class CGNamespace(CGWrapper):
def __init__(self, namespace, child, declareOnly=False):
pre = "namespace %s {\n" % namespace
post = "} // namespace %s\n" % namespace
CGWrapper.__init__(self, child, pre=pre, post=post,
declareOnly=declareOnly)
@staticmethod
def build(namespaces, child, declareOnly=False):
"""
Static helper method to build multiple wrapped namespaces.
"""
if not namespaces:
return CGWrapper(child, declareOnly=declareOnly)
inner = CGNamespace.build(namespaces[1:], child, declareOnly=declareOnly)
return CGNamespace(namespaces[0], inner, declareOnly=declareOnly)
class CGIncludeGuard(CGWrapper):
"""
Generates include guards for a header.
"""
def __init__(self, prefix, child):
"""|prefix| is the filename without the extension."""
define = 'mozilla_dom_%s_h__' % prefix
CGWrapper.__init__(self, child,
declarePre='#ifndef %s\n#define %s\n\n' % (define, define),
declarePost='\n#endif // %s\n' % define)
def getRelevantProviders(descriptor, config):
if descriptor is not None:
return [descriptor]
# Do both the non-worker and worker versions
return [
config.getDescriptorProvider(False),
config.getDescriptorProvider(True)
]
def getAllTypes(descriptors, dictionaries, callbacks):
"""
Generate all the types we're dealing with. For each type, a tuple
containing type, descriptor, dictionary is yielded. The
descriptor and dictionary can be None if the type does not come
from a descriptor or dictionary; they will never both be non-None.
"""
for d in descriptors:
if d.interface.isExternal():
continue
for t in getTypesFromDescriptor(d):
yield (t, d, None)
for dictionary in dictionaries:
for t in getTypesFromDictionary(dictionary):
yield (t, None, dictionary)
for callback in callbacks:
for t in getTypesFromCallback(callback):
yield (t, None, None)
class CGHeaders(CGWrapper):
"""
Generates the appropriate include statements.
"""
def __init__(self, descriptors, dictionaries, callbacks,
callbackDescriptors,
declareIncludes, defineIncludes, prefix, child,
config=None, jsImplementedDescriptors=[]):
"""
Builds a set of includes to cover |descriptors|.
Also includes the files in |declareIncludes| in the header
file and the files in |defineIncludes| in the .cpp.
|prefix| contains the basename of the file that we generate include
statements for.
"""
# Determine the filenames for which we need headers.
interfaceDeps = [d.interface for d in descriptors]
ancestors = []
for iface in interfaceDeps:
if iface.parent:
# We're going to need our parent's prototype, to use as the
# prototype of our prototype object.
ancestors.append(iface.parent)
# And if we have an interface object, we'll need the nearest
# ancestor with an interface object too, so we can use its
# interface object as the proto of our interface object.
if iface.hasInterfaceObject():
parent = iface.parent
while parent and not parent.hasInterfaceObject():
parent = parent.parent
if parent:
ancestors.append(parent)
interfaceDeps.extend(ancestors)
bindingIncludes = set(self.getDeclarationFilename(d) for d in interfaceDeps)
# Grab all the implementation declaration files we need.
implementationIncludes = set(d.headerFile for d in descriptors if d.needsHeaderInclude())
# Grab the includes for checking hasInstance
interfacesImplementingSelf = set()
for d in descriptors:
interfacesImplementingSelf |= d.interface.interfacesImplementingSelf
implementationIncludes |= set(self.getDeclarationFilename(i) for i in
interfacesImplementingSelf)
# Grab the includes for the things that involve XPCOM interfaces
hasInstanceIncludes = set("nsIDOM" + d.interface.identifier.name + ".h" for d
in descriptors if
NeedsGeneratedHasInstance(d) and
d.interface.hasInterfacePrototypeObject())
# Now find all the things we'll need as arguments because we
# need to wrap or unwrap them.
bindingHeaders = set()
declareIncludes = set(declareIncludes)
def addHeadersForType((t, descriptor, dictionary)):
"""
Add the relevant headers for this type. We use descriptor and
dictionary, if passed, to decide what to do with interface types.
"""
assert not descriptor or not dictionary
if t.nullable():
if dictionary:
# Need to make sure that Nullable as a dictionary
# member works.
declareIncludes.add("mozilla/dom/Nullable.h")
else:
bindingHeaders.add("mozilla/dom/Nullable.h")
unrolled = t.unroll()
if unrolled.isUnion():
# UnionConversions.h includes UnionTypes.h
bindingHeaders.add("mozilla/dom/UnionConversions.h")
if dictionary:
# Our dictionary definition is in the header and
# needs the union type.
declareIncludes.add("mozilla/dom/UnionTypes.h")
elif unrolled.isDate():
if dictionary or jsImplementedDescriptors:
headerSet = declareIncludes
else:
headerSet = bindingHeaders
headerSet.add("mozilla/dom/Date.h")
elif unrolled.isInterface():
if unrolled.isSpiderMonkeyInterface():
bindingHeaders.add("jsfriendapi.h")
if dictionary:
headerSet = declareIncludes
else:
headerSet = bindingHeaders
headerSet.add("mozilla/dom/TypedArray.h")
else:
providers = getRelevantProviders(descriptor, config)
for p in providers:
try:
typeDesc = p.getDescriptor(unrolled.inner.identifier.name)
except NoSuchDescriptorError:
continue
if dictionary:
# Dictionaries with interface members rely on the
# actual class definition of that interface member
# being visible in the binding header, because they
# store them in nsRefPtr and have inline
# constructors/destructors.
#
# XXXbz maybe dictionaries with interface members
# should just have out-of-line constructors and
# destructors?
declareIncludes.add(typeDesc.headerFile)
else:
implementationIncludes.add(typeDesc.headerFile)
elif unrolled.isDictionary():
bindingHeaders.add(self.getDeclarationFilename(unrolled.inner))
elif unrolled.isCallback():
# Callbacks are both a type and an object
bindingHeaders.add(self.getDeclarationFilename(t.unroll()))
elif unrolled.isFloat() and not unrolled.isUnrestricted():
# Restricted floats are tested for finiteness
bindingHeaders.add("mozilla/FloatingPoint.h")
bindingHeaders.add("mozilla/dom/PrimitiveConversions.h")
elif unrolled.isEnum():
filename = self.getDeclarationFilename(unrolled.inner)
# Do nothing if the enum is defined in the same webidl file
# (the binding header doesn't need to include itself).
if filename != prefix + ".h":
declareIncludes.add(filename)
elif unrolled.isPrimitive():
bindingHeaders.add("mozilla/dom/PrimitiveConversions.h")
map(addHeadersForType,
getAllTypes(descriptors + callbackDescriptors, dictionaries,
callbacks))
# Now for non-callback descriptors make sure we include any
# headers needed by Func declarations.
for desc in descriptors:
if desc.interface.isExternal():
continue
def addHeaderForFunc(func):
# Include the right class header, which we can only do
# if this is a class member function.
if func is not None and "::" in func:
# Strip out the function name and convert "::" to "/"
bindingHeaders.add("/".join(func.split("::")[:-1]) + ".h")
for m in desc.interface.members:
addHeaderForFunc(PropertyDefiner.getStringAttr(m, "Func"))
# getExtendedAttribute() returns a list, extract the entry.
funcList = desc.interface.getExtendedAttribute("Func")
if funcList is not None:
addHeaderForFunc(funcList[0])
for d in dictionaries:
if d.parent:
declareIncludes.add(self.getDeclarationFilename(d.parent))
bindingHeaders.add(self.getDeclarationFilename(d))
for c in callbacks:
bindingHeaders.add(self.getDeclarationFilename(c))
for c in callbackDescriptors:
bindingHeaders.add(self.getDeclarationFilename(c.interface))
if len(callbacks) != 0:
# We need CallbackFunction to serve as our parent class
declareIncludes.add("mozilla/dom/CallbackFunction.h")
# And we need BindingUtils.h so we can wrap "this" objects
declareIncludes.add("mozilla/dom/BindingUtils.h")
if len(callbackDescriptors) != 0 or len(jsImplementedDescriptors) != 0:
# We need CallbackInterface to serve as our parent class
declareIncludes.add("mozilla/dom/CallbackInterface.h")
# And we need BindingUtils.h so we can wrap "this" objects
declareIncludes.add("mozilla/dom/BindingUtils.h")
# Also need to include the headers for ancestors of
# JS-implemented interfaces.
for jsImplemented in jsImplementedDescriptors:
jsParent = jsImplemented.interface.parent
if jsParent:
parentDesc = jsImplemented.getDescriptor(jsParent.identifier.name)
declareIncludes.add(parentDesc.jsImplParentHeader)
if len(jsImplementedDescriptors) != 0:
bindingHeaders.add("nsIDOMGlobalPropertyInitializer.h")
# Let the machinery do its thing.
def _includeString(includes):
return ''.join(['#include "%s"\n' % i for i in includes]) + '\n'
CGWrapper.__init__(self, child,
declarePre=_includeString(sorted(declareIncludes)),
definePre=_includeString(sorted(set(defineIncludes) |
bindingIncludes |
bindingHeaders |
hasInstanceIncludes |
implementationIncludes)))
@staticmethod
def getDeclarationFilename(decl):
# Use our local version of the header, not the exported one, so that
# test bindings, which don't export, will work correctly.
basename = os.path.basename(decl.filename())
return basename.replace('.webidl', 'Binding.h')
def SortedTuples(l):
"""
Sort a list of tuples based on the first item in the tuple
"""
return sorted(l, key=operator.itemgetter(0))
def SortedDictValues(d):
"""
Returns a list of values from the dict sorted by key.
"""
# Create a list of tuples containing key and value, sorted on key.
d = SortedTuples(d.items())
# We're only interested in the values.
return (i[1] for i in d)
def UnionTypes(descriptors, dictionaries, callbacks, config):
"""
Returns a tuple containing a set of header filenames to include in
UnionTypes.h, a set of header filenames to include in UnionTypes.cpp, a set
of tuples containing a type declaration and a boolean if the type is a
struct for member types of the unions and a CGList containing CGUnionStructs
for every union.
"""
# Now find all the things we'll need as arguments and return values because
# we need to wrap or unwrap them.
headers = set()
implheaders = set(["UnionTypes.h"])
declarations = set()
unionStructs = dict()
owningUnionStructs = dict()
def addInfoForType((t, descriptor, dictionary)):
"""
Add info for the given type. descriptor and dictionary, if passed, are
used to figure out what to do with interface types.
"""
assert not descriptor or not dictionary
t = t.unroll()
if not t.isUnion():
return
name = str(t)
if not name in unionStructs:
providers = getRelevantProviders(descriptor, config)
# FIXME: Unions are broken in workers. See bug 809899.
unionStructs[name] = CGUnionStruct(t, providers[0])
owningUnionStructs[name] = CGUnionStruct(t, providers[0],
ownsMembers=True)
for f in t.flatMemberTypes:
f = f.unroll()
if f.nullable():
headers.add("mozilla/dom/Nullable.h")
if f.isInterface():
if f.isSpiderMonkeyInterface():
headers.add("jsfriendapi.h")
headers.add("mozilla/dom/TypedArray.h")
else:
for p in providers:
try:
typeDesc = p.getDescriptor(f.inner.identifier.name)
except NoSuchDescriptorError:
continue
declarations.add((typeDesc.nativeType, False))
implheaders.add(typeDesc.headerFile)
elif f.isDictionary():
# For a dictionary, we need to see its declaration in
# UnionTypes.h so we have its sizeof and know how big to
# make our union.
headers.add(CGHeaders.getDeclarationFilename(f.inner))
# And if it needs rooting, we need RootedDictionary too
if typeNeedsRooting(f):
headers.add("mozilla/dom/RootedDictionary.h")
elif t.isPrimitive():
implheaders.add("mozilla/dom/PrimitiveConversions.h")
map(addInfoForType, getAllTypes(descriptors, dictionaries, callbacks))
return (headers, implheaders, declarations,
CGList(itertools.chain(SortedDictValues(unionStructs),
SortedDictValues(owningUnionStructs)), "\n"))
def UnionConversions(descriptors, dictionaries, callbacks, config):
"""
Returns a CGThing to declare all union argument conversion helper structs.
"""
# Now find all the things we'll need as arguments because we
# need to unwrap them.
headers = set()
unionConversions = dict()
def addInfoForType((t, descriptor, dictionary)):
"""
Add info for the given type. descriptor and dictionary, if passed, are
used to figure out what to do with interface types.
"""
assert not descriptor or not dictionary
t = t.unroll()
if not t.isUnion():
return
name = str(t)
if not name in unionConversions:
providers = getRelevantProviders(descriptor, config)
unionConversions[name] = CGUnionConversionStruct(t, providers[0])
for f in t.flatMemberTypes:
f = f.unroll()
if f.isInterface():
if f.isSpiderMonkeyInterface():
headers.add("jsfriendapi.h")
headers.add("mozilla/dom/TypedArray.h")
elif not f.inner.isExternal():
headers.add(CGHeaders.getDeclarationFilename(f.inner))
# Check for whether we have a possibly-XPConnect-implemented
# interface. If we do, the right descriptor will come from
# providers[0], because that would be the non-worker
# descriptor provider, if we have one at all.
if (f.isGeckoInterface() and
providers[0].getDescriptor(f.inner.identifier.name).hasXPConnectImpls):
headers.add("nsDOMQS.h")
elif f.isDictionary():
headers.add(CGHeaders.getDeclarationFilename(f.inner))
elif f.isPrimitive():
headers.add("mozilla/dom/PrimitiveConversions.h")
map(addInfoForType, getAllTypes(descriptors, dictionaries, callbacks))
return (headers,
CGWrapper(CGList(SortedDictValues(unionConversions), "\n"),
post="\n\n"))
class Argument():
"""
A class for outputting the type and name of an argument
"""
def __init__(self, argType, name, default=None):
self.argType = argType
self.name = name
self.default = default
def declare(self):
string = self.argType + ' ' + self.name
if self.default is not None:
string += " = " + self.default
return string
def define(self):
return self.argType + ' ' + self.name
class CGAbstractMethod(CGThing):
"""
An abstract class for generating code for a method. Subclasses
should override definition_body to create the actual code.
descriptor is the descriptor for the interface the method is associated with
name is the name of the method as a string
returnType is the IDLType of the return value
args is a list of Argument objects
inline should be True to generate an inline method, whose body is
part of the declaration.
alwaysInline should be True to generate an inline method annotated with
MOZ_ALWAYS_INLINE.
static should be True to generate a static method, which only has
a definition.
If templateArgs is not None it should be a list of strings containing
template arguments, and the function will be templatized using those
arguments.
"""
def __init__(self, descriptor, name, returnType, args, inline=False, alwaysInline=False, static=False, templateArgs=None):
CGThing.__init__(self)
self.descriptor = descriptor
self.name = name
self.returnType = returnType
self.args = args
self.inline = inline
self.alwaysInline = alwaysInline
self.static = static
self.templateArgs = templateArgs
def _argstring(self, declare):
return ', '.join([a.declare() if declare else a.define() for a in self.args])
def _template(self):
if self.templateArgs is None:
return ''
return 'template <%s>\n' % ', '.join(self.templateArgs)
def _decorators(self):
decorators = []
if self.alwaysInline:
decorators.append('MOZ_ALWAYS_INLINE')
elif self.inline:
decorators.append('inline')
if self.static:
decorators.append('static')
decorators.append(self.returnType)
maybeNewline = " " if self.inline else "\n"
return ' '.join(decorators) + maybeNewline
def declare(self):
if self.inline:
return self._define(True)
return "%s%s%s(%s);\n" % (self._template(), self._decorators(), self.name, self._argstring(True))
def _define(self, fromDeclare=False):
return self.definition_prologue(fromDeclare) + "\n" + self.definition_body() + self.definition_epilogue()
def define(self):
return "" if self.inline else self._define()
def definition_prologue(self, fromDeclare):
return "%s%s%s(%s)\n{" % (self._template(), self._decorators(),
self.name, self._argstring(fromDeclare))
def definition_epilogue(self):
return "\n}\n"
def definition_body(self):
assert(False) # Override me!
class CGAbstractStaticMethod(CGAbstractMethod):
"""
Abstract base class for codegen of implementation-only (no
declaration) static methods.
"""
def __init__(self, descriptor, name, returnType, args):
CGAbstractMethod.__init__(self, descriptor, name, returnType, args,
inline=False, static=True)
def declare(self):
# We only have implementation
return ""
class CGAbstractClassHook(CGAbstractStaticMethod):
"""
Meant for implementing JSClass hooks, like Finalize or Trace. Does very raw
'this' unwrapping as it assumes that the unwrapped type is always known.
"""
def __init__(self, descriptor, name, returnType, args):
CGAbstractStaticMethod.__init__(self, descriptor, name, returnType,
args)
def definition_body_prologue(self):
return """
%s* self = UnwrapDOMObject<%s>(obj);
""" % (self.descriptor.nativeType, self.descriptor.nativeType)