literal.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. import { ParserConfigDSL } from "../dsl/ParserBuilder.js";
  20. const encoder = new TextEncoder();
  21. const decoder = new TextDecoder();
  22. export default class LiteralParserImpl {
  23. static meta = {
  24. inputs: 'bytes',
  25. outputs: 'node'
  26. }
  27. static createFunction ({ parserFactory }) {
  28. return (value) => {
  29. const conf = new ParserConfigDSL(parserFactory, this);
  30. conf.parseParams({ value });
  31. return conf;
  32. };
  33. }
  34. constructor ({ value }) {
  35. // adapt value
  36. if ( typeof value === 'string' ) {
  37. value = encoder.encode(value);
  38. }
  39. if ( value.length === 0 ) {
  40. throw new Error(
  41. 'tried to construct a LiteralParser with an ' +
  42. 'empty value, which could cause infinite ' +
  43. 'iteration'
  44. );
  45. }
  46. this.value = value;
  47. }
  48. parse (lexer) {
  49. for ( let i=0 ; i < this.value.length ; i++ ) {
  50. let { done, value } = lexer.next();
  51. if ( done ) return;
  52. if ( this.value[i] !== value ) return;
  53. }
  54. const text = decoder.decode(this.value);
  55. return { $: 'literal', text };
  56. }
  57. }