ParserBuilder.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 { SingleParserFactory } from "../parse.js";
  20. export class ParserConfigDSL extends SingleParserFactory {
  21. constructor (parserFactory, cls) {
  22. super();
  23. this.parserFactory = parserFactory;
  24. this.cls_ = cls;
  25. this.parseParams_ = {};
  26. this.grammarParams_ = {
  27. assign: {},
  28. };
  29. }
  30. parseParams (obj) {
  31. Object.assign(this.parseParams_, obj);
  32. return this;
  33. }
  34. assign (obj) {
  35. Object.assign(this.grammarParams_.assign, obj);
  36. return this;
  37. }
  38. create () {
  39. return this.parserFactory.create(
  40. this.cls_, this.parseParams_, this.grammarParams_,
  41. );
  42. }
  43. }
  44. export class ParserBuilder {
  45. constructor ({
  46. parserFactory,
  47. parserRegistry,
  48. }) {
  49. this.parserFactory = parserFactory;
  50. this.parserRegistry = parserRegistry;
  51. this.parserAPI_ = null;
  52. }
  53. get parserAPI () {
  54. if ( this.parserAPI_ ) return this.parserAPI_;
  55. const parserAPI = {};
  56. const parsers = this.parserRegistry.parsers;
  57. for ( const parserId in parsers ) {
  58. const parserCls = parsers[parserId];
  59. parserAPI[parserId] =
  60. this.createParserFunction(parserCls);
  61. }
  62. return this.parserAPI_ = parserAPI;
  63. }
  64. createParserFunction (parserCls) {
  65. if ( parserCls.hasOwnProperty('createFunction') ) {
  66. return parserCls.createFunction({
  67. parserFactory: this.parserFactory
  68. });
  69. }
  70. return params => {
  71. const configDSL = new ParserConfigDSL(parserCls)
  72. configDSL.parseParams(params);
  73. return configDSL;
  74. };
  75. }
  76. def (def) {
  77. const a = this.parserAPI;
  78. return def(a);
  79. }
  80. }