aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/hyperscan/src/rose/rose_build_convert.cpp
blob: d5b73cad550e095bac1674074e31e51eb8068119 (plain) (blame)
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
/*
 * Copyright (c) 2015-2017, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of Intel Corporation nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "rose_build_convert.h"

#include "grey.h"
#include "rose_build.h"
#include "rose_build_impl.h"
#include "rose_build_util.h"
#include "ue2common.h"
#include "hwlm/hwlm_build.h"
#include "nfa/castlecompile.h"
#include "nfa/limex_limits.h"
#include "nfagraph/ng_dump.h"
#include "nfagraph/ng_limex.h"
#include "nfagraph/ng_repeat.h"
#include "nfagraph/ng_reports.h"
#include "nfagraph/ng_split.h"
#include "nfagraph/ng_util.h"
#include "nfagraph/ng_width.h"
#include "util/bitutils.h"
#include "util/charreach.h"
#include "util/charreach_util.h"
#include "util/compile_context.h"
#include "util/depth.h"
#include "util/graph_range.h"
#include "util/make_unique.h"
#include "util/order_check.h"
#include "util/ue2string.h"

#include <algorithm>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include <boost/range/adaptor/map.hpp>

using namespace std;
using boost::adaptors::map_values;

namespace ue2 {

static
NFAVertex addHolderVertex(const CharReach &cr, NGHolder &out) {
    assert(cr.any());
    NFAVertex v = add_vertex(out);
    out[v].char_reach = cr;
    return v;
}

static
size_t suffixFloodLen(const ue2_literal &s) {
    if (s.empty()) {
        return 0;
    }

    const ue2_literal::elem &c = s.back();
    auto it = find_if(s.rbegin(), s.rend(),
                      [&c](const ue2_literal::elem &e) { return e != c; });
    return distance(s.rbegin(), it);
}

static
unique_ptr<NGHolder> makeFloodProneSuffix(const ue2_literal &s, size_t len,
                                          const flat_set<ReportID> &reports) {
    assert(len < s.length());
    assert(!reports.empty());

    unique_ptr<NGHolder> h = ue2::make_unique<NGHolder>(NFA_SUFFIX);

    NFAVertex u = h->start;
    for (auto it = s.begin() + s.length() - len; it != s.end(); ++it) {
        NFAVertex v = addHolderVertex(*it, *h);
        NFAEdge e = add_edge(u, v, *h);
        if (u == h->start) {
            (*h)[e].tops.insert(DEFAULT_TOP);
        }
        u = v;
    }

    (*h)[u].reports.insert(reports.begin(), reports.end());
    add_edge(u, h->accept, *h);
    return h;
}

static
unique_ptr<NGHolder> makeRosePrefix(const ue2_literal &s) {
    unique_ptr<NGHolder> h = ue2::make_unique<NGHolder>(NFA_PREFIX);

    NFAVertex u = h->startDs;
    for (const auto &c : s) {
        NFAVertex v = addHolderVertex(c, *h);
        add_edge(u, v, *h);
        u = v;
    }
    add_edge(u, h->accept, *h);
    return h;
}

static
void replaceWithLitPrefix(RoseBuildImpl &tbi, RoseVertex v, u32 lit_id,
                          const rose_literal_id &lit, size_t suffixlen,
                          size_t delay) {
    assert(suffixlen < lit.s.length());

    DEBUG_PRINTF("replacing '%s' with prefix, length=%zu, delay=%zu\n",
                 dumpString(lit.s).c_str(), lit.s.length() - suffixlen, delay);

    RoseGraph &g = tbi.g;
    ue2_literal new_lit = lit.s.substr(0, lit.s.length() - suffixlen);
    u32 new_id = tbi.getLiteralId(new_lit, delay, ROSE_FLOATING);
    rose_literal_info &old_info = tbi.literal_info.at(lit_id);
    old_info.vertices.erase(v);
    tbi.literal_info.at(new_id).vertices.insert(v);
    g[v].literals.clear();
    g[v].literals.insert(new_id);
}

static
bool delayLiteralWithPrefix(RoseBuildImpl &tbi, RoseVertex v, u32 lit_id,
                            const rose_literal_id &lit, size_t suffixlen) {
    if (suffixlen > MAX_DELAY) {
        DEBUG_PRINTF("delay too large\n");
        return false;
    }

    if (!tbi.isDirectReport(lit_id)) {
        DEBUG_PRINTF("literal is not direct report\n");
        return false;
    }

    if (tbi.cc.streaming &&
        lit.s.length() > tbi.cc.grey.maxHistoryAvailable + 1) {
        DEBUG_PRINTF("insufficient history to delay literal of len %zu\n",
                      lit.s.length());
        return false;
    }

    shared_ptr<NGHolder> h = makeRosePrefix(lit.s);
    ReportID prefix_report = 0;
    set_report(*h, prefix_report);

    if (!isImplementableNFA(*h, &tbi.rm, tbi.cc)) {
        DEBUG_PRINTF("prefix not implementable\n");
        return false;
    }

    RoseGraph &g = tbi.g;
    assert(!g[v].left);
    g[v].left.graph = h;
    g[v].left.lag = 0;
    g[v].left.leftfix_report = prefix_report;

    // Swap v's literal for a shorter one, delayed by suffix len.
    replaceWithLitPrefix(tbi, v, lit_id, lit, suffixlen, suffixlen);

    return true;
}

static
void convertFloodProneSuffix(RoseBuildImpl &tbi, RoseVertex v, u32 lit_id,
                             const rose_literal_id &lit, size_t suffixlen) {
    DEBUG_PRINTF("flood-prone leaf '%s'\n", dumpString(lit.s).c_str());
    DEBUG_PRINTF("turning last %zu chars into a suffix NFA\n", suffixlen);
    RoseGraph &g = tbi.g;
    assert(!g[v].eod_accept);

    // If we're a direct report literal, we may be able to convert this case
    // into a delayed literal with a (very boring) transient prefix that
    // handles our flood-prone suffix.
    if (delayLiteralWithPrefix(tbi, v, lit_id, lit, suffixlen)) {
        DEBUG_PRINTF("implemented as delayed literal with a rose prefix\n");
        return;
    }

    // General case: create a suffix that implements the flood-prone portion.

    // Create the NFA.
    auto h = makeFloodProneSuffix(lit.s, suffixlen, g[v].reports);
    if (!isImplementableNFA(*h, &tbi.rm, tbi.cc)) {
        DEBUG_PRINTF("not implementable\n");
        return;
    }

    // Apply the NFA.
    assert(!g[v].suffix);
    g[v].suffix.graph = move(h);
    g[v].reports.clear();

    // Swap v's literal for a shorter one.
    replaceWithLitPrefix(tbi, v, lit_id, lit, suffixlen, 0);

    // It's possible that min_offset might be an underestimate, so we
    // subtract min(min_offset, suffixlen) for safety.
    g[v].min_offset -= min((size_t)g[v].min_offset, suffixlen);

    if (g[v].max_offset < ROSE_BOUND_INF) {
        assert(g[v].max_offset >= suffixlen);
        g[v].max_offset -= suffixlen;
    }
}

/**
 * Collect an estimate of the number of literals in the floating table, and use
 * this to estimate the flood prone suffix length.
 */
static
size_t findFloodProneSuffixLen(const RoseBuildImpl &tbi) {
    size_t numLiterals = 0;
    for (const rose_literal_id &lit : tbi.literals) {
        if (lit.delay) {
            continue; // delay ids are virtual-ish
        }
        if (lit.table != ROSE_FLOATING) {
            continue;
        }

        numLiterals++;
    }

    return hwlmFloodProneSuffixLen(numLiterals, tbi.cc);
}

/**
 * \brief Convert flood-prone literal suffixes into suffix NFAs.
 *
 * For any trailing string in Rose (string cannot lead to more Rose roles or
 * NFAs, etc) ending with a continuous run of a single character with more than
 * 3 copies of that single character,
 *
 * If the result of removing all but 2 copies of that character yields a string
 * that is greater than FLOOD_PRONE_LIT_MIN_LENGTH characters, remove those
 * final characters from the literal and move them into a suffix NFA.
 */
void convertFloodProneSuffixes(RoseBuildImpl &tbi) {
    static const size_t FLOOD_PRONE_LIT_MIN_LENGTH = 5;

    if (!tbi.cc.grey.roseConvertFloodProneSuffixes) {
        return;
    }

    const size_t floodProneLen = findFloodProneSuffixLen(tbi);
    DEBUG_PRINTF("flood prone suffix len = %zu\n", floodProneLen);

    RoseGraph &g = tbi.g;

    for (auto v : vertices_range(g)) {
        if (!isLeafNode(v, g)) {
            continue;
        }

        if (g[v].reports.empty()) {
            continue;
        }

        // TODO: currently only boring vertices.
        if (!g[v].isBoring()) {
            continue;
        }

        // Currently only handles vertices with a single literal (should always
        // be the case this early in Rose construction).
        if (g[v].literals.size() != 1) {
            continue;
        }

        u32 lit_id = *g[v].literals.begin();
        const rose_literal_id &lit = tbi.literals.at(lit_id);

        // anchored or delayed literals need thought.
        if (lit.table != ROSE_FLOATING || lit.delay) {
            continue;
        }

        // don't do this to literals with msk/cmp.
        if (!lit.msk.empty()) {
            continue;
        }

        // Can't safely do this operation to vertices with delayed
        // predecessors.
        if (tbi.hasDelayPred(v)) {
            DEBUG_PRINTF("delayed pred\n");
            continue;
        }

        if (lit.s.length() <= FLOOD_PRONE_LIT_MIN_LENGTH) {
            DEBUG_PRINTF("literal is short enough already\n");
            continue;
        }

        size_t floodLen = suffixFloodLen(lit.s);
        if (floodLen < floodProneLen) {
            DEBUG_PRINTF("literal not flood-prone\n");
            continue;
        }

        if (floodLen == lit.s.length()) {
            DEBUG_PRINTF("whole literal is a flood\n");
            // Removing the part of the flood from the end of the literal would
            // leave us with a shorter, but still flood-prone, prefix. Better
            // to leave it alone.
            continue;
        }

        size_t suffixLen = floodLen - (floodProneLen - 1);
        if (lit.s.length() - suffixLen < FLOOD_PRONE_LIT_MIN_LENGTH) {
            DEBUG_PRINTF("removing flood would leave literal too short\n");
            continue;
        }

        convertFloodProneSuffix(tbi, v, lit_id, lit, suffixLen);
    }
}

static
CharReach getReachOfNormalVertex(const NGHolder &g) {
    for (auto v : vertices_range(g)) {
        if (is_special(v, g)) {
            continue;
        }
        return g[v].char_reach;
    }
    assert(0);
    return CharReach();
}

/**
 * \brief Set the edge bounds and appropriate history on the given edge in the
 * Rose graph.
 */
static
void setEdgeBounds(RoseGraph &g, const RoseEdge &e, u32 min_bound,
                   u32 max_bound) {
    assert(min_bound <= max_bound);
    assert(max_bound <= ROSE_BOUND_INF);

    g[e].minBound = min_bound;
    g[e].maxBound = max_bound;

    if (min_bound || max_bound < ROSE_BOUND_INF) {
        g[e].history = ROSE_ROLE_HISTORY_ANCH;
    } else {
        g[e].history = ROSE_ROLE_HISTORY_NONE;
    }
}

static
bool handleStartPrefixCliche(const NGHolder &h, RoseGraph &g, RoseVertex v,
                             const RoseEdge &e_old, RoseVertex ar,
                             vector<RoseEdge> *to_delete) {
    DEBUG_PRINTF("hi\n");

    /* check for prefix cliches connected to start (^.{N,M}) */
    if (!getReachOfNormalVertex(h).all()) {
        DEBUG_PRINTF(":(\n");
        return false;
    }

    PureRepeat repeat;
    if (!isPureRepeat(h, repeat)) {
        DEBUG_PRINTF(":(\n");
        return false;
    }

    assert(repeat.bounds.min.is_finite());
    assert(repeat.bounds.max.is_reachable());
    assert(repeat.bounds.min <= repeat.bounds.max);

    DEBUG_PRINTF("prefix is ^.{%s,%s}\n", repeat.bounds.min.str().c_str(),
                 repeat.bounds.max.str().c_str());

    /* update bounds on edge */

    // Convert to Rose graph bounds, which are not (yet?) depth classes.
    u32 bound_min = repeat.bounds.min;
    u32 bound_max =
        repeat.bounds.max.is_finite() ? (u32)repeat.bounds.max : ROSE_BOUND_INF;

    if (source(e_old, g) == ar) {
        assert(g[e_old].minBound <= bound_min);
        assert(g[e_old].maxBound >= bound_max);
        setEdgeBounds(g, e_old, bound_min, bound_max);
    } else {
        RoseEdge e_new = add_edge(ar, v, g);
        setEdgeBounds(g, e_new, bound_min, bound_max);
        to_delete->push_back(e_old);
    }

    g[v].left.reset(); /* clear the prefix info */
    return true;
}

static
bool handleStartDsPrefixCliche(const NGHolder &h, RoseGraph &g, RoseVertex v,
                               const RoseEdge &e) {
    DEBUG_PRINTF("hi\n");
    /* check for prefix cliches connected to start-ds (.{N}, ^.{N,}) */
    u32 repeatCount = 0;
    NFAVertex hu = h.startDs;

    auto start_succ = succs<set<NFAVertex>>(h.start, h);
    auto startds_succ = succs<set<NFAVertex>>(h.startDs, h);

    if (!is_subset_of(start_succ, startds_succ)) {
        DEBUG_PRINTF("not a simple chain\n");
        return false;
    }

    set<NFAVertex> seen;
    do {
        if (!h[hu].char_reach.all()) {
            return false;
        }
        NFAVertex hv = getSoleDestVertex(h, hu);
        if (!hv) {
            return false;
        }
        if (contains(seen, hv)) {
            assert(0);
            return false;
        }
        hu = hv;
        repeatCount++;
        if (hu == h.accept) {
            break;
        }
    } while(1);

    assert(hu == h.accept);

    repeatCount--; /* do not count accept as part of the chain */

    DEBUG_PRINTF("prefix is ^.{%u,}\n", repeatCount);

    /* update bounds on edge */
    assert(g[e].minBound <= repeatCount);
    setEdgeBounds(g, e, repeatCount, ROSE_BOUND_INF);

    g[v].left.reset(); /* clear the prefix info */

    return true;
}

static
bool handleMixedPrefixCliche(const NGHolder &h, RoseGraph &g, RoseVertex v,
                             const RoseEdge &e_old, RoseVertex ar,
                             vector<RoseEdge> *to_delete,
                             const CompileContext &cc) {
    assert(in_degree(h.acceptEod, h) == 1);

    bool anchored = !proper_out_degree(h.startDs, h);
    NFAVertex key = NGHolder::null_vertex();
    NFAVertex base = anchored ? h.start : h.startDs;

    if (!anchored) {
        auto start_succ = succs<set<NFAVertex>>(h.start, h);
        auto startds_succ = succs<set<NFAVertex>>(h.startDs, h);

        if (!is_subset_of(start_succ, startds_succ)) {
            DEBUG_PRINTF("not a simple chain\n");
            return false;
        }
    }

    for (auto w : adjacent_vertices_range(base, h)) {
        DEBUG_PRINTF("checking %zu\n", h[w].index);
        if (!h[w].char_reach.all()) {
            continue;
        }

        if (!is_special(w, h)) {
            key = w;
            break;
        }
    }

    if (!key) {
        return false;
    }

    vector<GraphRepeatInfo> repeats;
    findRepeats(h, 2, &repeats);

    vector<GraphRepeatInfo>::const_iterator it;
    for (it = repeats.begin(); it != repeats.end(); ++it) {
        DEBUG_PRINTF("checking.. %zu verts\n", it->vertices.size());
        if (find(it->vertices.begin(), it->vertices.end(), key)
            != it->vertices.end()) {
            break;
        }
    }
    if (it == repeats.end()) {
        DEBUG_PRINTF("no repeat found\n");
        return false;
    }

    GraphRepeatInfo ri = *it;

    set<NFAVertex> exits_and_repeat_verts;
    for (auto repeat_v : ri.vertices) {
        DEBUG_PRINTF("repeat vertex %zu\n", h[repeat_v].index);
        succ(h, repeat_v, &exits_and_repeat_verts);
        exits_and_repeat_verts.insert(repeat_v);
    }

    DEBUG_PRINTF("repeat {%s,%s}\n", ri.repeatMin.str().c_str(),
                 ri.repeatMax.str().c_str());

    set<NFAVertex> rep_verts;
    insert(&rep_verts, ri.vertices);

    set<NFAVertex> exits;
    exits = exits_and_repeat_verts;
    erase_all(&exits, rep_verts);

    auto base_succ = succs<set<NFAVertex>>(base, h);
    base_succ.erase(h.startDs);

    if (is_subset_of(base_succ, rep_verts)) {
        /* all good: repeat dominates the rest of the pattern */
    } else if (ri.repeatMin == depth(1)
               && is_subset_of(exits, base_succ)
               && is_subset_of(base_succ, exits_and_repeat_verts)) {
        /* we have a jump edge */
        ri.repeatMin = depth(0);
    } else {
        return false;
    }

    DEBUG_PRINTF("repeat {%s,%s}\n", ri.repeatMin.str().c_str(),
                 ri.repeatMax.str().c_str());
    DEBUG_PRINTF("woot?\n");

    shared_ptr<NGHolder> h_new = make_shared<NGHolder>();
    if (!h_new) {
        assert(0);
        throw std::bad_alloc();
    }
    unordered_map<NFAVertex, NFAVertex> rhs_map;
    vector<NFAVertex> exits_vec;
    insert(&exits_vec, exits_vec.end(), exits);
    splitRHS(h, exits_vec, h_new.get(), &rhs_map);
    h_new->kind = NFA_PREFIX;

    if (num_vertices(*h_new) <= N_SPECIALS) {
        DEBUG_PRINTF("not a hybrid??\n");
        /* TODO: pick up these cases, unify code */
        return false;
    }

    for (auto w : adjacent_vertices_range(h_new->start, *h_new)) {
        if (w != h_new->startDs) {
            add_edge(h_new->startDs, w, *h_new);
        }
    }
    clear_out_edges(h_new->start, *h_new);
    add_edge(h_new->start, h_new->startDs, *h_new);

    depth width = findMinWidth(*h_new);
    if (width != findMaxWidth(*h_new)) {
        return false;
    }

    if (g[v].left.dfa) {
        /* we were unable to implement initial graph as an nfa;
         * we need to to check if we still need a dfa and, if so, rebuild. */
        if (!isImplementableNFA(*h_new, nullptr, cc)) {
            return false; /* TODO: handle rebuilding dfa */
        }
    }

    if (anchored) {
        if (ri.repeatMax.is_infinite()) {
            return false; /* TODO */
        }

        if (source(e_old, g) == ar) {
            setEdgeBounds(g, e_old, ri.repeatMin + width, ri.repeatMax + width);
        } else {
            RoseEdge e_new = add_edge(ar, v, g);
            setEdgeBounds(g, e_new, ri.repeatMin + width, ri.repeatMax + width);
            to_delete->push_back(e_old);
        }

    } else {
        assert(g[e_old].minBound <= ri.repeatMin + width);
        setEdgeBounds(g, e_old, ri.repeatMin + width, ROSE_BOUND_INF);
    }

    g[v].left.dfa.reset();
    g[v].left.graph = h_new;

    return true;
}

/* turns simple prefixes like /^.{30,} into bounds on the root roles */
void convertPrefixToBounds(RoseBuildImpl &tbi) {
    RoseGraph &g = tbi.g;

    vector<RoseEdge> to_delete;
    RoseVertex ar = tbi.anchored_root;

    /* graphs with prefixes produced by rose are wired to tbi.root */

    for (const auto &e : out_edges_range(tbi.root, g)) {
        RoseVertex v = target(e, g);

        if (in_degree(v, g) != 1) {
            continue;
        }

        if (!g[v].left.graph) {
            continue;
        }

        if (g[v].left.tracksSom()) {
            continue;
        }

        const NGHolder &h = *g[v].left.graph;

        if (g[v].left.lag != tbi.minLiteralLen(v)
            || g[v].left.lag != tbi.maxLiteralLen(v)) {
            continue;
        }

        if (all_reports(h).size() != 1) {
            assert(0);
            continue;
        }

        DEBUG_PRINTF("inspecting prefix of %zu\n", g[v].index);

        if (!proper_out_degree(h.startDs, h)) {
            if (handleStartPrefixCliche(h, g, v, e, ar, &to_delete)) {
                continue;
            }
        } else {
            if (handleStartDsPrefixCliche(h, g, v, e)) {
                continue;
            }
        }

        /* prefix is not just a simple dot repeat. However, it is still
         * possible that it consists of dot repeat and fixed width mask that we
         * can handle. */
        handleMixedPrefixCliche(h, g, v, e, ar, &to_delete, tbi.cc);
    }

    for (const auto &e : out_edges_range(ar, g)) {
        RoseVertex v = target(e, g);

        /* note: vertices that we have rehomed will currently have an in-degree
         * of 2 */
        if (in_degree(v, g) != 1) {
            continue;
        }

        if (!g[v].left.graph) {
            continue;
        }

        if (g[v].left.tracksSom()) {
            continue;
        }

        if (g[v].left.lag != tbi.minLiteralLen(v)
            || g[v].left.lag != tbi.maxLiteralLen(v)) {
            continue;
        }

        const NGHolder &h = *g[v].left.graph;
        if (all_reports(h).size() != 1) {
            assert(0);
            continue;
        }

        DEBUG_PRINTF("inspecting prefix of %zu\n", g[v].index);

        if (!proper_out_degree(h.startDs, h)) {
            if (handleStartPrefixCliche(h, g, v, e, ar, &to_delete)) {
                continue;
            }
        } else {
            if (handleStartDsPrefixCliche(h, g, v, e)) {
                continue;
            }
        }

        /* prefix is not just a simple dot repeat. However, it is still
         * possible that it consists of dot repeat and fixed width mask that we
         * can handle. */
        handleMixedPrefixCliche(h, g, v, e, ar, &to_delete, tbi.cc);
    }

    for (const auto &e : to_delete) {
        remove_edge(e, g);
    }
}

/**
 * Identify dot-repeat infixes after fixed-depth literals and convert them to
 * edges with ROSE_ROLE_HISTORY_ANCH history and equivalent bounds.
 */
void convertAnchPrefixToBounds(RoseBuildImpl &tbi) {
    RoseGraph &g = tbi.g;

    for (const auto v : vertices_range(g)) {
        if (!g[v].left) {
            continue;
        }

        DEBUG_PRINTF("vertex %zu\n", g[v].index);

        // This pass runs after makeCastles, so we use the fact that bounded
        // repeat detection has already been done for us.

        if (!g[v].left.castle) {
            DEBUG_PRINTF("not a castle\n");
            continue;
        }

        const CastleProto &castle = *g[v].left.castle;

        if (castle.repeats.size() != 1) {
            DEBUG_PRINTF("too many repeats\n");
            assert(0); // Castles should not have been merged yet.
            continue;
        }

        if (!castle.reach().all()) {
            DEBUG_PRINTF("not dot\n");
            continue;
        }

        if (in_degree(v, g) != 1) {
            DEBUG_PRINTF("too many in-edges\n");
            continue;
        }

        RoseEdge e = *in_edges(v, g).first;
        RoseVertex u = source(e, g);

        if (g[e].history != ROSE_ROLE_HISTORY_NONE) {
            DEBUG_PRINTF("history already set to something other than NONE?\n");
            assert(0);
            continue;
        }

        if (g[u].min_offset != g[u].max_offset) {
            DEBUG_PRINTF("pred not fixed offset\n");
            continue;
        }
        DEBUG_PRINTF("pred is fixed offset, at %u\n", g[u].min_offset);
        assert(g[u].min_offset < ROSE_BOUND_INF);

        size_t lit_length = tbi.minLiteralLen(v);
        if (lit_length != tbi.maxLiteralLen(v)) {
            assert(0);
            DEBUG_PRINTF("variable literal lengths\n");
            continue;
        }

        u32 lag = g[v].left.lag;
        DEBUG_PRINTF("lit_length=%zu, lag=%u\n", lit_length, lag);
        assert(lag <= lit_length);
        depth delay_adj(lit_length - lag);

        const PureRepeat &pr = castle.repeats.begin()->second;
        DEBUG_PRINTF("castle has repeat %s\n", pr.bounds.str().c_str());
        DEBUG_PRINTF("delay adj %u\n", (u32)delay_adj);

        if (delay_adj >= pr.bounds.max) {
            DEBUG_PRINTF("delay adj too large\n");
            continue;
        }

        DepthMinMax bounds(pr.bounds); // copy
        if (delay_adj > bounds.min) {
            bounds.min = depth(0);
        } else {
            bounds.min -= delay_adj;
        }
        bounds.max -= delay_adj;
        setEdgeBounds(g, e, bounds.min, bounds.max.is_finite()
                                            ? (u32)bounds.max
                                            : ROSE_BOUND_INF);
        g[v].left.reset();
    }
}

} // namespace ue2