WordPress-iOS-Shared icon indicating copy to clipboard operation
WordPress-iOS-Shared copied to clipboard

An experimental tool to check regular expressions at compile time

Open crazytonyli opened this issue 3 years ago • 1 comments

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:

// CHECK-REGEX
let pattern = #"\[[^\]]+\]"#

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).


  • [ ] I have considered if this change warrants release notes and have added them to the appropriate section in the CHANGELOG.md if necessary.

crazytonyli avatar Nov 15 '22 08:11 crazytonyli

@AliSoftware Agreed. In practice, when adding a new regex, not sure about others but I always go to some regex tester website to ensure I have a valid regex for my use case. I sure don't want to test the regex by building and running an iOS app. Good point about P2 by the way, I'll start a draft when I get some time 👍

crazytonyli avatar Nov 18 '22 07:11 crazytonyli