ivprogProcessor.js 39 KB

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