import { Store } from "./store/store";
import { Modes } from "./modes";
import { Context } from "./context";
import { Types } from "./../typeSystem/types";
import { Operators } from "./../ast/operators";
import { LanguageDefinedFunction } from "./definedFunctions";
import {
  resultTypeAfterInfixOp,
  resultTypeAfterUnaryOp,
} from "./compatibilityTable";
import * as Commands from "./../ast/commands/";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Command } from "./../ast/commands/command";
import * as Expressions from "./../ast/expressions/";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Expression } from "./../ast/expressions/expression";
import * as Utils from "./../util/utils";
import { ArrayType } from "./../typeSystem/array_type";
import { convertToString, toInt } from "../typeSystem/parsers";
import { Config } from "../util/config";
import { ProcessorErrorFactory } from "./error/processorErrorFactory";
import { RuntimeError } from "./error/runtimeError";
import { Location } from "../memory/location";
import { StoreValue } from "./store/value/store_value";
import { StoreValueRef } from "./store/value/store_value_ref";
import { ArrayStoreValue } from "./store/value/array_store_value";
import { ArrayStoreValueRef } from "./store/value/array_store_value_ref";
import { StoreValueAddress } from "./store/value/store_value_address";
import {getInstance as LocalizedStrings} from "../services/localizedStringsService";

export class IVProgProcessor {
  static get MAIN_INTERNAL_ID () {
    return "$main";
  }

  constructor (ast) {
    this.ast = ast;
    this.globalStore = new Store("$global");
    this.stores = [this.globalStore];
    this.context = [Context.BASE];
    this.input = null;
    this.forceKill = false;
    this.output = null;
    this.mode = Modes.RUN;
    /**
     * Stores the sourceInfo of every function call, command or expression
     */
    this.function_call_stack = [];
    this.instruction_count = 0;
    this.function_call_count = 0;
  }

  registerInput (input) {
    if (this.input !== null) this.input = null;
    this.input = input;
  }

  registerOutput (output) {
    if (this.output !== null) this.output = null;
    this.output = output;
  }

  checkContext (context) {
    return this.context[this.context.length - 1] === context;
  }

  ignoreSwitchCases (store) {
    if (store.mode === Modes.RETURN) {
      return true;
    } else if (store.mode === Modes.BREAK) {
      return true;
    } else {
      return false;
    }
  }

  prepareState () {
    if (this.stores !== null) {
      for (let i = 0; i < this.stores.length; i++) {
        delete this.stores[i];
      }
      this.stores = null;
    }
    if (this.globalStore !== null) this.globalStore = null;
    this.globalStore = new Store("$global");
    this.stores = [this.globalStore];
    this.context = [Context.BASE];
    this.instruction_count = 0;
    this.mode = Modes.RUN;
  }

  async interpretAST () {
    this.prepareState();
    Location.clear();
    await this.initGlobal();
    const mainFunc = this.findMainFunction();
    if (mainFunc === null) {
      throw ProcessorErrorFactory.main_missing();
    }
    return this.runFunction(mainFunc, [], this.globalStore);
  }

  async initGlobal () {
    if (!this.checkContext(Context.BASE)) {
      return ProcessorErrorFactory.invalid_global_var();
    }
    return this.executeCommands(this.globalStore, this.ast.global);
  }

  findMainFunction () {
    return this.ast.functions.find((v) => v.isMain);
  }

  findFunction (name) {
    if (name.match(/^\$.+$/)) {
      if (name === IVProgProcessor.MAIN_INTERNAL_ID) {
        return this.findMainFunction();
      }
      const fun = LanguageDefinedFunction.getFunction(name);
      if (!fun) {
        throw ProcessorErrorFactory.not_implemented(name);
      }
      return fun;
    } else {
      const val = this.ast.functions.find((v) => v.name === name);
      if (!val) {
        throw ProcessorErrorFactory.function_missing(name);
      }
      return val;
    }
  }

  async runFunction (func, actualParameters, store) {
    const funcName = func.isMain ? IVProgProcessor.MAIN_INTERNAL_ID : func.name;
    const funcStore = new Store(funcName);
    funcStore.extendStore(this.globalStore);
    await this.associateParameters(
      func.formalParameters,
      actualParameters,
      store,
      funcStore
    );
    this.context.push(Context.FUNCTION);
    this.stores.push(funcStore);
    const stoWithVars = await this.executeCommands(
      funcStore,
      func.variablesDeclarations
    );
    const finalSto = await this.executeCommands(stoWithVars, func.commands);
    this.stores.pop();
    this.context.pop();
    return finalSto;
  }

  /**
   *
   * @param {import('./../ast/commands/formalParameter').FormalParameter[]} formal_params
   * @param {Expression[]} effective_params
   * @param {Store} caller_store
   * @param {Store} callee_store
   */
  async associateParameters (
    formal_params,
    effective_params,
    caller_store,
    callee_store
  ) {
    const funcName =
      callee_store.name === IVProgProcessor.MAIN_INTERNAL_ID
        ? LanguageDefinedFunction.getMainFunctionName()
        : callee_store.name;

    const hasVariadic = formal_params.some((p) => p.variadic);

    if (
      (formal_params.length != effective_params.length && !hasVariadic) ||
      formal_params.length > effective_params.length
    ) {
      throw ProcessorErrorFactory.invalid_parameters_size(
        funcName,
        formal_params.length,
        effective_params.length
      );
    }
    for (
      let i = 0, j = 0;
      i < formal_params.length && j < effective_params.length;
      i += 1, j += 1
    ) {
      const formalParameter = formal_params[i];
      if (formalParameter.variadic) {
        [j, callee_store] = await this.associateVariadicParameter(
          funcName,
          formalParameter,
          j,
          effective_params,
          caller_store,
          callee_store
        );
      } else {
        const actualParam = effective_params[i];
        callee_store = await this.associateParameter(
          funcName,
          formalParameter,
          actualParam,
          caller_store,
          callee_store
        );
      }
    }
    return callee_store;
  }

  /**
   *
   * @param {string} funcName
   * @param {import('./../ast/commands/formalParameter').FormalParameter} formalParameter
   * @param {number} index
   * @param {Expression[]} effective_params
   * @param {Store} caller_store
   * @param {Store} callee_store
   */
  async associateVariadicParameter (
    funcName,
    formalParameter,
    index,
    effective_params,
    caller_store,
    callee_store
  ) {
    let i;
    let count = 1;
    for (i = index; i < effective_params.length; i += 1) {
      const actualParam = effective_params[i];
      callee_store = await this.associateParameter(
        funcName,
        formalParameter,
        actualParam,
        caller_store,
        callee_store,
        count
      );
      count += 1;
    }
    const variadicCount = new StoreValue(Types.INTEGER, count, undefined, true);
    callee_store.insertStore(`${formalParameter.id}.0`, variadicCount);
    return [i - 1, callee_store];
  }

  /**
   *
   * @param {string} funcName
   * @param {import('./../ast/commands/formalParameter').FormalParameter} formalParameter
   * @param {Expression} actualParameter
   * @param {Store} callerStore
   * @param {Store} calleeStore
   * @param {number} variadicCount The number of the current value being assigned to the variadic parameter, default 0
   */
  async associateParameter (
    funcName,
    formalParameter,
    actualParameter,
    callerStore,
    calleeStore,
    variadicCount = 0
  ) {
    const actualValue = await this.evaluateExpression(
      callerStore,
      actualParameter
    );

    let shouldTypeCast = false;

    if (!formalParameter.type.isCompatible(actualValue.type)) {
      if (
        Config.enable_type_casting &&
        !formalParameter.byRef &&
        Store.canImplicitTypeCast(formalParameter.type, actualValue.type)
      ) {
        shouldTypeCast = true;
      } else {
        throw ProcessorErrorFactory.invalid_parameter_type(
          funcName,
          actualParameter.toString()
        );
      }
    }

    if (formalParameter.byRef && !actualValue.inStore()) {
      throw ProcessorErrorFactory.invalid_ref(
        funcName,
        actualParameter.toString()
      );
    }

    if (formalParameter.byRef) {
      const realObj = callerStore.getStoreObject(actualValue.id);
      let ref = null;
      if (actualValue instanceof ArrayStoreValue) {
        // it's a vector or matrix...
        const values = actualValue.get();
        const array_type = actualValue.type;
        const addresses = values.map((v) =>
          realObj.getLocAddressOf(v.line, v.column)
        );
        const columns = actualValue.isVector() ? 0 : actualValue.columns;
        ref = new ArrayStoreValueRef(
          array_type,
          values,
          addresses,
          actualValue.lines,
          columns,
          realObj.id
        );
      } else {
        if (actualValue instanceof StoreValueAddress) {
          const line = actualValue.line;
          const column = actualValue.column;
          ref = new StoreValueRef(
            actualValue.type,
            actualValue.get(),
            realObj.getLocAddressOf(line, column),
            realObj.id
          );
          ref.setReferenceDimension(realObj.type.dimensions);
        } else {
          ref = new StoreValueRef(
            actualValue.type,
            actualValue.get(),
            realObj.locAddress,
            realObj.id
          );
        }
      }
      let varID = formalParameter.id;
      if (formalParameter.variadic) varID = `${varID}.${variadicCount}`;
      calleeStore.insertStore(varID, ref);
    } else {
      let realValue = actualValue;
      if (shouldTypeCast) {
        realValue = Store.doImplicitCasting(formalParameter.type, realValue);
      }
      let varID = formalParameter.id;
      if (formalParameter.variadic) varID = `${varID}.${variadicCount}`;
      calleeStore.insertStore(varID, realValue);
    }
    return calleeStore;
  }

  /**
   *
   * @param {Store} store
   * @param {Command[]} cmds
   *
   * @returns {Promise<Store>}
   */
  async executeCommands (store, cmds) {
    // helper to partially apply a function, in this case executeCommand
    let sto = store;
    for (let i = 0; i < cmds.length; i += 1) {
      sto = await this.executeCommand(sto, cmds[i]);
    }
    return sto;
  }

  /**
   *
   * @param {Store} store
   * @param {Command} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeCommand (store, cmd) {
    this.instruction_count += 1;
    if (this.instruction_count % Config.suspend_threshold == 0) {
      //every Config.suspend_threshold instruction should briefly delay its execution in order to allow the browser to process other things
      await Utils.sleep(3);
    }

    // Checks if it must interrupt the execution for some reason
    if (this.instruction_count >= Config.max_instruction_count) {
      throw ProcessorErrorFactory.exceed_max_instructions();
    } else if (this.forceKill) {
      throw "FORCED_KILL!";
    } else if (store.mode === Modes.PAUSE) {
      return this.executeCommand(store, cmd);
    } else if (store.mode === Modes.RETURN) {
      return store;
    } else if (
      this.checkContext(Context.BREAKABLE) &&
      store.mode === Modes.BREAK
    ) {
      return store;
    } else if (this.mode === Modes.ABORT) {
      throw LocalizedStrings().getMessage("aborted_execution");
    }

    if (cmd instanceof Commands.Declaration) {
      return this.executeDeclaration(store, cmd);
    } else if (cmd instanceof Commands.ArrayIndexAssign) {
      return this.executeArrayIndexAssign(store, cmd);
    } else if (cmd instanceof Commands.Assign) {
      return this.executeAssign(store, cmd);
    } else if (cmd instanceof Commands.Break) {
      return this.executeBreak(store, cmd);
    } else if (cmd instanceof Commands.Return) {
      return this.executeReturn(store, cmd);
    } else if (cmd instanceof Commands.IfThenElse) {
      return this.executeIfThenElse(store, cmd);
    } else if (cmd instanceof Commands.RepeatUntil) {
      return this.executeRepeatUntil(store, cmd);
    } else if (cmd instanceof Commands.While) {
      return this.executeWhile(store, cmd);
    } else if (cmd instanceof Commands.For) {
      return this.executeFor(store, cmd);
    } else if (cmd instanceof Commands.Switch) {
      return this.executeSwitch(store, cmd);
    } else if (cmd instanceof Expressions.FunctionCall) {
      return this.executeFunctionCall(store, cmd);
    } else if (cmd instanceof Commands.SysCall) {
      return this.executeSysCall(store, cmd);
    } else {
      throw ProcessorErrorFactory.unknown_command(cmd.sourceInfo);
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.SysCall} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeSysCall (store, cmd) {
    const func = cmd.langFunc.bind(this);
    return func(store, cmd);
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.FunctionCall} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeFunctionCall (store, cmd) {
    let func = null;
    if (cmd.isMainCall) {
      func = this.findMainFunction();
    } else {
      func = this.findFunction(cmd.id);
    }
    this.function_call_stack.push(cmd.sourceInfo);
    const sto = await this.runFunction(func, cmd.actualParameters, store);
    sto.destroy();
    if (
      !Types.VOID.isCompatible(func.returnType) &&
      sto.mode !== Modes.RETURN
    ) {
      const funcName =
        func.name === IVProgProcessor.MAIN_INTERNAL_ID
          ? LanguageDefinedFunction.getMainFunctionName()
          : func.name;
      throw ProcessorErrorFactory.function_no_return(funcName);
    } else {
      this.function_call_stack.pop();
      return store;
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.Switch} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeSwitch (store, cmd) {
    this.context.push(Context.BREAKABLE);
    const switchCases = cmd.cases;
    let lastStore = store;
    let lastCaseCheckResult = false;
    for (
      let i = 0;
      i < switchCases.length && !this.ignoreSwitchCases(lastStore);
      i += 1
    ) {
      const switchCase = switchCases[i];
      if (lastCaseCheckResult || switchCase.isDefault) {
        lastStore = await this.executeCommands(lastStore, switchCase.commands);
      } else {
        const equalityInfixApp = new Expressions.InfixApp(
          Operators.EQ,
          cmd.expression,
          switchCase.expression
        );
        equalityInfixApp.sourceInfo = switchCase.sourceInfo;
        const result = await this.evaluateExpression(
          lastStore,
          equalityInfixApp
        );
        if (result.get()) {
          lastStore = await this.executeCommands(
            lastStore,
            switchCase.commands
          );
        }
        lastCaseCheckResult = result.get();
      }
    }
    this.context.pop();
    if (lastStore.mode === Modes.BREAK) {
      lastStore.mode = Modes.RUN;
    }
    return lastStore;
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.For} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeFor (store, cmd) {
    //BEGIN for -> while rewrite
    const initCmd = new Commands.Assign(cmd.for_id.id, cmd.for_from);
    initCmd.sourceInfo = cmd.sourceInfo;
    // Assume for is iterating forward and that pass is not missing
    let passValue = cmd.for_pass;
    let condition = new Expressions.InfixApp(
      Operators.LT,
      cmd.for_id,
      cmd.for_to
    );

    if (cmd.for_pass == null) {
      passValue = new Expressions.IntLiteral(toInt(1));
      const checkEndGTBegin = await this.evaluateExpression(
        store,
        new Expressions.InfixApp(Operators.GE, cmd.for_to, cmd.for_from)
      );
      if (!checkEndGTBegin.get()) {
        passValue = new Expressions.IntLiteral(toInt(-1));
        condition = new Expressions.InfixApp(
          Operators.GT,
          cmd.for_id,
          cmd.for_to
        );
      }
    } else {
      const isForward = await this.evaluateExpression(
        store,
        new Expressions.InfixApp(
          Operators.GE,
          cmd.for_pass,
          new Expressions.IntLiteral(toInt(0))
        )
      );
      if (!isForward.get()) {
        condition = new Expressions.InfixApp(
          Operators.GT,
          cmd.for_id,
          cmd.for_to
        );
      }
    }

    condition.sourceInfo = cmd.sourceInfo;
    const increment = new Commands.Assign(
      cmd.for_id.id,
      new Expressions.InfixApp(Operators.ADD, cmd.for_id, passValue)
    );
    increment.sourceInfo = cmd.sourceInfo;
    const whileBlock = new Commands.CommandBlock(
      [],
      cmd.commands.concat(increment)
    );
    const forAsWhile = new Commands.While(condition, whileBlock);
    forAsWhile.sourceInfo = cmd.sourceInfo;
    //END for -> while rewrite
    const newCmdList = [initCmd, forAsWhile];
    return this.executeCommands(store, newCmdList);
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.RepeatUntil} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeRepeatUntil (store, cmd) {
    this.context.push(Context.BREAKABLE);
    const sto = await this.executeCommands(store, cmd.commands);
    if (sto.mode === Modes.BREAK) {
      this.context.pop();
      sto.mode = Modes.RUN;
      return sto;
    }
    const checkCondition = await this.evaluateExpression(sto, cmd.expression);
    if (!checkCondition.type.isCompatible(Types.BOOLEAN)) {
      throw ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo);
    }
    this.context.pop();
    if (checkCondition.get()) {
      return sto;
    } else {
      return this.executeCommand(sto, cmd);
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.While} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeWhile (store, cmd) {
    this.context.push(Context.BREAKABLE);
    const checkCondition = await this.evaluateExpression(store, cmd.expression);
    if (!checkCondition.type.isCompatible(Types.BOOLEAN)) {
      throw ProcessorErrorFactory.loop_condition_type_full(
        cmd.expression.toString(),
        cmd.sourceInfo
      );
    }
    if (checkCondition.get()) {
      const sto = await this.executeCommands(store, cmd.commands);
      this.context.pop();
      if (sto.mode === Modes.BREAK) {
        sto.mode = Modes.RUN;
        return sto;
      }
      return this.executeCommand(sto, cmd);
    } else {
      this.context.pop();
      return store;
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.IfThenElse} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeIfThenElse (store, cmd) {
    const isTrue = await this.evaluateExpression(store, cmd.condition);
    if (!isTrue.type.isCompatible(Types.BOOLEAN)) {
      throw ProcessorErrorFactory.if_condition_type_full(
        cmd.condition.toString(),
        cmd.sourceInfo
      );
    }
    if (isTrue.get()) {
      return this.executeCommands(store, cmd.ifTrue.commands);
    } else if (cmd.ifFalse !== null) {
      if (cmd.ifFalse instanceof Commands.IfThenElse) {
        return this.executeCommand(store, cmd.ifFalse);
      } else {
        return this.executeCommands(store, cmd.ifFalse.commands);
      }
    } else {
      return store;
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.Return} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeReturn (store, cmd) {
    const funcName =
      store.name === IVProgProcessor.MAIN_INTERNAL_ID
        ? LanguageDefinedFunction.getMainFunctionName()
        : store.name;
    // console.log(funcName,  store.name === IVProgProcessor.MAIN_INTERNAL_ID);
    const func = this.findFunction(store.name);
    const funcType = func.returnType;
    const value = await this.evaluateExpression(store, cmd.expression);
    if (value === null && funcType.isCompatible(Types.VOID)) {
      store.mode = Modes.RETURN;
      return store;
    }

    let real_value = value;
    if (value === null || !funcType.isCompatible(value.type)) {
      if (
        !Config.enable_type_casting ||
        !Store.canImplicitTypeCast(funcType, value.type)
      ) {
        const stringInfo = funcType.stringInfo();
        const info = stringInfo[0];
        throw ProcessorErrorFactory.invalid_return_type_full(
          funcName,
          info.type,
          info.dim,
          cmd.sourceInfo
        );
      }
      real_value = Store.doImplicitCasting(funcType, value);
    }

    store.insertStore("$", real_value);
    store.mode = Modes.RETURN;
    return store;
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.Break} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeBreak (store, cmd) {
    if (this.checkContext(Context.BREAKABLE)) {
      store.mode = Modes.BREAK;
      return store;
    } else {
      throw ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo);
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.Assign} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeAssign (store, cmd) {
    const inStore = store.applyStore(cmd.id);
    if (inStore.isConst) {
      throw ProcessorErrorFactory.invalid_const_assignment_full(
        cmd.id,
        cmd.sourceInfo
      );
    }
    const value = await this.evaluateExpression(store, cmd.expression);
    let realValue = value;
    if (!inStore.type.isCompatible(realValue.type)) {
      if (
        Config.enable_type_casting &&
        Store.canImplicitTypeCast(inStore.type, value.type)
      ) {
        realValue = Store.doImplicitCasting(inStore.type, realValue);
      } else {
        const stringInfo = inStore.type.stringInfo();
        const info = stringInfo[0];
        const exp_type_string_info = value.type.stringInfo();
        const exp_type_info = exp_type_string_info[0];
        const exp = cmd.expression.toString();
        throw ProcessorErrorFactory.incompatible_types_full(
          info.type,
          info.dim,
          exp_type_info.type,
          exp_type_info.dim,
          exp,
          cmd.sourceInfo
        );
      }
    }

    if (inStore instanceof ArrayStoreValue) {
      const columns = realValue.columns == null ? 0 : realValue.columns;
      if (inStore.lines !== realValue.lines || inStore.columns !== columns) {
        const exp = cmd.expression.toString();
        if (inStore.isVector()) {
          throw ProcessorErrorFactory.invalid_vector_assignment_full(
            cmd.id,
            inStore.lines,
            exp,
            realValue.lines,
            cmd.sourceInfo
          );
        } else {
          throw ProcessorErrorFactory.invalid_matrix_assignment_full(
            cmd.id,
            inStore.lines,
            inStore.columns,
            exp,
            realValue.lines,
            realValue.columns,
            cmd.sourceInfo
          );
        }
      }
    }

    store.updateStore(cmd.id, realValue);
    return store;
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.ArrayIndexAssign} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeArrayIndexAssign (store, cmd) {
    const mustBeArray = store.applyStore(cmd.id);
    let used_dims = 0;
    if (mustBeArray.isConst) {
      throw ProcessorErrorFactory.invalid_const_assignment_full(
        cmd.id,
        cmd.sourceInfo
      );
    }
    if (!(mustBeArray.type instanceof ArrayType)) {
      throw ProcessorErrorFactory.invalid_array_access_full(
        cmd.id,
        cmd.sourceInfo
      );
    }
    const lineSV = await this.evaluateExpression(store, cmd.line);
    if (!Types.INTEGER.isCompatible(lineSV.type)) {
      throw ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo);
    }
    used_dims += 1;
    const line = lineSV.get().toNumber();
    const columnSV = await this.evaluateExpression(store, cmd.column);
    let column = null;
    if (columnSV != null) {
      if (!Types.INTEGER.isCompatible(columnSV.type)) {
        throw ProcessorErrorFactory.array_dimension_not_int_full(
          cmd.sourceInfo
        );
      }
      column = columnSV.get().toNumber();
      used_dims += 1;
    }
    const value = await this.evaluateExpression(store, cmd.expression);
    let actualValue = value;
    if (line >= mustBeArray.lines) {
      if (mustBeArray.isVector) {
        throw ProcessorErrorFactory.vector_line_outbounds_full(
          cmd.id,
          line,
          mustBeArray.lines,
          cmd.sourceInfo
        );
      } else {
        throw ProcessorErrorFactory.matrix_line_outbounds_full(
          cmd.id,
          line,
          mustBeArray.lines,
          cmd.sourceInfo
        );
      }
    } else if (line < 0) {
      throw ProcessorErrorFactory.array_dimension_not_positive_full(
        cmd.sourceInfo
      );
    }
    if (column != null && mustBeArray.columns === 0) {
      throw ProcessorErrorFactory.vector_not_matrix_full(
        cmd.id,
        cmd.sourceInfo
      );
    }
    if (column != null) {
      if (column >= mustBeArray.columns) {
        throw ProcessorErrorFactory.matrix_column_outbounds_full(
          cmd.id,
          column,
          mustBeArray.columns,
          cmd.sourceInfo
        );
      } else if (column < 0) {
        throw ProcessorErrorFactory.array_dimension_not_positive_full(
          cmd.sourceInfo
        );
      }
    }

    if (!mustBeArray.type.canAccept(value.type, used_dims)) {
      if (
        !Config.enable_type_casting ||
        !Store.canImplicitTypeCast(mustBeArray.type.innerType, value.type)
      ) {
        const type = mustBeArray.type.innerType;
        const stringInfo = type.stringInfo();
        const info = stringInfo[0];
        const exp_type_string_info = value.type.stringInfo();
        const exp_type_info = exp_type_string_info[0];
        const exp = cmd.expression.toString();
        throw ProcessorErrorFactory.incompatible_types_full(
          info.type,
          info.dim,
          exp_type_info.type,
          exp_type_info.dim,
          exp,
          cmd.sourceInfo
        );
      }
      actualValue = Store.doImplicitCasting(mustBeArray.type.innerType, value);
    }

    const current_value = mustBeArray.getAt(line, column);
    if (current_value instanceof ArrayStoreValue) {
      if (
        current_value.lines !== actualValue.lines ||
        current_value.columns !== actualValue.columns
      ) {
        const exp = cmd.expression.toString();
        throw ProcessorErrorFactory.invalid_matrix_index_assign_full(
          cmd.id,
          line,
          current_value.lines,
          exp,
          actualValue.lines,
          cmd.sourceInfo
        );
      }
    }

    return store.updateStoreArray(cmd.id, actualValue, line, column);
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.Declaration} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeDeclaration (store, cmd) {
    if (cmd instanceof Commands.ArrayDeclaration) {
      return this.executeArrayDeclaration(store, cmd);
    } else {
      let temp = new StoreValue(cmd.type, null, null, cmd.isConst);
      if (cmd.initial !== null) {
        const value = await this.evaluateExpression(store, cmd.initial);
        let realValue = value;
        if (!value.type.isCompatible(cmd.type)) {
          if (
            Config.enable_type_casting &&
            Store.canImplicitTypeCast(cmd.type, value.type)
          ) {
            realValue = Store.doImplicitCasting(cmd.type, realValue);
          } else {
            const stringInfo = value.type.stringInfo();
            const info = stringInfo[0];
            const exp_type_string_info = value.type.stringInfo();
            const exp_type_info = exp_type_string_info[0];
            const exp = cmd.expression.toString();
            throw ProcessorErrorFactory.incompatible_types_full(
              info.type,
              info.dim,
              exp_type_info.type,
              exp_type_info.dim,
              exp,
              cmd.sourceInfo
            );
          }
        }
        temp = new StoreValue(cmd.type, realValue.get(), null, cmd.isConst);
      }
      store.insertStore(cmd.id, temp);
      return store;
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.ArrayDeclaration} cmd
   *
   * @returns {Promise<Store>}
   */
  async executeArrayDeclaration (store, cmd) {
    const linesSV = await this.evaluateExpression(store, cmd.lines);
    if (!Types.INTEGER.isCompatible(linesSV.type)) {
      throw ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo);
    }
    const line = linesSV.get().toNumber();
    const columnsSV = await this.evaluateExpression(store, cmd.columns);
    let column = null;
    if (columnsSV !== null) {
      if (!Types.INTEGER.isCompatible(columnsSV.type)) {
        throw ProcessorErrorFactory.array_dimension_not_int_full(
          cmd.sourceInfo
        );
      }
      column = columnsSV.get().toNumber();
      if (column < 0) {
        throw ProcessorErrorFactory.array_dimension_not_positive_full(
          cmd.sourceInfo
        );
      }
    }
    let temp = new ArrayStoreValue(
      cmd.type,
      [],
      line,
      column,
      null,
      cmd.isConst
    );
    if (cmd.initial !== null) {
      // array can only be initialized by a literal....
      const valueList = await this.evaluateArrayLiteral(
        store,
        cmd.initial,
        cmd.type,
        line,
        column
      );
      temp = new ArrayStoreValue(
        cmd.type,
        valueList,
        line,
        column,
        null,
        cmd.isConst
      );
    }
    store.insertStore(cmd.id, temp);
    return store;
  }

  /**
   *
   * @param {Store} store
   * @param {Expression} exp
   *
   * @returns {Promise<import('./store/value/istore_value').IStoreValue>}
   */
  async evaluateExpression (store, exp) {
    this.instruction_count += 1;
    if (this.instruction_count % Config.suspend_threshold == 0) {
      //every Config.suspend_threshold instruction should briefly delay its execution in order to allow the browser to process other things
      await Utils.sleep(3);
    }
    if (this.mode === Modes.ABORT) {
      throw LocalizedStrings().getMessage("aborted_execution");
    }
    if (this.instruction_count >= Config.max_instruction_count) {
      throw new Error(
        "Número de instruções excedeu o limite definido. Verifique se seu código não possui laços infinitos ou muitas chamadas de funções recursivas."
      );
    }
    if (exp instanceof Expressions.UnaryApp) {
      return this.evaluateUnaryApp(store, exp);
    } else if (exp instanceof Expressions.InfixApp) {
      return this.evaluateInfixApp(store, exp);
    } else if (exp instanceof Expressions.ArrayAccess) {
      return this.evaluateArrayAccess(store, exp);
    } else if (exp instanceof Expressions.VariableLiteral) {
      return this.evaluateVariableLiteral(store, exp);
    } else if (exp instanceof Expressions.IntLiteral) {
      return this.evaluateLiteral(store, exp);
    } else if (exp instanceof Expressions.RealLiteral) {
      return this.evaluateLiteral(store, exp);
    } else if (exp instanceof Expressions.BoolLiteral) {
      return this.evaluateLiteral(store, exp);
    } else if (exp instanceof Expressions.StringLiteral) {
      return this.evaluateLiteral(store, exp);
    } else if (exp instanceof Expressions.CharLiteral) {
      return this.evaluateLiteral(store, exp);
    } else if (exp instanceof Expressions.ArrayLiteral) {
      throw new Error(
        "Internal Error: The system should not eval an array literal."
      );
    } else if (exp instanceof Expressions.FunctionCall) {
      return this.evaluateFunctionCall(store, exp);
    }
    return null;
  }

  async evaluateFunctionCall (store, exp) {
    if (exp.isMainCall) {
      throw ProcessorErrorFactory.void_in_expression_full(
        LanguageDefinedFunction.getMainFunctionName(),
        exp.sourceInfo
      );
    }
    const func = this.findFunction(exp.id);
    if (Types.VOID.isCompatible(func.returnType)) {
      throw ProcessorErrorFactory.void_in_expression_full(
        exp.id,
        exp.sourceInfo
      );
    }
    if (this.function_call_stack.length >= Config.max_call_stack) {
      throw ProcessorErrorFactory.exceeded_recursive_calls(exp.sourceInfo);
    }
    this.function_call_stack.push(exp.sourceInfo);
    const sto = await this.runFunction(func, exp.actualParameters, store);
    if (sto.mode !== Modes.RETURN) {
      throw new Error(
        "!!!Internal error: the function that was called did not have a return command or did not set the store mode properly -> " +
          exp.id
      );
    }
    const val = sto.applyStore("$");
    sto.destroy();
    this.function_call_stack.pop();
    return val;
  }

  /**
   *
   * @param {Store} store
   * @param {Expressions.ArrayLiteral} exp
   * @param {ArrayType} type
   *
   * @returns {Promise<StoreValue[]>}
   */
  async evaluateArrayLiteral (store, exp, type, lines, columns) {
    if (!exp.isVector) {
      if (columns == null) {
        throw new Error(
          "This should never happen: Vector cannot be initialized by a matrix"
        );
      }
      const storeValueMatrix = await this.evaluateMatrix(
        store,
        exp,
        type,
        lines,
        columns
      );
      return storeValueMatrix.reduce((prev, next) => prev.concat(next), []);
    } else {
      if (columns != null) {
        throw new Error(
          "This should never happen: Matrix cannot be initialized by a vector"
        );
      }
      return this.evaluateVector(store, exp, type, lines);
    }
  }

  /**
   * Evalautes a list of literals and expression composing the vector
   * @param {Store} store
   * @param {Expressions.ArrayLiteral} exps
   * @param {ArrayType} type
   * @param {number} n_elements
   *
   * @returns {Promise<StoreValue[]>} store object list
   */
  async evaluateVector (store, exps, type, n_elements) {
    const values = exps.value;
    if (n_elements !== values.length) {
      throw ProcessorErrorFactory.invalid_number_elements_vector(
        n_elements,
        exps.toString(),
        values.length,
        exps.sourceInfo
      );
    }
    const actualValues = await Promise.all(
      values.map((exp) => this.evaluateExpression(store, exp))
    );
    return actualValues.map((v, index) => {
      if (!type.canAccept(v.type, 1)) {
        if (
          !Config.enable_type_casting ||
          !Store.canImplicitTypeCast(type.innerType, v.type)
        ) {
          // const stringInfo = v.type.stringInfo();
          // const info = stringInfo[0];
          const exp_str = values[index].toString();
          // TODO - fix error message
          throw ProcessorErrorFactory.invalid_array_literal_type_full(
            exp_str,
            values[index].sourceInfo
          );
        }
        const newValue = Store.doImplicitCasting(type.innerType, v);
        return newValue;
      }
      return v;
    });
  }

  /**
   * Evaluates a list of array literals composing the matrix
   * @param {Store} store
   * @param {Expressions.ArrayLiteral} exps
   * @param {ArrayType} type
   *
   * @returns {Promise<StoreValue[][]>}
   */
  async evaluateMatrix (store, exps, type, lines, columns) {
    const values = exps.value;
    if (values.length !== lines) {
      throw ProcessorErrorFactory.invalid_number_lines_matrix(
        lines,
        exps.toString(),
        values.length,
        exps.sourceInfo
      );
    }
    const vectors = values.map((vector) => {
      const vec_type = new ArrayType(type.innerType, 1);
      return this.evaluateVector(store, vector, vec_type, columns);
    });
    return await Promise.all(vectors);
  }

  /**
   *
   * @param {Store} _
   * @param {import('../ast/expressions/literal').Literal} exp
   *
   * @returns {import('./store/value/istore_value').IStoreValue}
   */
  async evaluateLiteral (_, exp) {
    return new StoreValue(exp.type, exp.value);
  }

  /**
   *
   * @param {Store} store
   * @param {Expressions.VariableLiteral} exp
   *
   * @returns {import('./store/value/istore_value').IStoreValue}
   */
  async evaluateVariableLiteral (store, exp) {
    const val = store.applyStore(exp.id);
    return val;
  }

  /**
   *
   * @param {Store} store
   * @param {Expressions.ArrayAccess} exp
   *
   * @returns {import('./store/value/istore_value').IStoreValue}
   */
  async evaluateArrayAccess (store, exp) {
    const mustBeArray = store.getStoreObject(exp.id);
    if (!(mustBeArray.type instanceof ArrayType)) {
      throw ProcessorErrorFactory.invalid_array_access_full(
        exp.id,
        exp.sourceInfo
      );
    }
    const lineSV = await this.evaluateExpression(store, exp.line);
    if (!Types.INTEGER.isCompatible(lineSV.type)) {
      throw ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo);
    }
    const line = lineSV.get().toNumber();
    const columnSV = await this.evaluateExpression(store, exp.column);
    let column = null;
    if (columnSV !== null) {
      if (!Types.INTEGER.isCompatible(columnSV.type)) {
        throw ProcessorErrorFactory.array_dimension_not_int_full(
          exp.sourceInfo
        );
      }
      column = columnSV.get().toNumber();
    }
    if (line >= mustBeArray.lines) {
      if (mustBeArray.isVector) {
        throw ProcessorErrorFactory.vector_line_outbounds_full(
          exp.id,
          line,
          mustBeArray.lines,
          exp.sourceInfo
        );
      } else {
        throw ProcessorErrorFactory.matrix_line_outbounds_full(
          exp.id,
          line,
          mustBeArray.lines,
          exp.sourceInfo
        );
      }
    } else if (line < 0) {
      throw ProcessorErrorFactory.array_dimension_not_positive_full(
        exp.sourceInfo
      );
    }
    if (column !== null && mustBeArray.columns === 0) {
      throw ProcessorErrorFactory.vector_not_matrix_full(
        exp.id,
        exp.sourceInfo
      );
    }
    if (column !== null) {
      if (column >= mustBeArray.columns) {
        throw ProcessorErrorFactory.matrix_column_outbounds_full(
          exp.id,
          column,
          mustBeArray.columns,
          exp.sourceInfo
        );
      } else if (column < 0) {
        throw ProcessorErrorFactory.array_dimension_not_positive_full(
          exp.sourceInfo
        );
      }
    }
    const result = mustBeArray.getAt(line, column);
    const type = mustBeArray.type.innerType;
    if (Array.isArray(result)) {
      const values = result.map((val, col) => {
        return new StoreValueAddress(
          type,
          val,
          line,
          col,
          mustBeArray.id,
          mustBeArray.readOnly
        );
      });
      return new ArrayStoreValue(
        new ArrayType(type, 1),
        values,
        mustBeArray.columns,
        null,
        mustBeArray.id,
        mustBeArray.readOnly
      );
    } else {
      return new StoreValueAddress(
        type,
        result,
        line,
        column,
        mustBeArray.id,
        mustBeArray.readOnly
      );
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Expressions.UnaryApp} unaryApp
   *
   * @returns {import('./store/value/istore_value').IStoreValue}
   */
  async evaluateUnaryApp (store, unaryApp) {
    const left = await this.evaluateExpression(store, unaryApp.left);
    const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
    if (Types.UNDEFINED.isCompatible(resultType)) {
      const stringInfo = left.type.stringInfo();
      const info = stringInfo[0];
      throw ProcessorErrorFactory.invalid_unary_op_full(
        unaryApp.op,
        info.type,
        info.dim,
        unaryApp.sourceInfo
      );
    }
    switch (unaryApp.op.ord) {
      case Operators.ADD.ord:
        return new StoreValue(resultType, left.get());
      case Operators.SUB.ord:
        return new StoreValue(resultType, left.get().negated());
      case Operators.NOT.ord:
        return new StoreValue(resultType, !left.get());
      default:
        throw new RuntimeError("!!!Critical Invalid UnaryApp " + unaryApp.op);
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Expressions.InfixApp} infixApp
   *
   * @returns {import('./store/value/istore_value').IStoreValue}
   */
  async evaluateInfixApp (store, infixApp) {
    const left = await this.evaluateExpression(store, infixApp.left);
    const right = await this.evaluateExpression(store, infixApp.right);
    let shouldImplicitCast = false;
    let resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
    if (Types.UNDEFINED.isCompatible(resultType)) {
      if (
        Config.enable_type_casting &&
        Store.canImplicitTypeCast(left.type, right.type)
      ) {
        shouldImplicitCast = true;
      } else {
        const stringInfoLeft = left.type.stringInfo();
        const infoLeft = stringInfoLeft[0];
        const stringInfoRight = right.type.stringInfo();
        const infoRight = stringInfoRight[0];
        throw ProcessorErrorFactory.invalid_infix_op_full(
          infixApp.op,
          infoLeft.type,
          infoLeft.dim,
          infoRight.type,
          infoRight.dim,
          infixApp.sourceInfo
        );
      }
    }
    let result = null;
    switch (infixApp.op.ord) {
      case Operators.ADD.ord: {
        if (Types.STRING.isCompatible(left.type)) {
          const rightStr = convertToString(right.get(), right.type);
          return new StoreValue(resultType, left.get() + rightStr);
        } else if (Types.STRING.isCompatible(right.type)) {
          const leftStr = convertToString(left.get(), left.type);
          return new StoreValue(resultType, leftStr + right.get());
        } else if (Types.CHAR.isCompatible(left.type)) {
          const strLeft = convertToString(left.get(), left.type);
          const strRight = convertToString(right.get(), right.type);
          return new StoreValue(resultType, strLeft + strRight);
        } else {
          return new StoreValue(resultType, left.get().plus(right.get()));
        }
      }
      case Operators.SUB.ord:
        return new StoreValue(resultType, left.get().minus(right.get()));
      case Operators.MULT.ord: {
        result = left.get().times(right.get());
        return new StoreValue(resultType, result);
      }
      case Operators.DIV.ord: {
        if (right.get() == 0) {
          throw ProcessorErrorFactory.divsion_by_zero_full(
            infixApp.toString(),
            infixApp.sourceInfo
          );
        }
        if (Types.INTEGER.isCompatible(resultType))
          result = left.get().divToInt(right.get());
        else result = left.get().div(right.get());
        return new StoreValue(resultType, result);
      }
      case Operators.MOD.ord: {
        let leftValue = left.get();
        let rightValue = right.get();
        if (shouldImplicitCast) {
          resultType = Types.INTEGER;
          leftValue = leftValue.trunc();
          rightValue = rightValue.trunc();
        }
        result = leftValue.modulo(rightValue);
        return new StoreValue(resultType, result);
      }
      case Operators.GT.ord: {
        let leftValue = left.get();
        let rightValue = right.get();
        if (Types.STRING.isCompatible(left.type)) {
          result = leftValue.length > rightValue.length;
        } else if (Types.CHAR.isCompatible(left.type)) {
          result = leftValue.charCodeAt(0) > rightValue.charCodeAt(0);
        } else {
          if (shouldImplicitCast) {
            resultType = Types.BOOLEAN;
            leftValue = leftValue.trunc();
            rightValue = rightValue.trunc();
          }
          result = leftValue.gt(rightValue);
        }
        return new StoreValue(resultType, result);
      }
      case Operators.GE.ord: {
        let leftValue = left.get();
        let rightValue = right.get();
        if (Types.STRING.isCompatible(left.type)) {
          result = leftValue.length >= rightValue.length;
        } else if (Types.CHAR.isCompatible(left.type)) {
          result = leftValue.charCodeAt(0) >= rightValue.charCodeAt(0);
        } else {
          if (shouldImplicitCast) {
            resultType = Types.BOOLEAN;
            leftValue = leftValue.trunc();
            rightValue = rightValue.trunc();
          }
          result = leftValue.gte(rightValue);
        }
        return new StoreValue(resultType, result);
      }
      case Operators.LT.ord: {
        let leftValue = left.get();
        let rightValue = right.get();
        if (Types.STRING.isCompatible(left.type)) {
          result = leftValue.length < rightValue.length;
        } else if (Types.CHAR.isCompatible(left.type)) {
          result = leftValue.charCodeAt(0) < rightValue.charCodeAt(0);
        } else {
          if (shouldImplicitCast) {
            resultType = Types.BOOLEAN;
            leftValue = leftValue.trunc();
            rightValue = rightValue.trunc();
          }
          result = leftValue.lt(rightValue);
        }
        return new StoreValue(resultType, result);
      }
      case Operators.LE.ord: {
        let leftValue = left.get();
        let rightValue = right.get();
        if (Types.STRING.isCompatible(left.type)) {
          result = leftValue.length <= rightValue.length;
        } else if (Types.CHAR.isCompatible(left.type)) {
          result = leftValue.charCodeAt(0) <= rightValue.charCodeAt(0);
        } else {
          if (shouldImplicitCast) {
            resultType = Types.BOOLEAN;
            leftValue = leftValue.trunc();
            rightValue = rightValue.trunc();
          }
          result = leftValue.lte(rightValue);
        }
        return new StoreValue(resultType, result);
      }
      case Operators.EQ.ord: {
        let leftValue = left.get();
        let rightValue = right.get();
        if (
          Types.INTEGER.isCompatible(left.type) ||
          Types.REAL.isCompatible(left.type)
        ) {
          if (shouldImplicitCast) {
            resultType = Types.BOOLEAN;
            leftValue = leftValue.trunc();
            rightValue = rightValue.trunc();
          }
          result = leftValue.eq(rightValue);
        } else {
          result = leftValue === rightValue;
        }
        return new StoreValue(resultType, result);
      }
      case Operators.NEQ.ord: {
        let leftValue = left.get();
        let rightValue = right.get();
        if (
          Types.INTEGER.isCompatible(left.type) ||
          Types.REAL.isCompatible(left.type)
        ) {
          if (shouldImplicitCast) {
            resultType = Types.BOOLEAN;
            leftValue = leftValue.trunc();
            rightValue = rightValue.trunc();
          }
          result = !leftValue.eq(rightValue);
        } else {
          result = leftValue !== rightValue;
        }
        return new StoreValue(resultType, result);
      }
      case Operators.AND.ord:
        return new StoreValue(resultType, left.get() && right.get());
      case Operators.OR.ord:
        return new StoreValue(resultType, left.get() || right.get());
      default:
        throw new RuntimeError("!!!Critical Invalid InfixApp " + infixApp.op);
    }
  }
}
