Can swift be a self-hosted language?

I guess swift as a language itself is sufficient to become a self-hosted language.

Will it be the direction?

Parts of the Swift compiler are being written in Swift, but last I heard it's not a goal to actually rewrite the compiler in Swift entirely.

3 Likes

Many languages can do it in theory, but very few do now, because that would mean giving up LLVM.

Being self hosted doesn't mean you have to give up LLVM. Rust is self hosted and uses LLVM.

2 Likes

How so, since LLVM is written in C++, that means the Rust compiler is not self-hosted? As Jon says, many compilers are partially written in their own language, but full self-hosting is rarer now that many languages use LLVM for codegen.

Edit: If you mean that you can always maintain both the LLVM version and the self-hosted version, sure, but in practice one of them usually suffers as the other is the mostly used one.

They have a very small portion of the compiler that is written in C++ whose sole purpose is just talk to LLVM. rust/compiler/rustc_llvm/llvm-wrapper at main · rust-lang/rust · GitHub. Everything else is in Rust. LLVM also has a C api that can easily be called to from with enough extern C.

1 Like

IIRC rustc can be compiled with cranelift, so you technically don't need LLVM at all.

1 Like

It's worth noting that there are some not-insubstantial tradeoffs involved in choosing to use LLVM's C API, since it doesn't try to have parity with C++ (on the other hand, it's more stable across releases, so your code will be broken by LLVM updates less frequently).

4 Likes

As one of its former maintainers - to violently agree with you - that stability is a bit of an illusion. There was a time the C API promised some kind of backwards-compatibility but the details of that were never well defined and various parts of the API will certainly compile but have had their implementations stripped for one reason or another...

Swift has C++ interop, that should be the route any LLVM bindings would take in future.

2 Likes

Yeah, note I was careful to say "more stable," not "stable". :joy:

(And in as much as it's more stable, that's partially due to neglect.)

Also noting that the Swift compiler also deeply integrates with Clang, not just LLVM, and Clang has never had a C API that supports codegen (unless I am way out of date).

1 Like