ivprogProcessor.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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 { CompoundType } from './../typeSystem/compoundType';
  16. import { convertToString } from '../typeSystem/parsers';
  17. import { Config } from '../util/config';
  18. import Decimal from 'decimal.js';
  19. export class IVProgProcessor {
  20. static get LOOP_TIMEOUT () {
  21. return Config.loopTimeout;
  22. }
  23. static set LOOP_TIMEOUT (ms) {
  24. Config.setConfig({loopTimeout: ms});
  25. }
  26. constructor (ast) {
  27. this.ast = ast;
  28. this.globalStore = new Store("$global");
  29. this.stores = [this.globalStore];
  30. this.context = [Context.BASE];
  31. this.input = null;
  32. this.forceKill = false;
  33. this.loopTimers = [];
  34. this.output = null;
  35. }
  36. registerInput (input) {
  37. if(this.input !== null)
  38. this.input = null;
  39. this.input = input;
  40. }
  41. registerOutput (output) {
  42. if(this.output !== null)
  43. this.output = null;
  44. this.output = output;
  45. }
  46. checkContext(context) {
  47. return this.context[this.context.length - 1] === context;
  48. }
  49. ignoreSwitchCases (store) {
  50. if (store.mode === Modes.RETURN) {
  51. return true;
  52. } else if (store.mode === Modes.BREAK) {
  53. return true;
  54. } else {
  55. return false;
  56. }
  57. }
  58. prepareState () {
  59. if(this.stores !== null) {
  60. for (let i = 0; i < this.stores.length; i++) {
  61. delete this.stores[i];
  62. }
  63. this.stores = null;
  64. }
  65. if(this.globalStore !== null)
  66. this.globalStore = null;
  67. this.globalStore = new Store("$global");
  68. this.stores = [this.globalStore];
  69. this.context = [Context.BASE];
  70. }
  71. interpretAST () {
  72. this.prepareState();
  73. this.initGlobal();
  74. const mainFunc = this.findMainFunction();
  75. if(mainFunc === null) {
  76. // TODO: Better error message
  77. throw new Error("Missing main funciton.");
  78. }
  79. return this.runFunction(mainFunc, [], this.globalStore);
  80. }
  81. initGlobal () {
  82. if(!this.checkContext(Context.BASE)) {
  83. throw new Error("!!!CRITICAL: Invalid call to initGlobal outside BASE context!!!");
  84. }
  85. this.ast.global.forEach(decl => {
  86. this.executeCommand(this.globalStore, decl).then(sto => this.globalStore = sto);
  87. });
  88. }
  89. findMainFunction () {
  90. return this.ast.functions.find(v => v.isMain);
  91. }
  92. findFunction (name) {
  93. if(name.match(/^\$.+$/)) {
  94. const fun = LanguageDefinedFunction.getFunction(name);
  95. if(!!!fun) {
  96. throw new Error("!!!Internal Error. Language defined function not implemented -> " + name + "!!!");
  97. }
  98. return fun;
  99. } else {
  100. const val = this.ast.functions.find( v => v.name === name);
  101. if (!!!val) {
  102. // TODO: better error message;
  103. throw new Error(`Function ${name} is not defined.`);
  104. }
  105. return val;
  106. }
  107. }
  108. runFunction (func, actualParameters, store) {
  109. const funcName = func.isMain ? 'main' : func.name;
  110. let funcStore = new Store(funcName);
  111. funcStore.extendStore(this.globalStore);
  112. let returnStoreObject = null;
  113. if(func.returnType instanceof CompoundType) {
  114. if(func.returnType.dimensions > 1) {
  115. returnStoreObject = new StoreObjectArray(func.returnType,-1,-1,[[]]);
  116. } else {
  117. returnStoreObject = new StoreObjectArray(func.returnType,-1,null,[]);
  118. }
  119. } else {
  120. returnStoreObject = new StoreObject(func.returnType, null);
  121. }
  122. funcStore.insertStore('$', returnStoreObject);
  123. const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  124. return newFuncStore$.then(sto => {
  125. this.context.push(Context.FUNCTION);
  126. this.stores.push(sto);
  127. return this.executeCommands(sto, func.variablesDeclarations)
  128. .then(stoWithVars => this.executeCommands(stoWithVars, func.commands)).then(finalSto => {
  129. this.stores.pop();
  130. this.context.pop();
  131. return finalSto;
  132. });
  133. });
  134. }
  135. associateParameters (formalList, actualList, callerStore, calleeStore) {
  136. if (formalList.length != actualList.length) {
  137. // TODO: Better error message
  138. throw new Error("Numbers of parameters doesn't match");
  139. }
  140. const promises$ = actualList.map(actualParameter => this.evaluateExpression(callerStore, actualParameter));
  141. return Promise.all(promises$).then(values => {
  142. for (let i = 0; i < values.length; i++) {
  143. const stoObj = values[i];
  144. const formalParameter = formalList[i];
  145. if(formalParameter.type.isCompatible(stoObj.type)) {
  146. if(formalParameter.byRef && !stoObj.inStore) {
  147. throw new Error('You must inform a variable as parameter');
  148. }
  149. if(formalParameter.byRef) {
  150. let ref = null;
  151. if (stoObj instanceof StoreObjectArrayAddress) {
  152. ref = new StoreObjectArrayAddressRef(stoObj);
  153. } else {
  154. ref = new StoreObjectRef(stoObj.id, callerStore);
  155. }
  156. calleeStore.insertStore(formalParameter.id, ref);
  157. } else {
  158. let realValue = this.parseStoreObjectValue(stoObj);
  159. calleeStore.insertStore(formalParameter.id, realValue);
  160. }
  161. } else {
  162. throw new Error(`Parameter ${formalParameter.id} is not compatible with the value given.`);
  163. }
  164. }
  165. return calleeStore;
  166. });
  167. }
  168. executeCommands (store, cmds) {
  169. // helper to partially apply a function, in this case executeCommand
  170. const outerRef = this;
  171. const partial = (fun, cmd) => (sto) => fun(sto, cmd);
  172. return cmds.reduce((lastCommand, next) => {
  173. const nextCommand = partial(outerRef.executeCommand.bind(outerRef), next);
  174. return lastCommand.then(nextCommand);
  175. }, Promise.resolve(store));
  176. }
  177. executeCommand (store, cmd) {
  178. if(this.forceKill) {
  179. return Promise.reject("Interrupção forçada do programa!");
  180. } else if (store.mode === Modes.PAUSE) {
  181. return Promise.resolve(this.executeCommand(store, cmd));
  182. } else if(store.mode === Modes.RETURN) {
  183. return Promise.resolve(store);
  184. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  185. return Promise.resolve(store);
  186. }
  187. if (cmd instanceof Commands.Declaration) {
  188. return this.executeDeclaration(store, cmd);
  189. } else if (cmd instanceof Commands.ArrayIndexAssign) {
  190. return this.executeArrayIndexAssign(store, cmd);
  191. } else if (cmd instanceof Commands.Assign) {
  192. return this.executeAssign(store, cmd);
  193. } else if (cmd instanceof Commands.Break) {
  194. return this.executeBreak(store, cmd);
  195. } else if (cmd instanceof Commands.Return) {
  196. return this.executeReturn(store, cmd);
  197. } else if (cmd instanceof Commands.IfThenElse) {
  198. return this.executeIfThenElse(store, cmd);
  199. } else if (cmd instanceof Commands.While) {
  200. return this.executeWhile(store, cmd);
  201. } else if (cmd instanceof Commands.DoWhile) {
  202. return this.executeDoWhile(store, cmd);
  203. } else if (cmd instanceof Commands.For) {
  204. return this.executeFor(store, cmd);
  205. } else if (cmd instanceof Commands.Switch) {
  206. return this.executeSwitch(store, cmd);
  207. } else if (cmd instanceof Commands.FunctionCall) {
  208. return this.executeFunctionCall(store, cmd);
  209. } else if (cmd instanceof Commands.SysCall) {
  210. return this.executeSysCall(store, cmd);
  211. } else {
  212. throw new Error("!!!CRITICAL A unknown command was found!!!\n" + cmd);
  213. }
  214. }
  215. executeSysCall (store, cmd) {
  216. const func = cmd.langFunc.bind(this);
  217. return func(store, cmd);
  218. }
  219. executeFunctionCall (store, cmd) {
  220. const func = this.findFunction(cmd.id);
  221. return this.runFunction(func, cmd.actualParameters, store)
  222. .then(sto => {
  223. if(!Types.VOID.isCompatible(func.returnType) && sto.mode !== Modes.RETURN) {
  224. // TODO: better error message
  225. return Promise.reject(new Error(`Function ${func.name} must have a return command`));
  226. } else {
  227. return store;
  228. }
  229. })
  230. }
  231. executeSwitch (store, cmd) {
  232. this.context.push(Context.BREAKABLE);
  233. const auxCaseFun = (promise, switchExp, aCase) => {
  234. return promise.then( result => {
  235. const sto = result.sto;
  236. if (this.ignoreSwitchCases(sto)) {
  237. return Promise.resolve(result);
  238. } else if (result.wasTrue || aCase.isDefault) {
  239. const $newSto = this.executeCommands(result.sto,aCase.commands);
  240. return $newSto.then(nSto => {
  241. return Promise.resolve({wasTrue: true, sto: nSto});
  242. });
  243. } else {
  244. const $value = this.evaluateExpression(sto,
  245. new Expressions.InfixApp(Operators.EQ, switchExp, aCase.expression));
  246. return $value.then(vl => {
  247. if (vl.value) {
  248. const $newSto = this.executeCommands(result.sto,aCase.commands);
  249. return $newSto.then(nSto => {
  250. return Promise.resolve({wasTrue: true, sto: nSto});
  251. });
  252. } else {
  253. return Promise.resolve({wasTrue: false, sto: sto});
  254. }
  255. });
  256. }
  257. });
  258. }
  259. try {
  260. let breakLoop = false;
  261. let $result = Promise.resolve({wasTrue: false, sto: store});
  262. for (let index = 0; index < cmd.cases.length && !breakLoop; index++) {
  263. const aCase = cmd.cases[index];
  264. $result = auxCaseFun($result, cmd.expression, aCase);
  265. $result.then( r => breakLoop = this.ignoreSwitchCases(r.sto));
  266. }
  267. return $result.then(r => {
  268. this.context.pop();
  269. if(r.sto.mode === Modes.BREAK) {
  270. r.sto.mode = Modes.RUN;
  271. }
  272. return r.sto;
  273. });
  274. } catch (error) {
  275. return Promise.reject(error);
  276. }
  277. }
  278. executeFor (store, cmd) {
  279. try {
  280. //BEGIN for -> while rewrite
  281. const initCmd = cmd.assignment;
  282. const condition = cmd.condition;
  283. const increment = cmd.increment;
  284. const whileBlock = new Commands.CommandBlock([],
  285. cmd.commands.concat(increment));
  286. const forAsWhile = new Commands.While(condition, whileBlock);
  287. //END for -> while rewrite
  288. const newCmdList = [initCmd,forAsWhile];
  289. return this.executeCommands(store, newCmdList);
  290. } catch (error) {
  291. return Promise.reject(error);
  292. }
  293. }
  294. executeDoWhile (store, cmd) {
  295. const outerRef = this;
  296. try {
  297. outerRef.loopTimers.push(Date.now());
  298. outerRef.context.push(Context.BREAKABLE);
  299. const $newStore = outerRef.executeCommands(store, cmd.commands);
  300. return $newStore.then(sto => {
  301. if(sto.mode === Modes.BREAK) {
  302. outerRef.context.pop();
  303. sto.mode = Modes.RUN;
  304. outerRef.loopTimers.pop();
  305. return sto;
  306. }
  307. const $value = outerRef.evaluateExpression(sto, cmd.expression);
  308. return $value.then(vl => {
  309. if (!vl.type.isCompatible(Types.BOOLEAN)) {
  310. // TODO: Better error message -- Inform line and column from token!!!!
  311. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  312. return Promise.reject(new Error(`DoWhile expression must be of type boolean`));
  313. }
  314. if (vl.value) {
  315. outerRef.context.pop();
  316. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  317. const time = outerRef.loopTimers[i];
  318. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  319. console.log("Kill by Timeout...");
  320. outerRef.forceKill = true;
  321. return Promise.reject(new Error("Potential endless loop detected."));
  322. }
  323. }
  324. return outerRef.executeCommand(sto, cmd);
  325. } else {
  326. outerRef.context.pop();
  327. outerRef.loopTimers.pop();
  328. console.log("Clear Timeout...");
  329. return sto;
  330. }
  331. })
  332. })
  333. } catch (error) {
  334. return Promise.reject(error);
  335. }
  336. }
  337. executeWhile (store, cmd) {
  338. const outerRef = this;
  339. try {
  340. outerRef.loopTimers.push(Date.now());
  341. outerRef.context.push(Context.BREAKABLE);
  342. const $value = outerRef.evaluateExpression(store, cmd.expression);
  343. return $value.then(vl => {
  344. if(vl.type.isCompatible(Types.BOOLEAN)) {
  345. if(vl.value) {
  346. const $newStore = outerRef.executeCommands(store, cmd.commands);
  347. return $newStore.then(sto => {
  348. outerRef.context.pop();
  349. if (sto.mode === Modes.BREAK) {
  350. outerRef.loopTimers.pop();
  351. sto.mode = Modes.RUN;
  352. return sto;
  353. }
  354. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  355. const time = outerRef.loopTimers[i];
  356. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  357. console.log("Kill by Timeout...");
  358. outerRef.forceKill = true;
  359. return Promise.reject(new Error("Potential endless loop detected."));
  360. }
  361. }
  362. return outerRef.executeCommand(sto, cmd);
  363. });
  364. } else {
  365. outerRef.context.pop();
  366. outerRef.loopTimers.pop();
  367. console.log("Clear Timeout...");
  368. return store;
  369. }
  370. } else {
  371. // TODO: Better error message -- Inform line and column from token!!!!
  372. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  373. return Promise.reject(new Error(`Loop condition must be of type boolean`));
  374. }
  375. })
  376. } catch (error) {
  377. return Promise.reject(error);
  378. }
  379. }
  380. executeIfThenElse (store, cmd) {
  381. try {
  382. const $value = this.evaluateExpression(store, cmd.condition);
  383. return $value.then(vl => {
  384. if(vl.type.isCompatible(Types.BOOLEAN)) {
  385. if(vl.value) {
  386. return this.executeCommands(store, cmd.ifTrue.commands);
  387. } else if( cmd.ifFalse !== null){
  388. if(cmd.ifFalse instanceof Commands.IfThenElse) {
  389. return this.executeCommand(store, cmd.ifFalse);
  390. } else {
  391. return this.executeCommands(store, cmd.ifFalse.commands);
  392. }
  393. } else {
  394. return Promise.resolve(store);
  395. }
  396. } else {
  397. // TODO: Better error message -- Inform line and column from token!!!!
  398. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  399. return Promise.reject(new Error(`If expression must be of type boolean`));
  400. }
  401. });
  402. } catch (error) {
  403. return Promise.reject(error);
  404. }
  405. }
  406. executeReturn (store, cmd) {
  407. try {
  408. const funcType = store.applyStore('$').type;
  409. const $value = this.evaluateExpression(store, cmd.expression);
  410. const funcName = store.name;
  411. return $value.then(vl => {
  412. if(vl === null && funcType.isCompatible(Types.VOID)) {
  413. return Promise.resolve(store);
  414. }
  415. if (vl === null || !funcType.isCompatible(vl.type)) {
  416. // TODO: Better error message -- Inform line and column from token!!!!
  417. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  418. return Promise.reject(new Error(`Function ${funcName} must return ${funcType.type} instead of ${vl.type}.`));
  419. } else {
  420. let realValue = this.parseStoreObjectValue(vl);
  421. store.updateStore('$', realValue);
  422. store.mode = Modes.RETURN;
  423. return Promise.resolve(store);
  424. }
  425. });
  426. } catch (error) {
  427. return Promise.reject(error);
  428. }
  429. }
  430. executeBreak (store, _) {
  431. if(this.checkContext(Context.BREAKABLE)) {
  432. store.mode = Modes.BREAK;
  433. return Promise.resolve(store);
  434. } else {
  435. return Promise.reject(new Error("!!!CRITIAL: Break command outside Loop/Switch scope!!!"));
  436. }
  437. }
  438. executeAssign (store, cmd) {
  439. try {
  440. const $value = this.evaluateExpression(store, cmd.expression);
  441. return $value.then( vl => {
  442. let realValue = this.parseStoreObjectValue(vl);
  443. store.updateStore(cmd.id, realValue)
  444. return store;
  445. });
  446. } catch (error) {
  447. return Promise.reject(error);
  448. }
  449. }
  450. executeArrayIndexAssign (store, cmd) {
  451. const mustBeArray = store.applyStore(cmd.id);
  452. if(!(mustBeArray.type instanceof CompoundType)) {
  453. return Promise.reject(new Error(cmd.id + " is not a vector/matrix"));
  454. }
  455. const line$ = this.evaluateExpression(store, cmd.line);
  456. const column$ = this.evaluateExpression(store, cmd.column);
  457. const value$ = this.evaluateExpression(store, cmd.expression);
  458. return Promise.all([line$, column$, value$]).then(results => {
  459. const lineSO = results[0];
  460. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  461. // TODO: better error message
  462. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  463. return Promise.reject(new Error("Array dimension must be of type int"));
  464. }
  465. const line = lineSO.number;
  466. const columnSO = results[1];
  467. let column = null
  468. if (columnSO !== null) {
  469. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  470. // TODO: better error message
  471. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  472. return Promise.reject(new Error("Array dimension must be of type int"));
  473. }
  474. column = columnSO.number;
  475. }
  476. const value = this.parseStoreObjectValue(results[2]);
  477. if (line >= mustBeArray.lines) {
  478. // TODO: better error message
  479. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${lines}`));
  480. }
  481. if (column !== null && mustBeArray.columns === null ){
  482. // TODO: better error message
  483. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  484. }
  485. if(column !== null && column >= mustBeArray.columns) {
  486. // TODO: better error message
  487. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  488. }
  489. const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
  490. if (column !== null) {
  491. if (value.type instanceof CompoundType) {
  492. return Promise.reject(new Error("Invalid operation. This must be a value: line "+cmd.sourceInfo.line));
  493. }
  494. newArray.value[line].value[column] = value;
  495. store.updateStore(cmd.id, newArray);
  496. } else {
  497. if(mustBeArray.columns !== null && value.type instanceof CompoundType) {
  498. return Promise.reject(new Error("Invalid operation. This must be a vector: line "+cmd.sourceInfo.line));
  499. }
  500. newArray.value[line] = value;
  501. store.updateStore(cmd.id, newArray);
  502. }
  503. return store;
  504. });
  505. }
  506. executeDeclaration (store, cmd) {
  507. try {
  508. const $value = this.evaluateExpression(store, cmd.initial);
  509. if(cmd instanceof Commands.ArrayDeclaration) {
  510. const $lines = this.evaluateExpression(store, cmd.lines);
  511. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  512. return Promise.all([$lines, $columns, $value]).then(values => {
  513. const lineSO = values[0];
  514. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  515. // TODO: better error message
  516. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  517. return Promise.reject(new Error("Array dimension must be of type int"));
  518. }
  519. const line = lineSO.number;
  520. const columnSO = values[1];
  521. let column = null
  522. if (columnSO !== null) {
  523. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  524. // TODO: better error message
  525. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  526. return Promise.reject(new Error("Array dimension must be of type int"));
  527. }
  528. column = columnSO.number;
  529. }
  530. const value = values[2];
  531. const temp = new StoreObjectArray(cmd.type, line, column, null);
  532. store.insertStore(cmd.id, temp);
  533. let realValue = value;
  534. if (value !== null) {
  535. if(value instanceof StoreObjectArrayAddress) {
  536. if(value.type instanceof CompoundType) {
  537. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  538. } else {
  539. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  540. }
  541. }
  542. } else {
  543. realValue = new StoreObjectArray(cmd.type, line, column, [])
  544. if(column !== null) {
  545. for (let i = 0; i < line; i++) {
  546. realValue.value.push(new StoreObjectArray(new CompoundType(cmd.type.innerType, 1), column, null, []));
  547. }
  548. }
  549. }
  550. realValue.readOnly = cmd.isConst;
  551. store.updateStore(cmd.id, realValue);
  552. return store;
  553. });
  554. } else {
  555. const temp = new StoreObject(cmd.type, null);
  556. store.insertStore(cmd.id, temp);
  557. return $value.then(vl => {
  558. let realValue = vl;
  559. if (vl !== null) {
  560. if(vl instanceof StoreObjectArrayAddress) {
  561. if(vl.type instanceof CompoundType) {
  562. realValue = Object.assign(new StoreObjectArray(null,null,null), vl.refValue);
  563. } else {
  564. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  565. }
  566. }
  567. } else {
  568. realValue = new StoreObject(cmd.type,0);
  569. }
  570. realValue.readOnly = cmd.isConst;
  571. store.updateStore(cmd.id, realValue);
  572. return store;
  573. });
  574. }
  575. } catch (e) {
  576. return Promise.reject(e);
  577. }
  578. }
  579. evaluateExpression (store, exp) {
  580. if (exp instanceof Expressions.UnaryApp) {
  581. return this.evaluateUnaryApp(store, exp);
  582. } else if (exp instanceof Expressions.InfixApp) {
  583. return this.evaluateInfixApp(store, exp);
  584. } else if (exp instanceof Expressions.ArrayAccess) {
  585. return this.evaluateArrayAccess(store, exp);
  586. } else if (exp instanceof Expressions.VariableLiteral) {
  587. return this.evaluateVariableLiteral(store, exp);
  588. } else if (exp instanceof Expressions.IntLiteral) {
  589. return this.evaluateLiteral(store, exp);
  590. } else if (exp instanceof Expressions.RealLiteral) {
  591. return this.evaluateLiteral(store, exp);
  592. } else if (exp instanceof Expressions.BoolLiteral) {
  593. return this.evaluateLiteral(store, exp);
  594. } else if (exp instanceof Expressions.StringLiteral) {
  595. return this.evaluateLiteral(store, exp);
  596. } else if (exp instanceof Expressions.ArrayLiteral) {
  597. return this.evaluateArrayLiteral(store, exp);
  598. } else if (exp instanceof Expressions.FunctionCall) {
  599. return this.evaluateFunctionCall(store, exp);
  600. }
  601. return Promise.resolve(null);
  602. }
  603. evaluateFunctionCall (store, exp) {
  604. const func = this.findFunction(exp.id);
  605. if(Types.VOID.isCompatible(func.returnType)) {
  606. // TODO: better error message
  607. return Promise.reject(new Error(`Function ${exp.id} cannot be used inside an expression`));
  608. }
  609. const $newStore = this.runFunction(func, exp.actualParameters, store);
  610. return $newStore.then( sto => {
  611. if(sto.mode !== Modes.RETURN) {
  612. return Promise.reject(new Error("The function that was called did not had a return command: "+exp.id));
  613. }
  614. const val = sto.applyStore('$');
  615. if (val instanceof StoreObjectArray) {
  616. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  617. } else {
  618. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  619. }
  620. });
  621. }
  622. evaluateArrayLiteral (store, exp) {
  623. if(!exp.isVector) {
  624. const $matrix = this.evaluateMatrix(store, exp.value);
  625. return $matrix.then(list => {
  626. const type = new CompoundType(list[0].type.innerType, 2);
  627. const arr = new StoreObjectArray(type, list.length, list[0].lines, list);
  628. if(arr.isValid)
  629. return Promise.resolve(arr);
  630. else
  631. return Promise.reject(new Error(`Invalid array`))
  632. });
  633. } else {
  634. return this.evaluateVector(store, exp.value).then(list => {
  635. const type = new CompoundType(list[0].type, 1);
  636. const stoArray = new StoreObjectArray(type, list.length, null, list);
  637. if(stoArray.isValid)
  638. return Promise.resolve(stoArray);
  639. else
  640. return Promise.reject(new Error(`Invalid array`))
  641. });
  642. }
  643. }
  644. evaluateVector (store, exps) {
  645. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  646. }
  647. evaluateMatrix (store, exps) {
  648. return Promise.all(exps.map( vector => {
  649. const $vector = this.evaluateVector(store, vector.value)
  650. return $vector.then(list => {
  651. const type = new CompoundType(list[0].type, 1);
  652. return new StoreObjectArray(type, list.length, null, list)
  653. });
  654. } ));
  655. }
  656. evaluateLiteral (_, exp) {
  657. return Promise.resolve(new StoreObject(exp.type, exp.value));
  658. }
  659. evaluateVariableLiteral (store, exp) {
  660. try {
  661. const val = store.applyStore(exp.id);
  662. if (val instanceof StoreObjectArray) {
  663. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  664. } else {
  665. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  666. }
  667. } catch (error) {
  668. return Promise.reject(error);
  669. }
  670. }
  671. evaluateArrayAccess (store, exp) {
  672. const mustBeArray = store.applyStore(exp.id);
  673. if (!(mustBeArray.type instanceof CompoundType)) {
  674. // TODO: better error message
  675. console.log(mustBeArray.type);
  676. return Promise.reject(new Error(`${exp.id} is not of type array`));
  677. }
  678. const $line = this.evaluateExpression(store, exp.line);
  679. const $column = this.evaluateExpression(store, exp.column);
  680. return Promise.all([$line, $column]).then(values => {
  681. const lineSO = values[0];
  682. const columnSO = values[1];
  683. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  684. // TODO: better error message
  685. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  686. return Promise.reject(new Error("Array dimension must be of type int"));
  687. }
  688. const line = lineSO.number;
  689. let column = null;
  690. if(columnSO !== null) {
  691. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  692. // TODO: better error message
  693. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  694. return Promise.reject(new Error("Array dimension must be of type int"));
  695. }
  696. column = columnSO.number;
  697. }
  698. if (line >= mustBeArray.lines) {
  699. // TODO: better error message
  700. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${lines}`));
  701. }
  702. if (column !== null && mustBeArray.columns === null ){
  703. // TODO: better error message
  704. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  705. }
  706. if(column !== null && column >= mustBeArray.columns) {
  707. // TODO: better error message
  708. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  709. }
  710. return Promise.resolve(new StoreObjectArrayAddress(mustBeArray.id, line, column, store));
  711. });
  712. }
  713. evaluateUnaryApp (store, unaryApp) {
  714. const $left = this.evaluateExpression(store, unaryApp.left);
  715. return $left.then( left => {
  716. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  717. if (Types.UNDEFINED.isCompatible(resultType)) {
  718. // TODO: better urgent error message
  719. return Promise.reject(new Error(`Cannot use this op to ${left.type}`));
  720. }
  721. switch (unaryApp.op.ord) {
  722. case Operators.ADD.ord:
  723. return new StoreObject(resultType, left.value);
  724. case Operators.SUB.ord:
  725. return new StoreObject(resultType, left.value.negated());
  726. case Operators.NOT.ord:
  727. return new StoreObject(resultType, !left.value);
  728. default:
  729. return Promise.reject(new Error('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  730. }
  731. });
  732. }
  733. evaluateInfixApp (store, infixApp) {
  734. const $left = this.evaluateExpression(store, infixApp.left);
  735. const $right = this.evaluateExpression(store, infixApp.right);
  736. return Promise.all([$left, $right]).then(values => {
  737. const left = values[0];
  738. const right = values[1];
  739. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  740. if (Types.UNDEFINED.isCompatible(resultType)) {
  741. // TODO: better urgent error message
  742. return Promise.reject(new Error(`Cannot use this ${infixApp.op} to ${left.type} and ${right.type}`));
  743. }
  744. let result = null;
  745. switch (infixApp.op.ord) {
  746. case Operators.ADD.ord: {
  747. if(Types.STRING.isCompatible(left.type)) {
  748. const rightStr = convertToString(right.value, right.type);
  749. return new StoreObject(resultType, left.value + rightStr);
  750. } else if (Types.STRING.isCompatible(right.type)) {
  751. const leftStr = convertToString(left.value, left.type);
  752. return new StoreObject(resultType, leftStr + right.value);
  753. } else {
  754. return new StoreObject(resultType, left.value.plus(right.value));
  755. }
  756. }
  757. case Operators.SUB.ord:
  758. return new StoreObject(resultType, left.value.minus(right.value));
  759. case Operators.MULT.ord: {
  760. result = left.value.times(right.value);
  761. if(result.dp() > Config.decimalPlaces) {
  762. result = new Decimal(result.toFixed(Config.decimalPlaces));
  763. }
  764. return new StoreObject(resultType, result);
  765. }
  766. case Operators.DIV.ord: {
  767. if (Types.INTEGER.isCompatible(resultType))
  768. result = left.value.divToInt(right.value);
  769. else
  770. result = left.value.div(right.value);
  771. if(result.dp() > Config.decimalPlaces) {
  772. result = new Decimal(result.toFixed(Config.decimalPlaces));
  773. }
  774. return new StoreObject(resultType, result);
  775. }
  776. case Operators.MOD.ord: {
  777. result = left.value.modulo(right.value);
  778. if(result.dp() > Config.decimalPlaces) {
  779. result = new Decimal(result.toFixed(Config.decimalPlaces));
  780. }
  781. return new StoreObject(resultType, result);
  782. }
  783. case Operators.GT.ord: {
  784. if (Types.STRING.isCompatible(left.type)) {
  785. result = left.value.length > right.value.length;
  786. } else {
  787. result = left.value.gt(right.value);
  788. }
  789. return new StoreObject(resultType, result);
  790. }
  791. case Operators.GE.ord: {
  792. if (Types.STRING.isCompatible(left.type)) {
  793. result = left.value.length >= right.value.length;
  794. } else {
  795. result = left.value.gte(right.value);
  796. }
  797. return new StoreObject(resultType, result);
  798. }
  799. case Operators.LT.ord: {
  800. if (Types.STRING.isCompatible(left.type)) {
  801. result = left.value.length < right.value.length;
  802. } else {
  803. result = left.value.lt(right.value);
  804. }
  805. return new StoreObject(resultType, result);
  806. }
  807. case Operators.LE.ord: {
  808. if (Types.STRING.isCompatible(left.type)) {
  809. result = left.value.length <= right.value.length;
  810. } else {
  811. result = left.value.lte(right.value);
  812. }
  813. return new StoreObject(resultType, result);
  814. }
  815. case Operators.EQ.ord: {
  816. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  817. result = left.value.eq(right.value);
  818. } else {
  819. result = left.value === right.value;
  820. }
  821. return new StoreObject(resultType, result);
  822. }
  823. case Operators.NEQ.ord: {
  824. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  825. result = !left.value.eq(right.value);
  826. } else {
  827. result = left.value !== right.value;
  828. }
  829. return new StoreObject(resultType, result);
  830. }
  831. case Operators.AND.ord:
  832. return new StoreObject(resultType, left.value && right.value);
  833. case Operators.OR.ord:
  834. return new StoreObject(resultType, left.value || right.value);
  835. default:
  836. return Promise.reject(new Error('!!!Critical Invalid InfixApp '+ infixApp.op));
  837. }
  838. });
  839. }
  840. parseStoreObjectValue (vl) {
  841. let realValue = vl;
  842. if(vl instanceof StoreObjectArrayAddress) {
  843. if(vl.type instanceof CompoundType) {
  844. switch(vl.type.dimensions) {
  845. case 1: {
  846. realValue = new StoreObjectArray(vl.type, vl.value);
  847. break;
  848. }
  849. default: {
  850. throw new Error("Three dimensional array address...");
  851. }
  852. }
  853. } else {
  854. realValue = new StoreObject(vl.type, vl.value);
  855. }
  856. }
  857. return realValue;
  858. }
  859. }