parsers.js 1.8 KB

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