4 ms·
This feature is crying out for procedural macro support, not for being built into the language. For comparison, Rust has compile-time regular expressions (which
by eridius 12y ago
This feature is crying out for procedural macro support, not for being built into the language. For comparison, Rust has compile-time regular expressions (which, I will note, this blog post does not do; it's all runtime-parsed), implemented as a separate library that ships with Rust, using the procedural macro support (also called syntax extensions). This means the compiler and the language spec knows _nothing_ about regular expressions, and only the library libregex knows anything about it, and if you don't link against libregex, your program has no knowledge about it.
This ends up looking like the following:
#![feature(phase)] // feature-gate for syntax extensions
#[phase(plugin)] // tells the compiler the following crate has syntax extensions
extern crate regex_macros; // a crate is a rust library. this one provides the syntax extension
extern crate regex; // this one provides the runtime support for regular expressions
fn main() {
let re = regex!(r"^\d{4}-\d{2}-\d{2}$"); // compile-time regular expression
assert_eq!(re.is_match("2014-01-01"), true);
}
That `regex!(...)` call will trigger the compile-time syntax extension to parse the regular expression, throw a compile-time error if the parsing fails, and otherwise expand to an inline data structure that contains the runtime representation of the parsed regular expression. Even better, it generates native Rust code for various bits of the matching process, instead of relying on the generalized implementation used for runtime-parsed regular expressions, which means it's actually faster to use a compile-time regex. The downside is, of course, that it's generating specialized code for each one, so this can bloat your binary if you use a lot of regular expressions, but on the upside turning on Link-Time Optimization can get rid of a lot of this overhead.