ivprogProcessor.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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. // TODO: better error message;
  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 CompoundType) {
  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, null);
  124. }
  125. funcStore.insertStore('$', returnStoreObject);
  126. const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  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 => this.executeCommands(stoWithVars, func.commands)).then(finalSto => {
  132. this.stores.pop();
  133. this.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.While) {
  213. return this.executeWhile(store, cmd);
  214. } else if (cmd instanceof Commands.DoWhile) {
  215. return this.executeDoWhile(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.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.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. return Promise.resolve(store);
  425. }
  426. if (vl === null || !funcType.isCompatible(vl.type)) {
  427. const stringInfo = funcType.stringInfo();
  428. const info = stringInfo[0];
  429. return Promise.reject(ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
  430. } else {
  431. let realValue = this.parseStoreObjectValue(vl);
  432. store.updateStore('$', realValue);
  433. store.mode = Modes.RETURN;
  434. return Promise.resolve(store);
  435. }
  436. });
  437. } catch (error) {
  438. return Promise.reject(error);
  439. }
  440. }
  441. executeBreak (store, cmd) {
  442. if(this.checkContext(Context.BREAKABLE)) {
  443. store.mode = Modes.BREAK;
  444. return Promise.resolve(store);
  445. } else {
  446. return Promise.reject(ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo));
  447. }
  448. }
  449. executeAssign (store, cmd) {
  450. try {
  451. const inStore = store.applyStore(cmd.id);
  452. const $value = this.evaluateExpression(store, cmd.expression);
  453. return $value.then( vl => {
  454. let realValue = this.parseStoreObjectValue(vl);
  455. if(!inStore.type.isCompatible(realValue.type)) {
  456. if(Config.enable_type_casting && Store.canImplicitTypeCast(inStore.type, vl.type)) {
  457. realValue = Store.doImplicitCasting(inStore.type, realValue);
  458. } else {
  459. const stringInfo = inStore.type.stringInfo()
  460. const info = stringInfo[0]
  461. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  462. }
  463. }
  464. store.updateStore(cmd.id, realValue)
  465. return store;
  466. });
  467. } catch (error) {
  468. return Promise.reject(error);
  469. }
  470. }
  471. executeArrayIndexAssign (store, cmd) {
  472. const mustBeArray = store.applyStore(cmd.id);
  473. if(!(mustBeArray.type instanceof CompoundType)) {
  474. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
  475. }
  476. const line$ = this.evaluateExpression(store, cmd.line);
  477. const column$ = this.evaluateExpression(store, cmd.column);
  478. const value$ = this.evaluateExpression(store, cmd.expression);
  479. return Promise.all([line$, column$, value$]).then(results => {
  480. const lineSO = results[0];
  481. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  482. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  483. }
  484. const line = lineSO.number;
  485. const columnSO = results[1];
  486. let column = null
  487. if (columnSO !== null) {
  488. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  489. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  490. }
  491. column = columnSO.number;
  492. }
  493. const value = this.parseStoreObjectValue(results[2]);
  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 (value.type instanceof CompoundType || !newArray.type.canAccept(value.type)) {
  516. const type = mustBeArray.type.innerType;
  517. const stringInfo = type.stringInfo()
  518. const info = stringInfo[0]
  519. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  520. }
  521. newArray.value[line].value[column] = value;
  522. store.updateStore(cmd.id, newArray);
  523. } else {
  524. if((mustBeArray.columns !== null && value.type instanceof CompoundType) || !newArray.type.canAccept(value.type)) {
  525. const type = mustBeArray.type;
  526. const stringInfo = type.stringInfo()
  527. const info = stringInfo[0]
  528. const exp = cmd.expression.toString()
  529. return Promise.reject(ProcessorErrorFactory.incompatible_types_array_full(exp,info.type, info.dim-1, cmd.sourceInfo));
  530. }
  531. newArray.value[line] = value;
  532. store.updateStore(cmd.id, newArray);
  533. }
  534. return store;
  535. });
  536. }
  537. executeDeclaration (store, cmd) {
  538. try {
  539. const $value = this.evaluateExpression(store, cmd.initial);
  540. if(cmd instanceof Commands.ArrayDeclaration) {
  541. const $lines = this.evaluateExpression(store, cmd.lines);
  542. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  543. return Promise.all([$lines, $columns, $value]).then(values => {
  544. const lineSO = values[0];
  545. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  546. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  547. }
  548. const line = lineSO.number;
  549. if(line < 0) {
  550. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  551. }
  552. const columnSO = values[1];
  553. let column = null
  554. if (columnSO !== null) {
  555. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  556. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  557. }
  558. column = columnSO.number;
  559. if(column < 0) {
  560. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  561. }
  562. }
  563. const value = values[2];
  564. const temp = new StoreObjectArray(cmd.type, line, column, null);
  565. store.insertStore(cmd.id, temp);
  566. let realValue = value;
  567. if (value !== null) {
  568. if(value instanceof StoreObjectArrayAddress) {
  569. if(value.type instanceof CompoundType) {
  570. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  571. } else {
  572. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  573. }
  574. }
  575. } else {
  576. realValue = new StoreObjectArray(cmd.type, line, column, [])
  577. if(column !== null) {
  578. for (let i = 0; i < line; i++) {
  579. realValue.value.push(new StoreObjectArray(new CompoundType(cmd.type.innerType, 1), column, null, []));
  580. }
  581. }
  582. }
  583. realValue.readOnly = cmd.isConst;
  584. store.updateStore(cmd.id, realValue);
  585. return store;
  586. });
  587. } else {
  588. const temp = new StoreObject(cmd.type, null);
  589. store.insertStore(cmd.id, temp);
  590. return $value.then(vl => {
  591. let realValue = vl;
  592. if (vl !== null) {
  593. if(!vl.type.isCompatible(cmd.type)) {
  594. if(Config.enable_type_casting && Store.canImplicitTypeCast(cmd.type, vl.type)) {
  595. realValue = Store.doImplicitCasting(cmd.type, realValue);
  596. } else {
  597. const stringInfo = typeInfo.type.stringInfo();
  598. const info = stringInfo[0];
  599. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  600. }
  601. }
  602. if(vl instanceof StoreObjectArrayAddress) {
  603. if(vl.type instanceof CompoundType) {
  604. return Promise.reject(new Error("!!!Critical Error: Compatibility check failed, a Type accepts a CompoundType"))
  605. } else {
  606. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  607. }
  608. }
  609. } else {
  610. realValue = new StoreObject(cmd.type, 0);
  611. }
  612. realValue.readOnly = cmd.isConst;
  613. store.updateStore(cmd.id, realValue);
  614. return store;
  615. });
  616. }
  617. } catch (e) {
  618. return Promise.reject(e);
  619. }
  620. }
  621. evaluateExpression (store, exp) {
  622. if (exp instanceof Expressions.UnaryApp) {
  623. return this.evaluateUnaryApp(store, exp);
  624. } else if (exp instanceof Expressions.InfixApp) {
  625. return this.evaluateInfixApp(store, exp);
  626. } else if (exp instanceof Expressions.ArrayAccess) {
  627. return this.evaluateArrayAccess(store, exp);
  628. } else if (exp instanceof Expressions.VariableLiteral) {
  629. return this.evaluateVariableLiteral(store, exp);
  630. } else if (exp instanceof Expressions.IntLiteral) {
  631. return this.evaluateLiteral(store, exp);
  632. } else if (exp instanceof Expressions.RealLiteral) {
  633. return this.evaluateLiteral(store, exp);
  634. } else if (exp instanceof Expressions.BoolLiteral) {
  635. return this.evaluateLiteral(store, exp);
  636. } else if (exp instanceof Expressions.StringLiteral) {
  637. return this.evaluateLiteral(store, exp);
  638. } else if (exp instanceof Expressions.ArrayLiteral) {
  639. return this.evaluateArrayLiteral(store, exp);
  640. } else if (exp instanceof Expressions.FunctionCall) {
  641. return this.evaluateFunctionCall(store, exp);
  642. }
  643. return Promise.resolve(null);
  644. }
  645. evaluateFunctionCall (store, exp) {
  646. if(exp.isMainCall) {
  647. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
  648. }
  649. const func = this.findFunction(exp.id);
  650. if(Types.VOID.isCompatible(func.returnType)) {
  651. // TODO: better error message
  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. const left = values[0];
  814. const right = values[1];
  815. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  816. if (Types.UNDEFINED.isCompatible(resultType)) {
  817. const stringInfoLeft = left.type.stringInfo();
  818. const infoLeft = stringInfoLeft[0];
  819. const stringInfoRight = right.type.stringInfo();
  820. const infoRight = stringInfoRight[0];
  821. return Promise.reject(ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim,
  822. infoRight.type,infoRight.dim,infixApp.sourceInfo));
  823. }
  824. let result = null;
  825. switch (infixApp.op.ord) {
  826. case Operators.ADD.ord: {
  827. if(Types.STRING.isCompatible(left.type)) {
  828. const rightStr = convertToString(right.value, right.type);
  829. return new StoreObject(resultType, left.value + rightStr);
  830. } else if (Types.STRING.isCompatible(right.type)) {
  831. const leftStr = convertToString(left.value, left.type);
  832. return new StoreObject(resultType, leftStr + right.value);
  833. } else {
  834. return new StoreObject(resultType, left.value.plus(right.value));
  835. }
  836. }
  837. case Operators.SUB.ord:
  838. return new StoreObject(resultType, left.value.minus(right.value));
  839. case Operators.MULT.ord: {
  840. result = left.value.times(right.value);
  841. if(result.dp() > Config.decimalPlaces) {
  842. result = new Decimal(result.toFixed(Config.decimalPlaces));
  843. }
  844. return new StoreObject(resultType, result);
  845. }
  846. case Operators.DIV.ord: {
  847. if (Types.INTEGER.isCompatible(resultType))
  848. result = left.value.divToInt(right.value);
  849. else
  850. result = left.value.div(right.value);
  851. if(result.dp() > Config.decimalPlaces) {
  852. result = new Decimal(result.toFixed(Config.decimalPlaces));
  853. }
  854. return new StoreObject(resultType, result);
  855. }
  856. case Operators.MOD.ord: {
  857. result = left.value.modulo(right.value);
  858. if(result.dp() > Config.decimalPlaces) {
  859. result = new Decimal(result.toFixed(Config.decimalPlaces));
  860. }
  861. return new StoreObject(resultType, result);
  862. }
  863. case Operators.GT.ord: {
  864. if (Types.STRING.isCompatible(left.type)) {
  865. result = left.value.length > right.value.length;
  866. } else {
  867. result = left.value.gt(right.value);
  868. }
  869. return new StoreObject(resultType, result);
  870. }
  871. case Operators.GE.ord: {
  872. if (Types.STRING.isCompatible(left.type)) {
  873. result = left.value.length >= right.value.length;
  874. } else {
  875. result = left.value.gte(right.value);
  876. }
  877. return new StoreObject(resultType, result);
  878. }
  879. case Operators.LT.ord: {
  880. if (Types.STRING.isCompatible(left.type)) {
  881. result = left.value.length < right.value.length;
  882. } else {
  883. result = left.value.lt(right.value);
  884. }
  885. return new StoreObject(resultType, result);
  886. }
  887. case Operators.LE.ord: {
  888. if (Types.STRING.isCompatible(left.type)) {
  889. result = left.value.length <= right.value.length;
  890. } else {
  891. result = left.value.lte(right.value);
  892. }
  893. return new StoreObject(resultType, result);
  894. }
  895. case Operators.EQ.ord: {
  896. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  897. result = left.value.eq(right.value);
  898. } else {
  899. result = left.value === right.value;
  900. }
  901. return new StoreObject(resultType, result);
  902. }
  903. case Operators.NEQ.ord: {
  904. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  905. result = !left.value.eq(right.value);
  906. } else {
  907. result = left.value !== right.value;
  908. }
  909. return new StoreObject(resultType, result);
  910. }
  911. case Operators.AND.ord:
  912. return new StoreObject(resultType, left.value && right.value);
  913. case Operators.OR.ord:
  914. return new StoreObject(resultType, left.value || right.value);
  915. default:
  916. return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
  917. }
  918. });
  919. }
  920. parseStoreObjectValue (vl) {
  921. let realValue = vl;
  922. if(vl instanceof StoreObjectArrayAddress) {
  923. if(vl.type instanceof CompoundType) {
  924. switch(vl.type.dimensions) {
  925. case 1: {
  926. realValue = new StoreObjectArray(vl.type, vl.value);
  927. break;
  928. }
  929. default: {
  930. throw new RuntimeError("Three dimensional array address...");
  931. }
  932. }
  933. } else {
  934. realValue = new StoreObject(vl.type, vl.value);
  935. }
  936. }
  937. return realValue;
  938. }
  939. }