Search code examples
ccompiler-constructionflex-lexer

Flex not counting lines properly on multiline comments


I`m using the above regex to identify multiline comments in Flex:

[/][*][^*]*[*]+([^*/][^*]*[*]+)*[/]       { /* DO NOTHING */ }

But seems to me that flex/bison is not returning properly the line counter. For example:

Input:

1  ___bqmu7ftc
2 // _qXnFEgQL9Zsyn8Ohtx7zhToLK68xbu3XRrOvRi 
3 /* "{ output 6 = <=W if u7 do nN)T!=$||JN,a9vR)7" 
4  -758939 
5 -31943.6165480 
6 // "RND" 
7  '_' 
8 */
9 [br _int]

Output:

1 TK_IDENT [___bqmu7ftc]
4 [
4 TK_IDENT [br]
4 TK_IDENT [_int]
4 ]

The line should be 9 instead of 4.

Any ideas?


Solution

  • This is the solution I found on Flex manual

    Remember to declare int comment_caller; on your definition scope.

    %x comment 
    %x foo
    %%
    
    "/*" {comment_caller = INITIAL;
        BEGIN(comment);
          }
    
         <foo>"/*"  {
          comment_caller = foo;
          BEGIN(comment);
          }
    
         <comment>[^*\n]*    {}
         <comment>"*"+[^*/\n]*   {}
         <comment>\n       {++line_num;}
         <comment>"*"+"/"    BEGIN(comment_caller);