ivprogProcessor.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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. import { ProcessorErrorFactory } from './error/processorErrorFactory';
  20. import { RuntimeError } from './error/runtimeError';
  21. export class IVProgProcessor {
  22. static get LOOP_TIMEOUT () {
  23. return Config.loopTimeout;
  24. }
  25. static set LOOP_TIMEOUT (ms) {
  26. Config.setConfig({loopTimeout: ms});
  27. }
  28. static get MAIN_INTERNAL_ID () {
  29. return "$main";
  30. }
  31. constructor (ast) {
  32. this.ast = ast;
  33. this.globalStore = new Store("$global");
  34. this.stores = [this.globalStore];
  35. this.context = [Context.BASE];
  36. this.input = null;
  37. this.forceKill = false;
  38. this.loopTimers = [];
  39. this.output = null;
  40. }
  41. registerInput (input) {
  42. this.input = input;
  43. }
  44. registerOutput (output) {
  45. this.output = output;
  46. }
  47. checkContext(context) {
  48. return this.context[this.context.length - 1] === context;
  49. }
  50. ignoreSwitchCases (store) {
  51. if (store.mode === Modes.RETURN) {
  52. return true;
  53. } else if (store.mode === Modes.BREAK) {
  54. return true;
  55. } else {
  56. return false;
  57. }
  58. }
  59. interpretAST () {
  60. this.initGlobal();
  61. const mainFunc = this.findMainFunction();
  62. if(mainFunc === null) {
  63. throw ProcessorErrorFactory.main_missing();
  64. }
  65. return this.runFunction(mainFunc, [], this.globalStore);
  66. }
  67. initGlobal () {
  68. if(!this.checkContext(Context.BASE)) {
  69. throw ProcessorErrorFactory.invalid_global_var();
  70. }
  71. this.ast.global.forEach(decl => {
  72. this.executeCommand(this.globalStore, decl).then(sto => this.globalStore = sto);
  73. });
  74. }
  75. findMainFunction () {
  76. return this.ast.functions.find(v => v.isMain);
  77. }
  78. findFunction (name) {
  79. if(name.match(/^\$.+$/)) {
  80. const fun = LanguageDefinedFunction.getFunction(name);
  81. if(!!!fun) {
  82. throw ProcessorErrorFactory.not_implemented(name);
  83. }
  84. return fun;
  85. } else {
  86. const val = this.ast.functions.find( v => v.name === name);
  87. if (!!!val) {
  88. // TODO: better error message;
  89. throw ProcessorErrorFactory.function_missing(name);
  90. }
  91. return val;
  92. }
  93. }
  94. runFunction (func, actualParameters, store) {
  95. const funcName = func.isMain ? IVProgProcessor.MAIN_INTERNAL_ID : func.name;
  96. let funcStore = new Store(funcName);
  97. funcStore.extendStore(this.globalStore);
  98. let returnStoreObject = null;
  99. if(func.returnType instanceof CompoundType) {
  100. if(func.returnType.dimensions > 1) {
  101. returnStoreObject = new StoreObjectArray(func.returnType,-1,-1,[[]]);
  102. } else {
  103. returnStoreObject = new StoreObjectArray(func.returnType,-1,null,[]);
  104. }
  105. } else {
  106. returnStoreObject = new StoreObject(func.returnType, null);
  107. }
  108. funcStore.insertStore('$', returnStoreObject);
  109. const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  110. return newFuncStore$.then(sto => {
  111. this.context.push(Context.FUNCTION);
  112. this.stores.push(sto);
  113. return this.executeCommands(sto, func.variablesDeclarations)
  114. .then(stoWithVars => this.executeCommands(stoWithVars, func.commands)).then(finalSto => {
  115. this.stores.pop();
  116. this.context.pop();
  117. return finalSto;
  118. });
  119. });
  120. }
  121. associateParameters (formalList, actualList, callerStore, calleeStore) {
  122. const funcName = calleeStore.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  123. LanguageDefinedFunction.getMainFunctionName() : calleeStore.name;
  124. if (formalList.length != actualList.length) {
  125. throw ProcessorErrorFactory.invalid_parameters_size(funcName, formalList.length, actualList.length);
  126. }
  127. const promises$ = actualList.map(actualParameter => this.evaluateExpression(callerStore, actualParameter));
  128. return Promise.all(promises$).then(values => {
  129. for (let i = 0; i < values.length; i++) {
  130. const stoObj = values[i];
  131. const exp = actualList[i]
  132. const formalParameter = formalList[i];
  133. if(formalParameter.type.isCompatible(stoObj.type)) {
  134. if(formalParameter.byRef && !stoObj.inStore) {
  135. throw ProcessorErrorFactory.invalid_ref(funcName, exp.toString());
  136. }
  137. if(formalParameter.byRef) {
  138. let ref = null;
  139. if (stoObj instanceof StoreObjectArrayAddress) {
  140. ref = new StoreObjectArrayAddressRef(stoObj);
  141. } else {
  142. ref = new StoreObjectRef(stoObj.id, callerStore);
  143. }
  144. calleeStore.insertStore(formalParameter.id, ref);
  145. } else {
  146. let realValue = this.parseStoreObjectValue(stoObj);
  147. calleeStore.insertStore(formalParameter.id, realValue);
  148. }
  149. } else {
  150. throw ProcessorErrorFactory.invalid_parameter_type(funcName, exp.toString());
  151. }
  152. }
  153. return calleeStore;
  154. });
  155. }
  156. executeCommands (store, cmds) {
  157. // helper to partially apply a function, in this case executeCommand
  158. const outerRef = this;
  159. const partial = (fun, cmd) => (sto) => fun(sto, cmd);
  160. return cmds.reduce((lastCommand, next) => {
  161. const nextCommand = partial(outerRef.executeCommand.bind(outerRef), next);
  162. return lastCommand.then(nextCommand);
  163. }, Promise.resolve(store));
  164. }
  165. executeCommand (store, cmd) {
  166. if(this.forceKill) {
  167. return Promise.reject("FORCED_KILL!");
  168. } else if (store.mode === Modes.PAUSE) {
  169. return Promise.resolve(this.executeCommand(store, cmd));
  170. } else if(store.mode === Modes.RETURN) {
  171. return Promise.resolve(store);
  172. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  173. return Promise.resolve(store);
  174. }
  175. if (cmd instanceof Commands.Declaration) {
  176. return this.executeDeclaration(store, cmd);
  177. } else if (cmd instanceof Commands.ArrayIndexAssign) {
  178. return this.executeArrayIndexAssign(store, cmd);
  179. } else if (cmd instanceof Commands.Assign) {
  180. return this.executeAssign(store, cmd);
  181. } else if (cmd instanceof Commands.Break) {
  182. return this.executeBreak(store, cmd);
  183. } else if (cmd instanceof Commands.Return) {
  184. return this.executeReturn(store, cmd);
  185. } else if (cmd instanceof Commands.IfThenElse) {
  186. return this.executeIfThenElse(store, cmd);
  187. } else if (cmd instanceof Commands.While) {
  188. return this.executeWhile(store, cmd);
  189. } else if (cmd instanceof Commands.DoWhile) {
  190. return this.executeDoWhile(store, cmd);
  191. } else if (cmd instanceof Commands.For) {
  192. return this.executeFor(store, cmd);
  193. } else if (cmd instanceof Commands.Switch) {
  194. return this.executeSwitch(store, cmd);
  195. } else if (cmd instanceof Expressions.FunctionCall) {
  196. return this.executeFunctionCall(store, cmd);
  197. } else if (cmd instanceof Commands.SysCall) {
  198. return this.executeSysCall(store, cmd);
  199. } else {
  200. throw ProcessorErrorFactory.unknown_command(cmd.sourceInfo);
  201. }
  202. }
  203. executeSysCall (store, cmd) {
  204. const func = cmd.langFunc.bind(this);
  205. return func(store, cmd);
  206. }
  207. executeFunctionCall (store, cmd) {
  208. let func = null;
  209. if(cmd.isMainCall) {
  210. func = this.findMainFunction();
  211. } else {
  212. func = this.findFunction(cmd.id);
  213. }
  214. return this.runFunction(func, cmd.actualParameters, store)
  215. .then(sto => {
  216. if(!Types.VOID.isCompatible(func.returnType) && sto.mode !== Modes.RETURN) {
  217. const funcName = func.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  218. LanguageDefinedFunction.getMainFunctionName() : func.name;
  219. return Promise.reject(ProcessorErrorFactory.function_no_return(funcName));
  220. } else {
  221. return store;
  222. }
  223. })
  224. }
  225. executeSwitch (store, cmd) {
  226. this.context.push(Context.BREAKABLE);
  227. const auxCaseFun = (promise, switchExp, aCase) => {
  228. return promise.then( result => {
  229. const sto = result.sto;
  230. if (this.ignoreSwitchCases(sto)) {
  231. return Promise.resolve(result);
  232. } else if (result.wasTrue || aCase.isDefault) {
  233. const $newSto = this.executeCommands(result.sto,aCase.commands);
  234. return $newSto.then(nSto => {
  235. return Promise.resolve({wasTrue: true, sto: nSto});
  236. });
  237. } else {
  238. const $value = this.evaluateExpression(sto,
  239. new Expressions.InfixApp(Operators.EQ, switchExp, aCase.expression));
  240. return $value.then(vl => {
  241. if (vl.value) {
  242. const $newSto = this.executeCommands(result.sto,aCase.commands);
  243. return $newSto.then(nSto => {
  244. return Promise.resolve({wasTrue: true, sto: nSto});
  245. });
  246. } else {
  247. return Promise.resolve({wasTrue: false, sto: sto});
  248. }
  249. });
  250. }
  251. });
  252. }
  253. try {
  254. let breakLoop = false;
  255. let $result = Promise.resolve({wasTrue: false, sto: store});
  256. for (let index = 0; index < cmd.cases.length && !breakLoop; index++) {
  257. const aCase = cmd.cases[index];
  258. $result = auxCaseFun($result, cmd.expression, aCase);
  259. $result.then( r => breakLoop = this.ignoreSwitchCases(r.sto));
  260. }
  261. return $result.then(r => {
  262. this.context.pop();
  263. if(r.sto.mode === Modes.BREAK) {
  264. r.sto.mode = Modes.RUN;
  265. }
  266. return r.sto;
  267. });
  268. } catch (error) {
  269. return Promise.reject(error);
  270. }
  271. }
  272. executeFor (store, cmd) {
  273. try {
  274. //BEGIN for -> while rewrite
  275. const initCmd = cmd.assignment;
  276. const condition = cmd.condition;
  277. const increment = cmd.increment;
  278. const whileBlock = new Commands.CommandBlock([],
  279. cmd.commands.concat(increment));
  280. const forAsWhile = new Commands.While(condition, whileBlock);
  281. //END for -> while rewrite
  282. const newCmdList = [initCmd,forAsWhile];
  283. return this.executeCommands(store, newCmdList);
  284. } catch (error) {
  285. return Promise.reject(error);
  286. }
  287. }
  288. executeDoWhile (store, cmd) {
  289. const outerRef = this;
  290. try {
  291. outerRef.loopTimers.push(Date.now());
  292. outerRef.context.push(Context.BREAKABLE);
  293. const $newStore = outerRef.executeCommands(store, cmd.commands);
  294. return $newStore.then(sto => {
  295. if(sto.mode === Modes.BREAK) {
  296. outerRef.context.pop();
  297. sto.mode = Modes.RUN;
  298. outerRef.loopTimers.pop();
  299. return sto;
  300. }
  301. const $value = outerRef.evaluateExpression(sto, cmd.expression);
  302. return $value.then(vl => {
  303. if (!vl.type.isCompatible(Types.BOOLEAN)) {
  304. return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo));
  305. }
  306. if (vl.value) {
  307. outerRef.context.pop();
  308. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  309. const time = outerRef.loopTimers[i];
  310. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  311. outerRef.forceKill = true;
  312. return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
  313. }
  314. }
  315. return outerRef.executeCommand(sto, cmd);
  316. } else {
  317. outerRef.context.pop();
  318. outerRef.loopTimers.pop();
  319. return sto;
  320. }
  321. })
  322. })
  323. } catch (error) {
  324. return Promise.reject(error);
  325. }
  326. }
  327. executeWhile (store, cmd) {
  328. const outerRef = this;
  329. try {
  330. outerRef.loopTimers.push(Date.now());
  331. outerRef.context.push(Context.BREAKABLE);
  332. const $value = outerRef.evaluateExpression(store, cmd.expression);
  333. return $value.then(vl => {
  334. if(vl.type.isCompatible(Types.BOOLEAN)) {
  335. if(vl.value) {
  336. const $newStore = outerRef.executeCommands(store, cmd.commands);
  337. return $newStore.then(sto => {
  338. outerRef.context.pop();
  339. if (sto.mode === Modes.BREAK) {
  340. outerRef.loopTimers.pop();
  341. sto.mode = Modes.RUN;
  342. return sto;
  343. }
  344. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  345. const time = outerRef.loopTimers[i];
  346. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  347. outerRef.forceKill = true;
  348. return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
  349. }
  350. }
  351. return outerRef.executeCommand(sto, cmd);
  352. });
  353. } else {
  354. outerRef.context.pop();
  355. outerRef.loopTimers.pop();
  356. return store;
  357. }
  358. } else {
  359. return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo));
  360. }
  361. })
  362. } catch (error) {
  363. return Promise.reject(error);
  364. }
  365. }
  366. executeIfThenElse (store, cmd) {
  367. try {
  368. const $value = this.evaluateExpression(store, cmd.condition);
  369. return $value.then(vl => {
  370. if(vl.type.isCompatible(Types.BOOLEAN)) {
  371. if(vl.value) {
  372. return this.executeCommands(store, cmd.ifTrue.commands);
  373. } else if( cmd.ifFalse !== null){
  374. if(cmd.ifFalse instanceof Commands.IfThenElse) {
  375. return this.executeCommand(store, cmd.ifFalse);
  376. } else {
  377. return this.executeCommands(store, cmd.ifFalse.commands);
  378. }
  379. } else {
  380. return Promise.resolve(store);
  381. }
  382. } else {
  383. return Promise.reject(ProcessorErrorFactory.if_condition_type_full(cmd.sourceInfo));
  384. }
  385. });
  386. } catch (error) {
  387. return Promise.reject(error);
  388. }
  389. }
  390. executeReturn (store, cmd) {
  391. try {
  392. const funcType = store.applyStore('$').type;
  393. const $value = this.evaluateExpression(store, cmd.expression);
  394. const funcName = store.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  395. LanguageDefinedFunction.getMainFunctionName() : store.name;
  396. return $value.then(vl => {
  397. if(vl === null && funcType.isCompatible(Types.VOID)) {
  398. return Promise.resolve(store);
  399. }
  400. if (vl === null || !funcType.isCompatible(vl.type)) {
  401. const stringInfo = funcType.stringInfo();
  402. const info = stringInfo[0];
  403. return Promise.reject(ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
  404. } else {
  405. let realValue = this.parseStoreObjectValue(vl);
  406. store.updateStore('$', realValue);
  407. store.mode = Modes.RETURN;
  408. return Promise.resolve(store);
  409. }
  410. });
  411. } catch (error) {
  412. return Promise.reject(error);
  413. }
  414. }
  415. executeBreak (store, cmd) {
  416. if(this.checkContext(Context.BREAKABLE)) {
  417. store.mode = Modes.BREAK;
  418. return Promise.resolve(store);
  419. } else {
  420. return Promise.reject(ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo));
  421. }
  422. }
  423. executeAssign (store, cmd) {
  424. try {
  425. const $value = this.evaluateExpression(store, cmd.expression);
  426. return $value.then( vl => {
  427. let realValue = this.parseStoreObjectValue(vl);
  428. store.updateStore(cmd.id, realValue)
  429. return store;
  430. });
  431. } catch (error) {
  432. return Promise.reject(error);
  433. }
  434. }
  435. executeArrayIndexAssign (store, cmd) {
  436. const mustBeArray = store.applyStore(cmd.id);
  437. if(!(mustBeArray.type instanceof CompoundType)) {
  438. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
  439. }
  440. const line$ = this.evaluateExpression(store, cmd.line);
  441. const column$ = this.evaluateExpression(store, cmd.column);
  442. const value$ = this.evaluateExpression(store, cmd.expression);
  443. return Promise.all([line$, column$, value$]).then(results => {
  444. const lineSO = results[0];
  445. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  446. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  447. }
  448. const line = lineSO.number;
  449. const columnSO = results[1];
  450. let column = null
  451. if (columnSO !== null) {
  452. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  453. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  454. }
  455. column = columnSO.number;
  456. }
  457. const value = this.parseStoreObjectValue(results[2]);
  458. if (line >= mustBeArray.lines) {
  459. if(mustBeArray.isVector) {
  460. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  461. } else {
  462. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  463. }
  464. } else if (line < 0) {
  465. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  466. }
  467. if (column !== null && mustBeArray.columns === null ){
  468. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(cmd.id, cmd.sourceInfo));
  469. }
  470. if(column !== null ) {
  471. if (column >= mustBeArray.columns) {
  472. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(cmd.id, column,mustBeArray.columns, cmd.sourceInfo));
  473. } else if (column < 0) {
  474. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  475. }
  476. }
  477. const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
  478. if (column !== null) {
  479. if (value.type instanceof CompoundType) {
  480. const type = mustBeArray.type.innerType;
  481. const stringInfo = type.stringInfo()
  482. const info = stringInfo[0]
  483. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  484. }
  485. newArray.value[line].value[column] = value;
  486. store.updateStore(cmd.id, newArray);
  487. } else {
  488. if(mustBeArray.columns !== null && value.type instanceof CompoundType) {
  489. const type = mustBeArray.type;
  490. const stringInfo = type.stringInfo()
  491. const info = stringInfo[0]
  492. const exp = cmd.expression.toString()
  493. return Promise.reject(ProcessorErrorFactory.incompatible_types_array_full(exp,info.type, info.dim-1, cmd.sourceInfo));
  494. }
  495. newArray.value[line] = value;
  496. store.updateStore(cmd.id, newArray);
  497. }
  498. return store;
  499. });
  500. }
  501. executeDeclaration (store, cmd) {
  502. try {
  503. const $value = this.evaluateExpression(store, cmd.initial);
  504. if(cmd instanceof Commands.ArrayDeclaration) {
  505. const $lines = this.evaluateExpression(store, cmd.lines);
  506. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  507. return Promise.all([$lines, $columns, $value]).then(values => {
  508. const lineSO = values[0];
  509. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  510. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  511. }
  512. const line = lineSO.number;
  513. if(line < 0) {
  514. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  515. }
  516. const columnSO = values[1];
  517. let column = null
  518. if (columnSO !== null) {
  519. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  520. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  521. }
  522. column = columnSO.number;
  523. if(column < 0) {
  524. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  525. }
  526. }
  527. const value = values[2];
  528. const temp = new StoreObjectArray(cmd.type, line, column, null);
  529. store.insertStore(cmd.id, temp);
  530. let realValue = value;
  531. if (value !== null) {
  532. if(value instanceof StoreObjectArrayAddress) {
  533. if(value.type instanceof CompoundType) {
  534. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  535. } else {
  536. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  537. }
  538. }
  539. } else {
  540. realValue = new StoreObjectArray(cmd.type, line, column, [])
  541. if(column !== null) {
  542. for (let i = 0; i < line; i++) {
  543. realValue.value.push(new StoreObjectArray(new CompoundType(cmd.type.innerType, 1), column, null, []));
  544. }
  545. }
  546. }
  547. realValue.readOnly = cmd.isConst;
  548. store.updateStore(cmd.id, realValue);
  549. return store;
  550. });
  551. } else {
  552. const temp = new StoreObject(cmd.type, null);
  553. store.insertStore(cmd.id, temp);
  554. return $value.then(vl => {
  555. let realValue = vl;
  556. if (vl !== null) {
  557. if(vl instanceof StoreObjectArrayAddress) {
  558. if(vl.type instanceof CompoundType) {
  559. realValue = Object.assign(new StoreObjectArray(null,null,null), vl.refValue);
  560. } else {
  561. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  562. }
  563. }
  564. } else {
  565. realValue = new StoreObject(cmd.type,0);
  566. }
  567. realValue.readOnly = cmd.isConst;
  568. store.updateStore(cmd.id, realValue);
  569. return store;
  570. });
  571. }
  572. } catch (e) {
  573. return Promise.reject(e);
  574. }
  575. }
  576. evaluateExpression (store, exp) {
  577. if (exp instanceof Expressions.UnaryApp) {
  578. return this.evaluateUnaryApp(store, exp);
  579. } else if (exp instanceof Expressions.InfixApp) {
  580. return this.evaluateInfixApp(store, exp);
  581. } else if (exp instanceof Expressions.ArrayAccess) {
  582. return this.evaluateArrayAccess(store, exp);
  583. } else if (exp instanceof Expressions.VariableLiteral) {
  584. return this.evaluateVariableLiteral(store, exp);
  585. } else if (exp instanceof Expressions.IntLiteral) {
  586. return this.evaluateLiteral(store, exp);
  587. } else if (exp instanceof Expressions.RealLiteral) {
  588. return this.evaluateLiteral(store, exp);
  589. } else if (exp instanceof Expressions.BoolLiteral) {
  590. return this.evaluateLiteral(store, exp);
  591. } else if (exp instanceof Expressions.StringLiteral) {
  592. return this.evaluateLiteral(store, exp);
  593. } else if (exp instanceof Expressions.ArrayLiteral) {
  594. return this.evaluateArrayLiteral(store, exp);
  595. } else if (exp instanceof Expressions.FunctionCall) {
  596. return this.evaluateFunctionCall(store, exp);
  597. }
  598. return Promise.resolve(null);
  599. }
  600. evaluateFunctionCall (store, exp) {
  601. if(exp.isMainCall) {
  602. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
  603. }
  604. const func = this.findFunction(exp.id);
  605. if(Types.VOID.isCompatible(func.returnType)) {
  606. // TODO: better error message
  607. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(exp.id, exp.sourceInfo));
  608. }
  609. const $newStore = this.runFunction(func, exp.actualParameters, store);
  610. return $newStore.then( sto => {
  611. if(sto.mode !== Modes.RETURN) {
  612. return Promise.reject(new Error("The function that was called did not had a return command: "+exp.id));
  613. }
  614. const val = sto.applyStore('$');
  615. if (val instanceof StoreObjectArray) {
  616. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  617. } else {
  618. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  619. }
  620. });
  621. }
  622. evaluateArrayLiteral (store, exp) {
  623. const errorHelperFunction = (validationResult, exp) => {
  624. const errorCode = validationResult[0];
  625. switch(errorCode) {
  626. case StoreObjectArray.WRONG_COLUMN_NUMBER: {
  627. const columnValue = validationResult[1];
  628. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_column_full(arr.columns, columnValue, exp.sourceInfo));
  629. }
  630. case StoreObjectArray.WRONG_LINE_NUMBER: {
  631. const lineValue = validationResult[1];
  632. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_line_full(arr.lines, lineValue, exp.sourceInfo));
  633. }
  634. case StoreObjectArray.WRONG_TYPE: {
  635. let line = null;
  636. let strExp = null;
  637. if (validationResult.length > 2) {
  638. line = validationResult[1];
  639. const column = validationResult[2];
  640. strExp = exp.value[line].value[column].toString()
  641. } else {
  642. line = validationResult[1];
  643. strExp = exp.value[line].toString()
  644. }
  645. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_type_full(strExp, exp.sourceInfo)); }
  646. }
  647. };
  648. if(!exp.isVector) {
  649. const $matrix = this.evaluateMatrix(store, exp.value);
  650. return $matrix.then(list => {
  651. const type = new CompoundType(list[0].type.innerType, 2);
  652. const arr = new StoreObjectArray(type, list.length, list[0].lines, list);
  653. const checkResult = arr.isValid;
  654. if(checkResult.length == 0)
  655. return Promise.resolve(arr);
  656. else {
  657. return errorHelperFunction(checkResult, exp);
  658. }
  659. });
  660. } else {
  661. return this.evaluateVector(store, exp.value).then(list => {
  662. const type = new CompoundType(list[0].type, 1);
  663. const stoArray = new StoreObjectArray(type, list.length, null, list);
  664. const checkResult = stoArray.isValid;
  665. if(checkResult.length == 0)
  666. return Promise.resolve(stoArray);
  667. else {
  668. return errorHelperFunction(checkResult, exp);
  669. }
  670. });
  671. }
  672. }
  673. evaluateVector (store, exps) {
  674. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  675. }
  676. evaluateMatrix (store, exps) {
  677. return Promise.all(exps.map( vector => {
  678. const $vector = this.evaluateVector(store, vector.value)
  679. return $vector.then(list => {
  680. const type = new CompoundType(list[0].type, 1);
  681. return new StoreObjectArray(type, list.length, null, list)
  682. });
  683. } ));
  684. }
  685. evaluateLiteral (_, exp) {
  686. return Promise.resolve(new StoreObject(exp.type, exp.value));
  687. }
  688. evaluateVariableLiteral (store, exp) {
  689. try {
  690. const val = store.applyStore(exp.id);
  691. if (val instanceof StoreObjectArray) {
  692. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  693. } else {
  694. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  695. }
  696. } catch (error) {
  697. return Promise.reject(error);
  698. }
  699. }
  700. evaluateArrayAccess (store, exp) {
  701. const mustBeArray = store.applyStore(exp.id);
  702. if (!(mustBeArray.type instanceof CompoundType)) {
  703. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(exp.id, exp.sourceInfo));
  704. }
  705. const $line = this.evaluateExpression(store, exp.line);
  706. const $column = this.evaluateExpression(store, exp.column);
  707. return Promise.all([$line, $column]).then(values => {
  708. const lineSO = values[0];
  709. const columnSO = values[1];
  710. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  711. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  712. }
  713. const line = lineSO.number;
  714. let column = null;
  715. if(columnSO !== null) {
  716. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  717. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  718. }
  719. column = columnSO.number;
  720. }
  721. if (line >= mustBeArray.lines) {
  722. if(mustBeArray.isVector) {
  723. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  724. } else {
  725. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  726. }
  727. } else if (line < 0) {
  728. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  729. }
  730. if (column !== null && mustBeArray.columns === null ){
  731. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(exp.id, exp.sourceInfo));
  732. }
  733. if(column !== null ) {
  734. if (column >= mustBeArray.columns) {
  735. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(exp.id, column,mustBeArray.columns, exp.sourceInfo));
  736. } else if (column < 0) {
  737. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  738. }
  739. }
  740. return Promise.resolve(new StoreObjectArrayAddress(mustBeArray.id, line, column, store));
  741. });
  742. }
  743. evaluateUnaryApp (store, unaryApp) {
  744. const $left = this.evaluateExpression(store, unaryApp.left);
  745. return $left.then( left => {
  746. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  747. if (Types.UNDEFINED.isCompatible(resultType)) {
  748. const stringInfo = left.type.stringInfo();
  749. const info = stringInfo[0];
  750. return Promise.reject(ProcessorErrorFactory.invalid_unary_op_full(unaryApp.op, info.type, info.dim, unaryApp.sourceInfo));
  751. }
  752. switch (unaryApp.op.ord) {
  753. case Operators.ADD.ord:
  754. return new StoreObject(resultType, left.value);
  755. case Operators.SUB.ord:
  756. return new StoreObject(resultType, left.value.negated());
  757. case Operators.NOT.ord:
  758. return new StoreObject(resultType, !left.value);
  759. default:
  760. return Promise.reject(new RuntimeError('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  761. }
  762. });
  763. }
  764. evaluateInfixApp (store, infixApp) {
  765. const $left = this.evaluateExpression(store, infixApp.left);
  766. const $right = this.evaluateExpression(store, infixApp.right);
  767. return Promise.all([$left, $right]).then(values => {
  768. const left = values[0];
  769. const right = values[1];
  770. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  771. if (Types.UNDEFINED.isCompatible(resultType)) {
  772. const stringInfoLeft = left.type.stringInfo();
  773. const infoLeft = stringInfoLeft[0];
  774. const stringInfoRight = right.type.stringInfo();
  775. const infoRight = stringInfoRight[0];
  776. return Promise.reject(ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim,
  777. infoRight.type,infoRight.dim,infixApp.sourceInfo));
  778. }
  779. let result = null;
  780. switch (infixApp.op.ord) {
  781. case Operators.ADD.ord: {
  782. if(Types.STRING.isCompatible(left.type)) {
  783. const rightStr = convertToString(right.value, right.type);
  784. return new StoreObject(resultType, left.value + rightStr);
  785. } else if (Types.STRING.isCompatible(right.type)) {
  786. const leftStr = convertToString(left.value, left.type);
  787. return new StoreObject(resultType, leftStr + right.value);
  788. } else {
  789. return new StoreObject(resultType, left.value.plus(right.value));
  790. }
  791. }
  792. case Operators.SUB.ord:
  793. return new StoreObject(resultType, left.value.minus(right.value));
  794. case Operators.MULT.ord: {
  795. result = left.value.times(right.value);
  796. if(result.dp() > Config.decimalPlaces) {
  797. result = new Decimal(result.toFixed(Config.decimalPlaces));
  798. }
  799. return new StoreObject(resultType, result);
  800. }
  801. case Operators.DIV.ord: {
  802. if (Types.INTEGER.isCompatible(resultType))
  803. result = left.value.divToInt(right.value);
  804. else
  805. result = left.value.div(right.value);
  806. if(result.dp() > Config.decimalPlaces) {
  807. result = new Decimal(result.toFixed(Config.decimalPlaces));
  808. }
  809. return new StoreObject(resultType, result);
  810. }
  811. case Operators.MOD.ord: {
  812. result = left.value.modulo(right.value);
  813. if(result.dp() > Config.decimalPlaces) {
  814. result = new Decimal(result.toFixed(Config.decimalPlaces));
  815. }
  816. return new StoreObject(resultType, result);
  817. }
  818. case Operators.GT.ord: {
  819. if (Types.STRING.isCompatible(left.type)) {
  820. result = left.value.length > right.value.length;
  821. } else {
  822. result = left.value.gt(right.value);
  823. }
  824. return new StoreObject(resultType, result);
  825. }
  826. case Operators.GE.ord: {
  827. if (Types.STRING.isCompatible(left.type)) {
  828. result = left.value.length >= right.value.length;
  829. } else {
  830. result = left.value.gte(right.value);
  831. }
  832. return new StoreObject(resultType, result);
  833. }
  834. case Operators.LT.ord: {
  835. if (Types.STRING.isCompatible(left.type)) {
  836. result = left.value.length < right.value.length;
  837. } else {
  838. result = left.value.lt(right.value);
  839. }
  840. return new StoreObject(resultType, result);
  841. }
  842. case Operators.LE.ord: {
  843. if (Types.STRING.isCompatible(left.type)) {
  844. result = left.value.length <= right.value.length;
  845. } else {
  846. result = left.value.lte(right.value);
  847. }
  848. return new StoreObject(resultType, result);
  849. }
  850. case Operators.EQ.ord: {
  851. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  852. result = left.value.eq(right.value);
  853. } else {
  854. result = left.value === right.value;
  855. }
  856. return new StoreObject(resultType, result);
  857. }
  858. case Operators.NEQ.ord: {
  859. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  860. result = !left.value.eq(right.value);
  861. } else {
  862. result = left.value !== right.value;
  863. }
  864. return new StoreObject(resultType, result);
  865. }
  866. case Operators.AND.ord:
  867. return new StoreObject(resultType, left.value && right.value);
  868. case Operators.OR.ord:
  869. return new StoreObject(resultType, left.value || right.value);
  870. default:
  871. return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
  872. }
  873. });
  874. }
  875. parseStoreObjectValue (vl) {
  876. let realValue = vl;
  877. if(vl instanceof StoreObjectArrayAddress) {
  878. if(vl.type instanceof CompoundType) {
  879. switch(vl.type.dimensions) {
  880. case 1: {
  881. realValue = new StoreObjectArray(vl.type, vl.value);
  882. break;
  883. }
  884. default: {
  885. throw new RuntimeError("Three dimensional array address...");
  886. }
  887. }
  888. } else {
  889. realValue = new StoreObject(vl.type, vl.value);
  890. }
  891. }
  892. return realValue;
  893. }
  894. }