pervognsen / bitwise

Bitwise is an educational project where we create the software/hardware stack for a computer from scratch.
Other
5.12k stars 212 forks source link

Ion macros #59

Open tjpalmer opened 6 years ago

tjpalmer commented 6 years ago

I don't know what plans exist on macros, and I know there are lots of ways to do them with lots of pros and cons. That said, they are used extensively in the ion compiler in c. They might possibly be worth adding to ion, and in a way familiar to c programmers, but better. Something perhaps to consider, at least.

Here's maybe some syntax for syntactic macros:

macro DO_SOMETHING(x, y) {{{
    // Replacement syntax between braces.
    // Semi heredoc-ish, allow arbitrary number of opening braces,
    // so we can ignore braces in the middle.
    // And yes, this particular macro is useless.
    }
}}}

This requires a prepass and presumably these macros are non-hygienic, like c macros. Some syntax for concatenation or string formatting would also be good, like c.

I'd also recommend they be automatically namespaced like everything else in ion.

One other more innovative idea follows, but it wouldn't cover all use cases of standard syntactic macros. For cases it does cover, it would be more embedded in the language. First start with any old function:

// ** here because this isn't a macro, and we might need to change the pointer.
func buf_push(b: char**, elem: char) {
    buf_fit(b, 1 + buf_len(*b));
    (*b)[buf__hdr(*b).len++] = elem;
}

This function can then be called normally, or else it can be called macro-expanded:

// Type explicit here just to emphasize macro-ized call.
field: CompoundField = parse_expr_compound_field();
// Here, I use a trailing bang to tell the compiler I want it to create an ad hoc
// variation of the original function.
buf_push!(&fields, field);

In this case, I'd still recommend it create a new name-mangled function to match the call site.

As a final possibility of my own, I could also imagine importing packages, including the current package, with redefinitions of types or constants. As for the ad hoc function type replacement, it wouldn't cover all use cases of syntactic macros.

Of course, one could go all out with custom parsers like in Rust or any number of other ideas, but I think all that goes beyond the scope of a c-like language.

tjpalmer commented 6 years ago

And of course, if nothing should be done in this area, that's fine, too. Any option complicates things, but it has impacted translation of the ion compiler to ion, so I felt like listing some ideas I had along the way.

tjpalmer commented 6 years ago

If c-compatible macros go in, the ion compiler still needs to expand them, of course, but I'd be tempted for the c backend to have an option (maybe the default) to also generate the macros as c #define macros instead of the expanded form, as export for c consumers who might want to use them, and to make it easier to compare back to the original.