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

📄 syntax_analyzerdlg.cpp

📁 MFC做的语法分析器
💻 CPP
字号:
// syntax_analyzerDlg.cpp : implementation file
//

#include "stdafx.h"
#include "syntax_analyzer.h"
#include "syntax_analyzerDlg.h"
#include<stdio.h>
#include<malloc.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSyntax_analyzerDlg dialog

CSyntax_analyzerDlg::CSyntax_analyzerDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSyntax_analyzerDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CSyntax_analyzerDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CSyntax_analyzerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CSyntax_analyzerDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CSyntax_analyzerDlg, CDialog)
	//{{AFX_MSG_MAP(CSyntax_analyzerDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_open, Onopen)
	ON_BN_CLICKED(IDC_analyz, Onanalyz)
	ON_BN_CLICKED(IDC_save, Onsave)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSyntax_analyzerDlg message handlers

BOOL CSyntax_analyzerDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CSyntax_analyzerDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CSyntax_analyzerDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CSyntax_analyzerDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

#define READ(ch) ch=getc(fpin)     //宏:READ(ch)

char ch;             //声明为全局变量

bool  right=false;   //判断结果是否正确

struct struCH
{
	char   ch;
    struct struCH *next;

}struCH,*temp,*head,*shift;

//head指向字符线性链表的头结点

//shift指向动态建成的结点(游标)

void CSyntax_analyzerDlg::E()
{
	T();
	E1();
}
 
void CSyntax_analyzerDlg::E1()
{
	if(shift->ch=='+'||shift->ch=='-')
	{
		shift=shift->next;
        T();
        E1();
    }
    else
	{
		if(shift->ch=='#'||shift->ch==')')
		return;
		else
		right=false;
    }
}

void CSyntax_analyzerDlg::T(void)
{
	F();
	T1();
}

void CSyntax_analyzerDlg::T1(void)
{

       if(shift->ch=='*'||shift->ch=='/')
	   {
           shift=shift->next;
           F();
           T1();
       }
       else
	   {		 //如果不是'#'or')'or'+'or'+'or'-'则出错
           if(shift->ch!='#'&&shift->ch!=')'&&shift->ch!='+'&&shift->ch!='-')
           right=false;  
       }
}

void CSyntax_analyzerDlg::F(void)
{

       if(shift->ch=='i')
          shift=shift->next;
       else
	   {
          if(shift->ch=='(')
		  {
              shift=shift->next;
              E();
              if(shift->ch==')')
                shift=shift->next;
              else
                right=false;
          }
          else
            right=false;
       }
}

/**************遍历整个文件检测是否有非法字符***************/
       /*如果用while(!feof(fpin))语言,将会多出一个字符
      所以这里采用以下方法遍历整个文件检测其否有非法字符*/

//[1]计算文件中字符数量
void CSyntax_analyzerDlg::analyse(FILE *fpin,FILE *fpout)
{

    int errnum=0,k=0,m=0,countchar=0,rownum;
    int charerr=0;         //开关控制量

    while((ch=fgetc(fpin))!=EOF) 
	{
        countchar++;             //统计文件中的字符数(包括换行符及文件结束符)
    }
    rewind(fpin);                //将fpin文件指针重新指向文件头处,以备后面对文件的操作
	
//[2]开始遍历文件
    while(k<countchar)
	{      
        ch=getc(fpin);          
        if(!(ch=='('||ch==')'||ch=='i'||ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='#'||ch=='\n'))
		{
			charerr=1;
			errnum++;       //charerror出错标记,errnum统计出错个数
        }
        k++;      
    }

       rewind(fpin);        //将fpin文件指针重新指向文件头处,以备后面的建链表操作

       if(charerr==1)		//文件中有非法字符
	   {
		   MessageBox("存在非法字符","语法分析器",MB_ICONEXCLAMATION);
		   return;			//正常退出本程序
	   }
     
/*******************非空且无非法字符,则进行识别操作*****************/

       for(rownum=1;m<(countchar-1);rownum++)//识别所有行,rownum记录行号
	   {
              right=true;

              //初始存放待识别的表达式的线性链表头
              shift=(struct struCH *)malloc(sizeof(struCH));
              shift->next=NULL;
              head=shift;

              //读取一行形成线性链表
              READ(ch);
			  fprintf(fpout,&ch);
			  m++;
              while(ch!='\n'&&m<(countchar)) //行末or到文件尾。最后会读取文件结束符
			  {
										 //读取ch,读取存入结点,这样每行便形成一个线性链表
                     temp=(struct struCH *)malloc(sizeof(struCH));//得到一块新内存,值是随机的
                     temp->ch=ch;
                     temp->next=NULL;
                     shift->next=temp;
                     shift=shift->next;
					 READ(ch);
                     if(m!=(countchar-1)) fprintf(fpout,&ch);//不输出最后一次读取的文件结束符
                     m++;
              }

              head=head->next;           //消去第一个空头结点,并使head指向非空线性链表头
              shift=head;                //shift指向头结点,以便后面识别操作
              fprintf(fpout,"%d\n");

              E();                       //开始识别一行              
              if(shift->ch=='#'&&right==true)  //正确提示:[文件名] Line [行号]:right expression!
                fprintf(fpout,"%sLine%d\n",":\tright expression!",rownum);
              else                       //错误提示:[文件名] Line [行号]:error expression!
                fprintf(fpout,"%s  Line %d\n",":\t error expression!",rownum); 
              fprintf(fpout,"%d\n");

       }					//end for
       fprintf(fpout,"Completed!\n");
       //fclose(fpin);      //关闭文件
       //exit(0);           //正常结束程序
}

void CSyntax_analyzerDlg::Onopen() 
{
	// TODO: Add your control notification handler code here
		CFileDialog openFile(true);                        //定义对话框对象
	openFile.m_ofn.lpstrTitle="请选择你要词法分析的文件";  //对话框显示的标题
	openFile.m_ofn.lpstrInitialDir="e:\\";                 //对话框初始目录
	if(openFile.DoModal())					 //顾名思义:DO Modal 弹出对话框成功 
	{
		m_strFileName=openFile.GetPathName();//对话框对象获取路径名
		
		CStdioFile fstream;                  //定义能打开流式文件的对象
		CString str;						 //存放文件字符串
		if(fstream.Open(m_strFileName.GetBuffer(0),CFile::modeRead))//成功打开文件
		{
			CString  strTemp;				 //定义临时保存字符串变量
			while(fstream.ReadString(strTemp))//对象读流式文件
			{
				str+=strTemp;				 //每读一个字符串都换行
				str+="\r\n";
			}	
			SetDlgItemText(IDC_input,str);   //在源文件框输入框显示
			
			fstream.Close();				 //关闭流文件
		}
	}
}

void CSyntax_analyzerDlg::Onanalyz() 
{
	// TODO: Add your control notification handler code here
	if(this->m_strFileName.IsEmpty())         //如果当前没有打开文件
	{
		MessageBox("请先选择文件","语法分析器",MB_ICONEXCLAMATION);
		return;
	}
	FILE* fpin=fopen(m_strFileName.GetBuffer(0),"r");//定义打开读文件指针对象
	FILE* fpout=fopen("output.txt","w");             //定义打开写文件指针对象
	analyse(fpin,fpout);			//词法分析
	fclose(fpin);		//用读文件指针关闭文件
	fclose(fpout);		//用写文件指针关闭文件

	CStdioFile fstream;
	CString str;
	if(fstream.Open("output.txt",CFile::modeRead))   //输出到结果显示框
	{
		CString  strTemp;
		while(fstream.ReadString(strTemp))
		{
			str+=strTemp;
			str+="\r\n";
		}	
		SetDlgItemText(IDC_result,str);
		
		fstream.Close();
	}
}

void CSyntax_analyzerDlg::Onsave() 
{
	// TODO: Add your control notification handler code here
	if(this->m_strFileName.IsEmpty())			//如果没有打开文件报错
	{
		MessageBox("请先选择文件","词法分析器",MB_ICONEXCLAMATION);
		return;	
	}

	CFile fstream;
	if(fstream.Open(this->m_strFileName,CFile::modeWrite|CFile::modeCreate))
	{
		UpdateData();						//MFC使更新数据有效
		char buf[200]={0};
		GetDlgItemText(IDC_input,buf,200);	//把结果输出框的字节读到buf[]中
		fstream.Write(buf,strlen(buf));     //把strlen(buf)长度的字节流写到buf[]中
		fstream.Close();
		MessageBox("该文件保存成功","语法分析器",MB_ICONINFORMATION);
	}	
}

⌨️ 快捷键说明

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