ivprogProcessor.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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. return Promise.reject(ProcessorErrorFactory.main_missing())
  83. }
  84. return this.runFunction(mainFunc, [], this.globalStore);
  85. });
  86. }
  87. initGlobal () {
  88. if(!this.checkContext(Context.BASE)) {
  89. return Promise.reject(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. return Promise.reject(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. return Promise.reject(ProcessorErrorFactory.invalid_parameter_type(funcName, exp.toString()))
  148. }
  149. }
  150. if(formalParameter.byRef && !sto_value.inStore()) {
  151. return Promise.reject(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. return Promise.reject(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. return Promise.reject(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. const exp_type_string_info = vl.type.stringInfo();
  459. const exp_type_info = exp_type_string_info[0];
  460. const exp = cmd.expression.toString();
  461. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, exp_type_info.type, exp_type_info.dim, exp, cmd.sourceInfo));
  462. }
  463. }
  464. if(inStore instanceof ArrayStoreValue) {
  465. const columns = realValue.columns == null ? 0 : realValue.columns;
  466. if(inStore.lines !== realValue.lines || inStore.columns !== columns){
  467. const exp = cmd.expression.toString();
  468. if(inStore.isVector()) {
  469. return Promise.reject(ProcessorErrorFactory.invalid_vector_assignment_full(cmd.id, inStore.lines, exp, realValue.lines, cmd.sourceInfo));
  470. } else {
  471. return Promise.reject(ProcessorErrorFactory.invalid_matrix_assignment_full(cmd.id, inStore.lines, inStore.columns, exp, realValue.lines, realValue.columns, cmd.sourceInfo));
  472. }
  473. }
  474. }
  475. store.updateStore(cmd.id, realValue)
  476. return store;
  477. });
  478. } catch (error) {
  479. return Promise.reject(error);
  480. }
  481. }
  482. executeArrayIndexAssign (store, cmd) {
  483. const mustBeArray = store.applyStore(cmd.id);
  484. let used_dims = 0;
  485. if(mustBeArray.isConst) {
  486. return Promise.reject(ProcessorErrorFactory.invalid_const_assignment_full(cmd.id, cmd.sourceInfo))
  487. }
  488. if(!(mustBeArray.type instanceof ArrayType)) {
  489. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
  490. }
  491. const line$ = this.evaluateExpression(store, cmd.line);
  492. const column$ = this.evaluateExpression(store, cmd.column);
  493. const value$ = this.evaluateExpression(store, cmd.expression);
  494. return Promise.all([line$, column$, value$]).then(([line_sv, column_sv, value]) => {
  495. if(!Types.INTEGER.isCompatible(line_sv.type)) {
  496. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  497. }
  498. const line = line_sv.get().toNumber();
  499. used_dims += 1;
  500. let column = undefined;
  501. if (column_sv != null) {
  502. if(!Types.INTEGER.isCompatible(column_sv.type)) {
  503. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  504. }
  505. column = column_sv.get().toNumber();
  506. used_dims += 1;
  507. }
  508. let actualValue = value;
  509. if (line >= mustBeArray.lines) {
  510. if(mustBeArray.isVector) {
  511. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  512. } else {
  513. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  514. }
  515. } else if (line < 0) {
  516. return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo))
  517. }
  518. if (column != null && mustBeArray.columns === 0 ){
  519. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(cmd.id, cmd.sourceInfo));
  520. }
  521. if(column != null ) {
  522. if (column >= mustBeArray.columns) {
  523. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(cmd.id, column,mustBeArray.columns, cmd.sourceInfo));
  524. } else if (column < 0) {
  525. return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo))
  526. }
  527. }
  528. if (!mustBeArray.type.canAccept(value.type, used_dims)) {
  529. if(!Config.enable_type_casting || !Store.canImplicitTypeCast(mustBeArray.type.innerType, value.type)) {
  530. const type = mustBeArray.type.innerType;
  531. const stringInfo = type.stringInfo();
  532. const info = stringInfo[0];
  533. const exp_type_string_info = value.type.stringInfo();
  534. const exp_type_info = exp_type_string_info[0];
  535. const exp = cmd.expression.toString();
  536. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, exp_type_info.type, exp_type_info.dim, exp, cmd.sourceInfo));
  537. }
  538. actualValue = Store.doImplicitCasting(mustBeArray.type.innerType, value);
  539. }
  540. const current_value = mustBeArray.getAt(line, column);
  541. if(current_value instanceof ArrayStoreValue) {
  542. if(current_value.lines !== actualValue.lines || current_value.columns !== actualValue.columns){
  543. const exp = cmd.expression.toString();
  544. return Promise.reject(ProcessorErrorFactory.invalid_matrix_index_assign_full(cmd.id, line, current_value.lines, exp, actualValue.lines, cmd.sourceInfo))
  545. }
  546. }
  547. // mustBeArray.setAt(actualValue, line, column);
  548. // store.updateStore(cmd.id, mustBeArray);
  549. return store.updateStoreArray(cmd.id, actualValue, line, column);
  550. });
  551. }
  552. /**
  553. *
  554. * @param {Store} store
  555. * @param {Commands.Declaration} cmd
  556. */
  557. executeDeclaration (store, cmd) {
  558. try {
  559. let $value = Promise.resolve(null);
  560. if(cmd instanceof Commands.ArrayDeclaration) {
  561. return this.executeArrayDeclaration(store, cmd);
  562. } else {
  563. if(cmd.initial !== null) {
  564. $value = this.evaluateExpression(store, cmd.initial);
  565. }
  566. return $value.then(vl => {
  567. let realValue = vl;
  568. let temp = null;
  569. if (vl !== null) {
  570. if(!vl.type.isCompatible(cmd.type)) {
  571. if(Config.enable_type_casting && Store.canImplicitTypeCast(cmd.type, vl.type)) {
  572. realValue = Store.doImplicitCasting(cmd.type, realValue);
  573. } else {
  574. const stringInfo = vl.type.stringInfo();
  575. const info = stringInfo[0];
  576. const exp_type_string_info = vl.type.stringInfo();
  577. const exp_type_info = exp_type_string_info[0];
  578. const exp = cmd.expression.toString();
  579. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, exp_type_info.type, exp_type_info.dim, exp, cmd.sourceInfo));
  580. }
  581. }
  582. temp = new StoreValue(cmd.type, realValue.get(), null, cmd.isConst);
  583. } else {
  584. temp = new StoreValue(cmd.type, null, null, cmd.isConst);
  585. }
  586. store.insertStore(cmd.id, temp);
  587. return store;
  588. });
  589. }
  590. } catch (e) {
  591. return Promise.reject(e);
  592. }
  593. }
  594. /**
  595. *
  596. * @param {Store} store
  597. * @param {Commands.ArrayDeclaration} cmd
  598. */
  599. executeArrayDeclaration (store, cmd) {
  600. const $lines = this.evaluateExpression(store, cmd.lines);
  601. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  602. return Promise.all([$lines, $columns]).then(([line_sv, column_sv]) => {
  603. if(!Types.INTEGER.isCompatible(line_sv.type)) {
  604. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  605. }
  606. const line = line_sv.get().toNumber();
  607. if(line < 0) {
  608. return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo));
  609. }
  610. let column = null
  611. if (column_sv !== null) {
  612. if(!Types.INTEGER.isCompatible(column_sv.type)) {
  613. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  614. }
  615. column = column_sv.get().toNumber();
  616. if(column < 0) {
  617. return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo));
  618. }
  619. }
  620. let $value = Promise.resolve(null);
  621. if(cmd.initial !== null) {
  622. // array can only be initialized by a literal....
  623. $value = this.evaluateArrayLiteral(store, cmd.initial, cmd.type, line, column);
  624. }
  625. return $value.then(vector_list => {
  626. let temp = null;
  627. if (vector_list !== null) {
  628. temp = new ArrayStoreValue(cmd.type, vector_list, line, column, null, cmd.isConst);
  629. } else {
  630. temp = new ArrayStoreValue(cmd.type, [], line, column, null, cmd.isConst);
  631. }
  632. store.insertStore(cmd.id, temp);
  633. return store;
  634. })
  635. });
  636. }
  637. evaluateExpression (store, exp) {
  638. if (exp instanceof Expressions.UnaryApp) {
  639. return this.evaluateUnaryApp(store, exp);
  640. } else if (exp instanceof Expressions.InfixApp) {
  641. return this.evaluateInfixApp(store, exp);
  642. } else if (exp instanceof Expressions.ArrayAccess) {
  643. return this.evaluateArrayAccess(store, exp);
  644. } else if (exp instanceof Expressions.VariableLiteral) {
  645. return this.evaluateVariableLiteral(store, exp);
  646. } else if (exp instanceof Expressions.IntLiteral) {
  647. return this.evaluateLiteral(store, exp);
  648. } else if (exp instanceof Expressions.RealLiteral) {
  649. return this.evaluateLiteral(store, exp);
  650. } else if (exp instanceof Expressions.BoolLiteral) {
  651. return this.evaluateLiteral(store, exp);
  652. } else if (exp instanceof Expressions.StringLiteral) {
  653. return this.evaluateLiteral(store, exp);
  654. } else if (exp instanceof Expressions.ArrayLiteral) {
  655. return Promise.reject(new Error("Internal Error: The system should not eval an array literal."))
  656. } else if (exp instanceof Expressions.FunctionCall) {
  657. return this.evaluateFunctionCall(store, exp);
  658. }
  659. return Promise.resolve(null);
  660. }
  661. evaluateFunctionCall (store, exp) {
  662. if(exp.isMainCall) {
  663. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
  664. }
  665. const func = this.findFunction(exp.id);
  666. if(Types.VOID.isCompatible(func.returnType)) {
  667. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(exp.id, exp.sourceInfo));
  668. }
  669. const $newStore = this.runFunction(func, exp.actualParameters, store);
  670. return $newStore.then( sto => {
  671. if(sto.mode !== Modes.RETURN) {
  672. return Promise.reject(new Error("!!!Internal error: the function that was called did not have a return command or did not set the store mode properly -> "+exp.id));
  673. }
  674. const val = sto.applyStore('$');
  675. sto.destroy();
  676. return Promise.resolve(val);
  677. });
  678. }
  679. /**
  680. *
  681. * @param {Store} store
  682. * @param {Expressions.ArrayLiteral} exp
  683. * @param {ArrayType} type
  684. */
  685. evaluateArrayLiteral (store, exp, type, lines, columns) {
  686. if(!exp.isVector) {
  687. if(columns == null) {
  688. return Promise.reject(new Error("This should never happen: Vector cannot be initialized by a matrix"));
  689. }
  690. const $matrix = this.evaluateMatrix(store, exp, type, lines, columns);
  691. return Promise.all($matrix).then(vectorList => {
  692. const values = vectorList.reduce((prev, next) => prev.concat(next), []);
  693. return Promise.resolve(values);
  694. });
  695. } else {
  696. if(columns != null) {
  697. return Promise.reject(new Error("This should never happen: Matrix cannot be initialized by a vector"));
  698. }
  699. return this.evaluateVector(store, exp, type, lines).then(list => {
  700. return Promise.resolve(list);
  701. });
  702. }
  703. }
  704. /**
  705. * Evalautes a list of literals and expression composing the vector
  706. * @param {Store} store
  707. * @param {Expressions.ArrayLiteral} exps
  708. * @param {ArrayType} type
  709. * @param {number} n_elements
  710. * @returns {Promise<StoreValue[]>} store object list
  711. */
  712. evaluateVector (store, exps, type, n_elements) {
  713. const values = exps.value;
  714. if(n_elements !== values.length) {
  715. return Promise.reject(ProcessorErrorFactory.invalid_number_elements_vector(n_elements, exps.toString(), values.length, exps.sourceInfo));
  716. }
  717. const actual_values = Promise.all(values.map( exp => this.evaluateExpression(store, exp)));
  718. return actual_values.then( values => {
  719. return values.map((v, index) => {
  720. if(!type.canAccept(v.type, 1)) {
  721. if (!Config.enable_type_casting || !Store.canImplicitTypeCast(type.innerType, v.type)) {
  722. // const stringInfo = v.type.stringInfo();
  723. // const info = stringInfo[0];
  724. const exp_str = values[index].toString();
  725. // TODO - fix error message
  726. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_type_full(exp_str, values[index].sourceInfo));
  727. }
  728. const new_value = Store.doImplicitCasting(type.innerType, v);
  729. return new_value;
  730. }
  731. return v;
  732. });
  733. });
  734. }
  735. /**
  736. * Evaluates a list of array literals composing the matrix
  737. * @param {Store} store
  738. * @param {Expressions.ArrayLiteral} exps
  739. * @param {ArrayType} type
  740. * @returns {Promise<StoreValue[]>[]}
  741. */
  742. evaluateMatrix (store, exps, type, lines, columns) {
  743. const values = exps.value;
  744. if(values.length !== lines) {
  745. return Promise.reject(ProcessorErrorFactory.invalid_number_lines_matrix(lines,exps.toString(),values.length, exps.sourceInfo));
  746. }
  747. return values.map( vector => {
  748. const vec_type = new ArrayType(type.innerType, 1);
  749. return this.evaluateVector(store, vector, vec_type, columns);
  750. });
  751. }
  752. evaluateLiteral (_, exp) {
  753. return Promise.resolve(new StoreValue(exp.type, exp.value));
  754. }
  755. evaluateVariableLiteral (store, exp) {
  756. try {
  757. const val = store.applyStore(exp.id);
  758. return Promise.resolve(val);
  759. } catch (error) {
  760. return Promise.reject(error);
  761. }
  762. }
  763. evaluateArrayAccess (store, exp) {
  764. const mustBeArray = store.getStoreObject(exp.id);
  765. if (!(mustBeArray.type instanceof ArrayType)) {
  766. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(exp.id, exp.sourceInfo));
  767. }
  768. const $line = this.evaluateExpression(store, exp.line);
  769. const $column = this.evaluateExpression(store, exp.column);
  770. return Promise.all([$line, $column]).then(([line_sv, column_sv]) => {
  771. if(!Types.INTEGER.isCompatible(line_sv.type)) {
  772. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  773. }
  774. const line = line_sv.get().toNumber();
  775. let column = null;
  776. if(column_sv !== null) {
  777. if(!Types.INTEGER.isCompatible(column_sv.type)) {
  778. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  779. }
  780. column = column_sv.get().toNumber();
  781. }
  782. if (line >= mustBeArray.lines) {
  783. if(mustBeArray.isVector) {
  784. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  785. } else {
  786. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  787. }
  788. } else if (line < 0) {
  789. return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo));
  790. }
  791. if (column !== null && mustBeArray.columns === 0 ){
  792. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(exp.id, exp.sourceInfo));
  793. }
  794. if(column !== null ) {
  795. if (column >= mustBeArray.columns) {
  796. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(exp.id, column,mustBeArray.columns, exp.sourceInfo));
  797. } else if (column < 0) {
  798. return Promise.reject(ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo));
  799. }
  800. }
  801. const result = mustBeArray.getAt(line, column);
  802. const type = mustBeArray.type.innerType;
  803. if(Array.isArray(result)) {
  804. const values = result.map((v, c) => {
  805. return new StoreValueAddress(type, v, line, c, mustBeArray.id, mustBeArray.readOnly);
  806. });
  807. return Promise.resolve(new ArrayStoreValue(new ArrayType(type, 1),
  808. values, mustBeArray.columns, null, mustBeArray.id, mustBeArray.readOnly))
  809. } else {
  810. return Promise.resolve(new StoreValueAddress(type, result, line, column, mustBeArray.id, mustBeArray.readOnly));
  811. }
  812. });
  813. }
  814. evaluateUnaryApp (store, unaryApp) {
  815. const $left = this.evaluateExpression(store, unaryApp.left);
  816. return $left.then( left => {
  817. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  818. if (Types.UNDEFINED.isCompatible(resultType)) {
  819. const stringInfo = left.type.stringInfo();
  820. const info = stringInfo[0];
  821. return Promise.reject(ProcessorErrorFactory.invalid_unary_op_full(unaryApp.op, info.type, info.dim, unaryApp.sourceInfo));
  822. }
  823. switch (unaryApp.op.ord) {
  824. case Operators.ADD.ord:
  825. return new StoreValue(resultType, left.get());
  826. case Operators.SUB.ord:
  827. return new StoreValue(resultType, left.get().negated());
  828. case Operators.NOT.ord:
  829. return new StoreValue(resultType, !left.get());
  830. default:
  831. return Promise.reject(new RuntimeError('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  832. }
  833. });
  834. }
  835. evaluateInfixApp (store, infixApp) {
  836. const $left = this.evaluateExpression(store, infixApp.left);
  837. const $right = this.evaluateExpression(store, infixApp.right);
  838. return Promise.all([$left, $right]).then(values => {
  839. let shouldImplicitCast = false;
  840. const left = values[0];
  841. const right = values[1];
  842. let resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  843. if (Types.UNDEFINED.isCompatible(resultType)) {
  844. if (Config.enable_type_casting && Store.canImplicitTypeCast(left.type, right.type)) {
  845. shouldImplicitCast = true;
  846. } else {
  847. const stringInfoLeft = left.type.stringInfo();
  848. const infoLeft = stringInfoLeft[0];
  849. const stringInfoRight = right.type.stringInfo();
  850. const infoRight = stringInfoRight[0];
  851. return Promise.reject(ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim,
  852. infoRight.type,infoRight.dim,infixApp.sourceInfo));
  853. }
  854. }
  855. let result = null;
  856. switch (infixApp.op.ord) {
  857. case Operators.ADD.ord: {
  858. if(Types.STRING.isCompatible(left.type)) {
  859. const rightStr = convertToString(right.get(), right.type);
  860. return new StoreValue(resultType, (left.get() + rightStr));
  861. } else if (Types.STRING.isCompatible(right.type)) {
  862. const leftStr = convertToString(left.get(), left.type);
  863. return new StoreValue(resultType, (leftStr + right.get()));
  864. } else {
  865. return new StoreValue(resultType, (left.get().plus(right.get())));
  866. }
  867. }
  868. case Operators.SUB.ord:
  869. return new StoreValue(resultType, (left.get().minus(right.get())));
  870. case Operators.MULT.ord: {
  871. result = left.get().times(right.get());
  872. return new StoreValue(resultType, result);
  873. }
  874. case Operators.DIV.ord: {
  875. if (Types.INTEGER.isCompatible(resultType))
  876. result = left.get().divToInt(right.get());
  877. else
  878. result = left.get().div(right.get());
  879. return new StoreValue(resultType, (result));
  880. }
  881. case Operators.MOD.ord: {
  882. let leftValue = left.get();
  883. let rightValue = right.get();
  884. if(shouldImplicitCast) {
  885. resultType = Types.INTEGER;
  886. leftValue = leftValue.trunc();
  887. rightValue = rightValue.trunc();
  888. }
  889. result = leftValue.modulo(rightValue);
  890. return new StoreValue(resultType, (result));
  891. }
  892. case Operators.GT.ord: {
  893. let leftValue = left.get();
  894. let rightValue = right.get();
  895. if (Types.STRING.isCompatible(left.type)) {
  896. result = leftValue.length > rightValue.length;
  897. } else {
  898. if (shouldImplicitCast) {
  899. resultType = Types.BOOLEAN;
  900. leftValue = leftValue.trunc();
  901. rightValue = rightValue.trunc();
  902. }
  903. result = leftValue.gt(rightValue);
  904. }
  905. return new StoreValue(resultType, result);
  906. }
  907. case Operators.GE.ord: {
  908. let leftValue = left.get();
  909. let rightValue = right.get();
  910. if (Types.STRING.isCompatible(left.type)) {
  911. result = leftValue.length >= rightValue.length;
  912. } else {
  913. if (shouldImplicitCast) {
  914. resultType = Types.BOOLEAN;
  915. leftValue = leftValue.trunc();
  916. rightValue = rightValue.trunc();
  917. }
  918. result = leftValue.gte(rightValue);
  919. }
  920. return new StoreValue(resultType, result);
  921. }
  922. case Operators.LT.ord: {
  923. let leftValue = left.get();
  924. let rightValue = right.get();
  925. if (Types.STRING.isCompatible(left.type)) {
  926. result = leftValue.length < rightValue.length;
  927. } else {
  928. if (shouldImplicitCast) {
  929. resultType = Types.BOOLEAN;
  930. leftValue = leftValue.trunc();
  931. rightValue = rightValue.trunc();
  932. }
  933. result = leftValue.lt(rightValue);
  934. }
  935. return new StoreValue(resultType, (result));
  936. }
  937. case Operators.LE.ord: {
  938. let leftValue = left.get();
  939. let rightValue = right.get();
  940. if (Types.STRING.isCompatible(left.type)) {
  941. result = leftValue.length <= rightValue.length;
  942. } else {
  943. if (shouldImplicitCast) {
  944. resultType = Types.BOOLEAN;
  945. leftValue = leftValue.trunc();
  946. rightValue = rightValue.trunc();
  947. }
  948. result = leftValue.lte(rightValue);
  949. }
  950. return new StoreValue(resultType, result);
  951. }
  952. case Operators.EQ.ord: {
  953. let leftValue = left.get();
  954. let rightValue = right.get();
  955. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  956. if (shouldImplicitCast) {
  957. resultType = Types.BOOLEAN;
  958. leftValue = leftValue.trunc();
  959. rightValue = rightValue.trunc();
  960. }
  961. result = leftValue.eq(rightValue);
  962. } else {
  963. result = leftValue === rightValue;
  964. }
  965. return new StoreValue(resultType, result);
  966. }
  967. case Operators.NEQ.ord: {
  968. let leftValue = left.get();
  969. let rightValue = right.get();
  970. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  971. if (shouldImplicitCast) {
  972. resultType = Types.BOOLEAN;
  973. leftValue = leftValue.trunc();
  974. rightValue = rightValue.trunc();
  975. }
  976. result = !leftValue.eq(rightValue);
  977. } else {
  978. result = leftValue !== rightValue;
  979. }
  980. return new StoreValue(resultType, result);
  981. }
  982. case Operators.AND.ord:
  983. return new StoreValue(resultType, (left.get() && right.get()));
  984. case Operators.OR.ord:
  985. return new StoreValue(resultType, (left.get() || right.get()));
  986. default:
  987. return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
  988. }
  989. });
  990. }
  991. }