📄 gramanalyer.java
字号:
package com.lxx.compiler;
import java.util.*;
public class GramAnalyer {
private LexicalAnalyer lexAnalyer;
private String[] VT={"(",")","{","}","int","void","main","symbol",";"};
private String[] VN={"S","MAINFUCTION","FUCTIONAME","SENTENCE"};;
private String[][] LLlist={
{"error","error","error","error","MAINFUCTION ( ) { SENTENCE }" , "MAINFUCTION ( ) { SENTENCE }","error","error","error"},
{"error","error","error","error","int FUCTIONAME","void FUCTIONAME","error","error","error"},
{"error","error","error","error","error","error","main","error","error"},
{"error","error","error","E","int symbol ; SENTENCE","void symbol ;","error","error"},
};
public Stack<String> analyerStack=new Stack<String>();
public Token nowToken;
public GramAnalyer(String inputFile,String keyFile,String limitFile,String operatorFile)throws Exception
{
lexAnalyer=new LexicalAnalyer(inputFile,keyFile,limitFile,operatorFile);
}
public void showStack(){
int i,j;
String[] ch=new String[100];
j=analyerStack.size();
for(i=0;i<j;i++)
{
ch[i]=analyerStack.pop();
}
System.out.print("\t\t");
for(i=j-1;i>=0;i--)
{
System.out.print(ch[i]);
analyerStack.push(ch[i]);
}
}
public void error()
{
System.out.print("\nSorry,it has some grammer mistake !\n");
}
public int location(String c,String[] array)
{
int i;
for(i=0;i<array.length;i++)
{
if(c.equals(array[i]))
return i;
}
return -1;
}
public void Analyer() throws Exception
{
String[] temp;
int n=1;
String nowString;
analyerStack.push(VN[0]);
nowToken=lexAnalyer.NextToken();
System.out.println("步骤 分析栈 推导或匹配");
while(nowToken!=null)
{
nowString=nowToken.stringValue;
if(nowToken.tokenValue==2 && !(nowString.equals("main")))
{
nowString="symbol";
}
if(location(nowString,VT)==-1)
{
error();
return;
}
if(nowString.equals(analyerStack.peek()))
{
analyerStack.pop();
System.out.print(n);
n++;
showStack();
System.out.println("\t\t\t匹配");
nowToken=lexAnalyer.NextToken();
continue;
}
if(LLlist[location(analyerStack.peek(),VN)][location(nowString,VT)].equals("error"))
{
error();
return;
}
while(!nowToken.stringValue.equals(analyerStack.peek()))
{
System.out.print(n);
n++;
showStack();
System.out.println("\t\t\t\t"+LLlist[location(analyerStack.peek(),VN)][location(nowString,VT)]);
if(LLlist[location(analyerStack.peek(),VN)][location(nowString,VT)].equals("E"))
{
analyerStack.pop();
continue;
}
if(LLlist[location(analyerStack.peek(),VN)][location(nowString,VT)].equals("error"))
{
error();
return;
}
else
{
temp=LLlist[location(analyerStack.pop(),VN)][location(nowString,VT)].split(" ");
for(int i=temp.length-1;i>=0;i--)
{
analyerStack.push(temp[i]);
}
}
}
if(nowString.equals(analyerStack.peek()))
{
analyerStack.pop();
System.out.print(n);
n++;
showStack();
System.out.println("\t\t\t\t"+"匹配");
}
nowToken=lexAnalyer.NextToken();
}
System.out.print("\n it is RIGHT!\n");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -