ivprogProcessor.js 33 KB

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