javascriptregexparsingpeg

Callback from Peggy generated parser


I want to parse a string that is generated inside a class instance by calling a peggy generated parser. One of the parsing actions needs to invoke a function defined inside the class instance, so that I have access to the environment of that instance, including this. How can I make that happen?


Solution

  • You can set a "global-initializer" at the start of your grammar. You should be able to set up your environment there. From the docs:

    const parser = peggy.generate(`
    {
      // options are available in the per-parse initializer
      console.log(options.validWords);  // outputs "[ 'boo', 'baz', 'boop' ]"
    }
    
    validWord = @word:$[a-z]+ &{ return options.validWords.includes(word) }
    `);
    
    const result = parser.parse("boo", {
      validWords: [ "boo", "baz", "boop" ]
    });
    
    console.log(result);  // outputs "boo"