forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxpidl.py
1606 lines (1346 loc) · 52.8 KB
/
xpidl.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
# xpidl.py - A parser for cross-platform IDL (XPIDL) files.
#
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Mozilla Foundation.
# Portions created by the Initial Developer are Copyright (C) 2008
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Benjamin Smedberg <benjamin@smedbergs.us>
#
# Alternatively, the contents of this file may be used under the terms of
# either of the GNU General Public License Version 2 or later (the "GPL"),
# or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
"""A parser for cross-platform IDL (XPIDL) files."""
import sys, os.path, re
from ply import lex, yacc
"""A type conforms to the following pattern:
def isScriptable(self):
'returns True or False'
def nativeType(self, calltype):
'returns a string representation of the native type
calltype must be 'in', 'out', or 'inout'
Interface members const/method/attribute conform to the following pattern:
name = 'string'
def toIDL(self):
'returns the member signature as IDL'
"""
def attlistToIDL(attlist):
if len(attlist) == 0:
return ''
attlist = list(attlist)
attlist.sort(cmp=lambda a,b: cmp(a[0], b[0]))
return '[%s] ' % ','.join(["%s%s" % (name, value is not None and '(%s)' % value or '')
for name, value, aloc in attlist])
_paramsHardcode = {
2: ('array', 'shared', 'iid_is', 'size_is', 'retval'),
3: ('array', 'size_is', 'const'),
}
def paramAttlistToIDL(attlist):
if len(attlist) == 0:
return ''
# Hack alert: g_hash_table_foreach is pretty much unimitatable... hardcode
# quirk
attlist = list(attlist)
sorted = []
if len(attlist) in _paramsHardcode:
for p in _paramsHardcode[len(attlist)]:
i = 0
while i < len(attlist):
if attlist[i][0] == p:
sorted.append(attlist[i])
del attlist[i]
continue
i += 1
sorted.extend(attlist)
return '[%s] ' % ', '.join(["%s%s" % (name, value is not None and ' (%s)' % value or '')
for name, value, aloc in sorted])
def unaliasType(t):
while t.kind == 'typedef':
t = t.realtype
assert t is not None
return t
def getBuiltinOrNativeTypeName(t):
t = unaliasType(t)
if t.kind == 'builtin':
return t.name
elif t.kind == 'native':
assert t.specialtype is not None
return '[%s]' % t.specialtype
else:
return None
class BuiltinLocation(object):
def get(self):
return "<builtin type>"
def __str__(self):
return self.get()
class Builtin(object):
kind = 'builtin'
location = BuiltinLocation
def __init__(self, name, nativename, signed=False, maybeConst=False):
self.name = name
self.nativename = nativename
self.signed = signed
self.maybeConst = maybeConst
def isScriptable(self):
return True
def nativeType(self, calltype, shared=False, const=False):
if const:
print >>sys.stderr, IDLError("[const] doesn't make sense on builtin types.", self.location, warning=True)
const = 'const '
elif calltype == 'in' and self.nativename.endswith('*'):
const = 'const '
elif shared:
if not self.nativename.endswith('*'):
raise IDLError("[shared] not applicable to non-pointer types.", self.location)
const = 'const '
else:
const = ''
return "%s%s %s" % (const, self.nativename,
calltype != 'in' and '*' or '')
builtinNames = [
Builtin('boolean', 'bool'),
Builtin('void', 'void'),
Builtin('octet', 'PRUint8'),
Builtin('short', 'PRInt16', True, True),
Builtin('long', 'PRInt32', True, True),
Builtin('long long', 'PRInt64', True, False),
Builtin('unsigned short', 'PRUint16', False, True),
Builtin('unsigned long', 'PRUint32', False, True),
Builtin('unsigned long long', 'PRUint64', False, False),
Builtin('float', 'float', True, False),
Builtin('double', 'double', True, False),
Builtin('char', 'char', True, False),
Builtin('string', 'char *', False, False),
Builtin('wchar', 'PRUnichar', False, False),
Builtin('wstring', 'PRUnichar *', False, False),
]
builtinMap = {}
for b in builtinNames:
builtinMap[b.name] = b
class Location(object):
_line = None
def __init__(self, lexer, lineno, lexpos):
self._lineno = lineno
self._lexpos = lexpos
self._lexdata = lexer.lexdata
self._file = getattr(lexer, 'filename', "<unknown>")
def __eq__(self, other):
return self._lexpos == other._lexpos and \
self._file == other._file
def resolve(self):
if self._line:
return
startofline = self._lexdata.rfind('\n', 0, self._lexpos) + 1
endofline = self._lexdata.find('\n', self._lexpos, self._lexpos + 80)
self._line = self._lexdata[startofline:endofline]
self._colno = self._lexpos - startofline
def pointerline(self):
def i():
for i in xrange(0, self._colno):
yield " "
yield "^"
return "".join(i())
def get(self):
self.resolve()
return "%s line %s:%s" % (self._file, self._lineno, self._colno)
def __str__(self):
self.resolve()
return "%s line %s:%s\n%s\n%s" % (self._file, self._lineno, self._colno,
self._line, self.pointerline())
class NameMap(object):
"""Map of name -> object. Each object must have a .name and .location property.
Setting the same name twice throws an error."""
def __init__(self):
self._d = {}
def __getitem__(self, key):
if key in builtinMap:
return builtinMap[key]
return self._d[key]
def __iter__(self):
return self._d.itervalues()
def __contains__(self, key):
return key in builtinMap or key in self._d
def set(self, object):
if object.name in builtinMap:
raise IDLError("name '%s' is a builtin and cannot be redeclared" % (object.name), object.location)
if object.name in self._d:
old = self._d[object.name]
if old == object: return
if isinstance(old, Forward) and isinstance(object, Interface):
self._d[object.name] = object
elif isinstance(old, Interface) and isinstance(object, Forward):
pass
else:
raise IDLError("name '%s' specified twice. Previous location: %s" % (object.name, self._d[object.name].location), object.location)
else:
self._d[object.name] = object
def get(self, id, location):
try:
return self[id]
except KeyError:
raise IDLError("Name '%s' not found", location)
class IDLError(Exception):
def __init__(self, message, location, warning=False):
self.message = message
self.location = location
self.warning = warning
def __str__(self):
return "%s: %s, %s" % (self.warning and 'warning' or 'error',
self.message, self.location)
class Include(object):
kind = 'include'
def __init__(self, filename, location):
self.filename = filename
self.location = location
def __str__(self):
return "".join(["include '%s'\n" % self.filename])
def resolve(self, parent):
def incfiles():
yield self.filename
for dir in parent.incdirs:
yield os.path.join(dir, self.filename)
for file in incfiles():
if not os.path.exists(file): continue
self.IDL = parent.parser.parse(open(file).read(), filename=file)
self.IDL.resolve(parent.incdirs, parent.parser)
for type in self.IDL.getNames():
parent.setName(type)
parent.deps.extend(self.IDL.deps)
return
raise IDLError("File '%s' not found" % self.filename, self.location)
class IDL(object):
def __init__(self, productions):
self.productions = productions
self.deps = []
def setName(self, object):
self.namemap.set(object)
def getName(self, id, location):
try:
return self.namemap[id]
except KeyError:
raise IDLError("type '%s' not found" % id, location)
def hasName(self, id):
return id in self.namemap
def getNames(self):
return iter(self.namemap)
def __str__(self):
return "".join([str(p) for p in self.productions])
def resolve(self, incdirs, parser):
self.namemap = NameMap()
self.incdirs = incdirs
self.parser = parser
for p in self.productions:
p.resolve(self)
def includes(self):
for p in self.productions:
if p.kind == 'include':
yield p
def needsJSTypes(self):
for p in self.productions:
if p.kind == 'interface' and p.needsJSTypes():
return True
return False
class CDATA(object):
kind = 'cdata'
_re = re.compile(r'\n+')
def __init__(self, data, location):
self.data = self._re.sub('\n', data)
self.location = location
def resolve(self, parent):
pass
def __str__(self):
return "cdata: %s\n\t%r\n" % (self.location.get(), self.data)
def count(self):
return 0
class Typedef(object):
kind = 'typedef'
def __init__(self, type, name, location, doccomments):
self.type = type
self.name = name
self.location = location
self.doccomments = doccomments
def __eq__(self, other):
return self.name == other.name and self.type == other.type
def resolve(self, parent):
parent.setName(self)
self.realtype = parent.getName(self.type, self.location)
def isScriptable(self):
return self.realtype.isScriptable()
def nativeType(self, calltype):
return "%s %s" % (self.name,
calltype != 'in' and '*' or '')
def __str__(self):
return "typedef %s %s\n" % (self.type, self.name)
class Forward(object):
kind = 'forward'
def __init__(self, name, location, doccomments):
self.name = name
self.location = location
self.doccomments = doccomments
def __eq__(self, other):
return other.kind == 'forward' and other.name == self.name
def resolve(self, parent):
# Hack alert: if an identifier is already present, move the doccomments
# forward.
if parent.hasName(self.name):
for i in xrange(0, len(parent.productions)):
if parent.productions[i] is self: break
for i in xrange(i + 1, len(parent.productions)):
if hasattr(parent.productions[i], 'doccomments'):
parent.productions[i].doccomments[0:0] = self.doccomments
break
parent.setName(self)
def isScriptable(self):
return True
def nativeType(self, calltype):
return "%s %s" % (self.name,
calltype != 'in' and '* *' or '*')
def __str__(self):
return "forward-declared %s\n" % self.name
class Native(object):
kind = 'native'
modifier = None
specialtype = None
specialtypes = {
'nsid': None,
'domstring': 'nsAString',
'utf8string': 'nsACString',
'cstring': 'nsACString',
'astring': 'nsAString',
'jsval': 'JS::Value'
}
def __init__(self, name, nativename, attlist, location):
self.name = name
self.nativename = nativename
self.location = location
for name, value, aloc in attlist:
if value is not None:
raise IDLError("Unexpected attribute value", aloc)
if name in ('ptr', 'ref'):
if self.modifier is not None:
raise IDLError("More than one ptr/ref modifier", aloc)
self.modifier = name
elif name in self.specialtypes.keys():
if self.specialtype is not None:
raise IDLError("More than one special type", aloc)
self.specialtype = name
if self.specialtypes[name] is not None:
self.nativename = self.specialtypes[name]
else:
raise IDLError("Unexpected attribute", aloc)
def __eq__(self, other):
return self.name == other.name and \
self.nativename == other.nativename and \
self.modifier == other.modifier and \
self.specialtype == other.specialtype
def resolve(self, parent):
parent.setName(self)
def isScriptable(self):
if self.specialtype is None:
return False
if self.specialtype == 'nsid':
return self.modifier is not None
return self.modifier == 'ref'
def isPtr(self, calltype):
return self.modifier == 'ptr' or (self.modifier == 'ref' and self.specialtype == 'jsval' and calltype == 'out')
def isRef(self, calltype):
return self.modifier == 'ref' and not (self.specialtype == 'jsval' and calltype == 'out')
def nativeType(self, calltype, const=False, shared=False):
if shared:
if calltype != 'out':
raise IDLError("[shared] only applies to out parameters.")
const = True
if self.specialtype is not None and calltype == 'in':
const = True
if self.isRef(calltype):
m = '& '
elif self.isPtr(calltype):
m = '*' + ((self.modifier == 'ptr' and calltype != 'in') and '*' or '')
else:
m = calltype != 'in' and '*' or ''
return "%s%s %s" % (const and 'const ' or '', self.nativename, m)
def __str__(self):
return "native %s(%s)\n" % (self.name, self.nativename)
class BaseInterface(object):
def __init__(self, name, attlist, base, members, location, doccomments):
self.name = name
self.attributes = InterfaceAttributes(attlist, location)
self.base = base
self.members = members
self.location = location
self.namemap = NameMap()
self.doccomments = doccomments
self.nativename = name
for m in members:
if not isinstance(m, CDATA):
self.namemap.set(m)
self.ops = {
'index':
{
'getter': None,
'setter': None
},
'name':
{
'getter': None,
'setter': None
},
'stringifier': None
}
def __eq__(self, other):
return self.name == other.name and self.location == other.location
def resolve(self, parent):
self.idl = parent
# Hack alert: if an identifier is already present, libIDL assigns
# doc comments incorrectly. This is quirks-mode extraordinaire!
if parent.hasName(self.name):
for member in self.members:
if hasattr(member, 'doccomments'):
member.doccomments[0:0] = self.doccomments
break
self.doccomments = parent.getName(self.name, None).doccomments
if self.attributes.function:
has_method = False
for member in self.members:
if member.kind is 'method':
if has_method:
raise IDLError("interface '%s' has multiple methods, but marked 'function'" % self.name, self.location)
else:
has_method = True
parent.setName(self)
if self.base is not None:
realbase = parent.getName(self.base, self.location)
if realbase.kind != self.kind:
raise IDLError("%s '%s' inherits from non-%s type '%s'" % (self.kind, self.name, self.kind, self.base), self.location)
if self.attributes.scriptable and not realbase.attributes.scriptable:
print >>sys.stderr, IDLError("interface '%s' is scriptable but derives from non-scriptable '%s'" % (self.name, self.base), self.location, warning=True)
forwardedMembers = set()
for member in self.members:
member.resolve(self)
if member.kind is 'method' and member.forward:
forwardedMembers.add(member.forward)
for member in self.members:
if member.kind is 'method' and member.name in forwardedMembers:
forwardedMembers.remove(member.name)
for member in forwardedMembers:
raise IDLError("member '%s' on interface '%s' forwards to '%s' which is not on the interface itself" % (member.name, self.name, member.forward), self.location)
# The number 250 is NOT arbitrary; this number is the maximum number of
# stub entries defined in xpcom/reflect/xptcall/public/genstubs.pl
# Do not increase this value without increasing the number in that
# location, or you WILL cause otherwise unknown problems!
if self.countEntries() > 250 and not self.attributes.builtinclass:
raise IDLError("interface '%s' has too many entries" % self.name,
self.location)
def isScriptable(self):
# NOTE: this is not whether *this* interface is scriptable... it's
# whether, when used as a type, it's scriptable, which is true of all
# interfaces.
return True
def nativeType(self, calltype, const=False):
return "%s%s %s" % (const and 'const ' or '',
self.name,
calltype != 'in' and '* *' or '*')
def __str__(self):
l = ["interface %s\n" % self.name]
if self.base is not None:
l.append("\tbase %s\n" % self.base)
l.append(str(self.attributes))
if self.members is None:
l.append("\tincomplete type\n")
else:
for m in self.members:
l.append(str(m))
return "".join(l)
def getConst(self, name, location):
# The constant may be in a base class
iface = self
while name not in iface.namemap and iface is not None:
iface = self.idl.getName(self.base, self.location)
if iface is None:
raise IDLError("cannot find symbol '%s'" % name, c.location)
c = iface.namemap.get(name, location)
if c.kind != 'const':
raise IDLError("symbol '%s' is not a constant", c.location)
return c.getValue()
def needsJSTypes(self):
for m in self.members:
if m.kind == "attribute" and m.type == "jsval":
return True
if m.kind == "method" and m.needsJSTypes():
return True
return False
def countEntries(self):
''' Returns the number of entries in the vtable for this interface. '''
total = sum(member.count() for member in self.members)
if self.base is not None:
realbase = self.idl.getName(self.base, self.location)
total += realbase.countEntries()
return total
class Interface(BaseInterface):
kind = 'interface'
def __init__(self, name, attlist, base, members, location, doccomments):
BaseInterface.__init__(self, name, attlist, base, members, location, doccomments)
if self.attributes.uuid is None:
raise IDLError("interface has no uuid", location)
class Dictionary(BaseInterface):
kind = 'dictionary'
def __init__(self, name, attlist, base, members, location, doccomments):
BaseInterface.__init__(self, name, attlist, base, members, location, doccomments)
class InterfaceAttributes(object):
uuid = None
scriptable = False
builtinclass = False
function = False
deprecated = False
noscript = False
def setuuid(self, value):
self.uuid = value.lower()
def setscriptable(self):
self.scriptable = True
def setfunction(self):
self.function = True
def setnoscript(self):
self.noscript = True
def setbuiltinclass(self):
self.builtinclass = True
def setdeprecated(self):
self.deprecated = True
actions = {
'uuid': (True, setuuid),
'scriptable': (False, setscriptable),
'builtinclass': (False, setbuiltinclass),
'function': (False, setfunction),
'noscript': (False, setnoscript),
'deprecated': (False, setdeprecated),
'object': (False, lambda self: True),
}
def __init__(self, attlist, location):
def badattribute(self):
raise IDLError("Unexpected interface attribute '%s'" % name, location)
for name, val, aloc in attlist:
hasval, action = self.actions.get(name, (False, badattribute))
if hasval:
if val is None:
raise IDLError("Expected value for attribute '%s'" % name,
aloc)
action(self, val)
else:
if val is not None:
raise IDLError("Unexpected value for attribute '%s'" % name,
aloc)
action(self)
def __str__(self):
l = []
if self.uuid:
l.append("\tuuid: %s\n" % self.uuid)
if self.scriptable:
l.append("\tscriptable\n")
if self.builtinclass:
l.append("\tbuiltinclass\n")
if self.function:
l.append("\tfunction\n")
return "".join(l)
class ConstMember(object):
kind = 'const'
def __init__(self, type, name, value, location, doccomments):
self.type = type
self.name = name
self.value = value
self.location = location
self.doccomments = doccomments
def resolve(self, parent):
self.realtype = parent.idl.getName(self.type, self.location)
self.iface = parent
basetype = self.realtype
while isinstance(basetype, Typedef):
basetype = basetype.realtype
if not isinstance(basetype, Builtin) or not basetype.maybeConst:
raise IDLError("const may only be a short or long type, not %s" % self.type, self.location)
self.basetype = basetype
def getValue(self):
return self.value(self.iface)
def __str__(self):
return "\tconst %s %s = %s\n" % (self.type, self.name, self.getValue())
def count(self):
return 0
class Attribute(object):
kind = 'attribute'
noscript = False
notxpcom = False
readonly = False
implicit_jscontext = False
nostdcall = False
binaryname = None
null = None
undefined = None
deprecated = False
nullable = False
defvalue = None
def __init__(self, type, name, attlist, readonly, nullable, defvalue, location, doccomments):
self.type = type
self.name = name
self.attlist = attlist
self.readonly = readonly
self.nullable = nullable
self.defvalue = defvalue
self.location = location
self.doccomments = doccomments
for name, value, aloc in attlist:
if name == 'binaryname':
if value is None:
raise IDLError("binaryname attribute requires a value",
aloc)
self.binaryname = value
continue
if name == 'Null':
if value is None:
raise IDLError("'Null' attribute requires a value", aloc)
if readonly:
raise IDLError("'Null' attribute only makes sense for setters",
aloc);
if value not in ('Empty', 'Null', 'Stringify'):
raise IDLError("'Null' attribute value must be 'Empty', 'Null' or 'Stringify'",
aloc);
self.null = value
elif name == 'Undefined':
if value is None:
raise IDLError("'Undefined' attribute requires a value", aloc)
if readonly:
raise IDLError("'Undefined' attribute only makes sense for setters",
aloc);
if value not in ('Empty', 'Null'):
raise IDLError("'Undefined' attribute value must be 'Empty' or 'Null'",
aloc);
self.undefined = value
else:
if value is not None:
raise IDLError("Unexpected attribute value", aloc)
if name == 'noscript':
self.noscript = True
elif name == 'notxpcom':
self.notxpcom = True
elif name == 'implicit_jscontext':
self.implicit_jscontext = True
elif name == 'deprecated':
self.deprecated = True
elif name == 'nostdcall':
self.nostdcall = True
else:
raise IDLError("Unexpected attribute '%s'" % name, aloc)
def resolve(self, iface):
self.iface = iface
self.realtype = iface.idl.getName(self.type, self.location)
if (self.null is not None and
getBuiltinOrNativeTypeName(self.realtype) != '[domstring]'):
raise IDLError("'Null' attribute can only be used on DOMString",
self.location)
if (self.undefined is not None and
getBuiltinOrNativeTypeName(self.realtype) != '[domstring]'):
raise IDLError("'Undefined' attribute can only be used on DOMString",
self.location)
if (self.nullable and
getBuiltinOrNativeTypeName(self.realtype) != '[domstring]'):
raise IDLError("Nullable types (T?) is supported only for DOMString",
self.location)
def toIDL(self):
attribs = attlistToIDL(self.attlist)
readonly = self.readonly and 'readonly ' or ''
return "%s%sattribute %s %s;" % (attribs, readonly, self.type, self.name)
def isScriptable(self):
if not self.iface.attributes.scriptable: return False
return not (self.noscript or self.notxpcom)
def __str__(self):
return "\t%sattribute %s %s\n" % (self.readonly and 'readonly ' or '',
self.type, self.name)
def count(self):
return self.readonly and 1 or 2
class Method(object):
kind = 'method'
noscript = False
notxpcom = False
binaryname = None
implicit_jscontext = False
nostdcall = False
optional_argc = False
deprecated = False
getter = False
setter = False
stringifier = False
forward = None
def __init__(self, type, name, attlist, paramlist, location, doccomments, raises):
self.type = type
self.name = name
self.attlist = attlist
self.params = paramlist
self.location = location
self.doccomments = doccomments
self.raises = raises
for name, value, aloc in attlist:
if name == 'binaryname':
if value is None:
raise IDLError("binaryname attribute requires a value",
aloc)
self.binaryname = value
continue
if name == 'forward':
if value is None:
raise IDLError("forward attribute requires a value",
aloc)
self.forward = value
continue
if value is not None:
raise IDLError("Unexpected attribute value", aloc)
if name == 'noscript':
self.noscript = True
elif name == 'notxpcom':
self.notxpcom = True
elif name == 'implicit_jscontext':
self.implicit_jscontext = True
elif name == 'optional_argc':
self.optional_argc = True
elif name == 'deprecated':
self.deprecated = True
elif name == 'nostdcall':
self.nostdcall = True
elif name == 'getter':
if (len(self.params) != 1):
raise IDLError("Methods marked as getter must take 1 argument", aloc)
self.getter = True
elif name == 'setter':
if (len(self.params) != 2):
raise IDLError("Methods marked as setter must take 2 arguments", aloc)
self.setter = True
elif name == 'stringifier':
if (len(self.params) != 0):
raise IDLError("Methods marked as stringifier must take 0 arguments", aloc)
self.stringifier = True
else:
raise IDLError("Unexpected attribute '%s'" % name, aloc)
self.namemap = NameMap()
for p in paramlist:
self.namemap.set(p)
def resolve(self, iface):
self.iface = iface
self.realtype = self.iface.idl.getName(self.type, self.location)
for p in self.params:
p.resolve(self)
if self.getter:
if getBuiltinOrNativeTypeName(self.params[0].realtype) == 'unsigned long':
ops = 'index'
else:
if getBuiltinOrNativeTypeName(self.params[0].realtype) != '[domstring]':
raise IDLError("a getter must take a single unsigned long or DOMString argument" % self.iface.name, self.location)
ops = 'name'
if self.iface.ops[ops]['getter']:
raise IDLError("a %s getter was already defined on interface '%s'" % (ops, self.iface.name), self.location)
self.iface.ops[ops]['getter'] = self
if self.setter:
if getBuiltinOrNativeTypeName(self.params[0].realtype) == 'unsigned long':
ops = 'index'
else:
if getBuiltinOrNativeTypeName(self.params[0].realtype) != '[domstring]':
print getBuiltinOrNativeTypeName(self.params[0].realtype)
raise IDLError("a setter must take a unsigned long or DOMString argument" % self.iface.name, self.location)
ops = 'name'
if self.iface.ops[ops]['setter']:
raise IDLError("a %s setter was already defined on interface '%s'" % (ops, self.iface.name), self.location)
self.iface.ops[ops]['setter'] = self
if self.stringifier:
if self.iface.ops['stringifier']:
raise IDLError("a stringifier was already defined on interface '%s'" % self.iface.name, self.location)
if getBuiltinOrNativeTypeName(self.realtype) != '[domstring]':
raise IDLError("'stringifier' attribute can only be used on methods returning DOMString",
self.location)
self.iface.ops['stringifier'] = self
for p in self.params:
if p.retval and p != self.params[-1]:
raise IDLError("'retval' parameter '%s' is not the last parameter" % p.name, self.location)
if p.size_is:
found_size_param = False
for size_param in self.params:
if p.size_is == size_param.name:
found_size_param = True
if getBuiltinOrNativeTypeName(size_param.realtype) != 'unsigned long':
raise IDLError("is_size parameter must have type 'unsigned long'", self.location)
if not found_size_param:
raise IDLError("could not find is_size parameter '%s'" % p.size_is, self.location)
def isScriptable(self):
if not self.iface.attributes.scriptable: return False
return not (self.noscript or self.notxpcom)
def __str__(self):
return "\t%s %s(%s)\n" % (self.type, self.name, ", ".join([p.name for p in self.params]))
def toIDL(self):
if len(self.raises):
raises = ' raises (%s)' % ','.join(self.raises)
else:
raises = ''
return "%s%s %s (%s)%s;" % (attlistToIDL(self.attlist),
self.type,
self.name,
", ".join([p.toIDL()
for p in self.params]),
raises)
def needsJSTypes(self):
if self.implicit_jscontext:
return True
if self.type == "jsval":
return True
for p in self.params:
t = p.realtype
if isinstance(t, Native) and t.specialtype == "jsval":
return True
return False
def count(self):
return 1
class Param(object):
size_is = None
iid_is = None
const = False
array = False
retval = False
shared = False
optional = False
null = None
undefined = None
def __init__(self, paramtype, type, name, attlist, location, realtype=None):
self.paramtype = paramtype
self.type = type