adMartem
Most likely the real solution to your problem is to move the lexical state switch logic from the lexer to the parser. Did you ever come across this essay, I wonder? https://javacc.com/2021/01/24/context-sensitive-lexical-states/
That is from well over a year ago, but the funny (not ha-ha funny) is that it wasn't really working properly when I wrote that. At least not fully. There were various glitches that I nailed when I finally needed this stuff doing the Csharp grammar about a year later! As you might be aware, that CSharp is one nasty grammar to write, what with interpolated strings and stuff like that. Actually, I don't think that legacy JavaCC is powerful enough to write a decent CSharp grammar.
It could be useful to make some study of how the CSharp grammar I wrote deals with some of this stuff. In particular, just look at https://github.com/javacc21/javacc21/blob/master/examples/csharp/CSharp.javacc#L2255 until the end of the file, the various uses of the LEXICAL_STATE
directive there. By the way, the last two productions in the grammar are written differently, mostly just to have a certain bit more test coverage.
But I guess the essence might be that if you have a production that is considered to take place in a given lexical state, like the ubiquitous FOO
, let's say, you could have:
SomeProduction : FOO : blah blah ;
So we say that SomeProduction is in the FOO
lexical state, then
SCAN SomeProduction => DoSomething
should handle most of the housekeeping because it switches into FOO
and out of FOO
transparently, and thus, handle the messy details or banana peels you're tripping up on. (It should, but this is one of the less tested parts of the code base, so you could do the project some good by really putting it to a stringent use test.) But anyway, if you study the final 40-odd lines of the CSharp grammar, you might find some ideas for handling this elegantly. Or you could wait until, one of these years, this lexical state machinery stuff is properly documented in a proper manual.... (Well, we are working on that sort of thing, but...)