ivprogProcessor.js 42 KB

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