aboutsummaryrefslogtreecommitdiffstats
path: root/src/qml/jsruntime/qv4regexp.cpp
blob: 9c48199157faf7a30de6d34d10e578a63062cbd4 (plain)
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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qv4regexp_p.h"
#include "qv4engine_p.h"
#include "qv4scopedvalue_p.h"
#include <private/qv4mm_p.h>
#include <runtime/VM.h>

using namespace QV4;

#if ENABLE(YARR_JIT)
static constexpr quint8 RegexpJitThreshold = 5;
#endif

static JSC::RegExpFlags jscFlags(uint flags)
{
    JSC::RegExpFlags jscFlags = JSC::NoFlags;
    if (flags & CompiledData::RegExp::RegExp_Global)
        jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagGlobal);
    if (flags & CompiledData::RegExp::RegExp_IgnoreCase)
        jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagIgnoreCase);
    if (flags & CompiledData::RegExp::RegExp_Multiline)
        jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagMultiline);
    if (flags & CompiledData::RegExp::RegExp_Unicode)
        jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagUnicode);
    if (flags & CompiledData::RegExp::RegExp_Sticky)
        jscFlags = static_cast<JSC::RegExpFlags>(jscFlags | JSC::FlagSticky);
    return jscFlags;
}

RegExpCache::~RegExpCache()
{
    for (RegExpCache::Iterator it = begin(), e = end(); it != e; ++it) {
        if (RegExp *re = it.value().as<RegExp>())
            re->d()->cache = nullptr;
    }
}

DEFINE_MANAGED_VTABLE(RegExp);

uint RegExp::match(const QString &string, int start, uint *matchOffsets)
{
    if (!isValid())
        return JSC::Yarr::offsetNoMatch;

#if ENABLE(YARR_JIT)
    auto *priv = d();

    auto regenerateByteCode = [](Heap::RegExp *regexp) {
        JSC::Yarr::ErrorCode error = JSC::Yarr::ErrorCode::NoError;
        JSC::Yarr::YarrPattern yarrPattern(WTF::String(*regexp->pattern), jscFlags(regexp->flags),
                                           error);

        // As we successfully parsed the pattern before, we should still be able to.
        Q_ASSERT(error == JSC::Yarr::ErrorCode::NoError);

        regexp->byteCode = JSC::Yarr::byteCompile(
                                   yarrPattern,
                                   regexp->internalClass->engine->bumperPointerAllocator).release();
    };

    auto removeJitCode = [](Heap::RegExp *regexp) {
        delete regexp->jitCode;
        regexp->jitCode = nullptr;
        regexp->jitFailed = true;
    };

    auto removeByteCode = [](Heap::RegExp *regexp) {
        delete regexp->byteCode;
        regexp->byteCode = nullptr;
    };

    if (!priv->jitCode && !priv->jitFailed && priv->internalClass->engine->canJIT()
            && (string.length() > 1024 || priv->matchCount++ == RegexpJitThreshold)) {
        removeByteCode(priv);

        JSC::Yarr::ErrorCode error = JSC::Yarr::ErrorCode::NoError;
        JSC::Yarr::YarrPattern yarrPattern(
                WTF::String(*priv->pattern), jscFlags(priv->flags), error);
        if (!yarrPattern.m_containsBackreferences) {
            priv->jitCode = new JSC::Yarr::YarrCodeBlock;
            JSC::VM *vm = static_cast<JSC::VM *>(priv->internalClass->engine);
            JSC::Yarr::jitCompile(yarrPattern, JSC::Yarr::Char16, vm, *priv->jitCode);
        }

        if (!priv->hasValidJITCode()) {
            removeJitCode(priv);
            regenerateByteCode(priv);
        }
    }
#endif

    WTF::String s(string);

#if ENABLE(YARR_JIT)
    if (priv->hasValidJITCode()) {
        static const uint offsetJITFail = std::numeric_limits<unsigned>::max() - 1;
        uint ret = JSC::Yarr::offsetNoMatch;
#if ENABLE(YARR_JIT_ALL_PARENS_EXPRESSIONS)
        char buffer[8192];
        ret = uint(priv->jitCode->execute(s.characters16(), start, s.size(),
                                          (int*)matchOffsets, buffer, 8192).start);
#else
        ret = uint(priv->jitCode->execute(s.characters16(), start, s.length(),
                                          (int*)matchOffsets).start);
#endif
        if (ret != offsetJITFail)
            return ret;

        removeJitCode(priv);
        // JIT failed. We need byteCode to run the interpreter.
        Q_ASSERT(!priv->byteCode);
        regenerateByteCode(priv);
    }
#endif // ENABLE(YARR_JIT)

    return JSC::Yarr::interpret(byteCode(), s.characters16(), string.size(), start, matchOffsets);
}

QString RegExp::getSubstitution(const QString &matched, const QString &str, int position, const Value *captures, int nCaptures, const QString &replacement)
{
    QString result;

    int matchedLength = matched.size();
    Q_ASSERT(position >= 0 && position <= str.size());
    int tailPos = position + matchedLength;
    int seenDollar = -1;
    for (int i = 0; i < replacement.size(); ++i) {
        QChar ch = replacement.at(i);
        if (seenDollar >= 0) {
            if (ch.unicode() == '$') {
                result += QLatin1Char('$');
            } else if (ch.unicode() == '&') {
                result += matched;
            } else if (ch.unicode() == '`') {
                result += str.left(position);
            } else if (ch.unicode() == '\'') {
                result += str.mid(tailPos);
            } else if (ch.unicode() >= '0' && ch.unicode() <= '9') {
                int n = ch.unicode() - '0';
                if (i + 1 < replacement.size()) {
                    ch = replacement.at(i + 1);
                    if (ch.unicode() >= '0' && ch.unicode() <= '9') {
                        n = n*10 + (ch.unicode() - '0');
                        ++i;
                    }
                }
                if (n > 0 && n <= nCaptures) {
                    String *s = captures[n].stringValue();
                    if (s)
                        result += s->toQString();
                } else {
                    for (int j = seenDollar; j <= i; ++j)
                        result += replacement.at(j);
                }
            } else {
                result += QLatin1Char('$');
                result += ch;
            }
            seenDollar = -1;
        } else {
            if (ch == QLatin1Char('$')) {
                seenDollar = i;
                continue;
            }
            result += ch;
        }
    }
    if (seenDollar >= 0)
        result += QLatin1Char('$');
    return result;
}

QString Heap::RegExp::flagsAsString() const
{
    QString result;
    if (flags & CompiledData::RegExp::RegExp_Global)
        result += QLatin1Char('g');
    if (flags & CompiledData::RegExp::RegExp_IgnoreCase)
        result += QLatin1Char('i');
    if (flags & CompiledData::RegExp::RegExp_Multiline)
        result += QLatin1Char('m');
    if (flags & CompiledData::RegExp::RegExp_Unicode)
        result += QLatin1Char('u');
    if (flags & CompiledData::RegExp::RegExp_Sticky)
        result += QLatin1Char('y');
    return result;
}

Heap::RegExp *RegExp::create(ExecutionEngine* engine, const QString& pattern, uint flags)
{
    RegExpCacheKey key(pattern, flags);

    RegExpCache *cache = engine->regExpCache;
    if (!cache)
        cache = engine->regExpCache = new RegExpCache;

    QV4::WeakValue &cachedValue = (*cache)[key];
    if (QV4::RegExp *result = cachedValue.as<RegExp>())
        return result->d();

    Scope scope(engine);
    Scoped<RegExp> result(scope, engine->memoryManager->alloc<RegExp>(engine, pattern, flags));

    result->d()->cache = cache;
    cachedValue.set(engine, result);

    return result->d();
}

void Heap::RegExp::init(ExecutionEngine *engine, const QString &pattern, uint flags)
{
    Base::init();
    this->pattern = new QString(pattern);
    this->flags = flags;

    valid = false;
    jitFailed = false;
    matchCount = 0;

    JSC::Yarr::ErrorCode error = JSC::Yarr::ErrorCode::NoError;
    JSC::Yarr::YarrPattern yarrPattern(WTF::String(pattern), jscFlags(flags), error);
    if (error != JSC::Yarr::ErrorCode::NoError)
        return;
    subPatternCount = yarrPattern.m_numSubpatterns;
    Q_UNUSED(engine);
    byteCode = JSC::Yarr::byteCompile(yarrPattern, internalClass->engine->bumperPointerAllocator).release();
    if (byteCode)
        valid = true;
}

void Heap::RegExp::destroy()
{
    if (cache) {
        RegExpCacheKey key(this);
        cache->remove(key);
    }
#if ENABLE(YARR_JIT)
    delete jitCode;
#endif
    delete byteCode;
    delete pattern;
    Base::destroy();
}