parsers.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { LanguageService } from "../services/languageService";
  2. import { Types } from "./types";
  3. import { BigNumber } from 'bignumber.js'
  4. export function toInt (str) {
  5. return new BigNumber(str);
  6. }
  7. export function toString (str) {
  8. let value = str.replace(/^"/, '');
  9. value = value.replace(/"$/, '');
  10. value = value.replace(/\\b/g, "\b");
  11. value = value.replace(/\\t/g, "\t");
  12. value = value.replace(/\\n/g, "\n");
  13. value = value.replace(/\\r/g, "\r");
  14. value = value.replace(/\\\"/g, "\"");
  15. value = value.replace(/\\\'/g, "\'");
  16. value = value.replace(/\\\\/g, "\\");
  17. return value;
  18. }
  19. export function toReal (value) {
  20. return new BigNumber(value);
  21. }
  22. export function toBool (str) {
  23. const val = "'" + str + "'";
  24. const lexer = LanguageService.getCurrentLexer();
  25. const instance = new lexer(null);
  26. if (instance.literalNames[lexer.RK_TRUE] === val) {
  27. return true;
  28. } else if (instance.literalNames[lexer.RK_FALSE] === val) {
  29. return false;
  30. } else {
  31. // TODO: better error message
  32. throw new Error(str + "not a valid boolean");
  33. }
  34. }
  35. function convertBoolToString (bool) {
  36. const lexer = LanguageService.getCurrentLexer();
  37. const instance = new lexer(null);
  38. if (bool) {
  39. return instance.literalNames[lexer.RK_TRUE];
  40. } else {
  41. return instance.literalNames[lexer.RK_FALSE];
  42. }
  43. }
  44. export function convertToString(stoObj, type) {
  45. switch (type.ord) {
  46. case Types.INTEGER.ord:
  47. return stoObj.toString();
  48. case Types.REAL.ord: {
  49. if (stoObj.dp() <= 0) {
  50. return stoObj.toFixed(1);
  51. } else {
  52. return stoObj.toNumber();
  53. }
  54. }
  55. case Types.BOOLEAN.ord:
  56. return convertBoolToString(stoObj);
  57. default:
  58. return stoObj;
  59. }
  60. }