Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
saincogt opened this issue Apr 8, 2023 · 1 comment
Open

Comments

@saincogt
Copy link

saincogt commented Apr 8, 2023

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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants