ivprogProcessor.js 39 KB

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