protected object EvaluateFast(ScriptThread thread)
 {
     thread.CurrentNode = this;  //standard prolog
     var arg1 = Left.Evaluate(thread);
     var arg2 = Right.Evaluate(thread);
     //If we have _lastUsed, go straight for it; if types mismatch it will throw
     if (_lastUsed != null)
     {
         try
         {
             var res = _lastUsed.EvaluateBinary(arg1, arg2);
             thread.CurrentNode = Parent; //standard epilog
             return res;
         }
         catch
         {
             _lastUsed = null;
             _failureCount++;
             // if failed 3 times, change to method without direct try
             if (_failureCount > 3)
                 Evaluate = DefaultEvaluateImplementation;
         } //catch
     }// if _lastUsed
      // go for normal evaluation
     var result = thread.Runtime.ExecuteBinaryOperator(this.Op, arg1, arg2, ref _lastUsed);
     thread.CurrentNode = Parent; //standard epilog
     return result;
 }//method
Esempio n. 2
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   var closure = Lambda.Evaluate(thread); //returns closure
   NameNode.SetValue(thread, closure); 
   thread.CurrentNode = Parent; //standard epilog
   return closure;
 }
Esempio n. 3
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   object result = null; 
   var targetValue = _target.Evaluate(thread);
   if (targetValue == null)
     thread.ThrowScriptError("Target object is null.");
   var type = targetValue.GetType();
   var indexValue = _index.Evaluate(thread); 
   //string and array are special cases
   if (type == typeof(string)) {
     var sTarget = targetValue as string;
     var iIndex = Convert.ToInt32(indexValue); 
     result = sTarget[iIndex];
   } else if (type.IsArray) {
     var arr = targetValue as Array;
     var iIndex = Convert.ToInt32(indexValue);
     result = arr.GetValue(iIndex); 
   } else if (targetValue is IDictionary) {
     var dict = (IDictionary)targetValue;
     result = dict[indexValue];
   } else {
     const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.InvokeMethod;
     result = type.InvokeMember("get_Item", flags, null, targetValue, new object[] { indexValue }); 
   }
   thread.CurrentNode = Parent; //standard epilog
   return result; 
 }
 private object EvaluateOne(ScriptThread thread)
 {
     thread.CurrentNode = this;  //standard prolog
     object result = _singleChild.Evaluate(thread);
     thread.CurrentNode = Parent; //standard epilog
     return result;
 }
 public override void DoSetValue(ScriptThread thread, object value) {
   thread.CurrentNode = this;  //standard prolog
   var leftValue = _left.Evaluate(thread);
   if (leftValue == null)
     thread.ThrowScriptError("Target object is null.");
   var type = leftValue.GetType();
   var members = type.GetMember(_memberName);
   if (members == null || members.Length == 0)
     thread.ThrowScriptError("Member {0} not found in object of type {1}.", _memberName, type);
   var member = members[0];
   switch (member.MemberType) {
     case MemberTypes.Property:
       var propInfo = member as PropertyInfo;
       propInfo.SetValue(leftValue, value, null);
       break;
     case MemberTypes.Field:
       var fieldInfo = member as FieldInfo;
       fieldInfo.SetValue(leftValue, value);
       break;
     default:
       thread.ThrowScriptError("Cannot assign to member {0} of type {1}.", _memberName, type);
       break;
   }//switch
   thread.CurrentNode = Parent; //standard epilog
 }//method
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   var arg = Argument.Evaluate(thread);
   var result = thread.Runtime.ExecuteUnaryOperator(base.ExpressionType, arg, ref _lastUsed);
   thread.CurrentNode = Parent; //standard epilog
   return result; 
 }
Esempio n. 7
0
 private object EvaluateSimple(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   var value = Expression.Evaluate(thread);
   Target.SetValue(thread, value);
   thread.CurrentNode = Parent; //standard epilog
   return value;
 }
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   object result = null; 
   var leftValue = _left.Evaluate(thread);
   if (leftValue == null)
     thread.ThrowScriptError("Target object is null.");
   var type = leftValue.GetType();
   var members = type.GetMember(_memberName); 
   if (members == null || members.Length == 0)
     thread.ThrowScriptError("Member {0} not found in object of type {1}.", _memberName, type);
   var member = members[0];
   switch (member.MemberType) {
     case MemberTypes.Property:
       var propInfo = member as PropertyInfo;
       result = propInfo.GetValue(leftValue, null);
       break; 
     case MemberTypes.Field:
       var fieldInfo = member as FieldInfo;
       result = fieldInfo.GetValue(leftValue);
       break; 
     case MemberTypes.Method:
       result = new ClrMethodBindingTargetInfo(type, _memberName, leftValue); //this bindingInfo works as a call target
       break; 
     default:
       thread.ThrowScriptError("Invalid member type ({0}) for member {1} of type {2}.", member.MemberType, _memberName, type);
       result = null; 
       break; 
   }//switch
   thread.CurrentNode = Parent; //standard epilog
   return result; 
 }
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   SetupEvaluateMethod(thread); 
   var result = Evaluate(thread);
   thread.CurrentNode = Parent; //standard epilog
   return result;
 }
Esempio n. 10
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   //assign implementation method
   switch (Op) {
     case ExpressionType.AndAlso:
       this.Evaluate = EvaluateAndAlso;
       break; 
     case ExpressionType.OrElse:
       this.Evaluate = EvaluateOrElse;
       break;
     default:
       this.Evaluate = DefaultEvaluateImplementation;
       break; 
   }
   // actually evaluate and get the result.
   var result = Evaluate(thread); 
   // Check if result is constant - if yes, save the value and switch to method that directly returns the result.
   if (IsConstant()) {
     _constValue = result;
     AsString = Op + "(operator) Const=" + _constValue;
     this.Evaluate = EvaluateConst;
   }
   thread.CurrentNode = Parent; //standard epilog
   return result;
 }
 private object EvaluateAugmentedFast(ScriptThread thread)
 {
     thread.CurrentNode = this;  //standard prolog
     var value = Target.Evaluate(thread);
     var exprValue = Expression.Evaluate(thread);
     object result = null;
     if (_lastUsed != null)
     {
         try
         {
             result = _lastUsed.EvaluateBinary(value, exprValue);
         }
         catch
         {
             _failureCount++;
             // if failed 3 times, change to method without direct try
             if (_failureCount > 3)
                 Evaluate = EvaluateAugmented;
         } //catch
     }// if _lastUsed
     if (result == null)
         result = thread.Runtime.ExecuteBinaryOperator(BinaryExpressionType, value, exprValue, ref _lastUsed);
     Target.SetValue(thread, result);
     thread.CurrentNode = Parent; //standard epilog
     return result;
 }
Esempio n. 12
0
 private object EvaluateAfter(ScriptThread thread)
 {
     thread.CurrentNode = this;  //standard prolog
     var closure = new Closure(thread.CurrentScope, this);
     thread.CurrentNode = Parent; //standard epilog
     return closure;
 }
 // Evaluation for special forms
 private object EvaluateSpecialForm(ScriptThread thread)
 {
     thread.CurrentNode = this;  //standard prolog
     var result = _specialForm(thread, _specialFormArgs);
     thread.CurrentNode = Parent; //standard epilog
     return result;
 }
 private void SetupEvaluateMethod(ScriptThread thread)
 {
     var languageTailRecursive = thread.Runtime.Language.Grammar.LanguageFlags.IsSet(LanguageFlags.TailRecursive);
     lock (this.LockObject)
     {
         var target = TargetRef.Evaluate(thread);
         if (target is SpecialForm)
         {
             _specialForm = target as SpecialForm;
             _specialFormArgs = Arguments.ChildNodes.ToArray();
             this.Evaluate = EvaluateSpecialForm;
         }
         else
         {
             if (languageTailRecursive)
             {
                 var isTail = Flags.IsSet(AstNodeFlags.IsTail);
                 if (isTail)
                     this.Evaluate = EvaluateTail;
                 else
                     this.Evaluate = EvaluateWithTailCheck;
             }
             else
                 this.Evaluate = EvaluateNoTail;
         }
     }//lock 
 }
Esempio n. 15
0
 //Executed only once, on the first call
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   _accessor = thread.Bind(Symbol, BindingRequestFlags.Read);
   this.Evaluate = _accessor.GetValueRef; // Optimization - directly set method ref to accessor's method. EvaluateReader;
   var result = this.Evaluate(thread);
   thread.CurrentNode = Parent; //standard epilog
   return result; 
 }
Esempio n. 16
0
 public override void DoSetValue(ScriptThread thread, object value) {
   thread.CurrentNode = this;  //standard prolog
   if (_accessor == null) {
     _accessor = thread.Bind(Symbol, BindingRequestFlags.Write | BindingRequestFlags.ExistingOrNew);
   }
   _accessor.SetValueRef(thread, value);
   thread.CurrentNode = Parent;  //standard epilog
 }
Esempio n. 17
0
 private object EvaluateMultiple(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   object result = null;
   for (int i=0; i< ChildNodes.Count; i++) {
     result = ChildNodes[i].Evaluate(thread);
   }
   thread.CurrentNode = Parent; //standard epilog
   return result; //return result of last statement
 }
Esempio n. 18
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   var values = new object[ChildNodes.Count];
   for (int i = 0; i < values.Length; i++) {
     values[i] = ChildNodes[i].Evaluate(thread);
   }
   thread.CurrentNode = Parent; //standard epilog
   return values; 
 }
Esempio n. 19
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   var oldValue = Argument.Evaluate(thread);
   var newValue = thread.Runtime.ExecuteBinaryOperator(BinaryOp, oldValue, 1, ref _lastUsed);
   Argument.SetValue(thread, newValue);
   var result = IsPostfix ? oldValue : newValue;
   thread.CurrentNode = Parent; //standard epilog
   return result; 
 }
Esempio n. 20
0
 public object Call(Scope creatorScope, ScriptThread thread, object[] parameters) {
   var save = thread.CurrentNode; //prolog, not standard - the caller is NOT target node's parent
   thread.CurrentNode = this;
   thread.PushClosureScope(DependentScopeInfo, creatorScope, parameters);
   Parameters.Evaluate(thread); // pre-process parameters
   var result = Body.Evaluate(thread);
   thread.PopScope();
   thread.CurrentNode = save; //epilog, restoring caller 
   return result;
 }
Esempio n. 21
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   if (IsAugmented)
     Evaluate = EvaluateAugmentedFast;
   else
     Evaluate = EvaluateSimple; //non-augmented
   //call self-evaluate again, now to call real methods
   var result = this.Evaluate(thread);
   thread.CurrentNode = Parent; //standard epilog
   return result; 
 }
Esempio n. 22
0
 // Evaluation for non-tail languages
 private object EvaluateNoTail(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   var target = TargetRef.Evaluate(thread);
   var iCall = target as ICallTarget;
   if (iCall == null)
     thread.ThrowScriptError(Resources.ErrVarIsNotCallable, _targetName);
   var args = (object[])Arguments.Evaluate(thread);
   object result = iCall.Call(thread, args);
   thread.CurrentNode = Parent; //standard epilog
   return result;
 }
 private object BuiltInFormatMethod(ScriptThread thread, object[] args) {
   if (args == null || args.Length == 0) return null;
   var template = args[0] as string;
   if (template == null)
     this.ThrowScriptError("Format template must be a string.");
   if (args.Length == 1) return template;
   //create formatting args array
   var formatArgs = args.Skip(1).ToArray(); 
   var text = string.Format(template, formatArgs); 
   return text;
   
 }
Esempio n. 24
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   // Is called once, at first evaluation of FunctionDefNode
   // Creates parameter slots
   foreach (var child in this.ChildNodes) {
     var idNode = child as IdentifierNode;
     if (idNode != null) {
       thread.CurrentScope.Info.AddSlot(idNode.Symbol, SlotType.Parameter);
     }
   }
   this.Evaluate = EvaluateAfter;
   thread.CurrentNode = Parent; //standard epilog
   return null; 
 }//method
 //Built-in methods
 private object BuiltInPrintMethod(ScriptThread thread, object[] args) {
   string text = string.Empty;
   switch(args.Length) {
     case 1:
       text = string.Empty + args[0]; //compact and safe conversion ToString()
       break; 
     case 0:
       break; 
     default:
       text = string.Join(" ", args);
       break; 
   }
   thread.App.WriteLine(text);
   return null; 
 }
Esempio n. 26
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   object result = null; 
   var test = Test.Evaluate(thread);
   var isTrue = thread.Runtime.IsTrue(test);
   if (isTrue) {
     if (IfTrue != null)
       result = IfTrue.Evaluate(thread);
   } else {
     if (IfFalse != null)
       result = IfFalse.Evaluate(thread);
   }
   thread.CurrentNode = Parent; //standard epilog
   return result; 
 }
Esempio n. 27
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   lock (LockObject) {
     if (DependentScopeInfo == null) {
       var langCaseSensitive = thread.App.Language.Grammar.CaseSensitive;
       DependentScopeInfo = new ScopeInfo(this, langCaseSensitive);
     }
     // In the first evaluation the parameter list will add parameter's SlotInfo objects to Scope.ScopeInfo
     thread.PushScope(DependentScopeInfo, null);
     Parameters.Evaluate(thread);
     thread.PopScope();
     //Set Evaluate method and invoke it later
     this.Evaluate = EvaluateAfter;
   }
   var result = Evaluate(thread);
   thread.CurrentNode = Parent; //standard epilog
   return result;
 }
Esempio n. 28
0
        protected override object DoEvaluate(ScriptThread thread)
        {
            thread.CurrentNode = this; //standard prolog
            lock (LockObject) {
                if (DependentScopeInfo == null)
                {
                    base.DependentScopeInfo = new ScopeInfo(this, _languageCaseSensitive);
                }
                // In the first evaluation the parameter list will add parameter's SlotInfo objects to Scope.ScopeInfo
                thread.PushScope(DependentScopeInfo, null);
                Parameters.Evaluate(thread);
                thread.PopScope();
                //Set Evaluate method and invoke it later
                this.Evaluate = EvaluateAfter;
            }
            var result = Evaluate(thread);

            thread.CurrentNode = Parent; //standard epilog
            return(result);
        }
Esempio n. 29
0
        public static object StringJoin(ScriptThread thread, object instance, object[] parameters)
        {
            string ret = null;

            var separator  = parameters[0] as string;
            var valueTable = (parameters[1] as DataTable)?.GetIntIndexedDict();
            int startIndex = Convert.ToInt32(parameters[2]);
            int count      = Convert.ToInt32(parameters[3]);

            var value = new string[valueTable.Count];

            for (int i = 0; i < value.Length; i++)
            {
                value[i] = valueTable[i].ToString();
            }

            ret = string.Join(separator, value, startIndex, count);

            return(ret);
        }
Esempio n. 30
0
        public object Call(ScriptThread thread, object[] parameters)
        {
            var astNode      = new AstNode();        // TODO: figure it out
            var newScopeInfo = new ScopeInfo(astNode, thread.App.Language.Grammar.CaseSensitive);

            thread.PushScope(newScopeInfo, parameters);

            try
            {
                var expression =
                    parameters != null && parameters.Length > 0 ?
                    parameters[0] as PassiveExpression : null;

                return(Function(expression));
            }
            finally
            {
                thread.PopScope();
            }
        }
        //Built-in methods
        private object BuiltInPrintMethod(ScriptThread thread, object[] args)
        {
            string text = string.Empty;

            switch (args.Length)
            {
            case 1:
                text = string.Empty + args[0]; //compact and safe conversion ToString()
                break;

            case 0:
                break;

            default:
                text = string.Join(" ", args);
                break;
            }
            thread.App.WriteLine(text);
            return(null);
        }
Esempio n. 32
0
 protected override object DoEvaluate(ScriptThread thread) {
   thread.CurrentNode = this;  //standard prolog
   lock (LockObject) {
     switch (ChildNodes.Count) {
       case 0:
         Evaluate = EvaluateEmpty;
         break;
       case 1:
         _singleChild = ChildNodes[0];
         Evaluate = EvaluateOne;
         break; 
       default:
         Evaluate = EvaluateMultiple;
         break; 
     }//switch
   }//lock
   var result = Evaluate(thread);
   thread.CurrentNode = Parent; //standard epilog
   return result;
 }
Esempio n. 33
0
        private MtResult MtCar(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();
            var arr = args[0] as MtResult;

            arr.GetValue((o) =>
            {
                var wrkArr = o.Value as MtResult[];
                if (wrkArr == null)
                {
                    throw new Exception("Argument is not an array!");
                }

                wrkArr[0].GetValue((head) =>
                {
                    ret.SetValue(head);
                });
            });
            return(ret);
        }
Esempio n. 34
0
        public override object Call(ScriptThread thread, object[] parameters)
        {
            thread.PushScope(ScopeInfo, parameters);

            try
            {
                var expression =
                    parameters != null && parameters.Length > 0 ?
                    parameters[0] as PassiveExpression : null;

                Block.InputExpression = expression;
                Block.BlockPattern    = null;

                return(Block.Evaluate(thread));
            }
            finally
            {
                thread.PopScope();
            }
        }
Esempio n. 35
0
        private object MtLength(ScriptThread thread, object[] args)
        {
            var ret  = new MtResult();
            var arg0 = args[0] as MtResult;

            arg0.GetValue((o) =>
            {
                var arr = o.Value as MtResult[];
                if (arr == null)
                {
                    ret.SetValue(new MtObject(0));
                }
                else
                {
                    ret.SetValue(new MtObject(arr.Length));
                }
            });

            return(ret);
        }
Esempio n. 36
0
        private object MtNot(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();

            var the_arg = args[0] as MtResult;

            the_arg.GetValue(o =>
            {
                if (o.Value == MtObject.False.Value)
                {
                    ret.SetValue(MtObject.True);
                }
                else
                {
                    ret.SetValue(MtObject.False);
                }
            });

            return(ret);
        }
Esempio n. 37
0
        private MtResult MtZero(ScriptThread thread, object[] args)
        {
            try
            {
                var res = new MtResult();

                var arg = args[0] as MtResult;
                arg.GetValue((o) =>
                {
                    int value = (int)o.Value;
                    res.SetValue(value == 0 ? MtObject.True : MtObject.False);
                });

                return(res);
            }
            catch (Exception e)
            {
                throw new Exception("Exception on Runtime function: zero", e);
            }
        }
Esempio n. 38
0
        public override void Create()
        {
            base.Create();

            var levelMgr = ScriptThread.GetOrAddExtension <LevelManager>();

            var sessMgr = ScriptThread.GetOrAddExtension <SessionManager>();

            LevelSpawn spawnPoint = levelMgr.GetSpawnPoint(Info.Sess.TeamNum);

            // spawn above to avoid collision with teammates.

            Vector3 position = Utility.EnsureValidSpawnPos(spawnPoint.Position + new Vector3(0, 0, 2.0f));

            Model model = new Model(VehicleHash.Lazer);

            if (!model.IsLoaded)
            {
                model.Request(1000);
            }

            var vehicle = World.CreateVehicle(model, position, spawnPoint.Heading);

            vehicle.LodDistance   = 2000;
            vehicle.EngineRunning = true;
            vehicle.BodyHealth    = 1000;

            vehicle.MaxSpeed = 280.0f;

            Function.Call(Hash.SET_VEHICLE_EXPLODES_ON_HIGH_EXPLOSION_DAMAGE, vehicle, true);

            Ped ped = Game.Player.Character;

            TeamData team = sessMgr.GetTeamByIndex(Info.Sess.TeamNum);

            ped.RelationshipGroup = team.RelationshipGroup;

            ped.SetIntoVehicle(vehicle, VehicleSeat.Driver);

            Manage(ped, vehicle);
        }
Esempio n. 39
0
        public static object Length(ScriptThread thread, object instance, object[] parameters)
        {
            object result;

            switch (instance.GetType().Name)
            {
            case "DataTable":
                result = ((DataTable)instance).Length;
                break;

            case "Range":
            {
                var obj = (Range)instance;
                result = Math.Abs(obj.End - obj.Start);
            }
            break;

            case "RangeWithStep":
            {
                var obj = (RangeWithStep)instance;
                result = obj.LongCount();
            }
            break;

            case "String":
                result = ((string)instance).Length;
                break;

            default:
                if (instance.GetType().IsArray)
                {
                    result = ((Array)instance).Length;
                }
                else
                {
                    result = -1;
                }
                break;
            }
            return(result);
        }
Esempio n. 40
0
        public object MtStringStreamCreate(ScriptThread thread, object[] arguments)
        {
#if DEBUG && !SILVERLIGHT
            Debug.Print("Create stream from string");
#endif

            try
            {
                var result = new MtResult();
                var rStr   = arguments[0] as MtResult;
                rStr.GetValue((str) =>
                {
                    result.SetValue(new MtObject(new MtStreamString(str.Value as string)));
                });
                return(result);
            }
            catch (Exception e)
            {
                throw new Exception("Error on string stream create.", e);
            }
        }
Esempio n. 41
0
        public static unsafe object SetFilePointer(ScriptThread thread, object instance, object[] parameters)
        {
            IntPtr         preHandle = (IntPtr)parameters[0];
            SafeFileHandle handle    = new SafeFileHandle(preHandle, false);
            int            lo        = Convert.ToInt32(parameters[1]);
            int            hi        = Convert.ToInt32(parameters[2]);
            int            origin    = Convert.ToInt32(parameters[3]);

            object ret = null;

            lo = NativeMethods.SetFilePointer(handle, lo, &hi, origin);

            if (lo == -1)
            {
                hi = 0;
            }

            ret = (decimal)((((ulong)((uint)hi)) << 32) | ((uint)lo));

            return(ret);
        }
Esempio n. 42
0
        public override void OnUpdate(int gameTime)
        {
            if (!ScriptThread.GetVar <bool>("scr_hardcore").Value)
            {
                if (Game.IsControlJustPressed(0, Control.ScriptLB) || Game.IsControlJustPressed(0, (Control)48))
                {
                    var extinguisher = GetExtension <EngineExtinguisher>();

                    extinguisher.Start();
                }

                else if (Game.IsControlJustPressed(0, Control.ScriptRB) || Game.IsControlJustPressed(0, (Control)337))
                {
                    var flareMgr = GetExtension <IRFlareManager>();

                    flareMgr.Start();
                }
            }

            base.OnUpdate(gameTime);
        }
Esempio n. 43
0
        public void RenderPolygonB(ScriptThread thread)
        {
            int arrayIndex = thread.GetArrayParameter(0);

            if (arrayIndex == 0)
            {
                DebugLogger.WriteLog((thread.Process.Url != null && thread.Process.Url != "" ? thread.Process.Url : "A script") + " called RenderPolygon with an invalid object.", LogAlertLevel.Error);
                return;
            }
            int arrayLength = thread.GetArrayLength(arrayIndex);

            Vertex[] vertexs = new Vertex[(arrayLength / 3)];
            for (int i = 0; i < (arrayLength / 3); i++)
            {
                vertexs[i] = new Vertex(thread.GetFloatArrayElement(arrayIndex, (i * 3)),
                                        thread.GetFloatArrayElement(arrayIndex, (i * 3) + 1),
                                        thread.GetFloatArrayElement(arrayIndex, (i * 3) + 2));
            }

            GraphicsManager.RenderPolygon(vertexs, thread.GetBooleanParameter(1));
        }
Esempio n. 44
0
        }//

        private object BuildString(ScriptThread thread)
        {
            string[] values = new string[_segments.Count];
            for (int i = 0; i < _segments.Count; i++)
            {
                var segment = _segments[i];
                switch (segment.Type)
                {
                case SegmentType.Text:
                    values[i] = segment.Text;
                    break;

                case SegmentType.Expression:
                    values[i] = EvaluateExpression(thread, segment);
                    break;
                } //else
            }     //for i
            var result = string.Join(string.Empty, values);

            return(result);
        }//method
Esempio n. 45
0
        protected override object DoEvaluate(ScriptThread thread)
        {
            thread.CurrentNode = this;
            lock (lockObject)
            {
                if (DependentScopeInfo == null)
                {
                    DependentScopeInfo = new ScopeInfo(this);
                }

                thread.PushScope(DependentScopeInfo, null);
                Parameters.Evaluate(thread);
                thread.PopScope();
                Evaluate = EvaluateAfter;
            }

            var result = Evaluate(thread);

            thread.CurrentNode = Parent;
            return(result);
        }
Esempio n. 46
0
        public void BFCodeSubString(ScriptThread thread)
        {
            string bfCode        = thread.GetStringParameter(0);
            int    start         = thread.GetIntegerParameter(1);
            int    length        = thread.GetIntegerParameter(2);
            string finished      = "";
            int    currentLength = 0;

            if (bfCode == "" || bfCode == null)
            {
                return;
            }

            for (int currentPosition = 0; currentPosition < bfCode.Length; currentPosition++)
            {
                char currentCharacter = bfCode[currentPosition];
                if (currentCharacter == '[')
                {
                    // Skip to closing tag.
                    int newPosition = bfCode.IndexOf(']', currentPosition);
                    if (newPosition == -1)
                    {
                        continue;
                    }

                    finished       += bfCode.Substring(currentPosition, (newPosition - currentPosition) + 1);
                    currentPosition = newPosition;
                }
                else if (currentPosition >= start)
                {
                    finished += currentCharacter;
                    currentLength++;
                }
                if (currentLength >= length)
                {
                    break;
                }
            }
            thread.SetReturnValue(finished);
        }
Esempio n. 47
0
        protected override object DoEvaluate(ScriptThread thread)
        {
            // standard prolog
            thread.CurrentNode = this;

            // evaluate pattern and copy bound variables of the current block
            var patt = Pattern.Instantiate(thread);

            if (BlockPattern != null)
            {
                patt.CopyBoundVariables(BlockPattern);
            }

            object result = null;

            // if pattern is recognized, calculate new expression and return true
            var success = patt.Match(InputExpression);

            if (success)
            {
                // store last recognized pattern as a local variable
                thread.SetLastPattern(patt);

                // simple sentence
                if (Expression != null)
                {
                    result = Expression.Evaluate(thread);
                }

                // sentence with a where- or when-clause
                else if (Conditions != null)
                {
                    result = Conditions.Evaluate(thread);
                }
            }

            // standard epilog
            thread.CurrentNode = Parent;
            return(result);
        }
Esempio n. 48
0
        private void SetupEvaluateMethod(ScriptThread thread)
        {
            var languageTailRecursive = thread.Runtime.Language.Grammar.LanguageFlags.IsSet(LanguageFlags.TailRecursive);

            lock (this.LockObject) {
                _specialForm = null;
                var bnd = thread.Bind(_formName, BindingRequestFlags.Invoke);
                if (bnd != null)
                {
                    _specialForm = bnd.GetValueRef(thread) as SpecialForm;
                }
                IBindingSource src;
                var            target = thread.Runtime.BuiltIns.TryGetValue(_formName, out src);
                if (target is SpecialForm)
                {
                    _specialForm     = target as SpecialForm;
                    _specialFormArgs = Arguments.ChildNodes.ToArray();
                    this.Evaluate    = EvaluateSpecialForm;
                }
                else
                {
                    if (languageTailRecursive)
                    {
                        var isTail = Flags.IsSet(AstNodeFlags.IsTail);
                        if (isTail)
                        {
                            this.Evaluate = EvaluateTail;
                        }
                        else
                        {
                            this.Evaluate = EvaluateWithTailCheck;
                        }
                    }
                    else
                    {
                        this.Evaluate = EvaluateNoTail;
                    }
                }
            }//lock
        }
Esempio n. 49
0
        public static object GetType(ScriptThread thread, object thisRef, object[] parameters)
        {
            if (thisRef == null || Equals(thisRef, thread.Runtime.NullValue))
            {
                return("Null");
            }

            string result = thisRef.GetType().Name;

            switch (result)
            {
            case "Double":
            case "Decimal":
            case "Int32":
            case "Int64":
                return("Number");

            case "String":
                return("String");

            case "Char":
                return("Char");

            case "DataTable":
            case "Range":
            case "RangeWithStep":
                return("Table");

            case "Closure":
            case "BuiltInCallTarget":
            case "MethodTable":
                return("Function");

            case "Boolean":
                return("Bool");
            }

            return(result);
        }
Esempio n. 50
0
        public void CommandLineValue(ScriptThread thread)
        {
            string commandLine = thread.GetStringParameter(0);
            int    valueIndex  = thread.GetIntegerParameter(1);

            foreach (string arg in Engine.GlobalInstance.CommandLineArguments)
            {
                string[] value      = new string[0];
                string   command    = arg;
                int      colonIndex = arg.IndexOf(':');

                // Seperate values and command if a colon exists.
                if (colonIndex >= 0)
                {
                    value    = new string[1];
                    value[0] = arg.Substring(colonIndex + 1, arg.Length - colonIndex - 1);
                    if (value[0].IndexOf(",") >= 0)
                    {
                        value = value[0].Split(new char[1] {
                            ','
                        });
                    }
                    command = arg.Substring(0, colonIndex);
                }

                if (command.ToLower() == commandLine.ToLower())
                {
                    if (valueIndex < 0 || valueIndex >= value.Length)
                    {
                        DebugLogger.WriteLog((thread.Process.Url != null && thread.Process.Url != "" ? thread.Process.Url : "A script") + " called CommandLineValue with an invalid value index.", LogAlertLevel.Error);
                        return;
                    }
                    thread.SetReturnValue(value[valueIndex]);
                    return;
                }
            }

            DebugLogger.WriteLog((thread.Process.Url != null && thread.Process.Url != "" ? thread.Process.Url : "A script") + " called CommandLineValue with a non-existant command line.", LogAlertLevel.Error);
        }
Esempio n. 51
0
        public override void DoSetValue(ScriptThread thread, object value)
        {
            thread.CurrentNode = this;  //standard prolog
            var targetValue = _target.Evaluate(thread);

            if (targetValue == null)
            {
                thread.ThrowScriptError("Target object is null.");
            }

            var type       = targetValue.GetType();
            var indexValue = _index.Evaluate(thread);

            //string and array are special cases
            if (type == typeof(string))
            {
                thread.ThrowScriptError("String is read-only.");
            }
            else if (type.IsArray)
            {
                var arr    = (Array)targetValue;
                var iIndex = Convert.ToInt32(indexValue);
                arr.SetValue(value, iIndex);
            }
            else if (targetValue is IDictionary dict)
            {
                dict[indexValue] = value;
            }
            else
            {
                // Cannot use IndexerNameAttribute, see:
                // https://social.msdn.microsoft.com/Forums/en-US/60de101a-278d-4674-bc1a-0a04210d566c/identifying-the-indexername-attribute-on-an-indexer-property?forum=vstscode
                var defaultMemberAttr    = type.GetCustomAttribute <DefaultMemberAttribute>();
                var indexerName          = defaultMemberAttr?.MemberName ?? "Item";
                const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.InvokeMethod;
                type.InvokeMember("set_" + indexerName, flags, null, targetValue, new[] { indexValue, value });
            }
            thread.CurrentNode = Parent; //standard epilog
        }
Esempio n. 52
0
        private string BuildString(ScriptThread thread)
        {
            var values = new string[segments.Count];

            for (int i = 0; i < segments.Count; i++)
            {
                var segment = segments[i];

                switch (segment.Type)
                {
                case SegmentType.Text:
                    values[i] = segment.Text;
                    break;

                case SegmentType.Expression:
                    values[i] = EvaluateExpression(thread, segment);
                    break;
                }
            }

            return(string.Concat(values));
        }
Esempio n. 53
0
        private object EvaluateMultiple(ScriptThread thread)
        {
            thread.CurrentNode = this;
            FlowControl        = FlowControl.Next;
            var lastFlowControl = FlowControl.Next;

            object result = thread.Runtime.NullValue;

            for (int i = 0; i < ChildNodes.Count && lastFlowControl == FlowControl.Next; i++)
            {
                result          = ChildNodes[i].Evaluate(thread);
                lastFlowControl = ChildNodes[i].FlowControl;
            }

            if (lastFlowControl != FlowControl.Next)
            {
                FlowControl = lastFlowControl;
            }

            thread.CurrentNode = Parent;
            return(result);
        }
Esempio n. 54
0
        /// <summary>
        /// Start running the script in a loop.
        ///
        /// </summary>
        /// <param name="script_text"></param>
        public void RunLoop(string script_text, bool blocking = true)
        {
            RunThread(delegate()
            {
                DateTime start_time = DynamicTimerStart = DateTime.Now;
                int loop_count      = 0;

                List <FunctionCall> base_script = ProcessScript(script_text);
                while (true)
                {
                    ExecuteScript(base_script);

                    loop_count++;
                    OnLoopFinished(new LoopFinishedEventArgs(loop_count, DateTime.Now - start_time));
                }
            });

            if (blocking)
            {
                ScriptThread.Join();
            }
        }
        private object BuiltInFormatMethod(ScriptThread thread, object[] args)
        {
            if (args == null || args.Length == 0)
            {
                return(null);
            }
            var template = args[0] as string;

            if (template == null)
            {
                this.ThrowScriptError("Format template must be a string.");
            }
            if (args.Length == 1)
            {
                return(template);
            }
            //create formatting args array
            var formatArgs = args.Skip(1).ToArray();
            var text       = string.Format(template, formatArgs);

            return(text);
        }
Esempio n. 56
0
        protected override object DoEvaluate(ScriptThread thread)
        {
            thread.CurrentNode = this; //standard prolog
            object result      = null;
            var    targetValue = _target.Evaluate(thread);

            if (targetValue == null)
            {
                thread.ThrowScriptError("Target object is null.");
            }
            var type       = targetValue.GetType();
            var indexValue = _index.Evaluate(thread);

            //string and array are special cases
            if (type == typeof(string))
            {
                var sTarget = targetValue as string;
                var iIndex  = Convert.ToInt32(indexValue);
                result = sTarget[iIndex];
            }
            else if (type.IsArray)
            {
                var arr    = targetValue as Array;
                var iIndex = Convert.ToInt32(indexValue);
                result = arr.GetValue(iIndex);
            }
            else if (targetValue is IDictionary)
            {
                var dict = (IDictionary)targetValue;
                result = dict[indexValue];
            }
            else
            {
                const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.InvokeMethod;
                result = type.InvokeMember("get_Item", flags, null, targetValue, new object[] { indexValue });
            }
            thread.CurrentNode = Parent; //standard epilog
            return(result);
        }
Esempio n. 57
0
        protected override object DoEvaluate(ScriptThread thread)
        {
            thread.CurrentNode = this;

            if (children == null)
            {
                throw new ParserException();
            }
            var list = new StatementNode[children.Length];

            foreach (var(node, i) in children.Select((node, i) => (node, i)))
            {
                if (node.Evaluate(thread) is not StatementNode statement)
                {
                    throw new ParserException();
                }
                list[i] = statement;
            }

            thread.CurrentNode = Parent;
            return(new ProgramNode(list));
        }
Esempio n. 58
0
        private object MtSliceFrom(ScriptThread thread, object[] args)
        {
            var ret = new MtResult();

            var the_list = args[0] as MtResult;
            var the_idx  = args[1] as MtResult;

            the_list.GetValue(o_list =>
            {
                var arr = o_list.Value as MtResult[];
                if (arr == null)
                {
                    throw new Exception("slice_from expected a list!");
                }

                the_idx.GetValue(o_idx =>
                {
                    var idx = (int)o_idx.Value;
                    idx     = idx < 0 ? 0 : idx;

                    if (idx >= arr.Length)
                    {
                        // If idx is outside array, return an empty array
                        ret.SetValue(new MtObject(new MtResult[0]));
                    }
                    else
                    {
                        var len = arr.Length;

                        var ret_arr = new MtResult[len - idx];
                        Array.Copy(arr, idx, ret_arr, 0, ret_arr.Length);

                        ret.SetValue(new MtObject(ret_arr));
                    }
                });
            });

            return(ret);
        }
Esempio n. 59
0
 public override void DoSetValue(ScriptThread thread, object value) {
   thread.CurrentNode = this;  //standard prolog
   var targetValue = _target.Evaluate(thread);
   if (targetValue == null)
     thread.ThrowScriptError("Target object is null.");
   var type = targetValue.GetType();
   var indexValue = _index.Evaluate(thread);
   //string and array are special cases
   if (type == typeof(string)) {
     thread.ThrowScriptError("String is read-only.");
   } else if (type.IsArray) {
     var arr = targetValue as Array;
     var iIndex = Convert.ToInt32(indexValue);
     arr.SetValue(value, iIndex);
   } else if (targetValue is IDictionary) {
     var dict = (IDictionary)targetValue;
     dict[indexValue] = value;
   } else {
     const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.InvokeMethod;
     type.InvokeMember("set_Item", flags, null, targetValue, new object[] { indexValue, value }); 
   }
   thread.CurrentNode = Parent; //standard epilog
 }//method
Esempio n. 60
0
 private object EvaluateOrElse(ScriptThread thread) {
   var leftValue = Left.Evaluate(thread);
   if (thread.Runtime.IsTrue(leftValue)) return leftValue;
   return Right.Evaluate(thread);
 }