ivprogProcessor.js 31 KB

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