ivprogProcessor.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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 auxCaseFun = (promise, switchExp, aCase) => {
  253. return promise.then( result => {
  254. const sto = result.sto;
  255. if (this.ignoreSwitchCases(sto)) {
  256. return Promise.resolve(result);
  257. } else if (result.wasTrue || aCase.isDefault) {
  258. const $newSto = this.executeCommands(result.sto,aCase.commands);
  259. return $newSto.then(nSto => {
  260. return Promise.resolve({wasTrue: true, sto: nSto});
  261. });
  262. } else {
  263. const $value = this.evaluateExpression(sto,
  264. new Expressions.InfixApp(Operators.EQ, switchExp, aCase.expression));
  265. return $value.then(vl => {
  266. if (vl.value) {
  267. const $newSto = this.executeCommands(result.sto,aCase.commands);
  268. return $newSto.then(nSto => {
  269. return Promise.resolve({wasTrue: true, sto: nSto});
  270. });
  271. } else {
  272. return Promise.resolve({wasTrue: false, sto: sto});
  273. }
  274. });
  275. }
  276. });
  277. }
  278. try {
  279. let breakLoop = false;
  280. let $result = Promise.resolve({wasTrue: false, sto: store});
  281. for (let index = 0; index < cmd.cases.length && !breakLoop; index++) {
  282. const aCase = cmd.cases[index];
  283. $result = auxCaseFun($result, cmd.expression, aCase);
  284. $result.then( r => breakLoop = this.ignoreSwitchCases(r.sto));
  285. }
  286. return $result.then(r => {
  287. this.context.pop();
  288. if(r.sto.mode === Modes.BREAK) {
  289. r.sto.mode = Modes.RUN;
  290. }
  291. return r.sto;
  292. });
  293. } catch (error) {
  294. return Promise.reject(error);
  295. }
  296. }
  297. executeFor (store, cmd) {
  298. try {
  299. //BEGIN for -> while rewrite
  300. const initCmd = cmd.assignment;
  301. const condition = cmd.condition;
  302. const increment = cmd.increment;
  303. const whileBlock = new Commands.CommandBlock([],
  304. cmd.commands.concat(increment));
  305. const forAsWhile = new Commands.While(condition, whileBlock);
  306. forAsWhile.sourceInfo = cmd.sourceInfo;
  307. //END for -> while rewrite
  308. const newCmdList = [initCmd,forAsWhile];
  309. return this.executeCommands(store, newCmdList);
  310. } catch (error) {
  311. return Promise.reject(error);
  312. }
  313. }
  314. executeDoWhile (store, cmd) {
  315. const outerRef = this;
  316. try {
  317. outerRef.loopTimers.push(Date.now());
  318. outerRef.context.push(Context.BREAKABLE);
  319. const $newStore = outerRef.executeCommands(store, cmd.commands);
  320. return $newStore.then(sto => {
  321. if(sto.mode === Modes.BREAK) {
  322. outerRef.context.pop();
  323. sto.mode = Modes.RUN;
  324. outerRef.loopTimers.pop();
  325. return sto;
  326. }
  327. const $value = outerRef.evaluateExpression(sto, cmd.expression);
  328. return $value.then(vl => {
  329. if (!vl.type.isCompatible(Types.BOOLEAN)) {
  330. return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo));
  331. }
  332. if (vl.value) {
  333. outerRef.context.pop();
  334. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  335. const time = outerRef.loopTimers[i];
  336. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  337. outerRef.forceKill = true;
  338. return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
  339. }
  340. }
  341. return outerRef.executeCommand(sto, cmd);
  342. } else {
  343. outerRef.context.pop();
  344. outerRef.loopTimers.pop();
  345. return sto;
  346. }
  347. })
  348. })
  349. } catch (error) {
  350. return Promise.reject(error);
  351. }
  352. }
  353. executeWhile (store, cmd) {
  354. const outerRef = this;
  355. try {
  356. outerRef.loopTimers.push(Date.now());
  357. outerRef.context.push(Context.BREAKABLE);
  358. const $value = outerRef.evaluateExpression(store, cmd.expression);
  359. return $value.then(vl => {
  360. if(vl.type.isCompatible(Types.BOOLEAN)) {
  361. if(vl.value) {
  362. const $newStore = outerRef.executeCommands(store, cmd.commands);
  363. return $newStore.then(sto => {
  364. outerRef.context.pop();
  365. if (sto.mode === Modes.BREAK) {
  366. outerRef.loopTimers.pop();
  367. sto.mode = Modes.RUN;
  368. return sto;
  369. }
  370. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  371. const time = outerRef.loopTimers[i];
  372. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  373. outerRef.forceKill = true;
  374. return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
  375. }
  376. }
  377. return outerRef.executeCommand(sto, cmd);
  378. });
  379. } else {
  380. outerRef.context.pop();
  381. outerRef.loopTimers.pop();
  382. return store;
  383. }
  384. } else {
  385. return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.expression.toString(), cmd.sourceInfo));
  386. }
  387. })
  388. } catch (error) {
  389. return Promise.reject(error);
  390. }
  391. }
  392. executeIfThenElse (store, cmd) {
  393. try {
  394. const $value = this.evaluateExpression(store, cmd.condition);
  395. return $value.then(vl => {
  396. if(vl.type.isCompatible(Types.BOOLEAN)) {
  397. if(vl.value) {
  398. return this.executeCommands(store, cmd.ifTrue.commands);
  399. } else if( cmd.ifFalse !== null){
  400. if(cmd.ifFalse instanceof Commands.IfThenElse) {
  401. return this.executeCommand(store, cmd.ifFalse);
  402. } else {
  403. return this.executeCommands(store, cmd.ifFalse.commands);
  404. }
  405. } else {
  406. return Promise.resolve(store);
  407. }
  408. } else {
  409. return Promise.reject(ProcessorErrorFactory.if_condition_type_full(cmd.condition.toString(), cmd.sourceInfo));
  410. }
  411. });
  412. } catch (error) {
  413. return Promise.reject(error);
  414. }
  415. }
  416. executeReturn (store, cmd) {
  417. try {
  418. const funcType = store.applyStore('$').type;
  419. const $value = this.evaluateExpression(store, cmd.expression);
  420. const funcName = store.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  421. LanguageDefinedFunction.getMainFunctionName() : store.name;
  422. return $value.then(vl => {
  423. if(vl === null && funcType.isCompatible(Types.VOID)) {
  424. store.mode = Modes.RETURN;
  425. return Promise.resolve(store);
  426. }
  427. if (vl === null || !funcType.isCompatible(vl.type)) {
  428. const stringInfo = funcType.stringInfo();
  429. const info = stringInfo[0];
  430. return Promise.reject(ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
  431. } else {
  432. let realValue = this.parseStoreObjectValue(vl);
  433. store.updateStore('$', realValue);
  434. store.mode = Modes.RETURN;
  435. return Promise.resolve(store);
  436. }
  437. });
  438. } catch (error) {
  439. return Promise.reject(error);
  440. }
  441. }
  442. executeBreak (store, cmd) {
  443. if(this.checkContext(Context.BREAKABLE)) {
  444. store.mode = Modes.BREAK;
  445. return Promise.resolve(store);
  446. } else {
  447. return Promise.reject(ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo));
  448. }
  449. }
  450. executeAssign (store, cmd) {
  451. try {
  452. const inStore = store.applyStore(cmd.id);
  453. const $value = this.evaluateExpression(store, cmd.expression);
  454. return $value.then( vl => {
  455. let realValue = this.parseStoreObjectValue(vl);
  456. if(!inStore.type.isCompatible(realValue.type)) {
  457. if(Config.enable_type_casting && Store.canImplicitTypeCast(inStore.type, vl.type)) {
  458. realValue = Store.doImplicitCasting(inStore.type, realValue);
  459. } else {
  460. const stringInfo = inStore.type.stringInfo()
  461. const info = stringInfo[0]
  462. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  463. }
  464. }
  465. store.updateStore(cmd.id, realValue)
  466. return store;
  467. });
  468. } catch (error) {
  469. return Promise.reject(error);
  470. }
  471. }
  472. executeArrayIndexAssign (store, cmd) {
  473. const mustBeArray = store.applyStore(cmd.id);
  474. if(!(mustBeArray.type instanceof CompoundType)) {
  475. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
  476. }
  477. const line$ = this.evaluateExpression(store, cmd.line);
  478. const column$ = this.evaluateExpression(store, cmd.column);
  479. const value$ = this.evaluateExpression(store, cmd.expression);
  480. return Promise.all([line$, column$, value$]).then(results => {
  481. const lineSO = results[0];
  482. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  483. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  484. }
  485. const line = lineSO.number;
  486. const columnSO = results[1];
  487. let column = null
  488. if (columnSO !== null) {
  489. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  490. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  491. }
  492. column = columnSO.number;
  493. }
  494. const value = this.parseStoreObjectValue(results[2]);
  495. if (line >= mustBeArray.lines) {
  496. if(mustBeArray.isVector) {
  497. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  498. } else {
  499. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  500. }
  501. } else if (line < 0) {
  502. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  503. }
  504. if (column !== null && mustBeArray.columns === null ){
  505. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(cmd.id, cmd.sourceInfo));
  506. }
  507. if(column !== null ) {
  508. if (column >= mustBeArray.columns) {
  509. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(cmd.id, column,mustBeArray.columns, cmd.sourceInfo));
  510. } else if (column < 0) {
  511. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  512. }
  513. }
  514. const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
  515. if (column !== null) {
  516. if (value.type instanceof CompoundType || !newArray.type.canAccept(value.type)) {
  517. const type = mustBeArray.type.innerType;
  518. const stringInfo = type.stringInfo()
  519. const info = stringInfo[0]
  520. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  521. }
  522. newArray.value[line].value[column] = value;
  523. store.updateStore(cmd.id, newArray);
  524. } else {
  525. if((mustBeArray.columns !== null && value.type instanceof CompoundType) || !newArray.type.canAccept(value.type)) {
  526. const type = mustBeArray.type;
  527. const stringInfo = type.stringInfo()
  528. const info = stringInfo[0]
  529. const exp = cmd.expression.toString()
  530. return Promise.reject(ProcessorErrorFactory.incompatible_types_array_full(exp,info.type, info.dim-1, cmd.sourceInfo));
  531. }
  532. newArray.value[line] = value;
  533. store.updateStore(cmd.id, newArray);
  534. }
  535. return store;
  536. });
  537. }
  538. executeDeclaration (store, cmd) {
  539. try {
  540. const $value = this.evaluateExpression(store, cmd.initial);
  541. if(cmd instanceof Commands.ArrayDeclaration) {
  542. const $lines = this.evaluateExpression(store, cmd.lines);
  543. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  544. return Promise.all([$lines, $columns, $value]).then(values => {
  545. const lineSO = values[0];
  546. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  547. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  548. }
  549. const line = lineSO.number;
  550. if(line < 0) {
  551. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  552. }
  553. const columnSO = values[1];
  554. let column = null
  555. if (columnSO !== null) {
  556. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  557. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  558. }
  559. column = columnSO.number;
  560. if(column < 0) {
  561. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  562. }
  563. }
  564. const value = values[2];
  565. const temp = new StoreObjectArray(cmd.type, line, column, null);
  566. store.insertStore(cmd.id, temp);
  567. let realValue = value;
  568. if (value !== null) {
  569. if(value instanceof StoreObjectArrayAddress) {
  570. if(value.type instanceof CompoundType) {
  571. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  572. } else {
  573. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  574. }
  575. }
  576. } else {
  577. realValue = new StoreObjectArray(cmd.type, line, column, [])
  578. if(column !== null) {
  579. for (let i = 0; i < line; i++) {
  580. realValue.value.push(new StoreObjectArray(new CompoundType(cmd.type.innerType, 1), column, null, []));
  581. }
  582. }
  583. }
  584. realValue.readOnly = cmd.isConst;
  585. store.updateStore(cmd.id, realValue);
  586. return store;
  587. });
  588. } else {
  589. const temp = new StoreObject(cmd.type, null);
  590. store.insertStore(cmd.id, temp);
  591. return $value.then(vl => {
  592. let realValue = vl;
  593. if (vl !== null) {
  594. if(!vl.type.isCompatible(cmd.type)) {
  595. if(Config.enable_type_casting && Store.canImplicitTypeCast(cmd.type, vl.type)) {
  596. realValue = Store.doImplicitCasting(cmd.type, realValue);
  597. } else {
  598. const stringInfo = typeInfo.type.stringInfo();
  599. const info = stringInfo[0];
  600. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  601. }
  602. }
  603. if(vl instanceof StoreObjectArrayAddress) {
  604. if(vl.type instanceof CompoundType) {
  605. return Promise.reject(new Error("!!!Critical Error: Compatibility check failed, a Type accepts a CompoundType"))
  606. } else {
  607. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  608. }
  609. }
  610. } else {
  611. realValue = new StoreObject(cmd.type, 0);
  612. }
  613. realValue.readOnly = cmd.isConst;
  614. store.updateStore(cmd.id, realValue);
  615. return store;
  616. });
  617. }
  618. } catch (e) {
  619. return Promise.reject(e);
  620. }
  621. }
  622. evaluateExpression (store, exp) {
  623. if (exp instanceof Expressions.UnaryApp) {
  624. return this.evaluateUnaryApp(store, exp);
  625. } else if (exp instanceof Expressions.InfixApp) {
  626. return this.evaluateInfixApp(store, exp);
  627. } else if (exp instanceof Expressions.ArrayAccess) {
  628. return this.evaluateArrayAccess(store, exp);
  629. } else if (exp instanceof Expressions.VariableLiteral) {
  630. return this.evaluateVariableLiteral(store, exp);
  631. } else if (exp instanceof Expressions.IntLiteral) {
  632. return this.evaluateLiteral(store, exp);
  633. } else if (exp instanceof Expressions.RealLiteral) {
  634. return this.evaluateLiteral(store, exp);
  635. } else if (exp instanceof Expressions.BoolLiteral) {
  636. return this.evaluateLiteral(store, exp);
  637. } else if (exp instanceof Expressions.StringLiteral) {
  638. return this.evaluateLiteral(store, exp);
  639. } else if (exp instanceof Expressions.ArrayLiteral) {
  640. return this.evaluateArrayLiteral(store, exp);
  641. } else if (exp instanceof Expressions.FunctionCall) {
  642. return this.evaluateFunctionCall(store, exp);
  643. }
  644. return Promise.resolve(null);
  645. }
  646. evaluateFunctionCall (store, exp) {
  647. if(exp.isMainCall) {
  648. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
  649. }
  650. const func = this.findFunction(exp.id);
  651. if(Types.VOID.isCompatible(func.returnType)) {
  652. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(exp.id, exp.sourceInfo));
  653. }
  654. const $newStore = this.runFunction(func, exp.actualParameters, store);
  655. return $newStore.then( sto => {
  656. if(sto.mode !== Modes.RETURN) {
  657. return Promise.reject(new Error("The function that was called did not had a return command: "+exp.id));
  658. }
  659. const val = sto.applyStore('$');
  660. if (val instanceof StoreObjectArray) {
  661. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  662. } else {
  663. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  664. }
  665. });
  666. }
  667. evaluateArrayLiteral (store, exp) {
  668. const errorHelperFunction = (validationResult, exp) => {
  669. const errorCode = validationResult[0];
  670. switch(errorCode) {
  671. case StoreObjectArray.WRONG_COLUMN_NUMBER: {
  672. const columnValue = validationResult[1];
  673. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_column_full(arr.columns, columnValue, exp.sourceInfo));
  674. }
  675. case StoreObjectArray.WRONG_LINE_NUMBER: {
  676. const lineValue = validationResult[1];
  677. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_line_full(arr.lines, lineValue, exp.sourceInfo));
  678. }
  679. case StoreObjectArray.WRONG_TYPE: {
  680. let line = null;
  681. let strExp = null;
  682. if (validationResult.length > 2) {
  683. line = validationResult[1];
  684. const column = validationResult[2];
  685. strExp = exp.value[line].value[column].toString()
  686. } else {
  687. line = validationResult[1];
  688. strExp = exp.value[line].toString()
  689. }
  690. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_type_full(strExp, exp.sourceInfo)); }
  691. }
  692. };
  693. if(!exp.isVector) {
  694. const $matrix = this.evaluateMatrix(store, exp.value);
  695. return $matrix.then(list => {
  696. const type = new CompoundType(list[0].type.innerType, 2);
  697. const arr = new StoreObjectArray(type, list.length, list[0].lines, list);
  698. const checkResult = arr.isValid;
  699. if(checkResult.length == 0)
  700. return Promise.resolve(arr);
  701. else {
  702. return errorHelperFunction(checkResult, exp);
  703. }
  704. });
  705. } else {
  706. return this.evaluateVector(store, exp.value).then(list => {
  707. const type = new CompoundType(list[0].type, 1);
  708. const stoArray = new StoreObjectArray(type, list.length, null, list);
  709. const checkResult = stoArray.isValid;
  710. if(checkResult.length == 0)
  711. return Promise.resolve(stoArray);
  712. else {
  713. return errorHelperFunction(checkResult, exp);
  714. }
  715. });
  716. }
  717. }
  718. evaluateVector (store, exps) {
  719. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  720. }
  721. evaluateMatrix (store, exps) {
  722. return Promise.all(exps.map( vector => {
  723. const $vector = this.evaluateVector(store, vector.value)
  724. return $vector.then(list => {
  725. const type = new CompoundType(list[0].type, 1);
  726. return new StoreObjectArray(type, list.length, null, list)
  727. });
  728. } ));
  729. }
  730. evaluateLiteral (_, exp) {
  731. return Promise.resolve(new StoreObject(exp.type, exp.value));
  732. }
  733. evaluateVariableLiteral (store, exp) {
  734. try {
  735. const val = store.applyStore(exp.id);
  736. if (val instanceof StoreObjectArray) {
  737. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  738. } else {
  739. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  740. }
  741. } catch (error) {
  742. return Promise.reject(error);
  743. }
  744. }
  745. evaluateArrayAccess (store, exp) {
  746. const mustBeArray = store.applyStore(exp.id);
  747. if (!(mustBeArray.type instanceof CompoundType)) {
  748. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(exp.id, exp.sourceInfo));
  749. }
  750. const $line = this.evaluateExpression(store, exp.line);
  751. const $column = this.evaluateExpression(store, exp.column);
  752. return Promise.all([$line, $column]).then(values => {
  753. const lineSO = values[0];
  754. const columnSO = values[1];
  755. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  756. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  757. }
  758. const line = lineSO.number;
  759. let column = null;
  760. if(columnSO !== null) {
  761. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  762. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  763. }
  764. column = columnSO.number;
  765. }
  766. if (line >= mustBeArray.lines) {
  767. if(mustBeArray.isVector) {
  768. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  769. } else {
  770. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  771. }
  772. } else if (line < 0) {
  773. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  774. }
  775. if (column !== null && mustBeArray.columns === null ){
  776. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(exp.id, exp.sourceInfo));
  777. }
  778. if(column !== null ) {
  779. if (column >= mustBeArray.columns) {
  780. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(exp.id, column,mustBeArray.columns, exp.sourceInfo));
  781. } else if (column < 0) {
  782. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  783. }
  784. }
  785. return Promise.resolve(new StoreObjectArrayAddress(mustBeArray.id, line, column, store));
  786. });
  787. }
  788. evaluateUnaryApp (store, unaryApp) {
  789. const $left = this.evaluateExpression(store, unaryApp.left);
  790. return $left.then( left => {
  791. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  792. if (Types.UNDEFINED.isCompatible(resultType)) {
  793. const stringInfo = left.type.stringInfo();
  794. const info = stringInfo[0];
  795. return Promise.reject(ProcessorErrorFactory.invalid_unary_op_full(unaryApp.op, info.type, info.dim, unaryApp.sourceInfo));
  796. }
  797. switch (unaryApp.op.ord) {
  798. case Operators.ADD.ord:
  799. return new StoreObject(resultType, left.value);
  800. case Operators.SUB.ord:
  801. return new StoreObject(resultType, left.value.negated());
  802. case Operators.NOT.ord:
  803. return new StoreObject(resultType, !left.value);
  804. default:
  805. return Promise.reject(new RuntimeError('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  806. }
  807. });
  808. }
  809. evaluateInfixApp (store, infixApp) {
  810. const $left = this.evaluateExpression(store, infixApp.left);
  811. const $right = this.evaluateExpression(store, infixApp.right);
  812. return Promise.all([$left, $right]).then(values => {
  813. let shouldImplicitCast = false;
  814. const left = values[0];
  815. const right = values[1];
  816. let resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  817. if (Types.UNDEFINED.isCompatible(resultType)) {
  818. if (Config.enable_type_casting && Store.canImplicitTypeCast(left.type, right.type)) {
  819. shouldImplicitCast = true;
  820. } else {
  821. const stringInfoLeft = left.type.stringInfo();
  822. const infoLeft = stringInfoLeft[0];
  823. const stringInfoRight = right.type.stringInfo();
  824. const infoRight = stringInfoRight[0];
  825. return Promise.reject(ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim,
  826. infoRight.type,infoRight.dim,infixApp.sourceInfo));
  827. }
  828. }
  829. let result = null;
  830. switch (infixApp.op.ord) {
  831. case Operators.ADD.ord: {
  832. if(Types.STRING.isCompatible(left.type)) {
  833. const rightStr = convertToString(right.value, right.type);
  834. return new StoreObject(resultType, left.value + rightStr);
  835. } else if (Types.STRING.isCompatible(right.type)) {
  836. const leftStr = convertToString(left.value, left.type);
  837. return new StoreObject(resultType, leftStr + right.value);
  838. } else {
  839. return new StoreObject(resultType, left.value.plus(right.value));
  840. }
  841. }
  842. case Operators.SUB.ord:
  843. return new StoreObject(resultType, left.value.minus(right.value));
  844. case Operators.MULT.ord: {
  845. result = left.value.times(right.value);
  846. if(result.dp() > Config.decimalPlaces) {
  847. result = new Decimal(result.toFixed(Config.decimalPlaces));
  848. }
  849. return new StoreObject(resultType, result);
  850. }
  851. case Operators.DIV.ord: {
  852. if (Types.INTEGER.isCompatible(resultType))
  853. result = left.value.divToInt(right.value);
  854. else
  855. result = left.value.div(right.value);
  856. if(result.dp() > Config.decimalPlaces) {
  857. result = new Decimal(result.toFixed(Config.decimalPlaces));
  858. }
  859. return new StoreObject(resultType, result);
  860. }
  861. case Operators.MOD.ord: {
  862. let leftValue = left.value;
  863. let rightValue = right.value;
  864. if(shouldImplicitCast) {
  865. resultType = Types.INTEGER;
  866. leftValue = leftValue.trunc();
  867. rightValue = rightValue.trunc();
  868. }
  869. result = leftValue.modulo(rightValue);
  870. if(result.dp() > Config.decimalPlaces) {
  871. result = new Decimal(result.toFixed(Config.decimalPlaces));
  872. }
  873. return new StoreObject(resultType, result);
  874. }
  875. case Operators.GT.ord: {
  876. let leftValue = left.value;
  877. let rightValue = right.value;
  878. if (Types.STRING.isCompatible(left.type)) {
  879. result = left.value.length > right.value.length;
  880. } else {
  881. if (shouldImplicitCast) {
  882. resultType = Types.BOOLEAN;
  883. leftValue = leftValue.trunc();
  884. rightValue = rightValue.trunc();
  885. }
  886. result = leftValue.gt(rightValue);
  887. }
  888. return new StoreObject(resultType, result);
  889. }
  890. case Operators.GE.ord: {
  891. let leftValue = left.value;
  892. let rightValue = right.value;
  893. if (Types.STRING.isCompatible(left.type)) {
  894. result = left.value.length >= right.value.length;
  895. } else {
  896. if (shouldImplicitCast) {
  897. resultType = Types.BOOLEAN;
  898. leftValue = leftValue.trunc();
  899. rightValue = rightValue.trunc();
  900. }
  901. result = leftValue.gte(rightValue);
  902. }
  903. return new StoreObject(resultType, result);
  904. }
  905. case Operators.LT.ord: {
  906. let leftValue = left.value;
  907. let rightValue = right.value;
  908. if (Types.STRING.isCompatible(left.type)) {
  909. result = left.value.length < right.value.length;
  910. } else {
  911. if (shouldImplicitCast) {
  912. resultType = Types.BOOLEAN;
  913. leftValue = leftValue.trunc();
  914. rightValue = rightValue.trunc();
  915. }
  916. result = leftValue.lt(rightValue);
  917. }
  918. return new StoreObject(resultType, result);
  919. }
  920. case Operators.LE.ord: {
  921. let leftValue = left.value;
  922. let rightValue = right.value;
  923. if (Types.STRING.isCompatible(left.type)) {
  924. result = left.value.length <= right.value.length;
  925. } else {
  926. if (shouldImplicitCast) {
  927. resultType = Types.BOOLEAN;
  928. leftValue = leftValue.trunc();
  929. rightValue = rightValue.trunc();
  930. }
  931. result = leftValue.lte(rightValue);
  932. }
  933. return new StoreObject(resultType, result);
  934. }
  935. case Operators.EQ.ord: {
  936. let leftValue = left.value;
  937. let rightValue = right.value;
  938. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  939. if (shouldImplicitCast) {
  940. resultType = Types.BOOLEAN;
  941. leftValue = leftValue.trunc();
  942. rightValue = rightValue.trunc();
  943. }
  944. result = leftValue.eq(rightValue);
  945. } else {
  946. result = left.value === right.value;
  947. }
  948. return new StoreObject(resultType, result);
  949. }
  950. case Operators.NEQ.ord: {
  951. let leftValue = left.value;
  952. let rightValue = right.value;
  953. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  954. if (shouldImplicitCast) {
  955. resultType = Types.BOOLEAN;
  956. leftValue = leftValue.trunc();
  957. rightValue = rightValue.trunc();
  958. }
  959. result = !leftValue.eq(rightValue);
  960. } else {
  961. result = left.value !== right.value;
  962. }
  963. return new StoreObject(resultType, result);
  964. }
  965. case Operators.AND.ord:
  966. return new StoreObject(resultType, left.value && right.value);
  967. case Operators.OR.ord:
  968. return new StoreObject(resultType, left.value || right.value);
  969. default:
  970. return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
  971. }
  972. });
  973. }
  974. parseStoreObjectValue (vl) {
  975. let realValue = vl;
  976. if(vl instanceof StoreObjectArrayAddress) {
  977. if(vl.type instanceof CompoundType) {
  978. switch(vl.type.dimensions) {
  979. case 1: {
  980. realValue = new StoreObjectArray(vl.type, vl.value);
  981. break;
  982. }
  983. default: {
  984. throw new RuntimeError("Three dimensional array address...");
  985. }
  986. }
  987. } else {
  988. realValue = new StoreObject(vl.type, vl.value);
  989. }
  990. }
  991. return realValue;
  992. }
  993. }