ivprogProcessor.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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, toInt } from './../ast/types';
  8. import { Operators } from './../ast/operators';
  9. import { NAMES, LanguageDefinedFunction } from './definedFunctions';
  10. import { canApplyInfixOp, canApplyUnaryOp } from './compatibilityTable';
  11. import * as Commands from './../ast/commands/';
  12. import * as Expressions from './../ast/expressions/';
  13. export class IVProgProcessor {
  14. constructor (ast) {
  15. this.ast = ast;
  16. this.globalStore = new Store();
  17. this.stores = [this.globalStore];
  18. this.context = [Context.BASE];
  19. this.input = null;
  20. this.output = null;
  21. }
  22. registerInput (input) {
  23. this.input = input;
  24. }
  25. registerOutput (output) {
  26. this.output = output;
  27. }
  28. checkContext(context) {
  29. return this.context[this.context.length - 1] === context;
  30. }
  31. ignoreSwitchCases (store) {
  32. if (store.mode === Modes.RETURN) {
  33. return true;
  34. } else if (store.mode === Modes.BREAK) {
  35. return true;
  36. } else {
  37. return false;
  38. }
  39. }
  40. interpretAST () {
  41. this.initGlobal();
  42. const mainFunc = this.findMainFunction();
  43. if(mainFunc === null) {
  44. // TODO: Better error message
  45. throw new Error("Missing main funciton.");
  46. }
  47. return this.runFunction(mainFunc, [], this.globalStore);
  48. }
  49. initGlobal () {
  50. if(!this.checkContext(Context.BASE)) {
  51. throw new Error("!!!CRITICAL: Invalid call to initGlobal outside BASE context!!!");
  52. }
  53. this.ast.global.forEach(decl => {
  54. this.executeCommand(this.globalStore, decl).then(sto => this.globalStore = sto);
  55. });
  56. }
  57. findMainFunction () {
  58. return this.ast.functions.find(v => v.isMain);
  59. }
  60. findFunction (name) {
  61. if(name.match(/^\$.+$/)) {
  62. const fun = LanguageDefinedFunction[name];
  63. if(!!!fun) {
  64. throw new Error("!!!Internal Error. Language defined function not implemented -> " + name + "!!!");
  65. }
  66. return fun;
  67. } else {
  68. const val = this.ast.functions.find( v => v.name === name);
  69. if (!!!val) {
  70. // TODO: better error message;
  71. throw new Error(`Function ${name} is not defined.`);
  72. }
  73. return val;
  74. }
  75. }
  76. runFunction (func, actualParameters, store) {
  77. let funcStore = new Store();
  78. funcStore.extendStore(this.globalStore);
  79. const returnStoreObject = new StoreObject(func.returnType, null);
  80. const funcName = func.isMain ? 'main' : func.name;
  81. const funcNameStoreObject = new StoreObject(Types.STRING, funcName, true);
  82. funcStore.insertStore('$', returnStoreObject);
  83. funcStore.insertStore('$name', funcNameStoreObject);
  84. const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  85. return newFuncStore$.then(sto => {
  86. this.context.push(Context.FUNCTION);
  87. this.stores.push(sto);
  88. return this.executeCommands(sto, func.variablesDeclarations)
  89. .then(stoWithVars => this.executeCommands(stoWithVars, func.commands)).then(finalSto => {
  90. this.stores.pop();
  91. this.context.pop();
  92. return finalSto;
  93. });
  94. });
  95. }
  96. associateParameters (formalList, actualList, callerStore, calleeStore) {
  97. if (formalList.length != actualList.length) {
  98. // TODO: Better error message
  99. throw new Error("Numbers of parameters doesn't match");
  100. }
  101. const promises$ = actualList.map(actualParameter => this.evaluateExpression(callerStore, actualParameter));
  102. return Promise.all(promises$).then(values => {
  103. for (let i = 0; i < values.length; i++) {
  104. const stoObj = values[i];
  105. const formalParameter = formalList[i];
  106. switch (formalParameter.dimensions) {
  107. case 1: {
  108. if (stoObj.lines > 0 && stoObj.columns === null
  109. && stoObj.subtype === formalParameter.type) {
  110. if(formalParameter.byRef && !stoObj.inStore) {
  111. throw new Error('You must inform a variable as parameter');
  112. }
  113. if(formalParameter.byRef) {
  114. const ref = new StoreObjectRef(stoObj.id, callerStore);
  115. calleeStore.insertStore(formalParameter.id, ref);
  116. } else {
  117. calleeStore.insertStore(formalParameter.id, stoObj);
  118. }
  119. } else {
  120. // TODO: Better error message
  121. throw new Error(`Parameter ${formalParameter.id} is not compatible with the value given.`);
  122. }
  123. break;
  124. }
  125. case 2: {
  126. if (stoObj.lines > 0 && stoObj.columns > 0
  127. && stoObj.subtype === formalParameter.type) {
  128. if(formalParameter.byRef && !stoObj.inStore) {
  129. throw new Error('You must inform a variable as parameter');
  130. }
  131. if(formalParameter.byRef) {
  132. const ref = new StoreObjectRef(stoObj.id, callerStore);
  133. calleeStore.insertStore(formalParameter.id, ref);
  134. } else {
  135. calleeStore.insertStore(formalParameter.id, stoObj);
  136. }
  137. } else {
  138. // TODO: Better error message
  139. throw new Error(`Parameter ${formalParameter.id} is not compatible with the value given.`);
  140. }
  141. break;
  142. }
  143. case 0: {
  144. if(formalParameter.byRef && !stoObj.inStore) {
  145. throw new Error('You must inform a variable as parameter');
  146. } else if (formalParameter.type !== Types.ALL && stoObj.type !== formalParameter.type) {
  147. // TODO: Better error message
  148. throw new Error(`Parameter ${formalParameter.id} is not compatible with ${stoObj.type}.`);
  149. } else {
  150. if(formalParameter.byRef) {
  151. const ref = new StoreObjectRef(stoObj.id, callerStore);
  152. console.log('it\'s a ref...');
  153. console.log(ref);
  154. calleeStore.insertStore(formalParameter.id, ref);
  155. } else {
  156. calleeStore.insertStore(formalParameter.id, stoObj);
  157. }
  158. }
  159. }
  160. }
  161. }
  162. return calleeStore;
  163. });
  164. }
  165. executeCommands (store, cmds) {
  166. const auxExecCmdFun = (promise, cmd) => promise.then( sto => this.executeCommand(sto, cmd));
  167. let breakLoop = false;
  168. let $result = Promise.resolve(store);
  169. for (let index = 0; index < cmds.length && !breakLoop; index++) {
  170. const cmd = cmds[index];
  171. $result = auxExecCmdFun($result, cmd);
  172. $result.then(sto => {
  173. if(sto.mode === Modes.RETURN) {
  174. breakLoop = true;
  175. } else if (this.checkContext(Context.BREAKABLE &&
  176. sto.mode === Modes.BREAK)) {
  177. breakLoop = true;
  178. }
  179. return sto;
  180. });
  181. }
  182. return $result;
  183. }
  184. executeCommand (store, cmd) {
  185. while (store.mode === Modes.PAUSE) {
  186. continue;
  187. }
  188. if(store.mode === Modes.RETURN) {
  189. return Promise.resolve(store);
  190. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  191. return Promise.resolve(store);
  192. }
  193. if (cmd instanceof Commands.Declaration) {
  194. return this.executeDeclaration(store, cmd);
  195. } else if (cmd instanceof Commands.Assign) {
  196. return this.executeAssign(store, cmd);
  197. } else if (cmd instanceof Commands.Break) {
  198. return this.executeBreak(store, cmd);
  199. } else if (cmd instanceof Commands.Return) {
  200. return this.executeReturn(store, cmd);
  201. } else if (cmd instanceof Commands.IfThenElse) {
  202. return this.executeIfThenElse(store, cmd);
  203. } else if (cmd instanceof Commands.While) {
  204. return this.executeWhile(store, cmd);
  205. } else if (cmd instanceof Commands.DoWhile) {
  206. return this.executeDoWhile(store, cmd);
  207. } else if (cmd instanceof Commands.For) {
  208. return this.executeFor(store, cmd);
  209. } else if (cmd instanceof Commands.Switch) {
  210. return this.executeSwitch(store, cmd);
  211. } else if (cmd instanceof Commands.FunctionCall) {
  212. return this.executeFunctionCall(store, cmd);
  213. } else if (cmd instanceof Commands.SysCall) {
  214. return this.executeSysCall(store, cmd);
  215. } else {
  216. throw new Error("!!!CRITICAL A unknown command was found!!!\n" + cmd);
  217. }
  218. }
  219. executeSysCall (store, cmd) {
  220. if (cmd.id === NAMES.WRITE) {
  221. return this.runWriteFunction(store)
  222. } else if (cmd.id === NAMES.READ) {
  223. return this.runReadFunction(store);
  224. }
  225. }
  226. runWriteFunction (store) {
  227. const val = store.applyStore('p1');
  228. this.output.sendOutput(''+val.value);
  229. return Promise.resolve(store);
  230. }
  231. runReadFunction (store) {
  232. const request = new Promise((resolve, _) => {
  233. this.input.requestInput(resolve);
  234. });
  235. return request.then(text => {
  236. const typeToConvert = store.applyStore('p1').type;
  237. let stoObj = null;
  238. if (typeToConvert === Types.INTEGER) {
  239. const val = toInt(text);
  240. stoObj = new StoreObject(Types.INTEGER, val);
  241. } else if (typeToConvert === Types.REAL) {
  242. stoObj = new StoreObject(Types.REAL, parseFloat(text));
  243. } else if (typeToConvert === Types.BOOLEAN) {
  244. stoObj = new StoreObject(Types.BOOLEAN, true);
  245. } else if (typeToConvert === Types.STRING) {
  246. stoObj = new StoreObject(Types.STRING, text);
  247. }
  248. store.updateStore('p1', stoObj);
  249. return Promise.resolve(store);
  250. });
  251. }
  252. executeFunctionCall (store, cmd) {
  253. return new Promise((resolve, reject) => {
  254. const func = this.findFunction(cmd.id);
  255. this.runFunction(func, cmd.actualParameters, store)
  256. .then(_ => resolve(store))
  257. .catch(err => reject(err));
  258. });
  259. }
  260. executeSwitch (store, cmd) {
  261. this.context.push(Context.BREAKABLE);
  262. const auxCaseFun = (promise, switchExp, aCase) => {
  263. return promise.then( result => {
  264. const sto = result.sto;
  265. if (this.ignoreSwitchCases(sto)) {
  266. return Promise.resolve(result);
  267. } else if (result.wasTrue || aCase.isDefault) {
  268. const $newSto = this.executeCommands(result.sto,aCase.commands);
  269. return $newSto.then(nSto => {
  270. return Promise.resolve({wasTrue: true, sto: nSto});
  271. });
  272. } else {
  273. const $value = this.evaluateExpression(sto,
  274. new Expressions.InfixApp(Operators.EQ, switchExp, aCase.expression));
  275. return $value.then(vl => {
  276. if (vl.value) {
  277. const $newSto = this.executeCommands(result.sto,aCase.commands);
  278. return $newSto.then(nSto => {
  279. return Promise.resolve({wasTrue: true, sto: nSto});
  280. });
  281. } else {
  282. return Promise.resolve({wasTrue: false, sto: sto});
  283. }
  284. });
  285. }
  286. });
  287. }
  288. try {
  289. let breakLoop = false;
  290. let $result = Promise.resolve({wasTrue: false, sto: store});
  291. for (let index = 0; index < cmd.cases.length && !breakLoop; index++) {
  292. const aCase = cmd.cases[index];
  293. $result = auxCaseFun($result, cmd.expression, aCase);
  294. $result.then( r => breakLoop = this.ignoreSwitchCases(r.sto));
  295. }
  296. return $result.then(r => {
  297. this.context.pop();
  298. if(r.sto.mode === Modes.BREAK) {
  299. r.sto.mode = Modes.RUN;
  300. }
  301. return r.sto;
  302. });
  303. } catch (error) {
  304. return Promise.reject(error);
  305. }
  306. }
  307. executeFor (store, cmd) {
  308. try {
  309. //BEGIN for -> while rewrite
  310. const initCmd = cmd.assignment;
  311. const condition = cmd.condition;
  312. const increment = cmd.increment;
  313. const whileBlock = new Commands.CommandBlock([],
  314. cmd.commands.concat(increment));
  315. const forAsWhile = new Commands.While(condition, whileBlock);
  316. //END for -> while rewrite
  317. const newCmdList = [initCmd,forAsWhile];
  318. return this.executeCommands(store, newCmdList);
  319. } catch (error) {
  320. return Promise.reject(error);
  321. }
  322. }
  323. executeDoWhile (store, cmd) {
  324. try {
  325. this.context.push(Context.BREAKABLE);
  326. const $newStore = this.executeCommands(store, cmd.commands);
  327. return $newStore.then(sto => {
  328. if(sto.mode === Modes.BREAK) {
  329. this.context.pop();
  330. sto.mode = Modes.RUN;
  331. return Promise.resolve(sto);
  332. }
  333. const $value = this.evaluateExpression(sto, cmd.expression);
  334. return $value.then(vl => {
  335. if (vl.type !== Types.BOOLEAN) {
  336. // TODO: Better error message -- Inform line and column from token!!!!
  337. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  338. return Promise.reject(new Error(`DoWhile expression must be of type boolean`));
  339. }
  340. if (vl.value) {
  341. this.context.pop();
  342. return this.executeCommand(sto, cmd);
  343. } else {
  344. this.context.pop();
  345. return Promise.resolve(sto);
  346. }
  347. });
  348. });
  349. } catch (error) {
  350. return Promise.reject(error)
  351. }
  352. }
  353. executeWhile (store, cmd) {
  354. try {
  355. this.context.push(Context.BREAKABLE);
  356. const $value = this.evaluateExpression(store, cmd.expression);
  357. return $value.then(vl => {
  358. if(vl.type === Types.BOOLEAN) {
  359. if(vl.value) {
  360. const $newStore = this.executeCommands(store, cmd.commands);
  361. return $newStore.then(sto => {
  362. this.context.pop();
  363. if (sto.mode === Modes.BREAK) {
  364. sto.mode = Modes.RUN;
  365. return Promise.resolve(sto);
  366. }
  367. return this.executeCommand(sto, cmd);
  368. });
  369. } else {
  370. this.context.pop();
  371. return Promise.resolve(store);
  372. }
  373. } else {
  374. // TODO: Better error message -- Inform line and column from token!!!!
  375. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  376. return Promise.reject(new Error(`Loop condition must be of type boolean`));
  377. }
  378. });
  379. } catch (error) {
  380. return Promise.reject(error);
  381. }
  382. }
  383. executeIfThenElse (store, cmd) {
  384. try {
  385. const $value = this.evaluateExpression(store, cmd.condition);
  386. return $value.then(vl => {
  387. if(vl.type === Types.BOOLEAN) {
  388. if(vl.value) {
  389. return this.executeCommands(store, cmd.ifTrue.commands);
  390. } else if( cmd.ifFalse !== null){
  391. if(cmd.ifFalse instanceof Commands.IfThenElse) {
  392. return this.executeCommand(store, cmd.ifFalse);
  393. } else {
  394. return this.executeCommands(store, cmd.ifFalse.commands);
  395. }
  396. } else {
  397. return Promise.resolve(store);
  398. }
  399. } else {
  400. // TODO: Better error message -- Inform line and column from token!!!!
  401. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  402. return Promise.reject(new Error(`If expression must be of type boolean`));
  403. }
  404. });
  405. } catch (error) {
  406. return Promise.reject(error);
  407. }
  408. }
  409. executeReturn (store, cmd) {
  410. try {
  411. const funcType = store.applyStore('$');
  412. const $value = this.evaluateExpression(store, cmd.expression);
  413. const funcName = store.applyStore('$name');
  414. return $value.then(vl => {
  415. if(vl === null && funcType === Types.VOID) {
  416. return Promise.resolve(store);
  417. }
  418. if (vl === null || funcType.type !== vl.type) {
  419. // TODO: Better error message -- Inform line and column from token!!!!
  420. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  421. return Promise.reject(new Error(`Function ${funcName.value} must return ${funcType.type} instead of ${vl.type}.`));
  422. } else {
  423. store.updateStore('$', vl);
  424. store.mode = Modes.RETURN;
  425. return Promise.resolve(store);
  426. }
  427. });
  428. } catch (error) {
  429. return Promise.reject(error);
  430. }
  431. }
  432. executeBreak (store, _) {
  433. if(this.checkContext(Context.BREAKABLE)) {
  434. store.mode = Modes.BREAK;
  435. return Promise.resolve(store);
  436. } else {
  437. return Promise.reject(new Error("!!!CRITIAL: Break command outside Loop/Switch scope!!!"));
  438. }
  439. }
  440. executeAssign (store, cmd) {
  441. try {
  442. const $value = this.evaluateExpression(store, cmd.expression);
  443. return $value.then( vl => {
  444. store.updateStore(cmd.id, vl)
  445. return store;
  446. });
  447. } catch (error) {
  448. return Promise.reject(error);
  449. }
  450. }
  451. executeDeclaration (store, cmd) {
  452. try {
  453. const $value = this.evaluateExpression(store, cmd.initial);
  454. if(cmd instanceof Commands.ArrayDeclaration) {
  455. const $lines = this.evaluateExpression(store, cmd.lines);
  456. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  457. return Promise.all([$lines, $columns, $value]).then(values => {
  458. const lineSO = values[0];
  459. if(lineSO.type !== Types.INTEGER) {
  460. // TODO: better error message
  461. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  462. return Promise.reject(new Error("Array dimension must be of type int"));
  463. }
  464. const line = lineSO.value;
  465. const columnSO = values[1];
  466. let column = null
  467. if (columnSO !== null) {
  468. if(columnSO.type !== Types.INTEGER) {
  469. // TODO: better error message
  470. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  471. return Promise.reject(new Error("Array dimension must be of type int"));
  472. }
  473. column = columnSO.value;
  474. }
  475. const value = values[2];
  476. const temp = new StoreObjectArray(cmd.subtype, line, column, null, cmd.isConst);
  477. store.insertStore(cmd.id, temp);
  478. if(value !== null) {
  479. store.updateStore(cmd.id, value);
  480. }
  481. return store;
  482. });
  483. } else {
  484. const temp = new StoreObject(cmd.type, null, cmd.isConst);
  485. store.insertStore(cmd.id, temp);
  486. return $value.then(vl => {
  487. if (vl !== null)
  488. store.updateStore(cmd.id, vl)
  489. return store;
  490. });
  491. }
  492. } catch (e) {
  493. return Promise.reject(e);
  494. }
  495. }
  496. evaluateExpression (store, exp) {
  497. if (exp instanceof Expressions.UnaryApp) {
  498. return this.evaluateUnaryApp(store, exp);
  499. } else if (exp instanceof Expressions.InfixApp) {
  500. return this.evaluateInfixApp(store, exp);
  501. } else if (exp instanceof Expressions.ArrayAccess) {
  502. return this.evaluateArrayAccess(store, exp);
  503. } else if (exp instanceof Expressions.VariableLiteral) {
  504. return this.evaluateVariableLiteral(store, exp);
  505. } else if (exp instanceof Expressions.IntLiteral) {
  506. return this.evaluateLiteral(store, exp);
  507. } else if (exp instanceof Expressions.RealLiteral) {
  508. return this.evaluateLiteral(store, exp);
  509. } else if (exp instanceof Expressions.BoolLiteral) {
  510. return this.evaluateLiteral(store, exp);
  511. } else if (exp instanceof Expressions.StringLiteral) {
  512. return this.evaluateLiteral(store, exp);
  513. } else if (exp instanceof Expressions.ArrayLiteral) {
  514. return this.evaluateArrayLiteral(store, exp);
  515. } else if (exp instanceof Expressions.FunctionCall) {
  516. return this.evaluateFunctionCall(store, exp);
  517. }
  518. console.log('null exp');
  519. return Promise.resolve(null);
  520. }
  521. evaluateFunctionCall (store, exp) {
  522. const func = this.findFunction(exp.id);
  523. if(func.returnType === Types.VOID) {
  524. // TODO: better error message
  525. return Promise.reject(new Error(`Function ${exp.id} cannot be used inside an expression`));
  526. }
  527. const $newStore = this.runFunction(func, exp.actualParameters, store);
  528. return $newStore.then( sto => {
  529. const val = sto.applyStore('$');
  530. if (val.type === Types.ARRAY) {
  531. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  532. } else {
  533. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  534. }
  535. });
  536. }
  537. evaluateArrayLiteral (store, exp) {
  538. if(!exp.isVector) {
  539. const $matrix = this.evaluateMatrix(store, exp.value);
  540. return $matrix.then(list => {
  541. const arr = new StoreObjectArray(list[0].subtype, list.length, list[0].lines, list);
  542. if(arr.isValid)
  543. return Promise.resolve(arr);
  544. else
  545. return Promise.reject(new Error(`Invalid array`))
  546. });
  547. } else {
  548. return this.evaluateVector(store, exp.value).then(list => {
  549. const stoArray = new StoreObjectArray(list[0].type, list.length, null, list);
  550. if(stoArray.isValid)
  551. return Promise.resolve(stoArray);
  552. else
  553. return Promise.reject(new Error(`Invalid array`))
  554. });
  555. }
  556. }
  557. evaluateVector (store, exps) {
  558. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  559. }
  560. evaluateMatrix (store, exps) {
  561. return Promise.all(exps.map( vector => {
  562. const $vector = this.evaluateVector(store, vector.value)
  563. return $vector.then(list => new StoreObjectArray(list[0].type, list.length, null, list))
  564. } ));
  565. }
  566. evaluateLiteral (_, exp) {
  567. return Promise.resolve(new StoreObject(exp.type, exp.value));
  568. }
  569. evaluateVariableLiteral (store, exp) {
  570. try {
  571. const val = store.applyStore(exp.id);
  572. if (val.type === Types.ARRAY) {
  573. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  574. } else {
  575. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  576. }
  577. } catch (error) {
  578. return Promise.reject(error);
  579. }
  580. }
  581. evaluateArrayAccess (store, exp) {
  582. const mustBeArray = store.applyStore(exp.id);
  583. if (mustBeArray.type !== Types.ARRAY) {
  584. // TODO: better error message
  585. return Promise.reject(new Error(`${exp.id} is not of type array`));
  586. }
  587. const $line = this.evaluateExpression(store, exp.line);
  588. const $column = this.evaluateExpression(store, exp.column);
  589. return Promise.all([$line, $column]).then(values => {
  590. const lineSO = values[0];
  591. const columnSO = values[1];
  592. if(lineSO.type !== Types.INTEGER) {
  593. // TODO: better error message
  594. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  595. return Promise.reject(new Error("Array dimension must be of type int"));
  596. }
  597. const line = lineSO.value;
  598. let column = null;
  599. if(columnSO !== null) {
  600. if(columnSO.type !== Types.INTEGER) {
  601. // TODO: better error message
  602. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  603. return Promise.reject(new Error("Array dimension must be of type int"));
  604. }
  605. column = columnSO.value;
  606. }
  607. if (line >= mustBeArray.lines) {
  608. // TODO: better error message
  609. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${lines}`));
  610. }
  611. if (column !== null && mustBeArray.columns === null ){
  612. // TODO: better error message
  613. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  614. }
  615. if(column !== null && column >= mustBeArray.columns) {
  616. // TODO: better error message
  617. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  618. }
  619. if (column !== null) {
  620. return Promise.resolve(mustBeArray.value[line].value[column]);
  621. } else {
  622. return Promise.resolve(mustBeArray.value[line]);
  623. }
  624. });
  625. }
  626. evaluateUnaryApp (store, unaryApp) {
  627. const $left = this.evaluateExpression(store, unaryApp.left);
  628. return $left.then( left => {
  629. if (!canApplyUnaryOp(unaryApp.op, left)) {
  630. // TODO: better urgent error message
  631. return Promise.reject(new Error(`Cannot use this op to ${left.type}`));
  632. }
  633. switch (unaryApp.op) {
  634. case Operators.ADD:
  635. return new StoreObject(left.type, +left.value);
  636. case Operators.SUB:
  637. return new StoreObject(left.type, -left.value);
  638. case Operators.NOT:
  639. return new StoreObject(left.type, !left.value);
  640. default:
  641. return Promise.reject(new Error('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  642. }
  643. });
  644. }
  645. evaluateInfixApp (store, infixApp) {
  646. const $left = this.evaluateExpression(store, infixApp.left);
  647. const $right = this.evaluateExpression(store, infixApp.right);
  648. return Promise.all([$left, $right]).then(values => {
  649. const left = values[0];
  650. const right = values[1];
  651. if (!canApplyInfixOp(infixApp.op, left, right)) {
  652. // TODO: better urgent error message
  653. return Promise.reject(new Error(`Cannot use this op to ${left.type} and ${right.type}`));
  654. }
  655. switch (infixApp.op) {
  656. case Operators.ADD:
  657. return new StoreObject(left.type, left.value + right.value);
  658. case Operators.SUB:
  659. return new StoreObject(left.type, left.value - right.value);
  660. case Operators.MULT:
  661. return new StoreObject(left.type, left.value * right.value);
  662. case Operators.DIV:
  663. return new StoreObject(left.type, left.value / right.value);
  664. case Operators.MOD:
  665. return new StoreObject(left.type, left.value % right.value);
  666. case Operators.GT:
  667. return new StoreObject(Types.BOOLEAN, left.value > right.value);
  668. case Operators.GE:
  669. return new StoreObject(Types.BOOLEAN, left.value >= right.value);
  670. case Operators.LT:
  671. return new StoreObject(Types.BOOLEAN, left.value < right.value);
  672. case Operators.LE:
  673. return new StoreObject(Types.BOOLEAN, left.value <= right.value);
  674. case Operators.EQ:
  675. return new StoreObject(Types.BOOLEAN, left.value === right.value);
  676. case Operators.NEQ:
  677. return new StoreObject(Types.BOOLEAN, left.value !== right.value);
  678. case Operators.AND:
  679. return new StoreObject(Types.BOOLEAN, left.value && right.value);
  680. case Operators.OR:
  681. return new StoreObject(Types.BOOLEAN, left.value || right.value);
  682. default:
  683. return Promise.reject(new Error('!!!Critical Invalid InfixApp '+ infixApp.op));
  684. }
  685. });
  686. }
  687. }