ivprogProcessor.js 29 KB

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