Implementation of Symbol Table using Lex





File name sym.l


%{
#include<stdio.h>
#include<string.h>
typedef struct node {
    char ID[10],DataType[10];
    struct node * next;
} node_t;
node_t *head = NULL,*temp=NULL,*current=NULL;
%}
%%
int|float|char {if(head==NULL){head = (node_t*)malloc(sizeof(node_t)); strcpy(head->DataType,yytext);}else{strcpy(temp->DataType,yytext);}}
[a-zA-Z]+[a-zA-Z0-9]* {if(head->next==NULL){strcpy(head->ID,yytext);head->next=NULL;}else{strcpy(temp->ID,yytext);temp->next=NULL;}}
";"  {if(temp==NULL){temp=(struct node*)malloc(sizeof(struct node));head->next=temp;}else{temp->next=(struct node*)malloc(sizeof(struct node));temp=(node_t*)temp->next;}}
"\n" {node_t *current = head;
    while (current != NULL) {
        printf("%s\t%s\n", current->ID,current->DataType);
        current = current->next;
    }
             }
%%
void main()
{
yylex();
}
int yywrap()
{
return 1;
}


/*

OUTPUT:

rach@rach-virtual-machine:~/Compilers/Symbol Table$ lex sym.l
rach@rach-virtual-machine:~/Compilers/Symbol Table$ cc lex.yy.c
rach@rach-virtual-machine:~/Compilers/Symbol Table$ ./a.out
int a1
 a1 int
float b
 a1 int
 b float

rach@rach-virtual-machine:~/Compilers/Symbol Table$ ./a.out
char str1
 str1 char

*/

Popular posts from this blog

DDL DML DCL and TCL

Implementation of Calculator using lex and yacc

A Register Allocation algorithm that translates the given code into one with a fixed number of registers.