From e60db93999dd03ec8cb6da6d2d26726e1fba91a4 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Fri, 4 Dec 2026 02:56:07 +0100 Subject: [PATCH 1/2] Support bounded ordered TypeScript RegExp matching --- .../usvm/machine/expr/OrderedRegExpMatcher.kt | 119 ++++++++ .../usvm/machine/expr/OrderedRegExpProgram.kt | 279 ++++++++++++++++++ .../org/usvm/machine/expr/RegExpCalls.kt | 34 ++- .../machine/expr/OrderedRegExpRuntimeTest.kt | 134 +++++++++ .../usvm/machine/expr/RegExpRuntimeTest.kt | 2 - .../resources/models/OrderedRegExpRuntime.ts | 56 ++++ .../test/resources/models/RegExpRuntime.ts | 2 - 7 files changed, 613 insertions(+), 13 deletions(-) create mode 100644 usvm-ts/src/main/kotlin/org/usvm/machine/expr/OrderedRegExpMatcher.kt create mode 100644 usvm-ts/src/main/kotlin/org/usvm/machine/expr/OrderedRegExpProgram.kt create mode 100644 usvm-ts/src/test/kotlin/org/usvm/machine/expr/OrderedRegExpRuntimeTest.kt create mode 100644 usvm-ts/src/test/resources/models/OrderedRegExpRuntime.ts diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/expr/OrderedRegExpMatcher.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/OrderedRegExpMatcher.kt new file mode 100644 index 0000000000..36681d154b --- /dev/null +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/OrderedRegExpMatcher.kt @@ -0,0 +1,119 @@ +package org.usvm.machine.expr + +import io.ksmt.sort.KBv16Sort +import org.usvm.UBoolExpr +import org.usvm.UExpr +import org.usvm.UHeapRef +import org.usvm.isFalse +import org.usvm.isTrue +import org.usvm.machine.TsSizeSort +import org.usvm.machine.state.TsState +import org.usvm.util.mkStringBackingElementLValue +import org.usvm.util.stringCharacters +import org.usvm.util.stringLength + +internal class OrderedRegExpMatcher( + private val state: TsState, + string: UHeapRef, + private val bound: Int, +) { + private val ctx = state.ctx + private val length = state.stringLength(string) + private val characters = state.stringCharacters(string) + + fun match(program: OrderedRegExpProgram): RegExpMatch = with(ctx) { + val missing = RegExpMatch(falseExpr, mkBv(0), mkBv(0), emptyMap()) + var later = Array(program.instructions.size) { missing } + var leftmost = missing + // A consuming edge reads the next row. Every zero-width edge points to an earlier instruction. + for (offset in bound downTo 0) { + val position = mkBv(offset) + val withinInput = mkBvSignedLessExpr(position, length) + val unit = state.memory.read(mkStringBackingElementLValue(characters, position)) + val row = Array(program.instructions.size) { missing } + for ((address, instruction) in program.instructions.withIndex()) { + row[address] = matchInstruction(instruction, row, later, position, unit, withinInput) + } + + val current = row[program.entry] + val validStart = mkBvSignedLessOrEqualExpr(position, length) + val candidate = current.copy(success = mkAnd(validStart, current.success), start = position) + leftmost = prefer(candidate, leftmost) + later = row + } + + // String.match and RegExp.exec expose every capture index, including unchosen alternatives. + val absent = RegExpCapture(present = falseExpr, start = mkBv(0), end = mkBv(0)) + leftmost.copy(captures = (0 until program.captureCount).associateWith { leftmost.captures[it] ?: absent }) + } + + private fun matchInstruction( + instruction: RegExpInstruction, + row: Array, + later: Array, + position: UExpr, + unit: UExpr, + withinInput: UBoolExpr, + ): RegExpMatch = with(ctx) { + when (instruction) { + RegExpInstruction.Accept -> RegExpMatch(trueExpr, position, position, emptyMap()) + is RegExpInstruction.Consume -> { + val continuation = later[instruction.next] + val matches = characterMatches(instruction.ranges, unit) + continuation.copy(success = mkAnd(withinInput, matches, continuation.success)) + } + is RegExpInstruction.Split -> prefer(row[instruction.preferred], row[instruction.alternative]) + is RegExpInstruction.Boundary -> { + val next = row[instruction.next] + val boundary = if (instruction.start) mkBv(0) else length + next.copy(success = mkAnd(mkEq(position, boundary), next.success)) + } + is RegExpInstruction.Capture -> { + val next = row[instruction.next] + val capture = if (instruction.start) { + next.captures[instruction.id]?.copy(start = position) + ?: RegExpCapture(present = falseExpr, start = position, end = position) + } else { + RegExpCapture(present = trueExpr, start = position, end = position) + } + next.copy(captures = next.captures + (instruction.id to capture)) + } + } + } + + private fun prefer(first: RegExpMatch, second: RegExpMatch): RegExpMatch = with(ctx) { + val selected = first.success + if (selected.isTrue) return first + if (selected.isFalse) return second + + val absent = RegExpCapture(present = falseExpr, start = mkBv(0), end = mkBv(0)) + val captures = (first.captures.keys + second.captures.keys).associateWith { id -> + val preferred = first.captures[id] ?: absent + val alternative = second.captures[id] ?: absent + RegExpCapture( + present = mkIte(selected, preferred.present, alternative.present), + start = mkIte(selected, preferred.start, alternative.start), + end = mkIte(selected, preferred.end, alternative.end), + ) + } + RegExpMatch( + success = mkOr(selected, second.success), + start = mkIte(selected, first.start, second.start), + end = mkIte(selected, first.end, second.end), + captures = captures, + ) + } + + private fun characterMatches(ranges: List, value: UExpr): UBoolExpr = with(ctx) { + val alternatives = ranges.map { range -> + if (range.first == range.last) { + mkEq(value, mkBv(range.first, bv16Sort)) + } else { + val lowerBound = mkBv(range.first, bv16Sort) + val upperBound = mkBv(range.last, bv16Sort) + mkAnd(mkBvUnsignedGreaterOrEqualExpr(value, lowerBound), mkBvUnsignedLessOrEqualExpr(value, upperBound)) + } + } + mkOr(alternatives) + } +} diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/expr/OrderedRegExpProgram.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/OrderedRegExpProgram.kt new file mode 100644 index 0000000000..87e2bd36f9 --- /dev/null +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/OrderedRegExpProgram.kt @@ -0,0 +1,279 @@ +package org.usvm.machine.expr + +/** Ordered branches retain ECMAScript leftmost-first and greedy matching priorities. */ +internal data class OrderedRegExpProgram( + val entry: Int, + val instructions: List, + val captureCount: Int, +) { + fun inputBound(backingBound: Int): Int = + minOf(backingBound, MAX_INPUT_LENGTH, MAX_POSITION_INSTRUCTIONS / instructions.size - 1) +} + +private const val MAX_PATTERN_LENGTH = 256 +private const val MAX_GROUP_NESTING = 16 +private const val MAX_CAPTURE_COUNT = 12 +private const val MAX_INPUT_LENGTH = 128 +private const val MAX_POSITION_INSTRUCTIONS = 16_384 + +internal sealed interface RegExpInstruction { + object Accept : RegExpInstruction + data class Consume(val ranges: List, val next: Int) : RegExpInstruction + data class Split(val preferred: Int, val alternative: Int) : RegExpInstruction + data class Boundary(val start: Boolean, val next: Int) : RegExpInstruction + data class Capture(val id: Int, val start: Boolean, val next: Int) : RegExpInstruction +} + +internal fun compileOrderedRegExp(source: String): OrderedRegExpProgram? { + if (source.length > MAX_PATTERN_LENGTH) return null + + val parser = OrderedRegExpParser(source) + val result = parser.parse() ?: return null + val program = RegExpProgramBuilder() + val accept = program.emit(RegExpInstruction.Accept) + val entry = program.compile(result, accept) + return OrderedRegExpProgram(entry, program.instructions, captureCount = parser.captureCount) +} + +private enum class Repeat { ONCE, PLUS, STAR, OPTIONAL } + +private sealed interface RegExpFragment { + val nullable: Boolean + + data class Sequence(val items: List) : RegExpFragment { + override val nullable: Boolean = items.all { it.nullable } + } + + data class Choice(val alternatives: List) : RegExpFragment { + override val nullable: Boolean = alternatives.any { it.nullable } + } + + data class Atom(val ranges: List, val repeat: Repeat) : RegExpFragment { + override val nullable: Boolean = repeat == Repeat.STAR || repeat == Repeat.OPTIONAL + } + + data class Group(val body: Choice, val capture: Int?, val optional: Boolean) : RegExpFragment { + override val nullable: Boolean = optional || body.nullable + } + + data class Boundary(val start: Boolean) : RegExpFragment { + override val nullable: Boolean = true + } +} + +private class RegExpProgramBuilder { + private val code = mutableListOf() + val instructions: List get() = code.toList() + + fun emit(instruction: RegExpInstruction): Int { + val address = code.size + code += instruction + return address + } + + fun compile(fragment: RegExpFragment, next: Int): Int = when (fragment) { + is RegExpFragment.Sequence -> fragment.items.foldRight(next, ::compile) + is RegExpFragment.Choice -> { + val branches = fragment.alternatives.map { compile(it, next) } + branches.dropLast(1).foldRight(branches.last()) { preferred, fallback -> + emit(RegExpInstruction.Split(preferred, fallback)) + } + } + is RegExpFragment.Atom -> compileAtom(fragment, next) + is RegExpFragment.Group -> compileGroup(fragment, next) + is RegExpFragment.Boundary -> emit(RegExpInstruction.Boundary(start = fragment.start, next = next)) + } + + private fun compileAtom(fragment: RegExpFragment.Atom, next: Int): Int { + if (fragment.repeat == Repeat.ONCE) return emit(RegExpInstruction.Consume(fragment.ranges, next)) + + val atom = emit(RegExpInstruction.Consume(fragment.ranges, next)) + val first = emit(RegExpInstruction.Split(preferred = atom, alternative = next)) + if (fragment.repeat == Repeat.OPTIONAL) return first + + // The back edge is reached only after consuming a code unit. All zero-width edges go backward. + code[atom] = RegExpInstruction.Consume(fragment.ranges, next = first) + return if (fragment.repeat == Repeat.PLUS) atom else first + } + + private fun compileGroup(group: RegExpFragment.Group, next: Int): Int { + val capture = group.capture + if (capture == null) { + val body = compile(group.body, next) + return if (group.optional) emit(RegExpInstruction.Split(preferred = body, alternative = next)) else body + } + + val close = emit(RegExpInstruction.Capture(capture, start = false, next = next)) + val body = compile(group.body, close) + val open = emit(RegExpInstruction.Capture(capture, start = true, next = body)) + return if (group.optional) emit(RegExpInstruction.Split(preferred = open, alternative = next)) else open + } +} + +private val lineTerminators = listOf('\n'.code..'\n'.code, '\r'.code..'\r'.code, '\u2028'.code..'\u2029'.code) +private val whiteSpace = listOf( + '\t'.code..'\r'.code, + ' '.code..' '.code, + '\u00A0'.code..'\u00A0'.code, + '\u1680'.code..'\u1680'.code, + '\u2000'.code..'\u200A'.code, + '\u2028'.code..'\u2029'.code, + '\u202F'.code..'\u202F'.code, + '\u205F'.code..'\u205F'.code, + '\u3000'.code..'\u3000'.code, + '\uFEFF'.code..'\uFEFF'.code, +) +private val digits = listOf('0'.code..'9'.code) +private val wordCharacters = digits + listOf('A'.code..'Z'.code, '_'.code..'_'.code, 'a'.code..'z'.code) + +private fun complement(ranges: List): List { + val result = mutableListOf() + var low = 0 + for (range in ranges.sortedBy { it.first }) { + if (low < range.first) result += low until range.first + low = maxOf(low, range.last + 1) + } + if (low <= Char.MAX_VALUE.code) result += low..Char.MAX_VALUE.code + return result +} + +private class OrderedRegExpParser(private val source: String) { + private var index = 0 + var captureCount = 0 + private set + + fun parse(): RegExpFragment.Choice? { + val result = choice(depth = 0) ?: return null + return result.takeIf { index == source.length } + } + + private fun choice(depth: Int): RegExpFragment.Choice? { + val choices = mutableListOf() + do { + val parts = mutableListOf() + while (index < source.length && source[index] !in ")|") { + val part = fragment(depth) ?: return null + parts += part + } + choices += RegExpFragment.Sequence(parts) + } while (consume('|')) + + return RegExpFragment.Choice(choices) + } + + private fun fragment(depth: Int): RegExpFragment? { + val char = source[index] + if (char == '(') return group(depth) + if (char == '^' || char == '$') { + index++ + return RegExpFragment.Boundary(start = char == '^') + } + + val ranges = when (char) { + '.' -> { + index++ + complement(lineTerminators) + } + '[' -> characterClass() + else -> character(inClass = false) + } ?: return null + + val repeat = when { + consume('+') -> Repeat.PLUS + consume('*') -> Repeat.STAR + consume('?') -> Repeat.OPTIONAL + else -> Repeat.ONCE + } + return RegExpFragment.Atom(ranges, repeat) + } + + private fun group(depth: Int): RegExpFragment.Group? { + if (depth >= MAX_GROUP_NESTING) return null + index++ + val capture = if (source.startsWith("?:", startIndex = index)) { + index += 2 + null + } else { + if (source.getOrNull(index) == '?' || captureCount == MAX_CAPTURE_COUNT) return null + captureCount++ + } + val body = choice(depth + 1) ?: return null + if (!consume(')')) return null + val optional = consume('?') + // RepeatMatcher skips zero-width repetitions at minimum zero. Leave nullable optional groups residual. + if (optional && body.nullable) return null + return RegExpFragment.Group(body, capture, optional) + } + + private fun characterClass(): List? { + index++ + val negated = consume('^') + val ranges = mutableListOf() + while (index < source.length && source[index] != ']') { + val left = character(inClass = true) ?: return null + val hasRange = source.getOrNull(index) == '-' && source.getOrNull(index + 1) != ']' + if (!hasRange) { + ranges += left + continue + } + + index++ + val right = character(inClass = true) ?: return null + val from = left.singleOrNull() ?: return null + val to = right.singleOrNull() ?: return null + if (from.first != from.last || to.first != to.last || from.first > to.first) return null + ranges += from.first..to.first + } + if (!consume(']')) return null + return if (negated) complement(ranges) else ranges + } + + private fun character(inClass: Boolean): List? { + val value = source.getOrNull(index) ?: return null + index++ + if (value != '\\') { + if (!inClass && value in ".*+?()[]{}^$|") return null + return listOf(value.code..value.code) + } + + val escaped = source.getOrNull(index) ?: return null + index++ + return when (escaped) { + 'd' -> digits + 'D' -> complement(digits) + 'w' -> wordCharacters + 'W' -> complement(wordCharacters) + 's' -> whiteSpace + 'S' -> complement(whiteSpace) + 'u' -> hexadecimal(digits = 4) + 'x' -> hexadecimal(digits = 2) + 'n' -> point('\n') + 'r' -> point('\r') + 't' -> point('\t') + 'f' -> point('\u000C') + 'v' -> point('\u000B') + 'b' -> if (inClass) point('\b') else null + in "\\/.*+?()[]{}^$|-" -> point(escaped) + else -> null + } + } + + private fun hexadecimal(digits: Int): List? { + if (index + digits > source.length) return null + val text = source.substring(index, index + digits) + val isHexadecimal = text.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' } + if (!isHexadecimal) return null + + index += digits + val code = text.toInt(radix = 16) + return listOf(code..code) + } + + private fun consume(expected: Char): Boolean { + if (source.getOrNull(index) != expected) return false + index++ + return true + } + + private fun point(character: Char): List = listOf(character.code..character.code) +} diff --git a/usvm-ts/src/main/kotlin/org/usvm/machine/expr/RegExpCalls.kt b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/RegExpCalls.kt index 0afa233aa3..b8a385c41a 100644 --- a/usvm-ts/src/main/kotlin/org/usvm/machine/expr/RegExpCalls.kt +++ b/usvm-ts/src/main/kotlin/org/usvm/machine/expr/RegExpCalls.kt @@ -64,7 +64,8 @@ internal fun TsExprResolver.tryApproximateRegExpCall(stmt: TsVirtualMethodCallSt return when (method) { CONSTRUCTOR_NAME -> initializeRegExpLiteral(reference, stmt) "test" -> testRegExp(reference, stmt) - else -> unsupportedRegExp("Only intrinsic RegExp.test and String.match are supported") + "exec" -> matchRegExp(reference, stmt.args.firstOrNull()) + else -> unsupportedRegExp("Only intrinsic RegExp.test, RegExp.exec and String.match are supported") } } @@ -77,7 +78,7 @@ internal fun TsExprResolver.tryApproximateRegExpCall(stmt: TsVirtualMethodCallSt } if (!backedReceiver) return TsExprApproximationResult.NoApproximation - return matchRegExp(checkNotNull(expression), stmt) + return matchRegExp(checkNotNull(expression), stmt.instance) } private fun TsExprResolver.initializeRegExpLiteral( @@ -92,7 +93,8 @@ private fun TsExprResolver.initializeRegExpLiteral( if (pattern == null || flags != "") { return unsupportedRegExp("Only constant RegExp patterns without flags are supported") } - if (parseRegExpPattern(pattern) == null) { + val existingPattern = parseRegExpPattern(pattern) + if (existingPattern == null && compileOrderedRegExp(pattern) == null) { return unsupportedRegExp("RegExp pattern requires unsupported syntax or backtracking: $pattern") } @@ -114,15 +116,15 @@ private fun TsExprResolver.testRegExp( private fun TsExprResolver.matchRegExp( reference: UConcreteHeapRef, - stmt: TsVirtualMethodCallStmt, + argument: UExpr<*>?, ): TsExprApproximationResult = with(ctx) { - val result = computeRegExpMatch(reference, stmt.instance) ?: return TsExprApproximationResult.ResolveFailure + val result = computeRegExpMatch(reference, argument) ?: return TsExprApproximationResult.ResolveFailure val matched = scope.calcOnState { models.first().eval(result.success).isTrue } val selectedBranch = if (matched) result.success else mkNot(result.success) scope.fork(selectedBranch) ?: return TsExprApproximationResult.ResolveFailure if (!matched) return TsExprApproximationResult.SuccessfulApproximation(mkTsNullValue()) - val string = stmt.instance.asExpr(addressSort) + val string = checkNotNull(argument).asExpr(addressSort) val array = scope.calcOnState { createRegExpMatchArray(string, result) } TsExprApproximationResult.SuccessfulApproximation(array) } @@ -138,8 +140,7 @@ private fun TsExprResolver.computeRegExpMatch( } val source = scope.calcOnState { regularExpressions[reference] } - val pattern = source?.let(::parseRegExpPattern) - if (pattern == null) { + if (source == null) { unsupportedRegExp("RegExp literal has not been initialized") return null } @@ -154,7 +155,22 @@ private fun TsExprResolver.computeRegExpMatch( val length = scope.calcOnState { stringLength(string) } ensureLengthBounds(scope = scope, length = length, maxLength = bound) ?: return null - return scope.calcOnState { RegExpMatcher(state = this, string = string, bound = bound).match(pattern) } + val pattern = parseRegExpPattern(source) + if (pattern != null) { + return scope.calcOnState { RegExpMatcher(state = this, string = string, bound = bound).match(pattern) } + } + + val program = checkNotNull(compileOrderedRegExp(source)) + val supportedBound = program.inputBound(bound) + val withinBound = mkBvSignedLessOrEqualExpr(length, mkBv(supportedBound)) + scope.fork(withinBound, blockOnFalseState = { + val detail = "Ordered matching exceeds UTF-16 bound $supportedBound" + terminateAsUnsupported(reason = "REGULAR_EXPRESSION_LITERAL: $detail") + }) ?: return null + return scope.calcOnState { + val matcher = OrderedRegExpMatcher(state = this, string = string, bound = supportedBound) + matcher.match(program) + } } private fun TsState.createRegExpMatchArray(string: UHeapRef, result: RegExpMatch): UConcreteHeapRef = with(ctx) { diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/expr/OrderedRegExpRuntimeTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/expr/OrderedRegExpRuntimeTest.kt new file mode 100644 index 0000000000..2022021c6e --- /dev/null +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/expr/OrderedRegExpRuntimeTest.kt @@ -0,0 +1,134 @@ +package org.usvm.machine.expr + +import org.junit.jupiter.api.io.TempDir +import org.usvm.PathSelectionStrategy +import org.usvm.StateCollectionStrategy +import org.usvm.api.TsTest +import org.usvm.api.TsTestValue +import org.usvm.machine.TsMachine +import org.usvm.machine.TsMachineAnalysisResult +import org.usvm.machine.TsOptions +import org.usvm.machine.call.TsResidualCallPolicy +import org.usvm.machine.call.TsUnknownCallModelSelection +import org.usvm.util.TsMethodTestRunner +import org.usvm.util.TsTestResolver +import org.usvm.util.assertNodeReplay +import org.usvm.util.getResourcePath +import org.usvm.util.jsString +import java.nio.file.Path +import kotlin.io.path.readText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertTrue + +class OrderedRegExpRuntimeTest : TsMethodTestRunner() { + private val source = "/models/OrderedRegExpRuntime.ts" + override val scene = loadScene(source) + private val regressionMethods = listOf( + "moveCaptures", + "findLeftmostAndFirst", + "backtrackingPreservesCaptureOrder", + "whitespaceDotAndAbsoluteEnd", + "nativeExecOnLinearPattern", + ) + + @TempDir + lateinit var directory: Path + + init { + options = options.copy( + pathSelectionStrategies = listOf(PathSelectionStrategy.BFS), + stateCollectionStrategy = StateCollectionStrategy.ALL, + stopOnCoverage = 0, + throwExceptionOnStepFailure = true, + ) + } + + @Test + fun capturesAndBacktracking() { + for (name in regressionMethods) { + val tests = analyze(name) + + assertEquals(setOf(1.0), tests.map { assertIs(it.returnValue).number }.toSet(), name) + } + } + + @Test + fun symbolicResultsReplay() { + val tests = analyze("symbolic") + val outcomes = tests.map { assertIs(it.returnValue).value }.toSet() + + assertEquals(setOf(false, true), outcomes) + val witnesses = tests.joinToString(separator = "\n") { test -> + val input = assertIs(test.before.parameters.single()).value + val value = assertIs(test.returnValue).value + val sourceString = jsString(input) + "if (OrderedRegExpRuntime.symbolic($sourceString) !== $value) throw Error('symbolic mismatch');" + } + nativeReplay(witnesses) + } + + @Test + fun literalTestRemainsPrecise() { + val tests = analyze("plainTest") + + val values = tests.map { assertIs(it.returnValue).value }.toSet() + assertEquals(setOf(true), values) + } + + @Test + fun nativeConformance() { + val assertions = regressionMethods.joinToString(separator = "\n") { name -> + "if (OrderedRegExpRuntime.$name() !== 1) throw Error('$name');" + } + nativeReplay(assertions) + } + + @Test + fun unsupportedFlagsRemainResidual() { + assertTrue(analyze("flagsStayResidual").isEmpty()) + } + + @Test + fun oversizedInputIsStoppedWithoutTruncation() { + val outcome = analyzeOutcome("overBudget", maxArraySize = 256) + + assertTrue(outcome.states.isEmpty()) + val hitOrderedMatchLimit = outcome.unsupportedPaths.any { "exceeds UTF-16 bound 128" in it } + assertTrue(hitOrderedMatchLimit, outcome.unsupportedPaths.toString()) + nativeReplay("if (!OrderedRegExpRuntime.overBudget()) throw Error('overBudget');") + } + + private fun analyze(name: String): List { + val method = getMethod(name, className = "OrderedRegExpRuntime") + val outcome = analyzeOutcome(name, maxArraySize = 8) + return outcome.states.map { state -> TsTestResolver().resolve(method, state) } + } + + private fun analyzeOutcome(name: String, maxArraySize: Int): TsMachineAnalysisResult { + val method = getMethod(name, className = "OrderedRegExpRuntime") + val runtime = TsOptions( + maxArraySize = maxArraySize, + unknownCallModelSelection = TsUnknownCallModelSelection.Only(emptySet()), + unknownCallFallback = TsResidualCallPolicy.FRESH_SYMBOLIC_RETURN, + ) + + val outcome = TsMachine(scene = scene, options = options, tsOptions = runtime).use { machine -> + machine.analyzeWithMetadata(methods = listOf(method)) + } + + assertFalse(outcome.engineFailed, name) + return outcome + } + + private fun nativeReplay(assertions: String) { + assertNodeReplay( + source = getResourcePath(source).readText() + "\n" + assertions, + directory = directory, + name = "ordered-regexp", + timeoutMessage = "Ordered RegExp native validation timed out", + ) + } +} diff --git a/usvm-ts/src/test/kotlin/org/usvm/machine/expr/RegExpRuntimeTest.kt b/usvm-ts/src/test/kotlin/org/usvm/machine/expr/RegExpRuntimeTest.kt index 815a2ccbb7..8665b7587b 100644 --- a/usvm-ts/src/test/kotlin/org/usvm/machine/expr/RegExpRuntimeTest.kt +++ b/usvm-ts/src/test/kotlin/org/usvm/machine/expr/RegExpRuntimeTest.kt @@ -127,9 +127,7 @@ class RegExpRuntimeTest : TsMethodTestRunner() { fun `unsupported syntax flags and coercion remain explicit limitations`() { val names = listOf( "unsupportedFlags", - "unsupportedBacktracking", "unsupportedCoercion", - "unsupportedUnanchoredRun", "unsupportedExecOverride", "unsupportedPropertyWrite", "unsupportedPropertyRead", diff --git a/usvm-ts/src/test/resources/models/OrderedRegExpRuntime.ts b/usvm-ts/src/test/resources/models/OrderedRegExpRuntime.ts new file mode 100644 index 0000000000..0d0d44e962 --- /dev/null +++ b/usvm-ts/src/test/resources/models/OrderedRegExpRuntime.ts @@ -0,0 +1,56 @@ +export class OrderedRegExpRuntime { + static moveCaptures(): number { + const regexp = /^(\d+)?('?)/; + const prefixed = regexp.exec("12'R"); + const bare = "R".match(regexp); + return prefixed?.[0] === "12'" && prefixed[1] === "12" && prefixed[2] === "'" && + bare?.[0] === "" && bare[1] === undefined && bare[2] === "" ? 1 : 0; + } + + static findLeftmostAndFirst(): number { + const shorter = "xaba".match(/a|ab/); + const longer = /ab|a/.exec("xaba"); + return shorter?.[0] === "a" && shorter.index === 1 && + longer?.[0] === "ab" && longer.index === 1 ? 1 : 0; + } + + static backtrackingPreservesCaptureOrder(): number { + const greedy = /^(a*)a$/.exec("aaaa"); + const alternative = "ab".match(/^((ab)|a)(b)$/); + return greedy?.[0] === "aaaa" && greedy[1] === "aaa" && + alternative?.[1] === "a" && alternative[2] === undefined && alternative[3] === "b" ? 1 : 0; + } + + static whitespaceDotAndAbsoluteEnd(): number { + const whitespace = /^\s+a$/.test("\uFEFF\u2028a"); + const nelIsNotWhitespace = !/^\s+a$/.test("\u0085a"); + const astral = /^(.)(.)$/.exec("\uD83D\uDE42"); + const rejectsLineBreak = /^a*$/.exec("aa\r\n") === null; + const passesEmpty = /^a*$/.test(""); + return whitespace && nelIsNotWhitespace && astral?.[1] === "\uD83D" && astral[2] === "\uDE42" && + rejectsLineBreak && passesEmpty ? 1 : 0; + } + + static nativeExecOnLinearPattern(): number { + const output = /(ab)/.exec("zab"); + return output?.[1] === "ab" && output.index === 1 && output.input === "zab" ? 1 : 0; + } + + static symbolic(input: string): boolean { + if (/^(a*)ab$/.test(input)) return true; + return false; + } + + static plainTest(): boolean { + if (/^(a*)ab$/.test("aaab")) return true; + return false; + } + + static overBudget(): boolean { + return /^a*$/.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + + static flagsStayResidual(): boolean { + return /a*/g.test("aaa"); + } +} diff --git a/usvm-ts/src/test/resources/models/RegExpRuntime.ts b/usvm-ts/src/test/resources/models/RegExpRuntime.ts index 078ef9282d..1ff580ef60 100644 --- a/usvm-ts/src/test/resources/models/RegExpRuntime.ts +++ b/usvm-ts/src/test/resources/models/RegExpRuntime.ts @@ -95,12 +95,10 @@ export class RegExpRuntime { } static unsupportedFlags(): boolean { return /x/i.test("X"); } - static unsupportedBacktracking(): boolean { return /^a+ab$/.test("aaab"); } static unsupportedCoercion(): boolean { const value: any = 7; return /7/.test(value); } - static unsupportedUnanchoredRun(): boolean { return /a+/.test("aa"); } static unsupportedExecOverride(): boolean { const expression = /x/; expression.exec = (value: string): RegExpExecArray | null => null; From 9d06df91c9aba8090d40f0be49c76023b08263b2 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Fri, 4 Dec 2026 03:53:32 +0100 Subject: [PATCH 2/2] Keep the RegExp limitation fixture unsupported --- .../src/test/resources/models/RuntimeLimitationBoundaries.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usvm-ts/src/test/resources/models/RuntimeLimitationBoundaries.ts b/usvm-ts/src/test/resources/models/RuntimeLimitationBoundaries.ts index a30bc7339e..af15147b68 100644 --- a/usvm-ts/src/test/resources/models/RuntimeLimitationBoundaries.ts +++ b/usvm-ts/src/test/resources/models/RuntimeLimitationBoundaries.ts @@ -1,6 +1,6 @@ export class RuntimeLimitationBoundaries { static regularExpressionLiteral(): boolean { - return /value|other/.test("value"); + return /(?=value)value/.test("value"); } static unsupportedConversionOrSupportedSibling(flag: boolean, value: { field: number }): string {