Skip to content

Commit

Permalink
fix: Convert Go regex to Rust regex (#76)
Browse files Browse the repository at this point in the history
Convert Go regex to Rust regex

Go and Rust have some differences in their regex implementation. In Go
the following is valid:

```
uri=~"/v[1-9]/.*/{gid}/{uid}"
```

Rust sees the `{gid}` as a bad repetition, it expects a range like {1,4}

```
regex parse error:
    /v[1-9]/.*/{gid}/{uid}
                ^
error: repetition quantifier expects a valid decimal
```

For it to be a valid Rust regex the opening { has to be escaped.

This change adds that escaping.

The implementation is simple, iteration + writing in a result buffer. It
is probably not the best of nicest way of doing it, but it straight
forward
  • Loading branch information
fbs authored Nov 7, 2023
1 parent 6cf0736 commit 6d752e7
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 0 deletions.
84 changes: 84 additions & 0 deletions src/label/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,80 @@ impl Matcher {
}
}

// Go and Rust handle the repeat pattern differently
// in Go the following is valid: `aaa{bbb}ccc`
// in Rust {bbb} is seen as an invalid repeat and must be ecaped \{bbb}
// This escapes the opening { if its not followed by valid repeat pattern (e.g. 4,6).
fn convert_re(re: &str) -> String {
// (true, string) if its a valid repeat pattern (e.g. 1,2 or 2,)
fn is_repeat(chars: &mut std::str::Chars<'_>) -> (bool, String) {
let mut buf = String::new();
let mut comma = false;
for c in chars.by_ref() {
buf.push(c);

if c == ',' {
// two commas or {, are both invalid
if comma || buf == "," {
return (false, buf);
} else {
comma = true;
}
} else if c.is_ascii_digit() {
continue;
} else if c == '}' {
if buf == "}" {
return (false, buf);
} else {
return (true, buf);
}
} else {
return (false, buf);
}
}
(false, buf)
}

let mut result = String::new();
let mut chars = re.chars();

while let Some(c) = chars.next() {
if c != '{' {
result.push(c);
}

// if escaping, just push the next char as well
if c == '\\' {
if let Some(c) = chars.next() {
result.push(c);
}
} else if c == '{' {
match is_repeat(&mut chars) {
(true, s) => {
result.push('{');
result.push_str(&s);
}
(false, s) => {
result.push_str(r"\{");
result.push_str(&s);
}
}
}
}
result
}

pub fn new_matcher(id: TokenId, name: String, value: String) -> Result<Matcher, String> {
let op = match id {
T_EQL => Ok(MatchOp::Equal),
T_NEQ => Ok(MatchOp::NotEqual),
T_EQL_REGEX => {
let value = Matcher::convert_re(&value);
let re = Regex::new(&value).map_err(|_| format!("illegal regex for {}", &value))?;
Ok(MatchOp::Re(re))
}
T_NEQ_REGEX => {
let value = Matcher::convert_re(&value);
let re = Regex::new(&value).map_err(|_| format!("illegal regex for {}", &value))?;
Ok(MatchOp::NotRe(re))
}
Expand Down Expand Up @@ -465,4 +530,23 @@ mod tests {
let ms = matchers.find_matchers("foo");
assert_eq!(4, ms.len());
}

#[test]
fn test_convert_re() {
let convert = |s: &str| Matcher::convert_re(s);
assert_eq!(convert("abc{}"), r#"abc\{}"#);
assert_eq!(convert("abc{def}"), r#"abc\{def}"#);
assert_eq!(convert("abc{def"), r#"abc\{def"#);
assert_eq!(convert("abc{1}"), "abc{1}");
assert_eq!(convert("abc{1,}"), "abc{1,}");
assert_eq!(convert("abc{1,2}"), "abc{1,2}");
assert_eq!(convert("abc{,2}"), r#"abc\{,2}"#);
assert_eq!(convert("abc{{1,2}}"), r#"abc\{{1,2}}"#);
assert_eq!(convert(r#"abc\{abc"#), r#"abc\{abc"#);
assert_eq!(convert("abc{1a}"), r#"abc\{1a}"#);
assert_eq!(convert("abc{1,a}"), r#"abc\{1,a}"#);
assert_eq!(convert("abc{1,2a}"), r#"abc\{1,2a}"#);
assert_eq!(convert("abc{1,2,3}"), r#"abc\{1,2,3}"#);
assert_eq!(convert("abc{1,,2}"), r#"abc\{1,,2}"#);
}
}
16 changes: 16 additions & 0 deletions src/parser/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,22 @@ mod tests {
]);
Expr::new_vector_selector(None, matchers)
}),
(r#"foo:bar{a=~"bc{9}"}"#, {
let matchers = Matchers::one(Matcher::new(
MatchOp::Re(Regex::new("bc{9}").unwrap()),
"a",
"bc{9}",
));
Expr::new_vector_selector(Some(String::from("foo:bar")), matchers)
}),
(r#"foo:bar{a=~"bc{abc}"}"#, {
let matchers = Matchers::one(Matcher::new(
MatchOp::Re(Regex::new("bc\\{abc}").unwrap()),
"a",
"bc{abc}",
));
Expr::new_vector_selector(Some(String::from("foo:bar")), matchers)
}),
];
assert_cases(Case::new_result_cases(cases));

Expand Down

0 comments on commit 6d752e7

Please sign in to comment.