ivprogProcessor.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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, canImplicitTypeCast } from '../typeSystem/parsers';
  17. import { Config } from '../util/config';
  18. import Decimal from 'decimal.js';
  19. import { ProcessorErrorFactory } from './error/processorErrorFactory';
  20. import { RuntimeError } from './error/runtimeError';
  21. export class IVProgProcessor {
  22. static get LOOP_TIMEOUT () {
  23. return Config.loopTimeout;
  24. }
  25. static set LOOP_TIMEOUT (ms) {
  26. Config.setConfig({loopTimeout: ms});
  27. }
  28. static get MAIN_INTERNAL_ID () {
  29. return "$main";
  30. }
  31. constructor (ast) {
  32. this.ast = ast;
  33. this.globalStore = new Store("$global");
  34. this.stores = [this.globalStore];
  35. this.context = [Context.BASE];
  36. this.input = null;
  37. this.forceKill = false;
  38. this.loopTimers = [];
  39. this.output = null;
  40. }
  41. registerInput (input) {
  42. if(this.input !== null)
  43. this.input = null;
  44. this.input = input;
  45. }
  46. registerOutput (output) {
  47. if(this.output !== null)
  48. this.output = null;
  49. this.output = output;
  50. }
  51. checkContext(context) {
  52. return this.context[this.context.length - 1] === context;
  53. }
  54. ignoreSwitchCases (store) {
  55. if (store.mode === Modes.RETURN) {
  56. return true;
  57. } else if (store.mode === Modes.BREAK) {
  58. return true;
  59. } else {
  60. return false;
  61. }
  62. }
  63. prepareState () {
  64. if(this.stores !== null) {
  65. for (let i = 0; i < this.stores.length; i++) {
  66. delete this.stores[i];
  67. }
  68. this.stores = null;
  69. }
  70. if(this.globalStore !== null)
  71. this.globalStore = null;
  72. this.globalStore = new Store("$global");
  73. this.stores = [this.globalStore];
  74. this.context = [Context.BASE];
  75. }
  76. interpretAST () {
  77. this.prepareState();
  78. return this.initGlobal().then( _ => {
  79. const mainFunc = this.findMainFunction();
  80. if(mainFunc === null) {
  81. throw ProcessorErrorFactory.main_missing();
  82. }
  83. return this.runFunction(mainFunc, [], this.globalStore);
  84. });
  85. }
  86. initGlobal () {
  87. if(!this.checkContext(Context.BASE)) {
  88. throw ProcessorErrorFactory.invalid_global_var();
  89. }
  90. return this.executeCommands(this.globalStore, this.ast.global);
  91. }
  92. findMainFunction () {
  93. return this.ast.functions.find(v => v.isMain);
  94. }
  95. findFunction (name) {
  96. if(name.match(/^\$.+$/)) {
  97. const fun = LanguageDefinedFunction.getFunction(name);
  98. if(!!!fun) {
  99. throw ProcessorErrorFactory.not_implemented(name);
  100. }
  101. return fun;
  102. } else {
  103. const val = this.ast.functions.find( v => v.name === name);
  104. if (!!!val) {
  105. // TODO: better error message;
  106. throw ProcessorErrorFactory.function_missing(name);
  107. }
  108. return val;
  109. }
  110. }
  111. runFunction (func, actualParameters, store) {
  112. const funcName = func.isMain ? IVProgProcessor.MAIN_INTERNAL_ID : func.name;
  113. let funcStore = new Store(funcName);
  114. funcStore.extendStore(this.globalStore);
  115. let returnStoreObject = null;
  116. if(func.returnType instanceof CompoundType) {
  117. if(func.returnType.dimensions > 1) {
  118. returnStoreObject = new StoreObjectArray(func.returnType,-1,-1,[[]]);
  119. } else {
  120. returnStoreObject = new StoreObjectArray(func.returnType,-1,null,[]);
  121. }
  122. } else {
  123. returnStoreObject = new StoreObject(func.returnType, null);
  124. }
  125. funcStore.insertStore('$', returnStoreObject);
  126. const newFuncStore$ = this.associateParameters(func.formalParameters, actualParameters, store, funcStore);
  127. return newFuncStore$.then(sto => {
  128. this.context.push(Context.FUNCTION);
  129. this.stores.push(sto);
  130. return this.executeCommands(sto, func.variablesDeclarations)
  131. .then(stoWithVars => this.executeCommands(stoWithVars, func.commands)).then(finalSto => {
  132. this.stores.pop();
  133. this.context.pop();
  134. return finalSto;
  135. });
  136. });
  137. }
  138. associateParameters (formalList, actualList, callerStore, calleeStore) {
  139. const funcName = calleeStore.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  140. LanguageDefinedFunction.getMainFunctionName() : calleeStore.name;
  141. if (formalList.length != actualList.length) {
  142. throw ProcessorErrorFactory.invalid_parameters_size(funcName, formalList.length, actualList.length);
  143. }
  144. const promises$ = actualList.map(actualParameter => this.evaluateExpression(callerStore, actualParameter));
  145. return Promise.all(promises$).then(values => {
  146. for (let i = 0; i < values.length; i++) {
  147. const stoObj = values[i];
  148. const exp = actualList[i]
  149. const formalParameter = formalList[i];
  150. if(formalParameter.type.isCompatible(stoObj.type)) {
  151. if(formalParameter.byRef && !stoObj.inStore) {
  152. throw ProcessorErrorFactory.invalid_ref(funcName, exp.toString());
  153. }
  154. if(formalParameter.byRef) {
  155. let ref = null;
  156. if (stoObj instanceof StoreObjectArrayAddress) {
  157. ref = new StoreObjectArrayAddressRef(stoObj);
  158. } else {
  159. ref = new StoreObjectRef(stoObj.id, callerStore);
  160. }
  161. calleeStore.insertStore(formalParameter.id, ref);
  162. } else {
  163. let realValue = this.parseStoreObjectValue(stoObj);
  164. calleeStore.insertStore(formalParameter.id, realValue);
  165. }
  166. } else {
  167. throw ProcessorErrorFactory.invalid_parameter_type(funcName, exp.toString());
  168. }
  169. }
  170. return calleeStore;
  171. });
  172. }
  173. executeCommands (store, cmds) {
  174. // helper to partially apply a function, in this case executeCommand
  175. const outerRef = this;
  176. const partial = (fun, cmd) => (sto) => fun(sto, cmd);
  177. return cmds.reduce((lastCommand, next) => {
  178. const nextCommand = partial(outerRef.executeCommand.bind(outerRef), next);
  179. return lastCommand.then(nextCommand);
  180. }, Promise.resolve(store));
  181. }
  182. executeCommand (store, cmd) {
  183. if(this.forceKill) {
  184. return Promise.reject("FORCED_KILL!");
  185. } else if (store.mode === Modes.PAUSE) {
  186. return Promise.resolve(this.executeCommand(store, cmd));
  187. } else if(store.mode === Modes.RETURN) {
  188. return Promise.resolve(store);
  189. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  190. return Promise.resolve(store);
  191. }
  192. if (cmd instanceof Commands.Declaration) {
  193. return this.executeDeclaration(store, cmd);
  194. } else if (cmd instanceof Commands.ArrayIndexAssign) {
  195. return this.executeArrayIndexAssign(store, cmd);
  196. } else if (cmd instanceof Commands.Assign) {
  197. return this.executeAssign(store, cmd);
  198. } else if (cmd instanceof Commands.Break) {
  199. return this.executeBreak(store, cmd);
  200. } else if (cmd instanceof Commands.Return) {
  201. return this.executeReturn(store, cmd);
  202. } else if (cmd instanceof Commands.IfThenElse) {
  203. return this.executeIfThenElse(store, cmd);
  204. } else if (cmd instanceof Commands.While) {
  205. return this.executeWhile(store, cmd);
  206. } else if (cmd instanceof Commands.DoWhile) {
  207. return this.executeDoWhile(store, cmd);
  208. } else if (cmd instanceof Commands.For) {
  209. return this.executeFor(store, cmd);
  210. } else if (cmd instanceof Commands.Switch) {
  211. return this.executeSwitch(store, cmd);
  212. } else if (cmd instanceof Expressions.FunctionCall) {
  213. return this.executeFunctionCall(store, cmd);
  214. } else if (cmd instanceof Commands.SysCall) {
  215. return this.executeSysCall(store, cmd);
  216. } else {
  217. throw ProcessorErrorFactory.unknown_command(cmd.sourceInfo);
  218. }
  219. }
  220. executeSysCall (store, cmd) {
  221. const func = cmd.langFunc.bind(this);
  222. return func(store, cmd);
  223. }
  224. executeFunctionCall (store, cmd) {
  225. let func = null;
  226. if(cmd.isMainCall) {
  227. func = this.findMainFunction();
  228. } else {
  229. func = this.findFunction(cmd.id);
  230. }
  231. return this.runFunction(func, cmd.actualParameters, store)
  232. .then(sto => {
  233. if(!Types.VOID.isCompatible(func.returnType) && sto.mode !== Modes.RETURN) {
  234. const funcName = func.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  235. LanguageDefinedFunction.getMainFunctionName() : func.name;
  236. return Promise.reject(ProcessorErrorFactory.function_no_return(funcName));
  237. } else {
  238. return store;
  239. }
  240. })
  241. }
  242. executeSwitch (store, cmd) {
  243. this.context.push(Context.BREAKABLE);
  244. const auxCaseFun = (promise, switchExp, aCase) => {
  245. return promise.then( result => {
  246. const sto = result.sto;
  247. if (this.ignoreSwitchCases(sto)) {
  248. return Promise.resolve(result);
  249. } else if (result.wasTrue || aCase.isDefault) {
  250. const $newSto = this.executeCommands(result.sto,aCase.commands);
  251. return $newSto.then(nSto => {
  252. return Promise.resolve({wasTrue: true, sto: nSto});
  253. });
  254. } else {
  255. const $value = this.evaluateExpression(sto,
  256. new Expressions.InfixApp(Operators.EQ, switchExp, aCase.expression));
  257. return $value.then(vl => {
  258. if (vl.value) {
  259. const $newSto = this.executeCommands(result.sto,aCase.commands);
  260. return $newSto.then(nSto => {
  261. return Promise.resolve({wasTrue: true, sto: nSto});
  262. });
  263. } else {
  264. return Promise.resolve({wasTrue: false, sto: sto});
  265. }
  266. });
  267. }
  268. });
  269. }
  270. try {
  271. let breakLoop = false;
  272. let $result = Promise.resolve({wasTrue: false, sto: store});
  273. for (let index = 0; index < cmd.cases.length && !breakLoop; index++) {
  274. const aCase = cmd.cases[index];
  275. $result = auxCaseFun($result, cmd.expression, aCase);
  276. $result.then( r => breakLoop = this.ignoreSwitchCases(r.sto));
  277. }
  278. return $result.then(r => {
  279. this.context.pop();
  280. if(r.sto.mode === Modes.BREAK) {
  281. r.sto.mode = Modes.RUN;
  282. }
  283. return r.sto;
  284. });
  285. } catch (error) {
  286. return Promise.reject(error);
  287. }
  288. }
  289. executeFor (store, cmd) {
  290. try {
  291. //BEGIN for -> while rewrite
  292. const initCmd = cmd.assignment;
  293. const condition = cmd.condition;
  294. const increment = cmd.increment;
  295. const whileBlock = new Commands.CommandBlock([],
  296. cmd.commands.concat(increment));
  297. const forAsWhile = new Commands.While(condition, whileBlock);
  298. forAsWhile.sourceInfo = cmd.sourceInfo;
  299. //END for -> while rewrite
  300. const newCmdList = [initCmd,forAsWhile];
  301. return this.executeCommands(store, newCmdList);
  302. } catch (error) {
  303. return Promise.reject(error);
  304. }
  305. }
  306. executeDoWhile (store, cmd) {
  307. const outerRef = this;
  308. try {
  309. outerRef.loopTimers.push(Date.now());
  310. outerRef.context.push(Context.BREAKABLE);
  311. const $newStore = outerRef.executeCommands(store, cmd.commands);
  312. return $newStore.then(sto => {
  313. if(sto.mode === Modes.BREAK) {
  314. outerRef.context.pop();
  315. sto.mode = Modes.RUN;
  316. outerRef.loopTimers.pop();
  317. return sto;
  318. }
  319. const $value = outerRef.evaluateExpression(sto, cmd.expression);
  320. return $value.then(vl => {
  321. if (!vl.type.isCompatible(Types.BOOLEAN)) {
  322. return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo));
  323. }
  324. if (vl.value) {
  325. outerRef.context.pop();
  326. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  327. const time = outerRef.loopTimers[i];
  328. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  329. outerRef.forceKill = true;
  330. return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
  331. }
  332. }
  333. return outerRef.executeCommand(sto, cmd);
  334. } else {
  335. outerRef.context.pop();
  336. outerRef.loopTimers.pop();
  337. return sto;
  338. }
  339. })
  340. })
  341. } catch (error) {
  342. return Promise.reject(error);
  343. }
  344. }
  345. executeWhile (store, cmd) {
  346. const outerRef = this;
  347. try {
  348. outerRef.loopTimers.push(Date.now());
  349. outerRef.context.push(Context.BREAKABLE);
  350. const $value = outerRef.evaluateExpression(store, cmd.expression);
  351. return $value.then(vl => {
  352. if(vl.type.isCompatible(Types.BOOLEAN)) {
  353. if(vl.value) {
  354. const $newStore = outerRef.executeCommands(store, cmd.commands);
  355. return $newStore.then(sto => {
  356. outerRef.context.pop();
  357. if (sto.mode === Modes.BREAK) {
  358. outerRef.loopTimers.pop();
  359. sto.mode = Modes.RUN;
  360. return sto;
  361. }
  362. for (let i = 0; i < outerRef.loopTimers.length; i++) {
  363. const time = outerRef.loopTimers[i];
  364. if(Date.now() - time >= IVProgProcessor.LOOP_TIMEOUT) {
  365. outerRef.forceKill = true;
  366. return Promise.reject(ProcessorErrorFactory.endless_loop_full(cmd.sourceInfo));
  367. }
  368. }
  369. return outerRef.executeCommand(sto, cmd);
  370. });
  371. } else {
  372. outerRef.context.pop();
  373. outerRef.loopTimers.pop();
  374. return store;
  375. }
  376. } else {
  377. return Promise.reject(ProcessorErrorFactory.loop_condition_type_full(cmd.sourceInfo));
  378. }
  379. })
  380. } catch (error) {
  381. return Promise.reject(error);
  382. }
  383. }
  384. executeIfThenElse (store, cmd) {
  385. try {
  386. const $value = this.evaluateExpression(store, cmd.condition);
  387. return $value.then(vl => {
  388. if(vl.type.isCompatible(Types.BOOLEAN)) {
  389. if(vl.value) {
  390. return this.executeCommands(store, cmd.ifTrue.commands);
  391. } else if( cmd.ifFalse !== null){
  392. if(cmd.ifFalse instanceof Commands.IfThenElse) {
  393. return this.executeCommand(store, cmd.ifFalse);
  394. } else {
  395. return this.executeCommands(store, cmd.ifFalse.commands);
  396. }
  397. } else {
  398. return Promise.resolve(store);
  399. }
  400. } else {
  401. return Promise.reject(ProcessorErrorFactory.if_condition_type_full(cmd.sourceInfo));
  402. }
  403. });
  404. } catch (error) {
  405. return Promise.reject(error);
  406. }
  407. }
  408. executeReturn (store, cmd) {
  409. try {
  410. const funcType = store.applyStore('$').type;
  411. const $value = this.evaluateExpression(store, cmd.expression);
  412. const funcName = store.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  413. LanguageDefinedFunction.getMainFunctionName() : store.name;
  414. return $value.then(vl => {
  415. if(vl === null && funcType.isCompatible(Types.VOID)) {
  416. return Promise.resolve(store);
  417. }
  418. if (vl === null || !funcType.isCompatible(vl.type)) {
  419. const stringInfo = funcType.stringInfo();
  420. const info = stringInfo[0];
  421. return Promise.reject(ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
  422. } else {
  423. let realValue = this.parseStoreObjectValue(vl);
  424. store.updateStore('$', realValue);
  425. store.mode = Modes.RETURN;
  426. return Promise.resolve(store);
  427. }
  428. });
  429. } catch (error) {
  430. return Promise.reject(error);
  431. }
  432. }
  433. executeBreak (store, cmd) {
  434. if(this.checkContext(Context.BREAKABLE)) {
  435. store.mode = Modes.BREAK;
  436. return Promise.resolve(store);
  437. } else {
  438. return Promise.reject(ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo));
  439. }
  440. }
  441. executeAssign (store, cmd) {
  442. try {
  443. const $value = this.evaluateExpression(store, cmd.expression);
  444. return $value.then( vl => {
  445. let realValue = this.parseStoreObjectValue(vl);
  446. store.updateStore(cmd.id, realValue)
  447. return store;
  448. });
  449. } catch (error) {
  450. return Promise.reject(error);
  451. }
  452. }
  453. executeArrayIndexAssign (store, cmd) {
  454. const mustBeArray = store.applyStore(cmd.id);
  455. if(!(mustBeArray.type instanceof CompoundType)) {
  456. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
  457. }
  458. const line$ = this.evaluateExpression(store, cmd.line);
  459. const column$ = this.evaluateExpression(store, cmd.column);
  460. const value$ = this.evaluateExpression(store, cmd.expression);
  461. return Promise.all([line$, column$, value$]).then(results => {
  462. const lineSO = results[0];
  463. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  464. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  465. }
  466. const line = lineSO.number;
  467. const columnSO = results[1];
  468. let column = null
  469. if (columnSO !== null) {
  470. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  471. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  472. }
  473. column = columnSO.number;
  474. }
  475. const value = this.parseStoreObjectValue(results[2]);
  476. if (line >= mustBeArray.lines) {
  477. if(mustBeArray.isVector) {
  478. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  479. } else {
  480. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  481. }
  482. } else if (line < 0) {
  483. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  484. }
  485. if (column !== null && mustBeArray.columns === null ){
  486. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(cmd.id, cmd.sourceInfo));
  487. }
  488. if(column !== null ) {
  489. if (column >= mustBeArray.columns) {
  490. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(cmd.id, column,mustBeArray.columns, cmd.sourceInfo));
  491. } else if (column < 0) {
  492. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  493. }
  494. }
  495. const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
  496. if (column !== null) {
  497. if (value.type instanceof CompoundType || !newArray.type.canAccept(value.type)) {
  498. const type = mustBeArray.type.innerType;
  499. const stringInfo = type.stringInfo()
  500. const info = stringInfo[0]
  501. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  502. }
  503. newArray.value[line].value[column] = value;
  504. store.updateStore(cmd.id, newArray);
  505. } else {
  506. if((mustBeArray.columns !== null && value.type instanceof CompoundType) || !newArray.type.canAccept(value.type)) {
  507. const type = mustBeArray.type;
  508. const stringInfo = type.stringInfo()
  509. const info = stringInfo[0]
  510. const exp = cmd.expression.toString()
  511. return Promise.reject(ProcessorErrorFactory.incompatible_types_array_full(exp,info.type, info.dim-1, cmd.sourceInfo));
  512. }
  513. newArray.value[line] = value;
  514. store.updateStore(cmd.id, newArray);
  515. }
  516. return store;
  517. });
  518. }
  519. executeDeclaration (store, cmd) {
  520. try {
  521. const $value = this.evaluateExpression(store, cmd.initial);
  522. if(cmd instanceof Commands.ArrayDeclaration) {
  523. const $lines = this.evaluateExpression(store, cmd.lines);
  524. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  525. return Promise.all([$lines, $columns, $value]).then(values => {
  526. const lineSO = values[0];
  527. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  528. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  529. }
  530. const line = lineSO.number;
  531. if(line < 0) {
  532. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  533. }
  534. const columnSO = values[1];
  535. let column = null
  536. if (columnSO !== null) {
  537. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  538. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  539. }
  540. column = columnSO.number;
  541. if(column < 0) {
  542. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  543. }
  544. }
  545. const value = values[2];
  546. const temp = new StoreObjectArray(cmd.type, line, column, null);
  547. store.insertStore(cmd.id, temp);
  548. let realValue = value;
  549. if (value !== null) {
  550. if(value instanceof StoreObjectArrayAddress) {
  551. if(value.type instanceof CompoundType) {
  552. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  553. } else {
  554. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  555. }
  556. }
  557. } else {
  558. realValue = new StoreObjectArray(cmd.type, line, column, [])
  559. if(column !== null) {
  560. for (let i = 0; i < line; i++) {
  561. realValue.value.push(new StoreObjectArray(new CompoundType(cmd.type.innerType, 1), column, null, []));
  562. }
  563. }
  564. }
  565. realValue.readOnly = cmd.isConst;
  566. store.updateStore(cmd.id, realValue);
  567. return store;
  568. });
  569. } else {
  570. const temp = new StoreObject(cmd.type, null);
  571. store.insertStore(cmd.id, temp);
  572. return $value.then(vl => {
  573. let realValue = vl;
  574. if (vl !== null) {
  575. if(!vl.type.isCompatible(cmd.type)) {
  576. if(Config.enable_type_casting && canImplicitTypeCast(cmd.type, vl.type)) {
  577. if(Types.INTEGER.isCompatible(cmd.type)) {
  578. realValue = new StoreObject(cmd.type, vl.value.trunc());
  579. } else {
  580. realValue = new StoreObject(cmd.type, vl.value);
  581. }
  582. } else {
  583. const stringInfo = typeInfo.type.stringInfo();
  584. const info = stringInfo[0];
  585. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  586. }
  587. }
  588. if(vl instanceof StoreObjectArrayAddress) {
  589. if(vl.type instanceof CompoundType) {
  590. return Promise.reject(new Error("!!!Critical Error: Compatibility check failed, a Type accepts a CompoundType"))
  591. } else {
  592. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  593. }
  594. }
  595. } else {
  596. realValue = new StoreObject(cmd.type, 0);
  597. }
  598. realValue.readOnly = cmd.isConst;
  599. store.updateStore(cmd.id, realValue);
  600. return store;
  601. });
  602. }
  603. } catch (e) {
  604. return Promise.reject(e);
  605. }
  606. }
  607. evaluateExpression (store, exp) {
  608. if (exp instanceof Expressions.UnaryApp) {
  609. return this.evaluateUnaryApp(store, exp);
  610. } else if (exp instanceof Expressions.InfixApp) {
  611. return this.evaluateInfixApp(store, exp);
  612. } else if (exp instanceof Expressions.ArrayAccess) {
  613. return this.evaluateArrayAccess(store, exp);
  614. } else if (exp instanceof Expressions.VariableLiteral) {
  615. return this.evaluateVariableLiteral(store, exp);
  616. } else if (exp instanceof Expressions.IntLiteral) {
  617. return this.evaluateLiteral(store, exp);
  618. } else if (exp instanceof Expressions.RealLiteral) {
  619. return this.evaluateLiteral(store, exp);
  620. } else if (exp instanceof Expressions.BoolLiteral) {
  621. return this.evaluateLiteral(store, exp);
  622. } else if (exp instanceof Expressions.StringLiteral) {
  623. return this.evaluateLiteral(store, exp);
  624. } else if (exp instanceof Expressions.ArrayLiteral) {
  625. return this.evaluateArrayLiteral(store, exp);
  626. } else if (exp instanceof Expressions.FunctionCall) {
  627. return this.evaluateFunctionCall(store, exp);
  628. }
  629. return Promise.resolve(null);
  630. }
  631. evaluateFunctionCall (store, exp) {
  632. if(exp.isMainCall) {
  633. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
  634. }
  635. const func = this.findFunction(exp.id);
  636. if(Types.VOID.isCompatible(func.returnType)) {
  637. // TODO: better error message
  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. const left = values[0];
  800. const right = values[1];
  801. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  802. if (Types.UNDEFINED.isCompatible(resultType)) {
  803. const stringInfoLeft = left.type.stringInfo();
  804. const infoLeft = stringInfoLeft[0];
  805. const stringInfoRight = right.type.stringInfo();
  806. const infoRight = stringInfoRight[0];
  807. return Promise.reject(ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim,
  808. infoRight.type,infoRight.dim,infixApp.sourceInfo));
  809. }
  810. let result = null;
  811. switch (infixApp.op.ord) {
  812. case Operators.ADD.ord: {
  813. if(Types.STRING.isCompatible(left.type)) {
  814. const rightStr = convertToString(right.value, right.type);
  815. return new StoreObject(resultType, left.value + rightStr);
  816. } else if (Types.STRING.isCompatible(right.type)) {
  817. const leftStr = convertToString(left.value, left.type);
  818. return new StoreObject(resultType, leftStr + right.value);
  819. } else {
  820. return new StoreObject(resultType, left.value.plus(right.value));
  821. }
  822. }
  823. case Operators.SUB.ord:
  824. return new StoreObject(resultType, left.value.minus(right.value));
  825. case Operators.MULT.ord: {
  826. result = left.value.times(right.value);
  827. if(result.dp() > Config.decimalPlaces) {
  828. result = new Decimal(result.toFixed(Config.decimalPlaces));
  829. }
  830. return new StoreObject(resultType, result);
  831. }
  832. case Operators.DIV.ord: {
  833. if (Types.INTEGER.isCompatible(resultType))
  834. result = left.value.divToInt(right.value);
  835. else
  836. result = left.value.div(right.value);
  837. if(result.dp() > Config.decimalPlaces) {
  838. result = new Decimal(result.toFixed(Config.decimalPlaces));
  839. }
  840. return new StoreObject(resultType, result);
  841. }
  842. case Operators.MOD.ord: {
  843. result = left.value.modulo(right.value);
  844. if(result.dp() > Config.decimalPlaces) {
  845. result = new Decimal(result.toFixed(Config.decimalPlaces));
  846. }
  847. return new StoreObject(resultType, result);
  848. }
  849. case Operators.GT.ord: {
  850. if (Types.STRING.isCompatible(left.type)) {
  851. result = left.value.length > right.value.length;
  852. } else {
  853. result = left.value.gt(right.value);
  854. }
  855. return new StoreObject(resultType, result);
  856. }
  857. case Operators.GE.ord: {
  858. if (Types.STRING.isCompatible(left.type)) {
  859. result = left.value.length >= right.value.length;
  860. } else {
  861. result = left.value.gte(right.value);
  862. }
  863. return new StoreObject(resultType, result);
  864. }
  865. case Operators.LT.ord: {
  866. if (Types.STRING.isCompatible(left.type)) {
  867. result = left.value.length < right.value.length;
  868. } else {
  869. result = left.value.lt(right.value);
  870. }
  871. return new StoreObject(resultType, result);
  872. }
  873. case Operators.LE.ord: {
  874. if (Types.STRING.isCompatible(left.type)) {
  875. result = left.value.length <= right.value.length;
  876. } else {
  877. result = left.value.lte(right.value);
  878. }
  879. return new StoreObject(resultType, result);
  880. }
  881. case Operators.EQ.ord: {
  882. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  883. result = left.value.eq(right.value);
  884. } else {
  885. result = left.value === right.value;
  886. }
  887. return new StoreObject(resultType, result);
  888. }
  889. case Operators.NEQ.ord: {
  890. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  891. result = !left.value.eq(right.value);
  892. } else {
  893. result = left.value !== right.value;
  894. }
  895. return new StoreObject(resultType, result);
  896. }
  897. case Operators.AND.ord:
  898. return new StoreObject(resultType, left.value && right.value);
  899. case Operators.OR.ord:
  900. return new StoreObject(resultType, left.value || right.value);
  901. default:
  902. return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
  903. }
  904. });
  905. }
  906. parseStoreObjectValue (vl) {
  907. let realValue = vl;
  908. if(vl instanceof StoreObjectArrayAddress) {
  909. if(vl.type instanceof CompoundType) {
  910. switch(vl.type.dimensions) {
  911. case 1: {
  912. realValue = new StoreObjectArray(vl.type, vl.value);
  913. break;
  914. }
  915. default: {
  916. throw new RuntimeError("Three dimensional array address...");
  917. }
  918. }
  919. } else {
  920. realValue = new StoreObject(vl.type, vl.value);
  921. }
  922. }
  923. return realValue;
  924. }
  925. }