編譯原理之詞法分析程序的設計與實現


一、程序要求(以python為例)。

 

1.詞法分析程序(Lexical Analyzer)要求:

- 從左至右掃描構成源程序的字符流

-  識別出有詞法意義的單詞(Lexemes

-  返回單詞記錄(單詞類別,單詞本身)

-  濾掉空格

-  跳過注釋

-  發現詞法錯誤

 

2.程序結構:

輸入:字符流(什么輸入方式,什么數據結構保存)

處理:

–遍歷(什么遍歷方式)

–詞法規則

輸出:單詞流(什么輸出形式)

–二元組

 

3.單詞類別:

1.標識符(10)

2.無符號數(11)

3.保留字(一詞一碼)

4.運算符(一詞一碼)

5.界符(一詞一碼)

 

單詞符號

種別碼

單詞符號

種別碼

begin

1

:

17

if

2

:=

18

then

3

<

20

while

4

<=

21

do

5

<>

22

end

6

>

23

l(l|d)*

10

>=

24

dd*

11

=

25

+

13

;

26

-

14

(

27

*

15

)

28

/

16

#

0

 

二、代碼實現(以python為例)。

1.詞法分析程序。

 

 1 import re
 2 
 3 
 4 strs = "if sum >= 1000 then x : x - 1;#"+" "
 5 
 6 types = {'begin':1, 
 7          'if':2,
 8          'then':3,
 9          'while':4,
10          'do':5,
11          'end':6,
12          'l(l|d)*':10,
13          'dd*':11,
14          '+':13,
15          '-':14,
16          '*':15,
17          '/':16,
18          ':':17,
19          ':=':18,
20          '<':20,
21          '<=':21,
22          '<>':22,
23          '>':23,
24          '>=':24,
25          '=':25,
26          ';':26,
27          '(':27,
28          ')':28,
29          '#':0
30         }
31 
32 if __name__ == '__main__':
33     # strs = input('請輸入程序代碼:')+" " #補位
34     
35     index = 0
36     while index < len(strs):
37         keyIndex = 0
38         for key in types.keys():
39             if index+len(key) < len(strs):
40                 if strs[index:index+len(key)] == key and not re.match('^[=a-zA-Z0-9_-]$', strs[index+len(key)]):
41                     if not(strs[index] == '=' and re.match('^[<>]$', strs[index-1])):
42                         ss = strs[index:index+len(key)]
43                         print((ss, types.get(ss)))
44                 elif re.match('^[a-zA-Z0-9_]+', strs[index:]):
45                     ss = re.match('^([a-zA-Z0-9_]+)', strs[index:]).group()
46                     if not types.get(ss):
47                         if re.match('[a-zA-Z]+', ss):
48                             print((ss, '標識符'))
49                         elif re.match('\d+', ss):
50                             print((ss, '數字'))
51                         else:
52                             print((ss, '其他'))
53                     index += len(ss)
54             keyIndex+=1
55         index+=1

 

 

 

  2.運行結果展示。

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM