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.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.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. return Promise.resolve(store);
  425. }
  426. if (vl === null || !funcType.isCompatible(vl.type)) {
  427. const stringInfo = funcType.stringInfo();
  428. const info = stringInfo[0];
  429. return Promise.reject(ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
  430. } else {
  431. let realValue = this.parseStoreObjectValue(vl);
  432. store.updateStore('$', realValue);
  433. store.mode = Modes.RETURN;
  434. return Promise.resolve(store);
  435. }
  436. });
  437. } catch (error) {
  438. return Promise.reject(error);
  439. }
  440. }
  441. executeBreak (store, cmd) {
  442. if(this.checkContext(Context.BREAKABLE)) {
  443. store.mode = Modes.BREAK;
  444. return Promise.resolve(store);
  445. } else {
  446. return Promise.reject(ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo));
  447. }
  448. }
  449. executeAssign (store, cmd) {
  450. try {
  451. const inStore = store.applyStore(cmd.id);
  452. const $value = this.evaluateExpression(store, cmd.expression);
  453. return $value.then( vl => {
  454. let realValue = this.parseStoreObjectValue(vl);
  455. if(!inStore.type.isCompatible(realValue.type)) {
  456. if(Config.enable_type_casting && Store.canImplicitTypeCast(inStore.type, vl.type)) {
  457. realValue = Store.doImplicitCasting(inStore.type, realValue);
  458. } else {
  459. const stringInfo = inStore.type.stringInfo()
  460. const info = stringInfo[0]
  461. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  462. }
  463. }
  464. store.updateStore(cmd.id, realValue)
  465. return store;
  466. });
  467. } catch (error) {
  468. return Promise.reject(error);
  469. }
  470. }
  471. executeArrayIndexAssign (store, cmd) {
  472. const mustBeArray = store.applyStore(cmd.id);
  473. if(!(mustBeArray.type instanceof CompoundType)) {
  474. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
  475. }
  476. const line$ = this.evaluateExpression(store, cmd.line);
  477. const column$ = this.evaluateExpression(store, cmd.column);
  478. const value$ = this.evaluateExpression(store, cmd.expression);
  479. return Promise.all([line$, column$, value$]).then(results => {
  480. const lineSO = results[0];
  481. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  482. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  483. }
  484. const line = lineSO.number;
  485. const columnSO = results[1];
  486. let column = null
  487. if (columnSO !== null) {
  488. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  489. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  490. }
  491. column = columnSO.number;
  492. }
  493. const value = this.parseStoreObjectValue(results[2]);
  494. if (line >= mustBeArray.lines) {
  495. if(mustBeArray.isVector) {
  496. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  497. } else {
  498. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  499. }
  500. } else if (line < 0) {
  501. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  502. }
  503. if (column !== null && mustBeArray.columns === null ){
  504. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(cmd.id, cmd.sourceInfo));
  505. }
  506. if(column !== null ) {
  507. if (column >= mustBeArray.columns) {
  508. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(cmd.id, column,mustBeArray.columns, cmd.sourceInfo));
  509. } else if (column < 0) {
  510. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  511. }
  512. }
  513. const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
  514. if (column !== null) {
  515. if (value.type instanceof CompoundType || !newArray.type.canAccept(value.type)) {
  516. const type = mustBeArray.type.innerType;
  517. const stringInfo = type.stringInfo()
  518. const info = stringInfo[0]
  519. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  520. }
  521. newArray.value[line].value[column] = value;
  522. store.updateStore(cmd.id, newArray);
  523. } else {
  524. if((mustBeArray.columns !== null && value.type instanceof CompoundType) || !newArray.type.canAccept(value.type)) {
  525. const type = mustBeArray.type;
  526. const stringInfo = type.stringInfo()
  527. const info = stringInfo[0]
  528. const exp = cmd.expression.toString()
  529. return Promise.reject(ProcessorErrorFactory.incompatible_types_array_full(exp,info.type, info.dim-1, cmd.sourceInfo));
  530. }
  531. newArray.value[line] = value;
  532. store.updateStore(cmd.id, newArray);
  533. }
  534. return store;
  535. });
  536. }
  537. executeDeclaration (store, cmd) {
  538. try {
  539. const $value = this.evaluateExpression(store, cmd.initial);
  540. if(cmd instanceof Commands.ArrayDeclaration) {
  541. const $lines = this.evaluateExpression(store, cmd.lines);
  542. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  543. return Promise.all([$lines, $columns, $value]).then(values => {
  544. const lineSO = values[0];
  545. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  546. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  547. }
  548. const line = lineSO.number;
  549. if(line < 0) {
  550. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  551. }
  552. const columnSO = values[1];
  553. let column = null
  554. if (columnSO !== null) {
  555. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  556. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  557. }
  558. column = columnSO.number;
  559. if(column < 0) {
  560. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  561. }
  562. }
  563. const value = values[2];
  564. const temp = new StoreObjectArray(cmd.type, line, column, null);
  565. store.insertStore(cmd.id, temp);
  566. let realValue = value;
  567. if (value !== null) {
  568. if(value instanceof StoreObjectArrayAddress) {
  569. if(value.type instanceof CompoundType) {
  570. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  571. } else {
  572. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  573. }
  574. }
  575. } else {
  576. realValue = new StoreObjectArray(cmd.type, line, column, [])
  577. if(column !== null) {
  578. for (let i = 0; i < line; i++) {
  579. realValue.value.push(new StoreObjectArray(new CompoundType(cmd.type.innerType, 1), column, null, []));
  580. }
  581. }
  582. }
  583. realValue.readOnly = cmd.isConst;
  584. store.updateStore(cmd.id, realValue);
  585. return store;
  586. });
  587. } else {
  588. const temp = new StoreObject(cmd.type, null);
  589. store.insertStore(cmd.id, temp);
  590. return $value.then(vl => {
  591. let realValue = vl;
  592. if (vl !== null) {
  593. if(!vl.type.isCompatible(cmd.type)) {
  594. if(Config.enable_type_casting && Store.canImplicitTypeCast(cmd.type, vl.type)) {
  595. realValue = Store.doImplicitCasting(cmd.type, realValue);
  596. } else {
  597. const stringInfo = typeInfo.type.stringInfo();
  598. const info = stringInfo[0];
  599. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  600. }
  601. }
  602. if(vl instanceof StoreObjectArrayAddress) {
  603. if(vl.type instanceof CompoundType) {
  604. return Promise.reject(new Error("!!!Critical Error: Compatibility check failed, a Type accepts a CompoundType"))
  605. } else {
  606. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  607. }
  608. }
  609. } else {
  610. realValue = new StoreObject(cmd.type, 0);
  611. }
  612. realValue.readOnly = cmd.isConst;
  613. store.updateStore(cmd.id, realValue);
  614. return store;
  615. });
  616. }
  617. } catch (e) {
  618. return Promise.reject(e);
  619. }
  620. }
  621. evaluateExpression (store, exp) {
  622. if (exp instanceof Expressions.UnaryApp) {
  623. return this.evaluateUnaryApp(store, exp);
  624. } else if (exp instanceof Expressions.InfixApp) {
  625. return this.evaluateInfixApp(store, exp);
  626. } else if (exp instanceof Expressions.ArrayAccess) {
  627. return this.evaluateArrayAccess(store, exp);
  628. } else if (exp instanceof Expressions.VariableLiteral) {
  629. return this.evaluateVariableLiteral(store, exp);
  630. } else if (exp instanceof Expressions.IntLiteral) {
  631. return this.evaluateLiteral(store, exp);
  632. } else if (exp instanceof Expressions.RealLiteral) {
  633. return this.evaluateLiteral(store, exp);
  634. } else if (exp instanceof Expressions.BoolLiteral) {
  635. return this.evaluateLiteral(store, exp);
  636. } else if (exp instanceof Expressions.StringLiteral) {
  637. return this.evaluateLiteral(store, exp);
  638. } else if (exp instanceof Expressions.ArrayLiteral) {
  639. return this.evaluateArrayLiteral(store, exp);
  640. } else if (exp instanceof Expressions.FunctionCall) {
  641. return this.evaluateFunctionCall(store, exp);
  642. }
  643. return Promise.resolve(null);
  644. }
  645. evaluateFunctionCall (store, exp) {
  646. if(exp.isMainCall) {
  647. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
  648. }
  649. const func = this.findFunction(exp.id);
  650. if(Types.VOID.isCompatible(func.returnType)) {
  651. // TODO: better error message
  652. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(exp.id, exp.sourceInfo));
  653. }
  654. const $newStore = this.runFunction(func, exp.actualParameters, store);
  655. return $newStore.then( sto => {
  656. if(sto.mode !== Modes.RETURN) {
  657. return Promise.reject(new Error("The function that was called did not had a return command: "+exp.id));
  658. }
  659. const val = sto.applyStore('$');
  660. if (val instanceof StoreObjectArray) {
  661. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  662. } else {
  663. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  664. }
  665. });
  666. }
  667. evaluateArrayLiteral (store, exp) {
  668. const errorHelperFunction = (validationResult, exp) => {
  669. const errorCode = validationResult[0];
  670. switch(errorCode) {
  671. case StoreObjectArray.WRONG_COLUMN_NUMBER: {
  672. const columnValue = validationResult[1];
  673. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_column_full(arr.columns, columnValue, exp.sourceInfo));
  674. }
  675. case StoreObjectArray.WRONG_LINE_NUMBER: {
  676. const lineValue = validationResult[1];
  677. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_line_full(arr.lines, lineValue, exp.sourceInfo));
  678. }
  679. case StoreObjectArray.WRONG_TYPE: {
  680. let line = null;
  681. let strExp = null;
  682. if (validationResult.length > 2) {
  683. line = validationResult[1];
  684. const column = validationResult[2];
  685. strExp = exp.value[line].value[column].toString()
  686. } else {
  687. line = validationResult[1];
  688. strExp = exp.value[line].toString()
  689. }
  690. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_type_full(strExp, exp.sourceInfo)); }
  691. }
  692. };
  693. if(!exp.isVector) {
  694. const $matrix = this.evaluateMatrix(store, exp.value);
  695. return $matrix.then(list => {
  696. const type = new CompoundType(list[0].type.innerType, 2);
  697. const arr = new StoreObjectArray(type, list.length, list[0].lines, list);
  698. const checkResult = arr.isValid;
  699. if(checkResult.length == 0)
  700. return Promise.resolve(arr);
  701. else {
  702. return errorHelperFunction(checkResult, exp);
  703. }
  704. });
  705. } else {
  706. return this.evaluateVector(store, exp.value).then(list => {
  707. const type = new CompoundType(list[0].type, 1);
  708. const stoArray = new StoreObjectArray(type, list.length, null, list);
  709. const checkResult = stoArray.isValid;
  710. if(checkResult.length == 0)
  711. return Promise.resolve(stoArray);
  712. else {
  713. return errorHelperFunction(checkResult, exp);
  714. }
  715. });
  716. }
  717. }
  718. evaluateVector (store, exps) {
  719. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  720. }
  721. evaluateMatrix (store, exps) {
  722. return Promise.all(exps.map( vector => {
  723. const $vector = this.evaluateVector(store, vector.value)
  724. return $vector.then(list => {
  725. const type = new CompoundType(list[0].type, 1);
  726. return new StoreObjectArray(type, list.length, null, list)
  727. });
  728. } ));
  729. }
  730. evaluateLiteral (_, exp) {
  731. return Promise.resolve(new StoreObject(exp.type, exp.value));
  732. }
  733. evaluateVariableLiteral (store, exp) {
  734. try {
  735. const val = store.applyStore(exp.id);
  736. if (val instanceof StoreObjectArray) {
  737. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  738. } else {
  739. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  740. }
  741. } catch (error) {
  742. return Promise.reject(error);
  743. }
  744. }
  745. evaluateArrayAccess (store, exp) {
  746. const mustBeArray = store.applyStore(exp.id);
  747. if (!(mustBeArray.type instanceof CompoundType)) {
  748. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(exp.id, exp.sourceInfo));
  749. }
  750. const $line = this.evaluateExpression(store, exp.line);
  751. const $column = this.evaluateExpression(store, exp.column);
  752. return Promise.all([$line, $column]).then(values => {
  753. const lineSO = values[0];
  754. const columnSO = values[1];
  755. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  756. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  757. }
  758. const line = lineSO.number;
  759. let column = null;
  760. if(columnSO !== null) {
  761. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  762. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  763. }
  764. column = columnSO.number;
  765. }
  766. if (line >= mustBeArray.lines) {
  767. if(mustBeArray.isVector) {
  768. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  769. } else {
  770. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  771. }
  772. } else if (line < 0) {
  773. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  774. }
  775. if (column !== null && mustBeArray.columns === null ){
  776. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(exp.id, exp.sourceInfo));
  777. }
  778. if(column !== null ) {
  779. if (column >= mustBeArray.columns) {
  780. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(exp.id, column,mustBeArray.columns, exp.sourceInfo));
  781. } else if (column < 0) {
  782. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  783. }
  784. }
  785. return Promise.resolve(new StoreObjectArrayAddress(mustBeArray.id, line, column, store));
  786. });
  787. }
  788. evaluateUnaryApp (store, unaryApp) {
  789. const $left = this.evaluateExpression(store, unaryApp.left);
  790. return $left.then( left => {
  791. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  792. if (Types.UNDEFINED.isCompatible(resultType)) {
  793. const stringInfo = left.type.stringInfo();
  794. const info = stringInfo[0];
  795. return Promise.reject(ProcessorErrorFactory.invalid_unary_op_full(unaryApp.op, info.type, info.dim, unaryApp.sourceInfo));
  796. }
  797. switch (unaryApp.op.ord) {
  798. case Operators.ADD.ord:
  799. return new StoreObject(resultType, left.value);
  800. case Operators.SUB.ord:
  801. return new StoreObject(resultType, left.value.negated());
  802. case Operators.NOT.ord:
  803. return new StoreObject(resultType, !left.value);
  804. default:
  805. return Promise.reject(new RuntimeError('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  806. }
  807. });
  808. }
  809. evaluateInfixApp (store, infixApp) {
  810. const $left = this.evaluateExpression(store, infixApp.left);
  811. const $right = this.evaluateExpression(store, infixApp.right);
  812. return Promise.all([$left, $right]).then(values => {
  813. let shouldImplicitCast = false;
  814. const left = values[0];
  815. const right = values[1];
  816. let resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  817. if (Types.UNDEFINED.isCompatible(resultType)) {
  818. if (Config.enable_type_casting && Store.canImplicitTypeCast(left.type, right.type)) {
  819. shouldImplicitCast = true;
  820. } else {
  821. const stringInfoLeft = left.type.stringInfo();
  822. const infoLeft = stringInfoLeft[0];
  823. const stringInfoRight = right.type.stringInfo();
  824. const infoRight = stringInfoRight[0];
  825. return Promise.reject(ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim,
  826. infoRight.type,infoRight.dim,infixApp.sourceInfo));
  827. }
  828. }
  829. let result = null;
  830. switch (infixApp.op.ord) {
  831. case Operators.ADD.ord: {
  832. if(Types.STRING.isCompatible(left.type)) {
  833. const rightStr = convertToString(right.value, right.type);
  834. return new StoreObject(resultType, left.value + rightStr);
  835. } else if (Types.STRING.isCompatible(right.type)) {
  836. const leftStr = convertToString(left.value, left.type);
  837. return new StoreObject(resultType, leftStr + right.value);
  838. } else {
  839. return new StoreObject(resultType, left.value.plus(right.value));
  840. }
  841. }
  842. case Operators.SUB.ord:
  843. return new StoreObject(resultType, left.value.minus(right.value));
  844. case Operators.MULT.ord: {
  845. result = left.value.times(right.value);
  846. if(result.dp() > Config.decimalPlaces) {
  847. result = new Decimal(result.toFixed(Config.decimalPlaces));
  848. }
  849. return new StoreObject(resultType, result);
  850. }
  851. case Operators.DIV.ord: {
  852. if (Types.INTEGER.isCompatible(resultType))
  853. result = left.value.divToInt(right.value);
  854. else
  855. result = left.value.div(right.value);
  856. if(result.dp() > Config.decimalPlaces) {
  857. result = new Decimal(result.toFixed(Config.decimalPlaces));
  858. }
  859. return new StoreObject(resultType, result);
  860. }
  861. case Operators.MOD.ord: {
  862. let leftValue = left.value;
  863. let rightValue = right.value;
  864. if(shouldImplicitCast) {
  865. resultType = Types.INTEGER;
  866. leftValue = leftValue.trunc();
  867. rightValue = rightValue.trunc();
  868. }
  869. result = leftValue.modulo(rightValue);
  870. if(result.dp() > Config.decimalPlaces) {
  871. result = new Decimal(result.toFixed(Config.decimalPlaces));
  872. }
  873. return new StoreObject(resultType, result);
  874. }
  875. case Operators.GT.ord: {
  876. let leftValue = left.value;
  877. let rightValue = right.value;
  878. if (Types.STRING.isCompatible(left.type)) {
  879. result = left.value.length > right.value.length;
  880. } else {
  881. if (shouldImplicitCast) {
  882. resultType = Types.BOOLEAN;
  883. leftValue = leftValue.trunc();
  884. rightValue = rightValue.trunc();
  885. }
  886. result = leftValue.gt(rightValue);
  887. }
  888. return new StoreObject(resultType, result);
  889. }
  890. case Operators.GE.ord: {
  891. let leftValue = left.value;
  892. let rightValue = right.value;
  893. if (Types.STRING.isCompatible(left.type)) {
  894. result = left.value.length >= right.value.length;
  895. } else {
  896. if (shouldImplicitCast) {
  897. resultType = Types.BOOLEAN;
  898. leftValue = leftValue.trunc();
  899. rightValue = rightValue.trunc();
  900. }
  901. result = leftValue.gte(rightValue);
  902. }
  903. return new StoreObject(resultType, result);
  904. }
  905. case Operators.LT.ord: {
  906. let leftValue = left.value;
  907. let rightValue = right.value;
  908. if (Types.STRING.isCompatible(left.type)) {
  909. result = left.value.length < right.value.length;
  910. } else {
  911. if (shouldImplicitCast) {
  912. resultType = Types.BOOLEAN;
  913. leftValue = leftValue.trunc();
  914. rightValue = rightValue.trunc();
  915. }
  916. result = leftValue.lt(rightValue);
  917. }
  918. return new StoreObject(resultType, result);
  919. }
  920. case Operators.LE.ord: {
  921. let leftValue = left.value;
  922. let rightValue = right.value;
  923. if (Types.STRING.isCompatible(left.type)) {
  924. result = left.value.length <= right.value.length;
  925. } else {
  926. if (shouldImplicitCast) {
  927. resultType = Types.BOOLEAN;
  928. leftValue = leftValue.trunc();
  929. rightValue = rightValue.trunc();
  930. }
  931. result = leftValue.lte(rightValue);
  932. }
  933. return new StoreObject(resultType, result);
  934. }
  935. case Operators.EQ.ord: {
  936. let leftValue = left.value;
  937. let rightValue = right.value;
  938. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  939. if (shouldImplicitCast) {
  940. resultType = Types.BOOLEAN;
  941. leftValue = leftValue.trunc();
  942. rightValue = rightValue.trunc();
  943. }
  944. result = leftValue.eq(rightValue);
  945. } else {
  946. result = left.value === right.value;
  947. }
  948. return new StoreObject(resultType, result);
  949. }
  950. case Operators.NEQ.ord: {
  951. let leftValue = left.value;
  952. let rightValue = right.value;
  953. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  954. if (shouldImplicitCast) {
  955. resultType = Types.BOOLEAN;
  956. leftValue = leftValue.trunc();
  957. rightValue = rightValue.trunc();
  958. }
  959. result = !leftValue.eq(rightValue);
  960. } else {
  961. result = left.value !== right.value;
  962. }
  963. return new StoreObject(resultType, result);
  964. }
  965. case Operators.AND.ord:
  966. return new StoreObject(resultType, left.value && right.value);
  967. case Operators.OR.ord:
  968. return new StoreObject(resultType, left.value || right.value);
  969. default:
  970. return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
  971. }
  972. });
  973. }
  974. parseStoreObjectValue (vl) {
  975. let realValue = vl;
  976. if(vl instanceof StoreObjectArrayAddress) {
  977. if(vl.type instanceof CompoundType) {
  978. switch(vl.type.dimensions) {
  979. case 1: {
  980. realValue = new StoreObjectArray(vl.type, vl.value);
  981. break;
  982. }
  983. default: {
  984. throw new RuntimeError("Three dimensional array address...");
  985. }
  986. }
  987. } else {
  988. realValue = new StoreObject(vl.type, vl.value);
  989. }
  990. }
  991. return realValue;
  992. }
  993. }