用具递归功能的的高级语言来编制递归下降法的语法分析程序,并用其对Pascal语法算术表达式的一个简化子集进行语法分析,分析过程不嵌入任何语义动作。 1.文法规则是:
算术表达式 = 项 | 算术表达式+项 | 算术表达式-项 项 = 因式 | 项 * 因式 | 项/因式
因式= 变量 | (算术表达式) 变量=字母
字母=A| B| C| D| E| F| G| H| I| J| K| L| M| N| O| P| Q| R| S| T| U| V| W| X| Y| Z| a| b| c| d| e| f| g| h| I| j| k| l| m| n| o| p| q| r| s| t | u| v| w| x| y| z
2.构造如下的文法:
S代表算术表达式 E代表项 T代表因式 F代表变量 N代表字母
那么够则的文法为G[S]: S->E | S+E|S-E E->T | E* E | E/T T->F | (S) F ->N
N-> A| B| C| D| E| F| G| H| I| J| K| L| M| N| O| P| Q| R| S| T|
U| V| W| X| Y| Z| a| b| c| d| e| f| g| h| I| j| k| l| m| n| o| p| q| r| s| t | u| v| w| x| y| z
3.消除左递归,得如下的一个新文法:
S->ES1
S1->+ES1 | - ES1 | ∑ E ->TE1
E1-> *TE1 | / TE1 | ∑ T-> F | (S) F-> N
N-> A| B| C| D| E| F| G| H| I| J| K| L| M| N| O| P| Q| R| S| T| U|
V| W| X| Y| Z| a| b| c| d| e| f| g| h| I| j| k| l| m| n| o| p| q| r| s| t | u| v| w| x| y| z
4.编写如下源代码: /*
* @(#)Wenfajiance.java 1.0 06/05/25 *
* You can modify the template of this file in the
* directory ..\\JCreator\\Templates\\Template_1\\Project_Name.java *
* You can also create your own project template by making a new * folder in the directory ..\\JCreator\\Template\\. Use the other * templates as examples. *作者:沈云军
*联系地址:湖南省衡阳市南华大学计算机学院 */
package myprojects.wenfajiance;
import java.awt.*; import java.awt.event.*;
class Wenfajiance extends Frame implements ActionListener{ Button btn1;
TextField txf1; char sym; String str; static int i;
public Wenfajiance() { Panel pan1=new Panel(); Panel pan2=new Panel();
Label lb1=new Label(\请输入你要语法检查的单词序列以$结尾:\ pan1.setLayout(new FlowLayout(FlowLayout.LEFT)); pan2.setLayout(new FlowLayout(FlowLayout.LEFT)); btn1=new Button(\检查\ txf1=new TextField(30); pan1.add(lb1); pan2.add(txf1); pan2.add(btn1);
this.setLayout(new BorderLayout()); this.add(pan1,BorderLayout.NORTH); this.add(pan2,BorderLayout.CENTER); btn1.addActionListener(this);
addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } }); }
public void actionPerformed(ActionEvent e)
{ i=0;
str=txf1.getText(); scaner(); S();
if(sym=='$')
txf1.setText(\正确\ else
txf1.setText(\不正确\ }
public static void main(String args[]) { //System.out.println(\ Wenfajiance mainFrame = new Wenfajiance(); mainFrame.setSize(255, 160); mainFrame.setLocation(400,150); mainFrame.setTitle(\ mainFrame.setVisible(true); }
public void scaner()//read the next sym; {
if(i sym=str.charAt(i); i++; } }//end of scaner public void S() { E(); S1(); }//end of S public void S1() { if(sym=='+') { scaner(); E(); S1(); } else if(sym=='-') { scaner(); E(); S1(); } else if((sym !=')') && (sym !='$')) error(); }//end of S1 public void E() { T(); E1(); }//end of E 搜索“diyifanwen.net”或“第一范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,第一范文网,提供最新高中教育语法分析 全文阅读和word下载服务。
相关推荐: