Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: DESIGN LEXICAL ANALYZER IN C AIM: To design a Lexical Analyzer in C. ALGORITHM: 1. Declare the header files 2. Declare an array of strings containing all the reserve keywords in C. 3. Declare an array of characters containing all the operators in C. 4. Declare a function check_keyword() which returns 1 if the argument is a keyword, else returns 0. 5. Declare a function check_operator() which returns 1 if the argument is an operator, else returns 0. 6. Declare a function check_preprocessor() which uses a regular expression to check if the argument is a preprocessor and returns 1 if the argument is a preprocessor, else returns 0. 7. Declare a function check_identifier() which uses a regular expression to check and print the argument name as a valid/invalid identifier. 8. Declare variables and file pointers to read the contents of the sample file. 9. Open the file in ‘r’ mode. 10. Read the contents of the file and tokenise using strtok(). 11. Check if the content is header or identifier or operator or symbol or keyword by calling the corresponding function. 12. Loop till the end of file is reached. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: SOURCE CODE: #include <stdio.h> #include <string.h> #include <regex.h> regex_t regex; int reti; char keywords[33][12] = {"return", "continue", "extern", "static", "long", "signed", "switch", "char", "else", "unsigned", "if", "struct", "union", "goto", "while", "float", "enum", "sizeof", "double", "volatile", "const", "case", "for", "break", "void", "register", "int", "do", "default", "short", "typedef", "auto", "main"}; char operators[6][2] = {"+", "-", "*", "/", "%", "="}; int check_keyword(char *p) { for (int i = 0; i< 33; ++i) { if (strstr(p, keywords[i])) return 1; } return 0; } int check_operator(char *p) { for (int i = 0; i< 6; ++i) { if (strstr(p, operators[i])) return 1; } return 0; } int check_preprocessor(char *p) { reti = regcomp(®ex, "[#.*]", REG_EXTENDED); reti = regexec(®ex, p, 0, NULL, 0); if (!reti) return 1; else if (reti == REG_NOMATCH) Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: return 0; } int check_identifier(char *p) { reti = regcomp(®ex, "^[a-zA-Z_]+[a-zA-Z0-9_]*", REG_EXTENDED); reti = regexec(®ex, p, 0, NULL, 0); if (!reti) printf("%s \t\t\t Valid identifier\n", p); else if (reti == REG_NOMATCH) printf("%s \t\t\t Invalid identifier\n", p); } int main() { FILE *fp = fopen("sample.c", "r"); char str[100]; while (!feof(fp)) { fgets(str, sizeof(str), fp); char *p = strtok(str, " }{\n"); while (p != NULL) { int j = 0, f = 0; if (check_keyword(p)) printf("%s \t\t\t Keyword\n", p); else if (check_operator(p)) printf("%s \t\t\t Operator\n", p); else if (check_preprocessor(p)) printf("%s \t Preprocessor\n", p); else check_identifier(p); p = strtok(NULL, ",;()\n "); } } } Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: SAMPLE INPUT: sample.c #include<stdio.h> void main() { int a, b; float _f; char 2c; _f = a + b; } SAMPLE OUTPUT: #include<stdio.h> Preprocessor void Keyword main Keyword int Keyword a Valid identifier b Valid identifier float Keyword _f Valid identifier char Keyword 2c Invalid identifier _f Valid identifier = Operator a Valid identifier + Operator b Valid identifier RESULT: The C program to design a lexical analyzer was successfully implemented. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: ACCEPTANCE OF A STRING USING A REGULAR EXPRESSION AIM: To write a C program to check for the acceptance of a string using a Regular Expression. ALGORITHM: 1. Declare header files. 2. Declare a function match() which takes the pattern and string asarguments, usesregular expression to check if the string matches with thepattern. 3. If the string matches the pattern, return 1, else return 0. 4. In main function, get the pattern and string as input from the user and call the match() function until the user terminates the program. 5. If the function returns 1, print that the pattern matches. Else, print that the pattern does not match. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: SOURCE CODE: #include <stdio.h> #include <regex.h> int match(char *string, char *pattern) { regex_t re; if (regcomp(&re, pattern, REG_EXTENDED | REG_NOSUB) != 0) return 0; int status = regexec(&re, string, 0, NULL, 0); regfree(&re); if (status != 0) return 0; return 1; } int main(void) { char re[100]; printf("Enter Regular expression : "); scanf("%s", re); char s1[100]; while (1) { printf("Enter string : "); scanf("%s", s1); printf("%s", match(s1, re) ? "Valid string\n" : "Invalid string\n"); } }SAMPLE INPUT AND OUTPUT: Enter Regular expression : ^a*babba*b$ Enter string : ababbab Valid string Enter string : aaaababbaaab Valid string Enter string : abbabab Invalid string RESULT: A C program to check the acceptance of a string using a regular expression was successfully implemented. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: CONSTRUCTION OF NFA FOR A GIVEN REGULAR EXPRESSION AIM: To write a C program to construct a NFA for a given regular expression. ALGORITHM: 1. Declare a struct called Node with node_no, a_count, b_count and node pointers next_a, next_b and next. 2. Declare a static variable nodecount. 3. Get the regular expression from the user. 4. Check each character in the regular expression until the last is reached. 5. If the character is ‘(‘, parse the regex till ‘)’ is encountered. If the character is ‘a’, assign p->nexta=p and increment a_count. Do the same for ‘b’ 6. If the character is *, loop the state to itself. 7. If the character is ‘a’ or ‘b’, define a new state by creating a temp node and assign the respective pointers. 8. Increment the ‘nodecount’ value everytime a new node is created. 9. Print the transition table. For each state, print the next states for ‘a’ and ‘b’ inputs. 10. Stop. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: SOURCE CODE: #include <stdio.h> #include <string.h> #include <stdlib.h> int nodecount = 0; struct Node { struct Node *Next; int node_no; char nextA[3]; char nextB[3]; }; struct Node *Head, *p, *Temp; struct Node *create() { int c; Temp = (struct Node *)malloc(sizeof(struct Node)); Temp->node_no = nodecount; nodecount++; Temp->Next = NULL; return Temp; } void update(struct Node *p, char Ch) { char c; if (Ch == 'a') { c = p->node_no + '0'; //int to char conversion strncat(p->nextA, &c, 1); } else if (Ch == 'b') { c = p->node_no + '0'; strncat(p->nextB, &c, 1); } } int main(void) { char prev; Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: char regex[100], Ch[5]; int s, j, i; char c; printf("Enter the regular expression"); scanf("%s", regex); Head = create(); p = Head; for (i = 0; i<strlen(regex); i++) { if (regex[i] == '(') { s = 0; Ch[0] = Ch[1] = Ch[2] = '\0'; char prev; while (regex[i] != ')') { if (regex[i] == 'a' || regex[i] == 'b') { Ch[s] = regex[i]; s++; } i++; } if (regex[i + 1] == '*') { s = 0; while (Ch[s] != '\0') { update(p, Ch[s]); s++; } i++; } if (regex[i + 1] == '+') { Temp = create(); c = Temp->node_no + '0'; strcat(p->nextA, &c); strcat(p->nextB, &c); p->Next = Temp; s = 0; p = Temp; while (Ch[s] != '\0') Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: { update(p, Ch[s]); s++; } } } else if (regex[i] == '+') { prev = regex[i - 1]; update(p, prev); } else if (regex[i + 1] == '*') { prev = regex[i]; update(p, prev); i++; } else { // a or b Temp = create(); p->Next = Temp; c = Temp->node_no + '0'; if (regex[i] == 'a') strncat(p->nextA, &c, 1); else if (regex[i] == 'b') strncat(p->nextB, &c, 1); p = Temp; } } printf("\nTransition table"); printf("\n+-----------------------------------------------+"); printf("\n|\tState\t|\ta\t|\tb\t|"); printf("\n|-----------------------------------------------|"); p = Head; for (j = 0; j <nodecount; j++) { printf("\n|\t%d", p->node_no); if (p->nextA[0] == 0) printf("\t|\tnull"); else { printf("\t|\t"); Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: for (i = 0; i< p->nextA[i] != '\0'; i++) { printf("%c,", p->nextA[i]); } } if (p->nextB[0] == 0) printf("\t|\tnull\t|"); else { printf("\t|\t"); for (i = 0; p->nextB[i] != '\0'; i++) printf("%c,", p->nextB[i]); printf("\t|"); } p = p->Next; } printf("\n+-----------------------------------------------+"); return 0; } SAMPLE INPUT: Enter the regular expression (a/b)*abb SAMPLE OUTPUT: RESULT: The C program to construct NFA for a given regular expression was successfully implemented. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: CONSTRUCTION OF DFA FOR A GIVEN REGULAR EXPRESSION AIM: To write a C program to construct a DFA for a given regular expression. ALGORITHM: 1. Declare a struct called Node with node_no and node pointers nexta, nextb and nextnode. 2. Declare a static variable nodecount. 3. Get the regular expression from the user. 4. Check each character in the regular expression until the last is reached. 5. If the character is ‘(‘, parse the regex till ‘)’ is encountered. If the character is ‘a’, assign p->nexta=p and increment a_count. Do the same for ‘b’ 6. If the character is *, loop the state to itself and assign flag=1, temp1 to p. 7. If the character is ‘a’ or ‘b’, define a new state by creating a temp node and assign the respective pointers. If the flag is 1, point the p->nexta to temp1(if input is defined only for b). 8. Increment the ‘nodecount’ value everytime a new node is created. 9. Print the transition table. For each state, print the next states for ‘a’ and ‘b’ inputs. If the next state is NULL, print inf which refers to the dead state. 10. Stop. SOURCE CODE: #include <stdio.h> #include <stdlib.h> #include <string.h> #define INF -999 struct Node { struct Node *Prev; int State; struct Node *a; struct Node *b; struct Node *Next; }; struct Node *Head = NULL, *Temp = NULL, *p, *q; int main(void) { char regex[100]; int i, Count = 0; printf("Enter the regular expression : "); Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: scanf("%s", regex); Head = (struct Node *)malloc(sizeof(struct Node)); p = Head; p->State = 0; p->Prev = NULL; for (i = 0; i<strlen(regex); i++) { if (regex[i] == '(') { while (regex[i] != ')') i++; if (regex[i + 1] == '*') { if (regex[i + 2] == 'a') p->b = p; if (regex[i + 2] == 'b') p->a = p; } i++; } else { Temp = (struct Node *)malloc(sizeof(struct Node)); Temp->Prev = p; p->Next = Temp; Temp->State = ++Count; Temp->Next = NULL; if (regex[i] == 'a') p->a = Temp; else p->b = Temp; p = p->Next; } } p->a = p->b = Head; p = Head; while (p != NULL) { if (p->a == NULL) p->a = p->Prev->a; if (p->b == NULL) Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: p->b = p->Prev->b; p = p->Next; } printf("+-------+-------+-------+\n"); printf("|State\t|a\t| b\t|\n"); printf("|-------|-------|-------|\n"); p = Head; while (p) { printf("|%d\t|", p->State); if (p->a != NULL) printf("%d\t|", p->a->State); else printf("inf\t|"); if (p->b != NULL) printf("%d\t|\n", p->b->State); else printf("inf\t|\n"); p = p->Next; } printf("+-------+-------+-------+\n"); return 0; } SAMPLE INPUT: Enter the regular expression (a/b)*abb SAMPLE OUTPUT: RESULT: The C program to construct DFA for a given regular expression was successfully implemented. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: CONVERSION OF NFA TO DFA . AIM: To write a c program to convert NFA to DFA for a given regular expression. ALGORITHM: Suppose there is an NFA N < Q, ∑, q0, δ, F > which recognizes a language L. Then the DFA D < Q’, ∑, q0, δ’, F’ > can be constructed for language L as: Step 1: Initially Q’ = ɸ. Step 2: Add q0 to Q’. Step 3: For each state in Q’, find the possible set of states for each input symbol using transition function of NFA. If this set of states is not in Q’, add it to Q’. Step 4: Final state of DFA will be all states with contain F (final states of NFA) CODE: #include<stdio.h> #include<string.h> #include<stdlib.h> int nodecount=0; struct node{ struct node *next_node; int node_no; char nexta[3]; char nextb[3]; }*head, *p, *temp; struct node* create(){ int c; temp=(struct node*)malloc(sizeof(struct node)); temp->node_no=nodecount; nodecount++; temp->next_node=NULL; return temp; Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: } void update (struct node*p, char ch){ char c; if(ch=='a'){ c=p->node_no+'0';//int to char conversion strncat(p->nexta,&c,1); } else if(ch=='b'){ c=p->node_no+'0'; strncat(p->nextb,&c,1); } } main(){ char prev; char regex[100],ch[5]; printf("Enter the regular expression"); scanf("%s",regex); int s,j,i; char c; head=create(); p=head; for(i=0;i<strlen(regex);i++){ if(regex[i]=='('){ s=0; ch[0]=ch[1]=ch[2]='\0'; char prev; while(regex[i]!=')'){ if(regex[i]=='a'||regex[i]=='b'){ ch[s]=regex[i]; s++; } i++; } if(regex[i+1]=='*'){ s=0; while(ch[s]!='\0'){ Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: update(p,ch[s]); s++; } i++; } if(regex[i+1]=='+'){ temp=create(); c=temp->node_no+'0'; strcat(p->nexta,&c); strcat(p->nextb,&c); p->next_node=temp; s=0; p=temp; while(ch[s]!='\0'){ update(p,ch[s]); s++; } } } else if(regex[i]=='+'){ prev=regex[i-1]; update(p,prev); } else if(regex[i+1]=='*'){ prev=regex[i]; update(p,prev); i++; } else{ // a or b temp=create(); p->next_node=temp; c=temp->node_no+'0'; if(regex[i]=='a') strncat(p->nexta,&c,1); else if(regex[i]=='b') strncat(p->nextb,&c,1); p=temp; Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: } } //transition table p=head; printf("\nTransition table"); printf("\n+-----------------------------------------------+"); printf("\n|\tState\t|\ta\t|\tb\t|"); printf("\n|-----------------------------------------------|"); for(j=0;j<nodecount;j++) { printf("\n|\t%d",p->node_no); if(p->nexta[0]==0) printf("\t|\tnull"); else{ printf("\t|\t"); for(i=0;i<p->nexta[i]!='\0';i++){ printf("%c,",p->nexta[i]); } } if(p->nextb[0]==0) printf("\t|\tnull\t|"); else{ printf("\t|\t"); for(i=0;p->nextb[i]!='\0';i++){ printf("%c,",p->nextb[i]); } printf("\t|"); } p=p->next_node; } printf("\n+-----------------------------------------------+"); } Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: OUTPUT: RESULT: A C program was written to convert NFA to DFA for a given regular expression. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: SHIFT REDUCE PARSER AIM: To parse the given input string for a grammar using shift reduce parser. ALGORITHM: 1. Start 2. Define the grammar 3. Get input string. 4. Shift each symbol of the input string one by one into the stack. 5. While doing so, if the stack can be reduced using any of the production rule defined by the grammar. 6. If yes reduce by applying production rule else keep shifting 7. Repeat step 5-6 until only start symbol is present in the stack. 8. Stop. CODE: #include<stdio.h> #include<string.h> int k=0,z=0,i=0,j=0,c=0; char a[16],ac[20],stk[15],act[10]; void check(); int main() { puts("GRAMMAR is E->E+E \n E->E*E \n E->(E) \n E->id"); Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: puts("enter input string "); gets(a); c=strlen(a); strcpy(act,"SHIFT->"); puts("stack \t input \t action"); for(k=0,i=0; j<c; k++,i++,j++) { if(a[j]=='i' && a[j+1]=='d') { stk[i]=a[j]; stk[i+1]=a[j+1]; stk[i+2]='\0'; a[j]=' '; a[j+1]=' '; printf("\n$%s\t%s$\t%sid",stk,a,act); check(); } else { stk[i]=a[j]; stk[i+1]='\0'; a[j]=' '; printf("\n$%s\t%s$\t%ssymbols",stk,a,act); check(); Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: } } } void check() { strcpy(ac,"REDUCE TO E"); for(z=0; z<c; z++) if(stk[z]=='i' && stk[z+1]=='d') { stk[z]='E'; stk[z+1]='\0'; printf("\n$%s\t%s$\t%s",stk,a,ac); j++; } for(z=0; z<c; z++) if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='E') { stk[z]='E'; stk[z+1]='\0'; stk[z+2]='\0'; printf("\n$%s\t%s$\t%s",stk,a,ac); i=i-2; } Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: for(z=0; z<c; z++) if(stk[z]=='E' && stk[z+1]=='*' && stk[z+2]=='E') { stk[z]='E'; stk[z+1]='\0'; stk[z+1]='\0'; printf("\n$%s\t%s$\t%s",stk,a,ac); i=i-2; } for(z=0; z<c; z++) if(stk[z]=='(' && stk[z+1]=='E' && stk[z+2]==')') { stk[z]='E'; stk[z+1]='\0'; stk[z+1]='\0'; printf("\n$%s\t%s$\t%s",stk,a,ac); i=i-2; } } SAMPLE INPUT: GRAMMAR is E->E+E E->E*E E->(E) E->id Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: enter input string id+id*id+id SAMPLE OUTPUT: stack input action $id +id*id+id$ SHIFT->id $E +id*id+id$ REDUCE TO E $E+ id*id+id$ SHIFT->symbols $E+id *id+id$ SHIFT->id $E+E *id+id$ REDUCE TO E $E *id+id$ REDUCE TO E $E* id+id$ SHIFT->symbols $E*id +id$ SHIFT->id $E*E +id$ REDUCE TO E $E +id$ REDUCE TO E $E+ id$ SHIFT->symbols $E+id $ SHIFT->id $E+E $ REDUCE TO E $E $ REDUCE TO E RESULT: Thus an input string for a grammar is parsed using Shift reduce parser. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: DATA TYPE CHECKING AIM: To check the data type correctness of given expression. ALGORITHM: 1. Start. 2. Get input variables. 3. Get datatype of each variable. 4. Get input expression. 5. Check the type of the assigned variable, if it is correct, print “datatype correctly defined” 6. Else print the correct data type of assigned variable. 7. End. CODE: #include<stdlib.h> #include<stdio.h> int main() { int n,i,k,flag=0; char vari[15],typ[15],b[15],c; printf("Enter the number of variables:"); scanf(" %d",&n); for(i=0;i<n;i++) { Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: printf("Enter the variable[%d]:",i); scanf(" %c",&vari[i]); printf("Enter the variable-type[%d](float-f,int-i):",i); scanf(" %c",&typ[i]); if(typ[i]=='f') flag=1; } printf("Enter the Expression(end with $):"); i=0; getchar(); while((c=getchar())!='$') { b[i]=c; i++; } k=i; for(i=0;i<k;i++) { if(b[i]=='/') { flag=1; break; } } for(i=0;i<n;i++) { if(b[0]==vari[i]) Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: { if(flag==1) { if(typ[i]=='f') { printf("\nthe datatype is correctly defined..!\n"); break; } else { printf("Identifier %c must be a float type..!\n",vari[i]); break; } } else { printf("\nthe datatype is correctly defined..!\n"); break; } } } return 0; } SAMPLE INPUT 1: Enter the number of variables:4 Enter the variable[0]:a Enter the variable-type[0](float-f,int-i):i Enter the variable[1]:b Enter the variable-type[1](float-f,int-i):f Enter the variable[2]:c Enter the variable-type[2](float-f,int-i):i Enter the variable[3]:d Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: Enter the variable-type[3](float-f,int-i):i Enter the Expression(end with $):a=b*c/d$ SAMPLE OUTPUT 1: Identifier a must be a float type..! SAMPLE INPUT 2: Enter the number of variables:4 Enter the variable[0]:a Enter the variable-type[0](float-f,int-i):f Enter the variable[1]:b Enter the variable-type[1](float-f,int-i):f Enter the variable[2]:c Enter the variable-type[2](float-f,int-i):i Enter the variable[3]:d Enter the variable-type[3](float-f,int-i):i Enter the Expression(end with $):a=b*c/d$ SAMPLE OUTPUT 2: the datatype is correctly defined..! RESULT: Thus data type correctness of given expression is checked . Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: INTERMEDIATE CODE GENERATION AIM: To generate intermediate code for given expression. ALGORITHM: 1. Start. 2. Traverse the expression string and store the positions of all operators using a structure data type. 3. Now for each operator find the left and right operand and assign a new symbol to the sub expression. 4. Substitute the new symbol in place of the sub expression the main expression. 5. Repeat steps 3 and 4 till substitution is possible. 6. End. CODE: #include"stdio.h" #include "stdlib.h" #include"string.h" int i=1,j=0,no=0,tmpch=90; char str[100],left[15],right[15]; void findopr(); void explore(); void fleft(int); void fright(int); struct exp Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: { int pos; char op; }k[15]; void main() { printf("\t\tINTERMEDIATE CODE GENERATION\n\n"); printf("Enter the Expression :"); scanf("%s",str); printf("The intermediate code:\t\tExpression\n"); findopr(); explore(); } void findopr() { for(i=0;str[i]!='\0';i++) if(str[i]==':') { k[j].pos=i; k[j++].op=':'; } for(i=0;str[i]!='\0';i++) if(str[i]=='/') { Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: k[j].pos=i; k[j++].op='/'; } for(i=0;str[i]!='\0';i++) if(str[i]=='*') { k[j].pos=i; k[j++].op='*'; } for(i=0;str[i]!='\0';i++) if(str[i]=='+') { k[j].pos=i; k[j++].op='+'; } for(i=0;str[i]!='\0';i++) if(str[i]=='-') { k[j].pos=i; k[j++].op='-'; } } void explore() { Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: i=1; while(k[i].op!='\0') { fleft(k[i].pos); fright(k[i].pos); str[k[i].pos]=tmpch--; printf("\t%c := %s%c%s\t\t",str[k[i].pos],left,k[i].op,right); for(j=0;j <strlen(str);j++) if(str[j]!='$') printf("%c",str[j]); printf("\n"); i++; } fright(-1); if(no==0) { fleft(strlen(str)); printf("\t%s := %s",right,left); exit(0); } printf("\t%s := %c",right,str[k[--i].pos]); } void fleft(int x) Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: { int w=0,flag=0; x--; while(x!= -1 &&str[x]!= '+' &&str[x]!='*'&&str[x]!='='&&str[x]!='\0'&&str[x]!='- '&&str[x]!='/'&&str[x]!=':') { if(str[x]!='$'&& flag==0) { left[w++]=str[x]; left[w]='\0'; str[x]='$'; flag=1; } x--; } } void fright(int x) { int w=0,flag=0; x++; while(x!= -1 && str[x]!= '+'&&str[x]!='*'&&str[x]!='\0'&&str[x]!='='&&str[x]!=':'&&str[x]!='-'&&str[x]!='/') { if(str[x]!='$'&& flag==0) { Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: right[w++]=str[x]; right[w]='\0'; str[x]='$'; flag=1; } x++; } } SAMPLE INPUT: INTERMEDIATE CODE GENERATION Enter the Expression :w:=a*b+c/d-e/f+g*h SAMPLE OUTPUT: The intermediate code: Expression Z := c/d w:=a*b+Z-e/f+g*h Y := e/f w:=a*b+Z-Y+g*h X := a*b w:=X+Z-Y+g*h W := g*h w:=X+Z-Y+W V := X+Z w:=V-Y+W U := Y+W w:=V-U T := V-U w:=T w := T RESULT: Thus an intermediate code is generated for given expression. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: CODE GENERATION AIM: To generate code generation for the given expression. ALGORITHM: 1. Invoke a function getreg to find out the location L where the result of computation b op c should be stored. 2. Consult the address description for y to determine y'. If the value of y currently in memory and register both then prefer the register y' . If the value of y is not already in L then generate the instruction MOV y' , L to place a copy of y in L. 3. Generate the instruction OP z' , L where z' is used to show the current location of z. if z is in both then prefer a register to a memory location. Update the address descriptor of x to indicate that x is in location L. If x is in L then update its descriptor and remove x from all other descriptor. 4. If the current value of y or z have no next uses or not live on exit from the block or in register then alter the register descriptor to indicate that after execution of x : = y op z those register will no longer contain y or z. CODE: #include<stdio.h> #include<string.h> void main() { char a[10]; inti,j,n,h=1; printf("enter the expression\n"); scanf("%s",a); n=strlen(a); for(i=2;i<n;i++) { if(a[i]=='a' || a[i]=='b') Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: {printf("\nLDFR%d, %c",h,a[i]); h++;} } for(i=2;i<n;i++){ if(a[i]=='+') {printf("\nADDF R0,R1\nSTF %c,R0",a[0]);} if(a[i]=='-') {printf("\nSUBF R0,R1\nLDF %c,R0",a[0]);} if(a[i]=='*') {printf("\nMULF R0,R1\nLDF %c,R0",a[0]);} if(a[i]=='/') {printf("\nDIVF R0,R1\nLDF %c,R0",a[0]);} }} SAMPLE INPUT: Enter the expression c=a+b SAMPLE OUTPUT: LDFR1, a LDFR2, b ADDF R0,R1 STF c,R0 RESULT: Thus a code generation for a given expression. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: PROGRAMS USING LEX TOOL a. To count the number of vowels and consonants in a string AIM: To write a lex program to count the number of vowels and consonants in a string. ALGORITHM: 1. Start 2. Declare the header files and declare 2 variables to count the vowels and consonants. 3. Define the rules and actions Rule: [AEIOUaeiou] increment vowel count Rule: [A-Za-z] increment consonant count 4. Declare the main function and call yylex function 5. Print the vowel and consonant count 6. Stop CODE: %option noyywrap %{ #include<stdio.h> Int vowelc,consc=0; %} %% [AEIOUaeiou] {vowelc++;} [A-Za-z] {consc++;} %% main(){ printf(“Enter string”); yylex(); printf(“vowel count:%d\nConsonant count:%d”,vowelc,consc); Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: } SAMPLE INPUT/OUTPUT: RESULT: Thus a lex program was written to count the number of vowels and consonants. Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: b. To check whether a number is odd or even AIM: To write a lex program to check whether a given number is odd or even. ALGORITHM: 1. Start 2. Declare the header files. 3. Define the rules and actions Rule: [0-9]*[02468] print “even number” Rule: [0-9]+ print “Odd number” 4. Declare the main function and call yylex function 5. Stop CODE: %option noyywrap %{ #include<stdio.h> %} %% [0-9]*[02468] {printf(“Even number”);} [0-9]+ {printf(“Odd number”);} %% main(){ printf(“Enter number”); yylex(); } PAGENO: Register No: 180801097 Page No: Exercise No: IT18611 – AUTOMATA AND COMPILER DESIGN LABORATORY Date: EX NO:2 Automata and Compiler Laboratory REG.NO: 170801074 DATE: (IT16612) SAMPLE INPUT/OUTPUT: RESULT: A lex program was written to check whether given number is odd or even. Register No: 180801097 Page No:
Enter the password to open this PDF file:
-
-
-
-
-
-
-
-
-
-
-
-