1
0

ivprogProcessor.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. import * as Promise from 'bluebird'
  2. import { Store } from './store/store';
  3. import { StoreObject } from './store/storeObject';
  4. import { StoreObjectArray } from './store/storeObjectArray';
  5. import { StoreObjectRef } from './store/storeObjectRef';
  6. import { Modes } from './modes';
  7. import { Context } from './context';
  8. import { Types } from './../typeSystem/types';
  9. import { Operators } from './../ast/operators';
  10. import { LanguageDefinedFunction } from './definedFunctions';
  11. import { resultTypeAfterInfixOp, resultTypeAfterUnaryOp } from './compatibilityTable';
  12. import * as Commands from './../ast/commands/';
  13. import * as Expressions from './../ast/expressions/';
  14. import { StoreObjectArrayAddress } from './store/storeObjectArrayAddress';
  15. import { StoreObjectArrayAddressRef } from './store/storeObjectArrayAddressRef';
  16. import { CompoundType } from './../typeSystem/compoundType';
  17. import { convertToString } from '../typeSystem/parsers';
  18. let loopTimeoutMs = 10000
  19. export class IVProgProcessor {
  20. static get LOOP_TIMEOUT () {
  21. return loopTimeoutMs;
  22. }
  23. static set LOOP_TIMEOUT (ms) {
  24. loopTimeoutMs = ms;
  25. }
  26. constructor (ast) {
  27. this.ast = ast;
  28. this.globalStore = new Store();
  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. let funcStore = new Store();
  92. funcStore.extendStore(this.globalStore);
  93. let returnStoreObject = null;
  94. if(func.returnType instanceof CompoundType) {
  95. if(func.returnType.dimensions > 1) {
  96. returnStoreObject = new StoreObjectArray(func.returnType,-1,-1,[[]]);
  97. } else {
  98. returnStoreObject = new StoreObjectArray(func.returnType,-1,null,[]);
  99. }
  100. } else {
  101. returnStoreObject = new StoreObject(func.returnType, null);
  102. }
  103. const funcName = func.isMain ? 'main' : func.name;
  104. const funcNameStoreObject = new StoreObject(Types.STRING, funcName, true);
  105. funcStore.insertStore('$', returnStoreObject);
  106. funcStore.insertStore('$name', funcNameStoreObject);
  107. const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  108. return newFuncStore$.then(sto => {
  109. this.context.push(Context.FUNCTION);
  110. this.stores.push(sto);
  111. return this.executeCommands(sto, func.variablesDeclarations)
  112. .then(stoWithVars => this.executeCommands(stoWithVars, func.commands)).then(finalSto => {
  113. this.stores.pop();
  114. this.context.pop();
  115. return finalSto;
  116. });
  117. });
  118. }
  119. associateParameters (formalList, actualList, callerStore, calleeStore) {
  120. if (formalList.length != actualList.length) {
  121. // TODO: Better error message
  122. throw new Error("Numbers of parameters doesn't match");
  123. }
  124. const promises$ = actualList.map(actualParameter => this.evaluateExpression(callerStore, actualParameter));
  125. return Promise.all(promises$).then(values => {
  126. for (let i = 0; i < values.length; i++) {
  127. const stoObj = values[i];
  128. const formalParameter = formalList[i];
  129. if(formalParameter.type.isCompatible(stoObj.type)) {
  130. if(formalParameter.byRef && !stoObj.inStore) {
  131. throw new Error('You must inform a variable as parameter');
  132. }
  133. if(formalParameter.byRef) {
  134. let ref = null;
  135. if (stoObj instanceof StoreObjectArrayAddress) {
  136. ref = new StoreObjectArrayAddressRef(stoObj);
  137. } else {
  138. ref = new StoreObjectRef(stoObj.id, callerStore);
  139. }
  140. calleeStore.insertStore(formalParameter.id, ref);
  141. } else {
  142. let realValue = this.parseStoreObjectValue(stoObj);
  143. calleeStore.insertStore(formalParameter.id, realValue);
  144. }
  145. } else {
  146. throw new Error(`Parameter ${formalParameter.id} is not compatible with the value given.`);
  147. }
  148. }
  149. return calleeStore;
  150. });
  151. }
  152. executeCommands (store, cmds) {
  153. // helper to partially apply a function, in this case executeCommand
  154. const partial = (fun, cmd) => (sto) => fun(sto, cmd);
  155. return cmds.reduce((lastCommand, next) => {
  156. const nextCommand = partial(this.executeCommand.bind(this), 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. return new Promise.Promise((resolve, reject) => {
  204. const func = this.findFunction(cmd.id);
  205. this.runFunction(func, cmd.actualParameters, store)
  206. .then(sto => {
  207. if(!Types.VOID.isCompatible(func.returnType) && sto.mode !== Modes.RETURN) {
  208. // TODO: better error message
  209. reject(new Error(`Function ${func.name} must have a return command`));
  210. } else {
  211. resolve(store);
  212. }
  213. })
  214. .catch(err => reject(err));
  215. return null;
  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. return new Promise.Promise((resolve, reject) => {
  284. try {
  285. outerRef.loopTimers.push(Date.now());
  286. outerRef.context.push(Context.BREAKABLE);
  287. const $newStore = outerRef.executeCommands(store, cmd.commands);
  288. $newStore.then(sto => {
  289. if(sto.mode === Modes.BREAK) {
  290. outerRef.context.pop();
  291. sto.mode = Modes.RUN;
  292. outerRef.loopTimers.pop();
  293. resolve(sto);
  294. }
  295. const $value = outerRef.evaluateExpression(sto, cmd.expression);
  296. $value.then(vl => {
  297. if (!vl.type.isCompatible(Types.BOOLEAN)) {
  298. // TODO: Better error message -- Inform line and column from token!!!!
  299. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  300. reject(new Error(`DoWhile expression must be of type boolean`));
  301. }
  302. if (vl.value) {
  303. outerRef.context.pop();
  304. outerRef.loopTimers.forEach(t => {
  305. if(Date.now() - t >= IVProgProcessor.LOOP_TIMEOUT) {
  306. console.log("Timeout...");
  307. outerRef.forceKill = true;
  308. reject(new Error("Potential endless loop detected."));
  309. }
  310. })
  311. resolve(outerRef.executeCommand(sto, cmd));
  312. } else {
  313. outerRef.context.pop();
  314. outerRef.loopTimers.pop();
  315. console.log("Clear Timeout...");
  316. resolve(sto);
  317. }
  318. }).catch(err => reject(err));
  319. }).catch(err => reject(err));
  320. } catch (error) {
  321. reject(error)
  322. }
  323. return null;
  324. });
  325. }
  326. executeWhile (store, cmd) {
  327. const outerRef = this;
  328. return new Promise.Promise((resolve, reject) => {
  329. try {
  330. outerRef.loopTimers.push(Date.now());
  331. outerRef.context.push(Context.BREAKABLE);
  332. const $value = outerRef.evaluateExpression(store, cmd.expression);
  333. $value.then(vl => {
  334. if(vl.type.isCompatible(Types.BOOLEAN)) {
  335. if(vl.value) {
  336. const $newStore = outerRef.executeCommands(store, cmd.commands);
  337. $newStore.then(sto => {
  338. outerRef.context.pop();
  339. if (sto.mode === Modes.BREAK) {
  340. outerRef.loopTimers.pop();
  341. sto.mode = Modes.RUN;
  342. resolve(sto);
  343. } else
  344. outerRef.loopTimers.forEach(t => {
  345. if(Date.now() - t >= IVProgProcessor.LOOP_TIMEOUT) {
  346. console.log("Timeout...");
  347. outerRef.forceKill = true;
  348. reject(new Error("Potential endless loop detected."));
  349. }
  350. })
  351. resolve(outerRef.executeCommand(sto, cmd));
  352. }).catch(err => reject(err));
  353. } else {
  354. outerRef.context.pop();
  355. outerRef.loopTimers.pop();
  356. console.log("Clear Timeout...");
  357. resolve(store);
  358. }
  359. } else {
  360. // TODO: Better error message -- Inform line and column from token!!!!
  361. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  362. reject(new Error(`Loop condition must be of type boolean`));
  363. }
  364. }).catch(err => reject(err));
  365. } catch (error) {
  366. reject(error);
  367. }
  368. return null;
  369. });
  370. }
  371. executeIfThenElse (store, cmd) {
  372. try {
  373. const $value = this.evaluateExpression(store, cmd.condition);
  374. return $value.then(vl => {
  375. if(vl.type.isCompatible(Types.BOOLEAN)) {
  376. if(vl.value) {
  377. return this.executeCommands(store, cmd.ifTrue.commands);
  378. } else if( cmd.ifFalse !== null){
  379. if(cmd.ifFalse instanceof Commands.IfThenElse) {
  380. return this.executeCommand(store, cmd.ifFalse);
  381. } else {
  382. return this.executeCommands(store, cmd.ifFalse.commands);
  383. }
  384. } else {
  385. return Promise.resolve(store);
  386. }
  387. } else {
  388. // TODO: Better error message -- Inform line and column from token!!!!
  389. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  390. return Promise.reject(new Error(`If expression must be of type boolean`));
  391. }
  392. });
  393. } catch (error) {
  394. return Promise.reject(error);
  395. }
  396. }
  397. executeReturn (store, cmd) {
  398. try {
  399. const funcType = store.applyStore('$');
  400. const $value = this.evaluateExpression(store, cmd.expression);
  401. const funcName = store.applyStore('$name');
  402. return $value.then(vl => {
  403. if(vl === null && funcType.isCompatible(Types.VOID)) {
  404. return Promise.resolve(store);
  405. }
  406. if (vl === null || !funcType.type.isCompatible(vl.type)) {
  407. // TODO: Better error message -- Inform line and column from token!!!!
  408. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  409. return Promise.reject(new Error(`Function ${funcName.value} must return ${funcType.type} instead of ${vl.type}.`));
  410. } else {
  411. let realValue = this.parseStoreObjectValue(vl);
  412. store.updateStore('$', realValue);
  413. store.mode = Modes.RETURN;
  414. return Promise.resolve(store);
  415. }
  416. });
  417. } catch (error) {
  418. return Promise.reject(error);
  419. }
  420. }
  421. executeBreak (store, _) {
  422. if(this.checkContext(Context.BREAKABLE)) {
  423. store.mode = Modes.BREAK;
  424. return Promise.resolve(store);
  425. } else {
  426. return Promise.reject(new Error("!!!CRITIAL: Break command outside Loop/Switch scope!!!"));
  427. }
  428. }
  429. executeAssign (store, cmd) {
  430. try {
  431. const $value = this.evaluateExpression(store, cmd.expression);
  432. return $value.then( vl => {
  433. let realValue = this.parseStoreObjectValue(vl);
  434. store.updateStore(cmd.id, realValue)
  435. return store;
  436. });
  437. } catch (error) {
  438. return Promise.reject(error);
  439. }
  440. }
  441. executeArrayIndexAssign (store, cmd) {
  442. return new Promise.Promise((resolve, reject) => {
  443. const mustBeArray = store.applyStore(cmd.id);
  444. if(!(mustBeArray.type instanceof CompoundType)) {
  445. reject(new Error(cmd.id + " is not a vector/matrix"));
  446. return;
  447. }
  448. const line$ = this.evaluateExpression(store, cmd.line);
  449. const column$ = this.evaluateExpression(store, cmd.column);
  450. const value$ = this.evaluateExpression(store, cmd.expression);
  451. Promise.all([line$, column$, value$]).then(results => {
  452. const lineSO = results[0];
  453. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  454. // TODO: better error message
  455. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  456. reject(new Error("Array dimension must be of type int"));
  457. return;
  458. }
  459. const line = lineSO.number;
  460. const columnSO = results[1];
  461. let column = null
  462. if (columnSO !== null) {
  463. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  464. // TODO: better error message
  465. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  466. reject(new Error("Array dimension must be of type int"));
  467. return;
  468. }
  469. column = columnSO.number;
  470. }
  471. const value = this.parseStoreObjectValue(results[2]);
  472. if (line >= mustBeArray.lines) {
  473. // TODO: better error message
  474. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${lines}`));
  475. }
  476. if (column !== null && mustBeArray.columns === null ){
  477. // TODO: better error message
  478. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  479. }
  480. if(column !== null && column >= mustBeArray.columns) {
  481. // TODO: better error message
  482. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  483. }
  484. const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
  485. if (column !== null) {
  486. if (value.type instanceof CompoundType) {
  487. reject(new Error("Invalid operation. This must be a value: line "+cmd.sourceInfo.line));
  488. return;
  489. }
  490. newArray.value[line].value[column] = value;
  491. store.updateStore(cmd.id, newArray);
  492. } else {
  493. if(mustBeArray.columns !== null && value.type instanceof CompoundType) {
  494. reject(new Error("Invalid operation. This must be a vector: line "+cmd.sourceInfo.line));
  495. return;
  496. }
  497. newArray.value[line] = value;
  498. store.updateStore(cmd.id, newArray);
  499. }
  500. resolve(store);
  501. }).catch(err => reject(err));
  502. });
  503. }
  504. executeDeclaration (store, cmd) {
  505. try {
  506. const $value = this.evaluateExpression(store, cmd.initial);
  507. if(cmd instanceof Commands.ArrayDeclaration) {
  508. const $lines = this.evaluateExpression(store, cmd.lines);
  509. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  510. return Promise.all([$lines, $columns, $value]).then(values => {
  511. const lineSO = values[0];
  512. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  513. // TODO: better error message
  514. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  515. return Promise.reject(new Error("Array dimension must be of type int"));
  516. }
  517. const line = lineSO.number;
  518. const columnSO = values[1];
  519. let column = null
  520. if (columnSO !== null) {
  521. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  522. // TODO: better error message
  523. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  524. return Promise.reject(new Error("Array dimension must be of type int"));
  525. }
  526. column = columnSO.number;
  527. }
  528. const value = values[2];
  529. const temp = new StoreObjectArray(cmd.type, line, column, null);
  530. store.insertStore(cmd.id, temp);
  531. let realValue = value;
  532. if (value !== null) {
  533. if(value instanceof StoreObjectArrayAddress) {
  534. if(value.type instanceof CompoundType) {
  535. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  536. } else {
  537. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  538. }
  539. }
  540. } else {
  541. realValue = new StoreObjectArray(cmd.type, line, column, [])
  542. if(column !== null) {
  543. for (let i = 0; i < line; i++) {
  544. realValue.value.push(new StoreObjectArray(new CompoundType(cmd.type.innerType, 1), column, null, []));
  545. }
  546. }
  547. }
  548. realValue.readOnly = cmd.isConst;
  549. store.updateStore(cmd.id, realValue);
  550. return store;
  551. });
  552. } else {
  553. const temp = new StoreObject(cmd.type, null);
  554. store.insertStore(cmd.id, temp);
  555. return $value.then(vl => {
  556. let realValue = vl;
  557. if (vl !== null) {
  558. if(vl instanceof StoreObjectArrayAddress) {
  559. if(vl.type instanceof CompoundType) {
  560. realValue = Object.assign(new StoreObjectArray(null,null,null), vl.refValue);
  561. } else {
  562. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  563. }
  564. }
  565. } else {
  566. realValue = new StoreObject(cmd.type,0);
  567. }
  568. realValue.readOnly = cmd.isConst;
  569. store.updateStore(cmd.id, realValue);
  570. return store;
  571. });
  572. }
  573. } catch (e) {
  574. return Promise.reject(e);
  575. }
  576. }
  577. evaluateExpression (store, exp) {
  578. if (exp instanceof Expressions.UnaryApp) {
  579. return this.evaluateUnaryApp(store, exp);
  580. } else if (exp instanceof Expressions.InfixApp) {
  581. return this.evaluateInfixApp(store, exp);
  582. } else if (exp instanceof Expressions.ArrayAccess) {
  583. return this.evaluateArrayAccess(store, exp);
  584. } else if (exp instanceof Expressions.VariableLiteral) {
  585. return this.evaluateVariableLiteral(store, exp);
  586. } else if (exp instanceof Expressions.IntLiteral) {
  587. return this.evaluateLiteral(store, exp);
  588. } else if (exp instanceof Expressions.RealLiteral) {
  589. return this.evaluateLiteral(store, exp);
  590. } else if (exp instanceof Expressions.BoolLiteral) {
  591. return this.evaluateLiteral(store, exp);
  592. } else if (exp instanceof Expressions.StringLiteral) {
  593. return this.evaluateLiteral(store, exp);
  594. } else if (exp instanceof Expressions.ArrayLiteral) {
  595. return this.evaluateArrayLiteral(store, exp);
  596. } else if (exp instanceof Expressions.FunctionCall) {
  597. return this.evaluateFunctionCall(store, exp);
  598. }
  599. return Promise.resolve(null);
  600. }
  601. evaluateFunctionCall (store, exp) {
  602. const func = this.findFunction(exp.id);
  603. if(Types.VOID.isCompatible(func.returnType)) {
  604. // TODO: better error message
  605. return Promise.reject(new Error(`Function ${exp.id} cannot be used inside an expression`));
  606. }
  607. const $newStore = this.runFunction(func, exp.actualParameters, store);
  608. return $newStore.then( sto => {
  609. if(sto.mode !== Modes.RETURN) {
  610. return Promise.reject(new Error("The function that was called did not had a return command: "+exp.id));
  611. }
  612. const val = sto.applyStore('$');
  613. if (val instanceof StoreObjectArray) {
  614. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  615. } else {
  616. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  617. }
  618. });
  619. }
  620. evaluateArrayLiteral (store, exp) {
  621. if(!exp.isVector) {
  622. const $matrix = this.evaluateMatrix(store, exp.value);
  623. return $matrix.then(list => {
  624. const type = new CompoundType(list[0].type.innerType, 2);
  625. const arr = new StoreObjectArray(type, list.length, list[0].lines, list);
  626. if(arr.isValid)
  627. return Promise.resolve(arr);
  628. else
  629. return Promise.reject(new Error(`Invalid array`))
  630. });
  631. } else {
  632. return this.evaluateVector(store, exp.value).then(list => {
  633. const type = new CompoundType(list[0].type, 1);
  634. const stoArray = new StoreObjectArray(type, list.length, null, list);
  635. if(stoArray.isValid)
  636. return Promise.resolve(stoArray);
  637. else
  638. return Promise.reject(new Error(`Invalid array`))
  639. });
  640. }
  641. }
  642. evaluateVector (store, exps) {
  643. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  644. }
  645. evaluateMatrix (store, exps) {
  646. return Promise.all(exps.map( vector => {
  647. const $vector = this.evaluateVector(store, vector.value)
  648. return $vector.then(list => {
  649. const type = new CompoundType(list[0].type, 1);
  650. return new StoreObjectArray(type, list.length, null, list)
  651. });
  652. } ));
  653. }
  654. evaluateLiteral (_, exp) {
  655. return Promise.resolve(new StoreObject(exp.type, exp.value));
  656. }
  657. evaluateVariableLiteral (store, exp) {
  658. try {
  659. const val = store.applyStore(exp.id);
  660. if (val instanceof StoreObjectArray) {
  661. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  662. } else {
  663. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  664. }
  665. } catch (error) {
  666. return Promise.reject(error);
  667. }
  668. }
  669. evaluateArrayAccess (store, exp) {
  670. const mustBeArray = store.applyStore(exp.id);
  671. if (!(mustBeArray.type instanceof CompoundType)) {
  672. // TODO: better error message
  673. console.log(mustBeArray.type);
  674. return Promise.reject(new Error(`${exp.id} is not of type array`));
  675. }
  676. const $line = this.evaluateExpression(store, exp.line);
  677. const $column = this.evaluateExpression(store, exp.column);
  678. return Promise.all([$line, $column]).then(values => {
  679. const lineSO = values[0];
  680. const columnSO = values[1];
  681. if(!Types.INTEGER.isCompatible(lineSO.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. const line = lineSO.number;
  687. let column = null;
  688. if(columnSO !== null) {
  689. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  690. // TODO: better error message
  691. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  692. return Promise.reject(new Error("Array dimension must be of type int"));
  693. }
  694. column = columnSO.number;
  695. }
  696. if (line >= mustBeArray.lines) {
  697. // TODO: better error message
  698. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${lines}`));
  699. }
  700. if (column !== null && mustBeArray.columns === null ){
  701. // TODO: better error message
  702. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  703. }
  704. if(column !== null && column >= mustBeArray.columns) {
  705. // TODO: better error message
  706. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  707. }
  708. return Promise.resolve(new StoreObjectArrayAddress(mustBeArray.id, line, column, store));
  709. });
  710. }
  711. evaluateUnaryApp (store, unaryApp) {
  712. const $left = this.evaluateExpression(store, unaryApp.left);
  713. return $left.then( left => {
  714. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  715. if (Types.UNDEFINED.isCompatible(resultType)) {
  716. // TODO: better urgent error message
  717. return Promise.reject(new Error(`Cannot use this op to ${left.type}`));
  718. }
  719. switch (unaryApp.op.ord) {
  720. case Operators.ADD.ord:
  721. return new StoreObject(resultType, left.value);
  722. case Operators.SUB.ord:
  723. return new StoreObject(resultType, left.value.negated());
  724. case Operators.NOT.ord:
  725. return new StoreObject(resultType, !left.value);
  726. default:
  727. return Promise.reject(new Error('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  728. }
  729. });
  730. }
  731. evaluateInfixApp (store, infixApp) {
  732. const $left = this.evaluateExpression(store, infixApp.left);
  733. const $right = this.evaluateExpression(store, infixApp.right);
  734. return Promise.all([$left, $right]).then(values => {
  735. const left = values[0];
  736. const right = values[1];
  737. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  738. if (Types.UNDEFINED.isCompatible(resultType)) {
  739. // TODO: better urgent error message
  740. return Promise.reject(new Error(`Cannot use this ${infixApp.op} to ${left.type} and ${right.type}`));
  741. }
  742. let result = null;
  743. switch (infixApp.op.ord) {
  744. case Operators.ADD.ord: {
  745. if(Types.STRING.isCompatible(left.type)) {
  746. const rightStr = convertToString(right.value, right.type);
  747. return new StoreObject(resultType, left.value + rightStr);
  748. } else if (Types.STRING.isCompatible(right.type)) {
  749. const leftStr = convertToString(left.value, left.type);
  750. return new StoreObject(resultType, leftStr + right.value);
  751. } else {
  752. return new StoreObject(resultType, left.value.plus(right.value));
  753. }
  754. }
  755. case Operators.SUB.ord:
  756. return new StoreObject(resultType, left.value.minus(right.value));
  757. case Operators.MULT.ord:
  758. return new StoreObject(resultType, left.value.times(right.value));
  759. case Operators.DIV.ord: {
  760. result = left.value / right.value;
  761. if (Types.INTEGER.isCompatible(resultType))
  762. result = left.value.divToInt(right.value);
  763. else
  764. result = left.value.div(right.value);
  765. return new StoreObject(resultType, result);
  766. }
  767. case Operators.MOD.ord:
  768. return new StoreObject(resultType, left.value.modulo(right.value));
  769. case Operators.GT.ord: {
  770. if (Types.STRING.isCompatible(left.type)) {
  771. result = left.value.length > right.value.length;
  772. } else {
  773. result = left.value.gt(right.value);
  774. }
  775. return new StoreObject(resultType, result);
  776. }
  777. case Operators.GE.ord: {
  778. if (Types.STRING.isCompatible(left.type)) {
  779. result = left.value.length >= right.value.length;
  780. } else {
  781. result = left.value.gte(right.value);
  782. }
  783. return new StoreObject(resultType, result);
  784. }
  785. case Operators.LT.ord: {
  786. if (Types.STRING.isCompatible(left.type)) {
  787. result = left.value.length < right.value.length;
  788. } else {
  789. result = left.value.lt(right.value);
  790. }
  791. return new StoreObject(resultType, result);
  792. }
  793. case Operators.LE.ord: {
  794. if (Types.STRING.isCompatible(left.type)) {
  795. result = left.value.length <= right.value.length;
  796. } else {
  797. result = left.value.lte(right.value);
  798. }
  799. return new StoreObject(resultType, result);
  800. }
  801. case Operators.EQ.ord: {
  802. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  803. result = left.value.eq(right.value);
  804. } else {
  805. result = left.value === right.value;
  806. }
  807. return new StoreObject(resultType, result);
  808. }
  809. case Operators.NEQ.ord: {
  810. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  811. result = !left.value.eq(right.value);
  812. } else {
  813. result = left.value !== right.value;
  814. }
  815. return new StoreObject(resultType, result);
  816. }
  817. case Operators.AND.ord:
  818. return new StoreObject(resultType, left.value && right.value);
  819. case Operators.OR.ord:
  820. return new StoreObject(resultType, left.value || right.value);
  821. default:
  822. return Promise.reject(new Error('!!!Critical Invalid InfixApp '+ infixApp.op));
  823. }
  824. });
  825. }
  826. parseStoreObjectValue (vl) {
  827. let realValue = vl;
  828. if(vl instanceof StoreObjectArrayAddress) {
  829. if(vl.type instanceof CompoundType) {
  830. switch(vl.type.dimensions) {
  831. case 1: {
  832. realValue = new StoreObjectArray(vl.type, vl.value);
  833. break;
  834. }
  835. default: {
  836. throw new Error("Three dimensional array address...");
  837. }
  838. }
  839. } else {
  840. realValue = new StoreObject(vl.type, vl.value);
  841. }
  842. }
  843. return realValue;
  844. }
  845. }