ivprogProcessor.js 39 KB

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