1
0

ivprogProcessor.js 32 KB

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