Skip to content

Commit 48ec61a

Browse files
gh-91700: Validate the group number in conditional expression in RE (GH-91702)
In expression (?(group)...) an appropriate re.error is now raised if the group number refers to not defined group. Previously it raised RuntimeError: invalid SRE code.
1 parent 6ccfa31 commit 48ec61a

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

Lib/re/_parser.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ def __init__(self):
7777
self.groupdict = {}
7878
self.groupwidths = [None] # group 0
7979
self.lookbehindgroups = None
80+
self.grouprefpos = {}
8081
@property
8182
def groups(self):
8283
return len(self.groupwidths)
@@ -795,6 +796,10 @@ def _parse(source, state, verbose, nested, first=False):
795796
if condgroup >= MAXGROUPS:
796797
msg = "invalid group reference %d" % condgroup
797798
raise source.error(msg, len(condname) + 1)
799+
if condgroup not in state.grouprefpos:
800+
state.grouprefpos[condgroup] = (
801+
source.tell() - len(condname) - 1
802+
)
798803
state.checklookbehindgroup(condgroup, source)
799804
item_yes = _parse(source, state, verbose, nested + 1)
800805
if source.match("|"):
@@ -975,6 +980,11 @@ def parse(str, flags=0, state=None):
975980
assert source.next == ")"
976981
raise source.error("unbalanced parenthesis")
977982

983+
for g in p.state.grouprefpos:
984+
if g >= p.state.groups:
985+
msg = "invalid group reference %d" % g
986+
raise error(msg, str, p.state.grouprefpos[g])
987+
978988
if flags & SRE_FLAG_DEBUG:
979989
p.dump()
980990

Lib/test/test_re.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -593,6 +593,8 @@ def test_re_groupref_exists_errors(self):
593593
self.checkPatternError(r'()(?(1)a|b|c)',
594594
'conditional backref with more than '
595595
'two branches', 10)
596+
self.checkPatternError(r'()(?(2)a)',
597+
"invalid group reference 2", 5)
596598

597599
def test_re_groupref_overflow(self):
598600
from re._constants import MAXGROUPS
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Compilation of regular expression containing a conditional expression
2+
``(?(group)...)`` now raises an appropriate :exc:`re.error` if the group
3+
number refers to not defined group. Previously an internal RuntimeError was
4+
raised.

0 commit comments

Comments
 (0)