kach / nearley

📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
https://nearley.js.org
MIT License
3.57k stars 231 forks source link

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

Open saincogt opened 1 year ago

saincogt commented 1 year ago

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!

TekuConcept commented 3 months ago

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.