ivprogProcessor.js 29 KB

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