1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // Enable this to squash warnings due to exporting pieces of the representation
12 // for use with the regex! macro. See lib.rs for explanation.
14 pub use self::Inst::*;
17 use std::iter::repeat;
21 Nothing, Literal, Dot, AstClass, Begin, End, WordBoundary, Capture, Cat, Alt,
23 ZeroOne, ZeroMore, OneMore,
28 #[deriving(Show, Clone)]
30 // When a Match instruction is executed, the current thread is successful.
33 // The OneChar instruction matches a literal character.
34 // The flags indicate whether to do a case insensitive match.
37 // The CharClass instruction tries to match one input character against
38 // the range of characters given.
39 // The flags indicate whether to do a case insensitive match and whether
40 // the character class is negated or not.
41 CharClass(Vec<(char, char)>, Flags),
43 // Matches any character except new lines.
44 // The flags indicate whether to include the '\n' character.
47 // Matches the beginning of the string, consumes no characters.
48 // The flags indicate whether it matches if the preceding character
52 // Matches the end of the string, consumes no characters.
53 // The flags indicate whether it matches if the proceeding character
57 // Matches a word boundary (\w on one side and \W \A or \z on the other),
58 // and consumes no character.
59 // The flags indicate whether this matches a word boundary or something
60 // that isn't a word boundary.
61 EmptyWordBoundary(Flags),
63 // Saves the current position in the input string to the Nth save slot.
66 // Jumps to the instruction at the index given.
69 // Jumps to the instruction at the first index given. If that leads to
70 // a panic state, then the instruction at the second index given is
72 Split(InstIdx, InstIdx),
75 /// Program represents a compiled regular expression. Once an expression is
76 /// compiled, its representation is immutable and will never change.
78 /// All of the data in a compiled expression is wrapped in "MaybeStatic" or
79 /// "MaybeOwned" types so that a `Program` can be represented as static data.
80 /// (This makes it convenient and efficient for use with the `regex!` macro.)
83 /// A sequence of instructions.
85 /// If the regular expression requires a literal prefix in order to have a
86 /// match, that prefix is stored here. (It's used in the VM to implement
92 /// Compiles a Regex given its AST.
93 pub fn new(ast: parse::Ast) -> (Program, Vec<Option<String>>) {
94 let mut c = Compiler {
95 insts: Vec::with_capacity(100),
96 names: Vec::with_capacity(10),
99 c.insts.push(Save(0));
101 c.insts.push(Save(1));
104 // Try to discover a literal string prefix.
105 // This is a bit hacky since we have to skip over the initial
106 // 'Save' instruction.
107 let mut pre = String::with_capacity(5);
108 for inst in c.insts[1..].iter() {
110 OneChar(c, FLAG_EMPTY) => pre.push(c),
115 let Compiler { insts, names } = c;
123 /// Returns the total number of capture groups in the regular expression.
124 /// This includes the zeroth capture.
125 pub fn num_captures(&self) -> uint {
127 for inst in self.insts.iter() {
129 Save(c) => n = cmp::max(n, c+1),
133 // There's exactly 2 Save slots for every capture.
138 struct Compiler<'r> {
140 names: Vec<Option<String>>,
143 // The compiler implemented here is extremely simple. Most of the complexity
144 // in this crate is in the parser or the VM.
145 // The only tricky thing here is patching jump/split instructions to point to
146 // the right instruction.
147 impl<'r> Compiler<'r> {
148 fn compile(&mut self, ast: parse::Ast) {
151 Literal(c, flags) => self.push(OneChar(c, flags)),
152 Dot(nl) => self.push(Any(nl)),
153 AstClass(ranges, flags) =>
154 self.push(CharClass(ranges, flags)),
155 Begin(flags) => self.push(EmptyBegin(flags)),
156 End(flags) => self.push(EmptyEnd(flags)),
157 WordBoundary(flags) => self.push(EmptyWordBoundary(flags)),
158 Capture(cap, name, x) => {
159 let len = self.names.len();
161 self.names.extend(repeat(None).take(10 + cap - len))
163 self.names[cap] = name;
165 self.push(Save(2 * cap));
167 self.push(Save(2 * cap + 1));
170 for x in xs.into_iter() {
175 let split = self.empty_split(); // push: split 0, 0
176 let j1 = self.insts.len();
177 self.compile(*x); // push: insts for x
178 let jmp = self.empty_jump(); // push: jmp 0
179 let j2 = self.insts.len();
180 self.compile(*y); // push: insts for y
181 let j3 = self.insts.len();
183 self.set_split(split, j1, j2); // split 0, 0 -> split j1, j2
184 self.set_jump(jmp, j3); // jmp 0 -> jmp j3
186 Rep(x, ZeroOne, g) => {
187 let split = self.empty_split();
188 let j1 = self.insts.len();
190 let j2 = self.insts.len();
193 self.set_split(split, j1, j2);
195 self.set_split(split, j2, j1);
198 Rep(x, ZeroMore, g) => {
199 let j1 = self.insts.len();
200 let split = self.empty_split();
201 let j2 = self.insts.len();
203 let jmp = self.empty_jump();
204 let j3 = self.insts.len();
206 self.set_jump(jmp, j1);
208 self.set_split(split, j2, j3);
210 self.set_split(split, j3, j2);
213 Rep(x, OneMore, g) => {
214 let j1 = self.insts.len();
216 let split = self.empty_split();
217 let j2 = self.insts.len();
220 self.set_split(split, j1, j2);
222 self.set_split(split, j2, j1);
228 /// Appends the given instruction to the program.
230 fn push(&mut self, x: Inst) {
234 /// Appends an *empty* `Split` instruction to the program and returns
235 /// the index of that instruction. (The index can then be used to "patch"
236 /// the actual locations of the split in later.)
238 fn empty_split(&mut self) -> InstIdx {
239 self.insts.push(Split(0, 0));
243 /// Sets the left and right locations of a `Split` instruction at index
244 /// `i` to `pc1` and `pc2`, respectively.
245 /// If the instruction at index `i` isn't a `Split` instruction, then
246 /// `panic!` is called.
248 fn set_split(&mut self, i: InstIdx, pc1: InstIdx, pc2: InstIdx) {
249 let split = &mut self.insts[i];
251 Split(_, _) => *split = Split(pc1, pc2),
252 _ => panic!("BUG: Invalid split index."),
256 /// Appends an *empty* `Jump` instruction to the program and returns the
257 /// index of that instruction.
259 fn empty_jump(&mut self) -> InstIdx {
260 self.insts.push(Jump(0));
264 /// Sets the location of a `Jump` instruction at index `i` to `pc`.
265 /// If the instruction at index `i` isn't a `Jump` instruction, then
266 /// `panic!` is called.
268 fn set_jump(&mut self, i: InstIdx, pc: InstIdx) {
269 let jmp = &mut self.insts[i];
271 Jump(_) => *jmp = Jump(pc),
272 _ => panic!("BUG: Invalid jump index."),