Compiler Design and Construction
Assignment no.:02
Q. Write the java code to replace the inline function call with the body of inline:
inline int avg(int a,int b,int c)
{
return (a+b+c)/3;
}
void main()
{
int c=avg(1,2,3);
}
Solution:
package inline;
import java.io.File;
import java.io.PrintStream;
import java.util.Scanner;
/**
*
* @author sxc
*/
public class Main {
public static void main(String[] args) throws Exception{
String func= "",param = "";
String temp="";
String tcons="";
String skip="";
String consArr[]=new String [3];
String funname="";
String param1[]=new String [10];
String varArr[]=new String [15];
String arr[]=new String [15];
Scanner fin =new Scanner (new File("input.txt"));
while(fin.hasNext())
{
String str=fin.nextLine();
String str1 []=str.split(" ");
if(str1[0].endsWith("return"))
{
temp=str1[1];
}
if(str1[0].equals("inline"))
{
func= str1[2];
int k=0;
while(func.charAt(k)!='(')
{
funname=funname+func.charAt(k);
k++;
}
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==('('))
{
int j=i+1;
do
{
param=param+String.valueOf(str.charAt(j));
j++;
}while(str.charAt(j)!=')');
}
}
param1=param.split(",");
int count=0;
for(int i=0;i<param1.length;i++)
{
arr=param1[i].split(" ");
varArr[count]=arr[1];
count++;
}
}
}
fin.close();
Scanner fread=new Scanner(new File("input.txt"));
String temp1="";
String temp2="";
int cont=0;
int funlen=funname.length();
while(fread.hasNext())
{
String str = fread.nextLine();
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==funname.charAt(0) && str.charAt(i-1)=='=')
{
for(int j=i;j<i+funlen;j++)
{
temp1 = temp1 + str.charAt(j);
}
if(temp1.equals(funname))
{
int j=i+funlen+1;
do{
tcons=tcons+str.charAt(j);
j++;
}while(str.charAt(j)!=')');
consArr=tcons.split(",");
for(int m=0;m<consArr.length;m++)
{
}
consArr=tcons.split(",");
int flag=0;
for(int l=0;l<temp.length();l++)
{
cont=0;
flag=0;
while(cont!=consArr.length)
{
if((String.valueOf(temp.charAt(l))).equals(varArr[cont]))
{
temp2=temp2+consArr[cont];
flag++;
}
cont++;
}
if(flag==0)
temp2=temp2+temp.charAt(l);
}
}
System.out.println(temp2);
}
}
}
fread.close();
Scanner fr=new Scanner(new File("input.txt"));
PrintStream fwrite=new PrintStream(new File("output.txt"));
while(fr.hasNext())
{
String str = fr.nextLine();
if(str.startsWith("inline"))
{
do
{
skip=skip+str; str=fr.nextLine();
}while(str.charAt(0)!='}');
}
else
{
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)!='=')
{
fwrite.print(str.charAt(i));
}
else
{
int j=i+1;
fwrite.print(str.charAt(i));
fwrite.print(temp2);
do{
j++;
i++;
}while(str.charAt(j)!=';');
i++;
}
}
fwrite.println();
}
}
}
}
Output:
No comments:
Post a Comment