Repository navigation
Expand file tree
/
Copy pathtokenizer.mini
More file actions
77 lines (72 loc) · 1.99 KB
/
Copy pathtokenizer.mini
File metadata and controls
77 lines (72 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Mini 迷你分词器:读 stdin 的源码字符,逐字符分类计数。
# 这是「Mini 够用来表达编译器最前端」的实证——用到了此前所有特性:
# getc(输入)、全局状态、if/else 多路分支、比较、算术、putc/puts/print(输出)。
#
# 分类规则(和 minicc 词法器同一套):
# '0'..'9' -> 数字字符
# 'a'..'z' 'A'..'Z' '_' -> 标识符字符
# ' ' '\t' '\n' '\r' -> 空白
# 其余可见字符 -> 符号
# EOF(getc 返回 -1)时结束。
# 四类计数器设成全局,模拟分词器维护的跨步骤状态
global ndigit; # 数字字符数
global nident; # 标识符字符数
global nspace; # 空白字符数
global nsym; # 符号字符数
# 判断一个字符码是否落在 [lo, hi] 闭区间内
fn in_range(c, lo, hi)
if c < lo
return 0;
end
if c > hi
return 0;
end
return 1;
end
# 对单个字符码分类,命中则把对应全局计数 +1
fn classify(c)
if in_range(c, '0', '9')
let ndigit = ndigit + 1;
return 0;
end
if in_range(c, 'a', 'z')
let nident = nident + 1;
return 0;
end
if in_range(c, 'A', 'Z')
let nident = nident + 1;
return 0;
end
if c == '_'
let nident = nident + 1;
return 0;
end
if c == ' '
let nspace = nspace + 1;
return 0;
end
if c == '\t'
let nspace = nspace + 1;
return 0;
end
if c == '\n'
let nspace = nspace + 1;
return 0;
end
if c == '\r'
let nspace = nspace + 1;
return 0;
end
let nsym = nsym + 1; # 其余归为符号
return 0;
end
# 主循环:逐字符读 stdin,直到 EOF(-1)
let c = getc;
while c != 0 - 1 # Mini 无一元负号,用 0-1 表示 -1
let ignore = classify(c);
let c = getc;
end
puts "digit="; print ndigit;
puts "ident="; print nident;
puts "space="; print nspace;
puts "symbol="; print nsym;