What type functions mean on a language level

Stefan Koch uplink.coder at googlemail.com
Sat Jan 2 09:28:15 UTC 2021


On Saturday, 2 January 2021 at 08:47:07 UTC, Jacob Carlborg wrote:
> On 2021-01-02 01:05, Stefan Koch wrote:
>
>> Also I am not sure how I want the api to look like.
>> 
>> Perhaps like this?
>> struct StructField
>> {
>>      __type__ type;
>>      string name
>> }
>> __type__ makeStruct (string name, StructField[] fields)
>> {
>>      __struct__ sresult = __interal__magic__makeStruct(name);
>>      foreach(f;fields) { sresult.addField(f.name, f.type); }
>>      return __internal__magic__registerType(sresult);
>> }
>
> I'm not sure if it needs to have an API. Just look at how Zig 
> does it.
>
> __type__ LinkedList(__type__ ElementType)
> {
>     return struct {
>         static struct Node
>         {
>             ElementType element;
>             Node* next;
>             Node* prev;
>         }
>
>         Node* first;
>         Node* last;
>     }
> }
>
> LinkedList(int) list;

The issue here is knowing when the type is complete.
Imagine you did not put int into there, but some template or 
another typefunction result.
At which point can I take the lock and register myself in the 
type universe?
And how do I make sure I don't have to type LinkedList(f(x, g(y), 
j(z))) to reference the type?

I guess I could create the name to just be "LinkedList(f(x, g(y), 
j(z)))" where f(x, g(y), j(z))) is eagerly evaluated, and then 
the name is LinkedList(float) or something like that.

But that seems like reinventing templates with all their 
troubles...
perhaps it's still worthwhile though?

it's certainly better than a string mixin.

> If you want to pass in the field names, I guess you'll have to 
> resort to string mixins. Sure, there could be better 
> alternatives than string mixins, but I think that's a separate 
> issue.
>
>> See the sketch of a possible API above.
>> 
>> And feel free to suggest your own!
>
> Here I've experimented in exposing the compiler AST [1].
>
> [1] 
> https://github.com/jacob-carlborg/druntime/blob/517dafcf54ad73049fb35d1ed5fa2ad6619b9ac4/src/core/ast/expression.d

Hmm I wanted to avoid having to puzzle ast nodes together, as I 
find it rather counter verbose to use.
simple stuff like;
mixin(f(a, b));
becomes
new CallExp(findFunction("f"), [findVariableExpression("a"), 
findVariableExpression("b")].insertIntoTreeInPlace();



More information about the Digitalmars-d mailing list