This repository has been archived by the owner on Aug 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
regex.rs
75 lines (67 loc) · 1.76 KB
/
regex.rs
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
use std::rc::Rc;
#[deriving(Clone)]
pub enum Regex {
Or(~Regex, ~Regex),
Cat(~Regex, ~Regex),
Closure(~Regex),
Maybe(~Regex),
Char(u8),
Var(Rc<Regex>)
}
pub fn seq(start: u8, end: u8) -> Option<~Regex> {
if start >= end {
None
} else {
let mut ret = ~Char(start);
let mut c = start;
while c < end {
let op = ~Char(c);
ret = ~Or(ret, op);
c += 1
}
Some(~Or(ret, ~Char(end)))
}
}
pub fn string(string: &str) -> Option<~Regex> {
let mut it = string.bytes();
let mut reg = ~Char(match it.next() {
Some(ch) => ch,
None => return None
});
for ch in it {
reg = ~Cat(reg, ~Char(ch));
}
Some(reg)
}
impl Regex {
#[allow(dead_code)]
// prints the AST for debugging purposes
pub fn show(&self, span: &str) {
match self {
&Or(ref l, ref r) => {
println!("{:s} Or of: ", span);
l.show(format!(" {:s}", span));
r.show(format!(" {:s}", span));
}
&Cat(ref l, ref r) => {
println!("{:s} Cat of: ", span);
l.show(format!(" {:s}", span));
r.show(format!(" {:s}", span));
}
&Char(ref c) => {
println!("{:s} The char {:c}", span, *c as char);
}
&Closure(ref reg) => {
println!("{:s} The eclosure of", span);
reg.show(format!(" {:s}", span))
}
&Var(ref reg) => {
(**reg).show(span);
}
&Maybe(ref reg) => {
println!("{:s} Optionnally the regex:", span);
reg.show(span);
}
}
}
}