forked from denoland/rust-urlpattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent.rs
364 lines (349 loc) · 10.7 KB
/
component.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use crate::canonicalize_and_process::escape_pattern_string;
use crate::matcher::InnerMatcher;
use crate::matcher::Matcher;
use crate::parser::Options;
use crate::parser::Part;
use crate::parser::PartModifier;
use crate::parser::PartType;
use crate::parser::FULL_WILDCARD_REGEXP_VALUE;
use crate::regexp::RegExp;
use crate::tokenizer::is_valid_name_codepoint;
use crate::Error;
use std::fmt::Write;
// Ref: https://wicg.github.io/urlpattern/#component
#[derive(Debug)]
pub(crate) struct Component<R: RegExp> {
pub pattern_string: String,
pub regexp: Result<R, Error>,
pub group_name_list: Vec<String>,
pub matcher: Matcher<R>,
pub has_regexp_group: bool,
}
impl<R: RegExp> Component<R> {
// Ref: https://wicg.github.io/urlpattern/#compile-a-component
pub(crate) fn compile<F>(
input: Option<&str>,
encoding_callback: F,
options: Options,
) -> Result<Self, Error>
where
F: Fn(&str) -> Result<String, Error>,
{
let part_list = crate::parser::parse_pattern_string(
input.unwrap_or("*"),
&options,
encoding_callback,
)?;
let part_list = part_list.iter().collect::<Vec<_>>();
let (regexp_string, name_list) =
generate_regular_expression_and_name_list(&part_list, &options);
let flags = if options.ignore_case { "ui" } else { "u" };
let regexp = R::parse(®exp_string, flags).map_err(Error::RegExp);
let pattern_string = generate_pattern_string(&part_list, &options);
let matcher = generate_matcher::<R>(&part_list, &options, flags);
Ok(Component {
pattern_string,
regexp,
group_name_list: name_list,
matcher,
has_regexp_group: part_list
.iter()
.any(|part| part.kind == PartType::Regexp),
})
}
// Ref: https://wicg.github.io/urlpattern/#protocol-component-matches-a-special-scheme
pub(crate) fn protocol_component_matches_special_scheme(&self) -> bool {
const SPECIAL_SCHEMES: [&str; 6] =
["ftp", "file", "http", "https", "ws", "wss"];
if let Ok(regex) = &self.regexp {
for scheme in SPECIAL_SCHEMES {
if regex.matches(scheme).is_some() {
return true;
}
}
}
false
}
// Ref: https://wicg.github.io/urlpattern/#create-a-component-match-result
pub(crate) fn create_match_result(
&self,
input: String,
exec_result: Vec<Option<&str>>,
) -> crate::UrlPatternComponentResult {
let groups = self
.group_name_list
.clone()
.into_iter()
.zip(exec_result.into_iter().map(|s| s.map(str::to_owned)))
.collect();
crate::UrlPatternComponentResult { input, groups }
}
pub(crate) fn optionally_transpose_regex_error(
mut self,
do_transpose: bool,
) -> Result<Self, Error> {
if do_transpose {
self.regexp = Ok(self.regexp?);
}
Ok(self)
}
}
// Ref: https://wicg.github.io/urlpattern/#generate-a-regular-expression-and-name-list
fn generate_regular_expression_and_name_list(
part_list: &[&Part],
options: &Options,
) -> (String, Vec<String>) {
let mut result = String::from("^");
let mut name_list = vec![];
for part in part_list {
if part.kind == PartType::FixedText {
if part.modifier == PartModifier::None {
result.push_str(&options.escape_regexp_string(&part.value));
} else {
write!(
result,
"(?:{}){}",
options.escape_regexp_string(&part.value),
part.modifier
)
.unwrap();
}
continue;
}
assert!(!part.name.is_empty());
name_list.push(part.name.clone());
let regexp_value = if part.kind == PartType::SegmentWildcard {
options.generate_segment_wildcard_regexp()
} else if part.kind == PartType::FullWildcard {
FULL_WILDCARD_REGEXP_VALUE.to_string()
} else {
part.value.clone()
};
if part.prefix.is_empty() && part.suffix.is_empty() {
if matches!(part.modifier, PartModifier::None | PartModifier::Optional) {
write!(result, "({}){}", regexp_value, part.modifier).unwrap();
} else {
write!(result, "((?:{}){})", regexp_value, part.modifier).unwrap();
}
continue;
}
if matches!(part.modifier, PartModifier::None | PartModifier::Optional) {
write!(
result,
"(?:{}({}){}){}",
options.escape_regexp_string(&part.prefix),
regexp_value,
options.escape_regexp_string(&part.suffix),
part.modifier
)
.unwrap();
continue;
}
assert!(!part.prefix.is_empty() || !part.suffix.is_empty());
write!(
result,
"(?:{}((?:{})(?:{}{}(?:{}))*){}){}",
options.escape_regexp_string(&part.prefix),
regexp_value,
options.escape_regexp_string(&part.suffix),
options.escape_regexp_string(&part.prefix),
regexp_value,
options.escape_regexp_string(&part.suffix),
if part.modifier == PartModifier::ZeroOrMore {
"?"
} else {
""
}
)
.unwrap();
}
result.push('$');
(result, name_list)
}
// Ref: https://wicg.github.io/urlpattern/#generate-a-pattern-string
fn generate_pattern_string(part_list: &[&Part], options: &Options) -> String {
let mut result = String::new();
for (i, part) in part_list.iter().enumerate() {
let prev_part: Option<&Part> = if i == 0 {
None
} else {
part_list.get(i - 1).copied()
};
let next_part: Option<&Part> = part_list.get(i + 1).copied();
if part.kind == PartType::FixedText {
if part.modifier == PartModifier::None {
result.push_str(&escape_pattern_string(&part.value));
continue;
}
write!(
result,
"{{{}}}{}",
escape_pattern_string(&part.value),
part.modifier
)
.unwrap();
continue;
}
let custom_name = !part.name.chars().next().unwrap().is_ascii_digit();
let mut needs_grouping = !part.suffix.is_empty()
|| (!part.prefix.is_empty() && part.prefix != options.prefix_code_point);
if !needs_grouping
&& custom_name
&& part.kind == PartType::SegmentWildcard
&& part.modifier == PartModifier::None
&& matches!(next_part, Some(Part { prefix, suffix, .. }) if prefix.is_empty() && suffix.is_empty())
{
let next_part = next_part.unwrap();
if next_part.kind == PartType::FixedText {
needs_grouping = is_valid_name_codepoint(
next_part.value.chars().next().unwrap_or_default(),
false,
);
} else {
needs_grouping =
next_part.name.chars().next().unwrap().is_ascii_digit();
}
}
if !needs_grouping
&& part.prefix.is_empty()
&& matches!(
prev_part,
Some(Part {
kind: PartType::FixedText,
value,
..
}) if value.chars().last().unwrap().to_string() == options.prefix_code_point
)
{
needs_grouping = true;
}
assert!(!part.name.is_empty());
if needs_grouping {
result.push('{');
}
result.push_str(&escape_pattern_string(&part.prefix));
if custom_name {
result.push(':');
result.push_str(&part.name);
}
match part.kind {
PartType::FixedText => unreachable!(),
PartType::Regexp => write!(result, "({})", part.value).unwrap(),
PartType::SegmentWildcard if !custom_name => {
write!(result, "({})", options.generate_segment_wildcard_regexp())
.unwrap()
}
PartType::SegmentWildcard => {}
PartType::FullWildcard => {
if !custom_name
&& (prev_part.is_none()
|| prev_part.unwrap().kind == PartType::FixedText
|| prev_part.unwrap().modifier != PartModifier::None
|| needs_grouping
|| !part.prefix.is_empty())
{
result.push('*');
} else {
result.push_str(&format!("({FULL_WILDCARD_REGEXP_VALUE})"));
}
}
}
if part.kind == PartType::SegmentWildcard
&& custom_name
&& !part.suffix.is_empty()
&& is_valid_name_codepoint(part.suffix.chars().next().unwrap(), false)
{
result.push('\\');
}
result.push_str(&escape_pattern_string(&part.suffix));
if needs_grouping {
result.push('}');
}
result.push_str(&part.modifier.to_string());
}
result
}
/// This function generates a matcher for a given parts list.
fn generate_matcher<R: RegExp>(
mut part_list: &[&Part],
options: &Options,
flags: &str,
) -> Matcher<R> {
fn is_literal(part: &Part) -> bool {
part.kind == PartType::FixedText && part.modifier == PartModifier::None
}
// If the first part is a fixed string, we can use it as a literal prefix.
let mut prefix = match part_list.first() {
Some(part) if is_literal(part) => {
part_list = &part_list[1..];
part.value.clone()
}
_ => "".into(),
};
// If the last part is a fixed string, we can use it as a literal suffix.
let mut suffix = match part_list.last() {
Some(part) if is_literal(part) => {
part_list = &part_list[..part_list.len() - 1];
part.value.clone()
}
_ => "".into(),
};
// If there are no more parts, we must have a prefix and/or a suffix. We can
// combine these into a single fixed text literal matcher.
if part_list.is_empty() {
return Matcher {
prefix: "".to_string(),
suffix: "".to_string(),
inner: InnerMatcher::Literal {
literal: format!("{prefix}{suffix}"),
},
ignore_case: options.ignore_case,
};
}
let inner = match part_list {
// If there is only one part, and it is a simple full wildcard with no
// prefix or suffix, we can use a simple wildcard matcher.
[part]
if part.kind == PartType::FullWildcard
&& part.modifier == PartModifier::None =>
{
prefix += &part.prefix;
if !part.suffix.is_empty() {
suffix = format!("{}{suffix}", part.suffix);
}
InnerMatcher::SingleCapture {
filter: None,
allow_empty: true,
}
}
// If there is only one part, and it is a simple segment wildcard with no
// prefix or suffix, we can use a simple wildcard matcher.
[part]
if part.kind == PartType::SegmentWildcard
&& part.modifier == PartModifier::None =>
{
prefix += &part.prefix;
if !part.suffix.is_empty() {
suffix = format!("{}{suffix}", part.suffix);
}
InnerMatcher::SingleCapture {
filter: options.delimiter_code_point,
allow_empty: false,
}
}
// For all other cases, we fall back to a regexp matcher.
part_list => {
let (regexp_string, _) =
generate_regular_expression_and_name_list(part_list, options);
let regexp = R::parse(®exp_string, flags).map_err(Error::RegExp);
InnerMatcher::RegExp { regexp }
}
};
Matcher {
prefix,
suffix,
inner,
ignore_case: options.ignore_case,
}
}