]> git.proxmox.com Git - rustc.git/blob - src/doc/trpl/lang-items.md
8e7504c2f18ea5eb76bba3b5f02857ae98a5e17c
[rustc.git] / src / doc / trpl / lang-items.md
1 % Lang items
2
3 > **Note**: lang items are often provided by crates in the Rust distribution,
4 > and lang items themselves have an unstable interface. It is recommended to use
5 > officially distributed crates instead of defining your own lang items.
6
7 The `rustc` compiler has certain pluggable operations, that is,
8 functionality that isn't hard-coded into the language, but is
9 implemented in libraries, with a special marker to tell the compiler
10 it exists. The marker is the attribute `#[lang = "..."]` and there are
11 various different values of `...`, i.e. various different 'lang
12 items'.
13
14 For example, `Box` pointers require two lang items, one for allocation
15 and one for deallocation. A freestanding program that uses the `Box`
16 sugar for dynamic allocations via `malloc` and `free`:
17
18 ```rust
19 #![feature(lang_items, box_syntax, start, no_std, libc)]
20 #![no_std]
21
22 extern crate libc;
23
24 extern {
25 fn abort() -> !;
26 }
27
28 #[lang = "owned_box"]
29 pub struct Box<T>(*mut T);
30
31 #[lang = "exchange_malloc"]
32 unsafe fn allocate(size: usize, _align: usize) -> *mut u8 {
33 let p = libc::malloc(size as libc::size_t) as *mut u8;
34
35 // malloc failed
36 if p as usize == 0 {
37 abort();
38 }
39
40 p
41 }
42 #[lang = "exchange_free"]
43 unsafe fn deallocate(ptr: *mut u8, _size: usize, _align: usize) {
44 libc::free(ptr as *mut libc::c_void)
45 }
46
47 #[start]
48 fn main(argc: isize, argv: *const *const u8) -> isize {
49 let x = box 1;
50
51 0
52 }
53
54 #[lang = "stack_exhausted"] extern fn stack_exhausted() {}
55 #[lang = "eh_personality"] extern fn eh_personality() {}
56 #[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
57 ```
58
59 Note the use of `abort`: the `exchange_malloc` lang item is assumed to
60 return a valid pointer, and so needs to do the check internally.
61
62 Other features provided by lang items include:
63
64 - overloadable operators via traits: the traits corresponding to the
65 `==`, `<`, dereferencing (`*`) and `+` (etc.) operators are all
66 marked with lang items; those specific four are `eq`, `ord`,
67 `deref`, and `add` respectively.
68 - stack unwinding and general failure; the `eh_personality`, `fail`
69 and `fail_bounds_checks` lang items.
70 - the traits in `std::marker` used to indicate types of
71 various kinds; lang items `send`, `sync` and `copy`.
72 - the marker types and variance indicators found in
73 `std::marker`; lang items `covariant_type`,
74 `contravariant_lifetime`, etc.
75
76 Lang items are loaded lazily by the compiler; e.g. if one never uses
77 `Box` then there is no need to define functions for `exchange_malloc`
78 and `exchange_free`. `rustc` will emit an error when an item is needed
79 but not found in the current crate or any that it depends on.