1
0

ivprogProcessor.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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. this.initGlobal();
  79. const mainFunc = this.findMainFunction();
  80. if(mainFunc === null) {
  81. throw ProcessorErrorFactory.main_missing();
  82. }
  83. return this.runFunction(mainFunc, [], this.globalStore);
  84. }
  85. initGlobal () {
  86. if(!this.checkContext(Context.BASE)) {
  87. throw ProcessorErrorFactory.invalid_global_var();
  88. }
  89. this.ast.global.forEach(decl => {
  90. this.executeCommand(this.globalStore, decl).then(sto => this.globalStore = sto);
  91. });
  92. }
  93. findMainFunction () {
  94. return this.ast.functions.find(v => v.isMain);
  95. }
  96. findFunction (name) {
  97. if(name.match(/^\$.+$/)) {
  98. const fun = LanguageDefinedFunction.getFunction(name);
  99. if(!!!fun) {
  100. throw ProcessorErrorFactory.not_implemented(name);
  101. }
  102. return fun;
  103. } else {
  104. const val = this.ast.functions.find( v => v.name === name);
  105. if (!!!val) {
  106. // TODO: better error message;
  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 CompoundType) {
  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. return newFuncStore$.then(sto => {
  129. this.context.push(Context.FUNCTION);
  130. this.stores.push(sto);
  131. return this.executeCommands(sto, func.variablesDeclarations)
  132. .then(stoWithVars => this.executeCommands(stoWithVars, func.commands)).then(finalSto => {
  133. this.stores.pop();
  134. this.context.pop();
  135. return finalSto;
  136. });
  137. });
  138. }
  139. associateParameters (formalList, actualList, callerStore, calleeStore) {
  140. const funcName = calleeStore.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  141. LanguageDefinedFunction.getMainFunctionName() : calleeStore.name;
  142. if (formalList.length != actualList.length) {
  143. throw ProcessorErrorFactory.invalid_parameters_size(funcName, formalList.length, actualList.length);
  144. }
  145. const promises$ = actualList.map(actualParameter => this.evaluateExpression(callerStore, actualParameter));
  146. return Promise.all(promises$).then(values => {
  147. for (let i = 0; i < values.length; i++) {
  148. const stoObj = values[i];
  149. const exp = actualList[i]
  150. const formalParameter = formalList[i];
  151. if(formalParameter.type.isCompatible(stoObj.type)) {
  152. if(formalParameter.byRef && !stoObj.inStore) {
  153. throw ProcessorErrorFactory.invalid_ref(funcName, exp.toString());
  154. }
  155. if(formalParameter.byRef) {
  156. let ref = null;
  157. if (stoObj instanceof StoreObjectArrayAddress) {
  158. ref = new StoreObjectArrayAddressRef(stoObj);
  159. } else {
  160. ref = new StoreObjectRef(stoObj.id, callerStore);
  161. }
  162. calleeStore.insertStore(formalParameter.id, ref);
  163. } else {
  164. let realValue = this.parseStoreObjectValue(stoObj);
  165. calleeStore.insertStore(formalParameter.id, realValue);
  166. }
  167. } else {
  168. throw ProcessorErrorFactory.invalid_parameter_type(funcName, exp.toString());
  169. }
  170. }
  171. return calleeStore;
  172. });
  173. }
  174. executeCommands (store, cmds) {
  175. // helper to partially apply a function, in this case executeCommand
  176. const outerRef = this;
  177. const partial = (fun, cmd) => (sto) => fun(sto, cmd);
  178. return cmds.reduce((lastCommand, next) => {
  179. const nextCommand = partial(outerRef.executeCommand.bind(outerRef), next);
  180. return lastCommand.then(nextCommand);
  181. }, Promise.resolve(store));
  182. }
  183. executeCommand (store, cmd) {
  184. if(this.forceKill) {
  185. return Promise.reject("FORCED_KILL!");
  186. } else if (store.mode === Modes.PAUSE) {
  187. return Promise.resolve(this.executeCommand(store, cmd));
  188. } else if(store.mode === Modes.RETURN) {
  189. return Promise.resolve(store);
  190. } else if(this.checkContext(Context.BREAKABLE) && store.mode === Modes.BREAK) {
  191. return Promise.resolve(store);
  192. }
  193. if (cmd instanceof Commands.Declaration) {
  194. return this.executeDeclaration(store, cmd);
  195. } else if (cmd instanceof Commands.ArrayIndexAssign) {
  196. return this.executeArrayIndexAssign(store, cmd);
  197. } else if (cmd instanceof Commands.Assign) {
  198. return this.executeAssign(store, cmd);
  199. } else if (cmd instanceof Commands.Break) {
  200. return this.executeBreak(store, cmd);
  201. } else if (cmd instanceof Commands.Return) {
  202. return this.executeReturn(store, cmd);
  203. } else if (cmd instanceof Commands.IfThenElse) {
  204. return this.executeIfThenElse(store, cmd);
  205. } else if (cmd instanceof Commands.While) {
  206. return this.executeWhile(store, cmd);
  207. } else if (cmd instanceof Commands.DoWhile) {
  208. return this.executeDoWhile(store, cmd);
  209. } else if (cmd instanceof Commands.For) {
  210. return this.executeFor(store, cmd);
  211. } else if (cmd instanceof Commands.Switch) {
  212. return this.executeSwitch(store, cmd);
  213. } else if (cmd instanceof Expressions.FunctionCall) {
  214. return this.executeFunctionCall(store, cmd);
  215. } else if (cmd instanceof Commands.SysCall) {
  216. return this.executeSysCall(store, cmd);
  217. } else {
  218. throw ProcessorErrorFactory.unknown_command(cmd.sourceInfo);
  219. }
  220. }
  221. executeSysCall (store, cmd) {
  222. const func = cmd.langFunc.bind(this);
  223. return func(store, cmd);
  224. }
  225. executeFunctionCall (store, cmd) {
  226. let func = null;
  227. if(cmd.isMainCall) {
  228. func = this.findMainFunction();
  229. } else {
  230. func = this.findFunction(cmd.id);
  231. }
  232. return this.runFunction(func, cmd.actualParameters, store)
  233. .then(sto => {
  234. if(!Types.VOID.isCompatible(func.returnType) && sto.mode !== Modes.RETURN) {
  235. const funcName = func.name === IVProgProcessor.MAIN_INTERNAL_ID ?
  236. LanguageDefinedFunction.getMainFunctionName() : func.name;
  237. return Promise.reject(ProcessorErrorFactory.function_no_return(funcName));
  238. } else {
  239. return store;
  240. }
  241. })
  242. }
  243. executeSwitch (store, cmd) {
  244. this.context.push(Context.BREAKABLE);
  245. const auxCaseFun = (promise, switchExp, aCase) => {
  246. return promise.then( result => {
  247. const sto = result.sto;
  248. if (this.ignoreSwitchCases(sto)) {
  249. return Promise.resolve(result);
  250. } else if (result.wasTrue || aCase.isDefault) {
  251. const $newSto = this.executeCommands(result.sto,aCase.commands);
  252. return $newSto.then(nSto => {
  253. return Promise.resolve({wasTrue: true, sto: nSto});
  254. });
  255. } else {
  256. const $value = this.evaluateExpression(sto,
  257. new Expressions.InfixApp(Operators.EQ, switchExp, aCase.expression));
  258. return $value.then(vl => {
  259. if (vl.value) {
  260. const $newSto = this.executeCommands(result.sto,aCase.commands);
  261. return $newSto.then(nSto => {
  262. return Promise.resolve({wasTrue: true, sto: nSto});
  263. });
  264. } else {
  265. return Promise.resolve({wasTrue: false, sto: sto});
  266. }
  267. });
  268. }
  269. });
  270. }
  271. try {
  272. let breakLoop = false;
  273. let $result = Promise.resolve({wasTrue: false, sto: store});
  274. for (let index = 0; index < cmd.cases.length && !breakLoop; index++) {
  275. const aCase = cmd.cases[index];
  276. $result = auxCaseFun($result, cmd.expression, aCase);
  277. $result.then( r => breakLoop = this.ignoreSwitchCases(r.sto));
  278. }
  279. return $result.then(r => {
  280. this.context.pop();
  281. if(r.sto.mode === Modes.BREAK) {
  282. r.sto.mode = Modes.RUN;
  283. }
  284. return r.sto;
  285. });
  286. } catch (error) {
  287. return Promise.reject(error);
  288. }
  289. }
  290. executeFor (store, cmd) {
  291. try {
  292. //BEGIN for -> while rewrite
  293. const initCmd = cmd.assignment;
  294. const condition = cmd.condition;
  295. const increment = cmd.increment;
  296. const whileBlock = new Commands.CommandBlock([],
  297. cmd.commands.concat(increment));
  298. const forAsWhile = new Commands.While(condition, whileBlock);
  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) {
  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) {
  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 instanceof StoreObjectArrayAddress) {
  576. if(vl.type instanceof CompoundType) {
  577. realValue = Object.assign(new StoreObjectArray(null,null,null), vl.refValue);
  578. } else {
  579. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  580. }
  581. }
  582. } else {
  583. realValue = new StoreObject(cmd.type,0);
  584. }
  585. realValue.readOnly = cmd.isConst;
  586. store.updateStore(cmd.id, realValue);
  587. return store;
  588. });
  589. }
  590. } catch (e) {
  591. return Promise.reject(e);
  592. }
  593. }
  594. evaluateExpression (store, exp) {
  595. if (exp instanceof Expressions.UnaryApp) {
  596. return this.evaluateUnaryApp(store, exp);
  597. } else if (exp instanceof Expressions.InfixApp) {
  598. return this.evaluateInfixApp(store, exp);
  599. } else if (exp instanceof Expressions.ArrayAccess) {
  600. return this.evaluateArrayAccess(store, exp);
  601. } else if (exp instanceof Expressions.VariableLiteral) {
  602. return this.evaluateVariableLiteral(store, exp);
  603. } else if (exp instanceof Expressions.IntLiteral) {
  604. return this.evaluateLiteral(store, exp);
  605. } else if (exp instanceof Expressions.RealLiteral) {
  606. return this.evaluateLiteral(store, exp);
  607. } else if (exp instanceof Expressions.BoolLiteral) {
  608. return this.evaluateLiteral(store, exp);
  609. } else if (exp instanceof Expressions.StringLiteral) {
  610. return this.evaluateLiteral(store, exp);
  611. } else if (exp instanceof Expressions.ArrayLiteral) {
  612. return this.evaluateArrayLiteral(store, exp);
  613. } else if (exp instanceof Expressions.FunctionCall) {
  614. return this.evaluateFunctionCall(store, exp);
  615. }
  616. return Promise.resolve(null);
  617. }
  618. evaluateFunctionCall (store, exp) {
  619. if(exp.isMainCall) {
  620. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
  621. }
  622. const func = this.findFunction(exp.id);
  623. if(Types.VOID.isCompatible(func.returnType)) {
  624. // TODO: better error message
  625. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(exp.id, exp.sourceInfo));
  626. }
  627. const $newStore = this.runFunction(func, exp.actualParameters, store);
  628. return $newStore.then( sto => {
  629. if(sto.mode !== Modes.RETURN) {
  630. return Promise.reject(new Error("The function that was called did not had a return command: "+exp.id));
  631. }
  632. const val = sto.applyStore('$');
  633. if (val instanceof StoreObjectArray) {
  634. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  635. } else {
  636. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  637. }
  638. });
  639. }
  640. evaluateArrayLiteral (store, exp) {
  641. const errorHelperFunction = (validationResult, exp) => {
  642. const errorCode = validationResult[0];
  643. switch(errorCode) {
  644. case StoreObjectArray.WRONG_COLUMN_NUMBER: {
  645. const columnValue = validationResult[1];
  646. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_column_full(arr.columns, columnValue, exp.sourceInfo));
  647. }
  648. case StoreObjectArray.WRONG_LINE_NUMBER: {
  649. const lineValue = validationResult[1];
  650. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_line_full(arr.lines, lineValue, exp.sourceInfo));
  651. }
  652. case StoreObjectArray.WRONG_TYPE: {
  653. let line = null;
  654. let strExp = null;
  655. if (validationResult.length > 2) {
  656. line = validationResult[1];
  657. const column = validationResult[2];
  658. strExp = exp.value[line].value[column].toString()
  659. } else {
  660. line = validationResult[1];
  661. strExp = exp.value[line].toString()
  662. }
  663. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_type_full(strExp, exp.sourceInfo)); }
  664. }
  665. };
  666. if(!exp.isVector) {
  667. const $matrix = this.evaluateMatrix(store, exp.value);
  668. return $matrix.then(list => {
  669. const type = new CompoundType(list[0].type.innerType, 2);
  670. const arr = new StoreObjectArray(type, list.length, list[0].lines, list);
  671. const checkResult = arr.isValid;
  672. if(checkResult.length == 0)
  673. return Promise.resolve(arr);
  674. else {
  675. return errorHelperFunction(checkResult, exp);
  676. }
  677. });
  678. } else {
  679. return this.evaluateVector(store, exp.value).then(list => {
  680. const type = new CompoundType(list[0].type, 1);
  681. const stoArray = new StoreObjectArray(type, list.length, null, list);
  682. const checkResult = stoArray.isValid;
  683. if(checkResult.length == 0)
  684. return Promise.resolve(stoArray);
  685. else {
  686. return errorHelperFunction(checkResult, exp);
  687. }
  688. });
  689. }
  690. }
  691. evaluateVector (store, exps) {
  692. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  693. }
  694. evaluateMatrix (store, exps) {
  695. return Promise.all(exps.map( vector => {
  696. const $vector = this.evaluateVector(store, vector.value)
  697. return $vector.then(list => {
  698. const type = new CompoundType(list[0].type, 1);
  699. return new StoreObjectArray(type, list.length, null, list)
  700. });
  701. } ));
  702. }
  703. evaluateLiteral (_, exp) {
  704. return Promise.resolve(new StoreObject(exp.type, exp.value));
  705. }
  706. evaluateVariableLiteral (store, exp) {
  707. try {
  708. const val = store.applyStore(exp.id);
  709. if (val instanceof StoreObjectArray) {
  710. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  711. } else {
  712. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  713. }
  714. } catch (error) {
  715. return Promise.reject(error);
  716. }
  717. }
  718. evaluateArrayAccess (store, exp) {
  719. const mustBeArray = store.applyStore(exp.id);
  720. if (!(mustBeArray.type instanceof CompoundType)) {
  721. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(exp.id, exp.sourceInfo));
  722. }
  723. const $line = this.evaluateExpression(store, exp.line);
  724. const $column = this.evaluateExpression(store, exp.column);
  725. return Promise.all([$line, $column]).then(values => {
  726. const lineSO = values[0];
  727. const columnSO = values[1];
  728. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  729. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  730. }
  731. const line = lineSO.number;
  732. let column = null;
  733. if(columnSO !== null) {
  734. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  735. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  736. }
  737. column = columnSO.number;
  738. }
  739. if (line >= mustBeArray.lines) {
  740. if(mustBeArray.isVector) {
  741. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  742. } else {
  743. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  744. }
  745. } else if (line < 0) {
  746. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  747. }
  748. if (column !== null && mustBeArray.columns === null ){
  749. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(exp.id, exp.sourceInfo));
  750. }
  751. if(column !== null ) {
  752. if (column >= mustBeArray.columns) {
  753. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(exp.id, column,mustBeArray.columns, exp.sourceInfo));
  754. } else if (column < 0) {
  755. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  756. }
  757. }
  758. return Promise.resolve(new StoreObjectArrayAddress(mustBeArray.id, line, column, store));
  759. });
  760. }
  761. evaluateUnaryApp (store, unaryApp) {
  762. const $left = this.evaluateExpression(store, unaryApp.left);
  763. return $left.then( left => {
  764. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  765. if (Types.UNDEFINED.isCompatible(resultType)) {
  766. const stringInfo = left.type.stringInfo();
  767. const info = stringInfo[0];
  768. return Promise.reject(ProcessorErrorFactory.invalid_unary_op_full(unaryApp.op, info.type, info.dim, unaryApp.sourceInfo));
  769. }
  770. switch (unaryApp.op.ord) {
  771. case Operators.ADD.ord:
  772. return new StoreObject(resultType, left.value);
  773. case Operators.SUB.ord:
  774. return new StoreObject(resultType, left.value.negated());
  775. case Operators.NOT.ord:
  776. return new StoreObject(resultType, !left.value);
  777. default:
  778. return Promise.reject(new RuntimeError('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  779. }
  780. });
  781. }
  782. evaluateInfixApp (store, infixApp) {
  783. const $left = this.evaluateExpression(store, infixApp.left);
  784. const $right = this.evaluateExpression(store, infixApp.right);
  785. return Promise.all([$left, $right]).then(values => {
  786. const left = values[0];
  787. const right = values[1];
  788. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  789. if (Types.UNDEFINED.isCompatible(resultType)) {
  790. const stringInfoLeft = left.type.stringInfo();
  791. const infoLeft = stringInfoLeft[0];
  792. const stringInfoRight = right.type.stringInfo();
  793. const infoRight = stringInfoRight[0];
  794. return Promise.reject(ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim,
  795. infoRight.type,infoRight.dim,infixApp.sourceInfo));
  796. }
  797. let result = null;
  798. switch (infixApp.op.ord) {
  799. case Operators.ADD.ord: {
  800. if(Types.STRING.isCompatible(left.type)) {
  801. const rightStr = convertToString(right.value, right.type);
  802. return new StoreObject(resultType, left.value + rightStr);
  803. } else if (Types.STRING.isCompatible(right.type)) {
  804. const leftStr = convertToString(left.value, left.type);
  805. return new StoreObject(resultType, leftStr + right.value);
  806. } else {
  807. return new StoreObject(resultType, left.value.plus(right.value));
  808. }
  809. }
  810. case Operators.SUB.ord:
  811. return new StoreObject(resultType, left.value.minus(right.value));
  812. case Operators.MULT.ord: {
  813. result = left.value.times(right.value);
  814. if(result.dp() > Config.decimalPlaces) {
  815. result = new Decimal(result.toFixed(Config.decimalPlaces));
  816. }
  817. return new StoreObject(resultType, result);
  818. }
  819. case Operators.DIV.ord: {
  820. if (Types.INTEGER.isCompatible(resultType))
  821. result = left.value.divToInt(right.value);
  822. else
  823. result = left.value.div(right.value);
  824. if(result.dp() > Config.decimalPlaces) {
  825. result = new Decimal(result.toFixed(Config.decimalPlaces));
  826. }
  827. return new StoreObject(resultType, result);
  828. }
  829. case Operators.MOD.ord: {
  830. result = left.value.modulo(right.value);
  831. if(result.dp() > Config.decimalPlaces) {
  832. result = new Decimal(result.toFixed(Config.decimalPlaces));
  833. }
  834. return new StoreObject(resultType, result);
  835. }
  836. case Operators.GT.ord: {
  837. if (Types.STRING.isCompatible(left.type)) {
  838. result = left.value.length > right.value.length;
  839. } else {
  840. result = left.value.gt(right.value);
  841. }
  842. return new StoreObject(resultType, result);
  843. }
  844. case Operators.GE.ord: {
  845. if (Types.STRING.isCompatible(left.type)) {
  846. result = left.value.length >= right.value.length;
  847. } else {
  848. result = left.value.gte(right.value);
  849. }
  850. return new StoreObject(resultType, result);
  851. }
  852. case Operators.LT.ord: {
  853. if (Types.STRING.isCompatible(left.type)) {
  854. result = left.value.length < right.value.length;
  855. } else {
  856. result = left.value.lt(right.value);
  857. }
  858. return new StoreObject(resultType, result);
  859. }
  860. case Operators.LE.ord: {
  861. if (Types.STRING.isCompatible(left.type)) {
  862. result = left.value.length <= right.value.length;
  863. } else {
  864. result = left.value.lte(right.value);
  865. }
  866. return new StoreObject(resultType, result);
  867. }
  868. case Operators.EQ.ord: {
  869. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  870. result = left.value.eq(right.value);
  871. } else {
  872. result = left.value === right.value;
  873. }
  874. return new StoreObject(resultType, result);
  875. }
  876. case Operators.NEQ.ord: {
  877. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  878. result = !left.value.eq(right.value);
  879. } else {
  880. result = left.value !== right.value;
  881. }
  882. return new StoreObject(resultType, result);
  883. }
  884. case Operators.AND.ord:
  885. return new StoreObject(resultType, left.value && right.value);
  886. case Operators.OR.ord:
  887. return new StoreObject(resultType, left.value || right.value);
  888. default:
  889. return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
  890. }
  891. });
  892. }
  893. parseStoreObjectValue (vl) {
  894. let realValue = vl;
  895. if(vl instanceof StoreObjectArrayAddress) {
  896. if(vl.type instanceof CompoundType) {
  897. switch(vl.type.dimensions) {
  898. case 1: {
  899. realValue = new StoreObjectArray(vl.type, vl.value);
  900. break;
  901. }
  902. default: {
  903. throw new RuntimeError("Three dimensional array address...");
  904. }
  905. }
  906. } else {
  907. realValue = new StoreObject(vl.type, vl.value);
  908. }
  909. }
  910. return realValue;
  911. }
  912. }