编译原理之词法分析(C语言)
(2011-04-17 23:55:37)
标签:
杂谈 |
编译原理之词法分析*(C语言)
//词法分析
//main.c
//@author langx
#include "stdio.h"
//定义I/O库所用的某些宏和变量
#include "string.h"
//定义字符串库函数
#include "conio.h"
//提供有关屏幕窗口操作函数
#include "ctype.h"
//分类函数
#define LEN 6
char prog[80]= {'\0'},
token[80]=
{'\0'};
//存放构成单词符号的字符串
char ch;
int syn,
//存放单词字符的种别码
n,
sum,
//存放整数型单词
m,p;
//p是缓冲区prog的指针,m是token的指针
char *rwtab[LEN]= {"begin","if","then","while","do","end"};
scaner()
{
m=0;
sum=0;
for(n=0;
n<8; ++n)token[n]='\0';
ch=prog[p++];
while(ch=='
')
ch=prog[p++];
if(isalpha(ch))
//ch为字母字符
{
while(isalpha(ch)||isdigit(ch))
//ch 为字母字符或者数字字符
{
token[m++]=ch;
一 词法
(1)关键字:
所有的关键字都是小写。
(2)运算符和界符
: =
(3)其他单词是标识符(ID)和整型常数(SUM),通过以下正规式定义:
ID = letter (letter | digit)*
NUM = digit digit*
(4)空格有空白、制表符和换行符组成。空格一般用来分隔ID、SUM、运算符、界符和关键字,词法分析阶段通常被忽略。
二 各种单词符号对应的种别码
|
单词符号 |
种别码 |
单词符号 |
种别码 |
|
bgin |
1 |
: |
17 |
|
If |
2 |
:= |
18 |
|
Then |
3 |
< |
20 |
|
wile |
4 |
<> |
21 |
|
do |
5 |
<= |
22 |
|
end |
6 |
> |
23 |
|
lettet(letter|digit)* |
10 |
>= |
24 |
|
dight dight* |
11 |
= |
25 |
|
+ |
13 |
; |
26 |
|
— |
14 |
( |
27 |
|
* |
15 |
) |
28 |
|
/ |
16 |
# |
0 |
三 词法分析程序的功能:
输入:所给文法的源程序字符串。
输出:二元组(syn,token或sum)构成的序列。
其中:syn为单词种别码;
例如:对源程序begin x:=9: if x>9 then x:=2*x+1/3; end #的源文件,经过词法分析后输出如下序列:
(1,begin)(10,x)(18,:=)(11,9)(26,;)(2,if)……
============================================================================//词法分析
//main.c
//@author langx
#include "stdio.h"
#include "string.h"
#include "conio.h"
#include "ctype.h"
#define LEN 6
char prog[80]= {'\0'},
char ch;
int syn,
char *rwtab[LEN]= {"begin","if","then","while","do","end"};
scaner()
{

加载中…