-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathILBlockTranslator.cs
More file actions
3545 lines (2898 loc) · 150 KB
/
Copy pathILBlockTranslator.cs
File metadata and controls
3545 lines (2898 loc) · 150 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.ILAst;
using JSIL.Ast;
using JSIL.Compiler.Extensibility;
using JSIL.Internal;
using JSIL.Transforms;
using Microsoft.CSharp.RuntimeBinder;
using Mono.Cecil;
using Mono.Cecil.Cil;
using TypeInfo = JSIL.Internal.TypeInfo;
namespace JSIL {
public class ILBlockTranslator {
public readonly AssemblyTranslator Translator;
public readonly DecompilerContext Context;
public readonly MethodReference ThisMethodReference;
public readonly MethodDefinition ThisMethod;
public readonly MethodSymbols Symbols;
public readonly ILBlock Block;
public readonly JavascriptFormatter Output = null;
public readonly Dictionary<string, JSVariable> Variables = new Dictionary<string, JSVariable>();
protected readonly Dictionary<ILVariable, JSVariable> RenamedVariables = new Dictionary<ILVariable, JSVariable>();
private readonly Dictionary<string, JSIndirectVariable> IndirectVariables = new Dictionary<string, JSIndirectVariable>();
public readonly SpecialIdentifiers SpecialIdentifiers;
public List<TypeReference> TemporaryVariableTypes = new List<TypeReference>();
protected int RenamedVariableCount = 0;
protected int UnlabelledBlockCount = 0;
protected int NextSwitchId = 0;
protected readonly Stack<bool> AutoCastingState = new Stack<bool>();
protected readonly Stack<JSStatement> Blocks = new Stack<JSStatement>();
static readonly ConcurrentCache<ILCode, System.Reflection.MethodInfo[]> NodeTranslatorCache = new ConcurrentCache<ILCode, System.Reflection.MethodInfo[]>();
static readonly ConcurrentCache<ILCode, System.Reflection.MethodInfo[]>.CreatorFunction GetNodeTranslatorsUncached;
protected readonly Func<TypeReference, TypeReference> TypeReferenceReplacer;
protected readonly IFunctionTransformer[] FunctionTransformers;
private readonly HashSet<TypeReference> _rawTypes;
static ILBlockTranslator () {
GetNodeTranslatorsUncached = (code) => {
var methodName = String.Format("Translate_{0}", code);
var bindingFlags = System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.InvokeMethod |
System.Reflection.BindingFlags.NonPublic;
var t = typeof(ILBlockTranslator);
var methods = t.GetMember(
methodName, MemberTypes.Method, bindingFlags
).OfType<System.Reflection.MethodInfo>().ToArray();
if (methods.Length == 0) {
var alternateMethodName = methodName.Substring(0, methodName.LastIndexOf("_"));
methods = t.GetMember(
alternateMethodName, MemberTypes.Method, bindingFlags
).OfType<System.Reflection.MethodInfo>().ToArray();
}
if (methods.Length == 0)
return null;
return methods;
};
}
public ILBlockTranslator (
AssemblyTranslator translator, DecompilerContext context,
MethodReference methodReference, MethodDefinition methodDefinition,
MethodSymbols methodSymbols,
ILBlock ilb, IEnumerable<ILVariable> parameters,
IEnumerable<ILVariable> allVariables,
Func<TypeReference, TypeReference> referenceReplacer = null
) {
Translator = translator;
Context = context;
ThisMethodReference = methodReference;
ThisMethod = methodDefinition;
Block = ilb;
TypeReferenceReplacer = referenceReplacer;
Symbols = methodSymbols;
SpecialIdentifiers = translator.GetSpecialIdentifiers(TypeSystem);
_rawTypes = new HashSet<TypeReference>
{
TypeSystem.Boolean,
TypeSystem.SByte,
TypeSystem.Byte,
TypeSystem.Int16,
TypeSystem.UInt16,
TypeSystem.Int32,
TypeSystem.UInt32,
TypeSystem.Single,
TypeSystem.Double,
TypeSystem.Char
};
if (methodReference.HasThis)
Variables.Add("this", JSThisParameter.New(methodReference.DeclaringType, methodReference));
foreach (var parameter in parameters) {
if ((parameter.Name == "this") && (parameter.OriginalParameter.Index == -1))
continue;
var jsp = new JSParameter(parameter.Name, parameter.Type, methodReference);
Variables.Add(jsp.Name, jsp);
}
foreach (var variable in allVariables) {
DeclareVariable(variable, methodReference);
}
var methodInfo = TypeInfo.Get(methodReference) as Internal.MethodInfo;
TypeReference packedArrayAttributeType;
var packedArrayArgumentNames = PackedArrayUtil.GetPackedArrayArgumentNames(methodInfo, out packedArrayAttributeType);
if (packedArrayArgumentNames != null)
foreach (var argumentName in packedArrayArgumentNames) {
if (!Variables.ContainsKey(argumentName))
throw new ArgumentException("JSPackedArrayArguments specifies an argument named '" + argumentName + "' but no such argument exists");
var variable = Variables[argumentName];
var newVariableType = PackedArrayUtil.MakePackedArrayType(variable.GetActualType(TypeSystem), packedArrayAttributeType);
if (newVariableType == null)
throw new ArgumentException("JSPackedArrayArguments specifies an argument named '" + argumentName + "' but it cannot be made a packed array");
ChangeVariableType(Variables[argumentName], newVariableType);
}
AutoCastingState.Push(true);
FunctionTransformers = Translator.FunctionTransformers;
}
protected TypeReference FixupReference (TypeReference reference) {
// TODO: Expand !N to actual generic parameter it references
if (TypeReferenceReplacer != null)
return TypeReferenceReplacer(reference);
else
return reference;
}
// When a method body is replaced by the body of a proxy method, the method body
// will contain references to members of the proxy class instead of the class being
// proxied. We correct those references to point to the class being proxied (via
// a call to FixupReference) before doing MemberInfo lookups.
protected T GetMember<T> (MemberReference member)
where T : class, IMemberInfo
{
var declaringType = member.DeclaringType;
declaringType = FixupReference(declaringType);
var typeInfo = TypeInfo.Get(declaringType);
if (typeInfo == null) {
Console.Error.WriteLine("Warning: type not loaded: {0}", declaringType.FullName);
return default(T);
}
var identifier = MemberIdentifier.New(TypeInfo, member);
IMemberInfo result;
if (!typeInfo.Members.TryGetValue(identifier, out result)) {
// Console.Error.WriteLine("Warning: member not defined: {0}", member.FullName);
return default(T);
}
return result as T;
}
protected JSIL.Internal.MethodInfo GetMethod (MethodReference method) {
return GetMember<JSIL.Internal.MethodInfo>(method);
}
protected JSIL.Internal.FieldInfo GetField (FieldReference field) {
return GetMember<JSIL.Internal.FieldInfo>(field);
}
internal MethodTypeFactory MethodTypes {
get {
return Translator.FunctionCache.MethodTypes;
}
}
protected JSSpecialIdentifiers JS {
get {
return SpecialIdentifiers.JS;
}
}
protected JSILIdentifier JSIL {
get {
return SpecialIdentifiers.JSIL;
}
}
public ITypeInfoSource TypeInfo {
get {
return Translator.TypeInfoProvider;
}
}
public TypeSystem TypeSystem {
get {
return Context.CurrentModule.TypeSystem;
}
}
public JSBlockStatement Translate () {
try {
return TranslateNode(Block);
} catch (AbortTranslation at) {
Translator.WarningFormat("Method {0} not translated: {1}", ThisMethod.Name, at.Message);
return null;
}
}
public JSNode TranslateNode (ILNode node) {
Translator.WarningFormat("Node NYI: {0}", node.GetType().Name);
return new JSUntranslatableStatement(node.GetType().Name);
}
public List<JSExpression> Translate (IList<ILExpression> values, IList<ParameterDefinition> parameters, bool hasThis) {
var result = new List<JSExpression>();
ParameterDefinition parameter;
for (int i = 0, c = values.Count; i < c; i++) {
var value = values[i];
var parameterIndex = i;
if (hasThis)
parameterIndex -= 1;
if ((parameterIndex < parameters.Count) && (parameterIndex >= 0))
parameter = parameters[parameterIndex];
else
parameter = null;
var translated = TranslateNode(value);
if ((parameter != null) && (parameter.ParameterType is ByReferenceType)) {
result.Add(new JSPassByReferenceExpression(translated));
} else
result.Add(translated);
}
if (result.Any((je) => je == null)) {
var errorString = new StringBuilder();
errorString.AppendLine("The following expressions failed to translate:");
for (var i = 0; i < values.Count; i++) {
if (result[i] == null)
errorString.AppendLine(values[i].ToString());
}
throw new InvalidDataException(errorString.ToString());
}
return result;
}
public List<JSExpression> Translate (IEnumerable<ILExpression> values) {
var result = new List<JSExpression>();
StringBuilder errorString = null;
foreach (var value in values) {
var translated = TranslateNode(value);
if (translated == null) {
if (errorString == null) {
errorString = new StringBuilder();
errorString.AppendLine("The following expressions failed to translate:");
}
errorString.AppendLine(value.ToString());
} else {
result.Add(translated);
}
}
if (errorString != null)
throw new InvalidDataException(errorString.ToString());
return result;
}
protected bool NeedToRenameVariable (string name, TypeReference type) {
if (String.IsNullOrWhiteSpace(name))
return true;
if (!Variables.ContainsKey(name))
return false;
if (!TypeUtil.TypesAreEqual(Variables[name].IdentifierType, type))
return true;
return false;
}
protected JSVariable DeclareVariable (ILVariable variable, MethodReference function) {
if (variable.Name.StartsWith("<>c__")) {
return DeclareVariableInternal(JSClosureVariable.New(variable, function));
}
var name = variable.Name;
if (NeedToRenameVariable(name, variable.Type)) {
if (!NeedToRenameVariable(variable.OriginalVariable.Name, variable.Type))
name = variable.OriginalVariable.Name;
else
name = String.Format("{0}${1}", name, RenamedVariableCount++);
}
var result = JSVariable.New(name, variable.Type, function);
return DeclareVariableInternal(result);
}
protected JSVariable DeclareVariableInternal (JSVariable variable) {
JSVariable existing;
if (Variables.TryGetValue(variable.Identifier, out existing)) {
if (!TypeUtil.TypesAreEqual(variable.IdentifierType, existing.IdentifierType)) {
throw new InvalidOperationException(String.Format(
"A variable with the name '{0}' is already declared in this scope, with a different type.",
variable.Identifier
));
} else if (!variable.DefaultValue.Equals(existing.DefaultValue)) {
throw new InvalidOperationException(String.Format(
"A variable with the name '{0}' is already declared in this scope, with a different default value.",
variable.Identifier
));
}
return existing;
}
Variables[variable.Identifier] = variable;
return variable;
}
protected static bool CopyOnReturn (TypeReference type) {
return TypeUtil.IsStruct(type);
}
protected JSExpression Translate_UnaryOp (ILExpression node, JSUnaryOperator op) {
var inner = TranslateNode(node.Arguments[0]);
var innerType = JSExpression.DeReferenceType(inner.GetActualType(TypeSystem));
// Detect the weird pattern '!(x = y as z)' and transform it into '(x = y as z) != null'
if (
(op == JSOperator.LogicalNot) &&
!TypeUtil.TypesAreAssignable(TypeInfo, TypeSystem.Boolean, innerType)
) {
return new JSBinaryOperatorExpression(
JSOperator.Equal, inner, new JSDefaultValueLiteral(innerType), TypeSystem.Boolean
);
}
// Insert correct casts when unary operators are applied to enums.
if (TypeUtil.IsEnum(innerType) && TypeUtil.IsEnum(node.InferredType ?? node.ExpectedType)) {
return JSCastExpression.New(
new JSUnaryOperatorExpression(
op,
JSCastExpression.New(inner, TypeSystem.Int32, TypeSystem),
TypeSystem.Int32
),
node.InferredType ?? node.ExpectedType, TypeSystem
);
}
return new JSUnaryOperatorExpression(
op, inner, node.InferredType ?? node.ExpectedType
);
}
public static bool ShouldSuppressAutoCastingForOperator (JSOperator op) {
return (op is JSComparisonOperator);
}
protected JSExpression Translate_BinaryOp_Pointer (ILExpression node, JSBinaryOperator op, JSExpression lhs, JSExpression rhs) {
if ((lhs is JSUntranslatableExpression) || (rhs is JSUntranslatableExpression))
return new JSUntranslatableExpression(node);
// We can end up with a pointer literal in an arithmetic expression.
// In this case we want to switch it back to a normal integer literal so that the math operations work.
var leftPointer = lhs as JSPointerLiteral;
var rightPointer = rhs as JSPointerLiteral;
if (!(op is JSAssignmentOperator)) {
if (leftPointer != null)
lhs = new JSNativeIntegerLiteral((int)leftPointer.Value);
if (rightPointer != null)
rhs = new JSNativeIntegerLiteral((int)rightPointer.Value);
}
var leftCast = lhs as JSPointerCastExpression;
var rightCast = rhs as JSPointerCastExpression;
// HACK: IL sometimes does (T*)((UInt64)lhs + (UInt64)rhs). Strip the conversions so we can make sense of it
if (
(leftCast != null) &&
TypeUtil.IsIntegral(leftCast.NewType.Type)
)
lhs = leftCast.Pointer;
if (
(rightCast != null) &&
TypeUtil.IsIntegral(rightCast.NewType.Type)
)
rhs = rightCast.Pointer;
var leftType = lhs.GetActualType(TypeSystem);
var rightType = rhs.GetActualType(TypeSystem);
var leftIsNativeInt = TypeUtil.IsNativeInteger(leftType);
var rightIsNativeInt = TypeUtil.IsNativeInteger(rightType);
var leftIsPointerish = TypeUtil.IsPointer(leftType) || leftIsNativeInt;
var rightIsPointerish = TypeUtil.IsPointer(rightType) || rightIsNativeInt;
JSExpression result = null;
if (leftIsPointerish && TypeUtil.IsIntegral(rightType)) {
if (
(op == JSOperator.Add) ||
(op == JSOperator.AddAssignment)
) {
result = new JSPointerAddExpression(
lhs, rhs,
op == JSOperator.AddAssignment
);
} else if (
(op == JSOperator.Subtract) ||
(op == JSOperator.SubtractAssignment)
) {
result = new JSPointerAddExpression(
lhs,
new JSUnaryOperatorExpression(JSOperator.Negation, rhs, TypeSystem.NativeInt()),
op == JSOperator.SubtractAssignment
);
} else if (
(op == JSOperator.Divide) ||
(op == JSOperator.DivideAssignment)
) {
// This should only happen when the lhs is already a native int
if (TypeUtil.IsPointer(leftType))
return new JSUntranslatableExpression(node);
result = new JSBinaryOperatorExpression(
op, lhs, rhs, TypeSystem.NativeInt()
);
} else if (
op is JSComparisonOperator
) {
if (!TypeUtil.IsPointer(leftType))
return new JSUntranslatableExpression(node);
result = new JSBinaryOperatorExpression(
op,
new JSDotExpression(lhs, new JSStringIdentifier("offsetInBytes", TypeSystem.Int32, true)),
rhs,
TypeSystem.Boolean
);
} else {
// TODO: Implement ptr * <native-int>
// TODO: Implement ptr & <mask>
if (Debugger.IsAttached) {
Console.WriteLine("Debugger.Break()");
Console.Error.WriteLine("Debugger.Break()");
// Debugger.Break();
}
}
} else if (leftIsPointerish && rightIsPointerish) {
if (op == JSOperator.Subtract) {
result = new JSPointerDeltaExpression(
lhs, rhs, TypeSystem.NativeInt()
);
} else if (op is JSComparisonOperator) {
result = new JSPointerComparisonExpression(op, lhs, rhs, TypeSystem.Boolean);
} else if ((op == JSOperator.Add) && (leftIsNativeInt || rightIsNativeInt)) {
if (leftIsNativeInt)
return new JSPointerAddExpression(rhs, lhs, false);
else /* if (rightIsNativeInt) */
return new JSPointerAddExpression(lhs, rhs, false);
} else {
if (Debugger.IsAttached) {
Console.WriteLine("Debugger.Break()");
Console.Error.WriteLine("Debugger.Break()");
// Debugger.Break();
}
}
}
if (result == null)
return new JSUntranslatableExpression(node);
else
return result;
}
protected JSExpression Translate_BinaryOp (ILExpression node, JSBinaryOperator op) {
// Detect attempts to perform pointer arithmetic
if (TypeUtil.IsIgnoredType(node.Arguments[0].ExpectedType) ||
TypeUtil.IsIgnoredType(node.Arguments[1].ExpectedType) ||
TypeUtil.IsIgnoredType(node.Arguments[0].InferredType) ||
TypeUtil.IsIgnoredType(node.Arguments[1].InferredType)
) {
return new JSUntranslatableExpression(node);
}
// Detect attempts to perform pointer arithmetic on a local variable.
// (ldloca produces a reference, not a pointer, so the previous check won't catch this.)
if (
(node.Arguments[0].Code == ILCode.Ldloca) &&
!(op is JSAssignmentOperator)
)
return new JSUntranslatableExpression(node);
// HACK: Auto-casting for pointer arithmetic is undesirable, because ILSpy
// infers incorrect types here
var arePointersInvolved =
TypeUtil.IsPointer(TypeUtil.DereferenceType(node.Arguments[0].ExpectedType)) ||
TypeUtil.IsPointer(TypeUtil.DereferenceType(node.Arguments[0].InferredType)) ||
TypeUtil.IsPointer(TypeUtil.DereferenceType(node.Arguments[1].ExpectedType)) ||
TypeUtil.IsPointer(TypeUtil.DereferenceType(node.Arguments[1].InferredType));
JSExpression lhs, rhs;
AutoCastingState.Push(
!ShouldSuppressAutoCastingForOperator(op) &&
!arePointersInvolved
);
try {
lhs = TranslateNode(node.Arguments[0]);
rhs = TranslateNode(node.Arguments[1]);
} finally {
AutoCastingState.Pop();
}
if (TypeUtil.IsPointer(lhs.GetActualType(TypeSystem)))
arePointersInvolved |= true;
else if (TypeUtil.IsPointer(rhs.GetActualType(TypeSystem)))
arePointersInvolved |= true;
var boeLeft = lhs as JSBinaryOperatorExpression;
if (
(op is JSAssignmentOperator) &&
(boeLeft != null) && !(boeLeft.Operator is JSAssignmentOperator)
)
return new JSUntranslatableExpression(node);
if (arePointersInvolved)
return Translate_BinaryOp_Pointer(node, op, lhs, rhs);
var resultType = node.InferredType ?? node.ExpectedType;
var leftType = lhs.GetActualType(TypeSystem);
var rightType = rhs.GetActualType(TypeSystem);
if (
TypeUtil.IsIntegral(leftType) &&
TypeUtil.IsIntegral(rightType) &&
TypeUtil.IsIntegral(resultType) &&
!(op is JSBitwiseOperator)
) {
// HACK: Compensate for broken ILSpy type inference on certain forms of integer arithmetic
var sizeofLeft = TypeUtil.SizeOfType(leftType);
var sizeofRight = TypeUtil.SizeOfType(rightType);
TypeReference largestType;
if (sizeofLeft > sizeofRight)
largestType = leftType;
else
largestType = rightType;
var sizeofInferred = (node.InferredType != null) && TypeUtil.IsIntegral(node.InferredType)
? TypeUtil.SizeOfType(node.InferredType)
: 0;
var sizeofExpected = (node.ExpectedType != null) && TypeUtil.IsIntegral(node.ExpectedType)
? TypeUtil.SizeOfType(node.ExpectedType)
: 0;
if (TypeUtil.SizeOfType(largestType) > Math.Max(sizeofInferred, sizeofExpected)) {
// FIXME: Get the sign right?
resultType = largestType;
}
}
var result = new JSBinaryOperatorExpression(
op, lhs, rhs, resultType
);
return result;
}
protected JSExpression HandleJSReplacement (
MethodReference method, Internal.MethodInfo methodInfo,
JSExpression thisExpression, JSExpression[] arguments,
TypeReference resultType, bool explicitThis
) {
foreach (var transformer in FunctionTransformers) {
var externalReplacement = transformer.MaybeReplaceMethodCall(
ThisMethodReference,
method, methodInfo,
thisExpression, arguments,
resultType, explicitThis
);
if (externalReplacement != null)
return externalReplacement;
}
var metadata = methodInfo.Metadata;
if (metadata != null) {
var parms = metadata.GetAttributeParameters("JSIL.Meta.JSReplacement");
if (parms != null) {
var argsDict = new Dictionary<string, JSExpression>();
argsDict["assemblyof(executing)"] = new JSReflectionAssembly(ThisMethod.DeclaringType.Module.Assembly);
if (methodInfo.IsStatic) {
argsDict["this"] = new JSNullLiteral(TypeSystem.Object);
argsDict["typeof(this)"] = Translate_TypeOf(methodInfo.DeclaringType.Definition);
argsDict["etypeof(this)"] = Translate_TypeOf(methodInfo.DeclaringType.Definition.GetElementType());
argsDict["declaringType(method)"] = Translate_TypeOf(methodInfo.DeclaringType.Definition);
argsDict["explicitThis(method)"] = new JSBooleanLiteral(false);
}
else if (thisExpression != null)
{
argsDict["this"] = thisExpression;
argsDict["typeof(this)"] = Translate_TypeOf(thisExpression.GetActualType(TypeSystem));
argsDict["etypeof(this)"] = Translate_TypeOf(thisExpression.GetActualType(TypeSystem).GetElementType());
argsDict["this"] = thisExpression;
argsDict["declaringType(method)"] = Translate_TypeOf(methodInfo.DeclaringType.Definition);
argsDict["explicitThis(method)"] = new JSBooleanLiteral(explicitThis);
}
var genericMethod = method as GenericInstanceMethod;
if (genericMethod != null) {
foreach (var kvp in methodInfo.GenericParameterNames.Zip(genericMethod.GenericArguments, (n, p) => new { Name = n, Value = p })) {
argsDict.Add(kvp.Name, new JSTypeOfExpression(kvp.Value));
}
}
foreach (var kvp in methodInfo.Parameters.Zip(arguments, (p, v) => new { p.Name, Value = v })) {
argsDict.Add(kvp.Name, kvp.Value);
var type = kvp.Value.GetActualType(TypeSystem);
argsDict["typeof(" + kvp.Name + ")"] = Translate_TypeOf(type);
var typeSpecification = type as TypeSpecification;
argsDict["etypeof(" + kvp.Name + ")"] = Translate_TypeOf(typeSpecification != null ? typeSpecification.ElementType : type.GetElementType());
}
var isConstantIfArgumentsAre = methodInfo.Metadata.HasAttribute("JSIL.Meta.JSIsPure");
var result = new JSVerbatimLiteral(
method.Name, (string)parms[0].Value, argsDict, resultType, isConstantIfArgumentsAre
);
return PackedArrayUtil.FilterInvocationResult(
method, methodInfo,
result,
TypeInfo, TypeSystem
);
}
}
return null;
}
protected JSExpression Translate_ConstructorReplacement (
MethodReference constructor, Internal.MethodInfo constructorInfo, JSNewExpression newExpression
) {
var instanceType = newExpression.GetActualType(TypeSystem);
var jsr = HandleJSReplacement(
constructor, constructorInfo, new JSNullLiteral(instanceType), newExpression.Arguments.ToArray(),
instanceType, false
);
if (jsr != null)
return jsr;
return newExpression;
}
private JSIndirectVariable MakeIndirectVariable (string name) {
JSIndirectVariable result;
if (!IndirectVariables.TryGetValue(name, out result))
IndirectVariables.Add(name, result = new JSIndirectVariable(Variables, name, ThisMethodReference));
return result;
}
internal JSExpression DoMethodReplacement (
JSMethod method, JSExpression thisExpression,
JSExpression[] arguments, bool @virtual, bool @static, bool explicitThis, bool suppressThisClone
) {
var methodInfo = method.Method;
PackedArrayUtil.CheckInvocationSafety(method.Method, arguments, TypeSystem);
bool retry;
do {
retry = false;
var metadata = methodInfo.Metadata;
if (metadata != null) {
var jsr = HandleJSReplacement(
method.Reference, methodInfo, thisExpression, arguments,
method.Reference.ReturnType, explicitThis
);
if (jsr != null)
return jsr;
// Proxy method bodies can call other methods declared on the proxy
// that are actually stand-ins for methods declared on the proxied type.
if (
metadata.HasAttribute("JSIL.Proxy.JSNeverReplace") &&
!TypeUtil.TypesAreEqual(method.Reference.DeclaringType, methodInfo.DeclaringType.Definition) &&
!methodInfo.DeclaringType.IsProxy
) {
var proxyTypeInfo = TypeInfo.GetExisting(method.Reference.DeclaringType);
if ((proxyTypeInfo != null) && proxyTypeInfo.IsProxy) {
var originalMethod =
(from m in methodInfo.DeclaringType.Definition.Methods
let mi = TypeInfo.GetMethod(m)
where (mi != null) &&
mi.NamedSignature.Equals(methodInfo.NamedSignature)
select m).FirstOrDefault();
if (originalMethod != null) {
methodInfo = TypeInfo.GetMethod(originalMethod);
method = new JSMethod(originalMethod, methodInfo, method.MethodTypes, method.GenericArguments);
retry = true;
}
}
}
}
} while (retry);
if (methodInfo.IsIgnored)
return new JSIgnoredMemberReference(true, methodInfo, new[] { thisExpression }.Concat(arguments).ToArray());
JSExpression result = DoNonJSILMethodReplacement(method, arguments);
if (result != null)
return result;
result = DoJSILMethodReplacement(
method.Method.DeclaringType.FullName,
method.Method.Name,
method,
method.GenericArguments,
arguments
);
if (result != null)
return result;
result = Translate_PropertyCall(thisExpression, method, arguments, @virtual, @static);
if (result == null) {
if (@static)
result = JSInvocationExpression.InvokeStatic(method.Reference.DeclaringType, method, arguments);
else if (explicitThis)
result = JSInvocationExpression.InvokeBaseMethod(method.Reference.DeclaringType, method, thisExpression, arguments);
else
result = JSInvocationExpression.InvokeMethod(method.Reference.DeclaringType, method, thisExpression, arguments, suppressThisClone: suppressThisClone);
}
result = PackedArrayUtil.FilterInvocationResult(
method.Reference, method.Method,
result,
TypeInfo, TypeSystem
);
return result;
}
internal JSExpression DoJSILBuiltinsMethodReplacement (
string methodName,
IEnumerable<TypeReference> genericArguments,
JSExpression[] arguments,
bool forDynamic
) {
switch (methodName) {
case "CreateNamedFunction`1": {
JSExpression closureArg = null;
if (arguments.Length > 3)
closureArg = arguments[3];
return JSIL.CreateNamedFunction(
genericArguments.First(), arguments[0], arguments[1], arguments[2], closureArg
);
}
case "Eval":
return JSInvocationExpression.InvokeStatic(
JS.eval, arguments
);
case "IsTruthy":
return new JSUnaryOperatorExpression(
JSOperator.LogicalNot,
new JSUnaryOperatorExpression(JSOperator.LogicalNot, arguments.First(), TypeSystem.Boolean),
TypeSystem.Boolean
);
case "IsFalsy":
return new JSUnaryOperatorExpression(JSOperator.LogicalNot, arguments.First(), TypeSystem.Boolean);
case "get_This":
return MakeIndirectVariable("this");
case "get_IsJavascript":
return new JSBooleanLiteral(true);
}
return null;
}
internal JSExpression DoJSILMethodReplacement (
string typeName,
string methodName,
JSMethod method,
IEnumerable<TypeReference> genericArguments,
JSExpression[] arguments
) {
switch (typeName) {
case "JSIL.Builtins":
return DoJSILBuiltinsMethodReplacement(methodName, genericArguments, arguments, method == null);
case "JSIL.Verbatim": {
if (
(methodName == "Expression") || methodName.StartsWith("Expression`")
) {
var expression = arguments[0] as JSStringLiteral;
if (expression == null)
throw new InvalidOperationException("JSIL.Verbatim.Expression must recieve a string literal as an argument");
JSExpression commaFirstClause = null;
IDictionary<string, JSExpression> argumentsDict = null;
if (arguments.Length > 1) {
var argumentsExpression = arguments[1];
var argumentsArray = argumentsExpression as JSNewArrayExpression;
if (method == null || method.Method.Parameters[1].ParameterType is GenericParameter) {
// This call was made dynamically or through generic version of method, so the parameters are not an array.
argumentsDict = new Dictionary<string, JSExpression>();
for (var i = 0; i < (arguments.Length - 1); i++)
argumentsDict.Add(String.Format("{0}", i), arguments[i + 1]);
} else if (argumentsArray == null) {
// The array is static so we need to pull elements out of it after assigning it a name.
// FIXME: Only handles up to 40 elements.
var argumentsExpressionType = argumentsExpression.GetActualType(TypeSystem);
var temporaryVariable = MakeTemporaryVariable(argumentsExpressionType);
var temporaryAssignment = new JSBinaryOperatorExpression(JSOperator.Assignment, temporaryVariable, argumentsExpression, argumentsExpressionType);
commaFirstClause = temporaryAssignment;
argumentsDict = new Dictionary<string, JSExpression>();
for (var i = 0; i < 40; i++)
argumentsDict.Add(String.Format("{0}", i), new JSIndexerExpression(temporaryVariable, JSLiteral.New(i)));
} else {
var argumentsArrayExpression = argumentsArray.SizeOrArrayInitializer as JSArrayExpression;
if (argumentsArrayExpression == null)
throw new NotImplementedException("Literal array must have values");
argumentsDict = new Dictionary<string, JSExpression>();
int i = 0;
foreach (var value in argumentsArrayExpression.Values) {
argumentsDict.Add(String.Format("{0}", i), value);
i += 1;
}
}
}
var verbatimLiteral = new JSVerbatimLiteral(
methodName, expression.Value, argumentsDict
);
if (commaFirstClause != null)
return new JSCommaExpression(commaFirstClause, verbatimLiteral);
else
return verbatimLiteral;
} else {
throw new NotImplementedException("Verbatim method not implemented: " + methodName);
}
break;
}
case "JSIL.JSGlobal": {
if (methodName == "get_Item") {
var expression = arguments[0] as JSStringLiteral;
if (expression != null)
return new JSDotExpression(
JSIL.GlobalNamespace, new JSStringIdentifier(expression.Value, TypeSystem.Object, true)
);
else
return new JSIndexerExpression(
JSIL.GlobalNamespace, arguments[0], TypeSystem.Object
);
} else {
throw new NotImplementedException("JSGlobal method not implemented: " + methodName);
}
break;
}
case "JSIL.JSLocal": {
if (methodName == "get_Item") {
var expression = arguments[0] as JSStringLiteral;
if (expression == null)
throw new InvalidOperationException("JSLocal must recieve a string literal as an index");
return new JSStringIdentifier(expression.Value, TypeSystem.Object, true);
} else {
throw new NotImplementedException("JSLocal method not implemented: " + methodName);
}
break;
}
case "JSIL.Services": {
if (methodName == "Get") {
if (arguments.Length != 2)
throw new InvalidOperationException("JSIL.Services.Get must receive two arguments");
var serviceName = arguments[0];
var shouldThrow = arguments[1];
return JSInvocationExpression.InvokeStatic(
new JSRawOutputIdentifier(TypeSystem.Object, "JSIL.Host.getService"),
new[] {
serviceName,
new JSUnaryOperatorExpression(JSOperator.LogicalNot, shouldThrow, TypeSystem.Boolean)
}, true
);
} else {
throw new NotImplementedException("JSIL.Services method not implemented: " + methodName);
}
break;
}
}
return null;
}
internal JSExpression DoNonJSILMethodReplacement (JSMethod method, JSExpression[] arguments) {
switch (method.Method.Member.FullName) {
// Doing this replacement here enables more elimination of temporary variables
case "System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle)":
case "System.Reflection.MethodBase System.Reflection.MethodBase::GetMethodFromHandle(System.RuntimeMethodHandle)":
case "System.Reflection.MethodBase System.Reflection.MethodBase::GetMethodFromHandle(System.RuntimeMethodHandle,System.RuntimeTypeHandle)":
case "System.Reflection.FieldInfo System.Reflection.FieldInfo::GetFieldFromHandle(System.RuntimeFieldHandle)":
case "System.Reflection.FieldInfo System.Reflection.FieldInfo::GetFieldFromHandle(System.RuntimeFieldHandle,System.RuntimeTypeHandle)":
return arguments.First();
}
return null;
}
protected JSExpression Translate_PropertyCall (
JSExpression thisExpression, JSMethod method, JSExpression[] arguments, bool @virtual, bool @static
) {
var propertyInfo = method.Method.DeclaringProperty;
if (propertyInfo == null)
return null;
if (propertyInfo.IsIgnored)
return new JSIgnoredMemberReference(true, propertyInfo, arguments);
// JS provides no way to override [], so keep it as a regular method call
if (propertyInfo.Member.IsIndexer())
return null;
var parms = method.Method.Metadata.GetAttributeParameters("JSIL.Meta.JSReplacement") ??
propertyInfo.Metadata.GetAttributeParameters("JSIL.Meta.JSReplacement");
if (parms != null) {
var argsDict = new Dictionary<string, JSExpression>();
argsDict["this"] = thisExpression;
argsDict["typeof(this)"] = Translate_TypeOf(thisExpression.GetActualType(TypeSystem));
foreach (var kvp in method.Method.Parameters.Zip(arguments, (p, v) => new { p.Name, Value = v })) {
argsDict.Add(kvp.Name, kvp.Value);
}