ivprogProcessor.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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 { 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.getFunction(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 (typeof cmd.id === 'function') {
  208. return cmd.id.bind(this)(store, cmd);
  209. } else {
  210. throw new Error("invalid internal function impl.");
  211. }
  212. }
  213. executeFunctionCall (store, cmd) {
  214. return new Promise((resolve, reject) => {
  215. const func = this.findFunction(cmd.id);
  216. this.runFunction(func, cmd.actualParameters, store)
  217. .then(_ => resolve(store))
  218. .catch(err => reject(err));
  219. });
  220. }
  221. executeSwitch (store, cmd) {
  222. this.context.push(Context.BREAKABLE);
  223. const auxCaseFun = (promise, switchExp, aCase) => {
  224. return promise.then( result => {
  225. const sto = result.sto;
  226. if (this.ignoreSwitchCases(sto)) {
  227. return Promise.resolve(result);
  228. } else if (result.wasTrue || aCase.isDefault) {
  229. const $newSto = this.executeCommands(result.sto,aCase.commands);
  230. return $newSto.then(nSto => {
  231. return Promise.resolve({wasTrue: true, sto: nSto});
  232. });
  233. } else {
  234. const $value = this.evaluateExpression(sto,
  235. new Expressions.InfixApp(Operators.EQ, switchExp, aCase.expression));
  236. return $value.then(vl => {
  237. if (vl.value) {
  238. const $newSto = this.executeCommands(result.sto,aCase.commands);
  239. return $newSto.then(nSto => {
  240. return Promise.resolve({wasTrue: true, sto: nSto});
  241. });
  242. } else {
  243. return Promise.resolve({wasTrue: false, sto: sto});
  244. }
  245. });
  246. }
  247. });
  248. }
  249. try {
  250. let breakLoop = false;
  251. let $result = Promise.resolve({wasTrue: false, sto: store});
  252. for (let index = 0; index < cmd.cases.length && !breakLoop; index++) {
  253. const aCase = cmd.cases[index];
  254. $result = auxCaseFun($result, cmd.expression, aCase);
  255. $result.then( r => breakLoop = this.ignoreSwitchCases(r.sto));
  256. }
  257. return $result.then(r => {
  258. this.context.pop();
  259. if(r.sto.mode === Modes.BREAK) {
  260. r.sto.mode = Modes.RUN;
  261. }
  262. return r.sto;
  263. });
  264. } catch (error) {
  265. return Promise.reject(error);
  266. }
  267. }
  268. executeFor (store, cmd) {
  269. try {
  270. //BEGIN for -> while rewrite
  271. const initCmd = cmd.assignment;
  272. const condition = cmd.condition;
  273. const increment = cmd.increment;
  274. const whileBlock = new Commands.CommandBlock([],
  275. cmd.commands.concat(increment));
  276. const forAsWhile = new Commands.While(condition, whileBlock);
  277. //END for -> while rewrite
  278. const newCmdList = [initCmd,forAsWhile];
  279. return this.executeCommands(store, newCmdList);
  280. } catch (error) {
  281. return Promise.reject(error);
  282. }
  283. }
  284. executeDoWhile (store, cmd) {
  285. try {
  286. this.context.push(Context.BREAKABLE);
  287. const $newStore = this.executeCommands(store, cmd.commands);
  288. return $newStore.then(sto => {
  289. if(sto.mode === Modes.BREAK) {
  290. this.context.pop();
  291. sto.mode = Modes.RUN;
  292. return Promise.resolve(sto);
  293. }
  294. const $value = this.evaluateExpression(sto, cmd.expression);
  295. return $value.then(vl => {
  296. if (vl.type !== Types.BOOLEAN) {
  297. // TODO: Better error message -- Inform line and column from token!!!!
  298. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  299. return Promise.reject(new Error(`DoWhile expression must be of type boolean`));
  300. }
  301. if (vl.value) {
  302. this.context.pop();
  303. return this.executeCommand(sto, cmd);
  304. } else {
  305. this.context.pop();
  306. return Promise.resolve(sto);
  307. }
  308. });
  309. });
  310. } catch (error) {
  311. return Promise.reject(error)
  312. }
  313. }
  314. executeWhile (store, cmd) {
  315. try {
  316. this.context.push(Context.BREAKABLE);
  317. const $value = this.evaluateExpression(store, cmd.expression);
  318. return $value.then(vl => {
  319. if(vl.type === Types.BOOLEAN) {
  320. if(vl.value) {
  321. const $newStore = this.executeCommands(store, cmd.commands);
  322. return $newStore.then(sto => {
  323. this.context.pop();
  324. if (sto.mode === Modes.BREAK) {
  325. sto.mode = Modes.RUN;
  326. return Promise.resolve(sto);
  327. }
  328. return this.executeCommand(sto, cmd);
  329. });
  330. } else {
  331. this.context.pop();
  332. return Promise.resolve(store);
  333. }
  334. } else {
  335. // TODO: Better error message -- Inform line and column from token!!!!
  336. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  337. return Promise.reject(new Error(`Loop condition must be of type boolean`));
  338. }
  339. });
  340. } catch (error) {
  341. return Promise.reject(error);
  342. }
  343. }
  344. executeIfThenElse (store, cmd) {
  345. try {
  346. const $value = this.evaluateExpression(store, cmd.condition);
  347. return $value.then(vl => {
  348. if(vl.type === Types.BOOLEAN) {
  349. if(vl.value) {
  350. return this.executeCommands(store, cmd.ifTrue.commands);
  351. } else if( cmd.ifFalse !== null){
  352. if(cmd.ifFalse instanceof Commands.IfThenElse) {
  353. return this.executeCommand(store, cmd.ifFalse);
  354. } else {
  355. return this.executeCommands(store, cmd.ifFalse.commands);
  356. }
  357. } else {
  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(`If expression must be of type boolean`));
  364. }
  365. });
  366. } catch (error) {
  367. return Promise.reject(error);
  368. }
  369. }
  370. executeReturn (store, cmd) {
  371. try {
  372. const funcType = store.applyStore('$');
  373. const $value = this.evaluateExpression(store, cmd.expression);
  374. const funcName = store.applyStore('$name');
  375. return $value.then(vl => {
  376. if(vl === null && funcType === Types.VOID) {
  377. return Promise.resolve(store);
  378. }
  379. if (vl === null || funcType.type !== vl.type) {
  380. // TODO: Better error message -- Inform line and column from token!!!!
  381. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  382. return Promise.reject(new Error(`Function ${funcName.value} must return ${funcType.type} instead of ${vl.type}.`));
  383. } else {
  384. store.updateStore('$', vl);
  385. store.mode = Modes.RETURN;
  386. return Promise.resolve(store);
  387. }
  388. });
  389. } catch (error) {
  390. return Promise.reject(error);
  391. }
  392. }
  393. executeBreak (store, _) {
  394. if(this.checkContext(Context.BREAKABLE)) {
  395. store.mode = Modes.BREAK;
  396. return Promise.resolve(store);
  397. } else {
  398. return Promise.reject(new Error("!!!CRITIAL: Break command outside Loop/Switch scope!!!"));
  399. }
  400. }
  401. executeAssign (store, cmd) {
  402. try {
  403. const $value = this.evaluateExpression(store, cmd.expression);
  404. return $value.then( vl => {
  405. store.updateStore(cmd.id, vl)
  406. return store;
  407. });
  408. } catch (error) {
  409. return Promise.reject(error);
  410. }
  411. }
  412. executeDeclaration (store, cmd) {
  413. try {
  414. const $value = this.evaluateExpression(store, cmd.initial);
  415. if(cmd instanceof Commands.ArrayDeclaration) {
  416. const $lines = this.evaluateExpression(store, cmd.lines);
  417. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  418. return Promise.all([$lines, $columns, $value]).then(values => {
  419. const lineSO = values[0];
  420. if(lineSO.type !== Types.INTEGER) {
  421. // TODO: better error message
  422. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  423. return Promise.reject(new Error("Array dimension must be of type int"));
  424. }
  425. const line = lineSO.value;
  426. const columnSO = values[1];
  427. let column = null
  428. if (columnSO !== null) {
  429. if(columnSO.type !== Types.INTEGER) {
  430. // TODO: better error message
  431. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  432. return Promise.reject(new Error("Array dimension must be of type int"));
  433. }
  434. column = columnSO.value;
  435. }
  436. const value = values[2];
  437. const temp = new StoreObjectArray(cmd.subtype, line, column, null, cmd.isConst);
  438. store.insertStore(cmd.id, temp);
  439. if(value !== null) {
  440. store.updateStore(cmd.id, value);
  441. }
  442. return store;
  443. });
  444. } else {
  445. const temp = new StoreObject(cmd.type, null, cmd.isConst);
  446. store.insertStore(cmd.id, temp);
  447. return $value.then(vl => {
  448. if (vl !== null)
  449. store.updateStore(cmd.id, vl)
  450. return store;
  451. });
  452. }
  453. } catch (e) {
  454. return Promise.reject(e);
  455. }
  456. }
  457. evaluateExpression (store, exp) {
  458. if (exp instanceof Expressions.UnaryApp) {
  459. return this.evaluateUnaryApp(store, exp);
  460. } else if (exp instanceof Expressions.InfixApp) {
  461. return this.evaluateInfixApp(store, exp);
  462. } else if (exp instanceof Expressions.ArrayAccess) {
  463. return this.evaluateArrayAccess(store, exp);
  464. } else if (exp instanceof Expressions.VariableLiteral) {
  465. return this.evaluateVariableLiteral(store, exp);
  466. } else if (exp instanceof Expressions.IntLiteral) {
  467. return this.evaluateLiteral(store, exp);
  468. } else if (exp instanceof Expressions.RealLiteral) {
  469. return this.evaluateLiteral(store, exp);
  470. } else if (exp instanceof Expressions.BoolLiteral) {
  471. return this.evaluateLiteral(store, exp);
  472. } else if (exp instanceof Expressions.StringLiteral) {
  473. return this.evaluateLiteral(store, exp);
  474. } else if (exp instanceof Expressions.ArrayLiteral) {
  475. return this.evaluateArrayLiteral(store, exp);
  476. } else if (exp instanceof Expressions.FunctionCall) {
  477. return this.evaluateFunctionCall(store, exp);
  478. }
  479. console.log('null exp');
  480. return Promise.resolve(null);
  481. }
  482. evaluateFunctionCall (store, exp) {
  483. const func = this.findFunction(exp.id);
  484. if(func.returnType === Types.VOID) {
  485. // TODO: better error message
  486. return Promise.reject(new Error(`Function ${exp.id} cannot be used inside an expression`));
  487. }
  488. const $newStore = this.runFunction(func, exp.actualParameters, store);
  489. return $newStore.then( sto => {
  490. const val = sto.applyStore('$');
  491. if (val.type === Types.ARRAY) {
  492. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  493. } else {
  494. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  495. }
  496. });
  497. }
  498. evaluateArrayLiteral (store, exp) {
  499. if(!exp.isVector) {
  500. const $matrix = this.evaluateMatrix(store, exp.value);
  501. return $matrix.then(list => {
  502. const arr = new StoreObjectArray(list[0].subtype, list.length, list[0].lines, list);
  503. if(arr.isValid)
  504. return Promise.resolve(arr);
  505. else
  506. return Promise.reject(new Error(`Invalid array`))
  507. });
  508. } else {
  509. return this.evaluateVector(store, exp.value).then(list => {
  510. const stoArray = new StoreObjectArray(list[0].type, list.length, null, list);
  511. if(stoArray.isValid)
  512. return Promise.resolve(stoArray);
  513. else
  514. return Promise.reject(new Error(`Invalid array`))
  515. });
  516. }
  517. }
  518. evaluateVector (store, exps) {
  519. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  520. }
  521. evaluateMatrix (store, exps) {
  522. return Promise.all(exps.map( vector => {
  523. const $vector = this.evaluateVector(store, vector.value)
  524. return $vector.then(list => new StoreObjectArray(list[0].type, list.length, null, list))
  525. } ));
  526. }
  527. evaluateLiteral (_, exp) {
  528. return Promise.resolve(new StoreObject(exp.type, exp.value));
  529. }
  530. evaluateVariableLiteral (store, exp) {
  531. try {
  532. const val = store.applyStore(exp.id);
  533. if (val.type === Types.ARRAY) {
  534. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  535. } else {
  536. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  537. }
  538. } catch (error) {
  539. return Promise.reject(error);
  540. }
  541. }
  542. evaluateArrayAccess (store, exp) {
  543. const mustBeArray = store.applyStore(exp.id);
  544. if (mustBeArray.type !== Types.ARRAY) {
  545. // TODO: better error message
  546. return Promise.reject(new Error(`${exp.id} is not of type array`));
  547. }
  548. const $line = this.evaluateExpression(store, exp.line);
  549. const $column = this.evaluateExpression(store, exp.column);
  550. return Promise.all([$line, $column]).then(values => {
  551. const lineSO = values[0];
  552. const columnSO = values[1];
  553. if(lineSO.type !== Types.INTEGER) {
  554. // TODO: better error message
  555. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  556. return Promise.reject(new Error("Array dimension must be of type int"));
  557. }
  558. const line = lineSO.value;
  559. let column = null;
  560. if(columnSO !== null) {
  561. if(columnSO.type !== Types.INTEGER) {
  562. // TODO: better error message
  563. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  564. return Promise.reject(new Error("Array dimension must be of type int"));
  565. }
  566. column = columnSO.value;
  567. }
  568. if (line >= mustBeArray.lines) {
  569. // TODO: better error message
  570. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${lines}`));
  571. }
  572. if (column !== null && mustBeArray.columns === null ){
  573. // TODO: better error message
  574. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  575. }
  576. if(column !== null && column >= mustBeArray.columns) {
  577. // TODO: better error message
  578. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  579. }
  580. if (column !== null) {
  581. return Promise.resolve(mustBeArray.value[line].value[column]);
  582. } else {
  583. return Promise.resolve(mustBeArray.value[line]);
  584. }
  585. });
  586. }
  587. evaluateUnaryApp (store, unaryApp) {
  588. const $left = this.evaluateExpression(store, unaryApp.left);
  589. return $left.then( left => {
  590. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  591. if (resultType === Types.UNDEFINED) {
  592. // TODO: better urgent error message
  593. return Promise.reject(new Error(`Cannot use this op to ${left.type}`));
  594. }
  595. switch (unaryApp.op.ord) {
  596. case Operators.ADD.ord:
  597. return new StoreObject(resultType, +left.value);
  598. case Operators.SUB.ord:
  599. return new StoreObject(resultType, -left.value);
  600. case Operators.NOT.ord:
  601. return new StoreObject(resultType, !left.value);
  602. default:
  603. return Promise.reject(new Error('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  604. }
  605. });
  606. }
  607. evaluateInfixApp (store, infixApp) {
  608. const $left = this.evaluateExpression(store, infixApp.left);
  609. const $right = this.evaluateExpression(store, infixApp.right);
  610. return Promise.all([$left, $right]).then(values => {
  611. const left = values[0];
  612. const right = values[1];
  613. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  614. if (resultType === Types.UNDEFINED) {
  615. // TODO: better urgent error message
  616. return Promise.reject(new Error(`Cannot use this op to ${left.type} and ${right.type}`));
  617. }
  618. let result = null;
  619. switch (infixApp.op.ord) {
  620. case Operators.ADD.ord:
  621. return new StoreObject(resultType, left.value + right.value);
  622. case Operators.SUB.ord:
  623. return new StoreObject(resultType, left.value - right.value);
  624. case Operators.MULT.ord: {
  625. result = left.value * right.value;
  626. if (resultType === Types.INTEGER)
  627. result = Math.trunc(result);
  628. return new StoreObject(resultType, result);
  629. }
  630. case Operators.DIV.ord: {
  631. result = left.value / right.value;
  632. if (resultType === Types.INTEGER)
  633. result = Math.trunc(result);
  634. return new StoreObject(resultType, result);
  635. }
  636. case Operators.MOD.ord:
  637. return new StoreObject(resultType, left.value % right.value);
  638. case Operators.GT.ord:
  639. return new StoreObject(resultType, left.value > right.value);
  640. case Operators.GE.ord:
  641. return new StoreObject(resultType, left.value >= right.value);
  642. case Operators.LT.ord:
  643. return new StoreObject(resultType, left.value < right.value);
  644. case Operators.LE.ord:
  645. return new StoreObject(resultType, left.value <= right.value);
  646. case Operators.EQ.ord:
  647. return new StoreObject(resultType, left.value === right.value);
  648. case Operators.NEQ.ord:
  649. return new StoreObject(resultType, left.value !== right.value);
  650. case Operators.AND.ord:
  651. return new StoreObject(resultType, left.value && right.value);
  652. case Operators.OR.ord:
  653. return new StoreObject(resultType, left.value || right.value);
  654. default:
  655. return Promise.reject(new Error('!!!Critical Invalid InfixApp '+ infixApp.op));
  656. }
  657. });
  658. }
  659. }