Lex

时间:2018-09-13 05:54:31

标签: compiler-construction lex

我有一个编码作业,使用lex来计数文件中注释,行,字符,关键字和数字的数量。我相信我已经使行计数器,关键字计数器,数字计数器和注释计数器正常工作,但是我的字符计数器有点混乱。

我认为字符计数器不会计算注释中的字符,这就是为什么有错误,但是老实说我很困惑。

任何帮助将不胜感激。这是我的代码:

 %option noyywrap
 %{
 #include <stdio.h>
 #include <math.h>
 int charno=0;
 int lineno=0;
 int numno=0;
 int keyno=0;
 int comno=0;
 %}

 character [a-zA-Z]
 line [\n]
 digit [0-9]
 keyword if|else|while|return
 s_comment "{"[^}\n]*"}"
 l_comment "/*"([^*]|\*+[^*/])*\*+"/"


 %%
 {s_comment}     {
                    comno++;
                 }
 {digit}         {
                    charno++;
                 }
 {l_comment}     {
                    comno++;
                    lineno++;
                 }
 {digit}*        {
                    numno++;
                 }

 {character}     {
                    charno++;
                 }
 {line}          {
                    lineno++;
                 }
 .               {
                    charno++;
                 }
 {keyword}       {
                    keyno++;
                 }
 %%
 int main(int argc, char **argv)
 {
            ++argv, --argc; /*skip over program name */
            if (argc > 0)
                    yyin = fopen(argv[0], "r");
            else
                    yyin = stdin;
            yylex();

            printf("Number of characters: %d\n", charno);
            printf("Number of lines:      %d\n", lineno);
            printf("Number of keywords:   %d\n", keyno);
            printf("Number of numbers:    %d\n", numno);
            printf("Number of comments:   %d\n", comno);
            return 0;
 }

与此相对应时:

 /*this is a comment 1*/
 /*comment
   comment 2 
 */
 /*comment 3*
*/if this is a line
{this is a test comment 4}
int i = 101; 
int j = 202;
if i == 303 then
 {this is a test comment 5}
else
{Should have 3 keywords}
{Should have 3 numbers}
/*Should have 8 comments including
 *this one*/ 
end

它应该产生:

Number of characters:296
Number of lines: 17
Number of keywords: 3
Number of numbers: 3
Number of comments: 8

但是它产生:

Number of characters:52
Number of lines: 17
Number of keywords: 3
Number of numbers: 3
Number of comments: 8

0 个答案:

没有答案