Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
nitely committed Jan 18, 2025
1 parent b04f3f9 commit 4433fe2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
19 changes: 15 additions & 4 deletions src/regex.nim
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,7 @@ To compile the regex at runtime pass the regex expression as a ``var/let``.
]##

import std/locks
import std/tables
import std/sequtils
import std/unicode
Expand Down Expand Up @@ -508,16 +509,26 @@ proc reCheck(s: string) {.compileTime.} =
except RegexError:
raise newException(RegexError, getCurrentExceptionMsg())

func `~`*(s: static string): Regex2 {.nodestroy.} =
var tildes = initTable[string, Regex2]()
var tildelock: Lock
initLock(tildelock)

func `~`*(s: static string): Regex2 {.raises: [RegexError].} =
## Compile a regex at runtime.
## The compiled regex is cached and reused.
## It gets compiled once in a program lifetime.
## The regex is validated at compile-time,
## and so it may only raise a `RegexError` at compile-time.
static: reCheck(s)
{.cast(noSideEffect), cast(gcsafe).}:
var reg {.global.} = toRegex2 reImpl(s)
return reg
when nimvm:
return toRegex2 reImpl(s)
else:
{.cast(noSideEffect), cast(gcsafe), cast(raises: [RegexError]).}:
withLock tildelock:
if s in tildes:
return tildes[s]
tildes[s] = toRegex2 reImpl(s)
return tildes[s]

func group*(m: RegexMatch2, i: int): Slice[int] {.inline, raises: [].} =
## return slice for a given group.
Expand Down
8 changes: 4 additions & 4 deletions tests/tests2.nim
Original file line number Diff line number Diff line change
Expand Up @@ -3347,14 +3347,14 @@ test "tvarflags":
check(not match("a\Lb\L", re2(r"a.b(?-sm:.)", {regexDotAll, regexMultiline})))
check(not match("a\Lb\L", re2"(?ms)a.b(?-sm:.)"))

test "tsigil":
test "ttilde":
check "ab".match ~"ab"
check not "ab".match ~"zx"
check ~"ab" in "abcd"
check ~"zx" notin "abcd"
check not compiles(~"(+)")

test "tsigil_gcsafe":
func tsigil: bool {.gcsafe.} =
test "ttilde_gcsafe":
func ttilde: bool {.gcsafe.} =
"foo".match ~"foo"
doAssert tsigil()
doAssert ttilde()

0 comments on commit 4433fe2

Please sign in to comment.