ivprogProcessor.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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 { resultTypeAfterInfixOp, resultTypeAfterUnaryOp } 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. calleeStore.insertStore(formalParameter.id, ref);
  153. } else {
  154. calleeStore.insertStore(formalParameter.id, stoObj);
  155. }
  156. }
  157. }
  158. }
  159. }
  160. return calleeStore;
  161. });
  162. }
  163. executeCommands (store, cmds) {
  164. // helper to partially apply a function, in this case executeCommand
  165. const partial = (fun, cmd) => (sto) => fun(sto, cmd);
  166. return cmds.reduce((lastCommand, next) => {
  167. const nextCommand = partial(this.executeCommand.bind(this), next);
  168. return lastCommand.then(nextCommand);
  169. }, Promise.resolve(store));
  170. }
  171. executeCommand (store, cmd) {
  172. while (store.mode === Modes.PAUSE) {
  173. continue;
  174. }
  175. if(store.mode === Modes.RETURN) {
  176. return Promise.resolve(store);
  177. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  178. return Promise.resolve(store);
  179. }
  180. if (cmd instanceof Commands.Declaration) {
  181. return this.executeDeclaration(store, cmd);
  182. } else if (cmd instanceof Commands.Assign) {
  183. return this.executeAssign(store, cmd);
  184. } else if (cmd instanceof Commands.Break) {
  185. return this.executeBreak(store, cmd);
  186. } else if (cmd instanceof Commands.Return) {
  187. return this.executeReturn(store, cmd);
  188. } else if (cmd instanceof Commands.IfThenElse) {
  189. return this.executeIfThenElse(store, cmd);
  190. } else if (cmd instanceof Commands.While) {
  191. return this.executeWhile(store, cmd);
  192. } else if (cmd instanceof Commands.DoWhile) {
  193. return this.executeDoWhile(store, cmd);
  194. } else if (cmd instanceof Commands.For) {
  195. return this.executeFor(store, cmd);
  196. } else if (cmd instanceof Commands.Switch) {
  197. return this.executeSwitch(store, cmd);
  198. } else if (cmd instanceof Commands.FunctionCall) {
  199. return this.executeFunctionCall(store, cmd);
  200. } else if (cmd instanceof Commands.SysCall) {
  201. return this.executeSysCall(store, cmd);
  202. } else {
  203. throw new Error("!!!CRITICAL A unknown command was found!!!\n" + cmd);
  204. }
  205. }
  206. executeSysCall (store, cmd) {
  207. if (cmd.id === NAMES.WRITE) {
  208. return this.runWriteFunction(store)
  209. } else if (cmd.id === NAMES.READ) {
  210. return this.runReadFunction(store);
  211. }
  212. }
  213. runWriteFunction (store) {
  214. const val = store.applyStore('p1');
  215. this.output.sendOutput(''+val.value);
  216. return Promise.resolve(store);
  217. }
  218. runReadFunction (store) {
  219. const request = new Promise((resolve, _) => {
  220. this.input.requestInput(resolve);
  221. });
  222. return request.then(text => {
  223. const typeToConvert = store.applyStore('p1').type;
  224. let stoObj = null;
  225. if (typeToConvert === Types.INTEGER) {
  226. const val = toInt(text);
  227. stoObj = new StoreObject(Types.INTEGER, val);
  228. } else if (typeToConvert === Types.REAL) {
  229. stoObj = new StoreObject(Types.REAL, parseFloat(text));
  230. } else if (typeToConvert === Types.BOOLEAN) {
  231. stoObj = new StoreObject(Types.BOOLEAN, true);
  232. } else if (typeToConvert === Types.STRING) {
  233. stoObj = new StoreObject(Types.STRING, text);
  234. }
  235. store.updateStore('p1', stoObj);
  236. return Promise.resolve(store);
  237. });
  238. }
  239. executeFunctionCall (store, cmd) {
  240. return new Promise((resolve, reject) => {
  241. const func = this.findFunction(cmd.id);
  242. this.runFunction(func, cmd.actualParameters, store)
  243. .then(_ => resolve(store))
  244. .catch(err => reject(err));
  245. });
  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. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  617. if (resultType === Types.UNDEFINED) {
  618. // TODO: better urgent error message
  619. return Promise.reject(new Error(`Cannot use this op to ${left.type}`));
  620. }
  621. switch (unaryApp.op.ord) {
  622. case Operators.ADD.ord:
  623. return new StoreObject(resultType, +left.value);
  624. case Operators.SUB.ord:
  625. return new StoreObject(resultType, -left.value);
  626. case Operators.NOT.ord:
  627. return new StoreObject(resultType, !left.value);
  628. default:
  629. return Promise.reject(new Error('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  630. }
  631. });
  632. }
  633. evaluateInfixApp (store, infixApp) {
  634. const $left = this.evaluateExpression(store, infixApp.left);
  635. const $right = this.evaluateExpression(store, infixApp.right);
  636. return Promise.all([$left, $right]).then(values => {
  637. const left = values[0];
  638. const right = values[1];
  639. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  640. if (resultType === Types.UNDEFINED) {
  641. // TODO: better urgent error message
  642. return Promise.reject(new Error(`Cannot use this op to ${left.type} and ${right.type}`));
  643. }
  644. let result = null;
  645. switch (infixApp.op.ord) {
  646. case Operators.ADD.ord:
  647. return new StoreObject(resultType, left.value + right.value);
  648. case Operators.SUB.ord:
  649. return new StoreObject(resultType, left.value - right.value);
  650. case Operators.MULT.ord: {
  651. result = left.value * right.value;
  652. if (resultType === Types.INTEGER)
  653. result = Math.trunc(result);
  654. return new StoreObject(resultType, result);
  655. }
  656. case Operators.DIV.ord: {
  657. result = left.value / right.value;
  658. if (resultType === Types.INTEGER)
  659. result = Math.trunc(result);
  660. return new StoreObject(resultType, result);
  661. }
  662. case Operators.MOD.ord:
  663. return new StoreObject(resultType, left.value % right.value);
  664. case Operators.GT.ord:
  665. return new StoreObject(resultType, left.value > right.value);
  666. case Operators.GE.ord:
  667. return new StoreObject(resultType, left.value >= right.value);
  668. case Operators.LT.ord:
  669. return new StoreObject(resultType, left.value < right.value);
  670. case Operators.LE.ord:
  671. return new StoreObject(resultType, left.value <= right.value);
  672. case Operators.EQ.ord:
  673. return new StoreObject(resultType, left.value === right.value);
  674. case Operators.NEQ.ord:
  675. return new StoreObject(resultType, left.value !== right.value);
  676. case Operators.AND.ord:
  677. return new StoreObject(resultType, left.value && right.value);
  678. case Operators.OR.ord:
  679. return new StoreObject(resultType, left.value || right.value);
  680. default:
  681. return Promise.reject(new Error('!!!Critical Invalid InfixApp '+ infixApp.op));
  682. }
  683. });
  684. }
  685. }