ivprogProcessor.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. import { Store } from './store/store';
  2. import { StoreObject } from './store/storeObject';
  3. import { StoreObjectArray } from './store/storeObjectArray';
  4. import { StoreObjectRef } from './store/storeObjectRef';
  5. import { Modes } from './modes';
  6. import { Context } from './context';
  7. import { Types } from './../typeSystem/types';
  8. import { Operators } from './../ast/operators';
  9. import { LanguageDefinedFunction } from './definedFunctions';
  10. import { resultTypeAfterInfixOp, resultTypeAfterUnaryOp } from './compatibilityTable';
  11. import * as Commands from './../ast/commands/';
  12. import * as Expressions from './../ast/expressions/';
  13. import { StoreObjectArrayAddress } from './store/storeObjectArrayAddress';
  14. import { StoreObjectArrayAddressRef } from './store/storeObjectArrayAddressRef';
  15. import { ArrayType } from './../typeSystem/array_type';
  16. import { convertToString, toInt } from '../typeSystem/parsers';
  17. import { Config } from '../util/config';
  18. import Decimal from 'decimal.js';
  19. import { ProcessorErrorFactory } from './error/processorErrorFactory';
  20. import { RuntimeError } from './error/runtimeError';
  21. import { Type } from '../typeSystem/type';
  22. import { Literal } from '../ast/expressions/literal';
  23. export class IVProgProcessor {
  24. static get LOOP_TIMEOUT () {
  25. return Config.loopTimeout;
  26. }
  27. static set LOOP_TIMEOUT (ms) {
  28. Config.setConfig({loopTimeout: ms});
  29. }
  30. static get MAIN_INTERNAL_ID () {
  31. return "$main";
  32. }
  33. constructor (ast) {
  34. this.ast = ast;
  35. this.globalStore = new Store("$global");
  36. this.stores = [this.globalStore];
  37. this.context = [Context.BASE];
  38. this.input = null;
  39. this.forceKill = false;
  40. this.loopTimers = [];
  41. this.output = null;
  42. }
  43. registerInput (input) {
  44. if(this.input !== null)
  45. this.input = null;
  46. this.input = input;
  47. }
  48. registerOutput (output) {
  49. if(this.output !== null)
  50. this.output = null;
  51. this.output = output;
  52. }
  53. checkContext(context) {
  54. return this.context[this.context.length - 1] === context;
  55. }
  56. ignoreSwitchCases (store) {
  57. if (store.mode === Modes.RETURN) {
  58. return true;
  59. } else if (store.mode === Modes.BREAK) {
  60. return true;
  61. } else {
  62. return false;
  63. }
  64. }
  65. prepareState () {
  66. if(this.stores !== null) {
  67. for (let i = 0; i < this.stores.length; i++) {
  68. delete this.stores[i];
  69. }
  70. this.stores = null;
  71. }
  72. if(this.globalStore !== null)
  73. this.globalStore = null;
  74. this.globalStore = new Store("$global");
  75. this.stores = [this.globalStore];
  76. this.context = [Context.BASE];
  77. }
  78. interpretAST () {
  79. this.prepareState();
  80. return this.initGlobal().then( _ => {
  81. const mainFunc = this.findMainFunction();
  82. if(mainFunc === null) {
  83. throw ProcessorErrorFactory.main_missing();
  84. }
  85. return this.runFunction(mainFunc, [], this.globalStore);
  86. });
  87. }
  88. initGlobal () {
  89. if(!this.checkContext(Context.BASE)) {
  90. throw ProcessorErrorFactory.invalid_global_var();
  91. }
  92. return this.executeCommands(this.globalStore, this.ast.global);
  93. }
  94. findMainFunction () {
  95. return this.ast.functions.find(v => v.isMain);
  96. }
  97. findFunction (name) {
  98. if(name.match(/^\$.+$/)) {
  99. const fun = LanguageDefinedFunction.getFunction(name);
  100. if(!!!fun) {
  101. throw ProcessorErrorFactory.not_implemented(name);
  102. }
  103. return fun;
  104. } else {
  105. const val = this.ast.functions.find( v => v.name === name);
  106. if (!!!val) {
  107. throw ProcessorErrorFactory.function_missing(name);
  108. }
  109. return val;
  110. }
  111. }
  112. runFunction (func, actualParameters, store) {
  113. const funcName = func.isMain ? IVProgProcessor.MAIN_INTERNAL_ID : func.name;
  114. let funcStore = new Store(funcName);
  115. funcStore.extendStore(this.globalStore);
  116. let returnStoreObject = null;
  117. if(func.returnType instanceof ArrayType) {
  118. if(func.returnType.dimensions > 1) {
  119. returnStoreObject = new StoreObjectArray(func.returnType,-1,-1,[[]]);
  120. } else {
  121. returnStoreObject = new StoreObjectArray(func.returnType,-1,null,[]);
  122. }
  123. } else {
  124. returnStoreObject = new StoreObject(func.returnType, null);
  125. }
  126. funcStore.insertStore('$', returnStoreObject);
  127. const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  128. const outerRef = this;
  129. return newFuncStore$.then(sto => {
  130. this.context.push(Context.FUNCTION);
  131. this.stores.push(sto);
  132. return this.executeCommands(sto, func.variablesDeclarations)
  133. .then(stoWithVars => outerRef.executeCommands(stoWithVars, func.commands)).then(finalSto => {
  134. outerRef.stores.pop();
  135. outerRef.context.pop();
  136. return finalSto;
  137. });
  138. });
  139. }
  140. associateParameters (formalList, actualList, callerStore, calleeStore) {
  141. const funcName = calleeStore.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  142. LanguageDefinedFunction.getMainFunctionName() : calleeStore.name;
  143. if (formalList.length != actualList.length) {
  144. throw ProcessorErrorFactory.invalid_parameters_size(funcName, formalList.length, actualList.length);
  145. }
  146. const promises$ = actualList.map(actualParameter => this.evaluateExpression(callerStore, actualParameter));
  147. return Promise.all(promises$).then(values => {
  148. for (let i = 0; i < values.length; i++) {
  149. const stoObj = values[i];
  150. // console.log(calleeStore.name);
  151. // console.log(stoObj);
  152. const exp = actualList[i];
  153. let shouldTypeCast = false;
  154. const formalParameter = formalList[i];
  155. if(!formalParameter.type.isCompatible(stoObj.type)) {
  156. if (Config.enable_type_casting && !formalParameter.byRef
  157. && Store.canImplicitTypeCast(formalParameter.type, stoObj.type)) {
  158. shouldTypeCast = true;
  159. } else {
  160. throw ProcessorErrorFactory.invalid_parameter_type(funcName, exp.toString());
  161. }
  162. }
  163. if(formalParameter.byRef && !stoObj.inStore) {
  164. throw ProcessorErrorFactory.invalid_ref(funcName, exp.toString());
  165. }
  166. if(formalParameter.byRef) {
  167. let ref = null;
  168. if (stoObj instanceof StoreObjectArrayAddress) {
  169. ref = new StoreObjectArrayAddressRef(stoObj);
  170. } else {
  171. ref = new StoreObjectRef(stoObj.id, callerStore);
  172. }
  173. calleeStore.insertStore(formalParameter.id, ref);
  174. } else {
  175. let realValue = this.parseStoreObjectValue(stoObj);
  176. if (shouldTypeCast) {
  177. realValue = Store.doImplicitCasting(formalParameter.type, realValue);
  178. }
  179. calleeStore.insertStore(formalParameter.id, realValue);
  180. }
  181. }
  182. return calleeStore;
  183. });
  184. }
  185. executeCommands (store, cmds) {
  186. // helper to partially apply a function, in this case executeCommand
  187. const outerRef = this;
  188. const partial = (fun, cmd) => (sto) => fun(sto, cmd);
  189. return cmds.reduce((lastCommand, next) => {
  190. const nextCommand = partial(outerRef.executeCommand.bind(outerRef), next);
  191. return lastCommand.then(nextCommand);
  192. }, Promise.resolve(store));
  193. }
  194. executeCommand (store, cmd) {
  195. if(this.forceKill) {
  196. return Promise.reject("FORCED_KILL!");
  197. } else if (store.mode === Modes.PAUSE) {
  198. return Promise.resolve(this.executeCommand(store, cmd));
  199. } else if(store.mode === Modes.RETURN) {
  200. return Promise.resolve(store);
  201. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  202. return Promise.resolve(store);
  203. }
  204. if (cmd instanceof Commands.Declaration) {
  205. return this.executeDeclaration(store, cmd);
  206. } else if (cmd instanceof Commands.ArrayIndexAssign) {
  207. return this.executeArrayIndexAssign(store, cmd);
  208. } else if (cmd instanceof Commands.Assign) {
  209. return this.executeAssign(store, cmd);
  210. } else if (cmd instanceof Commands.Break) {
  211. return this.executeBreak(store, cmd);
  212. } else if (cmd instanceof Commands.Return) {
  213. return this.executeReturn(store, cmd);
  214. } else if (cmd instanceof Commands.IfThenElse) {
  215. return this.executeIfThenElse(store, cmd);
  216. } else if (cmd instanceof Commands.DoWhile) {
  217. return this.executeDoWhile(store, cmd);
  218. } else if (cmd instanceof Commands.While) {
  219. return this.executeWhile(store, cmd);
  220. } else if (cmd instanceof Commands.For) {
  221. return this.executeFor(store, cmd);
  222. } else if (cmd instanceof Commands.Switch) {
  223. return this.executeSwitch(store, cmd);
  224. } else if (cmd instanceof Expressions.FunctionCall) {
  225. return this.executeFunctionCall(store, cmd);
  226. } else if (cmd instanceof Commands.SysCall) {
  227. return this.executeSysCall(store, cmd);
  228. } else {
  229. throw ProcessorErrorFactory.unknown_command(cmd.sourceInfo);
  230. }
  231. }
  232. executeSysCall (store, cmd) {
  233. const func = cmd.langFunc.bind(this);
  234. return func(store, cmd);
  235. }
  236. executeFunctionCall (store, cmd) {
  237. let func = null;
  238. if(cmd.isMainCall) {
  239. func = this.findMainFunction();
  240. } else {
  241. func = this.findFunction(cmd.id);
  242. }
  243. return this.runFunction(func, cmd.actualParameters, store)
  244. .then(sto => {
  245. if(!Types.VOID.isCompatible(func.returnType) && sto.mode !== Modes.RETURN) {
  246. const funcName = func.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  247. LanguageDefinedFunction.getMainFunctionName() : func.name;
  248. return Promise.reject(ProcessorErrorFactory.function_no_return(funcName));
  249. } else {
  250. return store;
  251. }
  252. })
  253. }
  254. executeSwitch (store, cmd) {
  255. this.context.push(Context.BREAKABLE);
  256. const outerRef = this;
  257. const caseSequence = cmd.cases.reduce( (prev,next) => {
  258. return prev.then( tuple => {
  259. if(outerRef.ignoreSwitchCases(tuple[1])) {
  260. return Promise.resolve(tuple);
  261. } else if(tuple[0] || next.isDefault) {
  262. return outerRef.executeCommands(tuple[1], next.commands)
  263. .then(nSto => Promise.resolve([true, nSto]));
  264. } else {
  265. const equalityInfixApp = new Expressions.InfixApp(Operators.EQ, cmd.expression, next.expression);
  266. equalityInfixApp.sourceInfo = next.sourceInfo;
  267. return outerRef.evaluateExpression(tuple[1],equalityInfixApp).then(stoObj => stoObj.value)
  268. .then(isEqual => {
  269. if (isEqual) {
  270. return this.executeCommands(tuple[1], next.commands)
  271. .then(nSto => Promise.resolve([true, nSto]));
  272. } else {
  273. return Promise.resolve(tuple);
  274. }
  275. });
  276. }
  277. });
  278. }, Promise.resolve([false, store]));
  279. return caseSequence.then(tuple => {
  280. outerRef.context.pop();
  281. const newStore = tuple[1];
  282. if (newStore.mode === Modes.BREAK) {
  283. newStore.mode = Modes.RUN;
  284. }
  285. return newStore;
  286. });
  287. }
  288. /**
  289. *
  290. * @param {Store} store
  291. * @param {Commands.For} cmd
  292. */
  293. executeFor (store, cmd) {
  294. //BEGIN for -> while rewrite
  295. const initCmd = new Commands.Assign(cmd.for_id, cmd.for_from);
  296. initCmd.sourceInfo = cmd.sourceInfo;
  297. const is_forward_exp = new Expressions.InfixApp(Operators.GE, cmd.for_to, cmd.for_from);
  298. return this.evaluateExpression(store, is_forward_exp).then (result => {
  299. const is_forward = result.value;
  300. let condition = null;
  301. if (is_forward) {
  302. condition = new Expressions.InfixApp(Operators.LE, cmd.for_id, cmd.for_to);
  303. } else {
  304. condition = new Expressions.InfixApp(Operators.GE, cmd.for_id, cmd.for_to);
  305. }
  306. condition.sourceInfo = cmd.sourceInfo;
  307. let pass_value = cmd.for_pass;
  308. if(pass_value == null) {
  309. if(is_forward) {
  310. pass_value = new Expressions.IntLiteral(toInt(1));
  311. } else {
  312. pass_value = new Expressions.IntLiteral(toInt(-1));
  313. }
  314. }
  315. const increment = new Commands.Assign(cmd.for_id,
  316. new Expressions.InfixApp(Operators.ADD, cmd.for_id, pass_value));
  317. increment.sourceInfo = cmd.sourceInfo;
  318. const whileBlock = new Commands.CommandBlock([],
  319. cmd.commands.concat(increment));
  320. const forAsWhile = new Commands.While(condition, whileBlock);
  321. forAsWhile.sourceInfo = cmd.sourceInfo;
  322. //END for -> while rewrite
  323. const newCmdList = [initCmd,forAsWhile];
  324. return this.executeCommands(store, newCmdList);
  325. }).catch(error => Promise.reject(error));
  326. }
  327. executeDoWhile (store, cmd) {
  328. const outerRef = this;
  329. try {
  330. outerRef.loopTimers.push(Date.now());
  331. outerRef.context.push(Context.BREAKABLE);
  332. const $newStore = outerRef.executeCommands(store, cmd.commands);
  333. return $newStore.then(sto => {
  334. if(sto.mode === Modes.BREAK) {
  335. outerRef.context.pop();
  336. sto.mode = Modes.RUN;
  337. outerRef.loopTimers.pop();
  338. return sto;
  339. }
  340. const $value = outerRef.evaluateExpression(sto, cmd.expression);
  341. return $value.then(vl => {
  342. if (!vl.type.isCompatible(Types.BOOLEAN)) {
  343. return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo));
  344. }
  345. if (vl.value) {
  346. outerRef.context.pop();
  347. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  348. const time = outerRef.loopTimers[i];
  349. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  350. outerRef.forceKill = true;
  351. return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
  352. }
  353. }
  354. return outerRef.executeCommand(sto, cmd);
  355. } else {
  356. outerRef.context.pop();
  357. outerRef.loopTimers.pop();
  358. return sto;
  359. }
  360. })
  361. })
  362. } catch (error) {
  363. return Promise.reject(error);
  364. }
  365. }
  366. executeWhile (store, cmd) {
  367. const outerRef = this;
  368. try {
  369. outerRef.loopTimers.push(Date.now());
  370. outerRef.context.push(Context.BREAKABLE);
  371. const $value = outerRef.evaluateExpression(store, cmd.expression);
  372. return $value.then(vl => {
  373. if(vl.type.isCompatible(Types.BOOLEAN)) {
  374. if(vl.value) {
  375. const $newStore = outerRef.executeCommands(store, cmd.commands);
  376. return $newStore.then(sto => {
  377. outerRef.context.pop();
  378. if (sto.mode === Modes.BREAK) {
  379. outerRef.loopTimers.pop();
  380. sto.mode = Modes.RUN;
  381. return sto;
  382. }
  383. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  384. const time = outerRef.loopTimers[i];
  385. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  386. outerRef.forceKill = true;
  387. return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
  388. }
  389. }
  390. return outerRef.executeCommand(sto, cmd);
  391. });
  392. } else {
  393. outerRef.context.pop();
  394. outerRef.loopTimers.pop();
  395. return store;
  396. }
  397. } else {
  398. return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.expression.toString(), cmd.sourceInfo));
  399. }
  400. })
  401. } catch (error) {
  402. return Promise.reject(error);
  403. }
  404. }
  405. executeIfThenElse (store, cmd) {
  406. try {
  407. const $value = this.evaluateExpression(store, cmd.condition);
  408. return $value.then(vl => {
  409. if(vl.type.isCompatible(Types.BOOLEAN)) {
  410. if(vl.value) {
  411. return this.executeCommands(store, cmd.ifTrue.commands);
  412. } else if( cmd.ifFalse !== null){
  413. if(cmd.ifFalse instanceof Commands.IfThenElse) {
  414. return this.executeCommand(store, cmd.ifFalse);
  415. } else {
  416. return this.executeCommands(store, cmd.ifFalse.commands);
  417. }
  418. } else {
  419. return Promise.resolve(store);
  420. }
  421. } else {
  422. return Promise.reject(ProcessorErrorFactory.if_condition_type_full(cmd.condition.toString(), cmd.sourceInfo));
  423. }
  424. });
  425. } catch (error) {
  426. return Promise.reject(error);
  427. }
  428. }
  429. executeReturn (store, cmd) {
  430. try {
  431. const funcType = store.applyStore('$').type;
  432. const $value = this.evaluateExpression(store, cmd.expression);
  433. const funcName = store.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  434. LanguageDefinedFunction.getMainFunctionName() : store.name;
  435. return $value.then(vl => {
  436. if(vl === null && funcType.isCompatible(Types.VOID)) {
  437. store.mode = Modes.RETURN;
  438. return Promise.resolve(store);
  439. }
  440. if (vl === null || !funcType.isCompatible(vl.type)) {
  441. const stringInfo = funcType.stringInfo();
  442. const info = stringInfo[0];
  443. return Promise.reject(ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
  444. } else {
  445. let realValue = this.parseStoreObjectValue(vl);
  446. store.updateStore('$', realValue);
  447. store.mode = Modes.RETURN;
  448. return Promise.resolve(store);
  449. }
  450. });
  451. } catch (error) {
  452. return Promise.reject(error);
  453. }
  454. }
  455. executeBreak (store, cmd) {
  456. if(this.checkContext(Context.BREAKABLE)) {
  457. store.mode = Modes.BREAK;
  458. return Promise.resolve(store);
  459. } else {
  460. return Promise.reject(ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo));
  461. }
  462. }
  463. executeAssign (store, cmd) {
  464. try {
  465. const inStore = store.applyStore(cmd.id);
  466. const $value = this.evaluateExpression(store, cmd.expression);
  467. return $value.then( vl => {
  468. let realValue = this.parseStoreObjectValue(vl);
  469. if(!inStore.type.isCompatible(realValue.type)) {
  470. if(Config.enable_type_casting && Store.canImplicitTypeCast(inStore.type, vl.type)) {
  471. realValue = Store.doImplicitCasting(inStore.type, realValue);
  472. } else {
  473. const stringInfo = inStore.type.stringInfo()
  474. const info = stringInfo[0]
  475. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  476. }
  477. }
  478. store.updateStore(cmd.id, realValue)
  479. return store;
  480. });
  481. } catch (error) {
  482. return Promise.reject(error);
  483. }
  484. }
  485. executeArrayIndexAssign (store, cmd) {
  486. const mustBeArray = store.applyStore(cmd.id);
  487. if(!(mustBeArray.type instanceof ArrayType)) {
  488. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
  489. }
  490. const line$ = this.evaluateExpression(store, cmd.line);
  491. const column$ = this.evaluateExpression(store, cmd.column);
  492. const value$ = this.evaluateExpression(store, cmd.expression);
  493. return Promise.all([line$, column$, value$]).then(results => {
  494. const lineSO = results[0];
  495. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  496. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  497. }
  498. const line = lineSO.number;
  499. const columnSO = results[1];
  500. let column = null
  501. if (columnSO !== null) {
  502. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  503. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  504. }
  505. column = columnSO.number;
  506. }
  507. const value = this.parseStoreObjectValue(results[2]);
  508. let actualValue = value;
  509. if (line >= mustBeArray.lines) {
  510. if(mustBeArray.isVector) {
  511. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  512. } else {
  513. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  514. }
  515. } else if (line < 0) {
  516. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  517. }
  518. if (column !== null && mustBeArray.columns === null ){
  519. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(cmd.id, cmd.sourceInfo));
  520. }
  521. if(column !== null ) {
  522. if (column >= mustBeArray.columns) {
  523. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(cmd.id, column,mustBeArray.columns, cmd.sourceInfo));
  524. } else if (column < 0) {
  525. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  526. }
  527. }
  528. const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
  529. if (column !== null) {
  530. if (!newArray.type.canAccept(value.type)) {
  531. if(!Config.enable_type_casting || !Store.canImplicitTypeCast(mustBeArray.type.innerType, value.type)) {
  532. const type = mustBeArray.type.innerType;
  533. const stringInfo = type.stringInfo();
  534. const info = stringInfo[0];
  535. const exp = cmd.expression.toString();
  536. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  537. }
  538. actualValue = Store.doImplicitCasting(mustBeArray.type.innerType, value);
  539. }
  540. newArray.value[line].value[column] = actualValue;
  541. store.updateStore(cmd.id, newArray);
  542. } else {
  543. if(!newArray.type.canAccept(value.type)) {
  544. if(!Config.enable_type_casting || !Store.canImplicitTypeCast(mustBeArray.type.innerType, value.type)) {
  545. const type = mustBeArray.type;
  546. const stringInfo = type.stringInfo();
  547. const info = stringInfo[0];
  548. const exp = cmd.expression.toString();
  549. return Promise.reject(ProcessorErrorFactory.incompatible_types_array_full(exp,info.type, info.dim-1, cmd.sourceInfo));
  550. }
  551. actualValue = Store.doImplicitCasting(mustBeArray.type.innerType, value);
  552. }
  553. newArray.value[line] = actualValue;
  554. store.updateStore(cmd.id, newArray);
  555. }
  556. return store;
  557. });
  558. }
  559. /**
  560. *
  561. * @param {Store} store
  562. * @param {Commands.Declaration} cmd
  563. */
  564. executeDeclaration (store, cmd) {
  565. try {
  566. let $value = Promise.resolve(null);
  567. if(cmd instanceof Commands.ArrayDeclaration) {
  568. if(cmd.initial !== null) {
  569. // array can only be initialized by a literal....
  570. $value = this.evaluateArrayLiteral(store, cmd.initial, cmd.type);
  571. }
  572. const $lines = this.evaluateExpression(store, cmd.lines);
  573. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  574. return Promise.all([$lines, $columns, $value]).then(values => {
  575. const lineSO = values[0];
  576. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  577. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  578. }
  579. const line = lineSO.number;
  580. if(line < 0) {
  581. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  582. }
  583. const columnSO = values[1];
  584. let column = null
  585. if (columnSO !== null) {
  586. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  587. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  588. }
  589. column = columnSO.number;
  590. if(column < 0) {
  591. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  592. }
  593. }
  594. const value = values[2];
  595. const temp = new StoreObjectArray(cmd.type, line, column, null);
  596. store.insertStore(cmd.id, temp);
  597. let realValue = value;
  598. if (value !== null) {
  599. if(value instanceof StoreObjectArrayAddress) {
  600. if(value.type instanceof ArrayType) {
  601. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  602. } else {
  603. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  604. }
  605. }
  606. } else {
  607. realValue = new StoreObjectArray(cmd.type, line, column, [])
  608. if(column !== null) {
  609. for (let i = 0; i < line; i++) {
  610. realValue.value.push(new StoreObjectArray(new ArrayType(cmd.type.innerType, 1), column, null, []));
  611. }
  612. }
  613. }
  614. realValue.readOnly = cmd.isConst;
  615. store.updateStore(cmd.id, realValue);
  616. return store;
  617. });
  618. } else {
  619. if(cmd.initial !== null) {
  620. $value = this.evaluateExpression(store, cmd.initial);
  621. }
  622. const temp = new StoreObject(cmd.type, null);
  623. store.insertStore(cmd.id, temp);
  624. return $value.then(vl => {
  625. let realValue = vl;
  626. if (vl !== null) {
  627. if(!vl.type.isCompatible(cmd.type)) {
  628. if(Config.enable_type_casting && Store.canImplicitTypeCast(cmd.type, vl.type)) {
  629. realValue = Store.doImplicitCasting(cmd.type, realValue);
  630. } else {
  631. const stringInfo = typeInfo.type.stringInfo();
  632. const info = stringInfo[0];
  633. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  634. }
  635. }
  636. if(vl instanceof StoreObjectArrayAddress) {
  637. if(vl.type instanceof ArrayType) {
  638. return Promise.reject(new Error("!!!Critical Error: Compatibility check failed, a Type accepts a ArrayType"))
  639. } else {
  640. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  641. }
  642. }
  643. } else {
  644. realValue = new StoreObject(cmd.type, 0);
  645. }
  646. realValue.readOnly = cmd.isConst;
  647. store.updateStore(cmd.id, realValue);
  648. return store;
  649. });
  650. }
  651. } catch (e) {
  652. return Promise.reject(e);
  653. }
  654. }
  655. evaluateExpression (store, exp) {
  656. if (exp instanceof Expressions.UnaryApp) {
  657. return this.evaluateUnaryApp(store, exp);
  658. } else if (exp instanceof Expressions.InfixApp) {
  659. return this.evaluateInfixApp(store, exp);
  660. } else if (exp instanceof Expressions.ArrayAccess) {
  661. return this.evaluateArrayAccess(store, exp);
  662. } else if (exp instanceof Expressions.VariableLiteral) {
  663. return this.evaluateVariableLiteral(store, exp);
  664. } else if (exp instanceof Expressions.IntLiteral) {
  665. return this.evaluateLiteral(store, exp);
  666. } else if (exp instanceof Expressions.RealLiteral) {
  667. return this.evaluateLiteral(store, exp);
  668. } else if (exp instanceof Expressions.BoolLiteral) {
  669. return this.evaluateLiteral(store, exp);
  670. } else if (exp instanceof Expressions.StringLiteral) {
  671. return this.evaluateLiteral(store, exp);
  672. } else if (exp instanceof Expressions.ArrayLiteral) {
  673. return Promise.reject(new Error("Internal Error: The system should not eval an array literal."))
  674. } else if (exp instanceof Expressions.FunctionCall) {
  675. return this.evaluateFunctionCall(store, exp);
  676. }
  677. return Promise.resolve(null);
  678. }
  679. evaluateFunctionCall (store, exp) {
  680. if(exp.isMainCall) {
  681. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
  682. }
  683. const func = this.findFunction(exp.id);
  684. if(Types.VOID.isCompatible(func.returnType)) {
  685. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(exp.id, exp.sourceInfo));
  686. }
  687. const $newStore = this.runFunction(func, exp.actualParameters, store);
  688. return $newStore.then( sto => {
  689. if(sto.mode !== Modes.RETURN) {
  690. return Promise.reject(new Error("The function that was called did not had a return command: "+exp.id));
  691. }
  692. const val = sto.applyStore('$');
  693. if (val instanceof StoreObjectArray) {
  694. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  695. } else {
  696. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  697. }
  698. });
  699. }
  700. /**
  701. *
  702. * @param {Store} store
  703. * @param {Expressions.ArrayLiteral} exp
  704. * @param {ArrayType} type
  705. */
  706. evaluateArrayLiteral (store, exp, type) {
  707. const errorHelperFunction = (validationResult, exp) => {
  708. const errorCode = validationResult[0];
  709. let expectedColumns = null;
  710. let actualColumns = null;
  711. switch(errorCode) {
  712. case StoreObjectArray.WRONG_COLUMN_NUMBER: {
  713. expectedColumns = validationResult[1];
  714. actualColumns = validationResult[2];
  715. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_column_full(expectedColumns, actualColumns, exp.sourceInfo));
  716. }
  717. case StoreObjectArray.WRONG_LINE_NUMBER: {
  718. const lineValue = validationResult[1];
  719. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_line_full(arr.lines, lineValue, exp.sourceInfo));
  720. }
  721. case StoreObjectArray.WRONG_TYPE: {
  722. let line = null;
  723. let strExp = null;
  724. if (validationResult.length > 2) {
  725. line = validationResult[1];
  726. const column = validationResult[2];
  727. strExp = exp.value[line].value[column].toString()
  728. } else {
  729. line = validationResult[1];
  730. strExp = exp.value[line].toString()
  731. }
  732. // TODO - fix error message
  733. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_type_full(strExp, exp.sourceInfo)); }
  734. }
  735. };
  736. if(!exp.isVector) {
  737. const $matrix = this.evaluateMatrix(store, exp.value, type);
  738. return $matrix.then(list => {
  739. const arr = new StoreObjectArray(type, list.length, list[0].lines, list);
  740. const checkResult = arr.isValid;
  741. if(checkResult.length == 0)
  742. return Promise.resolve(arr);
  743. else {
  744. return errorHelperFunction(checkResult, exp);
  745. }
  746. });
  747. } else {
  748. return this.evaluateVector(store, exp.value, type).then(list => {
  749. const type = new ArrayType(list[0].type, 1);
  750. const stoArray = new StoreObjectArray(type, list.length, null, list);
  751. const checkResult = stoArray.isValid;
  752. if(checkResult.length == 0)
  753. return Promise.resolve(stoArray);
  754. else {
  755. return errorHelperFunction(checkResult, exp);
  756. }
  757. });
  758. }
  759. }
  760. /**
  761. * Evalautes a list of literals and expression composing the vector
  762. * @param {Store} store
  763. * @param {Literal[]} exps
  764. * @param {ArrayType} type
  765. * @returns {Promise<StoreObject[]>} store object list
  766. */
  767. evaluateVector (store, exps, type) {
  768. const actual_values = Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  769. return actual_values.then( values => {
  770. return values.map((v, index) => {
  771. if(!type.canAccept(v.type)) {
  772. if (!Config.enable_type_casting || !Store.canImplicitTypeCast(type.innerType, v.type)) {
  773. const stringInfo = v.type.stringInfo();
  774. const info = stringInfo[0];
  775. const exp_str = exps[index].toString();
  776. // TODO - fix error message
  777. throw ProcessorErrorFactory.invalid_array_literal_type_full(exp_str, exps[index].sourceInfo);
  778. }
  779. const new_value = Store.doImplicitCasting(type.innerType, v);
  780. return new_value;
  781. }
  782. return v;
  783. });
  784. });
  785. }
  786. /**
  787. * Evaluates a list of array literals composing the matrix
  788. * @param {Store} store
  789. * @param {Expressions.ArrayLiteral[]} exps
  790. * @param {ArrayType} type
  791. */
  792. evaluateMatrix (store, exps, type) {
  793. return Promise.all(exps.map( vector => {
  794. const vec_type = new ArrayType(type.innerType, 1);
  795. const $vector = this.evaluateVector(store, vector.value, vec_type);
  796. return $vector.then(list => {
  797. return new StoreObjectArray(vec_type, list.length, null, list)
  798. });
  799. } ));
  800. }
  801. evaluateLiteral (_, exp) {
  802. return Promise.resolve(new StoreObject(exp.type, exp.value));
  803. }
  804. evaluateVariableLiteral (store, exp) {
  805. try {
  806. const val = store.applyStore(exp.id);
  807. if (val instanceof StoreObjectArray) {
  808. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  809. } else {
  810. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  811. }
  812. } catch (error) {
  813. return Promise.reject(error);
  814. }
  815. }
  816. evaluateArrayAccess (store, exp) {
  817. const mustBeArray = store.applyStore(exp.id);
  818. if (!(mustBeArray.type instanceof ArrayType)) {
  819. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(exp.id, exp.sourceInfo));
  820. }
  821. const $line = this.evaluateExpression(store, exp.line);
  822. const $column = this.evaluateExpression(store, exp.column);
  823. return Promise.all([$line, $column]).then(values => {
  824. const lineSO = values[0];
  825. const columnSO = values[1];
  826. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  827. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  828. }
  829. const line = lineSO.number;
  830. let column = null;
  831. if(columnSO !== null) {
  832. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  833. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  834. }
  835. column = columnSO.number;
  836. }
  837. if (line >= mustBeArray.lines) {
  838. if(mustBeArray.isVector) {
  839. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  840. } else {
  841. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  842. }
  843. } else if (line < 0) {
  844. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  845. }
  846. if (column !== null && mustBeArray.columns === null ){
  847. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(exp.id, exp.sourceInfo));
  848. }
  849. if(column !== null ) {
  850. if (column >= mustBeArray.columns) {
  851. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(exp.id, column,mustBeArray.columns, exp.sourceInfo));
  852. } else if (column < 0) {
  853. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  854. }
  855. }
  856. return Promise.resolve(new StoreObjectArrayAddress(mustBeArray.id, line, column, store));
  857. });
  858. }
  859. evaluateUnaryApp (store, unaryApp) {
  860. const $left = this.evaluateExpression(store, unaryApp.left);
  861. return $left.then( left => {
  862. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  863. if (Types.UNDEFINED.isCompatible(resultType)) {
  864. const stringInfo = left.type.stringInfo();
  865. const info = stringInfo[0];
  866. return Promise.reject(ProcessorErrorFactory.invalid_unary_op_full(unaryApp.op, info.type, info.dim, unaryApp.sourceInfo));
  867. }
  868. switch (unaryApp.op.ord) {
  869. case Operators.ADD.ord:
  870. return new StoreObject(resultType, left.value);
  871. case Operators.SUB.ord:
  872. return new StoreObject(resultType, left.value.negated());
  873. case Operators.NOT.ord:
  874. return new StoreObject(resultType, !left.value);
  875. default:
  876. return Promise.reject(new RuntimeError('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  877. }
  878. });
  879. }
  880. evaluateInfixApp (store, infixApp) {
  881. const $left = this.evaluateExpression(store, infixApp.left);
  882. const $right = this.evaluateExpression(store, infixApp.right);
  883. return Promise.all([$left, $right]).then(values => {
  884. let shouldImplicitCast = false;
  885. const left = values[0];
  886. const right = values[1];
  887. let resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  888. if (Types.UNDEFINED.isCompatible(resultType)) {
  889. if (Config.enable_type_casting && Store.canImplicitTypeCast(left.type, right.type)) {
  890. shouldImplicitCast = true;
  891. } else {
  892. const stringInfoLeft = left.type.stringInfo();
  893. const infoLeft = stringInfoLeft[0];
  894. const stringInfoRight = right.type.stringInfo();
  895. const infoRight = stringInfoRight[0];
  896. return Promise.reject(ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim,
  897. infoRight.type,infoRight.dim,infixApp.sourceInfo));
  898. }
  899. }
  900. let result = null;
  901. switch (infixApp.op.ord) {
  902. case Operators.ADD.ord: {
  903. if(Types.STRING.isCompatible(left.type)) {
  904. const rightStr = convertToString(right.value, right.type);
  905. return new StoreObject(resultType, left.value + rightStr);
  906. } else if (Types.STRING.isCompatible(right.type)) {
  907. const leftStr = convertToString(left.value, left.type);
  908. return new StoreObject(resultType, leftStr + right.value);
  909. } else {
  910. return new StoreObject(resultType, left.value.plus(right.value));
  911. }
  912. }
  913. case Operators.SUB.ord:
  914. return new StoreObject(resultType, left.value.minus(right.value));
  915. case Operators.MULT.ord: {
  916. result = left.value.times(right.value);
  917. // if(result.dp() > Config.decimalPlaces) {
  918. // result = new Decimal(result.toFixed(Config.decimalPlaces));
  919. // }
  920. return new StoreObject(resultType, result);
  921. }
  922. case Operators.DIV.ord: {
  923. if (Types.INTEGER.isCompatible(resultType))
  924. result = left.value.divToInt(right.value);
  925. else
  926. result = left.value.div(right.value);
  927. // if(result.dp() > Config.decimalPlaces) {
  928. // result = new Decimal(result.toFixed(Config.decimalPlaces));
  929. // }
  930. return new StoreObject(resultType, result);
  931. }
  932. case Operators.MOD.ord: {
  933. let leftValue = left.value;
  934. let rightValue = right.value;
  935. if(shouldImplicitCast) {
  936. resultType = Types.INTEGER;
  937. leftValue = leftValue.trunc();
  938. rightValue = rightValue.trunc();
  939. }
  940. result = leftValue.modulo(rightValue);
  941. // if(result.dp() > Config.decimalPlaces) {
  942. // result = new Decimal(result.toFixed(Config.decimalPlaces));
  943. // }
  944. return new StoreObject(resultType, result);
  945. }
  946. case Operators.GT.ord: {
  947. let leftValue = left.value;
  948. let rightValue = right.value;
  949. if (Types.STRING.isCompatible(left.type)) {
  950. result = left.value.length > right.value.length;
  951. } else {
  952. if (shouldImplicitCast) {
  953. resultType = Types.BOOLEAN;
  954. leftValue = leftValue.trunc();
  955. rightValue = rightValue.trunc();
  956. }
  957. result = leftValue.gt(rightValue);
  958. }
  959. return new StoreObject(resultType, result);
  960. }
  961. case Operators.GE.ord: {
  962. let leftValue = left.value;
  963. let rightValue = right.value;
  964. if (Types.STRING.isCompatible(left.type)) {
  965. result = left.value.length >= right.value.length;
  966. } else {
  967. if (shouldImplicitCast) {
  968. resultType = Types.BOOLEAN;
  969. leftValue = leftValue.trunc();
  970. rightValue = rightValue.trunc();
  971. }
  972. result = leftValue.gte(rightValue);
  973. }
  974. return new StoreObject(resultType, result);
  975. }
  976. case Operators.LT.ord: {
  977. let leftValue = left.value;
  978. let rightValue = right.value;
  979. if (Types.STRING.isCompatible(left.type)) {
  980. result = left.value.length < right.value.length;
  981. } else {
  982. if (shouldImplicitCast) {
  983. resultType = Types.BOOLEAN;
  984. leftValue = leftValue.trunc();
  985. rightValue = rightValue.trunc();
  986. }
  987. result = leftValue.lt(rightValue);
  988. }
  989. return new StoreObject(resultType, result);
  990. }
  991. case Operators.LE.ord: {
  992. let leftValue = left.value;
  993. let rightValue = right.value;
  994. if (Types.STRING.isCompatible(left.type)) {
  995. result = left.value.length <= right.value.length;
  996. } else {
  997. if (shouldImplicitCast) {
  998. resultType = Types.BOOLEAN;
  999. leftValue = leftValue.trunc();
  1000. rightValue = rightValue.trunc();
  1001. }
  1002. result = leftValue.lte(rightValue);
  1003. }
  1004. return new StoreObject(resultType, result);
  1005. }
  1006. case Operators.EQ.ord: {
  1007. let leftValue = left.value;
  1008. let rightValue = right.value;
  1009. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  1010. if (shouldImplicitCast) {
  1011. resultType = Types.BOOLEAN;
  1012. leftValue = leftValue.trunc();
  1013. rightValue = rightValue.trunc();
  1014. }
  1015. result = leftValue.eq(rightValue);
  1016. } else {
  1017. result = left.value === right.value;
  1018. }
  1019. return new StoreObject(resultType, result);
  1020. }
  1021. case Operators.NEQ.ord: {
  1022. let leftValue = left.value;
  1023. let rightValue = right.value;
  1024. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  1025. if (shouldImplicitCast) {
  1026. resultType = Types.BOOLEAN;
  1027. leftValue = leftValue.trunc();
  1028. rightValue = rightValue.trunc();
  1029. }
  1030. result = !leftValue.eq(rightValue);
  1031. } else {
  1032. result = left.value !== right.value;
  1033. }
  1034. return new StoreObject(resultType, result);
  1035. }
  1036. case Operators.AND.ord:
  1037. return new StoreObject(resultType, left.value && right.value);
  1038. case Operators.OR.ord:
  1039. return new StoreObject(resultType, left.value || right.value);
  1040. default:
  1041. return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
  1042. }
  1043. });
  1044. }
  1045. parseStoreObjectValue (vl) {
  1046. let realValue = vl;
  1047. if(vl instanceof StoreObjectArrayAddress) {
  1048. if(vl.type instanceof ArrayType) {
  1049. switch(vl.type.dimensions) {
  1050. case 1: {
  1051. realValue = new StoreObjectArray(vl.type, vl.value.length, null, vl.value);
  1052. break;
  1053. }
  1054. default: {
  1055. throw new RuntimeError("Three dimensional array address...");
  1056. }
  1057. }
  1058. } else {
  1059. realValue = new StoreObject(vl.type, vl.value);
  1060. }
  1061. }
  1062. return realValue;
  1063. }
  1064. }