ivprogProcessor.js 31 KB

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