parsers.js 2.2 KB

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