ivprogProcessor.js 39 KB

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