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/';
import * as Expressions from './../ast/expressions/';
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 { 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;
  }

  interpretAST () {
    this.prepareState();
    Location.clear();
    return this.initGlobal().then( _ => {
      const mainFunc = this.findMainFunction();
      if(mainFunc === null) {
        return Promise.reject(ProcessorErrorFactory.main_missing())
      }
      return this.runFunction(mainFunc, [], this.globalStore);
    });
  }

  initGlobal () {
    if(!this.checkContext(Context.BASE)) {
      return Promise.reject(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;
    }
  }

  runFunction (func, actualParameters, store) {
    const funcName = func.isMain ? IVProgProcessor.MAIN_INTERNAL_ID : func.name;
    const funcStore = new Store(funcName);
    funcStore.extendStore(this.globalStore);
    return new Promise((resolve, reject) => {
      const run_lambda = () => {
        const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
        newFuncStore$.then(sto => {
          this.context.push(Context.FUNCTION);
          this.stores.push(sto);
          return this.executeCommands(sto, func.variablesDeclarations)
            .then(stoWithVars => this.executeCommands(stoWithVars, func.commands)).then(finalSto => {
              this.stores.pop();
              this.context.pop();
              return finalSto;
            });
        }).then(resolve)
        .catch(reject);
      }
      run_lambda();
    });

  }

  associateParameters (formal_params, effective_params, caller_store, callee_store) {
    const funcName = callee_store.name === IVProgProcessor.MAIN_INTERNAL_ID ?
      LanguageDefinedFunction.getMainFunctionName() : callee_store.name;

    if (formal_params.length != effective_params.length) {
      return Promise.reject(ProcessorErrorFactory.invalid_parameters_size(funcName, formal_params.length, effective_params.length))
    }
    const promises$ = effective_params.map(actual_param => this.evaluateExpression(caller_store, actual_param));
    return Promise.all(promises$).then(values => {
      for (let i = 0; i < values.length; i++) {
        const sto_value = values[i];
        // console.log(callee_store.name);
        // console.log(sto_value);
        const exp = effective_params[i];
        let shouldTypeCast = false;
        const formalParameter = formal_params[i];
        if(!formalParameter.type.isCompatible(sto_value.type)) {
          if (Config.enable_type_casting && !formalParameter.byRef
            && Store.canImplicitTypeCast(formalParameter.type, sto_value.type)) {
              shouldTypeCast =  true;
          } else {
            return Promise.reject(ProcessorErrorFactory.invalid_parameter_type(funcName, exp.toString()))
          }
        }

        if(formalParameter.byRef && !sto_value.inStore()) {
          return Promise.reject(ProcessorErrorFactory.invalid_ref(funcName, exp.toString()))
        }

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

  executeCommands (store, cmds) {
    // helper to partially apply a function, in this case executeCommand
    const partial = (fun, cmd) => (sto) => fun(sto, cmd);
    return cmds.reduce((lastCommand, next) => {
      const nextCommand = partial(this.executeCommand.bind(this), next);
      return lastCommand.then(nextCommand);
    }, Promise.resolve(store));
  }

  executeCommand (store, cmd) {
    this.instruction_count += 1;
    return new Promise((resolve, reject) => {
      const command_lambda = () => {
        if(this.instruction_count >= Config.max_instruction_count) {
          return reject(ProcessorErrorFactory.exceed_max_instructions());
        } else if(this.forceKill) {
          return reject("FORCED_KILL!");
        } else if (store.mode === Modes.PAUSE) {
          return resolve(this.executeCommand(store, cmd));
        } else if(store.mode === Modes.RETURN) {
          return resolve(store);
        } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
          return resolve(store);
        } else if (this.mode === Modes.ABORT) {
          return reject(LocalizedStrings.getMessage('aborted_execution'));
        }
        if (cmd instanceof Commands.Declaration) {
          return resolve(this.executeDeclaration(store, cmd));
        } else if (cmd instanceof Commands.ArrayIndexAssign) {
          return resolve(this.executeArrayIndexAssign(store, cmd));
        } else if (cmd instanceof Commands.Assign) {
          return resolve(this.executeAssign(store, cmd));
        } else if (cmd instanceof Commands.Break) {
          return resolve(this.executeBreak(store, cmd));
        } else if (cmd instanceof Commands.Return) {
          return resolve(this.executeReturn(store, cmd));
        } else if (cmd instanceof Commands.IfThenElse) {
          return resolve(this.executeIfThenElse(store, cmd));
        } else if (cmd instanceof Commands.RepeatUntil) {
          return resolve(this.executeRepeatUntil(store, cmd));
        } else if (cmd instanceof Commands.While) {
          return resolve(this.executeWhile(store, cmd));
        } else if (cmd instanceof Commands.For) {
          return resolve(this.executeFor(store, cmd));
        } else if (cmd instanceof Commands.Switch) {
          return resolve(this.executeSwitch(store, cmd));
        } else if (cmd instanceof Expressions.FunctionCall) {
          return resolve(this.executeFunctionCall(store, cmd));
        } else if (cmd instanceof Commands.SysCall) {
          return resolve(this.executeSysCall(store, cmd));
        } else {
          return reject(ProcessorErrorFactory.unknown_command(cmd.sourceInfo))
        }
      };
      if(this.instruction_count % Config.suspend_threshold == 0) {
        //every 100th command should briefly delay its execution in order to allow the browser to process other things
        setTimeout(command_lambda, 5);
      } else {
        command_lambda();
      }
    })
  }

  executeSysCall (store, cmd) {
    const func = cmd.langFunc.bind(this);
    return func(store, cmd);
  }

  executeFunctionCall (store, cmd) {
    let func = null;
    if(cmd.isMainCall) {
      func = this.findMainFunction();
    } else {
      func = this.findFunction(cmd.id);
    }
    // if(this.function_call_stack.length >= Config.max_call_stack) {
    //   return Promise.reject(ProcessorErrorFactory.exceeded_recursive_calls(cmd.sourceInfo));
    // }
    this.function_call_stack.push(cmd.sourceInfo);
    return this.runFunction(func, cmd.actualParameters, store)
      .then(sto => {
        sto.destroy();
        if(!Types.VOID.isCompatible(func.returnType) && sto.mode !== Modes.RETURN) {
          const funcName = func.name === IVProgProcessor.MAIN_INTERNAL_ID ?
            LanguageDefinedFunction.getMainFunctionName() : func.name;
          return Promise.reject(ProcessorErrorFactory.function_no_return(funcName));
        } else {
          this.function_call_stack.pop();
          return store;
        }
      });
  }

  executeSwitch (store, cmd) {
    this.context.push(Context.BREAKABLE);
    const caseSequence = cmd.cases.reduce( (prev,next) => {
      return prev.then( tuple => {
        if(this.ignoreSwitchCases(tuple[1])) {
          return Promise.resolve(tuple);
        } else if(tuple[0] || next.isDefault) {
          return this.executeCommands(tuple[1], next.commands)
            .then(nSto => Promise.resolve([true, nSto]));
        } else {
          const equalityInfixApp = new Expressions.InfixApp(Operators.EQ, cmd.expression, next.expression);
          equalityInfixApp.sourceInfo = next.sourceInfo;
          return this.evaluateExpression(tuple[1],equalityInfixApp).then(stoObj => stoObj.get())
            .then(isEqual => {
              if (isEqual) {
                return this.executeCommands(tuple[1], next.commands)
                  .then(nSto => Promise.resolve([true, nSto]));
              } else {
                return Promise.resolve(tuple);
              }
          });
        }
      });
    }, Promise.resolve([false, store]));
    return caseSequence.then(tuple => {
      this.context.pop();
      const newStore = tuple[1];
      if (newStore.mode === Modes.BREAK) {
        newStore.mode = Modes.RUN;
      }
      return newStore;
    });
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.For} cmd
   */
  executeFor (store, cmd) {
    //BEGIN for -> while rewrite
    const initCmd = new Commands.Assign(cmd.for_id.id, cmd.for_from);
    initCmd.sourceInfo = cmd.sourceInfo;
    const expression_tuple = []; //(for conditional, is for increasing)
    if(cmd.for_pass == null) {
      expression_tuple.push(Promise.resolve(null));
      expression_tuple.push(this.evaluateExpression(store, new Expressions.InfixApp(Operators.GE, cmd.for_to, cmd.for_from)));
    } else {
      expression_tuple.push(this.evaluateExpression(store, new Expressions.InfixApp(Operators.GE, cmd.for_pass, new Expressions.IntLiteral(toInt(0)))));
      expression_tuple.push(Promise.resolve(null));
    }

    return Promise.all(expression_tuple).then (results => {
      // console.log(results);
      let is_forward = true;
      let is_end_gt_init = undefined;
      let condition = null;
      let pass_value = cmd.for_pass;
      if (results[0] == null) {
        // pass is null, we need to deduce a value for it
        is_end_gt_init = results[1].value;
      } else {
        is_forward = results[0].value
      }

      if(is_end_gt_init == null) {
        // console.log("pass is not null and is forward? ", is_forward);
        if(is_forward) {
          condition = new Expressions.InfixApp(Operators.LE, cmd.for_id, cmd.for_to);
        } else {
          condition = new Expressions.InfixApp(Operators.GE, cmd.for_id, cmd.for_to);
        }
        // console.log("Cond", condition);
      } else if(is_end_gt_init) {
        pass_value = new Expressions.IntLiteral(toInt(1));
        condition = new Expressions.InfixApp(Operators.LE, cmd.for_id, cmd.for_to);
      } else {
        pass_value = new Expressions.IntLiteral(toInt(-1));
        condition = new Expressions.InfixApp(Operators.GE, 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, pass_value));
        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);
    }).catch(error => Promise.reject(error));
  }

  executeRepeatUntil (store, cmd) {
    try {
      this.context.push(Context.BREAKABLE);
      const $newStore = this.executeCommands(store, cmd.commands);
      return $newStore.then(sto => {
        if(sto.mode === Modes.BREAK) {
          this.context.pop();
          sto.mode = Modes.RUN;
          return sto;
        }
        const $value = this.evaluateExpression(sto, cmd.expression);
        return $value.then(vl => {
          if (!vl.type.isCompatible(Types.BOOLEAN)) {
            return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo));
          }
          if (!vl.get()) {
            this.context.pop();
            return this.executeCommand(sto, cmd);
          } else {
            this.context.pop();
            return sto;
          }
        })
      })
    } catch (error) {
      return Promise.reject(error);
    }
  }

  executeWhile (store, cmd) {
    try {
      this.context.push(Context.BREAKABLE);
      const $value = this.evaluateExpression(store, cmd.expression);
      return $value.then(vl => {
        if(vl.type.isCompatible(Types.BOOLEAN)) {
          if(vl.get()) {
            const $newStore = this.executeCommands(store, cmd.commands);
            return $newStore.then(sto => {
              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;
          }
        } else {
          return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.expression.toString(), cmd.sourceInfo));
        }
      })

    } catch (error) {
      return Promise.reject(error);
    }
  }

  executeIfThenElse (store, cmd) {
    try {
      const $value = this.evaluateExpression(store, cmd.condition);
      return $value.then(vl => {
        if(vl.type.isCompatible(Types.BOOLEAN)) {
          if(vl.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 Promise.resolve(store);
          }
        } else {
          return Promise.reject(ProcessorErrorFactory.if_condition_type_full(cmd.condition.toString(), cmd.sourceInfo));
        }
      });
    } catch (error) {
      return Promise.reject(error);
    }
  }

  executeReturn (store, cmd) {
    try {
      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 = this.evaluateExpression(store, cmd.expression);

      return $value.then(value => {

        let real_value = value;
        if(value === null && funcType.isCompatible(Types.VOID)) {
          store.mode = Modes.RETURN;
          return Promise.resolve(store);
        }

        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];
          return Promise.reject(ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
          }
          real_value = Store.doImplicitCasting(funcType, value);
        } else {
          store.insertStore('$', real_value);
          store.mode = Modes.RETURN;
          return Promise.resolve(store);
        }
      });
    } catch (error) {
      return Promise.reject(error);
    }
  }

  executeBreak (store, cmd) {
    if(this.checkContext(Context.BREAKABLE)) {
      store.mode = Modes.BREAK;
      return Promise.resolve(store);
    } else {
      return Promise.reject(ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo));
    }
  }

  executeAssign (store, cmd) {
    try {
      const inStore = store.applyStore(cmd.id);
      if(inStore.isConst) {
        return Promise.reject(ProcessorErrorFactory.invalid_const_assignment_full(cmd.id, cmd.sourceInfo))
      }
      const $value = this.evaluateExpression(store, cmd.expression);
      return $value.then( vl => {
        let realValue = vl;
        if(!inStore.type.isCompatible(realValue.type)) {
          if(Config.enable_type_casting && Store.canImplicitTypeCast(inStore.type, vl.type)) {
            realValue = Store.doImplicitCasting(inStore.type, realValue);
          } else {
            const stringInfo = inStore.type.stringInfo()
            const info = stringInfo[0]
            const exp_type_string_info = vl.type.stringInfo();
            const exp_type_info = exp_type_string_info[0];
            const exp = cmd.expression.toString();
            return Promise.reject(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()) {
              return Promise.reject(ProcessorErrorFactory.invalid_vector_assignment_full(cmd.id, inStore.lines, exp, realValue.lines, cmd.sourceInfo));
            } else {
              return Promise.reject(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;
      });
    } catch (error) {
      return Promise.reject(error);
    }
  }

  executeArrayIndexAssign (store, cmd) {
    const mustBeArray = store.applyStore(cmd.id);
    let used_dims = 0;
    if(mustBeArray.isConst) {
      return Promise.reject(ProcessorErrorFactory.invalid_const_assignment_full(cmd.id, cmd.sourceInfo))
    }
    if(!(mustBeArray.type instanceof ArrayType)) {
      return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
    }
    const line$ = this.evaluateExpression(store, cmd.line);
    const column$ = this.evaluateExpression(store, cmd.column);
    const value$ =  this.evaluateExpression(store, cmd.expression);
    return Promise.all([line$, column$, value$]).then(([line_sv, column_sv, value]) => {
      if(!Types.INTEGER.isCompatible(line_sv.type)) {
        return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
      }
      const line = line_sv.get().toNumber();
      used_dims += 1;
      let column = undefined;
      if (column_sv != null) {
        if(!Types.INTEGER.isCompatible(column_sv.type)) {
          return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
        }
        column = column_sv.get().toNumber();
        used_dims += 1;
      }
      let actualValue = value;
      if (line >= mustBeArray.lines) {
        if(mustBeArray.isVector) {
          return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
        } else {
          return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
        }
      } else if (line < 0) {
        return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo))
      }
      if (column != null && mustBeArray.columns === 0 ){
        return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(cmd.id, cmd.sourceInfo));
      }
      if(column != null ) {
        if (column >= mustBeArray.columns) {
          return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(cmd.id, column,mustBeArray.columns, cmd.sourceInfo));
        } else if (column < 0) {
          return Promise.reject(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();
          return Promise.reject(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();
          return Promise.reject(ProcessorErrorFactory.invalid_matrix_index_assign_full(cmd.id, line, current_value.lines, exp, actualValue.lines, cmd.sourceInfo))
        }
      }

      // mustBeArray.setAt(actualValue, line, column);
      // store.updateStore(cmd.id, mustBeArray);
      return store.updateStoreArray(cmd.id, actualValue, line, column);
    });
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.Declaration} cmd
   */
  executeDeclaration (store, cmd) {
    try {
      let $value = Promise.resolve(null);
      if(cmd instanceof Commands.ArrayDeclaration) {
        return this.executeArrayDeclaration(store, cmd);
      } else {
        if(cmd.initial !== null) {
          $value = this.evaluateExpression(store, cmd.initial);
        }
        return $value.then(vl => {
          let realValue = vl;
          let temp = null;
          if (vl !== null) {
            if(!vl.type.isCompatible(cmd.type)) {
              if(Config.enable_type_casting && Store.canImplicitTypeCast(cmd.type, vl.type)) {
                realValue = Store.doImplicitCasting(cmd.type, realValue);
              } else {
                const stringInfo = vl.type.stringInfo();
                const info = stringInfo[0];
                const exp_type_string_info = vl.type.stringInfo();
                const exp_type_info = exp_type_string_info[0];
                const exp = cmd.expression.toString();
                return Promise.reject(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);
          } else {
            temp = new StoreValue(cmd.type, null, null, cmd.isConst);
          }
          store.insertStore(cmd.id, temp);
          return store;
        });
      }
    } catch (e) {
      return Promise.reject(e);
    }
  }

  /**
   *
   * @param {Store} store
   * @param {Commands.ArrayDeclaration} cmd
   */
  executeArrayDeclaration (store, cmd) {
    const $lines = this.evaluateExpression(store, cmd.lines);
    const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
    return Promise.all([$lines, $columns]).then(([line_sv, column_sv]) => {
      if(!Types.INTEGER.isCompatible(line_sv.type)) {
        return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
      }
      const line = line_sv.get().toNumber();
      if(line < 0) {
        return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo));
      }
      let column = null
      if (column_sv !== null) {
        if(!Types.INTEGER.isCompatible(column_sv.type)) {
          return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
        }
        column = column_sv.get().toNumber();
        if(column < 0) {
          return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo));
        }
      }
      let $value = Promise.resolve(null);
      if(cmd.initial !== null) {
        // array can only be initialized by a literal....
        $value = this.evaluateArrayLiteral(store, cmd.initial, cmd.type, line, column);
      }
      return $value.then(vector_list => {
        let temp = null;
        if (vector_list !== null) {
          temp = new ArrayStoreValue(cmd.type, vector_list, line, column, null, cmd.isConst);
        } else {
          temp = new ArrayStoreValue(cmd.type, [], line, column, null, cmd.isConst);
        }
        store.insertStore(cmd.id, temp);
        return store;
      })
    });
  }

  evaluateExpression (store, exp) {
    this.instruction_count += 1;
    return new Promise((resolve, reject) => {
      const expression_lambda = () => {
        if (this.mode === Modes.ABORT) {
          return reject(LocalizedStrings.getMessage('aborted_execution'));
        }
        if(this.instruction_count >= Config.max_instruction_count) {
          return reject(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 resolve(this.evaluateUnaryApp(store, exp));
        } else if (exp instanceof Expressions.InfixApp) {
          return resolve(this.evaluateInfixApp(store, exp));
        } else if (exp instanceof Expressions.ArrayAccess) {
          return resolve(this.evaluateArrayAccess(store, exp));
        } else if (exp instanceof Expressions.VariableLiteral) {
          return resolve(this.evaluateVariableLiteral(store, exp));
        } else if (exp instanceof Expressions.IntLiteral) {
          return resolve(this.evaluateLiteral(store, exp));
        } else if (exp instanceof Expressions.RealLiteral) {
          return resolve(this.evaluateLiteral(store, exp));
        } else if (exp instanceof Expressions.BoolLiteral) {
          return resolve(this.evaluateLiteral(store, exp));
        } else if (exp instanceof Expressions.StringLiteral) {
          return resolve(this.evaluateLiteral(store, exp));
        } else if (exp instanceof Expressions.ArrayLiteral) {
          return reject(new Error("Internal Error: The system should not eval an array literal."))
        } else if (exp instanceof Expressions.FunctionCall) {
          return resolve(this.evaluateFunctionCall(store, exp));
        }
        return resolve(null);
      };
      if(this.instruction_count % Config.suspend_threshold == 0) {
        //every 100th command should briefly delay its execution in order to allow the browser to process other things
        setTimeout(expression_lambda, 5);
      } else {
        expression_lambda();
      }
    });

  }

  evaluateFunctionCall (store, exp) {
    if(exp.isMainCall) {
      return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
    }
    const func = this.findFunction(exp.id);
    if(Types.VOID.isCompatible(func.returnType)) {
      return Promise.reject(ProcessorErrorFactory.void_in_expression_full(exp.id, exp.sourceInfo));
    }
    if(this.function_call_stack.length >= Config.max_call_stack) {
      return Promise.reject(ProcessorErrorFactory.exceeded_recursive_calls(exp.sourceInfo));
    }
    this.function_call_stack.push(exp.sourceInfo);
    const $newStore = this.runFunction(func, exp.actualParameters, store);
    return $newStore.then( sto => {
      if(sto.mode !== Modes.RETURN) {
        return Promise.reject(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 Promise.resolve(val);
    });
  }

  /**
   *
   * @param {Store} store
   * @param {Expressions.ArrayLiteral} exp
   * @param {ArrayType} type
   */
  evaluateArrayLiteral (store, exp, type, lines, columns) {
    if(!exp.isVector) {
      if(columns == null) {
        return Promise.reject(new Error("This should never happen: Vector cannot be initialized by a matrix"));
      }
      const $matrix = this.evaluateMatrix(store, exp, type, lines, columns);
      return Promise.all($matrix).then(vectorList => {
        const values = vectorList.reduce((prev, next) =>  prev.concat(next), []);
        return Promise.resolve(values);
      });
    } else {
      if(columns != null) {
        return Promise.reject(new Error("This should never happen: Matrix cannot be initialized by a vector"));
      }
      return this.evaluateVector(store, exp, type, lines).then(list => {
        return Promise.resolve(list);
      });
    }
  }

  /**
   * 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
   */
  evaluateVector (store, exps, type, n_elements) {
    const values =  exps.value;
    if(n_elements !== values.length) {
      return Promise.reject(ProcessorErrorFactory.invalid_number_elements_vector(n_elements, exps.toString(), values.length, exps.sourceInfo));
    }
    const actual_values = Promise.all(values.map( exp => this.evaluateExpression(store, exp)));
    return actual_values.then( values => {
      return values.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
            return Promise.reject(ProcessorErrorFactory.invalid_array_literal_type_full(exp_str, values[index].sourceInfo));
          }
          const new_value = Store.doImplicitCasting(type.innerType, v);
          return new_value;
        }
        return v;
      });
    });
  }

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

  evaluateLiteral (_, exp) {
    return Promise.resolve(new StoreValue(exp.type, exp.value));
  }

  evaluateVariableLiteral (store, exp) {
    try {
      const val = store.applyStore(exp.id);
      return Promise.resolve(val);
    } catch (error) {
      return Promise.reject(error);
    }
  }

  evaluateArrayAccess (store, exp) {
    const mustBeArray = store.getStoreObject(exp.id);
    if (!(mustBeArray.type instanceof ArrayType)) {
      return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(exp.id, exp.sourceInfo));
    }
    const $line = this.evaluateExpression(store, exp.line);
    const $column = this.evaluateExpression(store, exp.column);
    return Promise.all([$line, $column]).then(([line_sv, column_sv]) => {
      if(!Types.INTEGER.isCompatible(line_sv.type)) {
        return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
      }
      const line = line_sv.get().toNumber();
      let column = null;
      if(column_sv !== null) {
        if(!Types.INTEGER.isCompatible(column_sv.type)) {
          return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
        }
        column = column_sv.get().toNumber();
      }

      if (line >= mustBeArray.lines) {
        if(mustBeArray.isVector) {
          return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
        } else {
          return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
        }
      } else if (line < 0) {
        return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo));
      }
      if (column !== null && mustBeArray.columns === 0 ){
        return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(exp.id, exp.sourceInfo));
      }
      if(column !== null ) {
        if (column >= mustBeArray.columns) {
          return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(exp.id, column,mustBeArray.columns, exp.sourceInfo));
        } else if (column < 0) {
          return Promise.reject(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((v, c) => {
          return new StoreValueAddress(type, v, line, c, mustBeArray.id, mustBeArray.readOnly);
        });
        return Promise.resolve(new ArrayStoreValue(new ArrayType(type, 1),
          values, mustBeArray.columns, null, mustBeArray.id, mustBeArray.readOnly))
      } else {
        return Promise.resolve(new StoreValueAddress(type, result, line, column, mustBeArray.id, mustBeArray.readOnly));
      }
    });
  }

  evaluateUnaryApp (store, unaryApp) {
    const $left = this.evaluateExpression(store, unaryApp.left);
    return $left.then( left => {
      const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
      if (Types.UNDEFINED.isCompatible(resultType)) {
        const stringInfo = left.type.stringInfo();
        const info = stringInfo[0];
        return Promise.reject(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:
          return Promise.reject(new RuntimeError('!!!Critical Invalid UnaryApp '+ unaryApp.op));
      }
    });
  }

  evaluateInfixApp (store, infixApp) {
    const $left = this.evaluateExpression(store, infixApp.left);
    const $right = this.evaluateExpression(store, infixApp.right);
    return Promise.all([$left, $right]).then(values => {
      let shouldImplicitCast = false;
      const left = values[0];
      const right = values[1];
      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];
          return Promise.reject(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 {
            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) {
            return Promise.reject(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 (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 (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 (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 (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:
          return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
      }
    });
  }

}