[just talk] what if implicitly typed literals were disallowed
Adam D. Ruppe
destructionator at gmail.com
Wed Oct 24 09:38:34 PDT 2012
I'm saying [just talk] because this isn't a serious proposal to
change the D language, I just want to discuss what if.
The thread about string and rep had me bring up my library string
implementation again, and it was shot down because of "auto a =
"foo";" meaning a would not have the library type.
It made me wonder: what if we got rid of literals? Well, can't do
that, we need some kind of building block. But, what if we
required their use to have a clear type?
I'm tempted to say literals should only be used when there is an
explicit type given somewhere
int a = 10; // allowed, explicitly int
auto a = 10; // disallowed, literal 10 has no declared type
int foo(int a) { return 0; /* allowed, explicit type in function
signature */ }
foo(10); // allowed, explicit type in function signature
auto a = 1 + 1; // illegal, the type is still not explicit
int a = 10;
auto b = 10 + a; // legal, a has an explicit type, so b does too
void foo(T)(T a) {}
foo(10); // illegal, T is implicit and it is literals so no go
foo!int(10); // legal
auto a = cast(int) 10; // legal, the cast makes it explicit
Why does this matter? Well it gives you a lot of user defined
capabilities here. Let's combine with the following:
* make the internal type of the literals a special word. _int
instead of int for example. Now int is not a keyword - it is
available to library redefinitions (surely in object.d, but you
can import your own int if you wanted to)
* have the library give them the prettier names. this might be
"alias int = _int;" or it might be struct int { this(_int i) { }
/* custom functionality */}; in other words you can give complete
user defined behavior without name conflicts. This can be
replaced at any time by hacking up your druntime.
* the requirement of being explicit ensures the internal types
don't leak out somewhere unintentionally in templates or other
auto types, so your behavior is always predictable, thus solving
the problem of the library replacement for string
Now using the existing richness for library types, we can
customize everything and put it in without the compiler even
caring.
Of course having to explicitly name literals *somewhere* could be
a major hassle... the code breakage means that part is definitely
out for D (though renaming the compiler types is something we
could do, since the object.d aliases will just work except maybe
for error messages)
But how annoying? Ignoring the reality of the situation, is this
a good idea in theory?
destroy
More information about the Digitalmars-d
mailing list