io.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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.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. store.updateStore('p1', stoObj);
  46. return Promise.resolve(store);
  47. });
  48. }
  49. const block = new Commands.CommandBlock([], [new Commands.SysCall(readFunction)]);
  50. const func = new Commands.Function('$read', Types.VOID,
  51. [new Commands.FormalParameter(Types.ALL, 'p1', true)],
  52. block);
  53. return func;
  54. }