ivprogProcessor.js 31 KB

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