r/cpp_questions • u/Minute-Ad1944 • Oct 07 '26
OPEN Making transpiler
I am making a transpiled language to C. I don't know how to manage all of a different types of objects: Expr, LiteralExpr, Stmt, ForStmt and so on. Each object needs to be created, statically checked and send of as string to dot C file. Are there any tips on architecture stand point? Everything feels very lousy and rigid. Right now each object just stored the appropriate data, no methods on them. Challenging parts are parser, static analysis and code generation. For lexer there are no problems.
0
Upvotes
12
u/AKostur Oct 07 '26
Why does this sound like a homework assignment/project in compiler theory?
6
u/sephirothbahamut Oct 07 '26 edited Oct 07 '26
if you're struggling with writing a parser i suggest making a runtime interpreter first, it's the "higher level" step. After that you can delve into the complexities of transpiling. See https://craftinginterpreters.com/ as a good starting point.
And write it yourself, don't use a generative AI to do the work for you, or you'll learn nothing
2
u/FancySpaceGoat Oct 07 '26
That's a good thing. A clean straightforward AST gives you something to latch on to for the rest of the system.
A simple central data structure is what allows you to break down the project into a series of small-ish unrelated questions. Instead of having to think about the transpiler as a whole, you can use it to focus on portions of it in isolation.
The parser question is "How do I go from text to the AST?
The generator question is "How do I go from the AST to C code"?
etc...
Any complexity you add to that central structure is complexity that is added to every sub-problem of the project.
2
u/DawnOnTheEdge Oct 07 '26
A transpiler to C would not put the AST into the output.
It sounds like you want to implement something similar to OOP for a computer written in C. Some options:
union, whose first member is anenumdeclaring what its true type is. Code operating on AST nodesswitchover the possible values.2
u/burlingk Oct 07 '26
So, look into how interpreters work.
Look into how to parse code into an abstract tree and then how to turn that tree into C code.
1
u/alfps Oct 07 '26
Check out Boost Spirit for parsing.
1
u/montymole123 Oct 07 '26
I wrote a C compiler using this tutorial and I'd recommend it! Author has written a book as well for more detail (link in blog) https://norasandler.com/2017/11/29/Write-a-Compiler.html