ivprogProcessor.js 38 KB

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