ivprogProcessor.js 41 KB

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