1
0

ivprogProcessor.js 42 KB

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