实验一、词法
分析
定性数据统计分析pdf销售业绩分析模板建筑结构震害分析销售进度分析表京东商城竞争战略分析
实验
手工实现、使用工具实现(例3.3所给的简单语言,可扩充)
实验目的
手工实现、使用工具实现(例3.3所给的简单语言,可扩充)
实验原理
1、算法的基本任务是从字符串表示的源程序中识别出具有独立意义的单词符号;
2、其基本思想是根据扫描到单词符号的第一个字符的种类,拼出相应的单词符号。
主要仪器设备
操作系统:WindowsXP
开发语言:Visual C++6.0
主要内容和步骤
(1)建立工作文件夹
如 D:\LEX
将词法分析工具flex.exe 拷入到该文件夹
(2)建立LEX源文件
如:用文本编辑器建立lextemp.txt源文件
%{
#include
#define BEGIN 101
#define END 202
%}
digit [0-9]
alpha [a-z]
alnum [a-z0-9]
%%
begin {out(BEGIN,"begin");}
end {out(END,"end");}
"*" {out(303,"*");}
"+" {out(404,"+");}
{alpha}{alnum}* {out(505,yytext);}
"=" {out(606,"=");}
%%
out(int c,char *val)
{
printf("word:%d, %s\n",c,val);
}
(3)建立简单语言的源程序文件
如:用文本编辑器建立data.txt文件
begin
abcd=100
efg=200
gh123=300
abcd=abcd*efgh+gh123
end
(4)在DOS运行flex 生成目标文件 lex.yy.c
flex lex源文件名
如:d:\lex\flex lextemp.txt
(5)进入VC,对lex.yy.c进行修改
1.增加或修改main()函数
1.1增加打开程序文件的语句
int main(void)
{
int c;
if ((yyin=fopen("data.txt","r"))==NULL)
{printf("can’t open the file\n");
exit(0);
}
yylex();
return 0;
}
2.增加函数
int yywrap()
{
return 0;
}
3.尾部上这二行屏蔽 // #if YY_MAIN
// #Endif
#ifdef YY_USE_PROTOS
static void yy_flex_free( void *ptr )
#else
static void yy_flex_free( ptr )
void *ptr;
#endif
{
free( ptr );
}
int yywrap()
{
return 0;
}
//#if YY_MAIN
int main(void)
{
int c;
if ((yyin=fopen("data.txt","r"))==NULL)
{printf("can't open the file\n");
exit(0);
}
yylex();
return 0;
}
//#endif
#line 16 "lextemp.txt"
out(int c,char *val)
{
printf("word:%d, %s\n",c,val);
}
软件设计与编程
/* A lexical scanner generated by flex */
/* Scanner skeleton version:
* $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.85 95/04/24 10:48:47 vern Exp $
*/
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#include
/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */
#ifdef c_plusplus
#ifndef __cplusplus
#define __cplusplus
#endif
#endif
#ifdef __cplusplus
#include
#include
/* Use prototypes in function declarations. */
#define YY_USE_PROTOS
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else
/* ! __cplusplus */
#if __STDC__
……
#ifdef YY_USE_PROTOS
static void yy_flex_free( void *ptr )
#else
static void yy_flex_free( ptr )
void *ptr;
#endif
{
free( ptr );
}
int yywrap()
{
return 0;
}
//#if YY_MAIN
int main(void)
{
int c;
if ((yyin=fopen("data.txt","r"))==NULL)
{printf("can't open the file\n");
exit(0);
}
yylex();
return 0;
}
//#endif
#line 16 "lextemp.txt"
out(int c,char *val)
{
printf("word:%d, %s\n",c,val);
}
程序测试结果
问题与建议
通过此次实验,让我了解到如何设计、编制并调试词法分析程序,加深对词法分析原理的理解,使用某种高级语言(例如C++语言)直接编写此法分析程序。