parsers.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. if (lexer.getReservedKeys()[lexer.getRules().RK_TRUE] === val) {
  40. return true;
  41. } else if (lexer.getReservedKeys()[lexer.getRules().RK_FALSE] === val) {
  42. return false;
  43. } else {
  44. // TODO: better error message
  45. throw new Error(str + "not a valid boolean");
  46. }
  47. }
  48. export function convertBoolToString (bool) {
  49. const lexer = LanguageService.getCurrentLexer();
  50. let result = null;
  51. if (bool) {
  52. result = lexer.getReservedKeys()[lexer.getRules().RK_TRUE];
  53. } else {
  54. result = lexer.getReservedKeys()[lexer.getRules().RK_FALSE];
  55. }
  56. //console.debug(result)
  57. return result.replace(/'/g, "");
  58. }
  59. export function convertToString (value, type) {
  60. switch (type.ord) {
  61. case Types.INTEGER.ord:
  62. return value.toString();
  63. case Types.REAL.ord: {
  64. if (value.dp() <= 0) {
  65. return value.toFixed(1);
  66. } else {
  67. return value.toFixed(Config.decimalPlaces);
  68. }
  69. }
  70. case Types.BOOLEAN.ord:
  71. return convertBoolToString(value);
  72. default:
  73. return value;
  74. }
  75. }