HACKER Q&A
📣 ghoward

How Much Do You Dislike Forward Declarations and Why?


I'm working on a programming language. For various reasons, it is a one-pass language that requires forward declarations.

However, [1] is criticizing Carbon's requirement for forward declarations, and it has many upvotes. This indicates that dislike for forward declarations is widespread and popular.

I've never hated forward declarations. I also work almost exclusively in C, so I'm used to them.

Yes, C makes them terrible with the header system. However, my language will use packages, which means that you don't need to forward declare everything; just the items in the same package (well, file) that refer to each other, such as mutually recursive functions or types that have pointers to each other.

Do you hate forward declarations enough that that would be a deal-breaker for using such a language? Why?

The technical details for my language: instead of defining macros like Rust, users can define new keywords. The keyword definition is responsible for parsing the tokens after the keyword, but it can generate whatever code it wants. If I made my compiler multi-pass, it would require all users who define keywords to make their parsing work with those multiple passes, which is doable, but I think it's too much.

I also chose defining keywords over macros because macros can be stateful (I think they might be in Rust), and requiring multiple passes makes keywords stateful too. For example, when defining a function (which uses a keyword), the first pass has to define it with its parameters and its return type, but then parse the body normally while generating nothing. Then, in the next pass, it needs to recognize that the function already exists, check that they are the same, and then parse the function body.

I can make it easy for keywords to know what state they are in, but they still have to act differently in each state.

Bonus question: if you can think of a way for my language to not require forward declarations while remaining a single-pass compiler, I'd love to hear it.

[1]: https://old.reddit.com/r/programming/comments/wiaggd/how_carbon_fixes_c_syntax/ijaeyna/


  👤 mmphosis Accepted Answer ✓
It depends who you are creating the language for. If the language is for the computer so that it can compile in a single pass then maybe forward declarations are a way.

When I write code, I don't want it cluttered with boilerplate and dependency declarations. And when I read code, I don't want it cluttered with boilerplate and dependency declarations. The problem is not your language, the problem is packages and the dependency hell they will create. There are no deal-breakers, just compromises.


👤 jjgreen
Long-time C user: I don't mind them at all, there are only a few which are extern so need to be in the header, and static ones are rarely needed if you write "upside down".