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