Skip to content

Commit 5878ec5

Browse files
committed
Ensure that js regex also works when using js obfuscator/compator
1 parent f7b7af7 commit 5878ec5

File tree

1 file changed

+4
-24
lines changed
  • src/jsMain/kotlin/com/github/h0tk3y/betterParse/lexer

1 file changed

+4
-24
lines changed

src/jsMain/kotlin/com/github/h0tk3y/betterParse/lexer/RegexToken.kt

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,29 @@
11
package com.github.h0tk3y.betterParse.lexer
22

3-
import kotlin.js.RegExp
4-
53
public actual class RegexToken : Token {
64
private val pattern: String
75
private val regex: Regex
86

9-
/**
10-
* To ensure that the [regex] will only match its pattern from the index where it is called on
11-
* with Regex.find(input, startIndex), set the JS RegExp flag 'y', which makes the RegExp
12-
* 'sticky'. See: https://javascript.info/regexp-sticky
13-
*/
14-
private fun preprocessRegex(regex: Regex) {
15-
val possibleNames = listOf("nativePattern_1", "nativePattern_0", "_nativePattern")
16-
for (name in possibleNames) {
17-
val r = regex.asDynamic()[name]
18-
if (jsTypeOf(r) !== "undefined" && r !== null) {
19-
val src = r.source as String
20-
val flags = r.flags as String + if (r.sticky as Boolean) "" else "y"
21-
regex.asDynamic()[name] = RegExp(src, flags)
22-
break
23-
}
24-
}
25-
}
26-
277
public actual constructor(
288
name: String?,
299
patternString: String,
3010
ignored: Boolean
3111
) : super(name, ignored) {
3212
pattern = patternString
3313
regex = pattern.toRegex()
34-
preprocessRegex(regex)
3514
}
3615

3716
public actual constructor(name: String?, regex: Regex, ignored: Boolean) : super(name, ignored) {
3817
pattern = regex.pattern
3918
this.regex = regex
40-
preprocessRegex(regex)
4119
}
4220

4321
override actual fun match(input: CharSequence, fromIndex: Int): Int =
4422
regex.find(input, fromIndex)?.range?.let {
45-
val length = it.last - it.first + 1
46-
length
23+
if (it.first == fromIndex) {
24+
val length = it.last - it.first + 1
25+
length
26+
} else 0
4727
} ?: 0
4828

4929
override fun toString(): String = "${name ?: ""} [$pattern]" + if (ignored) " [ignorable]" else ""

0 commit comments

Comments
 (0)