ivprogProcessor.js 39 KB

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