My Complete CC
My Complete CC
#include<stdio.h>
#include<string.h>
#include<ctype.h>
main()
{
int ln,tn,i=0,f;
char ch,a[10],b[10][10]={"main","int","printf"},c[10];
FILE *f1,*f2;
f1=fopen("input.txt","r");
f2=fopen("result.txt","w");
ln=1;
tn=1;
fprintf(f2,"lineno tokenno token lexeme\n");
while(!feof(f1))
{
ch=fgetc(f1);
l1:
f=0;
if(ch=='\n')
ln++;
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
{
fprintf(f2,"%d\t%d\t%c\toperators\n",ln,tn,ch);
tn++;
}
if(isdigit(ch))
{
i=0;
c[i]=ch;
i++;
ch=fgetc(f1);
while(isdigit(ch))
{
c[i]=ch;
ch=fgetc(f1);
i++;
}
c[i]='\0';
fprintf(f2,"%d\t%d\t%s\tdigit\n",ln,tn,c);
tn++;
goto l1;
}
if(ch=='('||ch==')'||ch=='{'||ch=='}'||ch==';'||ch==',')
{
fprintf(f2,"%d\t%d\t%c\tspecial symbol\n",ln,tn,ch);
tn++;
[Cse0939]
}
if(isalpha(ch))
{
i=0;
a[i]=ch;
i++;
ch=fgetc(f1);
while(isalnum(ch))
{
a[i]=ch;
ch=fgetc(f1);
i++;
}
a[i]='\0';
for(i=0;i<3;i++)
{
if(strcmp(a,b[i])==0)
f=1;
}
if(f==1)
{
fprintf(f2,"%d\t%d\t%s\tkeyword\n",ln,tn,a);
tn++;
goto l1;
}
else if(f==0)
{
fprintf(f2,"%d\t%d\t%s\tidentifier\n",ln,tn,a);
tn++;
goto l1;
}
}
}
}
Output:
cc scanner.c
./a.out
input.txt
main()
{
int a,b,c;
c=a+b+15;
printf;
}
[Cse0939]
output.txt
lineno
1
1
1
2
3
3
3
3
3
3
3
4
4
4
4
4
4
4
5
5
6
[Cse0939]
tokenno
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
token lexeme
main keyword
(
special symbol
)
special symbol
{
special symbol
int
keyword
a
identifier
,
special symbol
b
identifier
,
special symbol
c
identifier
;
special symbol
c
identifier
a
identifier
+
operators
b
identifier
+
operators
15
digit
;
special symbol
printf keyword
;
special symbol
}
special symbol
Output:
lex oct.l
cc lex.yy.c ll
./a.out
07
octal
0xA1
hexadecimal
4
decimal
[Cse0939]
[Cse0939]
Output:
token no.
1
3
3
1
2
2
[Cse0939]
line no.
0
0
0
1
1
1
tokens
keywords
Splsym
Splsym
keywords
Identifier
Splsym
lexeme
main
(
)
char
ch
;
Output:
Enter the no. of productions
3
A->Aa
B->ba
C->cC
Left recursive grammar
Grammar is not recursive
Right recursive grammar
[Cse0939]
[Cse0939]
i = 0;
printf("Items are:\n");
while(l!=i)
{
printf("%d)",i);
puts(items[i]);
printf("\n");
i++;
}
printf("\n");
//Finding Closure:
strcpy(closure[0],items[0]);
m=1;
j=0;
do
{
if(closure[j][4]>='A' && closure[j][4] <= 'Z')
{
for(i=0;i<l;i++)// l gives the number of items
{
if((closure[j][4]==items[i][0])&&(items[i][4]=='.'))
{
strcpy(closure[++j],items[i-1]);
m++;
}
}
}
else
flag=1;
}
while(flag==0);
printf("Closure is:\n");
for(j=0;j<m;j++)
puts(closure[j]);
printf("\n");
}
[Cse0939]
Output:
enter the number of productions
2
Enter productions:
A->C
C->b
Items are:
0)A->.C
1)A->C.
2)C->.b
3)C->b.
Closure is:
A->.C
C->.b
[Cse0939]
[Cse0939]
Output:
AB+C*D+
LA
AB
L
MC
L
AD
[Cse0939]