ivprogProcessor.js 41 KB

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