wordpress-mobile / WordPress-iOS-Shared

Shared components used in building the WordPress iOS apps and other library components
GNU General Public License v2.0
18 stars 22 forks source link

An experimental tool to check regular expressions at compile time #322

Open crazytonyli opened 1 year ago

crazytonyli commented 1 year ago

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


crazytonyli commented 1 year ago

@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 👍