qwertie / ecsharp

Home of LoycCore, the LES language of Loyc trees, the Enhanced C# parser, the LeMP macro preprocessor, and the LLLPG parser generator.
http://ecsharp.net
Other
172 stars 25 forks source link

how can i define new synatx macros #57

Closed furesoft closed 5 years ago

furesoft commented 5 years ago

hi, how can i define new syntax macros?

qwertie commented 5 years ago

Since EC# doesn't have dynamic syntax, the answer depends on what syntax you want. So what syntax do you want?

furesoft commented 5 years ago

i want a swap operator:

a <-> b

qwertie commented 5 years ago

While EC# doesn't let you use that exact syntax, you can use the backtick operator which has customizable text. Here's how it's supposed to work:

define operator`<->`($a, $b) { G.Swap(ref $a, ref $b); }

void f() {
    int a = 1, b = 2;
    a `<->` b;
}

This assumes you have a swap function called G.Swap (it exists in Loyc.Essentials). Unfortunately when I tried this, the output was incorrect... it came out as G.Swap(a, b) instead of G.Swap(ref a, ref b) so I will have to investigate how the ref modifier got eaten. However you can write it like this to do the swap inline:

define operator`<->`($a, $b) {
    { var _tmp_ = $a; $a = $b; $b = _tmp_; }
}

LeMP macros are not hygienic, so the _tmp_ variable needs to be declared inside its own scope to avoid conflicts when <-> is used more than once in a method.

qwertie commented 5 years ago

I hope that answers your question well enough.