ivprogProcessor.js 40 KB

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