io.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { StoreObject } from './../store/storeObject';
  2. import * as Commands from './../../ast/commands';
  3. import {Types, toInt, toString, toBool, toReal} from './../../ast/types';
  4. export function createOutputFun () {
  5. const writeFunction = function (store, _) {
  6. const val = store.applyStore('p1');
  7. if(val.type === Types.INTEGER) {
  8. this.output.sendOutput(val.value.toString());
  9. } else if (val.type === Types.REAL) {
  10. if (val.value.dp() <= 0) {
  11. this.output.sendOutput(val.value.toFixed(1));
  12. } else {
  13. this.output.sendOutput(val.value.toString());
  14. }
  15. } else {
  16. this.output.sendOutput(val.value);
  17. }
  18. return Promise.resolve(store);
  19. }
  20. const block = new Commands.CommandBlock([], [new Commands.SysCall(writeFunction)]);
  21. const func = new Commands.Function('$write', Types.VOID,
  22. [new Commands.FormalParameter(Types.ALL, 'p1', 0, false)],
  23. block);
  24. return func;
  25. }
  26. export function createInputFun () {
  27. const readFunction = function (store, _) {
  28. const request = new Promise((resolve, _) => {
  29. this.input.requestInput(resolve);
  30. });
  31. return request.then(text => {
  32. const typeToConvert = store.applyStore('p1').type;
  33. let stoObj = null;
  34. if (typeToConvert === Types.INTEGER) {
  35. const val = toInt(text);
  36. stoObj = new StoreObject(Types.INTEGER, val);
  37. } else if (typeToConvert === Types.REAL) {
  38. stoObj = new StoreObject(Types.REAL, toReal(text));
  39. } else if (typeToConvert === Types.BOOLEAN) {
  40. stoObj = new StoreObject(Types.BOOLEAN, toBool(text));
  41. } else if (typeToConvert === Types.STRING) {
  42. stoObj = new StoreObject(Types.STRING, toString(text));
  43. }
  44. store.updateStore('p1', stoObj);
  45. return Promise.resolve(store);
  46. });
  47. }
  48. const block = new Commands.CommandBlock([], [new Commands.SysCall(readFunction)]);
  49. const func = new Commands.Function('$read', Types.VOID,
  50. [new Commands.FormalParameter(Types.ALL, 'p1', 0, true)],
  51. block);
  52. return func;
  53. }