⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 byylscanner.java

📁 此为编译原理的词法分析部分
💻 JAVA
字号:
/**
 *This program is for compiled language!
 *  yanxiangtong         2006.10.29
 *本程序最终解释权属于040410206 闫相通。
 **/
//package byylscanner;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
//保留字类
class  KeyWord
{
  public StringBuffer word;
  public KeyWord()
  {
  	word=new StringBuffer();
  }
}
//符号表中的NAME类
class WordName
{
	public int start;
	public int length;
}
//符号表类
class Symbol
{   
	public WordName name;
	public StringBuffer type;
	public StringBuffer kind;
	public StringBuffer val;
	public int addressOfMemory;
	public int addr;
	 public Symbol()
	 {  name=new WordName();
	    type=new StringBuffer();
	    kind=new StringBuffer();
	    val=new StringBuffer();
	 }
	
}

 public  class ByylScanner implements ActionListener{
	private Frame frame;
	
	private MenuBar menubar;
	private Menu menuFile;
	private Menu menuBuild;
    private Menu menuSave;
        
	private MenuItem menuFileOpen;
	private MenuItem menuFileClose;
	private MenuItem menuFileExit;
	
	private MenuItem menuBuildMorphemeAnalysis;
	private MenuItem menuBuildParsing; 
	
	private MenuItem menuSaveSource;
	private MenuItem menuSaveSymbol;
	private MenuItem menuSaveToken;
	
	private TextArea inputTextArea;
	private TextArea symbolTableTextArea;
	private TextArea resultTextArea;
	private TextArea tokenTextArea;
	
	private File beforeFile=new File("yanxiangtongprince.java");
	private File currentFile=new File("yanxiangtongprince.java");
	private FileDialog  fileChooser ;
	private FileDialog  fileSaver ; 
	private FileInputStream fis;  //输入流
	private FileOutputStream fos; //输出流  
	private Token currentToken;   //当前token串
	private Symbol currentSymbol;   //当前符号表
	private String saveText;   //存放当前分析的程序的所有字符
	private StringBuffer alphabet;  //字母表
	private int len;  //读入文件的长度
	private   byte []buffer;  //读入的文件内容存在byte串中
	
	private Symbol []symbolList;  //符号表的每一行存放在数组里面
	private  int charId=-1;
	private char ch;  //读入的字符
	
    private int varCount=0;//字符串个数统计
	private int errorCount=0;  //错误计数器
	private int labelCount=1;  // 序号
	private int addrCount=1;  //入口地址
	private int rowCount=1;  //行计数器
	private int columnCount=1; //列计数器
	private  int beginCode=0;  //用于程序是否正常结束
	private  int endCode=0;
	private static final int MAX=500;  //设定符号表的最大长度
	private  int currentId=0;
	private static final int LENGTH=33;  //保留字的个数
	private KeyWord []keyWord;
	
	public ByylScanner(){
		frame =new Frame("simple语言编译器");
		frame.setSize(800,700); 
    	        
		frame.setBackground(Color.GRAY);
		frame.setLocation(0,0);
		menubar=new MenuBar();
		menuFile=new Menu("文件");
		menuFileOpen=new MenuItem("打开");
		menuFileClose=new MenuItem("关闭");
		menuFileExit= new MenuItem("退出");
		
               //添加监听事件
		menuFileOpen.addActionListener(this); 
	    menuFileClose.addActionListener(this);
		menuFileExit.addActionListener(this);

		menuFile.add(menuFileOpen);
    	menuFile.add(menuFileClose);
		menuFile.add(menuFileExit);
		
		menuBuild=new Menu("编译");
		menuBuildMorphemeAnalysis=new MenuItem("此法分析");
		menuBuildParsing=new MenuItem("语法分析");
		
		menuBuildMorphemeAnalysis.addActionListener(this);
		menuBuildParsing.addActionListener(this);
		
		menuBuild.add(menuBuildMorphemeAnalysis);
		menuBuild.add(menuBuildParsing);
		
		menuSave=new Menu("保存");
		menuSaveSymbol=new MenuItem("保存符号表");
		menuSaveSource=new MenuItem("保存源文件");
		menuSaveToken=new MenuItem("保存Token");
		
		menuSave.add(menuSaveSource);
		menuSave.add(menuSaveSymbol);
		menuSave.add(menuSaveToken);
		
		menuSaveSource.addActionListener(this);
		menuSaveSymbol.addActionListener(this);
		menuSaveToken.addActionListener(this);
		menubar.add(menuFile);
		menubar.add(menuBuild);
		menubar.add(menuSave);
		frame.setMenuBar(menubar);
		
		inputTextArea=new TextArea();
		symbolTableTextArea=new TextArea();
		resultTextArea=new TextArea();
		tokenTextArea=new TextArea();
		
		frame.setLayout(new GridLayout(2,2));
		frame.add(inputTextArea);
	
		frame.add(symbolTableTextArea);
		frame.add(resultTextArea);
    	frame.add(tokenTextArea);
		frame.setVisible(true);
		
		frame.addWindowListener( new WindowAdapter()
		{
			public void windowClosing(WindowEvent e )
			{
				System.exit(0);
			}
		}
			);		
	}
	
	public void actionPerformed(ActionEvent e )
	{   
	      
	  if(e.getSource()==menuFileOpen)
		{ //menuFileOpen begin 
		   try{
		   	    fileChooser= new FileDialog(frame);
		   	    fileChooser.setMode(0);
		   	    fileChooser.setVisible(true);
		   	    currentFile=new File(fileChooser.getFile());
		   	    System.out.println(currentFile.toString());
		   	    fis=new FileInputStream(currentFile);
	            len=fis.available();
	            buffer=new byte[len];
	            fis.read(buffer);
	            inputTextArea.setText(new String(buffer));
		     }catch(IOException Ioe) {};
		   	    
	            
		   
				
			
		}//menuFileOpen end
	  else if(e.getSource()==menuSaveSource)
		{  
		   try{ 
		
		        if(currentFile.equals(beforeFile))
		        {
		     	  fileSaver= new FileDialog(frame);
		     	  fileSaver.setMode(1);
		   	      fileSaver.setVisible(true);
		   	      currentFile=new File(fileSaver.getFile());
		        }
			     //输出文件名
			      System.out.println(currentFile.toString());
		   	      fos=new FileOutputStream(currentFile);
		   	 	  saveText=new String(inputTextArea.getText());
		   	 	  fos.write(saveText.getBytes());
			 }catch(IOException Ioe) {};	
		 }  	     
	 else if(e.getSource()==menuSaveSymbol)           
		   	 
	    {  
		  try{ 
		        fileSaver= new FileDialog(frame);
		     	fileSaver.setMode(1);
		   	    fileSaver.setVisible(true);
		   	    currentFile=new File(fileSaver.getFile());
		        System.out.println(currentFile.toString());
		   	    fos=new FileOutputStream(currentFile);
		   	 	saveText=new String(symbolTableTextArea.getText());
		   	 	fos.write(saveText.getBytes());
			
		   	 }catch(IOException Ioe) {};
		 
		   
	 	
		 }
    else if(e.getSource()==menuSaveToken)
		{  
		   try{ 
		        fileSaver= new FileDialog(frame);
		     	fileSaver.setMode(1);
		   	    fileSaver.setVisible(true);
		   	    currentFile=new File(fileSaver.getFile());
		        System.out.println(currentFile.toString());
		   	 	fos=new FileOutputStream(currentFile);
		   	 	saveText=new String(tokenTextArea.getText());
		   	 	fos.write(saveText.getBytes());
		   	 }catch(IOException Ioe) {};
		}
	 else if(e.getSource()==menuFileClose)
		{    
		 try{ 
		
		    if(!currentFile.exists())
		     {
		     	fileSaver= new FileDialog(frame);
		     	fileSaver.setMode(1);
		   	    fileSaver.setVisible(true);
		   	     currentFile=new File(fileSaver.getFile());
		     }
			 
		   	if(currentFile.exists())
			 {
			 	System.out.println(currentFile.toString());
		   	    fos=new FileOutputStream(currentFile);
		        saveText=new String(inputTextArea.getText());
		   	    fos.write(saveText.getBytes());
			 }
	         currentFile=beforeFile;
		   	 inputTextArea.setText("");
	       	 symbolTableTextArea.setText("");
		     resultTextArea.setText("");
		     tokenTextArea.setText("");
		   
		   } catch(IOException oe) {};
	            
	    }
	    else if(e.getSource()==menuFileExit)
		{
		System.exit(0);	
		}
    	else if(e.getSource()==menuBuildMorphemeAnalysis)
		{
		    beginScanner();	
		}
	    else if(e.getSource()==menuBuildParsing)
		{
		inputTextArea.setText("我是王子语法分析");	
		}
   }
    
    public void scannerInit()
    {   
       int i=0;
       try{
    
          currentSymbol=new Symbol();
          currentToken =new Token(); 
          alphabet=new StringBuffer();
          symbolList=new Symbol[MAX]; //创建数组
          for(i=0;i<MAX;i++)
          symbolList[i]=new Symbol();  //创建对象
    	  keyWord=new KeyWord[LENGTH+1];  //创建数组
    	  for(i=0;i<LENGTH;i++)
    	  keyWord[i]=new KeyWord();//创建对象
          
       
          keyWord[1].word.append("and");
          keyWord[2].word.append("array");
          keyWord[3].word.append("begin");
          keyWord[4].word.append("bool");
          keyWord[5].word.append("call");
          keyWord[6].word.append("case");
          keyWord[7].word.append("char");
          keyWord[8].word.append("constant");
          keyWord[9].word.append("do");
 		  keyWord[10].word.append("else");
  		  keyWord[11].word.append("end");
  		  keyWord[12].word.append("flase");
  		  keyWord[13].word.append("for");
  		  keyWord[14].word.append("if");
 		  keyWord[15].word.append("input");
 		  keyWord[16].word.append("integer");
 		  keyWord[17].word.append("not");
 		  keyWord[18].word.append("of");
  		  keyWord[19].word.append("or");
  		  keyWord[20].word.append("output");
  		  keyWord[21].word.append("procedure");
  		  keyWord[22].word.append("program");
  		  keyWord[23].word.append("read");
  		  keyWord[24].word.append("real");
  		  keyWord[25].word.append("repeat");
  		  keyWord[26].word.append("set");
  		  keyWord[27].word.append("then");
  		  keyWord[28].word.append("to");
  		  keyWord[29].word.append("true");
  		  keyWord[30].word.append("until");
  		  keyWord[31].word.append("var");
  		  keyWord[32].word.append("while");
  	  	  keyWord[33].word.append("write");
    
  
 }catch(Exception oe){}
    }
   public void beginScanner()
   {    
        
       
        scannerInit(); //初始化
        //文件操作
       try{ 
		   
		    if(!currentFile.exists())
		     {  
		     	fileSaver= new FileDialog(frame);
		     	fileSaver.setMode(1);
		   	    fileSaver.setVisible(true);
		   	    currentFile=new File(fileSaver.getFile());
		     }
			 
			    
			 	System.out.println(currentFile.toString()); //打印文件名字
		   	 
		   	 	fos=new FileOutputStream(currentFile);
		   	 	saveText=new String(inputTextArea.getText());
		   	 	buffer=saveText.getBytes();
	            fos.write(buffer);
	         
		   }catch(IOException Ioe) {};
			 
		   	 
		   	 //开始扫描
		   	 ch=getNextChar();
		   	 while(ch!=1000)
		   	 { 
		   	   if((ch>47)&&(ch<58))  //是数字
		   	       isNumber();
                            else  //是保留字或标志符
                               {if(((ch>64)&&(ch<90))||((ch>96)&&(ch<123))||ch=='_')
                                       isAlpha();
                               else  
                                 {if(ch=='/') isAnotation();//是否为注释
                                   else 
                                       if(ch=='\'') isChar(); //字符常数
                                      else  isOther(); //其他情况
                                  }
                                }
		   	 }
                    
                    
                                
           // if(!(saveText.endsWith(firstEndWith)||saveText.endsWith(secondEndWith)))
            //     error(4);                    
		   if(!(beginCode==endCode)) //检验程序是否正常结束
		   error(4);
		  
   	  
   }
   /**
    *获得下一个字符
    **/
   public char getNextChar()
   {   try{
           charId++;
           columnCount++;
           if(saveText.charAt(charId)==13) 
            {rowCount++;  //行计数器加一并把列计数器置零
             columnCount=0;
            }
        if(charId<saveText.length())
   	    return saveText.charAt(charId); 
   	    }catch(Exception oo){}
   	    return 1000;  //1000为程序结束标志
       
   }
   
    /**
     *处理保留字和字符串
     **/
   public void isAlpha()
   {  int keyFlag=0,i,alpaFlag;
   	  while(((ch>64)&&(ch<90))||((ch>96)&&(ch<123))||ch=='_')
   	  {
   	  	currentToken.name.append(ch);
   	  	ch=getNextChar();
   	  } //读完所有的字母并读入下一个非字母的、字符
   	  for(i=0;i<LENGTH;i++)  //检测是否为保留字
   	  { 
   	  	if(keyWord[i].word.toString().equals(currentToken.name.toString()))
   	  	   {keyFlag=1;break;}
   	  	   
   	  }
   	  
   	  if(keyFlag==1)  //是保留字
   	    {currentToken.code=i;
   	    currentToken.address=-1;
   	    }
   	    else  //是标志符
   	    {  currentToken.code=34;
   	       alpaFlag=wordExist(); //确定入口地址需要检测是否在贩

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -