]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/attributes.md
New upstream version 1.18.0+dfsg1
[rustc.git] / src / doc / reference / src / attributes.md
1 # Attributes
2
3 Any item declaration may have an _attribute_ applied to it. Attributes in Rust
4 are modeled on Attributes in ECMA-335, with the syntax coming from ECMA-334
5 (C#). An attribute is a general, free-form metadatum that is interpreted
6 according to name, convention, and language and compiler version. Attributes
7 may appear as any of:
8
9 * A single identifier, the attribute name
10 * An identifier followed by the equals sign '=' and a literal, providing a
11 key/value pair
12 * An identifier followed by a parenthesized list of sub-attribute arguments
13
14 Attributes with a bang ("!") after the hash ("#") apply to the item that the
15 attribute is declared within. Attributes that do not have a bang after the hash
16 apply to the item that follows the attribute.
17
18 An example of attributes:
19
20 ```rust
21 // General metadata applied to the enclosing module or crate.
22 #![crate_type = "lib"]
23
24 // A function marked as a unit test
25 #[test]
26 fn test_foo() {
27 /* ... */
28 }
29
30 // A conditionally-compiled module
31 #[cfg(target_os="linux")]
32 mod bar {
33 /* ... */
34 }
35
36 // A lint attribute used to suppress a warning/error
37 #[allow(non_camel_case_types)]
38 type int8_t = i8;
39 ```
40
41 > **Note:** At some point in the future, the compiler will distinguish between
42 > language-reserved and user-available attributes. Until then, there is
43 > effectively no difference between an attribute handled by a loadable syntax
44 > extension and the compiler.
45
46 ## Crate-only attributes
47
48 - `crate_name` - specify the crate's crate name.
49 - `crate_type` - see [linkage](linkage.html).
50 - `feature` - see [compiler features](#compiler-features).
51 - `no_builtins` - disable optimizing certain code patterns to invocations of
52 library functions that are assumed to exist
53 - `no_main` - disable emitting the `main` symbol. Useful when some other
54 object being linked to defines `main`.
55 - `no_start` - disable linking to the `native` crate, which specifies the
56 "start" language item.
57 - `no_std` - disable linking to the `std` crate.
58 - `plugin` - load a list of named crates as compiler plugins, e.g.
59 `#![plugin(foo, bar)]`. Optional arguments for each plugin,
60 i.e. `#![plugin(foo(... args ...))]`, are provided to the plugin's
61 registrar function. The `plugin` feature gate is required to use
62 this attribute.
63 - `recursion_limit` - Sets the maximum depth for potentially
64 infinitely-recursive compile-time operations like
65 auto-dereference or macro expansion. The default is
66 `#![recursion_limit="64"]`.
67 - `windows_subsystem` - Indicates that when this crate is linked for a Windows
68 target it will configure the resulting binary's
69 [subsystem] via the linker. Valid values for this
70 attribute are `console` and `windows`, corresponding to
71 those two respective subsystems. More subsystems may be
72 allowed in the future, and this attribute is ignored on
73 non-Windows targets.
74
75 [subsystem]: https://msdn.microsoft.com/en-us/library/fcc1zstk.aspx
76
77 ### Module-only attributes
78
79 - `no_implicit_prelude` - disable injecting `use std::prelude::*` in this
80 module.
81 - `path` - specifies the file to load the module from. `#[path="foo.rs"] mod
82 bar;` is equivalent to `mod bar { /* contents of foo.rs */ }`. The path is
83 taken relative to the directory that the current module is in.
84
85 ## Function-only attributes
86
87 - `main` - indicates that this function should be passed to the entry point,
88 rather than the function in the crate root named `main`.
89 - `plugin_registrar` - mark this function as the registration point for
90 [compiler plugins][plugin], such as loadable syntax extensions.
91 - `start` - indicates that this function should be used as the entry point,
92 overriding the "start" language item. See the "start" [language
93 item](#language-items) for more details.
94 - `test` - indicates that this function is a test function, to only be compiled
95 in case of `--test`.
96 - `ignore` - indicates that this test function is disabled.
97 - `should_panic` - indicates that this test function should panic, inverting the success condition.
98 - `cold` - The function is unlikely to be executed, so optimize it (and calls
99 to it) differently.
100 - `naked` - The function utilizes a custom ABI or custom inline ASM that requires
101 epilogue and prologue to be skipped.
102
103 ## Static-only attributes
104
105 - `thread_local` - on a `static mut`, this signals that the value of this
106 static may change depending on the current thread. The exact consequences of
107 this are implementation-defined.
108
109 ## FFI attributes
110
111 On an `extern` block, the following attributes are interpreted:
112
113 - `link_args` - specify arguments to the linker, rather than just the library
114 name and type. This is feature gated and the exact behavior is
115 implementation-defined (due to variety of linker invocation syntax).
116 - `link` - indicate that a native library should be linked to for the
117 declarations in this block to be linked correctly. `link` supports an optional
118 `kind` key with three possible values: `dylib`, `static`, and `framework`. See
119 [external blocks](items.html#external-blocks) for more about external blocks. Two
120 examples: `#[link(name = "readline")]` and
121 `#[link(name = "CoreFoundation", kind = "framework")]`.
122 - `linked_from` - indicates what native library this block of FFI items is
123 coming from. This attribute is of the form `#[linked_from = "foo"]` where
124 `foo` is the name of a library in either `#[link]` or a `-l` flag. This
125 attribute is currently required to export symbols from a Rust dynamic library
126 on Windows, and it is feature gated behind the `linked_from` feature.
127
128 On declarations inside an `extern` block, the following attributes are
129 interpreted:
130
131 - `link_name` - the name of the symbol that this function or static should be
132 imported as.
133 - `linkage` - on a static, this specifies the [linkage
134 type](http://llvm.org/docs/LangRef.html#linkage-types).
135
136 On `enum`s:
137
138 - `repr` - on C-like enums, this sets the underlying type used for
139 representation. Takes one argument, which is the primitive
140 type this enum should be represented for, or `C`, which specifies that it
141 should be the default `enum` size of the C ABI for that platform. Note that
142 enum representation in C is undefined, and this may be incorrect when the C
143 code is compiled with certain flags.
144
145 On `struct`s:
146
147 - `repr` - specifies the representation to use for this struct. Takes a list
148 of options. The currently accepted ones are `C` and `packed`, which may be
149 combined. `C` will use a C ABI compatible struct layout, and `packed` will
150 remove any padding between fields (note that this is very fragile and may
151 break platforms which require aligned access).
152
153 ## Macro-related attributes
154
155 - `macro_use` on a `mod` — macros defined in this module will be visible in the
156 module's parent, after this module has been included.
157
158 - `macro_use` on an `extern crate` — load macros from this crate. An optional
159 list of names `#[macro_use(foo, bar)]` restricts the import to just those
160 macros named. The `extern crate` must appear at the crate root, not inside
161 `mod`, which ensures proper function of the [`$crate` macro
162 variable](../book/first-edition/macros.html#the-variable-crate).
163
164 - `macro_reexport` on an `extern crate` — re-export the named macros.
165
166 - `macro_export` - export a macro for cross-crate usage.
167
168 - `no_link` on an `extern crate` — even if we load this crate for macros, don't
169 link it into the output.
170
171 See the [macros section of the
172 book](../book/first-edition/macros.html#scoping-and-macro-importexport) for more information on
173 macro scope.
174
175 ## Miscellaneous attributes
176
177 - `deprecated` - mark the item as deprecated; the full attribute is
178 `#[deprecated(since = "crate version", note = "...")`, where both arguments
179 are optional.
180 - `export_name` - on statics and functions, this determines the name of the
181 exported symbol.
182 - `link_section` - on statics and functions, this specifies the section of the
183 object file that this item's contents will be placed into.
184 - `no_mangle` - on any item, do not apply the standard name mangling. Set the
185 symbol for this item to its identifier.
186 - `simd` - on certain tuple structs, derive the arithmetic operators, which
187 lower to the target's SIMD instructions, if any; the `simd` feature gate
188 is necessary to use this attribute.
189 - `unsafe_destructor_blind_to_params` - on `Drop::drop` method, asserts that the
190 destructor code (and all potential specializations of that code) will
191 never attempt to read from nor write to any references with lifetimes
192 that come in via generic parameters. This is a constraint we cannot
193 currently express via the type system, and therefore we rely on the
194 programmer to assert that it holds. Adding this to a Drop impl causes
195 the associated destructor to be considered "uninteresting" by the
196 Drop-Check rule, and thus it can help sidestep data ordering
197 constraints that would otherwise be introduced by the Drop-Check
198 rule. Such sidestepping of the constraints, if done incorrectly, can
199 lead to undefined behavior (in the form of reading or writing to data
200 outside of its dynamic extent), and thus this attribute has the word
201 "unsafe" in its name. To use this, the
202 `unsafe_destructor_blind_to_params` feature gate must be enabled.
203 - `doc` - Doc comments such as `/// foo` are equivalent to `#[doc = "foo"]`.
204 - `rustc_on_unimplemented` - Write a custom note to be shown along with the error
205 when the trait is found to be unimplemented on a type.
206 You may use format arguments like `{T}`, `{A}` to correspond to the
207 types at the point of use corresponding to the type parameters of the
208 trait of the same name. `{Self}` will be replaced with the type that is supposed
209 to implement the trait but doesn't. To use this, the `on_unimplemented` feature gate
210 must be enabled.
211 - `must_use` - on structs and enums, will warn if a value of this type isn't used or
212 assigned to a variable. You may also include an optional message by using
213 `#[must_use = "message"]` which will be given alongside the warning.
214
215 ### Conditional compilation
216
217 Sometimes one wants to have different compiler outputs from the same code,
218 depending on build target, such as targeted operating system, or to enable
219 release builds.
220
221 Configuration options are boolean (on or off) and are named either with a
222 single identifier (e.g. `foo`) or an identifier and a string (e.g. `foo = "bar"`;
223 the quotes are required and spaces around the `=` are unimportant). Note that
224 similarly-named options, such as `foo`, `foo="bar"` and `foo="baz"` may each be set
225 or unset independently.
226
227 Configuration options are either provided by the compiler or passed in on the
228 command line using `--cfg` (e.g. `rustc main.rs --cfg foo --cfg 'bar="baz"'`).
229 Rust code then checks for their presence using the `#[cfg(...)]` attribute:
230
231 ```rust
232 // The function is only included in the build when compiling for macOS
233 #[cfg(target_os = "macos")]
234 fn macos_only() {
235 // ...
236 }
237
238 // This function is only included when either foo or bar is defined
239 #[cfg(any(foo, bar))]
240 fn needs_foo_or_bar() {
241 // ...
242 }
243
244 // This function is only included when compiling for a unixish OS with a 32-bit
245 // architecture
246 #[cfg(all(unix, target_pointer_width = "32"))]
247 fn on_32bit_unix() {
248 // ...
249 }
250
251 // This function is only included when foo is not defined
252 #[cfg(not(foo))]
253 fn needs_not_foo() {
254 // ...
255 }
256 ```
257
258 This illustrates some conditional compilation can be achieved using the
259 `#[cfg(...)]` attribute. `any`, `all` and `not` can be used to assemble
260 arbitrarily complex configurations through nesting.
261
262 The following configurations must be defined by the implementation:
263
264 * `target_arch = "..."` - Target CPU architecture, such as `"x86"`,
265 `"x86_64"` `"mips"`, `"powerpc"`, `"powerpc64"`, `"arm"`, or
266 `"aarch64"`. This value is closely related to the first element of
267 the platform target triple, though it is not identical.
268 * `target_os = "..."` - Operating system of the target, examples
269 include `"windows"`, `"macos"`, `"ios"`, `"linux"`, `"android"`,
270 `"freebsd"`, `"dragonfly"`, `"bitrig"` , `"openbsd"` or
271 `"netbsd"`. This value is closely related to the second and third
272 element of the platform target triple, though it is not identical.
273 * `target_family = "..."` - Operating system family of the target, e. g.
274 `"unix"` or `"windows"`. The value of this configuration option is defined
275 as a configuration itself, like `unix` or `windows`.
276 * `unix` - See `target_family`.
277 * `windows` - See `target_family`.
278 * `target_env = ".."` - Further disambiguates the target platform with
279 information about the ABI/libc. Presently this value is either
280 `"gnu"`, `"msvc"`, `"musl"`, or the empty string. For historical
281 reasons this value has only been defined as non-empty when needed
282 for disambiguation. Thus on many GNU platforms this value will be
283 empty. This value is closely related to the fourth element of the
284 platform target triple, though it is not identical. For example,
285 embedded ABIs such as `gnueabihf` will simply define `target_env` as
286 `"gnu"`.
287 * `target_endian = "..."` - Endianness of the target CPU, either `"little"` or
288 `"big"`.
289 * `target_pointer_width = "..."` - Target pointer width in bits. This is set
290 to `"32"` for targets with 32-bit pointers, and likewise set to `"64"` for
291 64-bit pointers.
292 * `target_has_atomic = "..."` - Set of integer sizes on which the target can perform
293 atomic operations. Values are `"8"`, `"16"`, `"32"`, `"64"` and `"ptr"`.
294 * `target_vendor = "..."` - Vendor of the target, for example `apple`, `pc`, or
295 simply `"unknown"`.
296 * `test` - Enabled when compiling the test harness (using the `--test` flag).
297 * `debug_assertions` - Enabled by default when compiling without optimizations.
298 This can be used to enable extra debugging code in development but not in
299 production. For example, it controls the behavior of the standard library's
300 `debug_assert!` macro.
301
302 You can also set another attribute based on a `cfg` variable with `cfg_attr`:
303
304 ```rust,ignore
305 #[cfg_attr(a, b)]
306 ```
307
308 This is the same as `#[b]` if `a` is set by `cfg`, and nothing otherwise.
309
310 Lastly, configuration options can be used in expressions by invoking the `cfg!`
311 macro: `cfg!(a)` evaluates to `true` if `a` is set, and `false` otherwise.
312
313 ### Lint check attributes
314
315 A lint check names a potentially undesirable coding pattern, such as
316 unreachable code or omitted documentation, for the static entity to which the
317 attribute applies.
318
319 For any lint check `C`:
320
321 * `allow(C)` overrides the check for `C` so that violations will go
322 unreported,
323 * `deny(C)` signals an error after encountering a violation of `C`,
324 * `forbid(C)` is the same as `deny(C)`, but also forbids changing the lint
325 level afterwards,
326 * `warn(C)` warns about violations of `C` but continues compilation.
327
328 The lint checks supported by the compiler can be found via `rustc -W help`,
329 along with their default settings. [Compiler
330 plugins][unstable book plugin] can provide additional lint checks.
331
332 ```rust,ignore
333 pub mod m1 {
334 // Missing documentation is ignored here
335 #[allow(missing_docs)]
336 pub fn undocumented_one() -> i32 { 1 }
337
338 // Missing documentation signals a warning here
339 #[warn(missing_docs)]
340 pub fn undocumented_too() -> i32 { 2 }
341
342 // Missing documentation signals an error here
343 #[deny(missing_docs)]
344 pub fn undocumented_end() -> i32 { 3 }
345 }
346 ```
347
348 This example shows how one can use `allow` and `warn` to toggle a particular
349 check on and off:
350
351 ```rust
352 #[warn(missing_docs)]
353 pub mod m2{
354 #[allow(missing_docs)]
355 pub mod nested {
356 // Missing documentation is ignored here
357 pub fn undocumented_one() -> i32 { 1 }
358
359 // Missing documentation signals a warning here,
360 // despite the allow above.
361 #[warn(missing_docs)]
362 pub fn undocumented_two() -> i32 { 2 }
363 }
364
365 // Missing documentation signals a warning here
366 pub fn undocumented_too() -> i32 { 3 }
367 }
368 ```
369
370 This example shows how one can use `forbid` to disallow uses of `allow` for
371 that lint check:
372
373 ```rust,ignore
374 #[forbid(missing_docs)]
375 pub mod m3 {
376 // Attempting to toggle warning signals an error here
377 #[allow(missing_docs)]
378 /// Returns 2.
379 pub fn undocumented_too() -> i32 { 2 }
380 }
381 ```
382
383 ### Language items
384
385 Some primitive Rust operations are defined in Rust code, rather than being
386 implemented directly in C or assembly language. The definitions of these
387 operations have to be easy for the compiler to find. The `lang` attribute
388 makes it possible to declare these operations. For example, the `str` module
389 in the Rust standard library defines the string equality function:
390
391 ```rust,ignore
392 #[lang = "str_eq"]
393 pub fn eq_slice(a: &str, b: &str) -> bool {
394 // details elided
395 }
396 ```
397
398 The name `str_eq` has a special meaning to the Rust compiler, and the presence
399 of this definition means that it will use this definition when generating calls
400 to the string equality function.
401
402 The set of language items is currently considered unstable. A complete
403 list of the built-in language items will be added in the future.
404
405 ### Inline attributes
406
407 The inline attribute suggests that the compiler should place a copy of
408 the function or static in the caller, rather than generating code to
409 call the function or access the static where it is defined.
410
411 The compiler automatically inlines functions based on internal heuristics.
412 Incorrectly inlining functions can actually make the program slower, so it
413 should be used with care.
414
415 `#[inline]` and `#[inline(always)]` always cause the function to be serialized
416 into the crate metadata to allow cross-crate inlining.
417
418 There are three different types of inline attributes:
419
420 * `#[inline]` hints the compiler to perform an inline expansion.
421 * `#[inline(always)]` asks the compiler to always perform an inline expansion.
422 * `#[inline(never)]` asks the compiler to never perform an inline expansion.
423
424 ### `derive`
425
426 The `derive` attribute allows certain traits to be automatically implemented
427 for data structures. For example, the following will create an `impl` for the
428 `PartialEq` and `Clone` traits for `Foo`, the type parameter `T` will be given
429 the `PartialEq` or `Clone` constraints for the appropriate `impl`:
430
431 ```rust
432 #[derive(PartialEq, Clone)]
433 struct Foo<T> {
434 a: i32,
435 b: T,
436 }
437 ```
438
439 The generated `impl` for `PartialEq` is equivalent to
440
441 ```rust
442 # struct Foo<T> { a: i32, b: T }
443 impl<T: PartialEq> PartialEq for Foo<T> {
444 fn eq(&self, other: &Foo<T>) -> bool {
445 self.a == other.a && self.b == other.b
446 }
447
448 fn ne(&self, other: &Foo<T>) -> bool {
449 self.a != other.a || self.b != other.b
450 }
451 }
452 ```
453
454 You can implement `derive` for your own type through [procedural
455 macros](procedural-macros.html).
456
457 ### Compiler Features
458
459 Certain aspects of Rust may be implemented in the compiler, but they're not
460 necessarily ready for every-day use. These features are often of "prototype
461 quality" or "almost production ready", but may not be stable enough to be
462 considered a full-fledged language feature.
463
464 For this reason, Rust recognizes a special crate-level attribute of the form:
465
466 ```rust,ignore
467 #![feature(feature1, feature2, feature3)]
468 ```
469
470 This directive informs the compiler that the feature list: `feature1`,
471 `feature2`, and `feature3` should all be enabled. This is only recognized at a
472 crate-level, not at a module-level. Without this directive, all features are
473 considered off, and using the features will result in a compiler error.
474
475 The currently implemented features of the reference compiler are documented in
476 [The Unstable Book].
477
478 If a feature is promoted to a language feature, then all existing programs will
479 start to receive compilation warnings about `#![feature]` directives which enabled
480 the new feature (because the directive is no longer necessary). However, if a
481 feature is decided to be removed from the language, errors will be issued (if
482 there isn't a parser error first). The directive in this case is no longer
483 necessary, and it's likely that existing code will break if the feature isn't
484 removed.
485
486 If an unknown feature is found in a directive, it results in a compiler error.
487 An unknown feature is one which has never been recognized by the compiler.
488
489 [The Unstable Book]: https://doc.rust-lang.org/nightly/unstable-book/
490 [unstable book plugin]: ../unstable-book/language-features/plugin.html#lint-plugins