ivprogProcessor.js 33 KB

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