r/cprogramming • u/gumnos • 47m ago
[lex/yacc] portability of jockeying yyin mid-parsing and potential concerns?
Working with a file-format that has include directives (effectively inlining the referenced file), my plan has been to have lex push/pop the top FILE* into a stack, open the included-file, set it to yyin to that new FILE*, continue lexing based on that new file (effectively recursing into any included files there), then close the included file, pop the original file's FILE* off the stack, and resume where it left off.
However, I have concerns whether monkeying with yyin like this is something that can be done portably, especially if lex implementations buffer the content read from the file (meaning that changing the yyin might not impact the next characters/tokens because they're already buffered, meaning lex sees the buffered next tokens from the first file rather than the tokens from the new/included file, which I understand flex might do). Similarly pushing items back (ungetc()/unput()) after an include directive might result in enqueuing a character from the including-file where I really want the next characters to come from the included-file.
Are there best practices for reliably switching the input streams provided to lex?
FWIW, the dev environment is FreeBSD/OpenBDS with their implementations of lex, not GNU flex out of the gate.