Search code examples
cyacclex

How do I specify an input buffer to lex and yacc?


I have to create an Assembler, with lex and yacc but I have to give the input to lex from a c file, where I have my main function. But how do I do such thing?

I just have a buffer.

char *buffer;

But I want to know how I could pass that buffer to lex.

I just expect to give a buffer to lex from a "C" file. I want an example showing how to do so. Thanks.


Solution

  • Scanning from a buffer is pretty easy, but it's almost certainly not what you want to do.

    If you want to scan from a file, you simply open the file for reading, saving the value from the fopen call into yyin. Make sure that you check that the fopen succeeded, because if yyin ends up being NULL (which is what will happen if the fopen fails) then the scanner will read from stdin.

    You'll need to declare yyin, unless the part of your program which sets up in the input file is contained in the same translation unit as your scanner definition. The declaration is:

    extern FILE* yyin;
    

    If you really want to read from a single string in memory, you just call

    yy_scan_string(buffer);
    

    before you start scanning. (There is also a function which takes both a buffer address and a length, which you can use for inputs which are not NUL-terminated and possibly include NUL bytes:

    yy_scan_bytes(buffer, buflen);
    

    But the buffer you provide must be the entire input; you don't use this interface to read a file a line at a time. (There are ways to do that, but I really don't think that's what you're looking for. It's described in the Multiple Input Buffers section of the Flex manual if you're curious.)