开发者

flex, defining char

开发者 https://www.devze.com 2022-12-11 13:46 出处:网络
I want to define char (ie \'a AND \'a\') but I am having issues in checking errors. Here how I write the rule and check:

I want to define char (ie 'a AND 'a') but I am having issues in checking errors. Here how I write the rule and check:

char         " ' " {letter}

code

{char}    {
          int x =input() ;
          //printf("%d",'a');

                if(x == 10)
                {
                    return(tCharunterm);
                }
                else if(x == '\'')
                {
                    return(tChar);
                }
                else
                {
                    yyerror("char overflow");
                }

And finally checking it:

'a
token = tCharunterm, value = "(null)"
'a'  
token = tChar开发者_StackOverflow社区, value = "(null)"
'as
char overflow
'asddd
char overflow
token = tIdentifier, value = "ddd"
^Z


Generally, you NEVER want to call 'input' directly in your flex code -- that's the routine flex uses to get more input, so if you call it, you're pulling in random characters out of the middle of the input and confusing flex into thinking they don't exist. The best way to do this is to define multiple rules and rely on the longest match to get the right one.

"'"{letter}"'"  { return(tChar); }
"'"{letter}"\n" { return(tCharunterm); }
"'"{letter}     { yyerror("char overflow"); return(rCharunterm); }

you might also want yylval.ch = yytext[1]; in these rules to return the actual character value you've matched.

0

精彩评论

暂无评论...
验证码 换一张
取 消