Bug 1732 – Mixin can not be instantiated

Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D1 (retired)
Platform
x86
OS
Windows
Creation time
2007-12-16T08:19:00Z
Last change time
2014-02-24T15:33:21Z
Keywords
rejects-valid
Assigned to
bugzilla
Creator
aarti
Blocks
1734

Comments

Comment #0 by aarti — 2007-12-16T08:19:27Z
template init() { a = 5; } void main() { int a; mixin init; } it doesn't compile, but it should. According to specs mixin should be evaluated in the context of its instantiation. Also another examples, in specs suggest that it should be allowed. Probably also 2.0 issue.
Comment #1 by matti.niemenmaa+dbugzilla — 2007-12-16T08:59:58Z
Templates can only contain declarations, not statements. The template alone is invalid. As http://www.digitalmars.com/d/1.0/template.html says: "The body of the TemplateDeclaration must be syntactically correct even if never instantiated. Semantic analysis is not done until instantiated. A template forms its own scope, and the template body can contain classes, structs, types, enums, variables, functions, and other templates." Your template is syntactically invalid, as it doesn't contain a DeclDef but an AssignExpression.
Comment #2 by aarti — 2007-12-16T09:24:36Z
Maybe, but I still find it very strange that following works: ---- import std.stdio; template init() { void func() {writefln(a);} } void main() { int a; mixin init; func(); } I see no real (practical) difference between both examples. I would say that they should be both invalid or both valid.
Comment #3 by matti.niemenmaa+dbugzilla — 2007-12-16T10:14:36Z
The difference is that one imports a declaration while the other imports a statement. The init() with a function could be mixed in at global scope or class scope, whereas the "a = 5" one only works at function scope. I see where you're coming from, though: some sort of implicitness here might be handy. For instance, if a template contains statements, it is allowed only as a mixin at function scope. That is: template T() { statements } void foo() { mixin T; } Could be equivalent to: template T() { void __unique_internal_name() { statements } } void foo() { mixin T; __unique_internal_name(); } And you get inlining for free.
Comment #4 by aarti — 2007-12-16T12:02:55Z
I think about the issue differently. For me its more consistency issue. It should be just enough when compiler checks: 1. if template body is syntacticly correct (but not as a whole, so variables doesn't have to be declared) 2. compiler instantiates template or paste mixin, then it tries to compile it as a whole That should be enough to use it. But when I think about it, this probably will cause problems for compiler (more compilations than necessary). And probably that's why macros will be introduced...
Comment #5 by aarti — 2007-12-16T13:03:00Z
I will make from this improvement request as I think current state is just wrong. Will at least work as issue tracker...