]> git.proxmox.com Git - rustc.git/blame - src/librustc/diagnostics.rs
Imported Upstream version 1.6.0+dfsg1
[rustc.git] / src / librustc / diagnostics.rs
CommitLineData
1a4d82fc
JJ
1// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11#![allow(non_snake_case)]
12
9346a6ac
AL
13// Error messages for EXXXX errors.
14// Each message should start and end with a new line, and be wrapped to 80 characters.
15// In vim you can `:set tw=80` and use `gq` to wrap paragraphs. Use `:set tw=0` to disable.
85aaf69f 16register_long_diagnostics! {
1a4d82fc 17
9346a6ac
AL
18E0001: r##"
19This error suggests that the expression arm corresponding to the noted pattern
20will never be reached as for all possible values of the expression being
21matched, one of the preceding patterns will match.
22
23This means that perhaps some of the preceding patterns are too general, this one
24is too specific or the ordering is incorrect.
c1a9b12d
SL
25
26For example, the following `match` block has too many arms:
27
28```
29match foo {
30 Some(bar) => {/* ... */}
31 None => {/* ... */}
32 _ => {/* ... */} // All possible cases have already been handled
33}
34```
35
36`match` blocks have their patterns matched in order, so, for example, putting
37a wildcard arm above a more specific arm will make the latter arm irrelevant.
38
39Ensure the ordering of the match arm is correct and remove any superfluous
40arms.
9346a6ac
AL
41"##,
42
43E0002: r##"
c1a9b12d 44This error indicates that an empty match expression is invalid because the type
9346a6ac
AL
45it is matching on is non-empty (there exist values of this type). In safe code
46it is impossible to create an instance of an empty type, so empty match
e9174d1e 47expressions are almost never desired. This error is typically fixed by adding
9346a6ac
AL
48one or more cases to the match expression.
49
c1a9b12d
SL
50An example of an empty type is `enum Empty { }`. So, the following will work:
51
52```
53fn foo(x: Empty) {
54 match x {
55 // empty
56 }
57}
58```
59
60However, this won't:
61
62```
63fn foo(x: Option<String>) {
64 match x {
65 // empty
66 }
67}
68```
9346a6ac
AL
69"##,
70
71E0003: r##"
72Not-a-Number (NaN) values cannot be compared for equality and hence can never
c1a9b12d
SL
73match the input to a match expression. So, the following will not compile:
74
75```
76const NAN: f32 = 0.0 / 0.0;
77
78match number {
79 NAN => { /* ... */ },
80 // ...
81}
82```
83
84To match against NaN values, you should instead use the `is_nan()` method in a
85guard, like so:
86
87```
88match number {
89 // ...
90 x if x.is_nan() => { /* ... */ }
91 // ...
92}
93```
9346a6ac
AL
94"##,
95
96E0004: r##"
97This error indicates that the compiler cannot guarantee a matching pattern for
98one or more possible inputs to a match expression. Guaranteed matches are
99required in order to assign values to match expressions, or alternatively,
100determine the flow of execution.
101
102If you encounter this error you must alter your patterns so that every possible
103value of the input type is matched. For types with a small number of variants
104(like enums) you should probably cover all cases explicitly. Alternatively, the
105underscore `_` wildcard pattern can be added after all other patterns to match
106"anything else".
107"##,
108
9346a6ac 109E0005: r##"
d9579d0f
AL
110Patterns used to bind names must be irrefutable, that is, they must guarantee
111that a name will be extracted in all cases. If you encounter this error you
112probably need to use a `match` or `if let` to deal with the possibility of
113failure.
9346a6ac
AL
114"##,
115
9346a6ac
AL
116E0007: r##"
117This error indicates that the bindings in a match arm would require a value to
118be moved into more than one location, thus violating unique ownership. Code like
d9579d0f 119the following is invalid as it requires the entire `Option<String>` to be moved
9346a6ac
AL
120into a variable called `op_string` while simultaneously requiring the inner
121String to be moved into a variable called `s`.
122
d9579d0f 123```
9346a6ac
AL
124let x = Some("s".to_string());
125match x {
126 op_string @ Some(s) => ...
127 None => ...
128}
d9579d0f 129```
9346a6ac
AL
130
131See also Error 303.
132"##,
133
134E0008: r##"
135Names bound in match arms retain their type in pattern guards. As such, if a
136name is bound by move in a pattern, it should also be moved to wherever it is
137referenced in the pattern guard code. Doing so however would prevent the name
138from being available in the body of the match arm. Consider the following:
139
d9579d0f 140```
9346a6ac
AL
141match Some("hi".to_string()) {
142 Some(s) if s.len() == 0 => // use s.
143 ...
144}
d9579d0f 145```
9346a6ac 146
d9579d0f
AL
147The variable `s` has type `String`, and its use in the guard is as a variable of
148type `String`. The guard code effectively executes in a separate scope to the
149body of the arm, so the value would be moved into this anonymous scope and
150therefore become unavailable in the body of the arm. Although this example seems
9346a6ac
AL
151innocuous, the problem is most clear when considering functions that take their
152argument by value.
153
d9579d0f 154```
9346a6ac
AL
155match Some("hi".to_string()) {
156 Some(s) if { drop(s); false } => (),
157 Some(s) => // use s.
158 ...
159}
d9579d0f 160```
9346a6ac
AL
161
162The value would be dropped in the guard then become unavailable not only in the
163body of that arm but also in all subsequent arms! The solution is to bind by
164reference when using guards or refactor the entire expression, perhaps by
165putting the condition inside the body of the arm.
166"##,
167
d9579d0f
AL
168E0009: r##"
169In a pattern, all values that don't implement the `Copy` trait have to be bound
170the same way. The goal here is to avoid binding simultaneously by-move and
171by-ref.
172
173This limitation may be removed in a future version of Rust.
174
175Wrong example:
176
177```
178struct X { x: (), }
179
180let x = Some((X { x: () }, X { x: () }));
181match x {
182 Some((y, ref z)) => {},
183 None => panic!()
184}
185```
186
187You have two solutions:
188
189Solution #1: Bind the pattern's values the same way.
190
191```
192struct X { x: (), }
193
194let x = Some((X { x: () }, X { x: () }));
195match x {
196 Some((ref y, ref z)) => {},
197 // or Some((y, z)) => {}
198 None => panic!()
199}
200```
201
202Solution #2: Implement the `Copy` trait for the `X` structure.
203
204However, please keep in mind that the first solution should be preferred.
205
206```
207#[derive(Clone, Copy)]
208struct X { x: (), }
209
210let x = Some((X { x: () }, X { x: () }));
211match x {
212 Some((y, ref z)) => {},
213 None => panic!()
214}
215```
216"##,
217
218E0010: r##"
219The value of statics and constants must be known at compile time, and they live
220for the entire lifetime of a program. Creating a boxed value allocates memory on
e9174d1e
SL
221the heap at runtime, and therefore cannot be done at compile time. Erroneous
222code example:
223
224```
225#![feature(box_syntax)]
226
227const CON : Box<i32> = box 0;
228```
d9579d0f
AL
229"##,
230
62682a34
SL
231E0011: r##"
232Initializers for constants and statics are evaluated at compile time.
233User-defined operators rely on user-defined functions, which cannot be evaluated
234at compile time.
235
236Bad example:
237
238```
239use std::ops::Index;
240
241struct Foo { a: u8 }
242
243impl Index<u8> for Foo {
244 type Output = u8;
245
246 fn index<'a>(&'a self, idx: u8) -> &'a u8 { &self.a }
247}
248
249const a: Foo = Foo { a: 0u8 };
250const b: u8 = a[0]; // Index trait is defined by the user, bad!
251```
252
253Only operators on builtin types are allowed.
254
255Example:
256
257```
258const a: &'static [i32] = &[1, 2, 3];
259const b: i32 = a[0]; // Good!
260```
261"##,
262
d9579d0f
AL
263E0013: r##"
264Static and const variables can refer to other const variables. But a const
265variable cannot refer to a static variable. For example, `Y` cannot refer to `X`
266here:
267
268```
269static X: i32 = 42;
270const Y: i32 = X;
271```
272
273To fix this, the value can be extracted as a const and then used:
274
275```
276const A: i32 = 42;
277static X: i32 = A;
278const Y: i32 = A;
279```
280"##,
281
62682a34
SL
282E0014: r##"
283Constants can only be initialized by a constant value or, in a future
284version of Rust, a call to a const function. This error indicates the use
285of a path (like a::b, or x) denoting something other than one of these
286allowed items. Example:
287
288```
289const FOO: i32 = { let x = 0; x }; // 'x' isn't a constant nor a function!
290```
291
292To avoid it, you have to replace the non-constant value:
293
294```
295const FOO: i32 = { const X : i32 = 0; X };
296// or even:
297const FOO: i32 = { 0 }; // but brackets are useless here
298```
299"##,
300
b039eaaf 301// FIXME(#24111) Change the language here when const fn stabilizes
d9579d0f 302E0015: r##"
62682a34 303The only functions that can be called in static or constant expressions are
b039eaaf
SL
304`const` functions, and struct/enum constructors. `const` functions are only
305available on a nightly compiler. Rust currently does not support more general
306compile-time function execution.
307
308```
309const FOO: Option<u8> = Some(1); // enum constructor
310struct Bar {x: u8}
311const BAR: Bar = Bar {x: 1}; // struct constructor
312```
62682a34
SL
313
314See [RFC 911] for more details on the design of `const fn`s.
315
316[RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
317"##,
318
319E0016: r##"
320Blocks in constants may only contain items (such as constant, function
321definition, etc...) and a tail expression. Example:
322
323```
324const FOO: i32 = { let x = 0; x }; // 'x' isn't an item!
325```
326
327To avoid it, you have to replace the non-item object:
328
329```
330const FOO: i32 = { const X : i32 = 0; X };
331```
d9579d0f
AL
332"##,
333
c1a9b12d
SL
334E0017: r##"
335References in statics and constants may only refer to immutable values. Example:
336
337```
338static X: i32 = 1;
339const C: i32 = 2;
340
341// these three are not allowed:
342const CR: &'static mut i32 = &mut C;
343static STATIC_REF: &'static mut i32 = &mut X;
344static CONST_REF: &'static mut i32 = &mut C;
345```
346
347Statics are shared everywhere, and if they refer to mutable data one might
348violate memory safety since holding multiple mutable references to shared data
349is not allowed.
350
351If you really want global mutable state, try using `static mut` or a global
352`UnsafeCell`.
c1a9b12d
SL
353"##,
354
d9579d0f
AL
355E0018: r##"
356The value of static and const variables must be known at compile time. You
357can't cast a pointer as an integer because we can't know what value the
358address will take.
359
360However, pointers to other constants' addresses are allowed in constants,
361example:
362
363```
364const X: u32 = 50;
365const Y: *const u32 = &X;
366```
367
368Therefore, casting one of these non-constant pointers to an integer results
369in a non-constant integer which lead to this error. Example:
370
371```
62682a34
SL
372const X: u32 = 1;
373const Y: usize = &X as *const u32 as usize;
374println!("{}", Y);
375```
376"##,
377
378E0019: r##"
379A function call isn't allowed in the const's initialization expression
380because the expression's value must be known at compile-time. Example of
381erroneous code:
382
383```
384enum Test {
385 V1
386}
387
388impl Test {
389 fn test(&self) -> i32 {
390 12
391 }
392}
393
394fn main() {
395 const FOO: Test = Test::V1;
396
397 const A: i32 = FOO.test(); // You can't call Test::func() here !
398}
399```
400
401Remember: you can't use a function call inside a const's initialization
c1a9b12d 402expression! However, you can totally use it anywhere else:
62682a34
SL
403
404```
405fn main() {
406 const FOO: Test = Test::V1;
407
408 FOO.func(); // here is good
409 let x = FOO.func(); // or even here!
410}
d9579d0f
AL
411```
412"##,
413
414E0020: r##"
415This error indicates that an attempt was made to divide by zero (or take the
e9174d1e
SL
416remainder of a zero divisor) in a static or constant expression. Erroneous
417code example:
418
419```
420const X: i32 = 42 / 0;
421// error: attempted to divide by zero in a constant expression
422```
d9579d0f
AL
423"##,
424
c1a9b12d
SL
425E0022: r##"
426Constant functions are not allowed to mutate anything. Thus, binding to an
427argument with a mutable pattern is not allowed. For example,
428
429```
430const fn foo(mut x: u8) {
431 // do stuff
432}
433```
434
435is bad because the function body may not mutate `x`.
436
437Remove any mutable bindings from the argument list to fix this error. In case
438you need to mutate the argument, try lazily initializing a global variable
439instead of using a `const fn`, or refactoring the code to a functional style to
440avoid mutation if possible.
441"##,
442
443E0030: r##"
444When matching against a range, the compiler verifies that the range is
445non-empty. Range patterns include both end-points, so this is equivalent to
446requiring the start of the range to be less than or equal to the end of the
447range.
448
449For example:
450
451```
452match 5u32 {
453 // This range is ok, albeit pointless.
454 1 ... 1 => ...
455 // This range is empty, and the compiler can tell.
456 1000 ... 5 => ...
457}
458```
459"##,
460
461E0038: r####"
462Trait objects like `Box<Trait>` can only be constructed when certain
463requirements are satisfied by the trait in question.
464
465Trait objects are a form of dynamic dispatch and use a dynamically sized type
466for the inner type. So, for a given trait `Trait`, when `Trait` is treated as a
467type, as in `Box<Trait>`, the inner type is 'unsized'. In such cases the boxed
468pointer is a 'fat pointer' that contains an extra pointer to a table of methods
469(among other things) for dynamic dispatch. This design mandates some
470restrictions on the types of traits that are allowed to be used in trait
471objects, which are collectively termed as 'object safety' rules.
472
473Attempting to create a trait object for a non object-safe trait will trigger
474this error.
475
476There are various rules:
477
478### The trait cannot require `Self: Sized`
479
480When `Trait` is treated as a type, the type does not implement the special
481`Sized` trait, because the type does not have a known size at compile time and
482can only be accessed behind a pointer. Thus, if we have a trait like the
483following:
484
485```
486trait Foo where Self: Sized {
487
488}
489```
490
491we cannot create an object of type `Box<Foo>` or `&Foo` since in this case
492`Self` would not be `Sized`.
493
494Generally, `Self : Sized` is used to indicate that the trait should not be used
495as a trait object. If the trait comes from your own crate, consider removing
496this restriction.
497
498### Method references the `Self` type in its arguments or return type
499
500This happens when a trait has a method like the following:
501
502```
503trait Trait {
504 fn foo(&self) -> Self;
505}
506
507impl Trait for String {
508 fn foo(&self) -> Self {
509 "hi".to_owned()
510 }
511}
512
513impl Trait for u8 {
514 fn foo(&self) -> Self {
515 1
516 }
517}
518```
519
520(Note that `&self` and `&mut self` are okay, it's additional `Self` types which
521cause this problem)
522
523In such a case, the compiler cannot predict the return type of `foo()` in a
524situation like the following:
525
526```
527fn call_foo(x: Box<Trait>) {
528 let y = x.foo(); // What type is y?
529 // ...
530}
531```
532
533If only some methods aren't object-safe, you can add a `where Self: Sized` bound
534on them to mark them as explicitly unavailable to trait objects. The
535functionality will still be available to all other implementers, including
536`Box<Trait>` which is itself sized (assuming you `impl Trait for Box<Trait>`).
537
538```
539trait Trait {
540 fn foo(&self) -> Self where Self: Sized;
541 // more functions
542}
543```
544
545Now, `foo()` can no longer be called on a trait object, but you will now be
546allowed to make a trait object, and that will be able to call any object-safe
547methods". With such a bound, one can still call `foo()` on types implementing
548that trait that aren't behind trait objects.
549
550### Method has generic type parameters
551
552As mentioned before, trait objects contain pointers to method tables. So, if we
553have:
554
555```
556trait Trait {
557 fn foo(&self);
558}
559impl Trait for String {
560 fn foo(&self) {
561 // implementation 1
562 }
563}
564impl Trait for u8 {
565 fn foo(&self) {
566 // implementation 2
567 }
568}
569// ...
570```
571
572At compile time each implementation of `Trait` will produce a table containing
573the various methods (and other items) related to the implementation.
574
575This works fine, but when the method gains generic parameters, we can have a
576problem.
577
578Usually, generic parameters get _monomorphized_. For example, if I have
579
580```
581fn foo<T>(x: T) {
582 // ...
583}
584```
585
586the machine code for `foo::<u8>()`, `foo::<bool>()`, `foo::<String>()`, or any
587other type substitution is different. Hence the compiler generates the
588implementation on-demand. If you call `foo()` with a `bool` parameter, the
589compiler will only generate code for `foo::<bool>()`. When we have additional
590type parameters, the number of monomorphized implementations the compiler
591generates does not grow drastically, since the compiler will only generate an
592implementation if the function is called with unparametrized substitutions
593(i.e., substitutions where none of the substituted types are themselves
594parametrized).
595
596However, with trait objects we have to make a table containing _every_ object
597that implements the trait. Now, if it has type parameters, we need to add
598implementations for every type that implements the trait, and there could
599theoretically be an infinite number of types.
600
601For example, with:
602
603```
604trait Trait {
605 fn foo<T>(&self, on: T);
606 // more methods
607}
608impl Trait for String {
609 fn foo<T>(&self, on: T) {
610 // implementation 1
611 }
612}
613impl Trait for u8 {
614 fn foo<T>(&self, on: T) {
615 // implementation 2
616 }
617}
618// 8 more implementations
619```
620
621Now, if we have the following code:
622
623```
624fn call_foo(thing: Box<Trait>) {
625 thing.foo(true); // this could be any one of the 8 types above
626 thing.foo(1);
627 thing.foo("hello");
628}
629```
630
631we don't just need to create a table of all implementations of all methods of
632`Trait`, we need to create such a table, for each different type fed to
633`foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
634types being fed to `foo()`) = 30 implementations!
635
636With real world traits these numbers can grow drastically.
637
638To fix this, it is suggested to use a `where Self: Sized` bound similar to the
639fix for the sub-error above if you do not intend to call the method with type
640parameters:
641
642```
643trait Trait {
644 fn foo<T>(&self, on: T) where Self: Sized;
645 // more methods
646}
647```
648
649If this is not an option, consider replacing the type parameter with another
650trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
651of types you intend to feed to this method is limited, consider manually listing
652out the methods of different types.
653
654### Method has no receiver
655
656Methods that do not take a `self` parameter can't be called since there won't be
657a way to get a pointer to the method table for them
658
659```
660trait Foo {
661 fn foo() -> u8;
662}
663```
664
665This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
666an implementation.
667
668Adding a `Self: Sized` bound to these methods will generally make this compile.
669
670```
671trait Foo {
672 fn foo() -> u8 where Self: Sized;
673}
674```
675
676### The trait cannot use `Self` as a type parameter in the supertrait listing
677
678This is similar to the second sub-error, but subtler. It happens in situations
679like the following:
680
681```
682trait Super<A> {}
683
684trait Trait: Super<Self> {
685}
686
687struct Foo;
688
689impl Super<Foo> for Foo{}
690
691impl Trait for Foo {}
692```
693
694Here, the supertrait might have methods as follows:
695
696```
697trait Super<A> {
698 fn get_a(&self) -> A; // note that this is object safe!
699}
700```
701
702If the trait `Foo` was deriving from something like `Super<String>` or
703`Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
704`get_a()` will definitely return an object of that type.
705
706However, if it derives from `Super<Self>`, even though `Super` is object safe,
707the method `get_a()` would return an object of unknown type when called on the
708function. `Self` type parameters let us make object safe traits no longer safe,
709so they are forbidden when specifying supertraits.
710
711There's no easy fix for this, generally code will need to be refactored so that
712you no longer need to derive from `Super<Self>`.
713"####,
714
c1a9b12d
SL
715E0109: r##"
716You tried to give a type parameter to a type which doesn't need it. Erroneous
717code example:
718
719```
720type X = u32<i32>; // error: type parameters are not allowed on this type
721```
722
723Please check that you used the correct type and recheck its definition. Perhaps
724it doesn't need the type parameter.
725
726Example:
727
728```
729type X = u32; // this compiles
730```
731
732Note that type parameters for enum-variant constructors go after the variant,
733not after the enum (Option::None::<u32>, not Option::<u32>::None).
734"##,
735
736E0110: r##"
737You tried to give a lifetime parameter to a type which doesn't need it.
738Erroneous code example:
739
740```
741type X = u32<'static>; // error: lifetime parameters are not allowed on
742 // this type
743```
744
745Please check that the correct type was used and recheck its definition; perhaps
746it doesn't need the lifetime parameter. Example:
747
748```
749type X = u32; // ok!
750```
d9579d0f
AL
751"##,
752
753E0133: r##"
e9174d1e
SL
754Using unsafe functionality, is potentially dangerous and disallowed
755by safety checks. Examples:
756
757- Dereferencing raw pointers
758- Calling functions via FFI
759- Calling functions marked unsafe
760
761These safety checks can be relaxed for a section of the code
62682a34 762by wrapping the unsafe instructions with an `unsafe` block. For instance:
d9579d0f
AL
763
764```
765unsafe fn f() { return; }
766
767fn main() {
768 unsafe { f(); }
769}
770```
771
c1a9b12d
SL
772See also https://doc.rust-lang.org/book/unsafe.html
773"##,
774
775// This shouldn't really ever trigger since the repeated value error comes first
776E0136: r##"
777A binary can only have one entry point, and by default that entry point is the
778function `main()`. If there are multiple such functions, please rename one.
d9579d0f
AL
779"##,
780
781E0137: r##"
782This error indicates that the compiler found multiple functions with the
783`#[main]` attribute. This is an error because there must be a unique entry
784point into a Rust program.
785"##,
786
c1a9b12d
SL
787E0138: r##"
788This error indicates that the compiler found multiple functions with the
789`#[start]` attribute. This is an error because there must be a unique entry
790point into a Rust program.
791"##,
792
793// FIXME link this to the relevant turpl chapters for instilling fear of the
794// transmute gods in the user
795E0139: r##"
796There are various restrictions on transmuting between types in Rust; for example
797types being transmuted must have the same size. To apply all these restrictions,
798the compiler must know the exact types that may be transmuted. When type
799parameters are involved, this cannot always be done.
800
801So, for example, the following is not allowed:
802
803```
804struct Foo<T>(Vec<T>)
805
806fn foo<T>(x: Vec<T>) {
807 // we are transmuting between Vec<T> and Foo<T> here
808 let y: Foo<T> = unsafe { transmute(x) };
809 // do something with y
810}
811```
812
813In this specific case there's a good chance that the transmute is harmless (but
814this is not guaranteed by Rust). However, when alignment and enum optimizations
815come into the picture, it's quite likely that the sizes may or may not match
816with different type parameter substitutions. It's not possible to check this for
817_all_ possible types, so `transmute()` simply only accepts types without any
818unsubstituted type parameters.
819
820If you need this, there's a good chance you're doing something wrong. Keep in
821mind that Rust doesn't guarantee much about the layout of different structs
822(even two structs with identical declarations may have different layouts). If
823there is a solution that avoids the transmute entirely, try it instead.
824
825If it's possible, hand-monomorphize the code by writing the function for each
826possible type substitution. It's possible to use traits to do this cleanly,
827for example:
828
829```
830trait MyTransmutableType {
831 fn transmute(Vec<Self>) -> Foo<Self>
832}
833
834impl MyTransmutableType for u8 {
835 fn transmute(x: Foo<u8>) -> Vec<u8> {
836 transmute(x)
837 }
838}
839impl MyTransmutableType for String {
840 fn transmute(x: Foo<String>) -> Vec<String> {
841 transmute(x)
842 }
843}
844// ... more impls for the types you intend to transmute
845
846fn foo<T: MyTransmutableType>(x: Vec<T>) {
847 let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
848 // do something with y
849}
850```
851
852Each impl will be checked for a size match in the transmute as usual, and since
853there are no unbound type parameters involved, this should compile unless there
854is a size mismatch in one of the impls.
855
856It is also possible to manually transmute:
857
858```
e9174d1e 859ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType`
c1a9b12d 860```
92a42be0
SL
861
862Note that this does not move `v` (unlike `transmute`), and may need a
863call to `mem::forget(v)` in case you want to avoid destructors being called.
c1a9b12d
SL
864"##,
865
d9579d0f
AL
866E0152: r##"
867Lang items are already implemented in the standard library. Unless you are
868writing a free-standing application (e.g. a kernel), you do not need to provide
869them yourself.
870
871You can build a free-standing crate by adding `#![no_std]` to the crate
872attributes:
873
874```
d9579d0f
AL
875#![no_std]
876```
877
878See also https://doc.rust-lang.org/book/no-stdlib.html
879"##,
880
881E0158: r##"
882`const` and `static` mean different things. A `const` is a compile-time
883constant, an alias for a literal value. This property means you can match it
884directly within a pattern.
885
886The `static` keyword, on the other hand, guarantees a fixed location in memory.
887This does not always mean that the value is constant. For example, a global
888mutex can be declared `static` as well.
889
890If you want to match against a `static`, consider using a guard instead:
891
892```
893static FORTY_TWO: i32 = 42;
894match Some(42) {
895 Some(x) if x == FORTY_TWO => ...
896 ...
897}
898```
899"##,
900
901E0161: r##"
902In Rust, you can only move a value when its size is known at compile time.
903
904To work around this restriction, consider "hiding" the value behind a reference:
905either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
906it around as usual.
907"##,
908
9346a6ac
AL
909E0162: r##"
910An if-let pattern attempts to match the pattern, and enters the body if the
d9579d0f
AL
911match was successful. If the match is irrefutable (when it cannot fail to
912match), use a regular `let`-binding instead. For instance:
9346a6ac 913
d9579d0f 914```
9346a6ac
AL
915struct Irrefutable(i32);
916let irr = Irrefutable(0);
917
918// This fails to compile because the match is irrefutable.
919if let Irrefutable(x) = irr {
920 // This body will always be executed.
921 foo(x);
922}
923
924// Try this instead:
925let Irrefutable(x) = irr;
926foo(x);
d9579d0f 927```
85aaf69f
SL
928"##,
929
9346a6ac
AL
930E0165: r##"
931A while-let pattern attempts to match the pattern, and enters the body if the
d9579d0f
AL
932match was successful. If the match is irrefutable (when it cannot fail to
933match), use a regular `let`-binding inside a `loop` instead. For instance:
9346a6ac 934
d9579d0f 935```
9346a6ac
AL
936struct Irrefutable(i32);
937let irr = Irrefutable(0);
938
939// This fails to compile because the match is irrefutable.
940while let Irrefutable(x) = irr {
941 ...
942}
943
944// Try this instead:
945loop {
946 let Irrefutable(x) = irr;
947 ...
948}
d9579d0f
AL
949```
950"##,
951
952E0170: r##"
953Enum variants are qualified by default. For example, given this type:
954
955```
956enum Method {
957 GET,
958 POST
959}
960```
961
962you would match it using:
963
964```
965match m {
966 Method::GET => ...
967 Method::POST => ...
968}
969```
970
971If you don't qualify the names, the code will bind new variables named "GET" and
972"POST" instead. This behavior is likely not what you want, so `rustc` warns when
973that happens.
974
975Qualified names are good practice, and most code works well with them. But if
976you prefer them unqualified, you can import the variants into scope:
977
978```
979use Method::*;
980enum Method { GET, POST }
981```
c1a9b12d
SL
982
983If you want others to be able to import variants from your module directly, use
984`pub use`:
985
986```
987pub use Method::*;
988enum Method { GET, POST }
989```
d9579d0f
AL
990"##,
991
62682a34
SL
992E0261: r##"
993When using a lifetime like `'a` in a type, it must be declared before being
994used.
995
996These two examples illustrate the problem:
997
998```
999// error, use of undeclared lifetime name `'a`
1000fn foo(x: &'a str) { }
1001
1002struct Foo {
1003 // error, use of undeclared lifetime name `'a`
1004 x: &'a str,
1005}
1006```
1007
1008These can be fixed by declaring lifetime parameters:
1009
1010```
1011fn foo<'a>(x: &'a str) { }
1012
1013struct Foo<'a> {
1014 x: &'a str,
1015}
1016```
1017"##,
1018
1019E0262: r##"
1020Declaring certain lifetime names in parameters is disallowed. For example,
1021because the `'static` lifetime is a special built-in lifetime name denoting
1022the lifetime of the entire program, this is an error:
1023
1024```
c1a9b12d 1025// error, invalid lifetime parameter name `'static`
62682a34
SL
1026fn foo<'static>(x: &'static str) { }
1027```
1028"##,
1029
1030E0263: r##"
1031A lifetime name cannot be declared more than once in the same scope. For
1032example:
1033
1034```
1035// error, lifetime name `'a` declared twice in the same scope
1036fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
1037```
1038"##,
1039
92a42be0
SL
1040E0264: r##"
1041An unknown external lang item was used. Erroneous code example:
1042
1043```
1044#![feature(lang_items)]
1045
1046extern "C" {
1047 #[lang = "cake"] // error: unknown external lang item: `cake`
1048 fn cake();
1049}
1050```
1051
1052A list of available external lang items is available in
1053`src/librustc/middle/weak_lang_items.rs`. Example:
1054
1055```
1056#![feature(lang_items)]
1057
1058extern "C" {
1059 #[lang = "panic_fmt"] // ok!
1060 fn cake();
1061}
1062```
1063"##,
1064
d9579d0f
AL
1065E0265: r##"
1066This error indicates that a static or constant references itself.
1067All statics and constants need to resolve to a value in an acyclic manner.
1068
1069For example, neither of the following can be sensibly compiled:
1070
1071```
1072const X: u32 = X;
1073```
1074
1075```
1076const X: u32 = Y;
1077const Y: u32 = X;
1078```
1079"##,
1080
1081E0267: r##"
1082This error indicates the use of a loop keyword (`break` or `continue`) inside a
c1a9b12d
SL
1083closure but outside of any loop. Erroneous code example:
1084
1085```
1086let w = || { break; }; // error: `break` inside of a closure
1087```
1088
1089`break` and `continue` keywords can be used as normal inside closures as long as
1090they are also contained within a loop. To halt the execution of a closure you
1091should instead use a return statement. Example:
1092
1093```
1094let w = || {
1095 for _ in 0..10 {
1096 break;
1097 }
1098};
1099
1100w();
1101```
d9579d0f
AL
1102"##,
1103
1104E0268: r##"
1105This error indicates the use of a loop keyword (`break` or `continue`) outside
1106of a loop. Without a loop to break out of or continue in, no sensible action can
c1a9b12d
SL
1107be taken. Erroneous code example:
1108
1109```
1110fn some_func() {
1111 break; // error: `break` outside of loop
1112}
1113```
1114
1115Please verify that you are using `break` and `continue` only in loops. Example:
1116
1117```
1118fn some_func() {
1119 for _ in 0..10 {
1120 break; // ok!
1121 }
1122}
1123```
1124"##,
1125
1126E0269: r##"
1127Functions must eventually return a value of their return type. For example, in
1128the following function
1129
1130```
1131fn foo(x: u8) -> u8 {
1132 if x > 0 {
1133 x // alternatively, `return x`
1134 }
1135 // nothing here
1136}
1137```
1138
1139if the condition is true, the value `x` is returned, but if the condition is
1140false, control exits the `if` block and reaches a place where nothing is being
1141returned. All possible control paths must eventually return a `u8`, which is not
1142happening here.
1143
1144An easy fix for this in a complicated function is to specify a default return
1145value, if possible:
1146
1147```
1148fn foo(x: u8) -> u8 {
1149 if x > 0 {
1150 x // alternatively, `return x`
1151 }
1152 // lots of other if branches
1153 0 // return 0 if all else fails
1154}
1155```
1156
1157It is advisable to find out what the unhandled cases are and check for them,
1158returning an appropriate value or panicking if necessary.
1159"##,
1160
1161E0270: r##"
1162Rust lets you define functions which are known to never return, i.e. are
1163'diverging', by marking its return type as `!`.
1164
1165For example, the following functions never return:
1166
1167```
1168fn foo() -> ! {
1169 loop {}
1170}
1171
1172fn bar() -> ! {
1173 foo() // foo() is diverging, so this will diverge too
1174}
1175
1176fn baz() -> ! {
1177 panic!(); // this macro internally expands to a call to a diverging function
1178}
1179
1180```
1181
1182Such functions can be used in a place where a value is expected without
1183returning a value of that type, for instance:
1184
1185```
1186let y = match x {
1187 1 => 1,
1188 2 => 4,
1189 _ => foo() // diverging function called here
1190};
1191println!("{}", y)
1192```
1193
1194If the third arm of the match block is reached, since `foo()` doesn't ever
1195return control to the match block, it is fine to use it in a place where an
1196integer was expected. The `match` block will never finish executing, and any
1197point where `y` (like the print statement) is needed will not be reached.
1198
1199However, if we had a diverging function that actually does finish execution
1200
1201```
1202fn foo() -> {
1203 loop {break;}
1204}
1205```
1206
1207then we would have an unknown value for `y` in the following code:
1208
1209```
1210let y = match x {
1211 1 => 1,
1212 2 => 4,
1213 _ => foo()
1214};
1215println!("{}", y);
1216```
1217
1218In the previous example, the print statement was never reached when the wildcard
1219match arm was hit, so we were okay with `foo()` not returning an integer that we
1220could set to `y`. But in this example, `foo()` actually does return control, so
1221the print statement will be executed with an uninitialized value.
1222
1223Obviously we cannot have functions which are allowed to be used in such
1224positions and yet can return control. So, if you are defining a function that
1225returns `!`, make sure that there is no way for it to actually finish executing.
d9579d0f
AL
1226"##,
1227
1228E0271: r##"
1229This is because of a type mismatch between the associated type of some
1230trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
1231and another type `U` that is required to be equal to `T::Bar`, but is not.
1232Examples follow.
1233
1234Here is a basic example:
1235
1236```
1237trait Trait { type AssociatedType; }
1238fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1239 println!("in foo");
1240}
1241impl Trait for i8 { type AssociatedType = &'static str; }
1242foo(3_i8);
1243```
1244
1245Here is that same example again, with some explanatory comments:
1246
1247```
1248trait Trait { type AssociatedType; }
1249
1250fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1251// ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
1252// | |
1253// This says `foo` can |
1254// only be used with |
1255// some type that |
1256// implements `Trait`. |
1257// |
1258// This says not only must
1259// `T` be an impl of `Trait`
1260// but also that the impl
1261// must assign the type `u32`
1262// to the associated type.
1263 println!("in foo");
1264}
1265
1266impl Trait for i8 { type AssociatedType = &'static str; }
1267~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1268// | |
1269// `i8` does have |
1270// implementation |
1271// of `Trait`... |
1272// ... but it is an implementation
1273// that assigns `&'static str` to
1274// the associated type.
1275
1276foo(3_i8);
1277// Here, we invoke `foo` with an `i8`, which does not satisfy
62682a34 1278// the constraint `<i8 as Trait>::AssociatedType=u32`, and
d9579d0f
AL
1279// therefore the type-checker complains with this error code.
1280```
1281
1282Here is a more subtle instance of the same problem, that can
1283arise with for-loops in Rust:
1284
1285```
1286let vs: Vec<i32> = vec![1, 2, 3, 4];
1287for v in &vs {
1288 match v {
1289 1 => {}
1290 _ => {}
1291 }
1292}
1293```
1294
1295The above fails because of an analogous type mismatch,
1296though may be harder to see. Again, here are some
1297explanatory comments for the same example:
1298
1299```
1300{
1301 let vs = vec![1, 2, 3, 4];
1302
1303 // `for`-loops use a protocol based on the `Iterator`
1304 // trait. Each item yielded in a `for` loop has the
1305 // type `Iterator::Item` -- that is,I `Item` is the
1306 // associated type of the concrete iterator impl.
1307 for v in &vs {
1308// ~ ~~~
1309// | |
1310// | We borrow `vs`, iterating over a sequence of
1311// | *references* of type `&Elem` (where `Elem` is
1312// | vector's element type). Thus, the associated
1313// | type `Item` must be a reference `&`-type ...
1314// |
1315// ... and `v` has the type `Iterator::Item`, as dictated by
1316// the `for`-loop protocol ...
1317
1318 match v {
1319 1 => {}
1320// ~
1321// |
1322// ... but *here*, `v` is forced to have some integral type;
1323// only types like `u8`,`i8`,`u16`,`i16`, et cetera can
1324// match the pattern `1` ...
1325
1326 _ => {}
1327 }
1328
1329// ... therefore, the compiler complains, because it sees
1330// an attempt to solve the equations
1331// `some integral-type` = type-of-`v`
1332// = `Iterator::Item`
1333// = `&Elem` (i.e. `some reference type`)
1334//
1335// which cannot possibly all be true.
1336
1337 }
1338}
1339```
1340
1341To avoid those issues, you have to make the types match correctly.
1342So we can fix the previous examples like this:
1343
1344```
1345// Basic Example:
1346trait Trait { type AssociatedType; }
1347fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
1348 println!("in foo");
1349}
1350impl Trait for i8 { type AssociatedType = &'static str; }
1351foo(3_i8);
1352
1353// For-Loop Example:
1354let vs = vec![1, 2, 3, 4];
1355for v in &vs {
1356 match v {
1357 &1 => {}
1358 _ => {}
1359 }
1360}
1361```
1362"##,
1363
c1a9b12d
SL
1364E0272: r##"
1365The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1366message for when a particular trait isn't implemented on a type placed in a
1367position that needs that trait. For example, when the following code is
1368compiled:
1369
1370```
1371fn foo<T: Index<u8>>(x: T){}
1372
1373#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1374trait Index<Idx> { ... }
1375
1376foo(true); // `bool` does not implement `Index<u8>`
1377```
1378
1379there will be an error about `bool` not implementing `Index<u8>`, followed by a
1380note saying "the type `bool` cannot be indexed by `u8`".
1381
1382As you can see, you can specify type parameters in curly braces for substitution
1383with the actual types (using the regular format string syntax) in a given
1384situation. Furthermore, `{Self}` will substitute to the type (in this case,
1385`bool`) that we tried to use.
1386
1387This error appears when the curly braces contain an identifier which doesn't
1388match with any of the type parameters or the string `Self`. This might happen if
1389you misspelled a type parameter, or if you intended to use literal curly braces.
1390If it is the latter, escape the curly braces with a second curly brace of the
1391same type; e.g. a literal `{` is `{{`
1392"##,
1393
1394E0273: r##"
1395The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1396message for when a particular trait isn't implemented on a type placed in a
1397position that needs that trait. For example, when the following code is
1398compiled:
1399
1400```
1401fn foo<T: Index<u8>>(x: T){}
1402
1403#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1404trait Index<Idx> { ... }
1405
1406foo(true); // `bool` does not implement `Index<u8>`
1407```
1408
1409there will be an error about `bool` not implementing `Index<u8>`, followed by a
1410note saying "the type `bool` cannot be indexed by `u8`".
1411
1412As you can see, you can specify type parameters in curly braces for substitution
1413with the actual types (using the regular format string syntax) in a given
1414situation. Furthermore, `{Self}` will substitute to the type (in this case,
1415`bool`) that we tried to use.
1416
1417This error appears when the curly braces do not contain an identifier. Please
1418add one of the same name as a type parameter. If you intended to use literal
1419braces, use `{{` and `}}` to escape them.
1420"##,
1421
1422E0274: r##"
1423The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1424message for when a particular trait isn't implemented on a type placed in a
1425position that needs that trait. For example, when the following code is
1426compiled:
1427
1428```
1429fn foo<T: Index<u8>>(x: T){}
1430
1431#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1432trait Index<Idx> { ... }
1433
1434foo(true); // `bool` does not implement `Index<u8>`
1435```
1436
1437there will be an error about `bool` not implementing `Index<u8>`, followed by a
1438note saying "the type `bool` cannot be indexed by `u8`".
1439
1440For this to work, some note must be specified. An empty attribute will not do
1441anything, please remove the attribute or add some helpful note for users of the
1442trait.
1443"##,
1444
1445E0275: r##"
1446This error occurs when there was a recursive trait requirement that overflowed
1447before it could be evaluated. Often this means that there is unbounded recursion
1448in resolving some type bounds.
1449
1450For example, in the following code
1451
1452```
1453trait Foo {}
1454
1455struct Bar<T>(T);
1456
1457impl<T> Foo for T where Bar<T>: Foo {}
1458```
1459
1460to determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
1461to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To determine
1462this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is clearly a
1463recursive requirement that can't be resolved directly.
1464
1465Consider changing your trait bounds so that they're less self-referential.
1466"##,
1467
1468E0276: r##"
1469This error occurs when a bound in an implementation of a trait does not match
1470the bounds specified in the original trait. For example:
1471
1472```
1473trait Foo {
1474 fn foo<T>(x: T);
1475}
1476
1477impl Foo for bool {
1478 fn foo<T>(x: T) where T: Copy {}
1479}
1480```
1481
1482Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
1483take any type `T`. However, in the `impl` for `bool`, we have added an extra
1484bound that `T` is `Copy`, which isn't compatible with the original trait.
1485
1486Consider removing the bound from the method or adding the bound to the original
1487method definition in the trait.
1488"##,
1489
1490E0277: r##"
1491You tried to use a type which doesn't implement some trait in a place which
1492expected that trait. Erroneous code example:
1493
1494```
1495// here we declare the Foo trait with a bar method
1496trait Foo {
1497 fn bar(&self);
1498}
1499
1500// we now declare a function which takes an object implementing the Foo trait
1501fn some_func<T: Foo>(foo: T) {
1502 foo.bar();
1503}
1504
1505fn main() {
1506 // we now call the method with the i32 type, which doesn't implement
1507 // the Foo trait
1508 some_func(5i32); // error: the trait `Foo` is not implemented for the
1509 // type `i32`
1510}
1511```
1512
1513In order to fix this error, verify that the type you're using does implement
1514the trait. Example:
1515
1516```
1517trait Foo {
1518 fn bar(&self);
1519}
1520
1521fn some_func<T: Foo>(foo: T) {
1522 foo.bar(); // we can now use this method since i32 implements the
1523 // Foo trait
1524}
1525
1526// we implement the trait on the i32 type
1527impl Foo for i32 {
1528 fn bar(&self) {}
1529}
1530
1531fn main() {
1532 some_func(5i32); // ok!
1533}
1534```
1535"##,
1536
e9174d1e
SL
1537E0281: r##"
1538You tried to supply a type which doesn't implement some trait in a location
1539which expected that trait. This error typically occurs when working with
1540`Fn`-based types. Erroneous code example:
1541
1542```
1543fn foo<F: Fn()>(x: F) { }
1544
1545fn main() {
1546 // type mismatch: the type ... implements the trait `core::ops::Fn<(_,)>`,
1547 // but the trait `core::ops::Fn<()>` is required (expected (), found tuple
1548 // [E0281]
1549 foo(|y| { });
1550}
1551```
1552
1553The issue in this case is that `foo` is defined as accepting a `Fn` with no
1554arguments, but the closure we attempted to pass to it requires one argument.
1555"##,
1556
d9579d0f
AL
1557E0282: r##"
1558This error indicates that type inference did not result in one unique possible
1559type, and extra information is required. In most cases this can be provided
1560by adding a type annotation. Sometimes you need to specify a generic type
1561parameter manually.
1562
1563A common example is the `collect` method on `Iterator`. It has a generic type
1564parameter with a `FromIterator` bound, which for a `char` iterator is
1565implemented by `Vec` and `String` among others. Consider the following snippet
1566that reverses the characters of a string:
1567
1568```
1569let x = "hello".chars().rev().collect();
1570```
1571
1572In this case, the compiler cannot infer what the type of `x` should be:
1573`Vec<char>` and `String` are both suitable candidates. To specify which type to
1574use, you can use a type annotation on `x`:
1575
1576```
1577let x: Vec<char> = "hello".chars().rev().collect();
1578```
1579
1580It is not necessary to annotate the full type. Once the ambiguity is resolved,
1581the compiler can infer the rest:
1582
1583```
1584let x: Vec<_> = "hello".chars().rev().collect();
1585```
1586
1587Another way to provide the compiler with enough information, is to specify the
1588generic type parameter:
1589
1590```
1591let x = "hello".chars().rev().collect::<Vec<char>>();
1592```
1593
1594Again, you need not specify the full type if the compiler can infer it:
1595
1596```
1597let x = "hello".chars().rev().collect::<Vec<_>>();
1598```
1599
1600Apart from a method or function with a generic type parameter, this error can
1601occur when a type parameter of a struct or trait cannot be inferred. In that
1602case it is not always possible to use a type annotation, because all candidates
1603have the same return type. For instance:
1604
1605```
1606struct Foo<T> {
1607 // Some fields omitted.
1608}
1609
1610impl<T> Foo<T> {
1611 fn bar() -> i32 {
1612 0
1613 }
1614
1615 fn baz() {
1616 let number = Foo::bar();
1617 }
1618}
1619```
1620
1621This will fail because the compiler does not know which instance of `Foo` to
1622call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1623"##,
1624
1625E0296: r##"
1626This error indicates that the given recursion limit could not be parsed. Ensure
1627that the value provided is a positive integer between quotes, like so:
1628
1629```
1630#![recursion_limit="1000"]
1631```
85aaf69f
SL
1632"##,
1633
9346a6ac
AL
1634E0297: r##"
1635Patterns used to bind names must be irrefutable. That is, they must guarantee
1636that a name will be extracted in all cases. Instead of pattern matching the
1637loop variable, consider using a `match` or `if let` inside the loop body. For
1638instance:
1639
d9579d0f 1640```
9346a6ac
AL
1641// This fails because `None` is not covered.
1642for Some(x) in xs {
1643 ...
1644}
1645
1646// Match inside the loop instead:
1647for item in xs {
1648 match item {
1649 Some(x) => ...
1650 None => ...
1651 }
1652}
85aaf69f 1653
9346a6ac
AL
1654// Or use `if let`:
1655for item in xs {
1656 if let Some(x) = item {
1657 ...
1658 }
1659}
d9579d0f 1660```
85aaf69f
SL
1661"##,
1662
9346a6ac
AL
1663E0301: r##"
1664Mutable borrows are not allowed in pattern guards, because matching cannot have
1665side effects. Side effects could alter the matched object or the environment
1666on which the match depends in such a way, that the match would not be
1667exhaustive. For instance, the following would not match any arm if mutable
1668borrows were allowed:
1669
d9579d0f 1670```
9346a6ac
AL
1671match Some(()) {
1672 None => { },
1673 option if option.take().is_none() => { /* impossible, option is `Some` */ },
1674 Some(_) => { } // When the previous match failed, the option became `None`.
1675}
d9579d0f 1676```
9346a6ac
AL
1677"##,
1678
1679E0302: r##"
1680Assignments are not allowed in pattern guards, because matching cannot have
1681side effects. Side effects could alter the matched object or the environment
1682on which the match depends in such a way, that the match would not be
1683exhaustive. For instance, the following would not match any arm if assignments
1684were allowed:
1685
d9579d0f 1686```
9346a6ac
AL
1687match Some(()) {
1688 None => { },
1689 option if { option = None; false } { },
1690 Some(_) => { } // When the previous match failed, the option became `None`.
1691}
d9579d0f 1692```
85aaf69f
SL
1693"##,
1694
9346a6ac
AL
1695E0303: r##"
1696In certain cases it is possible for sub-bindings to violate memory safety.
1697Updates to the borrow checker in a future version of Rust may remove this
1698restriction, but for now patterns must be rewritten without sub-bindings.
1699
d9579d0f 1700```
c1a9b12d
SL
1701// Before.
1702match Some("hi".to_string()) {
1703 ref op_string_ref @ Some(ref s) => ...
9346a6ac
AL
1704 None => ...
1705}
1706
d9579d0f
AL
1707// After.
1708match Some("hi".to_string()) {
1709 Some(ref s) => {
c1a9b12d 1710 let op_string_ref = &Some(s);
9346a6ac
AL
1711 ...
1712 }
1713 None => ...
1714}
d9579d0f
AL
1715```
1716
1717The `op_string_ref` binding has type `&Option<&String>` in both cases.
9346a6ac
AL
1718
1719See also https://github.com/rust-lang/rust/issues/14587
d9579d0f
AL
1720"##,
1721
1722E0306: r##"
1723In an array literal `[x; N]`, `N` is the number of elements in the array. This
1724number cannot be negative.
1725"##,
1726
1727E0307: r##"
1728The length of an array is part of its type. For this reason, this length must be
1729a compile-time constant.
1730"##,
1731
1732E0308: r##"
1733This error occurs when the compiler was unable to infer the concrete type of a
c1a9b12d 1734variable. It can occur for several cases, the most common of which is a
d9579d0f
AL
1735mismatch in the expected type that the compiler inferred for a variable's
1736initializing expression, and the actual type explicitly assigned to the
1737variable.
1738
1739For example:
1740
1741```
1742let x: i32 = "I am not a number!";
1743// ~~~ ~~~~~~~~~~~~~~~~~~~~
1744// | |
1745// | initializing expression;
1746// | compiler infers type `&str`
1747// |
1748// type `i32` assigned to variable `x`
1749```
1750"##,
1751
1752E0309: r##"
1753Types in type definitions have lifetimes associated with them that represent
1754how long the data stored within them is guaranteed to be live. This lifetime
1755must be as long as the data needs to be alive, and missing the constraint that
1756denotes this will cause this error.
1757
1758```
1759// This won't compile because T is not constrained, meaning the data
1760// stored in it is not guaranteed to last as long as the reference
1761struct Foo<'a, T> {
1762 foo: &'a T
1763}
1764
1765// This will compile, because it has the constraint on the type parameter
1766struct Foo<'a, T: 'a> {
1767 foo: &'a T
1768}
1769```
1770"##,
1771
1772E0310: r##"
1773Types in type definitions have lifetimes associated with them that represent
1774how long the data stored within them is guaranteed to be live. This lifetime
1775must be as long as the data needs to be alive, and missing the constraint that
1776denotes this will cause this error.
1777
1778```
1779// This won't compile because T is not constrained to the static lifetime
1780// the reference needs
1781struct Foo<T> {
1782 foo: &'static T
1783}
1784
1785// This will compile, because it has the constraint on the type parameter
1786struct Foo<T: 'static> {
1787 foo: &'static T
1788}
1789```
62682a34
SL
1790"##,
1791
1792E0378: r##"
1793Method calls that aren't calls to inherent `const` methods are disallowed
1794in statics, constants, and constant functions.
1795
1796For example:
1797
1798```
1799const BAZ: i32 = Foo(25).bar(); // error, `bar` isn't `const`
1800
1801struct Foo(i32);
1802
1803impl Foo {
1804 const fn foo(&self) -> i32 {
1805 self.bar() // error, `bar` isn't `const`
1806 }
1807
1808 fn bar(&self) -> i32 { self.0 }
1809}
1810```
1811
1812For more information about `const fn`'s, see [RFC 911].
1813
1814[RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
1815"##,
1816
1817E0394: r##"
1818From [RFC 246]:
1819
c1a9b12d 1820 > It is invalid for a static to reference another static by value. It is
62682a34
SL
1821 > required that all references be borrowed.
1822
1823[RFC 246]: https://github.com/rust-lang/rfcs/pull/246
1824"##,
1825
c1a9b12d
SL
1826E0395: r##"
1827The value assigned to a constant expression must be known at compile time,
1828which is not the case when comparing raw pointers. Erroneous code example:
1829
1830```
1831static foo: i32 = 42;
1832static bar: i32 = 43;
1833
1834static baz: bool = { (&foo as *const i32) == (&bar as *const i32) };
1835// error: raw pointers cannot be compared in statics!
1836```
1837
1838Please check that the result of the comparison can be determined at compile time
1839or isn't assigned to a constant expression. Example:
1840
1841```
1842static foo: i32 = 42;
1843static bar: i32 = 43;
1844
1845let baz: bool = { (&foo as *const i32) == (&bar as *const i32) };
1846// baz isn't a constant expression so it's ok
1847```
1848"##,
1849
1850E0396: r##"
1851The value assigned to a constant expression must be known at compile time,
1852which is not the case when dereferencing raw pointers. Erroneous code
1853example:
1854
1855```
1856const foo: i32 = 42;
1857const baz: *const i32 = (&foo as *const i32);
1858
1859const deref: i32 = *baz;
1860// error: raw pointers cannot be dereferenced in constants
1861```
1862
1863To fix this error, please do not assign this value to a constant expression.
1864Example:
1865
1866```
1867const foo: i32 = 42;
1868const baz: *const i32 = (&foo as *const i32);
1869
1870unsafe { let deref: i32 = *baz; }
1871// baz isn't a constant expression so it's ok
1872```
1873
1874You'll also note that this assignment must be done in an unsafe block!
1875"##,
1876
62682a34
SL
1877E0397: r##"
1878It is not allowed for a mutable static to allocate or have destructors. For
1879example:
1880
1881```
1882// error: mutable statics are not allowed to have boxes
1883static mut FOO: Option<Box<usize>> = None;
1884
1885// error: mutable statics are not allowed to have destructors
1886static mut BAR: Option<Vec<i32>> = None;
1887```
1888"##,
1889
1890E0398: r##"
1891In Rust 1.3, the default object lifetime bounds are expected to
1892change, as described in RFC #1156 [1]. You are getting a warning
1893because the compiler thinks it is possible that this change will cause
1894a compilation error in your code. It is possible, though unlikely,
1895that this is a false alarm.
1896
1897The heart of the change is that where `&'a Box<SomeTrait>` used to
1898default to `&'a Box<SomeTrait+'a>`, it now defaults to `&'a
1899Box<SomeTrait+'static>` (here, `SomeTrait` is the name of some trait
1900type). Note that the only types which are affected are references to
1901boxes, like `&Box<SomeTrait>` or `&[Box<SomeTrait>]`. More common
1902types like `&SomeTrait` or `Box<SomeTrait>` are unaffected.
1903
1904To silence this warning, edit your code to use an explicit bound.
1905Most of the time, this means that you will want to change the
1906signature of a function that you are calling. For example, if
1907the error is reported on a call like `foo(x)`, and `foo` is
1908defined as follows:
1909
1910```
1911fn foo(arg: &Box<SomeTrait>) { ... }
1912```
1913
1914you might change it to:
1915
1916```
1917fn foo<'a>(arg: &Box<SomeTrait+'a>) { ... }
1918```
1919
1920This explicitly states that you expect the trait object `SomeTrait` to
1921contain references (with a maximum lifetime of `'a`).
1922
1923[1]: https://github.com/rust-lang/rfcs/pull/1156
b039eaaf
SL
1924"##,
1925
92a42be0
SL
1926E0400: r##"
1927A user-defined dereference was attempted in an invalid context. Erroneous
1928code example:
b039eaaf
SL
1929
1930```
92a42be0
SL
1931use std::ops::Deref;
1932
1933struct A;
1934
1935impl Deref for A {
1936 type Target = str;
1937
1938 fn deref(&self)-> &str { "foo" }
1939}
1940
1941const S: &'static str = &A;
1942// error: user-defined dereference operators are not allowed in constants
1943
1944fn main() {
1945 let foo = S;
1946}
b039eaaf
SL
1947```
1948
92a42be0
SL
1949You cannot directly use a dereference operation whilst initializing a constant
1950or a static. To fix this error, restructure your code to avoid this dereference,
1951perhaps moving it inline:
b039eaaf
SL
1952
1953```
92a42be0
SL
1954use std::ops::Deref;
1955
1956struct A;
1957
1958impl Deref for A {
1959 type Target = str;
1960
1961 fn deref(&self)-> &str { "foo" }
1962}
1963
1964fn main() {
1965 let foo : &str = &A;
1966}
b039eaaf
SL
1967```
1968"##,
1969
92a42be0
SL
1970E0452: r##"
1971An invalid lint attribute has been given. Erroneous code example:
b039eaaf
SL
1972
1973```
92a42be0 1974#![allow(foo = "")] // error: malformed lint attribute
b039eaaf
SL
1975```
1976
92a42be0
SL
1977Lint attributes only accept a list of identifiers (where each identifier is a
1978lint name). Ensure the attribute is of this form:
1979
1980```
1981#![allow(foo)] // ok!
1982// or:
1983#![allow(foo, foo2)] // ok!
1984```
b039eaaf
SL
1985"##,
1986
92a42be0
SL
1987E0492: r##"
1988A borrow of a constant containing interior mutability was attempted. Erroneous
1989code example:
b039eaaf
SL
1990
1991```
92a42be0
SL
1992use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
1993
1994const A: AtomicUsize = ATOMIC_USIZE_INIT;
1995static B: &'static AtomicUsize = &A;
1996// error: cannot borrow a constant which contains interior mutability, create a
1997// static instead
b039eaaf
SL
1998```
1999
92a42be0
SL
2000A `const` represents a constant value that should never change. If one takes
2001a `&` reference to the constant, then one is taking a pointer to some memory
2002location containing the value. Normally this is perfectly fine: most values
2003can't be changed via a shared `&` pointer, but interior mutability would allow
2004it. That is, a constant value could be mutated. On the other hand, a `static` is
2005explicitly a single memory location, which can be mutated at will.
2006
2007So, in order to solve this error, either use statics which are `Sync`:
2008
2009```
2010use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
b039eaaf 2011
92a42be0
SL
2012static A: AtomicUsize = ATOMIC_USIZE_INIT;
2013static B: &'static AtomicUsize = &A; // ok!
b039eaaf 2014```
92a42be0
SL
2015
2016You can also have this error while using a cell type:
2017
b039eaaf 2018```
92a42be0
SL
2019#![feature(const_fn)]
2020
2021use std::cell::Cell;
2022
2023const A: Cell<usize> = Cell::new(1);
2024const B: &'static Cell<usize> = &A;
2025// error: cannot borrow a constant which contains interior mutability, create
2026// a static instead
2027
2028// or:
2029struct C { a: Cell<usize> }
2030
2031const D: C = C { a: Cell::new(1) };
2032const E: &'static Cell<usize> = &D.a; // error
2033
2034// or:
2035const F: &'static C = &D; // error
2036```
2037
2038This is because cell types do operations that are not thread-safe. Due to this,
2039they don't implement Sync and thus can't be placed in statics. In this
2040case, `StaticMutex` would work just fine, but it isn't stable yet:
2041https://doc.rust-lang.org/nightly/std/sync/struct.StaticMutex.html
2042
2043However, if you still wish to use these types, you can achieve this by an unsafe
2044wrapper:
2045
2046```
2047#![feature(const_fn)]
2048
2049use std::cell::Cell;
2050use std::marker::Sync;
2051
2052struct NotThreadSafe<T> {
2053 value: Cell<T>,
2054}
2055
2056unsafe impl<T> Sync for NotThreadSafe<T> {}
2057
2058static A: NotThreadSafe<usize> = NotThreadSafe { value : Cell::new(1) };
2059static B: &'static NotThreadSafe<usize> = &A; // ok!
2060```
2061
2062Remember this solution is unsafe! You will have to ensure that accesses to the
2063cell are synchronized.
b039eaaf
SL
2064"##,
2065
2066E0493: r##"
2067A type with a destructor was assigned to an invalid type of variable. Erroneous
2068code example:
2069
2070```
2071struct Foo {
2072 a: u32
2073}
2074
2075impl Drop for Foo {
2076 fn drop(&mut self) {}
2077}
2078
2079const F : Foo = Foo { a : 0 };
2080// error: constants are not allowed to have destructors
2081static S : Foo = Foo { a : 0 };
2082// error: statics are not allowed to have destructors
2083```
2084
2085To solve this issue, please use a type which does allow the usage of type with
2086destructors.
2087"##,
2088
2089E0494: r##"
2090A reference of an interior static was assigned to another const/static.
2091Erroneous code example:
2092
2093```
2094struct Foo {
2095 a: u32
2096}
2097
2098static S : Foo = Foo { a : 0 };
2099static A : &'static u32 = &S.a;
2100// error: cannot refer to the interior of another static, use a
2101// constant instead
2102```
2103
2104The "base" variable has to be a const if you want another static/const variable
2105to refer to one of its fields. Example:
2106
2107```
2108struct Foo {
2109 a: u32
2110}
2111
2112const S : Foo = Foo { a : 0 };
2113static A : &'static u32 = &S.a; // ok!
2114```
2115"##,
2116
2117E0496: r##"
2118A lifetime name is shadowing another lifetime name. Erroneous code example:
2119
2120```
2121struct Foo<'a> {
2122 a: &'a i32,
2123}
2124
2125impl<'a> Foo<'a> {
2126 fn f<'a>(x: &'a i32) { // error: lifetime name `'a` shadows a lifetime
2127 // name that is already in scope
2128 }
2129}
2130```
2131
2132Please change the name of one of the lifetimes to remove this error. Example:
2133
b039eaaf
SL
2134```
2135struct Foo<'a> {
2136 a: &'a i32,
2137}
2138
2139impl<'a> Foo<'a> {
2140 fn f<'b>(x: &'b i32) { // ok!
2141 }
2142}
2143
2144fn main() {
2145}
2146```
2147"##,
2148
2149E0497: r##"
2150A stability attribute was used outside of the standard library. Erroneous code
2151example:
2152
2153```
2154#[stable] // error: stability attributes may not be used outside of the
2155 // standard library
2156fn foo() {}
2157```
2158
2159It is not possible to use stability attributes outside of the standard library.
2160Also, for now, it is not possible to write deprecation messages either.
2161"##,
9346a6ac 2162
92a42be0
SL
2163E0517: r##"
2164This error indicates that a `#[repr(..)]` attribute was placed on an unsupported
2165item.
2166
2167Examples of erroneous code:
2168
2169```
2170#[repr(C)]
2171type Foo = u8;
2172
2173#[repr(packed)]
2174enum Foo {Bar, Baz}
2175
2176#[repr(u8)]
2177struct Foo {bar: bool, baz: bool}
2178
2179#[repr(C)]
2180impl Foo {
2181 ...
2182}
2183```
2184
2185 - The `#[repr(C)]` attribute can only be placed on structs and enums
2186 - The `#[repr(packed)]` and `#[repr(simd)]` attributes only work on structs
2187 - The `#[repr(u8)]`, `#[repr(i16)]`, etc attributes only work on enums
2188
2189These attributes do not work on typedefs, since typedefs are just aliases.
2190
2191Representations like `#[repr(u8)]`, `#[repr(i64)]` are for selecting the
2192discriminant size for C-like enums (when there is no associated data, e.g. `enum
2193Color {Red, Blue, Green}`), effectively setting the size of the enum to the size
2194of the provided type. Such an enum can be cast to a value of the same type as
2195well. In short, `#[repr(u8)]` makes the enum behave like an integer with a
2196constrained set of allowed values.
2197
2198Only C-like enums can be cast to numerical primitives, so this attribute will
2199not apply to structs.
2200
2201`#[repr(packed)]` reduces padding to make the struct size smaller. The
2202representation of enums isn't strictly defined in Rust, and this attribute won't
2203work on enums.
2204
2205`#[repr(simd)]` will give a struct consisting of a homogenous series of machine
2206types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via
2207SIMD. This doesn't make much sense for enums since they don't consist of a
2208single list of data.
2209"##,
2210
2211E0518: r##"
2212This error indicates that an `#[inline(..)]` attribute was incorrectly placed on
2213something other than a function or method.
2214
2215Examples of erroneous code:
2216
2217```
2218#[inline(always)]
2219struct Foo;
2220
2221#[inline(never)]
2222impl Foo {
2223 ...
2224}
2225```
2226
2227`#[inline]` hints the compiler whether or not to attempt to inline a method or
2228function. By default, the compiler does a pretty good job of figuring this out
2229itself, but if you feel the need for annotations, `#[inline(always)]` and
2230`#[inline(never)]` can override or force the compiler's decision.
2231
2232If you wish to apply this attribute to all methods in an impl, manually annotate
2233each method; it is not possible to annotate the entire impl with an `#[inline]`
2234attribute.
2235"##,
2236
85aaf69f 2237}
1a4d82fc 2238
d9579d0f 2239
1a4d82fc 2240register_diagnostics! {
c1a9b12d
SL
2241 // E0006 // merged with E0005
2242// E0134,
2243// E0135,
e9174d1e 2244 E0229, // associated type bindings are not allowed here
85aaf69f
SL
2245 E0278, // requirement is not satisfied
2246 E0279, // requirement is not satisfied
2247 E0280, // requirement is not satisfied
85aaf69f
SL
2248 E0283, // cannot resolve type
2249 E0284, // cannot resolve type
2250 E0285, // overflow evaluation builtin bounds
85aaf69f
SL
2251 E0298, // mismatched types between arms
2252 E0299, // mismatched types between arms
2253 E0300, // unexpanded macro
85aaf69f
SL
2254 E0304, // expected signed integer constant
2255 E0305, // expected constant
85aaf69f
SL
2256 E0311, // thing may not live long enough
2257 E0312, // lifetime of reference outlives lifetime of borrowed content
2258 E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
2259 E0314, // closure outlives stack frame
2260 E0315, // cannot invoke closure outside of its lifetime
c34b1796 2261 E0316, // nested quantification of lifetimes
b039eaaf 2262 E0453, // overruled by outer forbid
b039eaaf
SL
2263 E0471, // constant evaluation error: ..
2264 E0472, // asm! is unsupported on this target
2265 E0473, // dereference of reference outside its lifetime
2266 E0474, // captured variable `..` does not outlive the enclosing closure
2267 E0475, // index of slice outside its lifetime
2268 E0476, // lifetime of the source pointer does not outlive lifetime bound...
2269 E0477, // the type `..` does not fulfill the required lifetime...
2270 E0478, // lifetime bound not satisfied
2271 E0479, // the type `..` (provided as the value of a type parameter) is...
2272 E0480, // lifetime of method receiver does not outlive the method call
2273 E0481, // lifetime of function argument does not outlive the function call
2274 E0482, // lifetime of return value does not outlive the function call
2275 E0483, // lifetime of operand does not outlive the operation
2276 E0484, // reference is not valid at the time of borrow
2277 E0485, // automatically reference is not valid at the time of borrow
2278 E0486, // type of expression contains references that are not valid during...
2279 E0487, // unsafe use of destructor: destructor might be called while...
2280 E0488, // lifetime of variable does not enclose its declaration
2281 E0489, // type/lifetime parameter not in scope here
2282 E0490, // a value of type `..` is borrowed for too long
2283 E0491, // in type `..`, reference has a longer lifetime than the data it...
b039eaaf 2284 E0495, // cannot infer an appropriate lifetime due to conflicting requirements
1a4d82fc 2285}