-
Notifications
You must be signed in to change notification settings - Fork 8
/
hir.rs
266 lines (246 loc) · 9.77 KB
/
hir.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#[cfg(feature = "miette")]
use miette::Diagnostic;
use regex_syntax::hir::{self, Hir};
use std::borrow::Borrow;
#[cfg(feature = "miette")]
use std::fmt::Display;
use thiserror::Error;
pub use regex_automata::meta::Regex;
use crate::token::walk::{Fold, FoldPosition, Forward};
use crate::token::{self, Archetype, BranchKind, ConcatenationTree, LeafKind};
use crate::IteratorExt as _;
trait IntoHir {
fn into_hir(self) -> Hir;
}
impl IntoHir for hir::ClassUnicode {
fn into_hir(self) -> Hir {
Hir::class(hir::Class::Unicode(self))
}
}
/// Describes errors that occur when compiling a glob expression.
///
/// **This error only occurs when the size of the compiled program is too large.** All other
/// compilation errors are considered internal bugs and will panic.
#[derive(Clone, Debug, Error)]
#[error("failed to compile glob: {kind}")]
pub struct CompileError {
kind: CompileErrorKind,
}
#[derive(Clone, Copy, Debug, Error)]
#[non_exhaustive]
enum CompileErrorKind {
#[error("oversized program")]
OversizedProgram,
}
#[cfg(feature = "miette")]
#[cfg_attr(docsrs, doc(cfg(feature = "miette")))]
impl Diagnostic for CompileError {
fn code<'a>(&'a self) -> Option<Box<dyn 'a + Display>> {
Some(Box::new(String::from(match self.kind {
CompileErrorKind::OversizedProgram => "wax::glob::oversized_program",
})))
}
}
// TODO: The implementation of this function depends on platform/OS.
fn separator() -> hir::ClassUnicode {
hir::ClassUnicode::new([hir::ClassUnicodeRange::new('/', '/')])
}
fn not_separator() -> hir::ClassUnicode {
let mut hir = separator();
hir.negate();
hir
}
fn case_folded_literal(text: impl AsRef<str>) -> Hir {
Hir::concat(
text.as_ref()
.chars()
.map(|point| hir::ClassUnicode::new([hir::ClassUnicodeRange::new(point, point)]))
.map(|mut hir| {
let _ = hir.try_case_fold_simple();
hir
})
.map(hir::Class::Unicode)
.map(Hir::class)
.collect(),
)
}
pub fn case_folded_eq(lhs: impl AsRef<str>, rhs: impl AsRef<str>) -> bool {
let lhs = self::case_folded_literal(lhs);
let rhs = rhs.as_ref();
let regex = Regex::builder()
.build_from_hir(&lhs)
.expect("failed to compile case folding regular expression");
regex.find(rhs).map_or(false, |matched| {
matched.start() == 0 && matched.end() == rhs.len()
})
}
pub fn compile<'t, T>(tree: impl Borrow<T>) -> Result<Regex, CompileError>
where
T: ConcatenationTree<'t>,
{
#[derive(Debug, Default)]
struct Compile;
impl<'t, A> Fold<'t, A> for Compile {
type Sequencer = Forward;
type Term = Hir;
fn sequencer() -> Self::Sequencer {
Forward
}
fn fold(
&mut self,
_: impl FoldPosition<'t, A>,
branch: &BranchKind<'t, A>,
terms: Vec<Self::Term>,
) -> Option<Self::Term> {
use BranchKind::{Alternation, Concatenation, Repetition};
Some(match branch {
Alternation(_) => Hir::alternation(terms),
Concatenation(_) => Hir::concat(terms),
Repetition(ref repetition) => {
let (min, max) = repetition.bound_specification();
Hir::repetition(hir::Repetition {
min: u32::try_from(min).unwrap_or(u32::MAX),
max: max.map(u32::try_from).transpose().unwrap_or(Some(u32::MAX)),
greedy: true,
sub: Box::new(Hir::concat(terms)),
})
},
})
}
fn finalize(&mut self, _branch: &BranchKind<'t, A>, term: Self::Term) -> Self::Term {
term
}
fn term(&mut self, position: impl FoldPosition<'t, A>, leaf: &LeafKind<'t>) -> Self::Term {
use token::Wildcard::{One, Tree, ZeroOrMore};
use Archetype::{Character, Range};
use LeafKind::{Class, Literal, Separator, Wildcard};
let adjacency = position.adjacency();
match leaf {
Class(ref class) => {
let is_negated = class.is_negated();
let mut class =
hir::ClassUnicode::new(class.archetypes().iter().map(|archetype| {
let (start, end) = match archetype {
Character(ref point) => (*point, *point),
Range(ref start, ref end) => (*start, *end),
};
hir::ClassUnicodeRange::new(start, end)
}));
if is_negated {
class.union(&self::separator());
class.negate();
}
else {
class.difference(&self::separator());
}
class.into_hir()
},
Literal(ref literal) => {
if literal.is_case_insensitive() {
self::case_folded_literal(literal.text())
}
else {
Hir::literal(literal.text().as_bytes())
}
},
Separator(_) => {
if adjacency.right.is_some() {
self::separator().into_hir()
}
else {
Hir::alternation(vec![
self::separator().into_hir(),
Hir::look(hir::Look::End),
])
}
},
Wildcard(ref wildcard) => match wildcard {
One => Hir::class(hir::Class::Unicode(self::not_separator())),
Tree { has_root } => Hir::alternation(vec![
Hir::concat(vec![
if *has_root {
self::separator().into_hir()
}
else {
Hir::empty()
},
Hir::repetition(hir::Repetition {
min: 0,
max: None,
greedy: true,
sub: Box::new(Hir::dot(hir::Dot::AnyChar)),
}),
Hir::alternation(vec![
self::separator().into_hir(),
Hir::look(hir::Look::End),
]),
]),
self::separator().into_hir(),
Hir::empty(),
]),
ZeroOrMore(ref evaluation) => Hir::repetition(hir::Repetition {
min: if adjacency.is_open() || adjacency.is_closed_boundary() {
1
}
else {
0
},
max: None,
greedy: evaluation.is_eager(),
sub: Box::new(self::not_separator().into_hir()),
}),
},
}
}
}
let mut capture_group_index = 1u32;
let hir = Hir::concat(
Some(Hir::look(hir::Look::Start))
.into_iter()
.chain(
tree.borrow()
.concatenation()
.iter()
.adjacent()
.map(|token| {
let hir = token.fold_with_adjacent(Compile).unwrap_or_else(Hir::empty);
if token.into_item().is_capturing() {
let index = capture_group_index;
capture_group_index = capture_group_index
.checked_add(1)
.expect("overflow in capture group index");
// TODO: This captures any and all text that is matched by the token. This is
// much more consistent and predictable than before. However, it is
// difficult to assemble paths from matched text for some tokens.
//
// To address this, provide APIs for trimming matched text. In
// particular, the matched text for tree wildcards is easier to use when
// leading separators are stripped (even when this results in empty match
// text). One exception is a tree wildcard that roots an expression. To
// handle cases like this, additional information about the capturing
// token can be gathered here and used in `MatchedText`.
Hir::capture(hir::Capture {
index,
name: None,
sub: Box::new(hir),
})
}
else {
hir
}
}),
)
.chain(Some(Hir::look(hir::Look::End)))
.collect(),
);
// TODO: Remove this.
//eprintln!("TREE\n{:#?}", hir);
Regex::builder()
.build_from_hir(&hir)
.map_err(|error| match error.size_limit() {
Some(_) => CompileError {
kind: CompileErrorKind::OversizedProgram,
},
_ => panic!("failed to compile glob"),
})
}