Exemplo n.º 1
0
        internal HybInstance RunWrappedFunc(HybInstance _this, Func <HybInstance[], HybInstance> func, HybInstance[] args)
        {
            BindThis(_this);
            var ret = func.Invoke(args);

            if (Halt == HaltType.Return)
            {
                Halt = HaltType.None;
            }
            return(ret);
        }
Exemplo n.º 2
0
        public static HybInstance[] Wrap(this object[] _this)
        {
            var objs = new HybInstance[_this.Length];

            for (int i = 0; i < _this.Length; i++)
            {
                objs[i] = HybInstance.Object(_this[i]);
            }

            return(objs);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Runs conditional access expression. (CS6)
        ///   [Syntax] EXPR?.WHEN_NOT_NULL
        /// </summary>
        private HybInstance RunConditionalAccess(ConditionalAccessExpressionSyntax node)
        {
            var left = RunExpression(node.Expression);

            Ctx._bound = left;

            if (left.IsNull() == false)
            {
                return(RunExpression(node.WhenNotNull));
            }
            return(HybInstance.Null());
        }
Exemplo n.º 4
0
 /// <summary>
 /// Invokes given method without any exceptions.
 /// This method actually made for UniScript/SendMessage
 /// </summary>
 public HybInstance InvokeSafe(string name, params object[] args)
 {
     try
     {
         return(Invoke(name, args));
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
     return(HybInstance.Null());
 }
Exemplo n.º 5
0
        private HybInstance RunIs(BinaryExpressionSyntax node)
        {
            var left = RunExpression(node.Left);
            var type = Resolver.GetType($"{node.Right}");

            if (type == null)
            {
                throw new SemanticViolationException($"Unrecognized type: {node.Right}");
            }

            return(left.Is(type) ? HybInstance.Bool(true) : HybInstance.Bool(false));
        }
Exemplo n.º 6
0
 public HybInstance Cast <T>()
 {
     if (IsCompiledType)
     {
         return(HybInstance.Object((T)Convert.ChangeType(Obj, typeof(T))));
     }
     if (Is <T>())
     {
         return(Parent.Cast <T>());
     }
     throw new InvalidCastException($"Cannot be casted to {typeof(T)}");
 }
Exemplo n.º 7
0
 public HybInstance GetDefault()
 {
     if (IsCompiledType)
     {
         if (CompiledType.IsValueType)
         {
             return(HybInstance.Object(Activator.CreateInstance(CompiledType)));
         }
         return(HybInstance.Null());
     }
     return(HybInstance.Null());
 }
Exemplo n.º 8
0
        public static HybInstance PostfixUnary(HybInstance a, string op)
        {
            if (op == "++")
            {
                return(PostfixInc(a));
            }
            if (op == "--")
            {
                return(PostfixDec(a));
            }

            throw new ArgumentException($"Unrecognized operator: '{op}'.");
        }
Exemplo n.º 9
0
 private bool IsDictionaryAddible(HybInstance obj, InitializerExpressionSyntax init)
 {
     if (init.Expressions.Count > 0 &&
         (init.Expressions[0] is AssignmentExpressionSyntax ||
          init.Expressions[0] is InitializerExpressionSyntax))
     {
         if (obj.GetSetIndexerMethod() != null)
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 10
0
        private HybInstance RunObjectCreation(ObjectCreationExpressionSyntax node)
        {
            HybType type = null;

            var args  = new HybInstance[node.ArgumentList.Arguments.Count];
            var count = 0;

            foreach (var arg in node.ArgumentList.Arguments)
            {
                args[count++] = RunExpression(arg.Expression);
            }

            if (node.Type is GenericNameSyntax gn)
            {
                type = Resolver.GetGenericType(
                    $"{gn.Identifier}",
                    gn.TypeArgumentList.Arguments.Count);

                var genericArgs = new HybType[gn.TypeArgumentList.Arguments.Count];
                count = 0;
                foreach (var arg in gn.TypeArgumentList.Arguments)
                {
                    genericArgs[count++] = Resolver.GetType($"{arg}");
                }
                type = type.MakeGenericType(genericArgs);
            }
            else
            {
                type = Resolver.GetType($"{node.Type}");
            }

            if (type.IsCompiledType)
            {
                if (type.CompiledType == typeof(Action))
                {
                    return(args[0]);
                }
                if (type.CompiledType == typeof(Func <int>))
                {
                    return(args[0]);
                }
            }

            var inst = type.CreateInstance(this, args);

            if (node.Initializer != null)
            {
                ProcessInitializer(inst, node.Initializer);
            }
            return(inst);
        }
Exemplo n.º 11
0
        private bool SetValueUpwards(string key, HybInstance value)
        {
            if (Values.ContainsKey(key))
            {
                Values[key] = value;
                return(true);
            }

            if (Parent == null)
            {
                return(false);
            }
            return(Parent.SetValueUpwards(key, value));
        }
Exemplo n.º 12
0
        public static HybInstance And(HybInstance a, HybInstance b)
        {
            if (a.IsCompiledType && b.IsCompiledType)
            {
                if (a.Is <bool>() && b.Is <bool>())
                {
                    return(a.As <bool>() && b.As <bool>() ?
                           HybInstanceCache.True :
                           HybInstanceCache.False);
                }
            }

            throw new NotImplementedException();
        }
Exemplo n.º 13
0
        private void ActionBody(SeparatedSyntaxList <ParameterSyntax> ps, BlockSyntax body, params object[] args)
        {
            var vf = new VarFrame(Vars);

            for (int i = 0; i < ps.Count; i++)
            {
                vf.SetValue($"{ps[i].Identifier}", HybInstance.Object(args[i]));
            }
            RunBlock(body as BlockSyntax, vf);
            if (Halt == HaltType.Return)
            {
                Halt = HaltType.None;
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Process trailing object's initializer.
 ///
 /// new Object() {
 ///     foo = "bar",
 ///     zoo = 5,
 /// };
 /// </summary>
 private void ProcessInitializer(HybInstance inst, InitializerExpressionSyntax init)
 {
     if (IsDictionaryAddible(inst, init))
     {
         ProcessDictionaryInitializer(inst, init);
     }
     else if (IsArrayAddible(inst))
     {
         ProcessArrayInitializer(inst, init);
     }
     else
     {
         ProcessObjectInitializer(inst, init);
     }
 }
Exemplo n.º 15
0
        private HybInstance CreateInstanceInterpretType(Runner runner, HybInstance[] args,
                                                        object parentObject = null)
        {
            var inst  = new HybInstance(runner, this, InterpretKlass, parentObject);
            var ctors = GetMethods("$_ctor");

            if (ctors.Length > 0)
            {
                var ctor = OverloadingResolver
                           .FindMethodWithArguments(runner.Resolver, ctors, new HybType[] { }, ref args);
                ctor.Target.Invoke(inst, args);
            }

            return(inst);
        }
Exemplo n.º 16
0
        public override HybInstance GetValue(HybInstance _this)
        {
            if (IsStatic)
            {
                return(DeclaringClass.Runner.Globals
                       .GetStaticField(DeclaringClass, Id));
            }

            // it's fast enough to do like this
            if (FieldPtr == -1)
            {
                FieldPtr = _this.Fields.GetPtr(Id);
            }
            return(_this.Fields.GetByPtr(FieldPtr));
        }
Exemplo n.º 17
0
        public HybInstance Cast(HybType type)
        {
            if (IsCompiledType)
            {
                if (type.IsCompiledType)
                {
                    var casted = Convert.ChangeType(Obj, type.CompiledType);
                    return(HybInstance.Object(casted));
                }
                throw new InvalidCastException(
                          $"{Obj} cannot be casted to {type.InterpretKlass.Id}");
            }

            throw new NotImplementedException();
        }
Exemplo n.º 18
0
        public HybInstance Eval(string src)
        {
            var         root = ParseAndValidate(src, isScript: true);
            HybInstance ret  = null;

            foreach (var child in root.ChildNodes())
            {
                if (child is GlobalStatementSyntax gstmt)
                {
                    ret = Runner.RunScriptStatement(gstmt.Statement);
                }
            }
            return(ret);
            //throw new ArgumentException("src is not a expression");
        }
Exemplo n.º 19
0
        public override void SetValue(HybInstance _this, HybInstance value)
        {
            if (IsStatic)
            {
                DeclaringClass.Runner.Globals
                .SetStaticField(DeclaringClass, Id, value);
                return;
            }

            // it's fast enough to do like this
            if (FieldPtr == -1)
            {
                FieldPtr = _this.Fields.GetPtr(Id);
            }
            _this.Fields.SetByPtr(FieldPtr, value);
        }
Exemplo n.º 20
0
        public bool TryGetValue(string key, out HybInstance value)
        {
            if (Values.ContainsKey(key))
            {
                value = Values[key];
                return(true);
            }

            if (Parent == null)
            {
                value = null;
                return(false);
            }

            return(Parent.TryGetValue(key, out value));
        }
Exemplo n.º 21
0
        private void RunAssign(ExpressionSyntax leftNode, HybInstance right)
        {
            if (leftNode is IdentifierNameSyntax id)
            {
                var key = id.Identifier.ValueText;
                UpdateVariable(key, right);
            }
            else if (leftNode is MemberAccessExpressionSyntax ma)
            {
                if (ma.Expression is IdentifierNameSyntax idNode)
                {
                    var     key = $"{idNode.Identifier}";
                    HybType leftType;
                    if (Resolver.TryGetType(key, out leftType))
                    {
                        leftType.SetStaticPropertyOrField($"{ma.Name.Identifier}", right);
                        return;
                    }
                }

                var left        = RunExpression(ma.Expression);
                var accessLevel = AccessLevel.Outside;

                if (ma.Expression is ThisExpressionSyntax)
                {
                    accessLevel = AccessLevel.This;
                }

                left.SetPropertyOrField($"{ma.Name}", right, accessLevel);
            }
            else if (leftNode is ElementAccessExpressionSyntax ea)
            {
                var callee = RunExpression(ea.Expression);
                var args   = new HybInstance[ea.ArgumentList.Arguments.Count];

                var count = 0;
                foreach (var arg in ea.ArgumentList.Arguments)
                {
                    args[count++] = RunExpression(arg.Expression);
                }

                if (callee.SetIndexer(args, right) == false)
                {
                    throw new NoSuchMemberException("[]");
                }
            }
        }
Exemplo n.º 22
0
        private HybInstance ResolveLiteral(LiteralExpressionSyntax node)
        {
            var cache = OptCache.GetOrCreate(node, () => {
                var optNode = new OptLiteralNode();

                if (node.Token.Value == null)
                {
                    optNode.value = HybInstance.Null();
                }
                else if (node.Token.Value is char c)
                {
                    optNode.value = HybInstance.Char(c);
                }
                else if (node.Token.Value is string str)
                {
                    optNode.value = HybInstance.String(str);
                }
                else if (node.Token.Value is bool b)
                {
                    optNode.value = HybInstance.Bool(b);
                }
                else if (node.Token.Value is int i)
                {
                    if (int.TryParse(node.Token.Text, out _) == false)
                    {
                        throw new SemanticViolationException($"Integer literal out of range");
                    }
                    optNode.value = HybInstance.Int(i);
                }
                else if (node.Token.Value is float f)
                {
                    optNode.value = HybInstance.Float(f);
                }
                else if (node.Token.Value is double d)
                {
                    optNode.value = HybInstance.Double(d);
                }
                else
                {
                    throw new InvalidOperationException();
                }

                return(optNode);
            });

            return(cache.value);
        }
Exemplo n.º 23
0
        private HybInstance ResolveId(IdentifierNameSyntax node)
        {
            if (string.IsNullOrEmpty(node.Identifier.Text))
            {
                throw new SemanticViolationException($"Invalid syntax: {node.Parent}");
            }

            var         id = $"{node.Identifier}";
            HybInstance v  = null;

            if (Vars.TryGetValue(id, out v))
            {
                return(v);
            }

            if (Ctx._this != null)
            {
                if (Ctx._this.GetPropertyOrField(id, out v, AccessLevel.This))
                {
                    return(v);
                }
            }

            if (Ctx.Method.DeclaringType.GetStaticPropertyOrField(id, out v))
            {
                return(v);
            }

            /*
             * Class klass = ctx.method.declaringClass;
             * SSFieldInfo field;
             * if (klass.TryGetField(id, out field))
             * {
             *  if (field.isStatic)
             *      return globals.GetStaticField(klass, id);
             * }
             * SSPropertyInfo property;
             * if (klass.TryGetProperty(id, out property))
             * {
             *  if (property.isStatic)
             *      return property.getMethod.Invoke(null, new HybInstance[] { });
             * }
             */
            //if (field.)

            throw new NoSuchMemberException($"{id}");
        }
Exemplo n.º 24
0
        public HybInstance Invoke(HybInstance _this, HybInstance[] args, bool hasRefOrOut = false)
        {
            if (IsCompiled)
            {
                Console.WriteLine($"Invoke {CompiledMethod.Name}");
            }
            else
            {
                Console.WriteLine($"Invoke ");
            }

            if (Type == InvokeType.ReflectionInvoke)
            {
                if (CompiledMethod.GetParameters().Length > args.Length)
                {
                    args = ExpandArgs(args, CompiledMethod);
                }

                var unwrappedArgs = args.Unwrap();
                var ret           = CompiledMethod.Invoke(_this?.InnerObject, unwrappedArgs);

                if (hasRefOrOut)
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        args[i] = HybInstance.Object(unwrappedArgs[i]);
                    }
                }

                return(HybInstance.Object(ret));
            }
            else if (Type == InvokeType.FuncInvoke)
            {
                return(Runner.RunWrappedFunc(_this, FuncMethod, args));
            }
            else if (Type == InvokeType.Interpret)
            {
                var ps = InterpretMethod.ParameterList.Parameters;
                //if (args.Length != ps.Count)
                //throw new SemanticViolationException($"Parameters.Count does not match");

                return(Runner.RunMethod(
                           _this as HybInstance, MethodInfo, args));
            }

            throw new NotImplementedException($"Unknown type: {Type}");
        }
Exemplo n.º 25
0
        private HybInstance RunArrayCreation(ArrayCreationExpressionSyntax node)
        {
            var rtAry = Resolver.GetType($"{node.Type.ElementType}");

            Array ary = null;
            Type  elemType;

            if (rtAry.IsCompiledType)
            {
                elemType = rtAry.CompiledType;
            }
            else
            {
                elemType = typeof(HybInstance);
            }

            if (node.Initializer != null)
            {
                ary = Array.CreateInstance(
                    elemType, node.Initializer.Expressions.Count);

                var count = 0;
                foreach (var expr in node.Initializer.Expressions)
                {
                    var value = RunExpression(expr);

                    if (rtAry.IsCompiledType)
                    {
                        ary.SetValue(value.InnerObject, count++);
                    }
                    else
                    {
                        ary.SetValue(value, count++);
                    }
                }
            }
            else
            {
                var ranks = node.Type.RankSpecifiers
                            .SelectMany(x => x.Sizes)
                            .Select(x => RunExpression(x).As <int>())
                            .ToArray();
                ary = Array.CreateInstance(elemType, ranks);
            }

            return(HybInstance.Object(ary));
        }
Exemplo n.º 26
0
        public static HybInstance PrefixUnary(HybInstance a, string op)
        {
            if (op == "!")
            {
                return(PrefixNot(a));
            }
            if (op == "-")
            {
                return(PrefixMinus(a));
            }
            if (op == "+")
            {
                return(PrefixPlus(a));
            }

            throw new ArgumentException($"Unrecognized operator: '{op}'.");
        }
Exemplo n.º 27
0
        private (HybInstance[], bool) ResolveArgumentList(ArgumentListSyntax node)
        {
            var args        = new HybInstance[node.Arguments.Count];
            var hasRefOrOut = false;

            for (int i = 0; i < node.Arguments.Count; i++)
            {
                var refOrOut = node.Arguments[i].RefKindKeyword.Text ?? "";
                if (refOrOut == "ref" || refOrOut == "out")
                {
                    hasRefOrOut = true;
                }
                args[i] = RunExpression(node.Arguments[i].Expression);
            }

            return(args, hasRefOrOut);
        }
Exemplo n.º 28
0
        public static HybInstance PrefixMinus(HybInstance a)
        {
            if (a.IsCompiledType)
            {
                if (a.GetHybType().IsValueType)
                {
                    if (a.Is <Decimal>())
                    {
                        return(HybInstance.Decimal(-a.As <Decimal>()));
                    }
                    if (a.Is <Double>())
                    {
                        return(HybInstance.Double(-a.As <Double>()));
                    }
                    if (a.Is <Single>())
                    {
                        return(HybInstance.Float(-a.As <Single>()));
                    }
                    if (a.Is <Int64>())
                    {
                        return(HybInstance.Int64(-a.As <Int64>()));
                    }
                    if (a.Is <Int32>())
                    {
                        return(HybInstance.Int(-a.As <Int32>()));
                    }
                    if (a.Is <short>())
                    {
                        return(HybInstance.Short(-a.As <short>()));
                    }
                    if (a.Is <sbyte>())
                    {
                        return(HybInstance.Byte(-a.As <sbyte>()));
                    }
                }
            }

            var negationMethod = GetUnaryNegationMethod(a);

            if (negationMethod != null)
            {
                return(negationMethod.Target.Invoke(null, new HybInstance[] { a }));
            }

            throw new NotImplementedException();
        }
Exemplo n.º 29
0
 private void InitializeFields()
 {
     foreach (var field in Klass.GetFields()
              .Where(x => x.IsStatic == false)
              .OfType <SSInterpretFieldInfo>())
     {
         if (field.declartor == null || field.declartor.Initializer == null)
         {
             Fields.Add(field.Id,
                        HybInstance.Object(field.fieldType.GetDefault()));
         }
         else
         {
             Fields.Add(field.Id,
                        Runner.RunExpression(field.declartor.Initializer.Value));
         }
     }
 }
Exemplo n.º 30
0
        /// <summary>
        /// Runs interpolated string expression.
        ///   [Syntax] $"My name is {VALUE}"
        /// </summary>
        private HybInstance RunInterpolatedString(InterpolatedStringExpressionSyntax node)
        {
            var sb = new StringBuilder();

            foreach (var content in node.Contents)
            {
                if (content is InterpolationSyntax s)
                {
                    sb.Append(RunExpression(s.Expression));
                }
                else if (content is InterpolatedStringTextSyntax)
                {
                    sb.Append(content.GetText());
                }
            }

            return(HybInstance.String(sb.ToString()));
        }