1
0

ivprogProcessor.js 39 KB

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