Grammar details of Delphi’s “type type” feature

If you’re a hardcore VCL geek like me, you probably already know about Delphi’s “type type” feature. But I learned some interesting details about it last night while discovering the Delphi grammar.

The documentation doesn’t give a name to this language construct, so “type type” is a name I made up. It’s when you prepend “type” to a type declaration to give it its own type identity:

type
TColor = type Integer;

I won’t go into any details on what you would use this for, because it’s not that useful for anything outside the Object Inspector. You probably wouldn’t even notice it was a different type if you never used it as a var parameter. But it’s more useful than goto, and I’ve got that in my parser…

Anyway, I found some interesting details about “type type” in my research. Specifically, there are only three type constructs that allow you to prepend “type” to them: identifiers, string, and file.

type
TTypeQualId = type System.Integer; // or any (qualified) identifier
TTypeString = type string;
TTypeFile = type file;

No variations on these are allowed, and no other types are allowed (I tried every type in the Delphi grammar):

type
TTypeStringOfLength = type string[42]; // compiler error
TTypeFileOfType = type file of Integer; // compiler error

I suspect the reason for this is that (according to the documentation) every time you declare something like string[42], it’s automatically considered a distinct type from every other string[42] you’ve ever defined — and therefore has its own RTTI identity, and isn’t var-parameter compatible with the others. You don’t need to declare type string[42] because it’s already distinct.

I found type file to be particularly interesting. Even if you’re dealing with an untyped file — the ones where you have to pass that second parameter to Reset and Rewrite to make them even remotely useful, the ones that have been utterly replaced by TStream — you can still make distinct types, and let the compiler make sure you pass the right ones to your var parameters. That’s actually an interesting feature, since file parameters always have to be var. I wonder if anybody has ever used this.

Update: Sébastien Doeraene, alias sjrd, posted some good details about “type type” in the comments, including how this construct affects the IDE’s autocompletion features and the distinction with type aliases.

Leave a Reply

Your email address will not be published. Required fields are marked *