resharp-algebra 0.5.0

boolean algebra and symbolic rewriting engine for resharp regex
Documentation
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
#[derive(Clone, Copy, PartialEq, Hash, Eq, Debug, PartialOrd, Ord)]
pub struct TSet(pub [u64; 4]);

impl TSet {
    #[inline]
    pub const fn splat(v: u64) -> Self {
        TSet([v, v, v, v])
    }

    pub fn from_bytes(bytes: &[u8]) -> Self {
        let mut bits = [0u64; 4];
        for &b in bytes {
            bits[b as usize / 64] |= 1u64 << (b as usize % 64);
        }
        Self(bits)
    }

    #[inline(always)]
    pub fn contains_byte(&self, b: u8) -> bool {
        self.0[b as usize / 64] & (1u64 << (b as usize % 64)) != 0
    }
}

impl std::ops::Index<usize> for TSet {
    type Output = u64;
    #[inline]
    fn index(&self, i: usize) -> &u64 {
        &self.0[i]
    }
}

impl std::ops::IndexMut<usize> for TSet {
    #[inline]
    fn index_mut(&mut self, i: usize) -> &mut u64 {
        &mut self.0[i]
    }
}

impl std::ops::BitAnd for TSet {
    type Output = TSet;
    #[inline]
    fn bitand(self, rhs: TSet) -> TSet {
        TSet([
            self.0[0] & rhs.0[0],
            self.0[1] & rhs.0[1],
            self.0[2] & rhs.0[2],
            self.0[3] & rhs.0[3],
        ])
    }
}

impl std::ops::BitAnd for &TSet {
    type Output = TSet;
    #[inline]
    fn bitand(self, rhs: &TSet) -> TSet {
        TSet([
            self.0[0] & rhs.0[0],
            self.0[1] & rhs.0[1],
            self.0[2] & rhs.0[2],
            self.0[3] & rhs.0[3],
        ])
    }
}

impl std::ops::BitOr for TSet {
    type Output = TSet;
    #[inline]
    fn bitor(self, rhs: TSet) -> TSet {
        TSet([
            self.0[0] | rhs.0[0],
            self.0[1] | rhs.0[1],
            self.0[2] | rhs.0[2],
            self.0[3] | rhs.0[3],
        ])
    }
}

impl std::ops::Not for TSet {
    type Output = TSet;
    #[inline]
    fn not(self) -> TSet {
        TSet([!self.0[0], !self.0[1], !self.0[2], !self.0[3]])
    }
}

// &TSet ops used by Solver helper methods
impl std::ops::BitAnd<TSet> for &TSet {
    type Output = TSet;
    #[inline]
    fn bitand(self, rhs: TSet) -> TSet {
        TSet([
            self.0[0] & rhs.0[0],
            self.0[1] & rhs.0[1],
            self.0[2] & rhs.0[2],
            self.0[3] & rhs.0[3],
        ])
    }
}

impl std::ops::BitOr<TSet> for &TSet {
    type Output = TSet;
    #[inline]
    fn bitor(self, rhs: TSet) -> TSet {
        TSet([
            self.0[0] | rhs.0[0],
            self.0[1] | rhs.0[1],
            self.0[2] | rhs.0[2],
            self.0[3] | rhs.0[3],
        ])
    }
}

const EMPTY: TSet = TSet::splat(u64::MIN);
const FULL: TSet = TSet::splat(u64::MAX);

#[derive(Clone, Copy, PartialEq, Hash, Eq, Debug, PartialOrd, Ord)]
pub struct TSetId(pub u32);
impl TSetId {
    pub const EMPTY: TSetId = TSetId(0);
    pub const FULL: TSetId = TSetId(1);
}

use rustc_hash::FxHashMap;
use std::collections::BTreeSet;

pub struct Solver {
    cache: FxHashMap<TSet, TSetId>,
    pub array: Vec<TSet>,
}

impl Default for Solver {
    fn default() -> Self {
        Self::new()
    }
}

impl Solver {
    pub fn new() -> Solver {
        let mut inst = Self {
            cache: FxHashMap::default(),
            array: Vec::new(),
        };
        let _ = inst.init(Solver::empty()); // 0
        let _ = inst.init(Solver::full()); // 1
        inst
    }

    fn init(&mut self, inst: TSet) -> TSetId {
        let new_id = TSetId(self.cache.len() as u32);
        self.cache.insert(inst, new_id);
        self.array.push(inst);
        new_id
    }

    pub fn get_set(&self, set_id: TSetId) -> TSet {
        self.array[set_id.0 as usize]
    }

    pub fn get_set_ref(&self, set_id: TSetId) -> &TSet {
        &self.array[set_id.0 as usize]
    }

    pub fn get_id(&mut self, inst: TSet) -> TSetId {
        match self.cache.get(&inst) {
            Some(&id) => id,
            None => self.init(inst),
        }
    }

    pub fn has_bit_set(&mut self, set_id: TSetId, idx: usize, bit: u64) -> bool {
        self.array[set_id.0 as usize][idx] & bit != 0
    }

    pub fn pp_collect_ranges(tset: &TSet) -> BTreeSet<(u8, u8)> {
        let mut ranges: BTreeSet<(u8, u8)> = BTreeSet::new();
        let mut rangestart: Option<u8> = None;
        let mut prevchar: Option<u8> = None;
        for i in 0..4 {
            for j in 0..64 {
                let nthbit = 1u64 << j;
                if tset[i] & nthbit != 0 {
                    let cc = (i * 64 + j) as u8;
                    if rangestart.is_none() {
                        rangestart = Some(cc);
                        prevchar = Some(cc);
                        continue;
                    }

                    if let (Some(currstart), Some(currprev)) = (rangestart, prevchar) {
                        if currprev == cc - 1 {
                            prevchar = Some(cc);
                            continue;
                        }
                        ranges.insert((currstart, currprev));
                        rangestart = Some(cc);
                        prevchar = Some(cc);
                    }
                }
            }
        }
        if let (Some(start), Some(end)) = (rangestart, prevchar) {
            ranges.insert((start, end));
        }
        ranges
    }

    fn pp_byte(b: u8) -> String {
        if cfg!(feature = "graphviz") {
            match b as char {
                // graphviz doesnt like \n so we use \á¹…
                '\n' => return r"\á¹…".to_owned(),
                '"' => return r"\u{201c}".to_owned(),
                '\r' => return r"\r".to_owned(),
                '\t' => return r"\t".to_owned(),
                _ => {}
            }
        }
        match b as char {
            '\n' => r"\n".to_owned(),
            '\r' => r"\r".to_owned(),
            '\t' => r"\t".to_owned(),
            ' ' => r" ".to_owned(),
            '_' | '.' | '+' | '-' | '\\' | '&' | '|' | '~' | '{' | '}' | '[' | ']' | '(' | ')'
            | '*' | '?' | '^' | '$' => r"\".to_owned() + &(b as char).to_string(),
            c if c.is_ascii_punctuation() || c.is_ascii_alphanumeric() => c.to_string(),
            _ => format!("\\x{:02X}", b),
        }
    }

    fn pp_content(ranges: &BTreeSet<(u8, u8)>) -> String {
        let display_range = |c, c2| {
            if c == c2 {
                Self::pp_byte(c)
            } else if c.abs_diff(c2) == 1 {
                format!("{}{}", Self::pp_byte(c), Self::pp_byte(c2))
            } else {
                format!("{}-{}", Self::pp_byte(c), Self::pp_byte(c2))
            }
        };

        if ranges.is_empty() {
            return "\u{22a5}".to_owned();
        }
        if ranges.len() == 1 {
            let (s, e) = ranges.iter().next().unwrap();
            if s == e {
                return Self::pp_byte(*s);
            } else {
                return ranges
                    .iter()
                    .map(|(s, e)| display_range(*s, *e))
                    .collect::<Vec<_>>()
                    .join("")
                    .to_string();
            }
        }
        if ranges.len() > 20 {
            return "\u{03c6}".to_owned();
        }
        ranges
            .iter()
            .map(|(s, e)| display_range(*s, *e))
            .collect::<Vec<_>>()
            .join("")
            .to_string()
    }

    pub fn pp_first(&self, tset: &TSet) -> char {
        let tryn1 = |i: usize| {
            for j in 0..32 {
                let nthbit = 1u64 << j;
                if tset[i] & nthbit != 0 {
                    let cc = (i * 64 + j) as u8 as char;
                    return Some(cc);
                }
            }
            None
        };
        let tryn2 = |i: usize| {
            for j in 33..64 {
                let nthbit = 1u64 << j;
                if tset[i] & nthbit != 0 {
                    let cc = (i * 64 + j) as u8 as char;
                    return Some(cc);
                }
            }
            None
        };
        // readable ones first
        tryn2(0)
            .or_else(|| tryn2(1))
            .or_else(|| tryn1(1))
            .or_else(|| tryn1(2))
            .or_else(|| tryn2(2))
            .or_else(|| tryn1(3))
            .or_else(|| tryn2(3))
            .or_else(|| tryn1(0))
            .unwrap_or('\u{22a5}')
    }

    pub fn byte_ranges(&self, tset: TSetId) -> Vec<(u8, u8)> {
        let tset = self.get_set(tset);
        Self::pp_collect_ranges(&tset).into_iter().collect()
    }

    #[allow(unused)]
    fn first_byte(tset: &TSet) -> u8 {
        for i in 0..4 {
            for j in 0..64 {
                let nthbit = 1u64 << j;
                if tset[i] & nthbit != 0 {
                    let cc = (i * 64 + j) as u8;
                    return cc;
                }
            }
        }
        0
    }

    pub fn pp(&self, tset: TSetId) -> String {
        if tset == TSetId::FULL {
            return "_".to_owned();
        }
        if tset == TSetId::EMPTY {
            return "\u{22a5}".to_owned();
        }
        let tset = self.get_set(tset);
        let ranges: BTreeSet<(u8, u8)> = Self::pp_collect_ranges(&tset);
        let rstart = ranges.first().unwrap().0;
        let rend = ranges.last().unwrap().1;
        if ranges.len() >= 2 && rstart == 0 && rend == 255 {
            let not_id = Self::not(&tset);
            let not_ranges = Self::pp_collect_ranges(&not_id);
            if not_ranges.len() == 1 && not_ranges.iter().next() == Some(&(10, 10)) {
                return r".".to_owned();
            }
            let content = Self::pp_content(&not_ranges);
            return format!("[^{}]", content);
        }
        if ranges.is_empty() {
            return "\u{22a5}".to_owned();
        }
        if ranges.len() == 1 {
            let (s, e) = ranges.iter().next().unwrap();
            if s == e {
                return Self::pp_byte(*s);
            } else {
                let content = Self::pp_content(&ranges);
                return format!("[{}]", content);
            }
        }
        let content = Self::pp_content(&ranges);
        format!("[{}]", content)
    }
}

impl Solver {
    #[inline]
    pub fn full() -> TSet {
        FULL
    }

    #[inline]
    pub fn empty() -> TSet {
        EMPTY
    }

    #[inline]
    pub fn or_id(&mut self, set1: TSetId, set2: TSetId) -> TSetId {
        self.get_id(self.get_set(set1) | self.get_set(set2))
    }

    #[inline]
    pub fn and_id(&mut self, set1: TSetId, set2: TSetId) -> TSetId {
        self.get_id(self.get_set(set1) & self.get_set(set2))
    }

    #[inline]
    pub fn not_id(&mut self, set_id: TSetId) -> TSetId {
        self.get_id(!self.get_set(set_id))
    }

    #[inline]
    pub fn is_sat_id(&mut self, set1: TSetId, set2: TSetId) -> bool {
        self.and_id(set1, set2) != TSetId::EMPTY
    }
    #[inline]
    pub fn unsat_id(&mut self, set1: TSetId, set2: TSetId) -> bool {
        self.and_id(set1, set2) == TSetId::EMPTY
    }

    pub fn byte_count(&self, set_id: TSetId) -> u32 {
        let tset = self.get_set(set_id);
        (0..4).map(|i| tset[i].count_ones()).sum()
    }

    pub fn collect_bytes(&self, set_id: TSetId) -> Vec<u8> {
        let tset = self.get_set(set_id);
        let mut bytes = Vec::new();
        for i in 0..4 {
            let mut bits = tset[i];
            while bits != 0 {
                let j = bits.trailing_zeros() as usize;
                bytes.push((i * 64 + j) as u8);
                bits &= bits - 1;
            }
        }
        bytes
    }

    pub fn single_byte(&self, set_id: TSetId) -> Option<u8> {
        let tset = self.get_set(set_id);
        let total: u32 = (0..4).map(|i| tset[i].count_ones()).sum();
        if total != 1 {
            return None;
        }
        for i in 0..4 {
            if tset[i] != 0 {
                return Some((i * 64 + tset[i].trailing_zeros() as usize) as u8);
            }
        }
        None
    }

    #[inline]
    pub fn is_empty_id(&self, set1: TSetId) -> bool {
        set1 == TSetId::EMPTY
    }

    #[inline]
    pub fn is_full_id(&self, set1: TSetId) -> bool {
        set1 == TSetId::FULL
    }

    #[inline]
    pub fn contains_id(&mut self, large_id: TSetId, small_id: TSetId) -> bool {
        let not_large = self.not_id(large_id);
        self.and_id(small_id, not_large) == TSetId::EMPTY
    }

    pub fn u8_to_set_id(&mut self, byte: u8) -> TSetId {
        let mut result = TSet::splat(u64::MIN);
        let nthbit = 1u64 << (byte % 64);
        match byte {
            0..=63 => {
                result[0] = nthbit;
            }
            64..=127 => {
                result[1] = nthbit;
            }
            128..=191 => {
                result[2] = nthbit;
            }
            192..=255 => {
                result[3] = nthbit;
            }
        }
        self.get_id(result)
    }

    pub fn range_to_set_id(&mut self, start: u8, end: u8) -> TSetId {
        let mut result = TSet::splat(u64::MIN);
        for byte in start..=end {
            let nthbit = 1u64 << (byte % 64);
            match byte {
                0..=63 => {
                    result[0] |= nthbit;
                }
                64..=127 => {
                    result[1] |= nthbit;
                }
                128..=191 => {
                    result[2] |= nthbit;
                }
                192..=255 => {
                    result[3] |= nthbit;
                }
            }
        }
        self.get_id(result)
    }

    #[inline]
    pub fn and(set1: &TSet, set2: &TSet) -> TSet {
        *set1 & *set2
    }

    #[inline]
    pub fn is_sat(set1: &TSet, set2: &TSet) -> bool {
        *set1 & *set2 != Solver::empty()
    }

    #[inline]
    pub fn or(set1: &TSet, set2: &TSet) -> TSet {
        *set1 | *set2
    }

    #[inline]
    pub fn not(set: &TSet) -> TSet {
        !*set
    }

    #[inline]
    pub fn is_full(set: &TSet) -> bool {
        *set == Self::full()
    }

    #[inline]
    pub fn is_empty(set: &TSet) -> bool {
        *set == Solver::empty()
    }

    #[inline]
    pub fn contains(large: &TSet, small: &TSet) -> bool {
        Solver::empty() == (*small & !*large)
    }

    pub fn u8_to_set(byte: u8) -> TSet {
        let mut result = TSet::splat(u64::MIN);
        let nthbit = 1u64 << (byte % 64);
        match byte {
            0..=63 => {
                result[0] = nthbit;
            }
            64..=127 => {
                result[1] = nthbit;
            }
            128..=191 => {
                result[2] = nthbit;
            }
            192..=255 => {
                result[3] = nthbit;
            }
        }
        result
    }

    pub fn range_to_set(start: u8, end: u8) -> TSet {
        let mut result = TSet::splat(u64::MIN);
        for byte in start..=end {
            let nthbit = 1u64 << (byte % 64);
            match byte {
                0..=63 => {
                    result[0] |= nthbit;
                }
                64..=127 => {
                    result[1] |= nthbit;
                }
                128..=191 => {
                    result[2] |= nthbit;
                }
                192..=255 => {
                    result[3] |= nthbit;
                }
            }
        }
        result
    }
}