Why we cannot use string in mixins?

Chris Wright via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 27 18:10:35 PST 2016


On Sat, 27 Feb 2016 23:29:49 +0000, mahdi wrote:

> I read this criticism about D on Reddit and it claims that you cannot
> use strings in mixins. Can you please elaborate about this and the
> reason behind it?
> 
> QUOTE:
> Look at strings: they are defined as immutable(char []).

That would be an immutable array pointing to immutable characters. That 
is, you have a (length, pointer) tuple; the tuple and its members can't 
be modified.

In other words, this isn't valid:

  immutable(char[]) s = "hello";
  s = "world";

Because you'd be overwriting the pointer and length properties of `s`.

If `string` were an alias to `immutable(char[])`, that would be pretty 
inconvenient.

Instead, strings are defined as immutable(char)[]. That's a (length, 
pointer) tuple; the length and the pointer are mutable. However, the data 
that the pointer points to cannot be modified.

> "immutable" as in "you could put it in ROM",

immutable means you could mprotect(2) that data as readonly and it 
wouldn't change how the program runs. You can come up with mutable data 
at runtime and then make an immutable copy of it. Arrays, for instance, 
have a special property, idup, that yields an immutable copy. You can 
create a class which can be constructed as an immutable instance.

enum, on the other hand, means that the data (and anything it points to) 
must be known at compile time. It's all in the binary's data segment.

> ... CTFE can't see strings correctly (can't be determined at compile
> time).

CTFE is performed at compile time. The person was complaining that all 
strings must be determined at compile time. This objection doesn't even 
make sense given their misconceptions about the meaning of 'immutable'.

> So rather than fix the compiler
> so that strings can be used in mixins in the way that people expect it
> to work even if that means making them something other than
> immutable(char []), they decided to start using enums where strings
> actually go. Seriously: take the same code and replace 'string "foo"'
> with 'enum "foo"' and it starts to work!

Neither of those examples are valid D syntax.

The person might have observed something like: you can declare a variable 
as a string initialized with a compile-time constant. Then you try to use 
it as a template parameter or a CTFE function parameter. It fails, 
complaining that you tried to use a variable that's not a compile-time 
constant. You replace `string` with `enum` and it works.

In other words, you replace a mutable pointer and length with a compile-
time constant and suddenly you can use it as a compile-time constant. I'm 
sure this is shocking.


More information about the Digitalmars-d-learn mailing list