parsinglexflex-lexerlexical-analysis

Testing Current start-state in flex


I have a flex file with two rules that differ only in one line of code:

<STATE1>{SAME_REGEX} {
    same_code();
}

<STATE2>{SAME_REGEX} {
    same_code();
    one_extra_line();
}

Is there any way, for brevity and ease of maintenance (even if the same_code() part changes, they will always have that part the same), to combine these two, by testing current state with an if statement? for instance:

<STATE1,STATE2>{SAME_REGEX} {
    same_code();
    if(STATE2){
        one_extra_line();
    }
}

Solution

  • You're close. Listing several start states between < > is valid. To get the current state, you can call yy_top_state()

    <STATE1,STATE2>{SAME_REGEX} {
        same_code();
        if(yy_top_state() == STATE2){
            one_extra_line();
        }
    }