Ejemplo n.º 1
0
    public bool Sense(EvalContext context, EntityType entityToBeDetected)
    {
        IfDetector detector = context.Target.GetComponent <IfDetector>();

        if (detector == null)
        {
            detector = context.Target.gameObject.AddComponent <IfDetector>();
        }
        Moveable  moveable = context.Target.GetComponent <Moveable>();
        Rigidbody rb       = context.Target.GetComponent <Rigidbody>();

        if (moveable != null)
        {   //block된 상황에서 부들거리는 현상을 없애기 위해 iskinematic 변환 효과 없앰
            bool current = rb.isKinematic;
            moveable.Ungravitate();
            rb.isKinematic = current;
        }
        bool value = detector.Detect(entityToBeDetected);

        if (moveable != null)
        {
            moveable.Gravitate();
        }

        return(value);
    }
Ejemplo n.º 2
0
        public object Next(FunctionArgument _args, EvalContext cal)
        {
            StringBuilder sb = new StringBuilder();
            char?         c  = null;

            while (!sr.EndOfStream)
            {
                c = (char)sr.Read();
                if (!char.IsWhiteSpace(c.Value))
                {
                    break;
                }
            }
            if (c.HasValue == false)
            {
                return((StringValue)(sb.ToString()));
            }
            sb.Append(c.Value);
            while (!sr.EndOfStream)
            {
                c = (char)sr.Read();
                if (char.IsWhiteSpace(c.Value))
                {
                    break;
                }
                sb.Append(c);
            }
            return((StringValue)sb.ToString());
        }
Ejemplo n.º 3
0
        public override async Task <StmtResult> Eval(EvalContext context)
        {
            //Debug.Log("if begins");
            await base.Eval(context);

            //object condResult = Cond.Eval();
            object condResult = Inst.CommandMgr.Sense(context, Cond.type);

            if (condResult is bool)
            {
                bool condValue = (bool)condResult;
                if ((condValue ^ Cond.Value) && Then != null)
                {
                    return(await Then.Eval(context));
                }
                if (Else != null)
                {
                    return(await Else.Eval(context));
                }
                return(StmtResult.None);
            }
            else
            {
                throw new LangException("condition in if is not boolean");
            }
        }
        //[CascadingParameter]
        //protected EditContext CurrentEditContext { get; set; }

        protected async override Task OnInitializedAsync()
        {
            //todo: allow upload of fitness
            //FitnessTypeNameOptions = Jtc.Optimization.Objects.FitnessTypeNameOptions.Options; assembly.GetTypes().Where(w => w.GetInterfaces().Contains(typeof(IFitness))).Select(s => s.FullName).OrderBy(o => o);

            using (dynamic context = new EvalContext(JSRuntime))
            {
                (context as EvalContext).Expression = () => context.ClientStorage.fetchConfig();
                var json = await(context as EvalContext).InvokeAsync <string>();

                if (!string.IsNullOrEmpty(json))
                {
                    Config = JsonSerializer.Deserialize <Models.OptimizerConfiguration>(json);
                }
            }

            ToggleFitness();

            using (dynamic context = new EvalContext(JSRuntime))
            {
                (context as EvalContext).Expression = () => context.jQuery("body").css("overflow-y", "scroll");
            }

            await base.OnInitializedAsync();
        }
Ejemplo n.º 5
0
        protected async Task UpdateChart()
        {
            await Wait.Show();

            try
            {
                _stopWatch.Start();
                await BindRemote();

                //todo: reinstate new only
                if (NewOnly)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    var settings = new EvalContextSettings();
                    settings.SerializableTypes.Add(typeof(PlotlyData[]));
                    using (dynamic context = new EvalContext(JSRuntime))
                    {
                        (context as EvalContext).Expression = () => context.PlotlyInterop.newPlot(Config);
                    }
                }
            }
            finally
            {
                await Wait.Hide();
            }
        }
Ejemplo n.º 6
0
        protected async Task GetStoredChart()
        {
            _stopWatch.Start();
            await Wait.Show();

            StateHasChanged();
            //todo: reinstate new only
            //if (!NewOnly)
            //{
            //    Config.Data.Datasets.Clear();
            //    await JsRuntime.SetupChart(Config);
            //}

            try
            {
                dynamic context = new EvalContext(JSRuntime);
                (context as EvalContext).Expression = () => context.ClientStorage.fetchChartData();
                var log = await(context as EvalContext).InvokeAsync <string>();

                using (var reader = new SwitchReader(new StringReader(log)))
                {
                    var data = await PlotlyBinder.Read(reader, SampleRate == 0? 1 : SampleRate, false, NewOnly?NewestTimestamp : DateTime.MinValue, minimumFitness : MinimumFitness);
                    await ShowChart(data);
                }
            }
            catch (Exception ex)
            {
                ShowError(ex, "An error occurred attempting to bind.");
            }
            finally
            {
                await Wait.Hide();
            }
        }
Ejemplo n.º 7
0
        private bool GetHasChartData()
        {
            dynamic context = new EvalContext(JSRuntime);

            (context as EvalContext).Expression = () => context.ClientStorage.hasChartData();
            return((context as EvalContext).Invoke <bool>());
        }
        protected async override Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                using (dynamic context = new EvalContext(JSRuntime))
                {
                    (context as EvalContext).Expression = () => context.ace.edit("editor").setTheme("ace/theme/monokai");
                    await(context as EvalContext).InvokeAsync <dynamic>();

                    context.Reset();

                    (context as EvalContext).Expression = () => context.ace.edit("editor").session.setMode("ace/mode/javascript");
                    await(context as EvalContext).InvokeAsync <dynamic>();
                }
            }

            using (dynamic context = new EvalContext(JSRuntime))
            {
                (context as EvalContext).Expression = () => context.ace.edit("editor").session.setValue(MinimizeFunctionCode.Code);
                await(context as EvalContext).InvokeAsync <dynamic>();

                context.Reset();

                (context as EvalContext).Expression = () => context.ClientStorage.fetchConfig("config");
                var raw = await(context as EvalContext).InvokeAsync <string>();

                if (raw != null)
                {
                    _config = JsonSerializer.Deserialize <Objects.OptimizerConfiguration>(raw);
                }
            }

            await base.OnAfterRenderAsync(firstRender);
        }
Ejemplo n.º 9
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     if (p.Length != 1)
         throw new Exception("Invalid number of parameters.");
     context.DoOutputText(p[0].Evaluate(context).ToString());
     return null;
 }
Ejemplo n.º 10
0
 public override void Execute(EvalContext context)
 {
     if ((NumberType)Conditional.Evaluate(context) != FALSE)
         TStmtList.Excecute(context);
     else
         FStmtList.Excecute(context);
 }
Ejemplo n.º 11
0
 public void Hide()
 {
     using (dynamic context = new EvalContext(JsRuntime))
     {
         (context as EvalContext).Expression = () => context.jQuery(Selector).hide();
     }
 }
Ejemplo n.º 12
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     if (p.Length != 1)
         throw new Exception("Invalid number of parameters.");
     var n = p[0].Evaluate(context) as NumberType;
     return new NumberType(Math.Ceiling(n.value), n.Unit);
 }
Ejemplo n.º 13
0
 public override EvalType Evaluate(EvalContext context)
 {
     NumberType[] n = new NumberType[Parameters.Length];
     for (int i = 0; i < n.Length; i++)
         n[i] = NT(Parameters[i].Evaluate(context));
     return new NumberListType(n);
 }
Ejemplo n.º 14
0
        private dynamic RenderSeries(dynamic req)
        {
            try
            {
                var model = new RenderSeriesModel();

                this.BindTo(model, new BindingConfig {
                    BodyOnly = false
                });

                var tgt = (string)Request.Form.target;

                var now   = DateTime.UtcNow;
                var from  = DateTimeParser.ParseDateTime(model.From, now, now.AddHours(-1));
                var until = DateTimeParser.ParseDateTime(model.Until, now, now);

                var targets = string.Join("', '", model.Target);
                log.Debug("started rendering metrics using '{0}' from {1:s} to {2:s} ({3})", targets, from, until, until - from);

                var environment = new Statsify.Core.Expressions.Environment {
                    MetricRegistry         = metricRegistry,
                    QueuedMetricDatapoints = metricAggregator.Queue
                };

                var evalContext = new EvalContext(@from, until);
                var expressions =
                    expressionCompiler.Parse(model.Target).
                    Select(e =>
                           e is MetricSelectorExpression ?
                           new EvaluatingMetricSelectorExpression(e as MetricSelectorExpression) :
                           e).
                    ToList();

                log.Debug("started evaluating expression");
                var r = expressions.SelectMany(e => (Core.Model.Metric[])e.Evaluate(environment, evalContext)).ToArray();
                log.Debug("evaluated expression");

                var metrics = new List <Core.Model.Metric>(r);

                var seriesViewList =
                    metrics.
                    Select(m =>
                           new SeriesView {
                    Target     = m.Name,
                    Datapoints =
                        m.Series.Datapoints.
                        Select(d => new[] { d.Value, d.Timestamp.ToUnixTimestamp() }).
                        ToArray()
                }).
                    ToArray();

                log.Debug("rendered {0} metrics using '{1}' from {2:s} to {3:s}", seriesViewList.Length, targets, from, until);

                return(Response.AsJson(seriesViewList));
            }
            catch (Exception e)
            {
                return(Response.AsJson(new { e.Message, e.StackTrace }, HttpStatusCode.InternalServerError));
            }
        }
Ejemplo n.º 15
0
 public void Register(EvalContext c)
 {
     c.RegisterAssembly(typeof(Startup).Assembly);
     c.RegisterAssembly(typeof(Utilities.ReflectionUtils).Assembly);
     c.RegisterExtensionMethod(typeof(EntityFrameworkQueryableExtensions));
     c.RegisterType(typeof(JsonConvert));
 }
Ejemplo n.º 16
0
 public async Task Hide()
 {
     using (dynamic context = new EvalContext(JsRuntime))
     {
         (context as EvalContext).Expression = () => context.jQuery("#wait").hide();
         await(context as EvalContext).InvokeAsync <dynamic>();
     }
 }
 private string GetChartDataSaved()
 {
     using (dynamic context = new EvalContext(JSRuntime))
     {
         (context as EvalContext).Expression = () => context.ClientStorage.hasChartData();
         return((context as EvalContext).Invoke <bool>() ? null : "d-none");
     }
 }
Ejemplo n.º 18
0
 public IExpr Calculate(EvalContext cal, IExpr[] exps)
 {
     /*if (QuantityNumber != -1)
      * {
      *  if (exps.Length != QuantityNumber) throw new Exception("The number of quantitys is wrong. It should be " + QuantityNumber.ToString());
      * }*/
     return(EvaluateFunc.Invoke(exps, cal));
 }
Ejemplo n.º 19
0
 public virtual async Task <StmtResult> Eval(EvalContext context)
 {
     if (Inst.CancelAllPrograms)
     {
         throw new CancelException();
     }
     return(StmtResult.None);
 }
Ejemplo n.º 20
0
 public override void Prepare(EvalContext ctx, string path)
 {
     base.Prepare(ctx, path);
     foreach (var statement in Statements)
     {
         statement.Prepare(ctx, m_Path);
     }
 }
Ejemplo n.º 21
0
        /// <summary>
        /// </summary>
        /// <exception cref="ApiException">Thrown when fails to make API call</exception>
        /// <param name="body">evalution batch request</param>
        /// <returns>Task of ApiResponse (EvaluationBatchResponse)</returns>
        public async Task <ApiResponse <EvalResult> > PostEvaluationAsync(EvalContext body)
        {
            if (body == null)
            {
                throw new ApiException(400, "Missing required parameter 'body' when calling EvaluationApi->PostEvaluationBatch");
            }

            return(await _httpClient.PostAsync("evaluation").WithBody((x) => x.Model(body)).AsApiResponse <EvalResult>());
        }
Ejemplo n.º 22
0
        public EvalContext CreateFreshEvalContext()
        {
            PackageGlobals.VSMultiInstanceInfo multi_instance_info;
            GetVSMultiInstanceInfo(out multi_instance_info);
            EvalContext eval_ctx = new EvalContext();

            SetVariableValuesFromIDEState(eval_ctx, multi_instance_info);
            return(eval_ctx);
        }
Ejemplo n.º 23
0
        public override async Task <StmtResult> Eval(EvalContext context)
        {
            await base.Eval(context);

            Expr.Eval();
            await new WaitForSeconds(Inst.Delay);
            Inst.Nounce++;
            return(StmtResult.None);
        }
Ejemplo n.º 24
0
        public void Eval(EvalContext <TInput, TOutput> context, object value)
        {
            foreach (var converter in Converters)
            {
                value = converter.Convert(value);
            }

            SetValue(context, value);
        }
Ejemplo n.º 25
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     context.DoOutputText(context.FunctionList.functions.Count + " functions defined.");
     foreach (var f in context.FunctionList.functions)
     {
         context.DoOutputText(f.Key + ":" + f.Value.Name + "=>" + f.Value);
     }
     return null;
 }
Ejemplo n.º 26
0
 public ModuleValue(string name, string author, string version, EvalContext context = null) : base(context)
 {
     Author       = author;
     Name         = name;
     Version      = version;
     this.author  = new ReadOnlyConcreteValue(author);
     this.version = new ReadOnlyConcreteValue(version);
     this.name    = new ReadOnlyConcreteValue(name);
 }
Ejemplo n.º 27
0
        public void Eval(EvalContext <TInput, TOutput> context)
        {
            var value = GetValue(context);

            foreach (var target in _targets)
            {
                target.Eval(context, value);
            }
        }
Ejemplo n.º 28
0
 public override void Execute(EvalContext ctx)
 {
     Operation.GetValue(ctx);
     //ignore the resulting abort
     if (ResetAbort)
     {
         ctx.ResetAbort();
     }
 }
Ejemplo n.º 29
0
        public object Has(FunctionArgument _args, EvalContext cal)
        {
            var args = _args.Arguments;

            OperationHelper.AssertArgsNumberThrowIf(this, 1, args);
            OperationHelper.AssertCertainValueThrowIf(this, args);
            var ov = cal.GetValue <IValue>(args[0]);

            return(this.Contains(ov));
        }
        public void Given_a_dynamic_expression_And_multiline_string_argument_When_invoked_Then_should_execute_evaluation(string argument, string expected)
        {
            var runtime = new Mock <IJSRuntime>();

            using (dynamic context = new EvalContext(runtime.Object))
            {
                (context as EvalContext).Expression = () => context.alert(argument);
            }
            Verify(runtime, $"alert({expected})");
        }
Ejemplo n.º 31
0
        public static TupleValue Split(FunctionArgument _args, EvalContext cal)
        {
            var args = _args.Arguments;

            OperationHelper.AssertArgsNumberThrowIf(null, 2, args);
            OperationHelper.AssertCertainValueThrowIf(null, args);
            var ov = cal.GetValue <StringValue>(args);

            return(new TupleValue(ov[0].Value.Split(ov[1].Value[0]).Select(x => new iExpr.Values.ConcreteValue(new StringValue(x)))));
        }
Ejemplo n.º 32
0
        public static number Cos(FunctionArgument _args, EvalContext cal)
        {
            var args = _args.Arguments;

            OperationHelper.AssertArgsNumberThrowIf(null, 1, args);
            OperationHelper.AssertCertainValueThrowIf(null, args);
            var ov = cal.GetValue <number>(args[0]);

            return(new number(System.Math.Cos(ov)));
        }
        private string GetConfigSaved()
        {
            using (dynamic context = new EvalContext(JSRuntime))
            {
                (context as EvalContext).Expression = () => context.ClientStorage.fetchConfig();
                var json = (context as EvalContext).Invoke <string>();

                return(string.IsNullOrEmpty(json) ? "d-none" : null);
            }
        }
Ejemplo n.º 34
0
        public static bool Exists(FunctionArgument _args, EvalContext cal)
        {
            var args = _args.Arguments;

            OperationHelper.AssertArgsNumberThrowIf(null, 1, args);
            OperationHelper.AssertCertainValueThrowIf(null, args);
            var ov = cal.GetValue <StringValue>(args)[0];

            return(File.Exists(ov));
        }
Ejemplo n.º 35
0
        public static FileEasyWriter OpenEasyWrite(FunctionArgument _args, EvalContext cal)
        {
            var args = _args.Arguments;

            OperationHelper.AssertArgsNumberThrowIf(null, 1, args);
            OperationHelper.AssertCertainValueThrowIf(null, args);
            var ov = cal.GetValue <StringValue>(args)[0];

            return(new FileEasyWriter(ov));
        }
Ejemplo n.º 36
0
 public EvalType Excecute(EvalContext context)
 {
     for (int i = 0; i < Statements.Count; i++)
     {
         if (Statements[i] is ReturnStatement)
             return (Statements[i] as ReturnStatement).Expression.Evaluate(context);
         else
             Statements[i].Execute(context);
     }
     return null;
 }
Ejemplo n.º 37
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     if (p.Length != 1)
         throw new Exception("Invalid number of parameters.");
     var en = p[0].Evaluate(context);
     if (en is NumberType)
         return new NumberType(1, UnitType.Empty());
     if (en is StringType)
         return new NumberType((en as StringType).Value.Length, UnitType.Empty());
     return new NumberType(((NumberListType)en).Length, UnitType.Empty());
 }
Ejemplo n.º 38
0
 public override void Execute(EvalContext context)
 {
     int lc = 0;
     for (var n = ((NumberType)FromExpr.Evaluate(context)).Copy(); n <= ((NumberType)ToExpr.Evaluate(context)); n = n + (NumberType)IncExpr.Evaluate(context))
     {
         context.VariableList[VarName] = n;
         StmtList.Excecute(context);
         lc++;
         if (lc > Globals.MAX_LOOP)
             throw new Exception("Max loops reached.");
     }
 }
Ejemplo n.º 39
0
        public override void Execute(EvalContext context)
        {
            int lc = 0;
            while ((NumberType)Conditional.Evaluate(context) != FALSE)
            {
                StmtList.Excecute(context);

                lc++;
                if (lc > Globals.MAX_LOOP)
                    throw new Exception("Max loops reached.");
            }
        }
Ejemplo n.º 40
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     //TODO: Check range.
     var inc = new NumberType("1", UnitType.Empty());
     var mv = p[0].Evaluate(context);
     var tv = new NumberType("1", UnitType.Empty());
     for (NumberType i = new NumberType("1", UnitType.Empty()); i.LessEql(mv); i += inc)
     {
         tv *= i;
     }
     return tv;
 }
Ejemplo n.º 41
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     if (p.Length != 1)
         throw new Exception("Invalid number of parameters.");
     var en = p[0].Evaluate(context);
     if (en is NumberType)
         return en;
     var nl = en as NumberListType;
     NumberType mag = new NumberType(0, UnitType.Empty());
     for (int i = 0; i < nl.Length; i++)
         mag += nl[i];
     return mag;
 }
Ejemplo n.º 42
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     if (p.Length != 4)
         throw new Exception("Invalid number of parameters.");
     NumberType sum = new NumberType("0", UnitType.Empty());
     NumberType inc = new NumberType("1", UnitType.Empty());
     //EvalContext c = new EvalContext(context, ((VariableNode)p[1]).Variable)
     for (NumberType i = (p[2].Evaluate(context) as NumberType).Copy(); i.LessEql(p[3].Evaluate(context)); i += inc)
     {
         context.VariableList[((VariableNode)p[1]).Variable] = i;
         sum += p[0].Evaluate(context) as NumberType;
     }
     return sum;
 }
Ejemplo n.º 43
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     if (p.Length != 1)
         throw new Exception("Invalid number of parameters.");
     var en = p[0].Evaluate(context);
     if (en is NumberType)
         return new NumberType(Math.Abs((en as NumberType).value), (en as NumberType).Unit);
     var nl = en as NumberListType;
     NumberType mag = new NumberType(0, UnitType.Empty());
     NumberType two = new NumberType(2, UnitType.Empty());
     NumberType oneOverTwo = new NumberType(.5, UnitType.Empty());
     for (int i = 0; i < nl.Length; i++)
         mag += nl[i] ^ two;
     return mag ^ oneOverTwo;
 }
Ejemplo n.º 44
0
 public override EvalType Evaluate(EvalContext context)
 {
     switch (Type)
     {
         case CompareType.Equal:
             return Left.Evaluate(context).Equals(Right.Evaluate(context)) ? NumberType.TRUE : NumberType.FALSE;
         case CompareType.NotEqual:
             return !Left.Evaluate(context).Equals(Right.Evaluate(context)) ? NumberType.TRUE : NumberType.FALSE;
         case CompareType.Less:
             return Left.Evaluate(context).Less(Right.Evaluate(context)) ? NumberType.TRUE : NumberType.FALSE;
         case CompareType.LessEqual:
             return Left.Evaluate(context).LessEql(Right.Evaluate(context)) ? NumberType.TRUE : NumberType.FALSE;
         case CompareType.Greater:
             return Left.Evaluate(context).Greater(Right.Evaluate(context)) ? NumberType.TRUE : NumberType.FALSE;
         case CompareType.GreaterEqual:
             return Left.Evaluate(context).GreaterEql(Right.Evaluate(context)) ? NumberType.TRUE : NumberType.FALSE;
     }
     throw new Exception("Invalid compare type.");
 }
Ejemplo n.º 45
0
 /// <summary>
 /// Evaluates the node.
 /// </summary>
 /// <param name="context">The context to use.</param>
 /// <returns></returns>
 public abstract EvalType Evaluate(EvalContext context);
Ejemplo n.º 46
0
 public override EvalType Evaluate(EvalContext context)
 {
     return context.VariableList[Variable];
 }
 public EvalContext CreateFreshEvalContext()
 {
     PackageGlobals.VSMultiInstanceInfo multi_instance_info;
     GetVSMultiInstanceInfo(out multi_instance_info);
     EvalContext eval_ctx = new EvalContext();
     SetVariableValuesFromIDEState(eval_ctx, multi_instance_info);
     return eval_ctx;
 }
Ejemplo n.º 48
0
 /// <summary>
 /// Evaluates the function to an EvalType.
 /// </summary>
 /// <param name="context">The context to use in evaluation.</param>
 /// <param name="p">The parameters.</param>
 /// <returns></returns>
 public virtual EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     throw new Exception("Function left undefined.");
 }
Ejemplo n.º 49
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     if (p.Length != 1)
         throw new Exception("Invalid number of parameters.");
     return p[0].Evaluate(context).Pow(new NumberType(".5", UnitType.Empty()));//new NumberType(Math.Sqrt(p[0].Evaluate(context).value));
 }
Ejemplo n.º 50
0
 public abstract void Execute(EvalContext context);
Ejemplo n.º 51
0
        void Evaluate(string expression_str, Expression expr, string label)
        {
            EvalContext ctx = new EvalContext();
            ctx.SetVariable("x", "XXX");
            ctx.SetVariable("y", "YYY");
            ctx.SetVariable("true", "SSS");
            SafeEvalContext safe_ctx = new SafeEvalContext(ctx);
            Value v = expr.Evaluate(safe_ctx);
            Console.WriteLine("{0}: {1}", label, v.ToString());

            List<Variable> unresolved_variables = expr.CollectUnresolvedVariables(ctx);
            if (unresolved_variables.Count > 0)
            {
                Console.WriteLine("Unresolved variables in the expression: {0}", unresolved_variables.Count);
                Console.WriteLine(expression_str);
                foreach (Variable var in unresolved_variables)
                {
                    Console.WriteLine(new string(' ', var.Position) + "^");
                    Console.WriteLine(new string(' ', var.Position) + var.Name);
                }
            }
        }
Ejemplo n.º 52
0
 public override void Execute(EvalContext context)
 {
     context.VariableList[Variable] = context.VariableList[Variable].Div(Expression.Evaluate(context));
 }
Ejemplo n.º 53
0
        public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
        {
            if (p.Length != 2)
                throw new Exception("Invalid number of parameters.");
            var ie = p[1].Evaluate(context);
            if (!(ie is NumberType))
                throw new Exception("Index must be a number.");
            var index = ie as NumberType;
            var ti = p[0].Evaluate(context);
            if (ti is NumberType)
            {
                if (index.value == 1)
                    return ti;
                throw new Exception("Index out of range.");
            }
            if (ti is NumberListType)
            {
                var i = (int)Math.Floor(index.value);
                return (ti as NumberListType)[i - 1];
            }
            if (ti is StringType)
            {
                var i = (int)Math.Floor(index.value);
                return new StringType((ti as StringType).Value[i].ToString());
            }

            throw new Exception("Invalid type to index.");
        }
Ejemplo n.º 54
0
	public EvalContext eval() {
		EvalContext _localctx = new EvalContext(Context, State);
		EnterRule(_localctx, 0, RULE_eval);
		try {
			EnterOuterAlt(_localctx, 1);
			{
			State = 44; exp(0);
			State = 45; Match(Eof);
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			ErrorHandler.ReportError(this, re);
			ErrorHandler.Recover(this, re);
		}
		finally {
			ExitRule();
		}
		return _localctx;
	}
Ejemplo n.º 55
0
        public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
        {
            if (p.Length != 2)
                throw new Exception("Invalid number of parameters.");
            var left = p[0].Evaluate(context) as NumberListType;
            var right = p[1].Evaluate(context) as NumberListType;

            if (left.Length != 3 || right.Length != 3)
                throw new Exception("NumberList must be length 3.");

            return new NumberListType(
                left[1] * right[2] - left[2] * right[1],
                left[2] * right[0] - left[0] * right[2],
                left[0] * right[1] - left[1] * right[0]);
        }
 public override void Execute(EvalContext context)
 {
     context.FunctionList.Set(new StatementFunction(FctName, ParamNames, StatementList));
 }
Ejemplo n.º 57
0
 public override EvalType Evaluate(EvalContext context)
 {
     return Left.Evaluate(context).Div(Right.Evaluate(context));
 }
Ejemplo n.º 58
0
        public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
        {
            if (p.Length != 2)
                throw new Exception("Invalid number of parameters.");
            var left = p[0].Evaluate(context) as NumberListType;
            var right = p[1].Evaluate(context) as NumberListType;

            return ls.Evaluate(context, new ListNode((left * right).Numbers));
        }
Ejemplo n.º 59
0
 public override EvalType Evaluate(EvalContext context, params ExprNode[] p)
 {
     var c = new EvalContext(context, ParamNames, p);
     return StmtList.Excecute(c);
 }
Ejemplo n.º 60
0
 public override EvalType Evaluate(EvalContext context)
 {
     return context.FunctionList[Function].Evaluate(context, Parameters);
 }