/// <summary> /// Get the interactive interpreter command prefix (debug, trace_debug related) /// <para/>Looking at <see cref="Global.getSetting"/>("debug") and <see cref="Global.getSetting"/>("trace debug") /// </summary> /// <returns> command input prefix</returns> private static string getInteractivePrefix() { string prefix = " "; // debugs bool debug = Global.getSetting("debug"); bool trace_debug = Global.getSetting("trace debug"); bool parse_debug = Global.getSetting("parse debug"); // any ? int debug_count = (debug ? 1 : 0) + (trace_debug ? 1 : 0) + (parse_debug ? 1 : 0); if (debug_count == 0) { return(prefix); } // some debug is enabled prefix += "("; if (debug) { prefix += "debug | "; } if (trace_debug) { prefix += "trace | "; } if (parse_debug) { prefix += "parse | "; } return(prefix.Substring(0, prefix.Length - 3) + ")"); }
/// <summary> /// Assert that the status is the one given as input. /// Does not assert if: /// <para/>* the Context is not <see cref="Global.settings"/>["fail on context assertions"] /// <para/>* the Context is <see cref="_frozen"/> /// </summary> /// <param name="supposed"> wanted status</param> /// <exception cref="Exception"> the status is not the input status</exception> public static void assertStatus(StatusEnum supposed) { if (Global.getSetting("fail on context assertions") && !_frozen && (int)supposed != _status) // not sure about not being blocked ? { throw new Exception("Context Assertion Error. Supposed: " + supposed + " but actual: " + (StatusEnum)_status); } }
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(); }
public override string ToString() { if (Global.getSetting("debug") || Global.getSetting("trace debug")) { return("Boolean (" + (_bool_value ? "true" : "false") + ")"); } return(_bool_value ? "true" : "false"); // _bool_value.ToString() capitalizes "true" and "false" }
public override string ToString() { if (Global.getSetting("debug") || Global.getSetting("trace debug")) { return("Integer (" + numeric_value + ")"); } return(numeric_value.ToString()); }
public override string ToString() { if (Global.getSetting("debug") || Global.getSetting("trace debug")) { return("Float (" + numeric_value + ")"); } return(numeric_value.ToString(CultureInfo.InvariantCulture)); }
protected override void updateTestModeValues() { if (!Global.getSetting("test mode")) { return; } Algorithm.testModeInstructionUpdate(); }
/// <summary> /// unfreeze the status /// <para/>Exception will be raised if the context is not frozen /// </summary> public static void unfreeze() { if (Global.getSetting("flame mode")) { return; } Debugging.assert(_frozen); _frozen = false; }
protected override void updateTestModeValues() { Global.instruction_count++; Debugging.print("instruction count incrementation"); if (!Global.getSetting("test mode")) { return; } Algorithm.testModeInstructionUpdate(); }
/// <summary> /// Add a <see cref="Function"/> to the <see cref="user_functions"/> dict. /// If the function already exists and the settings are set accordingly ("user function overwriting"), /// the function will be overwritten /// </summary> /// <param name="func"> <see cref="Function"/> object</param> public static void addUserFunction(Function func) { if (user_functions.ContainsKey(func.getName()) && Global.getSetting("user function overwriting")) { Debugging.print("overwriting already existing user defined function: " + func.getName()); user_functions[func.getName()] = func; } else { user_functions.Add(func.getName(), func); } }
public override string ToString() { if (_list.Count == 0) { return("[]"); } string s = _list.Aggregate("", (current, variable) => current + (variable + ", ")); s = "[" + s.Substring(0, s.Length - 2) + "]"; if (Global.getSetting("debug") || Global.getSetting("trace debug")) { s = "List (" + s + ")"; } return(s); }
internal static void testModeInstructionUpdate() { Debugging.assert(Global.getSetting("test mode"), new AquilaExceptions.RuntimeError("Not in test mode")); // update instruction counter Global.test_values["instruction counter"]++; Debugging.print("- test run - Instruction count: ", Global.test_values["instruction counter"]); // still valid runtime ? if (Global.test_values["stopwatch"].ElapsedMilliseconds <= Global.test_values["max elapsed ms"] && Global.test_values["instruction counter"] <= Global.test_values["max instruction counter"]) { return; } // unfinished algorithm Global.test_values["unfinished run"] = true; throw new AquilaExceptions.RuntimeError("Test max run time exceeded"); }
/// <summary> /// Add teh <see cref="Event"/> on top of the <see cref="Tracer.events"/> stack and /// process the make some assertions to detect abnormal behaviours /// </summary> /// <param name="event_"></param> public override void update(Event event_) { // blocked context ? if (Context.isFrozen() && !Global.getSetting("allow tracing in frozen context")) { return; } // checks Debugging.assert(event_.alter != null); // variable events can only hold Alterations, so checking for null // update events.Push(event_); printTrace("updated (value: " + StringUtils.dynamic2Str(peekValue()) + ")"); // handle callUpdateHandler(event_.alter); }
/// <summary> /// Call the <see cref="Global.tracer_update_handler_function"/> with the Alteration. /// If no function was defined, prints it to the debugging stdout and does nothing /// </summary> /// <param name="alter"> Alteration you want to animate</param> protected static void callUpdateHandler(Alteration alter) { if (Global.getSetting("test mode")) { return; } if (Global.tracer_update_handler_function != null) { printTrace("Calling graphical function"); if (Global.tracer_update_handler_function(alter)) { Global.waitForRun(true); } } else { printTrace("Graphical function is none"); } }
public Declaration(int line_index, string var_name, Expression var_expr, string var_type = StringConstants.Types.AUTO_TYPE, bool assignment = true, bool safe_mode = false, bool overwrite = false, bool constant = false, bool global = false) { // mode: 0 -> new var (must not exist); 1 -> force overwrite (must exist); 2 -> safe overwrite (can exist) this.line_index = line_index; _var_name = var_name; _var_expr = var_expr; _var_type = var_type; _assignment = assignment; _constant = constant; _global = global; // check variable naming Debugging.assert(StringUtils.validObjectName(var_name), new AquilaExceptions.SyntaxExceptions.SyntaxError($"Invalid object name \"{var_name}\"")); // the declaration is not initiated in the right scope... cannot do this here bool var_exists = Global.variableExistsInCurrentScope(var_name); Debugging.print("new declaration: var_name = " + var_name + ", var_expr = ", var_expr.expr, ", var_type = ", var_type, ", assignment = ", assignment, ", mode = ", StringUtils.boolString(safe_mode, overwrite, _constant, _global), ", exists = ", var_exists); // should not check overwriting modes if this is true if (Global.getSetting("implicit declaration in assignment")) { Debugging.print("implicit declaration in assignments, so skipping var existence checks (var exists: ", var_exists, ")"); return; } if (safe_mode && var_exists) { Debugging.assert(!Global.variableFromName(var_name).isTraced()); } if (overwrite) { Debugging.assert(var_exists); } }
/// <summary> /// Print the given values only if the "trace debug" setting is set to true. /// For debugging only /// </summary> /// <param name="args"></param> public static void printTrace(params object[] args) { // if not in debugging mode, return if (!Global.getSetting("trace debug")) { return; } // default settings int max_call_name_length = 30; int num_new_method_separators = 25; bool enable_function_depth = true; int num_function_depth_chars = 4; string prefix = "- TRACE"; // print the args nicely // ReSharper disable once ConditionIsAlwaysTrueOrFalse StringUtils.nicePrintFunction(max_call_name_length, num_new_method_separators, enable_function_depth, num_function_depth_chars, prefix, args); }
/// <summary> /// Initialize the test run mode /// </summary> private static void initTestMode() { Debugging.assert(!Global.getSetting("test mode"), new AquilaExceptions.RuntimeError("Already in test mode")); Global.setSetting("test mode", true); if (Global.test_values.Count != 0) { Global.test_values.Clear(); } Stopwatch stopwatch = new Stopwatch(); Global.test_values.Add("stopwatch", stopwatch); Global.test_values.Add("max elapsed ms", 10000); // n/1000 seconds Global.test_values.Add("instruction counter", 0); Global.test_values.Add("max instruction counter", 120); Global.test_values.Add("unfinished run", false); Global.test_values.Add("variable names", new List <string>()); Global.test_values.Add("value variables", new List <string>()); Global.test_values.Add("index variables", new List <string>()); stopwatch.Start(); }
/// <summary> /// Process the <see cref="Event"/> /// </summary> /// <param name="event_"> <see cref="Event"/> that should be processed</param> public override void update(Event event_) { // blocked context ? if (Context.isFrozen() && !Global.getSetting("allow tracing in frozen context")) { printTrace("Context is blocked in function tracer update call. Normal behaviour ?"); return; } // checks Debugging.assert(event_ != null); // extract events.Push(event_); printTrace("event stack size: " + events.Count); Alteration alter = event_.alter; Variable affected = alter.affected; Debugging.assert(affected != null); Debugging.assert(affected.isTraced()); affected.tracer.update(new Event(new Alteration(traced_func, affected, event_.alter.main_value, event_.alter.minor_values))); //! just push event_ ! printTrace("updated all in function tracer update"); }
/// <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)); }
/// <summary> /// Process the input from the interpreter. /// If the input is one of the interactive-mode-only commands, the command should not /// be executed by the interpreter but will be executed by this function manually. /// </summary> /// <param name="input"> command line from the interactive-mode</param> /// <returns> should the command be executed ?</returns> internal static bool processInterpreterInput(string input) { switch (input) { case "help": { Global.stdoutWriteLine("All existing interactive-mode-only commands:"); // ReSharper disable once RedundantExplicitArrayCreation foreach (string command in new string[] { "help", "exit", "reset_env", "clear", // base interactive-mode "exec", "exec_info", // exec "debug", "trace_debug", "parse_debug", // debugging (enable/disable) "eval %expr", // expr "var %var_name", "vars", "$%var_name", // variables // ReSharper disable once StringLiteralTypo "funcs", "df_funcs", // functions "type", // ? "trace_info", "trace_uniq_stacks", "rewind %n %var_name", "peek_trace $%traced_value", // trace "get_context", "set_status", "set_info_null", "reset_context", // context "scope_info", // scope "show-settings", // settings }) { Global.stdoutWriteLine(" -> " + command); } return(false); } case "clear": if (!Global.getSetting("redirect debug stout & stderr")) { Console.Clear(); } return(false); case "vars": { Global.stdoutWriteLine("Global Variables:"); foreach (var pair in Global.getGlobalVariables()) { Global.stdoutWriteLine("\t" + pair.Key + " : " + pair.Value); } int i = 0; Global.stdoutWriteLine("Local Scope Variables:"); foreach (var dict in Global.getCurrentDictList()) { i++; foreach (var pair in dict) { Global.stdoutWrite(new string('\t', i)); Global.stdoutWrite(pair.Key + " : "); Global.stdoutWriteLine(pair.Value.ToString()); } } return(false); } // ReSharper disable once StringLiteralTypo case "funcs": { Global.stdoutWriteLine("User defined functions:"); foreach (var pair in Functions.user_functions) { Global.stdoutWriteLine(" * " + pair.Key + (pair.Value.isRec() ? " : [rec] " : " : ") + "(" + pair.Value.func_args.Count + ") -> " + pair.Value.getType()); } return(false); } case "df_funcs": Global.stdoutWriteLine("Default (predefined) functions:"); foreach (var pair in Functions.functions_dict) { MethodInfo method = pair.Value.GetMethodInfo(); Global.stdoutWriteLine(" * " + pair.Key + " [?] : (" + method.GetParameters().Length + ") -> " + method.ReturnType); } return(false); case "debug": Global.setSetting("debug", !Global.getSetting("debug")); return(false); case "trace_debug": Global.setSetting("trace debug", !Global.getSetting("trace debug")); return(false); case "parse_debug": Global.setSetting("parse debug", !Global.getSetting("parse debug")); return(false); case "trace_info": { Global.stdoutWriteLine("var tracers:"); foreach (VarTracer tracer in Global.var_tracers) { Global.stdoutWriteLine(" - var : " + (tracer.getTracedObject() as Variable).getName()); Global.stdoutWriteLine(" - stack : " + tracer.getStackCount()); Global.stdoutWriteLine(" - updated : " + tracer.last_stack_count); } Global.stdoutWriteLine("func tracers:"); foreach (FuncTracer tracer in Global.func_tracers) { Global.stdoutWriteLine(" - func : " + tracer.getTracedObject()); Global.stdoutWriteLine(" - stack : " + tracer.getStackCount()); } return(false); } case "trace_uniq_stacks": Global.var_tracers[0].printEventStack(); return(false); case "reset_env": Global.resetEnv(); Global.stdoutWriteLine(" [!] Global Environment reset"); return(false); case "get_context": { int status = Context.getStatus(); Context.StatusEnum status_quote = (Context.StatusEnum)status; object info = Context.getInfo(); bool blocked = Context.isFrozen(); bool enabled = Global.getSetting("fail on context assertions"); Global.stdoutWriteLine("status : " + status); Global.stdoutWriteLine("quote : " + status_quote); Global.stdoutWriteLine("info : " + info); Global.stdoutWriteLine("blocked : " + blocked); Global.stdoutWriteLine("asserts : " + enabled); return(false); } case "set_info_null": Context.setInfo(null); return(false); case "reset_context": Context.reset(); return(false); case "type": Global.stdoutWriteLine("type of NullVar: " + typeof(NullVar)); Global.stdoutWriteLine("type of Variable: " + typeof(Variable)); Global.stdoutWriteLine("type of Integer: " + typeof(Integer)); return(false); case "scope_info": Global.stdoutWriteLine("local scope depth: " + Global.getLocalScopeDepth()); Global.stdoutWriteLine("main scope depth: " + Global.getMainScopeDepth()); return(false); case "show-settings": foreach (var pair in Global.getSettings()) { Global.stdoutWriteLine($" - {pair.Key} : {pair.Value}"); } return(false); } if (input[0] == '$' && Global.variableExistsInCurrentScope(input.Substring(1))) { Global.stdoutWriteLine(Global.variableFromName(input.Substring(1)).ToString()); return(false); } if (input.StartsWith("set_status ")) { int status = int.Parse(input.Substring(11)); Context.setStatus((Context.StatusEnum)status); return(false); } if (input.StartsWith("eval ")) { Variable var_ = Expression.parse(input.Substring(5)); Global.stdoutWriteLine(var_.ToString()); return(false); } if (input.StartsWith("var ")) { string var_name = input.Substring(4); var_name = StringUtils.normalizeWhiteSpaces(var_name); if (var_name == "") { return(false); } Variable var_ = Global.variableFromName(var_name); Global.stdoutWriteLine("name : " + var_.getName()); Global.stdoutWriteLine("type : " + var_.getTypeString()); Global.stdoutWriteLine("const : " + var_.isConst()); Global.stdoutWriteLine("assigned : " + var_.assigned); Global.stdoutWriteLine("value : " + var_); Global.stdoutWriteLine("traced : " + var_.isTraced()); Global.stdoutWriteLine("^ mode : " + var_.trace_mode); if (var_ is NumericalValue value) { Global.stdoutWriteLine("*source : " + StringUtils.dynamic2Str(value.source_vars)); } return(false); } if (input.StartsWith("rewind")) { string[] splitted = input.Split(' '); if (splitted.Length == 3) { if (!int.TryParse(splitted[1], out int n)) { Global.stdoutWriteLine("cannot read n"); return(false); } string var_name = splitted[2]; Variable var_ = Expression.parse(var_name); if (!var_.isTraced()) { Global.stdoutWriteLine("Variable is not traced! Use the \"trace\" instruction to start tracing variables"); return(false); } var_.tracer.rewind(n); return(false); } Global.stdoutWriteLine("split count does not match 3"); return(false); } if (input.StartsWith("peek_trace")) { if (input.Length < 11) { return(false); } Variable var_ = Expression.parse(input.Substring(11)); if (!var_.isTraced()) { Global.stdoutWriteLine("Variable is not traced! Use the \"trace\" instruction to start tracing variables"); return(false); } Alteration alter = var_.tracer.peekEvent().alter; Global.stdoutWriteLine("name : " + alter.name); Global.stdoutWriteLine("variable : " + alter.affected.getName()); Global.stdoutWriteLine("main value : " + StringUtils.dynamic2Str(alter.main_value)); Global.stdoutWriteLine("num minor : " + alter.minor_values.Length); Global.stdoutWriteLine("minor values : " + StringUtils.dynamic2Str(alter.main_value)); Global.stdoutWriteLine("stack count : " + var_.tracer.getStackCount()); Global.stdoutWriteLine("updated : " + var_.tracer.last_stack_count); return(false); } if (input.StartsWith("#")) { Global.stdoutWriteLine("Handling macro parameter"); if (!input.Contains(' ')) { Parser.handleMacro(input.Substring(1), null); return(false); } int index = input.IndexOf(' '); // extract the key & value pair string value = input.Substring(index); input = input.Substring(1, index); // purge pair value = StringUtils.normalizeWhiteSpaces(value); input = StringUtils.normalizeWhiteSpaces(input); Parser.handleMacro(input, value); return(false); } return(true); }
/// <summary> /// This function should be called at the end of every <see cref="Instruction.execute"/> call that is susceptible of /// changing the value of a <see cref="Variable"/>. It works in 3 steps: /// <para/>* Checks for any new assigned <see cref="Variable"/>s in the <see cref="Global._variable_stack"/> (if found: adds to the <see cref="Global.usable_variables"/>) /// <para/>* Update/Process all the awaiting <see cref="Event"/>s (<seealso cref="update"/>) /// <para/>* Check for any new <see cref="Event"/> which has not been processed by the <see cref="Global.tracer_update_handler_function"/> /// </summary> /// <param name="add_call_info"> stands for "additional calling information". If it has any value, it will be printed by the <see cref="Debugging.print"/> function for debugging</param> public static void updateTracers(string add_call_info = "") { if (Global.getSetting("test mode")) { return; } printTrace("updating tracers"); // printTrace alter info about the call if needed if (add_call_info != "") { printTrace(add_call_info); } // check for new usable variables foreach (var pair in Global.getCurrentDict().Where(pair => !Global.usable_variables.Contains(pair.Key))) { printTrace("checking potential var ", pair.Value is NullVar ? StringConstants.Types.NULL_TYPE : pair.Value.getName()); if (pair.Value is NullVar || !pair.Value.assigned) { continue; } // new usable variable ! printTrace("var ", pair.Value.getName(), " is usable (non-null & assigned)"); Global.usable_variables.Add(pair.Key); } // checking tracers checkAllAwaitingEvents(); // check tracer event stacks printTrace("checking variable tracers event stack counts"); foreach (VarTracer tracer in Global.var_tracers) { // unread tracers updates while (tracer.last_stack_count != tracer.getStackCount()) { printTrace("stack count changed for ", tracer.getVar().getName(), " from ", tracer.last_stack_count, " to ", tracer.getStackCount()); //Global.stdoutWriteLine("call graphical function " + StringUtils.varList2String(tracer.getVar().getRawValue()) + " & call event: " + tracer.peekEvent().ToString()); // traced functions have already been processed. checking awaiting stacks int diff = tracer.getStackCount() - tracer.last_stack_count; Debugging.assert(diff > 0); // will run forever tracer.last_stack_count++; //! here } // awaiting tracer stacks while (tracer._awaiting_events.Count != 0) { printTrace("awaiting stacks: ", tracer._awaiting_events.Count); Alteration alter = tracer._awaiting_events.Peek().alter; callUpdateHandler(alter); tracer.update(tracer._awaiting_events.Pop()); } } // update data_tree printTrace("Updating Global.data_tree"); // ReSharper disable once InvertIf if (Global.getSetting("update data tree")) { Debugging.assert(Global.data_tree != null, new AquilaExceptions.RuntimeError("Tried to update data_tree, but it is null")); Global.data_tree = Global.data_tree.update(); } }
/// <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}\""); }
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(); }