1
0

ivprogProcessor.js 32 KB

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