aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/regex/pcre/regexp.cpp
blob: 487a9100b995c18dd1a5d6f31f5fc5b610fb1a3e (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
#include "regexp.h"

#include <util/generic/string.h>
#include <util/string/ascii.h>
#include <util/system/defaults.h>

#include <cstdlib>
#include <util/generic/noncopyable.h> 

class TGlobalImpl : TNonCopyable { 
private:
    const char* Str;
    regmatch_t* Pmatch;
    int Options;
    int StrLen;
    int StartOffset, NotEmptyOpts, MatchPos;
    int MatchBuf[NMATCHES * 3];
    pcre* PregComp;

    enum StateCode {
        TGI_EXIT,
        TGI_CONTINUE,
        TGI_WALKTHROUGH
    };

private:
    void CopyResults(int count) {
        for (int i = 0; i < count; i++) {
            Pmatch[MatchPos].rm_so = MatchBuf[2 * i];
            Pmatch[MatchPos].rm_eo = MatchBuf[2 * i + 1];
            MatchPos++;
            if (MatchPos >= NMATCHES) {
                ythrow yexception() << "TRegExBase::Exec(): Not enough space in internal buffer.";
            }
        }
    }

    int DoPcreExec(int opts) {
        int rc = pcre_exec(
            PregComp,    /* the compiled pattern */
            nullptr,     /* no extra data - we didn't study the pattern */
            Str,         /* the subject string */
            StrLen,      /* the length of the subject */
            StartOffset, /* start at offset 0 in the subject */
            opts,        /* default options */
            MatchBuf,    /* output vector for substring information */
            NMATCHES);   /* number of elements in the output vector */

        if (rc == 0) {
            ythrow yexception() << "TRegExBase::Exec(): Not enough space in internal buffer.";
        }

        return rc;
    }

    StateCode CheckEmptyCase() {
        if (MatchBuf[0] == MatchBuf[1]) { // founded an empty string
            if (MatchBuf[0] == StrLen) {  // at the end
                return TGI_EXIT;
            }
            NotEmptyOpts = PCRE_NOTEMPTY | PCRE_ANCHORED; // trying to find non empty string
        }
        return TGI_WALKTHROUGH;
    }

    StateCode CheckNoMatch(int rc) {
        if (rc == PCRE_ERROR_NOMATCH) {
            if (NotEmptyOpts == 0) {
                return TGI_EXIT;
            }

            MatchBuf[1] = StartOffset + 1; // we have failed to find non-empty-string. trying to find again shifting "previous match offset"
            return TGI_CONTINUE;
        }
        return TGI_WALKTHROUGH;
    }

public:
    TGlobalImpl(const char* st, regmatch_t& pma, int opts, pcre* pc_re)
        : Str(st)
        , Pmatch(&pma)
        , Options(opts)
        , StartOffset(0)
        , NotEmptyOpts(0)
        , MatchPos(0)
        , PregComp(pc_re)
    {
        memset(Pmatch, -1, sizeof(regmatch_t) * NMATCHES);
        StrLen = strlen(Str);
    }

    int ExecGlobal() {
        StartOffset = 0;
        int rc = DoPcreExec(Options);

        if (rc < 0) {
            return rc;
        }
        CopyResults(rc);
        do {
            NotEmptyOpts = 0;
            StartOffset = MatchBuf[1];

            if (CheckEmptyCase() == TGI_EXIT) {
                return 0;
            }

            rc = DoPcreExec(NotEmptyOpts | Options);

            switch (CheckNoMatch(rc)) {
                case TGI_CONTINUE:
                    continue;
                case TGI_EXIT:
                    return 0;
                case TGI_WALKTHROUGH:
                default:
                    break;
            }

            if (rc < 0) {
                return rc;
            }

            CopyResults(rc);
        } while (true);

        return 0;
    }

private:
};

class TRegExBaseImpl: public TAtomicRefCount<TRegExBaseImpl> {
    friend class TRegExBase;

protected:
    int CompileOptions;
    TString RegExpr;
    regex_t Preg;

public:
    TRegExBaseImpl()
        : CompileOptions(0)
    {
        memset(&Preg, 0, sizeof(Preg));
    }

    TRegExBaseImpl(const TString& re, int cflags)
        : CompileOptions(cflags)
        , RegExpr(re)
    {
        int rc = regcomp(&Preg, re.data(), cflags); 
        if (rc) {
            const size_t ERRBUF_SIZE = 100;
            char errbuf[ERRBUF_SIZE];
            regerror(rc, &Preg, errbuf, ERRBUF_SIZE);
            Error = "Error: regular expression " + re + " is wrong: " + errbuf;
            ythrow yexception() << "RegExp " << re << ": " << Error.data(); 
        }
    }

    int Exec(const char* str, regmatch_t pmatch[], int eflags, int nmatches) const {
        if (!RegExpr) {
            ythrow yexception() << "Regular expression is not compiled";
        }
        if (!str) {
            ythrow yexception() << "Empty string is passed to TRegExBaseImpl::Exec";
        }
        if ((eflags & REGEXP_GLOBAL) == 0) {
            return regexec(&Preg, str, nmatches, pmatch, eflags);
        } else {
            int options = 0;
            if ((eflags & REG_NOTBOL) != 0)
                options |= PCRE_NOTBOL;
            if ((eflags & REG_NOTEOL) != 0)
                options |= PCRE_NOTEOL;

            return TGlobalImpl(str, pmatch[0], options, (pcre*)Preg.re_pcre).ExecGlobal();
        }
    }

    bool IsCompiled() {
        return Preg.re_pcre;
    }

    ~TRegExBaseImpl() {
        regfree(&Preg);
    }

private:
    TString Error;
};

bool TRegExBase::IsCompiled() const {
    return Impl && Impl->IsCompiled();
}

TRegExBase::TRegExBase(const char* re, int cflags) {
    if (re) {
        Compile(re, cflags);
    }
}

TRegExBase::TRegExBase(const TString& re, int cflags) {
    Compile(re, cflags);
}

TRegExBase::~TRegExBase() {
}

void TRegExBase::Compile(const TString& re, int cflags) {
    Impl = new TRegExBaseImpl(re, cflags);
}

int TRegExBase::Exec(const char* str, regmatch_t pmatch[], int eflags, int nmatches) const {
    if (!Impl)
        ythrow yexception() << "!Regular expression is not compiled";
    return Impl->Exec(str, pmatch, eflags, nmatches);
}

int TRegExBase::GetCompileOptions() const {
    if (!Impl)
        ythrow yexception() << "!Regular expression is not compiled";
    return Impl->CompileOptions;
}

TString TRegExBase::GetRegExpr() const {
    if (!Impl)
        ythrow yexception() << "!Regular expression is not compiled";
    return Impl->RegExpr;
}

TRegExMatch::TRegExMatch(const char* re, int cflags)
    : TRegExBase(re, cflags)
{
}

TRegExMatch::TRegExMatch(const TString& re, int cflags)
    : TRegExBase(re, cflags)
{
}

bool TRegExMatch::Match(const char* str) const {
    return Exec(str, nullptr, 0, 0) == 0;
}

TRegExSubst::TRegExSubst(const char* re, int cflags)
    : TRegExBase(re, cflags)
    , Replacement(nullptr)
{
    memset(Brfs, 0, sizeof(TBackReferences) * NMATCHES);
}

TString TRegExSubst::Replace(const char* str, int eflags) {
    TString s;
    if (BrfsCount) {
        if (Exec(str, PMatch, eflags) == 0) {
            int i;
            for (i = 0; i < BrfsCount; i++) {
                s += TString(Replacement, Brfs[i].Beg, Brfs[i].End - Brfs[i].Beg);
                if (Brfs[i].Refer >= 0 && Brfs[i].Refer < NMATCHES)
                    s += TString(str, PMatch[Brfs[i].Refer].rm_so, int(PMatch[Brfs[i].Refer].rm_eo - PMatch[Brfs[i].Refer].rm_so));
            }
            s += TString(Replacement, Brfs[i].Beg, Brfs[i].End - Brfs[i].Beg);
        }
    } else {
        s = Replacement;
    }
    return s;
}

//***
// ��� ������������ ������ aaa.$1.$$$$.$2.bbb.$$$ccc Brfs ����� �����:
// {beg = 0,  end = 4,  Refer =  1} => "aaa." + $1_match
// {beg = 6,  end = 8,  Refer = -1} => ".$"
// {beg = 9,  end = 10, Refer = -1} => "$"
// {beg = 11, end = 12, Refer =  2} => "." + $2_match
// {beg = 14, end = 20, Refer = -1} => ".bbb.$"
// {beg = 21, end = 22, Refer = -1} => "$"
// {beg = 22, end = 25, Refer = -1} => "ccc"
// {beg = 0,  end = 0,  Refer =  0}
//***
int TRegExSubst::ParseReplacement(const char* repl) {
    Replacement = repl;
    if (!Replacement || *Replacement == 0)
        return 0;
    char* pos = (char*)Replacement;
    char* pos1 = nullptr;
    char* pos2 = nullptr;
    int i = 0;
    while (pos && *pos && i < NMATCHES) {
        pos1 = strchr(pos, '$');
        Brfs[i].Refer = -1;
        pos2 = pos1;
        if (pos1) {
            pos2 = pos1 + 1;
            while (IsAsciiDigit(*pos2))
                pos2++;
            if (pos2 > pos1 + 1) {
                Brfs[i].Refer = atol(TString(Replacement, pos1 + 1 - Replacement, pos2 - (pos1 + 1)).data()); 
            } else {
                pos1++;
                if (*pos2 == '$')
                    pos2++;
                Brfs[i].Refer = -1;
            }
        }
        Brfs[i].Beg = int(pos - (char*)Replacement);
        Brfs[i].End = (pos1 == nullptr ? (int)strlen(Replacement) : int(pos1 - Replacement));
        pos = pos2;
        i++;
    }
    Brfs[i].Beg = Brfs[i].End = 0;
    Brfs[i].Refer = -1;
    BrfsCount = i;
    return BrfsCount;
}