]> git.proxmox.com Git - rustc.git/blob - src/doc/rustc-dev-guide/src/diagnostics/diagnostic-codes.md
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / src / doc / rustc-dev-guide / src / diagnostics / diagnostic-codes.md
1 # Diagnostic Codes
2 We generally try to assign each error message a unique code like `E0123`. These
3 codes are defined in the compiler in the `diagnostics.rs` files found in each
4 crate, which basically consist of macros. The codes come in two varieties: those
5 that have an extended write-up, and those that do not. Whenever possible, if you
6 are making a new code, you should write an extended write-up.
7
8 ### Allocating a fresh code
9
10 Error codes are stored in `compiler/rustc_error_codes`.
11
12 To create a new error, you first need to find the next available
13 code. You can find it with `tidy`:
14
15 ```
16 ./x.py test tidy
17 ```
18
19 This will invoke the tidy script, which generally checks that your code obeys
20 our coding conventions. One of those jobs is to check that diagnostic codes are
21 indeed unique. Once it is finished with that, tidy will print out the lowest
22 unused code:
23
24 ```
25 ...
26 tidy check (x86_64-apple-darwin)
27 * 470 error codes
28 * highest error code: E0591
29 ...
30 ```
31
32 Here we see the highest error code in use is `E0591`, so we _probably_ want
33 `E0592`. To be sure, run `rg E0592` and check, you should see no references.
34
35 Ideally, you will write an extended description for your error,
36 which will go in `rustc_error_codes/src/error_codes/E0592.md`.
37 To register the error, open `rustc_error_codes/src/error_codes.rs` and add the
38 code (in its proper numerical order) into` register_diagnostics!` macro, like
39 this:
40
41 ```rust
42 register_diagnostics! {
43 ...
44 E0592: include_str!("./error_codes/E0592.md"),
45 }
46 ```
47
48 But you can also add it without an extended description:
49
50 ```rust
51 register_diagnostics! {
52 ...
53 E0592, // put a description here
54 }
55 ```
56
57 To actually issue the error, you can use the `struct_span_err!` macro:
58
59 ```rust
60 struct_span_err!(self.tcx.sess, // some path to the session here
61 span, // whatever span in the source you want
62 E0592, // your new error code
63 &format!("text of the error"))
64 .emit() // actually issue the error
65 ```
66
67 If you want to add notes or other snippets, you can invoke methods before you
68 call `.emit()`:
69
70 ```rust
71 struct_span_err!(...)
72 .span_label(another_span, "something to label in the source")
73 .span_note(another_span, "some separate note, probably avoid these")
74 .emit_()
75 ```
76
77 For an example of a PR adding an error code, see [#76143].
78
79 [#76143]: https://github.com/rust-lang/rust/pull/76143