ConcreteSyntaxError.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (C) 2024 Puter Technologies Inc.
  3. *
  4. * This file is part of Phoenix Shell.
  5. *
  6. * Phoenix Shell is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published
  8. * by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * An error for which the location it occurred within the input is known.
  21. */
  22. export class ConcreteSyntaxError extends Error {
  23. constructor(message, cst_location) {
  24. super(message);
  25. this.cst_location = cst_location;
  26. }
  27. /**
  28. * Prints the location of the error in the input.
  29. *
  30. * Example output:
  31. *
  32. * ```
  33. * 1: echo $($(echo zxcv))
  34. * ^^^^^^^^^^^
  35. * ```
  36. *
  37. * @param {*} input
  38. */
  39. print_here (input) {
  40. const lines = input.split('\n');
  41. const line = lines[this.cst_location.line];
  42. const str_line_number = String(this.cst_location.line + 1) + ': ';
  43. const n_spaces =
  44. str_line_number.length +
  45. this.cst_location.start;
  46. const n_arrows = Math.max(
  47. this.cst_location.end - this.cst_location.start,
  48. 1
  49. );
  50. return (
  51. str_line_number + line + '\n' +
  52. ' '.repeat(n_spaces) + '^'.repeat(n_arrows)
  53. );
  54. }
  55. }