ivprogProcessor.js 39 KB

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