1
0

ivprogProcessor.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. import { Store } from './store/store';
  2. import { StoreObject } from './store/storeObject';
  3. import { StoreObjectArray } from './store/storeObjectArray';
  4. import { StoreObjectRef } from './store/storeObjectRef';
  5. import { Modes } from './modes';
  6. import { Context } from './context';
  7. import { Types } from './../typeSystem/types';
  8. import { Operators } from './../ast/operators';
  9. import { LanguageDefinedFunction } from './definedFunctions';
  10. import { resultTypeAfterInfixOp, resultTypeAfterUnaryOp } from './compatibilityTable';
  11. import * as Commands from './../ast/commands/';
  12. import * as Expressions from './../ast/expressions/';
  13. import { StoreObjectArrayAddress } from './store/storeObjectArrayAddress';
  14. import { StoreObjectArrayAddressRef } from './store/storeObjectArrayAddressRef';
  15. import { CompoundType } from './../typeSystem/compoundType';
  16. import { convertToString } from '../typeSystem/parsers';
  17. import { Config } from '../util/config';
  18. import Decimal from 'decimal.js';
  19. import { ProcessorErrorFactory } from './error/processorErrorFactory';
  20. import { RuntimeError } from './error/runtimeError';
  21. export class IVProgProcessor {
  22. static get LOOP_TIMEOUT () {
  23. return Config.loopTimeout;
  24. }
  25. static set LOOP_TIMEOUT (ms) {
  26. Config.setConfig({loopTimeout: ms});
  27. }
  28. static get MAIN_INTERNAL_ID () {
  29. return "$main";
  30. }
  31. constructor (ast) {
  32. this.ast = ast;
  33. this.globalStore = new Store("$global");
  34. this.stores = [this.globalStore];
  35. this.context = [Context.BASE];
  36. this.input = null;
  37. this.forceKill = false;
  38. this.loopTimers = [];
  39. this.output = null;
  40. }
  41. registerInput (input) {
  42. if(this.input !== null)
  43. this.input = null;
  44. this.input = input;
  45. }
  46. registerOutput (output) {
  47. if(this.output !== null)
  48. this.output = null;
  49. this.output = output;
  50. }
  51. checkContext(context) {
  52. return this.context[this.context.length - 1] === context;
  53. }
  54. ignoreSwitchCases (store) {
  55. if (store.mode === Modes.RETURN) {
  56. return true;
  57. } else if (store.mode === Modes.BREAK) {
  58. return true;
  59. } else {
  60. return false;
  61. }
  62. }
  63. prepareState () {
  64. if(this.stores !== null) {
  65. for (let i = 0; i < this.stores.length; i++) {
  66. delete this.stores[i];
  67. }
  68. this.stores = null;
  69. }
  70. if(this.globalStore !== null)
  71. this.globalStore = null;
  72. this.globalStore = new Store("$global");
  73. this.stores = [this.globalStore];
  74. this.context = [Context.BASE];
  75. }
  76. interpretAST () {
  77. this.prepareState();
  78. return this.initGlobal().then( _ => {
  79. const mainFunc = this.findMainFunction();
  80. if(mainFunc === null) {
  81. throw ProcessorErrorFactory.main_missing();
  82. }
  83. return this.runFunction(mainFunc, [], this.globalStore);
  84. });
  85. }
  86. initGlobal () {
  87. if(!this.checkContext(Context.BASE)) {
  88. throw ProcessorErrorFactory.invalid_global_var();
  89. }
  90. return this.executeCommands(this.globalStore, this.ast.global);
  91. }
  92. findMainFunction () {
  93. return this.ast.functions.find(v => v.isMain);
  94. }
  95. findFunction (name) {
  96. if(name.match(/^\$.+$/)) {
  97. const fun = LanguageDefinedFunction.getFunction(name);
  98. if(!!!fun) {
  99. throw ProcessorErrorFactory.not_implemented(name);
  100. }
  101. return fun;
  102. } else {
  103. const val = this.ast.functions.find( v => v.name === name);
  104. if (!!!val) {
  105. // 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. //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.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.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. return Promise.resolve(store);
  416. }
  417. if (vl === null || !funcType.isCompatible(vl.type)) {
  418. const stringInfo = funcType.stringInfo();
  419. const info = stringInfo[0];
  420. return Promise.reject(ProcessorErrorFactory.invalid_return_type_full(funcName, info.type, info.dim, cmd.sourceInfo));
  421. } else {
  422. let realValue = this.parseStoreObjectValue(vl);
  423. store.updateStore('$', realValue);
  424. store.mode = Modes.RETURN;
  425. return Promise.resolve(store);
  426. }
  427. });
  428. } catch (error) {
  429. return Promise.reject(error);
  430. }
  431. }
  432. executeBreak (store, cmd) {
  433. if(this.checkContext(Context.BREAKABLE)) {
  434. store.mode = Modes.BREAK;
  435. return Promise.resolve(store);
  436. } else {
  437. return Promise.reject(ProcessorErrorFactory.unexpected_break_command_full(cmd.sourceInfo));
  438. }
  439. }
  440. executeAssign (store, cmd) {
  441. try {
  442. const $value = this.evaluateExpression(store, cmd.expression);
  443. return $value.then( vl => {
  444. let realValue = this.parseStoreObjectValue(vl);
  445. store.updateStore(cmd.id, realValue)
  446. return store;
  447. });
  448. } catch (error) {
  449. return Promise.reject(error);
  450. }
  451. }
  452. executeArrayIndexAssign (store, cmd) {
  453. const mustBeArray = store.applyStore(cmd.id);
  454. if(!(mustBeArray.type instanceof CompoundType)) {
  455. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(cmd.id, cmd.sourceInfo));
  456. }
  457. const line$ = this.evaluateExpression(store, cmd.line);
  458. const column$ = this.evaluateExpression(store, cmd.column);
  459. const value$ = this.evaluateExpression(store, cmd.expression);
  460. return Promise.all([line$, column$, value$]).then(results => {
  461. const lineSO = results[0];
  462. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  463. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  464. }
  465. const line = lineSO.number;
  466. const columnSO = results[1];
  467. let column = null
  468. if (columnSO !== null) {
  469. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  470. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  471. }
  472. column = columnSO.number;
  473. }
  474. const value = this.parseStoreObjectValue(results[2]);
  475. if (line >= mustBeArray.lines) {
  476. if(mustBeArray.isVector) {
  477. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  478. } else {
  479. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(cmd.id, line, mustBeArray.lines, cmd.sourceInfo));
  480. }
  481. } else if (line < 0) {
  482. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  483. }
  484. if (column !== null && mustBeArray.columns === null ){
  485. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(cmd.id, cmd.sourceInfo));
  486. }
  487. if(column !== null ) {
  488. if (column >= mustBeArray.columns) {
  489. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(cmd.id, column,mustBeArray.columns, cmd.sourceInfo));
  490. } else if (column < 0) {
  491. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  492. }
  493. }
  494. const newArray = Object.assign(new StoreObjectArray(null,null,null), mustBeArray);
  495. if (column !== null) {
  496. if (value.type instanceof CompoundType) {
  497. const type = mustBeArray.type.innerType;
  498. const stringInfo = type.stringInfo()
  499. const info = stringInfo[0]
  500. return Promise.reject(ProcessorErrorFactory.incompatible_types_full(info.type, info.dim, cmd.sourceInfo));
  501. }
  502. newArray.value[line].value[column] = value;
  503. store.updateStore(cmd.id, newArray);
  504. } else {
  505. if(mustBeArray.columns !== null && value.type instanceof CompoundType) {
  506. const type = mustBeArray.type;
  507. const stringInfo = type.stringInfo()
  508. const info = stringInfo[0]
  509. const exp = cmd.expression.toString()
  510. return Promise.reject(ProcessorErrorFactory.incompatible_types_array_full(exp,info.type, info.dim-1, cmd.sourceInfo));
  511. }
  512. newArray.value[line] = value;
  513. store.updateStore(cmd.id, newArray);
  514. }
  515. return store;
  516. });
  517. }
  518. executeDeclaration (store, cmd) {
  519. try {
  520. const $value = this.evaluateExpression(store, cmd.initial);
  521. if(cmd instanceof Commands.ArrayDeclaration) {
  522. const $lines = this.evaluateExpression(store, cmd.lines);
  523. const $columns = cmd.columns === null ? null: this.evaluateExpression(store, cmd.columns);
  524. return Promise.all([$lines, $columns, $value]).then(values => {
  525. const lineSO = values[0];
  526. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  527. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  528. }
  529. const line = lineSO.number;
  530. if(line < 0) {
  531. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  532. }
  533. const columnSO = values[1];
  534. let column = null
  535. if (columnSO !== null) {
  536. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  537. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(cmd.sourceInfo));
  538. }
  539. column = columnSO.number;
  540. if(column < 0) {
  541. throw ProcessorErrorFactory.array_dimension_not_positive_full(cmd.sourceInfo);
  542. }
  543. }
  544. const value = values[2];
  545. const temp = new StoreObjectArray(cmd.type, line, column, null);
  546. store.insertStore(cmd.id, temp);
  547. let realValue = value;
  548. if (value !== null) {
  549. if(value instanceof StoreObjectArrayAddress) {
  550. if(value.type instanceof CompoundType) {
  551. realValue = Object.assign(new StoreObjectArray(null,null,null), value.refValue);
  552. } else {
  553. realValue = Object.assign(new StoreObject(null,null), value.refValue);
  554. }
  555. }
  556. } else {
  557. realValue = new StoreObjectArray(cmd.type, line, column, [])
  558. if(column !== null) {
  559. for (let i = 0; i < line; i++) {
  560. realValue.value.push(new StoreObjectArray(new CompoundType(cmd.type.innerType, 1), column, null, []));
  561. }
  562. }
  563. }
  564. realValue.readOnly = cmd.isConst;
  565. store.updateStore(cmd.id, realValue);
  566. return store;
  567. });
  568. } else {
  569. const temp = new StoreObject(cmd.type, null);
  570. store.insertStore(cmd.id, temp);
  571. return $value.then(vl => {
  572. let realValue = vl;
  573. if (vl !== null) {
  574. if(vl instanceof StoreObjectArrayAddress) {
  575. if(vl.type instanceof CompoundType) {
  576. realValue = Object.assign(new StoreObjectArray(null,null,null), vl.refValue);
  577. } else {
  578. realValue = Object.assign(new StoreObject(null,null), vl.refValue);
  579. }
  580. }
  581. } else {
  582. realValue = new StoreObject(cmd.type,0);
  583. }
  584. realValue.readOnly = cmd.isConst;
  585. store.updateStore(cmd.id, realValue);
  586. return store;
  587. });
  588. }
  589. } catch (e) {
  590. return Promise.reject(e);
  591. }
  592. }
  593. evaluateExpression (store, exp) {
  594. if (exp instanceof Expressions.UnaryApp) {
  595. return this.evaluateUnaryApp(store, exp);
  596. } else if (exp instanceof Expressions.InfixApp) {
  597. return this.evaluateInfixApp(store, exp);
  598. } else if (exp instanceof Expressions.ArrayAccess) {
  599. return this.evaluateArrayAccess(store, exp);
  600. } else if (exp instanceof Expressions.VariableLiteral) {
  601. return this.evaluateVariableLiteral(store, exp);
  602. } else if (exp instanceof Expressions.IntLiteral) {
  603. return this.evaluateLiteral(store, exp);
  604. } else if (exp instanceof Expressions.RealLiteral) {
  605. return this.evaluateLiteral(store, exp);
  606. } else if (exp instanceof Expressions.BoolLiteral) {
  607. return this.evaluateLiteral(store, exp);
  608. } else if (exp instanceof Expressions.StringLiteral) {
  609. return this.evaluateLiteral(store, exp);
  610. } else if (exp instanceof Expressions.ArrayLiteral) {
  611. return this.evaluateArrayLiteral(store, exp);
  612. } else if (exp instanceof Expressions.FunctionCall) {
  613. return this.evaluateFunctionCall(store, exp);
  614. }
  615. return Promise.resolve(null);
  616. }
  617. evaluateFunctionCall (store, exp) {
  618. if(exp.isMainCall) {
  619. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(LanguageDefinedFunction.getMainFunctionName(), exp.sourceInfo));
  620. }
  621. const func = this.findFunction(exp.id);
  622. if(Types.VOID.isCompatible(func.returnType)) {
  623. // TODO: better error message
  624. return Promise.reject(ProcessorErrorFactory.void_in_expression_full(exp.id, exp.sourceInfo));
  625. }
  626. const $newStore = this.runFunction(func, exp.actualParameters, store);
  627. return $newStore.then( sto => {
  628. if(sto.mode !== Modes.RETURN) {
  629. return Promise.reject(new Error("The function that was called did not had a return command: "+exp.id));
  630. }
  631. const val = sto.applyStore('$');
  632. if (val instanceof StoreObjectArray) {
  633. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null,null), val));
  634. } else {
  635. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  636. }
  637. });
  638. }
  639. evaluateArrayLiteral (store, exp) {
  640. const errorHelperFunction = (validationResult, exp) => {
  641. const errorCode = validationResult[0];
  642. switch(errorCode) {
  643. case StoreObjectArray.WRONG_COLUMN_NUMBER: {
  644. const columnValue = validationResult[1];
  645. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_column_full(arr.columns, columnValue, exp.sourceInfo));
  646. }
  647. case StoreObjectArray.WRONG_LINE_NUMBER: {
  648. const lineValue = validationResult[1];
  649. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_line_full(arr.lines, lineValue, exp.sourceInfo));
  650. }
  651. case StoreObjectArray.WRONG_TYPE: {
  652. let line = null;
  653. let strExp = null;
  654. if (validationResult.length > 2) {
  655. line = validationResult[1];
  656. const column = validationResult[2];
  657. strExp = exp.value[line].value[column].toString()
  658. } else {
  659. line = validationResult[1];
  660. strExp = exp.value[line].toString()
  661. }
  662. return Promise.reject(ProcessorErrorFactory.invalid_array_literal_type_full(strExp, exp.sourceInfo)); }
  663. }
  664. };
  665. if(!exp.isVector) {
  666. const $matrix = this.evaluateMatrix(store, exp.value);
  667. return $matrix.then(list => {
  668. const type = new CompoundType(list[0].type.innerType, 2);
  669. const arr = new StoreObjectArray(type, list.length, list[0].lines, list);
  670. const checkResult = arr.isValid;
  671. if(checkResult.length == 0)
  672. return Promise.resolve(arr);
  673. else {
  674. return errorHelperFunction(checkResult, exp);
  675. }
  676. });
  677. } else {
  678. return this.evaluateVector(store, exp.value).then(list => {
  679. const type = new CompoundType(list[0].type, 1);
  680. const stoArray = new StoreObjectArray(type, list.length, null, list);
  681. const checkResult = stoArray.isValid;
  682. if(checkResult.length == 0)
  683. return Promise.resolve(stoArray);
  684. else {
  685. return errorHelperFunction(checkResult, exp);
  686. }
  687. });
  688. }
  689. }
  690. evaluateVector (store, exps) {
  691. return Promise.all(exps.map( exp => this.evaluateExpression(store, exp)));
  692. }
  693. evaluateMatrix (store, exps) {
  694. return Promise.all(exps.map( vector => {
  695. const $vector = this.evaluateVector(store, vector.value)
  696. return $vector.then(list => {
  697. const type = new CompoundType(list[0].type, 1);
  698. return new StoreObjectArray(type, list.length, null, list)
  699. });
  700. } ));
  701. }
  702. evaluateLiteral (_, exp) {
  703. return Promise.resolve(new StoreObject(exp.type, exp.value));
  704. }
  705. evaluateVariableLiteral (store, exp) {
  706. try {
  707. const val = store.applyStore(exp.id);
  708. if (val instanceof StoreObjectArray) {
  709. return Promise.resolve(Object.assign(new StoreObjectArray(null,null,null,null), val));
  710. } else {
  711. return Promise.resolve(Object.assign(new StoreObject(null,null), val));
  712. }
  713. } catch (error) {
  714. return Promise.reject(error);
  715. }
  716. }
  717. evaluateArrayAccess (store, exp) {
  718. const mustBeArray = store.applyStore(exp.id);
  719. if (!(mustBeArray.type instanceof CompoundType)) {
  720. return Promise.reject(ProcessorErrorFactory.invalid_array_access_full(exp.id, exp.sourceInfo));
  721. }
  722. const $line = this.evaluateExpression(store, exp.line);
  723. const $column = this.evaluateExpression(store, exp.column);
  724. return Promise.all([$line, $column]).then(values => {
  725. const lineSO = values[0];
  726. const columnSO = values[1];
  727. if(!Types.INTEGER.isCompatible(lineSO.type)) {
  728. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  729. }
  730. const line = lineSO.number;
  731. let column = null;
  732. if(columnSO !== null) {
  733. if(!Types.INTEGER.isCompatible(columnSO.type)) {
  734. return Promise.reject(ProcessorErrorFactory.array_dimension_not_int_full(exp.sourceInfo));
  735. }
  736. column = columnSO.number;
  737. }
  738. if (line >= mustBeArray.lines) {
  739. if(mustBeArray.isVector) {
  740. return Promise.reject(ProcessorErrorFactory.vector_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  741. } else {
  742. return Promise.reject(ProcessorErrorFactory.matrix_line_outbounds_full(exp.id, line, mustBeArray.lines, exp.sourceInfo));
  743. }
  744. } else if (line < 0) {
  745. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  746. }
  747. if (column !== null && mustBeArray.columns === null ){
  748. return Promise.reject(ProcessorErrorFactory.vector_not_matrix_full(exp.id, exp.sourceInfo));
  749. }
  750. if(column !== null ) {
  751. if (column >= mustBeArray.columns) {
  752. return Promise.reject(ProcessorErrorFactory.matrix_column_outbounds_full(exp.id, column,mustBeArray.columns, exp.sourceInfo));
  753. } else if (column < 0) {
  754. throw ProcessorErrorFactory.array_dimension_not_positive_full(exp.sourceInfo);
  755. }
  756. }
  757. return Promise.resolve(new StoreObjectArrayAddress(mustBeArray.id, line, column, store));
  758. });
  759. }
  760. evaluateUnaryApp (store, unaryApp) {
  761. const $left = this.evaluateExpression(store, unaryApp.left);
  762. return $left.then( left => {
  763. const resultType = resultTypeAfterUnaryOp(unaryApp.op, left.type);
  764. if (Types.UNDEFINED.isCompatible(resultType)) {
  765. const stringInfo = left.type.stringInfo();
  766. const info = stringInfo[0];
  767. return Promise.reject(ProcessorErrorFactory.invalid_unary_op_full(unaryApp.op, info.type, info.dim, unaryApp.sourceInfo));
  768. }
  769. switch (unaryApp.op.ord) {
  770. case Operators.ADD.ord:
  771. return new StoreObject(resultType, left.value);
  772. case Operators.SUB.ord:
  773. return new StoreObject(resultType, left.value.negated());
  774. case Operators.NOT.ord:
  775. return new StoreObject(resultType, !left.value);
  776. default:
  777. return Promise.reject(new RuntimeError('!!!Critical Invalid UnaryApp '+ unaryApp.op));
  778. }
  779. });
  780. }
  781. evaluateInfixApp (store, infixApp) {
  782. const $left = this.evaluateExpression(store, infixApp.left);
  783. const $right = this.evaluateExpression(store, infixApp.right);
  784. return Promise.all([$left, $right]).then(values => {
  785. const left = values[0];
  786. const right = values[1];
  787. const resultType = resultTypeAfterInfixOp(infixApp.op, left.type, right.type);
  788. if (Types.UNDEFINED.isCompatible(resultType)) {
  789. const stringInfoLeft = left.type.stringInfo();
  790. const infoLeft = stringInfoLeft[0];
  791. const stringInfoRight = right.type.stringInfo();
  792. const infoRight = stringInfoRight[0];
  793. return Promise.reject(ProcessorErrorFactory.invalid_infix_op_full(infixApp.op, infoLeft.type, infoLeft.dim,
  794. infoRight.type,infoRight.dim,infixApp.sourceInfo));
  795. }
  796. let result = null;
  797. switch (infixApp.op.ord) {
  798. case Operators.ADD.ord: {
  799. if(Types.STRING.isCompatible(left.type)) {
  800. const rightStr = convertToString(right.value, right.type);
  801. return new StoreObject(resultType, left.value + rightStr);
  802. } else if (Types.STRING.isCompatible(right.type)) {
  803. const leftStr = convertToString(left.value, left.type);
  804. return new StoreObject(resultType, leftStr + right.value);
  805. } else {
  806. return new StoreObject(resultType, left.value.plus(right.value));
  807. }
  808. }
  809. case Operators.SUB.ord:
  810. return new StoreObject(resultType, left.value.minus(right.value));
  811. case Operators.MULT.ord: {
  812. result = left.value.times(right.value);
  813. if(result.dp() > Config.decimalPlaces) {
  814. result = new Decimal(result.toFixed(Config.decimalPlaces));
  815. }
  816. return new StoreObject(resultType, result);
  817. }
  818. case Operators.DIV.ord: {
  819. if (Types.INTEGER.isCompatible(resultType))
  820. result = left.value.divToInt(right.value);
  821. else
  822. result = left.value.div(right.value);
  823. if(result.dp() > Config.decimalPlaces) {
  824. result = new Decimal(result.toFixed(Config.decimalPlaces));
  825. }
  826. return new StoreObject(resultType, result);
  827. }
  828. case Operators.MOD.ord: {
  829. result = left.value.modulo(right.value);
  830. if(result.dp() > Config.decimalPlaces) {
  831. result = new Decimal(result.toFixed(Config.decimalPlaces));
  832. }
  833. return new StoreObject(resultType, result);
  834. }
  835. case Operators.GT.ord: {
  836. if (Types.STRING.isCompatible(left.type)) {
  837. result = left.value.length > right.value.length;
  838. } else {
  839. result = left.value.gt(right.value);
  840. }
  841. return new StoreObject(resultType, result);
  842. }
  843. case Operators.GE.ord: {
  844. if (Types.STRING.isCompatible(left.type)) {
  845. result = left.value.length >= right.value.length;
  846. } else {
  847. result = left.value.gte(right.value);
  848. }
  849. return new StoreObject(resultType, result);
  850. }
  851. case Operators.LT.ord: {
  852. if (Types.STRING.isCompatible(left.type)) {
  853. result = left.value.length < right.value.length;
  854. } else {
  855. result = left.value.lt(right.value);
  856. }
  857. return new StoreObject(resultType, result);
  858. }
  859. case Operators.LE.ord: {
  860. if (Types.STRING.isCompatible(left.type)) {
  861. result = left.value.length <= right.value.length;
  862. } else {
  863. result = left.value.lte(right.value);
  864. }
  865. return new StoreObject(resultType, result);
  866. }
  867. case Operators.EQ.ord: {
  868. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  869. result = left.value.eq(right.value);
  870. } else {
  871. result = left.value === right.value;
  872. }
  873. return new StoreObject(resultType, result);
  874. }
  875. case Operators.NEQ.ord: {
  876. if (Types.INTEGER.isCompatible(left.type) || Types.REAL.isCompatible(left.type)) {
  877. result = !left.value.eq(right.value);
  878. } else {
  879. result = left.value !== right.value;
  880. }
  881. return new StoreObject(resultType, result);
  882. }
  883. case Operators.AND.ord:
  884. return new StoreObject(resultType, left.value && right.value);
  885. case Operators.OR.ord:
  886. return new StoreObject(resultType, left.value || right.value);
  887. default:
  888. return Promise.reject(new RuntimeError('!!!Critical Invalid InfixApp '+ infixApp.op));
  889. }
  890. });
  891. }
  892. parseStoreObjectValue (vl) {
  893. let realValue = vl;
  894. if(vl instanceof StoreObjectArrayAddress) {
  895. if(vl.type instanceof CompoundType) {
  896. switch(vl.type.dimensions) {
  897. case 1: {
  898. realValue = new StoreObjectArray(vl.type, vl.value);
  899. break;
  900. }
  901. default: {
  902. throw new RuntimeError("Three dimensional array address...");
  903. }
  904. }
  905. } else {
  906. realValue = new StoreObject(vl.type, vl.value);
  907. }
  908. }
  909. return realValue;
  910. }
  911. }