Skip to content

Effort free video editing!

Port tinyre to Nim and fold case for more scripts

WyattBlueb2d9cc937e90
diff --git a/src/analyze/subtitle.nim b/src/analyze/subtitle.nim
index a4e9bedb..35c86abb 100644
--- a/src/analyze/subtitle.nim
+++ b/src/analyze/subtitle.nim
@@ -1,9 +1,8 @@
from ../log import AutoEditorError, error
from std/math import floor, ceil
-import ../[av, ffmpeg]
+import ../[av, ffmpeg, tinyre]
import ../util/rational
-import ../vendor/tinyre/tinyre
proc subtitle*(container: InputContainer, tb: AVRational, pattern: Re,
stream: int16): (int32, seq[bool]) {.raises: [AutoEditorError].} =
diff --git a/src/cmds/levels.nim b/src/cmds/levels.nim
index 81655e3b..dc0876e9 100644
--- a/src/cmds/levels.nim
+++ b/src/cmds/levels.nim
@@ -2,13 +2,11 @@ import std/[options, strformat, strutils]
import ../util/rational
import ../lib/dnorm16
-import ../[av, cache, cli, editparse, ffmpeg, log]
+import ../[av, cache, cli, editparse, ffmpeg, log, tinyre]
import ../analyze/[audio, blackdetect, motion, subtitle]
import ../lib/audioutil
import ./help
-import ../vendor/tinyre/tinyre
-
proc parseUnitFloat(name, value: string): float32 =
let f = (
try: parseFloat(value)
diff --git a/src/edit.nim b/src/edit.nim
index 8bd9be65..8f5d6ad5 100644
--- a/src/edit.nim
+++ b/src/edit.nim
@@ -1,11 +1,9 @@
import std/[math, options, os, sequtils, strformat, strutils]
-import ./[av, editexpr, editlexer, editparse, ffmpeg, log]
+import ./[av, editexpr, editlexer, editparse, ffmpeg, log, tinyre]
import ./analyze/[audio, blackdetect, motion, subtitle]
import ./lib/[audioutil, dnorm16, wordre]
import ./util/[bar, fun, rational, suggest]
-import ./vendor/tinyre/tinyre
-
type
NormSymbol = enum
nsUnknown, nsEbu, nsPeak
diff --git a/src/lib/wordre.nim b/src/lib/wordre.nim
index db003f62..7340b101 100644
--- a/src/lib/wordre.nim
+++ b/src/lib/wordre.nim
@@ -1,7 +1,7 @@
## The pattern the `word` edit method matches subtitles with. Kept apart from
## the CLI so other programs can match exactly as auto-editor does.
-import ../vendor/tinyre/tinyre
+import ../tinyre
func lastCharStart(s: string): int =
## The byte where the last UTF-8 character of `s` starts.
diff --git a/src/main.nim b/src/main.nim
index aaa6ef5e..6e2bda1f 100644
--- a/src/main.nim
+++ b/src/main.nim
@@ -10,7 +10,7 @@ when not defined(emscripten):
when not defined(windows) and not defined(emscripten):
import std/posix_utils
-import ./[about, action, cli, conductor, edit, ffmpeg, license, log]
+import ./[about, action, cli, conductor, edit, ffmpeg, license, log, tinyre]
from ./av import codecAlias
import render/burnsubs
import ./lib/escape
@@ -19,8 +19,6 @@ when defined(emscripten):
import cmds/[info, desc, cache, levels, subdump, whisper]
import util/[color, fun, term, rational, suggest]
-import vendor/tinyre/tinyre
-
var micCaptureActive = false
var stopMicCapture = false
diff --git a/src/tinyre.nim b/src/tinyre.nim
new file mode 100644
index 00000000..5d467f47
--- /dev/null
+++ b/src/tinyre.nim
@@ -0,0 +1,930 @@
+#====================================================================
+#
+# TinyRE - A Tiny Regex Engine for Nim
+# Copyright (c) Chen Kai-Hung, Ward
+#
+#====================================================================
+#
+# Copyright (c) Chen Kai-Hung, Ward
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+# IN THE SOFTWARE.
+
+##[
+ TinyRE is a tiny regex engine based on Rob Pike's VM, ported to Nim from
+ its C implementation. Compared to other small regex engines, it
+ supports unicode and most of common regex syntax, in less than 10K
+ code size (LOC < 1K), and guarantees that input regex will scale O(n)
+ with the size of the string.
+
+ **NOTICE: This implementation always return entire pattern as first
+ capture. This is different from std/re.**
+
+ Syntax
+ ######
+
+ .. code-block::
+ ^ Match beginning of a buffer
+ $ Match end of a buffer
+ (...) Grouping and substring capturing
+ (?:...) Non-capture grouping
+ \s Match whitespace [ \t\n\r\f\v]
+ \S Match non-whitespace [^ \t\n\r\f\v]
+ \w Match alphanumeric [a-zA-Z0-9_]
+ \W Match non-alphanumeric [^a-zA-Z0-9_]
+ \d Match decimal digit [0-9]
+ \D Match non-decimal digit [^0-9]
+ \n Match new line character
+ \r Match line feed character
+ \f Match form feed character
+ \v Match vertical tab character
+ \t Match horizontal tab character
+ + Match one or more times (greedy)
+ +? Match one or more times (non-greedy)
+ * Match zero or more times (greedy)
+ *? Match zero or more times (non-greedy)
+ ? Match zero or once (greedy)
+ ?? Match zero or once (non-greedy)
+ x|y Match x or y (alternation operator)
+ \meta Match one of the meta character: ^$().[]{}*+?|\
+ \x00 Match hex character code (exactly 2 digits)
+ \u0000 Match hex character code (exactly 4 digits)
+ \U00000000 Match hex character code (exactly 8 digits)
+ \<, \> Match start-of-word and end-of-word
+ \b Matches a word boundary
+ \B Matches a nonword boundary
+ [...] Match any character from set. Ranges like [a-z] or [\x00-\u0000] are supported
+ [^...] Match any character but ones from set
+ {n} Matches exactly n times
+ {n,} Matches the preceding character at least n times (greedy)
+ {n,m} Matches the preceding character at least n and at most m times (greedy)
+ {n,}? Matches the preceding character at least n times (non-greedy)
+ {n,m}? Matches the preceding character at least n and at most m times (non-greedy)
+
+]##
+
+# Copyright 2007-2009 Russ Cox. Copyright 2020-2021 Kyryl Melekhin. The VM's
+# design and much of its compiler come from their BSD-licensed pikevm.
+
+type
+ Prog = object
+ code: seq[int] # instructions; each split's operand is its relative jump
+ nsubs: int # capturing groups
+ splitIds: int # one past the largest split id, for the seen-set
+ slots: int # capture slots: a start and an end for the match and each group
+
+ Re* = object
+ prog: Prog
+ insensitive, utf8, global: bool
+
+ ReFlag* = enum
+ reIgnoreCase # Perform case-insensitive matching
+ reGlobal # Perform global matching
+ reUtf8 # Perform utf8 matching
+
+ ReErrorKind* = enum
+ ## Why a pattern didn't compile.
+ reeNone ## (not an error)
+ reeTrailingBackslash ## the pattern ends in a lone `\`
+ reeBadEscape ## `\x`, `\u` or `\U` without enough hex digits
+ reeUnclosedSet ## a `[` with no `]`
+ reeBadRange ## a class like `\d` as one end of a range in a set
+ reeUnsupportedGroup ## `(?` not followed by `:`
+ reeUnclosedGroup ## a `(` with no `)`
+ reeUnmatchedParen ## a `)` with no `(`
+ reeBadRepeat ## a `{` that isn't `{n}`, `{n,}` or `{n,m}`
+ reeRepeatTooLarge ## a repeat count over 65535
+ reeNothingToRepeat ## `?`, `*` or `+` with nothing before it
+ reeTooNested ## too many nested groups or alternatives
+ reeTooLarge ## the compiled pattern is too large
+ reeNoMemory ## out of memory
+
+ ReError* = object of ValueError
+ ## A pattern that didn't compile: why, and where, as a byte offset into
+ ## the pattern.
+ kind*: ReErrorKind
+ pos*: int
+
+ ReGlobalKind = enum
+ rgNone
+ rgIncludeLastEmpty
+ rgExcludeLastEmpty
+
+const
+ # Instructions that consume a character come first: `op < opWbeg`.
+ opChar = 1
+ opClass = 2
+ opMatch = 3
+ opAny = 4
+ opWbeg = 5
+ opWend = 6
+ opWb = 7
+ opNotb = 8
+ opBol = 9
+ opEol = 10
+ opSave = 11
+ opJmp = 12
+ opSplit = 13 # compiled to an odd id >= opSplit; prefers the next instruction
+ opRsplit = 14 # compiled to minus such an id; prefers its jump
+
+ # Caps the code size so counting it can't overflow.
+ maxCode = 1 shl 20
+ # The C matcher kept its thread lists on the stack, and refused patterns
+ # needing more than this; kept so the same patterns compile.
+ maxMatchStack = 256 * 1024
+ altMax = 4096
+
+# Text and patterns read like C strings: past the end is a NUL.
+template at(s: string, i: int): int =
+ (if i < s.len: int(s[i].uint8) else: 0)
+
+const utf8Length: array[256, int8] = block:
+ var t: array[256, int8]
+ for i in 0 .. 255:
+ t[i] = (if i < 0xC0: 1 elif i < 0xE0: 2 elif i < 0xF0: 3 elif i < 0xF8: 4 else: 1)
+ t
+
+func ucLen(s: string, i: int, utf8: bool): int =
+ ## The length of the character at `i`. A lead byte missing any of its
+ ## continuation bytes counts as one byte.
+ if not utf8: return 1
+ let n = utf8Length[s.at(i)].int
+ for k in 1 ..< n:
+ if (s.at(i + k) and 0xC0) != 0x80: return 1
+ n
+
+func ucCode(s: string, i: int, utf8: bool): int =
+ ## The code point of the character at `i`.
+ result = s.at(i)
+ if ucLen(s, i, utf8) > 1:
+ let d = result
+ if d < 192: discard
+ elif d < 224: result = ((d and 0x1f) shl 6) or (s.at(i+1) and 0x3f)
+ elif d < 240:
+ result = ((d and 0x0f) shl 12) or ((s.at(i+1) and 0x3f) shl 6) or
+ (s.at(i+2) and 0x3f)
+ elif d < 248:
+ result = ((d and 0x07) shl 18) or ((s.at(i+1) and 0x3f) shl 12) or
+ ((s.at(i+2) and 0x3f) shl 6) or (s.at(i+3) and 0x3f)
+ else: result = 0
+
+func isUniPunct(u: int): bool =
+ ## Whether code point `u` is a space or punctuation from the blocks
+ ## subtitles use: Latin-1's (but not its ª, µ, º), General and Supplemental
+ ## Punctuation, CJK punctuation, and the fullwidth ASCII punctuation.
+ if u in 0xA0 .. 0xBF: return u notin [0xAA, 0xB5, 0xBA]
+ if u in [0xD7, 0xF7]: return true
+ if u in 0x2000 .. 0x206F or u in 0x2E00 .. 0x2E7F: return true
+ if u in 0x3000 .. 0x303F: return u notin 0x3005 .. 0x3007
+ u in 0xFF01 .. 0xFF0F or u in 0xFF1A .. 0xFF20 or u in 0xFF3B .. 0xFF40 or
+ u in 0xFF5B .. 0xFF65
+
+func isAsciiWord(c: int): bool =
+ c in ord('a') .. ord('z') or c in ord('A') .. ord('Z') or c in ord('0') .. ord('9') or
+ c == ord('_')
+
+func isAsciiDigit(c: int): bool = c in ord('0') .. ord('9')
+func isAsciiSpace(c: int): bool = c == ord(' ') or c in 9 .. 13
+
+func isWordAt(s: string, i: int): bool =
+ ## What `\b` counts as a word character: ASCII letters, digits and `_`, and
+ ## any other character but Unicode spaces and punctuation. A byte inside a
+ ## UTF-8 character counts as one, so there's never a boundary within it.
+ let c = s.at(i)
+ if c < 128: return isAsciiWord(c)
+ if c < 0xC0: return true
+ not isUniPunct(ucCode(s, i, true))
+
+func isWordChar*(s: string, i: int): bool =
+ ## Whether the character starting at byte `i` of `s` is one `\b` counts as
+ ## part of a word: ASCII letters, digits and `_`, and any other character
+ ## but Unicode spaces and punctuation.
+ i in 0 ..< s.len and isWordAt(s, i)
+
+# Unicode simple case folding (one character to one) for the scripts
+# subtitles mostly use. In each range of alternating case, the capital is on
+# the even (or odd) code point and its small letter is the next one.
+const alternating = [
+ (0x0100, 0x012F, 0), (0x0132, 0x0137, 0), (0x0139, 0x0148, 1),
+ (0x014A, 0x0177, 0), (0x0179, 0x017E, 1), (0x01A0, 0x01A5, 0),
+ (0x01CD, 0x01DC, 1), (0x01DE, 0x01EF, 0), (0x01F8, 0x021F, 0),
+ (0x0222, 0x0233, 0), (0x03D8, 0x03EF, 0), (0x0460, 0x0481, 0),
+ (0x048A, 0x04BF, 0), (0x04C1, 0x04CE, 1), (0x04D0, 0x052F, 0),
+ (0x1E00, 0x1E95, 0), (0x1EA0, 0x1EFF, 0)]
+
+func fold(c: int, utf8: bool): int =
+ ## The case-folded form of character `c`: its small letter, for the
+ ## scripts above. Without `utf8`, `c` is a byte and only ASCII folds,
+ ## since a byte past 127 is part of a UTF-8 character, not Latin-1.
+ if c < 128 or not utf8:
+ return (if c in ord('A') .. ord('Z'): c + 32 else: c)
+ if c <= 0xDE: return (if c >= 0xC0 and c != 0xD7: c + 32 else: c)
+ if c < 0x100: return c
+ for (lo, hi, capitalParity) in alternating:
+ if c >= lo and c <= hi:
+ return (if (c and 1) == capitalParity: c + 1 else: c)
+ case c
+ of 0x0178: 0x00FF # Ÿ
+ of 0x017F: ord('s') # long s
+ of 0x0386: 0x03AC # Ά
+ of 0x0388 .. 0x038A: c + 37
+ of 0x038C: 0x03CC
+ of 0x038E, 0x038F: c + 63
+ of 0x0391 .. 0x03A1, 0x03A3 .. 0x03AB: c + 32 # Greek capitals
+ of 0x03C2: 0x03C3 # final sigma
+ of 0x0400 .. 0x040F: c + 80
+ of 0x0410 .. 0x042F: c + 32 # Cyrillic capitals
+ of 0x04C0: 0x04CF
+ of 0x0531 .. 0x0556: c + 48 # Armenian capitals
+ of 0x1E9E: 0x00DF # capital sharp s
+ of 0xFF21 .. 0xFF3A: c + 32 # fullwidth Latin capitals
+ else: c
+
+func classMatch(code: openArray[int], pc0: int, c: int): bool =
+ ## Whether `c` is in the class whose "positive" flag is at `pc0`. Ignoring
+ ## case, `c` and the class's ranges are already folded.
+ var pc = pc0
+ let positive = code[pc] != 0
+ let cnt = code[pc + 1]
+ pc += 2
+ for _ in 0 ..< cnt:
+ if code[pc] == -1:
+ let hit =
+ case chr(code[pc + 1])
+ of 'd': isAsciiDigit(c)
+ of 'D': not isAsciiDigit(c)
+ of 's': isAsciiSpace(c)
+ of 'S': not isAsciiSpace(c)
+ of 'w': isAsciiWord(c)
+ of 'W': not isAsciiWord(c)
+ else: false
+ if hit: return positive
+ elif c >= code[pc] and c <= code[pc + 1]: return positive
+ pc += 2
+ not positive
+
+func hexDigit(c: int): int =
+ if c in ord('0') .. ord('9'): c - ord('0')
+ elif c in ord('a') .. ord('f'): c - ord('a') + 10
+ elif c in ord('A') .. ord('F'): c - ord('A') + 10
+ else: -1
+
+func hexCode(re: string, i, n: int): int =
+ ## The value of the `n` hex digits after `i`, or -1.
+ for k in 1 .. n:
+ let d = hexDigit(re.at(i + k))
+ if d < 0: return -1
+ result = (result shl 4) or d
+ # C's int overflowed past this, and the negative value read as an error.
+ if result > 0x7FFFFFFF: return -1
+
+func token(re: string, i0: int, forward: var int, utf8: bool): int =
+ ## A character of a set: its code, minus a class letter for `\d` and the
+ ## like, or -1 at the end or on a bad escape.
+ var i = i0
+ if re.at(i) == 0: return -1
+ if re.at(i) == ord('\\'):
+ inc i
+ if re.at(i) == 0: return -1
+ forward = 2
+ case chr(re.at(i))
+ of 'd', 'D', 'w', 'W', 's', 'S': return -re.at(i)
+ of 'n': return ord('\n')
+ of 'r': return ord('\r')
+ of 't': return ord('\t')
+ of 'f': return ord('\f')
+ of 'v': return ord('\v')
+ of 'x', 'u', 'U':
+ forward = (if re.at(i) == ord('x'): 2 elif re.at(i) == ord('u'): 4 else: 8)
+ let ch = hexCode(re, i, forward)
+ if ch < 0: return -1
+ forward += 2
+ return ch
+ else: discard # an escaped character stands for itself
+ forward = i - i0 + ucLen(re, i, utf8)
+ ucCode(re, i, utf8)
+
+type CompileError = object
+ kind: ReErrorKind
+ pos: int
+
+func compileCode(re: string, prog: var Prog, utf8: bool, err: var CompileError): bool =
+ ## Compile `re` into `prog.code`, false with `err` set on failure.
+ template code: untyped = prog.code
+ template pc: int = code.len
+ template emit(v: int) = code.add v
+ template fail(k: ReErrorKind, where: int) =
+ err = CompileError(kind: k, pos: where)
+ return false
+ template insertCode(where, num: int) =
+ for _ in 0 ..< num: code.insert(0, where)
+ template rel(a, b: int): int = b - a - 2
+ # The C sizing pass, which made the size errors, counted from 3.
+ template tooLarge: bool = pc + 3 > maxCode
+
+ var i = 0
+ var start = pc
+ var term = pc
+ var altLabel = 0
+ var altStack: seq[int]
+ var capStack: seq[int] # five entries a group
+ var openStack: seq[int] # where each open group starts, for errors
+ # The C sizing pass never lowered its count of alternatives at `)`, so its
+ # limit applied to the whole pattern.
+ var allAlts = 0
+
+ while re.at(i) != 0:
+ case chr(re.at(i))
+ of '\\':
+ inc i
+ if re.at(i) == 0: fail(reeTrailingBackslash, i - 1)
+ let e = chr(re.at(i))
+ case e
+ of '<', '>', 'B', 'b':
+ emit(if e == '<': opWbeg elif e == '>': opWend elif e == 'B': opNotb else: opWb)
+ term = pc
+ of 'd', 'D', 's', 'S', 'w', 'W':
+ term = pc
+ emit opClass; emit 1; emit 1; emit -1; emit ord(e)
+ of 'n', 'r', 't', 'f', 'v':
+ term = pc
+ emit opChar
+ emit(if e == 'n': ord('\n') elif e == 'r': ord('\r') elif e == 't': ord('\t')
+ elif e == 'f': ord('\f') else: ord('\v'))
+ of 'x', 'u', 'U':
+ let n = (if e == 'x': 2 elif e == 'u': 4 else: 8)
+ term = pc
+ let ch = hexCode(re, i, n)
+ if ch < 0: fail(reeBadEscape, i - 1)
+ i += n
+ emit opChar; emit ch
+ else:
+ term = pc
+ emit opChar; emit ucCode(re, i, utf8)
+ of '.':
+ term = pc
+ emit opAny
+ of '[':
+ let setStart = i
+ term = pc
+ inc i
+ emit opClass
+ let neg = re.at(i) == ord('^')
+ emit(if neg: 0 else: 1)
+ if neg: inc i
+ emit 0 # the number of pairs, filled in below
+ var cnt = 0
+ while re.at(i) != ord(']'):
+ var forward = 0
+ var tok = token(re, i, forward, utf8)
+ if tok == -1:
+ if re.at(i) == 0 or (re.at(i) == ord('\\') and re.at(i+1) == 0):
+ fail(reeUnclosedSet, setStart)
+ fail(reeBadEscape, i)
+ i += forward
+ if tok < 0: # \d\D\s\S\w\W
+ emit -1; emit -tok
+ inc cnt
+ continue
+ emit tok
+ if re.at(i) == ord('-') and re.at(i+1) != ord(']'):
+ inc i
+ tok = token(re, i, forward, utf8)
+ if tok < 0: # a class can't end a range
+ if re.at(i) == 0 or (re.at(i) == ord('\\') and re.at(i+1) == 0):
+ fail(reeUnclosedSet, setStart)
+ fail(if tok == -1: reeBadEscape else: reeBadRange, i)
+ i += forward
+ emit tok
+ inc cnt
+ code[term + 2] = cnt
+ of '(':
+ term = pc
+ var capture = true
+ let groupStart = i
+ if re.at(i+1) == ord('?'):
+ i += 2
+ if re.at(i) == ord(':'): capture = false
+ else: fail(reeUnsupportedGroup, groupStart)
+ if capture:
+ inc prog.nsubs
+ emit opSave; emit prog.nsubs
+ if capStack.len + 5 > altMax * 5: fail(reeTooNested, groupStart)
+ openStack.add groupStart
+ capStack.add [(if capture: prog.nsubs else: 0), term, altLabel, start, altStack.len]
+ altLabel = 0
+ start = pc
+ of ')':
+ if capStack.len < 5: fail(reeUnmatchedParen, i)
+ let groupAlts = capStack.pop
+ if altLabel != 0:
+ code[altLabel] = rel(altLabel, pc) + 1
+ let alts = altStack.len
+ var altc = alts
+ while altc > groupAlts:
+ let where = altStack[groupAlts + alts - altc] + (altc - groupAlts) * 2
+ code[where] = rel(where, pc) + 1
+ dec altc
+ altStack.setLen(groupAlts)
+ start = capStack.pop
+ altLabel = capStack.pop
+ term = capStack.pop
+ discard openStack.pop
+ let group = capStack.pop
+ if group != 0:
+ # The end's slot follows every start's, so it waits on the group count.
+ emit opSave; emit -group
+ of '{':
+ var maxcnt = 0
+ var mincnt = 0
+ let size = pc - term
+ var split = opSplit
+ var rsplit = opRsplit
+ let brace = i
+ inc i
+ if not isAsciiDigit(re.at(i)): fail(reeBadRepeat, brace)
+ while isAsciiDigit(re.at(i)):
+ mincnt = mincnt * 10 + re.at(i) - ord('0')
+ inc i
+ if mincnt > 65535: fail(reeRepeatTooLarge, brace)
+ if re.at(i) == ord('}'):
+ maxcnt = mincnt
+ elif re.at(i) == ord(','):
+ inc i
+ if re.at(i) == ord('}'):
+ maxcnt = -1
+ elif isAsciiDigit(re.at(i)):
+ while isAsciiDigit(re.at(i)):
+ maxcnt = maxcnt * 10 + re.at(i) - ord('0')
+ inc i
+ if maxcnt > 65535: fail(reeRepeatTooLarge, brace)
+ if re.at(i) != ord('}'): fail(reeBadRepeat, brace)
+ else:
+ fail(reeBadRepeat, brace)
+ else:
+ fail(reeBadRepeat, brace)
+ if re.at(i+1) == ord('?'): # non-greedy
+ swap(split, rsplit)
+ inc i
+ for _ in 0 ..< mincnt - 1:
+ if tooLarge: fail(reeTooLarge, i)
+ for k in 0 ..< size: emit code[term + k]
+ if maxcnt < 0:
+ emit rsplit
+ emit rel(pc - 1, pc - 1 - size)
+ elif maxcnt > 0:
+ let diff = (if mincnt == 0: 1 else: 0)
+ var k = maxcnt - mincnt - diff
+ while k > 0:
+ if tooLarge: fail(reeTooLarge, i)
+ emit split
+ emit rel(pc, pc + (size + 2) * k)
+ for m in 0 ..< size: emit code[term + m]
+ dec k
+ if mincnt == 0:
+ insertCode(term, 2)
+ code[term] = (if maxcnt == 0: opJmp else: split)
+ code[term + 1] = rel(term, pc)
+ term = pc
+ of '?':
+ if pc == term: fail(reeNothingToRepeat, i)
+ insertCode(term, 2)
+ code[term] = (if re.at(i+1) == ord('?'): opRsplit else: opSplit)
+ if re.at(i+1) == ord('?'): inc i
+ code[term + 1] = rel(term, pc)
+ term = pc
+ of '*':
+ if pc == term: fail(reeNothingToRepeat, i)
+ insertCode(term, 2)
+ emit opJmp
+ emit rel(pc - 1, term)
+ code[term] = (if re.at(i+1) == ord('?'): opRsplit else: opSplit)
+ if re.at(i+1) == ord('?'): inc i
+ code[term + 1] = rel(term, pc)
+ term = pc
+ of '+':
+ if pc == term: fail(reeNothingToRepeat, i)
+ emit(if re.at(i+1) == ord('?'): opSplit else: opRsplit)
+ if re.at(i+1) == ord('?'): inc i
+ emit rel(pc - 1, term)
+ term = pc
+ of '|':
+ if altLabel != 0:
+ if allAlts >= altMax: fail(reeTooNested, i)
+ inc allAlts
+ altStack.add altLabel
+ insertCode(start, 2)
+ emit opJmp
+ altLabel = pc
+ emit 0
+ code[start] = opSplit
+ code[start + 1] = rel(start, pc)
+ term = pc
+ of '^', '$':
+ emit(if re.at(i) == ord('^'): opBol else: opEol)
+ term = pc
+ else:
+ term = pc
+ emit opChar; emit ucCode(re, i, utf8)
+ if tooLarge: fail(reeTooLarge, i)
+ i += ucLen(re, i, utf8)
+
+ if altLabel != 0:
+ code[altLabel] = rel(altLabel, pc) + 1
+ let alts = altStack.len
+ var altc = alts
+ while altc > 0:
+ let where = altStack[alts - altc] + altc * 2
+ code[where] = rel(where, pc) + 1
+ dec altc
+ if capStack.len > 0: fail(reeUnclosedGroup, openStack[^1])
+ true
+
+func compile(pattern: string, utf8: bool, err: var CompileError): Prog =
+ ## Compile `pattern`; `err.kind` is reeNone on success.
+ # A C string ends at its first NUL, and so did patterns.
+ let nul = pattern.find('\0')
+ let re = (if nul >= 0: pattern[0 ..< nul] else: pattern)
+ if not compileCode(re, result, utf8, err):
+ return
+ # Number the splits for the matcher's seen-set, counting instructions as
+ # the C matcher sized its thread lists.
+ var icnt = 0
+ var scnt = opSplit
+ var i = 0
+ template code: untyped = result.code
+ while i < code.len:
+ case code[i]
+ of opClass:
+ i += code[i + 2] * 2 + 2
+ inc icnt
+ of opSplit:
+ code[i] = scnt
+ inc i
+ scnt += 2
+ inc icnt
+ of opRsplit:
+ code[i] = -scnt
+ scnt += 2
+ inc i
+ inc icnt
+ of opJmp, opSave, opChar:
+ if code[i] == opSave and code[i + 1] < 0:
+ code[i + 1] = -code[i + 1] + result.nsubs + 1
+ inc i
+ inc icnt
+ of opAny:
+ inc icnt
+ else: discard
+ inc i
+ code.add [opSave, result.nsubs + 1, opMatch]
+ let splits = (scnt - opSplit) div 2
+ let len = icnt + 2
+ let ptrSize = sizeof(pointer)
+ let rsubSize = (if ptrSize == 8: 16 else: 8)
+ let presub = rsubSize + ptrSize * (result.nsubs + 1) * 2
+ let subsz = presub * (len - splits + 3)
+ let stack = subsz + splits * 2 * ptrSize + scnt * 4 + 2 * len * 2 * ptrSize
+ if stack > maxMatchStack:
+ err = CompileError(kind: reeTooLarge, pos: 0)
+ return
+ result.splitIds = scnt
+ result.slots = (result.nsubs + 1) * 2
+
+type
+ Thread = object
+ pc: int
+ sub: int # index of its captures in the pool
+
+ Scratch = object
+ ## The matcher's working memory, kept between matches of one search.
+ pool: seq[int] # captures, `slots` ints a set
+ refs: seq[int] # threads sharing each set
+ freeSubs: seq[int]
+ seen: seq[int] # the step a split was last taken in
+ step: int
+ clist, nlist: seq[Thread] # in use up to clen and nlen
+ clen, nlen: int
+ stack: seq[(int, int)] # in use up to top
+
+func pikevm(re: Re, s: string, start: int, caps: var seq[int], cont: int,
+ sc: var Scratch): bool =
+ ## Leftmost-first match of `re` in `s[start..]`. `caps` gets each slot's
+ ## byte offset in `s`, or -1: the starts of the match and its groups, then
+ ## their ends. `cont` is where the character before `start` begins, when
+ ## matching resumes after an earlier match, or -1.
+ template code: untyped = re.prog.code
+ let nslots = re.prog.slots
+ let half = nslots div 2
+ sc.pool.setLen(0)
+ sc.refs.setLen(0)
+ sc.freeSubs.setLen(0)
+ if sc.seen.len < re.prog.splitIds: sc.seen.setLen(re.prog.splitIds)
+ sc.clen = 0
+ var matched = -1
+ var top = 0
+
+ template newSub(): int =
+ var n: int
+ if sc.freeSubs.len > 0:
+ n = sc.freeSubs.pop
+ else:
+ n = sc.refs.len
+ sc.refs.add 0
+ sc.pool.setLen(sc.pool.len + nslots)
+ sc.refs[n] = 1
+ n
+
+ template decref(sub: int) =
+ let d = sub
+ dec sc.refs[d]
+ if sc.refs[d] == 0: sc.freeSubs.add d
+
+ # Follow the non-consuming instructions from `pc`, adding the threads that
+ # wait on a character to `list` in priority order. `pos` is where they
+ # stand; `prev` is where the character before them starts.
+ template push(list: var seq[Thread], count: var int, t: Thread) =
+ if count == list.len: list.add t else: list[count] = t
+ inc count
+ template pushAlt(x: (int, int)) =
+ if top == sc.stack.len: sc.stack.add x else: sc.stack[top] = x
+ inc top
+
+ template addThread(list: var seq[Thread], count: var int, pc0, sub0, pos, prev: int,
+ first: bool) =
+ top = 0
+ pushAlt((pc0, sub0))
+ while top > 0:
+ dec top
+ var (pc, sub) = sc.stack[top]
+ while true:
+ let op = code[pc]
+ if op >= 0 and op < opWbeg:
+ push(list, count, Thread(pc: pc, sub: sub))
+ break
+ if op > opJmp or op < 0:
+ let id = abs(op)
+ if sc.seen[id] == sc.step:
+ decref(sub)
+ break
+ sc.seen[id] = sc.step
+ inc sc.refs[sub]
+ let target = pc + 2 + code[pc + 1]
+ if op > 0:
+ pushAlt((target, sub))
+ pc += 2
+ else:
+ pushAlt((pc + 2, sub))
+ pc = target
+ continue
+ if op == opSave:
+ if sc.refs[sub] > 1:
+ dec sc.refs[sub]
+ let copy = newSub()
+ for k in 0 ..< nslots: sc.pool[copy * nslots + k] = sc.pool[sub * nslots + k]
+ sub = copy
+ sc.pool[sub * nslots + code[pc + 1]] = pos
+ pc += 2
+ continue
+ if op == opJmp:
+ pc += 2 + code[pc + 1]
+ continue
+ template wordBefore: bool =
+ if first: cont >= 0 and isWordAt(s, cont) else: isWordAt(s, prev)
+ let pass =
+ case op
+ of opWb: wordBefore != isWordAt(s, pos)
+ of opNotb: wordBefore == isWordAt(s, pos)
+ # At a restart, \< ignores the character before it, as C's did.
+ of opWbeg:
+ if first: isWordAt(s, pos) else: not isWordAt(s, prev) and isWordAt(s, pos)
+ of opWend: not first and isWordAt(s, prev) and not isWordAt(s, pos)
+ of opBol: first and pos == start and cont < 0
+ of opEol: pos >= s.len
+ else: false
+ if not pass:
+ decref(sub)
+ break
+ inc pc
+
+ var sp = start
+ inc sc.step
+ block:
+ let sub = newSub()
+ for k in 0 ..< nslots: sc.pool[sub * nslots + k] = -1
+ sc.pool[sub * nslots] = start
+ addThread(sc.clist, sc.clen, 0, sub, start, -1, true)
+ while true:
+ let atEnd = sp >= s.len
+ var c = (if atEnd: 0 else: ucCode(s, sp, re.utf8))
+ if re.insensitive: c = fold(c, re.utf8)
+ let next = (if atEnd: sp else: sp + ucLen(s, sp, re.utf8))
+ inc sc.step
+ sc.nlen = 0
+ var i = 0
+ while i < sc.clen:
+ let t = sc.clist[i]
+ inc i
+ let op = code[t.pc]
+ var npc = -1
+ case op
+ of opChar:
+ if not atEnd and c == code[t.pc + 1]:
+ npc = t.pc + 2
+ of opClass:
+ if not atEnd and classMatch(code, t.pc + 1, c):
+ npc = t.pc + code[t.pc + 2] * 2 + 3
+ of opAny:
+ if not atEnd: npc = t.pc + 1
+ of opMatch:
+ if matched >= 0: decref(matched)
+ matched = t.sub
+ # The rest of the list is lower priority than this match.
+ for k in i ..< sc.clen: decref(sc.clist[k].sub)
+ break
+ else: discard
+ if npc < 0:
+ decref(t.sub)
+ else:
+ addThread(sc.nlist, sc.nlen, npc, t.sub, next, sp, false)
+ if atEnd: break
+ if matched < 0:
+ let sub = newSub()
+ for k in 0 ..< nslots: sc.pool[sub * nslots + k] = -1
+ sc.pool[sub * nslots] = next
+ addThread(sc.nlist, sc.nlen, 0, sub, next, sp, false)
+ elif sc.nlen == 0:
+ break
+ swap(sc.clist, sc.nlist)
+ swap(sc.clen, sc.nlen)
+ sp = next
+ if matched < 0: return false
+ caps.setLen(nslots)
+ for k in 0 ..< half:
+ caps[2 * k] = sc.pool[matched * nslots + k]
+ caps[2 * k + 1] = sc.pool[matched * nslots + half + k]
+ true
+
+iterator matchRaw(s: string, start: int, re: Re, global: ReGlobalKind, sub: bool
+ ): Slice[int] {.closure.} =
+ var
+ p = start
+ lastEnd = -1
+ cont = -1
+ caps: seq[int]
+ scratch: Scratch
+
+ while true:
+ if not pikevm(re, s, p, caps, cont, scratch): break
+
+ var i = 0
+ while i < re.prog.slots:
+ let slice =
+ if caps[i] < 0 or caps[i + 1] < 0: -1 .. -1
+ else: caps[i] .. caps[i + 1] - 1
+ if i == 0 and lastEnd == caps[1] and p == lastEnd:
+ # An empty match at the same place as the last one's end, as `\<`
+ # matches both sides of a restart: don't yield it twice.
+ discard
+ else:
+ yield slice
+ if not sub:
+ break
+ i += 2
+
+ if p == caps[1]:
+ # An empty match: step over a character instead of stopping.
+ cont = p
+ p += ucLen(s, p, re.utf8)
+ else:
+ p = caps[1]
+ # The character before `p`, from its first byte, so `\b` sees all of it.
+ var before = p - 1
+ while before > start and (s.at(before) and 0xC0) == 0x80:
+ dec before
+ cont = before
+
+ lastEnd = caps[1]
+ case global
+ of rgNone:
+ break
+ of rgIncludeLastEmpty:
+ if p > s.len:
+ break
+ of rgExcludeLastEmpty:
+ if p >= s.len:
+ break
+
+const reErrorMessages: array[ReErrorKind, string] = [
+ "no error", "trailing backslash", "bad escape", "unclosed set",
+ "bad range in set", "unsupported group", "unclosed group",
+ "unmatched parenthesis", "bad repeat", "repeat count too large",
+ "nothing to repeat", "too many nested groups", "pattern too large",
+ "out of memory"]
+
+func message*(kind: ReErrorKind): string =
+ ## A short English description of `kind`.
+ reErrorMessages[kind]
+
+proc re*(s: string, flags: set[ReFlag] = {}): Re =
+ ## Constructor of regular expressions. Raises ReError (a ValueError) saying
+ ## why and where `s` didn't compile.
+ var err: CompileError
+ let prog = compile(s, reUtf8 in flags, err)
+ if err.kind != reeNone:
+ var e = newException(ReError,
+ "cannot compile pattern: " & err.kind.message & " at byte " & $err.pos)
+ e.kind = err.kind
+ e.pos = err.pos
+ raise e
+ result = Re(prog: prog, insensitive: reIgnoreCase in flags,
+ utf8: reUtf8 in flags, global: reGlobal in flags)
+ if result.insensitive:
+ # Fold the pattern's characters once here; matching folds the text's.
+ template code: untyped = result.prog.code
+ var i = 0
+ while i < code.len:
+ case code[i]
+ of opChar:
+ code[i + 1] = fold(code[i + 1], result.utf8)
+ i += 2
+ of opClass:
+ for k in 0 ..< code[i + 2]:
+ let at = i + 3 + 2 * k
+ if code[at] != -1:
+ code[at] = fold(code[at], result.utf8)
+ code[at + 1] = fold(code[at + 1], result.utf8)
+ i += 3 + 2 * code[i + 2]
+ of opSave, opJmp: i += 2
+ else:
+ i += (if code[i] > opJmp or code[i] < 0: 2 else: 1)
+
+proc groupsCount*(re: Re): int =
+ ## Returns the number of capturing groups, counting the whole match.
+ re.prog.slots div 2
+
+iterator match*(s: string, pattern: Re, start = 0): string =
+ ## Yields all matching substrings of `s[start..]` that match `pattern`.
+ let rg = if pattern.global: rgIncludeLastEmpty else: rgNone
+ for slice in matchRaw(s, start, pattern, rg, true):
+ yield if slice.b >= slice.a and slice.a >= 0: s[slice] else: ""
+
+iterator matchBounds*(s: string, pattern: Re, start = 0): Slice[int] =
+ ## The byte bounds in `s` of every whole match in `s[start..]`, whether or
+ ## not the pattern has reGlobal. An empty match comes out as `a ..< a`,
+ ## that is with `b == a - 1`, once at each position it occurs, including
+ ## one at the end of `s`.
+ for slice in matchRaw(s, start, pattern, rgIncludeLastEmpty, false):
+ yield slice
+
+proc match*(s: string, pattern: Re, start = 0): seq[string] =
+ ## Returns all matching substrings of `s[start..]` that match `pattern`.
+ for m in match(s, pattern, start):
+ result.add m
+
+proc replace*(s: string, sub: Re, by: string = "", limit = 0): string =
+ ## Replaces `sub` in `s` by the string `by`. Captures cannot be accessed in `by`.
+ var
+ pos = 0
+ count = 0
+
+ for slice in matchRaw(s, 0, sub, rgExcludeLastEmpty, false):
+ if slice.b >= slice.a and slice.a >= 0: # not empty match
+ result.add s[pos..slice.a - 1]
+ result.add by
+ pos = slice.b + 1
+ count.inc
+ if limit > 0 and count >= limit:
+ break
+
+ result.add s[pos..^1]
+
+proc escapeRe*(s: string): string {.raises: [].} =
+ ## Escapes `s` so that it can be matched verbatim.
+ for c in s:
+ case c
+ of '\n': result.add "\\n"
+ of '\r': result.add "\\r"
+ of '\t': result.add "\\t"
+ of '\f': result.add "\\f"
+ of '\v': result.add "\\v"
+ of '^', '$', '(', ')', '.', '[', ']', '{', '}', '*', '+', '?', '|', '\\':
+ result.add '\\'
+ result.add c
+ else:
+ result.add c
diff --git a/src/vendor/tinyre/LICENSE b/src/vendor/tinyre/LICENSE
deleted file mode 100644
index 11001278..00000000
--- a/src/vendor/tinyre/LICENSE
+++ /dev/null
@@ -1,7 +0,0 @@
-Copyright (c) Chen Kai-Hung, Ward
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/src/vendor/tinyre/re.c b/src/vendor/tinyre/re.c
deleted file mode 100644
index d913e67c..00000000
--- a/src/vendor/tinyre/re.c
+++ /dev/null
@@ -1,894 +0,0 @@
-/*
-Copyright (c) Chen Kai-Hung, Ward. All rights reserved.
-
-Modifications:
- * Add meta characters: \n \r \t \b \v \f \s \S \d \D \w \W \B
- \xHH \uHHHH \UHHHHHHHH.
- * Add case insensitive mode and binary mode.
- * Deal with 0 and large number in {n} {n,} {n,m} {n,}? {n, m}?.
- * Add wrap codes to compile and run the regex.
-*/
-
-/*
-Copyright 2007-2009 Russ Cox. All Rights Reserved.
-Copyright 2020-2021 Kyryl Melekhin. All Rights Reserved.
-Use of this source code is governed by a BSD-style
-*/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-
-unsigned char utf8_length[256] = {
- /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
- /* 0 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* 1 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* 2 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* 3 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* 4 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* 5 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* 6 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* 7 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* 8 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* 9 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* A */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* B */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- /* C */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- /* D */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- /* E */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
- /* F */ 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1
-};
-
-static int uc_len(const char * s, int utf8) {
- /* return the length of a utf-8 character. A lead byte missing any of its
- continuation bytes counts as one byte, so a sequence cut off by the end
- of the string can't step past its terminator. */
- if (!utf8) return 1;
- int n = utf8_length[(unsigned char)s[0]];
- for (int i = 1; i < n; i++)
- if (((unsigned char)s[i] & 0xc0) != 0x80) return 1;
- return n;
-}
-
-static int uc_code(const char * s, int utf8) {
- /* the unicode codepoint of the given utf-8 character */
- int dst = (unsigned char)s[0];
- if (uc_len(s, utf8) > 1) {
- if (dst < 192) {}
- else if (dst < 224) dst = ((dst & 0x1f) << 6) | (s[1] & 0x3f);
- else if (dst < 240) dst = ((dst & 0x0f) << 12) | ((s[1] & 0x3f) << 6) | (s[2] & 0x3f);
- else if (dst < 248) dst = ((dst & 0x07) << 18) | ((s[1] & 0x3f) << 12) | ((s[2] & 0x3f) << 6) | (s[3] & 0x3f);
- else dst = 0;
- }
- return dst;
-}
-
-/* Whether code point u is a space or punctuation from the blocks subtitles
- * use: Latin-1's (but not its ª, µ, º), General and Supplemental
- * Punctuation, CJK punctuation, and the fullwidth ASCII punctuation. */
-static int isunipunct(int u)
-{
- if (u >= 0xA0 && u <= 0xBF) return u != 0xAA && u != 0xB5 && u != 0xBA;
- if (u == 0xD7 || u == 0xF7) return 1;
- if (u >= 0x2000 && u <= 0x206F) return 1;
- if (u >= 0x2E00 && u <= 0x2E7F) return 1;
- if (u >= 0x3000 && u <= 0x303F) return u < 0x3005 || u > 0x3007;
- return (u >= 0xFF01 && u <= 0xFF0F) || (u >= 0xFF1A && u <= 0xFF20) ||
- (u >= 0xFF3B && u <= 0xFF40) || (u >= 0xFF5B && u <= 0xFF65);
-}
-
-/* What \b counts as a word character: ASCII letters, digits and `_`, and any
- * other character but Unicode spaces and punctuation. A byte inside a UTF-8
- * character counts as one, so there's never a boundary within it. */
-int re_isword(const char *s)
-{
- int c = (unsigned char) s[0];
- if (c < 128) return isalnum(c) || c == '_';
- if (c < 0xC0) return 1;
- return !isunipunct(uc_code(s, 1));
-}
-#define isword re_isword
-
-/* tolower for ASCII only: past 255, C's tolower is undefined. */
-static int fold(int c)
-{
- return c < 128 ? tolower(c) : c;
-}
-
-static int isasciiword(int c)
-{
- return isalnum(c) || c == '_';
-}
-
-typedef struct rcode rcode;
-struct rcode
-{
- int unilen; /* number of integers in insts */
- int len; /* number of atoms/instructions */
- int sub; /* interim val = save count; final val = nsubs size */
- int presub; /* interim val = save count; final val = 1 rsub size */
- int splits; /* number of split insts */
- int sparsesz; /* sdense size */
- int insts[]; /* re code */
-};
-
-enum
-{
- /* Instructions which consume input bytes */
- /* SPLIT must odd number */
- CHAR = 1,
- CLASS,
- MATCH,
- ANY,
- /* Assert position */
- WBEG,
- WEND,
- WB,
- NOTB,
- BOL,
- EOL,
- /* Other (special) instructions */
- SAVE,
- /* Instructions which take relative offset as arg */
- JMP,
- SPLIT,
- RSPLIT,
-};
-
-typedef struct rsub rsub;
-struct rsub
-{
- int ref;
- rsub *freesub;
- const char *sub[];
-};
-
-typedef struct rthread rthread;
-struct rthread
-{
- int *pc;
- rsub *sub;
-};
-
-#define INSERT_CODE(at, num, pc) \
-if (code) \
- memmove(code + at + num, code + at, (pc - at)*sizeof(int)); \
-pc += num;
-#define REL(at, to) (to - at - 2)
-#define EMIT(at, byte) (code ? (code[at] = byte) : at)
-#define PC (prog->unilen)
-/* Caps the code size so counting it can't overflow an int. */
-#define MAX_CODE (1 << 20)
-/* re_pikevm keeps its thread lists on the stack; the wasm build's is 1 MiB. */
-#define MAX_MATCH_STACK (256 * 1024)
-#define ALT_MAX 4096
-
-static int re_classmatch(const int *pc, int c, int insensitive)
-{
- /* pc points to "classnot" byte after opcode */
- int is_positive = *pc++;
- int cnt = *pc++;
- while (cnt--) {
- if (*pc == -1) {
- switch(pc[1]) {
- case 'd': if (isdigit(c)) return is_positive; break;
- case 'D': if (!isdigit(c)) return is_positive; break;
- case 's': if (isspace(c)) return is_positive; break;
- case 'S': if (!isspace(c)) return is_positive; break;
- case 'w': if (isasciiword(c)) return is_positive; break;
- case 'W': if (!isasciiword(c)) return is_positive; break;
- }
- } else if (!insensitive) {
- if (c >= *pc && c <= pc[1]) return is_positive;
- } else {
- c = fold(c);
- if (c >= fold(*pc) && c <= fold(pc[1])) return is_positive;
- }
- pc += 2;
- }
- return !is_positive;
-}
-
-static int _toi(int x) {
- return isdigit(x) ? x - '0' : x - 'a' + 10;
-}
-
-static int _code(const char *re, int n) {
- int i, result = 0;
- for (i = 1; i <= n; i++) {
- if (!isxdigit(re[i])) return -1;
- result <<= 4;
- result |= _toi(tolower(re[i]));
- }
- return result;
-}
-
-/* Why a pattern failed to compile; mirrored by ReErrorKind in tinyre.nim. */
-enum {
- RE_OK, RE_TRAILING_BACKSLASH, RE_BAD_ESCAPE, RE_UNCLOSED_SET, RE_BAD_RANGE,
- RE_UNSUPPORTED_GROUP, RE_UNCLOSED_GROUP, RE_UNMATCHED_PAREN, RE_BAD_REPEAT,
- RE_REPEAT_TOO_LARGE, RE_NOTHING_TO_REPEAT, RE_TOO_NESTED, RE_TOO_LARGE,
- RE_NO_MEMORY
-};
-
-typedef struct { int kind, pos; } re_err;
-
-/* Record the first failure: `at` is where in the pattern it happened. */
-#define FAIL(k, at) do { \
- if (err && !err->kind) { err->kind = (k); err->pos = (int)((at) - re_loc); } \
- return -1; } while (0)
-
-static int token(const char *re0, int* forward, int utf8) {
- const char *re = re0;
- int ch;
- switch (*re) {
- case 0:
- return -1;
-
- case '\\':
- re++;
- if (!*re) return -1; /* Trailing backslash */
- *forward = 2;
- switch (*re) {
- case 'd': case 'D': case 'w': case 'W': case 's': case 'S':
- return -(*re);
-
- case 'n': return '\n';
- case 'r': return '\r';
- case 't': return '\t';
- case 'f': return '\f';
- case 'v': return '\v';
- // case '\\': return '\\'; // deal '\' by fall-through
-
- case 'x': *forward = 2; goto _hex;
- case 'u': *forward = 4; goto _hex;
- case 'U': *forward = 8; _hex:
- ch = _code(re, *forward);
- if (ch < 0) return -1;
- *forward += 2;
- return ch;
- }
- // fall-through -> skip the '\'
-
- default:
- *forward = re - re0 + uc_len(re, utf8);
- return uc_code(re, utf8);
- }
-}
-
-static int _compilecode(const char *re_loc, rcode *prog, int sizecode, int utf8,
- re_err *err)
-{
- const char *re = re_loc;
- int *code = sizecode ? NULL : prog->insts;
- int start = PC, term = PC;
- int alt_label = 0, c;
- int alt_stack[ALT_MAX], altc = 0;
- int cap_stack[ALT_MAX * 5], capc = 0;
- int open_stack[ALT_MAX]; /* where each open group starts, for errors */
- int n, ch;
-
- while (*re) {
- switch (*re) {
- case '\\':
- re++;
- if (!*re) FAIL(RE_TRAILING_BACKSLASH, re - 1);
- switch (*re) {
- case '<': case '>': case 'B': case 'b':
- EMIT(PC++, *re == '<' ? WBEG : (*re == '>' ? WEND : (*re == 'B' ? NOTB : WB)));
- term = PC;
- break;
- case 'd': case 'D': case 's': case 'S': case 'w': case 'W':
- term = PC;
- EMIT(PC++, CLASS);
- EMIT(PC++, 1);
- EMIT(PC++, 1);
- EMIT(PC++, -1);
- EMIT(PC++, *re);
- break;
- case 'n': case 'r': case 't': case 'f': case 'v':
- term = PC;
- switch (*re) {
- case 'n': ch = '\n'; goto _char;
- case 'r': ch = '\r'; goto _char;
- case 't': ch = '\t'; goto _char;
- case 'f': ch = '\f'; goto _char;
- case 'v': ch = '\v'; goto _char;
- }
- break;
- case 'x': n = 2; goto _hex;
- case 'u': n = 4; goto _hex;
- case 'U': n = 8; _hex:
- term = PC;
- ch = _code(re, n);
- if (ch < 0) FAIL(RE_BAD_ESCAPE, re - 1);
- re += n;
- goto _char;
- default: goto _default;
- }
- break;
- default:
- _default:
- term = PC;
- ch = uc_code(re, utf8);
- _char:
- EMIT(PC++, CHAR);
- EMIT(PC++, ch);
- break;
- case '.':
- term = PC;
- EMIT(PC++, ANY);
- break;
- case '[':;
- const char *set_start = re;
- term = PC;
- re++;
- EMIT(PC++, CLASS);
- int neg = (*re == '^');
- EMIT(PC++, !neg);
- if (neg) re++;
- PC++; /* Skip "# of pairs" byte */
-
- int cnt = 0;
- while (*re != ']') {
- int forward;
- int tok = token(re, &forward, utf8);
- if (tok == -1) {
- if (!*re || (*re == '\\' && !re[1])) FAIL(RE_UNCLOSED_SET, set_start);
- FAIL(RE_BAD_ESCAPE, re);
- }
- re += forward;
-
- if (tok < 0) { // \d\D\s\S\w\W etc.
- EMIT(PC++, -1);
- EMIT(PC++, -tok);
- cnt++;
- continue;
- }
-
- EMIT(PC++, tok);
- if (*re == '-' && re[1] != ']') {
- re++; // skip '-'
- tok = token(re, &forward, utf8);
- if (tok < 0) { // not allow \d\D\s\S\w\W here
- if (!*re || (*re == '\\' && !re[1])) FAIL(RE_UNCLOSED_SET, set_start);
- FAIL(tok == -1 ? RE_BAD_ESCAPE : RE_BAD_RANGE, re);
- }
- re += forward;
- }
- EMIT(PC++, tok);
- cnt++;
- }
- EMIT(term + 2, cnt);
- break;
- case '(':;
- term = PC;
- int sub;
- int capture = 1;
- const char *group_start = re;
- if (*(re+1) == '?') {
- re += 2;
- if (*re == ':')
- capture = 0;
- else
- FAIL(RE_UNSUPPORTED_GROUP, group_start);
- }
- if (capture) {
- sub = ++prog->sub;
- EMIT(PC++, SAVE);
- EMIT(PC++, sub);
- }
- if (capc + 5 > ALT_MAX * 5) FAIL(RE_TOO_NESTED, group_start);
- open_stack[capc / 5] = (int)(group_start - re_loc);
- cap_stack[capc++] = capture;
- cap_stack[capc++] = term;
- cap_stack[capc++] = alt_label;
- cap_stack[capc++] = start;
- cap_stack[capc++] = altc;
- alt_label = 0;
- start = PC;
- break;
- case ')':
- if (capc < 5) FAIL(RE_UNMATCHED_PAREN, re);
- --capc;
- if (code && alt_label) {
- EMIT(alt_label, REL(alt_label, PC) + 1);
- int _altc = cap_stack[capc];
- for (int alts = altc; altc > _altc; altc--) {
- int at = alt_stack[_altc+alts-altc]+(altc-_altc)*2;
- EMIT(at, REL(at, PC) + 1);
- }
- }
- start = cap_stack[--capc];
- alt_label = cap_stack[--capc];
- term = cap_stack[--capc];
- if (cap_stack[--capc]) {
- EMIT(PC++, SAVE);
- EMIT(PC++, code[term+1] + prog->presub + 1);
- }
- break;
- case '{':;
- int maxcnt = 0, mincnt = 0, size = PC - term;
- int split = SPLIT, rsplit = RSPLIT;
- const char *brace = re;
- re++;
- // {n}, {n,}, or {n,m}
- if (!isdigit((unsigned char) *re)) FAIL(RE_BAD_REPEAT, brace);
- while (isdigit((unsigned char) *re)) {
- mincnt = mincnt * 10 + *re++ - '0';
- if (mincnt > 65535) FAIL(RE_REPEAT_TOO_LARGE, brace);
- }
- if (*re == '}') { // {n}
- maxcnt = mincnt;
- } else if (*re == ',') { // {n,} or {n,m}
- re++;
- if (*re == '}') { // {n,}
- maxcnt = -1;
- } else if (isdigit((unsigned char) *re)) { // {n,m}
- while (isdigit((unsigned char) *re)) {
- maxcnt = maxcnt * 10 + *re++ - '0';
- if (maxcnt > 65535) FAIL(RE_REPEAT_TOO_LARGE, brace);
- }
- if (*re != '}') FAIL(RE_BAD_REPEAT, brace);
- } else {
- FAIL(RE_BAD_REPEAT, brace);
- }
- } else {
- FAIL(RE_BAD_REPEAT, brace);
- }
- if (re[1] == '?') { // non-greedy
- split = RSPLIT;
- rsplit = SPLIT;
- re++;
- }
- // {0}, {0,}, {0,2}
- // {1}, {1,}, {1,3}
- for (int i = 0; i < mincnt - 1; i++) {
- if (PC > MAX_CODE) FAIL(RE_TOO_LARGE, re);
- if (code)
- memcpy(&code[PC], &code[term], size*sizeof(int));
- PC += size;
- }
- if (maxcnt < 0) {
- EMIT(PC, rsplit);
- EMIT(PC+1, REL(PC, PC - size));
- PC += 2;
- }
- else if (maxcnt > 0) {
- int diff = mincnt == 0 ? 1 : 0;
- for (int i = maxcnt - mincnt - diff; i > 0; i--) {
- if (PC > MAX_CODE) FAIL(RE_TOO_LARGE, re);
- EMIT(PC++, split);
- EMIT(PC++, REL(PC, PC+((size+2)*i)));
- if (code)
- memcpy(&code[PC], &code[term], size*sizeof(int));
- PC += size;
- }
- }
- if (mincnt == 0) {
- INSERT_CODE(term, 2, PC);
- EMIT(term, maxcnt == 0 ? JMP : split);
- EMIT(term + 1, REL(term, PC));
- term = PC;
- }
- break;
- case '?':
- if (PC == term) FAIL(RE_NOTHING_TO_REPEAT, re);
- INSERT_CODE(term, 2, PC);
- EMIT(term, re[1] == '?' ? RSPLIT : SPLIT);
- if (re[1] == '?') re++;
- EMIT(term + 1, REL(term, PC));
- term = PC;
- break;
- case '*':
- if (PC == term) FAIL(RE_NOTHING_TO_REPEAT, re);
- INSERT_CODE(term, 2, PC);
- EMIT(PC, JMP);
- EMIT(PC + 1, REL(PC, term));
- PC += 2;
- EMIT(term, re[1] == '?' ? RSPLIT : SPLIT);
- if (re[1] == '?') re++;
- EMIT(term + 1, REL(term, PC));
- term = PC;
- break;
- case '+':
- if (PC == term) FAIL(RE_NOTHING_TO_REPEAT, re);
- EMIT(PC, re[1] == '?' ? SPLIT : RSPLIT);
- if (re[1] == '?') re++;
- EMIT(PC + 1, REL(PC, term));
- PC += 2;
- term = PC;
- break;
- case '|':
- if (alt_label) {
- if (altc >= ALT_MAX) FAIL(RE_TOO_NESTED, re);
- alt_stack[altc++] = alt_label;
- }
- INSERT_CODE(start, 2, PC);
- EMIT(PC++, JMP);
- alt_label = PC++;
- EMIT(start, SPLIT);
- EMIT(start + 1, REL(start, PC));
- term = PC;
- break;
- case '^': case '$':
- EMIT(PC++, *re == '^' ? BOL : EOL);
- term = PC;
- break;
- }
- if (PC > MAX_CODE) FAIL(RE_TOO_LARGE, re);
- c = uc_len(re, utf8); re += c;
- }
- if (code && alt_label) {
- EMIT(alt_label, REL(alt_label, PC) + 1);
- for (int alts = altc; altc; altc--) {
- int at = alt_stack[alts-altc]+altc*2;
- EMIT(at, REL(at, PC) + 1);
- }
- }
- if (capc) FAIL(RE_UNCLOSED_GROUP, re_loc + open_stack[capc / 5 - 1]);
- return 0;
-}
-
-int re_sizecode(const char *re, int *nsub, int utf8, re_err *err)
-{
- rcode dummyprog;
- dummyprog.unilen = 3;
- dummyprog.sub = 0;
-
- int res = _compilecode(re, &dummyprog, 1, utf8, err);
- if (res < 0) return res;
- *nsub = dummyprog.sub;
- return dummyprog.unilen;
-}
-
-int re_comp(rcode *prog, const char *re, int nsubs, int utf8)
-{
- prog->len = 0;
- prog->unilen = 0;
- prog->sub = 0;
- prog->presub = nsubs;
- prog->splits = 0;
-
- int res = _compilecode(re, prog, 0, utf8, NULL);
- if (res < 0) return res;
- int icnt = 0, scnt = SPLIT;
- for (int i = 0; i < prog->unilen; i++)
- switch (prog->insts[i]) {
- case CLASS:
- i += prog->insts[i+2] * 2 + 2;
- icnt++;
- break;
- case SPLIT:
- prog->insts[i++] = scnt;
- scnt += 2;
- icnt++;
- break;
- case RSPLIT:
- prog->insts[i] = -scnt;
- scnt += 2;
- case JMP:
- case SAVE:
- case CHAR:
- i++;
- case ANY:
- icnt++;
- }
- prog->insts[prog->unilen++] = SAVE;
- prog->insts[prog->unilen++] = prog->sub + 1;
- prog->insts[prog->unilen++] = MATCH;
- prog->splits = (scnt - SPLIT) / 2;
- prog->len = icnt + 2;
- prog->presub = sizeof(rsub)+(sizeof(char*) * (nsubs + 1) * 2);
- long long subsz = (long long)prog->presub * (prog->len - prog->splits + 3);
- long long stack = subsz + (long long)prog->splits * (sizeof(int*) + sizeof(rsub*)) +
- (long long)scnt * sizeof(unsigned int) + 2LL * prog->len * sizeof(rthread);
- if (stack > MAX_MATCH_STACK) return -1;
- prog->sub = (int)subsz;
- prog->sparsesz = scnt;
- return 0;
-}
-
-#define newsub(init, copy) \
-if (freesub) \
- { s1 = freesub; freesub = s1->freesub; copy } \
-else \
- { if (suboff == prog->sub) suboff = 0; \
- s1 = (rsub*)&nsubs[suboff]; suboff += rsubsize; init } \
-
-#define decref(csub) \
-if (--csub->ref == 0) { \
- csub->freesub = freesub; \
- freesub = csub; \
-} \
-
-#define rec_check(nn) \
-if (si) { \
- npc = pcs[--si]; \
- nsub = subs[si]; \
- goto rec##nn; \
-} \
-
-#define deccheck(nn) { decref(nsub) rec_check(nn) continue; } \
-
-#define onlist(nn) \
-if (sdense[spc] < sparsesz) \
- if (sdense[sdense[spc] * 2] == (unsigned int)spc) \
- deccheck(nn) \
-sdense[spc] = sparsesz; \
-sdense[sparsesz++ * 2] = spc; \
-
-#define fastrec(nn, list, listidx) \
-nsub->ref++; \
-spc = *npc; \
-if ((unsigned int)spc < WBEG) { \
- list[listidx].sub = nsub; \
- list[listidx++].pc = npc; \
- npc = pcs[si]; \
- goto rec##nn; \
-} \
-subs[si++] = nsub; \
-goto next##nn; \
-
-#define saveclist() \
-if (npc[1] > nsubp / 2 && nsub->ref > 1) { \
- nsub->ref--; \
- newsub(memcpy(s1->sub, nsub->sub, osubp);, \
- memcpy(s1->sub, nsub->sub, osubp / 2);) \
- nsub = s1; \
- nsub->ref = 1; \
-} \
-
-#define savenlist() \
-if (nsub->ref > 1) { \
- nsub->ref--; \
- newsub(/*nop*/, /*nop*/) \
- memcpy(s1->sub, nsub->sub, osubp); \
- nsub = s1; \
- nsub->ref = 1; \
-} \
-
-#define clistmatch()
-#define nlistmatch() \
-if (spc == MATCH) \
- for (i++; i < clistidx; i++) { \
- npc = clist[i].pc; \
- nsub = clist[i].sub; \
- if (*npc == MATCH) \
- goto matched; \
- decref(nsub) \
- } \
-
-#define addthread(nn, list, listidx) \
-rec##nn: \
-spc = *npc; \
-if ((unsigned int)spc < WBEG) { \
- list[listidx].sub = nsub; \
- list[listidx++].pc = npc; \
- rec_check(nn) \
- list##match() \
- continue; \
-} \
-next##nn: \
-if (spc > JMP) { \
- onlist(nn) \
- npc += 2; \
- pcs[si] = npc + npc[-1]; \
- fastrec(nn, list, listidx) \
-} else if (spc == SAVE) { \
- save##list() \
- nsub->sub[npc[1]] = _sp; \
- npc += 2; \
- goto rec##nn; \
-} else if (spc == NOTB) { \
- if ((sp == s && _sp == s && \
- (cont ? isword(cont) != isword(sp) : isword(sp))) || \
- isword(_sp) != isword(sp)) \
- deccheck(nn) \
- npc++; goto rec##nn; \
-} else if (spc == WB) { \
- if (!((sp == s && _sp == s && \
- (cont ? isword(cont) != isword(sp) : isword(sp))) || \
- isword(_sp) != isword(sp))) \
- deccheck(nn) \
- npc++; goto rec##nn; \
-} else if (spc == WBEG) { \
- if (((sp != s || sp != _sp) && isword(sp)) || !isword(_sp)) \
- deccheck(nn) \
- npc++; goto rec##nn; \
-} else if (spc < 0) { \
- spc = -spc; \
- onlist(nn) \
- npc += 2; \
- pcs[si] = npc; \
- npc += npc[-1]; \
- fastrec(nn, list, listidx) \
-} else if (spc == WEND) { \
- if (!isword(sp) || isword(_sp)) \
- deccheck(nn) \
- npc++; goto rec##nn; \
-} else if (spc == EOL) { \
- if (!last) \
- deccheck(nn) \
- npc++; goto rec##nn; \
-} else if (spc == JMP) { \
- npc += 2 + npc[1]; \
- goto rec##nn; \
-} else { \
- /* BOL. A restart (cont set) begins mid-string, so it isn't the start. */ \
- if (_sp != s || cont) { \
- if (!si && !clistidx) \
- return 0; \
- deccheck(nn) \
- } \
- npc++; goto rec##nn; \
-} \
-
-#define swaplist() \
-tmp = clist; \
-clist = nlist; \
-nlist = tmp; \
-clistidx = nlistidx; \
-
-#define deccont() { decref(nsub) continue; }
-
-int re_pikevm(rcode *prog, const char *s, int len, const char **subp, int nsubp, int insensitive, int utf8, const char* cont)
-{
- int rsubsize = prog->presub, suboff = 0;
- int spc, i, j, c, *npc, osubp = nsubp * sizeof(char*);
- int si = 0, clistidx = 0, nlistidx, mcont = MATCH;
- const char *sp = s, *_sp = s;
- int last = 0;
- int *insts = prog->insts;
- int *pcs[prog->splits];
- rsub *subs[prog->splits];
- unsigned int sdense[prog->sparsesz], sparsesz = 0;
- rsub *nsub, *s1, *matched = NULL, *freesub = NULL;
- rthread _clist[prog->len], _nlist[prog->len];
- rthread *clist = _clist, *nlist = _nlist, *tmp;
- char nsubs[prog->sub];
- if (len == 0) last = 1;
- goto jmp_start;
- for (;; sp = _sp) {
- if (last) {
- i = 0;
- c = 0;
- } else {
- i = uc_len(sp, utf8);
- c = uc_code(sp, utf8);
- }
- _sp = sp+i;
- if (_sp >= s + len) last = 1;
- nlistidx = 0; sparsesz = 0;
- for (i = 0; i < clistidx; i++) {
- npc = clist[i].pc;
- nsub = clist[i].sub;
- spc = *npc;
- if (spc == CHAR) {
- if (!insensitive) {
- if (c != *(npc+1)) deccont()
- } else {
- if (fold(c) != fold(*(npc+1))) deccont()
- }
- npc += 2;
- } else if (spc == CLASS) {
- if (!re_classmatch(npc+1, c, insensitive))
- deccont()
- npc += *(npc+2) * 2 + 3;
- } else if (spc == MATCH) {
- matched:
- nlist[nlistidx++].pc = &mcont;
- if (npc != &mcont) {
- if (matched)
- decref(matched)
- matched = nsub;
- }
- if (sp == _sp || nlistidx == 1) {
- for (i = 0, j = i; i < nsubp; i+=2, j++) {
- subp[i] = matched->sub[j];
- subp[i+1] = matched->sub[nsubp / 2 + j];
- }
- return 1;
- }
- swaplist()
- goto _continue;
- } else
- npc++;
- addthread(2, nlist, nlistidx)
- }
- if (sp == _sp)
- break;
- swaplist()
- jmp_start:
- newsub(memset(s1->sub, 0, osubp);, /*nop*/)
- s1->ref = 1;
- s1->sub[0] = _sp;
- nsub = s1; npc = insts;
- addthread(1, clist, clistidx)
- _continue:;
- }
- return 0;
-}
-
-typedef struct RE RE;
-struct RE {
- const char **captures;
- char* buffer;
- int count;
- int sub_els;
- int insensitive;
- int utf8;
- int size;
-};
-
-/* As re_compile, but on failure says why in *kind (an RE_ value) and where
- * in *pos (a byte offset into pattern). */
-RE* re_compile_err(const char *pattern, int insensitive, int utf8, int *kind,
- int *pos) {
- re_err err = {RE_OK, 0};
- int sub_els;
- int sz = re_sizecode(pattern, &sub_els, utf8, &err) * sizeof(int);
- *kind = err.kind;
- *pos = err.pos;
- if (sz < 0) return NULL;
- int count = (sub_els + 1) * 2;
- int captures_size = count * sizeof(char*);
- int buffer_size = sizeof(rcode) + sz;
-
- RE* re = (RE*) malloc(sizeof(RE) + captures_size + buffer_size);
- if(!re) {
- *kind = RE_NO_MEMORY;
- return NULL;
- }
-
- re->sub_els = sub_els;
- re->captures = (const char**) (((char*)re) + sizeof(RE));
- re->buffer = (char*) re + sizeof(RE) + captures_size;
- re->count = count;
- re->insensitive = insensitive;
- re->utf8 = utf8;
- re->size = sizeof(RE) + captures_size + buffer_size;
-
- if (re_comp((rcode *)re->buffer, pattern, sub_els, utf8)) {
- free(re);
- *kind = RE_TOO_LARGE; /* sizing passed, so only the size can differ */
- return NULL;
- }
- return re;
-}
-
-RE* re_compile(const char *pattern, int insensitive, int utf8) {
- int kind, pos;
- return re_compile_err(pattern, insensitive, utf8, &kind, &pos);
-}
-
-RE* re_dup(RE* re) {
- if (!re || re->size == 0) return NULL;
- RE* newre = malloc(re->size);
- memcpy(newre, re, re->size);
- return newre;
-}
-
-
-int re_max_matches(RE* re) {
- return re->count;
-}
-
-int re_uc_len(RE* re, const char * s) {
- return uc_len(s, re->utf8);
-}
-
-void re_free(RE* re) {
- free(re);
-}
-
-const char** re_match(RE* re, const char* string, int len, const char* cont) {
- if (re == NULL) return NULL;
-
- memset(re->captures, 0, re->count * sizeof(char*));
- int sz = re_pikevm((rcode *)re->buffer, string, len, re->captures, re->count, re->insensitive, re->utf8, cont);
-
- if (!sz) return NULL;
- return re->captures;
-}
diff --git a/src/vendor/tinyre/tinyre.nim b/src/vendor/tinyre/tinyre.nim
deleted file mode 100644
index f80b0392..00000000
--- a/src/vendor/tinyre/tinyre.nim
+++ /dev/null
@@ -1,291 +0,0 @@
-#====================================================================
-#
-# TinyRE - A Tiny Regex Engine for Nim
-# Copyright (c) Chen Kai-Hung, Ward
-#
-#====================================================================
-
-##[
- TinyRE is a Nim wrap for a tiny regex engine based on Rob Pike's VM
- implementation. Compare to other small regex engines, this engine
- supports unicode and most of common regex syntax, in less than 10K
- code size (LOC < 1K), and guarantees that input regex will scale O(n)
- with the size of the string.
-
- **NOTICE: This implementation always return entire pattern as first
- capture. This is different from std/re.**
-
- Syntax
- ######
-
- .. code-block::
- ^ Match beginning of a buffer
- $ Match end of a buffer
- (...) Grouping and substring capturing
- (?:...) Non-capture grouping
- \s Match whitespace [ \t\n\r\f\v]
- \S Match non-whitespace [^ \t\n\r\f\v]
- \w Match alphanumeric [a-zA-Z0-9_]
- \W Match non-alphanumeric [^a-zA-Z0-9_]
- \d Match decimal digit [0-9]
- \D Match non-decimal digit [^0-9]
- \n Match new line character
- \r Match line feed character
- \f Match form feed character
- \v Match vertical tab character
- \t Match horizontal tab character
- + Match one or more times (greedy)
- +? Match one or more times (non-greedy)
- * Match zero or more times (greedy)
- *? Match zero or more times (non-greedy)
- ? Match zero or once (greedy)
- ?? Match zero or once (non-greedy)
- x|y Match x or y (alternation operator)
- \meta Match one of the meta character: ^$().[]{}*+?|\
- \x00 Match hex character code (exactly 2 digits)
- \u0000 Match hex character code (exactly 4 digits)
- \U00000000 Match hex character code (exactly 8 digits)
- \<, \> Match start-of-word and end-of-word
- \b Matches a word boundary
- \B Matches a nonword boundary
- [...] Match any character from set. Ranges like [a-z] or [\x00-\u0000] are supported
- [^...] Match any character but ones from set
- {n} Matches exactly n times
- {n,} Matches the preceding character at least n times (greedy)
- {n,m} Matches the preceding character at least n and at most m times (greedy)
- {n,}? Matches the preceding character at least n times (non-greedy)
- {n,m}? Matches the preceding character at least n and at most m times (non-greedy)
-
-]##
-
-when defined(js):
- {.error: "This library needs to be compiled with a c-like backend".}
-
-{.compile: "re.c".}
-
-type
- ReRaw = ptr object
- Re* = object
- raw: ReRaw
- global: bool
-
- ReFlag* = enum
- reIgnoreCase # Perform case-insensitive matching
- reGlobal # Perform global matching
- reUtf8 # Perform utf8 matching
-
- ReErrorKind* = enum
- ## Why a pattern didn't compile. The order matches the RE_ codes in re.c.
- reeNone ## (not an error)
- reeTrailingBackslash ## the pattern ends in a lone `\`
- reeBadEscape ## `\x`, `\u` or `\U` without enough hex digits
- reeUnclosedSet ## a `[` with no `]`
- reeBadRange ## a class like `\d` as one end of a range in a set
- reeUnsupportedGroup ## `(?` not followed by `:`
- reeUnclosedGroup ## a `(` with no `)`
- reeUnmatchedParen ## a `)` with no `(`
- reeBadRepeat ## a `{` that isn't `{n}`, `{n,}` or `{n,m}`
- reeRepeatTooLarge ## a repeat count over 65535
- reeNothingToRepeat ## `?`, `*` or `+` with nothing before it
- reeTooNested ## too many nested groups or alternatives
- reeTooLarge ## the compiled pattern is too large
- reeNoMemory ## out of memory
-
- ReError* = object of ValueError
- ## A pattern that didn't compile: why, and where, as a byte offset into
- ## the pattern.
- kind*: ReErrorKind
- pos*: int
-
- ReGlobalKind = enum
- rgNone
- rgIncludeLastEmpty
- rgExcludeLastEmpty
-
-proc re_compile(pattern: cstring, i: cint, u: cint): ReRaw {.importc, cdecl.}
-proc re_compile_err(pattern: cstring, i: cint, u: cint, kind, pos: var cint): ReRaw {.importc, cdecl.}
-proc re_free(re: ReRaw) {.importc, cdecl.}
-proc re_dup(re: ReRaw): ReRaw {.importc, cdecl.}
-proc re_match(re: ReRaw, text: cstring, L: cint, cont: cstring): cstringArray {.importc, cdecl.}
-proc re_max_matches(re: ReRaw): cint {.importc, cdecl.}
-proc re_uc_len(re: ReRaw, s: cstring): cint {.importc, cdecl.}
-proc re_isword(s: cstring): cint {.importc, cdecl, noSideEffect.}
-
-func isWordChar*(s: string, i: int): bool =
- ## Whether the character starting at byte `i` of `s` is one `\b` counts as
- ## part of a word: ASCII letters, digits and `_`, and any other character
- ## but Unicode spaces and punctuation.
- if i notin 0 ..< s.len: return false
- let c = s[i].uint8
- # re_isword decodes the whole character; a cut-off one counts as a word.
- let size = (if c < 0xC0: 1 elif c < 0xE0: 2 elif c < 0xF0: 3 else: 4)
- if i + size > s.len: return true
- re_isword(cast[cstring](unsafeAddr s[i])) != 0
-
-proc `=destroy`(re: Re) =
- if not re.raw.isNil:
- re_free(re.raw)
-
-proc `=copy`(dest: var Re, source: Re) =
- if dest.raw == source.raw: return
- `=destroy`(dest)
- wasMoved(dest)
- dest.raw = re_dup(source.raw)
- if dest.raw.isNil: raise newException(OutOfMemDefect, "out of memory")
-
-iterator matchRaw(s: cstring, L0: int, re: ReRaw, global: ReGlobalKind, sub: bool
- ): Slice[int] {.closure.} =
-
- template `===`(a, b: cstring): bool =
- # must cast to ptr to compare cstring
- cast[pointer](a) == cast[pointer](b)
-
- assert not re.isNil
- var
- L = L0
- p = s
- lastMatch1: cstring
- cont: cstring = nil
-
- while true:
- var matches = re_match(re, p, cint L, cont)
- if matches.isNil: break
-
- var i = 0
- while i < re_max_matches(re):
- var slice = cast[int](matches[i]) .. cast[int](matches[i + 1])
- if slice.a == 0 or slice.b == 0: # (?, ?)
- slice = -1 .. -1
- else:
- slice.a = slice.a -% cast[int](s)
- slice.b = slice.b -% cast[int](s) -% 1
-
- if i == 0 and lastMatch1 === matches[1] and p === lastMatch1:
- # match same anchor again, avoid to yield the same slice twice.
- # for example, match(" a", re"\<")
- # first time match "| |a", second time match " ||a"
- # but yield the same slice because the pattern has no length.
- discard
- else:
- yield slice
-
- if not sub:
- break
- i.inc(2)
-
- if p === matches[1]:
- # zero length captures, advance one character instead of break
- cont = p
- let uclen = int re_uc_len(re, p)
- L -= uclen
- p = cast[cstring](cast[int](p) +% uclen)
- else:
- L -= cast[int](matches[1]) -% cast[int](p)
- p = matches[1]
- # The character before `p`, from its first byte, so `\b` sees all of it.
- var before = cast[int](p) -% 1
- while before >% cast[int](s) and (cast[ptr uint8](before)[] and 0xC0) == 0x80:
- before = before -% 1
- cont = cast[cstring](before)
-
- lastMatch1 = matches[1]
- case global
- of rgNone:
- break
- of rgIncludeLastEmpty:
- if cast[int](p) >% cast[int](s) +% L0:
- break
- of rgExcludeLastEmpty:
- if cast[int](p) >=% cast[int](s) +% L0:
- break
-
-const reErrorMessages: array[ReErrorKind, string] = [
- "no error", "trailing backslash", "bad escape", "unclosed set",
- "bad range in set", "unsupported group", "unclosed group",
- "unmatched parenthesis", "bad repeat", "repeat count too large",
- "nothing to repeat", "too many nested groups", "pattern too large",
- "out of memory"]
-
-func message*(kind: ReErrorKind): string =
- ## A short English description of `kind`.
- reErrorMessages[kind]
-
-proc re*(s: string, flags: set[ReFlag] = {}): Re =
- ## Constructor of regular expressions. Raises ReError (a ValueError) saying
- ## why and where `s` didn't compile.
- var kind, pos: cint
- result = Re(
- raw: re_compile_err(s, cint(reIgnoreCase in flags), cint(reUtf8 in flags),
- kind, pos),
- global: reGlobal in flags
- )
- if result.raw.isNil:
- let k = (if kind in 1.cint .. ord(high(ReErrorKind)).cint: ReErrorKind(kind)
- else: reeTooLarge)
- var e = newException(ReError,
- "cannot compile pattern: " & k.message & " at byte " & $pos)
- e.kind = k
- e.pos = pos
- raise e
-
-proc groupsCount*(re: Re): int =
- # Returns the number of capturing groups.
- assert not re.raw.isNil
- return re_max_matches(re.raw) div 2
-
-iterator match*(s: string, pattern: Re, start = 0): string =
- # Yields all matching substrings of `s[start..]` that match `pattern`.
- let start0 = start # avoid to be modified during iteration
- let cs = cast[cstring](cast[int](s.cstring) +% start0)
- let rg = if pattern.global: rgIncludeLastEmpty else: rgNone
- for i in matchRaw(cs, s.len - start0, pattern.raw, rg, true):
- var slice = (i.a +% start0) .. (i.b +% start0)
- yield if slice.b >= slice.a and slice.a >= 0: s[slice] else: ""
-
-iterator matchBounds*(s: string, pattern: Re, start = 0): Slice[int] =
- ## The byte bounds in `s` of every whole match in `s[start..]`, whether or
- ## not the pattern has reGlobal. An empty match comes out as `a ..< a`,
- ## that is with `b == a - 1`, once at each position it occurs, including
- ## one at the end of `s`.
- let start0 = start # avoid to be modified during iteration
- let cs = cast[cstring](cast[int](s.cstring) +% start0)
- for i in matchRaw(cs, s.len - start0, pattern.raw, rgIncludeLastEmpty, false):
- yield (i.a +% start0) .. (i.b +% start0)
-
-proc match*(s: string, pattern: Re, start = 0): seq[string] =
- # Returns all matching substrings of `s[start..]` that match `pattern`.
- for m in match(s, pattern, start):
- result.add m
-
-proc replace*(s: string, sub: Re, by: string = "", limit = 0): string =
- # Replaces `sub` in `s` by the string `by`. Captures cannot be accessed in `by`.
- let cs = s.cstring
- var
- pos = 0
- count = 0
-
- for slice in matchRaw(cs, s.len, sub.raw, rgExcludeLastEmpty, false):
- if slice.b >= slice.a and slice.a >= 0: # not empty match
- result.add s[pos..slice.a - 1]
- result.add by
- pos = slice.b + 1
- count.inc
- if limit > 0 and count >= limit:
- break
-
- result.add s[pos..^1]
-
-proc escapeRe*(s: string): string {.raises: [].} =
- # Escapes `s` so that it can be matched verbatim.
- for c in s:
- case c
- of '\n': result.add "\\n"
- of '\r': result.add "\\r"
- of '\t': result.add "\\t"
- of '\f': result.add "\\f"
- of '\v': result.add "\\v"
- of '^', '$', '(', ')', '.', '[', ']', '{', '}', '*', '+', '?', '|', '\\':
- result.add '\\'
- result.add c
- else:
- result.add c