ivprogProcessor.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. import { Store } from './store/store';
  2. import { StoreObject } from './store/storeObject';
  3. import { StoreObjectArray } from './store/storeObjectArray';
  4. import { Modes } from './modes';
  5. import { Context } from './context';
  6. import { Types } from './../ast/types';
  7. import { Operators } from './../ast/operators';
  8. import { canApplyInfixOp, canApplyUnaryOp } from './compatibilityTable';
  9. import * as Commands from './../ast/commands/';
  10. import * as Expressions from './../ast/expressions/';
  11. export class IVProgProcessor {
  12. constructor(ast) {
  13. this.ast = ast;
  14. this.globalStore = new Store();
  15. this.stores = [this.globalStore];
  16. this.context = [Context.BASE];
  17. this.input = null;
  18. this.output = null;
  19. }
  20. registerInput (input) {
  21. this.input = input;
  22. }
  23. registerOutput (output) {
  24. this.output = output;
  25. }
  26. checkContext(context) {
  27. return this.context[this.context.length] === context;
  28. }
  29. ignoreSwitchCases (store) {
  30. if (store.mode === Modes.RETURN) {
  31. return true;
  32. } else if (store.mode === Modes.BREAK) {
  33. return true;
  34. } else {
  35. return false;
  36. }
  37. }
  38. interpretAST () {
  39. this.initGlobal();
  40. const mainFunc = this.findMainFunction();
  41. if(mainFunc === null) {
  42. // TODO: Better error message
  43. throw new Error("Missing main funciton.");
  44. }
  45. return this.runFunction(mainFunc, [], this.globalStore);
  46. }
  47. initGlobal () {
  48. if(!this.checkContext(Context.BASE)) {
  49. throw new Error("!!!CRITICAL: Invalid call to initGlobal outside BASE context!!!");
  50. }
  51. this.ast.global.forEach(decl => {
  52. this.executeCommand(this.globalStore, decl).then(sto => this.globalStore = sto);
  53. });
  54. }
  55. findMainFunction () {
  56. return this.ast.functions.find(v => v.isMain);
  57. }
  58. findFunction (name) {
  59. const val = this.ast.functions.find( v => v.name === name);
  60. if (!!!val) {
  61. // TODO: better error message;
  62. throw new Error(`Function ${name} is not defined.`);
  63. }
  64. return val;
  65. }
  66. runFunction (func, actualParameters, store) {
  67. let funcStore = new Store();
  68. funcStore.extendStore(this.globalStore);
  69. const returnStoreObject = new StoreObject(func.returnType, null);
  70. const funcName = func.isMain ? 'main' : func.name;
  71. const funcNameStoreObject = new StoreObject(Types.STRING, funcName, true);
  72. funcStore.insertStore('$', returnStoreObject);
  73. funcStore.insertStore('$name', funcNameStoreObject);
  74. funcStore = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  75. this.context.push(Context.FUNCTION);
  76. this.stores.push(funcStore);
  77. const result = this.executeCommands(funcStore, func.commands);
  78. this.stores.pop();
  79. this.context.pop();
  80. return result;
  81. }
  82. associateParameters (formalList, actualList, callerStore, calleeStore) {
  83. if (formalList.length != actualList.length) {
  84. // TODO: Better error message
  85. throw new Error("Numbers of parameters doesn't match");
  86. }
  87. formalList.forEach((v, i) => {
  88. this.evaluateExpression(callerStore, actualList[i])
  89. .then(vl => {
  90. switch (v.dimensions) {
  91. case 1: {
  92. if (vl.lines > 0 && vl.columns === null
  93. && vl.subtype === v.subtype) {
  94. calleeStore.insertStore(v.id, vl);
  95. } else {
  96. // TODO: Better error message
  97. throw new Error(`Parameter ${v.id} is not compatible with the value given.`);
  98. }
  99. break;
  100. }
  101. case 2: {
  102. if (vl.lines > 0 && vl.columns > 0
  103. && vl.subtype === v.subtype) {
  104. calleeStore.insertStore(v.id, vl);
  105. } else {
  106. // TODO: Better error message
  107. throw new Error(`Parameter ${v.id} is not compatible with the value given.`);
  108. }
  109. break;
  110. }
  111. case 0: {
  112. if (vl.type !== v.type) {
  113. // TODO: Better error message
  114. throw new Error(`Parameter ${v.id} is not compatible with ${vl.type}.`);
  115. } else {
  116. calleeStore.insertStore(v.id, vl);
  117. }
  118. }
  119. }
  120. });
  121. });
  122. return calleeStore;
  123. }
  124. executeCommands (store, cmds) {
  125. const auxExecCmdFun = (promise, cmd) => promise.then( sto => this.executeCommand(sto, cmd));
  126. let breakLoop = false;
  127. let $result = Promise.resolve(store);
  128. for (let index = 0; index < cmds.length && !breakLoop; index++) {
  129. const cmd = cmds[index];
  130. $result = auxExecCmdFun($result, cmd);
  131. $result.then(sto => {
  132. if(sto.mode === Modes.RETURN) {
  133. breakLoop = true;
  134. } else if (this.checkContext(Context.BREAKABLE &&
  135. sto.mode === Modes.BREAK)) {
  136. breakLoop = true;
  137. }
  138. return sto;
  139. });
  140. }
  141. return $result;
  142. }
  143. executeCommand (store, cmd) {
  144. while (store.mode === Modes.PAUSE) {
  145. continue;
  146. }
  147. if(store.mode === Modes.RETURN) {
  148. return Promise.resolve(store);
  149. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  150. return Promise.resolve(store);
  151. }
  152. if (cmd instanceof Commands.Declaration) {
  153. return this.executeDeclaration(store, cmd);
  154. } else if (cmd instanceof Commands.Assign) {
  155. return this.executeAssign(store, cmd);
  156. } else if (cmd instanceof Commands.Break) {
  157. return this.executeBreak(store, cmd);
  158. } else if (cmd instanceof Commands.Return) {
  159. return this.executeReturn(store, cmd);
  160. } else if (cmd instanceof Commands.IfThenElse) {
  161. return this.executeIfThenElse(store, cmd);
  162. } else if (cmd instanceof Commands.While) {
  163. return this.executeWhile(store, cmd);
  164. } else if (cmd instanceof Commands.DoWhile) {
  165. return this.executeDoWhile(store, cmd);
  166. } else if (cmd instanceof Commands.For) {
  167. return this.executeFor(store, cmd);
  168. } else if (cmd instanceof Commands.Switch) {
  169. return this.executeSwitch(store, cmd);
  170. } else if (cmd instanceof Commands.FunctionCall) {
  171. return this.executeFunctionCall(store, cmd);
  172. } else {
  173. throw new Error("!!!CRITICAL A unknown command was found!!!\n" + cmd);
  174. }
  175. }
  176. executeFunctionCall (store, cmd) {
  177. const func = this.findFunction(cmd.id);
  178. this.runFunction(func, cmd.actualParameters, store);
  179. return Promise.resolve(store);
  180. }
  181. executeSwitch (store, cmd) {
  182. const auxCaseFun = (promise, switchExp, aCase) => {
  183. return promise.then( result => {
  184. const sto = result.sto;
  185. if (this.ignoreSwitchCases(sto)) {
  186. return Promise.resolve(result);
  187. } else if (result.wasTrue || aCase.isDefault) {
  188. const $newSto = this.executeCommand(result.sto,aCase.commands);
  189. return $newSto.then(nSto => {
  190. return Promise.resolve({wasTrue: true, sto: nSto});
  191. });
  192. } else {
  193. const $value = this.evaluateExpression(sto,
  194. new Expressions.InfixApp('==', switchExp, aCase.expression));
  195. return $value.then(vl => {
  196. if (vl.value) {
  197. const $newSto = this.executeCommand(result.sto,aCase.commands);
  198. return $newSto.then(nSto => {
  199. return Promise.resolve({wasTrue: true, sto: nSto});
  200. });
  201. } else {
  202. return Promise.resolve({wasTrue: false, sto: sto});
  203. }
  204. });
  205. }
  206. });
  207. }
  208. try {
  209. this.context.push(Context.BREAKABLE);
  210. let breakLoop = false;
  211. const case0 = cmd.cases[0];
  212. let $result = Promise.resolve({wasTrue: false, sto: store});
  213. for (let index = 0; index < cmd.cases.length && !breakLoop; index++) {
  214. const aCase = cmd.cases[index];
  215. $result = auxCaseFun($result, cmd.expression, aCase);
  216. $result.then( r => breakLoop = this.ignoreSwitchCases(r.sto));
  217. }
  218. this.context.pop();
  219. return result.then(r => r.sto);
  220. } catch (error) {
  221. return Promise.reject(error);
  222. }
  223. }
  224. executeFor (store, cmd) {
  225. try {
  226. //BEGIN for -> while rewrite
  227. const initCmd = cmd.assignment;
  228. const condition = cmd.condition;
  229. const increment = cmd.increment;
  230. const whileBlock = new Commands.CommandBlock([],
  231. cmd.commands.concat(increment));
  232. const forAsWhile = new Commands.While(condition, whileBlock);
  233. //END for -> while rewrite
  234. const newCmdList = [initCmd,forAsWhile];
  235. return this.executeCommands(store, newCmdList);
  236. } catch (error) {
  237. return Promise.reject(error);
  238. }
  239. }
  240. executeDoWhile (store, cmd) {
  241. try {
  242. this.context.push(Context.BREAKABLE);
  243. const $newStore = this.executeCommands(store, cmd.commands);
  244. return $newStore.then(sto => {
  245. const $value = this.evaluateExpression(sto, cmd.expression);
  246. return $value.then(vl => {
  247. if (vl.type !== Types.BOOLEAN) {
  248. // TODO: Better error message -- Inform line and column from token!!!!
  249. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  250. return Promise.reject(new Error(`DoWhile expression must be of type boolean`));
  251. }
  252. if (vl.value) {
  253. this.context.pop();
  254. return this.executeCommand(sto, cmd);
  255. } else {
  256. this.context.pop();
  257. return Promise.resolve(sto);
  258. }
  259. });
  260. });
  261. } catch (error) {
  262. return Promise.reject(error)
  263. }
  264. }
  265. executeWhile (store, cmd) {
  266. try {
  267. this.context.push(Context.BREAKABLE);
  268. const $value = this.evaluateExpression(store, cmd.expression);
  269. return $value.then(vl => {
  270. if(vl.type === Types.BOOLEAN) {
  271. if(vl.value) {
  272. const $newStore = this.executeCommands(store, cmd.commands);
  273. return $newStore.then(sto => {
  274. this.context.pop();
  275. return this.executeCommand(sto, cmd);
  276. });
  277. } else {
  278. this.context.pop();
  279. return Promise.resolve(store);
  280. }
  281. } else {
  282. // TODO: Better error message -- Inform line and column from token!!!!
  283. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  284. return Promise.reject(new Error(`Loop condition must be of type boolean`));
  285. }
  286. });
  287. } catch (error) {
  288. return Promise.reject(error);
  289. }
  290. }
  291. executeIfThenElse (store, cmd) {
  292. try {
  293. const $value = this.evaluateExpression(cmd.condition);
  294. return $value.then(vl => {
  295. if(vl.type === Types.BOOLEAN) {
  296. if(vl.value) {
  297. return this.executeCommands(store, cmd.ifTrue);
  298. } else {
  299. return this.executeCommands(store, cmd.ifFalse);
  300. }
  301. } else {
  302. // TODO: Better error message -- Inform line and column from token!!!!
  303. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  304. return Promise.reject(new Error(`If expression must be of type boolean`));
  305. }
  306. });
  307. } catch (error) {
  308. return Promise.reject(error);
  309. }
  310. }
  311. executeReturn (store, cmd) {
  312. try {
  313. const funcType = store.applyStore('$');
  314. const $value = this.evaluateExpression(store, cmd.expression);
  315. const funcName = store.applyStore('$name');
  316. return $value.then(vl => {
  317. if (funcType.type !== vl.type) {
  318. // TODO: Better error message -- Inform line and column from token!!!!
  319. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  320. return Promise.reject(new Error(`Function ${funcName.value} must return ${funcType.type} instead of ${vl.type}.`));
  321. } else {
  322. store.updateStore('$', vl);
  323. store.mode = Modes.RETURN;
  324. return Promise.resolve(store);
  325. }
  326. });
  327. } catch (error) {
  328. return Promise.reject(error);
  329. }
  330. }
  331. executeBreak (store, _) {
  332. if(this.checkContext(Context.BREAKABLE)) {
  333. store.mode = Modes.BREAK;
  334. return Promise.resolve(store);
  335. } else {
  336. return Promise.reject(new Error("!!!CRITIAL: Break command outside Loop/Switch scope!!!"));
  337. }
  338. }
  339. executeAssign (store, cmd) {
  340. try {
  341. const $value = this.evaluateExpression(store, cmd.expression);
  342. return $value.then( vl => {
  343. store.updateStore(cmd.id, vl)
  344. return store;
  345. });
  346. } catch (error) {
  347. return Promise.reject(error);
  348. }
  349. }
  350. executeDeclaration (store, cmd) {
  351. try {
  352. const $value = this.evaluateExpression(store, cmd.initial);
  353. if(cmd instanceof Commands.ArrayDeclaration) {
  354. const temp = new StoreObjectArray(decl.subtype, decl.lines, decl.columns, null, decl.isConst);
  355. store.insertStore(decl.id, temp);
  356. return $value.then(vl => {
  357. store.updateStore(decl.id, vl)
  358. return store;
  359. });
  360. } else {
  361. const temp = new StoreObject(decl.type, null, decl.isConst);
  362. store.insertStore(decl.id, temp);
  363. return $value.then(vl => {
  364. store.updateStore(decl.id, vl)
  365. return store;
  366. });
  367. }
  368. } catch (e) {
  369. return Promise.reject(e);
  370. }
  371. }
  372. evaluateExpression (store, exp) {
  373. if (exp instanceof Expressions.UnaryApp) {
  374. return this.evaluateUnaryApp(store, exp);
  375. } else if (exp instanceof Expressions.InfixApp) {
  376. return this.evaluateInfixApp(store, exp);
  377. } else if (exp instanceof Expressions.ArrayAccess) {
  378. return this.evaluateArrayAccess(store, exp);
  379. } else if (exp instanceof Expressions.VariableLiteral) {
  380. return this.evaluateVariableLiteral(store, exp);
  381. } else if (exp instanceof Expressions.IntLiteral) {
  382. return this.evaluateLiteral(store, exp);
  383. } else if (exp instanceof Expressions.RealLiteral) {
  384. return this.evaluateLiteral(store, exp);
  385. } else if (exp instanceof Expressions.BoolLiteral) {
  386. return this.evaluateLiteral(store, exp);
  387. } else if (exp instanceof Expressions.StringLiteral) {
  388. return this.evaluateLiteral(store, exp);
  389. } else if (exp instanceof Expressions.ArrayLiteral) {
  390. return this.evaluateArrayLiteral(store, exp);
  391. } else if (exp instanceof Expressions.FunctionCall) {
  392. return this.evaluateFunctionCall(store, exp);
  393. }
  394. }
  395. evaluateFunctionCall (store, exp) {
  396. const func = this.findFunction(exp.id);
  397. if(func.returnType === Types.VOID) {
  398. // TODO: better error message
  399. return Promise.reject(new Error(`Function ${exp.id} cannot be used inside an expression`));
  400. }
  401. const $newStore = this.runFunction(func, exp.actualParameters, store);
  402. return $newStore.then( sto => sto.applyStore('$'));
  403. }
  404. evaluateArrayLiteral (store, exp) {
  405. if(exp.columns !== null) {
  406. let column = [];
  407. for (let i = 0; i < exp.lines; i++) {
  408. const line = [];
  409. for (let j = 0; j < exp.columns; j++) {
  410. const $value = this.evaluateExpression(store, exp.value[i].value[j]);
  411. $value.then(value => line.push(value));
  412. }
  413. const stoArray = new StoreObjectArray(line[0].type, line.length, null, line);
  414. column.push(stoArray);
  415. }
  416. const arr = new StoreObjectArray(column[0].subtype, column.length, column[0].lines, column);
  417. return Promise.resolve(arr);
  418. } else {
  419. let line = [];
  420. for (let i = 0; i < exp.lines; i++) {
  421. const $value = this.evaluateExpression(store, exp.value[i].value[j]);
  422. $value.then(value => line.push(value));
  423. }
  424. const stoArray = new StoreObjectArray(line[0].type, line.length, null, line);
  425. return Promise.resolve(stoArray);
  426. }
  427. }
  428. evaluateLiteral (_, exp) {
  429. return Promise.resolve(new StoreObject(exp.type, exp.value));
  430. }
  431. evaluateVariableLiteral (store, exp) {
  432. try {
  433. const val = store.applyStore(exp.id);
  434. return Promise.resolve(val);
  435. } catch (error) {
  436. return Promise.reject(error);
  437. }
  438. }
  439. evaluateArrayAccess (store, exp) {
  440. const mustBeArray = store.applyStore(exp.id);
  441. if (mustBeArray.type !== Types.ARRAY) {
  442. // TODO: better error message
  443. return Promise.reject(new Error(`${exp.id} is not of type array`));
  444. }
  445. if (exp.line >= mustBeArray.lines) {
  446. // TODO: better error message
  447. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${exp.lines}`));
  448. }
  449. if (exp.column !== null && mustBeArray.columns === null ){
  450. // TODO: better error message
  451. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${exp.column}`));
  452. }
  453. if(exp.column !== null && exp.column >= mustBeArray.columns) {
  454. // TODO: better error message
  455. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${exp.column}`));
  456. }
  457. if (exp.column !== null) {
  458. return Promise.resolve(mustBeArray.value[exp.line][exp.column]);
  459. } else {
  460. return Promise.resolve(mustBeArray.value[exp.line]);
  461. }
  462. }
  463. evaluateUnaryApp (store, unaryApp) {
  464. const $left = this.evaluateExpression(store, infixApp.left);
  465. return $left.then( left => {
  466. if (!canApplyUnaryOp(infixApp.op, left)) {
  467. // TODO: better urgent error message
  468. return Promise.reject(new Error(`Cannot use this op to ${left.type}`));
  469. }
  470. switch (unaryApp.op) {
  471. case Operators.ADD:
  472. return new StoreObject(left.type, +left.value);
  473. case Operators.SUB:
  474. return new StoreObject(left.type, -left.value);
  475. case Operators.NOT:
  476. return new StoreObject(left.type, !left.value);
  477. default:
  478. return Promise.reject(new Error('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  479. }
  480. });
  481. }
  482. evaluateInfixApp (store, infixApp) {
  483. const $left = this.evaluateExpression(store, infixApp.left);
  484. const $right = this.evaluateExpression(store, infixApp.right);
  485. return Promise.all([$left, $right]).then(values => {
  486. const left = values[0];
  487. const right = values[1];
  488. if (!canApplyInfixOp(infixApp.op, left, right)) {
  489. // TODO: better urgent error message
  490. return Promise.reject(new Error(`Cannot use this op to ${left.type} and ${right.type}`));
  491. }
  492. switch (infixApp.op) {
  493. case Operators.ADD:
  494. return new StoreObject(left.type, left.value + right.value);
  495. case Operators.SUB:
  496. return new StoreObject(left.type, left.value - right.value);
  497. case Operators.MULT:
  498. return new StoreObject(left.type, left.value * right.value);
  499. case Operators.DIV:
  500. return new StoreObject(left.type, left.value / right.value);
  501. case Operators.MOD:
  502. return new StoreObject(left.type, left.value % right.value);
  503. case Operators.GT:
  504. return new StoreObject(Types.BOOLEAN, left.value > right.value);
  505. case Operators.GE:
  506. return new StoreObject(Types.BOOLEAN, left.value >= right.value);
  507. case Operators.LT:
  508. return new StoreObject(Types.BOOLEAN, left.value < right.value);
  509. case Operators.LE:
  510. return new StoreObject(Types.BOOLEAN, left.value <= right.value);
  511. case Operators.EQ:
  512. return new StoreObject(Types.BOOLEAN, left.value === right.value);
  513. case Operators.NEQ:
  514. return new StoreObject(Types.BOOLEAN, left.value !== right.value);
  515. case Operators.AND:
  516. return new StoreObject(Types.BOOLEAN, left.value && right.value);
  517. case Operators.OR:
  518. return new StoreObject(Types.BOOLEAN, left.value || right.value);
  519. default:
  520. return Promise.reject(new Error('!!!Critical Invalid InfixApp '+ infixApp.op));
  521. }
  522. });
  523. }
  524. }