ivprogProcessor.js 41 KB

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