1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084 |
- import { Store } from './store/store';
- import { StoreObjectArray } from './store/storeObjectArray';
- 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 { StoreObjectArrayAddress } from './store/storeObjectArrayAddress';
- import { StoreObjectArrayAddressRef } from './store/storeObjectArrayAddressRef';
- import { ArrayType } from './../typeSystem/array_type';
- import { convertToString } 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';
- export class IVProgProcessor {
- static get LOOP_TIMEOUT () {
- return Config.loopTimeout;
- }
- static set LOOP_TIMEOUT (ms) {
- Config.setConfig({loopTimeout: ms});
- }
- 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.loopTimers = [];
- this.output = null;
- }
- 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];
- }
- interpretAST () {
- this.prepareState();
- Location.clear();
- return this.initGlobal().then( _ => {
- const mainFunc = this.findMainFunction();
- if(mainFunc === null) {
- throw ProcessorErrorFactory.main_missing();
- }
- return this.runFunction(mainFunc, [], this.globalStore);
- });
- }
- initGlobal () {
- if(!this.checkContext(Context.BASE)) {
- throw 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(/^\$.+$/)) {
- 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);
- let returnStoreObject = null;
- if(func.returnType instanceof ArrayType) {
- if(func.returnType.dimensions > 1) {
- returnStoreObject = new StoreObjectArray(func.returnType,-1,-1,[[]]);
- } else {
- returnStoreObject = new StoreObjectArray(func.returnType,-1,null,[]);
- }
- } else {
- returnStoreObject = new StoreValue(func.returnType, null, null);//new StoreObject(func.returnType, Location.allocate(null));
- }
- funcStore.insertStore('$', returnStoreObject);
- const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
- const outerRef = this;
- return newFuncStore$.then(sto => {
- this.context.push(Context.FUNCTION);
- this.stores.push(sto);
- return this.executeCommands(sto, func.variablesDeclarations)
- .then(stoWithVars => outerRef.executeCommands(stoWithVars, func.commands)).then(finalSto => {
- outerRef.stores.pop();
- outerRef.context.pop();
- return finalSto;
- });
- });
- }
- 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) {
- throw 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 {
- throw ProcessorErrorFactory.invalid_parameter_type(funcName, exp.toString());
- }
- }
- if(formalParameter.byRef && !sto_value.inStore()) {
- throw 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);
- } 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 outerRef = this;
- const partial = (fun, cmd) => (sto) => fun(sto, cmd);
- return cmds.reduce((lastCommand, next) => {
- const nextCommand = partial(outerRef.executeCommand.bind(outerRef), next);
- return lastCommand.then(nextCommand);
- }, Promise.resolve(store));
- }
- executeCommand (store, cmd) {
- if(this.forceKill) {
- return Promise.reject("FORCED_KILL!");
- } else if (store.mode === Modes.PAUSE) {
- return Promise.resolve(this.executeCommand(store, cmd));
- } else if(store.mode === Modes.RETURN) {
- return Promise.resolve(store);
- } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
- return Promise.resolve(store);
- }
- 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.DoWhile) {
- return this.executeDoWhile(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);
- }
- }
- 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);
- }
- 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 {
- return store;
- }
- });
- }
- executeSwitch (store, cmd) {
- this.context.push(Context.BREAKABLE);
- const outerRef = this;
- const caseSequence = cmd.cases.reduce( (prev,next) => {
- return prev.then( tuple => {
- if(outerRef.ignoreSwitchCases(tuple[1])) {
- return Promise.resolve(tuple);
- } else if(tuple[0] || next.isDefault) {
- return outerRef.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 outerRef.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 => {
- outerRef.context.pop();
- const newStore = tuple[1];
- if (newStore.mode === Modes.BREAK) {
- newStore.mode = Modes.RUN;
- }
- return newStore;
- });
- }
- executeFor (store, cmd) {
- try {
- //BEGIN for -> while rewrite
- const initCmd = cmd.assignment;
- const condition = cmd.condition;
- const increment = cmd.increment;
- 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) {
- return Promise.reject(error);
- }
- }
- executeDoWhile (store, cmd) {
- const outerRef = this;
- try {
- outerRef.loopTimers.push(Date.now());
- outerRef.context.push(Context.BREAKABLE);
- const $newStore = outerRef.executeCommands(store, cmd.commands);
- return $newStore.then(sto => {
- if(sto.mode === Modes.BREAK) {
- outerRef.context.pop();
- sto.mode = Modes.RUN;
- outerRef.loopTimers.pop();
- return sto;
- }
- const $value = outerRef.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()) {
- outerRef.context.pop();
- if(outerRef.loopTimers.length > 0) {
- const time = outerRef.loopTimers[0];
- if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
- outerRef.forceKill = true;
- return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
- }
- }
- return outerRef.executeCommand(sto, cmd);
- } else {
- outerRef.context.pop();
- outerRef.loopTimers.pop();
- return sto;
- }
- })
- })
- } catch (error) {
- return Promise.reject(error);
- }
- }
- executeWhile (store, cmd) {
- const outerRef = this;
- try {
- outerRef.loopTimers.push(Date.now());
- outerRef.context.push(Context.BREAKABLE);
- const $value = outerRef.evaluateExpression(store, cmd.expression);
- return $value.then(vl => {
- if(vl.type.isCompatible(Types.BOOLEAN)) {
- if(vl.get()) {
- const $newStore = outerRef.executeCommands(store, cmd.commands);
- return $newStore.then(sto => {
- outerRef.context.pop();
- if (sto.mode === Modes.BREAK) {
- outerRef.loopTimers.pop();
- sto.mode = Modes.RUN;
- return sto;
- }
- if (outerRef.loopTimers.length > 0) {
- const time = outerRef.loopTimers[0];
- if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
- outerRef.forceKill = true;
- return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
- }
- }
- return outerRef.executeCommand(sto, cmd);
- });
- } else {
- outerRef.context.pop();
- outerRef.loopTimers.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 funcType = store.applyStore('$').type;
- const $value = this.evaluateExpression(store, cmd.expression);
- const funcName = store.name === IVProgProcessor.MAIN_INTERNAL_ID ?
- LanguageDefinedFunction.getMainFunctionName() : store.name;
- return $value.then(vl => {
- if(vl === null && funcType.isCompatible(Types.VOID)) {
- store.mode = Modes.RETURN;
- return Promise.resolve(store);
- }
- if (vl === null || !funcType.isCompatible(vl.type)) {
- const stringInfo = funcType.stringInfo();
- const info = stringInfo[0];
- return Promise.reject(ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
- } else {
- const realValue = this.parseStoreObjectValue(vl);
- store.updateStore('$', realValue);
- 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);
- const $value = this.evaluateExpression(store, cmd.expression);
- return $value.then( vl => {
- let realValue = this.parseStoreObjectValue(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]
- return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
- }
- }
-
- store.updateStore(cmd.id, realValue)
- return store;
- });
- } catch (error) {
- return Promise.reject(error);
- }
- }
- executeArrayIndexAssign (store, cmd) {
- const mustBeArray = store.applyStore(cmd.id);
- 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(results => {
- const lineSO = results[0];
- if(!Types.INTEGER.isCompatible(lineSO.type)) {
- return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
- }
- const line = lineSO.get();
- const columnSO = results[1];
- let column = null
- if (columnSO !== null) {
- if(!Types.INTEGER.isCompatible(columnSO.type)) {
- return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
- }
- column = columnSO.get();
- }
- const value = this.parseStoreObjectValue(results[2]);
- 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) {
- throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
- }
- if (column !== null && mustBeArray.columns === null ){
- 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) {
- throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
- }
- }
- const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
- if (column !== null) {
- if (!newArray.type.canAccept(value.type)) {
- 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 = cmd.expression.toString();
- return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
- }
- actualValue = Store.doImplicitCasting(mustBeArray.type.innerType, value);
- }
- newArray.value[line].value[column] = actualValue;
- store.updateStore(cmd.id, newArray);
- } else {
- if(!newArray.type.canAccept(value.type)) {
- if(!Config.enable_type_casting || !Store.canImplicitTypeCast(mustBeArray.type.innerType, value.type)) {
- const type = mustBeArray.type;
- const stringInfo = type.stringInfo();
- const info = stringInfo[0];
- const exp = cmd.expression.toString();
- return Promise.reject(ProcessorErrorFactory.incompatible_types_array_full(exp,info.type, info.dim-1, cmd.sourceInfo));
- }
- actualValue = Store.doImplicitCasting(mustBeArray.type.innerType, value);
- }
- newArray.value[line] = actualValue;
- store.updateStore(cmd.id, newArray);
- }
- return store;
- });
- }
- /**
- *
- * @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];
- return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, 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) {
- throw 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) {
- throw 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) {
- 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.ArrayLiteral) {
- return Promise.reject(new Error("Internal Error: The system should not eval an array literal."))
- } else if (exp instanceof Expressions.FunctionCall) {
- return this.evaluateFunctionCall(store, exp);
- }
- return Promise.resolve(null);
- }
- 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));
- }
- const $newStore = this.runFunction(func, exp.actualParameters, store);
- return $newStore.then( sto => {
- if(sto.mode !== Modes.RETURN) {
- return Promise.reject(new Error("The function that was called did not have a return command: "+exp.id));
- }
- const val = sto.applyStore('$');
- sto.destroy();
- if (val instanceof StoreObjectArray) {
- return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
- } else {
- return val;
- }
- });
- }
- /**
- *
- * @param {Store} store
- * @param {Expressions.ArrayLiteral} exp
- * @param {ArrayType} type
- */
- evaluateArrayLiteral (store, exp, type, lines, columns) {
- if(!exp.isVector) {
- if(columns == null) {
- throw new Error("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) {
- throw new Error("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) {
- throw new Error("invalid number of elements to array literal...");
- }
- 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)) {
- 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 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) {
- throw new Error("Invalid number of lines to matrix literal...");
- }
- 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);
- // if (val instanceof StoreObjectArray) {
- // return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
- // } else {
- // 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) {
- throw 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) {
- throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
- }
- }
- const result = mustBeArray.getAt(line, column);
- const type = mustBeArray.type.innerType;
- if(Array.isArray(result)) {
- let l = 0;
- const values = result.map(v => {
- if(!Array.isArray(v)) {
- return new StoreValueAddress(type.innerType, v, l++, undefined, mustBeArray.id, mustBeArray.readOnly);
- } else {
- throw new Error("Indexing 3D structure....");
- }
- });
- 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));
- }
- //return Promise.resolve(mustBeArray.getAt(line, column));
- });
- }
- 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());
- // if(result.dp() > Config.decimalPlaces) {
- // result = new Decimal(result.toFixed(Config.decimalPlaces));
- // }
- return new StoreValue(resultType, result);
- }
- case Operators.DIV.ord: {
- if (Types.INTEGER.isCompatible(resultType))
- result = left.get().divToInt(right.get());
- else
- result = left.get().div(right.get());
- // if(result.dp() > Config.decimalPlaces) {
- // result = new Decimal(result.toFixed(Config.decimalPlaces));
- // }
- 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);
- // if(result.dp() > Config.decimalPlaces) {
- // result = new Decimal(result.toFixed(Config.decimalPlaces));
- // }
- 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));
- }
- });
- }
- parseStoreObjectValue (vl) {
- let realValue = vl;
- if(vl instanceof StoreObjectArrayAddress) {
- if(vl.type instanceof ArrayType) {
- switch(vl.type.dimensions) {
- case 1: {
- realValue = new StoreObjectArray(vl.type, vl.get().length, null, vl.get());
- break;
- }
- default: {
- throw new RuntimeError("Three dimensional array address...");
- }
- }
- } else {
- realValue = new StoreValue(vl.type, vl.get());
- }
- }
- return realValue;
- }
- }
|