]> git.proxmox.com Git - rustc.git/blame - 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
CommitLineData
dfeec247 1# Diagnostic Codes
6a06907d 2We generally try to assign each error message a unique code like `E0123`. These
dfeec247
XL
3codes are defined in the compiler in the `diagnostics.rs` files found in each
4crate, which basically consist of macros. The codes come in two varieties: those
5that have an extended write-up, and those that do not. Whenever possible, if you
6are making a new code, you should write an extended write-up.
7
8### Allocating a fresh code
9
6a06907d
XL
10Error codes are stored in `compiler/rustc_error_codes`.
11
12To create a new error, you first need to find the next available
13code. You can find it with `tidy`:
dfeec247
XL
14
15```
6a06907d 16./x.py test tidy
dfeec247
XL
17```
18
19This will invoke the tidy script, which generally checks that your code obeys
20our coding conventions. One of those jobs is to check that diagnostic codes are
21indeed unique. Once it is finished with that, tidy will print out the lowest
22unused code:
23
24```
25...
26tidy check (x86_64-apple-darwin)
27* 470 error codes
28* highest error code: E0591
29...
30```
31
32Here 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
6a06907d
XL
35Ideally, you will write an extended description for your error,
36which will go in `rustc_error_codes/src/error_codes/E0592.md`.
37To register the error, open `rustc_error_codes/src/error_codes.rs` and add the
38code (in its proper numerical order) into` register_diagnostics!` macro, like
39this:
dfeec247
XL
40
41```rust
6a06907d 42register_diagnostics! {
dfeec247 43 ...
6a06907d 44 E0592: include_str!("./error_codes/E0592.md"),
dfeec247
XL
45}
46```
47
48But you can also add it without an extended description:
49
50```rust
51register_diagnostics! {
52 ...
53 E0592, // put a description here
54}
55```
56
57To actually issue the error, you can use the `struct_span_err!` macro:
58
59```rust
60struct_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
67If you want to add notes or other snippets, you can invoke methods before you
68call `.emit()`:
69
70```rust
71struct_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```
6a06907d
XL
76
77For an example of a PR adding an error code, see [#76143].
78
79[#76143]: https://github.com/rust-lang/rust/pull/76143