ivprogProcessor.js 39 KB

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