207 points · by wcrichton · 10y ago · 121 comments
- Your compile times will be a lot slower than they would otherwise be. This is a big one for me.
- If your type system is materially different than Rust's, you don't gain any benefits since you have to write your own type checker anyways.
- LLVM is designed to be easy to machine generate, including having a library API for generating code. Rust doesn't yet.
- You can't necessarily re-use Cargo if your language requires type info to link that wouldn't be in the Rust source files generated.
- If you have semantic differences in memory model you'll need to give up the advantage of Rust's safety by having your code generate unsafe pointers, for example if you want to have shared mutability in a single-threaded context, which Rust doesn't handle nicely.
- If you do re-use Rust's type checker the error messages you get out will be terrible and point into generated Rust code.
- Debug info and debugging get even harder.
- If you want Rust interoperability you have to replicate Rust's enormous type system in your language's FFI, which is hard if you also have your own type checker, see above.
Basically it is a good idea, if your language has semantics and type system very close to Rust.
A much better idea IMO is to target LLVM and then write an LLVM plugin that can link to Golang object files and generate Golang struct metadata. Golang's FFI and type system are much much simpler and more likely to be able to graft onto new languages. Also Go's library ecosystem is larger.
- When you say "materially different," how different are we talking? I'll admit that if you want to implement Haskell (or anything with HKT) that it's a long shot, but if you want to implement Javascript, it shouldn't be that hard, yes?
- Can you give an example of when you need type info to link?
- RE: debug info and error messages, do you disagree with what's written in the post? I agree this is an issue, but it doesn't seem unsolvable.
Generally, I guess I don't see how most languages have semantics terribly different from Rust. You don't need unsafe pointers for shared mutability with a single thread because you can use a RefCell (see: my language linked in the post). In my experience, most type systems for general-purpose languages have roughly the same feature set as Rust.
I buy that implementing a language completely different from Rust in semantics/types makes Rust not a good target, but for most languages we use nowadays, isn't that not the case?
Imagine you have machine code generated by compiling a C program and now want to figure out what struct some function takes as an argument.
As you go down towards machine code you lose information that you cannot easily recover.
Solving all of these issues is also only practical, if the Rust developers themselves cooperate. It seems to me the very purpose of creating a new language, is in freeing yourself of the limits existing ones have. Building a new language on technology that are restrictive doesn't really make sense from that perspective.
- The type system I'm thinking of includes effect inference from Koka (http://www.rise4fun.com/koka/tutorial), is simpler in other places, and has full type inference even of function signatures.
- An example of type info to link is effects. I could do things like serializing my type structures into Rust method names and then decoding them, but that's pretty hacky.
- Error reporting isn't just mapping, it's the messages too. I don't want my language getting error messages like "modification of an immutable borrow" or "cannot pass an Rc<RefCell<MyLangInt>> to a function that takes an Rc<RefCell<Vec<MyLangInt>>" when it doesn't look like that or have those constructs.
- RefCell has runtime overhead where every other compiled language doesn't.
- I think the type systems of most statically typed languages are substantially different from Rust that it would be an impedance mismatch.
I think this is only remotely better for dynamically typed languages, since that also solves a lot of the issues with errors since those are mostly created by your runtime functions.
As a supporting point, TypeScript requires definition files (.d.ts) for JavaScript libraries to properly type them. Unless the language has a 1:1 correspondence to Rust types, something similar will probably need to happen.
Embedding the Rust compiler would be pretty difficult, especially if your compiler isn't written in Rust.
I think that using Rust as a compiler target is a completely goofy idea. But perhaps Rust's MIR intermediate representation could work for other source languages.
- almost nobody has Rust installed already, and it's a ~100MB download. With a new version every six weeks or so.
Linking to Go libraries from a certain type of language could be super easy and the libraries would be nice enough to use to not need a wrapper layer.
I talked about that because IMO a really important part of having a usable language is an ecosystem, and if you're going to start a new language today piggybacking off of Go's sounds like a good plan.
LLVM is not platform-independent.
LLVM IR has baked-in constants, ABI details, and other platform-specific things. The "LLVM IR is a compiler IR" post has a good summary,
http://comments.gmane.org/gmane.comp.compilers.llvm.devel/43...
One result of that is that the following quote is not true:
> a compiler writer can target LLVM and then have his language work across platforms (e.g. on Linux, Mac, and Windows machines)
Actually a compiler must generate different LLVM IR for each platform.
It is true that LLVM does abstract some or even most things away - CPU architecture is (mostly) handled for you, for example, which is what the author mentions - but many important things aren't.
> as well as with other languages that use LLVM
You'll still need to make sure to use the right ABIs for those languages.
In fact, LLVM has somewhat poor abstraction for the C ABI, in that it exists in clang and not in LLVM, as a result, Rust has had to duplicate a bunch of that code. This point actually supports the author's position - targeting Rust would actually be a more portable target than LLVM!
Overall, it might make sense to compile to Rust. But probably to Rust MIR, the IR they are developing. MIR needs to mature and stabilize, but there are already signs of an ecosystem starting to form around it. It's interesting speculation, but it would be exciting to see Rust MIR be "the new LLVM."
For all those reading this that may have thought LLVM acts like a low-level version of something like the JVM (as the name suggests, I got caught out with this before too), it's not the case. LLVM is a compiler framework, the main output of which isn't bytecode for a VM but is rather machine code for the platform you're running on. There is no performance overhead from running LLVM-generated code because LLVM is not part of the final runtime.
What makes the LLVM low-level, compared to the JVM or the LVM for example, is that it doesn't offer the same level of abstraction that they do. For example, the JVM abstracts not only the machine, but also the operating system, the program linker/loader, and even some devices, etc. On the other hand, the LLVM essentially abstracts the CPU's instruction set, and that's about it. This is why even when generating LLVM bitcode rather than native code, you still need to worry about things like ABI, naming conventions, system calls, etc. -- because those things are separate from the physical machine's ISA.
However, just like with physical machines, I'd wager that it'd be possible to implement those abstractions on top of the LLVM, though it's likely easier and more efficient to just have a retargetable code generator.
Note that the LLVM can also operate as a JIT VM much like Java's HotSpot VM or LuaJIT's VM, and in such a mode the differences are less obvious from the outside. Similarly, both Java and Lua can be compiled to native code (in fact, in order for JIT to work, this must be the case), but going a step further, they can be compiled AOT. In a sort of "middle-ground", they can be compiled to their respective bitcode, and then further compiled into native code -- precisely the way the LLVM tends to operate.
The idea goes way back. There are plenty of examples throughout history of compilers targeting virtual (abstract) machines, and it offers several advantages. Portability is the one everyone talks about, but there can also be advantages for code density and compiler complexity, among others. For example, the ANSI/ISO/IEC standard for the C programming language defines the semantics of C in terms of the operation of an abstract machine. A handy way to specify the operational semantics of a language! [EDIT: In fact, the original purpose of abstract machines was for this kind of formal specification of semantics; it was nearly a decade before people realized the other advantages of AMs when used as an abstraction in programs themselves.]
See also: Landin's SECD machine, BCPL (O-code), UCSD Pascal (P-code), (O)Caml (CAM - categorical abstract machine), the G-machine, and many more.
In the interest of being precise, I'd rather call LLVM an "abstract" machine, in the same vein as the C abstract machine defined by the C language specification (https://blogs.msdn.microsoft.com/larryosterman/2007/05/16/th...).
To further clarify this point, LLVM's bytecode format is called LLVM IR, where IR stands for Intermediate Representation. GCC has its own intermediate representation for the same reasons LLVM does.
As for compiling to MIR, that's a solid point--I think the only reason you would compile to Rust instead of MIR is that it's easier as the compiler writer. As mentioned in the post, you can write code generators quickly just using quasiquotations.
> (look at Rust's battle for Windows for some perspective!)
Or in other directions, there's some instances where Windows support is _better_ than other platforms, like stack probes.I chose to write both parts in Rust. Fwiw the semantics of the language really didn't match Rust at all (though, I suspect you weren't thinking of DSLs when you wrote your paragraph).
In the end I had all the benefits of _safe_ Rust when compiling the transformed code into the DSO.
This DSO is a critical component and can not fail. I can't imagine transforming the AST into C or LLVM - I wouldn't be able to sleep at night. I'm only human; I know I'd fall into a number of traps that humans fall into when coding in C - especially when I am _generating_ C from an AST...
Most obviously you cannot map Javascript or Java methods or variables directly to Rust because these languages don't have anything like the borrow checker. You could come up with a way to work around that, but then why target Rust at all?
I think there's a deeper problem with your proposal though, which is - why? I know you try and answer that in the article but I found it unconvincing. The JVM was explicitly designed to solve the problem you're trying to solve, as you clearly know, so a good starting point would be to much more thoroughly analyse why you aren't satisfied with it.
You say you have to "shoulder the runtime overhead of a garbage collector" but then name lots of languages you want to compile to Rust, all of which assume and require the presence of a garbage collector. Then later you talk about needing a good GC written in Rust. Well ... why? If you're gonna have to provide a GC anyway for practically every modern language, then the runtime overhead of this will be paid no matter what.
Having studied the JVM quite extensively, I don't see much in it that's obviously wrong or could be done wildly better, but I see a lot that's done right. If you re-walk that path, you will probably end up reinventing the wheel.
With regards to efficiency, a "unique design" is of little direct consequence; we are always mapping from one very different language to another, since assembly bears ultimately little resemblance to Java or Ruby or Haskell.
A language can be a bad compile target but that has more to do with runtime restrictions. For example, it's hard to build command line tools that start quickly if you target the JVM. Compacting GC can make interop with other languages hard (since objects get moved around). But Rust doesn't come with abstractions or an execution model that are any more heavy weight than C++ (which is no way a bad language for implementing interpreters or compilers, and has even served as a compile target on occasion); in fact it is a more conservative extension of C than C++ is.
Rust does impose a burden that is kind of like saying, your compiler/interpreter has to pass Valgrind+Coverity; but this is perhaps more of a help than a hindrance -- and it doesn't limit the kind of language you can write.
Then he wants a "battle hardened GC", a JVM, access to the internal syntax tree of the compiler, and enough dynamism to allow an interpretive environment. What? Those are all features that Rust deliberately doesn't have. Adding them would drastically change the language and add considerable complexity. They would not contribute to Rust's main goal - provide something in which to write reliable production software.
From the feature list this guy is asking for, what he really wants is Microsoft's ".NET" system. That has all the run-time stuff he wants, and multiple compilers compile to it.
Will's idea seems to be to use Rust as a target for a high level GCd language, which can then (mostly) seamlessly interop with "pure" Rust code, and the interop won't have an unsafe boundary.
You get an OO ABI, with support for generics and OS level interoperability and reference counting as the GC algorithm.
Yes, using COM from C is a pain, but it was never intended to be used as such, rather C++, VB, Delphi and any other Windows language able to speak COM.
It seems to address a similar need as the one i mentioned above, among others.
But if you want less verbosity, you can write your compiler in Kotlin instead. There's no requirement that Truffle languages be written in Java, they just do it that way because Java gives closest control over the bytecode which is generated. But Kotlin generates bytecode that's very similar to what Java creates, so you could use it and get a more modern syntax.
At any rate, I can guarantee you that adjusting an existing language to be less verbose or more to your liking is a lot less effort than building an entire ecosystem of compilers that try to use Rust as their lingua-franca, given that Rust was never designed for this task.
As for what I want from Rust: when I ask for a GC, this doesn't have to be in the compiler. It can be implemented as a library. Access to ASTs is coming in PRs (see the links in the post). And I don't need Rust to change to get a REPL, I just need to fix the darn JIT. I'm only asking Rust to change to support a few features which greatly improve the experience of using Rust as compile target.
Initially Microsoft was going to make it fully native and based on COM, it was called Ext-VOS project from Microsoft Research and the runtime COM+ Runtime.
Eventually they decided to create the CLR instead and things never fully worked out that way.
However with Windows 8 they have gone back to the original idea and WinRT was born. Which is basically the same COM+ Runtime ideas, but using .NET metadata instead of COM type libraries.
On Windows .NET follows a similar idea as mainframes do language interoperability by having the runtime being part of the OS.
The whole problem with GC and JIT implementations as library is that they will never be as good as the ones that work together with the compiler.
There are many types of optimization algorithms that require an helping hand of the compiler how the data structures and specific code patterns get generated.
Of course it depends what are the goals in terms of performance, throughput and latency.
(rust-gc already exists, but it can be far more efficient with some compiler support. I would recommend waiting for that.)
This post oversimplifies the problem of language interoperability. Interop is not limited because of lack of a common target. Every platform/OS combination has a well-defined ABI. Most languages have facilities to use functions that conform to this ABI and most can also export functions which use the ABI. The choice of LLVM has nothing to do with it -- LLVM simply uses the ABI. The fact that many compilers use LLVM is not because a hand-rolled solution couldn't implement this ABI, but rather because LLVM is easy to use.
As for Haskell, I agree that it doesn't fit into this language vision. Both its lazy semantics and type system would be difficult to fit into the model I suggest.
The kindest thing I can say about this article is "simplistic".
The #line directive in C is limited, at best. Debugging flex/lex/yacc/bison, for instance, is sketchy at best. But of course line numbers are only part of the problem. If someone really wants to create Spiffy New Language as a Rust-front, then SNL structures/objects/collections/whoozits will want to pass symbolic information to the debugger so that users can explore their data structures using meaningful names.
And even so, this assumes that with debug symbols on, you can turn optimization off. Debugging optimized code gets wacky very fast because associating line numbers to source is not always possible any more, and gives non-intuitive results due to code motion and inlining even when it is possible. (You haven't lived until you've seen gdb's source line pointer jump around like a weasel on crack due to code re-arrangement.)
At Rust's current level of maturity, I suspect there are bigger fish to fry than passing debug info from Rust-fronts, so rejecting ambitious debug symbol machinery is probably the right strategic decision for the time being.
What? The static typing guarantees should be checked (statically!) by the compiler, so the choice of language you emit doesn't need to affect what kind of type system you can design your input language to accept.
And please refrain from ad hominem. It adds little to the conversation.
std::vector<int> foo = ...;
for (iter = foo.begin(); iter != foo.end(); ++iter) {
*iter += 1;
foo[0] += *iter;
}
A naive translation to Rust would run afoul of the borrow checker. If we are to compile C++ to Rust, how are we to address this? Should we simply generate unsafe Rust?The point is to translate new, generally higher level languages to rust. These won't fall afoul of the borrow checker if handled right. I suspect Rust will not have a major restricting effect on their design either. A lot of the borrow checker issues can be papered over with sufficient codegen. When I was working on rust-gc, I often remarked that if we wrote some codegen plugins that convert all types to `Gc<RefCell<Trait>>`, we're effectively Java ;) (Most of this papering over can be done in a way that avoids runtime cost, though not this specific simplistic example for Java)
Though there is this thing called Corrode which is trying to translate C into Rust and iirc they are trying to minimize the unsafe usage in the generated code. That may eventually be able to convert your code into an indexed iteration.
(Also, while the specific code you wrote is safe, if the mutation being performed were more complicated with a non-primitive, it could lead to segfaults)
How would one transpile this code to Rust? Or is the idea that every language ought to have Rust-style semantics? If so, it's hard to reconcile that with "Rust is the new LLVM," since LLVM does not demand such strict semantics.
let mut foo = vec!(1, 2, 3);
for mut iter in 0..foo.len() {
iter += 1;
foo[0] += iter;
}
No unsafe required, I think.But you didn't quite get away with it. The C++ code increments the value in the array through the iterator, while the above Rust increments the iterator (err, index) itself. So it doesn't produce the same result.
More generally, std::vector in C++ typically implements iterators with just raw pointers. This is quite unsafe, but doesn't impose borrow-checker restrictions on the user. How can such languages be compiled to Rust?
I have to admit that I don't understand you here. Can you elaborate on the difference between the two programs?
I assure you that this post is thought out past the point of just "fanboyism." Have some faith :-)
Consider this fact for example: many languages make use of objects allocated on the heap in a way that prevents to know statically when they are to be disposed; then a GC takes care of that dinamically. How are they going to give Rust the necessary information to track lifetimes, when the information is not there to start with? Of course, one can just write a GC in Rust, but how is this an improvement with respect to a GC written in C?
Also - what about typed languages - such as Go - that do not have generics? These are not going to map well to the Rust type system. Or what about lazy languages? Or languages that save the stack on the heap to implement call/cc?
In short, whenever the semantics is different enough, you will not be able to map to idiomatic Rust constructs, and in fact if you don't want to pay the cost of interpretation, you will probably map to unsafe constructs most of the time.
https://github.com/mystor/rust-callcc is callcc for Rust. Technically abuses a feature for a purpose it was explicitly not intended for, but meh :)
callcc and gc are usually not useful operations in rust. That doesn't mean that its not possible to implement them. The implementation might be annoying to use, but of you are codegenning to rust this doesn't matter.
Yes, some semantics won't copy over. I feel like most would though. Those that don't can often be emulated at the lower level with enough codegen.
And Rust-as-a-target doesn't necessarily mean you're doing it for the borrow checker. It could also be the typesystem (with the perf and safety of lower level code as a unique bonus). Yes, other, better, typesystems exist, but nobody's saying that Rust is the only language you can do this with :)
(The LLVM backend is known to produce better-optimized code, but the compile times are slower.)
And/or you could do what Rust and Swift are doing (with MIR and SIL, respectively), and define your own ASM-like language between your parsed AST and LLVM IR. That way you can do high-level optimizations, static analysis, etc. before you drop too far down and lose much context.
As an aside it may be interesting if this could be "Target MIR", but that's a future prospect
You might be interested in checking out Dyon
APL implementation:
https://www.youtube.com/watch?v=XVv1GipR5yU
As a code generator for the Go assembler:
"Second, LLVM is a simpler language to target than traditional assembly languages—it has nice features like infinite registers and recently support for stack frames."
Aren't stack frames a basic component of any run time? How was support for those only recently added? Maybe I am not fully understanding the context. I looked at this docs but it didn't clear it up for me.
I'm not trying to nitpick here but CPUs are interpreters of binary words. I think that sentence might be misleading to someone.