コード例 #1
0
        public FunctionCall(string function_name, List <Expression> arg_expr_list)
        {
            Functions.assertFunctionExists(function_name);

            _function_name = function_name;
            _arg_expr_list = arg_expr_list;
            assigned       = true;
            is_const       = false;
        }
コード例 #2
0
        /// <summary>
        /// Transforms a <see cref="RawInstruction"/> into an <see cref="Instruction"/>.
        /// <para/>The order of operations is:
        /// <para/>* variable declaration
        /// <para/>* variable modification
        /// <para/>* for loop
        /// <para/>* while loop
        /// <para/>* if statement
        /// <para/>* void function call
        /// </summary>
        /// <param name="line_index"> index of the line in the purged source code</param>
        /// <param name="raw_instr"> a <see cref="RawInstruction"/> to convert</param>
        /// <returns> the corresponding <see cref="Instruction"/></returns>
        /// <exception cref="AquilaExceptions.SyntaxExceptions.SyntaxError"> Invalid syntax</exception>
        private static Instruction rawInstr2Instr(int line_index, RawInstruction raw_instr)
        {
            /* Order of operations:
             * tracing
             * declaration
             * variable assignment
             * function definition
             * for loop
             * while loop
             * if statement
             * void function call
             */

            Parser.print($"from raw instr to instr: \"{raw_instr._instr}\" at line {line_index}");

            // split instruction
            List <string> instr = StringUtils.splitStringKeepingStructureIntegrity(raw_instr._instr, ' ', Global.base_delimiters);

            Parser.print("trace ?");
            // variable tracing
            if (instr[0] == StringConstants.Keywords.TRACE_KEYWORD)
            {
                if (Global.getSetting("auto trace"))
                {
                    Parser.print("\"trace\" instruction, but \"auto trace\" is set to true ?");
                }

                List <Expression> traced_vars = new List <Expression>();
                for (int i = 1; i < instr.Count; i++)
                {
                    traced_vars.Add(new Expression(instr[i]));
                }

                return(new Tracing(line_index, traced_vars));
            }

            Parser.print("decl ?");
            // variable declaration
            if (instr.Contains(StringConstants.Keywords.DECLARATION_KEYWORD))
            {
                // declaration modes
                bool safe_mode = false,
                     overwrite = false,
                     constant  = false,
                     global    = false;
                while (instr[0] != StringConstants.Keywords.DECLARATION_KEYWORD)
                {
                    switch (instr[0])
                    {
                    case StringConstants.Keywords.SAFE_DECLARATION_KEYWORD:
                        safe_mode = true;
                        Parser.print("safe mode !");
                        break;

                    case StringConstants.Keywords.OVERWRITE_DECLARATION_KEYWORD:
                        overwrite = true;
                        Parser.print("overwrite !");
                        break;

                    case StringConstants.Keywords.CONST_DECLARATION_KEYWORD:
                        constant = true;
                        Parser.print("const !");
                        break;

                    case StringConstants.Keywords.GLOBAL_DECLARATION_KEYWORD:
                        global = true;
                        Parser.print("global !");
                        break;

                    default:
                        throw new AquilaExceptions.UnknownKeywordError($"Unknown keyword in declaration: \"{instr[0]}\"");
                    }

                    instr.RemoveAt(0);
                }

                // remove the "decl"
                instr.RemoveAt(0);

                // define the type
                string type = StringConstants.Types.AUTO_TYPE;
                if (Global.type_list.Contains(instr[0]))
                {
                    type = instr[0];
                    instr.RemoveAt(0);
                    Debugging.assert(type != StringConstants.Types.NULL_TYPE,
                                     new AquilaExceptions.InvalidTypeError($"Cannot declare a variable with type: \"{StringConstants.Types.NULL_TYPE}\""));
                }

                Parser.print("instr: ", instr);

                Expression default_value;
                bool       valid_default_value;
                if (type != StringConstants.Types.AUTO_TYPE)
                {
                    default_value       = Global.default_values_by_var_type[type];
                    valid_default_value = true;
                }
                else
                {
                    default_value       = null;
                    valid_default_value = false;
                }
                var variable_declaration_buffer = new List <string>();
                var declarations = new List <Instruction>();

                foreach (string s in instr)
                {
                    Parser.print("Doing ", s, " with buffer ", StringUtils.dynamic2Str(variable_declaration_buffer));
                    // buffer should be "$var" "="
                    Parser.print(variable_declaration_buffer.Count);
                    if (variable_declaration_buffer.Count == 2)
                    {
                        Parser.print("adding with assignment", StringUtils.dynamic2Str(variable_declaration_buffer));
                        Debugging.assert(variable_declaration_buffer[1] == "=",
                                         new AquilaExceptions.SyntaxExceptions.SyntaxError($"Invalid declaration syntax at token: {s}"));
                        declarations.Add(new Declaration(line_index,
                                                         variable_declaration_buffer[0].Substring(1),
                                                         new Expression(s),
                                                         type,
                                                         true,
                                                         safe_mode,
                                                         overwrite,
                                                         constant,
                                                         global));
                        variable_declaration_buffer.Clear();
                        continue;
                    }
                    if (s.StartsWith(StringConstants.Other.VARIABLE_PREFIX))
                    {
                        if (variable_declaration_buffer.Any())
                        {
                            Debugging.assert(valid_default_value,
                                             new AquilaExceptions.InvalidTypeError($"Invalid variable type without assignment {StringConstants.Types.AUTO_TYPE}"));
                            // add the (empty) declaration
                            Parser.print("adding empty ", StringUtils.dynamic2Str(variable_declaration_buffer));
                            declarations.Add(new Declaration(line_index,
                                                             variable_declaration_buffer[0].Substring(1),
                                                             default_value,
                                                             type,
                                                             false,
                                                             safe_mode,
                                                             overwrite,
                                                             constant,
                                                             global));
                            // clear the buffer & restart
                            variable_declaration_buffer.Clear();
                            variable_declaration_buffer.Add(s);
                        }
                        else
                        {
                            // add variable to the buffer (start of buffer)
                            variable_declaration_buffer.Add(s);
                            Debugging.assert(variable_declaration_buffer.Count < 3,
                                             new AquilaExceptions.SyntaxExceptions.SyntaxError($"Invalid declaration syntax (buffer count > 3): {s}"));
                        }

                        continue;
                    }

                    // must be "="
                    Debugging.assert(s == "=",
                                     new AquilaExceptions.SyntaxExceptions.SyntaxError($"Cannot declare a value: {s}"));
                    variable_declaration_buffer.Add(s);
                }

                // trailing variable ?
                if (variable_declaration_buffer.Any())
                {
                    Parser.print("Trailing var decl buffer: ", variable_declaration_buffer);
                    Debugging.assert(variable_declaration_buffer.Count == 1,
                                     new AquilaExceptions.SyntaxExceptions.SyntaxError($"Invalid trailing declarations: {StringUtils.dynamic2Str(variable_declaration_buffer)}"));
                    declarations.Add(new Declaration(line_index, variable_declaration_buffer[0].Substring(1), default_value,
                                                     type, false, safe_mode, overwrite, constant, global));
                }

                return(new MultiInstruction(declarations.ToArray()));
            }

            Parser.print("assignment ?");
            // variable assignment
            if (instr.Count > 1 && instr[1].EndsWith("=") && (instr[0][0] == '$' || instr[0].Contains("(")))
            {
                Debugging.assert(instr.Count > 2); // syntax ?unfinished line?
                string var_designation = instr[0];
                string equal_sign      = instr[1];
                instr.RemoveAt(0); // remove "$name"
                instr.RemoveAt(0); // remove "{op?}="
                // reunite all on the right side of the "=" sign
                string assignment_string = StringUtils.reuniteBySymbol(instr);
                // custom operator in assignment
                if (equal_sign.Length != 1)
                {
                    Parser.print("Custom operator detected: ", equal_sign);
                    Debugging.assert(equal_sign.Length == 2);
                    assignment_string = $"{var_designation} {equal_sign[0]} ({assignment_string})";
                }
                // get the Expresion
                Expression assignment = new Expression(assignment_string);
                return(new Assignment(line_index, var_designation, assignment));
            }
            // increment || decrement
            if (instr.Count == 2 && (instr[1] == "++" || instr[1] == "--"))
            {
                Parser.print("Increment or Decrement detected");
                return(new Assignment(line_index, instr[0], new Expression($"{instr[0]} {instr[1][0]} 1")));
            }

            Parser.print("function definition ?");
            if (instr[0] == StringConstants.Keywords.FUNCTION_KEYWORD)
            {
                Debugging.assert(raw_instr._is_nested);                 // syntax???
                Debugging.assert(instr.Count == 3 || instr.Count == 4); // "function" "type" ("keyword"?) "name(args)"

                Function func = Functions.readFunction(raw_instr._instr, raw_instr._sub_instr_list);
                return(new FunctionDef(line_index, func));
            }

            Parser.print("for loop ?");
            // for loop
            if (instr[0] == StringConstants.Keywords.FOR_KEYWORD)
            {
                Debugging.assert(raw_instr._is_nested);                               // syntax???
                Debugging.assert(instr[1].StartsWith("(") && instr[1].EndsWith(")")); // syntax
                List <string> sub_instr =
                    StringUtils.splitStringKeepingStructureIntegrity(instr[1].Substring(1, instr[1].Length - 2), ';', Global.base_delimiters);
                sub_instr = StringUtils.normalizeWhiteSpacesInStrings(sub_instr);
                Parser.print(sub_instr);
                Debugging.assert(sub_instr.Count == 3); // syntax

                // start
                Instruction start = new RawInstruction(sub_instr[0], raw_instr._line_index).toInstr();

                // stop
                Expression condition = new Expression(sub_instr[1]);

                // step
                Instruction step = new RawInstruction(sub_instr[2], raw_instr._line_index).toInstr();

                // instr
                List <Instruction> loop_instructions = new List <Instruction>();
                int add_index = 0;
                foreach (RawInstruction loop_instr in raw_instr._sub_instr_list)
                {
                    loop_instructions.Add(rawInstr2Instr(line_index + ++add_index, loop_instr));
                }

                return(new ForLoop(line_index, start, condition, step, loop_instructions));
            }

            Parser.print("while loop ?");
            // while loop
            if (instr[0] == StringConstants.Keywords.WHILE_KEYWORD)
            {
                // syntax check
                Debugging.assert(instr.Count == 2); // syntax

                // condition expression
                Expression condition = new Expression(instr[1]);

                // instr
                List <Instruction> loop_instructions = new List <Instruction>();
                int add_index = 0;
                foreach (RawInstruction loop_instr in raw_instr._sub_instr_list)
                {
                    loop_instructions.Add(rawInstr2Instr(line_index + ++add_index, loop_instr));
                }

                return(new WhileLoop(line_index, condition, loop_instructions));
            }

            Parser.print("if statement ?");
            // if statement
            if (instr[0] == StringConstants.Keywords.IF_KEYWORD)
            {
                // syntax check
                Debugging.assert(instr.Count == 2); // syntax

                // condition expression
                Expression condition = new Expression(instr[1]);

                // instr
                List <Instruction> if_instructions   = new List <Instruction>();
                List <Instruction> else_instructions = new List <Instruction>();
                bool if_section = true;
                int  add_index  = 0;
                foreach (RawInstruction loop_instr in raw_instr._sub_instr_list)
                {
                    add_index++;
                    if (if_section)
                    {
                        if (loop_instr._instr == StringConstants.Keywords.ELSE_KEYWORD)
                        {
                            if_section = false;
                            continue;
                        }
                        if_instructions.Add(rawInstr2Instr(line_index + add_index, loop_instr));
                    }
                    else
                    {
                        else_instructions.Add(rawInstr2Instr(line_index + add_index, loop_instr));
                    }
                }

                return(new IfCondition(line_index, condition, if_instructions, else_instructions));
            }

            Parser.print("function call ?");
            // function call with spaces between function name and parenthesis
            if (instr.Count == 2 && instr[1].StartsWith("("))
            {
                Parser.print("function call with space between name and first parenthesis. Merging ", instr[0], " and ", instr[1]);
                instr[0] += instr[1];
                instr.RemoveAt(1);
            }
            // void function call (no return value, or return value not used)
            if (instr[0].Contains('('))
            {
                // syntax checks
                Debugging.assert(instr.Count == 1);                     // syntax
                Debugging.assert(instr[0][instr[0].Length - 1] == ')'); // syntax

                // function name
                string function_name = instr[0].Split('(')[0]; // extract function name
                if (Global.getSetting("check function existence before runtime"))
                {
                    Functions.assertFunctionExists(function_name);                                                               // assert function exists
                }
                Parser.print("expr_string for function call ", instr[0]);
                // extract args
                string exprs = instr[0].Substring(function_name.Length + 1); // + 1 : '('
                exprs = exprs.Substring(0, exprs.Length - 1);                // ')'
                List <string> arg_expr_str = StringUtils.splitStringKeepingStructureIntegrity(exprs, ',', Global.base_delimiters);

                // no args ?
                if (arg_expr_str.Count == 1 && StringUtils.normalizeWhiteSpaces(arg_expr_str[0]) == "")
                {
                    return(new VoidFunctionCall(line_index, function_name));
                }

                // ReSharper disable once SuggestVarOrType_Elsewhere
                object[] args = arg_expr_str.Select(x => (object)new Expression(x)).ToArray();

                return(new VoidFunctionCall(line_index, function_name, args));
            }

            // try using this as a function ?
            if (instr.Count == 1 && Functions.functionExists(instr[0]))
            {
                Parser.print($"Call the function \"{instr[0]}\" with no parameters");
                return(new VoidFunctionCall(line_index, instr[0]));
            }

            Parser.print("unrecognized line: \"", raw_instr._instr, "\"");
            throw new AquilaExceptions.SyntaxExceptions.SyntaxError($"Unknown syntax \"{raw_instr._instr}\"");
        }
コード例 #3
0
ファイル: Expression.cs プロジェクト: Nicolas-Reyland/Aquila
        /// <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));
        }