ivprogProcessor.js 25 KB

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