ivprogProcessor.js 39 KB

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