ivprogProcessor.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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. funcStore = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  77. this.context.push(Context.FUNCTION);
  78. this.stores.push(funcStore);
  79. const result = this.executeCommands(funcStore, func.variablesDeclarations).then(sto => {
  80. return this.executeCommands(sto, func.commands)
  81. });
  82. this.stores.pop();
  83. this.context.pop();
  84. return result;
  85. }
  86. associateParameters (formalList, actualList, callerStore, calleeStore) {
  87. if (formalList.length != actualList.length) {
  88. // TODO: Better error message
  89. throw new Error("Numbers of parameters doesn't match");
  90. }
  91. formalList.forEach((v, i) => {
  92. this.evaluateExpression(callerStore, actualList[i])
  93. .then(vl => {
  94. switch (v.dimensions) {
  95. case 1: {
  96. if (vl.lines > 0 && vl.columns === null
  97. && vl.subtype === v.type) {
  98. if(v.byRef && !vl.inStore) {
  99. throw new Error('You must inform a variable as parameter');
  100. }
  101. if(v.byRef) {
  102. const ref = new StoreObjectRef(vl.id, callerStore);
  103. calleeStore.insertStore(v.id, ref);
  104. } else {
  105. calleeStore.insertStore(v.id, vl);
  106. }
  107. } else {
  108. // TODO: Better error message
  109. throw new Error(`Parameter ${v.id} is not compatible with the value given.`);
  110. }
  111. break;
  112. }
  113. case 2: {
  114. if (vl.lines > 0 && vl.columns > 0
  115. && vl.subtype === v.type) {
  116. if(v.byRef) {
  117. const ref = new StoreObjectRef(vl.id, callerStore);
  118. calleeStore.insertStore(v.id, ref);
  119. } else {
  120. calleeStore.insertStore(v.id, vl);
  121. }
  122. } else {
  123. // TODO: Better error message
  124. throw new Error(`Parameter ${v.id} is not compatible with the value given.`);
  125. }
  126. break;
  127. }
  128. case 0: {
  129. if(v.byRef && !vl.inStore) {
  130. throw new Error('You must inform a variable as parameter');
  131. } else if (v.type !== Types.ALL && vl.type !== v.type) {
  132. // TODO: Better error message
  133. throw new Error(`Parameter ${v.id} is not compatible with ${vl.type}.`);
  134. } else {
  135. if(v.byRef) {
  136. const ref = new StoreObjectRef(vl.id, callerStore);
  137. calleeStore.insertStore(v.id, ref);
  138. } else {
  139. calleeStore.insertStore(v.id, vl);
  140. }
  141. }
  142. }
  143. }
  144. });
  145. });
  146. return calleeStore;
  147. }
  148. executeCommands (store, cmds) {
  149. const auxExecCmdFun = (promise, cmd) => promise.then( sto => this.executeCommand(sto, cmd));
  150. let breakLoop = false;
  151. let $result = Promise.resolve(store);
  152. for (let index = 0; index < cmds.length && !breakLoop; index++) {
  153. const cmd = cmds[index];
  154. $result = auxExecCmdFun($result, cmd);
  155. $result.then(sto => {
  156. if(sto.mode === Modes.RETURN) {
  157. breakLoop = true;
  158. } else if (this.checkContext(Context.BREAKABLE &&
  159. sto.mode === Modes.BREAK)) {
  160. breakLoop = true;
  161. }
  162. return sto;
  163. });
  164. }
  165. return $result;
  166. }
  167. executeCommand (store, cmd) {
  168. while (store.mode === Modes.PAUSE) {
  169. continue;
  170. }
  171. if(store.mode === Modes.RETURN) {
  172. return Promise.resolve(store);
  173. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  174. return Promise.resolve(store);
  175. }
  176. if (cmd instanceof Commands.Declaration) {
  177. return this.executeDeclaration(store, cmd);
  178. } else if (cmd instanceof Commands.Assign) {
  179. return this.executeAssign(store, cmd);
  180. } else if (cmd instanceof Commands.Break) {
  181. return this.executeBreak(store, cmd);
  182. } else if (cmd instanceof Commands.Return) {
  183. return this.executeReturn(store, cmd);
  184. } else if (cmd instanceof Commands.IfThenElse) {
  185. return this.executeIfThenElse(store, cmd);
  186. } else if (cmd instanceof Commands.While) {
  187. return this.executeWhile(store, cmd);
  188. } else if (cmd instanceof Commands.DoWhile) {
  189. return this.executeDoWhile(store, cmd);
  190. } else if (cmd instanceof Commands.For) {
  191. return this.executeFor(store, cmd);
  192. } else if (cmd instanceof Commands.Switch) {
  193. return this.executeSwitch(store, cmd);
  194. } else if (cmd instanceof Commands.FunctionCall) {
  195. return this.executeFunctionCall(store, cmd);
  196. } else if (cmd instanceof Commands.SysCall) {
  197. return this.executeSysCall(store, cmd);
  198. } else {
  199. throw new Error("!!!CRITICAL A unknown command was found!!!\n" + cmd);
  200. }
  201. }
  202. executeSysCall (store, cmd) {
  203. if (cmd.id === NAMES.WRITE) {
  204. this.runWriteFunction(store)
  205. }
  206. }
  207. runWriteFunction (store) {
  208. const val = store.applyStore('p1');
  209. this.output.appendText(val.val);
  210. return Promise.resolve(store);
  211. }
  212. runReadFunction (store) {
  213. const typeToConvert = store.applyStore('p1').type;
  214. const listenInput = (text) => {
  215. if (typeToConvert === Types.INTEGER) {
  216. const val = toInt(text);
  217. return new StoreObject(Types.INTEGER, val);
  218. } else if (typeToConvert === Types.REAL) {
  219. return new StoreObject(Types.REAL, parseFloat(text));
  220. } else if (typeToConvert === Types.BOOLEAN) {
  221. } else if (typeToConvert === Types.STRING) {
  222. return new StoreObject(Types.STRING, text);
  223. }
  224. }
  225. return Promise.resolve(store).then( sto => {
  226. let received = false;
  227. const notify = (text) => {
  228. received = true;
  229. const result = listenInput(text);
  230. sto.updateStore('p1', result);
  231. }
  232. const obj = {notify: notify.bind(this)}
  233. this.input.registerListener(obj);
  234. this.input.requestInput();
  235. while(!received) {
  236. continue;
  237. }
  238. this.input.removeListener(obj);
  239. return sto;
  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. const auxCaseFun = (promise, switchExp, aCase) => {
  249. return promise.then( result => {
  250. const sto = result.sto;
  251. if (this.ignoreSwitchCases(sto)) {
  252. return Promise.resolve(result);
  253. } else if (result.wasTrue || aCase.isDefault) {
  254. const $newSto = this.executeCommand(result.sto,aCase.commands);
  255. return $newSto.then(nSto => {
  256. return Promise.resolve({wasTrue: true, sto: nSto});
  257. });
  258. } else {
  259. const $value = this.evaluateExpression(sto,
  260. new Expressions.InfixApp(Operators.EQ, switchExp, aCase.expression));
  261. return $value.then(vl => {
  262. if (vl.value) {
  263. const $newSto = this.executeCommand(result.sto,aCase.commands);
  264. return $newSto.then(nSto => {
  265. return Promise.resolve({wasTrue: true, sto: nSto});
  266. });
  267. } else {
  268. return Promise.resolve({wasTrue: false, sto: sto});
  269. }
  270. });
  271. }
  272. });
  273. }
  274. try {
  275. this.context.push(Context.BREAKABLE);
  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. this.context.pop();
  284. return result.then(r => {
  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(cmd.condition);
  373. return $value.then(vl => {
  374. if(vl.type === Types.BOOLEAN) {
  375. if(vl.value) {
  376. return this.executeCommands(store, cmd.ifTrue);
  377. } else {
  378. return this.executeCommands(store, cmd.ifFalse);
  379. }
  380. } else {
  381. // TODO: Better error message -- Inform line and column from token!!!!
  382. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  383. return Promise.reject(new Error(`If expression must be of type boolean`));
  384. }
  385. });
  386. } catch (error) {
  387. return Promise.reject(error);
  388. }
  389. }
  390. executeReturn (store, cmd) {
  391. try {
  392. const funcType = store.applyStore('$');
  393. const $value = this.evaluateExpression(store, cmd.expression);
  394. const funcName = store.applyStore('$name');
  395. return $value.then(vl => {
  396. if (funcType.type !== vl.type) {
  397. // TODO: Better error message -- Inform line and column from token!!!!
  398. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  399. return Promise.reject(new Error(`Function ${funcName.value} must return ${funcType.type} instead of ${vl.type}.`));
  400. } else {
  401. store.updateStore('$', vl);
  402. store.mode = Modes.RETURN;
  403. return Promise.resolve(store);
  404. }
  405. });
  406. } catch (error) {
  407. return Promise.reject(error);
  408. }
  409. }
  410. executeBreak (store, _) {
  411. if(this.checkContext(Context.BREAKABLE)) {
  412. store.mode = Modes.BREAK;
  413. return Promise.resolve(store);
  414. } else {
  415. return Promise.reject(new Error("!!!CRITIAL: Break command outside Loop/Switch scope!!!"));
  416. }
  417. }
  418. executeAssign (store, cmd) {
  419. try {
  420. const $value = this.evaluateExpression(store, cmd.expression);
  421. return $value.then( vl => {
  422. store.updateStore(cmd.id, vl)
  423. return store;
  424. });
  425. } catch (error) {
  426. return Promise.reject(error);
  427. }
  428. }
  429. executeDeclaration (store, cmd) {
  430. try {
  431. const $value = this.evaluateExpression(store, cmd.initial);
  432. if(cmd instanceof Commands.ArrayDeclaration) {
  433. const $lines = this.evaluateExpression(store, cmd.lines);
  434. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  435. return Promise.all([$lines, $columns, $value]).then(values => {
  436. const lineSO = values[0];
  437. if(lineSO.type !== Types.INTEGER) {
  438. // TODO: better error message
  439. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  440. return Promise.reject(new Error("Array dimension must be of type int"));
  441. }
  442. const line = lineSO.value;
  443. const columnSO = values[1];
  444. let column = null
  445. if (columnSO !== null) {
  446. if(columnSO.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. column = columnSO.value;
  452. }
  453. const value = values[2];
  454. const temp = new StoreObjectArray(cmd.subtype, line, column, null, cmd.isConst);
  455. store.insertStore(cmd.id, temp);
  456. return store.updateStore(cmd.id, value);
  457. });
  458. } else {
  459. const temp = new StoreObject(cmd.type, null, cmd.isConst);
  460. store.insertStore(cmd.id, temp);
  461. return $value.then(vl => store.updateStore(cmd.id, vl));
  462. }
  463. } catch (e) {
  464. return Promise.reject(e);
  465. }
  466. }
  467. evaluateExpression (store, exp) {
  468. if (exp instanceof Expressions.UnaryApp) {
  469. return this.evaluateUnaryApp(store, exp);
  470. } else if (exp instanceof Expressions.InfixApp) {
  471. return this.evaluateInfixApp(store, exp);
  472. } else if (exp instanceof Expressions.ArrayAccess) {
  473. return this.evaluateArrayAccess(store, exp);
  474. } else if (exp instanceof Expressions.VariableLiteral) {
  475. return this.evaluateVariableLiteral(store, exp);
  476. } else if (exp instanceof Expressions.IntLiteral) {
  477. return this.evaluateLiteral(store, exp);
  478. } else if (exp instanceof Expressions.RealLiteral) {
  479. return this.evaluateLiteral(store, exp);
  480. } else if (exp instanceof Expressions.BoolLiteral) {
  481. return this.evaluateLiteral(store, exp);
  482. } else if (exp instanceof Expressions.StringLiteral) {
  483. return this.evaluateLiteral(store, exp);
  484. } else if (exp instanceof Expressions.ArrayLiteral) {
  485. return this.evaluateArrayLiteral(store, exp);
  486. } else if (exp instanceof Expressions.FunctionCall) {
  487. return this.evaluateFunctionCall(store, exp);
  488. }
  489. return Promise.resolve(null);
  490. }
  491. evaluateFunctionCall (store, exp) {
  492. const func = this.findFunction(exp.id);
  493. if(func.returnType === Types.VOID) {
  494. // TODO: better error message
  495. return Promise.reject(new Error(`Function ${exp.id} cannot be used inside an expression`));
  496. }
  497. const $newStore = this.runFunction(func, exp.actualParameters, store);
  498. return $newStore.then( sto => sto.applyStore('$'));
  499. }
  500. evaluateArrayLiteral (store, exp) {
  501. if(!exp.isVector) {
  502. const $matrix = this.evaluateMatrix(store, exp.value);
  503. return $matrix.then(list => {
  504. const arr = new StoreObjectArray(list[0].subtype, list.length, list[0].lines, list);
  505. if(arr.isValid)
  506. return Promise.resolve(arr);
  507. else
  508. return Promise.reject(new Error(`Invalid array`))
  509. });
  510. } else {
  511. return this.evaluateVector(store, exp.value).then(list => {
  512. const stoArray = new StoreObjectArray(list[0].type, list.length, null, list);
  513. if(stoArray.isValid)
  514. return Promise.resolve(stoArray);
  515. else
  516. return Promise.reject(new Error(`Invalid array`))
  517. });
  518. }
  519. }
  520. evaluateVector (store, exps) {
  521. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  522. }
  523. evaluateMatrix (store, exps) {
  524. return Promise.all(exps.map( vector => {
  525. const $vector = this.evaluateVector(store, vector.value)
  526. return $vector.then(list => new StoreObjectArray(list[0].type, list.length, null, list))
  527. } ));
  528. }
  529. evaluateLiteral (_, exp) {
  530. return Promise.resolve(new StoreObject(exp.type, exp.value));
  531. }
  532. evaluateVariableLiteral (store, exp) {
  533. try {
  534. const val = store.applyStore(exp.id);
  535. return Promise.resolve(val);
  536. } catch (error) {
  537. return Promise.reject(error);
  538. }
  539. }
  540. evaluateArrayAccess (store, exp) {
  541. const mustBeArray = store.applyStore(exp.id);
  542. if (mustBeArray.type !== Types.ARRAY) {
  543. // TODO: better error message
  544. return Promise.reject(new Error(`${exp.id} is not of type array`));
  545. }
  546. const $line = this.evaluateExpression(store, exp.line);
  547. const $column = this.evaluateExpression(store, exp.column);
  548. return Promise.all([$line, $column]).then(values => {
  549. const lineSO = values[0];
  550. const columnSO = values[1];
  551. if(lineSO.type !== Types.INTEGER) {
  552. // TODO: better error message
  553. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  554. return Promise.reject(new Error("Array dimension must be of type int"));
  555. }
  556. const line = lineSO.value;
  557. let column = null;
  558. if(columnSO !== null) {
  559. if(columnSO.type !== Types.INTEGER) {
  560. // TODO: better error message
  561. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  562. return Promise.reject(new Error("Array dimension must be of type int"));
  563. }
  564. column = columnSO.value;
  565. }
  566. if (line >= mustBeArray.lines) {
  567. // TODO: better error message
  568. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${lines}`));
  569. }
  570. if (column !== null && mustBeArray.columns === null ){
  571. // TODO: better error message
  572. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  573. }
  574. if(column !== null && column >= mustBeArray.columns) {
  575. // TODO: better error message
  576. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  577. }
  578. if (column !== null) {
  579. return Promise.resolve(mustBeArray.value[line].value[column]);
  580. } else {
  581. return Promise.resolve(mustBeArray.value[line]);
  582. }
  583. });
  584. }
  585. evaluateUnaryApp (store, unaryApp) {
  586. const $left = this.evaluateExpression(store, infixApp.left);
  587. return $left.then( left => {
  588. if (!canApplyUnaryOp(infixApp.op, left)) {
  589. // TODO: better urgent error message
  590. return Promise.reject(new Error(`Cannot use this op to ${left.type}`));
  591. }
  592. switch (unaryApp.op) {
  593. case Operators.ADD:
  594. return new StoreObject(left.type, +left.value);
  595. case Operators.SUB:
  596. return new StoreObject(left.type, -left.value);
  597. case Operators.NOT:
  598. return new StoreObject(left.type, !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. if (!canApplyInfixOp(infixApp.op, left, right)) {
  611. // TODO: better urgent error message
  612. return Promise.reject(new Error(`Cannot use this op to ${left.type} and ${right.type}`));
  613. }
  614. switch (infixApp.op) {
  615. case Operators.ADD:
  616. return new StoreObject(left.type, left.value + right.value);
  617. case Operators.SUB:
  618. return new StoreObject(left.type, left.value - right.value);
  619. case Operators.MULT:
  620. return new StoreObject(left.type, left.value * right.value);
  621. case Operators.DIV:
  622. return new StoreObject(left.type, left.value / right.value);
  623. case Operators.MOD:
  624. return new StoreObject(left.type, left.value % right.value);
  625. case Operators.GT:
  626. return new StoreObject(Types.BOOLEAN, left.value > right.value);
  627. case Operators.GE:
  628. return new StoreObject(Types.BOOLEAN, left.value >= right.value);
  629. case Operators.LT:
  630. return new StoreObject(Types.BOOLEAN, left.value < right.value);
  631. case Operators.LE:
  632. return new StoreObject(Types.BOOLEAN, left.value <= right.value);
  633. case Operators.EQ:
  634. return new StoreObject(Types.BOOLEAN, left.value === right.value);
  635. case Operators.NEQ:
  636. return new StoreObject(Types.BOOLEAN, left.value !== right.value);
  637. case Operators.AND:
  638. return new StoreObject(Types.BOOLEAN, left.value && right.value);
  639. case Operators.OR:
  640. return new StoreObject(Types.BOOLEAN, left.value || right.value);
  641. default:
  642. return Promise.reject(new Error('!!!Critical Invalid InfixApp '+ infixApp.op));
  643. }
  644. });
  645. }
  646. }