Permalink
Browse files

Handle regex syntax errors at runtime.

libc.regex_match() now raises RuntimeError if the regex can't be
compiled by regcomp().
  • Loading branch information...
Andy Chu
Andy Chu committed Jun 15, 2018
1 parent f427f91 commit ef848b30983a6818ff1b1186fc5bc3652d2c2703
Showing with 10 additions and 12 deletions.
  1. +4 −7 core/expr_eval.py
  2. +4 −4 native/libc.c
  3. +2 −1 native/libc_test.py
View
@@ -606,13 +606,10 @@ def Eval(self, node):
return s1 != s2
if op_id == Id.BoolBinary_EqualTilde:
matches = libc.regex_match(s2, s1)
# NOTE: regex matching shouldn't fail if compilation succeeds.
if matches == -1:
raise AssertionError(
"Invalid regex %r: should have been caught at compile time" %
s2)
try:
matches = libc.regex_match(s2, s1)
except RuntimeError:
e_die("Invalid regex %r", s2, word=node.right)
if matches is None:
return False
View
@@ -246,8 +246,8 @@ func_regex_match(PyObject *self, PyObject *args) {
regex_t pat;
if (regcomp(&pat, pattern, REG_EXTENDED) != 0) {
// When the regex contains a variable, it can't be checked at compile-time.
fprintf(stderr, "Invalid regex at runtime\n");
return PyLong_FromLong(-1);
PyErr_SetString(PyExc_RuntimeError, "Invalid regex syntax (func_regex_match)");
return NULL;
}
int outlen = pat.re_nsub + 1;
@@ -334,8 +334,8 @@ static PyMethodDef methods[] = {
{"regex_parse", func_regex_parse, METH_VARARGS,
"Compile a regex in ERE syntax, returning whether it is valid"},
{"regex_match", func_regex_match, METH_VARARGS,
"Match regex against a string. Returns a list of matches, None if no match, or "
"-1 if the regex is invalid."},
"Match regex against a string. Returns a list of matches, None if no match. "
"Raises RuntimeError if the regex is invalid."},
{"regex_first_group_match", func_regex_first_group_match, METH_VARARGS,
"If the regex matches the string, return the start and end position of the "
"first group. None for no match; -1 for invalid regex."},
View
@@ -75,7 +75,8 @@ def testRegex(self):
self.assertEqual(expected, actual)
# Error.
print(libc.regex_match(r'*', 'abcd'))
self.assertRaises(
RuntimeError, libc.regex_match, r'*', 'abcd')
def testRegexFirstGroupMatch(self):
s='oXooXoooXoX'

0 comments on commit ef848b3

Please sign in to comment.