ivprogProcessor.js 41 KB

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