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

📄 bydlg.cpp

📁 词法分析器,将输入的字符串识别成c语言的关键字等
💻 CPP
字号:
// byDlg.cpp : implementation file
//

#include "stdafx.h"
#include "by.h"
#include "byDlg.h"

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

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

char  ch =' ';			// 存放读入当前的输入字符
int lineno;

struct reserve		 //关键字
{
	char lexptr[MAXBUF];
	int token;
};

struct reserve symtable[MAX];
char * str[]={"int","printf","auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","inline","int",
"long","register","restrict","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while" };



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()

/////////////////////////////////////////////////////////////////////////////
// CByDlg dialog

CByDlg::CByDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CByDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CByDlg)
		// 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 CByDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CByDlg)
	DDX_Control(pDX, IDC_STATIC1, m_me);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CByDlg, CDialog)
	//{{AFX_MSG_MAP(CByDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_OPEN, OnOpen)
	ON_BN_CLICKED(IDC_FENXI, OnFenxi)
	ON_BN_CLICKED(IDC_STATIC1, OnStatic1)
	ON_BN_CLICKED(IDC_SAVE, OnSave)
	ON_BN_CLICKED(IDC_BUTTON1, OnOk)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CByDlg message handlers

BOOL CByDlg::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
	
	m_font.CreateFont(12, 0,0,0,FW_NORMAL, 0,0,0,
		DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS,
		DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Fixedsys");
	GetDlgItem(IDC_EDIT1)->SetFont(&m_font);
	GetDlgItem(IDC_EDIT2)->SetFont(&m_font);

	m_me.SetToolTipText("访问我的网站: http://210.40.7.234/~j3b083");

	

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CByDlg::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 CByDlg::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 CByDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CByDlg::init()
{
	for( int j=0; j<18; j++)
	{ 
		strcpy(symtable[j].lexptr,str[j]);
		symtable[j].token=j+3;
	}

}

int CByDlg::search(char *temp)
{

	for(int i=0; i<sizeof(symtable)/sizeof(symtable[0]); i++)
	{
		if(!strcmp(symtable[i].lexptr ,temp))
		{
			return  symtable[i].token;
		}
	}
	return 0;
}

 void CByDlg::analyse(FILE *fpin, FILE *fpout)
{
	char arr[MAXBUF];
	int i=0;
	int j=0;
	int s_count=0;
	bool flag=0;
	int m_count=0;
	char c[MAXBUF];
	while((ch=fgetc(fpin))!=EOF)  		//读入字符判断,空格、字母、数字、界符
	{
		if(ch==' '||ch=='\t')
		{
			
		}
		else if(ch=='\n')				//如果是换行符,则行号加1
		{  
			lineno++;
		}
		else if(isdigit(ch))			//如果是数字
		{ char a[500];
		int t=0;int count=0;
			while(isdigit(ch)||ch=='.')			//判断和读取数字
			{
				arr[j]=ch;
				a[j]=ch;
				j++;
				ch=fgetc(fpin);
				t=j;

			} 
			arr[j]='\0';
			j=0;
			fseek(fpin,-1L,SEEK_CUR);
			for(int i=0;i<t;i++){
				if(a[i]=='.')
					count++;
			}
			if(count==1)
			fprintf(fpout,"(real,%s)\n",arr);
				else if(count>1)
            fprintf(fpout,"无法识别%s\n",arr);
				else
		    fprintf(fpout,"(integer,%s)\n",arr);
		}
		else if (isalpha(ch)||ch=='_')		//如果是字母
		{   //char b[500];
		    //int n=0;//bool flag;
			while(isalpha(ch)||isdigit(ch)||ch=='_')
			{
				arr[j]=ch;
				//b[j]=ch;
				j++;
				ch=fgetc(fpin);
				//n=j;
			}
			fseek(fpin,-1L,SEEK_CUR);
			arr[j]='\0';
			j=0;
			//for(int m=0;m<n;m++){
			//	if(b[m]=='@')
			//		flag=1;
			//	else flag=0;
			//}
			if (search(arr))	//如果是关键字
			{
				fprintf(fpout,"(%s,_)\n",arr);
			}
			//else if(flag)
			//	fprintf(fpout,"(出错,%s)\n",arr); 
			else
				fprintf(fpout,"(id,%s)\n",arr);	//普通标志符
		}
		else if(ch==':')  
		{
			ch=fgetc(fpin);
			if(ch=='=') 
			{
				fprintf(fpout,"(%s,_)\n",":=");    //如果是 :=
			}
			else
			{
				fprintf(fpout,"(%s,_)\n",":");   //如果是 :
				fseek(fpin,-1L,SEEK_CUR);
			}
		}
		else if (ch=='>')
		{
			ch=fgetc(fpin);
			if(ch=='=')    //如果是 >=
			{
				fprintf(fpout,"(%s,_)\n",">=");
			}
			else
			{
				fprintf(fpout,"(%s,_)\n",">");  //如果是 >
				fseek(fpin,-1L,SEEK_CUR);
			}
		}
		else if(ch=='<')
		{ 
			ch=fgetc(fpin);
			if(ch=='>')
			{
				fprintf(fpout,"(%s,_)\n","<>");  // 如果是 <>
			}
			else if(ch=='=')
			{
				fprintf(fpout,"(%s,_)\n","<=");   //如果是 <=
			}
			else 
			{
				fprintf(fpout,"(%s,_)\n","<");   //如果是 <
				fseek(fpin,-1L,SEEK_CUR);
			}
		}
		else if(ch=='/')
		{ 
			ch=fgetc(fpin);
			if(ch=='*')
			{
				ch=fgetc(fpin);
s:
				while(ch!='*')
				{
					ch=fgetc(fpin);
				}
				while(ch=='*')
				{
					ch=fgetc(fpin);
					while(ch!='/')
					{
						goto s;			//如果是注释 /*  */
					}
				}
			}
			else if(ch=='/')
			{
				ch=fgetc(fpin);
				while(ch!='\n')
				{
					ch=fgetc(fpin);	  //如果是注释 //
				}
			}
			else 
			{  
				fprintf(fpout,"(%s,_)\n","/");
				fseek(fpin,-1L,SEEK_CUR);
			}
		}
		else if(ch=='+')
		{
			fprintf(fpout,"(%s,_)\n","+");
		}
		else if(ch=='-')
		{
			fprintf(fpout,"(%s,_)\n","-");
		}
		else if(ch=='*')
		{
			fprintf(fpout,"(%s,_)\n","*");
		}
		else if(ch=='(')
		{
			fprintf(fpout,"(%s,_)\n","(");
		}
		else if(ch==')')
		{
			fprintf(fpout,"(%s,_)\n",")");
		}
		else if(ch=='[')
		{
			fprintf(fpout,"(%s,_)\n","[");
		}
		else if(ch==']')
		{
			fprintf(fpout,"(%s,_)\n","]");
		}
		else if(ch=='.')
		{
			fprintf(fpout,"(%s,_)\n",".");
		}
		else if(ch==';')
		{
			fprintf(fpout,"(%s,_)\n",";");
		}
		else if(ch=='=')
		{
			fprintf(fpout,"(%s,_)\n","=");
		}
		else if(ch==',')
		{
			fprintf(fpout,"(%s,_)\n",",");
		}
		else if(ch=='@')
		{
        fprintf(fpout,"(出错,%s)\n","@"); 
		}
		else if(ch=='"'){
		fprintf(fpout,"(%s,_)\n","\"");
        m_count=1;
	    s_count=s_count+1;
		}
		else fprintf(fpout,"(%c,_)\n",ch);
			//m_count=i;
		
        if(s_count==1){
			do{
			ch=fgetc(fpin);
			if(ch=='"')s_count=s_count+1;
		    c[i]=ch;
	    	i++;
		}while(s_count!=2&&ch!=EOF);
			if(s_count==1)
			{
				c[i-1]='\0';
			fprintf(fpout,"(id,%s)\n",c);
			flag=0;}
		else{s_count=0;
		flag=1;
		c[i-1]='\0';
	   }
		}
	  if(flag){	
		    i=0;
			flag=0;
			fprintf(fpout,"(sentence,%s)\n",c);
		}
	 if(m_count==1)
	{
		fprintf(fpout,"(%s,_)\n","\"");
			m_count=0;
	}
		//}	else fprintf(fpout,"(%c,_)\n",ch);
   }
   //else fprintf(fpout,"(%c,_)\n",ch);
}

void CByDlg::OnOpen() 
{
	CFileDialog fd(true);
	fd.m_ofn.lpstrTitle="请选择你要打开的文件";  //标题
	fd.m_ofn.lpstrInitialDir="d:\\";            //初始目录
	if(fd.DoModal())
	{
		m_strFileName=fd.GetPathName();
		
		CStdioFile sf;
		CString str;
		if(sf.Open(m_strFileName.GetBuffer(0),CFile::modeRead))
		{
			CString  strTemp;
			while(sf.ReadString(strTemp))
			{
				str+=strTemp;
				str+="\r\n";
			}	
			SetDlgItemText(IDC_EDIT1,str);
			
			sf.Close();
		}
	}
}

void CByDlg::OnFenxi() 
{
	if(this->m_strFileName.IsEmpty())
	{
		MessageBox("请先选择一个源文件或者保存你编辑的代码后再进行词法分析","词法分析器",MB_ICONEXCLAMATION);
		return;
	}
	FILE* fpin=fopen(m_strFileName.GetBuffer(0),"r");
	FILE* fpout=fopen("output.txt","w");
	init();
	analyse(fpin,fpout);
	fclose(fpin);
	fclose(fpout);	

	CStdioFile sf;
	CString str;
	if(sf.Open("output.txt",CFile::modeRead))
	{
		CString  strTemp;
		while(sf.ReadString(strTemp))
		{
			str+=strTemp;
			str+="\r\n";
		}	
		SetDlgItemText(IDC_EDIT2,str);
		
		sf.Close();
	}

}

void CByDlg::OnStatic1() 
{
	::ShellExecute(NULL,"open","http://210.40.7.234/~j3b083",NULL,NULL,SW_SHOWNORMAL);
}

BOOL CByDlg::PreTranslateMessage(MSG* pMsg) 
{
    if(pMsg -> message == WM_KEYDOWN)
	{
        if(pMsg -> wParam == VK_ESCAPE)
		return TRUE;

	}return CDialog::PreTranslateMessage(pMsg);	

}

void CByDlg::OnSave() 
{
	if(this->m_strFileName.IsEmpty())
	{
		CFileDialog fd(false);
		fd.m_ofn.lpstrTitle="请选择你要打开的文件";  //标题
		fd.m_ofn.lpstrInitialDir="d:\\";            //初始目录
		if(fd.DoModal())
		{
			m_strFileName=fd.GetPathName();
		}
			
	}

	CFile sf;
	if(sf.Open(this->m_strFileName,CFile::modeWrite|CFile::modeCreate))
	{
		UpdateData();
		char buf[5000]={0};
		GetDlgItem(IDC_EDIT1)->GetWindowText(buf,5000);
		sf.Write(buf,strlen(buf));
		sf.Close();
		MessageBox("保存成功","词法分析器",MB_ICONINFORMATION);
	}	
}

BOOL CByDlg::PreCreateWindow(CREATESTRUCT& cs) 
{
   // Create a window without min/max buttons or sizable border.
   cs.style = WS_OVERLAPPED | WS_SYSMENU | WS_BORDER;

   // Size the window to 1/3 screen size and center it.
   cs.cy = ::GetSystemMetrics(SM_CYSCREEN) ;
   cs.cx = ::GetSystemMetrics(SM_CXSCREEN) ;
   cs.y = ((cs.cy * 3) - cs.cy);
   cs.x = ((cs.cx * 3) - cs.cx);

    return CByDlg::PreCreateWindow(cs);

}

void CByDlg::OnOk() 
{
//if(AfxMessageBox("确定"))
CByDlg::OnOK();
}

⌨️ 快捷键说明

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