]> git.proxmox.com Git - rustc.git/blame - src/librustc/diagnostics.rs
Imported Upstream version 1.3.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
47expressions are almost never desired. This error is typically fixed by adding
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
221the heap at runtime, and therefore cannot be done at compile time.
222"##,
223
62682a34
SL
224E0011: r##"
225Initializers for constants and statics are evaluated at compile time.
226User-defined operators rely on user-defined functions, which cannot be evaluated
227at compile time.
228
229Bad example:
230
231```
232use std::ops::Index;
233
234struct Foo { a: u8 }
235
236impl Index<u8> for Foo {
237 type Output = u8;
238
239 fn index<'a>(&'a self, idx: u8) -> &'a u8 { &self.a }
240}
241
242const a: Foo = Foo { a: 0u8 };
243const b: u8 = a[0]; // Index trait is defined by the user, bad!
244```
245
246Only operators on builtin types are allowed.
247
248Example:
249
250```
251const a: &'static [i32] = &[1, 2, 3];
252const b: i32 = a[0]; // Good!
253```
254"##,
255
d9579d0f
AL
256E0013: r##"
257Static and const variables can refer to other const variables. But a const
258variable cannot refer to a static variable. For example, `Y` cannot refer to `X`
259here:
260
261```
262static X: i32 = 42;
263const Y: i32 = X;
264```
265
266To fix this, the value can be extracted as a const and then used:
267
268```
269const A: i32 = 42;
270static X: i32 = A;
271const Y: i32 = A;
272```
273"##,
274
62682a34
SL
275E0014: r##"
276Constants can only be initialized by a constant value or, in a future
277version of Rust, a call to a const function. This error indicates the use
278of a path (like a::b, or x) denoting something other than one of these
279allowed items. Example:
280
281```
282const FOO: i32 = { let x = 0; x }; // 'x' isn't a constant nor a function!
283```
284
285To avoid it, you have to replace the non-constant value:
286
287```
288const FOO: i32 = { const X : i32 = 0; X };
289// or even:
290const FOO: i32 = { 0 }; // but brackets are useless here
291```
292"##,
293
d9579d0f 294E0015: r##"
62682a34
SL
295The only functions that can be called in static or constant expressions are
296`const` functions. Rust currently does not support more general compile-time
297function execution.
298
299See [RFC 911] for more details on the design of `const fn`s.
300
301[RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
302"##,
303
304E0016: r##"
305Blocks in constants may only contain items (such as constant, function
306definition, etc...) and a tail expression. Example:
307
308```
309const FOO: i32 = { let x = 0; x }; // 'x' isn't an item!
310```
311
312To avoid it, you have to replace the non-item object:
313
314```
315const FOO: i32 = { const X : i32 = 0; X };
316```
d9579d0f
AL
317"##,
318
c1a9b12d
SL
319E0017: r##"
320References in statics and constants may only refer to immutable values. Example:
321
322```
323static X: i32 = 1;
324const C: i32 = 2;
325
326// these three are not allowed:
327const CR: &'static mut i32 = &mut C;
328static STATIC_REF: &'static mut i32 = &mut X;
329static CONST_REF: &'static mut i32 = &mut C;
330```
331
332Statics are shared everywhere, and if they refer to mutable data one might
333violate memory safety since holding multiple mutable references to shared data
334is not allowed.
335
336If you really want global mutable state, try using `static mut` or a global
337`UnsafeCell`.
338
339"##,
340
d9579d0f
AL
341E0018: r##"
342The value of static and const variables must be known at compile time. You
343can't cast a pointer as an integer because we can't know what value the
344address will take.
345
346However, pointers to other constants' addresses are allowed in constants,
347example:
348
349```
350const X: u32 = 50;
351const Y: *const u32 = &X;
352```
353
354Therefore, casting one of these non-constant pointers to an integer results
355in a non-constant integer which lead to this error. Example:
356
357```
62682a34
SL
358const X: u32 = 1;
359const Y: usize = &X as *const u32 as usize;
360println!("{}", Y);
361```
362"##,
363
364E0019: r##"
365A function call isn't allowed in the const's initialization expression
366because the expression's value must be known at compile-time. Example of
367erroneous code:
368
369```
370enum Test {
371 V1
372}
373
374impl Test {
375 fn test(&self) -> i32 {
376 12
377 }
378}
379
380fn main() {
381 const FOO: Test = Test::V1;
382
383 const A: i32 = FOO.test(); // You can't call Test::func() here !
384}
385```
386
387Remember: you can't use a function call inside a const's initialization
c1a9b12d 388expression! However, you can totally use it anywhere else:
62682a34
SL
389
390```
391fn main() {
392 const FOO: Test = Test::V1;
393
394 FOO.func(); // here is good
395 let x = FOO.func(); // or even here!
396}
d9579d0f
AL
397```
398"##,
399
400E0020: r##"
401This error indicates that an attempt was made to divide by zero (or take the
402remainder of a zero divisor) in a static or constant expression.
403"##,
404
c1a9b12d
SL
405E0022: r##"
406Constant functions are not allowed to mutate anything. Thus, binding to an
407argument with a mutable pattern is not allowed. For example,
408
409```
410const fn foo(mut x: u8) {
411 // do stuff
412}
413```
414
415is bad because the function body may not mutate `x`.
416
417Remove any mutable bindings from the argument list to fix this error. In case
418you need to mutate the argument, try lazily initializing a global variable
419instead of using a `const fn`, or refactoring the code to a functional style to
420avoid mutation if possible.
421"##,
422
423E0030: r##"
424When matching against a range, the compiler verifies that the range is
425non-empty. Range patterns include both end-points, so this is equivalent to
426requiring the start of the range to be less than or equal to the end of the
427range.
428
429For example:
430
431```
432match 5u32 {
433 // This range is ok, albeit pointless.
434 1 ... 1 => ...
435 // This range is empty, and the compiler can tell.
436 1000 ... 5 => ...
437}
438```
439"##,
440
441E0038: r####"
442Trait objects like `Box<Trait>` can only be constructed when certain
443requirements are satisfied by the trait in question.
444
445Trait objects are a form of dynamic dispatch and use a dynamically sized type
446for the inner type. So, for a given trait `Trait`, when `Trait` is treated as a
447type, as in `Box<Trait>`, the inner type is 'unsized'. In such cases the boxed
448pointer is a 'fat pointer' that contains an extra pointer to a table of methods
449(among other things) for dynamic dispatch. This design mandates some
450restrictions on the types of traits that are allowed to be used in trait
451objects, which are collectively termed as 'object safety' rules.
452
453Attempting to create a trait object for a non object-safe trait will trigger
454this error.
455
456There are various rules:
457
458### The trait cannot require `Self: Sized`
459
460When `Trait` is treated as a type, the type does not implement the special
461`Sized` trait, because the type does not have a known size at compile time and
462can only be accessed behind a pointer. Thus, if we have a trait like the
463following:
464
465```
466trait Foo where Self: Sized {
467
468}
469```
470
471we cannot create an object of type `Box<Foo>` or `&Foo` since in this case
472`Self` would not be `Sized`.
473
474Generally, `Self : Sized` is used to indicate that the trait should not be used
475as a trait object. If the trait comes from your own crate, consider removing
476this restriction.
477
478### Method references the `Self` type in its arguments or return type
479
480This happens when a trait has a method like the following:
481
482```
483trait Trait {
484 fn foo(&self) -> Self;
485}
486
487impl Trait for String {
488 fn foo(&self) -> Self {
489 "hi".to_owned()
490 }
491}
492
493impl Trait for u8 {
494 fn foo(&self) -> Self {
495 1
496 }
497}
498```
499
500(Note that `&self` and `&mut self` are okay, it's additional `Self` types which
501cause this problem)
502
503In such a case, the compiler cannot predict the return type of `foo()` in a
504situation like the following:
505
506```
507fn call_foo(x: Box<Trait>) {
508 let y = x.foo(); // What type is y?
509 // ...
510}
511```
512
513If only some methods aren't object-safe, you can add a `where Self: Sized` bound
514on them to mark them as explicitly unavailable to trait objects. The
515functionality will still be available to all other implementers, including
516`Box<Trait>` which is itself sized (assuming you `impl Trait for Box<Trait>`).
517
518```
519trait Trait {
520 fn foo(&self) -> Self where Self: Sized;
521 // more functions
522}
523```
524
525Now, `foo()` can no longer be called on a trait object, but you will now be
526allowed to make a trait object, and that will be able to call any object-safe
527methods". With such a bound, one can still call `foo()` on types implementing
528that trait that aren't behind trait objects.
529
530### Method has generic type parameters
531
532As mentioned before, trait objects contain pointers to method tables. So, if we
533have:
534
535```
536trait Trait {
537 fn foo(&self);
538}
539impl Trait for String {
540 fn foo(&self) {
541 // implementation 1
542 }
543}
544impl Trait for u8 {
545 fn foo(&self) {
546 // implementation 2
547 }
548}
549// ...
550```
551
552At compile time each implementation of `Trait` will produce a table containing
553the various methods (and other items) related to the implementation.
554
555This works fine, but when the method gains generic parameters, we can have a
556problem.
557
558Usually, generic parameters get _monomorphized_. For example, if I have
559
560```
561fn foo<T>(x: T) {
562 // ...
563}
564```
565
566the machine code for `foo::<u8>()`, `foo::<bool>()`, `foo::<String>()`, or any
567other type substitution is different. Hence the compiler generates the
568implementation on-demand. If you call `foo()` with a `bool` parameter, the
569compiler will only generate code for `foo::<bool>()`. When we have additional
570type parameters, the number of monomorphized implementations the compiler
571generates does not grow drastically, since the compiler will only generate an
572implementation if the function is called with unparametrized substitutions
573(i.e., substitutions where none of the substituted types are themselves
574parametrized).
575
576However, with trait objects we have to make a table containing _every_ object
577that implements the trait. Now, if it has type parameters, we need to add
578implementations for every type that implements the trait, and there could
579theoretically be an infinite number of types.
580
581For example, with:
582
583```
584trait Trait {
585 fn foo<T>(&self, on: T);
586 // more methods
587}
588impl Trait for String {
589 fn foo<T>(&self, on: T) {
590 // implementation 1
591 }
592}
593impl Trait for u8 {
594 fn foo<T>(&self, on: T) {
595 // implementation 2
596 }
597}
598// 8 more implementations
599```
600
601Now, if we have the following code:
602
603```
604fn call_foo(thing: Box<Trait>) {
605 thing.foo(true); // this could be any one of the 8 types above
606 thing.foo(1);
607 thing.foo("hello");
608}
609```
610
611we don't just need to create a table of all implementations of all methods of
612`Trait`, we need to create such a table, for each different type fed to
613`foo()`. In this case this turns out to be (10 types implementing `Trait`)*(3
614types being fed to `foo()`) = 30 implementations!
615
616With real world traits these numbers can grow drastically.
617
618To fix this, it is suggested to use a `where Self: Sized` bound similar to the
619fix for the sub-error above if you do not intend to call the method with type
620parameters:
621
622```
623trait Trait {
624 fn foo<T>(&self, on: T) where Self: Sized;
625 // more methods
626}
627```
628
629If this is not an option, consider replacing the type parameter with another
630trait object (e.g. if `T: OtherTrait`, use `on: Box<OtherTrait>`). If the number
631of types you intend to feed to this method is limited, consider manually listing
632out the methods of different types.
633
634### Method has no receiver
635
636Methods that do not take a `self` parameter can't be called since there won't be
637a way to get a pointer to the method table for them
638
639```
640trait Foo {
641 fn foo() -> u8;
642}
643```
644
645This could be called as `<Foo as Foo>::foo()`, which would not be able to pick
646an implementation.
647
648Adding a `Self: Sized` bound to these methods will generally make this compile.
649
650```
651trait Foo {
652 fn foo() -> u8 where Self: Sized;
653}
654```
655
656### The trait cannot use `Self` as a type parameter in the supertrait listing
657
658This is similar to the second sub-error, but subtler. It happens in situations
659like the following:
660
661```
662trait Super<A> {}
663
664trait Trait: Super<Self> {
665}
666
667struct Foo;
668
669impl Super<Foo> for Foo{}
670
671impl Trait for Foo {}
672```
673
674Here, the supertrait might have methods as follows:
675
676```
677trait Super<A> {
678 fn get_a(&self) -> A; // note that this is object safe!
679}
680```
681
682If the trait `Foo` was deriving from something like `Super<String>` or
683`Super<T>` (where `Foo` itself is `Foo<T>`), this is okay, because given a type
684`get_a()` will definitely return an object of that type.
685
686However, if it derives from `Super<Self>`, even though `Super` is object safe,
687the method `get_a()` would return an object of unknown type when called on the
688function. `Self` type parameters let us make object safe traits no longer safe,
689so they are forbidden when specifying supertraits.
690
691There's no easy fix for this, generally code will need to be refactored so that
692you no longer need to derive from `Super<Self>`.
693"####,
694
d9579d0f
AL
695E0079: r##"
696Enum variants which contain no data can be given a custom integer
c1a9b12d
SL
697representation. This error indicates that the value provided is not an integer
698literal and is therefore invalid.
699
700For example, in the following code,
701
702```
703enum Foo {
704 Q = "32"
705}
706```
707
708we try to set the representation to a string.
709
710There's no general fix for this; if you can work with an integer then just set
711it to one:
712
713```
714enum Foo {
715 Q = 32
716}
717```
718
719however if you actually wanted a mapping between variants and non-integer
720objects, it may be preferable to use a method with a match instead:
721
722```
723enum Foo { Q }
724impl Foo {
725 fn get_str(&self) -> &'static str {
726 match *self {
727 Foo::Q => "32",
728 }
729 }
730}
731```
d9579d0f
AL
732"##,
733
734E0080: r##"
735This error indicates that the compiler was unable to sensibly evaluate an
736integer expression provided as an enum discriminant. Attempting to divide by 0
737or causing integer overflow are two ways to induce this error. For example:
738
739```
740enum Enum {
741 X = (1 << 500),
742 Y = (1 / 0)
743}
744```
745
746Ensure that the expressions given can be evaluated as the desired integer type.
747See the FFI section of the Reference for more information about using a custom
748integer type:
749
c1a9b12d
SL
750https://doc.rust-lang.org/reference.html#ffi-attributes
751"##,
752
753E0109: r##"
754You tried to give a type parameter to a type which doesn't need it. Erroneous
755code example:
756
757```
758type X = u32<i32>; // error: type parameters are not allowed on this type
759```
760
761Please check that you used the correct type and recheck its definition. Perhaps
762it doesn't need the type parameter.
763
764Example:
765
766```
767type X = u32; // this compiles
768```
769
770Note that type parameters for enum-variant constructors go after the variant,
771not after the enum (Option::None::<u32>, not Option::<u32>::None).
772"##,
773
774E0110: r##"
775You tried to give a lifetime parameter to a type which doesn't need it.
776Erroneous code example:
777
778```
779type X = u32<'static>; // error: lifetime parameters are not allowed on
780 // this type
781```
782
783Please check that the correct type was used and recheck its definition; perhaps
784it doesn't need the lifetime parameter. Example:
785
786```
787type X = u32; // ok!
788```
d9579d0f
AL
789"##,
790
791E0133: r##"
792Using unsafe functionality, such as dereferencing raw pointers and calling
793functions via FFI or marked as unsafe, is potentially dangerous and disallowed
62682a34
SL
794by safety checks. These safety checks can be relaxed for a section of the code
795by wrapping the unsafe instructions with an `unsafe` block. For instance:
d9579d0f
AL
796
797```
798unsafe fn f() { return; }
799
800fn main() {
801 unsafe { f(); }
802}
803```
804
c1a9b12d
SL
805See also https://doc.rust-lang.org/book/unsafe.html
806"##,
807
808// This shouldn't really ever trigger since the repeated value error comes first
809E0136: r##"
810A binary can only have one entry point, and by default that entry point is the
811function `main()`. If there are multiple such functions, please rename one.
d9579d0f
AL
812"##,
813
814E0137: r##"
815This error indicates that the compiler found multiple functions with the
816`#[main]` attribute. This is an error because there must be a unique entry
817point into a Rust program.
818"##,
819
c1a9b12d
SL
820E0138: r##"
821This error indicates that the compiler found multiple functions with the
822`#[start]` attribute. This is an error because there must be a unique entry
823point into a Rust program.
824"##,
825
826// FIXME link this to the relevant turpl chapters for instilling fear of the
827// transmute gods in the user
828E0139: r##"
829There are various restrictions on transmuting between types in Rust; for example
830types being transmuted must have the same size. To apply all these restrictions,
831the compiler must know the exact types that may be transmuted. When type
832parameters are involved, this cannot always be done.
833
834So, for example, the following is not allowed:
835
836```
837struct Foo<T>(Vec<T>)
838
839fn foo<T>(x: Vec<T>) {
840 // we are transmuting between Vec<T> and Foo<T> here
841 let y: Foo<T> = unsafe { transmute(x) };
842 // do something with y
843}
844```
845
846In this specific case there's a good chance that the transmute is harmless (but
847this is not guaranteed by Rust). However, when alignment and enum optimizations
848come into the picture, it's quite likely that the sizes may or may not match
849with different type parameter substitutions. It's not possible to check this for
850_all_ possible types, so `transmute()` simply only accepts types without any
851unsubstituted type parameters.
852
853If you need this, there's a good chance you're doing something wrong. Keep in
854mind that Rust doesn't guarantee much about the layout of different structs
855(even two structs with identical declarations may have different layouts). If
856there is a solution that avoids the transmute entirely, try it instead.
857
858If it's possible, hand-monomorphize the code by writing the function for each
859possible type substitution. It's possible to use traits to do this cleanly,
860for example:
861
862```
863trait MyTransmutableType {
864 fn transmute(Vec<Self>) -> Foo<Self>
865}
866
867impl MyTransmutableType for u8 {
868 fn transmute(x: Foo<u8>) -> Vec<u8> {
869 transmute(x)
870 }
871}
872impl MyTransmutableType for String {
873 fn transmute(x: Foo<String>) -> Vec<String> {
874 transmute(x)
875 }
876}
877// ... more impls for the types you intend to transmute
878
879fn foo<T: MyTransmutableType>(x: Vec<T>) {
880 let y: Foo<T> = <T as MyTransmutableType>::transmute(x);
881 // do something with y
882}
883```
884
885Each impl will be checked for a size match in the transmute as usual, and since
886there are no unbound type parameters involved, this should compile unless there
887is a size mismatch in one of the impls.
888
889It is also possible to manually transmute:
890
891```
892let result: SomeType = mem::uninitialized();
893unsafe { copy_nonoverlapping(&v, &result) };
894result // `v` transmuted to type `SomeType`
895```
896"##,
897
d9579d0f
AL
898E0152: r##"
899Lang items are already implemented in the standard library. Unless you are
900writing a free-standing application (e.g. a kernel), you do not need to provide
901them yourself.
902
903You can build a free-standing crate by adding `#![no_std]` to the crate
904attributes:
905
906```
907#![feature(no_std)]
908#![no_std]
909```
910
911See also https://doc.rust-lang.org/book/no-stdlib.html
912"##,
913
914E0158: r##"
915`const` and `static` mean different things. A `const` is a compile-time
916constant, an alias for a literal value. This property means you can match it
917directly within a pattern.
918
919The `static` keyword, on the other hand, guarantees a fixed location in memory.
920This does not always mean that the value is constant. For example, a global
921mutex can be declared `static` as well.
922
923If you want to match against a `static`, consider using a guard instead:
924
925```
926static FORTY_TWO: i32 = 42;
927match Some(42) {
928 Some(x) if x == FORTY_TWO => ...
929 ...
930}
931```
932"##,
933
934E0161: r##"
935In Rust, you can only move a value when its size is known at compile time.
936
937To work around this restriction, consider "hiding" the value behind a reference:
938either `&x` or `&mut x`. Since a reference has a fixed size, this lets you move
939it around as usual.
940"##,
941
9346a6ac
AL
942E0162: r##"
943An if-let pattern attempts to match the pattern, and enters the body if the
d9579d0f
AL
944match was successful. If the match is irrefutable (when it cannot fail to
945match), use a regular `let`-binding instead. For instance:
9346a6ac 946
d9579d0f 947```
9346a6ac
AL
948struct Irrefutable(i32);
949let irr = Irrefutable(0);
950
951// This fails to compile because the match is irrefutable.
952if let Irrefutable(x) = irr {
953 // This body will always be executed.
954 foo(x);
955}
956
957// Try this instead:
958let Irrefutable(x) = irr;
959foo(x);
d9579d0f 960```
85aaf69f
SL
961"##,
962
9346a6ac
AL
963E0165: r##"
964A while-let pattern attempts to match the pattern, and enters the body if the
d9579d0f
AL
965match was successful. If the match is irrefutable (when it cannot fail to
966match), use a regular `let`-binding inside a `loop` instead. For instance:
9346a6ac 967
d9579d0f 968```
9346a6ac
AL
969struct Irrefutable(i32);
970let irr = Irrefutable(0);
971
972// This fails to compile because the match is irrefutable.
973while let Irrefutable(x) = irr {
974 ...
975}
976
977// Try this instead:
978loop {
979 let Irrefutable(x) = irr;
980 ...
981}
d9579d0f
AL
982```
983"##,
984
985E0170: r##"
986Enum variants are qualified by default. For example, given this type:
987
988```
989enum Method {
990 GET,
991 POST
992}
993```
994
995you would match it using:
996
997```
998match m {
999 Method::GET => ...
1000 Method::POST => ...
1001}
1002```
1003
1004If you don't qualify the names, the code will bind new variables named "GET" and
1005"POST" instead. This behavior is likely not what you want, so `rustc` warns when
1006that happens.
1007
1008Qualified names are good practice, and most code works well with them. But if
1009you prefer them unqualified, you can import the variants into scope:
1010
1011```
1012use Method::*;
1013enum Method { GET, POST }
1014```
c1a9b12d
SL
1015
1016If you want others to be able to import variants from your module directly, use
1017`pub use`:
1018
1019```
1020pub use Method::*;
1021enum Method { GET, POST }
1022```
d9579d0f
AL
1023"##,
1024
62682a34
SL
1025E0261: r##"
1026When using a lifetime like `'a` in a type, it must be declared before being
1027used.
1028
1029These two examples illustrate the problem:
1030
1031```
1032// error, use of undeclared lifetime name `'a`
1033fn foo(x: &'a str) { }
1034
1035struct Foo {
1036 // error, use of undeclared lifetime name `'a`
1037 x: &'a str,
1038}
1039```
1040
1041These can be fixed by declaring lifetime parameters:
1042
1043```
1044fn foo<'a>(x: &'a str) { }
1045
1046struct Foo<'a> {
1047 x: &'a str,
1048}
1049```
1050"##,
1051
1052E0262: r##"
1053Declaring certain lifetime names in parameters is disallowed. For example,
1054because the `'static` lifetime is a special built-in lifetime name denoting
1055the lifetime of the entire program, this is an error:
1056
1057```
c1a9b12d 1058// error, invalid lifetime parameter name `'static`
62682a34
SL
1059fn foo<'static>(x: &'static str) { }
1060```
1061"##,
1062
1063E0263: r##"
1064A lifetime name cannot be declared more than once in the same scope. For
1065example:
1066
1067```
1068// error, lifetime name `'a` declared twice in the same scope
1069fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { }
1070```
1071"##,
1072
d9579d0f
AL
1073E0265: r##"
1074This error indicates that a static or constant references itself.
1075All statics and constants need to resolve to a value in an acyclic manner.
1076
1077For example, neither of the following can be sensibly compiled:
1078
1079```
1080const X: u32 = X;
1081```
1082
1083```
1084const X: u32 = Y;
1085const Y: u32 = X;
1086```
1087"##,
1088
1089E0267: r##"
1090This error indicates the use of a loop keyword (`break` or `continue`) inside a
c1a9b12d
SL
1091closure but outside of any loop. Erroneous code example:
1092
1093```
1094let w = || { break; }; // error: `break` inside of a closure
1095```
1096
1097`break` and `continue` keywords can be used as normal inside closures as long as
1098they are also contained within a loop. To halt the execution of a closure you
1099should instead use a return statement. Example:
1100
1101```
1102let w = || {
1103 for _ in 0..10 {
1104 break;
1105 }
1106};
1107
1108w();
1109```
d9579d0f
AL
1110"##,
1111
1112E0268: r##"
1113This error indicates the use of a loop keyword (`break` or `continue`) outside
1114of a loop. Without a loop to break out of or continue in, no sensible action can
c1a9b12d
SL
1115be taken. Erroneous code example:
1116
1117```
1118fn some_func() {
1119 break; // error: `break` outside of loop
1120}
1121```
1122
1123Please verify that you are using `break` and `continue` only in loops. Example:
1124
1125```
1126fn some_func() {
1127 for _ in 0..10 {
1128 break; // ok!
1129 }
1130}
1131```
1132"##,
1133
1134E0269: r##"
1135Functions must eventually return a value of their return type. For example, in
1136the following function
1137
1138```
1139fn foo(x: u8) -> u8 {
1140 if x > 0 {
1141 x // alternatively, `return x`
1142 }
1143 // nothing here
1144}
1145```
1146
1147if the condition is true, the value `x` is returned, but if the condition is
1148false, control exits the `if` block and reaches a place where nothing is being
1149returned. All possible control paths must eventually return a `u8`, which is not
1150happening here.
1151
1152An easy fix for this in a complicated function is to specify a default return
1153value, if possible:
1154
1155```
1156fn foo(x: u8) -> u8 {
1157 if x > 0 {
1158 x // alternatively, `return x`
1159 }
1160 // lots of other if branches
1161 0 // return 0 if all else fails
1162}
1163```
1164
1165It is advisable to find out what the unhandled cases are and check for them,
1166returning an appropriate value or panicking if necessary.
1167"##,
1168
1169E0270: r##"
1170Rust lets you define functions which are known to never return, i.e. are
1171'diverging', by marking its return type as `!`.
1172
1173For example, the following functions never return:
1174
1175```
1176fn foo() -> ! {
1177 loop {}
1178}
1179
1180fn bar() -> ! {
1181 foo() // foo() is diverging, so this will diverge too
1182}
1183
1184fn baz() -> ! {
1185 panic!(); // this macro internally expands to a call to a diverging function
1186}
1187
1188```
1189
1190Such functions can be used in a place where a value is expected without
1191returning a value of that type, for instance:
1192
1193```
1194let y = match x {
1195 1 => 1,
1196 2 => 4,
1197 _ => foo() // diverging function called here
1198};
1199println!("{}", y)
1200```
1201
1202If the third arm of the match block is reached, since `foo()` doesn't ever
1203return control to the match block, it is fine to use it in a place where an
1204integer was expected. The `match` block will never finish executing, and any
1205point where `y` (like the print statement) is needed will not be reached.
1206
1207However, if we had a diverging function that actually does finish execution
1208
1209```
1210fn foo() -> {
1211 loop {break;}
1212}
1213```
1214
1215then we would have an unknown value for `y` in the following code:
1216
1217```
1218let y = match x {
1219 1 => 1,
1220 2 => 4,
1221 _ => foo()
1222};
1223println!("{}", y);
1224```
1225
1226In the previous example, the print statement was never reached when the wildcard
1227match arm was hit, so we were okay with `foo()` not returning an integer that we
1228could set to `y`. But in this example, `foo()` actually does return control, so
1229the print statement will be executed with an uninitialized value.
1230
1231Obviously we cannot have functions which are allowed to be used in such
1232positions and yet can return control. So, if you are defining a function that
1233returns `!`, make sure that there is no way for it to actually finish executing.
d9579d0f
AL
1234"##,
1235
1236E0271: r##"
1237This is because of a type mismatch between the associated type of some
1238trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
1239and another type `U` that is required to be equal to `T::Bar`, but is not.
1240Examples follow.
1241
1242Here is a basic example:
1243
1244```
1245trait Trait { type AssociatedType; }
1246fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1247 println!("in foo");
1248}
1249impl Trait for i8 { type AssociatedType = &'static str; }
1250foo(3_i8);
1251```
1252
1253Here is that same example again, with some explanatory comments:
1254
1255```
1256trait Trait { type AssociatedType; }
1257
1258fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
1259// ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
1260// | |
1261// This says `foo` can |
1262// only be used with |
1263// some type that |
1264// implements `Trait`. |
1265// |
1266// This says not only must
1267// `T` be an impl of `Trait`
1268// but also that the impl
1269// must assign the type `u32`
1270// to the associated type.
1271 println!("in foo");
1272}
1273
1274impl Trait for i8 { type AssociatedType = &'static str; }
1275~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1276// | |
1277// `i8` does have |
1278// implementation |
1279// of `Trait`... |
1280// ... but it is an implementation
1281// that assigns `&'static str` to
1282// the associated type.
1283
1284foo(3_i8);
1285// Here, we invoke `foo` with an `i8`, which does not satisfy
62682a34 1286// the constraint `<i8 as Trait>::AssociatedType=u32`, and
d9579d0f
AL
1287// therefore the type-checker complains with this error code.
1288```
1289
1290Here is a more subtle instance of the same problem, that can
1291arise with for-loops in Rust:
1292
1293```
1294let vs: Vec<i32> = vec![1, 2, 3, 4];
1295for v in &vs {
1296 match v {
1297 1 => {}
1298 _ => {}
1299 }
1300}
1301```
1302
1303The above fails because of an analogous type mismatch,
1304though may be harder to see. Again, here are some
1305explanatory comments for the same example:
1306
1307```
1308{
1309 let vs = vec![1, 2, 3, 4];
1310
1311 // `for`-loops use a protocol based on the `Iterator`
1312 // trait. Each item yielded in a `for` loop has the
1313 // type `Iterator::Item` -- that is,I `Item` is the
1314 // associated type of the concrete iterator impl.
1315 for v in &vs {
1316// ~ ~~~
1317// | |
1318// | We borrow `vs`, iterating over a sequence of
1319// | *references* of type `&Elem` (where `Elem` is
1320// | vector's element type). Thus, the associated
1321// | type `Item` must be a reference `&`-type ...
1322// |
1323// ... and `v` has the type `Iterator::Item`, as dictated by
1324// the `for`-loop protocol ...
1325
1326 match v {
1327 1 => {}
1328// ~
1329// |
1330// ... but *here*, `v` is forced to have some integral type;
1331// only types like `u8`,`i8`,`u16`,`i16`, et cetera can
1332// match the pattern `1` ...
1333
1334 _ => {}
1335 }
1336
1337// ... therefore, the compiler complains, because it sees
1338// an attempt to solve the equations
1339// `some integral-type` = type-of-`v`
1340// = `Iterator::Item`
1341// = `&Elem` (i.e. `some reference type`)
1342//
1343// which cannot possibly all be true.
1344
1345 }
1346}
1347```
1348
1349To avoid those issues, you have to make the types match correctly.
1350So we can fix the previous examples like this:
1351
1352```
1353// Basic Example:
1354trait Trait { type AssociatedType; }
1355fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
1356 println!("in foo");
1357}
1358impl Trait for i8 { type AssociatedType = &'static str; }
1359foo(3_i8);
1360
1361// For-Loop Example:
1362let vs = vec![1, 2, 3, 4];
1363for v in &vs {
1364 match v {
1365 &1 => {}
1366 _ => {}
1367 }
1368}
1369```
1370"##,
1371
c1a9b12d
SL
1372E0272: r##"
1373The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1374message for when a particular trait isn't implemented on a type placed in a
1375position that needs that trait. For example, when the following code is
1376compiled:
1377
1378```
1379fn foo<T: Index<u8>>(x: T){}
1380
1381#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1382trait Index<Idx> { ... }
1383
1384foo(true); // `bool` does not implement `Index<u8>`
1385```
1386
1387there will be an error about `bool` not implementing `Index<u8>`, followed by a
1388note saying "the type `bool` cannot be indexed by `u8`".
1389
1390As you can see, you can specify type parameters in curly braces for substitution
1391with the actual types (using the regular format string syntax) in a given
1392situation. Furthermore, `{Self}` will substitute to the type (in this case,
1393`bool`) that we tried to use.
1394
1395This error appears when the curly braces contain an identifier which doesn't
1396match with any of the type parameters or the string `Self`. This might happen if
1397you misspelled a type parameter, or if you intended to use literal curly braces.
1398If it is the latter, escape the curly braces with a second curly brace of the
1399same type; e.g. a literal `{` is `{{`
1400"##,
1401
1402E0273: r##"
1403The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1404message for when a particular trait isn't implemented on a type placed in a
1405position that needs that trait. For example, when the following code is
1406compiled:
1407
1408```
1409fn foo<T: Index<u8>>(x: T){}
1410
1411#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1412trait Index<Idx> { ... }
1413
1414foo(true); // `bool` does not implement `Index<u8>`
1415```
1416
1417there will be an error about `bool` not implementing `Index<u8>`, followed by a
1418note saying "the type `bool` cannot be indexed by `u8`".
1419
1420As you can see, you can specify type parameters in curly braces for substitution
1421with the actual types (using the regular format string syntax) in a given
1422situation. Furthermore, `{Self}` will substitute to the type (in this case,
1423`bool`) that we tried to use.
1424
1425This error appears when the curly braces do not contain an identifier. Please
1426add one of the same name as a type parameter. If you intended to use literal
1427braces, use `{{` and `}}` to escape them.
1428"##,
1429
1430E0274: r##"
1431The `#[rustc_on_unimplemented]` attribute lets you specify a custom error
1432message for when a particular trait isn't implemented on a type placed in a
1433position that needs that trait. For example, when the following code is
1434compiled:
1435
1436```
1437fn foo<T: Index<u8>>(x: T){}
1438
1439#[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"]
1440trait Index<Idx> { ... }
1441
1442foo(true); // `bool` does not implement `Index<u8>`
1443```
1444
1445there will be an error about `bool` not implementing `Index<u8>`, followed by a
1446note saying "the type `bool` cannot be indexed by `u8`".
1447
1448For this to work, some note must be specified. An empty attribute will not do
1449anything, please remove the attribute or add some helpful note for users of the
1450trait.
1451"##,
1452
1453E0275: r##"
1454This error occurs when there was a recursive trait requirement that overflowed
1455before it could be evaluated. Often this means that there is unbounded recursion
1456in resolving some type bounds.
1457
1458For example, in the following code
1459
1460```
1461trait Foo {}
1462
1463struct Bar<T>(T);
1464
1465impl<T> Foo for T where Bar<T>: Foo {}
1466```
1467
1468to determine if a `T` is `Foo`, we need to check if `Bar<T>` is `Foo`. However,
1469to do this check, we need to determine that `Bar<Bar<T>>` is `Foo`. To determine
1470this, we check if `Bar<Bar<Bar<T>>>` is `Foo`, and so on. This is clearly a
1471recursive requirement that can't be resolved directly.
1472
1473Consider changing your trait bounds so that they're less self-referential.
1474"##,
1475
1476E0276: r##"
1477This error occurs when a bound in an implementation of a trait does not match
1478the bounds specified in the original trait. For example:
1479
1480```
1481trait Foo {
1482 fn foo<T>(x: T);
1483}
1484
1485impl Foo for bool {
1486 fn foo<T>(x: T) where T: Copy {}
1487}
1488```
1489
1490Here, all types implementing `Foo` must have a method `foo<T>(x: T)` which can
1491take any type `T`. However, in the `impl` for `bool`, we have added an extra
1492bound that `T` is `Copy`, which isn't compatible with the original trait.
1493
1494Consider removing the bound from the method or adding the bound to the original
1495method definition in the trait.
1496"##,
1497
1498E0277: r##"
1499You tried to use a type which doesn't implement some trait in a place which
1500expected that trait. Erroneous code example:
1501
1502```
1503// here we declare the Foo trait with a bar method
1504trait Foo {
1505 fn bar(&self);
1506}
1507
1508// we now declare a function which takes an object implementing the Foo trait
1509fn some_func<T: Foo>(foo: T) {
1510 foo.bar();
1511}
1512
1513fn main() {
1514 // we now call the method with the i32 type, which doesn't implement
1515 // the Foo trait
1516 some_func(5i32); // error: the trait `Foo` is not implemented for the
1517 // type `i32`
1518}
1519```
1520
1521In order to fix this error, verify that the type you're using does implement
1522the trait. Example:
1523
1524```
1525trait Foo {
1526 fn bar(&self);
1527}
1528
1529fn some_func<T: Foo>(foo: T) {
1530 foo.bar(); // we can now use this method since i32 implements the
1531 // Foo trait
1532}
1533
1534// we implement the trait on the i32 type
1535impl Foo for i32 {
1536 fn bar(&self) {}
1537}
1538
1539fn main() {
1540 some_func(5i32); // ok!
1541}
1542```
1543"##,
1544
d9579d0f
AL
1545E0282: r##"
1546This error indicates that type inference did not result in one unique possible
1547type, and extra information is required. In most cases this can be provided
1548by adding a type annotation. Sometimes you need to specify a generic type
1549parameter manually.
1550
1551A common example is the `collect` method on `Iterator`. It has a generic type
1552parameter with a `FromIterator` bound, which for a `char` iterator is
1553implemented by `Vec` and `String` among others. Consider the following snippet
1554that reverses the characters of a string:
1555
1556```
1557let x = "hello".chars().rev().collect();
1558```
1559
1560In this case, the compiler cannot infer what the type of `x` should be:
1561`Vec<char>` and `String` are both suitable candidates. To specify which type to
1562use, you can use a type annotation on `x`:
1563
1564```
1565let x: Vec<char> = "hello".chars().rev().collect();
1566```
1567
1568It is not necessary to annotate the full type. Once the ambiguity is resolved,
1569the compiler can infer the rest:
1570
1571```
1572let x: Vec<_> = "hello".chars().rev().collect();
1573```
1574
1575Another way to provide the compiler with enough information, is to specify the
1576generic type parameter:
1577
1578```
1579let x = "hello".chars().rev().collect::<Vec<char>>();
1580```
1581
1582Again, you need not specify the full type if the compiler can infer it:
1583
1584```
1585let x = "hello".chars().rev().collect::<Vec<_>>();
1586```
1587
1588Apart from a method or function with a generic type parameter, this error can
1589occur when a type parameter of a struct or trait cannot be inferred. In that
1590case it is not always possible to use a type annotation, because all candidates
1591have the same return type. For instance:
1592
1593```
1594struct Foo<T> {
1595 // Some fields omitted.
1596}
1597
1598impl<T> Foo<T> {
1599 fn bar() -> i32 {
1600 0
1601 }
1602
1603 fn baz() {
1604 let number = Foo::bar();
1605 }
1606}
1607```
1608
1609This will fail because the compiler does not know which instance of `Foo` to
1610call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.
1611"##,
1612
1613E0296: r##"
1614This error indicates that the given recursion limit could not be parsed. Ensure
1615that the value provided is a positive integer between quotes, like so:
1616
1617```
1618#![recursion_limit="1000"]
1619```
85aaf69f
SL
1620"##,
1621
9346a6ac
AL
1622E0297: r##"
1623Patterns used to bind names must be irrefutable. That is, they must guarantee
1624that a name will be extracted in all cases. Instead of pattern matching the
1625loop variable, consider using a `match` or `if let` inside the loop body. For
1626instance:
1627
d9579d0f 1628```
9346a6ac
AL
1629// This fails because `None` is not covered.
1630for Some(x) in xs {
1631 ...
1632}
1633
1634// Match inside the loop instead:
1635for item in xs {
1636 match item {
1637 Some(x) => ...
1638 None => ...
1639 }
1640}
85aaf69f 1641
9346a6ac
AL
1642// Or use `if let`:
1643for item in xs {
1644 if let Some(x) = item {
1645 ...
1646 }
1647}
d9579d0f 1648```
85aaf69f
SL
1649"##,
1650
9346a6ac
AL
1651E0301: r##"
1652Mutable borrows are not allowed in pattern guards, because matching cannot have
1653side effects. Side effects could alter the matched object or the environment
1654on which the match depends in such a way, that the match would not be
1655exhaustive. For instance, the following would not match any arm if mutable
1656borrows were allowed:
1657
d9579d0f 1658```
9346a6ac
AL
1659match Some(()) {
1660 None => { },
1661 option if option.take().is_none() => { /* impossible, option is `Some` */ },
1662 Some(_) => { } // When the previous match failed, the option became `None`.
1663}
d9579d0f 1664```
9346a6ac
AL
1665"##,
1666
1667E0302: r##"
1668Assignments are not allowed in pattern guards, because matching cannot have
1669side effects. Side effects could alter the matched object or the environment
1670on which the match depends in such a way, that the match would not be
1671exhaustive. For instance, the following would not match any arm if assignments
1672were allowed:
1673
d9579d0f 1674```
9346a6ac
AL
1675match Some(()) {
1676 None => { },
1677 option if { option = None; false } { },
1678 Some(_) => { } // When the previous match failed, the option became `None`.
1679}
d9579d0f 1680```
85aaf69f
SL
1681"##,
1682
9346a6ac
AL
1683E0303: r##"
1684In certain cases it is possible for sub-bindings to violate memory safety.
1685Updates to the borrow checker in a future version of Rust may remove this
1686restriction, but for now patterns must be rewritten without sub-bindings.
1687
d9579d0f 1688```
c1a9b12d
SL
1689// Before.
1690match Some("hi".to_string()) {
1691 ref op_string_ref @ Some(ref s) => ...
9346a6ac
AL
1692 None => ...
1693}
1694
d9579d0f
AL
1695// After.
1696match Some("hi".to_string()) {
1697 Some(ref s) => {
c1a9b12d 1698 let op_string_ref = &Some(s);
9346a6ac
AL
1699 ...
1700 }
1701 None => ...
1702}
d9579d0f
AL
1703```
1704
1705The `op_string_ref` binding has type `&Option<&String>` in both cases.
9346a6ac
AL
1706
1707See also https://github.com/rust-lang/rust/issues/14587
d9579d0f
AL
1708"##,
1709
1710E0306: r##"
1711In an array literal `[x; N]`, `N` is the number of elements in the array. This
1712number cannot be negative.
1713"##,
1714
1715E0307: r##"
1716The length of an array is part of its type. For this reason, this length must be
1717a compile-time constant.
1718"##,
1719
1720E0308: r##"
1721This error occurs when the compiler was unable to infer the concrete type of a
c1a9b12d 1722variable. It can occur for several cases, the most common of which is a
d9579d0f
AL
1723mismatch in the expected type that the compiler inferred for a variable's
1724initializing expression, and the actual type explicitly assigned to the
1725variable.
1726
1727For example:
1728
1729```
1730let x: i32 = "I am not a number!";
1731// ~~~ ~~~~~~~~~~~~~~~~~~~~
1732// | |
1733// | initializing expression;
1734// | compiler infers type `&str`
1735// |
1736// type `i32` assigned to variable `x`
1737```
1738"##,
1739
1740E0309: r##"
1741Types in type definitions have lifetimes associated with them that represent
1742how long the data stored within them is guaranteed to be live. This lifetime
1743must be as long as the data needs to be alive, and missing the constraint that
1744denotes this will cause this error.
1745
1746```
1747// This won't compile because T is not constrained, meaning the data
1748// stored in it is not guaranteed to last as long as the reference
1749struct Foo<'a, T> {
1750 foo: &'a T
1751}
1752
1753// This will compile, because it has the constraint on the type parameter
1754struct Foo<'a, T: 'a> {
1755 foo: &'a T
1756}
1757```
1758"##,
1759
1760E0310: r##"
1761Types in type definitions have lifetimes associated with them that represent
1762how long the data stored within them is guaranteed to be live. This lifetime
1763must be as long as the data needs to be alive, and missing the constraint that
1764denotes this will cause this error.
1765
1766```
1767// This won't compile because T is not constrained to the static lifetime
1768// the reference needs
1769struct Foo<T> {
1770 foo: &'static T
1771}
1772
1773// This will compile, because it has the constraint on the type parameter
1774struct Foo<T: 'static> {
1775 foo: &'static T
1776}
1777```
62682a34
SL
1778"##,
1779
1780E0378: r##"
1781Method calls that aren't calls to inherent `const` methods are disallowed
1782in statics, constants, and constant functions.
1783
1784For example:
1785
1786```
1787const BAZ: i32 = Foo(25).bar(); // error, `bar` isn't `const`
1788
1789struct Foo(i32);
1790
1791impl Foo {
1792 const fn foo(&self) -> i32 {
1793 self.bar() // error, `bar` isn't `const`
1794 }
1795
1796 fn bar(&self) -> i32 { self.0 }
1797}
1798```
1799
1800For more information about `const fn`'s, see [RFC 911].
1801
1802[RFC 911]: https://github.com/rust-lang/rfcs/blob/master/text/0911-const-fn.md
1803"##,
1804
1805E0394: r##"
1806From [RFC 246]:
1807
c1a9b12d 1808 > It is invalid for a static to reference another static by value. It is
62682a34
SL
1809 > required that all references be borrowed.
1810
1811[RFC 246]: https://github.com/rust-lang/rfcs/pull/246
1812"##,
1813
c1a9b12d
SL
1814E0395: r##"
1815The value assigned to a constant expression must be known at compile time,
1816which is not the case when comparing raw pointers. Erroneous code example:
1817
1818```
1819static foo: i32 = 42;
1820static bar: i32 = 43;
1821
1822static baz: bool = { (&foo as *const i32) == (&bar as *const i32) };
1823// error: raw pointers cannot be compared in statics!
1824```
1825
1826Please check that the result of the comparison can be determined at compile time
1827or isn't assigned to a constant expression. Example:
1828
1829```
1830static foo: i32 = 42;
1831static bar: i32 = 43;
1832
1833let baz: bool = { (&foo as *const i32) == (&bar as *const i32) };
1834// baz isn't a constant expression so it's ok
1835```
1836"##,
1837
1838E0396: r##"
1839The value assigned to a constant expression must be known at compile time,
1840which is not the case when dereferencing raw pointers. Erroneous code
1841example:
1842
1843```
1844const foo: i32 = 42;
1845const baz: *const i32 = (&foo as *const i32);
1846
1847const deref: i32 = *baz;
1848// error: raw pointers cannot be dereferenced in constants
1849```
1850
1851To fix this error, please do not assign this value to a constant expression.
1852Example:
1853
1854```
1855const foo: i32 = 42;
1856const baz: *const i32 = (&foo as *const i32);
1857
1858unsafe { let deref: i32 = *baz; }
1859// baz isn't a constant expression so it's ok
1860```
1861
1862You'll also note that this assignment must be done in an unsafe block!
1863"##,
1864
62682a34
SL
1865E0397: r##"
1866It is not allowed for a mutable static to allocate or have destructors. For
1867example:
1868
1869```
1870// error: mutable statics are not allowed to have boxes
1871static mut FOO: Option<Box<usize>> = None;
1872
1873// error: mutable statics are not allowed to have destructors
1874static mut BAR: Option<Vec<i32>> = None;
1875```
1876"##,
1877
1878E0398: r##"
1879In Rust 1.3, the default object lifetime bounds are expected to
1880change, as described in RFC #1156 [1]. You are getting a warning
1881because the compiler thinks it is possible that this change will cause
1882a compilation error in your code. It is possible, though unlikely,
1883that this is a false alarm.
1884
1885The heart of the change is that where `&'a Box<SomeTrait>` used to
1886default to `&'a Box<SomeTrait+'a>`, it now defaults to `&'a
1887Box<SomeTrait+'static>` (here, `SomeTrait` is the name of some trait
1888type). Note that the only types which are affected are references to
1889boxes, like `&Box<SomeTrait>` or `&[Box<SomeTrait>]`. More common
1890types like `&SomeTrait` or `Box<SomeTrait>` are unaffected.
1891
1892To silence this warning, edit your code to use an explicit bound.
1893Most of the time, this means that you will want to change the
1894signature of a function that you are calling. For example, if
1895the error is reported on a call like `foo(x)`, and `foo` is
1896defined as follows:
1897
1898```
1899fn foo(arg: &Box<SomeTrait>) { ... }
1900```
1901
1902you might change it to:
1903
1904```
1905fn foo<'a>(arg: &Box<SomeTrait+'a>) { ... }
1906```
1907
1908This explicitly states that you expect the trait object `SomeTrait` to
1909contain references (with a maximum lifetime of `'a`).
1910
1911[1]: https://github.com/rust-lang/rfcs/pull/1156
85aaf69f 1912"##
9346a6ac 1913
85aaf69f 1914}
1a4d82fc 1915
d9579d0f 1916
1a4d82fc 1917register_diagnostics! {
c1a9b12d
SL
1918 // E0006 // merged with E0005
1919// E0134,
1920// E0135,
85aaf69f 1921 E0264, // unknown external lang item
85aaf69f
SL
1922 E0278, // requirement is not satisfied
1923 E0279, // requirement is not satisfied
1924 E0280, // requirement is not satisfied
1925 E0281, // type implements trait but other trait is required
85aaf69f
SL
1926 E0283, // cannot resolve type
1927 E0284, // cannot resolve type
1928 E0285, // overflow evaluation builtin bounds
85aaf69f
SL
1929 E0298, // mismatched types between arms
1930 E0299, // mismatched types between arms
1931 E0300, // unexpanded macro
85aaf69f
SL
1932 E0304, // expected signed integer constant
1933 E0305, // expected constant
85aaf69f
SL
1934 E0311, // thing may not live long enough
1935 E0312, // lifetime of reference outlives lifetime of borrowed content
1936 E0313, // lifetime of borrowed pointer outlives lifetime of captured variable
1937 E0314, // closure outlives stack frame
1938 E0315, // cannot invoke closure outside of its lifetime
c34b1796 1939 E0316, // nested quantification of lifetimes
62682a34 1940 E0370, // discriminant overflow
c1a9b12d 1941 E0400 // overloaded derefs are not allowed in constants
1a4d82fc 1942}