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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
|
//! ref: composer/vendor/composer/pcre/src/Preg.php
use super::pcre_exception::PcreException;
use super::unexpected_null_match_exception::UnexpectedNullMatchException;
use indexmap::IndexMap;
pub const PREG_PATTERN_ORDER: i64 = 1;
pub const PREG_SET_ORDER: i64 = 2;
pub const PREG_OFFSET_CAPTURE: i64 = 256;
pub const PREG_UNMATCHED_AS_NULL: i64 = 512;
pub const PREG_SPLIT_NO_EMPTY: i64 = 1;
pub const PREG_SPLIT_DELIM_CAPTURE: i64 = 2;
pub const PREG_SPLIT_OFFSET_CAPTURE: i64 = 4;
pub const PREG_GREP_INVERT: i64 = 1;
#[derive(Debug)]
pub struct Preg;
impl Preg {
pub fn match3(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, String>>,
) -> anyhow::Result<bool> {
Self::match5(pattern, subject, matches, 0, 0)
}
pub fn match5(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, String>>,
flags: i64,
offset: usize,
) -> anyhow::Result<bool> {
Self::check_offset_capture(flags, "matchWithOffsets");
let mut internal: IndexMap<CaptureKey, Option<String>> = IndexMap::new();
let result = preg_match(
pattern,
subject,
Some(&mut internal),
flags | PREG_UNMATCHED_AS_NULL,
offset,
)
.ok_or_else(|| PcreException::from_function("preg_match", pattern))?;
if let Some(out) = matches {
*out = drop_null_matches(internal);
}
Ok(result == 1)
}
pub fn match_strict_groups3(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, String>>,
) -> anyhow::Result<bool> {
Self::match_strict_groups5(pattern, subject, matches, 0, 0)
}
pub fn match_strict_groups5(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, String>>,
flags: i64,
offset: usize,
) -> anyhow::Result<bool> {
Self::check_offset_capture(flags, "matchWithOffsets");
let mut internal: IndexMap<CaptureKey, Option<String>> = IndexMap::new();
let result = preg_match(
pattern,
subject,
Some(&mut internal),
flags | PREG_UNMATCHED_AS_NULL,
offset,
)
.ok_or_else(|| PcreException::from_function("preg_match", pattern))?;
let enforced = Self::enforce_non_null_matches(pattern, internal, "match")?;
if let Some(out) = matches {
*out = enforced;
}
Ok(result == 1)
}
pub fn match_all3(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, Vec<String>>>,
) -> anyhow::Result<usize> {
Self::match_all5(pattern, subject, matches, 0, 0)
}
pub fn match_all5(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, Vec<String>>>,
flags: i64,
offset: usize,
) -> anyhow::Result<usize> {
Self::check_offset_capture(flags, "matchAllWithOffsets");
Self::check_set_order(flags);
let mut internal: IndexMap<CaptureKey, Vec<Option<String>>> = IndexMap::new();
let result = preg_match_all(
pattern,
subject,
Some(&mut internal),
flags | PREG_UNMATCHED_AS_NULL,
offset,
)
.ok_or_else(|| PcreException::from_function("preg_match_all", pattern))?;
if let Some(out) = matches {
*out = null_to_empty_match_all(internal);
}
Ok(result as usize)
}
pub fn match_all_strict_groups(pattern: &str, subject: &str) -> anyhow::Result<usize> {
Self::match_all_strict_groups5(pattern, subject, None, 0, 0)
}
pub fn match_all_strict_groups5(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, Vec<String>>>,
flags: i64,
offset: usize,
) -> anyhow::Result<usize> {
Self::check_offset_capture(flags, "matchAllWithOffsets");
Self::check_set_order(flags);
let mut internal: IndexMap<CaptureKey, Vec<Option<String>>> = IndexMap::new();
let result = preg_match_all(
pattern,
subject,
Some(&mut internal),
flags | PREG_UNMATCHED_AS_NULL,
offset,
)
.ok_or_else(|| PcreException::from_function("preg_match_all", pattern))?;
let enforced = Self::enforce_non_null_match_all(pattern, internal, "matchAll")?;
if let Some(out) = matches {
*out = enforced;
}
Ok(result as usize)
}
pub fn match_all_with_offsets5(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, Vec<(String, usize)>>>,
flags: i64,
offset: usize,
) -> anyhow::Result<usize> {
Self::check_set_order(flags);
let mut internal: IndexMap<CaptureKey, Vec<(Option<String>, i64)>> = IndexMap::new();
let result = preg_match_all_offset_capture(
pattern,
subject,
Some(&mut internal),
flags | PREG_UNMATCHED_AS_NULL | PREG_OFFSET_CAPTURE,
offset,
)
.ok_or_else(|| PcreException::from_function("preg_match_all", pattern))?;
if let Some(out) = matches {
*out = null_to_empty_offset_match_all(internal);
}
Ok(result as usize)
}
pub fn replace(pattern: &str, replacement: &str, subject: &str) -> anyhow::Result<String> {
Self::replace_impl(pattern, replacement, subject, -1, None)
}
pub fn replace4(
pattern: &str,
replacement: &str,
subject: &str,
limit: i64,
) -> anyhow::Result<String> {
Self::replace_impl(pattern, replacement, subject, limit, None)
}
pub fn replace5(
pattern: &str,
replacement: &str,
subject: &str,
limit: i64,
count: &mut usize,
) -> anyhow::Result<String> {
Self::replace_impl(pattern, replacement, subject, limit, Some(count))
}
fn replace_impl(
pattern: &str,
replacement: &str,
subject: &str,
limit: i64,
count: Option<&mut usize>,
) -> anyhow::Result<String> {
// `$subject` is statically a string here, so the is_scalar/is_array
// guards (ARRAY_MSG / INVALID_TYPE_MSG) of the PHP original are
// unreachable and not reproduced.
preg_replace(pattern, replacement, subject, limit, count)
.ok_or_else(|| PcreException::from_function("preg_replace", pattern).into())
}
pub fn replace_callback<F: FnMut(&IndexMap<CaptureKey, String>) -> String>(
pattern: &str,
replacement: F,
subject: &str,
) -> anyhow::Result<String> {
Self::replace_callback6(pattern, replacement, subject, -1, None, 0)
}
pub fn replace_callback6<F: FnMut(&IndexMap<CaptureKey, String>) -> String>(
pattern: &str,
mut replacement: F,
subject: &str,
limit: i64,
count: Option<&mut usize>,
flags: i64,
) -> anyhow::Result<String> {
let adapter = |internal: &IndexMap<CaptureKey, Option<String>>| -> String {
replacement(&drop_null_matches_ref(internal))
};
preg_replace_callback(pattern, adapter, subject, limit, count, flags)
.ok_or_else(|| PcreException::from_function("preg_replace_callback", pattern).into())
}
pub fn split(pattern: &str, subject: &str) -> anyhow::Result<Vec<String>> {
Self::split4(pattern, subject, -1, 0)
}
pub fn split4(
pattern: &str,
subject: &str,
limit: i64,
flags: i64,
) -> anyhow::Result<Vec<String>> {
assert!(
flags & PREG_SPLIT_OFFSET_CAPTURE == 0,
"PREG_SPLIT_OFFSET_CAPTURE is not supported as it changes the type of $matches, use splitWithOffsets() instead"
);
preg_split(pattern, subject, limit, flags)
.ok_or_else(|| PcreException::from_function("preg_split", pattern).into())
}
pub fn grep(pattern: &str, array: &[&str]) -> anyhow::Result<Vec<String>> {
Self::grep3(pattern, array, 0)
}
pub fn grep3(pattern: &str, array: &[&str], flags: i64) -> anyhow::Result<Vec<String>> {
preg_grep(pattern, array, flags)
.ok_or_else(|| PcreException::from_function("preg_grep", pattern).into())
}
pub fn is_match(pattern: &str, subject: &str) -> anyhow::Result<bool> {
Self::match5(pattern, subject, None, 0, 0)
}
pub fn is_match3(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, String>>,
) -> anyhow::Result<bool> {
Self::match5(pattern, subject, matches, 0, 0)
}
pub fn is_match5(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, String>>,
flags: i64,
offset: usize,
) -> anyhow::Result<bool> {
Self::match5(pattern, subject, matches, flags, offset)
}
pub fn is_match_named(
pattern: &str,
subject: &str,
matches: &mut IndexMap<String, String>,
) -> anyhow::Result<bool> {
let mut internal: IndexMap<CaptureKey, Option<String>> = IndexMap::new();
let result = preg_match(
pattern,
subject,
Some(&mut internal),
PREG_UNMATCHED_AS_NULL,
0,
)
.ok_or_else(|| PcreException::from_function("preg_match", pattern))?;
matches.clear();
for (key, value) in internal {
if let (CaptureKey::ByName(name), Some(value)) = (key, value) {
matches.insert(name, value);
}
}
Ok(result == 1)
}
pub fn is_match_strict_groups3(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, String>>,
) -> anyhow::Result<bool> {
Self::match_strict_groups5(pattern, subject, matches, 0, 0)
}
pub fn is_match_strict_groups5(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, String>>,
flags: i64,
offset: usize,
) -> anyhow::Result<bool> {
Self::match_strict_groups5(pattern, subject, matches, flags, offset)
}
pub fn is_match_with_indexed_captures(
pattern: &str,
subject: &str,
) -> anyhow::Result<Option<Vec<String>>> {
// Classic preg_match semantics (no PREG_UNMATCHED_AS_NULL): trailing
// unmatched groups are truncated, interior unmatched groups become "".
let mut internal: IndexMap<CaptureKey, Option<String>> = IndexMap::new();
let result = preg_match(pattern, subject, Some(&mut internal), 0, 0)
.ok_or_else(|| PcreException::from_function("preg_match", pattern))?;
if result == 0 {
return Ok(None);
}
let max_index = internal
.keys()
.filter_map(|key| match key {
CaptureKey::ByIndex(index) => Some(*index),
CaptureKey::ByName(_) => None,
})
.max()
.unwrap_or(0);
let mut captures = Vec::with_capacity(max_index + 1);
for index in 0..=max_index {
let value = internal
.get(&CaptureKey::ByIndex(index))
.and_then(|value| value.clone())
.unwrap_or_default();
captures.push(value);
}
Ok(Some(captures))
}
pub fn is_match_all3(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, Vec<String>>>,
) -> anyhow::Result<bool> {
Ok(Self::match_all5(pattern, subject, matches, 0, 0)? > 0)
}
pub fn is_match_all_strict_groups3(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, Vec<String>>>,
) -> anyhow::Result<bool> {
Ok(Self::match_all_strict_groups5(pattern, subject, matches, 0, 0)? > 0)
}
pub fn is_match_all_with_offsets3(
pattern: &str,
subject: &str,
matches: Option<&mut IndexMap<CaptureKey, Vec<(String, usize)>>>,
) -> anyhow::Result<bool> {
Ok(Self::match_all_with_offsets5(pattern, subject, matches, 0, 0)? > 0)
}
fn check_offset_capture(flags: i64, use_function_name: &str) {
assert!(
flags & PREG_OFFSET_CAPTURE == 0,
"PREG_OFFSET_CAPTURE is not supported as it changes the type of $matches, use {}() instead",
use_function_name
);
}
fn check_set_order(flags: i64) {
assert!(
flags & PREG_SET_ORDER == 0,
"PREG_SET_ORDER is not supported as it changes the type of $matches"
);
}
fn enforce_non_null_matches(
pattern: &str,
matches: IndexMap<CaptureKey, Option<String>>,
variant_method: &str,
) -> anyhow::Result<IndexMap<CaptureKey, String>> {
let mut result = IndexMap::new();
for (group, m) in matches {
match m {
None => {
return Err(UnexpectedNullMatchException::new(format!(
"Pattern \"{}\" had an unexpected unmatched group \"{}\", make sure the pattern always matches or use {}() instead.",
pattern,
capture_key_to_string(&group),
variant_method
))
.into());
}
Some(value) => {
result.insert(group, value);
}
}
}
Ok(result)
}
fn enforce_non_null_match_all(
pattern: &str,
matches: IndexMap<CaptureKey, Vec<Option<String>>>,
variant_method: &str,
) -> anyhow::Result<IndexMap<CaptureKey, Vec<String>>> {
let mut result = IndexMap::new();
for (group, group_matches) in matches {
let mut converted = Vec::with_capacity(group_matches.len());
for m in group_matches {
match m {
None => {
return Err(UnexpectedNullMatchException::new(format!(
"Pattern \"{}\" had an unexpected unmatched group \"{}\", make sure the pattern always matches or use {}() instead.",
pattern,
capture_key_to_string(&group),
variant_method
))
.into());
}
Some(value) => converted.push(value),
}
}
result.insert(group, converted);
}
Ok(result)
}
}
fn capture_key_to_string(key: &CaptureKey) -> String {
match key {
CaptureKey::ByIndex(index) => index.to_string(),
CaptureKey::ByName(name) => name.clone(),
}
}
// Drops `null` (unmatched) groups, mirroring how the public `string`-valued
// `matches` map represents PHP's `string|null` entries by their absence.
fn drop_null_matches(
matches: IndexMap<CaptureKey, Option<String>>,
) -> IndexMap<CaptureKey, String> {
matches
.into_iter()
.filter_map(|(key, value)| value.map(|value| (key, value)))
.collect()
}
fn drop_null_matches_ref(
matches: &IndexMap<CaptureKey, Option<String>>,
) -> IndexMap<CaptureKey, String> {
matches
.iter()
.filter_map(|(key, value)| value.clone().map(|value| (key.clone(), value)))
.collect()
}
// In the `Vec<String>`-valued maps a per-iteration `null` cannot be stored, so
// unmatched groups collapse to "" (the classic non-PREG_UNMATCHED_AS_NULL form).
fn null_to_empty_match_all(
matches: IndexMap<CaptureKey, Vec<Option<String>>>,
) -> IndexMap<CaptureKey, Vec<String>> {
matches
.into_iter()
.map(|(key, values)| {
(
key,
values
.into_iter()
.map(|value| value.unwrap_or_default())
.collect(),
)
})
.collect()
}
fn null_to_empty_offset_match_all(
matches: IndexMap<CaptureKey, Vec<(Option<String>, i64)>>,
) -> IndexMap<CaptureKey, Vec<(String, usize)>> {
matches
.into_iter()
.map(|(key, values)| {
(
key,
values
.into_iter()
.map(|(value, offset)| (value.unwrap_or_default(), offset.max(0) as usize))
.collect(),
)
})
.collect()
}
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub enum CaptureKey {
ByIndex(usize),
ByName(String),
}
pub fn preg_last_error() -> i64 {
todo!()
}
pub fn preg_last_error_msg() -> String {
todo!()
}
// Returns Some(0|1) on success or None when the underlying preg_match returned
// false. Unmatched groups are reported as None (PREG_UNMATCHED_AS_NULL).
pub fn preg_match(
_pattern: &str,
_subject: &str,
_matches: Option<&mut IndexMap<CaptureKey, Option<String>>>,
_flags: i64,
_offset: usize,
) -> Option<i64> {
todo!()
}
pub fn preg_match_all(
_pattern: &str,
_subject: &str,
_matches: Option<&mut IndexMap<CaptureKey, Vec<Option<String>>>>,
_flags: i64,
_offset: usize,
) -> Option<i64> {
todo!()
}
pub fn preg_match_all_offset_capture(
_pattern: &str,
_subject: &str,
_matches: Option<&mut IndexMap<CaptureKey, Vec<(Option<String>, i64)>>>,
_flags: i64,
_offset: usize,
) -> Option<i64> {
todo!()
}
pub fn preg_replace(
_pattern: &str,
_replacement: &str,
_subject: &str,
_limit: i64,
_count: Option<&mut usize>,
) -> Option<String> {
todo!()
}
pub fn preg_replace_callback<F: FnMut(&IndexMap<CaptureKey, Option<String>>) -> String>(
_pattern: &str,
_callback: F,
_subject: &str,
_limit: i64,
_count: Option<&mut usize>,
_flags: i64,
) -> Option<String> {
todo!()
}
pub fn preg_split(_pattern: &str, _subject: &str, _limit: i64, _flags: i64) -> Option<Vec<String>> {
todo!()
}
pub fn preg_grep(_pattern: &str, _array: &[&str], _flags: i64) -> Option<Vec<String>> {
todo!()
}
|