ivprogProcessor.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. export class IVProgProcessor {
  17. constructor (ast) {
  18. this.ast = ast;
  19. this.globalStore = new Store();
  20. this.stores = [this.globalStore];
  21. this.context = [Context.BASE];
  22. this.input = null;
  23. this.output = null;
  24. }
  25. registerInput (input) {
  26. this.input = input;
  27. }
  28. registerOutput (output) {
  29. this.output = output;
  30. }
  31. checkContext(context) {
  32. return this.context[this.context.length - 1] === context;
  33. }
  34. ignoreSwitchCases (store) {
  35. if (store.mode === Modes.RETURN) {
  36. return true;
  37. } else if (store.mode === Modes.BREAK) {
  38. return true;
  39. } else {
  40. return false;
  41. }
  42. }
  43. interpretAST () {
  44. this.initGlobal();
  45. const mainFunc = this.findMainFunction();
  46. if(mainFunc === null) {
  47. // TODO: Better error message
  48. throw new Error("Missing main funciton.");
  49. }
  50. return this.runFunction(mainFunc, [], this.globalStore);
  51. }
  52. initGlobal () {
  53. if(!this.checkContext(Context.BASE)) {
  54. throw new Error("!!!CRITICAL: Invalid call to initGlobal outside BASE context!!!");
  55. }
  56. this.ast.global.forEach(decl => {
  57. this.executeCommand(this.globalStore, decl).then(sto => this.globalStore = sto);
  58. });
  59. }
  60. findMainFunction () {
  61. return this.ast.functions.find(v => v.isMain);
  62. }
  63. findFunction (name) {
  64. if(name.match(/^\$.+$/)) {
  65. const fun = LanguageDefinedFunction.getFunction(name);
  66. if(!!!fun) {
  67. throw new Error("!!!Internal Error. Language defined function not implemented -> " + name + "!!!");
  68. }
  69. return fun;
  70. } else {
  71. const val = this.ast.functions.find( v => v.name === name);
  72. if (!!!val) {
  73. // TODO: better error message;
  74. throw new Error(`Function ${name} is not defined.`);
  75. }
  76. return val;
  77. }
  78. }
  79. runFunction (func, actualParameters, store) {
  80. let funcStore = new Store();
  81. funcStore.extendStore(this.globalStore);
  82. const returnStoreObject = new StoreObject(func.returnType, null);
  83. const funcName = func.isMain ? 'main' : func.name;
  84. const funcNameStoreObject = new StoreObject(Types.STRING, funcName, true);
  85. funcStore.insertStore('$', returnStoreObject);
  86. funcStore.insertStore('$name', funcNameStoreObject);
  87. const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  88. return newFuncStore$.then(sto => {
  89. this.context.push(Context.FUNCTION);
  90. this.stores.push(sto);
  91. return this.executeCommands(sto, func.variablesDeclarations)
  92. .then(stoWithVars => this.executeCommands(stoWithVars, func.commands)).then(finalSto => {
  93. this.stores.pop();
  94. this.context.pop();
  95. return finalSto;
  96. });
  97. });
  98. }
  99. associateParameters (formalList, actualList, callerStore, calleeStore) {
  100. if (formalList.length != actualList.length) {
  101. // TODO: Better error message
  102. throw new Error("Numbers of parameters doesn't match");
  103. }
  104. const promises$ = actualList.map(actualParameter => this.evaluateExpression(callerStore, actualParameter));
  105. return Promise.all(promises$).then(values => {
  106. for (let i = 0; i < values.length; i++) {
  107. const stoObj = values[i];
  108. const formalParameter = formalList[i];
  109. if(formalParameter.type.isCompatible(stoObj.type)) {
  110. if(formalParameter.byRef && !stoObj.inStore) {
  111. throw new Error('You must inform a variable as parameter');
  112. }
  113. if(formalParameter.byRef) {
  114. let ref = null;
  115. if (stoObj instanceof StoreObjectArrayAddress) {
  116. ref = new StoreObjectArrayAddressRef(stoObj);
  117. } else {
  118. ref = new StoreObjectRef(stoObj.id, callerStore);
  119. }
  120. calleeStore.insertStore(formalParameter.id, ref);
  121. } else {
  122. calleeStore.insertStore(formalParameter.id, stoObj);
  123. }
  124. } else {
  125. throw new Error(`Parameter ${formalParameter.id} is not compatible with the value given.`);
  126. }
  127. }
  128. return calleeStore;
  129. });
  130. }
  131. executeCommands (store, cmds) {
  132. // helper to partially apply a function, in this case executeCommand
  133. const partial = (fun, cmd) => (sto) => fun(sto, cmd);
  134. return cmds.reduce((lastCommand, next) => {
  135. const nextCommand = partial(this.executeCommand.bind(this), next);
  136. return lastCommand.then(nextCommand);
  137. }, Promise.resolve(store));
  138. }
  139. executeCommand (store, cmd) {
  140. while (store.mode === Modes.PAUSE) {
  141. continue;
  142. }
  143. if(store.mode === Modes.RETURN) {
  144. return Promise.resolve(store);
  145. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  146. return Promise.resolve(store);
  147. }
  148. if (cmd instanceof Commands.Declaration) {
  149. return this.executeDeclaration(store, cmd);
  150. } else if (cmd instanceof Commands.ArrayIndexAssign) {
  151. return this.executeArrayIndexAssign(store, cmd);
  152. } else if (cmd instanceof Commands.Assign) {
  153. return this.executeAssign(store, cmd);
  154. } else if (cmd instanceof Commands.Break) {
  155. return this.executeBreak(store, cmd);
  156. } else if (cmd instanceof Commands.Return) {
  157. return this.executeReturn(store, cmd);
  158. } else if (cmd instanceof Commands.IfThenElse) {
  159. return this.executeIfThenElse(store, cmd);
  160. } else if (cmd instanceof Commands.While) {
  161. return this.executeWhile(store, cmd);
  162. } else if (cmd instanceof Commands.DoWhile) {
  163. return this.executeDoWhile(store, cmd);
  164. } else if (cmd instanceof Commands.For) {
  165. return this.executeFor(store, cmd);
  166. } else if (cmd instanceof Commands.Switch) {
  167. return this.executeSwitch(store, cmd);
  168. } else if (cmd instanceof Commands.FunctionCall) {
  169. return this.executeFunctionCall(store, cmd);
  170. } else if (cmd instanceof Commands.SysCall) {
  171. return this.executeSysCall(store, cmd);
  172. } else {
  173. throw new Error("!!!CRITICAL A unknown command was found!!!\n" + cmd);
  174. }
  175. }
  176. executeSysCall (store, cmd) {
  177. const func = cmd.langFunc.bind(this);
  178. return func(store, cmd);
  179. }
  180. executeFunctionCall (store, cmd) {
  181. return new Promise((resolve, reject) => {
  182. const func = this.findFunction(cmd.id);
  183. this.runFunction(func, cmd.actualParameters, store)
  184. .then(_ => resolve(store))
  185. .catch(err => reject(err));
  186. });
  187. }
  188. executeSwitch (store, cmd) {
  189. this.context.push(Context.BREAKABLE);
  190. const auxCaseFun = (promise, switchExp, aCase) => {
  191. return promise.then( result => {
  192. const sto = result.sto;
  193. if (this.ignoreSwitchCases(sto)) {
  194. return Promise.resolve(result);
  195. } else if (result.wasTrue || aCase.isDefault) {
  196. const $newSto = this.executeCommands(result.sto,aCase.commands);
  197. return $newSto.then(nSto => {
  198. return Promise.resolve({wasTrue: true, sto: nSto});
  199. });
  200. } else {
  201. const $value = this.evaluateExpression(sto,
  202. new Expressions.InfixApp(Operators.EQ, switchExp, aCase.expression));
  203. return $value.then(vl => {
  204. if (vl.value) {
  205. const $newSto = this.executeCommands(result.sto,aCase.commands);
  206. return $newSto.then(nSto => {
  207. return Promise.resolve({wasTrue: true, sto: nSto});
  208. });
  209. } else {
  210. return Promise.resolve({wasTrue: false, sto: sto});
  211. }
  212. });
  213. }
  214. });
  215. }
  216. try {
  217. let breakLoop = false;
  218. let $result = Promise.resolve({wasTrue: false, sto: store});
  219. for (let index = 0; index < cmd.cases.length && !breakLoop; index++) {
  220. const aCase = cmd.cases[index];
  221. $result = auxCaseFun($result, cmd.expression, aCase);
  222. $result.then( r => breakLoop = this.ignoreSwitchCases(r.sto));
  223. }
  224. return $result.then(r => {
  225. this.context.pop();
  226. if(r.sto.mode === Modes.BREAK) {
  227. r.sto.mode = Modes.RUN;
  228. }
  229. return r.sto;
  230. });
  231. } catch (error) {
  232. return Promise.reject(error);
  233. }
  234. }
  235. executeFor (store, cmd) {
  236. try {
  237. //BEGIN for -> while rewrite
  238. const initCmd = cmd.assignment;
  239. const condition = cmd.condition;
  240. const increment = cmd.increment;
  241. const whileBlock = new Commands.CommandBlock([],
  242. cmd.commands.concat(increment));
  243. const forAsWhile = new Commands.While(condition, whileBlock);
  244. //END for -> while rewrite
  245. const newCmdList = [initCmd,forAsWhile];
  246. return this.executeCommands(store, newCmdList);
  247. } catch (error) {
  248. return Promise.reject(error);
  249. }
  250. }
  251. executeDoWhile (store, cmd) {
  252. try {
  253. this.context.push(Context.BREAKABLE);
  254. const $newStore = this.executeCommands(store, cmd.commands);
  255. return $newStore.then(sto => {
  256. if(sto.mode === Modes.BREAK) {
  257. this.context.pop();
  258. sto.mode = Modes.RUN;
  259. return Promise.resolve(sto);
  260. }
  261. const $value = this.evaluateExpression(sto, cmd.expression);
  262. return $value.then(vl => {
  263. if (!vl.type.isCompatible(Types.BOOLEAN)) {
  264. // TODO: Better error message -- Inform line and column from token!!!!
  265. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  266. return Promise.reject(new Error(`DoWhile expression must be of type boolean`));
  267. }
  268. if (vl.value) {
  269. this.context.pop();
  270. return this.executeCommand(sto, cmd);
  271. } else {
  272. this.context.pop();
  273. return Promise.resolve(sto);
  274. }
  275. });
  276. });
  277. } catch (error) {
  278. return Promise.reject(error)
  279. }
  280. }
  281. executeWhile (store, cmd) {
  282. try {
  283. this.context.push(Context.BREAKABLE);
  284. const $value = this.evaluateExpression(store, cmd.expression);
  285. return $value.then(vl => {
  286. if(vl.type.isCompatible(Types.BOOLEAN)) {
  287. if(vl.value) {
  288. const $newStore = this.executeCommands(store, cmd.commands);
  289. return $newStore.then(sto => {
  290. this.context.pop();
  291. if (sto.mode === Modes.BREAK) {
  292. sto.mode = Modes.RUN;
  293. return Promise.resolve(sto);
  294. }
  295. return this.executeCommand(sto, cmd);
  296. });
  297. } else {
  298. this.context.pop();
  299. return Promise.resolve(store);
  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(`Loop condition must be of type boolean`));
  305. }
  306. });
  307. } catch (error) {
  308. return Promise.reject(error);
  309. }
  310. }
  311. executeIfThenElse (store, cmd) {
  312. try {
  313. const $value = this.evaluateExpression(store, cmd.condition);
  314. return $value.then(vl => {
  315. if(vl.type.isCompatible(Types.BOOLEAN)) {
  316. if(vl.value) {
  317. return this.executeCommands(store, cmd.ifTrue.commands);
  318. } else if( cmd.ifFalse !== null){
  319. if(cmd.ifFalse instanceof Commands.IfThenElse) {
  320. return this.executeCommand(store, cmd.ifFalse);
  321. } else {
  322. return this.executeCommands(store, cmd.ifFalse.commands);
  323. }
  324. } else {
  325. return Promise.resolve(store);
  326. }
  327. } else {
  328. // TODO: Better error message -- Inform line and column from token!!!!
  329. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  330. return Promise.reject(new Error(`If expression must be of type boolean`));
  331. }
  332. });
  333. } catch (error) {
  334. return Promise.reject(error);
  335. }
  336. }
  337. executeReturn (store, cmd) {
  338. try {
  339. const funcType = store.applyStore('$');
  340. const $value = this.evaluateExpression(store, cmd.expression);
  341. const funcName = store.applyStore('$name');
  342. return $value.then(vl => {
  343. if(vl === null && funcType.isCompatible(Types.VOID)) {
  344. return Promise.resolve(store);
  345. }
  346. if (vl === null || !funcType.type.isCompatible(vl.type)) {
  347. // TODO: Better error message -- Inform line and column from token!!!!
  348. // THIS IF SHOULD BE IN A SEMANTIC ANALYSER
  349. return Promise.reject(new Error(`Function ${funcName.value} must return ${funcType.type} instead of ${vl.type}.`));
  350. } else {
  351. store.updateStore('$', vl);
  352. store.mode = Modes.RETURN;
  353. return Promise.resolve(store);
  354. }
  355. });
  356. } catch (error) {
  357. return Promise.reject(error);
  358. }
  359. }
  360. executeBreak (store, _) {
  361. if(this.checkContext(Context.BREAKABLE)) {
  362. store.mode = Modes.BREAK;
  363. return Promise.resolve(store);
  364. } else {
  365. return Promise.reject(new Error("!!!CRITIAL: Break command outside Loop/Switch scope!!!"));
  366. }
  367. }
  368. executeAssign (store, cmd) {
  369. try {
  370. const $value = this.evaluateExpression(store, cmd.expression);
  371. return $value.then( vl => {
  372. store.updateStore(cmd.id, vl)
  373. return store;
  374. });
  375. } catch (error) {
  376. return Promise.reject(error);
  377. }
  378. }
  379. executeArrayIndexAssign (store, cmd) {
  380. return new Promise((resolve, reject) => {
  381. const mustBeArray = store.applyStore(cmd.id);
  382. if(!(mustBeArray.type instanceof CompoundType)) {
  383. reject(new Error(cmd.id + " is not a vector/matrix"));
  384. return;
  385. }
  386. const line$ = this.evaluateExpression(store, cmd.line);
  387. const column$ = this.evaluateExpression(store, cmd.column);
  388. const value$ = this.evaluateExpression(store, cmd.expression);
  389. Promise.all([line$, column$, value$]).then(results => {
  390. const lineSO = results[0];
  391. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  392. // TODO: better error message
  393. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  394. reject(new Error("Array dimension must be of type int"));
  395. return;
  396. }
  397. const line = lineSO.number;
  398. const columnSO = results[1];
  399. let column = null
  400. if (columnSO !== null) {
  401. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  402. // TODO: better error message
  403. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  404. reject(new Error("Array dimension must be of type int"));
  405. return;
  406. }
  407. column = columnSO.number;
  408. }
  409. const value = results[2];
  410. if (line >= mustBeArray.lines) {
  411. // TODO: better error message
  412. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${lines}`));
  413. }
  414. if (column !== null && mustBeArray.columns === null ){
  415. // TODO: better error message
  416. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  417. }
  418. if(column !== null && column >= mustBeArray.columns) {
  419. // TODO: better error message
  420. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  421. }
  422. const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
  423. if (column !== null) {
  424. if (value.type instanceof CompoundType) {
  425. reject(new Error("Invalid operation. This must be a value: line "+cmd.sourceInfo.line));
  426. return;
  427. }
  428. newArray.value[line].value[column] = value;
  429. store.updateStore(cmd.id, newArray);
  430. } else {
  431. if(mustBeArray.columns !== null && value.type instanceof CompoundType) {
  432. reject(new Error("Invalid operation. This must be a vector: line "+cmd.sourceInfo.line));
  433. return;
  434. }
  435. newArray.value[line] = value;
  436. store.updateStore(cmd.id, newArray);
  437. }
  438. resolve(store);
  439. }).catch(err => reject(err));
  440. });
  441. }
  442. executeDeclaration (store, cmd) {
  443. try {
  444. const $value = this.evaluateExpression(store, cmd.initial);
  445. if(cmd instanceof Commands.ArrayDeclaration) {
  446. const $lines = this.evaluateExpression(store, cmd.lines);
  447. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  448. return Promise.all([$lines, $columns, $value]).then(values => {
  449. const lineSO = values[0];
  450. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  451. // TODO: better error message
  452. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  453. return Promise.reject(new Error("Array dimension must be of type int"));
  454. }
  455. const line = lineSO.number;
  456. const columnSO = values[1];
  457. let column = null
  458. if (columnSO !== null) {
  459. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  460. // TODO: better error message
  461. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  462. return Promise.reject(new Error("Array dimension must be of type int"));
  463. }
  464. column = columnSO.number;
  465. }
  466. const value = values[2];
  467. const temp = new StoreObjectArray(cmd.type, line, column, null, cmd.isConst);
  468. store.insertStore(cmd.id, temp);
  469. if (value !== null) {
  470. let realValue = value;
  471. if(value instanceof StoreObjectArrayAddress) {
  472. if(value.type instanceof CompoundType) {
  473. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  474. } else {
  475. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  476. }
  477. }
  478. store.updateStore(cmd.id, realValue)
  479. }
  480. return store;
  481. });
  482. } else {
  483. const temp = new StoreObject(cmd.type, null, cmd.isConst);
  484. store.insertStore(cmd.id, temp);
  485. return $value.then(vl => {
  486. if (vl !== null) {
  487. let realValue = vl;
  488. if(vl instanceof StoreObjectArrayAddress) {
  489. if(vl.type instanceof CompoundType) {
  490. realValue = Object.assign(new StoreObjectArray(null,null,null), vl.refValue);
  491. } else {
  492. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  493. }
  494. }
  495. store.updateStore(cmd.id, realValue)
  496. }
  497. return store;
  498. });
  499. }
  500. } catch (e) {
  501. return Promise.reject(e);
  502. }
  503. }
  504. evaluateExpression (store, exp) {
  505. if (exp instanceof Expressions.UnaryApp) {
  506. return this.evaluateUnaryApp(store, exp);
  507. } else if (exp instanceof Expressions.InfixApp) {
  508. return this.evaluateInfixApp(store, exp);
  509. } else if (exp instanceof Expressions.ArrayAccess) {
  510. return this.evaluateArrayAccess(store, exp);
  511. } else if (exp instanceof Expressions.VariableLiteral) {
  512. return this.evaluateVariableLiteral(store, exp);
  513. } else if (exp instanceof Expressions.IntLiteral) {
  514. return this.evaluateLiteral(store, exp);
  515. } else if (exp instanceof Expressions.RealLiteral) {
  516. return this.evaluateLiteral(store, exp);
  517. } else if (exp instanceof Expressions.BoolLiteral) {
  518. return this.evaluateLiteral(store, exp);
  519. } else if (exp instanceof Expressions.StringLiteral) {
  520. return this.evaluateLiteral(store, exp);
  521. } else if (exp instanceof Expressions.ArrayLiteral) {
  522. return this.evaluateArrayLiteral(store, exp);
  523. } else if (exp instanceof Expressions.FunctionCall) {
  524. return this.evaluateFunctionCall(store, exp);
  525. }
  526. console.log('null exp');
  527. return Promise.resolve(null);
  528. }
  529. evaluateFunctionCall (store, exp) {
  530. const func = this.findFunction(exp.id);
  531. if(Types.VOID.isCompatible(func.returnType)) {
  532. // TODO: better error message
  533. return Promise.reject(new Error(`Function ${exp.id} cannot be used inside an expression`));
  534. }
  535. const $newStore = this.runFunction(func, exp.actualParameters, store);
  536. return $newStore.then( sto => {
  537. const val = sto.applyStore('$');
  538. if (val instanceof StoreObjectArray) {
  539. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  540. } else {
  541. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  542. }
  543. });
  544. }
  545. evaluateArrayLiteral (store, exp) {
  546. if(!exp.isVector) {
  547. const $matrix = this.evaluateMatrix(store, exp.value);
  548. return $matrix.then(list => {
  549. const type = new CompoundType(list[0].type.innerType, 2);
  550. const arr = new StoreObjectArray(type, list.length, list[0].lines, list);
  551. if(arr.isValid)
  552. return Promise.resolve(arr);
  553. else
  554. return Promise.reject(new Error(`Invalid array`))
  555. });
  556. } else {
  557. return this.evaluateVector(store, exp.value).then(list => {
  558. const type = new CompoundType(list[0].type, 1);
  559. const stoArray = new StoreObjectArray(type, list.length, null, list);
  560. if(stoArray.isValid)
  561. return Promise.resolve(stoArray);
  562. else
  563. return Promise.reject(new Error(`Invalid array`))
  564. });
  565. }
  566. }
  567. evaluateVector (store, exps) {
  568. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  569. }
  570. evaluateMatrix (store, exps) {
  571. return Promise.all(exps.map( vector => {
  572. const $vector = this.evaluateVector(store, vector.value)
  573. return $vector.then(list => {
  574. const type = new CompoundType(list[0].type, 1);
  575. return new StoreObjectArray(type, list.length, null, list)
  576. });
  577. } ));
  578. }
  579. evaluateLiteral (_, exp) {
  580. return Promise.resolve(new StoreObject(exp.type, exp.value));
  581. }
  582. evaluateVariableLiteral (store, exp) {
  583. try {
  584. const val = store.applyStore(exp.id);
  585. if (val instanceof StoreObjectArray) {
  586. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  587. } else {
  588. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  589. }
  590. } catch (error) {
  591. return Promise.reject(error);
  592. }
  593. }
  594. evaluateArrayAccess (store, exp) {
  595. const mustBeArray = store.applyStore(exp.id);
  596. if (!(mustBeArray.type instanceof CompoundType)) {
  597. // TODO: better error message
  598. console.log(mustBeArray.type);
  599. return Promise.reject(new Error(`${exp.id} is not of type array`));
  600. }
  601. const $line = this.evaluateExpression(store, exp.line);
  602. const $column = this.evaluateExpression(store, exp.column);
  603. return Promise.all([$line, $column]).then(values => {
  604. const lineSO = values[0];
  605. const columnSO = values[1];
  606. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  607. // TODO: better error message
  608. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  609. return Promise.reject(new Error("Array dimension must be of type int"));
  610. }
  611. const line = lineSO.number;
  612. let column = null;
  613. if(columnSO !== null) {
  614. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  615. // TODO: better error message
  616. //SHOULD NOT BE HERE. IT MUST HAVE A SEMANTIC ANALYSIS
  617. return Promise.reject(new Error("Array dimension must be of type int"));
  618. }
  619. column = columnSO.number;
  620. }
  621. if (line >= mustBeArray.lines) {
  622. // TODO: better error message
  623. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${lines}`));
  624. }
  625. if (column !== null && mustBeArray.columns === null ){
  626. // TODO: better error message
  627. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  628. }
  629. if(column !== null && column >= mustBeArray.columns) {
  630. // TODO: better error message
  631. return Promise.reject(new Error(`${exp.id}: index out of bounds: ${column}`));
  632. }
  633. return Promise.resolve(new StoreObjectArrayAddress(mustBeArray.id, line, column, store));
  634. });
  635. }
  636. evaluateUnaryApp (store, unaryApp) {
  637. const $left = this.evaluateExpression(store, unaryApp.left);
  638. return $left.then( left => {
  639. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  640. if (Types.UNDEFINED.isCompatible(resultType)) {
  641. // TODO: better urgent error message
  642. return Promise.reject(new Error(`Cannot use this op to ${left.type}`));
  643. }
  644. switch (unaryApp.op.ord) {
  645. case Operators.ADD.ord:
  646. return new StoreObject(resultType, left.value);
  647. case Operators.SUB.ord:
  648. return new StoreObject(resultType, left.value.negated());
  649. case Operators.NOT.ord:
  650. return new StoreObject(resultType, !left.value);
  651. default:
  652. return Promise.reject(new Error('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  653. }
  654. });
  655. }
  656. evaluateInfixApp (store, infixApp) {
  657. const $left = this.evaluateExpression(store, infixApp.left);
  658. const $right = this.evaluateExpression(store, infixApp.right);
  659. return Promise.all([$left, $right]).then(values => {
  660. const left = values[0];
  661. const right = values[1];
  662. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  663. if (Types.UNDEFINED.isCompatible(resultType)) {
  664. // TODO: better urgent error message
  665. return Promise.reject(new Error(`Cannot use this ${infixApp.op} to ${left.type} and ${right.type}`));
  666. }
  667. let result = null;
  668. switch (infixApp.op.ord) {
  669. case Operators.ADD.ord:
  670. return new StoreObject(resultType, left.value.plus(right.value));
  671. case Operators.SUB.ord:
  672. return new StoreObject(resultType, left.value.minus(right.value));
  673. case Operators.MULT.ord:
  674. return new StoreObject(resultType, left.value.times(right.value));
  675. case Operators.DIV.ord: {
  676. result = left.value / right.value;
  677. if (Types.INTEGER.isCompatible(resultType))
  678. result = left.value.idiv(right.value);
  679. else
  680. result = left.value.div(right.value);
  681. return new StoreObject(resultType, result);
  682. }
  683. case Operators.MOD.ord:
  684. return new StoreObject(resultType, left.value.modulo(right.value));
  685. case Operators.GT.ord: {
  686. if (Types.STRING.isCompatible(left.type)) {
  687. result = left.value.length > right.value.length;
  688. } else {
  689. result = left.value.gt(right.value);
  690. }
  691. return new StoreObject(resultType, result);
  692. }
  693. case Operators.GE.ord: {
  694. if (Types.STRING.isCompatible(left.type)) {
  695. result = left.value.length >= right.value.length;
  696. } else {
  697. result = left.value.gte(right.value);
  698. }
  699. return new StoreObject(resultType, result);
  700. }
  701. case Operators.LT.ord: {
  702. if (Types.STRING.isCompatible(left.type)) {
  703. result = left.value.length < right.value.length;
  704. } else {
  705. result = left.value.lt(right.value);
  706. }
  707. return new StoreObject(resultType, result);
  708. }
  709. case Operators.LE.ord: {
  710. if (Types.STRING.isCompatible(left.type)) {
  711. result = left.value.length <= right.value.length;
  712. } else {
  713. result = left.value.lte(right.value);
  714. }
  715. return new StoreObject(resultType, result);
  716. }
  717. case Operators.EQ.ord: {
  718. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  719. result = left.value.eq(right.value);
  720. } else {
  721. result = left.value === right.value;
  722. }
  723. return new StoreObject(resultType, result);
  724. }
  725. case Operators.NEQ.ord: {
  726. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  727. result = !left.value.eq(right.value);
  728. } else {
  729. result = left.value !== right.value;
  730. }
  731. return new StoreObject(resultType, result);
  732. }
  733. case Operators.AND.ord:
  734. return new StoreObject(resultType, left.value && right.value);
  735. case Operators.OR.ord:
  736. return new StoreObject(resultType, left.value || right.value);
  737. default:
  738. return Promise.reject(new Error('!!!Critical Invalid InfixApp '+ infixApp.op));
  739. }
  740. });
  741. }
  742. }