127 points · by burntsushi · 10y ago · 108 comments
Most other languages are "dead ends", because code written in them is not easily reusable from other languages.
pragma Export(Convention => C, Entity => My_Ada_Function, External_Name => "mypackage_ada_function");
You can kinda coerce D and C++¹ to do the same thing, but this is definitely something Rust and Ada got really right.--
¹Okay I lied, C++ does this pretty easily with extern "C". However, C++ APIs frequently do not convert well to C at all and you often have to write wrappers for them. C++ classes in particular just can't cross ABI boundaries without a lot of pain, while Ada records and Rust structs are usually just a pragma away from being accessible from C (their “methods” don't use a special calling convention; method calls are just syntactic sugar for passing a struct as the first argument).
Hopefully if such a thing exists you could link directly to a rust library from other high level languages and possibly even have lower overhead.
For now being able to do the equivalent of extern "C" is not that new but still really useful I suppose.
Which is only true, when we forget about the history of computing before C was widespread outside AT&T and C ABI became a synonym for OS ABI.
Rust is great, and a very good step forward in terms of safe code, but lets not forget the ones that came before.
We may as well remember Lucy, the former vacuum tube assembler and current resident of the dustbin of history.
For example, many millennial have this strange idea that C and C++ are the only option for native AOT compiled code, with language features for cache control, RAII or system programming in general.
The aren't the only option, they became the only option given the decisions that the OS vendors took regarding which languages to sell to their customers on the OS SDKs.
Many of those decisions weren't taken in terms of language quality, rather due to money as UNIX was a free OS, whereas other OSes with better Rust like safety were of course more expensive than free.
So young developers get taught this myth that C was the first system programming language, when in the mid-60's we already had mainframe systems being programmed in type safe systems programming languages, across the whole stack.
Using languages like NEWP (https://en.wikipedia.org/wiki/NEWP), just to give one example. A language where one already had the distinction between safe and unsafe modules, with unsafe modules requiring administrator privileges to run.
For example, the NEWP in MCP only allowed unsafe code in modes where the system administrator would configure them as such, back in 1961.
http://www.smecc.org/The%20Architecture%20%20of%20the%20Burr...
For instance, if I bind a Rust library that opens a file on disk and use it from Go, I lose all the benefits of the Go runtime like the fact that the FD is not inherited by sub processes (as Go always uses O_CLOEXEC, while glibc doesn't), or the fact that blocking calls never return EINTR to application code in case of signals (the Go runtime handles this for the application).
So you might think that the library works, while its subtly violating your language's runtime conventions in a way that might cause hard to debug bugs in production.
One of the benefit of writing code in single "modern" language/runtime is that you don't have to worry about these hairy issues.
This process was lucrative. My first draft of the C API defined an iterator that held on to a pointer to the text being searched for the lifetime of the iterator. It turns out that this is inconvenient to use from a language like Go (or perhaps, any language with a moving GC) because C holding on to pointers to memory allocated in the host language can be bad juju. Because I did this process in tandem, I was able to correct the issue at the C API level.
As a result, if you need fast regexes in Go, you now have an option, and that option is built on a reasonably mature regex library with thousands of tests and a benchmark harness that sports PCRE1, PCRE2, Tcl, RE2 and Oniguruma, of which, Rust's regex engine compares quite favorably.
The GP comment said that Rust is nice because you can write libraries that can be bound to other languages with more runtime. I was highlighting that this property sounds nice in theory, but has a small scope of applicability in practice. A regex library fits the small scope.
FFI isn't the only way to be reusable from another language though. Many interpreted languages are easy to embed into C, C++, and often other languages.
Basically, having base types convert toll-free is HUGE.
You can call Go from C, or even from Java on Android out-of-the-box (and Objective C on iOS), for example.
You just don't see Java or Go code (let alone both) used in programs predominantly written in another language.
(BTW I am genuinely asking)
Which is also technically true for C as well. The ABI [EDIT: Not API] is an implementation detail which can vary from compiler to compiler.
So long as you're just using LLVM-based compilers for both Rust and your other languages, you should be OK, but don't be surprised if you run into problems.
No. You can use the Go bindings to Rust's regex library where the regex library is compiled with `rustc` (llvm based) and your host program, written in Go, is compiled with the standard Go compiler, which is not llvm based.
This works because the Go toolchain knows how to link with objects exposing a C ABI and the Rust toolchain knows how to provide said objects. There is no particular dependency on llvm here.
The C ABI (API is less relevant there) is really the platform/OS's calling convention, which — aside from Microsoft (and embedded systems I guess, because embedded) — is generally the architecture's calling conventions. Which are usually well documented.
> So long as you're just using LLVM-based compilers for both Rust and your other languages, you should be OK, but don't be surprised if you run into problems.
As long as all the languages involved use the same ABI you're in the clear, that's got nothing to do with LLVM. That's what cgo does on the Go side[0]. And as pcwalton notes in an other comment, in theory you could even have the Rust FFI follow the Go/Plan9 ABI.
[0] at a significant cost for the default toolchain since `gc` doesn't use the platform ABI. I believe the gccgo-based alternative toolchain has no cgo overhead.
- Rust allows you to export functions with the C ABI
- LLVM wasn't involved here at all
We find Rust intriguing and the fine-grained control would be a good match for what our run-time needs; it would be a interesting project to re-implement parts of Hyperscan in Rust.
I'm happy to wrap the C directly (in fact, that's what I've done for most of the other regex engines I benchmark against). Before I try to wrangle the callback-style API, is there an alternate API with a more explicit iterator-like interface?
There are no other interfaces outside of the callback API. It's an interesting prospect to have an iterator-like API but a naive implementation of an iterator API would involve us having to save out all of our state somehow (in an explicit fashion, as opposed to a bunch of stack frames). Our system is pretty complex and so it's not just a case of saving out a couple DFA states...
The first thing I noticed was that hyperscan wasn't lining up with match counts from the rest of the regex engines. I dug into your docs a bit more, and indeed, your engine reports all matches, whereas traditionally, most regex engines offer an iterator over successive non-overlapping leftmost-first matches (including start+end). Of course, that's not to say you're wrong or anything---it's just going to be a real bear to accurately benchmark them.
All in all, hyperscan looks pretty fast. Some of your docs suggest you're doing even smarter literal detection than I am. Prefix literals and literals "near the front" are easy enough to figure out (the latter is on my list of things to do), but literals at the end or middle of a regex seem much trickier. In particular, it seems very easy to fall into worst case quadratic behavior. If you felt like expanding on some implementation details there, that would be awesome. :-)
In any case, I'll share some timings. I ran all of the following regexes on a ~2GB file containing a concatenation of some large sample of Project Gutenberg. It's my goto for "feeling" out regexes and collecting large samples for profiling. I modified simplegrep.c to not print every match and instead increment a single static `count`. I also modified it to mmap the file, so that it is comparable to my utility in Rust which also mmaps the file. The count of total matches is printed at the end. I tried to limit the regexes to ones that had the same number of matches in all regex engines, but on some of them, hyperscan reported slightly more. I then modified simplegrep.c to use the HS_FLAG_SOM_LEFTMOST flag. I did this because that's what Rust's regex engine does (and so do most others). Thus, the benchmark is flawed. But knowing this...
Benchmarks are reported in seconds. I tried to take the best of 3 where appropriate, but overall, I saw very little variation run to run.
pattern rust pcre2-jit hs hs-start-end
\w+\s+Holmes 4.4 17.0 0.5 3.4
[1] 4.4 4.0 0.5 0.5
(?i)Sherlock|Holmes|Watson 4.6 7.5 0.5 0.5
Sher[a-z]+|Hol[a-z]+ 0.9 0.6 0.6 0.6
(?i)Sher[a-z]+|Hol[a-z]+ 4.6 7.0 0.6 0.7
[2] 0.9 2.0 0.5 0.5
[3] 1.0 --- 0.5 0.5
[a-zA-Z]+ing 5.1 7.2 1.3 2.2
\s[a-zA-Z]{0,12}ing\s 4.9 20.0 1.6 2.6
\w{7}\s\w{7} 5.0 32.6 7.0 7.1
[0-9]+[a-z]+[0-9]+[a-z]+[0-9]+ 2.1 2.1 0.5 0.5
[1] Sherlock|Holmes|Watson|Irene|Adler|John|Baker
[2] Holmes.{0,25}Watson|Watson.{0,25}Holmes
[3] Holmes(?:\s*.+\s*){0,10}Watson|Watson(?:\s*.+\s*){0,10}Holmes
That's a pretty impressive showing! I'll have to learn your secrets. :-)And, impressive work on the regex engine!
There is some analysis---only for Rust's regex engine---with the definition of the benchmarks themselves: https://github.com/rust-lang-nursery/regex/blob/master/bench... (If you fish around there, you'll also see how everything is wired up.)
My plan at the moment is to publish something more comprehensive, but it will take time.
And yes, the benchmarks you linked are not only outdated, but misleading, and parts of the conclusion I do not agree with. It also doesn't include PCRE2, which is very fast.
I'm also asking beyond Go, so if the answer is "M:N really screws up Go w.r.t. Rust", I'm also curious about whether, for instance, you could write native Rust extensions to Perl or Python or $WHATEVER by changing out the runtime or something. If it works better for some languages than others, which ones might they be?
It's nice to be able to generate true C functions, and it is of course perfectly appropriate and correct to start there, given the real-world state of the ecosystem. But a lot of languages take various forms of penalties to call into C, in order to ensure guarantees that are not necessarily required by languages that aren't C, and, simultaneously, miss out on guarantees that Rust may be able to provide that C can't express and thus the C bindings can't count on.
[0]: https://github.com/rust-lang-nursery/regex/commit/e5a5198eee...
However, there are plenty of benchmarks well over 10x that are not silly at all. Look at the second block. The BeforeHolmes benchmark in particular is a good litmus test, since it defeats most optimizations.
Those particular speed ups are due to algorithms used. RE2 would have a similar speedup when compared with Go's regexp package.
Some of the other benchmarks in the 100x-400x range are likely due to smarter use of literal scanning.
1. Compiling regexes at compile time requires a compiler plugin, which only works on nightly.
2. The compile-time regexes are dramatically slower (think orders of magnitude) than the normal Regex::new method. The normal Regex::new method is what's shown here in these bindings.
The compiler plugin was code I wrote two years ago, and really hasn't changed since then. Regex::new on the other hand has gotten a lot of love.
The plugin's performance may one day get better, but it won't be soon unless someone else works on it.
The plugin has these tools at its disposal: Pike VM.
But yeah, killercup is correct. The DFA (online) is one of the bigger reasons. But the offline DFA and Boyer-Moore are probably just as important.
You might glean more information from my hacking guide: https://github.com/rust-lang-nursery/regex/blob/master/HACKI...
There is [a lint][1] which checks that your regular expressions are valid (at compile time), though.
[1]: https://github.com/Manishearth/rust-clippy/wiki#invalid_rege...