Skip to content

Commit 9112311

Browse files
mark-i-mpetrochenkov
authored andcommitted
Add the small amount i know about hygiene (#167)
* add the small amount i know about hygiene * use en-dash
1 parent bf2f7c8 commit 9112311

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/macro-expansion.md

+50
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,55 @@ in [`src/libsyntax/ext/tt/macro_parser.rs`][code_mp].
143143

144144
### Hygiene
145145

146+
If you have ever used C/C++ preprocessor macros, you know that there are some
147+
annoying and hard-to-debug gotchas! For example, consider the following C code:
148+
149+
```c
150+
#define DEFINE_FOO struct Bar {int x;}; struct Foo {Bar bar;};
151+
152+
// Then, somewhere else
153+
struct Bar {
154+
...
155+
};
156+
157+
DEFINE_FOO
158+
```
159+
160+
Most people avoid writing C like this – and for good reason: it doesn't
161+
compile. The `struct Bar` defined by the macro clashes names with the `struct
162+
Bar` defined in the code. Consider also the following example:
163+
164+
```c
165+
#define DO_FOO(x) {\
166+
int y = 0;\
167+
foo(x, y);\
168+
}
169+
170+
// Then elsewhere
171+
int y = 22;
172+
DO_FOO(y);
173+
```
174+
175+
Do you see the problem? We wanted to generate a call `foo(22, 0)`, but instead
176+
we got `foo(0, 0)` because the macro defined its own `y`!
177+
178+
These are both examples of _macro hygiene_ issues. _Hygiene_ relates to how to
179+
handle names defined _within a macro_. In particular, a hygienic macro system
180+
prevents errors due to names introduced within a macro. Rust macros are hygienic
181+
in that they do not allow one to write the sorts of bugs above.
182+
183+
At a high level, hygiene within the rust compiler is accomplished by keeping
184+
track of the context where a name is introduced and used. We can then
185+
disambiguate names based on that context. Future iterations of the macro system
186+
will allow greater control to the macro author to use that context. For example,
187+
a macro author may want to introduce a new name to the context where the macro
188+
was called. Alternately, the macro author may be defining a variable for use
189+
only within the macro (i.e. it should not be visible outside the macro).
190+
191+
In rustc, this "context" is tracked via `Span`s.
192+
193+
TODO: what is call-site hygiene? what is def-site hygiene?
194+
146195
TODO
147196
148197
### Procedural Macros
@@ -153,6 +202,7 @@ TODO
153202
154203
TODO
155204
205+
TODO: maybe something about macros 2.0?
156206
157207
158208
[code_dir]: https://github.com/rust-lang/rust/tree/master/src/libsyntax/ext/tt

0 commit comments

Comments
 (0)