Experiments
/*Experiment 1. Design a Lexical analyzer for the given language. The lexical analyzer should ignore redundant spaces, tabs and new lines. It should also ignore comments. Although the syntax specification states that identifiers can be arbitrarily long, you may restrict the length to some reasonable value.*/
#include
#include
#include
void keyw(char *p);
int i = 0, id = 0, kw = 0, num = 0, op = 0;
char keys[32][10] = {"auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while"};
void main() {
char ch, str[25], seps[15] = " \t\n,;(){}[]#\"<>", oper[] = "!%^&*-+=~|.<>/?";
int j;
FILE *f1;
f1 = fopen("E:/SCET/CDCF/LAB/cd1.txt", "r");
if (f1 == NULL) {
printf("Error opening file.\n");
return;
}
while ((ch = fgetc(f1)) != EOF) {
for (j = 0; j <= 14; j++) {
if (ch == oper[j]) {
printf("%c is an operator\n", ch);
op++;
str[i] = '\0';
keyw(str);
}
}
for (j = 0; j <= 14; j++) {
if (i == -1)
break;
if (ch == seps[j]) {
if (ch == '#') {
while ((ch = fgetc(f1)) != '>' && ch != EOF) {
printf("%c", ch);
}
printf("%c is a header file\n", ch);
i = -1;
break;
} else if (ch == '"') {
do {
ch = fgetc(f1);
printf("%c", ch);
} while (ch != '"' && ch != EOF);
printf("\b is a literal\n");
i = -1;
break;
}
str[i] = '\0';
keyw(str);
}
}
if (i != -1) {
str[i] = ch;
i++;
} else {
i = 0;
}
}
fclose(f1); // Close the file
printf("Keywords: %d\nIdentifiers: %d\nOperators: %d\nNumbers: %d\n", kw, id, op, num);
}
void keyw(char *p) {
int k, flag = 0;
for (k = 0; k <= 31; k++) {
if (strcmp(keys[k], p) == 0) {
printf("%s is a keyword\n", p);
kw++;
flag = 1;
break;
}
}
if (flag == 0) {
if (isdigit(p[0])) {
printf("%s is a number\n", p);
num++;
} else {
if (p[0] != '\0') {
printf("%s is an identifier\n", p);
id++;
}
}
}
i = -1;
}
%{
#include <stdio.h>
%}
delim [\\t]
ws {delim}+
letter [A-Za-z]
digit [0-9]
id {letter}({letter}|{digit})*
num {digit}+(\\.{digit}+)?(E[+|-]?{digit}+)?
%%
{ws} { printf("no action\\n"); }
if|else|then { printf("%s is a keyword\\n", yytext); }
{id} { printf("%s is an identifier\\n", yytext); }
{num} { printf("it is a number\\n"); }
"<" { printf("it is a relational operator less than\\n"); }
"<=" { printf("it is a relational operator less than or equal\\n"); }
">" { printf("it is a relational operator greater than\\n"); }
">=" { printf("it is a relational operator greater than or equal\\n"); }
"==" { printf("it is a relational operator equal\\n"); }
"<>" { printf("it is a relational operator not equal\\n"); }
%%
int main() {
yylex();
return 0;
}
int yywrap() {
return 1;
}
No comments:
Post a Comment