parsers.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 toChar (str) {
  21. let value = str.replace(/^'/, '');
  22. value = value.replace(/'$/, '');
  23. return value;
  24. }
  25. export function toReal (value) {
  26. return new Decimal(value);
  27. }
  28. export function toBool (str) {
  29. const val = "'" + str + "'";
  30. const lexer = LanguageService.getCurrentLexer();
  31. const instance = new lexer(null);
  32. if (instance.literalNames[lexer.RK_TRUE] === val) {
  33. return true;
  34. } else if (instance.literalNames[lexer.RK_FALSE] === val) {
  35. return false;
  36. } else {
  37. // TODO: better error message
  38. throw new Error(str + "not a valid boolean");
  39. }
  40. }
  41. export function convertBoolToString (bool) {
  42. const lexer = LanguageService.getCurrentLexer();
  43. const instance = new lexer(null);
  44. let result = null;
  45. if (bool) {
  46. result = instance.literalNames[lexer.RK_TRUE];
  47. } else {
  48. result = instance.literalNames[lexer.RK_FALSE];
  49. }
  50. return result.replace(/'/g,"");
  51. }
  52. export function convertToString(value, type) {
  53. switch (type.ord) {
  54. case Types.INTEGER.ord:
  55. return value.toString();
  56. case Types.REAL.ord: {
  57. if (value.dp() <= 0) {
  58. return value.toFixed(1);
  59. } else {
  60. return value.toFixed(Config.decimalPlaces);
  61. }
  62. }
  63. case Types.BOOLEAN.ord:
  64. return convertBoolToString(value);
  65. default:
  66. return value;
  67. }
  68. }