Esempio n. 1
0
        public override void execute()
        {
            setContext();
            int context_integrity_check = Context.getStatusStackCount();

            Debugging.print("Assignment: ", _var_name, " = ", _var_value.expr);

            // set the new value
            Variable variable;

            try
            {
                variable = Expression.parse(_var_name);
            }
            catch (AquilaExceptions.NameError)
            {
                // implicit declaration
                if (!Global.getSetting("implicit declaration in assignment"))
                {
                    throw;
                }
                Debugging.print("Implicit declaration in Assignment!");
                Declaration decl = new Declaration(line_index, _var_name.Substring(1), _var_value); // in the Assignment constructor: already check if _var_name != ""
                decl.execute();

                // update things 'n stuff
                Global.onElementaryInstruction();

                // reset Context
                // Smooth Context
                Context.resetUntilCountReached(context_integrity_check);
                Context.reset();

                return;
            }

            // parsing new value
            Variable val = _var_value.evaluate();

            Debugging.print("assigning " + _var_name + " with expr " + _var_value.expr + " with value " + val + " (2nd value assigned: " + val.assigned + ") and type: " + val.getTypeString());
            // assert the new is not an unassigned (only declared) variable
            val.assertAssignment();

            if (variable.hasSameParent(val))
            {
                variable.setValue(val);
            }
            else
            {
                throw new AquilaExceptions.InvalidTypeError("You cannot change the type of your variables (" + variable.getTypeString() + " -> " + val.getTypeString() + "). This will never be supported because it would be considered bad style.");
            }

            // update things 'n stuff
            Global.onElementaryInstruction();

            // reset Context
            // Smooth Context
            Context.resetUntilCountReached(context_integrity_check);
            Context.reset();
        }
Esempio n. 2
0
        /// <summary>
        /// Default function
        /// </summary>
        /// <para>
        /// Swaps the elements at index a and b in a list
        /// </para>
        /// <param name="list_expr"> the target <see cref="DynamicList"/> (as an <see cref="Expression"/>)</param>
        /// <param name="a_expr"> index of the first element</param>
        /// <param name="b_expr"> index of the second element</param>
        /// <returns> <see cref="NullVar"/> (equivalent of null/void)</returns>
        private static NullVar swapFunction(Expression list_expr, Expression a_expr, Expression b_expr)
        {
            // evaluate every expression
            DynamicList list = list_expr.evaluate() as DynamicList;
            Integer     a    = a_expr.evaluate() as Integer;
            Integer     b    = b_expr.evaluate() as Integer;

            // check indexes
            list.validateIndex(a);
            list.validateIndex(b);
            // extract both values
            Variable var_a = list.atIndex(a);
            Variable var_b = list.atIndex(b);

            // freeze the context
            Context.freeze();
            // change a
            list.removeValue(a);
            list.insertValue(var_b, a);
            // change b
            list.removeValue(b);
            list.insertValue(var_a, b);
            // unfreeze the context
            Context.unfreeze();
            // update manually (void)
            if (list.isTraced())
            {
                list.tracer.update(new Event(
                                       new Alteration("swap", list, list.getRawValue(), new dynamic[] { a.getRawValue(), b.getRawValue() })));
            }

            return(new NullVar());
        }
Esempio n. 3
0
        /// <summary>
        /// Remove a <see cref="Variable"/> and its references
        /// </summary>
        /// <param name="expr"> <see cref="Expression"/> resulting in a <see cref="Variable"/></param>
        /// <returns> <see cref="NullVar"/> (equivalent of null/void)</returns>
        private static NullVar deleteVarFunction(Expression expr)
        {
            // evaluate every expression
            Variable variable = expr.evaluate();
            string   var_name = variable.getName();

            // delete var
            Debugging.assert(Global.variableExistsInCurrentScope(var_name),
                             new AquilaExceptions.NameError($"Variable name \"{var_name}\" does not exist in the current Context"));
            // remove the Tracer if is traced
            if (variable.isTraced())
            {
                // remove from the usable variables
                Global.usable_variables.Remove(var_name);
                // Deletion Alteration
                var alter = new Alteration("delete_var", variable, null, new dynamic[] {});
                // Update the tracer with the death event
                variable.tracer.update(new Event(alter));
                // Remove the tracer
                Global.var_tracers.Remove(variable.tracer);
            }
            // remove from the dict
            Global.getCurrentDict().Remove(var_name);

            return(new NullVar());
        }
Esempio n. 4
0
        public override void execute()
        {
            setContext();
            int context_integrity_check = Context.getStatusStackCount();

            if (((BooleanVar)_condition.evaluate()).getValue())
            {
                foreach (Instruction instr in instructions)
                {
                    instr.execute();
                }
            }
            else
            {
                foreach (Instruction instr in _else_instructions)
                {
                    instr.execute();
                }
            }

            // Smooth Context
            Context.resetUntilCountReached(context_integrity_check);
            Context.reset();
            Global.resetLocalContextScope();
        }
Esempio n. 5
0
        /// <summary>
        /// Default function
        /// <para>
        /// Calculates the length of a <see cref="DynamicList"/> and returns it as an <see cref="Integer"/>
        /// </para>
        /// </summary>
        /// <param name="list_expr"> The target <see cref="DynamicList"/></param>
        /// <returns> <see cref="Integer"/> which has the list's length as value</returns>
        private static Variable lengthFunction(Expression list_expr)
        {
            // evaluate every expression
            DynamicList list = list_expr.evaluate() as DynamicList;

            // length
            return(list.length());
        }
Esempio n. 6
0
        /// <summary>
        /// Prints the value of an <see cref="Expression"/> to the stdout. Does add a return '\n' symbol
        /// </summary>
        /// <param name="value"> Expression you want to print (the evaluated value)</param>
        /// <returns> <see cref="NullVar"/> (equivalent of null/void)</returns>
        private static NullVar printValEndlFunction(Expression value)
        {
            Debugging.print("begin printing to console: (" + value.expr + ")");
            Global.stdoutWriteLine(value.evaluate().ToString());
            Debugging.print("end printing to console");

            return(new NullVar());
        }
Esempio n. 7
0
        protected bool test()
        {
            Variable cond = _condition.evaluate();

            Debugging.assert(cond is BooleanVar); // TypeError
            bool bool_cond = cond.getValue();

            return(bool_cond);
        }
Esempio n. 8
0
        /// <summary>
        /// Execute the Algorithm/Function. <see cref="Instruction"/> by <see cref="Instruction"/>,
        /// until the list of instructions is exhausted and we can return the <see cref="_return_value"/>,
        /// using <see cref="Expression.parse"/> on it (it is an <see cref="Expression"/>)
        /// </summary>
        /// <returns> The evaluated <see cref="_return_value"/> after all the <see cref="_instructions"/> have been executed</returns>
        /// <exception cref="AquilaExceptions.RuntimeError"> ReturnValueException is null</exception>
        public Variable run()
        {
            try
            {
                // Algorithm start
                setStartContext();

                foreach (Instruction instr in _instructions)
                {
                    try
                    {
                        instr.execute();
                    }
                    catch (System.Reflection.TargetInvocationException out_exception)
                    {
                        // normal TargetInvocationException
                        if (!(out_exception.InnerException is AquilaControlFlowExceptions.ReturnValueException))
                        {
                            throw;
                        }
                        // casted ReturnValueException
                        AquilaControlFlowExceptions.ReturnValueException exception =
                            (AquilaControlFlowExceptions.ReturnValueException)out_exception.InnerException;

                        if (exception == null)
                        {
                            throw new AquilaExceptions.RuntimeError(
                                      "The inner ReturnValueException in the TargetInvocationException is null"); // something went wrong
                        }
                        _return_value = new Expression(exception.getExprStr());
                        Context.reset();
                        return(_return_value.evaluate());
                    }
                }

                // no resetting here. algorithm finished
                setEndContext();

                return(new NullVar()); // NoReturnCallWarning
            }
            catch (StopInterpreterException)
            {
                Global.stdoutWriteLine("Stopped Interpreter");
                Global.resetEnv();

                return(new NullVar());
            }
            catch (Exception e)
            {
                Global.stdoutWriteLine(e.ToString());

                return(new NullVar());
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Run the Algorithm as a test run. <see cref="Instruction"/> by <see cref="Instruction"/>,
        /// until the list of instructions is exhausted and we can return the <see cref="_return_value"/>,
        /// using <see cref="Expression.parse"/> on it (it is an <see cref="Expression"/>)
        /// </summary>
        /// <returns> The evaluated <see cref="_return_value"/> after all the <see cref="_instructions"/> have been executed</returns>
        /// <exception cref="AquilaExceptions.RuntimeError"> ReturnValueException is null</exception>
        public Variable testRun()
        {
            initTestMode();
            try
            {
                // Run start
                Debugging.print("Starting Algorithm test run");
                setStartContext();

                foreach (Instruction instr in _instructions)
                {
                    try
                    {
                        instr.execute();
                    }
                    catch (System.Reflection.TargetInvocationException out_exception)
                    {
                        // normal TargetInvocationException
                        if (!(out_exception.InnerException is AquilaControlFlowExceptions.ReturnValueException))
                        {
                            throw;
                        }
                        // casted ReturnValueException
                        AquilaControlFlowExceptions.ReturnValueException exception =
                            (AquilaControlFlowExceptions.ReturnValueException)out_exception.InnerException;

                        if (exception == null)
                        {
                            throw new AquilaExceptions.RuntimeError("The inner ReturnValueException in the TargetInvocationException is null");                    // something went wrong
                        }
                        _return_value = new Expression(exception.getExprStr());
                        Context.reset();
                        Debugging.print("Ended Algorithm test run with return value");
                        Global.setSetting("test mode", false);
                        return(_return_value.evaluate());
                    }
                }

                // no resetting here. algorithm finished
                setEndContext();

                Debugging.print("Ended Algorithm test run with no return");
                Global.setSetting("test mode", false);
                return(new NullVar()); // NoReturnCallWarning
            }
            catch (Exception e)
            {
                Global.stdoutWriteLine(e.ToString());

                Debugging.print("Ended Algorithm test run with exception");
                Global.setSetting("test mode", false);
                return(new NullVar());
            }
        }
Esempio n. 10
0
        // ReSharper disable once InconsistentNaming
        /// <summary>
        /// Convert an <see cref="Integer"/> into and <see cref="FloatVar"/>
        /// </summary>
        /// <param name="expr"> <see cref="Expression"/> resulting in an <see cref="int"/></param>
        /// <returns> The new <see cref="FloatVar"/></returns>
        /// <exception cref="AquilaExceptions.InvalidTypeError"> The value is not an <see cref="int"/></exception>
        private static Variable int2floatFunction(Expression expr)
        {
            dynamic value = expr.evaluate().getValue();

            if (!(value is int))
            {
                throw new AquilaExceptions.InvalidTypeError($"Type should be int but is {value.GetType()}");
            }
            // ReSharper disable once PossibleInvalidCastException
            return(new FloatVar((float)value));
        }
Esempio n. 11
0
        /// <summary>
        /// Default function
        /// </summary>
        /// <para>
        /// Creates a copy of a <see cref="DynamicList"/>
        /// </para>
        /// <param name="list_expr"> the target <see cref="DynamicList"/></param>
        /// <returns> A new <see cref="DynamicList"/>. It's values are the same as the target list</returns>
        private static Variable copyListFunction(Expression list_expr)
        {
            // evaluate every expression
            Variable var_ = list_expr.evaluate();

            Debugging.assert(var_ is DynamicList); // TypeError
            DynamicList list = var_ as DynamicList;
            // copy list
            var raw = new List <dynamic>(list.getRawValue());

            return(Variable.fromRawValue(raw));
        }
Esempio n. 12
0
        /// <summary>
        /// Append a value to the end of a list
        /// </summary>
        /// <param name="list_expr"> The list</param>
        /// <param name="value_expr"> The value</param>
        /// <returns> <see cref="NullVar"/> (equivalent of null/void)</returns>
        private static NullVar appendValue(Expression list_expr, Expression value_expr)
        {
            // extract list
            Variable list_var = list_expr.evaluate();

            Debugging.assert(list_var is DynamicList); // TypeError
            DynamicList list = list_var as DynamicList;
            // index
            Integer    index      = list.length();
            Expression index_expr = new Expression(index.getValue().ToString()); // this should definitely be ok

            // insert
            return(insertValueAt(list_expr, index_expr, value_expr));
        }
Esempio n. 13
0
        /// <summary>
        /// Changes the tracing mode of a variable. If it is not traced, trace it beforehand
        /// </summary>
        /// <param name="var_expr"> Traced variable</param>
        /// <param name="mode_expr"> Mode (expresion content as string)</param>
        /// <returns> <see cref="NullVar"/> (equivalent of null/void)</returns>
        private static NullVar traceModeFunction(Expression var_expr, Expression mode_expr)
        {
            Tracer.printTrace($"Tracing \"{var_expr.expr}\" with mode \"{mode_expr.expr}\"");
            // get the variable
            Variable var = var_expr.evaluate();

            // change the tracing mode (using in Alteration.mode)
            var.trace_mode = mode_expr.expr;
            // trace it if not already traced
            if (!var.isTraced())
            {
                var.startTracing();
            }


            return(new NullVar());
        }
Esempio n. 14
0
        /// <summary>
        /// Delete the nth value of a list
        /// </summary>
        /// <param name="list_expr"> expression resulting in a <see cref="DynamicList"/> variable</param>
        /// <param name="index_expr"> expression resulting in a <see cref="Integer"/> variable</param>
        /// <returns> <see cref="NullVar"/> (equivalent of null/void)</returns>
        private static NullVar deleteValueAt(Expression list_expr, Expression index_expr)
        {
            // extract list
            Variable list_var = list_expr.evaluate();

            Debugging.assert(list_var is DynamicList); // TypeError
            DynamicList list = list_var as DynamicList;
            // extract index
            Variable index_var = index_expr.evaluate();

            Debugging.assert(index_var is Integer); // TypeError
            Integer index = index_var as Integer;

            // delete
            list.removeValue(index);
            return(new NullVar());
        }
Esempio n. 15
0
        /// <summary>
        /// Calculate the square root of a float
        /// </summary>
        /// <param name="expr"> The float</param>
        /// <returns> The sqrt of the input float</returns>
        private static Variable sqrtFunction(Expression expr)
        {
            Variable v = expr.evaluate();

            if (v is Integer)
            {
                int raw_int = v.getValue();
                // ReSharper disable once RedundantCast
                float raw_float = (float)raw_int;
                v = new FloatVar(raw_float);
            }
            Debugging.assert(v is FloatVar);
            double real      = (double)v.getValue();
            float  real_sqrt = (float)Math.Sqrt(real);

            return(new FloatVar(real_sqrt));
        }
Esempio n. 16
0
        // ReSharper disable once InconsistentNaming
        /// <summary>
        /// Convert a <see cref="FloatVar"/> into and <see cref="Integer"/>
        /// </summary>
        /// <param name="expr"> <see cref="Expression"/> resulting in a <see cref="float"/> value</param>
        /// <returns> The new <see cref="Integer"/></returns>
        /// <exception cref="AquilaExceptions.InvalidTypeError"> The value is not a <see cref="float"/> or the cast failed internally</exception>
        private static Variable float2intFunction(Expression expr)
        {
            dynamic value = expr.evaluate().getValue();

            if (!(value is float))
            {
                throw new AquilaExceptions.InvalidTypeError($"Type should be float but is {value.GetType()}");
            }
            try
            {
                // ReSharper disable once PossibleInvalidCastException
                return(new Integer((int)value));
            }
            catch (InvalidCastException)
            {
                throw new AquilaExceptions.InvalidTypeError("The cast did not succeed (float to int)"); //! RuntimeError instead ?
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Insert the given value in the list at the given index
        /// </summary>
        /// <param name="list_expr"> The list</param>
        /// <param name="index_expr"> The index</param>
        /// <param name="value_expr"> The value</param>
        /// <returns> <see cref="NullVar"/> (equivalent of null/void)</returns>
        private static NullVar insertValueAt(Expression list_expr, Expression index_expr, Expression value_expr)
        {
            // extract list
            Variable list_var = list_expr.evaluate();

            Debugging.assert(list_var is DynamicList); // TypeError
            DynamicList list = list_var as DynamicList;
            // extract index
            Variable index_var = index_expr.evaluate();

            Debugging.assert(index_var is Integer);
            Integer index = index_var as Integer;
            // extract var
            Variable var_ = value_expr.evaluate();

            // insert
            list.insertValue(var_, index);
            return(new NullVar());
        }
Esempio n. 18
0
        /// <summary>
        /// Call the function with input parameters (args)
        /// </summary>
        /// <param name="args"> The variables defining the new Main Context Stack</param>
        /// <returns> The return value of the function</returns>
        public Variable callFunction(Dictionary <string, Variable> args)
        {
            initialize(args);

            Debugging.assert(_in_function_scope);
            foreach (Instruction instruction in _instructions)
            {
                try
                {
                    instruction.execute(); // return here (not continue, nor break)
                }
                catch (System.Reflection.TargetInvocationException out_exception)
                {
                    if (!(out_exception.InnerException is AquilaControlFlowExceptions.ReturnValueException return_value_exception))
                    {
                        throw;
                    }
                    Debugging.print("ReturnValueException was thrown");
                    string     return_value_string     = return_value_exception.getExprStr();
                    Expression return_value_expression = new Expression(return_value_string);
                    Variable   return_value            = return_value_expression.evaluate();

                    if (_type != StringConstants.Types.AUTO_TYPE && _type != StringConstants.Types.NULL_TYPE)
                    {
                        Debugging.assert(return_value.getTypeString() == _type);
                    }
                    restore();
                    return(return_value);
                }
            }
            Debugging.print("no ReturnValueException thrown. returning NullVar");

            if (_type != StringConstants.Types.AUTO_TYPE)
            {
                Debugging.assert(_type == StringConstants.Types.NULL_TYPE);
            }
            restore();
            return(new NullVar());
        }
Esempio n. 19
0
        /// <summary>
        /// Get the value at the index in a list
        /// </summary>
        /// <param name="list_expr"> The list</param>
        /// <param name="index_list_expr"> The index</param>
        /// <returns></returns>
        private static Variable listAtFunction(Expression list_expr, Expression index_list_expr)
        {
            // extract list
            Variable list_var = list_expr.evaluate();

            Debugging.assert(list_var is DynamicList); // TypeError
            DynamicList list = list_var as DynamicList;
            // extract index
            Variable index_list_var = index_list_expr.evaluate();

            Debugging.assert(index_list_var is DynamicList); // TypeError
            DynamicList index_list = index_list_var as DynamicList;

            /*// test run ?
             * if (Global.getSetting("test mode"))
             * {
             *  // function to add to index dict
             *  void addToIndexList(string var_name)
             *  {
             *      if (var_name == "") return;
             *      var index_var_name_list = (List<string>) Global.test_values["index values"];
             *      // variable name already in index dict ?
             *      if (index_var_name_list.Contains(var_name)) return;
             *      // add to index dict
             *      index_var_name_list.Add(var_name);
             *  }
             * }*/
            // access at index
            Variable result = list.atIndexList(index_list);

            // trace list
            if (!list_var.isTraced())
            {
                return(result);
            }
            Tracer.printTrace("list_at last event: " + list_var.tracer.peekEvent());
            handleValueFunctionTracing("list_at", list,
                                       new dynamic[] { index_list.getValue() });
            // trace index
            //Tracer.printTrace("tmp list at ", index_list.toString());

            /*var index_list_var_value = index_list_var.getValue();
             * for (int i = 0; i < index_list_var_value.Count; i++)
             * {
             *  Variable index_var = index_list_var_value[i];
             *  var numeric_index = (NumericalValue) index_var;
             *  NumericalValue source = numeric_index.getTracedSource();
             *  if (source == null)
             *  {
             *      Tracer.printTrace("tmp index without source var");
             *      numeric_index.setName($"comp /{i}/");
             *      list.tracer.update(new Event(new Alteration("tmp_list_at", numeric_index,
             *          numeric_index.getValue(), new[] {list.getName(), index_list.getValue()},
             *          mode:"index")));
             *      continue;
             *  }
             *
             *  Tracer.printTrace("Traced source var: " + source.getName());
             *  numeric_index.setName($"comp /{i}/");
             *  list.tracer.update(new Event(new Alteration("tmp_list_at", numeric_index,
             *  numeric_index.getValue(), new[] {list.getName(), index_list.getValue()},
             *      mode:"index")));
             * }*/

            return(result);
        }
Esempio n. 20
0
        public override void execute()
        {
            setContext();

            // get variable value
            Variable variable_value = _var_expr.evaluate();

            // is the value assigned ? (only relevant if other variable)
            variable_value.assertAssignment();
            Variable variable = Variable.fromRawValue(variable_value.getRawValue());

            // keep track of source vars -> should do something generic for lots of attributes ...
            if (variable is NumericalValue)
            {
                ((NumericalValue)variable).source_vars = new Dictionary <string, NumericalValue>(((NumericalValue)variable_value).source_vars);
            }
            variable.setName(_var_name);
            // explicit typing
            if (_var_type != StringConstants.Types.AUTO_TYPE)
            {
                Debugging.print("checking variable explicit type");
                Expression default_value = Global.default_values_by_var_type[_var_type];
                Debugging.assert(variable_value.hasSameParent(default_value.evaluate()));   // TypeException
            }
            // constant
            if (_constant)
            {
                if (variable_value.isConst())
                {
                    variable.setConst();
                }
                else
                {
                    throw new AquilaExceptions.InvalidVariableClassifierException(
                              "The \"const\" cannot be used when assigning to a non-const value");
                }
            }
            // actually declare it to its value
            if (_global)
            {
                Global.addGlobalVariable(_var_name, variable);
            }
            else
            {
                Global.getCurrentDict()[_var_name] = variable; // overwriting is mandatory
                Debugging.print("variable exists ", Global.variableExistsInCurrentScope(_var_name));
                if (_assignment)
                {
                    variable.assign();              // should not need this, but doing anyway
                }
                else
                {
                    variable.assigned = false;
                }
            }
            Debugging.print("finished declaration with value assignment: ", variable.assigned);

            // automatic tracing ?
            if (_assignment && Global.getSetting("auto trace"))
            {
                Debugging.print("Tracing variable: \"auto trace\" setting set to true");
                // Does NOT work by simply doing "variable.startTracing()", and idk why
                Tracing tracing_instr = new RawInstruction($"trace ${_var_name}", line_index).toInstr() as Tracing;
                //Tracing tracing_instr = new Tracing(line_index, new List<Expression>{_var_expr}); // <- does not work either :(
                tracing_instr.execute();
            }

            // update things 'n stuff
            Global.onElementaryInstruction();

            // reset Context
            Context.reset();
        }