parsers.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { LanguageService } from "../services/languageService";
  2. import { Types } from "./types";
  3. import Decimal from "decimal.js";
  4. export function toInt (str) {
  5. return new Decimal(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 Decimal(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. export function convertBoolToString (bool) {
  36. const lexer = LanguageService.getCurrentLexer();
  37. const instance = new lexer(null);
  38. let result = null;
  39. if (bool) {
  40. result = instance.literalNames[lexer.RK_TRUE];
  41. } else {
  42. result = instance.literalNames[lexer.RK_FALSE];
  43. }
  44. return result.replace(/'/g,"");
  45. }
  46. export function convertToString(value, type) {
  47. switch (type.ord) {
  48. case Types.INTEGER.ord:
  49. return value.toString();
  50. case Types.REAL.ord: {
  51. if (value.dp() <= 0) {
  52. return value.toFixed(1);
  53. } else {
  54. return value.toNumber();
  55. }
  56. }
  57. case Types.BOOLEAN.ord:
  58. return convertBoolToString(value);
  59. default:
  60. return value;
  61. }
  62. }