ivprogProcessor.js 37 KB

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