This repository was archived by the owner on Jan 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathnativegen.py
executable file
·3144 lines (2800 loc) · 131 KB
/
nativegen.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
# -*- Mode: Python; indent-tabs-mode: nil -*-
# vi: set ts=4 sw=4 expandtab:
# 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/.
# Documentation for native annotations.
#
# Classes can be annotated with 'native' metainformation:
#
# [native(cls="...", ...)]
# public class Fnord extends FnordBase { ... }
#
# or
#
# [native("...")]
# public class Fnord extends FnordBase { ... }
#
# The latter form is equivalent to the former with a single cls attribute (?).
#
# The named attributes are:
#
# cls the C++ name for the class object's class (required)
# instance the C++ name for the instance object's class (required)
# gc the GC method for both class and instance objects
# classgc the GC method for the class object
# instancegc the GC method for the instance object
# methods ?
# construct indicates that the class has a nonstandard construction pipeline:
#
# "none": the class cannot be instantiated, nor can subclasses; we will generate a stub
# that throws kCantInstantiateError. (Typically used for classes that provide only
# static members and/or static methods.)
#
# "check": the class is expected to provide a function of the form
#
# static void FASTCALL preCreateInstanceCheck(ClassClosure* cls)
#
# which will be called prior to creation of an instance; this function is
# allowed to throw an exception to prevent object creation. (Throwing
# an exception in the C++ ctor is discouraged, as our current longjmp implementation
# of exception handling can result in a half-constructed object, which could cause
# issues at object destruction time.)
#
# "restricted": subclasses must be defined in the same ABC chunk as the baseclass (otherwise they will
# throw kCantInstantiateError). This is an odd beast, used by Flash for classes
# which can't be subclassed by user code (only by builtin code.)
#
# "restricted-check": Like restricted, but with a preCreateInstanceCheck function required as well.
#
# "abstract": the class cannot be instantiated, but its subclasses can (ie, an Abstract Base Class);
# we will generate a stub that throws kCantInstantiateError when appropriate.
#
# "abstract-restricted": is the union of of abstract+restricted: the class can't be instantiated,
# and subclasses can only from from the same ABC chunk.
#
# "native": the class can be instantiated only from the C++ constructObject() wrapper;
# attempting to instantiate from AS3 will throw kCantInstantiateError.
#
# * THE FOLLOWING VALUES FOR construct ARE ONLY LEGAL FOR USE IN THE BASE VM BUILTINS *
#
# "override": the Class must provide an override of the ScriptObject::construct() method.
# (We will autogenerate a createInstanceProc stub that asserts if called.)
#
# "instance": the Class *and* Instance must provide an override of the ScriptObject::construct() method.
# (We will autogenerate a createInstanceProc stub that asserts if called.)
#
# instancebase if the instance inherits from a C++ class that can't be inferred from the AS3 inheritance,
# it must be specified here. this is not supported for new code; it's provided for temporary support
# of existing code.
#
# The allowable values for "gc", "classgc", and "instancegc" are "exact"
# and "conservative"; the default is "conservative". If the value is "exact"
# then tracers are autogenerated based on annotations on the C++ class and
# on the pointer fields in the C++ class.
#
# For more information about GC see the documentation in utils/exactgc.as.
import optparse, struct, os, sys, StringIO
from optparse import OptionParser
from struct import *
from os import path
from math import floor
from sys import stderr
import os, stat, sys, traceback
# A list of the interfaces that contain a PSDK C++ flash player interface glue object. This structure must match the one in "modules/psdk/scripts/psdkconfig.py" TODO: Merge them.
psdk_interface_classes = set([
"TimelineOperation",
"TimelineMarker",
"DRMErrorListener",
"DRMOperationCompleteListener",
"DRMAuthenticateListener",
"DRMAcquireLicenseListener",
"DRMReturnLicenseListener",
"AdPolicySelector",
"ContentFactory",
"ContentResolver",
"ContentTracker",
"CustomAdHandler",
"OpportunityGenerator"
])
# Look for additional modules in the halfmoon templates directory.
hm_scripts = os.path.abspath(os.path.join(os.path.dirname(__file__), '../halfmoon/templates'))
sys.path.append(hm_scripts)
from mangle import *
parser = OptionParser(usage="usage: %prog [importfile [, importfile]...] file...")
parser.add_option("-v", "--thunkvprof", action="store_true", default=False)
parser.add_option("-e", "--externmethodandclassetables", action="store_true", default=False, help="generate extern decls for method and class tables")
parser.add_option("--native-id-namespace", dest="nativeIDNS", default="avmplus::NativeID", help="Specifies the C++ namespace in which all generated should be in.")
parser.add_option("--root-implementation-namespace", dest="rootImplNS", default="avmplus", help="Specifies the C++ namespace in under which all implementation classes can be found.")
opts, args = parser.parse_args()
if not args:
parser.print_help()
exit(2)
NEED_ARGUMENTS = 0x01
NEED_ACTIVATION = 0x02
NEED_REST = 0x04
HAS_OPTIONAL = 0x08
IGNORE_REST = 0x10
NATIVE = 0x20
HAS_ParamNames = 0x80
CONSTANT_Utf8 = 0x01
CONSTANT_Float = 0x02
CONSTANT_Int = 0x03
CONSTANT_UInt = 0x04
CONSTANT_PrivateNs = 0x05
CONSTANT_Double = 0x06
CONSTANT_Qname = 0x07
CONSTANT_Namespace = 0x08
CONSTANT_Multiname = 0x09
CONSTANT_False = 0x0A
CONSTANT_True = 0x0B
CONSTANT_Null = 0x0C
CONSTANT_QnameA = 0x0D
CONSTANT_MultinameA = 0x0E
CONSTANT_RTQname = 0x0F
CONSTANT_RTQnameA = 0x10
CONSTANT_RTQnameL = 0x11
CONSTANT_RTQnameLA = 0x12
CONSTANT_NameL = 0x13
CONSTANT_NameLA = 0x14
CONSTANT_NamespaceSet = 0x15
CONSTANT_PackageNs = 0x16
CONSTANT_PackageInternalNs = 0x17
CONSTANT_ProtectedNs = 0x18
CONSTANT_ExplicitNamespace = 0x19
CONSTANT_StaticProtectedNs = 0x1A
CONSTANT_MultinameL = 0x1B
CONSTANT_MultinameLA = 0x1C
CONSTANT_TypeName = 0x1D
CONSTANT_Float4 = 0x1E
TRAIT_Slot = 0x00
TRAIT_Method = 0x01
TRAIT_Getter = 0x02
TRAIT_Setter = 0x03
TRAIT_Class = 0x04
TRAIT_Const = 0x06
TRAIT_mask = 15
ATTR_final = 0x10
ATTR_override = 0x20
ATTR_metadata = 0x40
CTYPE_VOID = 0
CTYPE_ATOM = 1
CTYPE_BOOLEAN = 2
CTYPE_INT = 3
CTYPE_UINT = 4
CTYPE_DOUBLE = 5
CTYPE_STRING = 6
CTYPE_NAMESPACE = 7
CTYPE_OBJECT = 8
CTYPE_FLOAT = 9
CTYPE_FLOAT4 = 10
MIN_API_MARK = 0xE000
MAX_API_MARK = 0xF8FF
MPL_HEADER = "/* This Source Code Form is subject to the terms of the Mozilla Public\n" \
" * License, v. 2.0. If a copy of the MPL was not distributed with this\n" \
" * file, You can obtain one at http://mozilla.org/MPL/2.0/. */"
# Python 2.5 and earlier didn't reliably handle float("nan") and friends uniformly
# across all platforms. This is a workaround that appears to be more reliable.
# if/when we require Python 2.6 or later we can use a less hack-prone approach
kPosInf = 1e300000
kNegInf = -1e300000
kNaN = kPosInf / kPosInf
def is_nan(val):
strValLower = str(val).lower()
return strValLower == "nan"
def is_pos_inf(val):
# [-]1.#INF on Windows in Python 2.5.2!
strValLower = str(val).lower()
return strValLower.endswith("inf") and not strValLower.startswith("-")
def is_neg_inf(val):
# [-]1.#INF on Windows in Python 2.5.2!
strValLower = str(val).lower()
return strValLower.endswith("inf") and strValLower.startswith("-")
def warn_notwriteable(file):
if os.path.exists(file) and not os.stat(file).st_mode & stat.S_IWUSR:
print("warning: %s is not writeable" % file)
return True
return False
class Float4:
x = kNaN
y = kNaN
z = kNaN
w = kNaN
def __init__(self, x, y, z, w):
self.x = x
self.y = y
self.z = z
self.w = w
def __str__(self):
return str(self.x)+','+str(self.y)+','+str(self.z)+','+str(self.w)
class Error(Exception):
nm = ""
def __init__(self, n):
self.nm = n
def __str__(self):
return self.nm
BASE_CLASS_NAME = "avmplus::ClassClosure"
BASE_INSTANCE_NAME = "avmplus::ScriptObject"
TYPEMAP_RETTYPE = {
CTYPE_OBJECT: "%s*",
CTYPE_ATOM: "avmplus::Atom",
CTYPE_VOID: "void",
CTYPE_BOOLEAN: "bool",
CTYPE_INT: "int32_t",
CTYPE_UINT: "uint32_t",
CTYPE_DOUBLE: "double",
CTYPE_FLOAT: "float",
CTYPE_FLOAT4: "float4_t",
CTYPE_STRING: "avmplus::String*",
CTYPE_NAMESPACE: "avmplus::Namespace*",
}
TYPEMAP_RETTYPE_GCREF = {
CTYPE_OBJECT: lambda t: "GCRef<%s>" % t.fqcppname(),
CTYPE_ATOM: lambda t: "avmplus::Atom",
CTYPE_VOID: lambda t: "void",
CTYPE_BOOLEAN: lambda t: "bool",
CTYPE_INT: lambda t: "int32_t",
CTYPE_UINT: lambda t: "uint32_t",
CTYPE_DOUBLE: lambda t: "double",
CTYPE_FLOAT: lambda t: "float",
CTYPE_FLOAT4: lambda t: "float4_t",
CTYPE_STRING: lambda t: "GCRef<avmplus::String>",
CTYPE_NAMESPACE: lambda t: "GCRef<avmplus::Namespace>",
}
TYPEMAP_THUNKRETTYPE = {
CTYPE_OBJECT: "avmplus::Atom(%s)",
CTYPE_ATOM: "avmplus::Atom(%s)",
CTYPE_VOID: "avmplus::Atom(%s)",
CTYPE_BOOLEAN: "avmplus::Atom(%s)",
CTYPE_INT: "avmplus::Atom(%s)",
CTYPE_UINT: "avmplus::Atom(%s)",
CTYPE_DOUBLE: "double(%s)",
CTYPE_FLOAT: "float(%s)",
CTYPE_FLOAT4: "%s",
CTYPE_STRING: "avmplus::Atom(%s)",
CTYPE_NAMESPACE: "avmplus::Atom(%s)",
}
TYPEMAP_MEMBERTYPE = {
CTYPE_OBJECT: "MMgc::GCTraceableObject::GCMember<%s>",
CTYPE_ATOM: "avmplus::AtomWB",
CTYPE_VOID: "#error",
CTYPE_BOOLEAN: "avmplus::bool32",
CTYPE_INT: "int32_t",
CTYPE_UINT: "uint32_t",
CTYPE_DOUBLE: "double",
CTYPE_FLOAT: "float",
CTYPE_FLOAT4: "float4_t",
CTYPE_STRING: "MMgc::GCTraceableObject::GCMember<avmplus::String>",
CTYPE_NAMESPACE: "MMgc::GCTraceableObject::GCMember<avmplus::Namespace>",
}
TYPEMAP_ARGTYPE = {
CTYPE_OBJECT: "%s*",
CTYPE_ATOM: "avmplus::Atom",
CTYPE_VOID: "void",
CTYPE_BOOLEAN: "avmplus::bool32",
CTYPE_INT: "int32_t",
CTYPE_UINT: "uint32_t",
CTYPE_DOUBLE: "double",
CTYPE_FLOAT: "float",
CTYPE_FLOAT4: "float4_t",
CTYPE_STRING: "avmplus::String*",
CTYPE_NAMESPACE: "avmplus::Namespace*",
}
TYPEMAP_ARGTYPE_SUFFIX = {
CTYPE_OBJECT: "OBJECT",
CTYPE_ATOM: "ATOM",
CTYPE_VOID: "VOID",
CTYPE_BOOLEAN: "BOOLEAN",
CTYPE_INT: "INT",
CTYPE_UINT: "UINT",
CTYPE_DOUBLE: "DOUBLE",
CTYPE_FLOAT: "FLOAT",
CTYPE_FLOAT4: "FLOAT4",
CTYPE_STRING: "STRING",
CTYPE_NAMESPACE: "NAMESPACE",
}
TYPEMAP_ARGTYPE_FOR_UNBOX = {
CTYPE_OBJECT: "%s*",
CTYPE_ATOM: "avmplus::Atom",
CTYPE_VOID: "#error",
CTYPE_BOOLEAN: "avmplus::bool32",
CTYPE_INT: "int32_t",
CTYPE_UINT: "uint32_t",
CTYPE_DOUBLE: "double",
CTYPE_FLOAT: "float",
CTYPE_FLOAT4: "float4_t",
CTYPE_STRING: "avmplus::String*",
CTYPE_NAMESPACE: "avmplus::Namespace*",
}
TYPEMAP_TO_ATOM = {
# The explicit cast to ScriptObject is necessary because the type in
# question may have only been forward-declared, thus calling methods
# on it isn't legal; since we know it's a ScriptObject, we can force the issue.
# Note that, for this reason, we can't use staticCast, as the compiler
# will complain that they are apparently unrelated types.
CTYPE_OBJECT: lambda val: "%s.reinterpretCast<avmplus::ScriptObject>()->atom()" % val,
CTYPE_ATOM: lambda val: "%s" % val,
CTYPE_VOID: lambda val: "undefinedAtom",
CTYPE_BOOLEAN: lambda val: "((%s) ? trueAtom : falseAtom)" % val,
CTYPE_INT: lambda val: "core->intToAtom(%s)" % val,
CTYPE_UINT: lambda val: "core->uintToAtom(%s)" % val,
CTYPE_DOUBLE: lambda val: "core->doubleToAtom(%s)" % val,
CTYPE_FLOAT: lambda val: "core->floatToAtom(%s)" % val,
CTYPE_FLOAT4: lambda val: "core->float4ToAtom(%s)" % val,
CTYPE_STRING: lambda val: "%s->atom()" % val,
CTYPE_NAMESPACE: lambda val: "%s->atom()" % val,
}
TYPEMAP_TO_ATOM_NEEDS_CORE = {
CTYPE_OBJECT: False,
CTYPE_ATOM: False,
CTYPE_VOID: False,
CTYPE_BOOLEAN: False,
CTYPE_INT: True,
CTYPE_UINT: True,
CTYPE_DOUBLE: True,
CTYPE_FLOAT: True,
CTYPE_FLOAT4: True,
CTYPE_STRING: False,
CTYPE_NAMESPACE: False,
}
TYPEMAP_ATOM_TO_GCREF = {
# We can't use static_cast<> because the subclass might be only forward-declared at this point;
# use good old brute-force cast instead.
CTYPE_OBJECT: lambda val,t: "GCRef<%s>((%s*)(avmplus::AvmCore::atomToScriptObject(%s)))" % (t.fqcppname(),t.fqcppname(),val),
CTYPE_ATOM: lambda val,t: "%s" % val,
CTYPE_VOID: lambda val,t: "avmplus::undefinedAtom",
CTYPE_BOOLEAN: lambda val,t: "((%s) != avmplus::falseAtom)" % val,
CTYPE_INT: lambda val,t: "avmplus::AvmCore::integer(%s)" % val,
CTYPE_UINT: lambda val,t: "avmplus::AvmCore::toUInt32(%s)" % val,
CTYPE_DOUBLE: lambda val,t: "avmplus::AvmCore::number(%s)" % val,
CTYPE_FLOAT: lambda val,t: "avmplus::AvmCore::singlePrecisionFloat(%s)" % val,
# no value for CTYPE_FLOAT4; this is intentional, since the case of float4 is more complex, and needs to be treated separately
CTYPE_STRING: lambda val,t: "GCRef<avmplus::String>(avmplus::AvmCore::atomToString(%s))" % val,
CTYPE_NAMESPACE: lambda val,t: "GCRef<avmplus::Namespace>(avmplus::AvmCore::atomToNamespace(%s))" % val,
}
def uint(i):
return int(i) & 0xffffffff
def c_argtype_from_enum(ct):
assert ct != CTYPE_OBJECT
r = TYPEMAP_ARGTYPE[ct]
return r
def to_cname(nm):
nm = str(nm)
nm = nm.replace("+", "_");
nm = nm.replace("-", "_");
nm = nm.replace("?", "_");
nm = nm.replace("!", "_");
nm = nm.replace("<", "_");
nm = nm.replace(">", "_");
nm = nm.replace("=", "_");
nm = nm.replace("(", "_");
nm = nm.replace(")", "_");
nm = nm.replace("\"", "_");
nm = nm.replace("'", "_");
nm = nm.replace("*", "_");
nm = nm.replace(" ", "_");
nm = nm.replace(".", "_");
nm = nm.replace("$", "_");
nm = nm.replace("::", "_");
nm = nm.replace(":", "_");
nm = nm.replace("/", "_");
return nm
GLUECLASSES_WITHOUT_NS = frozenset((
'bool',
'double',
'float',
'float4_t',
'int32_t',
'uint32_t'))
def ns_prefix(ns, iscls):
if not ns.isPublic() and not ns.isInternal():
if ns.isPrivate() and not iscls:
return "private_";
if ns.isProtected():
return "protected_";
if ns.srcname != None:
return to_cname(str(ns.srcname)) + "_"
p = to_cname(ns.uri);
if len(p) > 0:
p += "_"
return p
def stripVersion(uri):
if len(uri) > 0:
uri16 = uri.decode('utf8')
cc = ord(uri16[-1])
if cc >= MIN_API_MARK and cc <= MAX_API_MARK:
return cc-MIN_API_MARK, uri16[0:len(uri16)-1].encode('utf8')
return -1,uri
class Namespace:
uri = ""
kind = 0
srcname = None
def __init__(self, uri, kind):
self.uri = uri
self.kind = kind
def __str__(self):
return self.uri
def isPublic(self):
return self.kind in [CONSTANT_Namespace, CONSTANT_PackageNs] and self.uri == ""
def isInternal(self):
return self.kind in [CONSTANT_PackageInternalNs]
def isPrivate(self):
return self.kind in [CONSTANT_PrivateNs]
def isProtected(self):
return self.kind in [CONSTANT_ProtectedNs, CONSTANT_StaticProtectedNs]
def stripVersion(self):
api, strippeduri = stripVersion(self.uri)
# it's important to return 'self' (and not an identical clone)
# if we are unversioned, otherwise native methods with custom namespaces
# may be emitted incorrectly
if api < 0:
return self
newself = Namespace(strippeduri, self.kind)
newself.srcname = self.srcname
return newself
class QName:
ns = None
name = ""
def __init__(self, ns, name):
self.ns = ns
self.name = name
def __str__(self):
if str(self.ns) == "":
return self.name
if self.ns == None:
return "*::" + self.name
return str(self.ns) + "::" + self.name
class Multiname:
nsset = None
name = ""
def __init__(self, nsset, name):
self.nsset = nsset
self.name = name
def __str__(self):
nsStrings = map(lambda ns: '"' + str(ns).decode("utf8") + '"', self.nsset)
stringForNSSet = '[' + ', '.join(nsStrings) + ']'
return stringForNSSet + '::' + unicode(self.name.decode("utf8"))
class TypeName:
name = ""
types = None
def __init__(self, name, types):
self.name = name
self.types = types
def __str__(self):
# @todo horrible special-casing, improve someday
s = str(self.name)
t = str(self.types[0])
if t == "int":
s += "$int"
elif t == "uint":
s += "$uint"
elif t == "Number":
s += "$double"
elif t == "float":
s += "$float"
elif t == "float4":
s += "$float4"
else:
s += "$object"
return s
class MetaData:
name = ""
attrs = {}
def __init__(self, name):
self.name = name
self.attrs = {}
class MemberInfo:
id = -1
kind = -1
name = ""
name_index = -1
metadata = None
class MethodInfo(MemberInfo):
flags = 0
debugName = ""
paramTypes = None
paramNames = None
optional_count = 0
optionalValues = None
returnType = None
local_count = 0
max_scope = 0
max_stack = 0
code_length = 0
code = None
activation = None
native_id_name = None
native_method_name = None
final = False
override = False
receiver = None
unbox_this = -1 # -1 == undetermined, 0 = no, 1 = yes
vtable_index = -1
def isNative(self):
return (self.flags & NATIVE) != 0
def needRest(self):
return (self.flags & NEED_REST) != 0
def hasOptional(self):
return (self.flags & HAS_OPTIONAL) != 0
def assign_names(self, traits, prefix):
self.receiver = traits
if self == traits.init:
if self.isNative():
raise Error("ctors cannot be native")
return
assert(isinstance(self.name, QName))
self.native_id_name = prefix + ns_prefix(self.name.ns, False) + self.name.name
self.native_method_name = self.name.name
if self.kind == TRAIT_Getter:
self.native_id_name += "_get"
self.native_method_name = "get_" + self.native_method_name
elif self.kind == TRAIT_Setter:
self.native_id_name += "_set"
self.native_method_name = "set_" + self.native_method_name
if self.name.ns.srcname != None:
self.native_method_name = str(self.name.ns.srcname) + "_" + self.native_method_name
# if we are an override, prepend the classname to the C method name.
# (native method implementations must not be virtual, and some compilers
# will be unhappy if a subclass overrides a method with the same name and signature
# without it being virtual.) Note that we really only need to do this if the ancestor
# implementation is native, rather than pure AS3, but we currently do it regardless.
if self.override:
self.native_method_name = traits.name.name + "_" + self.native_method_name
self.native_method_name = to_cname(self.native_method_name)
class SlotInfo(MemberInfo):
type = ""
value = ""
ns = None
fileOffset = -1
class NativeInfo:
traits = None
itraits = None
class_gc_exact = None
instancebase_name = None
instance_gc_exact = None
method_map_name = None
construct = None
def __init__(self, traits, itraits):
self.traits = traits
self.itraits = itraits
def parse_one_nativeinfo(self, attrs, is_vm_builtin):
for k in attrs.keys():
v = attrs[k]
if (k == "script"):
raise Error("native scripts are no longer supported; please use a native class instead and wrap with AS3 code as necessary.")
elif (k == "cls"):
self.set_class(v)
elif (k == "instance"):
self.set_instance(v)
elif (k == "instancebase"):
self.set_instancebase(v)
elif (k == "gc"):
self.set_classGC(v)
self.set_instanceGC(v)
elif (k == "classgc"):
self.set_classGC(v)
elif (k == "instancegc"):
self.set_instanceGC(v)
elif (k == "methods"):
if v != "auto":
self.method_map_name = v
elif (k == "construct"):
self.set_construct(v, is_vm_builtin)
elif (k == "friend"):
self.set_friend(v)
else:
raise Error("unknown attribute native(%s)" % k)
if (self.traits.cpp_name_comps == None) and (self.itraits.cpp_name_comps == None):
# it's OK to specify construct="native" for a pure AS3 class
# it's OK to specify friend="whatever" for a pure AS3 class
# it's OK to specify gc="whatever" for a pure AS3 class
if not (self.construct == "native" or self.traits.cpp_friend_classes != None or self.class_gc_exact != None or self.instance_gc_exact != None):
raise Error("native metadata must specify (cls,instance): %s" % str(attrs))
def fullyQualifiedCPPClassName(self, className):
r = className.split('::')
if (len(opts.rootImplNS) > 0) and not className.startswith('::') and not className in GLUECLASSES_WITHOUT_NS:
r.insert(0, opts.rootImplNS)
return r
def set_friend(self, name):
if self.traits.cpp_friend_classes != None:
raise Error("native(friend) may not be specified multiple times for the same class: %s %s" % (self.traits.fqcppname(), name))
self.traits.cpp_friend_classes = name.split(',')
self.itraits.cpp_friend_classes = name.split(',')
def set_class(self, name):
if self.traits.cpp_name_comps != None:
raise Error("native(cls) may not be specified multiple times for the same class: %s %s" % (self.traits.fqcppname(), name))
self.traits.cpp_name_comps = self.fullyQualifiedCPPClassName(name)
def set_instance(self, name):
if self.itraits.cpp_name_comps != None:
raise Error("native(instance) may not be specified multiple times for the same class: %s %s" % (self.itraits.fqcppname(), name))
if name == "ScriptObject" or name == BASE_INSTANCE_NAME:
raise Error("native(instance='ScriptObject') is no longer supported:")
self.itraits.cpp_name_comps = self.fullyQualifiedCPPClassName(name)
def set_instancebase(self, name):
if self.instancebase_name != None:
raise Error("native(instancebase) may not be specified multiple times for the same class: %s %s" % (self.instancebase_name, name))
comps = self.fullyQualifiedCPPClassName(name)
self.instancebase_name = '::'.join(filter(lambda ns: len(ns) > 0, comps))
def set_construct(self, value, is_vm_builtin):
if self.construct != None:
raise Error("native(construct) may not be specified multiple times for the same class")
if value in ["override", "instance"]:
if not is_vm_builtin:
raise Error('construct=%s may only be specified for the VM builtins' % value)
self.construct = value
elif value in ["none", "abstract", "abstract-restricted", "restricted", "check", "restricted-check", "native"]:
self.construct = value
else:
raise Error('native metadata specified illegal value, "%s" for construct field.' % value)
def set_classGC(self, gc):
if self.class_gc_exact != None:
raise Error("native(classgc) may not be specified multiple times for the same class: %s %s" % (self.traits.fqcppname(), gc))
if gc == "exact":
self.class_gc_exact = True
elif gc == "conservative":
self.class_gc_exact = False
else:
raise Error("native(classgc) can only be specified as 'exact' or 'conservative': %s %s" % (self.traits.fqcppname(), gc))
def set_instanceGC(self, gc):
if self.instance_gc_exact != None:
raise Error("native(instancegc) may not be specified multiple times for the same class: %s %s" % (self.itraits.fqcppname(), gc))
if gc == "exact":
self.instance_gc_exact = True
elif gc == "conservative":
self.instance_gc_exact = False
else:
raise Error("native(instancegc) can only be specified as 'exact' or 'conservative': %s %s" % (self.itraits.fqcppname(), gc))
@staticmethod
def parse_native_info(t, is_vm_builtin):
itraits = t.itraits
ni = NativeInfo(t, itraits)
if t.metadata != None:
for md in t.metadata:
if md.name == "native":
ni.parse_one_nativeinfo(md.attrs, is_vm_builtin)
if itraits.is_interface:
if t.cpp_name_comps != None or itraits.cpp_name_comps != None:
raise Error("It is not legal to specify native(cls/instance) for an interface")
# this is a little hacky, but it allows us to assume that all traits have a valid CPP name.
# since we don't yet surface a C++ wrapper for interfaces, this will have to do.
t.cpp_name_comps = ni.fullyQualifiedCPPClassName(itraits.name.name + "Class")
t.is_synthetic = True
itraits.cpp_name_comps = ni.fullyQualifiedCPPClassName(itraits.name.name + "Interface")
itraits.is_synthetic = True
itraits.base = "Object"
else:
if t.cpp_name_comps == None and itraits.cpp_name_comps != None:
raise Error("It is not legal to specify native(instance) without native(cls)")
if t.cpp_name_comps == None:
t.cpp_name_comps = ni.fullyQualifiedCPPClassName(itraits.name.name + "Class")
t.is_synthetic = True
# if gc metadata not specified, assume we want it exact
if ni.class_gc_exact == None:
ni.class_gc_exact = True
if itraits.cpp_name_comps == None:
if str(t.name) == "Object$":
# "Object" is special-cased.
itraits.cpp_name_comps = BASE_INSTANCE_NAME.split('::')
else:
itraits.cpp_name_comps = ni.fullyQualifiedCPPClassName(itraits.name.name + "Object")
itraits.is_synthetic = True
# if gc metadata not specified, assume we want it exact
if ni.instance_gc_exact == None:
ni.instance_gc_exact = True
# force to True or False (no "None" allowed)
if ni.class_gc_exact != True:
ni.class_gc_exact = False;
if ni.instance_gc_exact != True:
ni.instance_gc_exact = False;
t.is_gc_exact = ni.class_gc_exact
itraits.is_gc_exact = ni.instance_gc_exact
if ni.construct != None:
t.construct = ni.construct
if t.construct in ["override", "instance"]:
t.has_construct_method_override = True
if t.construct in ["abstract-restricted", "restricted", "restricted-check"]:
t.is_restricted_inheritance = True
if t.construct in ["abstract", "abstract-restricted"]:
t.is_abstract_base = True
if t.construct in ["check", "restricted-check"]:
t.has_pre_create_check = True
if ni.construct == "instance":
itraits.construct = "override"
itraits.has_construct_method_override = True
if str(t.name) == "Object$":
# "Object" is special-cased.
t.createInstanceProcName = "ClassClosure::createScriptObjectProc"
elif t.construct in ["none", "abstract", "abstract-restricted"]:
t.createInstanceProcName = "ClassClosure::cantInstantiateCreateInstanceProc"
elif t.construct in ["override", "instance"] or itraits.ctype != CTYPE_OBJECT:
t.createInstanceProcName = "ClassClosure::impossibleCreateInstanceProc"
elif t.construct == "native":
t.createInstanceProcName = "ClassClosure::cantInstantiateCreateInstanceProc"
t.has_custom_createInstanceProc = True
assert t.cpp_name_comps != None
elif t.cpp_name_comps != None:
t.createInstanceProcName = "%s::createInstanceProc" % t.fqcppname()
t.has_custom_createInstanceProc = True
# t.fqinstancebase_name = ni.instancebase_name # not supported for classes
t.method_map_name = t.fqcppname() # custom method_map_name never applies to class
t.slotsStructName = to_cname(t.fqcppname()) + 'Slots'
t.slotsInstanceName = 'm_slots_' + t.cppname()
assert itraits != None
itraits.fqinstancebase_name = ni.instancebase_name
if ni.method_map_name != None:
itraits.method_map_name = ni.method_map_name
else:
itraits.method_map_name = itraits.fqcppname()
itraits.slotsStructName = to_cname(itraits.fqcppname()) + 'Slots'
itraits.slotsInstanceName = 'm_slots_' + itraits.cppname()
BMAP = {
"Object": CTYPE_ATOM, # yes, items of exactly class "Object" are stored as Atom; subclasses are stored as pointer-to-Object
"null": CTYPE_ATOM,
"*": CTYPE_ATOM,
"void": CTYPE_VOID,
"int": CTYPE_INT,
"uint": CTYPE_UINT,
"Number": CTYPE_DOUBLE,
"Boolean": CTYPE_BOOLEAN,
"String": CTYPE_STRING,
"Namespace": CTYPE_NAMESPACE,
"float": CTYPE_FLOAT,
"float4": CTYPE_FLOAT4
};
class Traits:
name = ""
qname = None
init = None
itraits = None
ctraits = None
base = None
flags = 0
protectedNs = 0
is_sealed = False
is_final = False
is_interface = False
interfaces = None
names = None
slots = None
tmethods = None
tmethod_index_count = -1
tmethods_name_map = None
members = None
class_id = -1
ctype = CTYPE_OBJECT
metadata = None
cpp_name_comps = None
cpp_friend_classes = None
slotsStructName = None
slotsInstanceName = None
nextSlotId = 0
is_gc_exact = False
construct = None
createInstanceProcName = None
# some values for "construct" imply an override to the ScriptObject::construct method,
# some don't. this simplifies things.
has_construct_method_override = False
has_custom_createInstanceProc = False
is_restricted_inheritance = False
is_abstract_base = False
has_pre_create_check = False
is_synthetic = False
# FIXME, this is a hack for MI classes in AIR
fqinstancebase_name = None
# FIXME, this is a hack for MI classes in AIR
method_map_name = None
def __init__(self, name):
self.names = {}
self.slots = []
self.tmethods = []
self.name = name
if BMAP.has_key(str(name)):
self.ctype = BMAP[str(name)]
def __str__(self):
return str(self.name)
def cpp_offsetof_slots(self):
if (len(self.slots) > 0):
return "offsetof(%s, %s)" % (self.fqcppname(), self.slotsInstanceName)
else:
return "0"
# What's the C++ type to use when declaring this type as a member of a GCObject?
def cpp_gcmember_name(self):
r = TYPEMAP_MEMBERTYPE[self.ctype]
if self.ctype == CTYPE_OBJECT:
r = r % self.fqcppname()
return r
# What's the C++ type to use when declaring this type as an input argument to a C++ method?
def cpp_argument_name(self):
r = TYPEMAP_ARGTYPE[self.ctype]
if self.ctype == CTYPE_OBJECT:
r = r % self.fqcppname()
return r
# What's the C++ type to use when unboxing this type as an input argument to a C++ method?
def cpp_unboxing_argument_name(self):
r = TYPEMAP_ARGTYPE_FOR_UNBOX[self.ctype]
if self.ctype == CTYPE_OBJECT:
r = r % self.fqcppname()
return r
# What's the C++ type to use when returning this as a function result?
def cpp_return_name(self):
r = TYPEMAP_RETTYPE[self.ctype]
if self.ctype == CTYPE_OBJECT:
r = r % self.fqcppname()
return r
# return the fully qualified cpp name, eg "foo::bar::FooObject"
def fqcppname(self):
return '::'.join(filter(lambda ns: len(ns) > 0, self.cpp_name_comps))
# return the cpp name minus namespaces, eg "FooObject"
def cppname(self):
return self.cpp_name_comps[-1]
# return the cpp namespace(s), eg "foo::bar"
def cppns(self):
return '::'.join(filter(lambda ns: len(ns) > 0, self.cpp_name_comps[:-1]))
# return the complete name if it starts with ::, otherwise just the cppname
def niname(self):
if self.cpp_name_comps[0] == "":
return '::'.join(self.cpp_name_comps)
else:
return self.cpp_name_comps[-1]
NULL = Traits("*")
UNDEFINED = Traits("void")
class ByteArray:
data = None
pos = 0
def __init__(self, data):
self.data = data
self.pos = 0
def readU8(self):
r = unpack_from("B", self.data, self.pos)[0]
self.pos += 1
assert(r >= 0 and r <= 255)
return r
def readU16(self):
r = unpack_from("<h", self.data, self.pos)[0]
self.pos += 2
assert(r >= 0 and r <= 65535)
return r
def readDouble(self):
r = unpack_from("<d", self.data, self.pos)[0]
self.pos += 8
return r
def readFloat(self):
r = unpack_from("<f", self.data, self.pos)[0]
self.pos += 4
return r
def readFloat4(self):
r = unpack_from("<4f", self.data, self.pos)[0]
self.pos += 16
return r
def readBytes(self, lenbytes):
r = self.data[self.pos:self.pos+lenbytes]
self.pos += lenbytes
return r
def readUTF8(self):
lenbytes = self.readU30()
return self.readBytes(lenbytes)
def readU30(self):
result = self.readU8()
if not result & 0x00000080:
return result
result = (result & 0x0000007f) | (self.readU8() << 7)
if not result & 0x00004000:
return result
result = (result & 0x00003fff) | (self.readU8() << 14)
if not result & 0x00200000:
return result
result = (result & 0x001fffff) | (self.readU8() << 21)
if not result & 0x10000000: