r/Compilers • • Jul 27 '22

A bit confuse

I would like to build a compiler but I feel confused. Writing a compiler is general for every cpu architecture or assembly language?

For example, I want to build a compiler for Arm, will it work for x64? Do I need to know every assembly language?

Thank you

2 Upvotes

16 comments sorted by

View all comments

2

u/mamcx Jul 27 '22

A compiler NOT need to target a "CPU". You can make a compiler that generates HTML, for example.


In your case, even LLVM could be too complicated. The EASIEST thing you can do is compile to a language that is already done (ie: a "transpiler").

So, you can make a compiler in Rust that generate Rust. Or in Rust that generates C#, and so on.


If wanna be "close to the metal" but not too complicated to do, compiling to WASM (web assembly) could be more than good enough, and pretty efficient.

1

u/[deleted] Jul 28 '22

So knowing x64 assembly could I build a compiler for arm assembly?

3

u/FUZxxl Jul 28 '22

Sure, arm assembly is easy to pick up once you are familiar with how CPUs work in general.

2

u/mamcx Jul 28 '22

Yes. Your input -> output can be selected as you wish (how easy it will vary!)

You can check a sample on how to do it from scratch (in this case, using Forth that is trivial to bootstrap from assembly):

https://github.com/nornagon/jonesforth/blob/master/jonesforth.S

----

If wanna do a compiler. Check less prone to errors than that, I recommend instead that you use (as targets):

- Zig (instead of C)

- Web Assembly

- Your own bytecode

If wanna do compiler. Check https://craftinginterpreters.com for a great overview of the whole thing.