Parser for IF-THEN Statements - YACC - LEX - Compiler Design

Program:

(if.l)

ALPHA [A-Za-z]
DIGIT [0-9]
%%
[ \t\n]
if                return IF;
then                return THEN;
{DIGIT}+            return NUM;
{ALPHA}({ALPHA}|{DIGIT})*         return ID;
"<="                return LE;
">="                return GE;
"=="                return EQ;
"!="                return NE;
"||"                return OR;
"&&"                return AND;
.                return yytext[0];
%%          

(if.y)

%{
#include <stdio.h>
#include <stdlib.h>
%}
%token ID NUM IF THEN LE GE EQ NE OR AND
%right '='
%left AND OR
%left '<' '>' LE GE EQ NE
%left '+''-'
%left '*''/'
%right UMINUS
%left '!'
%%
S   : ST {printf("Input accepted.\n");exit(0);};
ST  :    IF '(' E2 ')' THEN ST1';'
    ;
ST1 : ST
    | E
    ;      
E   : ID'='E
    | E'+'E
    | E'-'E
    | E'*'E
    | E'/'E
    | E'<'E
    | E'>'E
    | E LE E
    | E GE E
    | E EQ E
    | E NE E
    | E OR E
    | E AND E
    | ID
    | NUM
    ;
E2  : E'<'E
    | E'>'E
    | E LE E
    | E GE E
    | E EQ E
    | E NE E
    | E OR E
    | E AND E
    | ID
    | NUM
    ;
%%

#include "lex.yy.c"

main()
{
printf("Enter the statement: ");
yyparse();
}  
Output:
nn@linuxmint ~ $ lex if.l
nn@linuxmint ~ $ yacc if.y
nn@linuxmint ~ $ gcc y.tab.c -ll -ly
nn@linuxmint ~ $ ./a.out
Enter the statement: if(i>) then i=1;
syntax error
nn@linuxmint ~ $ ./a.out
Enter the statement: if(i>8) then i=1;
Input accepted.
nn@linuxmint ~ $

Data Communications and Networking - Behrouz A. Forouzan - Presentation Slides



Data Communications and Networking
Behrouz A. Forouzan

Download Presentation Slides:
Sample ppt from Tata McGraw-Hill


Visit Tata McGraw-Hill - Behrouz A. Forouzan

Computer Networking: A Top Down Approach Featuring the Internet - Jim Kurose and Keith Ross - Presentation Slides

Computer Networking: A Top Down Approach Featuring the Internet,
4th edition.,Jim Kurose and Keith Ross, Addison-Wesley, 2008.

  1. Chapter 1
  2. Chapter 2
  3. Chapter 3
  4. Chapter 4
  5. Chapter 5
  6. Chapter 6
  7. Chapter 7
  8. Chapter 8
  9. Chapter 9

Postfix Evaluaion YACC LEX S6

YACC Program:(p1.y)

%{
#include<stdio.h>
#include<assert.h>
 int Pop();
 int Top();
 void Push(int val);
%}

%token T_Int

%%
S : S E    {printf(" %d\n", Top());}
  |
  ;

E : E E '+' {Push(Pop()+Pop());}
  | E E '-' {int op2=Pop();Push(Pop()-op2);}
  | E E '*' {Push(Pop() * Pop());}
  | E E '/' {int op2=Pop();Push(Pop()/op2);}
  | T_Int   {Push(yylval);}
  ;
%%
#include "lex.yy.c"
 int stack[100],count=0;

 int Pop()
 {
  assert(count>0);
  return stack[--count];
 }

 int Top()
 {
  assert(count>0);
  return stack[count-1];
 }

 void Push(int val)
 {
  assert(count<sizeof(stack)/sizeof(int));
  stack[count++]=val;
 }

int main()
 {
  return yyparse();
 }

Lex progam:(p1.l)

DIGIT    [0-9]
%%
{DIGIT}+ {yylval=atoi(yytext);return T_Int;}
[-+*/] {return yytext[0];}
\n    yyterminate();
.    ;

Output:

students@ccflab-desktop:~$ lex p1.l
students@ccflab-desktop:~$ yacc p1.y
conflicts: 1 shift/reduce
students@ccflab-desktop:~$ gcc y.tab.c -ll -ly
students@ccflab-desktop:~$ ./a.out
2 3 +
5
students@ccflab-desktop:~$ ./a.out
2 3 *
6
students@ccflab-desktop:~$ ./a.out
3 2 -
1
students@ccflab-desktop:~$ ./a.out
6 3 /
2
students@ccflab-desktop:~$


Expression Evaluation YACC S6

%{
#include<stdio.h>
%}
%token DIGIT
%%
S    : E '\n' {printf("%d\n",$1);return 1;}
    ;
E    : E '+'    T    { $$ = $1 + $3 ; }
    | T
    ;
T    : T '*'    F    { $$ = $1 * $3; }
    | F
    ;
F    : '(' E    ')'    { $$=$2; }
    | DIGIT
    ;
%%
yylex(){
int c;
c=getchar();
if(isdigit(c))
{
    yylval=c-'0';
    return DIGIT;
}

return c;
}
main()
{
printf("Enter the exp:");
yyparse();   
return 0;
}

Output:
students@ccflab-desktop:~$ yacc aa.y
students@ccflab-desktop:~$ gcc y.tab.c -ly
students@ccflab-desktop:~$ ./a.out
Enter the exp:2+5*5
27
students@ccflab-desktop:~$

Implement Finite Automata in lex-Odd no of 'a's

                                                 




program:

%{

%}

reg (b|ab*a)*ab* 

%%

{reg}      printf("%s Accepted",yytext);
.*     printf("%s Not Accepted",yytext);


%%

main()
{
yylex();
return 0;
}

Input:x.c
a
ab
aab
aba
abba

Output:
students@ccflab-desktop:~$ lex b.l
students@ccflab-desktop:~$ gcc lex.yy.c -lfl
students@ccflab-desktop:~$ ./a.out<x.c
a Accepted
ab Accepted
aab Not Accepted
aba Not Accepted
abba Not Accepted
students@ccflab-desktop:~$ 

Java RMI - Distributed Computing Assignment-II

Topic:  Case study:Java RMI


Reference:

The download link has been removed temporarily.

Korose & Ross - S6 DCCN Application layer slide-

Select Lines Starting with 'm' - Lex Program - Compiler Design

Program:

%{
%}
reg1 ^m.*\n

%%
{reg1} {ECHO;}
. ;
%%
Output:

( input file : c1.c

#include<stdio.h>
main ()
{
    int i,n,fact=1;
    printf("Enter the number: ");
    scanf("%d",&n);            //inputing the number
    for(i=1;i<=n;i++)        /* finding factorial */
    {
        fact = fact*i;
            }
    printf("Factorial=%d\n",fact);
}

)


nn@linuxmint ~ $ lex l7.lex
nn@linuxmint ~ $ gcc lex.yy.c -lfl
nn@linuxmint ~ $ ./a.out <c1.c

main ()











nn@linuxmint ~ $

Count The Number of Lines,Words and Characters - Lex Program - Compiler Design

Program:
%{
   
    int lnno=0,wordno=0,charno=0;
%}

word [.* .*\t]
eol [\n]

%%
{word}    {wordno++; charno+=yyleng;}
{eol}     {charno++;lnno++;wordno++;}
.    {charno++;}
%%
main()
{
    yylex();
    printf("Line number= %d\n",lnno);
    printf("Word number= %d\n",wordno);
    printf("Character number= %d\n",charno);
    return 0;
}

Output:

nn@linuxmint ~ $ lex l6.l
nn@linuxmint ~ $ gcc lex.yy.c -lfl
nn@linuxmint ~ $ ./a.out <c1.c
Line number= 13
Word number= 43
Character number= 232
nn@linuxmint ~ $
( input file : c1.c

#include<stdio.h>
main ()
{
    int i,n,fact=1;
    printf("Enter the number: ");
    scanf("%d",&n);            //inputing the number
    for(i=1;i<=n;i++)        /* finding factorial */
    {
        fact = fact*i;
    }
    printf("Factorial=%d\n",fact);

}
)

Remove All The Occurrences of a Word or Letter - Lex Program - Compiler Design

Program:

%{
  

%}

%%
"printf"    ;
(.|\n)        ECHO;
%%
main()
{
yylex();
return 0;
}

Output:
( input file: c1.c
#include<stdio.h>
main ()
{
    int i,n,fact=1;
    printf("Enter the number: ");
    scanf("%d",&n);            //inputing the number
    for(i=1;i<=n;i++)        /* finding factorial */
    {
        fact = fact*i;
    }
    printf("Factorial=%d\n",fact);

}
)


nn@linuxmint ~ $ lex l5.lex
nn@linuxmint ~ $ gcc lex.yy.c -lfl
nn@linuxmint ~ $ ./a.out <c1.c
#include<stdio.h>
main ()
{
    int i,n,fact=1;
    ("Enter the number: ");
    scanf("%d",&n);            //inputing the number
    for(i=1;i<=n;i++)        /* finding factorial */
    {
        fact = fact*i;
    }
    ("Factorial=%d\n",fact);

}


nn@linuxmint ~ $

Count The Number of Occurrences of a Particular Word or Letter - Lex Program - Compiler Design

Program:

%{
    int icount=0,factcount=0;
%}

%%

fact    factcount++;
i         icount++;
(.|\n)    ;

%%
main()
{
    yylex();
    printf("Count of \"fact\"= %d \nCount of letter 'i' = %d\n",factcount,icount);  
    return 0;
}

Output:


nn@linuxmint ~ $ lex l4.l
nn@linuxmint ~ $ gcc lex.yy.c -ll
nn@linuxmint ~ $ ./a.out<c1.c
Count of "fact"= 5
Count of letter 'i' = 17
nn@linuxmint ~ $


// Input file: c1.c
#include<stdio.h>
main ()
{
    int i,n,fact=1;
    printf("Enter the number: ");
    scanf("%d",&n);            //inputing the number
    for(i=1;i<=n;i++)        /* finding factorial */
    {
        fact = fact*i;
    }
    printf("Factorial=%d\n",fact);

}

Replace Sequences of White Spaces by a Single Blank Character - Lex Program - Compiler Design

Elimination of Multiple Spaces ,Tabs & Emptylines

Program:

%{
   
%}

space [ \t]
emptyline \n
%%

{space}+ printf(" ");
{emptyline}+ printf("\n");
. ECHO;

%%

main()
{

    yylex();
}
Output:

 // input: sum.c

#include<stdio.h>
main()
{


//program to add two numbers
int a,      b,c;
scanf("%d%d",&a,&b);
c=a+b;/* finding sum &
printing*/
printf("sum=%d",c);
}



nn@linuxmint ~ $ lex mw.l
nn@linuxmint ~ $ gcc lex.yy.c -ll
nn@linuxmint ~ $ ./a.out<sum.c
#include<stdio.h>
main()
{
//program to add two numbers
int a, b,c;
scanf("%d%d",&a,&b);
c=a+b;/* finding sum &
printing*/
printf("sum=%d",c);
}
nn@linuxmint ~ $

Comment Removal - Lex Program - Compiler Design

Program:

%{
  
%}

comment1    \/\*(.|\n)*\*\/
comment2    \/\/.*

%%

{comment1}    ;
{comment2}    ;
.|\n        ECHO;

%%
main()
{
    yylex();
    return 0;
}

Output:

( input file: c1.c

#include<stdio.h>
main ()
{
    int i,n,fact=1;
    printf("Enter the number: ");
    scanf("%d",&n);            //inputing the number
    for(i=1;i<=n;i++)        /* finding factorial */
    {
        fact = fact*i;
    }
    printf("Factorial=%d\n",fact);

}
)


nn@linuxmint ~ $ lex l2.lex
nn@linuxmint ~ $ gcc lex.yy.c -lfl
nn@linuxmint ~ $ ./a.out <c1.c
#include<stdio.h>
main ()
{
    int i,n,fact=1;
    printf("Enter the number: ");
    scanf("%d",&n);           
    for(i=1;i<=n;i++)       
    {
        fact = fact*i;
    }
    printf("Factorial=%d\n",fact);

}
nn@linuxmint ~ $

Number Each Line - Lex Program - Compiler Design

Program:

%{
int lineno =1;
%}

line .*\n

%%
{line} {printf("%5d %s", lineno++,yytext);}

%%
main()
{
yylex();
return 0;
}


Output:
input: compilerdesign.txt

Design of a Lexical Analyzer using Finite Automation
Design of lexical analyzer using LEX
Design of recursive descent and LL (1) parsers
Implementation of Operator precedence Parsing
Design of parser for arithmetic expressions using YACC
Design of a simple type checker
Generation of IC for arithmetic expressions
Simple code optimization strategies
Design of a code generator
Writing a simple Compiler
                    www.2k8618.blogspot.com
                  
                  
nn@linuxmint ~ $ lex l1.l
nn@linuxmint ~ $ gcc lex.yy.c -lfl
nn@linuxmint ~ $ ./a.out <compilerdesign.txt
    1 Design of a Lexical Analyzer using Finite Automation
    2 Design of lexical analyzer using LEX
    3 Design of recursive descent and LL (1) parsers
    4 Implementation of Operator precedence Parsing
    5 Design of parser for arithmetic expressions using YACC
    6 Design of a simple type checker
    7 Generation of IC for arithmetic expressions
    8 Simple code optimization strategies
    9 Design of a code generator
   10 Writing a simple Compiler
   11                     www.2k8618.blogspot.com

Recursive Predictive Parser - Compiler Lab - C Program

Aim:
Parse the following grammar.


E --> E + T / T
T --> T * F / F
F --> ( E ) / id


Program:
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
void err(const char* s)
{
perror(s);
exit(0);
}
int factor()
{
int val,i;
char ch[0];
scanf("%s",ch);
switch(ch[0])
{
case '(':
val=expr();
scanf("%s",ch);
if(ch[0]!=')')
err("Missing closing paranthesis in factor.");
break;
default :{
for(i=0;i<strlen(ch);i++)
{
if((ch[i]>'0')&&(ch[i]<='9'))
continue;
else
err("Illegal character sequence in place of factor.");
}
val=atoi(ch);
}
}
return val;
}
int term()
{
int val;
char ch[10];
val=factor();
while(1)
{
scanf("%s",ch);
if(ch[0]=='*')
{
val=val*factor();
}
else
break;
}
ungetc(ch[0],stdin);
return val;
}
int expr()
{
int val;
char ch[10];
val=term();
while(1)
{
scanf("%s",ch);
if(ch[0]=='+')
val=val+term();
else
break;
}
ungetc(ch[0],stdin);
return val;
}
main()
{
printf("\nEnter the expression: ");
printf("\n Result: %d\n",expr());
}

       

Output:
nn@linuxmint ~ $ gcc rec.c
nn@linuxmint ~ $ ./a.out
Enter the expression: 5 * ( 3 + 1 )
;
Result: 20
nn@linuxmint ~ $

Comment Removal Program - Compiler Lab - C Program

Program:

#include<stdio.h>
main()
{
    FILE *ip,*op;
    char ipname[10],opname[10];
    char c;
    int flag=0;
    printf("\nEnter the input file name : ");
    scanf("%s",ipname);
    printf("\nEnter the output file name : ");
    scanf("%s",opname);
    if((ip=fopen(ipname,"r"))==NULL)
        printf("Input file does not exist !\n");
    else
    {   
        op=fopen(opname,"w");
        while((c=getc(ip))!=EOF)
        {
            if(c=='/')
            {
                c=getc(ip);
                if(c=='*')
                    flag=1;
                if(c=='/')
                    flag=2;
            }
   
            if((flag==2)&&(c=='\n'))
                flag=0;
            if(flag==0)
                putc(c,op);
            if((flag==1)&&(c=='*'))
            {
                c=getc(ip);
                if(c=='/')
                    flag=0;
            }
        }
        fclose(ip);
        fclose(op);
    }
}


Output:

nn@ubuntu:~$ gcc cmt.c
nn@ubuntu:~$ ./a.out

Enter the input file name : a.c

Enter the output file name : b.c
nn@ubuntu:~$

a.c: (Input File)
#include<stdio.h>
main()
{
prntf("hai...");//comment removal program in c
printf("hello...");/*www.2k8618.blogspot.com */
}


b.c:(Output File)
#include<stdio.h>
main()
{
prntf("hai...");
printf("hello...");
}

Palindrome Check - Client-Server Program - Network-DBMS Lab - Java program


Program:

//ServerCode2 .java

import java.io.*;
import java.net.*;

public class ServerCode2 {
ServerSocket ss;
Socket socket;
BufferedReader sock_in,kdb_in;
PrintWriter sock_out;
String str;
    public ServerCode2()
    {
    try{
        ss=new ServerSocket(8765);
        System.out.println("Server is listening port 8765");
        socket=ss.accept();
        System.out.println("Connection established...");
        kdb_in=new BufferedReader(new InputStreamReader(System.in));
        sock_in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        sock_out=new PrintWriter(socket.getOutputStream());
        while(true)
        {
        System.out.println("Msg from client");
        str=sock_in.readLine();
        int k=str.length();
        System.out.println(str);
        int left=0,right=k-1;int flag=1;
        while(left<=right)
        {
            if(str.charAt(left)!=(str.charAt(right)))
            {
                flag=0;
                break;
            }
            else
            {
                left++;right--;
            }
        }
        if(flag==1)
            str="....Palindrome....";
        else
            str="....Not Palindrome....";
        //System.out.println("Enter the msg");
        //str=kdb_in.readLine();
        sock_out.println(str);
        sock_out.flush();
        if(str.equals("bye"))
            break;
        }
    }catch (Exception e) { }
    }
public static void main(String arg[])
{
    new ServerCode2();
}}


//ClientCode.java

import java.io.*;
import java.net.*;

public class ClientCode{

Socket socket;
BufferedReader sock_in,kdb_in;
PrintWriter sock_out;
String str;
    public ClientCode()
    {
    try{

        Socket socket=new Socket("127.0.0.1",8765);
        kdb_in=new BufferedReader(new InputStreamReader(System.in));
        sock_in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        sock_out=new PrintWriter(socket.getOutputStream());
        while(true)
        {
       
        System.out.println("Enter the msg");
        str=kdb_in.readLine();
        sock_out.println(str);
        sock_out.flush();
        System.out.println("Msg from Server");
        str=sock_in.readLine();
        System.out.println(str);
        if(str.equals("bye"))
            break;
        }
        socket.close();
    }catch (Exception e) { }
    }
public static void main(String arg[])
{
    new ClientCode();
}}

Output:

Terminal 1 (Server):

students@ccflab-desktop:~$ javac ServerCode2.java
students@ccflab-desktop:~$ java ServerCode2
Server is listening port 8765
Connection established...
Msg from client
malayalam
Msg from client
abc
Msg from client

Terminal 2(Client):

students@ccflab-desktop:~$ javac ClientCode.java
students@ccflab-desktop:~$ java ClientCode
Enter the msg
malayalam
Msg from Server
....Palindrome....
Enter the msg
abc
Msg from Server
....Not Palindrome....
Enter the msg

TCP - Client-Server Program - Networks & DBMS Lab - Java Program

Program:

//ServerCode.java

import java.io.*;
import java.net.*;

public class ServerCode{
ServerSocket ss;
Socket socket;
BufferedReader sock_in,kdb_in;
PrintWriter sock_out;
String str;
    public ServerCode()
    {
    try{
        ss=new ServerSocket(8765);
        System.out.println("Server is listening port 8765");
        socket=ss.accept();
        System.out.println("Connection established...");
        kdb_in=new BufferedReader(new InputStreamReader(System.in));
        sock_in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        sock_out=new PrintWriter(socket.getOutputStream());
        while(true)
        {
        System.out.println("Msg from client");
        str=sock_in.readLine();

        System.out.println(str);
      
        System.out.println("Enter the msg");
        str=kdb_in.readLine();
        sock_out.println(str);
        sock_out.flush();
        if(str.equals("bye"))
            break;
        }
    }catch (Exception e) { }
    }
public static void main(String arg[])
{
    new ServerCode();
}}
   
//ClientCode.java
import java.io.*;
import java.net.*;

public class ClientCode{

Socket socket;
BufferedReader sock_in,kdb_in;
PrintWriter sock_out;
String str;
    public ClientCode()
    {
    try{

        Socket socket=new Socket("127.0.0.1",8765);
        kdb_in=new BufferedReader(new InputStreamReader(System.in));
        sock_in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        sock_out=new PrintWriter(socket.getOutputStream());
        while(true)
        {
       
        System.out.println("Enter the msg");
        str=kdb_in.readLine();
        sock_out.println(str);
        sock_out.flush();
        System.out.println("Msg from Server");
        str=sock_in.readLine();
        System.out.println(str);
        if(str.equals("bye"))
            break;
        }
        socket.close();
    }catch (Exception e) { }
    }
public static void main(String arg[])
{
    new ClientCode();
}}
   
Output:
Terminal 1:

students@ccflab-desktop:~$ javac ServerCode.java
students@ccflab-desktop:~$ java ServerCode
Server is listening port 8765
Connection established...
Msg from client
hai...
Enter the msg
hello...
Msg from client
bye
Enter the msg
bye
students@ccflab-desktop:~$

Terminal 2:

students@ccflab-desktop:~$ javac ClientCode.java
students@ccflab-desktop:~$ java ClientCode
Enter the msg
hai...
Msg from Server
hello...
Enter the msg
bye
Msg from Server
bye
students@ccflab-desktop:~$
Related Posts Plugin for WordPress, Blogger...