NICUP14 / MiniLang

A type-safe C successor that compiles directly to various platforms.
MIT License
137 stars 3 forks source link

Why do we need macros in the first place? #5

Open xiaodaigh opened 2 weeks ago

xiaodaigh commented 2 weeks ago

Great write-up on macros but it doesn't answer a more fundamental question: why do we need macros in the first place?

It's because the syntax of the code doesn't support what you want or you want to repeat duplicated code that only changes a few things.

NICUP14 commented 2 weeks ago

Great write-up on macros but it doesn't answer a more fundamental question: why do we need macros in the first place?

It's because the syntax of the code doesn't support what you want or you want to repeat duplicated code that only changes a few things.

That's a really good question! The macro system of MiniLang is completely optional (but hear me out). The language is complete to the point that it doesn't require macros to write programs. However, macros provide convenience and simplicity (through flexible and safe AST transformations), which cannot be expressed by the rigid structure of a MiniLang program. The ability to modify statement lists and argument lists greatly simplifies the interaction between function (simple or variadic) and abstracts code generation and transformation behind a macro. The user doesn't necesarily need to know how the macro is implemented to be able to use it effectively.

Take print as an example. It's a recursive and variadic macro which calls a _print helper function (argument type is determined via function overloading of _print), which inturn calls printf. You can definitely use other methods to output values to the console, but print is convenient and safe enough to serve ~90% of output-related tasks. Additionally, the developer isn't concerned about the inner-working of print. He passes a bunch of arguments to print and it outputs them to the console. That's all the developer needs to know to be able to use print effectively.

NICUP14 commented 2 weeks ago

It's also important to mention that macros provide a way to force inlining, compared to languages like C++ where inline is more of a request and reuqires more attention as inline functions need to be defined within the header.