Search code examples
flex-lexerlex

How to do initializing in Flex before any rules are executed?


My lexer rules rely on an array being populated. So, before any rules are executed, I need to initialize the array. I could use YY_USER_ACTION to do the initializing (check a global flag to see if it's not set, if so call the init function) but that would be very inefficient as it checks to see if the array is initialized for every rule. Is there a way in Flex to express: "Run this code before executing any rules."?


Solution

  • The macro YY_USER_INIT does exactly that. (You said you're using specifically Flex. Other Lex implementations may not support it.)

    You use it similarly to the mentioned YY_USER_ACTION.

    %code {
        void populateArray();
        #define YY_USER_INIT populateArray();
    %}
    
    %%
    
    // Rules
    
    %%
    
    void populateArray()
    {
        //...
    }