forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Codegen.py
3020 lines (2641 loc) · 117 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 os
import string
from WebIDL import *
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 = '_Construct'
HASINSTANCE_HOOK_NAME = '_HasInstance'
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()
def toStringBool(arg):
return str(not not arg).lower()
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!
class CGNativePropertyHooks(CGThing):
"""
Generate a NativePropertyHooks for a given descriptor
"""
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def declare(self):
return " extern const NativePropertyHooks NativeHooks;\n"
def define(self):
parent = self.descriptor.interface.parent
parentHooks = "&" + parent.identifier.name + "::NativeHooks" if parent else 'NULL'
return """
const NativePropertyHooks NativeHooks = { ResolveProperty, EnumerateProperties, %s };
""" % parentHooks
class CGDOMJSClass(CGThing):
"""
Generate a DOMJSClass for a given descriptor
"""
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def declare(self):
return " extern DOMJSClass Class;\n"
def define(self):
traceHook = TRACE_HOOK_NAME if self.descriptor.customTrace else 'NULL'
protoList = ['id::' + proto for proto in self.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.
while len(protoList) < self.descriptor.config.maxProtoChainLength:
protoList.append('id::_ID_Count')
prototypeChainString = ', '.join(protoList)
return """
DOMJSClass Class = {
{ "%s",
JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(1),
%s, /* addProperty */
JS_PropertyStub, /* delProperty */
JS_PropertyStub, /* getProperty */
JS_StrictPropertyStub, /* setProperty */
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
%s, /* finalize */
NULL, /* checkAccess */
NULL, /* call */
NULL, /* construct */
NULL, /* hasInstance */
%s, /* trace */
JSCLASS_NO_INTERNAL_MEMBERS
},
{ %s },
-1, %s, DOM_OBJECT_SLOT,
&NativeHooks
};
""" % (self.descriptor.interface.identifier.name,
ADDPROPERTY_HOOK_NAME if self.descriptor.concrete and not self.descriptor.workers else 'JS_PropertyStub',
FINALIZE_HOOK_NAME, traceHook, prototypeChainString,
str(self.descriptor.nativeIsISupports).lower())
class CGPrototypeJSClass(CGThing):
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def declare(self):
# We're purely for internal consumption
return ""
def define(self):
return """
static JSClass PrototypeClass = {
"%s Prototype", 0,
JS_PropertyStub, /* addProperty */
JS_PropertyStub, /* delProperty */
JS_PropertyStub, /* getProperty */
JS_StrictPropertyStub, /* setProperty */
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
NULL, /* finalize */
NULL, /* checkAccess */
NULL, /* call */
NULL, /* construct */
NULL, /* hasInstance */
NULL, /* trace */
JSCLASS_NO_INTERNAL_MEMBERS
};
""" % (self.descriptor.interface.identifier.name)
class CGInterfaceObjectJSClass(CGThing):
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def declare(self):
# We're purely for internal consumption
return ""
def define(self):
if not self.descriptor.hasInstanceInterface:
return ""
ctorname = "NULL" if not self.descriptor.interface.ctor() else CONSTRUCT_HOOK_NAME
hasinstance = HASINSTANCE_HOOK_NAME
return """
static JSClass InterfaceObjectClass = {
"Function", 0,
JS_PropertyStub, /* addProperty */
JS_PropertyStub, /* delProperty */
JS_PropertyStub, /* getProperty */
JS_StrictPropertyStub, /* setProperty */
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
NULL, /* finalize */
NULL, /* checkAccess */
%s, /* call */
%s, /* construct */
%s, /* hasInstance */
NULL, /* trace */
JSCLASS_NO_INTERNAL_MEMBERS
};
""" % (ctorname, ctorname, hasinstance)
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)
self.children = children
self.joiner = joiner
def append(self, child):
self.children.append(child)
def prepend(self, child):
self.children.insert(0, child)
def declare(self):
return self.joiner.join([child.declare() for child in self.children])
def define(self):
return self.joiner.join([child.define() for child in self.children])
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
# 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):
CGThing.__init__(self)
self.child = child
self.indent = " " * indentLevel
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 "":
return re.sub(lineStartDetector, self.indent, defn)
else:
return ""
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):
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
def declare(self):
return self.declarePre + self.child.declare() + self.declarePost
def define(self):
if self.declareOnly:
return ''
return self.definePre + self.child.define() + self.definePost
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 child
return CGNamespace(namespaces[0], CGNamespace.build(namespaces[1:],
child),
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_bindings_%s_h__' % prefix
CGWrapper.__init__(self, child,
declarePre='#ifndef %s\n#define %s\n\n' % (define, define),
declarePost='\n#endif // %s\n' % define)
class CGHeaders(CGWrapper):
"""
Generates the appropriate include statements.
"""
def __init__(self, descriptors, declareIncludes, defineIncludes, child):
"""
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.
"""
# Determine the filenames for which we need headers.
interfaceDeps = [d.interface for d in descriptors]
ancestors = []
for iface in interfaceDeps:
while iface.parent:
ancestors.append(iface.parent)
iface = iface.parent
interfaceDeps.extend(ancestors)
bindingIncludes = set(self.getInterfaceFilename(d) for d in interfaceDeps)
# Grab all the implementation declaration files we need.
implementationIncludes = set(d.headerFile for d in descriptors)
# Now find all the things we'll need as arguments because we
# need to wrap or unwrap them.
bindingHeaders = set()
for d in descriptors:
members = [m for m in d.interface.members]
signatures = [s for m in members if m.isMethod() for s in m.signatures()]
types = []
for s in signatures:
assert len(s) == 2
(returnType, arguments) = s
types.append(returnType)
types.extend([a.type for a in arguments])
attrs = [a for a in members if a.isAttr()]
types.extend([a.type for a in attrs])
for t in types:
if t.unroll().isInterface():
if t.unroll().isArrayBuffer():
bindingHeaders.add("jsfriendapi.h")
else:
typeDesc = d.getDescriptor(t.unroll().inner.identifier.name)
if typeDesc is not None:
implementationIncludes.add(typeDesc.headerFile)
bindingHeaders.add(self.getInterfaceFilename(typeDesc.interface))
# 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(declareIncludes),
definePre=_includeString(sorted(set(defineIncludes) |
bindingIncludes |
bindingHeaders |
implementationIncludes)))
@staticmethod
def getInterfaceFilename(interface):
basename = os.path.basename(interface.filename())
return 'mozilla/dom/bindings/' + \
basename.replace('.webidl', 'Binding.h')
class Argument():
"""
A class for outputting the type and name of an argument
"""
def __init__(self, argType, name):
self.argType = argType
self.name = name
def __str__(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.
static should be True to generate a static method, which only has
a definition.
"""
def __init__(self, descriptor, name, returnType, args, inline=False, static=False):
CGThing.__init__(self)
self.descriptor = descriptor
self.name = name
self.returnType = returnType
self.args = args
self.inline = inline
self.static = static
def _argstring(self):
return ', '.join([str(a) for a in self.args])
def _decorators(self):
decorators = []
if self.inline:
decorators.append('inline')
if self.static:
decorators.append('static')
decorators.append(self.returnType)
return ' '.join(decorators)
def declare(self):
if self.inline:
return self._define()
return "\n %s %s(%s);\n" % (self._decorators(), self.name, self._argstring())
def _define(self):
return self.definition_prologue() + "\n" + self.definition_body() + self.definition_epilogue()
def define(self):
return "" if self.inline else self._define()
def definition_prologue(self):
maybeNewline = " " if self.inline else "\n"
return "\n%s%s%s(%s)\n{" % (self._decorators(), maybeNewline,
self.name, self._argstring())
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 """
MOZ_ASSERT(js::GetObjectJSClass(obj) == Class.ToJSClass());
%s* self = UnwrapDOMObject<%s>(obj, Class.ToJSClass());
""" % (self.descriptor.nativeType, self.descriptor.nativeType)
def definition_body(self):
return self.definition_body_prologue() + self.generate_code()
def generate_code(self):
# Override me
assert(False)
class CGAddPropertyHook(CGAbstractClassHook):
"""
A hook for addProperty, used to preserve our wrapper from GC.
"""
def __init__(self, descriptor):
args = [Argument('JSContext*', 'cx'), Argument('JSObject*', 'obj'),
Argument('jsid', 'id'), Argument('jsval*', 'vp')]
CGAbstractClassHook.__init__(self, descriptor, ADDPROPERTY_HOOK_NAME,
'JSBool', args)
def generate_code(self):
return """
JSCompartment* compartment = js::GetObjectCompartment(obj);
xpc::CompartmentPrivate* priv =
static_cast<xpc::CompartmentPrivate*>(JS_GetCompartmentPrivate(compartment));
if (!priv->RegisterDOMExpandoObject(obj)) {
return false;
}
self->SetPreservingWrapper(true);
return true;"""
class CGClassFinalizeHook(CGAbstractClassHook):
"""
A hook for finalize, used to release our native object.
"""
def __init__(self, descriptor):
args = [Argument('JSFreeOp*', 'fop'), Argument('JSObject*', 'obj')]
CGAbstractClassHook.__init__(self, descriptor, FINALIZE_HOOK_NAME,
'void', args)
def generate_code(self):
if self.descriptor.customFinalize:
return """ if (self) {
self->%s(%s);
}""" % (self.name, self.args[0].name)
if self.descriptor.workers:
release = "self->Release();"
else:
assert self.descriptor.nativeIsISupports
release = """
XPCJSRuntime *rt = nsXPConnect::GetRuntimeInstance();
if (rt) {
rt->DeferredRelease(NativeToSupports(self));
} else {
NS_RELEASE(self);
}"""
return """
self->ClearWrapper();
%s""" % (release)
class CGClassTraceHook(CGAbstractClassHook):
"""
A hook to trace through our native object; used for GC and CC
"""
def __init__(self, descriptor):
args = [Argument('JSTracer*', 'trc'), Argument('JSObject*', 'obj')]
CGAbstractClassHook.__init__(self, descriptor, TRACE_HOOK_NAME, 'void',
args)
def generate_code(self):
return """ if (self) {
self->%s(%s);
}""" % (self.name, self.args[0].name)
class CGClassConstructHook(CGAbstractStaticMethod):
"""
JS-visible constructor for our objects
"""
def __init__(self, descriptor):
args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'), Argument('JS::Value*', 'vp')]
CGAbstractStaticMethod.__init__(self, descriptor, CONSTRUCT_HOOK_NAME,
'JSBool', args)
self._ctor = self.descriptor.interface.ctor()
def define(self):
if not self._ctor:
return ""
return CGAbstractStaticMethod.define(self)
def definition_body(self):
return self.generate_code()
def generate_code(self):
preamble = """
JSObject* obj = JS_GetGlobalForObject(cx, JSVAL_TO_OBJECT(JS_CALLEE(cx, vp)));
"""
preArgs = ""
if self.descriptor.workers:
preArgs = "cx, obj, "
else:
preamble += """
nsISupports* global;
xpc_qsSelfRef globalRef;
{
nsresult rv;
JS::Value val = OBJECT_TO_JSVAL(obj);
rv = xpc_qsUnwrapArg<nsISupports>(cx, val, &global, &globalRef.ptr, &val);
if (NS_FAILED(rv)) {
return Throw<true>(cx, NS_ERROR_XPC_BAD_CONVERT_JS);
}
}
"""
preArgs = "global, "
name = "_" + self._ctor.identifier.name
nativeName = "_" + MakeNativeName(self._ctor.identifier.name)
nativeName = self.descriptor.binaryNames.get(name, nativeName)
callGenerator = CGMethodCall(preArgs, nativeName, True,
self.descriptor, self._ctor, {})
return preamble + callGenerator.define();
class CGClassHasInstanceHook(CGAbstractStaticMethod):
def __init__(self, descriptor):
args = [Argument('JSContext*', 'cx'), Argument('JSObject*', 'obj'),
Argument('const jsval*', 'v'), Argument('JSBool*', 'bp')]
CGAbstractStaticMethod.__init__(self, descriptor, HASINSTANCE_HOOK_NAME,
'JSBool', args)
def define(self):
if not self.descriptor.hasInstanceInterface:
return ""
return CGAbstractStaticMethod.define(self)
def definition_body(self):
return self.generate_code()
def generate_code(self):
return """ if (!v->isObject()) {
*bp = false;
return true;
}
jsval protov;
if (!JS_GetProperty(cx, obj, "prototype", &protov))
return false;
if (!protov.isObject()) {
JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_PROTOTYPE,
"%s");
return false;
}
obj = &protov.toObject();
JSObject* instance = &v->toObject();
JSObject* proto = JS_GetPrototype(instance);
while (proto) {
if (proto == obj) {
*bp = true;
return true;
}
proto = JS_GetPrototype(proto);
}
nsISupports* native =
nsContentUtils::XPConnect()->GetNativeOfWrapper(cx, instance);
nsCOMPtr<%s> qiResult = do_QueryInterface(native);
*bp = !!qiResult;
return true;
""" % (self.descriptor.name, self.descriptor.hasInstanceInterface)
def isChromeOnly(m):
return m.getExtendedAttribute("ChromeOnly")
class PropertyDefiner:
"""
A common superclass for defining things on prototype objects.
Subclasses should implement generateArray to generate the actual arrays of
things we're defining. They should also set self.chrome to the list of
things exposed to chrome and self.regular to the list of things exposed to
web pages. self.chrome must be a superset of self.regular but also include
all the ChromeOnly stuff.
"""
def __init__(self, descriptor, name):
self.descriptor = descriptor
self.name = name
def hasChromeOnly(self):
return len(self.chrome) > len(self.regular)
def hasNonChromeOnly(self):
return len(self.regular) > 0
def variableName(self, chrome):
if chrome and self.hasChromeOnly():
return "sChrome" + self.name
if self.hasNonChromeOnly():
return "s" + self.name
return "NULL"
def __str__(self):
str = self.generateArray(self.regular, self.variableName(False))
if self.hasChromeOnly():
str += self.generateArray(self.chrome, self.variableName(True))
return str
# The length of a method is the maximum of the lengths of the
# argument lists of all its overloads.
def methodLength(method):
signatures = method.signatures()
return max([len(arguments) for (retType, arguments) in signatures])
class MethodDefiner(PropertyDefiner):
"""
A class for defining methods on a prototype object.
"""
def __init__(self, descriptor, name, static):
PropertyDefiner.__init__(self, descriptor, name)
methods = [m for m in descriptor.interface.members if
m.isMethod() and m.isStatic() == static]
self.chrome = [{"name": m.identifier.name,
"length": methodLength(m),
"flags": "JSPROP_ENUMERATE"} for m in methods]
self.regular = [{"name": m.identifier.name,
"length": methodLength(m),
"flags": "JSPROP_ENUMERATE"}
for m in methods if not isChromeOnly(m)]
if not descriptor.interface.parent and not static and not descriptor.workers:
self.chrome.append({"name": 'QueryInterface',
"length": 1,
"flags": "0"})
self.regular.append({"name": 'QueryInterface',
"length": 1,
"flags": "0"})
if static:
if not descriptor.interface.hasInterfaceObject():
# static methods go on the interface object
assert not self.hasChromeOnly() and not self.hasNonChromeOnly()
else:
if not descriptor.interface.hasInterfacePrototypeObject():
# non-static methods go on the interface prototype object
assert not self.hasChromeOnly() and not self.hasNonChromeOnly()
@staticmethod
def generateArray(array, name):
if len(array) == 0:
return ""
funcdecls = [' JS_FN("%s", %s, %s, %s)' %
(m["name"], m["name"], m["length"], m["flags"])
for m in array]
# And add our JS_FS_END
funcdecls.append(' JS_FS_END')
return ("static JSFunctionSpec %s[] = {\n" +
',\n'.join(funcdecls) + "\n" +
"};\n\n" +
"static jsid %s_ids[%i] = { JSID_VOID };\n\n") % (name, name, len(array))
class AttrDefiner(PropertyDefiner):
def __init__(self, descriptor, name):
PropertyDefiner.__init__(self, descriptor, name)
self.name = name
self.chrome = [m for m in descriptor.interface.members if m.isAttr()]
self.regular = [m for m in self.chrome if not isChromeOnly(m)]
@staticmethod
def generateArray(array, name):
if len(array) == 0:
return ""
def flags(attr):
flags = "JSPROP_SHARED | JSPROP_ENUMERATE"
if generateNativeAccessors:
flags = "JSPROP_NATIVE_ACCESSORS | " + flags
elif attr.readonly:
return "JSPROP_READONLY | " + flags
return flags
def getter(attr):
return "get_" + attr.identifier.name
def setter(attr):
if attr.readonly:
return "NULL"
return "set_" + attr.identifier.name
attrdecls = [' { "%s", 0, %s, (JSPropertyOp)%s, (JSStrictPropertyOp)%s }' %
(attr.identifier.name, flags(attr), getter(attr),
setter(attr)) for attr in array]
attrdecls.append(' { 0, 0, 0, 0, 0 }')
return ("static JSPropertySpec %s[] = {\n" +
',\n'.join(attrdecls) + "\n" +
"};\n\n" +
"static jsid %s_ids[%i] = { JSID_VOID };\n\n") % (name, name, len(array))
class ConstDefiner(PropertyDefiner):
"""
A class for definining constants on the interface object
"""
def __init__(self, descriptor, name):
PropertyDefiner.__init__(self, descriptor, name)
self.name = name
self.chrome = [m for m in descriptor.interface.members if m.isConst()]
self.regular = [m for m in self.chrome if not isChromeOnly(m)]
@staticmethod
def generateArray(array, name):
if len(array) == 0:
return ""
constdecls = [' { "%s", %s }' %
(const.identifier.name,
convertConstIDLValueToJSVal(const.value))
for const in array]
constdecls.append(' { 0, JSVAL_VOID }')
return ("static ConstantSpec %s[] = {\n" +
',\n'.join(constdecls) + "\n" +
"};\n\n" +
"static jsid %s_ids[%i] = { JSID_VOID };\n\n") % (name, name, len(array))
class PropertyArrays():
def __init__(self, descriptor):
self.staticMethods = MethodDefiner(descriptor, "StaticMethods", True)
self.methods = MethodDefiner(descriptor, "Methods", False)
self.attrs = AttrDefiner(descriptor, "Attributes")
self.consts = ConstDefiner(descriptor, "Constants")
@staticmethod
def arrayNames():
return [ "staticMethods", "methods", "attrs", "consts" ]
def hasChromeOnly(self):
return reduce(lambda b, a: b or getattr(self, a).hasChromeOnly(),
self.arrayNames(), False)
def variableNames(self, chrome):
names = {}
for array in self.arrayNames():
names[array] = getattr(self, array).variableName(chrome)
return names
def __str__(self):
define = ""
for array in self.arrayNames():
define += str(getattr(self, array))
return define
class CGCreateInterfaceObjectsMethod(CGAbstractMethod):
"""
Generate the CreateInterfaceObjects method for an interface descriptor.
properties should be a PropertyArrays instance.
"""
def __init__(self, descriptor, properties):
args = [Argument('JSContext*', 'aCx'), Argument('JSObject*', 'aGlobal'),
Argument('JSObject*', 'aReceiver')]
CGAbstractMethod.__init__(self, descriptor, 'CreateInterfaceObjects', 'JSObject*', args)
self.properties = properties
def definition_body(self):
protoChain = self.descriptor.prototypeChain
if len(protoChain) == 1:
getParentProto = "JS_GetObjectPrototype(aCx, aGlobal)"
else:
parentProtoName = self.descriptor.prototypeChain[-2]
getParentProto = "%s::GetProtoObject(aCx, aGlobal, aReceiver)" % (parentProtoName)
needInterfaceObject = self.descriptor.interface.hasInterfaceObject()
needInterfacePrototypeObject = self.descriptor.interface.hasInterfacePrototypeObject()
# if we don't need to create anything, why are we generating this?
assert needInterfaceObject or needInterfacePrototypeObject
idsToInit = []
for var in self.properties.arrayNames():
props = getattr(self.properties, var)
if props.hasNonChromeOnly():
idsToInit.append(props.variableName(False))
if props.hasChromeOnly() and not self.descriptor.workers:
idsToInit.append(props.variableName(True))
initIds = ""
if len(idsToInit) > 0:
init = ' ||\n '.join(["!InitIds(aCx, %s, %s_ids)" % (varname, varname)
for varname in idsToInit])
if len(idsToInit) > 1:
init = '(' + init + ')'
initIds = (" if (%s_ids[0] == JSID_VOID &&\n" +
" %s) {\n" +
" %s_ids[0] = JSID_VOID;\n"
" return NULL;\n"
" }\n\n") % (idsToInit[0], init, idsToInit[0])
getParentProto = (" JSObject* parentProto = %s;\n" +
" if (!parentProto) {\n" +
" return NULL;\n" +
" }") % getParentProto
needInterfaceObjectClass = (needInterfaceObject and
self.descriptor.hasInstanceInterface)
needConstructor = (needInterfaceObject and
not self.descriptor.hasInstanceInterface)
if self.descriptor.interface.ctor():
constructHook = CONSTRUCT_HOOK_NAME
constructArgs = methodLength(self.descriptor.interface.ctor())
else:
constructHook = "ThrowingConstructorWorkers" if self.descriptor.workers else "ThrowingConstructor"
constructArgs = 0
call = """return bindings::CreateInterfaceObjects(aCx, aGlobal, aReceiver, parentProto,
%s, %s, %s, %d,
%%(methods)s, %%(attrs)s, %%(consts)s, %%(staticMethods)s,
%s);""" % (
"&PrototypeClass" if needInterfacePrototypeObject else "NULL",
"&InterfaceObjectClass" if needInterfaceObjectClass else "NULL",
constructHook if needConstructor else "NULL",
constructArgs,
'"' + self.descriptor.interface.identifier.name + '"' if needInterfaceObject else "NULL")
if self.properties.hasChromeOnly():
if self.descriptor.workers:
accessCheck = "mozilla::dom::workers::GetWorkerPrivateFromContext(aCx)->IsChromeWorker()"
else:
accessCheck = "xpc::AccessCheck::isChrome(js::GetObjectCompartment(aGlobal))"
chrome = """
if (%s) {
%s
}
""" % (accessCheck, call.replace("\n ", "\n ") % self.properties.variableNames(True))
else:
chrome = ""
return initIds + getParentProto + chrome + "\n " + call % self.properties.variableNames(False)
class CGGetPerInterfaceObject(CGAbstractMethod):
"""
A method for getting a per-interface object (a prototype object or interface
constructor object).
"""
def __init__(self, descriptor, name, idPrefix=""):
args = [Argument('JSContext*', 'aCx'), Argument('JSObject*', 'aGlobal'),
Argument('JSObject*', 'aReceiver')]
CGAbstractMethod.__init__(self, descriptor, name,
'JSObject*', args, inline=True)
self.id = idPrefix + "id::" + self.descriptor.name
def definition_body(self):
return """
/* aGlobal and aReceiver are usually the same, but they can be different
too. For example a sandbox often has an xray wrapper for a window as the
prototype of the sandbox's global. In that case aReceiver is the xray
wrapper and aGlobal is the sandbox's global.
*/
/* Make sure our global is sane. Hopefully we can remove this sometime */
if (!(js::GetObjectClass(aGlobal)->flags & JSCLASS_DOM_GLOBAL)) {
return NULL;
}
/* Check to see whether the interface objects are already installed */
JSObject** protoOrIfaceArray = GetProtoOrIfaceArray(aGlobal);
JSObject* cachedObject = protoOrIfaceArray[%s];
if (!cachedObject) {
protoOrIfaceArray[%s] = cachedObject = CreateInterfaceObjects(aCx, aGlobal, aReceiver);
}
/* cachedObject might _still_ be null, but that's OK */
return cachedObject;""" % (self.id, self.id)
class CGGetProtoObjectMethod(CGGetPerInterfaceObject):
"""
A method for getting the interface prototype object.
"""
def __init__(self, descriptor):
CGGetPerInterfaceObject.__init__(self, descriptor, "GetProtoObject")
def definition_body(self):
return """
/* Get the interface prototype object for this class. This will create the
object as needed. */""" + CGGetPerInterfaceObject.definition_body(self)
class CGGetConstructorObjectMethod(CGGetPerInterfaceObject):
"""
A method for getting the interface constructor object.
"""
def __init__(self, descriptor):
CGGetPerInterfaceObject.__init__(self, descriptor, "GetConstructorObject", "constructors::")
def definition_body(self):
return """
/* Get the interface object for this class. This will create the object as
needed. */""" + CGGetPerInterfaceObject.definition_body(self)
def CheckPref(descriptor, globalName, varName, retval, wrapperCache = None):
"""
Check whether bindings should be enabled for this descriptor. If not, set
varName to false and return retval.
"""
if not descriptor.prefable:
return ""
if wrapperCache:
wrapperCache = " %s->ClearIsDOMBinding();\n" % (wrapperCache)
else:
wrapperCache = ""
return """
{
XPCWrappedNativeScope* scope =
XPCWrappedNativeScope::FindInJSObjectScope(aCx, %s);
if (!scope) {
return %s;
}
if (!scope->ParisBindingsEnabled()) {
%s %s = false;
return %s;
}
}
""" % (globalName, retval, wrapperCache, varName, retval)
class CGDefineDOMInterfaceMethod(CGAbstractMethod):
"""
A method for resolve hooks to try to lazily define the interface object for
a given interface.
"""
def __init__(self, descriptor):
args = [Argument('JSContext*', 'aCx'), Argument('JSObject*', 'aReceiver'),
Argument('bool*', 'aEnabled')]
CGAbstractMethod.__init__(self, descriptor, 'DefineDOMInterface', 'bool', args)
def declare(self):
if self.descriptor.workers:
return ''
return CGAbstractMethod.declare(self)
def define(self):
if self.descriptor.workers:
return ''
return CGAbstractMethod.define(self)
def definition_body(self):
if self.descriptor.interface.hasInterfacePrototypeObject():
# We depend on GetProtoObject defining an interface constructor
# object as needed.
getter = "GetProtoObject"
else:
getter = "GetConstructorObject"
return (" JSObject* global = JS_GetGlobalForObject(aCx, aReceiver);\n" +
CheckPref(self.descriptor, "global", "*aEnabled", "false") +
"""
*aEnabled = true;
return !!%s(aCx, global, aReceiver);""" % (getter))
class CGNativeToSupportsMethod(CGAbstractStaticMethod):
"""
A method to cast our native to an nsISupports. We do it by casting up the
interface chain in hopes of getting to something that singly-inherits from
nsISupports.
"""
def __init__(self, descriptor):
args = [Argument(descriptor.nativeType + '*', 'aNative')]
CGAbstractStaticMethod.__init__(self, descriptor, 'NativeToSupports', 'nsISupports*', args)
def definition_body(self):
cur = CGGeneric("aNative")
for proto in reversed(self.descriptor.prototypeChain[:-1]):
d = self.descriptor.getDescriptor(proto)
cast = "static_cast<%s*>(\n" % d.nativeType;
cur = CGWrapper(CGIndenter(cur), pre=cast, post=")")