15 ms·
The tooling for the web written in JavaScript is excellent, so I was curious, are there any options there are for calling JavaScript from Rust code? I know ther
by malandrew 11y ago
The tooling for the web written in JavaScript is excellent, so I was curious, are there any options there are for calling JavaScript from Rust code? I know there is the ffi module for NodeJS that allows you to call Rust from JavaScript, but I was wondering if there is something that works well in the other direction.
- kibwen 11y agoIt's an interesting question. You can embed V8 in Node, so theoretically you could also embed the entirety of V8 in a Rust program just as you could embed Lua or Python in a Rust program. But just because it's possible doesn't necessarily mean that it's easy... it would be a fascinating project for someone adventurous. :)
- aselzer 11y agoEmbedding JS in Rust by using V8 (as kibwen has mentioned) would be no problem, but using node.js modules might not be so easy. It's like calling ruby gems from C. What do you mean by "tooling for the web"? If it's preprocessors like LESS (that are written in JS), you could run the JS in V8 to transform the CSS efficiently, but maybe the compiler "binary" (script) is enough. In this case it's the best approach, since performance will be good, and you don't have to reinvent everything. But if it's something like express.js, it's probably not worth it. It's surely possible somehow, but in a pretty hacky way and at the cost of high overhead and complexity caused by calling from a static language to a dynamic one.
- barosl 11y agoI once experimented this, and it worked. I wanted to do this because I needed a decent and fast CommonMark library, but Rust didn't have one. (Yes, I tried to embed JavaScript in Rust just to parse some MarkDown text!) There are two libraries that embed V8 in Rust, but all of them seem to be abandoned for now. However if there become enough interests, a new project will arise I think. (FWIW, I ended up calling CommonMark library written in Python from Rust, because embedding CPython was easier than embedding V8. Unfortunately CPython's performance is worse than V8, but as I know Python better than JavaScript it was a reasonable choice.)
- thristian 11y agoYou know there's a CommonMark reference implementation in C, right? https://github.com/jgm/cmark https://github.com/jgm/cmark I haven't tried it, but I would expect it would be easier to link with Rust than an entire other language VM.
- barosl 11y agoOh, yes. I had also tried that, but found some convenient features missing, e.g. line breaks treated as `<br>` (not two consecutive blank lines), GitHub-flavored tables, and the strikethrough syntax. I'll have to wait until the official CommonMark spec includes them. Also the third-party CommonMark libraries are usually easier to extend, with your own syntax addition.