Example #1
0
        public IValue As(CilType cilType)
        {
            if (cilType is CilTypeValueType cilTypeValueType)
            {
                return(this);
            }

            throw new System.NotImplementedException();
        }
Example #2
0
        public object AsRuntime(CilType cilType, CilManagedMemory managedMemory, CilProgram program)
        {
            if (cilType is CilTypeUInt32)
            {
                return(Value);
            }

            throw new System.NotImplementedException();
        }
Example #3
0
        public CilArray(CilType type, int numElems, CilProgram program)
        {
            _array = new IValue[numElems];
            for (int i = 0; i < numElems; i++)
            {
                _array[i] = type.CreateDefaultValue(program);
            }

            _type = type;
        }
Example #4
0
 private Dictionary <string, string> GetVtable(CilType type)
 {
     return(type
            .ReflectionType
            .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)
            .Where(m => m.IsVirtual)
            .ToDictionary(
                m => GetVirtualMethodIdentifier(m),
                m => GetUnboundMethodAccessor(m).ToString())
            );
 }
Example #5
0
        public override object AsRuntime(CilType type, CilManagedMemory managedMemory, CilProgram program)
        {
            if (type is CilTypeArray cilTypeArray)
            {
                var result    = Array.CreateInstance(cilTypeArray.ElementType.GetRuntimeType(program), Length);
                var objectArr = _array.Select(elem => elem.AsRuntime(cilTypeArray.ElementType, managedMemory, program)).ToArray();
                Array.Copy(objectArr, result, Length);
                return(result);
            }

            throw new System.NotImplementedException();
        }
Example #6
0
        private JSExpression GetMethods(CilType type)
        {
            var ms = type.ReflectionType.GetMethods(
                BindingFlags.DeclaredOnly |
                BindingFlags.Public | //BindingFlags.NonPublic |
                BindingFlags.Instance // | BindingFlags.Static
                );

            return(JSFactory.Array(
                       ms.Select(m => GetMethodInfo(type, m)).ToArray()
                       ));
        }
Example #7
0
 protected string GetTranslatedFieldName(CilType type, FieldInfo f)
 {
     if (f.IsStatic == false && f.IsPrivate && f.DeclaringType.IsValueType == false)
     {
         var ns = (f.DeclaringType.Namespace ?? "").Replace('.', '_');
         return(ns + GetSimpleName(f.DeclaringType) + f.Name);
     }
     else
     {
         return(f.Name);
     }
 }
Example #8
0
        public IValue As(CilType cilType)
        {
            if (cilType is CilTypeInt16)
            {
                return(this);
            }
            else if (cilType is CilTypeUInt16)
            {
                return(new CilValueUInt16((ushort)Value));
            }

            throw new System.NotImplementedException();
        }
Example #9
0
        public IValue As(CilType cilType)
        {
            if (cilType is CilTypeInt8)
            {
                return(this);
            }
            if (cilType is CilTypeUInt8)
            {
                return(new CilValueUInt8((byte)Value));
            }

            throw new System.NotImplementedException();
        }
Example #10
0
        public override object AsRuntime(CilType type, CilManagedMemory managedMemory, CilProgram program)
        {
            if (type is CilTypeObject)
            {
                return(ExternalObject);
            }

            if (type.GetRuntimeType(program).IsAssignableFrom(ExternalObject.GetType()))
            {
                return(ExternalObject);
            }

            throw new NotImplementedException();
        }
Example #11
0
 private CilMethod ProcessMethod(CilType type, MethodBase method)
 {
     return(new CilMethod
     {
         Name = method.Name,
         ReflectionMethod = method,
         IsHideBySig = method.IsHideBySig,
         IsVirtual = method.IsVirtual,
         MethodBody = method.GetMethodBody(),
         MetadataToken = method.MetadataToken,
         Resolver = new ModuleILResolver(method),
         DeclaringType = type
     });
 }
Example #12
0
        public static ArrayType Instance(CilType type)
        {
            if (type == null)
            {
                return(ReferenceType);
            }
            if (ArrayMap.ContainsKey(type))
            {
                return(ArrayMap[type]);
            }
            var result = new ArrayType(type);

            ArrayMap.Add(type, result);
            return(result);
        }
Example #13
0
        private JSExpression GetMethodInfo(CilType type, MethodInfo m)
        {
            var parts = new List <JSExpression>
            {
                GetAssemblyIdentifier(type.ReflectionType),
                JSFactory.Literal(GetMethodIdentifier(m)),
                JSFactory.Literal(m.Name)
            };

            if (m.CustomAttributes.Any())
            {
                parts.Add(GetAttributes(type.ReflectionType, m));
            }

            return(JSFactory.Array(true, parts.ToArray()));
        }
Example #14
0
        public IValue As(CilType cilType)
        {
            if (cilType is CilTypeString)
            {
                return(this);
            }
            if (cilType is CilTypeClass)
            {
                return(this);
            }
            if (cilType is CilTypeArray)
            {
                return(this);
            }

            throw new System.NotImplementedException();
        }
Example #15
0
        public object AsRuntime(CilType cilType, CilManagedMemory managedMemory, CilProgram program)
        {
            if (cilType is CilTypeChar)
            {
                return((char)Value);
            }
            if (cilType is CilTypeInt16)
            {
                return(Value);
            }
            if (cilType is CilTypeUInt16)
            {
                return((ushort)Value);
            }
            if (cilType is CilTypeValueType)
            {
                return(Value);
            }

            throw new System.NotImplementedException();
        }
Example #16
0
        public BoxedType(CilType fromType, bool isLocal)
        {
            if (fromType is BoxedType)
            {
                throw CilMain.Where.Exception("already boxed");
            }

            IsLocal     = isLocal;
            UnboxedType = fromType;

            if (fromType.IsReference)
            {
                ClassName = "system.Reference";
            }
            else
            {
                ClassName = fromType.JavaName;  // e.g., system.Int32
            }
            JavaName = ClassName;

            SetBoxedFlags(isLocal);
        }
Example #17
0
        private List <JSStatement> GetPrototype(CilType type)
        {
            var baseType = type.ReflectionType.BaseType;

            var shouldHaveBasePrototype =
                baseType != null &&
                baseType.FullName != "System.MulticastDelegate" &&
                baseType.FullName != "System.ValueType";

            JSExpression basePrototype;
            var          body = new List <JSStatement>();

            if (shouldHaveBasePrototype)
            {
                basePrototype = new JSNewExpression
                {
                    Constructor = GetTypeIdentifier(baseType, typeScope: type.ReflectionType)
                };

                if (baseType.IsGenericType)
                {
                    body.AddRange(baseType
                                  .GetGenericArguments()
                                  .Where(g => g.IsGenericParameter == false)
                                  .Select(g => GetTypeIdentifier(g, typeScope: type.ReflectionType))
                                  .Select(g => JSFactory.Call(JSFactory.Identifier(g, "init")).ToStatement()));
                }
            }
            else
            {
                basePrototype = new JSObjectLiteral();
            }

            body.Add(new JSReturnExpression {
                Expression = basePrototype
            }.ToStatement());
            return(body);
        }
Example #18
0
        private KeyValuePair <string, JSExpression> GetFieldInitializer(FieldInfo f, CilType type)
        {
            if (regex.IsMatch(f.FieldType.Name))
            {
                var size  = int.Parse(regex.Match(f.FieldType.Name).Groups[1].Value);
                var array = new byte[size];
                f.__GetDataFromRVA(array, 0, size);

                return(new KeyValuePair <string, JSExpression>(
                           GetTranslatedFieldName(type, f),
                           new JSArrayLiteral {
                    Inline = true, Values = array.Select(b => new JSNumberLiteral {
                        Value = b
                    })
                }));
            }
            else
            {
                return(new KeyValuePair <string, JSExpression>(
                           GetTranslatedFieldName(type, f),
                           GetDefaultValue(f.FieldType, typeScope: type.ReflectionType)));
            }
        }
Example #19
0
 private object GetRuntimeThis(CilClassInstance classInstance, CilType type)
 {
     return(classInstance?.AsRuntime(type, ManagedMemory, _program));
 }
Example #20
0
        public JSFunctionDelcaration GetFirstCallInitializer(CilAssembly assembly, CilType type, CilMethod method)
        {
            if (type.IsIgnored)
            {
                throw new ArgumentException("cannot translate method of ignored class");
            }

            if (!method.NeedInitializer)
            {
                throw new ArgumentException("method need no initialization");
            }

            var functionBlock = new List <JSStatement>();

            JSExpression closedMethodInitializer;
            JSExpression openMethodInitializer = JSFactory.Identifier("asm", GetMethodIdentifier(method.ReflectionMethod) + "_init");

            if (HasGenericParameters(method))
            {
                closedMethodInitializer = new JSCallExpression
                {
                    Function  = openMethodInitializer,
                    Arguments = GetGenericParameterList(method.ReflectionMethod)
                                .Select(t => JSFactory.Identifier(t.Name))
                                .ToList()
                };
            }
            else
            {
                closedMethodInitializer = openMethodInitializer;
            }

            functionBlock.Add(
                new JSCallExpression
            {
                Function  = JSFactory.Identifier(closedMethodInitializer, "apply"),
                Arguments = { JSFactory.Identifier("this"), JSFactory.Identifier("arguments") }
            }.ToStatement());

            JSExpression openMethodImplementation = JSFactory.Identifier("asm", GetMethodIdentifier(method.ReflectionMethod) + "_");
            JSExpression closedMethodImplementation;

            if (HasGenericParameters(method))
            {
                closedMethodImplementation = new JSCallExpression
                {
                    Function  = openMethodImplementation,
                    Arguments = GetGenericParameterList(method.ReflectionMethod)
                                .Select(t => JSFactory.Identifier(t.Name))
                                .ToList()
                };
            }
            else
            {
                closedMethodImplementation = openMethodImplementation;
            }

            functionBlock.Add(
                new JSReturnExpression
            {
                Expression = new JSCallExpression
                {
                    Function  = JSFactory.Identifier(closedMethodImplementation, "apply"),
                    Arguments = { JSFactory.Identifier("this"), JSFactory.Identifier("arguments") }
                }
            }.ToStatement());

            var ps = GetParameterCount(method);

            var f = new JSFunctionDelcaration
            {
                Body       = functionBlock,
                Parameters = Enumerable.Range(0, ps).Select(i => new JSFunctionParameter {
                    Name = "arg" + i
                }).ToList()
            };

            return(HasGenericParameters(method) ? CreateGenericFunction(method, f) : f);
        }
Example #21
0
        private JSFunctionDelcaration TranslateNormalMethod(CilAssembly asm, CilType type, CilMethod method)
        {
            var functionBlock = new List <JSStatement>();

            if (method.Name == ".cctor")
            {
                var type_id  = GetTypeIdentifier(type.ReflectionType, method.ReflectionMethod);
                var has_init = JSFactory.Identifier(type_id, "FieldsInitialized");

                functionBlock.Add(
                    new JSIfStatement
                {
                    Condition  = has_init,
                    Statements =
                    {
                        new JSReturnExpression().ToStatement()
                    }
                });

                functionBlock.Add(
                    JSFactory
                    .Assignment(has_init, JSFactory.Literal(true))
                    .ToStatement());
            }

            var thisScope = GetThisScope(method.ReflectionMethod, method.ReflectionMethod.DeclaringType);

            if (method.ReferencedTypes != null)
            {
                var tIdx         = 0;
                var typesInScope = new List <Type>();
                foreach (var t in method.ReferencedTypes)
                {
                    functionBlock.Add(
                        new JSVariableDelcaration
                    {
                        Name  = "t" + tIdx,
                        Value = GetTypeIdentifier(t, method.ReflectionMethod, method.ReflectionMethod.DeclaringType, thisScope, typesInScope)
                    }
                        .ToStatement());

                    typesInScope.Add(t);

                    tIdx++;
                }
            }

            if (method.MethodBody.InitLocals)
            {
                var locIdx = 0;

                foreach (var loc in method.MethodBody.LocalVariables)
                {
                    if (method.Locals[locIdx].NeedInit)
                    {
                        functionBlock.Add(
                            new JSExpressionStatement
                        {
                            Expression = new JSVariableDelcaration
                            {
                                Name  = "loc" + locIdx,
                                Value = GetDefaultValue(loc.LocalType, methodScope: method.ReflectionMethod, typeScope: method.ReflectionMethod.DeclaringType, thisScope: thisScope)
                            }
                        });
                    }

                    locIdx++;
                }
            }

            functionBlock.AddRange(
                method
                .Block
                .GetExpressions()
                .Where(o => o.StoreLocations != null)
                .SelectMany(o => o.StoreLocations)
                .Select(l => l.Name)
                .Distinct()
                .OrderBy(n => n)
                .Select(
                    n => new JSExpressionStatement
            {
                Expression = new JSVariableDelcaration
                {
                    Name = n
                }
            }));

            var blockTranslator = new BlockTranslator(context, asm, type, method, thisScope);

            functionBlock.AddRange(
                blockTranslator
                .Translate(method.Block)
                .Where(s => !(s is JSSwitchCase) && !((s is JSExpressionStatement) && (
                                                          ((JSExpressionStatement)s).Expression is JSBreakExpression)))
                .StartWith(
                    new JSVariableDelcaration {
                Name = "__pos__", Value = JSFactory.Hex(0)
            }
                    .ToStatement()));

            var ps = GetParameterCount(method);

            var function = new JSFunctionDelcaration
            {
                Body       = functionBlock,
                Name       = GetSimpleName(method.ReflectionMethod),
                Parameters = Enumerable.Range(0, ps).Select(i => new JSFunctionParameter {
                    Name = "arg" + i
                }).ToList()
            };

            return
                (HasGenericParameters(method) ?
                 CreateGenericFunction(method, function) :
                 function);
        }
Example #22
0
        public JSFunctionDelcaration GetInitializer(CilAssembly assembly, CilType type, CilMethod method)
        {
            if (type.IsIgnored)
            {
                throw new ArgumentException("cannot translate method of ignored class");
            }

            if (method.NeedInitializer == false)
            {
                return(null);
            }

            var functionBlock = new List <JSStatement>();

            var thisScope = GetThisScope(method.ReflectionMethod, method.ReflectionMethod.DeclaringType);

            foreach (var t in method.ReferencedTypes)
            {
                if (t.IsGenericParameter) // types shall be initialized before they are used as generic parameters
                {
                    continue;
                }

                functionBlock.Add(
                    new JSCallExpression
                {
                    Function = JSFactory.Identifier(GetTypeIdentifier(t, method.ReflectionMethod, method.ReflectionMethod.DeclaringType, thisScope), "init")
                }
                    .ToStatement());
            }

            bool mustInitialize = false;

            if (method.DeclaringType.ReflectionType.IsGenericTypeDefinition && method.ReflectionMethod.IsConstructor)
            {
                mustInitialize = true;
            }

            else if (HasGenericParameters(method) || type.ReflectionType.IsGenericType)
            {
                var args = GetGenericParameterList(method.ReflectionMethod)
                           .Concat(type.ReflectionType.GetGenericArguments())
                           .ToList()
                ;

                mustInitialize = method
                                 .ReferencedTypes
                                 .Where(r => r.IsGenericType || r.IsArray)
                                 .Any(r => r
                                      .GetGenericArguments()
                                      .Intersect(args)
                                      .Any() ||
                                      (r.IsArray && args.Contains(r.GetElementType())));
            }

            // We need to always call the initializer for
            //  1. constructors of generic types, since we have no type arguments
            //  2. any method with generic arguments which are used in the initializer
            //
            // TODO: we should inline the initialization for those cases.

            if (!mustInitialize)
            {
                functionBlock.Add(
                    JSFactory
                    .Assignment(
                        JSFactory.Identifier("asm", GetMethodIdentifier(method.ReflectionMethod)),
                        JSFactory.Identifier("asm", GetMethodIdentifier(method.ReflectionMethod) + "_"))
                    .ToStatement());
            }

            var f = new JSFunctionDelcaration
            {
                Body = functionBlock
            };

            return(HasGenericParameters(method) ? CreateGenericFunction(method, f) : f);
        }
Example #23
0
        public IEnumerable <JSStatement> GetInitialization(string n, CilType type)
        {
            yield return(JSFactory
                         .Assignment(
                             JSFactory.Identifier(n, "init"),
                             JSFactory.Identifier("BLR", "nop"))
                         .ToStatement());

            yield return(JSFactory
                         .Call(
                             JSFactory.Identifier("BLR", "init_type"),

                             JSFactory.Identifier(n),
                             JSFactory.Identifier("asm"),
                             JSFactory.String(type.ReflectionType.FullName),

                             new JSBoolLiteral {
                Value = type.ReflectionType.IsValueType
            },
                             new JSBoolLiteral {
                Value = type.ReflectionType.IsPrimitive
            },
                             new JSBoolLiteral {
                Value = type.ReflectionType.IsInterface
            },
                             new JSBoolLiteral {
                Value = type.ReflectionType.IsGenericTypeDefinition
            },
                             new JSBoolLiteral {
                Value = type.ReflectionType.FullName.StartsWith("System.Nullable")
            },

                             GetAttributes(type.ReflectionType, type.ReflectionType),
                             GetMethods(type),
                             GetBaseType(type),
                             GetIsInst(type),
                             GetArrayType(type),
                             JSFactory.Literal(GetTypeMetadataName(type.ReflectionType))
                             )
                         .ToStatement());

            var staticProperties = GetStaticFieldInitializers(type);

            foreach (var p in staticProperties)
            {
                yield return(JSFactory
                             .Assignment(
                                 JSFactory.Identifier(n, p.Key),
                                 p.Value)
                             .ToStatement());
            }

            for (var current = type.ReflectionType; current != null; current = current.BaseType)
            {
                var genericArguments = GetGenericArgumentsArray(current, type.ReflectionType);
                if (genericArguments != null && genericArguments.Values.Any())
                {
                    yield return(JSFactory
                                 .Assignment(
                                     JSFactory.Identifier(n, "GenericArguments", GetTypeMetadataName(current)),
                                     genericArguments)
                                 .ToStatement());
                }
            }

            yield return(JSFactory
                         .Assignment(
                             JSFactory.Identifier(n, "GenericTypeMetadataName"),
                             GetGenericTypeMetadataName(type.ReflectionType))
                         .ToStatement());

            foreach (var f in GetVtable(type))
            {
                yield return(JSFactory.Call(
                                 JSFactory.Identifier("BLR", "declare_virtual"),
                                 JSFactory.Identifier(n),
                                 JSFactory.Literal(f.Key),
                                 JSFactory.Literal(f.Value))
                             .ToStatement());
            }

            foreach (var iface in GetInterfaceMaps(type))
            {
                var call = JSFactory
                           .Call(
                    JSFactory.Identifier("BLR", "implement_interface"),
                    JSFactory.Identifier(n),
                    JSFactory.Array(inline: true, exprs: iface.Key),
                    iface.Value);

                call.Indent = true;

                yield return(call.ToStatement());
            }

            var prototypeProperties = GetFieldInitializers(type)
                                      .Concat(GetPrototypeMethods(type));

            foreach (var f in prototypeProperties)
            {
                yield return(JSFactory
                             .Assignment(
                                 JSFactory.Identifier(n, "prototype", f.Key),
                                 f.Value)
                             .ToStatement());
            }
        }
Example #24
0
 public ThreadBoxedType(CilType fromType)
     : base(fromType, false)
 {
     OldClassName = ClassName;
     ClassName    = JavaName = "system.threading.ThreadLocal";
 }
Example #25
0
 public object AsRuntime(CilType cilType, CilManagedMemory managedMemory, CilProgram program)
 {
     throw new NotImplementedException();
 }
Example #26
0
 private IEnumerable <KeyValuePair <JSExpression[], JSExpression> > GetInterfaceMaps(CilType type)
 {
     return(type.ReflectionType
            .GetInterfaces()
            .Select(
                iface => new KeyValuePair <JSExpression[], JSExpression>(
                    new[] { GetTypeIdentifier(iface, typeScope: type.ReflectionType) }
                    .Concat(
                        iface.GenericTypeArguments.Select(
                            g => GetTypeIdentifier(g, typeScope: type.ReflectionType)))
                    .ToArray(),
                    type.ReflectionType.IsInterface
                            ? JSFactory.Null()
                            : GetInterfaceMap(type, iface))));
 }
Example #27
0
        private JSExpression GetArrayType(CilType type)
        {
            if (type.ReflectionType.FullName == "System.Byte")
            {
                return new JSIdentifier {
                           Name = "Uint8Array"
                }
            }
            ;

            if (type.ReflectionType.FullName == "System.SByte")
            {
                return new JSIdentifier {
                           Name = "Int8Array"
                }
            }
            ;

            if (type.ReflectionType.FullName == "System.Int16")
            {
                return new JSIdentifier {
                           Name = "Int16Array"
                }
            }
            ;

            if (type.ReflectionType.FullName == "System.UInt16")
            {
                return new JSIdentifier {
                           Name = "Uint16Array"
                }
            }
            ;

            if (type.ReflectionType.FullName == "System.Int32")
            {
                return new JSIdentifier {
                           Name = "Int32Array"
                }
            }
            ;

            if (type.ReflectionType.FullName == "System.UInt32")
            {
                return new JSIdentifier {
                           Name = "Uint32Array"
                }
            }
            ;

            if (type.ReflectionType.FullName == "System.Single")
            {
                return new JSIdentifier {
                           Name = "Float32Array"
                }
            }
            ;

            if (type.ReflectionType.FullName == "System.Double")
            {
                return new JSIdentifier {
                           Name = "Float64Array"
                }
            }
            ;

            if (type.ReflectionType.FullName == "System.Char")
            {
                return new JSIdentifier {
                           Name = "Uint16Array"
                }
            }
            ;

            return(new JSIdentifier {
                Name = "Array"
            });
        }
Example #28
0
 private IEnumerable <KeyValuePair <string, JSExpression> > GetStaticFieldInitializers(CilType type)
 {
     return(type
            .ReflectionType
            .GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
            .Select(
                f => GetFieldInitializer(f, type)));
 }
Example #29
0
 public IValue As(CilType cilType)
 {
     throw new System.NotImplementedException();
 }
Example #30
0
        private IEnumerable <KeyValuePair <string, JSExpression> > GetPrototypeMethods(CilType type)
        {
            foreach (var m in type.Methods)
            {
                if (m.IsPrototypeAccessible == false)
                {
                    continue;
                }

                if (m.IsVirtual || type.IsInterface)
                {
                    throw new NotSupportedException("Interface or virtual methods cannot be accessible from prototype");
                }

                yield return(new KeyValuePair <string, JSExpression>(m.Name, GetMethodAccessor(m.ReflectionMethod)));
            }
        }