nearley icon indicating copy to clipboard operation
nearley copied to clipboard

Use nearley parser at front end, how to reset parser for new input

Open saincogt opened this issue 1 year ago • 1 comments

Hello,

I just started using nearley for a React side project. I would like to input text into an input field, and log the parse results:

const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));
...
const [value, setValue] = useState('');

const onChange = ({ target: { value }}) => {
  setValue(value);
  try {
    parser.feed(value);
    console.log(parser.results);
  } catch(e) {
    // error handling
  }
};

return <input value={value} onChange={onChange} />

Obviously it won't work - I understand nearley is a streaming parser - an input 'abc' from the user input will equivalently feeding 'aababc' to parser. There is a hack that always creating new instance of the parser inside the onChange function but its not I wanted.

FYI, parser.finish() does not work.

Is there a way to reset parser or any other workaround for this case?

Thank you very much!

saincogt avatar Apr 08 '23 04:04 saincogt

Do the following:

const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar))
const initialState = parser.save()
...
parser.feed(value)
// do something with the parsed result
parser.restore(initialState) // restore (or reset) parser to its initial state

Alternatively, you can just create a new parser.

TekuConcept avatar Mar 30 '24 19:03 TekuConcept