ivprogProcessor.js 31 KB

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