ivprogProcessor.js 33 KB

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