Exemplo n.º 1
0
 public GraphicalList(string name, Parser.DynamicList list, Vector3 dimensions, Vector3 position, int representation)
 {
     this.name           = name;
     this.list           = list;
     this.dimensions     = dimensions;
     this.position       = position;
     this.representation = representation;
 }
Exemplo n.º 2
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());
        }
Exemplo n.º 3
0
 /// <summary>
 /// Returns a <see cref="Variable"/> instance, corresponding to the value of "o"
 /// </summary>
 /// <param name="o"> value to interpret as a <see cref="Variable"/></param>
 /// <returns> corresponding <see cref="Variable"/></returns>
 /// <exception cref="AquilaExceptions.RuntimeError"> Raw type not supported</exception>
 public static Variable fromRawValue(dynamic o)
 {
     if (o is int)
     {
         return(new Integer(o));
     }
     if (o is float)
     {
         return(new FloatVar(o));
     }
     if (o is bool)
     {
         return(new BooleanVar(o));
     }
     if (o is List <dynamic> )
     {
         return(new DynamicList(DynamicList.valueFromRawList(o)));
     }
     throw new AquilaExceptions.RuntimeError($"Raw type \"{o.GetType()}\" not supported");
 }
Exemplo n.º 4
0
    public void Start()
    {
        GraphicalList graphList = gameObject.AddComponent <GraphicalList>();

        List <int> testList = new List <int>()
        {
            5, 4, 3, 2, 1
        };

        Parser.DynamicList list_test = Parser.VariableUtils.createDynamicList(testList);

        (list_test.atIndex(new Parser.Integer(0))).setName("int1");
        (list_test.atIndex(new Parser.Integer(1))).setName("int2");
        (list_test.atIndex(new Parser.Integer(2))).setName("int3");
        (list_test.atIndex(new Parser.Integer(3))).setName("int4");
        (list_test.atIndex(new Parser.Integer(4))).setName("int5");

        Dictionary <string, GameObject> list_dict_test = new Dictionary <string, GameObject>();

        graphList.list_dict = list_dict_test;
        graphList.list      = list_test;

        graphList.drawObject(); // To update the dictionary

        /* INSERT DEMO
         * Parser.Integer insert_numb = new Parser.Integer(5);
         * insert_numb.setName("int6");
         *
         * graphList.insert(new Parser.Integer(2), insert_numb); // tester avec les index qui se trouvent a l'extremite
         */

        /* REMOVE DEMO
         * graphList.remove(new Parser.Integer(1));
         */

        /* SWAP DEMO
         * graphList.swap(new Parser.Integer(1), new Parser.Integer(4));
         */

        /*float t = Time.time;
         *
         * while (t < Time.time - 2)
         * {
         *
         * }*/

        //Thread.Sleep(1000);

        //Debug.Log("Animation finished!");


        StartCoroutine(testTimeDelay());

        /* BUBBLE SORT DEMO
         * StartCoroutine(bubbleSort());
         */

        IEnumerator testTimeDelay()
        {
            graphList.swap(new Parser.Integer(1), new Parser.Integer(4));
            yield return(new WaitForSeconds(10f));

            graphList.remove(new Parser.Integer(1));
        }

        IEnumerator bubbleSort()
        {
            for (int j = 0; j <= list_test.length().getValue() - 2; j++)
            {
                for (int i = 0; i <= list_test.length().getValue() - 2; i++)
                {
                    if (list_test.atIndex(new Parser.Integer(i)).getValue() > list_test.atIndex(new Parser.Integer(i + 1)).getValue())
                    {
                        graphList.swap(new Parser.Integer(i), new Parser.Integer(i + 1));
                        yield return(new WaitForSeconds(2.5f));
                    }
                }
            }
        }

        /*IEnumerator TimeDelayFunction()
         * {
         *
         *  for (int j = 0; j <= list_test.length().getValue() - 2; j++)
         *  {
         *      for (int i = 0; i <= list_test.length().getValue() - 2; i++)
         *      {
         *          if (list_test.atIndex(new Parser.Integer(i)).getValue() > list_test.atIndex(new Parser.Integer(i + 1)).getValue())
         *          {
         *              graphList.swap(new Parser.Integer(i), new Parser.Integer(i + 1));
         *              yield return new WaitForSeconds(1f);
         *          }
         *      }
         *  }
         *  /*
         *  int smallest;
         *
         *  for (int i = 0; i < list_test.length().getValue() - 1; i++)
         *  {
         *      smallest = i;
         *      for (int j = i + 1; j < list_test.length().getValue(); j++)
         *      {
         *          if (list_test.atIndex(new Parser.Integer(j)).getValue() < list_test.atIndex(new Parser.Integer(smallest)).getValue())
         *          {
         *              smallest = j;
         *          }
         *      }
         *
         *      graphList.swap(new Parser.Integer(smallest), new Parser.Integer(i));
         *      yield return new WaitForSeconds(1f);
         *  }
         *
         *  Debug.Log("List is sorted !");
         * }
         */
    }
Exemplo n.º 5
0
        /// <summary>
        /// Takes an arithmetical or logical expression and returns the corresponding variable
        /// <para/>Examples:
        /// <para/>* "5 + 6" : returns Integer (11)
        /// <para/>* "$l[5 * (1 - $i)]" : returns the elements at index 5*(1-i) in the list "l"
        /// <para/>* "$l" : returns the list variable l
        /// </summary>
        /// <param name="expr_string"> expression to parse</param>
        /// <returns> Variable object containing the value of the evaluated expression value (at time t)</returns>
        public static Variable parse(string expr_string)
        {
            /* Order of operations:
             * checking expression string integrity
             * raw dynamic list
             * clean redundant symbols
             * raw integer value
             * raw boolean value (not done yet)
             * raw float value (not done yet)
             * mathematical or logical operation
             * function call
             * variable access (e.g. $name or in list by index)
             */

            // clean expression
            expr_string = StringUtils.normalizeWhiteSpaces(expr_string);
            Exception invalid_expr_exception =
                new AquilaExceptions.SyntaxExceptions.SyntaxError($"The sentence \"{expr_string}\" is not understood");

            Debugging.print("input expression: " + expr_string);

            // matching parentheses & brackets
            Debugging.assert(StringUtils.checkMatchingDelimiters(expr_string, '(', ')'),
                             new AquilaExceptions.SyntaxExceptions.UnclosedTagError("Unclosed parenthesis"));
            Debugging.assert(StringUtils.checkMatchingDelimiters(expr_string, '[', ']'),
                             new AquilaExceptions.SyntaxExceptions.UnclosedTagError("Unclosed bracket"));
            expr_string = StringUtils.removeRedundantMatchingDelimiters(expr_string, '(', ')');

            Debugging.print("dynamic list ?");
            // dynamic list
            {
                DynamicList list = StringUtils.parseListExpression(expr_string);
                if (list != null)
                {
                    return(list);
                }
            }

            // now that lists are over, check for redundant brackets
            expr_string = StringUtils.removeRedundantMatchingDelimiters(expr_string, '[', ']');

            if (expr_string == null)
            {
                throw new AquilaExceptions.SyntaxExceptions.SyntaxError("Null Expression");
            }

            Debugging.assert(expr_string != ""); //! NullValue here, instead of Exception

            Debugging.print("int ?");
            // try evaluating expression as an integer
            if (int.TryParse(expr_string, out int int_value))
            {
                return(new Integer(int_value, true));
            }

            Debugging.print("bool ?");
            // try evaluating expression as a boolean
            if (expr_string == "true")
            {
                return(new BooleanVar(true, true));
            }

            if (expr_string == "false")
            {
                return(new BooleanVar(false, true));
            }

            Debugging.print("float ?");
            // try evaluating expression as float
            if (!expr_string.Contains(' '))
            {
                if (float.TryParse(expr_string, out float float_value))
                {
                    Debugging.print("french/classic float");
                    return(new FloatVar(float_value, true));
                }

                if (float.TryParse(expr_string.Replace('.', ','), out float_value))
                {
                    Debugging.print("normalized float");
                    return(new FloatVar(float_value, true));
                }

                if (expr_string.EndsWith("f") &&
                    float.TryParse(expr_string.Substring(0, expr_string.Length - 1), out float_value))
                {
                    Debugging.print("f-float");
                    return(new FloatVar(float_value, true));
                }

                if (expr_string.EndsWith("f") &&
                    float.TryParse(expr_string.Replace('.', ',').Substring(0, expr_string.Length - 1), out float_value))
                {
                    Debugging.print("f-float");
                    return(new FloatVar(float_value, true));
                }
            }

            Debugging.print("checking for negative expression");
            // special step: check for -(expr)
            if (expr_string.StartsWith("-"))
            {
                Debugging.print("evaluating expression without \"-\" sign");
                string   opposite_sign_expr = expr_string.Substring(1); // take away the "-"
                Variable opposite_sign_var  = parse(opposite_sign_expr);
                Debugging.print("evaluated expression without the \"-\" symbol is of type ", opposite_sign_var.getTypeString(), " and value ", opposite_sign_var.getValue());

                // ReSharper disable once ConvertIfStatementToSwitchExpression
                if (opposite_sign_var is Integer)
                {
                    return(new Integer(-opposite_sign_var.getValue()));
                }
                if (opposite_sign_var is FloatVar)
                {
                    return(new FloatVar(-opposite_sign_var.getValue()));
                }
                throw new AquilaExceptions.InvalidTypeError($"Cannot cast \"-\" on a {opposite_sign_var.getTypeString()} variable");
            }

            Debugging.print("AL operations ?");
            // mathematical and logical operations
            foreach (char op in Global.al_operations)
            {
                // ReSharper disable once PossibleNullReferenceException
                if (expr_string.Contains(op.ToString()))
                {
                    string simplified = StringUtils.simplifyExpr(expr_string, new [] { op }); // only look for specific delimiter
                    // more than one simplified expression ?
                    if (simplified.Split(op).Length > 1)
                    {
                        Debugging.print("operation ", expr_string, " and op: ", op);
                        List <string> splitted_str =
                            StringUtils.splitStringKeepingStructureIntegrity(expr_string, op, Global.base_delimiters);

                        // custom: logic operations laziness here (tmp) //!
                        Variable variable = parse(splitted_str[0]);
                        if (Global.getSetting("lazy logic") && variable is BooleanVar)
                        {
                            Debugging.print("lazy logic evaluation");
                            bool first = (variable as BooleanVar).getValue();
                            switch (op)
                            {
                            case '|':    // when first:
                                if (first)
                                {
                                    return(new BooleanVar(true, true));
                                }
                                break;

                            case '&':    // when !first:
                                if (!first)
                                {
                                    return(new BooleanVar(false, true));
                                }
                                break;
                            }
                        }

                        var splitted_var = new List <Variable> {
                            variable
                        };
                        splitted_var.AddRange(splitted_str.GetRange(1, splitted_str.Count - 1).Select(parse));

                        // reduce the list to a list of one element
                        // e.g. expr1 + expr2 + expr3 => final_expr
                        while (splitted_var.Count > 1)
                        {
                            // merge the two first expressions
                            Variable expr1_var = splitted_var[0];
                            Variable expr2_var = splitted_var[1];
                            Variable result    = applyOperator(expr1_var, expr2_var, op);
                            // merge result of 0 and 1
                            splitted_var[0] = result;
                            // remove 1 (part of it found in 0 now)
                            splitted_var.RemoveAt(1);
                        }

                        return(splitted_var[0]);
                    }
                }
            }
            Debugging.print("not (!) operator ?");
            // '!' operator (only one to take one variable)
            if (expr_string.StartsWith("!"))
            {
                Debugging.assert(expr_string[1] == '(');
                Debugging.assert(expr_string[expr_string.Length - 1] == ')');
                Variable expr = parse(expr_string.Substring(2, expr_string.Length - 3));
                Debugging.assert(expr is BooleanVar);
                Debugging.print("base val b4 not operator is ", expr.getValue());
                return(((BooleanVar)expr).not());
            }

            Debugging.print("value function call ?");
            // value function call
            if (expr_string.Contains("("))
            {
                string function_name    = expr_string.Split('(')[0]; // extract function name
                int    func_call_length = function_name.Length;
                function_name = StringUtils.normalizeWhiteSpaces(function_name);
                Debugging.print("function name: ", function_name);
                Functions.assertFunctionExists(function_name);
                expr_string = expr_string.Substring(func_call_length);          // remove function name
                expr_string = expr_string.Substring(1, expr_string.Length - 2); // remove parenthesis
                Debugging.print("expr_string for function call ", expr_string);

                var arg_list = new List <Expression>();
                foreach (string arg_string in StringUtils.splitStringKeepingStructureIntegrity(expr_string, ',', Global.base_delimiters))
                {
                    string     purged_arg_string = StringUtils.normalizeWhiteSpaces(arg_string);
                    Expression arg_expr          = new Expression(purged_arg_string);
                    arg_list.Add(arg_expr);
                }

                if (arg_list.Count == 1 && arg_list[0].expr == "")
                {
                    arg_list = new List <Expression>();
                }

                Debugging.print("creating value function call with ", arg_list.Count, " parameters");

                FunctionCall func_call = new FunctionCall(function_name, arg_list);
                return(func_call.callFunction());
            }

            // function call without parenthesis -> no parameters either
            if (!expr_string.StartsWith(StringConstants.Other.VARIABLE_PREFIX) && !expr_string.Contains(' '))
            {
                Debugging.print($"Call the function \"{expr_string}\" with no parameters");
                var func_call = new FunctionCall(expr_string, new List <Expression>());
                return(func_call.callFunction());
            }

            Debugging.print("variable ?");
            // variable access

            // since it is the last possibility for the parse call to return something, assert it is a variable
            Debugging.assert(expr_string.StartsWith(StringConstants.Other.VARIABLE_PREFIX), invalid_expr_exception);
            Debugging.print("list access ?");
            // ReSharper disable once PossibleNullReferenceException
            if (expr_string.Contains("["))
            {
                // brackets
                Debugging.assert(expr_string.EndsWith("]"), invalid_expr_exception); // cannot be "$l[0] + 5" bc AL_operations have already been processed
                int bracket_start_index = expr_string.IndexOf('[');
                Debugging.assert(bracket_start_index > 1, invalid_expr_exception);   // "$[$i - 4]" is not valid
                // variable
                Expression var_name_expr = new Expression(expr_string.Substring(0, bracket_start_index));
                Debugging.print("list name: " + var_name_expr.expr);
                // index list
                IEnumerable <string> index_list = StringUtils.getBracketsContent(expr_string.Substring(bracket_start_index));
                string index_list_expr_string   = index_list.Aggregate("", (current, s) => current + s + ", ");
                index_list_expr_string = "[" + index_list_expr_string.Substring(0, index_list_expr_string.Length - 2) + "]";
                var index_list_expr = new Expression(index_list_expr_string);

                Debugging.print("index: " + index_list_expr.expr);

                // create a value function call (list_at call)
                object[] args = { var_name_expr, index_list_expr };
                return(Functions.callFunctionByName("list_at", args));
            }

            // only variable name, no brackets
            Debugging.print("var by name: ", expr_string);
            return(variableFromName(expr_string));
        }
Exemplo n.º 6
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);
        }