EXPERIMENT 5
To implement Implement type checking using Lex and Yacc.

========================================================================

LEX Program (typecheck.l)
-------------------------
%{
    #include "y.tab.h"
    #include <stdlib.h>
    #include <string.h>
    %}
%%
"int"                         { return INT; }
"float"                       { return FLOAT; }
[0-9]+"."[0-9]+              { yylval.fval = atof(yytext); return FLOAT_NUM; }
[0-9]+                        { yylval.ival = atoi(yytext); return INT_NUM; }
[a-zA-Z_][a-zA-Z0-9_]*       { yylval.sval = strdup(yytext); return ID; }
"="                           { return ASSIGN; }
";"                           { return SEMI; }
"+"                           { return PLUS; }
\n                            ;
[ \t]+                        ;
.                             { return yytext[0]; }
%%
int yywrap()
{
    return 1;
}

YACC Program (typecheck.y)
--------------------------
%{
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    typedef struct Symbol {
        char *name;
        char *type;
    } Symbol;
Symbol symtab[100];
int symcount = 0;
char* lookup(char *name)
{
    for (int i = 0; i < symcount; i++)
    {
        if (strcmp(symtab[i].name, name) == 0)
        return symtab[i].type;
    }
return NULL;
}
void insert(char *name, char *type)
{
    symtab[symcount].name = name;
    symtab[symcount].type = type;
    symcount++;
}
int yyerror(char *s)
{
    printf("Error: %s\n", s);
    return 0;
}
int yylex();
%}
%union {
    int ival;
    float fval;
    char *sval;
    char *type;
}
%token <ival> INT_NUM
%token <fval> FLOAT_NUM
%token <sval> ID
%token INT FLOAT
%token ASSIGN SEMI PLUS
%type <type> expr
%%
program
: program stmt
| /* empty */
;
stmt
: decl SEMI
| assign SEMI
;
decl
: INT ID
{
    insert($2, "int");
}
| FLOAT ID
{
    insert($2, "float");
}
;
assign
: ID ASSIGN expr
{
    char *lhs = lookup($1);
    if (!lhs)
    {
        printf("Undeclared variable %s\n", $1);
    }
else if (strcmp($3, "error") == 0)
{
    /* Error already reported in expression */
}
else if (strcmp(lhs, $3) != 0)
{
    printf("Type error: cannot assign %s to %s\n",
    $3, lhs);
}
else
{
    printf("Assignment OK: %s = %s\n",
    lhs, $3);
}
}
;
expr
: expr PLUS expr
{
    if (strcmp($1, "error") == 0 ||
    strcmp($3, "error") == 0)
    {
        $$ = "error";
    }
else if (strcmp($1, $3) != 0)
{
    printf("Type error in expression: %s + %s\n",
    $1, $3);
    $$ = "error";
}
else
{
    $$ = $1;
}
}
| INT_NUM
{
    $$ = "int";
}
| FLOAT_NUM
{
    $$ = "float";
}
| ID
{
    char *t = lookup($1);
    if (!t)
    {
        printf("Undeclared variable %s\n", $1);
        $$ = "error";
    }
else
{
    $$ = t;
}
}
;
%%
int main()
{
    yyparse();
    return 0;
}

Test Input (test.txt)
---------------------
int a;
int b;
float x;
float y;
a = 10;
b = a + 20;
x = 5.5;
y = x + 2.5;
