Templates are way lazy. Is this expected behaviour?
Ary Borenszweig
ary at esperanto.org.ar
Fri Apr 25 15:46:26 PDT 2008
First I'll post the new thing I learned today about D, then I'll explain
why I made this experiment.
I have a module named "other":
---
module other;
class Something {
char[] name = "other";
}
template Foo() {
Something something;
static this() {
something = new Something();
}
}
---
Then I have a module named "main":
---
module main;
import std.stdio;
import other;
mixin Foo!();
void main() {
writefln("%s", something.name);
}
---
The output of compiling and running this is: other
Now... I modify "main" like this:
---
module main;
import std.stdio;
import other;
// Here is the change, I added this
class Something {
char[] name = "main";
}
mixin Foo!();
void main() {
writefln("%s", something.name);
}
---
The output of compiling and running this is: main
Not only that. If I change it to this:
---
module main;
import std.stdio;
import other;
class Something {
// Here is the change this time
char[] nameX = "main";
}
mixin Foo!();
void main() {
writefln("%s", something.name);
}
---
I can't compile main anymore:
main.d(15): Error: no property 'name' for type 'main.Something'
So, basically, I can change a template's instantiation by overriding the
symbols it uses. Is that expected behaviour?
I did the experiment because you currently don't get autocompletion or
any cool stuff in Descent inside templates (as well as inside templated
classes and functions), and won't probably in the next release. Why?
Because these features rely heavily in DMD's semantic, but semantic
isn't done for templates, not even checking that an identifier resolves
correctly, until they are instantiated. So in the above example:
---
module other;
class Something {
char[] name = "other";
}
template Foo() {
Something something;
static this() {
something. // I'd like to suggest you the field "name",
// but who knows if it even exists!
}
}
---
I know, no one will do that, but because template logic is evaluated at
the location of the instantiation, I'd like to ask: could templates have
at least some kind of semantic analysis done? I'd like the compiler to
show an error if "Something" is not defined in the module I defined the
template. What I do with template parameters doesn't care, but at least
some kind of logic...
More information about the Digitalmars-d
mailing list