@geastack/compiler 1.0.25 → 1.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,7 @@
29
29
  #else
30
30
  #include <chrono>
31
31
  #endif
32
+ #include <bitset>
32
33
  #include <cmath>
33
34
  #include <cstdint>
34
35
  #include <cstdio>
@@ -607,6 +608,7 @@ public:
607
608
  // C++20 coroutines: `gea::Iterator<E>`'s generator source is a real coroutine
608
609
  // frame, exactly as v1's `gea_cpp_generator<T>` (`value_09_generator.h`) is.
609
610
  #include <coroutine>
611
+ #include <bitset>
610
612
  #include <cmath>
611
613
  #include <cstddef>
612
614
  #include <cstdint>
@@ -20032,6 +20034,22 @@ struct DynamicCarrier<CallableObject<Result(Arguments...)>> {
20032
20034
  if (value.payloadType() == payloadTypeTagFor<Self>() && value.receivesThis() == targetReceivesThis &&
20033
20035
  value.restFrom() == targetRestFrom)
20034
20036
  return value.as<Self>();
20037
+ if constexpr (std::is_void_v<Result>) {
20038
+ // A target that discards its result, fed a native callable boxed with the
20039
+ // same frame and a result: `@hono/node-server` hands its
20040
+ // `async (req, res) => Promise<void>` listener through a `createServer:
20041
+ // any` into node-compat's `(req, res) => void` slot. Calling it natively
20042
+ // and dropping the result is exactly what the language does with it; the
20043
+ // generic adapter below boxed both arguments on every request instead.
20044
+ if (!targetReceivesThis && targetRestFrom == -1 && !value.receivesThis() && value.restFrom() == -1) {
20045
+ Self discarding;
20046
+ if (discardingAdapt<Promise<void>>(value, discarding) || discardingAdapt<Promise<Undefined>>(value, discarding) ||
20047
+ discardingAdapt<Undefined>(value, discarding) || discardingAdapt<Value>(value, discarding) ||
20048
+ discardingAdapt<bool>(value, discarding) || discardingAdapt<double>(value, discarding) ||
20049
+ discardingAdapt<std::string>(value, discarding))
20050
+ return discarding;
20051
+ }
20052
+ }
20035
20053
  Self adapted(entry, gea::packEnvironment<Value>(value));
20036
20054
  // A dynamic-to-native ABI adapter changes only the invocation convention.
20037
20055
  // It is not a new Function allocation, so it must retain both object
@@ -20040,6 +20058,16 @@ struct DynamicCarrier<CallableObject<Result(Arguments...)>> {
20040
20058
  return adapted;
20041
20059
  }
20042
20060
 
20061
+ template <typename SourceResult>
20062
+ static bool discardingAdapt(const Value& value, Self& out) {
20063
+ using Source = CallableObject<SourceResult(Arguments...)>;
20064
+ if (value.payloadType() != payloadTypeTagFor<Source>()) return false;
20065
+ out = Self::adaptSource(value.as<Source>(), +[](void* environment, Arguments... arguments) -> void {
20066
+ static_cast<Source*>(environment)->call(std::move(arguments)...);
20067
+ });
20068
+ return true;
20069
+ }
20070
+
20043
20071
  static Result adapt(void* environment, Arguments... arguments) {
20044
20072
  alignas(void*) unsigned char slot[sizeof(void*)];
20045
20073
  const Value* source = gea::unpackEnvironment<Value>(environment, slot);
@@ -26740,6 +26768,25 @@ inline std::size_t utf16OffsetFromByte(const std::string &s, std::size_t target)
26740
26768
  return units;
26741
26769
  }
26742
26770
 
26771
+ /** Whether every byte is ASCII, so the string's UTF-8 bytes are its UTF-16 code units. */
26772
+ inline bool asciiOnly(const std::string &s) {
26773
+ for (const char byte : s)
26774
+ if (static_cast<unsigned char>(byte) & 0x80u) return false;
26775
+ return true;
26776
+ }
26777
+
26778
+ /**
26779
+ * Whether `s` holds a lone surrogate (WTF-8 `ED A0..BF ..`). Without one its
26780
+ * bytes and its code units agree on prefixes and suffixes; with one they do
26781
+ * not -- `'\u{1F600}'.startsWith('\uD83D')` is true in UTF-16 and false byte
26782
+ * for byte, since the pair is one four-byte sequence in UTF-8.
26783
+ */
26784
+ inline bool holdsSurrogateEncoding(const std::string &s) {
26785
+ for (std::size_t i = 0; i + 1 < s.size(); ++i)
26786
+ if (static_cast<unsigned char>(s[i]) == 0xEDu && static_cast<unsigned char>(s[i + 1]) >= 0xA0u) return true;
26787
+ return false;
26788
+ }
26789
+
26743
26790
  /** ECMA-262 22.2.5.3 AdvanceStringIndex in the string's public UTF-16 index space. */
26744
26791
  inline std::size_t advanceStringIndex(const std::string &s, std::size_t index, bool unicode) {
26745
26792
  const std::u16string units = utf16CodeUnits(s);
@@ -27728,9 +27775,23 @@ inline std::string normalize(const std::string &s, const std::string &form) {
27728
27775
 
27729
27776
  /** ECMA-262 22.1.3.9 `indexOf(searchString, position)`. `-1` on miss; an empty needle answers the clamped start. v1: `gea_cpp_string_index_of`. */
27730
27777
  inline double indexOf(const std::string &s, const std::string &needle, double position) {
27731
- const std::size_t length = utf16Length(s);
27732
- const std::size_t needleLength = utf16Length(needle);
27778
+ const Utf16Metadata metadata = utf16Metadata(s);
27779
+ const std::size_t length = metadata.units;
27733
27780
  const std::size_t start = clampedPosition(position, length);
27781
+ // An ASCII needle is a byte search: every byte of a multi-byte UTF-8
27782
+ // sequence has its high bit set, so no ASCII byte run can match inside one,
27783
+ // and a byte match is exactly a code-unit match. Walking every position and
27784
+ // slicing a fresh `substringUtf16` at each made one `indexOf` quadratic and
27785
+ // allocating -- 3% of @hono/node-server's CPU, splitting a request's
27786
+ // ninety-byte header block.
27787
+ if (asciiOnly(needle)) {
27788
+ if (needle.empty()) return static_cast<double>(start);
27789
+ const std::size_t from = metadata.basicLatin ? start : byteOffsetFromUtf16(s, start);
27790
+ const std::size_t at = s.find(needle, from);
27791
+ if (at == std::string::npos) return -1.0;
27792
+ return static_cast<double>(metadata.basicLatin ? at : utf16OffsetFromByte(s, at));
27793
+ }
27794
+ const std::size_t needleLength = utf16Length(needle);
27734
27795
  if (needleLength == 0) return static_cast<double>(start);
27735
27796
  if (needleLength > length || start > length - needleLength) return -1.0;
27736
27797
  for (std::size_t index = start; index <= length - needleLength; ++index) {
@@ -27743,12 +27804,22 @@ inline double indexOf(const std::string &s, const std::string &needle) { return
27743
27804
 
27744
27805
  /** ECMA-262 22.1.3.10 `lastIndexOf(searchString, position)`. A NaN `position` means "search the whole string". v1: `gea_cpp_string_last_index_of`. */
27745
27806
  inline double lastIndexOf(const std::string &s, const std::string &needle, double position) {
27746
- const std::size_t length = utf16Length(s);
27807
+ const Utf16Metadata metadata = utf16Metadata(s);
27808
+ const std::size_t length = metadata.units;
27747
27809
  const std::size_t needleLength = utf16Length(needle);
27748
27810
  const std::size_t requested = std::isnan(position) ? length : clampedPosition(position, length);
27749
27811
  const std::size_t start = needleLength > length ? 0 : std::min(requested, length - needleLength);
27750
27812
  if (needleLength == 0) return static_cast<double>(requested);
27751
27813
  if (needleLength > length) return -1.0;
27814
+ // The byte search `indexOf` states: an ASCII needle cannot match inside a
27815
+ // multi-byte sequence, so the last byte match at or before `start` is the
27816
+ // last code-unit match.
27817
+ if (asciiOnly(needle)) {
27818
+ const std::size_t from = metadata.basicLatin ? start : byteOffsetFromUtf16(s, start);
27819
+ const std::size_t at = s.rfind(needle, from);
27820
+ if (at == std::string::npos) return -1.0;
27821
+ return static_cast<double>(metadata.basicLatin ? at : utf16OffsetFromByte(s, at));
27822
+ }
27752
27823
  for (std::size_t index = start + 1; index > 0; --index) {
27753
27824
  const std::size_t candidate = index - 1;
27754
27825
  if (substringUtf16(s, candidate, candidate + needleLength) == needle) return static_cast<double>(candidate);
@@ -27767,6 +27838,10 @@ inline bool includes(const std::string &s, const std::string &needle) { return i
27767
27838
 
27768
27839
  /** ECMA-262 22.1.3.23 `startsWith(searchString, position)`. v1: `gea_cpp_string_starts_with`. */
27769
27840
  inline bool startsWith(const std::string &s, const std::string &needle, double position) {
27841
+ // At position 0 a prefix of bytes is a prefix of code units: UTF-8 is
27842
+ // prefix-free, so the needle's bytes lead `s` exactly when its code units do
27843
+ // -- unless the needle ends half way through a surrogate pair.
27844
+ if (position == 0.0 && !holdsSurrogateEncoding(needle)) return s.size() >= needle.size() && s.compare(0, needle.size(), needle) == 0;
27770
27845
  const std::size_t length = utf16Length(s);
27771
27846
  const std::size_t start = clampedPosition(position, length);
27772
27847
  const std::size_t needleLength = utf16Length(needle);
@@ -27777,6 +27852,10 @@ inline bool startsWith(const std::string &s, const std::string &needle) { return
27777
27852
 
27778
27853
  /** ECMA-262 22.1.3.7 `endsWith(searchString, endPosition)`. An omitted `endPosition` arrives as +infinity and clamps to len. v1: `gea_cpp_string_ends_with`. */
27779
27854
  inline bool endsWith(const std::string &s, const std::string &needle, double endPosition) {
27855
+ // The whole-string suffix is a byte suffix, for the reason `startsWith`
27856
+ // states about prefixes.
27857
+ if (endPosition == std::numeric_limits<double>::infinity() && !holdsSurrogateEncoding(needle))
27858
+ return s.size() >= needle.size() && s.compare(s.size() - needle.size(), needle.size(), needle) == 0;
27780
27859
  const std::size_t length = utf16Length(s);
27781
27860
  const std::size_t end = clampedPosition(endPosition, length);
27782
27861
  const std::size_t needleLength = utf16Length(needle);
@@ -29118,6 +29197,447 @@ struct MatchSlice {
29118
29197
  };
29119
29198
 
29120
29199
  // v1: `gea::runtime::regex::Pattern`.
29200
+ /**
29201
+ * A backtracking matcher for the plain subset of patterns most programs
29202
+ * write -- `/^[a-z0-9._-]+(?::\d{3,4})?$/`, `/\/\.\.?(?:[/?#]|$)/` -- run on
29203
+ * the UTF-8 bytes directly.
29204
+ *
29205
+ * `std::regex` over a transcoded `std::wstring` costs a conversion and an
29206
+ * allocation per call before matching starts: three such `test`s per request
29207
+ * were 5% of @hono/node-server's CPU. This answers `test` without either.
29208
+ *
29209
+ * Bytes are exactly UTF-16 code units when the input is ASCII. When it is
29210
+ * not, the answer is still exact if no atom of the pattern can match anything
29211
+ * but an ASCII character (`ascii` below): every byte of a multi-byte sequence
29212
+ * then fails every atom, as each of that character's code units would, and
29213
+ * `^`, `$` and `\b` classify those bytes exactly as they classify non-ASCII
29214
+ * code units -- not a line terminator, not a word character.
29215
+ *
29216
+ * The subset: literals, `.`, classes with ranges, `\d \w \s` and their
29217
+ * negations, `\b \B ^ $`, groups, `(?:)`, alternation, and every quantifier
29218
+ * greedy or lazy. Anything else -- a lookaround, a backreference, a named
29219
+ * group, a non-ASCII or `\u` literal, any flag but `d` -- leaves the pattern
29220
+ * to `std::regex`.
29221
+ */
29222
+ namespace simple {
29223
+
29224
+ struct Alternation;
29225
+
29226
+ struct Atom {
29227
+ enum class Kind : unsigned char { Byte, Set, Any, Begin, End, WordBoundary, NotWordBoundary, Group } kind = Kind::Byte;
29228
+ unsigned char byte = 0;
29229
+ std::bitset<128> set;
29230
+ bool negated = false;
29231
+ std::unique_ptr<Alternation> group;
29232
+ };
29233
+
29234
+ struct Term {
29235
+ Atom atom;
29236
+ std::size_t min = 1;
29237
+ std::size_t max = 1;
29238
+ bool greedy = true;
29239
+ };
29240
+
29241
+ using Sequence = std::vector<Term>;
29242
+
29243
+ struct Alternation {
29244
+ std::vector<Sequence> alternatives;
29245
+ };
29246
+
29247
+ struct Program {
29248
+ Alternation top;
29249
+ /** Every alternative starts with `^`: only position 0 can match. */
29250
+ bool anchored = false;
29251
+ /** No atom matches a non-ASCII character, so non-ASCII input is exact too. */
29252
+ bool ascii = true;
29253
+ /**
29254
+ * The bytes a match can start with, when every alternative opens with a
29255
+ * consuming byte or class: an unanchored search skips every other start
29256
+ * instead of entering the matcher there. `@hono/node-server` tests each
29257
+ * request URL against `/\/\.\.?(?:[/?#]|$)/`, which only `/` can open.
29258
+ */
29259
+ bool firstKnown = false;
29260
+ std::bitset<128> first;
29261
+ };
29262
+
29263
+ inline bool isWordByte(unsigned char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; }
29264
+
29265
+ inline void addClassEscape(std::bitset<128> &set, char escape) {
29266
+ for (unsigned c = 0; c < 128; ++c) {
29267
+ const bool digit = c >= '0' && c <= '9';
29268
+ const bool word = isWordByte(static_cast<unsigned char>(c));
29269
+ const bool space = c == ' ' || (c >= '\t' && c <= '\r');
29270
+ const bool in = escape == 'd' ? digit : escape == 'D' ? !digit : escape == 'w' ? word : escape == 'W' ? !word : escape == 's' ? space : !space;
29271
+ if (in) set.set(c);
29272
+ }
29273
+ }
29274
+
29275
+ struct Parser {
29276
+ const std::string &text;
29277
+ std::size_t at = 0;
29278
+ bool ascii = true;
29279
+ bool failed = false;
29280
+
29281
+ bool done() const { return at >= text.size(); }
29282
+ char peek() const { return text[at]; }
29283
+
29284
+ /** The code of a one-character escape (`\n`, `\.`), or -1 for anything this matcher does not take. */
29285
+ int simpleEscape(char c, bool inClass) {
29286
+ switch (c) {
29287
+ case 't': return '\t';
29288
+ case 'n': return '\n';
29289
+ case 'r': return '\r';
29290
+ case 'v': return '\v';
29291
+ case 'f': return '\f';
29292
+ case '0':
29293
+ if (at < text.size() && text[at] >= '0' && text[at] <= '9') return -1;
29294
+ return 0;
29295
+ case 'x': {
29296
+ if (at + 2 > text.size()) return -1;
29297
+ int value = 0;
29298
+ for (int k = 0; k < 2; ++k) {
29299
+ const char h = text[at + k];
29300
+ const int digit = h >= '0' && h <= '9' ? h - '0' : h >= 'a' && h <= 'f' ? h - 'a' + 10 : h >= 'A' && h <= 'F' ? h - 'A' + 10 : -1;
29301
+ if (digit < 0) return -1;
29302
+ value = value * 16 + digit;
29303
+ }
29304
+ if (value >= 0x80) return -1;
29305
+ at += 2;
29306
+ return value;
29307
+ }
29308
+ default:
29309
+ break;
29310
+ }
29311
+ if (std::string_view("^$\\.*+?()[]{}|/").find(c) != std::string_view::npos) return static_cast<unsigned char>(c);
29312
+ if (inClass && c == '-') return '-';
29313
+ return -1;
29314
+ }
29315
+
29316
+ bool parseClass(Atom &atom) {
29317
+ atom.kind = Atom::Kind::Set;
29318
+ if (!done() && peek() == '^') {
29319
+ atom.negated = true;
29320
+ ascii = false;
29321
+ ++at;
29322
+ }
29323
+ // `]` closes the class wherever it appears, first included: `[]` is the
29324
+ // empty class and `[^]` matches anything.
29325
+ while (!done() && peek() != ']') {
29326
+ int low;
29327
+ char c = text[at++];
29328
+ if (static_cast<unsigned char>(c) >= 0x80) return false;
29329
+ if (c == '\\') {
29330
+ if (done()) return false;
29331
+ const char e = text[at++];
29332
+ if (std::string_view("dDwWsS").find(e) != std::string_view::npos) {
29333
+ if (e == 'D' || e == 'W' || e == 'S') ascii = false;
29334
+ if (e == 's') ascii = false;
29335
+ addClassEscape(atom.set, e);
29336
+ continue;
29337
+ }
29338
+ low = simpleEscape(e, true);
29339
+ if (low < 0) return false;
29340
+ } else {
29341
+ low = static_cast<unsigned char>(c);
29342
+ }
29343
+ if (at + 1 < text.size() && text[at] == '-' && text[at + 1] != ']') {
29344
+ ++at;
29345
+ int high;
29346
+ char h = text[at++];
29347
+ if (static_cast<unsigned char>(h) >= 0x80) return false;
29348
+ if (h == '\\') {
29349
+ if (done()) return false;
29350
+ high = simpleEscape(text[at++], true);
29351
+ if (high < 0) return false;
29352
+ } else {
29353
+ high = static_cast<unsigned char>(h);
29354
+ }
29355
+ if (high < low) return false;
29356
+ for (int k = low; k <= high; ++k) atom.set.set(static_cast<std::size_t>(k));
29357
+ } else {
29358
+ atom.set.set(static_cast<std::size_t>(low));
29359
+ }
29360
+ }
29361
+ if (done()) return false;
29362
+ ++at;
29363
+ return true;
29364
+ }
29365
+
29366
+ bool parseQuantifier(Term &term) {
29367
+ if (done()) return true;
29368
+ const char c = peek();
29369
+ if (c == '*' || c == '+' || c == '?') {
29370
+ ++at;
29371
+ term.min = c == '+' ? 1 : 0;
29372
+ term.max = c == '?' ? 1 : SIZE_MAX;
29373
+ } else if (c == '{') {
29374
+ std::size_t cursor = at + 1;
29375
+ const auto number = [&](std::size_t &out) {
29376
+ const std::size_t begin = cursor;
29377
+ out = 0;
29378
+ while (cursor < text.size() && text[cursor] >= '0' && text[cursor] <= '9') {
29379
+ out = out * 10 + static_cast<std::size_t>(text[cursor] - '0');
29380
+ if (out > 100000) return false;
29381
+ ++cursor;
29382
+ }
29383
+ return cursor > begin;
29384
+ };
29385
+ std::size_t low = 0, high = 0;
29386
+ if (!number(low)) return false;
29387
+ if (cursor < text.size() && text[cursor] == ',') {
29388
+ ++cursor;
29389
+ if (cursor < text.size() && text[cursor] == '}') high = SIZE_MAX;
29390
+ else if (!number(high)) return false;
29391
+ } else {
29392
+ high = low;
29393
+ }
29394
+ if (cursor >= text.size() || text[cursor] != '}' || high < low) return false;
29395
+ at = cursor + 1;
29396
+ term.min = low;
29397
+ term.max = high;
29398
+ } else {
29399
+ return true;
29400
+ }
29401
+ if (term.atom.kind == Atom::Kind::Begin || term.atom.kind == Atom::Kind::End || term.atom.kind == Atom::Kind::WordBoundary ||
29402
+ term.atom.kind == Atom::Kind::NotWordBoundary)
29403
+ return false;
29404
+ if (!done() && peek() == '?') {
29405
+ term.greedy = false;
29406
+ ++at;
29407
+ }
29408
+ return true;
29409
+ }
29410
+
29411
+ bool parseAlternation(Alternation &out, int depth) {
29412
+ if (depth > 32) return false;
29413
+ out.alternatives.emplace_back();
29414
+ while (!done()) {
29415
+ const char c = text[at];
29416
+ if (c == ')') break;
29417
+ if (c == '|') {
29418
+ ++at;
29419
+ out.alternatives.emplace_back();
29420
+ continue;
29421
+ }
29422
+ Term term;
29423
+ ++at;
29424
+ if (static_cast<unsigned char>(c) >= 0x80) return false;
29425
+ switch (c) {
29426
+ case '^': term.atom.kind = Atom::Kind::Begin; break;
29427
+ case '$': term.atom.kind = Atom::Kind::End; break;
29428
+ case '.':
29429
+ term.atom.kind = Atom::Kind::Any;
29430
+ ascii = false;
29431
+ break;
29432
+ case '[':
29433
+ if (!parseClass(term.atom)) return false;
29434
+ break;
29435
+ case '(': {
29436
+ if (!done() && peek() == '?') {
29437
+ if (at + 1 >= text.size() || text[at + 1] != ':') return false;
29438
+ at += 2;
29439
+ }
29440
+ term.atom.kind = Atom::Kind::Group;
29441
+ term.atom.group = std::make_unique<Alternation>();
29442
+ if (!parseAlternation(*term.atom.group, depth + 1)) return false;
29443
+ if (done() || peek() != ')') return false;
29444
+ ++at;
29445
+ break;
29446
+ }
29447
+ case '\\': {
29448
+ if (done()) return false;
29449
+ const char e = text[at++];
29450
+ if (e == 'b' || e == 'B') {
29451
+ term.atom.kind = e == 'b' ? Atom::Kind::WordBoundary : Atom::Kind::NotWordBoundary;
29452
+ } else if (std::string_view("dDwWsS").find(e) != std::string_view::npos) {
29453
+ term.atom.kind = Atom::Kind::Set;
29454
+ if (e == 'D' || e == 'W' || e == 'S' || e == 's') ascii = false;
29455
+ addClassEscape(term.atom.set, e);
29456
+ } else {
29457
+ const int code = simpleEscape(e, false);
29458
+ if (code < 0) return false;
29459
+ term.atom.kind = Atom::Kind::Byte;
29460
+ term.atom.byte = static_cast<unsigned char>(code);
29461
+ }
29462
+ break;
29463
+ }
29464
+ case '*':
29465
+ case '+':
29466
+ case '?':
29467
+ case '{':
29468
+ case '}':
29469
+ case ']':
29470
+ return false;
29471
+ default:
29472
+ term.atom.kind = Atom::Kind::Byte;
29473
+ term.atom.byte = static_cast<unsigned char>(c);
29474
+ break;
29475
+ }
29476
+ if (!parseQuantifier(term)) return false;
29477
+ out.alternatives.back().push_back(std::move(term));
29478
+ }
29479
+ return true;
29480
+ }
29481
+ };
29482
+
29483
+ /** The program for `source`, or `nullptr` when it leaves the subset. */
29484
+ inline std::unique_ptr<Program> compile(const std::string &source) {
29485
+ Parser parser{source};
29486
+ auto program = std::make_unique<Program>();
29487
+ if (!parser.parseAlternation(program->top, 0) || !parser.done()) return nullptr;
29488
+ program->ascii = parser.ascii;
29489
+ program->anchored = !program->top.alternatives.empty();
29490
+ for (const Sequence &sequence : program->top.alternatives)
29491
+ if (sequence.empty() || sequence.front().atom.kind != Atom::Kind::Begin) program->anchored = false;
29492
+ program->firstKnown = !program->top.alternatives.empty();
29493
+ for (const Sequence &sequence : program->top.alternatives) {
29494
+ const Term *opening = sequence.empty() ? nullptr : &sequence.front();
29495
+ if (opening == nullptr || opening->min == 0) {
29496
+ program->firstKnown = false;
29497
+ } else if (opening->atom.kind == Atom::Kind::Byte && opening->atom.byte < 128) {
29498
+ program->first.set(opening->atom.byte);
29499
+ } else if (opening->atom.kind == Atom::Kind::Set && !opening->atom.negated) {
29500
+ program->first |= opening->atom.set;
29501
+ } else {
29502
+ program->firstKnown = false;
29503
+ }
29504
+ }
29505
+ return program;
29506
+ }
29507
+
29508
+ /** What remains to match after the current sequence position: the rest of an enclosing sequence, or another repetition. */
29509
+ struct Continuation {
29510
+ const Sequence *sequence = nullptr;
29511
+ std::size_t index = 0;
29512
+ const Term *repeat = nullptr;
29513
+ std::size_t count = 0;
29514
+ std::size_t iterationStart = 0;
29515
+ const Continuation *next = nullptr;
29516
+ };
29517
+
29518
+ struct Matcher {
29519
+ const unsigned char *data;
29520
+ std::size_t size;
29521
+ std::size_t steps = 0;
29522
+ std::size_t depth = 0;
29523
+ bool exhausted = false;
29524
+
29525
+ bool singleMatches(const Atom &atom, std::size_t position) const {
29526
+ if (position >= size) return false;
29527
+ const unsigned char c = data[position];
29528
+ switch (atom.kind) {
29529
+ case Atom::Kind::Byte: return c == atom.byte;
29530
+ case Atom::Kind::Any: return c != '\n' && c != '\r';
29531
+ case Atom::Kind::Set: return (c < 128 && atom.set.test(c)) != atom.negated;
29532
+ default: return false;
29533
+ }
29534
+ }
29535
+
29536
+ bool assertionHolds(const Atom &atom, std::size_t position) const {
29537
+ switch (atom.kind) {
29538
+ case Atom::Kind::Begin: return position == 0;
29539
+ case Atom::Kind::End: return position == size;
29540
+ default: {
29541
+ const bool before = position > 0 && isWordByte(data[position - 1]);
29542
+ const bool after = position < size && isWordByte(data[position]);
29543
+ return (before != after) == (atom.kind == Atom::Kind::WordBoundary);
29544
+ }
29545
+ }
29546
+ }
29547
+
29548
+ bool resume(std::size_t position, const Continuation *k) {
29549
+ if (k == nullptr) return true;
29550
+ if (k->repeat) return repeatGroup(*k->repeat, k->count, position, k->iterationStart, k->next);
29551
+ return sequence(*k->sequence, k->index, position, k->next);
29552
+ }
29553
+
29554
+ /** After `count` iterations of a group term (the last starting at `iterationStart`), match more or stop. */
29555
+ bool repeatGroup(const Term &term, std::size_t count, std::size_t position, std::size_t iterationStart, const Continuation *k) {
29556
+ // An iteration that consumed nothing ends the loop (ES 22.2.2.3.1 RepeatMatcher step 2.b).
29557
+ if (count > 0 && position == iterationStart && count >= term.min) return resume(position, k);
29558
+ const auto more = [&]() {
29559
+ if (count >= term.max) return false;
29560
+ Continuation after{nullptr, 0, &term, count + 1, position, k};
29561
+ for (const Sequence &alternative : term.atom.group->alternatives)
29562
+ if (sequence(alternative, 0, position, &after)) return true;
29563
+ return false;
29564
+ };
29565
+ if (count < term.min) return more();
29566
+ if (term.greedy) return more() || resume(position, k);
29567
+ return resume(position, k) || more();
29568
+ }
29569
+
29570
+ bool sequence(const Sequence &terms, std::size_t index, std::size_t position, const Continuation *k) {
29571
+ // Bounded in work and in stack: a group repetition recurses once per
29572
+ // iteration, so a long input could otherwise run the native stack out.
29573
+ // Either limit hands the pattern back to `std::regex`.
29574
+ if (exhausted || ++steps > 1000000 || depth > 4096) {
29575
+ exhausted = true;
29576
+ return false;
29577
+ }
29578
+ ++depth;
29579
+ const bool matched = sequenceStep(terms, index, position, k);
29580
+ --depth;
29581
+ return matched;
29582
+ }
29583
+
29584
+ bool sequenceStep(const Sequence &terms, std::size_t index, std::size_t position, const Continuation *k) {
29585
+ if (index == terms.size()) return resume(position, k);
29586
+ const Term &term = terms[index];
29587
+ const Atom &atom = term.atom;
29588
+ if (atom.kind == Atom::Kind::Begin || atom.kind == Atom::Kind::End || atom.kind == Atom::Kind::WordBoundary ||
29589
+ atom.kind == Atom::Kind::NotWordBoundary)
29590
+ return assertionHolds(atom, position) && sequence(terms, index + 1, position, k);
29591
+ if (atom.kind == Atom::Kind::Group) {
29592
+ Continuation rest{&terms, index + 1, nullptr, 0, 0, k};
29593
+ return repeatGroup(term, 0, position, position, &rest);
29594
+ }
29595
+ std::size_t available = 0;
29596
+ while (available < term.max && singleMatches(atom, position + available)) ++available;
29597
+ if (available < term.min) return false;
29598
+ if (term.greedy) {
29599
+ for (std::size_t taken = available + 1; taken-- > term.min;)
29600
+ if (sequence(terms, index + 1, position + taken, k)) return true;
29601
+ } else {
29602
+ for (std::size_t taken = term.min; taken <= available; ++taken)
29603
+ if (sequence(terms, index + 1, position + taken, k)) return true;
29604
+ }
29605
+ return false;
29606
+ }
29607
+ };
29608
+
29609
+ /** `1` match, `0` no match, `-1` the step budget ran out and the caller must ask `std::regex`. */
29610
+ inline int search(const Program &program, const std::string &input) {
29611
+ Matcher matcher{reinterpret_cast<const unsigned char *>(input.data()), input.size()};
29612
+ const std::size_t last = program.anchored ? 0 : input.size();
29613
+ const bool skip = program.firstKnown && !program.anchored;
29614
+ const bool single = skip && program.first.count() == 1;
29615
+ unsigned char only = 0;
29616
+ if (single)
29617
+ while (!program.first.test(only)) ++only;
29618
+ for (std::size_t start = 0; start <= last; ++start) {
29619
+ if (skip) {
29620
+ // Non-ASCII bytes are never in `first`: an opening atom here is ASCII.
29621
+ if (single) {
29622
+ const void *found = start < input.size() ? std::memchr(input.data() + start, only, input.size() - start) : nullptr;
29623
+ if (found == nullptr) return 0;
29624
+ start = static_cast<std::size_t>(static_cast<const char *>(found) - input.data());
29625
+ } else {
29626
+ while (start < input.size() && !(static_cast<unsigned char>(input[start]) < 128 && program.first.test(static_cast<unsigned char>(input[start]))))
29627
+ ++start;
29628
+ if (start >= input.size()) return 0;
29629
+ }
29630
+ }
29631
+ for (const Sequence &alternative : program.top.alternatives) {
29632
+ if (matcher.sequence(alternative, 0, start, nullptr)) return 1;
29633
+ if (matcher.exhausted) return -1;
29634
+ }
29635
+ }
29636
+ return 0;
29637
+ }
29638
+
29639
+ } // namespace simple
29640
+
29121
29641
  struct Pattern {
29122
29642
  // ECMAScript-spec named slots for `RegExp.prototype.{source,flags,...}` so
29123
29643
  // `regexp.dotAll`, `regexp.ignoreCase`, `regexp.hasIndices`, etc. read
@@ -29183,6 +29703,23 @@ struct Pattern {
29183
29703
  // first use: 0 unknown, 1 literal (`literalUtf8` holds it), -1 not.
29184
29704
  mutable signed char literalState = 0;
29185
29705
  mutable std::string literalUtf8;
29706
+ // The native program for a pattern in `simple`'s subset, resolved on first
29707
+ // `test`: 0 unknown, 1 compiled, -1 outside the subset.
29708
+ mutable signed char simpleState = 0;
29709
+ mutable std::shared_ptr<const simple::Program> simpleProgram;
29710
+
29711
+ const simple::Program *simplePattern() const {
29712
+ if (simpleState == 0) {
29713
+ simpleState = -1;
29714
+ if (!ignoreCase && !multiline && !dotAll && !unicode && !sticky && !global) {
29715
+ if (auto compiled = simple::compile(source)) {
29716
+ simpleProgram = std::move(compiled);
29717
+ simpleState = 1;
29718
+ }
29719
+ }
29720
+ }
29721
+ return simpleState == 1 ? simpleProgram.get() : nullptr;
29722
+ }
29186
29723
 
29187
29724
  /**
29188
29725
  * Whether `compiledSource` denotes exactly one literal string, and that
@@ -29649,6 +30186,12 @@ struct Pattern {
29649
30186
  bool test(const std::string &input) const {
29650
30187
  if (global || sticky) return matchAt(input).matched;
29651
30188
  if (literalPattern()) return input.find(literalUtf8) != std::string::npos;
30189
+ if (const simple::Program *program = simplePattern()) {
30190
+ if (program->ascii || gea::runtime::string::utf16Metadata(input).basicLatin) {
30191
+ const int found = simple::search(*program, input);
30192
+ if (found >= 0) return found == 1;
30193
+ }
30194
+ }
29652
30195
  const std::wstring inputUnits = matcherInput(input);
29653
30196
  return std::regex_search(inputUnits, compiledRegex());
29654
30197
  }