Search code examples
ccompiler-constructionlex

scanner.l:22: warning, rule cannot be matched


I am currently attempting to write a program that counts the number of characters and lines in a .in file. The issue is that when I input the command:

 lex scanner.l

It produces an error that says:

scanner.l:22:warning, rule cannot be matched

I would appreciate any help on this matter. Below is my code:

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

character [a-zA-Z]
line [\n]
digit [0-9]

%%

{digit}
        {
                charno++;
        }

{character}
        {
                charno++;
        }
{line}
        {
                lineno++;
        }
.      
        {
                charno++;
        }

%%
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 ", charno);
            printf("Number of lines:      %d ", lineno);
            return 0;
}

Solution

  • There should be no newline between the matched token and the action. So :

    {digit}
            {
                    charno++;
            }
    

    should be :

    {digit} {
                    charno++;
            }
    

    (and similarly for the others)