definedFunctions.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import * as Commands from './../ast/commands';
  2. import {Types, toInt, toString, toBool} from './../ast/types';
  3. import { LanguageService } from '../services/languageService';
  4. import { StoreObject } from './store/storeObject';
  5. function createOutputFun () {
  6. const writeFunction = function (store, _) {
  7. const val = store.applyStore('p1');
  8. this.output.sendOutput(''+val.value);
  9. return Promise.resolve(store);
  10. }
  11. const block = new Commands.CommandBlock([], [new Commands.SysCall(writeFunction)]);
  12. const func = new Commands.Function('$write', Types.VOID,
  13. [new Commands.FormalParameter(Types.ALL, 'p1', 0, false)],
  14. block);
  15. return func;
  16. }
  17. function createInputFun () {
  18. const readFunction = function (store, _) {
  19. const request = new Promise((resolve, _) => {
  20. this.input.requestInput(resolve);
  21. });
  22. return request.then(text => {
  23. const typeToConvert = store.applyStore('p1').type;
  24. let stoObj = null;
  25. if (typeToConvert === Types.INTEGER) {
  26. const val = toInt(text);
  27. stoObj = new StoreObject(Types.INTEGER, val);
  28. } else if (typeToConvert === Types.REAL) {
  29. stoObj = new StoreObject(Types.REAL, parseFloat(text));
  30. } else if (typeToConvert === Types.BOOLEAN) {
  31. stoObj = new StoreObject(Types.BOOLEAN, toBool(text));
  32. } else if (typeToConvert === Types.STRING) {
  33. stoObj = new StoreObject(Types.STRING, toString(text));
  34. }
  35. store.updateStore('p1', stoObj);
  36. return Promise.resolve(store);
  37. });
  38. }
  39. const block = new Commands.CommandBlock([], [new Commands.SysCall(readFunction)]);
  40. const func = new Commands.Function('$read', Types.VOID,
  41. [new Commands.FormalParameter(Types.ALL, 'p1', 0, true)],
  42. block);
  43. return func;
  44. }
  45. function valueToKey (value, object) {
  46. for (const key in object) {
  47. if(object.hasOwnProperty(key)){
  48. if (object[key] === value) {
  49. return key;
  50. }
  51. }
  52. }
  53. return null;
  54. }
  55. const funcsObject = {
  56. $read: createInputFun(),
  57. $write: createOutputFun()
  58. }
  59. export const LanguageDefinedFunction = Object.freeze({
  60. getMainFunctionName: () => LanguageService.getCurrentLangFuncs().main_function,
  61. getInternalName: (localName) => valueToKey(localName, LanguageService.getCurrentLangFuncs()),
  62. getFunction: (internalName) => funcsObject[internalName],
  63. });