ivprogProcessor.js 30 KB

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