ivprogProcessor.js 39 KB

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