forked from dlang/dlang.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mixin.dd
99 lines (73 loc) · 2.13 KB
/
mixin.dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
Ddoc
$(D_S Mixins,
$(P Mixins (not to be confused with
$(LINK2 template-mixin.html, template mixins))
enable string constants to be compiled as regular D code
and inserted into the program.
Combining this with compile time manipulation of strings
enables the creation of domain-specific languages.
)
$(P For example, here we can create a template that generates
a struct with the named members:
)
---
template GenStruct(string Name, string M1)
{
const char[] GenStruct = "struct " ~ Name ~ "{ int " ~ M1 ~ "; }";
}
mixin(GenStruct!("Foo", "bar"));
---
$(P which generates:)
---
struct Foo { int bar; }
---
$(P Superficially, since D mixins can manipulate text and compile
the result, it has some similar properties to the C preprocessor.
But there are major, fundamental differences:
)
$(UL
$(LI The C preprocessing step occurs $(B before) lexical analysis.
This makes it impossible to lex or parse C without access to
all of the context, including all #include'd files, paths and all
relevant compiler switches.
Mixins occur during semantic analysis, and do not affect
the lexing or parsing process.
Lexing and parsing can still occur without semantic analysis.
)
$(LI The C preprocessor can be used to create what appears to
be different syntax:
$(CCODE
#define BEGIN {
#define END }
BEGIN
int x = 3;
foo(x);
END
)
This monkey business is impossible with mixins.
Mixed in text must form complete declarations,
statements, or expressions.
)
$(LI C macros will affect everything following that has
the same name, even if they are in nested scopes.
C macros cut across all scopes.
This problem is called being not "coding hygenic".
Mixins follow the usual scoping rules, and is
hygenic.
)
$(LI C preprocessing expressions follow a different syntax
and have different semantic rules than the C language.
The C preprocessor is technically a different language.
Mixins are in the same language.
)
$(LI C const declarations and C++ templates are invisible
to C preprocessing.
Mixins can be manipulated using templates and const
declarations.
)
)
)
Macros:
TITLE=Mixins
WIKI=Mixins
CATEGORY_ARTICLES=$0