Search code examples
cparsingflex-lexer

What is the difference between BEGIN vs yy_push_state in Flex?


My intuition on what the names implied, as well as some observations, tells me that BEGIN simply starts a new state and destroys the whole state stack on hold, while yy_push_state push a new state into the state stack, so that later we can use yy_pop_state to get the caller state back.

Is my intuition correct?


Solution

  • It turns out the behavior is well-documented at here, I somehow ignored it when searching.

    My assumptions stated in question is half correct but half wrong.

    I am correct in that yy_push_state(int new_state) pushes the currently activated state into stack and activates the new_state. yy_pop_state() pop the state at the top of the stack then activate it. See the toy GDB test below:

    (gdb) p yy_push_state(0)
    $30 = void
    (gdb) p yy_push_state(1)
    $31 = void
    (gdb) p yy_push_state(2)
    $32 = void
    (gdb) p yy_push_state(3)
    $33 = void
    (gdb) p yy_top_state()
    $34 = 2
    (gdb) p yy_pop_state()
    $36 = void
    (gdb) p yy_top_state()
    $37 = 1
    

    I am wrong in that BEGIN has nothing to do with stack, it simply activate its argument. The stack is not affected by BEGIN whatsoever.

    #define BEGIN (yy_start) = 1 + 2 *