java词法分析器【自己改编的】


SrcAnalyse.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.JButton;

public class SrcAnalyse extends Frame implements ActionListener{
        int row = 1;
        int line = 1;
        
        public static JButton button1=new JButton("打开文件");
        public static JButton button2=new JButton("开始分析");
        public static JButton button3=new JButton("退出");
        
        TextArea text = new TextArea(15,60);         
        TextArea analyse_text = new TextArea(15,60);   

        int begin = 0;
        int end = 0;
        
    
        FileDialog file_dialog_load = new FileDialog(this, "打开文件", FileDialog.LOAD);
        SrcAnalyse(){
             
                this.setLayout(new FlowLayout());

                
                this.add(text);
                
                this.add(button1);//打开
                this.add(button2);//分析
                this.add(button3);//退出
                
                this.add(analyse_text);
                analyse_text.setText("分析信息如下: \n");
                
                button1.addActionListener(this);
                button2.addActionListener(this);
                button3.addActionListener(this);
                
                this.setSize(500, 650);
                this.setResizable(false);//设为窗口不可变
                this.setLocation(400,150);
                
                text.setEditable(true);
                analyse_text.setEditable(false);
                
                
                this.addWindowListener(new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                                System.exit(0);
                        }
                });
                
                this.setVisible(true);
        }
        
        public static void main(String[] args) {
                SrcAnalyse compiler = new SrcAnalyse();
                compiler.setTitle("词法分析程序v1.0——(C语言版)                    Power by luosng007");
        }

        public void actionPerformed(ActionEvent e){
                if(e.getSource() == button3){
                        System.exit(0);
                }else if(e.getSource() == button1){
                        file_dialog_load.setVisible(true);
      
                        File myfile = new File(file_dialog_load.getDirectory(), file_dialog_load.getFile());
                        try{   
                                BufferedReader bufReader = new BufferedReader(new FileReader(myfile));
                                String content = "";
                                String str;
                           
                                while((str = bufReader.readLine()) != null){
                                        content += str + "\n";
                                        text.setText(content);
                                }
                        }catch(IOException ie){
                                System.out.println("IOexception occurs...");
                        }
                }else if(e.getSource() == button2){
        
                	analyse_text.setText("");
                        row = 0;
                        line = 1;
                        analyse();
                }
        }
/**词法分析*/
        public void analyse(){
                String analyse_info = analyse_text.getText();
                String content = text.getText();
                String content1 ="";
             
                if(content.equals("")){
                	analyse_info += "Text is empty! You havn't input any code!\n";
                        analyse_text.setText(analyse_info);
                }
                
                else{
                        int i = 0;
                        int N = content.length();
                       
                        int state = 0;
                        
                       System.out.println(end);
                        
                        for(i = 0; i < N; i++){
                                row++;
                                char code;
                                char c = content.charAt(i);//当前读取字符
                                code = c;
                                System.out.print(code);
                                switch(state){
                                        case 0:
                                               
                                                if(c == ',' || c == ' ' || c == '\t' || c == '{' || c =='}' || c == '(' || c == ')' || c == ';' || c == '[' || c == ']')
                                                   { 
                                                     
                                                        if(isDigit(content.charAt(i - 1)) && isDigit(content.charAt(begin))){
                                                                end = i;
                                                                analyse_text.append("info:0 数值表达式:    " + content.substring(begin, end) +'\n');
                                                                
                                                        }                                                                                 
                                                        state = 0;
                                                }
                                                else if(c == '+') state = 1;
                                                else if(c == '-') state = 2;
                                                else if(c == '*') state = 3;
                                                else if(c == '/') state = 4;
                                                else if(c == '!') state = 5;
                                                else if(c == '>') state = 6;
                                                else if(c == '<') state = 7;
                                                else if(c == '=') state = 8;
                                                else if(((int)c) == 10) state = 9;//输入为回车
                                               
                                                                                               
                                                else if(isLetter(c)) {
                                                        state = 10;
                                                        begin = i;
                                                }
                                               //isDigit(int) 
                                                else if(isDigit(c)) {
                                                        begin = i;
                                                        state = 11;
                                                }
                                                else if(c == '#') state = 12;
                                                else if(c == '&') state = 14;
                                                else if(c == '|') state = 15;
                                                else if(c == '"') state = 16;
                                                else analyse_text.append("line: " + line + " row: " + row + " error: '" + c + "' Undefined character! \n");
                                                
                                                break;
                                        case 1://标识符为 + 
                                                //row++;
                                                if(c == '+'){
                                                        state = 0;
                                                        analyse_text.append("info:1 运算符'++':\n");
                                                }
                                                else if(c == '='){
                                                        state = 0;
                                                        analyse_text.append("info:1 运算符'+=':\n");
                                                }else{
                                                        state = 0;
                                                        analyse_text.append("info:1 运算符 '+':\n");
                                                        i--;
                                                        row--;
                                                }
                                                break;
                                        case 2://标志符为 - 
                                                if(c == '-')
                                                	analyse_text.append("info:2 运算符'--':\n");
                                                else if(c == '=')
                                                	analyse_text.append("info:2 运算符'-=':\n");
                                                else{
                                                	analyse_text.append("info:2 运算符'-':\n");
                                                        i--;
                                                        row--;
                                                }
                                                state = 0;
                                                break;
                                        case 3://运算符 *
                                                if(c == '=')
                                                	analyse_text.append("info:3 运算符  '*=':\n");
                                                else{
                        	                        analyse_text.append("info:3 运算符  '*':\n");
                                                        i--;
                                                        row--;
                                                }
                                                state = 0;
                                                break;
                                        case 4://运算符 / 
                                                if(c == '/'){
                                                  if((c=content.charAt(i+1))=='*')
                                                   state=3;
                                                   
                                                  else{
                                                	  while((c) != '\n'){
                                                		  c=content.charAt(i);
                                                		  i++;
                                           }
                                     
                                      System.out.println("");
                                      c = content.charAt(i);
                                                        state = 0;
                                                        analyse_text.append("info:4 注释部分  //: \n");
                                                                                                          }
                                                }else if(c == '='){
                                                        state = 0;
                                                        analyse_text.append("info:4 运算符  /= :\n");
                                                }else{
                                                        state = 0;
                                                        analyse_text.append("info:4 运算符  / :\n");
                                                        i--;
                                                        row--;
                                                }
                                                
                                                break;
                                        case 5://运算符 ! 
                                                if(c == '='){
                                                	analyse_text.append("info:5 运算符  != :\n");
                                                        state = 0;
                                                }else{
                                                        state = 0;
                                                        i--;
                                                        row--;
                                                        analyse_text.append("info:5 运算符 !: \n");
                                                }
                                                
                                                break;
                                        case 6://运算符 >
                                                if(c == '='){
                                                	analyse_text.append("info:6 运算符  >= :\n");
                                                        state = 0;
                                                }else{
                                                        state = 0;
                                                        analyse_text.append("info:6 运算符   >: \n");
                                                }
                                                
                                                break;
                                        case 7://运算符 < 
                                                if(c == '='){
                                                	analyse_text.append("info:7 运算符 <= :\n");
                                                        state = 0;
                                                }else{
                                                        state = 0;
                                                        analyse_text.append("info:7 运算符  <: \n");
                                                }
                                                break;
                                        case 8://运算符 =
                                                if(c == '='){
                                                	analyse_text.append("info:8 运算符 == :\n");
                                                        state = 0;
                                                }else{
                                                        state = 0;
                                                        analyse_text.append("info:8 运算符 = :\n");
                                                }
                                                break;
                                        case 9://回车  
                                                 state = 0;
                                                 row = 1;
                                                 line ++;
                                                 analyse_text.append("info:9 回车 : \n");
                                                break;
                                        case 10:// 字母
                                                if(isLetter(c) || isDigit(c)){
                                                        state = 10;
                                                }else{
                                                        end = i;
                                                        String id = content.substring(begin, end);
                                                        if(isKey(id))
                                                        	analyse_text.append("info:关键字 : "+id+'\n');
                                                                //error_text.appendText("info  ? :   10" + id + '\n');
                                                        else
                                                        	analyse_text.append("info:标识符  :" + id + '\n');
                                                        i--;
                                                        row--;
                                                        state = 0;
                                                }
                                                
                                                break;
                                        case 11:// 数字
                                                if(c == 'e' || c == 'E')
                                                        state = 13;
                                                else if(isDigit(c) || c == '.'){
                                                       
                                                }else {
                                                        if(isLetter(c)){
                                                        	analyse_text.append("error: line " + line + " row " + row + " ????\n");
                                                        }
                                                        //i--;
                                                        //row--;
                                                        int temp = i;
                                                        i = find(i,content);
                                                        row += (i - temp);
                                                        state = 0;
                                                }
                                                break;
                                        case 12://标识符为#
                                                String id = "";
                                                while(c != '<'){
                                                        id += c;
                                                        i++;
                                                        c = content.charAt(i);
                                                        System.out.print(c);
                                                        
                                                }
                                                if(id.trim().equals("include")){
                                                        while(c != '>' && ( c != '\n')){
                                                                i++;
                                                                c = content.charAt(i);
                                                                System.out.print(c);
                                                        }
                                                        if(c == '>')
                                                        	analyse_text.append("info # :12 :  \n");
                                                   }else
                                                	   analyse_text.append("error: " + "line " + line + ", row " + row + " ?\n");
                                               
                                                state = 0;
                                                break;
                                        case 13:// 检测指数表示方式
                                                if(c == '+' || c == '-' || isDigit(c)){
                                                        i++;
                                                        c = content.charAt(i);
                                                        while(isDigit(c)){
                                                                i++;
                                                                c = content.charAt(i);
                                                        }
                                                        if(isLetter(c) || c == '.'){
                                                        	analyse_text.append("error line " + line + " row " + row + "指数格式错误!\n");
                                                                state = 0;
                                                                int temp = i;
                                                                i = find(i,content);
                                                                row += (i - temp);
                                                               
                                                        }else{
                                                                end = i;
                                                                analyse_text.append("info:13 指数: " + content.substring(begin, end) + '\n');
                                                        }
                                                       
                                                        state = 0;
                                                }
                                                break;
                                        case 14://&&
                                                if(c == '&')
                                                	analyse_text.append("info:14 '&' :   \n");
                                                else{
                                                        i--;
                                                        analyse_text.append("info:14 '&&' : \n");
                                                }
                                                state = 0;
                                                break;
                                        case 15://||
                                                if(c == '|')
                                                	analyse_text.append("info:15 '||': \n");
                                                else{
                                                        i--;
                                                        analyse_text.append("info:15 '|':  \n");
                                                }
                                                state = 0;
                                                break;
                                        case 16://""
                                        	analyse_text.append("info:16 引号 :"+ '"' + '\n');
                                                i--;
                                                state = 0;
                                                break;
                                }
                          
                        }
                      
                }
                
                analyse_text.append("分析完成  \r\n");

        }
/**判定是否字母*/
        boolean isLetter(char c){
                if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_')
                        return true;
                return false;
        }
/**判定是否数字*/
        boolean isDigit(char c){
                if(c >= '0' && c <= '9') return true;
                return false;
        }
/**判定是否关键字*/
        boolean isKey(String str){
                if(
                		str.equals("char") || str.equals("double") || str.equals("enum") || str.equals("float") 
                	||  str.equals("int") || str.equals("long") || str.equals("short") || str.equals("signed") 
                	|| str.equals("struct")||str.equals("void") || str.equals("unsigned") || str.equals("union") 
                	|| str.equals("for") || str.equals("do") || str.equals("while") || str.equals("break") 
                	|| str.equals("continue") || str.equals("if")||str.equals("else")||str.equals("goto")
                    || str.equals("switch") || str.equals("case") || str.equals("default") || str.equals("return") 
                    || str.equals("auto")||str.equals("extern")||str.equals("register")||str.equals("static")
                    ||str.equals("const")||str.equals("sizeof")||str.equals("typedef")||str.equals("volatile")
                    )
                        return true;
                return false;
        }

/**寻找分隔符空格、括号、回车*/
        int find(int begin, String str){
                if(begin >= str.length())
                        return str.length();
                for(int i = begin; i < str.length(); i++){
                        char c = str.charAt(i);
                        if(c == '\n' || c == ',' || c == ' ' || c == '\t' || c == '{' || c =='}' || c == '(' || c == ')' || c == ';' || c == '=' || c == '+'|| c == '-' || c == '*' || c == '/')
                                return i - 1;
                }
                return str.length();
        }
}

你可能感兴趣的:(java,C++,c,IE,C#)