io.js 2.1 KB

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