/* 8a. Write a LEX program to count the number of identifiers */

%{
int id_ct=0;
%}


SPC [ \t]*
IDE [a-zA-Z_][a-zA-Z0-9_]*
DEC "int "|"float "|"char "|"long "|"unsigned "
%s DEFN

%%
{SPC}{DEC}{SPC} {BEGIN(DEFN);}
<DEFN>{IDE}{SPC}\,{SPC} {id_ct++;}
<DEFN>{IDE}{SPC}\;{SPC} {id_ct++;BEGIN(INITIAL);}
<*>./\n+;
.;
%%

main(int argc,char *argv[])
{
    yyin=fopen(argv[1],"r");
    yylex();
    printf("\nNumber of identifiers is %d\n",id_ct);
}


 

/* 8b. Write a YACC program to identify a valid if statement and a valid if then else
statement */

%token IF
%token THEN
%token ELSE 
%token aop
%token rop
%token letter 

%%

iflist:
    |iflist '\n'
    |iflist list '\n' { if (flag == 0)
                            printf("\nValid If statement");
                        else
                            printf("\nValid If Then Else statement");
                      }
;

list:
    |IF condition THEN stlist ELSE stlist
    |IF condition THEN stlist
;

condition:
    |exp 
    |exp rop condition
    |'(' condition ')'


stlist:
    |exp
    |stlist exp
    |'{' stlist '}'
    |'{' list '}'
;

exp:
    |letter
    |exp aop letter
;


%%


#include<stdio.h>
int flag=0;
main()
{
    yyparse();
}
yylex()
{
    int c;
    while((c=getchar())=='\t'||c==' '||c=='\n');
        if(c=='I' || c=='i')
        {
            if((c=getchar())=='F' || c=='f')
                return IF ;
            else
                return c;
        }
    if(c=='T' || c=='t')
        if((c=getchar())=='H'||c=='h')
            if((c=getchar())=='E' ||c=='e')
                if((c=getchar())=='N' ||c=='n')
                    return THEN;
    if(c=='E'||c=='e')
        if((c=getchar())=='L'||c=='l')
            if((c=getchar())=='S'||c=='s')
                if((c=getchar())=='E'||c=='e')
                {
                    flag = 1;
                    return ELSE;
                }
    if(isalpha(c))
        return letter;
    if(c=='+'||c=='-'||c=='*'||c=='/')
        return aop;
    if(c=='<'||c=='>')
        return rop;
}
yyerror(char *s)
{
    printf("\n%s : Not a valid if then else statement\n ",s);
}