ivprogProcessor.js 26 KB

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