1
0

ivprogProcessor.js 42 KB

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