An experimental tool to check regular expressions at compile time #322
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a random idea popped into my head today, not sure if it's worth pursuing, but I had fun learning swift-syntax and swift AST. We can move this tool into the bash-cache plugin or some other places, if we find this tool useful. 😸
The idea is use a special inline comment
// CHECK-REGEX
to check if the following string constant declaration is a valid regex. Kinda like Swift 5.7's Regex constant compile time check, except we don't have to wait for 2 or 3 years (Swift's Regex is only available on iOS 16).Here is an example:
One requirement of this check is the string constant needs to be a raw string literal (without string interpolation), otherwise we can't know the regex at compile time.
The implementation is quite simple. Iterate through all the Swift files in given directory, find a declaration that has this special inline comment, extract the regex from the expression, and finally check the regex by creating a
NSRegularExpression
instance with it.Since this is an experimental tool, I didn't handle any edge cases (i.e. the inline comment is used on a non-string declaration) and the error reporting probably can be improved too (i.e. include file and line number in the error message).
CHANGELOG.md
if necessary.