1
0

parsers.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. function convertBoolToString (bool) {
  36. const lexer = LanguageService.getCurrentLexer();
  37. const instance = new lexer(null);
  38. if (bool) {
  39. return instance.literalNames[lexer.RK_TRUE];
  40. } else {
  41. return instance.literalNames[lexer.RK_FALSE];
  42. }
  43. }
  44. export function canImplicitTypeCast (castType, sourceType) {
  45. if (castType.isCompatible(Types.INTEGER) || castType.isCompatible(Types.REAL)) {
  46. if (sourceType.isCompatible(Types.INTEGER) || sourceType.isCompatible(Types.REAL)) {
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52. export function convertToString(stoObj, type) {
  53. switch (type.ord) {
  54. case Types.INTEGER.ord:
  55. return stoObj.toString();
  56. case Types.REAL.ord: {
  57. if (stoObj.dp() <= 0) {
  58. return stoObj.toFixed(1);
  59. } else {
  60. return stoObj.toNumber();
  61. }
  62. }
  63. case Types.BOOLEAN.ord:
  64. return convertBoolToString(stoObj);
  65. default:
  66. return stoObj;
  67. }
  68. }