ivprogProcessor.js 39 KB

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