Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions codeflash/languages/javascript/instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ def __init__(self, function_to_optimize: FunctionToOptimize, capture_func: str)
rf"(\s*)(await\s+)?(\w+)\[['\"]({re.escape(self.func_name)})['\"]]\s*\("
)

# Compiled regex to find the next character of interest (quotes, parentheses, backslash).
# This lets us skip large stretches of irrelevant characters in C instead of Python.
self._special_char_re = re.compile(r'["\'`()\\]')

def transform(self, code: str) -> str:
"""Transform all standalone calls in the code."""
result: list[str] = []
Expand Down Expand Up @@ -327,13 +331,21 @@ def _find_balanced_parens(self, code: str, open_paren_pos: int) -> tuple[str | N
s_len = len(s)
quotes = "\"'`"

special_re = self._special_char_re

# Use regex to jump to the next special character (quote, parenthesis, backslash).
# This reduces Python-level iterations by leveraging C-level scanning.
while pos < s_len and depth > 0:
char = s[pos]
m = special_re.search(s, pos)
if not m:
return None, -1
i = m.start()
char = m.group(0)

# Handle string literals
# Note: preserve original escaping semantics (only checks immediate preceding char)
if char in quotes:
prev_char = s[pos - 1] if pos > 0 else None
prev_char = s[i - 1] if i > 0 else None
if prev_char != "\\":
if not in_string:
in_string = True
Expand All @@ -347,7 +359,7 @@ def _find_balanced_parens(self, code: str, open_paren_pos: int) -> tuple[str | N
elif char == ")":
depth -= 1

pos += 1
pos = i + 1

if depth != 0:
return None, -1
Expand Down
Loading