www.pudn.com > Analyzer.rar > Form1.cs


using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.IO; 
 
namespace word 
{  
///   
/// Form1 的摘要说明。  
///   
public class Form1 : System.Windows.Forms.Form 
{  
 
private System.Windows.Forms.Button button1; 
private System.Windows.Forms.Button button2;  
 
private System.Windows.Forms.RichTextBox richTextBox1;  
private System.Windows.Forms.RichTextBox richTextBox2; 
 
private System.Windows.Forms.OpenFileDialog openFileDialog1; 
private Button button3; 
private RichTextBox richTextBox3; 
private Label label1;  
 
///   
/// 必需的设计器变量。  
///   
private System.ComponentModel.Container components = null;  
 
public Form1()  
{  
//  
// Windows 窗体设计器支持所必需的  
//  
InitializeComponent();  
 
//  
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码  
//  
}  
 
///   
/// 清理所有正在使用的资源。  
///   
protected override void Dispose( bool disposing )  
{  
if( disposing )  
{  
if (components != null)  
{  
components.Dispose();  
}  
}  
base.Dispose( disposing );  
}  
 
#region Windows 窗体设计器生成的代码  
///   
/// 设计器支持所需的方法 - 不要使用代码编辑器修改  
/// 此方法的内容。  
///   
private void InitializeComponent()  
{ 
    this.button1 = new System.Windows.Forms.Button(); 
    this.richTextBox1 = new System.Windows.Forms.RichTextBox(); 
    this.button2 = new System.Windows.Forms.Button(); 
    this.richTextBox2 = new System.Windows.Forms.RichTextBox(); 
    this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); 
    this.button3 = new System.Windows.Forms.Button(); 
    this.richTextBox3 = new System.Windows.Forms.RichTextBox(); 
    this.label1 = new System.Windows.Forms.Label(); 
    this.SuspendLayout(); 
    //  
    // button1 
    //  
    this.button1.Location = new System.Drawing.Point(276, 8); 
    this.button1.Name = "button1"; 
    this.button1.Size = new System.Drawing.Size(64, 23); 
    this.button1.TabIndex = 1; 
    this.button1.Text = "词法分析"; 
    this.button1.Click += new System.EventHandler(this.button1_Click); 
    //  
    // richTextBox1 
    //  
    this.richTextBox1.Location = new System.Drawing.Point(12, 48); 
    this.richTextBox1.Name = "richTextBox1"; 
    this.richTextBox1.Size = new System.Drawing.Size(188, 352); 
    this.richTextBox1.TabIndex = 2; 
    this.richTextBox1.Text = ""; 
    //  
    // button2 
    //  
    this.button2.Location = new System.Drawing.Point(96, 8); 
    this.button2.Name = "button2"; 
    this.button2.Size = new System.Drawing.Size(64, 23); 
    this.button2.TabIndex = 3; 
    this.button2.Text = "读入"; 
    this.button2.Click += new System.EventHandler(this.button2_Click); 
    //  
    // richTextBox2 
    //  
    this.richTextBox2.Location = new System.Drawing.Point(206, 48); 
    this.richTextBox2.Name = "richTextBox2"; 
    this.richTextBox2.Size = new System.Drawing.Size(195, 352); 
    this.richTextBox2.TabIndex = 4; 
    this.richTextBox2.Text = ""; 
    //  
    // button3 
    //  
    this.button3.Location = new System.Drawing.Point(480, 8); 
    this.button3.Name = "button3"; 
    this.button3.Size = new System.Drawing.Size(71, 23); 
    this.button3.TabIndex = 5; 
    this.button3.Text = "语法分析"; 
    this.button3.UseVisualStyleBackColor = true; 
    this.button3.Click += new System.EventHandler(this.button3_Click); 
    //  
    // richTextBox3 
    //  
    this.richTextBox3.Location = new System.Drawing.Point(408, 48); 
    this.richTextBox3.Name = "richTextBox3"; 
    this.richTextBox3.Size = new System.Drawing.Size(195, 352); 
    this.richTextBox3.TabIndex = 6; 
    this.richTextBox3.Text = ""; 
    //  
    // label1 
    //  
    this.label1.AutoSize = true; 
    this.label1.Location = new System.Drawing.Point(422, 412); 
    this.label1.Name = "label1"; 
    this.label1.Size = new System.Drawing.Size(41, 12); 
    this.label1.TabIndex = 7; 
    this.label1.Text = "label1"; 
    //  
    // Form1 
    //  
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); 
    this.ClientSize = new System.Drawing.Size(625, 436); 
    this.Controls.Add(this.label1); 
    this.Controls.Add(this.richTextBox3); 
    this.Controls.Add(this.button3); 
    this.Controls.Add(this.richTextBox2); 
    this.Controls.Add(this.button2); 
    this.Controls.Add(this.richTextBox1); 
    this.Controls.Add(this.button1); 
    this.MaximizeBox = false; 
    this.Name = "Form1"; 
    this.Text = "分析器"; 
    this.ResumeLayout(false); 
    this.PerformLayout(); 
 
}  
#endregion  
 
///   
/// 应用程序的主入口点。  
///   
[STAThread]  
static void Main()  
{  
Application.Run(new Form1());  
}  
///   
/// 词法分析函数  
///   
///   
///   
private void button1_Click(object sender, System.EventArgs e)  
{  
//得到想要的字符数组。  
char[] getch = textToCharArray(); 
 
 
//将字符数组,转换为词法分析后的 单词数组。  
string[] stringArray = charArrayToStringArray(getch);  
 
//将单词数组分类,用数字标出各个单词所在的类别。  
string[,] twoStringArray = stringArrayToTwoStringArray(stringArray);  
 
//用于输出二维数组。  
printString(twoStringArray);  
 
}  
///   
/// 输出结果 即用于输出二 维数组。  
///   
///   
private void printString(string[,] twoStringArray)  
{  
//提示说明  
this.richTextBox2.Text ="1 -> 关键字" + "\r\n" +  
"2 -> 运算符" + "\r\n" +  
"3 -> 分隔符" + "\r\n" +  
"4 -> 数字 " + "\r\n" +  
"5 -> 其它" + "\r\n"+ 
"============================" + "\r\n"; 
//输出二维数组中的数据  
for(int x=0;x  
/// 打开方件  
///   
///   
///   
private void button2_Click(object sender, System.EventArgs e)// 文件打开的方法。  
{  
openFileDialog1.Filter = "文本文件(*.txt)|*.txt";  
openFileDialog1.Title = "打开要分析的源文件。";  
 
if(openFileDialog1.ShowDialog() == DialogResult.OK)  
{  
System.IO.StreamReader sr = new  
System.IO.StreamReader(openFileDialog1.FileName);  
this.richTextBox1.Text = sr.ReadToEnd();  
sr.Close();  
}  
}  
///   
/// 保存文件   
///   
///   
///   
//private void button3_Click(object sender, System.EventArgs e)  
//{  
//saveFileDialog1.Filter = "文本文件(*.txt)|*.txt";  
//saveFileDialog1.Title = "保存分析结果.";  
//if(saveFileDialog1.ShowDialog() == DialogResult.OK)  
//{  
//System.IO.StreamWriter wr = new  
//System.IO.StreamWriter(saveFileDialog1.FileName);  
//wr.Write(this.richTextBox2.Text);  
//wr.Close();  
//}  
//}  
 
///   
/// 引用二维数组和单词的标志j  
///   
///   
///   
private void oneArrayToTwo(ref string[,] twoArray,ref int j)  
{  
 
string[,] tempArray = twoArray;  
twoArray = new string[2,j+2];  
for(int x=0;x<2;x++)  
{  
for(int y=0;y  
/// 引用单词数组,和要加入单词数组的单词  
///   
///   
///   
private void stringToArrayString(ref string[] stringArrange, string st)  
{  
 
if(stringArrange[0] =="")  
{  
stringArrange[0] = st;  
}  
else  
{  
string[] oldA = stringArrange;//刚得到的字符串  
int i=oldA.Length +1;  
stringArrange = new string[i];//申请一个长一个的字符数组。  
oldA.CopyTo(stringArrange,0);//将先前的字符数组考到现在这个数组中。  
stringArrange[stringArrange.Length -1] = st;  
}  
}  
///   
/// 将Text中的字符串,存入一个字符数组中。  
///   
///   
private char[] textToCharArray()  
{  
string stringTemp;  
stringTemp = this.richTextBox1.Text;  
char[] getch = stringTemp.ToCharArray();//要处理的字符都在getch这个数组中。  
return getch;  
}  
///   
/// 字符数组 到 单词数组  
///   
///   
///   
private string[] charArrayToStringArray(char[] getch)//将字符数组转换为字符串数组。即词法分析后的单词数组。  
{  
string[] stringArrange={""} ;//用这个字符串数组存放词法分析后得到的单词。  
char charTemp;  
string stringSave = "";// 存放一个分析得到的单词  
 
//一次循环因得到一个单词。  
for(int i = 0;i < getch.Length;i++)  
{  
charTemp = getch[i];  
 
//由字母开头 数字和字母组成的单词。  
if( charTemp >= 'a'&&  
charTemp <= 'z'  
||  
charTemp >= 'A' &&  
charTemp <= 'Z' 
    )  
{  
stringSave = charTemp.ToString();  
i = i + 1;  
int test = 0;//判断循环是否结束,1 为结束。  
while(test == 0)  
{  
charTemp = getch[i];  
if( charTemp >= 'a'&&  
charTemp <= 'z'  
||  
charTemp >= 'A' &&  
charTemp <= 'Z' 
||  
charTemp >= '0' &&  
charTemp <= '9')  
{  
stringSave = stringSave + charTemp.ToString();  
i = i + 1;  
}  
else  
test = 1;  
}  
stringToArrayString(ref stringArrange,stringSave);  
}  
stringSave = "";  
//由数字组成的单词。  
if( charTemp >= '0' &&  
charTemp <= '9')  
{  
stringSave = stringSave + charTemp.ToString();  
i = i + 1;  
int test1 = 0;  
while(test1 == 0)  
{  
charTemp = getch[i];  
if( charTemp >= '0' &&  
charTemp <= '9')  
{  
stringSave = stringSave + charTemp.ToString();  
i = i + 1;  
}  
else  
test1 = 1;  
}  
stringToArrayString(ref stringArrange,stringSave);  
}  
stringSave = "";  
//由运算符组成的单词。  
if( charTemp == '+' 
|| charTemp == '-'  
|| charTemp == '*'  
|| charTemp == '/'  
|| charTemp == '=' 
|| charTemp == '<' 
|| charTemp == '>' 
|| charTemp == '!')  
{  
stringSave = stringSave + charTemp.ToString();  
i = i + 1;  
int test2 = 0;  
while(test2 == 0)  
{  
charTemp = getch[i];  
if( charTemp == '+'  
|| charTemp == '-'  
|| charTemp == '*'  
|| charTemp == '/'  
|| charTemp == '='  
|| charTemp == '<' 
|| charTemp == '>' 
|| charTemp == '!')  
{  
stringSave = stringSave + charTemp.ToString();  
i = i + 1;  
}  
else  
test2 = 1;  
}  
stringToArrayString(ref stringArrange,stringSave);  
}  
stringSave = "";  
//由介符组成的单词。  
if( charTemp == '(' 
||charTemp == ')'  
||charTemp == '{'  
||charTemp == '}' 
||charTemp == '['  
||charTemp == ']'  
||charTemp == ','  
||charTemp == ':'  
||charTemp == ';'  
 
 
||charTemp == '\\')  
{  
stringSave = stringSave + charTemp.ToString();  
stringToArrayString(ref stringArrange,stringSave);  
}  
}  
return stringArrange;  
}  
///   
/// 单词数组 到 二维单词数组。  
///   
///   
///   
private string[,] stringArrayToTwoStringArray(string[] stringArray)  
{  
//存放单词标识后的结果。  
string [,] twoArray = new string[2,1];  
//单词的标志  
int j=0;  
/* 
Const(常数)  Dim(定义) As(为) Mod(取模)   
 
And(并且)   Or(或者)   Not(非)  
 
If (如果)  Then(那么)   Else(否则)  
 
Stop(停止) End(结束)  
 
Select(选择)  Case(条件) Is (是)  
 
For(计数)   To(到)    Step(步长)    
 
Byref(传址)  Byval(传值)  
 
Sub(子程序) Function(函数)  Exit(退出)    
 
Do(做)  Loop(循环)   Until(除非)  While(当)  Wend(当结束)   
 
Let(让) Call(调用)  
 
Rem(注释)         
 
Integer(整数)  Long(长整数)  Single(单精度小数) Double(双精度,小数)   Boolean(布尔)  String(字符串,文字)*/ 
 
//每循环一次,把一个单词归于一类,即前面加上一个数字。  
for(int i=0;i"  
|| stringArray[i] == "<"  
|| stringArray[i] == ">="  
|| stringArray[i] == "<="  
|| stringArray[i] == "!="  
|| stringArray[i] == "=="  
|| stringArray[i] == "++"  
|| stringArray[i] == "--"  
|| stringArray[i] == "=")  
{  
twoArray[0,j] = "2";  
twoArray[1,j] = stringArray[i];  
this.oneArrayToTwo(ref twoArray,ref j);  
}  
//分隔符 3  
else  
if( stringArray[i] == "("  
|| stringArray[i] == ")"  
|| stringArray[i] == "{"  
|| stringArray[i] == "}"  
|| stringArray[i] == "["  
|| stringArray[i] == "]"  
|| stringArray[i] == ","  
|| stringArray[i] == ";"  
|| stringArray[i] == ":"  
|| stringArray[i] == "\""  
|| stringArray[i] == "/*"  
|| stringArray[i] == "*/")  
{  
twoArray[0,j] = "3";  
twoArray[1,j] = stringArray[i];  
this.oneArrayToTwo(ref twoArray,ref j);  
}  
//数字 4  
else  
if( stringArray[i].ToCharArray()[0] >='0' &&  
stringArray[i].ToCharArray()[0] <= '9')  
{  
twoArray[0,j] = "4";//数字  
twoArray[1,j] = stringArray[i];  
this.oneArrayToTwo(ref twoArray,ref j);  
}  
//其它 5(变量等)  
else  
{  
twoArray[0,j] = "5";  
twoArray[1,j] = stringArray[i];  
this.oneArrayToTwo(ref twoArray,ref j);  
}  
}  
return twoArray;  
} 
 
private void button3_Click(object sender, EventArgs e) 
{ 
    
    WordAnalyse(); 
    StringBuilder sb = new StringBuilder(); 
    foreach (string item in strList) 
    { 
         
         
            sb.Append(item).Append("\n" ); 
        
         
    } 
    richTextBox3.Text = sb.ToString(); 
} 
    int j = 0; 
StringBuilder sbError = new StringBuilder(); 
private void GramAnalyse() 
{ 
    sbError.Append("行").Append("\t").Append("错误信息!").Append("\n"); 
    if (strList[j] != "begin") 
    { 
        sbError.Append(rowList[j] + 1).Append("\t").Append("开始应为begin").Append("\n"); 
    } 
 
    j++; 
    if (Sentence()) 
    { 
        if (strList[j] != "end") 
            sbError.Append(rowList[j] + 1).Append("\t").Append("应以end结束").Append("\n"); 
    } 
    //else 
    //sbError.Append(rowList[j] + 1).Append("\t").Append("语句出错!").Append("\n"); 
} 
 
 
private bool Sentence()//语句 
{ 
    if (fzSentence()) 
        return true; 
 
    if (tjSentence()) 
        return true; 
    else return false; 
 
} 
private bool fzSentence()//赋值语句 
{ 
    if (!Variable())//变量 
        return false; 
 
    j++; 
    if (strList[j] != ":=")//:= 
    { 
        return false; 
    } 
 
    j++; 
    if (expression()) return true;//表达式 
    else 
    { 
        sbError.Append(rowList[j] + 1).Append("\t").Append("表达式出错!").Append("\n"); 
        return false; 
    } 
 
 
} 
 
private bool tjSentence()//条件语句 
{ 
    if (strList[j] != "if")//if 
        return false; 
 
    j++; 
    if (!expression())//表达式 
    { 
        sbError.Append(rowList[j] + 1).Append("\t").Append("表达式出错!").Append("\n"); 
        return false; 
    } 
 
    if (strList[j] != "then")//then    
    { 
        sbError.Append(rowList[j] + 1).Append("\t").Append("应为then!").Append("\n"); 
        return false; 
    } 
 
    j++; 
    if (Sentence()) return true;//语句 
    else 
    { 
        return false; 
    } 
 
} 
private bool expression()//表达式 
{ 
    if (!Variable()) //变量    
        return false; 
    j++; 
    while (strList[j] == "+")//+ 
    { 
        j++; 
        if (!expression())//表达式 
        { 
            j--; 
            return false; 
        } 
    } 
    return true; 
 
} 
private bool Variable()//变量 
{ 
    if (strList[j] == "i") 
    { 
        return true; 
    } 
    else 
    { 
        return false; 
    } 
} 
#region 词法分析 
List strList; 
List typeList; 
List rowList; 
private void WordAnalyse()//词法分析 
{ 
    strList = new List(); 
    typeList = new List(); 
    rowList = new List(); 
    int row = 0; 
    char[] arr = richTextBox1.Text.ToCharArray(); 
    List l = new List(); 
 
    string s; 
    bool letterStar = false; bool digitStart = false; 
    for (int i = 0; i < arr.Count(); i++) 
    { 
        if (isLetter(arr[i]))//字母 
        { 
            l.Add(arr[i]); 
            if (digitStart == true) label1.Text = "第" + row.ToString() + "行出错!"; 
            if (letterStar == false && digitStart == false) letterStar = true; 
        } 
        else if (isDigit(arr[i]))//数字 
        { 
            l.Add(arr[i]); 
            if (letterStar == false && digitStart == false) digitStart = true; 
        } 
        else if (isoperate(arr[i]) == true)//运算符 
        { 
            s = new string(l.ToArray()); 
            if (digitStart == true) 
            { 
                Save(row, 3, s); 
            } 
            else if (letterStar == true) 
            { 
                if (isKeyword(s)) 
                    Save(row, 1, s); 
                else 
                    Save(row, 2, s); 
            } 
            letterStar = false; digitStart = false; 
            l.Clear(); 
 
 
            if ((arr[i] == '<') && ((arr[i + 1] == '=') || (arr[i + 1] == '>'))) 
            { 
                l.Add(arr[i]); 
                l.Add(arr[i + 1]); 
                i++; 
            } 
            else if ((arr[i] == '>') && (arr[i + 1] == '=')) 
            { 
                l.Add(arr[i]); 
                l.Add(arr[i + 1]); 
                i++; 
            } 
            else 
            { 
                l.Add(arr[i]); 
            } 
 
            s = new string(l.ToArray()); 
            Save(row, 4, s); 
            l.Clear(); 
        } 
        else if (isSeperate(arr[i]))//分隔符 
        { 
            s = new string(l.ToArray()); 
            if (digitStart == true) 
            { 
                Save(row, 3, s); 
            } 
            else if (letterStar == true) 
            { 
                if (isKeyword(s)) 
                    Save(row, 1, s); 
                else 
                    Save(row, 2, s); 
            } 
            letterStar = false; digitStart = false; 
            l.Clear(); 
 
            if (arr[i] == '\n') row = row + 1;//行数 
 
            if (!(arr[i] == ' ') && !(arr[i] == '\n') && !(arr[i] == '\t')) 
            { 
                if (arr[i] == ':' && arr[i + 1] == '=') 
                { 
                    l.Add(arr[i]); 
                    l.Add(arr[i + 1]); 
                    i++; 
                } 
                else 
                { 
                    l.Add(arr[i]); 
                } 
                s = new string(l.ToArray()); 
                Save(row, 5, s); 
                l.Clear(); 
            } 
        } 
        else 
        { 
            label1.Text = "第" + row.ToString() + "行非法字符!"; 
        } 
        if (i == arr.Count() - 1) 
        { 
            s = new string(l.ToArray()); 
            if (digitStart == true) 
            { 
                Save(row, 3, s); 
            } 
            else if (letterStar == true) 
            { 
                if (isKeyword(s)) 
                    Save(row, 1, s); 
                else 
                    Save(row, 2, s); 
            } 
            letterStar = false; digitStart = false; 
            l.Clear(); 
 
        } 
 
    } 
} 
 
 
 
 
 
private bool isSeperate(char c)//是否分隔符 
{ 
    bool boo = false; 
    switch (c) 
    { 
        case ',': boo = true; break;//逗号 
        case ';': boo = true; break;//分号 
        case '.': boo = true; break;//句号 
        case ':': boo = true; break;//冒号 
        case '(': boo = true; break; 
        case ')': boo = true; break; 
        case ' ': boo = true; break; 
        case '\n': boo = true; break; 
        case '\t': boo = true; break; 
        default: boo = false; break; 
    } 
 
 
    return boo; 
} 
private bool isKeyword(string str)//是否关键字 
{ 
    bool boo = false; 
    switch (str.ToUpperInvariant()) 
    { 
        case "BEGIN": boo = true; break; 
        case "DO": boo = true; break; 
        case "ELSE": boo = true; break; 
        case "END": boo = true; break; 
        case "IF": boo = true; break; 
        case "THEN": boo = true; break; 
        case "VAR": boo = true; break; 
        case "WHILE": boo = true; break; 
        case "INTEGER": boo = true; break; 
 
    } 
    return boo; 
} 
private bool isoperate(char c)//是否操作符 
{ 
 
    //bool boo=false; 
    string str = "+-*/<=>"; 
    if (str.Contains(c)) 
        return true; 
    else return false; 
    //if (c == '+') 
    //{ 
    //    boo=true; 
    //} 
    //if (c == '-') 
    //{ 
    //    boo = true; 
    //} 
    //if (c == '*') 
    //{ 
    //    boo = true; 
    //} 
    //if (c == '/') 
    //{ 
    //    boo = true; 
    //} 
    //if (c == '<') 
    //{ 
    //    boo = true; 
    //} 
    //if (c == '=') 
    //{ 
    //    boo = true; 
    //} 
    //if (c == '>') 
    //{ 
    //    boo = true; 
    //} 
    //return boo; 
 
} 
private bool isLetter(char c)//是否字母或下划线 
{ 
    bool boo = false; 
    string str = "abcdefghijklmnopqrstuvwxyz_"; 
    if (str.Contains(c)) 
    { 
        boo = true; 
    } 
    string str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ_"; 
    if (str1.Contains(c)) 
    { 
        boo = true; 
    } 
    return boo; 
} 
private bool isDigit(char c)//是否数字 
{ 
    bool boo = false; 
    string str = "0123456789"; 
    if (str.Contains(c)) 
    { 
        boo = true; 
    } 
    return boo; 
} 
private void Save(int row, int type, string word) 
{ 
    rowList.Add(row); 
    typeList.Add(type); 
    strList.Add(word); 
} 
#endregion 
}  
}