{"_id":"doc-en-rust-4afe5857f53f951490166aa76a1b7c29ce180c19c88275a9279183844654065a","title":"","text":"// be added explicitly if necessary, see the error in `fn link_rlib`) compiled // as an executable due to `--test`. Use whole-archive implicitly, like before // the introduction of native lib modifiers. || (bundle != Some(false) && sess.opts.test) || (whole_archive == None && bundle != Some(false) && sess.opts.test) { cmd.link_whole_staticlib( name,"} {"_id":"doc-en-rust-624ae0ac265c5e384b2cc5141d19685b1cc3d46a07c1e1d230e838675c412dca","title":"","text":"# ignore-cross-compile -- compiling C++ code does not work well when cross-compiling # This test case makes sure that native libraries are linked with --whole-archive semantics # when the `-bundle,+whole-archive` modifiers are applied to them. # This test case makes sure that native libraries are linked with appropriate semantics # when the `[+-]bundle,[+-]whole-archive` modifiers are applied to them. # # The test works by checking that the resulting executables produce the expected output, # part of which is emitted by otherwise unreferenced C code. If +whole-archive didn't work"} {"_id":"doc-en-rust-b6731058b5b36a612c3849f7ce661953e5a368440fb315c251e35e53770074fd","title":"","text":"-include ../../run-make-fulldeps/tools.mk all: $(TMPDIR)/$(call BIN,directly_linked) $(TMPDIR)/$(call BIN,indirectly_linked) $(TMPDIR)/$(call BIN,indirectly_linked_via_attr) all: $(TMPDIR)/$(call BIN,directly_linked) $(TMPDIR)/$(call BIN,directly_linked_test_plus_whole_archive) $(TMPDIR)/$(call BIN,directly_linked_test_minus_whole_archive) $(TMPDIR)/$(call BIN,indirectly_linked) $(TMPDIR)/$(call BIN,indirectly_linked_via_attr) $(call RUN,directly_linked) | $(CGREP) 'static-initializer.directly_linked.' $(call RUN,directly_linked_test_plus_whole_archive) --nocapture | $(CGREP) 'static-initializer.' $(call RUN,directly_linked_test_minus_whole_archive) --nocapture | $(CGREP) -v 'static-initializer.' $(call RUN,indirectly_linked) | $(CGREP) 'static-initializer.indirectly_linked.' $(call RUN,indirectly_linked_via_attr) | $(CGREP) 'static-initializer.native_lib_in_src.'"} {"_id":"doc-en-rust-5c287c509077516e7d8920d4d582ea5496786a7d313c94b12f29b1ce5a9a9665","title":"","text":"$(TMPDIR)/$(call BIN,directly_linked): $(call NATIVE_STATICLIB,c_static_lib_with_constructor) $(RUSTC) directly_linked.rs -l static:+whole-archive=c_static_lib_with_constructor # Native lib linked into test executable, +whole-archive $(TMPDIR)/$(call BIN,directly_linked_test_plus_whole_archive): $(call NATIVE_STATICLIB,c_static_lib_with_constructor) $(RUSTC) directly_linked_test_plus_whole_archive.rs --test -l static:+whole-archive=c_static_lib_with_constructor # Native lib linked into test executable, -whole-archive $(TMPDIR)/$(call BIN,directly_linked_test_minus_whole_archive): $(call NATIVE_STATICLIB,c_static_lib_with_constructor) $(RUSTC) directly_linked_test_minus_whole_archive.rs --test -l static:-whole-archive=c_static_lib_with_constructor # Native lib linked into RLIB via `-l static:-bundle,+whole-archive`, RLIB linked into executable $(TMPDIR)/$(call BIN,indirectly_linked): $(TMPDIR)/librlib_with_cmdline_native_lib.rlib $(RUSTC) indirectly_linked.rs"} {"_id":"doc-en-rust-67471abdd0ddc9119e2079c17e37000dac506c26c58ff18e79b3e69938c381a3","title":"","text":" use std::io::Write; #[test] fn test_thing() { print!(\"ran the test\"); std::io::stdout().flush().unwrap(); } "} {"_id":"doc-en-rust-5e919feb57b32b4e2de2653fdd76d40950fadad10055856bec4c7fe086fe40c0","title":"","text":"} } Err(coercion_error) => { // Mark that we've failed to coerce the types here to suppress // any superfluous errors we might encounter while trying to // emit or provide suggestions on how to fix the initial error. fcx.set_tainted_by_errors(); let (expected, found) = if label_expression_as_expected { // In the case where this is a \"forced unit\", like // `break`, we want to call the `()` \"expected\""} {"_id":"doc-en-rust-6ab89acff960b9d9e745ae5e70c5e40ddd20e6eb50657e27c5e470f7150bf6cb","title":"","text":" #![recursion_limit = \"5\"] // To reduce noise //expect incompatible type error when ambiguous traits are in scope //and not an overflow error on the span in the main function. struct Ratio(T); pub trait Pow { fn pow(self) -> Self; } impl<'a, T> Pow for &'a Ratio where &'a T: Pow, { fn pow(self) -> Self { self } } fn downcast<'a, W: ?Sized>() -> std::io::Result<&'a W> { todo!() } struct Other; fn main() -> std::io::Result<()> { let other: Other = downcast()?;//~ERROR 28:24: 28:35: `?` operator has incompatible types Ok(()) } "} {"_id":"doc-en-rust-d4d7a50cfd12d70ecf5dd82051d906d5925ae9b05d2699cbd07b7669524e650f","title":"","text":" error[E0308]: `?` operator has incompatible types --> $DIR/issue-100246.rs:28:24 | LL | let other: Other = downcast()?; | ^^^^^^^^^^^ expected struct `Other`, found reference | = note: `?` operator cannot convert from `&_` to `Other` = note: expected struct `Other` found reference `&_` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-6dff33ae23034e8e88dfbbdfe93bf051c76c390cf3daf47505f7c4863370de30","title":"","text":"} #[cfg(not(no_global_oom_handling))] #[stable(feature = \"vec_from_array_ref\", since = \"CURRENT_RUSTC_VERSION\")] impl From<&[T; N]> for Vec { /// Allocate a `Vec` and fill it by cloning `s`'s items. /// /// # Examples /// /// ``` /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]); /// ``` fn from(s: &[T; N]) -> Vec { Self::from(s.as_slice()) } } #[cfg(not(no_global_oom_handling))] #[stable(feature = \"vec_from_array_ref\", since = \"CURRENT_RUSTC_VERSION\")] impl From<&mut [T; N]> for Vec { /// Allocate a `Vec` and fill it by cloning `s`'s items. /// /// # Examples /// /// ``` /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]); /// ``` fn from(s: &mut [T; N]) -> Vec { Self::from(s.as_mut_slice()) } } #[cfg(not(no_global_oom_handling))] #[stable(feature = \"vec_from_array\", since = \"1.44.0\")] impl From<[T; N]> for Vec { /// Allocate a `Vec` and move `s`'s items into it."} {"_id":"doc-en-rust-572c22047c7744daa74d87cda217ceb1d0c07714cb3de350f47db62b31379e39","title":"","text":"// Ensure all ZSTs have been freed. assert!(alloc.state.borrow().0.is_empty()); } #[test] fn test_vec_from_array_ref() { assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]); } #[test] fn test_vec_from_array_mut_ref() { assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]); } "} {"_id":"doc-en-rust-f3f7f5e01f8251a55707e13afa2e65af213be833fd5681197673728f4e889e93","title":"","text":"let ai = &self.expected_indices; let ii = &self.provided_indices; // Issue: 100478, when we end the iteration, // `next_unmatched_idx` will point to the index of the first unmatched let mut next_unmatched_idx = 0; for i in 0..cmp::max(ai.len(), ii.len()) { // If we eliminate the last row, any left-over inputs are considered missing // If we eliminate the last row, any left-over arguments are considered missing if i >= mat.len() { return Some(Issue::Missing(i)); return Some(Issue::Missing(next_unmatched_idx)); } // If we eliminate the last column, any left-over arguments are extra // If we eliminate the last column, any left-over inputs are extra if mat[i].len() == 0 { return Some(Issue::Extra(i)); return Some(Issue::Extra(next_unmatched_idx)); } // Make sure we don't pass the bounds of our matrix"} {"_id":"doc-en-rust-ebd767aaad5a65adba0584ceb8e15ce564316d3edb06a7654030a68b15f32d41","title":"","text":"let is_input = i < ii.len(); if is_arg && is_input && matches!(mat[i][i], Compatibility::Compatible) { // This is a satisfied input, so move along next_unmatched_idx += 1; continue; }"} {"_id":"doc-en-rust-942c3746659d5b40277e7901a8045b4b3338538bc3e8d229bfd4d7b59a815af4","title":"","text":"if is_input { for j in 0..ai.len() { // If we find at least one argument that could satisfy this input // this argument isn't useless // this input isn't useless if matches!(mat[i][j], Compatibility::Compatible) { useless = false; break;"} {"_id":"doc-en-rust-9eb7da14c9ae1c7d6b22042d4bcc90ff37b06a4b9981b4a2380ad3b9f7d56f78","title":"","text":"if matches!(c, Compatibility::Compatible) { Some(i) } else { None } }) .collect(); if compat.len() != 1 { // this could go into multiple slots, don't bother exploring both if compat.len() < 1 { // try to find a cycle even when this could go into multiple slots, see #101097 is_cycle = false; break; }"} {"_id":"doc-en-rust-2523308c1b39de3002461a020cff97d2ed0b10c807e5234a318ebfe099be3bc9","title":"","text":"} while !self.provided_indices.is_empty() || !self.expected_indices.is_empty() { match self.find_issue() { let res = self.find_issue(); match res { Some(Issue::Invalid(idx)) => { let compatibility = self.compatibility_matrix[idx][idx].clone(); let input_idx = self.provided_indices[idx];"} {"_id":"doc-en-rust-d1b5b133ec582ab2b6489ed539624d749b96ef0f3bd3bad707836fe0027c40b1","title":"","text":"None => { // We didn't find any issues, so we need to push the algorithm forward // First, eliminate any arguments that currently satisfy their inputs for (inp, arg) in self.eliminate_satisfied() { let eliminated = self.eliminate_satisfied(); assert!(!eliminated.is_empty(), \"didn't eliminated any indice in this round\"); for (inp, arg) in eliminated { matched_inputs[arg] = Some(inp); } }"} {"_id":"doc-en-rust-0057aaa88e4a9598550189bcad3abf64505c7e9524bb4951bab0a0f1d48d9b4b","title":"","text":" use std::sync::Arc; macro_rules! GenT { ($name:tt) => { #[derive(Default, Debug)] struct $name { #[allow(unused)] val: i32, } impl $name { #[allow(unused)] fn new(val: i32) -> Self { $name { val } } } }; } GenT!(T1); GenT!(T2); GenT!(T3); GenT!(T4); GenT!(T5); GenT!(T6); GenT!(T7); GenT!(T8); #[allow(unused)] fn foo(p1: T1, p2: Arc, p3: T3, p4: Arc, p5: T5, p6: T6, p7: T7, p8: Arc) {} fn three_diff(_a: T1, _b: T2, _c: T3) {} fn four_shuffle(_a: T1, _b: T2, _c: T3, _d: T4) {} fn main() { three_diff(T2::new(0)); //~ ERROR this function takes four_shuffle(T3::default(), T4::default(), T1::default(), T2::default()); //~ ERROR 35:5: 35:17: arguments to this function are incorrect [E0308] four_shuffle(T3::default(), T2::default(), T1::default(), T3::default()); //~ ERROR 36:5: 36:17: arguments to this function are incorrect [E0308] let p1 = T1::new(0); let p2 = Arc::new(T2::new(0)); let p3 = T3::new(0); let p4 = Arc::new(T4::new(1)); let p5 = T5::new(0); let p6 = T6::new(0); let p7 = T7::new(0); let p8 = Arc::default(); foo( //~^ 47:5: 47:8: this function takes 8 arguments but 7 arguments were supplied [E0061] p1, //p2, p3, p4, p5, p6, p7, p8, ); } "} {"_id":"doc-en-rust-a83781cf9b92f81a58d0ed6034b14dc5dad17513a009ffd45ccf6881248b46f3","title":"","text":" error[E0061]: this function takes 3 arguments but 1 argument was supplied --> $DIR/issue-100478.rs:34:5 | LL | three_diff(T2::new(0)); | ^^^^^^^^^^------------ | || | |an argument of type `T1` is missing | an argument of type `T3` is missing | note: function defined here --> $DIR/issue-100478.rs:30:4 | LL | fn three_diff(_a: T1, _b: T2, _c: T3) {} | ^^^^^^^^^^ ------ ------ ------ help: provide the arguments | LL | three_diff(/* T1 */, T2::new(0), /* T3 */); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-100478.rs:35:5 | LL | four_shuffle(T3::default(), T4::default(), T1::default(), T2::default()); | ^^^^^^^^^^^^ ------------- ------------- ------------- ------------- expected `T4`, found `T2` | | | | | | | expected `T3`, found `T1` | | expected `T2`, found `T4` | expected `T1`, found `T3` | note: function defined here --> $DIR/issue-100478.rs:31:4 | LL | fn four_shuffle(_a: T1, _b: T2, _c: T3, _d: T4) {} | ^^^^^^^^^^^^ ------ ------ ------ ------ help: did you mean | LL | four_shuffle(T1::default(), T2::default(), T3::default(), T4::default()); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-100478.rs:36:5 | LL | four_shuffle(T3::default(), T2::default(), T1::default(), T3::default()); | ^^^^^^^^^^^^ ------------- ------------- ------------- expected struct `T4`, found struct `T3` | | | | | expected `T3`, found `T1` | expected `T1`, found `T3` | note: function defined here --> $DIR/issue-100478.rs:31:4 | LL | fn four_shuffle(_a: T1, _b: T2, _c: T3, _d: T4) {} | ^^^^^^^^^^^^ ------ ------ ------ ------ help: swap these arguments | LL | four_shuffle(T1::default(), T2::default(), T3::default(), /* T4 */); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error[E0061]: this function takes 8 arguments but 7 arguments were supplied --> $DIR/issue-100478.rs:47:5 | LL | foo( | ^^^ ... LL | p3, p4, p5, p6, p7, p8, | -- an argument of type `Arc` is missing | note: function defined here --> $DIR/issue-100478.rs:29:4 | LL | fn foo(p1: T1, p2: Arc, p3: T3, p4: Arc, p5: T5, p6: T6, p7: T7, p8: Arc) {} | ^^^ ------ ----------- ------ ----------- ------ ------ ------ ----------- help: provide the argument | LL | foo(p1, /* Arc */, p3, p4, p5, p6, p7, p8); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to 4 previous errors Some errors have detailed explanations: E0061, E0308. For more information about an error, try `rustc --explain E0061`. "} {"_id":"doc-en-rust-0a7fd02582517c2e3952bba31c641dc352d0a768f655d6058db808d918968c10","title":"","text":" struct A; struct B; struct C; struct D; fn f( a1: A, a2: A, b1: B, b2: B, c1: C, c2: C, ) {} fn main() { f(C, A, A, A, B, B, C); //~ ERROR this function takes 6 arguments but 7 arguments were supplied [E0061] f(C, C, A, A, B, B); //~ ERROR arguments to this function are incorrect [E0308] f(A, A, D, D, B, B); //~ arguments to this function are incorrect [E0308] f(C, C, B, B, A, A); //~ arguments to this function are incorrect [E0308] f(C, C, A, B, A, A); //~ arguments to this function are incorrect [E0308] } "} {"_id":"doc-en-rust-2a37c17de89d2adf96bdacbadf6fc804cb57b3663f0cec72aa0a834c9db1d7cb","title":"","text":" error[E0061]: this function takes 6 arguments but 7 arguments were supplied --> $DIR/issue-101097.rs:16:5 | LL | f(C, A, A, A, B, B, C); | ^ - - - - expected `C`, found `B` | | | | | | | argument of type `A` unexpected | | expected `B`, found `A` | expected `A`, found `C` | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( | ^ LL | a1: A, | ----- LL | a2: A, | ----- LL | b1: B, | ----- LL | b2: B, | ----- LL | c1: C, | ----- LL | c2: C, | ----- help: did you mean | LL | f(A, A, B, B, C, C); | ~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-101097.rs:17:5 | LL | f(C, C, A, A, B, B); | ^ | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( | ^ LL | a1: A, | ----- LL | a2: A, | ----- LL | b1: B, | ----- LL | b2: B, | ----- LL | c1: C, | ----- LL | c2: C, | ----- help: did you mean | LL | f(A, A, B, B, C, C); | ~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-101097.rs:18:5 | LL | f(A, A, D, D, B, B); | ^ - - ---- two arguments of type `C` and `C` are missing | | | | | argument of type `D` unexpected | argument of type `D` unexpected | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( | ^ LL | a1: A, | ----- LL | a2: A, | ----- LL | b1: B, | ----- LL | b2: B, | ----- LL | c1: C, | ----- LL | c2: C, | ----- help: did you mean | LL | f(A, A, B, B, /* C */, /* C */); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-101097.rs:19:5 | LL | f(C, C, B, B, A, A); | ^ - - - - expected `C`, found `A` | | | | | | | expected `C`, found `A` | | expected `A`, found `C` | expected `A`, found `C` | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( | ^ LL | a1: A, | ----- LL | a2: A, | ----- LL | b1: B, | ----- LL | b2: B, | ----- LL | c1: C, | ----- LL | c2: C, | ----- help: did you mean | LL | f(A, A, B, B, C, C); | ~~~~~~~~~~~~~~~~~~ error[E0308]: arguments to this function are incorrect --> $DIR/issue-101097.rs:20:5 | LL | f(C, C, A, B, A, A); | ^ - - - - - expected `C`, found `A` | | | | | | | | | expected `C`, found `A` | | | expected struct `B`, found struct `A` | | expected `A`, found `C` | expected `A`, found `C` | note: function defined here --> $DIR/issue-101097.rs:6:4 | LL | fn f( | ^ LL | a1: A, | ----- LL | a2: A, | ----- LL | b1: B, | ----- LL | b2: B, | ----- LL | c1: C, | ----- LL | c2: C, | ----- help: did you mean | LL | f(A, A, /* B */, B, C, C); | ~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to 5 previous errors Some errors have detailed explanations: E0061, E0308. For more information about an error, try `rustc --explain E0061`. "} {"_id":"doc-en-rust-c2cc41b5bc4000bb98837f086956ce211a39cdddaa7469adca9ec6fd4ae4be5b","title":"","text":"// NOTE: generics must be cleaned before args let generics = clean_generics(generics, cx); let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id); let decl = clean_fn_decl_with_args(cx, sig.decl, args); let mut decl = clean_fn_decl_with_args(cx, sig.decl, args); if sig.header.is_async() { decl.output = decl.sugared_async_return_type(); } (generics, decl) }); Box::new(Function { decl, generics })"} {"_id":"doc-en-rust-f23a1cc0dea2e83595057cc5195c1c3911ad470579c5a93c922a658daf25b7b7","title":"","text":"///
Used to determine line-wrapping. /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is /// necessary. /// * `asyncness`: Whether the function is async or not. pub(crate) fn full_print<'a, 'tcx: 'a>( &'a self, header_len: usize, indent: usize, asyncness: hir::IsAsync, cx: &'a Context<'tcx>, ) -> impl fmt::Display + 'a + Captures<'tcx> { display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx)) display_fn(move |f| self.inner_full_print(header_len, indent, f, cx)) } fn inner_full_print( &self, header_len: usize, indent: usize, asyncness: hir::IsAsync, f: &mut fmt::Formatter<'_>, cx: &Context<'_>, ) -> fmt::Result {"} {"_id":"doc-en-rust-faa6ea1d5096d1f84fe72722d0489952d17549b0ab261aba2dc9a4dc3c055bc1","title":"","text":"args_plain.push_str(\", ...\"); } let arrow_plain; let arrow = if let hir::IsAsync::Async = asyncness { let output = self.sugared_async_return_type(); arrow_plain = format!(\"{:#}\", output.print(cx)); if f.alternate() { arrow_plain.clone() } else { format!(\"{}\", output.print(cx)) } } else { arrow_plain = format!(\"{:#}\", self.output.print(cx)); if f.alternate() { arrow_plain.clone() } else { format!(\"{}\", self.output.print(cx)) } }; let arrow_plain = format!(\"{:#}\", self.output.print(cx)); let arrow = if f.alternate() { arrow_plain.clone() } else { format!(\"{}\", self.output.print(cx)) }; let declaration_len = header_len + args_plain.len() + arrow_plain.len(); let output = if declaration_len > 80 {"} {"_id":"doc-en-rust-967156c9a20cb1a9d03b741d038f1c461180b7b735d43ed9d697a598ccd33427","title":"","text":"href = href, name = name, generics = g.print(cx), decl = d.full_print(header_len, indent, header.asyncness, cx), decl = d.full_print(header_len, indent, cx), notable_traits = notable_traits_decl(d, cx), where_clause = print_where_clause(g, cx, indent, end_newline), )"} {"_id":"doc-en-rust-869961c083ad0a831bb9672af92dea916d6e5d58e33168d2048c5648f4e43fb3","title":"","text":"name = name, generics = f.generics.print(cx), where_clause = print_where_clause(&f.generics, cx, 0, Ending::Newline), decl = f.decl.full_print(header_len, 0, header.asyncness, cx), decl = f.decl.full_print(header_len, 0, cx), notable_traits = notable_traits_decl(&f.decl, cx), ); });"} {"_id":"doc-en-rust-64243003a241e9945e8c6c48683f198525294751eb24da1f8ea3c962060eb8d2","title":"","text":" // edition:2021 // ignore-tidy-linelength // Regression test for use std::future::Future; // @is \"$.index[*][?(@.name=='get_int')].inner.decl.output\" '{\"inner\": \"i32\", \"kind\": \"primitive\"}' // @is \"$.index[*][?(@.name=='get_int')].inner.header.async\" false pub fn get_int() -> i32 { 42 } // @is \"$.index[*][?(@.name=='get_int_async')].inner.decl.output\" '{\"inner\": \"i32\", \"kind\": \"primitive\"}' // @is \"$.index[*][?(@.name=='get_int_async')].inner.header.async\" true pub async fn get_int_async() -> i32 { 42 } // @is \"$.index[*][?(@.name=='get_int_future')].inner.decl.output.kind\" '\"impl_trait\"' // @is \"$.index[*][?(@.name=='get_int_future')].inner.decl.output.inner[0].trait_bound.trait.name\" '\"Future\"' // @is \"$.index[*][?(@.name=='get_int_future')].inner.decl.output.inner[0].trait_bound.trait.args.angle_bracketed.bindings[0].name\" '\"Output\"' // @is \"$.index[*][?(@.name=='get_int_future')].inner.decl.output.inner[0].trait_bound.trait.args.angle_bracketed.bindings[0].binding.equality.type\" '{\"inner\": \"i32\", \"kind\": \"primitive\"}' // @is \"$.index[*][?(@.name=='get_int_future')].inner.header.async\" false pub fn get_int_future() -> impl Future { async { 42 } } // @is \"$.index[*][?(@.name=='get_int_future_async')].inner.decl.output.kind\" '\"impl_trait\"' // @is \"$.index[*][?(@.name=='get_int_future_async')].inner.decl.output.inner[0].trait_bound.trait.name\" '\"Future\"' // @is \"$.index[*][?(@.name=='get_int_future_async')].inner.decl.output.inner[0].trait_bound.trait.args.angle_bracketed.bindings[0].name\" '\"Output\"' // @is \"$.index[*][?(@.name=='get_int_future_async')].inner.decl.output.inner[0].trait_bound.trait.args.angle_bracketed.bindings[0].binding.equality.type\" '{\"inner\": \"i32\", \"kind\": \"primitive\"}' // @is \"$.index[*][?(@.name=='get_int_future_async')].inner.header.async\" true pub async fn get_int_future_async() -> impl Future { async { 42 } } "} {"_id":"doc-en-rust-2630d55c4ae836f17e1fc246ca4816a7e397655b16480c9fa9ae2cd09b743c8e","title":"","text":" // check-pass // edition:2021 // aux-build:test-macros.rs #![no_std] // Don't load unnecessary hygiene information from std extern crate std; #[macro_use] extern crate test_macros; macro_rules! foo { ($($path:ident)::*) => ( test_macros::recollect!( $($path)::* ) ) } macro_rules! baz { () => ( foo!($crate::BAR) ) } pub const BAR: u32 = 19; fn main(){ std::println!(\"{}\", baz!()); } "} {"_id":"doc-en-rust-40a4d35f5d51f2b6f8ee202cc47a08503fe7b6e056dd458424d76e4a9836f007","title":"","text":"kw::Extern, kw::Impl, kw::Unsafe, kw::Const, kw::Static, kw::Union, kw::Macro,"} {"_id":"doc-en-rust-0e6d8fa97e39d1f5c21ac2bb17a0433e28edb16d2868ca0f67e175f22799fe03","title":"","text":" // run-rustfix mod test { pub const X: i32 = 123; //~^ ERROR expected one of `!` or `::`, found keyword `const` } fn main() { println!(\"{}\", test::X); } "} {"_id":"doc-en-rust-7af6d1e4e63c04408f44fc086a0aff375e349f1d9bd8379b7cb88a2c0afe0610","title":"","text":" // run-rustfix mod test { public const X: i32 = 123; //~^ ERROR expected one of `!` or `::`, found keyword `const` } fn main() { println!(\"{}\", test::X); } "} {"_id":"doc-en-rust-55d3193411deecc0ec6238e89127dbdc2527419d7c1554faf06a6bb6855cfdc6","title":"","text":" error: expected one of `!` or `::`, found keyword `const` --> $DIR/public-instead-of-pub-3.rs:3:12 | LL | public const X: i32 = 123; | ^^^^^ expected one of `!` or `::` | help: write `pub` instead of `public` to make the item public | LL | pub const X: i32 = 123; | ~~~ error: aborting due to previous error "} {"_id":"doc-en-rust-a4f4514d8dc5d6f07a53769f4ea3cf405a29ccf71bebcdce22435b3dc9b7a141","title":"","text":"} /// When encountering an fn-like type, try accessing the output of the type /// // and suggesting calling it if it satisfies a predicate (i.e. if the /// and suggesting calling it if it satisfies a predicate (i.e. if the /// output has a method or a field): /// ```compile_fail,E0308 /// fn foo(x: usize) -> usize { x }"} {"_id":"doc-en-rust-a3218ddeeede4ed1908e2e3c4f7deb47e11eef7da8eb427fb5b662116f3ef754","title":"","text":"} else { err.span_suggestion(sp, &msg, suggestion, applicability); } } else if self.suggest_else_fn_with_closure(err, expr, found, expected) { } else if self.suggest_fn_call(err, expr, found, |output| self.can_coerce(output, expected)) && let ty::FnDef(def_id, ..) = &found.kind() && let Some(sp) = self.tcx.hir().span_if_local(*def_id)"} {"_id":"doc-en-rust-d3f1e466460f2a6d0508d66622737a32c5e6fbdff2e76e10b0d20c077a3abb8f","title":"","text":"} } /// issue #102320, for `unwrap_or` with closure as argument, suggest `unwrap_or_else` /// FIXME: currently not working for suggesting `map_or_else`, see #102408 pub(crate) fn suggest_else_fn_with_closure( &self, err: &mut Diagnostic, expr: &hir::Expr<'_>, found: Ty<'tcx>, expected: Ty<'tcx>, ) -> bool { let Some((_def_id_or_name, output, _inputs)) = self.extract_callable_info(expr, found) else { return false; }; if !self.can_coerce(output, expected) { return false; } let parent = self.tcx.hir().get_parent_node(expr.hir_id); if let Some(Node::Expr(call_expr)) = self.tcx.hir().find(parent) && let hir::ExprKind::MethodCall( hir::PathSegment { ident: method_name, .. }, self_expr, args, .., ) = call_expr.kind && let Some(self_ty) = self.typeck_results.borrow().expr_ty_opt(self_expr) { let new_name = Ident { name: Symbol::intern(&format!(\"{}_else\", method_name.as_str())), span: method_name.span, }; let probe = self.lookup_probe( expr.span, new_name, self_ty, self_expr, ProbeScope::TraitsInScope, ); // check the method arguments number if let Ok(pick) = probe && let fn_sig = self.tcx.fn_sig(pick.item.def_id) && let fn_args = fn_sig.skip_binder().inputs() && fn_args.len() == args.len() + 1 { err.span_suggestion_verbose( method_name.span.shrink_to_hi(), &format!(\"try calling `{}` instead\", new_name.name.as_str()), \"_else\", Applicability::MaybeIncorrect, ); return true; } } false } /// Checks whether there is a local type somewhere in the chain of /// autoderefs of `rcvr_ty`. fn type_derefs_to_local("} {"_id":"doc-en-rust-e8b91c8f3d6dbffd57e250c567214c4fa261bd9520e6f8961406a52b64adb3e9","title":"","text":" // run-rustfix fn main() { let x = \"com.example.app\"; let y: Option<&str> = None; let _s = y.unwrap_or_else(|| x.split('.').nth(1).unwrap()); //~^ ERROR: mismatched types [E0308] } "} {"_id":"doc-en-rust-2e7a54e15299641f6ea233f1c9c8b845b9d9b885bf9e74ff8b79b3ffe1079d18","title":"","text":" // run-rustfix fn main() { let x = \"com.example.app\"; let y: Option<&str> = None; let _s = y.unwrap_or(|| x.split('.').nth(1).unwrap()); //~^ ERROR: mismatched types [E0308] } "} {"_id":"doc-en-rust-310929917132e49a03efefafbf92a49b21ffaa24a5b02cb501a376cbcbf11304","title":"","text":" error[E0308]: mismatched types --> $DIR/sugg-else-for-closure.rs:6:26 | LL | let _s = y.unwrap_or(|| x.split('.').nth(1).unwrap()); | --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found closure | | | arguments to this function are incorrect | = note: expected reference `&str` found closure `[closure@$DIR/sugg-else-for-closure.rs:6:26: 6:28]` note: associated function defined here --> $SRC_DIR/core/src/option.rs:LL:COL | LL | pub const fn unwrap_or(self, default: T) -> T | ^^^^^^^^^ help: try calling `unwrap_or_else` instead | LL | let _s = y.unwrap_or_else(|| x.split('.').nth(1).unwrap()); | +++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-ab2a4cfb2916c123bc3e270b24a6a2cc00afde724abfb69f7a8e92b44e6fb23b","title":"","text":"use crate::fmt; use crate::io; use crate::marker::PhantomData; use crate::mem; use crate::mem::{self, forget}; use crate::num::NonZeroU64; use crate::num::NonZeroUsize; use crate::panic;"} {"_id":"doc-en-rust-033faff9d8e0e7d243e93dd44d907588787c4077294b279c82e55eceee9d11c2","title":"","text":"imp::Thread::sleep(dur) } /// Used to ensure that `park` and `park_timeout` do not unwind, as that can /// cause undefined behaviour if not handled correctly (see #102398 for context). struct PanicGuard; impl Drop for PanicGuard { fn drop(&mut self) { rtabort!(\"an irrecoverable error occurred while synchronizing threads\") } } /// Blocks unless or until the current thread's token is made available. /// /// A call to `park` does not guarantee that the thread will remain parked /// forever, and callers should be prepared for this possibility. /// forever, and callers should be prepared for this possibility. However, /// it is guaranteed that this function will not panic (it may abort the /// process if the implementation encounters some rare errors). /// /// # park and unpark ///"} {"_id":"doc-en-rust-c8846382e071e573268ff724c03bf391504fe53c6e8a3d9e756c3b920d67ce53","title":"","text":"/// [`thread::park_timeout`]: park_timeout #[stable(feature = \"rust1\", since = \"1.0.0\")] pub fn park() { let guard = PanicGuard; // SAFETY: park_timeout is called on the parker owned by this thread. unsafe { current().inner.as_ref().parker().park(); } // No panic occurred, do not abort. forget(guard); } /// Use [`park_timeout`]."} {"_id":"doc-en-rust-3dca63e4680d7674d4ba023584ba545c398ef9b0a050a9c2b2dd82d6af47a6aa","title":"","text":"/// ``` #[stable(feature = \"park_timeout\", since = \"1.4.0\")] pub fn park_timeout(dur: Duration) { let guard = PanicGuard; // SAFETY: park_timeout is called on the parker owned by this thread. unsafe { current().inner.as_ref().parker().park_timeout(dur); } // No panic occurred, do not abort. forget(guard); } ////////////////////////////////////////////////////////////////////////////////"} {"_id":"doc-en-rust-6320ad2e2b0b6370ba80a7746ba3f558e921ce4b5c8b6f0d062014b441f1a4ad","title":"","text":"span: Span, origin: &hir::OpaqueTyOrigin, ) { let hidden_type = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs); let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); let defining_use_anchor = match *origin { hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did,"} {"_id":"doc-en-rust-4793ee367c6c1b8e40c25c1b58a0dd972ebfff5378748d02a303143f00b02b35","title":"","text":"let ocx = ObligationCtxt::new(&infcx); let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs); // `ReErased` regions appear in the \"parent_substs\" of closures/generators. // We're ignoring them here and replacing them with fresh region variables. // See tests in ui/type-alias-impl-trait/closure_{parent_substs,wf_outlives}.rs. // // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it // here rather than using ReErased. let hidden_ty = tcx.bound_type_of(def_id.to_def_id()).subst(tcx, substs); let hidden_ty = tcx.fold_regions(hidden_ty, |re, _dbi| match re.kind() { ty::ReErased => infcx.next_region_var(RegionVariableOrigin::MiscVariable(span)), _ => re, }); let misc_cause = traits::ObligationCause::misc(span, hir_id); match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_type) { match infcx.at(&misc_cause, param_env).eq(opaque_ty, hidden_ty) { Ok(infer_ok) => ocx.register_infer_ok_obligations(infer_ok), Err(ty_err) => { tcx.sess.delay_span_bug( span, &format!(\"could not unify `{hidden_type}` with revealed type:n{ty_err}\"), &format!(\"could not unify `{hidden_ty}` with revealed type:n{ty_err}\"), ); } }"} {"_id":"doc-en-rust-8a6f9c46988cb5bd7f5a816bbed16eb5be29539a7ea8b7401b8111c0f9fd0853","title":"","text":"// Defining use functions may have more bounds than the opaque type, which is ok, as long as the // hidden type is well formed even without those bounds. let predicate = ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_type.into())).to_predicate(tcx); ty::Binder::dummy(ty::PredicateKind::WellFormed(hidden_ty.into())).to_predicate(tcx); ocx.register_obligation(Obligation::new(misc_cause, param_env, predicate)); // Check that all obligations are satisfied by the implementation's"} {"_id":"doc-en-rust-fbea4869e3d86847d9d9692c0207cb1ddd71f0a82b321a27c66486a928b39147","title":"","text":" // When WF checking the hidden type in the ParamEnv of the opaque type, // one complication arises when the hidden type is a closure/generator: // the \"parent_substs\" of the type may reference lifetime parameters // not present in the opaque type. // These region parameters are not really useful in this check. // So here we ignore them and replace them with fresh region variables. // check-pass #![feature(type_alias_impl_trait)] #![allow(dead_code)] // Basic test mod test1 { // Hidden type = Closure['_#0r] type Opaque = impl Sized; fn define<'a: 'a>() -> Opaque { || {} } } // the region vars cannot both be equal to `'static` or `'empty` mod test2 { trait Trait {} // Hidden type = Closure['a, '_#0r, '_#1r] // Constraints = [('_#0r: 'a), ('a: '_#1r)] type Opaque<'a> where &'a (): Trait, = impl Sized + 'a; fn define<'a, 'x, 'y>() -> Opaque<'a> where &'a (): Trait, 'x: 'a, 'a: 'y, { || {} } } // the region var cannot be equal to `'a` or `'b` mod test3 { trait Trait {} // Hidden type = Closure['a, 'b, '_#0r] // Constraints = [('_#0r: 'a), ('_#0r: 'b)] type Opaque<'a, 'b> where (&'a (), &'b ()): Trait, = impl Sized + 'a + 'b; fn define<'a, 'b, 'x>() -> Opaque<'a, 'b> where (&'a (), &'b ()): Trait, 'x: 'a, 'x: 'b, { || {} } } fn main() {} "} {"_id":"doc-en-rust-b31e7e41b9a51271c078eab0833230fe067c42a73eaf2e7d0d72de6ae2e74048","title":"","text":" // If the hidden type is a closure, we require the \"outlives\" bounds that appear on the // defining site to also appear on the opaque type. // // It's not clear if this is the desired behavior but at least // it's consistent and has no back-compat risk. // check-fail #![feature(type_alias_impl_trait)] #![allow(dead_code)] // requires `'a: 'b` bound mod test1 { type Opaque<'a, 'b> = impl Sized + 'a + 'b; //~^ ERROR lifetime bound not satisfied fn define<'a, 'b>() -> Opaque<'a, 'b> where 'a: 'b, { || {} } } // Same as the above but through indirection `'x` mod test2 { type Opaque<'a, 'b> = impl Sized + 'a + 'b; //~^ ERROR cannot infer an appropriate lifetime fn define<'a, 'b, 'x>() -> Opaque<'a, 'b> where 'a: 'x, 'x: 'b, { || {} } } // fixed version of the above mod test2_fixed { type Opaque<'a: 'b, 'b> = impl Sized + 'a + 'b; fn define<'a, 'b, 'x>() -> Opaque<'a, 'b> where 'a: 'x, 'x: 'b, { || {} } } // requires `T: 'static` mod test3 { type Opaque = impl Sized; //~^ ERROR the parameter type `T` may not live long enough fn define() -> Opaque where T: 'static, { || {} } } fn main() {} "} {"_id":"doc-en-rust-76f95d36be9dd54211793ed4db6df541378f0c610cefc90fb73b72e1831c0c3b","title":"","text":" error[E0478]: lifetime bound not satisfied --> $DIR/closure_wf_outlives.rs:14:27 | LL | type Opaque<'a, 'b> = impl Sized + 'a + 'b; | ^^^^^^^^^^^^^^^^^^^^ | note: lifetime parameter instantiated with the lifetime `'a` as defined here --> $DIR/closure_wf_outlives.rs:14:17 | LL | type Opaque<'a, 'b> = impl Sized + 'a + 'b; | ^^ note: but lifetime parameter must outlive the lifetime `'b` as defined here --> $DIR/closure_wf_outlives.rs:14:21 | LL | type Opaque<'a, 'b> = impl Sized + 'a + 'b; | ^^ error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements --> $DIR/closure_wf_outlives.rs:27:27 | LL | type Opaque<'a, 'b> = impl Sized + 'a + 'b; | ^^^^^^^^^^^^^^^^^^^^ | note: first, the lifetime cannot outlive the lifetime `'a` as defined here... --> $DIR/closure_wf_outlives.rs:27:17 | LL | type Opaque<'a, 'b> = impl Sized + 'a + 'b; | ^^ note: ...so that the declared lifetime parameter bounds are satisfied --> $DIR/closure_wf_outlives.rs:27:27 | LL | type Opaque<'a, 'b> = impl Sized + 'a + 'b; | ^^^^^^^^^^^^^^^^^^^^ note: but, the lifetime must be valid for the lifetime `'b` as defined here... --> $DIR/closure_wf_outlives.rs:27:21 | LL | type Opaque<'a, 'b> = impl Sized + 'a + 'b; | ^^ note: ...so that the declared lifetime parameter bounds are satisfied --> $DIR/closure_wf_outlives.rs:27:27 | LL | type Opaque<'a, 'b> = impl Sized + 'a + 'b; | ^^^^^^^^^^^^^^^^^^^^ error[E0310]: the parameter type `T` may not live long enough --> $DIR/closure_wf_outlives.rs:54:22 | LL | type Opaque = impl Sized; | ^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds... | note: ...that is required by this bound --> $DIR/closure_wf_outlives.rs:59:12 | LL | T: 'static, | ^^^^^^^ help: consider adding an explicit lifetime bound... | LL | type Opaque = impl Sized; | +++++++++ error: aborting due to 3 previous errors Some errors have detailed explanations: E0310, E0478, E0495. For more information about an error, try `rustc --explain E0310`. "} {"_id":"doc-en-rust-9fcce6f13f9c8e7803965c102e27944759bfb1b2ea207f88440b6d007705ae5a","title":"","text":"let ocx = ObligationCtxt::new(infcx); let norm_cause = ObligationCause::misc(return_span, impl_m_hir_id); let impl_return_ty = ocx.normalize( let impl_sig = ocx.normalize( norm_cause.clone(), param_env, infcx .replace_bound_vars_with_fresh_vars( return_span, infer::HigherRankedType, tcx.fn_sig(impl_m.def_id), ) .output(), infcx.replace_bound_vars_with_fresh_vars( return_span, infer::HigherRankedType, tcx.fn_sig(impl_m.def_id), ), ); let impl_return_ty = impl_sig.output(); let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_hir_id); let unnormalized_trait_return_ty = tcx let unnormalized_trait_sig = tcx .liberate_late_bound_regions( impl_m.def_id, tcx.bound_fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs), ) .output() .fold_with(&mut collector); let trait_return_ty = ocx.normalize(norm_cause.clone(), param_env, unnormalized_trait_return_ty); let trait_sig = ocx.normalize(norm_cause.clone(), param_env, unnormalized_trait_sig); let trait_return_ty = trait_sig.output(); let wf_tys = FxHashSet::from_iter([unnormalized_trait_return_ty, trait_return_ty]); let wf_tys = FxHashSet::from_iter( unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()), ); match infcx.at(&cause, param_env).eq(trait_return_ty, impl_return_ty) { Ok(infer::InferOk { value: (), obligations }) => {"} {"_id":"doc-en-rust-e54bd6a00e527cfc967f42ecdb8b003cee1be3a38052a8500774ab9eab74b44d","title":"","text":"} } // Unify the whole function signature. We need to do this to fully infer // the lifetimes of the return type, but do this after unifying just the // return types, since we want to avoid duplicating errors from // `compare_predicate_entailment`. match infcx .at(&cause, param_env) .eq(tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig)), tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig))) { Ok(infer::InferOk { value: (), obligations }) => { ocx.register_obligations(obligations); } Err(terr) => { let guar = tcx.sess.delay_span_bug( return_span, format!(\"could not unify `{trait_sig}` and `{impl_sig}`: {terr:?}\"), ); return Err(guar); } } // Check that all obligations are satisfied by the implementation's // RPITs. let errors = ocx.select_all_or_error();"} {"_id":"doc-en-rust-b8e1465e8fe8b9be8278d3e8f25e684f813955b013c51cfe2ae95b40b170735e","title":"","text":"let id_substs = InternalSubsts::identity_for_item(tcx, def_id); debug!(?id_substs, ?substs); let map: FxHashMap, ty::GenericArg<'tcx>> = substs.iter().enumerate().map(|(index, arg)| (arg, id_substs[index])).collect(); std::iter::zip(substs, id_substs).collect(); debug!(?map); // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound // region substs that are synthesized during AST lowering. These are substs // that are appended to the parent substs (trait and trait method). However, // we're trying to infer the unsubstituted type value of the RPITIT inside // the *impl*, so we can later use the impl's method substs to normalize // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`). // // Due to the design of RPITITs, during AST lowering, we have no idea that // an impl method corresponds to a trait method with RPITITs in it. Therefore, // we don't have a list of early-bound region substs for the RPITIT in the impl. // Since early region parameters are index-based, we can't just rebase these // (trait method) early-bound region substs onto the impl, and there's no // guarantee that the indices from the trait substs and impl substs line up. // So to fix this, we subtract the number of trait substs and add the number of // impl substs to *renumber* these early-bound regions to their corresponding // indices in the impl's substitutions list. // // Also, we only need to account for a difference in trait and impl substs, // since we previously enforce that the trait method and impl method have the // same generics. let num_trait_substs = trait_to_impl_substs.len(); let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len(); let ty = tcx.fold_regions(ty, |region, _| { if let ty::ReFree(_) = region.kind() { map[®ion.into()].expect_region() } else { region } let ty::ReFree(_) = region.kind() else { return region; }; let ty::ReEarlyBound(e) = map[®ion.into()].expect_region().kind() else { bug!(\"expected ReFree to map to ReEarlyBound\"); }; tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: e.def_id, name: e.name, index: (e.index as usize - num_trait_substs + num_impl_substs) as u32, })) }); debug!(%ty); collected_tys.insert(def_id, ty);"} {"_id":"doc-en-rust-cda9a2fcb3cc3f599426414e6a849d0308ca4120b7cdadb1739b952cad27e5bd","title":"","text":"fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { #[cold] #[inline(never)] fn region_param_out_of_range(data: ty::EarlyBoundRegion) -> ! { fn region_param_out_of_range(data: ty::EarlyBoundRegion, substs: &[GenericArg<'_>]) -> ! { bug!( \"Region parameter out of range when substituting in region {} (index={})\", \"Region parameter out of range when substituting in region {} (index={}, substs = {:?})\", data.name, data.index, substs, ) } #[cold] #[inline(never)] fn region_param_invalid(data: ty::EarlyBoundRegion, other: GenericArgKind<'_>) -> ! { bug!( \"Unexpected parameter {:?} when substituting in region {} (index={})\", other, data.name, data.index )"} {"_id":"doc-en-rust-6b4bd1ec019c814cb762f0dd314c7109e3cca942940279ff1c2984dcf0ad7830","title":"","text":"let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); match rk { Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), _ => region_param_out_of_range(data), Some(other) => region_param_invalid(data, other), None => region_param_out_of_range(data, self.substs), } } _ => r,"} {"_id":"doc-en-rust-59409bb73630405e9b10438f8a266f9fbff7b88edf4e414d9b509b061ad2c781","title":"","text":"} let impl_fn_def_id = leaf_def.item.def_id; let impl_fn_substs = obligation.predicate.substs.rebase_onto(tcx, trait_fn_def_id, data.substs); // Rebase from {trait}::{fn}::{opaque} to {impl}::{fn}::{opaque}, // since `data.substs` are the impl substs. let impl_fn_substs = obligation.predicate.substs.rebase_onto(tcx, tcx.parent(trait_fn_def_id), data.substs); let cause = ObligationCause::new( obligation.cause.span,"} {"_id":"doc-en-rust-00b47a2d6b20d93b6442813bff34d18af6c622a25bcd803ec65f99ad80a47db1","title":"","text":" // check-pass // edition:2021 #![feature(async_fn_in_trait)] #![allow(incomplete_features)] pub trait SpiDevice { async fn transaction(&mut self); } impl SpiDevice for () { async fn transaction(&mut self) {} } fn main() {} "} {"_id":"doc-en-rust-0d51a30d7b7fd807e18b402e7fd5c30c7e15a42491505e3df17e60a3a2b51c72","title":"","text":" // check-pass #![feature(return_position_impl_trait_in_trait)] #![allow(incomplete_features)] trait Foo { fn foo>(self) -> impl Foo; } struct Bar; impl Foo for Bar { fn foo>(self) -> impl Foo { self } } fn main() {} "} {"_id":"doc-en-rust-bda41a824ccd6ecd60914bf03b7400af1b795f2f30e3ad5f24d3d1a785aaa404","title":"","text":"kind: ast::VisibilityKind::Inherited, tokens: None, }, span: ecx.with_def_site_ctxt(sp), span: sp, tokens: None, })]) } else {"} {"_id":"doc-en-rust-4fc02deeafe3cc018fb8d8df24572b0763fdb29edf13e3bc289bb67c257619e6","title":"","text":"lint_builtin_export_name_fn = declaration of a function with `export_name` lint_builtin_export_name_method = declaration of a method with `export_name` lint_builtin_export_name_static = declaration of a static with `export_name` lint_builtin_global_asm = usage of `core::arch::global_asm` lint_builtin_global_macro_unsafety = using this macro is unsafe even though it does not need an `unsafe` block lint_builtin_impl_unsafe_method = implementation of an `unsafe` method lint_builtin_incomplete_features = the feature `{$name}` is incomplete and may not be safe to use and/or cause compiler crashes"} {"_id":"doc-en-rust-2c57698504158a94cb26d7e03298b344da31a0e5010d0f128c848b4e024ed1fd","title":"","text":"} } ast::ItemKind::GlobalAsm(..) => { self.report_unsafe(cx, it.span, BuiltinUnsafe::GlobalAsm); } _ => {} } }"} {"_id":"doc-en-rust-244691bd6f4046bf41600d49c547b48d0a32d7c38c304afdb4543d6a1a2832db","title":"","text":"DeclUnsafeMethod, #[diag(lint_builtin_impl_unsafe_method)] ImplUnsafeMethod, #[diag(lint_builtin_global_asm)] #[note(lint_builtin_global_macro_unsafety)] GlobalAsm, } #[derive(LintDiagnostic)]"} {"_id":"doc-en-rust-c619989f74689b58b6114e7696a4a030f2ddffd8d78a12b7e562abfae64ac142","title":"","text":"| LL | global_asm!(\"\"); | ^^^^^^^^^^^^^^^ | = note: this error originates in the macro `global_asm` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors"} {"_id":"doc-en-rust-1a142f63f525aacf655c1dd2c1c056fafaaae3d25cc3cacb68fa9cc9ef34d3cf","title":"","text":" //@ needs-asm-support #![deny(unsafe_code)] use std::arch::global_asm; #[allow(unsafe_code)] mod allowed_unsafe { std::arch::global_asm!(\"\"); } macro_rules! unsafe_in_macro { () => { global_asm!(\"\"); //~ ERROR: usage of `core::arch::global_asm` }; } global_asm!(\"\"); //~ ERROR: usage of `core::arch::global_asm` unsafe_in_macro!(); fn main() {} "} {"_id":"doc-en-rust-8e1a06bb159a8ba148db854a36ae1f9196fa79cd5d54eb08aed478d25ca51437","title":"","text":" error: usage of `core::arch::global_asm` --> $DIR/lint-global-asm-as-unsafe.rs:17:1 | LL | global_asm!(\"\"); | ^^^^^^^^^^^^^^^ | = note: using this macro is unsafe even though it does not need an `unsafe` block note: the lint level is defined here --> $DIR/lint-global-asm-as-unsafe.rs:2:9 | LL | #![deny(unsafe_code)] | ^^^^^^^^^^^ error: usage of `core::arch::global_asm` --> $DIR/lint-global-asm-as-unsafe.rs:13:9 | LL | global_asm!(\"\"); | ^^^^^^^^^^^^^^^ ... LL | unsafe_in_macro!(); | ------------------ in this macro invocation | = note: using this macro is unsafe even though it does not need an `unsafe` block = note: this error originates in the macro `unsafe_in_macro` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-49a3d465cf57f18f08ad317691227b011c5682468c746f1dde7204942d833cdb","title":"","text":"/// Returns a new span representing the next character after the end-point of this span. /// Special cases: /// - if span is a dummy one, returns the same span /// - if next_point reached the end of source, return span with lo = hi /// - if next_point reached the end of source, return a span exceeding the end of source, /// which means sm.span_to_snippet(next_point) will get `Err` /// - respect multi-byte characters pub fn next_point(&self, sp: Span) -> Span { if sp.is_dummy() {"} {"_id":"doc-en-rust-5d00c8da674586db0fc58151ac4da0918a00e85ae974ff657911f762557694b6","title":"","text":"let start_of_next_point = sp.hi().0; let width = self.find_width_of_character_at_span(sp, true); if width == 0 { return Span::new(sp.hi(), sp.hi(), sp.ctxt(), None); } // If the width is 1, then the next span should only contain the next char besides current ending. // However, in the case of a multibyte character, where the width != 1, the next span should // span multiple bytes to include the whole character."} {"_id":"doc-en-rust-61153530fc25fb81918a4d498a9afc7f761c4abec564f935b11b63744d100584","title":"","text":"// Ensure indexes are also not malformed. if start_index > end_index || end_index > source_len - 1 { debug!(\"find_width_of_character_at_span: source indexes are malformed\"); return 0; return 1; } let src = local_begin.sf.external_src.borrow();"} {"_id":"doc-en-rust-a24035534e4fd8d914ff68c6bf93be4a19a8f5ea8504f83bb3237057110d3206","title":"","text":"assert_eq!(span.lo().0, 4); assert_eq!(span.hi().0, 5); // A non-empty span at the last byte should advance to create an empty // span pointing at the end of the file. // Reaching to the end of file, return a span that will get error with `span_to_snippet` let span = Span::with_root_ctxt(BytePos(4), BytePos(5)); let span = sm.next_point(span); assert_eq!(span.lo().0, 5); assert_eq!(span.hi().0, 5); assert_eq!(span.hi().0, 6); assert!(sm.span_to_snippet(span).is_err()); // Empty span pointing just past the last byte. // Reaching to the end of file, return a span that will get error with `span_to_snippet` let span = Span::with_root_ctxt(BytePos(5), BytePos(5)); let span = sm.next_point(span); assert_eq!(span.lo().0, 5); assert_eq!(span.hi().0, 5); assert_eq!(span.hi().0, 6); assert!(sm.span_to_snippet(span).is_err()); }"} {"_id":"doc-en-rust-82cb57866e2ca1cddfa3a3546cdbd7d9c2cc0a5e1acf5264808ea3bb575d85e3","title":"","text":" // error-pattern: this file contains an unclosed delimiter // error-pattern: expected value, found struct `R` struct R { } struct S { x: [u8; R "} {"_id":"doc-en-rust-7d3e95e2912a904344760220a21f20e81e0b6a2162d55317c1d2e3a688b07795","title":"","text":" error: this file contains an unclosed delimiter --> $DIR/issue-103451.rs:5:15 | LL | struct S { | - unclosed delimiter LL | x: [u8; R | - ^ | | | unclosed delimiter error: this file contains an unclosed delimiter --> $DIR/issue-103451.rs:5:15 | LL | struct S { | - unclosed delimiter LL | x: [u8; R | - ^ | | | unclosed delimiter error[E0423]: expected value, found struct `R` --> $DIR/issue-103451.rs:5:13 | LL | struct R { } | ------------ `R` defined here LL | struct S { LL | x: [u8; R | ^ help: use struct literal syntax instead: `R {}` error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0423`. "} {"_id":"doc-en-rust-b37100f7b8e4102c829ddeb80021c7526eda36feb60c7d0ae82fe13d53e3e046","title":"","text":"} /// Parses the parameter list of a function, including the `(` and `)` delimiters. fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec> { pub(super) fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec> { let mut first_param = true; // Parse the arguments, starting out with `self` being allowed... let (mut params, _) = self.parse_paren_comma_seq(|p| {"} {"_id":"doc-en-rust-da52bc6a24cf6d5779ba6fdc69022ae788e939cddfee1cd3a355b0769065d150","title":"","text":"has_parens: bool, modifiers: BoundModifiers, ) -> PResult<'a, GenericBound> { let lifetime_defs = self.parse_late_bound_lifetime_defs()?; let path = if self.token.is_keyword(kw::Fn) let mut lifetime_defs = self.parse_late_bound_lifetime_defs()?; let mut path = if self.token.is_keyword(kw::Fn) && self.look_ahead(1, |tok| tok.kind == TokenKind::OpenDelim(Delimiter::Parenthesis)) && let Some(path) = self.recover_path_from_fn() {"} {"_id":"doc-en-rust-02a6547f7e7e0986caf04e5715e6ca6e41813e1eb553078a9baff68a6ad4df5a","title":"","text":"} else { self.parse_path(PathStyle::Type)? }; if self.may_recover() && self.token == TokenKind::OpenDelim(Delimiter::Parenthesis) { self.recover_fn_trait_with_lifetime_params(&mut path, &mut lifetime_defs)?; } if has_parens { if self.token.is_like_plus() { // Someone has written something like `&dyn (Trait + Other)`. The correct code"} {"_id":"doc-en-rust-f57d1a41dd9970bfc5cee2205570704f80e58a07fbb4571ccceeb2adf5e17614","title":"","text":"} } /// Recover from `Fn`-family traits (Fn, FnMut, FnOnce) with lifetime arguments /// (e.g. `FnOnce<'a>(&'a str) -> bool`). Up to generic arguments have already /// been eaten. fn recover_fn_trait_with_lifetime_params( &mut self, fn_path: &mut ast::Path, lifetime_defs: &mut Vec, ) -> PResult<'a, ()> { let fn_path_segment = fn_path.segments.last_mut().unwrap(); let generic_args = if let Some(p_args) = &fn_path_segment.args { p_args.clone().into_inner() } else { // Normally it wouldn't come here because the upstream should have parsed // generic parameters (otherwise it's impossible to call this function). return Ok(()); }; let lifetimes = if let ast::GenericArgs::AngleBracketed(ast::AngleBracketedArgs { span: _, args }) = &generic_args { args.into_iter() .filter_map(|arg| { if let ast::AngleBracketedArg::Arg(generic_arg) = arg && let ast::GenericArg::Lifetime(lifetime) = generic_arg { Some(lifetime) } else { None } }) .collect() } else { Vec::new() }; // Only try to recover if the trait has lifetime params. if lifetimes.is_empty() { return Ok(()); } // Parse `(T, U) -> R`. let inputs_lo = self.token.span; let inputs: Vec<_> = self.parse_fn_params(|_| false)?.into_iter().map(|input| input.ty).collect(); let inputs_span = inputs_lo.to(self.prev_token.span); let output = self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?; let args = ast::ParenthesizedArgs { span: fn_path_segment.span().to(self.prev_token.span), inputs, inputs_span, output, } .into(); *fn_path_segment = ast::PathSegment { ident: fn_path_segment.ident, args, id: ast::DUMMY_NODE_ID }; // Convert parsed `<'a>` in `Fn<'a>` into `for<'a>`. let mut generic_params = lifetimes .iter() .map(|lt| GenericParam { id: lt.id, ident: lt.ident, attrs: ast::AttrVec::new(), bounds: Vec::new(), is_placeholder: false, kind: ast::GenericParamKind::Lifetime, colon_span: None, }) .collect::>(); lifetime_defs.append(&mut generic_params); let generic_args_span = generic_args.span(); let mut err = self.struct_span_err(generic_args_span, \"`Fn` traits cannot take lifetime parameters\"); let snippet = format!( \"for<{}> \", lifetimes.iter().map(|lt| lt.ident.as_str()).intersperse(\", \").collect::(), ); let before_fn_path = fn_path.span.shrink_to_lo(); err.multipart_suggestion( \"consider using a higher-ranked trait bound instead\", vec![(generic_args_span, \"\".to_owned()), (before_fn_path, snippet)], Applicability::MaybeIncorrect, ) .emit(); Ok(()) } pub(super) fn check_lifetime(&mut self) -> bool { self.expected_tokens.push(TokenType::Lifetime); self.token.is_lifetime()"} {"_id":"doc-en-rust-e19cdef2666eb58dd2348948f49f3020a6609f247e2c01c944de240beb74fb99","title":"","text":" // Test that Fn-family traits with lifetime parameters shouldn't compile and // we suggest the usage of higher-rank trait bounds instead. fn fa(_: impl Fn<'a>(&'a str) -> bool) {} //~^ ERROR `Fn` traits cannot take lifetime parameters fn fb(_: impl FnMut<'a, 'b>(&'a str, &'b str) -> bool) {} //~^ ERROR `Fn` traits cannot take lifetime parameters fn fc(_: impl std::fmt::Display + FnOnce<'a>(&'a str) -> bool + std::fmt::Debug) {} //~^ ERROR `Fn` traits cannot take lifetime parameters use std::ops::Fn as AliasedFn; fn fd(_: impl AliasedFn<'a>(&'a str) -> bool) {} //~^ ERROR `Fn` traits cannot take lifetime parameters fn fe(_: F) where F: Fn<'a>(&'a str) -> bool {} //~^ ERROR `Fn` traits cannot take lifetime parameters fn main() {} "} {"_id":"doc-en-rust-464b468bc537e41e043c0793e77faedd70dd646e0cfb054cf71f98a725a6b959","title":"","text":" error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:4:17 | LL | fn fa(_: impl Fn<'a>(&'a str) -> bool) {} | ^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fa(_: impl Fn<'a>(&'a str) -> bool) {} LL + fn fa(_: impl for<'a> Fn(&'a str) -> bool) {} | error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:7:20 | LL | fn fb(_: impl FnMut<'a, 'b>(&'a str, &'b str) -> bool) {} | ^^^^^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fb(_: impl FnMut<'a, 'b>(&'a str, &'b str) -> bool) {} LL + fn fb(_: impl for<'a, 'b> FnMut(&'a str, &'b str) -> bool) {} | error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:10:41 | LL | fn fc(_: impl std::fmt::Display + FnOnce<'a>(&'a str) -> bool + std::fmt::Debug) {} | ^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fc(_: impl std::fmt::Display + FnOnce<'a>(&'a str) -> bool + std::fmt::Debug) {} LL + fn fc(_: impl std::fmt::Display + for<'a> FnOnce(&'a str) -> bool + std::fmt::Debug) {} | error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:14:24 | LL | fn fd(_: impl AliasedFn<'a>(&'a str) -> bool) {} | ^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fd(_: impl AliasedFn<'a>(&'a str) -> bool) {} LL + fn fd(_: impl for<'a> AliasedFn(&'a str) -> bool) {} | error: `Fn` traits cannot take lifetime parameters --> $DIR/hrtb-malformed-lifetime-generics.rs:17:27 | LL | fn fe(_: F) where F: Fn<'a>(&'a str) -> bool {} | ^^^^ | help: consider using a higher-ranked trait bound instead | LL - fn fe(_: F) where F: Fn<'a>(&'a str) -> bool {} LL + fn fe(_: F) where F: for<'a> Fn(&'a str) -> bool {} | error: aborting due to 5 previous errors "} {"_id":"doc-en-rust-6c47754c8ed6e092b48442c113c92c8f929eda25ee70a2529ef82293ffb3dd90","title":"","text":"drain_array_with(self, |iter| try_from_trusted_iterator(iter.map(f))) } /// 'Zips up' two arrays into a single array of pairs. /// /// `zip()` returns a new array where every element is a tuple where the /// first element comes from the first array, and the second element comes /// from the second array. In other words, it zips two arrays together, /// into a single one. /// /// # Examples /// /// ``` /// #![feature(array_zip)] /// let x = [1, 2, 3]; /// let y = [4, 5, 6]; /// let z = x.zip(y); /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]); /// ``` #[unstable(feature = \"array_zip\", issue = \"80094\")] pub fn zip(self, rhs: [U; N]) -> [(T, U); N] { drain_array_with(self, |lhs| { drain_array_with(rhs, |rhs| from_trusted_iterator(crate::iter::zip(lhs, rhs))) }) } /// Returns a slice containing the entire array. Equivalent to `&s[..]`. #[stable(feature = \"array_as_slice\", since = \"1.57.0\")] #[rustc_const_stable(feature = \"array_as_slice\", since = \"1.57.0\")]"} {"_id":"doc-en-rust-9514b22fcadc0fa668a845a1e07d8925c5a893f767abbced5983d8ad6425a73a","title":"","text":"// ignore-debug (the extra assertions get in the way) #![crate_type = \"lib\"] #![feature(array_zip)] // CHECK-LABEL: @short_integer_map #[no_mangle]"} {"_id":"doc-en-rust-cc2e14ed86617a78ed4fd02f335ede9f588169ccdff6d2c0a713b9154a86e8d8","title":"","text":"x.map(|x| 2 * x + 1) } // CHECK-LABEL: @short_integer_zip_map #[no_mangle] pub fn short_integer_zip_map(x: [u32; 8], y: [u32; 8]) -> [u32; 8] { // CHECK: %[[A:.+]] = load <8 x i32> // CHECK: %[[B:.+]] = load <8 x i32> // CHECK: sub <8 x i32> %[[B]], %[[A]] // CHECK: store <8 x i32> x.zip(y).map(|(x, y)| x - y) } // This test is checking that LLVM can SRoA away a bunch of the overhead, // like fully moving the iterators to registers. Notably, previous implementations // of `map` ended up `alloca`ing the whole `array::IntoIterator`, meaning both a"} {"_id":"doc-en-rust-ce9452778466e5770489541a57db5510a3c3bf67057b71c7e47d453db8821c87","title":"","text":"// compile-flags: -C opt-level=3 -Z merge-functions=disabled // only-x86_64 #![crate_type = \"lib\"] #![feature(array_zip)] // CHECK-LABEL: @auto_vectorize_direct #[no_mangle]"} {"_id":"doc-en-rust-e2666d1bafc641d5d04d76d14c17b484dbcb7638ed18cdf94dd36b1db25229d2","title":"","text":"c } // CHECK-LABEL: @auto_vectorize_array_zip_map // CHECK-LABEL: @auto_vectorize_array_from_fn #[no_mangle] pub fn auto_vectorize_array_zip_map(a: [f32; 4], b: [f32; 4]) -> [f32; 4] { pub fn auto_vectorize_array_from_fn(a: [f32; 4], b: [f32; 4]) -> [f32; 4] { // CHECK: load <4 x float> // CHECK: load <4 x float> // CHECK: fadd <4 x float> // CHECK: store <4 x float> a.zip(b).map(|(a, b)| a + b) std::array::from_fn(|i| a[i] + b[i]) }"} {"_id":"doc-en-rust-4534f1fa4c657fb1f377bea19a98ec4b65074bc679a352dd53b40b89c598d4a2","title":"","text":"let my_out = match mode { // This is the intended out directory for compiler documentation. Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target), Mode::Std => out_dir.join(target.triple).join(\"doc\"), Mode::Std => { if self.config.cmd.json() { out_dir.join(target.triple).join(\"json-doc\") } else { out_dir.join(target.triple).join(\"doc\") } } _ => panic!(\"doc mode {:?} not expected\", mode), }; let rustdoc = self.rustdoc(compiler);"} {"_id":"doc-en-rust-1dce3404916607d491ea0e76370b4be5899225e08be3cabacb7836b29abc7b66","title":"","text":"); } let compiler = builder.compiler(stage, builder.config.build); let target_doc_dir_name = if format == DocumentationFormat::JSON { \"json-doc\" } else { \"doc\" }; let target_dir = builder.stage_out(compiler, Mode::Std).join(target.triple).join(target_doc_dir_name); // This is directory where the compiler will place the output of the command. // We will then copy the files from this directory into the final `out` directory, the specified // as a function parameter. let out_dir = builder.stage_out(compiler, Mode::Std).join(target.triple).join(\"doc\"); // `cargo` uses the same directory for both JSON docs and HTML docs. // This could lead to cross-contamination when copying files into the specified `out` directory. // For example: // ```bash // x doc std // x doc std --json // ``` // could lead to HTML docs being copied into the JSON docs output directory. // To avoid this issue, we clean the doc folder before invoking `cargo`. if out_dir.exists() { builder.remove_dir(&out_dir); } let out_dir = target_dir.join(target.triple).join(\"doc\"); let run_cargo_rustdoc_for = |package: &str| { let mut cargo = builder.cargo(compiler, Mode::Std, SourceType::InTree, target, \"rustdoc\"); compile::std_cargo(builder, target, compiler.stage, &mut cargo); cargo .arg(\"--target-dir\") .arg(&*target_dir.to_string_lossy()) .arg(\"-p\") .arg(package) .arg(\"-Zskip-rustdoc-fingerprint\")"} {"_id":"doc-en-rust-78150ba0abe090457887c07e69b27bbf2e0cfca6597cded17acd25d4547c1645","title":"","text":" include ../../run-make-fulldeps/tools.mk OUTPUT_DIR := \"$(TMPDIR)/rustdoc\" TMP_OUTPUT_DIR := \"$(TMPDIR)/tmp-rustdoc\" all: # Generate html docs $(RUSTDOC) src/lib.rs --crate-name foobar --crate-type lib --out-dir $(OUTPUT_DIR) # Copy first output for to check if it's exactly same after second compilation cp -R $(OUTPUT_DIR) $(TMP_OUTPUT_DIR) # Generate html docs once again on same output $(RUSTDOC) src/lib.rs --crate-name foobar --crate-type lib --out-dir $(OUTPUT_DIR) # Check if everything exactly same $(DIFF) -r -q $(OUTPUT_DIR) $(TMP_OUTPUT_DIR) # Generate json doc on the same output $(RUSTDOC) src/lib.rs --crate-name foobar --crate-type lib --out-dir $(OUTPUT_DIR) -Z unstable-options --output-format json # Check if expected json file is generated [ -e $(OUTPUT_DIR)/foobar.json ] # TODO # We should re-generate json doc once again and compare the diff with previously # generated one. Because layout of json docs changes in each compilation, we can't # do that currently. # # See https://github.com/rust-lang/rust/issues/103785#issuecomment-1307425590 for details. # remove generated json doc rm $(OUTPUT_DIR)/foobar.json # Check if json doc compilation broke any of the html files generated previously $(DIFF) -r -q $(OUTPUT_DIR) $(TMP_OUTPUT_DIR) "} {"_id":"doc-en-rust-ee35056138fca78bdd5de55146f2ab41873333470d92bc1f6bf0211d51fc510a","title":"","text":"*[other] patterns `{$witness_1}`, `{$witness_2}`, `{$witness_3}` and {$remainder} more } not covered mir_build_privately_uninhabited = pattern `{$witness_1}` is currently uninhabited, but this variant contains private fields which may become inhabited in the future mir_build_pattern_not_covered = refutable pattern in {$origin} .pattern_ty = the matched value is of type `{$pattern_ty}`"} {"_id":"doc-en-rust-ba6d283cc34e7d43be953f72d1d562755930cb86c76ed2d9ef65339205c25031","title":"","text":"pub interpreted_as_const: Option, #[subdiagnostic] pub adt_defined_here: Option>, #[note(mir_build_privately_uninhabited)] pub witness_1_is_privately_uninhabited: Option<()>, #[note(mir_build_pattern_ty)] pub _p: (), pub pattern_ty: Ty<'tcx>,"} {"_id":"doc-en-rust-516cccde6c75961669b62fb40e134ece0d76e7056b8a118477d90b7f25c5b06a","title":"","text":"AdtDefinedHere { adt_def_span, ty, variants } }; // Emit an extra note if the first uncovered witness is // visibly uninhabited anywhere in the current crate. let witness_1_is_privately_uninhabited = if cx.tcx.features().exhaustive_patterns && let Some(witness_1) = witnesses.get(0) && let ty::Adt(adt, substs) = witness_1.ty().kind() && adt.is_enum() && let Constructor::Variant(variant_index) = witness_1.ctor() { let variant = adt.variant(*variant_index); let inhabited = variant.inhabited_predicate(cx.tcx, *adt).subst(cx.tcx, substs); assert!(inhabited.apply(cx.tcx, cx.param_env, cx.module)); !inhabited.apply_ignore_module(cx.tcx, cx.param_env) } else { false }; self.error = Err(self.tcx.sess.emit_err(PatternNotCovered { span: pat.span, origin, uncovered: Uncovered::new(pat.span, &cx, witnesses), inform, interpreted_as_const, witness_1_is_privately_uninhabited: witness_1_is_privately_uninhabited.then_some(()), _p: (), pattern_ty, let_suggestion,"} {"_id":"doc-en-rust-7c96fb1fc3bd08778300a8b7af18e62abc246f9d9ed3fdf6a3d6de9b9e70fc54","title":"","text":"LL | A(A), LL | B(inner::Wrapper), | - not covered = note: pattern `Either::B(_)` is currently uninhabited, but this variant contains private fields which may become inhabited in the future = note: the matched value is of type `Either<(), !>` help: you might want to use `if let` to ignore the variant that isn't matched |"} {"_id":"doc-en-rust-80826f11beaa8e89dd25b5da4c7cfba237152e3e628f043280c4ae6e0b1b1f4f","title":"","text":"} enum Foo { //~^ NOTE `Foo` defined here A(foo::SecretlyEmpty), //~^ NOTE not covered B(foo::NotSoSecretlyEmpty), C(NotSoSecretlyEmpty), D(u32, u32),"} {"_id":"doc-en-rust-bae1a69b6d0f1edc8a5a5ebe78e6bc2d58bd4abecc035261913d68f8b0f7fca6","title":"","text":"let Foo::D(_y, _z) = x; //~^ ERROR refutable pattern in local binding //~| `Foo::A(_)` not covered //~| NOTE `let` bindings require an \"irrefutable pattern\" //~| NOTE for more information //~| NOTE pattern `Foo::A(_)` is currently uninhabited //~| NOTE the matched value is of type `Foo` //~| HELP you might want to use `let else` }"} {"_id":"doc-en-rust-497fe439c18495592b076f18b3107afa9b54e3287b7df8e6461d63fda3c568b6","title":"","text":"error[E0005]: refutable pattern in local binding --> $DIR/uninhabited-irrefutable.rs:27:9 --> $DIR/uninhabited-irrefutable.rs:29:9 | LL | let Foo::D(_y, _z) = x; | ^^^^^^^^^^^^^^ pattern `Foo::A(_)` not covered"} {"_id":"doc-en-rust-2e18fad3ae262a993f8c7965fbbe9f21491f454ca27c13f09bbc5fa48d19e63a","title":"","text":"| LL | enum Foo { | ^^^ LL | LL | A(foo::SecretlyEmpty), | - not covered = note: pattern `Foo::A(_)` is currently uninhabited, but this variant contains private fields which may become inhabited in the future = note: the matched value is of type `Foo` help: you might want to use `let else` to handle the variant that isn't matched |"} {"_id":"doc-en-rust-2def19a331433a1abd578abfaef1ac611c3a538619719d22c3083b4aa3c64c57","title":"","text":"let literal = constant.literal; match literal { ConstantKind::Ty(c) => match c.kind() { ConstKind::Param(_) => {} ConstKind::Param(_) | ConstKind::Error(_) => {} _ => bug!(\"only ConstKind::Param should be encountered here, got {:#?}\", c), }, ConstantKind::Unevaluated(..) => self.required_consts.push(*constant),"} {"_id":"doc-en-rust-819c05428d98eefe2889551d84d3ab631dd094cbee45c8afb7c0e775ff8d9fa5","title":"","text":" fn f() -> impl Sized { 2.0E //~^ ERROR expected at least one digit in exponent } fn main() {} "} {"_id":"doc-en-rust-9b291932bfcdc8a2a054c6621c0c87f08e75fd9e7904874f4759f1f5be7e3238","title":"","text":" error: expected at least one digit in exponent --> $DIR/invalid-const-in-body.rs:2:5 | LL | 2.0E | ^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-dae98f47b72f867a1ae86d3396acd90f7db755d107d1641723860acdcef21c4a","title":"","text":"font-weight: 600; margin: 0; padding: 0; /* position notable traits in mobile mode within the header */ position: relative; } #crate-search,"} {"_id":"doc-en-rust-52a402a65bebc40e37708480f7def66d38ab55d6710e04ec4338220114639b84","title":"","text":"// Check the impl items. assert-css: (\".impl-items .has-srclink .srclink\", {\"font-size\": \"16px\", \"font-weight\": 400}, ALL) assert-css: (\".impl-items .has-srclink .code-header\", {\"font-size\": \"16px\", \"font-weight\": 600}, ALL) // Check that we can click on source link store-document-property: (url, \"URL\") click: \".impl-items .has-srclink .srclink\" assert-document-property-false: {\"URL\": |url|} "} {"_id":"doc-en-rust-2dd7c5780b5cf6ddcfa3e671d81a0b610429615db0337950062f1bb5e7dd4687","title":"","text":"//! //! * Should probably have something like this for strings. //! * Should they implement Closable? Would take extra state. use cmp::max; use cmp::min; use prelude::*; use super::*;"} {"_id":"doc-en-rust-81b9bcac09820a958917105f529f452a13065b337f9c8ca17e82ce9df7c6fc89","title":"","text":"} } // FIXME(#10432) impl Seek for MemWriter { fn tell(&self) -> u64 { self.pos as u64 } fn seek(&mut self, pos: i64, style: SeekStyle) { match style { SeekSet => { self.pos = pos as uint; } SeekEnd => { self.pos = self.buf.len() + pos as uint; } SeekCur => { self.pos += pos as uint; } } // compute offset as signed and clamp to prevent overflow let offset = match style { SeekSet => { 0 } SeekEnd => { self.buf.len() } SeekCur => { self.pos } } as i64; self.pos = max(0, offset+pos) as uint; } }"} {"_id":"doc-en-rust-c5ba2db8bf97d4ecbb2da08434a93f95cd677a207080c47d98bd46693168cf2e","title":"","text":"/// Writes to a fixed-size byte slice /// /// If a write will not fit in the buffer, it raises the `io_error` /// condition and does not write any data. pub struct BufWriter<'self> { priv buf: &'self mut [u8], priv pos: uint"} {"_id":"doc-en-rust-c613c67566ca31167d66a00878e411e62852494580c2e66f17bed7b457bcaa46","title":"","text":"} impl<'self> Writer for BufWriter<'self> { fn write(&mut self, _buf: &[u8]) { fail!() } fn write(&mut self, buf: &[u8]) { // raises a condition if the entire write does not fit in the buffer let max_size = self.buf.len(); if self.pos >= max_size || (self.pos + buf.len()) > max_size { io_error::cond.raise(IoError { kind: OtherIoError, desc: \"Trying to write past end of buffer\", detail: None }); return; } fn flush(&mut self) { fail!() } vec::bytes::copy_memory(self.buf.mut_slice_from(self.pos), buf, buf.len()); self.pos += buf.len(); } } // FIXME(#10432) impl<'self> Seek for BufWriter<'self> { fn tell(&self) -> u64 { fail!() } fn tell(&self) -> u64 { self.pos as u64 } fn seek(&mut self, _pos: i64, _style: SeekStyle) { fail!() } fn seek(&mut self, pos: i64, style: SeekStyle) { // compute offset as signed and clamp to prevent overflow let offset = match style { SeekSet => { 0 } SeekEnd => { self.buf.len() } SeekCur => { self.pos } } as i64; self.pos = max(0, offset+pos) as uint; } }"} {"_id":"doc-en-rust-713750027e213bf62249d1c3daf30a0355e948f12607a350f291890c6e4deaac","title":"","text":"} #[test] fn test_buf_writer() { let mut buf = [0 as u8, ..8]; { let mut writer = BufWriter::new(buf); assert_eq!(writer.tell(), 0); writer.write([0]); assert_eq!(writer.tell(), 1); writer.write([1, 2, 3]); writer.write([4, 5, 6, 7]); assert_eq!(writer.tell(), 8); } assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7]); } #[test] fn test_buf_writer_seek() { let mut buf = [0 as u8, ..8]; { let mut writer = BufWriter::new(buf); assert_eq!(writer.tell(), 0); writer.write([1]); assert_eq!(writer.tell(), 1); writer.seek(2, SeekSet); assert_eq!(writer.tell(), 2); writer.write([2]); assert_eq!(writer.tell(), 3); writer.seek(-2, SeekCur); assert_eq!(writer.tell(), 1); writer.write([3]); assert_eq!(writer.tell(), 2); writer.seek(-1, SeekEnd); assert_eq!(writer.tell(), 7); writer.write([4]); assert_eq!(writer.tell(), 8); } assert_eq!(buf, [1, 3, 2, 0, 0, 0, 0, 4]); } #[test] fn test_buf_writer_error() { let mut buf = [0 as u8, ..2]; let mut writer = BufWriter::new(buf); writer.write([0]); let mut called = false; do io_error::cond.trap(|err| { assert_eq!(err.kind, OtherIoError); called = true; }).inside { writer.write([0, 0]); } assert!(called); } #[test] fn test_mem_reader() { let mut reader = MemReader::new(~[0, 1, 2, 3, 4, 5, 6, 7]); let mut buf = [];"} {"_id":"doc-en-rust-2683d51390a781f634aa37785691fdd525ed5abbd7b39c6175fa52c4cdf6f5f3","title":"","text":"let tcx = self.infcx.tcx; // Try to find predicates on *generic params* that would allow copying `ty` let infcx = tcx.infer_ctxt().build(); if infcx .type_implements_trait( tcx.lang_items().clone_trait().unwrap(), [tcx.erase_regions(ty)], self.param_env, ) .must_apply_modulo_regions() if let Some(clone_trait_def) = tcx.lang_items().clone_trait() && infcx .type_implements_trait( clone_trait_def, [tcx.erase_regions(ty)], self.param_env, ) .must_apply_modulo_regions() { err.span_suggestion_verbose( span.shrink_to_hi(),"} {"_id":"doc-en-rust-96b9a8a8f8bc1871a033c37cc40698387768dc8f884fea7847748b1e8251683f","title":"","text":" // Avoid panicking if the Clone trait is not found while building error suggestions // See #104870 #![feature(no_core, lang_items)] #![no_core] #[lang = \"sized\"] trait Sized {} #[lang = \"copy\"] trait Copy {} fn g(x: T) {} fn f(x: *mut u8) { g(x); g(x); //~ ERROR use of moved value: `x` } fn main() {} "} {"_id":"doc-en-rust-258ac8555ee9126bfaa3a19504c8c8c246164e1eecfa2ac4faf564abb3361c4b","title":"","text":" error[E0382]: use of moved value: `x` --> $DIR/missing-clone-for-suggestion.rs:17:7 | LL | fn f(x: *mut u8) { | - move occurs because `x` has type `*mut u8`, which does not implement the `Copy` trait LL | g(x); | - value moved here LL | g(x); | ^ value used here after move | note: consider changing this parameter type in function `g` to borrow instead if owning the value isn't necessary --> $DIR/missing-clone-for-suggestion.rs:13:12 | LL | fn g(x: T) {} | - ^ this parameter takes ownership of the value | | | in this function error: aborting due to previous error For more information about this error, try `rustc --explain E0382`. "} {"_id":"doc-en-rust-280f492344298b6e0e74e1c58efa22eb95af1ac52bb4f8f4fa0f7df8262b0dd6","title":"","text":")); } // FIXME: remove the suggestions that are from derive, as the span is not correct suggestions = suggestions .into_iter() .filter(|(span, _, _)| !span.in_derive_expansion()) .collect::>(); if suggestions.len() == 1 { let (span, suggestion, msg) = suggestions.pop().unwrap();"} {"_id":"doc-en-rust-e80e6a6bba09dc5dfacc2c74f6e78f2ec5859dd26c4f7bbc836bea4cca31088f","title":"","text":" // force-host // no-prefer-dynamic #![crate_type = \"proc-macro\"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(AddImpl)] pub fn derive(input: TokenStream) -> TokenStream { \"use std::cmp::Ordering; impl Ord for PriorityQueue { fn cmp(&self, other: &Self) -> Ordering { self.0.cmp(&self.height) } } \" .parse() .unwrap() } "} {"_id":"doc-en-rust-b7badba7d13e80ab31791a2fe658848f4f40bea17e1d72ec903fd1114c2b585d","title":"","text":" // aux-build:issue-104884.rs use std::collections::BinaryHeap; #[macro_use] extern crate issue_104884; #[derive(PartialEq, Eq, PartialOrd, Ord)] struct PriorityQueueEntry { value: T, } #[derive(PartialOrd, AddImpl)] //~^ ERROR can't compare `PriorityQueue` with `PriorityQueue` //~| ERROR the trait bound `PriorityQueue: Eq` is not satisfied //~| ERROR can't compare `T` with `T` struct PriorityQueue(BinaryHeap>); fn main() {} "} {"_id":"doc-en-rust-c85b5368e0b66a72cdb24b9c282ca19e4aee8727ddc762fe63e4eae7fc7b64da","title":"","text":" error[E0277]: can't compare `PriorityQueue` with `PriorityQueue` --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:10 | LL | #[derive(PartialOrd, AddImpl)] | ^^^^^^^^^^ no implementation for `PriorityQueue == PriorityQueue` | = help: the trait `PartialEq` is not implemented for `PriorityQueue` note: required by a bound in `PartialOrd` --> $SRC_DIR/core/src/cmp.rs:LL:COL | LL | pub trait PartialOrd: PartialEq { | ^^^^^^^^^^^^^^ required by this bound in `PartialOrd` = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `PriorityQueue: Eq` is not satisfied --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:22 | LL | #[derive(PartialOrd, AddImpl)] | ^^^^^^^ the trait `Eq` is not implemented for `PriorityQueue` | note: required by a bound in `Ord` --> $SRC_DIR/core/src/cmp.rs:LL:COL | LL | pub trait Ord: Eq + PartialOrd { | ^^ required by this bound in `Ord` = note: this error originates in the derive macro `AddImpl` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `T` with `T` --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:22 | LL | #[derive(PartialOrd, AddImpl)] | ^^^^^^^ no implementation for `T < T` and `T > T` | note: required for `PriorityQueue` to implement `PartialOrd` --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:10 | LL | #[derive(PartialOrd, AddImpl)] | ^^^^^^^^^^ note: required by a bound in `Ord` --> $SRC_DIR/core/src/cmp.rs:LL:COL | LL | pub trait Ord: Eq + PartialOrd { | ^^^^^^^^^^^^^^^^ required by this bound in `Ord` = note: this error originates in the derive macro `AddImpl` which comes from the expansion of the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-250356a05983b669717f7cfcbaa12f367ed9335d34fda8c59ccf3fa7bd38a4ce","title":"","text":"//! OS-specific networking functionality. // See cfg macros in `library/std/src/os/mod.rs` for why these platforms must // be special-cased during rustdoc generation. #[cfg(not(all( doc, any( all(target_arch = \"wasm32\", not(target_os = \"wasi\")), all(target_vendor = \"fortanix\", target_env = \"sgx\") ) )))] #[cfg(any(target_os = \"linux\", target_os = \"android\", doc))] pub(super) mod linux_ext;"} {"_id":"doc-en-rust-a7d760a707f971560db5d92d3838ab6e426d255d84d9263390c33ef113466689","title":"","text":"// Use `||` to give these suggestions a precedence let _ = self.suggest_missing_parentheses(err, expr) || self.suggest_remove_last_method_call(err, expr, expected) || self.suggest_associated_const(err, expr, expected) || self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr) || self.suggest_option_to_bool(err, expr, expr_ty, expected)"} {"_id":"doc-en-rust-092b7957328c2530c6e91dfac6d5d92cd3e4f64f5c7eeca631462d728c358d12","title":"","text":"} } pub fn suggest_remove_last_method_call( &self, err: &mut Diagnostic, expr: &hir::Expr<'tcx>, expected: Ty<'tcx>, ) -> bool { if let hir::ExprKind::MethodCall(hir::PathSegment { ident: method, .. }, recv_expr, &[], _) = expr.kind && let Some(recv_ty) = self.typeck_results.borrow().expr_ty_opt(recv_expr) && self.can_coerce(recv_ty, expected) { let span = if let Some(recv_span) = recv_expr.span.find_ancestor_inside(expr.span) { expr.span.with_lo(recv_span.hi()) } else { expr.span.with_lo(method.span.lo() - rustc_span::BytePos(1)) }; err.span_suggestion_verbose( span, \"try removing the method call\", \"\", Applicability::MachineApplicable, ); return true; } false } pub fn suggest_deref_ref_or_into( &self, err: &mut Diagnostic,"} {"_id":"doc-en-rust-aa423afe830fc762a5e760afac9a6318842333e400efb4dd5a415b099b63ef96","title":"","text":" fn test1() { let _v: i32 = (1 as i32).to_string(); //~ ERROR mismatched types // won't suggestion let _v: i32 = (1 as i128).to_string(); //~ ERROR mismatched types let _v: &str = \"foo\".to_string(); //~ ERROR mismatched types } fn test2() { let mut path: String = \"/usr\".to_string(); let folder: String = \"lib\".to_string(); path = format!(\"{}/{}\", path, folder).as_str(); //~ ERROR mismatched types println!(\"{}\", &path); } fn main() { test1(); test2(); } "} {"_id":"doc-en-rust-68d6690276e2f227418f3b6b617d99915b6fe0caa61f6e9f352ce6e3091bc500","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-105494.rs:2:19 | LL | let _v: i32 = (1 as i32).to_string(); | --- ^^^^^^^^^^^^^^^^^^^^^^ expected `i32`, found struct `String` | | | expected due to this | help: try removing the method call | LL - let _v: i32 = (1 as i32).to_string(); LL + let _v: i32 = (1 as i32); | error[E0308]: mismatched types --> $DIR/issue-105494.rs:5:19 | LL | let _v: i32 = (1 as i128).to_string(); | --- ^^^^^^^^^^^^^^^^^^^^^^^ expected `i32`, found struct `String` | | | expected due to this error[E0308]: mismatched types --> $DIR/issue-105494.rs:7:20 | LL | let _v: &str = \"foo\".to_string(); | ---- ^^^^^^^^^^^^^^^^^ expected `&str`, found struct `String` | | | expected due to this | help: try removing the method call | LL - let _v: &str = \"foo\".to_string(); LL + let _v: &str = \"foo\"; | error[E0308]: mismatched types --> $DIR/issue-105494.rs:14:12 | LL | let mut path: String = \"/usr\".to_string(); | ------ expected due to this type ... LL | path = format!(\"{}/{}\", path, folder).as_str(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `String`, found `&str` | help: try removing the method call | LL - path = format!(\"{}/{}\", path, folder).as_str(); LL + path = format!(\"{}/{}\", path, folder); | error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-6b67df3bb7d7b83e3d705ae9003cee4bbdc9ac458e44294e85f43a28c4e4abae","title":"","text":") -> OperandRef<'tcx, Bx::Value> { let tcx = bx.tcx(); let mut span_to_caller_location = |span: Span| { let mut span_to_caller_location = |mut span: Span| { // Remove `Inlined` marks as they pollute `expansion_cause`. while span.is_inlined() { span.remove_mark(); } let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let caller = tcx.sess.source_map().lookup_char_pos(topmost.lo()); let const_loc = tcx.const_caller_location(("} {"_id":"doc-en-rust-c61f8bb0fad8bc377606b089ef41ebda0503983d6c9f48c8accbcaa03d83947f","title":"","text":"location } pub(crate) fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) { pub(crate) fn location_triple_for_span(&self, mut span: Span) -> (Symbol, u32, u32) { // Remove `Inlined` marks as they pollute `expansion_cause`. while span.is_inlined() { span.remove_mark(); } let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo()); ("} {"_id":"doc-en-rust-5df73485d1b86fe1d7af04491f4d18b20400a015ffc84065c6ee561962f6d6d0","title":"","text":"pub fn fresh_expansion(self, expn_id: LocalExpnId) -> Span { HygieneData::with(|data| { self.with_ctxt(data.apply_mark( SyntaxContext::root(), self.ctxt(), expn_id.to_expn_id(), Transparency::Transparent, ))"} {"_id":"doc-en-rust-7cdea07721f18aabb3ccb3dad6765e24ba6572bb814fbfaf74db08532a2bd159","title":"","text":"// run-pass // revisions: default mir-opt //[default] compile-flags: -Zinline-mir=no //[mir-opt] compile-flags: -Zmir-opt-level=4 macro_rules! caller_location_from_macro {"} {"_id":"doc-en-rust-0523094a1a5c6164148f6efbbcb6388c9221d4f672c777688c49c9aeafeb0b99","title":"","text":"fn main() { let loc = core::panic::Location::caller(); assert_eq!(loc.file(), file!()); assert_eq!(loc.line(), 10); assert_eq!(loc.line(), 11); assert_eq!(loc.column(), 15); // `Location::caller()` in a macro should behave similarly to `file!` and `line!`, // i.e. point to where the macro was invoked, instead of the macro itself. let loc2 = caller_location_from_macro!(); assert_eq!(loc2.file(), file!()); assert_eq!(loc2.line(), 17); assert_eq!(loc2.line(), 18); assert_eq!(loc2.column(), 16); }"} {"_id":"doc-en-rust-dbde42a5a4d7f289f9694b0ba7db768b72f3d89c7f725433f34a0be77d6359fe","title":"","text":" // run-pass // revisions: default mir-opt //[default] compile-flags: -Zinline-mir=no //[mir-opt] compile-flags: -Zmir-opt-level=4 use std::panic::Location; macro_rules! f { () => { Location::caller() }; } #[inline(always)] fn g() -> &'static Location<'static> { f!() } fn main() { let loc = g(); assert_eq!(loc.line(), 16); assert_eq!(loc.column(), 5); } "} {"_id":"doc-en-rust-8054c7de4092538b914128a8f45ad75b97525169015a98bf627466ae57592445","title":"","text":"}); } else { debug_assert!(self.tcx.is_trait(trait_def_id)); if self.tcx.trait_is_auto(trait_def_id) { return; } for item in self.impl_or_trait_item(trait_def_id) { // Check whether `trait_def_id` defines a method with suitable name. if !self.has_applicable_self(&item) {"} {"_id":"doc-en-rust-814ae92a73e188e2ec0db4e2e3b46d3dc3bdedc87826a21b215d15b901b1c2bd","title":"","text":"_ => false, } }) && (type_is_local || info.def_id.is_local()) && !self.tcx.trait_is_auto(info.def_id) && self .associated_value(info.def_id, item_name) .filter(|item| {"} {"_id":"doc-en-rust-664a5304f7cf639592fdae522702fbf55e7f597a5af7dede8f333475e60f49c8","title":"","text":"trait Bar { fn f(&self) { self.g(); //~ ERROR the method `g` exists for reference `&Self`, but its trait bounds were not satisfied // issue #105788 self.g(); //~ ERROR no method named `g` found for reference `&Self` in the current scope } }"} {"_id":"doc-en-rust-db614a25a3097d166f312a772cfbaf98d7b630dfdde90c6da0ec46e602e927f4","title":"","text":"LL | fn g(&self); | ---^-------- help: remove these associated items error[E0599]: the method `g` exists for reference `&Self`, but its trait bounds were not satisfied --> $DIR/issue-105732.rs:9:14 error[E0599]: no method named `g` found for reference `&Self` in the current scope --> $DIR/issue-105732.rs:10:14 | LL | self.g(); | ^ | = note: the following trait bounds were not satisfied: `Self: Foo` which is required by `&Self: Foo` `&Self: Foo` = help: items from traits can only be used if the type parameter is bounded by the trait help: the following trait defines an item `g`, perhaps you need to add a supertrait for it: | LL | trait Bar: Foo { | +++++ | ^ help: there is a method with a similar name: `f` error: aborting due to 2 previous errors"} {"_id":"doc-en-rust-f57a9860dec8debdada3f409e25824dc7b548f76de410529f7a4389b41d83be5","title":"","text":"); for virtual_dir in virtual_rust_source_base_dir.iter().flatten() { if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { if let rustc_span::FileName::Real(old_name) = name { if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = old_name { if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { let virtual_name = virtual_name.clone(); // The std library crates are in // `$sysroot/lib/rustlib/src/rust/library`, whereas other crates // may be in `$sysroot/lib/rustlib/src/rust/` directly. So we // detect crates from the std libs and handle them specially. const STD_LIBS: &[&str] = &[ \"core\", \"alloc\", \"std\", \"test\", \"term\", \"unwind\", \"proc_macro\", \"panic_abort\", \"panic_unwind\", \"profiler_builtins\", \"rtstartup\", \"rustc-std-workspace-core\", \"rustc-std-workspace-alloc\", \"rustc-std-workspace-std\", \"backtrace\", ]; let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l)); let new_path = if is_std_lib { real_dir.join(\"library\").join(rest) } else { real_dir.join(rest) }; debug!( \"try_to_translate_virtual_to_real: `{}` -> `{}`\", virtual_name.display(), new_path.display(), ); let new_name = rustc_span::RealFileName::Remapped { local_path: Some(new_path), virtual_name, }; *old_name = new_name; } if let Some(real_dir) = &sess.opts.real_rust_source_base_dir && let rustc_span::FileName::Real(old_name) = name && let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = old_name && let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { // The std library crates are in // `$sysroot/lib/rustlib/src/rust/library`, whereas other crates // may be in `$sysroot/lib/rustlib/src/rust/` directly. So we // detect crates from the std libs and handle them specially. const STD_LIBS: &[&str] = &[ \"core\", \"alloc\", \"std\", \"test\", \"term\", \"unwind\", \"proc_macro\", \"panic_abort\", \"panic_unwind\", \"profiler_builtins\", \"rtstartup\", \"rustc-std-workspace-core\", \"rustc-std-workspace-alloc\", \"rustc-std-workspace-std\", \"backtrace\", ]; let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l)); let new_path = if is_std_lib { real_dir.join(\"library\").join(rest) } else { real_dir.join(rest) }; debug!( \"try_to_translate_virtual_to_real: `{}` -> `{}`\", virtual_name.display(), new_path.display(), ); // Check if the translated real path is affected by any user-requested // remaps via --remap-path-prefix. Apply them if so. // Note that this is a special case for imported rust-src paths specified by // https://rust-lang.github.io/rfcs/3127-trim-paths.html#handling-sysroot-paths. // Other imported paths are not currently remapped (see #66251). let (user_remapped, applied) = sess.source_map().path_mapping().map_prefix(&new_path); let new_name = if applied { rustc_span::RealFileName::Remapped { local_path: Some(new_path.clone()), virtual_name: user_remapped.to_path_buf(), } } } else { rustc_span::RealFileName::LocalPath(new_path) }; *old_name = new_name; } } };"} {"_id":"doc-en-rust-e429dcc58ee178bb5576d2b31fa15f249386ebf9801b2e4a49414888025d8394","title":"","text":"const CWD: &str = \"{{cwd}}\"; const SRC_BASE: &str = \"{{src-base}}\"; const BUILD_BASE: &str = \"{{build-base}}\"; const RUST_SRC_BASE: &str = \"{{rust-src-base}}\"; const SYSROOT_BASE: &str = \"{{sysroot-base}}\"; const TARGET_LINKER: &str = \"{{target-linker}}\"; const TARGET: &str = \"{{target}}\";"} {"_id":"doc-en-rust-a79f0033684be5df6feaa4e48e6cfdd54d7ad8c6da85335d266c3ece3f6dee25","title":"","text":"value = value.replace(TARGET, &config.target); } if value.contains(RUST_SRC_BASE) { let src_base = config.sysroot_base.join(\"lib/rustlib/src/rust\"); src_base.try_exists().expect(&*format!(\"{} should exists\", src_base.display())); let src_base = src_base.read_link().unwrap_or(src_base); value = value.replace(RUST_SRC_BASE, &src_base.to_string_lossy()); } value }"} {"_id":"doc-en-rust-586b69106cc8076747464ccb7f57539f53bccb4c96ef0d817b497de640b4e225","title":"","text":"} let base_dir = Path::new(\"/rustc/FAKE_PREFIX\"); // Paths into the libstd/libcore // Fake paths into the libstd/libcore normalize_path(&base_dir.join(\"library\"), \"$SRC_DIR\"); // `ui-fulldeps` tests can show paths to the compiler source when testing macros from // `rustc_macros` // eg. /home/user/rust/compiler normalize_path(&base_dir.join(\"compiler\"), \"$COMPILER_DIR\"); // Real paths into the libstd/libcore let rust_src_dir = &self.config.sysroot_base.join(\"lib/rustlib/src/rust\"); rust_src_dir.try_exists().expect(&*format!(\"{} should exists\", rust_src_dir.display())); let rust_src_dir = rust_src_dir.read_link().unwrap_or(rust_src_dir.to_path_buf()); normalize_path(&rust_src_dir.join(\"library\"), \"$SRC_DIR_REAL\"); // Paths into the build directory let test_build_dir = &self.config.build_base; let parent_build_dir = test_build_dir.parent().unwrap().parent().unwrap().parent().unwrap();"} {"_id":"doc-en-rust-6d783e014a5d643cbc12a8ca15eb52ca6d0852aba484100b5931087fdde5e087","title":"","text":"// eg. /home/user/rust/build normalize_path(parent_build_dir, \"$BUILD_DIR\"); // Paths into lib directory. normalize_path(&parent_build_dir.parent().unwrap().join(\"lib\"), \"$LIB_DIR\"); if json { // escaped newlines in json strings should be readable // in the stderr files. There's no point int being correct,"} {"_id":"doc-en-rust-53d92c80779062ba63e173dec942c5b0ab9a289196564b770770f4e8f65f37a9","title":"","text":" //@ revisions: with-remap without-remap //@ compile-flags: -g -Ztranslate-remapped-path-to-local-path=yes //@ [with-remap]compile-flags: --remap-path-prefix={{rust-src-base}}=remapped //@ [with-remap]compile-flags: --remap-path-prefix={{src-base}}=remapped-tests-ui //@ [without-remap]compile-flags: //@ error-pattern: E0507 // The $SRC_DIR*.rs:LL:COL normalisation doesn't kick in automatically // as the remapped revision will not begin with $SRC_DIR_REAL, // so we have to do it ourselves. //@ normalize-stderr-test: \".rs:d+:d+\" -> \".rs:LL:COL\" use std::thread; struct Worker { thread: thread::JoinHandle<()>, } impl Drop for Worker { fn drop(&mut self) { self.thread.join().unwrap(); } } pub fn main(){} "} {"_id":"doc-en-rust-c127948485ece503124dc70019ed32b24d0c6eab8be75a76d14be1e3568eea3d","title":"","text":" error[E0507]: cannot move out of `self.thread` which is behind a mutable reference --> remapped-tests-ui/errors/remap-path-prefix-sysroot.rs:LL:COL | LL | self.thread.join().unwrap(); | ^^^^^^^^^^^ ------ `self.thread` moved due to this method call | | | move occurs because `self.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait | note: `JoinHandle::::join` takes ownership of the receiver `self`, which moves `self.thread` --> remapped/library/std/src/thread/mod.rs:LL:COL | LL | pub fn join(self) -> Result { | ^^^^ error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0507`. "} {"_id":"doc-en-rust-df8ca95eadc6779bed4cf773feff307c46a5f9c28ccb7a00b052127a3e0f75df","title":"","text":" error[E0507]: cannot move out of `self.thread` which is behind a mutable reference --> $DIR/remap-path-prefix-sysroot.rs:LL:COL | LL | self.thread.join().unwrap(); | ^^^^^^^^^^^ ------ `self.thread` moved due to this method call | | | move occurs because `self.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait | note: `JoinHandle::::join` takes ownership of the receiver `self`, which moves `self.thread` --> $SRC_DIR_REAL/std/src/thread/mod.rs:LL:COL | LL | pub fn join(self) -> Result { | ^^^^ error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0507`. "} {"_id":"doc-en-rust-306e89ceccd411cf73ff8bc4b0441c169ac84e824765f6208f808dcc46ef8e5b","title":"","text":"|| self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty) || self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected) || self.suggest_copied_or_cloned(err, expr, expr_ty, expected) || self.suggest_clone_for_ref(err, expr, expr_ty, expected) || self.suggest_into(err, expr, expr_ty, expected) || self.suggest_floating_point_literal(err, expr, expected); if !suggested {"} {"_id":"doc-en-rust-2ced6609157c9203f14a6a7ef6be0fb1dbc309c997c44ac5d5c64777dde4fa73","title":"","text":"} } pub(crate) fn suggest_clone_for_ref( &self, diag: &mut Diagnostic, expr: &hir::Expr<'_>, expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool { if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind() && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait() && expected_ty == *inner_ty && self .infcx .type_implements_trait( clone_trait_def, [self.tcx.erase_regions(expected_ty)], self.param_env ) .must_apply_modulo_regions() { diag.span_suggestion_verbose( expr.span.shrink_to_hi(), \"consider using clone here\", \".clone()\", Applicability::MachineApplicable, ); return true; } false } pub(crate) fn suggest_copied_or_cloned( &self, diag: &mut Diagnostic,"} {"_id":"doc-en-rust-6a12f3bb7b50b956fd1e337efdbe953c82d5ff9ed044bf90605a26fd60e64207","title":"","text":"); } if self.suggest_add_clone_to_arg(&obligation, &mut err, trait_predicate) { err.emit(); return; } if self.suggest_impl_trait(&mut err, span, &obligation, trait_predicate) { err.emit(); return;"} {"_id":"doc-en-rust-2505d0040a833973662443a92b8d2ea6f4a7acb7001ffc3461f3737e7f8c1bf7","title":"","text":"use crate::traits::{NormalizeExt, ObligationCtxt}; use hir::def::CtorOf; use hir::HirId; use hir::{Expr, HirId}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{"} {"_id":"doc-en-rust-f8650c92d48a052fde5569c4042a9d43451ec64c3a1ea03715f90eda9c2cdd3b","title":"","text":"trait_pred: ty::PolyTraitPredicate<'tcx>, ); fn suggest_add_clone_to_arg( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic, trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool; fn suggest_add_reference_to_arg( &self, obligation: &PredicateObligation<'tcx>,"} {"_id":"doc-en-rust-0cbaccc8ad8377a32e0585865e2f1975edca13702c88f3fd49be63d0ea809639","title":"","text":"} } fn suggest_add_clone_to_arg( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic, trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool { let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); let ty = self.tcx.erase_late_bound_regions(self_ty); let owner = self.tcx.hir().get_parent_item(obligation.cause.body_id); let Some(generics) = self.tcx.hir().get_generics(owner.def_id) else { return false }; let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false }; let ty::Param(param) = inner_ty.kind() else { return false }; let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() else { return false }; let arg_node = self.tcx.hir().get(*arg_hir_id); let Node::Expr(Expr { kind: hir::ExprKind::Path(_), ..}) = arg_node else { return false }; let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None); let has_clone = |ty| { self.type_implements_trait(clone_trait, [ty], obligation.param_env) .must_apply_modulo_regions() }; let new_obligation = self.mk_trait_obligation_with_new_self_ty( obligation.param_env, trait_pred.map_bound(|trait_pred| (trait_pred, *inner_ty)), ); if self.predicate_may_hold(&new_obligation) && has_clone(ty) { if !has_clone(param.to_ty(self.tcx)) { suggest_constraining_type_param( self.tcx, generics, err, param.name.as_str(), \"Clone\", Some(clone_trait), ); } err.span_suggestion_verbose( obligation.cause.span.shrink_to_hi(), \"consider using clone here\", \".clone()\".to_string(), Applicability::MaybeIncorrect, ); return true; } false } fn suggest_add_reference_to_arg( &self, obligation: &PredicateObligation<'tcx>,"} {"_id":"doc-en-rust-4de7e07273b3386c1ca46a32a9cdbda6ad37b1eded3bb1acd7f17075aa5d9195","title":"","text":" #[derive(Clone)] struct S; // without Clone struct T; fn foo(_: S) {} fn test1() { let s = &S; foo(s); //~ ERROR mismatched types } fn bar(_: T) {} fn test2() { let t = &T; bar(t); //~ ERROR mismatched types } fn main() { test1(); test2(); } "} {"_id":"doc-en-rust-753045b13a470997b963fb2a13415bafa4b717f689fd8d934967e12b151328c0","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-106443-sugg-clone-for-arg.rs:11:9 | LL | foo(s); | --- ^ expected struct `S`, found `&S` | | | arguments to this function are incorrect | note: function defined here --> $DIR/issue-106443-sugg-clone-for-arg.rs:7:4 | LL | fn foo(_: S) {} | ^^^ ---- help: consider using clone here | LL | foo(s.clone()); | ++++++++ error[E0308]: mismatched types --> $DIR/issue-106443-sugg-clone-for-arg.rs:17:9 | LL | bar(t); | --- ^ expected struct `T`, found `&T` | | | arguments to this function are incorrect | note: function defined here --> $DIR/issue-106443-sugg-clone-for-arg.rs:14:4 | LL | fn bar(_: T) {} | ^^^ ---- error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-08ac133e9640a3f81dbfc771ced21e79f30b3e6d137252e4d17d088e61fbabc8","title":"","text":" #[derive(Clone)] struct S; trait X {} impl X for S {} fn foo(_: T) {} fn bar(s: &T) { foo(s); //~ ERROR the trait bound `&T: X` is not satisfied } fn bar_with_clone(s: &T) { foo(s); //~ ERROR the trait bound `&T: X` is not satisfied } fn main() { let s = &S; bar(s); } "} {"_id":"doc-en-rust-da658f74e5cc6d9c84cb69ec593a2cf47436df35f55bcb185be2e7b88fd9294b","title":"","text":" error[E0277]: the trait bound `&T: X` is not satisfied --> $DIR/issue-106443-sugg-clone-for-bound.rs:10:9 | LL | foo(s); | ^ the trait `X` is not implemented for `&T` | help: consider further restricting this bound | LL | fn bar(s: &T) { | +++++++ help: consider using clone here | LL | foo(s.clone()); | ++++++++ error[E0277]: the trait bound `&T: X` is not satisfied --> $DIR/issue-106443-sugg-clone-for-bound.rs:14:9 | LL | foo(s); | ^ the trait `X` is not implemented for `&T` | help: consider using clone here | LL | foo(s.clone()); | ++++++++ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-a0c9b5642d393ee4d7e0fc0eacc548c331e68f9f73466c85156b20b9051386d6","title":"","text":"names: FxHashMap, } // FIXME: Rustdoc has trouble proving Send/Sync for this. See #106930. #[cfg(parallel_compiler)] unsafe impl Sync for FormatArguments {} #[cfg(parallel_compiler)] unsafe impl Send for FormatArguments {} impl FormatArguments { pub fn new() -> Self { Self {"} {"_id":"doc-en-rust-671f2e6c5b862d2a5697b9a65b12e9cecfece874cec96d261cac2d00934c36c4","title":"","text":"cx: &mut DocContext<'_>, item_def_id: DefId, ) -> impl Iterator { // FIXME: To be removed once `parallel_compiler` bugs are fixed! // More information in . if cfg!(parallel_compiler) { return vec![].into_iter().chain(vec![].into_iter()); } let auto_impls = cx .sess() .prof"} {"_id":"doc-en-rust-d7d7aa01a14563ab38b711706ca59a2486657ae11d10f101ec80dc5c791c49b1","title":"","text":"use rustc_middle::ty::TyCtxt; pub fn check_crate(tcx: TyCtxt<'_>) { tcx.dep_graph.assert_ignored(); if tcx.sess.opts.unstable_opts.hir_stats { crate::hir_stats::print_hir_stats(tcx); }"} {"_id":"doc-en-rust-80f15df5db75930bc7cddcdc2f7359c4df93876523f65eaed6b520857229475d","title":"","text":"assert_eq!(_green_node_index, DepNodeIndex::SINGLETON_DEPENDENCYLESS_ANON_NODE); // Instantiate a dependy-less red node only once for anonymous queries. let (_red_node_index, _prev_and_index) = current.intern_node( let (red_node_index, red_node_prev_index_and_color) = current.intern_node( profiler, &prev_graph, DepNode { kind: DepKind::RED, hash: Fingerprint::ZERO.into() },"} {"_id":"doc-en-rust-31660b630a74d6782a24a3153f7fc479947b44b861bd7baa7cfc80cb363509b5","title":"","text":"None, false, ); assert_eq!(_red_node_index, DepNodeIndex::FOREVER_RED_NODE); assert!(matches!(_prev_and_index, None | Some((_, DepNodeColor::Red)))); assert_eq!(red_node_index, DepNodeIndex::FOREVER_RED_NODE); match red_node_prev_index_and_color { None => { // This is expected when we have no previous compilation session. assert!(prev_graph_node_count == 0); } Some((prev_red_node_index, DepNodeColor::Red)) => { assert_eq!(prev_red_node_index.as_usize(), red_node_index.as_usize()); colors.insert(prev_red_node_index, DepNodeColor::Red); } Some((_, DepNodeColor::Green(_))) => { // There must be a logic error somewhere if we hit this branch. panic!(\"DepNodeIndex::FOREVER_RED_NODE evaluated to DepNodeColor::Green\") } } DepGraph { data: Some(Lrc::new(DepGraphData {"} {"_id":"doc-en-rust-cb079dd9aec96a14f4d8e876c9a15dc11cb8ab3a5ef7a09f9d8714fd662249ee","title":"","text":"})) }; let task_deps_ref = match &task_deps { Some(deps) => TaskDepsRef::Allow(deps), None => TaskDepsRef::Ignore, }; let task_deps_ref = task_deps.as_ref().map(TaskDepsRef::Allow).unwrap_or(TaskDepsRef::EvalAlways); let result = K::with_deps(task_deps_ref, || task(cx, arg)); let edges = task_deps.map_or_else(|| smallvec![], |lock| lock.into_inner().reads);"} {"_id":"doc-en-rust-1db21ed5ba51ca986db4c2a69243cb006c29a12fc800835c22aa530140554b59","title":"","text":"K::read_deps(|task_deps| { let mut task_deps = match task_deps { TaskDepsRef::Allow(deps) => deps.lock(), TaskDepsRef::EvalAlways => { // We don't need to record dependencies of eval_always // queries. They are re-evaluated unconditionally anyway. return; } TaskDepsRef::Ignore => return, TaskDepsRef::Forbid => { panic!(\"Illegal read of: {dep_node_index:?}\")"} {"_id":"doc-en-rust-82cff8ffc9127b5c91e43c10a3ec56fbeb3b56a658f0fe7f320c0714f466b137","title":"","text":"let mut edges = SmallVec::new(); K::read_deps(|task_deps| match task_deps { TaskDepsRef::Allow(deps) => edges.extend(deps.lock().reads.iter().copied()), TaskDepsRef::Ignore => {} // During HIR lowering, we have no dependencies. TaskDepsRef::EvalAlways => { edges.push(DepNodeIndex::FOREVER_RED_NODE); } TaskDepsRef::Ignore => {} TaskDepsRef::Forbid => { panic!(\"Cannot summarize when dependencies are not recorded.\") }"} {"_id":"doc-en-rust-b12c0ffb0dbf27a5626c61c33c17f2684a782ffcb4eacf63e006f3ceaec9f99a","title":"","text":"/// `TaskDeps`. This is used when executing a 'normal' query /// (no `eval_always` modifier) Allow(&'a Lock>), /// New dependencies are ignored. This is used when /// executing an `eval_always` query, since there's no /// This is used when executing an `eval_always` query. We don't /// need to track dependencies for a query that's always /// re-executed. This is also used for `dep_graph.with_ignore` /// re-executed -- but we need to know that this is an `eval_always` /// query in order to emit dependencies to `DepNodeIndex::FOREVER_RED_NODE` /// when directly feeding other queries. EvalAlways, /// New dependencies are ignored. This is also used for `dep_graph.with_ignore`. Ignore, /// Any attempt to add new dependencies will cause a panic. /// This is used when decoding a query result from disk,"} {"_id":"doc-en-rust-13aad5225e2a0689971368696fe04fedac645ebe3266919ab05caa132c50723c","title":"","text":" // revisions: cpass1 cpass2 #![crate_type = \"rlib\"] use std::fmt::Debug; // MCVE kindly provided by Nilstrieb at // https://github.com/rust-lang/rust/issues/108481#issuecomment-1493080185 #[derive(Debug)] pub struct ConstGeneric { _p: [(); CHUNK_SIZE], } #[cfg(cpass1)] impl ConstGeneric {} "} {"_id":"doc-en-rust-347e8299559d96c98c206b708d42ac9f1f0573c80a52d1b5d6f1c7647612b048","title":"","text":"self.draw_code_line( &mut buffer, &mut row_num, &Vec::new(), &[], p + line_start, l, show_code_change,"} {"_id":"doc-en-rust-8538698363ad5cc2bba62d34cf6861113f4ddbe697b5b5051a4fb2cc392233b9","title":"","text":"self.draw_code_line( &mut buffer, &mut row_num, highlight_parts, &highlight_parts, line_pos + line_start, line, show_code_change,"} {"_id":"doc-en-rust-eac7d28f35d7278c5c236dc3ee4d219b7bff7518f24168504c2acd59ec485e37","title":"","text":"&self, buffer: &mut StyledBuffer, row_num: &mut usize, highlight_parts: &Vec, highlight_parts: &[SubstitutionHighlight], line_num: usize, line_to_add: &str, show_code_change: DisplaySuggestion,"} {"_id":"doc-en-rust-835aa6514d3469134aa67bc8f2401f80ed347c41430b361b6413efc0fdeb5831","title":"","text":"}); buf.push_str(&part.snippet); let cur_hi = sm.lookup_char_pos(part.span.hi()); if prev_hi.line == cur_lo.line && cur_hi.line == cur_lo.line { if cur_hi.line == cur_lo.line { // Account for the difference between the width of the current code and the // snippet being suggested, so that the *later* suggestions are correctly // aligned on the screen."} {"_id":"doc-en-rust-94e58ddb5bf77c87de3f7c247596b816f01acad7d0197a8a30757200de6f0079","title":"","text":" // compile-flags: --error-format=human --color=always // ignore-windows fn short(foo_bar: &Vec<&i32>) -> &i32 { //~ ERROR missing lifetime specifier &12 } fn long( //~ ERROR missing lifetime specifier foo_bar: &Vec<&i32>, something_very_long_so_that_the_line_will_wrap_around__________: i32, ) -> &i32 { &12 } fn long2( //~ ERROR missing lifetime specifier foo_bar: &Vec<&i32>) -> &i32 { &12 } fn main() {} "} {"_id":"doc-en-rust-680602bcceb95b6a94962adef76c261b47bc5fafac6f33cda3f68b62cd2f127f","title":"","text":" \u001b[0m\u001b[1m\u001b[38;5;9merror[E0106]\u001b[0m\u001b[0m\u001b[1m: missing lifetime specifier\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m--> \u001b[0m\u001b[0m$DIR/multiline-multipart-suggestion.rs:4:34\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\u001b[0m \u001b[0m\u001b[0mfn short(foo_bar: &Vec<&i32>) -> &i32 { \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m----------\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;9m^\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;9mexpected named lifetime parameter\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m= \u001b[0m\u001b[0m\u001b[1mhelp\u001b[0m\u001b[0m: this function's return type contains a borrowed value, but the signature does not say which one of `foo_bar`'s 2 lifetimes it is borrowed from\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;14mhelp\u001b[0m\u001b[0m: consider introducing a named lifetime parameter\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0mfn short\u001b[0m\u001b[0m\u001b[38;5;10m<'a>\u001b[0m\u001b[0m(foo_bar: &\u001b[0m\u001b[0m\u001b[38;5;10m'a \u001b[0m\u001b[0mVec<&\u001b[0m\u001b[0m\u001b[38;5;10m'a \u001b[0m\u001b[0mi32>) -> &\u001b[0m\u001b[0m\u001b[38;5;10m'a \u001b[0m\u001b[0mi32 { \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[38;5;10m++++\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[38;5;10m++\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[38;5;10m++\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[38;5;10m++\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;9merror[E0106]\u001b[0m\u001b[0m\u001b[1m: missing lifetime specifier\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m--> \u001b[0m\u001b[0m$DIR/multiline-multipart-suggestion.rs:11:6\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\u001b[0m \u001b[0m\u001b[0m foo_bar: &Vec<&i32>,\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m----------\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\u001b[0m \u001b[0m\u001b[0m something_very_long_so_that_the_line_will_wrap_around__________: i32,\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\u001b[0m \u001b[0m\u001b[0m) -> &i32 {\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;9m^\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;9mexpected named lifetime parameter\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m= \u001b[0m\u001b[0m\u001b[1mhelp\u001b[0m\u001b[0m: this function's return type contains a borrowed value, but the signature does not say which one of `foo_bar`'s 2 lifetimes it is borrowed from\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;14mhelp\u001b[0m\u001b[0m: consider introducing a named lifetime parameter\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[38;5;10m~ \u001b[0m\u001b[0mfn long\u001b[0m\u001b[0m\u001b[38;5;10m<'a>\u001b[0m\u001b[0m( \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[38;5;10m~ \u001b[0m\u001b[0m foo_bar: &\u001b[0m\u001b[0m\u001b[38;5;10m'a \u001b[0m\u001b[0mVec<&\u001b[0m\u001b[0m\u001b[38;5;10m'a \u001b[0m\u001b[0mi32>,\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0m something_very_long_so_that_the_line_will_wrap_around__________: i32,\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[38;5;10m~ \u001b[0m\u001b[0m) -> &\u001b[0m\u001b[0m\u001b[38;5;10m'a \u001b[0m\u001b[0mi32 {\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;9merror[E0106]\u001b[0m\u001b[0m\u001b[1m: missing lifetime specifier\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m--> \u001b[0m\u001b[0m$DIR/multiline-multipart-suggestion.rs:16:29\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m\u001b[0m \u001b[0m\u001b[0m foo_bar: &Vec<&i32>) -> &i32 {\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m| \u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m----------\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;9m^\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;9mexpected named lifetime parameter\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m= \u001b[0m\u001b[0m\u001b[1mhelp\u001b[0m\u001b[0m: this function's return type contains a borrowed value, but the signature does not say which one of `foo_bar`'s 2 lifetimes it is borrowed from\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;14mhelp\u001b[0m\u001b[0m: consider introducing a named lifetime parameter\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[38;5;10m~ \u001b[0m\u001b[0mfn long2\u001b[0m\u001b[0m\u001b[38;5;10m<'a>\u001b[0m\u001b[0m( \u001b[0m\u001b[1m\u001b[38;5;12mLL\u001b[0m\u001b[0m \u001b[0m\u001b[0m\u001b[38;5;10m~ \u001b[0m\u001b[0m foo_bar: &\u001b[0m\u001b[0m\u001b[38;5;10m'a \u001b[0m\u001b[0mVec<&\u001b[0m\u001b[0m\u001b[38;5;10m'a \u001b[0m\u001b[0mi32>) -> &\u001b[0m\u001b[0m\u001b[38;5;10m'a \u001b[0m\u001b[0mi32 {\u001b[0m \u001b[0m \u001b[0m\u001b[0m\u001b[1m\u001b[38;5;12m|\u001b[0m \u001b[0m\u001b[1m\u001b[38;5;9merror\u001b[0m\u001b[0m\u001b[1m: aborting due to 3 previous errors\u001b[0m \u001b[0m\u001b[1mFor more information about this error, try `rustc --explain E0106`.\u001b[0m "} {"_id":"doc-en-rust-64a9c7b9b601f8625925ba8aaae38dbce8a72b271579aed0278e10b3c11a2a6b","title":"","text":"BareFunctionDecl { unsafety: bare_fn.unsafety, abi: bare_fn.abi, decl, generic_params } } /// This visitor is used to go through only the \"top level\" of a item and not enter any sub /// item while looking for a given `Ident` which is stored into `item` if found. struct OneLevelVisitor<'hir> { /// Get DefId of of an item's user-visible parent. /// /// \"User-visible\" should account for re-exporting and inlining, which is why this function isn't /// just `tcx.parent(def_id)`. If the provided `path` has more than one path element, the `DefId` /// of the second-to-last will be given. /// /// ```text /// use crate::foo::Bar; /// ^^^ DefId of this item will be returned /// ``` /// /// If the provided path has only one item, `tcx.parent(def_id)` will be returned instead. fn get_path_parent_def_id( tcx: TyCtxt<'_>, def_id: DefId, path: &hir::UsePath<'_>, ) -> Option { if let [.., parent_segment, _] = &path.segments { match parent_segment.res { hir::def::Res::Def(_, parent_def_id) => Some(parent_def_id), _ if parent_segment.ident.name == kw::Crate => { // In case the \"parent\" is the crate, it'll give `Res::Err` so we need to // circumvent it this way. Some(tcx.parent(def_id)) } _ => None, } } else { // If the path doesn't have a parent, then the parent is the current module. Some(tcx.parent(def_id)) } } /// This visitor is used to find an HIR Item based on its `use` path. This doesn't use the ordinary /// name resolver because it does not walk all the way through a chain of re-exports. pub(crate) struct OneLevelVisitor<'hir> { map: rustc_middle::hir::map::Map<'hir>, item: Option<&'hir hir::Item<'hir>>, pub(crate) item: Option<&'hir hir::Item<'hir>>, looking_for: Ident, target_def_id: LocalDefId, } impl<'hir> OneLevelVisitor<'hir> { fn new(map: rustc_middle::hir::map::Map<'hir>, target_def_id: LocalDefId) -> Self { pub(crate) fn new(map: rustc_middle::hir::map::Map<'hir>, target_def_id: LocalDefId) -> Self { Self { map, item: None, looking_for: Ident::empty(), target_def_id } } fn reset(&mut self, looking_for: Ident) { self.looking_for = looking_for; pub(crate) fn find_target( &mut self, tcx: TyCtxt<'_>, def_id: DefId, path: &hir::UsePath<'_>, ) -> Option<&'hir hir::Item<'hir>> { let parent_def_id = get_path_parent_def_id(tcx, def_id, path)?; let parent = self.map.get_if_local(parent_def_id)?; // We get the `Ident` we will be looking for into `item`. self.looking_for = path.segments[path.segments.len() - 1].ident; // We reset the `item`. self.item = None; match parent { hir::Node::Item(parent_item) => { hir::intravisit::walk_item(self, parent_item); } hir::Node::Crate(m) => { hir::intravisit::walk_mod( self, m, tcx.local_def_id_to_hir_id(parent_def_id.as_local().unwrap()), ); } _ => return None, } self.item } }"} {"_id":"doc-en-rust-ee765f14995f267eac0cec3d7eeed9450cd57cef47076587b86cec93dcab6c2d","title":"","text":"add_without_unwanted_attributes(attributes, hir_map.attrs(item.hir_id()), is_inline); } let def_id = if let [.., parent_segment, _] = &path.segments { match parent_segment.res { hir::def::Res::Def(_, def_id) => def_id, _ if parent_segment.ident.name == kw::Crate => { // In case the \"parent\" is the crate, it'll give `Res::Err` so we need to // circumvent it this way. tcx.parent(item.owner_id.def_id.to_def_id()) } _ => break, } } else { // If the path doesn't have a parent, then the parent is the current module. tcx.parent(item.owner_id.def_id.to_def_id()) }; let Some(parent) = hir_map.get_if_local(def_id) else { break }; // We get the `Ident` we will be looking for into `item`. let looking_for = path.segments[path.segments.len() - 1].ident; visitor.reset(looking_for); match parent { hir::Node::Item(parent_item) => { hir::intravisit::walk_item(&mut visitor, parent_item); } hir::Node::Crate(m) => { hir::intravisit::walk_mod( &mut visitor, m, tcx.local_def_id_to_hir_id(def_id.as_local().unwrap()), ); } _ => break, } if let Some(i) = visitor.item { if let Some(i) = visitor.find_target(tcx, item.owner_id.def_id.to_def_id(), path) { item = i; } else { break;"} {"_id":"doc-en-rust-53032e9255e0206057d77cd84f5afbd41027607a73d5e4c90def3444edb3bdc8","title":"","text":"use std::mem; use crate::clean::{cfg::Cfg, AttributesExt, NestedAttributesExt}; use crate::clean::{cfg::Cfg, AttributesExt, NestedAttributesExt, OneLevelVisitor}; use crate::core; /// This module is used to store stuff from Rust's AST in a more convenient"} {"_id":"doc-en-rust-08f6463083dfa8d1c28717af81dd429822b99d8f3f021921717051c6203b7d10","title":"","text":"renamed: Option, glob: bool, please_inline: bool, path: &hir::UsePath<'_>, ) -> bool { debug!(\"maybe_inline_local res: {:?}\", res);"} {"_id":"doc-en-rust-18edf76ee9f2df2408afa2e63e9c46ec3ff8eda8e53b1b52f231f2b812ed1994","title":"","text":"return false; } if !please_inline && let mut visitor = OneLevelVisitor::new(self.cx.tcx.hir(), res_did) && let Some(item) = visitor.find_target(self.cx.tcx, def_id.to_def_id(), path) && let item_def_id = item.owner_id.def_id && item_def_id != def_id && self .cx .cache .effective_visibilities .is_directly_public(self.cx.tcx, item_def_id.to_def_id()) && !inherits_doc_hidden(self.cx.tcx, item_def_id) { // The imported item is public and not `doc(hidden)` so no need to inline it. return false; } let ret = match tcx.hir().get_by_def_id(res_did) { Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => { let prev = mem::replace(&mut self.inlining, true);"} {"_id":"doc-en-rust-b7528342a66a9168faed64d14dbb69829ca17916a3b683178faa1e134e2aee37","title":"","text":"ident, is_glob, please_inline, path, ) { continue; }"} {"_id":"doc-en-rust-daffa026baf6a71bcf5f6d6cf0fe56550007974591ec9ef8b5336423ac3f0ea9","title":"","text":" // This test ensures that the `struct.B.html` only exists in `a`: // since `a::B` is public (and inlined too), `self::a::B` doesn't // need to be inlined as well. #![crate_name = \"foo\"] pub mod a { // @has 'foo/a/index.html' // Should only contain \"Structs\". // @count - '//*[@id=\"main-content\"]//*[@class=\"item-table\"]' 1 // @has - '//*[@id=\"structs\"]' 'Structs' // @has - '//*[@id=\"main-content\"]//a[@href=\"struct.A.html\"]' 'A' // @has - '//*[@id=\"main-content\"]//a[@href=\"struct.B.html\"]' 'B' mod b { pub struct B; } pub use self::b::B; pub struct A; } // @has 'foo/index.html' // @!has - '//*[@id=\"structs\"]' 'Structs' // @has - '//*[@id=\"reexports\"]' 'Re-exports' // @has - '//*[@id=\"modules\"]' 'Modules' // @has - '//*[@id=\"main-content\"]//*[@id=\"reexport.A\"]' 'pub use self::a::A;' // @has - '//*[@id=\"main-content\"]//*[@id=\"reexport.B\"]' 'pub use self::a::B;' // Should only contain \"Modules\" and \"Re-exports\". // @count - '//*[@id=\"main-content\"]//*[@class=\"item-table\"]' 2 pub use self::a::{A, B}; "} {"_id":"doc-en-rust-0e8476d70769c441629af8d18f3dc3d80de088c396f65ef6e6aeaba50aab8416","title":"","text":"None } fn suggest_missing_writer( &self, rcvr_ty: Ty<'tcx>, args: (&'tcx hir::Expr<'tcx>, &'tcx [hir::Expr<'tcx>]), ) -> DiagnosticBuilder<'_, ErrorGuaranteed> { let (ty_str, _ty_file) = self.tcx.short_ty_string(rcvr_ty); let mut err = struct_span_err!(self.tcx.sess, args.0.span, E0599, \"cannot write into `{}`\", ty_str); err.span_note( args.0.span, \"must implement `io::Write`, `fmt::Write`, or have a `write_fmt` method\", ); if let ExprKind::Lit(_) = args.0.kind { err.span_help( args.0.span.shrink_to_lo(), \"a writer is needed before this format string\", ); }; err } pub fn report_no_match_method_error( &self, mut span: Span,"} {"_id":"doc-en-rust-24ab77df76fa9b84d90490d51e0da3b7c5880e87e72d4d322a51b4763d14b3ef","title":"","text":"} } let mut err = struct_span_err!( tcx.sess, span, E0599, \"no {} named `{}` found for {} `{}` in the current scope\", item_kind, item_name, rcvr_ty.prefix_string(self.tcx), ty_str_reported, ); let is_write = sugg_span.ctxt().outer_expn_data().macro_def_id.map_or(false, |def_id| { tcx.is_diagnostic_item(sym::write_macro, def_id) || tcx.is_diagnostic_item(sym::writeln_macro, def_id) }) && item_name.name == Symbol::intern(\"write_fmt\"); let mut err = if is_write && let Some(args) = args { self.suggest_missing_writer(rcvr_ty, args) } else { struct_span_err!( tcx.sess, span, E0599, \"no {} named `{}` found for {} `{}` in the current scope\", item_kind, item_name, rcvr_ty.prefix_string(self.tcx), ty_str_reported, ) }; if tcx.sess.source_map().is_multiline(sugg_span) { err.span_label(sugg_span.with_hi(span.lo()), \"\"); }"} {"_id":"doc-en-rust-a73437b1c6488c8dd5a1fe864a6f805bbe036386c95f959bb617cc5b8cb4c237","title":"","text":" // Check error for missing writer in writeln! and write! macro fn main() { let x = 1; let y = 2; write!(\"{}_{}\", x, y); //~^ ERROR format argument must be a string literal //~| HELP you might be missing a string literal to format with //~| ERROR cannot write into `&'static str` //~| NOTE must implement `io::Write`, `fmt::Write`, or have a `write_fmt` method //~| HELP a writer is needed before this format string writeln!(\"{}_{}\", x, y); //~^ ERROR format argument must be a string literal //~| HELP you might be missing a string literal to format with //~| ERROR cannot write into `&'static str` //~| NOTE must implement `io::Write`, `fmt::Write`, or have a `write_fmt` method //~| HELP a writer is needed before this format string } "} {"_id":"doc-en-rust-977e307c5cd2f356711afe37c9416f196d05621be029ef8c8dd339779afeb597","title":"","text":" error: format argument must be a string literal --> $DIR/missing-writer.rs:5:21 | LL | write!(\"{}_{}\", x, y); | ^ | help: you might be missing a string literal to format with | LL | write!(\"{}_{}\", \"{} {}\", x, y); | ++++++++ error: format argument must be a string literal --> $DIR/missing-writer.rs:11:23 | LL | writeln!(\"{}_{}\", x, y); | ^ | help: you might be missing a string literal to format with | LL | writeln!(\"{}_{}\", \"{} {}\", x, y); | ++++++++ error[E0599]: cannot write into `&'static str` --> $DIR/missing-writer.rs:5:12 | LL | write!(\"{}_{}\", x, y); | -------^^^^^^^------- method not found in `&str` | note: must implement `io::Write`, `fmt::Write`, or have a `write_fmt` method --> $DIR/missing-writer.rs:5:12 | LL | write!(\"{}_{}\", x, y); | ^^^^^^^ help: a writer is needed before this format string --> $DIR/missing-writer.rs:5:12 | LL | write!(\"{}_{}\", x, y); | ^ error[E0599]: cannot write into `&'static str` --> $DIR/missing-writer.rs:11:14 | LL | writeln!(\"{}_{}\", x, y); | ---------^^^^^^^------- method not found in `&str` | note: must implement `io::Write`, `fmt::Write`, or have a `write_fmt` method --> $DIR/missing-writer.rs:11:14 | LL | writeln!(\"{}_{}\", x, y); | ^^^^^^^ help: a writer is needed before this format string --> $DIR/missing-writer.rs:11:14 | LL | writeln!(\"{}_{}\", x, y); | ^ error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0599`. "} {"_id":"doc-en-rust-c790c4ac41ab23cdf05c6c17dde23c78844b73dddc01229d6b9cd463a3234ed8","title":"","text":"--> $SRC_DIR/std/src/io/buffered/bufwriter.rs:LL:COL error[E0599]: the method `write_fmt` exists for struct `BufWriter<&dyn Write>`, but its trait bounds were not satisfied --> $DIR/mut-borrow-needed-by-trait.rs:21:5 --> $DIR/mut-borrow-needed-by-trait.rs:21:14 | LL | writeln!(fp, \"hello world\").unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ method cannot be called on `BufWriter<&dyn Write>` due to unsatisfied trait bounds | ---------^^---------------- method cannot be called on `BufWriter<&dyn Write>` due to unsatisfied trait bounds --> $SRC_DIR/std/src/io/buffered/bufwriter.rs:LL:COL | = note: doesn't satisfy `BufWriter<&dyn std::io::Write>: std::io::Write` | note: must implement `io::Write`, `fmt::Write`, or have a `write_fmt` method --> $DIR/mut-borrow-needed-by-trait.rs:21:14 | LL | writeln!(fp, \"hello world\").unwrap(); | ^^ = note: the following trait bounds were not satisfied: `&dyn std::io::Write: std::io::Write` which is required by `BufWriter<&dyn std::io::Write>: std::io::Write` = note: this error originates in the macro `writeln` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors"} {"_id":"doc-en-rust-bb4ec4786ff1e21c7cf4d14dfe32bdcca36902f613f1c6dfbb69af181be2df43","title":"","text":"r: ty::Region<'tcx>, ) -> ty::Region<'tcx> { match *r { ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReErased | ty::ReStatic => r, ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReErased | ty::ReStatic | ty::ReError(_) => r, ty::ReVar(_) => canonicalizer.canonical_var_for_region_in_root_universe(r), _ => { ty::RePlaceholder(..) | ty::ReLateBound(..) => { // We only expect region names that the user can type. bug!(\"unexpected region in query response: `{:?}`\", r) }"} {"_id":"doc-en-rust-5845b9e5b13e26c0909ba1c86253f7dfb5d6fa4219eef083615e779829da5786","title":"","text":" // Regression test for #109072. // Check that we don't ICE when canonicalizing user annotation. trait Lt<'a> { type T; } impl Lt<'missing> for () { //~ ERROR undeclared lifetime type T = &'missing (); //~ ERROR undeclared lifetime } fn main() { let _: <() as Lt<'_>>::T = &(); } "} {"_id":"doc-en-rust-435ce0308e28860f41fc39890faa2afb13db8b116d5ed98eb61aecca45436b1d","title":"","text":" error[E0261]: use of undeclared lifetime name `'missing` --> $DIR/region-error-ice-109072.rs:8:9 | LL | impl Lt<'missing> for () { | - ^^^^^^^^ undeclared lifetime | | | help: consider introducing lifetime `'missing` here: `<'missing>` error[E0261]: use of undeclared lifetime name `'missing` --> $DIR/region-error-ice-109072.rs:9:15 | LL | type T = &'missing (); | ^^^^^^^^ undeclared lifetime | help: consider introducing lifetime `'missing` here | LL | type T<'missing> = &'missing (); | ++++++++++ help: consider introducing lifetime `'missing` here | LL | impl<'missing> Lt<'missing> for () { | ++++++++++ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0261`. "} {"_id":"doc-en-rust-47eaedd1117a9d7072ed895118c9c440f2968ca7fabf277a9b37b3a29a45932c","title":"","text":"e.note( \"the macro call doesn't expand to an expression, but it can expand to a statement\", ); e.span_suggestion_verbose( site_span.shrink_to_hi(), \"add `;` to interpret the expansion as a statement\", \";\", Applicability::MaybeIncorrect, ); if parser.token == token::Semi { if let Ok(snippet) = parser.sess.source_map().span_to_snippet(site_span) { e.span_suggestion_verbose( site_span, \"surround the macro invocation with `{}` to interpret the expansion as a statement\", format!(\"{{ {}; }}\", snippet), Applicability::MaybeIncorrect, ); } } else { e.span_suggestion_verbose( site_span.shrink_to_hi(), \"add `;` to interpret the expansion as a statement\", \";\", Applicability::MaybeIncorrect, ); } } }, _ => annotate_err_with_kind(&mut e, kind, site_span),"} {"_id":"doc-en-rust-123b448a710c1a9964e2777d6c23749db0600ac3129b6ff1130f5d56048368be","title":"","text":" macro_rules! statement { () => {;}; //~ ERROR expected expression } fn main() { let _ = statement!(); } "} {"_id":"doc-en-rust-ea1b9e79b4bcae31609117650e887056393a28c0aedb68a83863e172751bc950","title":"","text":" error: expected expression, found `;` --> $DIR/issue-109237.rs:2:12 | LL | () => {;}; | ^ expected expression ... LL | let _ = statement!(); | ------------ in this macro invocation | = note: the macro call doesn't expand to an expression, but it can expand to a statement = note: this error originates in the macro `statement` (in Nightly builds, run with -Z macro-backtrace for more info) help: surround the macro invocation with `{}` to interpret the expansion as a statement | LL | let _ = { statement!(); }; | ~~~~~~~~~~~~~~~~~ error: aborting due to previous error "} {"_id":"doc-en-rust-5c75e96ed4d0f3d572dd00289e87a2117ed13704ad290aaef7dd9be78723d51e","title":"","text":"// the expected const's type. Specifically, we don't want const infer vars // to do any type shapeshifting before and after resolution. if let Err(guar) = compatible_types { return Ok(self.tcx.const_error_with_guaranteed( if relation.a_is_expected() { a.ty() } else { b.ty() }, guar, )); // HACK: equating both sides with `[const error]` eagerly prevents us // from leaving unconstrained inference vars during things like impl // matching in the solver. let a_error = self.tcx.const_error_with_guaranteed(a.ty(), guar); if let ty::ConstKind::Infer(InferConst::Var(vid)) = a.kind() { return self.unify_const_variable(vid, a_error); } let b_error = self.tcx.const_error_with_guaranteed(b.ty(), guar); if let ty::ConstKind::Infer(InferConst::Var(vid)) = b.kind() { return self.unify_const_variable(vid, b_error); } return Ok(if relation.a_is_expected() { a_error } else { b_error }); } match (a.kind(), b.kind()) {"} {"_id":"doc-en-rust-ffb14f4a9fc7222bc52dd8532667115afb97a753d46b2011b789a9105c223f2d","title":"","text":"use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{error_code, DelayDm, Diagnostic}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::ty::{self, ImplSubject, Ty, TyCtxt}; use rustc_middle::ty::{self, ImplSubject, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::ty::{InternalSubsts, SubstsRef}; use rustc_session::lint::builtin::COHERENCE_LEAK_CHECK; use rustc_session::lint::builtin::ORDER_DEPENDENT_TRAIT_OBJECTS;"} {"_id":"doc-en-rust-1233d615099b4458f19ee2b19031040cf75f4a2f437250dfb318528bb08d9797","title":"","text":"impl_span: Span, err: &mut Diagnostic, ) { if (overlap.trait_ref, overlap.self_ty).references_error() { err.downgrade_to_delayed_bug(); } match tcx.span_of_impl(overlap.with_impl) { Ok(span) => { err.span_label(span, \"first implementation here\");"} {"_id":"doc-en-rust-8ee3a17400690d42808ac9d944e77099f4c91dc1558a1aa458c21e3562b41a54","title":"","text":" // incremental #![crate_type = \"lib\"] trait Q { const ASSOC: usize; } impl Q for [u8; N] { //~^ ERROR mismatched types const ASSOC: usize = 1; } pub fn test() -> [u8; <[u8; 13] as Q>::ASSOC] { todo!() } "} {"_id":"doc-en-rust-9127f071f7db222a3d56f33329a7c796bbcf217866e51013a35c908d3d613a8e","title":"","text":" error[E0308]: mismatched types --> $DIR/bad-subst-const-kind.rs:8:31 | LL | impl Q for [u8; N] { | ^ expected `usize`, found `u64` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-8a0da227d69e45c554414021b6a55538162156dee0d75f0c308271eae868a606","title":"","text":"// An impl that has an erroneous const substitution should not specialize one // that is well-formed. #[derive(Clone)] struct S; impl Copy for S {} //~^ ERROR the constant `N` is not of type `usize` impl Copy for S {} //~^ ERROR conflicting implementations of trait `Copy` for type `S<_>` fn main() {}"} {"_id":"doc-en-rust-7b8c351b34224c281f19568994a29558a4d4fdd6b5d3df0f25e6f9471173209f","title":"","text":" error[E0119]: conflicting implementations of trait `Copy` for type `S<_>` --> $DIR/bad-const-wf-doesnt-specialize.rs:9:1 error: the constant `N` is not of type `usize` --> $DIR/bad-const-wf-doesnt-specialize.rs:8:29 | LL | impl Copy for S {} | -------------------------------- first implementation here LL | impl Copy for S {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `S<_>` | ^^^^ | note: required by a bound in `S` --> $DIR/bad-const-wf-doesnt-specialize.rs:6:10 | LL | struct S; | ^^^^^^^^^^^^^^ required by this bound in `S` error: aborting due to previous error For more information about this error, try `rustc --explain E0119`. "} {"_id":"doc-en-rust-b8149d9b16886f23c0088098782373d9b4d177bce7724078f7ac476f963fa1e4","title":"","text":"use rustc_infer::traits::ObligationCause; use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind}; use rustc_middle::middle::stability::AllowUnstable; use rustc_middle::ty::fold::FnMutDelegate; use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, SubstsRef}; use rustc_middle::ty::DynKind; use rustc_middle::ty::GenericParamDefKind;"} {"_id":"doc-en-rust-799bf0d2be9cd918e0e6cedfb1a6b195fc908d0749f6c03ac215037197e12483","title":"","text":"let param_env = tcx.param_env(block.owner.to_def_id()); let cause = ObligationCause::misc(span, block.owner.def_id); let mut fulfillment_errors = Vec::new(); let mut applicable_candidates: Vec<_> = candidates .iter() .filter_map(|&(impl_, (assoc_item, def_scope))| { infcx.probe(|_| { let ocx = ObligationCtxt::new_in_snapshot(&infcx); let mut applicable_candidates: Vec<_> = infcx.probe(|_| { let universe = infcx.create_next_universe(); // Regions are not considered during selection. let self_ty = tcx.replace_escaping_bound_vars_uncached( self_ty, FnMutDelegate { regions: &mut |_| tcx.lifetimes.re_erased, types: &mut |bv| { tcx.mk_placeholder(ty::PlaceholderType { universe, name: bv.kind }) }, consts: &mut |bv, ty| { tcx.mk_const(ty::PlaceholderConst { universe, name: bv }, ty) }, }, ); let impl_ty = tcx.type_of(impl_); let impl_substs = infcx.fresh_item_substs(impl_); let impl_ty = impl_ty.subst(tcx, impl_substs); let impl_ty = ocx.normalize(&cause, param_env, impl_ty); candidates .iter() .filter_map(|&(impl_, (assoc_item, def_scope))| { infcx.probe(|_| { let ocx = ObligationCtxt::new_in_snapshot(&infcx); // Check that the Self-types can be related. // FIXME(fmease): Should we use `eq` here? ocx.sup(&ObligationCause::dummy(), param_env, impl_ty, self_ty).ok()?; let impl_ty = tcx.type_of(impl_); let impl_substs = infcx.fresh_item_substs(impl_); let impl_ty = impl_ty.subst(tcx, impl_substs); let impl_ty = ocx.normalize(&cause, param_env, impl_ty); // Check whether the impl imposes obligations we have to worry about. let impl_bounds = tcx.predicates_of(impl_); let impl_bounds = impl_bounds.instantiate(tcx, impl_substs); // Check that the Self-types can be related. // FIXME(fmease): Should we use `eq` here? ocx.sup(&ObligationCause::dummy(), param_env, impl_ty, self_ty).ok()?; let impl_bounds = ocx.normalize(&cause, param_env, impl_bounds); // Check whether the impl imposes obligations we have to worry about. let impl_bounds = tcx.predicates_of(impl_); let impl_bounds = impl_bounds.instantiate(tcx, impl_substs); let impl_obligations = traits::predicates_for_generics( |_, _| cause.clone(), param_env, impl_bounds, ); let impl_bounds = ocx.normalize(&cause, param_env, impl_bounds); ocx.register_obligations(impl_obligations); let impl_obligations = traits::predicates_for_generics( |_, _| cause.clone(), param_env, impl_bounds, ); let mut errors = ocx.select_where_possible(); if !errors.is_empty() { fulfillment_errors.append(&mut errors); return None; } ocx.register_obligations(impl_obligations); let mut errors = ocx.select_where_possible(); if !errors.is_empty() { fulfillment_errors.append(&mut errors); return None; } // FIXME(fmease): Unsolved vars can escape this InferCtxt snapshot. Some((assoc_item, def_scope, infcx.resolve_vars_if_possible(impl_substs))) // FIXME(fmease): Unsolved vars can escape this InferCtxt snapshot. Some((assoc_item, def_scope, infcx.resolve_vars_if_possible(impl_substs))) }) }) }) .collect(); .collect() }); if applicable_candidates.len() > 1 { return Err(self.complain_about_ambiguous_inherent_assoc_type("} {"_id":"doc-en-rust-bf99f5cb90df8197e4ada8da8f91f42eaccea0a3ca05706d5125af950e5969d5","title":"","text":" #![feature(inherent_associated_types, non_lifetime_binders, type_alias_impl_trait)] #![allow(incomplete_features)] struct Lexer(T); impl Lexer { type Cursor = (); } type X = impl for Fn() -> Lexer::Cursor; //~ ERROR associated type `Cursor` not found for `Lexer` in the current scope fn main() {} "} {"_id":"doc-en-rust-4e03581d61cee966567a39b338a121f6d7ac6d27ad54b16c9d6239cd4b1ddc61","title":"","text":" error[E0220]: associated type `Cursor` not found for `Lexer` in the current scope --> $DIR/issue-109299-1.rs:10:40 | LL | struct Lexer(T); | --------------- associated item `Cursor` not found for this struct ... LL | type X = impl for Fn() -> Lexer::Cursor; | ^^^^^^ associated item not found in `Lexer` | = note: the associated type was found for - `Lexer` error: aborting due to previous error For more information about this error, try `rustc --explain E0220`. "} {"_id":"doc-en-rust-8ab27e0ef6dce63877db2dd041d012f1496bf94bf79877447f51e921470c3d2c","title":"","text":" #![feature(inherent_associated_types)] #![allow(incomplete_features)] struct Lexer<'d>(&'d ()); impl Lexer<'d> { //~ ERROR use of undeclared lifetime name `'d` type Cursor = (); } fn test(_: Lexer::Cursor) {} fn main() {} "} {"_id":"doc-en-rust-c2d2fdd2db01468f50a2c7bfa08c6810c7938e2fa45f34da11efccf2bb70ba52","title":"","text":" error[E0261]: use of undeclared lifetime name `'d` --> $DIR/issue-109299.rs:6:12 | LL | impl Lexer<'d> { | - ^^ undeclared lifetime | | | help: consider introducing lifetime `'d` here: `<'d>` error: aborting due to previous error For more information about this error, try `rustc --explain E0261`. "} {"_id":"doc-en-rust-8f2c9fefcc72f91999758b38f5d0e6f8363ae1e69138a908258758b924ef4c8b","title":"","text":"// the ugliness comes from inlining across crates where // everything comes in as a fully resolved QPath (hard to // look at). match href(trait_.def_id(), cx) { Ok((ref url, _, ref path)) if !f.alternate() => { write!( f, \"{name}{args}\", url = url, shortty = ItemType::AssocType, name = assoc.name, path = join_with_double_colon(path), args = assoc.args.print(cx), )?; } _ => write!(f, \"{}{:#}\", assoc.name, assoc.args.print(cx))?, } Ok(()) if !f.alternate() && let Ok((url, _, path)) = href(trait_.def_id(), cx) { write!( f, \"{name}\", shortty = ItemType::AssocType, name = assoc.name, path = join_with_double_colon(&path), ) } else { write!(f, \"{}\", assoc.name) }?; // Carry `f.alternate()` into this display w/o branching manually. fmt::Display::fmt(&assoc.args.print(cx), f) } } }"} {"_id":"doc-en-rust-38779178563d905e02f579a93477e7dc980680d18af3fecf7a87cd58e4b699d1","title":"","text":" // Make sure that we escape the arguments of the GAT projection even if we fail to compute // the href of the corresponding trait (in this case it is private). // Further, test that we also linkify the GAT arguments. // @has 'issue_109488/type.A.html' // @has - '//pre[@class=\"rust item-decl\"]' '::P>' // @has - '//pre[@class=\"rust item-decl\"]//a[@class=\"enum\"]/@href' '{{channel}}/core/option/enum.Option.html' pub type A = ::P>; /*private*/ trait Tr { type P; } pub struct S; impl Tr for S { type P = (); } "} {"_id":"doc-en-rust-89b5f098eb2592d464b94aa5f659bc8d9b4bac9367b059c38eece88b770f212e","title":"","text":"use crate::builder::crate_description; use crate::builder::Cargo; use crate::builder::{Builder, Kind, RunConfig, ShouldRun, Step}; use crate::builder::{Builder, Kind, PathSet, RunConfig, ShouldRun, Step, TaskPath}; use crate::cache::{Interned, INTERNER}; use crate::config::{LlvmLibunwind, RustcLto, TargetSelection}; use crate::dist;"} {"_id":"doc-en-rust-82b97af7082de5f34f99ae3c2be4cc5efa3cb9f27f78d022c8fccfa6cf0d988d","title":"","text":"pub backend: Interned, } fn needs_codegen_config(run: &RunConfig<'_>) -> bool { let mut needs_codegen_cfg = false; for path_set in &run.paths { needs_codegen_cfg = match path_set { PathSet::Set(set) => set.iter().any(|p| is_codegen_cfg_needed(p, run)), PathSet::Suite(suite) => is_codegen_cfg_needed(&suite, run), } } needs_codegen_cfg } const CODEGEN_BACKEND_PREFIX: &str = \"rustc_codegen_\"; fn is_codegen_cfg_needed(path: &TaskPath, run: &RunConfig<'_>) -> bool { if path.path.to_str().unwrap().contains(&CODEGEN_BACKEND_PREFIX) { let mut needs_codegen_backend_config = true; for &backend in &run.builder.config.rust_codegen_backends { if path .path .to_str() .unwrap() .ends_with(&(CODEGEN_BACKEND_PREFIX.to_owned() + &backend)) { needs_codegen_backend_config = false; } } if needs_codegen_backend_config { run.builder.info( \"Warning: no codegen-backends config matched the requested path to build a codegen backend. Help: add backend to codegen-backends in config.toml.\", ); return true; } } return false; } impl Step for CodegenBackend { type Output = (); const ONLY_HOSTS: bool = true;"} {"_id":"doc-en-rust-350c952572a44492d69d0c2d2314fbd3ae4526dd607ecb58829dd48adba05d03","title":"","text":"} fn make_run(run: RunConfig<'_>) { if needs_codegen_config(&run) { return; } for &backend in &run.builder.config.rust_codegen_backends { if backend == \"llvm\" { continue; // Already built as part of rustc"} {"_id":"doc-en-rust-81fb057c353b530318402da780dbf61e2e7e4dc6c054d5966d6d4e5a18479b74","title":"","text":"let tcx = self.tcx; let def_id = instance.def_id(); let containing_scope = get_containing_scope(self, instance); let (containing_scope, is_method) = get_containing_scope(self, instance); let span = tcx.def_span(def_id); let loc = self.lookup_debug_loc(span.lo()); let file_metadata = file_metadata(self, &loc.file);"} {"_id":"doc-en-rust-273c7e6bbc3125a4901e982b47f083a82e0bb3bf34ad31bbe719cd431d914e8b","title":"","text":"} } unsafe { return llvm::LLVMRustDIBuilderCreateFunction( // When we're adding a method to a type DIE, we only want a DW_AT_declaration there, because // LLVM LTO can't unify type definitions when a child DIE is a full subprogram definition. // When we use this `decl` below, the subprogram definition gets created at the CU level // with a DW_AT_specification pointing back to the type's declaration. let decl = is_method.then(|| unsafe { llvm::LLVMRustDIBuilderCreateMethod( DIB(self), containing_scope, name.as_ptr().cast(), name.len(), linkage_name.as_ptr().cast(), linkage_name.len(), file_metadata, loc.line, function_type_metadata, flags, spflags & !DISPFlags::SPFlagDefinition, template_parameters, ) }); return unsafe { llvm::LLVMRustDIBuilderCreateFunction( DIB(self), containing_scope, name.as_ptr().cast(),"} {"_id":"doc-en-rust-004b0f27c043622f4cf292a91cb7d1d01dc2407189414de16781512a28d9c3d7","title":"","text":"spflags, maybe_definition_llfn, template_parameters, None, ); } decl, ) }; fn get_function_signature<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>,"} {"_id":"doc-en-rust-577347ff97a897de52aeafa2b5ea174a38d8065492229dedd255a8acc7029c42","title":"","text":"names } /// Returns a scope, plus `true` if that's a type scope for \"class\" methods, /// otherwise `false` for plain namespace scopes. fn get_containing_scope<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>, ) -> &'ll DIScope { ) -> (&'ll DIScope, bool) { // First, let's see if this is a method within an inherent impl. Because // if yes, we want to make the result subroutine DIE a child of the // subroutine's self-type. let self_type = cx.tcx.impl_of_method(instance.def_id()).and_then(|impl_def_id| { if let Some(impl_def_id) = cx.tcx.impl_of_method(instance.def_id()) { // If the method does *not* belong to a trait, proceed if cx.tcx.trait_id_of_impl(impl_def_id).is_none() { let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions("} {"_id":"doc-en-rust-812257b9bdeb685c50874e6f128920f13b777316032b980e574632fdda214a1c","title":"","text":"// Only \"class\" methods are generally understood by LLVM, // so avoid methods on other types (e.g., `<*mut T>::null`). match impl_self_ty.kind() { ty::Adt(def, ..) if !def.is_box() => { // Again, only create type information if full debuginfo is enabled if cx.sess().opts.debuginfo == DebugInfo::Full && !impl_self_ty.has_param() { Some(type_di_node(cx, impl_self_ty)) } else { Some(namespace::item_namespace(cx, def.did())) } if let ty::Adt(def, ..) = impl_self_ty.kind() && !def.is_box() { // Again, only create type information if full debuginfo is enabled if cx.sess().opts.debuginfo == DebugInfo::Full && !impl_self_ty.has_param() { return (type_di_node(cx, impl_self_ty), true); } else { return (namespace::item_namespace(cx, def.did()), false); } _ => None, } } else { // For trait method impls we still use the \"parallel namespace\" // strategy None } }); } self_type.unwrap_or_else(|| { namespace::item_namespace( cx, DefId { krate: instance.def_id().krate, index: cx .tcx .def_key(instance.def_id()) .parent .expect(\"get_containing_scope: missing parent?\"), }, ) }) let scope = namespace::item_namespace( cx, DefId { krate: instance.def_id().krate, index: cx .tcx .def_key(instance.def_id()) .parent .expect(\"get_containing_scope: missing parent?\"), }, ); (scope, false) } }"} {"_id":"doc-en-rust-0be7240ef85bc21347d918bc5d890d696866e23a0db884eb854b166a26b2507e","title":"","text":"Decl: Option<&'a DIDescriptor>, ) -> &'a DISubprogram; pub fn LLVMRustDIBuilderCreateMethod<'a>( Builder: &DIBuilder<'a>, Scope: &'a DIDescriptor, Name: *const c_char, NameLen: size_t, LinkageName: *const c_char, LinkageNameLen: size_t, File: &'a DIFile, LineNo: c_uint, Ty: &'a DIType, Flags: DIFlags, SPFlags: DISPFlags, TParam: &'a DIArray, ) -> &'a DISubprogram; pub fn LLVMRustDIBuilderCreateBasicType<'a>( Builder: &DIBuilder<'a>, Name: *const c_char,"} {"_id":"doc-en-rust-4e8f316ef48671535b797caecef9dca4f9964f383067bca8b9067100a3c86f70","title":"","text":"return wrap(Sub); } extern \"C\" LLVMMetadataRef LLVMRustDIBuilderCreateMethod( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, const char *LinkageName, size_t LinkageNameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, LLVMRustDIFlags Flags, LLVMRustDISPFlags SPFlags, LLVMMetadataRef TParam) { DITemplateParameterArray TParams = DITemplateParameterArray(unwrap(TParam)); DISubprogram::DISPFlags llvmSPFlags = fromRust(SPFlags); DINode::DIFlags llvmFlags = fromRust(Flags); DISubprogram *Sub = Builder->createMethod( unwrapDI(Scope), StringRef(Name, NameLen), StringRef(LinkageName, LinkageNameLen), unwrapDI(File), LineNo, unwrapDI(Ty), 0, 0, nullptr, // VTable params aren't used llvmFlags, llvmSPFlags, TParams); return wrap(Sub); } extern \"C\" LLVMMetadataRef LLVMRustDIBuilderCreateBasicType( LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen, uint64_t SizeInBits, unsigned Encoding) {"} {"_id":"doc-en-rust-04b039140e9d55e2882bf916372c154de5846db9f452826e34f921a8d9a56423","title":"","text":" # ignore-cross-compile include ../tools.mk # With the upgrade to LLVM 16, this was getting: # # error: Cannot represent a difference across sections # # The error stemmed from DI function definitions under type scopes, fixed by # only declaring in type scope and defining the subprogram elsewhere. all: $(RUSTC) lib.rs --test -C lto=fat -C debuginfo=2 -C incremental=$(TMPDIR)/inc-fat "} {"_id":"doc-en-rust-3832c1dda031dac89de40e50c7c43769c33998421d496b0b2e5f0bd53e2bae8d","title":"","text":" extern crate alloc; #[cfg(test)] mod tests { #[test] fn something_alloc() { assert_eq!(Vec::::new(), Vec::::new()); } } "} {"_id":"doc-en-rust-b89a07102f94aa3d4af991b5a69478b7b581cbfd147de13de43e78ed9727f5a2","title":"","text":"sugar for dynamic allocations via `malloc` and `free`: ```rust,ignore (libc-is-finicky) #![feature(lang_items, box_syntax, start, libc, core_intrinsics, rustc_private)] #![feature(lang_items, start, libc, core_intrinsics, rustc_private, rustc_attrs)] #![no_std] use core::intrinsics; use core::panic::PanicInfo; use core::ptr::NonNull; extern crate libc; struct Unique(*mut T); struct Unique(NonNull); #[lang = \"owned_box\"] pub struct Box(Unique); impl Box { pub fn new(x: T) -> Self { #[rustc_box] Box::new(x) } } #[lang = \"exchange_malloc\"] unsafe fn allocate(size: usize, _align: usize) -> *mut u8 { let p = libc::malloc(size as libc::size_t) as *mut u8;"} {"_id":"doc-en-rust-c0802fee18e4ec5c97eb2f7bcc48c43493ff19254bf47d53167e5159600adebc","title":"","text":"#[start] fn main(_argc: isize, _argv: *const *const u8) -> isize { let _x = box 1; let _x = Box::new(1); 0 } #[lang = \"eh_personality\"] extern fn rust_eh_personality() {} #[lang = \"panic_impl\"] extern fn rust_begin_panic(info: &PanicInfo) -> ! { unsafe { intrinsics::abort() } } #[lang = \"panic_impl\"] extern fn rust_begin_panic(_info: &PanicInfo) -> ! { intrinsics::abort() } #[no_mangle] pub extern fn rust_eh_register_frames () {} #[no_mangle] pub extern fn rust_eh_unregister_frames () {} ```"} {"_id":"doc-en-rust-9cec961e71dcac175156eaa7373fd8d9a9a51578e163d8a4839b9f5dd0f60657","title":"","text":"that warns about any item named `lintme`. ```rust,ignore (requires-stage-2) #![feature(box_syntax, rustc_private)] #![feature(rustc_private)] extern crate rustc_ast;"} {"_id":"doc-en-rust-f702e0276be6d1efb43ca1f613f78a983c5afdcd119418cb2e4607f81bfa3e3c","title":"","text":"#[no_mangle] fn __rustc_plugin_registrar(reg: &mut Registry) { reg.lint_store.register_lints(&[&TEST_LINT]); reg.lint_store.register_early_pass(|| box Pass); reg.lint_store.register_early_pass(|| Box::new(Pass)); } ```"} {"_id":"doc-en-rust-f27e5dbc27a6b9f371caf94c9759cb9f23d296e09f6e9ab8d93e841b76903bef","title":"","text":"let mut head = self.head.index.load(Ordering::Acquire); let mut block = self.head.block.load(Ordering::Acquire); // If we're going to be dropping messages we need to synchronize with initialization if head >> SHIFT != tail >> SHIFT { // The block can be null here only if a sender is in the process of initializing the // channel while another sender managed to send a message by inserting it into the // semi-initialized channel and advanced the tail. // In that case, just wait until it gets initialized. while block.is_null() { backoff.spin_heavy(); block = self.head.block.load(Ordering::Acquire); } } unsafe { // Drop all messages between head and tail and deallocate the heap-allocated blocks. while head >> SHIFT != tail >> SHIFT {"} {"_id":"doc-en-rust-1f98cf4d8a778599bd4f25a0783ff6972450937673cb35ec757d0d95556b6292","title":"","text":"// Forward test filters. cargo.arg(\"--\").args(builder.config.cmd.test_args()); add_flags_and_try_run_tests(builder, &mut cargo.into()); // This can NOT be `add_flags_and_try_run_tests` since the Miri test runner // does not understand those flags! let mut cargo = Command::from(cargo); builder.run(&mut cargo); // # Run `cargo miri test`. // This is just a smoke test (Miri's own CI invokes this in a bunch of different ways and ensures"} {"_id":"doc-en-rust-0a879985da1f6513a75e1b27672012468ee0dda4c115afc5cd9778180230fa15","title":"","text":"}; use crate::traits::{Obligation, PredicateObligations}; use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation}; use rustc_middle::ty::relate::{ relate_args_invariantly, relate_args_with_variances, Relate, RelateResult, TypeRelation, }; use rustc_middle::ty::TyVar; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::Span;"} {"_id":"doc-en-rust-e655a953cec881ce0981db3e177e6ceff64963f1658f281fca523fac8974b0d8","title":"","text":"self.fields.infcx.tcx } fn relate_item_args( &mut self, item_def_id: rustc_hir::def_id::DefId, a_arg: ty::GenericArgsRef<'tcx>, b_arg: ty::GenericArgsRef<'tcx>, ) -> RelateResult<'tcx, ty::GenericArgsRef<'tcx>> { if self.ambient_variance == ty::Variance::Invariant { // Avoid fetching the variance if we are in an invariant // context; no need, and it can induce dependency cycles // (e.g., #41849). relate_args_invariantly(self, a_arg, b_arg) } else { let tcx = self.tcx(); let opt_variances = tcx.variances_of(item_def_id); relate_args_with_variances(self, item_def_id, opt_variances, a_arg, b_arg, false) } } fn relate_with_variance>( &mut self, variance: ty::Variance,"} {"_id":"doc-en-rust-1e1c8ffde5f297e643b3b2820bbf4758d443e6cbeda978b216926b73a488e148","title":"","text":" //@ check-pass #![feature(inherent_associated_types)] //~^ WARN the feature `inherent_associated_types` is incomplete struct D { a: T } impl D { type Item = T; fn next() -> Self::Item { Self::Item::default() } } fn main() { } "} {"_id":"doc-en-rust-c986e4992cf4d6bf7f35ab3a4d7b97a25a91b6755b836f17e013c597d341b22f","title":"","text":" warning: the feature `inherent_associated_types` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/variance-computation-requires-equality.rs:3:12 | LL | #![feature(inherent_associated_types)] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #8995 for more information = note: `#[warn(incomplete_features)]` on by default warning: 1 warning emitted "} {"_id":"doc-en-rust-c60ab1f34e6b4b0c553db2321aad7b05db2524e8eb671ad4891803f53ca7b979","title":"","text":"use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::DefineOpaqueTypes; use rustc_infer::infer::InferOk; use rustc_infer::traits::query::NoSolution; use rustc_infer::traits::ObligationCause; use rustc_middle::middle::stability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};"} {"_id":"doc-en-rust-ce9a9fc0d16ef942cd5682197c2e1bc500a47d79769b8c00e8460514ddcfb1ba","title":"","text":"use rustc_target::abi::FieldIdx; use rustc_target::spec::abi::Abi::RustIntrinsic; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt; use rustc_trait_selection::traits::ObligationCtxt; use rustc_trait_selection::traits::{self, ObligationCauseCode}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> {"} {"_id":"doc-en-rust-69517d268a83c668cdef01c25e13a3085a4970963b5b7d15577f5e54ef45e91f","title":"","text":"element_ty } None => { // Attempt to *shallowly* search for an impl which matches, // but has nested obligations which are unsatisfied. for (base_t, _) in self.autoderef(base.span, base_t).silence_errors() { if let Some((_, index_ty, element_ty)) = self.find_and_report_unsatisfied_index_impl(expr.hir_id, base, base_t) { self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No); return element_ty; } } let mut err = type_error_struct!( self.tcx.sess, expr.span,"} {"_id":"doc-en-rust-10cd505bbd34e15b46176070fb7822e9160507ad16d634e2aac3507bd304e93c","title":"","text":"} } /// Try to match an implementation of `Index` against a self type, and report /// the unsatisfied predicates that result from confirming this impl. /// /// Given an index expression, sometimes the `Self` type shallowly but does not /// deeply satisfy an impl predicate. Instead of simply saying that the type /// does not support being indexed, we want to point out exactly what nested /// predicates cause this to be, so that the user can add them to fix their code. fn find_and_report_unsatisfied_index_impl( &self, index_expr_hir_id: HirId, base_expr: &hir::Expr<'_>, base_ty: Ty<'tcx>, ) -> Option<(ErrorGuaranteed, Ty<'tcx>, Ty<'tcx>)> { let index_trait_def_id = self.tcx.lang_items().index_trait()?; let index_trait_output_def_id = self.tcx.get_diagnostic_item(sym::IndexOutput)?; let mut relevant_impls = vec![]; self.tcx.for_each_relevant_impl(index_trait_def_id, base_ty, |impl_def_id| { relevant_impls.push(impl_def_id); }); let [impl_def_id] = relevant_impls[..] else { // Only report unsatisfied impl predicates if there's one impl return None; }; self.commit_if_ok(|_| { let ocx = ObligationCtxt::new_in_snapshot(self); let impl_substs = self.fresh_substs_for_item(base_expr.span, impl_def_id); let impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id).unwrap().subst(self.tcx, impl_substs); let cause = self.misc(base_expr.span); // Match the impl self type against the base ty. If this fails, // we just skip this impl, since it's not particularly useful. let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref); ocx.eq(&cause, self.param_env, impl_trait_ref.self_ty(), base_ty)?; // Register the impl's predicates. One of these predicates // must be unsatisfied, or else we wouldn't have gotten here // in the first place. ocx.register_obligations(traits::predicates_for_generics( |idx, span| { traits::ObligationCause::new( base_expr.span, self.body_id, if span.is_dummy() { traits::ExprItemObligation(impl_def_id, index_expr_hir_id, idx) } else { traits::ExprBindingObligation(impl_def_id, span, index_expr_hir_id, idx) }, ) }, self.param_env, self.tcx.predicates_of(impl_def_id).instantiate(self.tcx, impl_substs), )); // Normalize the output type, which we can use later on as the // return type of the index expression... let element_ty = ocx.normalize( &cause, self.param_env, self.tcx.mk_projection(index_trait_output_def_id, impl_trait_ref.substs), ); let errors = ocx.select_where_possible(); // There should be at least one error reported. If not, we // will still delay a span bug in `report_fulfillment_errors`. Ok::<_, NoSolution>(( self.err_ctxt().report_fulfillment_errors(&errors), impl_trait_ref.substs.type_at(1), element_ty, )) }) .ok() } fn point_at_index_if_possible( &self, errors: &mut Vec>,"} {"_id":"doc-en-rust-355a93491c2661032f692a77a3f9b10a172e2e27487c2c3212a7230a1344b5db","title":"","text":"HashSet, Hasher, Implied, IndexOutput, Input, Into, IntoDiagnostic,"} {"_id":"doc-en-rust-b9a198019267f2c210875a18466562c9b833c34c817790fc4ac0b652e847426f","title":"","text":"pub trait Index { /// The returned type after indexing. #[stable(feature = \"rust1\", since = \"1.0.0\")] #[rustc_diagnostic_item = \"IndexOutput\"] type Output: ?Sized; /// Performs the indexing (`container[index]`) operation."} {"_id":"doc-en-rust-fdfa68d49a37819648e4a07abd73c21a997d573c0b474a16c86fa158a6fd4508","title":"","text":" use std::hash::Hash; use std::marker::PhantomData; use std::ops::Index; struct HashMap(PhantomData<(K, V)>); impl Index<&K> for HashMap where K: Hash, V: Copy, { type Output = V; fn index(&self, k: &K) -> &V { todo!() } } fn index<'a, K, V>(map: &'a HashMap, k: K) -> &'a V { map[k] //~^ ERROR the trait bound `K: Hash` is not satisfied //~| ERROR the trait bound `V: Copy` is not satisfied //~| ERROR mismatched types //~| ERROR mismatched types } fn main() {} "} {"_id":"doc-en-rust-9fbe00d2fc1616d83ac6edab4d11b39650beeeac77935ce2210142cc8777716f","title":"","text":" error[E0277]: the trait bound `K: Hash` is not satisfied --> $DIR/bad-index-due-to-nested.rs:20:5 | LL | map[k] | ^^^ the trait `Hash` is not implemented for `K` | note: required by a bound in ` as Index<&K>>` --> $DIR/bad-index-due-to-nested.rs:9:8 | LL | K: Hash, | ^^^^ required by this bound in ` as Index<&K>>` help: consider restricting type parameter `K` | LL | fn index<'a, K: std::hash::Hash, V>(map: &'a HashMap, k: K) -> &'a V { | +++++++++++++++++ error[E0277]: the trait bound `V: Copy` is not satisfied --> $DIR/bad-index-due-to-nested.rs:20:5 | LL | map[k] | ^^^ the trait `Copy` is not implemented for `V` | note: required by a bound in ` as Index<&K>>` --> $DIR/bad-index-due-to-nested.rs:10:8 | LL | V: Copy, | ^^^^ required by this bound in ` as Index<&K>>` help: consider restricting type parameter `V` | LL | fn index<'a, K, V: std::marker::Copy>(map: &'a HashMap, k: K) -> &'a V { | +++++++++++++++++++ error[E0308]: mismatched types --> $DIR/bad-index-due-to-nested.rs:20:9 | LL | fn index<'a, K, V>(map: &'a HashMap, k: K) -> &'a V { | - this type parameter LL | map[k] | ^ | | | expected `&K`, found type parameter `K` | help: consider borrowing here: `&k` | = note: expected reference `&K` found type parameter `K` error[E0308]: mismatched types --> $DIR/bad-index-due-to-nested.rs:20:5 | LL | fn index<'a, K, V>(map: &'a HashMap, k: K) -> &'a V { | - this type parameter ----- expected `&'a V` because of return type LL | map[k] | ^^^^^^ | | | expected `&V`, found type parameter `V` | help: consider borrowing here: `&map[k]` | = note: expected reference `&'a V` found type parameter `V` error: aborting due to 4 previous errors Some errors have detailed explanations: E0277, E0308. For more information about an error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-ffb6bb7cfb1acb8924c19f1e29065a0d8efdd385c1f505d6cbbd2cceaf988533","title":"","text":"Some(blk_id), ); if !fcx.tcx.features().unsized_locals { unsized_return = self.is_return_ty_unsized(fcx, blk_id); unsized_return = self.is_return_ty_definitely_unsized(fcx); } if let Some(expression) = expression && let hir::ExprKind::Loop(loop_blk, ..) = expression.kind {"} {"_id":"doc-en-rust-7c47ab8835c309972ef14a5d31a20f371edd96d38f47bff14fa324ba8bb2fa0c","title":"","text":"None, ); if !fcx.tcx.features().unsized_locals { let id = fcx.tcx.hir().parent_id(id); unsized_return = self.is_return_ty_unsized(fcx, id); unsized_return = self.is_return_ty_definitely_unsized(fcx); } } _ => {"} {"_id":"doc-en-rust-cd277a832bca41477ef11abac734e614fd335f48dff7b5a2af7cdbb1653a631e","title":"","text":"err.help(\"you could instead create a new `enum` with a variant for each returned type\"); } fn is_return_ty_unsized<'a>(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool { if let Some((_, fn_decl, _)) = fcx.get_fn_decl(blk_id) && let hir::FnRetTy::Return(ty) = fn_decl.output && let ty = fcx.astconv().ast_ty_to_ty( ty) && let ty::Dynamic(..) = ty.kind() { return true; /// Checks whether the return type is unsized via an obligation, which makes /// sure we consider `dyn Trait: Sized` where clauses, which are trivially /// false but technically valid for typeck. fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool { if let Some(sig) = fcx.body_fn_sig() { !fcx.predicate_may_hold(&Obligation::new( fcx.tcx, ObligationCause::dummy(), fcx.param_env, ty::TraitRef::new( fcx.tcx, fcx.tcx.require_lang_item(hir::LangItem::Sized, None), [sig.output()], ), )) } else { false } false } pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {"} {"_id":"doc-en-rust-662ceaa36cb3b22d706f3e5402df6f12fa9d97d5099d87cb82691e59e4db392b","title":"","text":" trait Trait {} fn foo() -> dyn Trait where dyn Trait: Sized, // pesky sized predicate { 42 //~^ ERROR mismatched types } fn main() {} "} {"_id":"doc-en-rust-0ef5cb0b037be6c182b82a908694aeb66ff91e0c15aa5785b404787b87504d27","title":"","text":" error[E0308]: mismatched types --> $DIR/return-dyn-type-mismatch-2.rs:7:5 | LL | fn foo() -> dyn Trait | ------------ expected `(dyn Trait + 'static)` because of return type ... LL | 42 | ^^ expected `dyn Trait`, found integer | = note: expected trait object `(dyn Trait + 'static)` found type `{integer}` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-c2bcde32b5073108ff863662204af03fddde638278b657dcbf6b6af105a24cb6","title":"","text":" pub trait TestTrait { type MyType; fn func() -> Option where Self: Sized; } impl dyn TestTrait where Self: Sized, // pesky sized predicate { fn other_func() -> dyn TestTrait { match Self::func() { None => None, //~^ ERROR mismatched types } } } fn main() {} "} {"_id":"doc-en-rust-715c3bcd90ab28aed5c67fb6cf70566a338d2bd080615117798a6325aff1624e","title":"","text":" error[E0308]: mismatched types --> $DIR/return-dyn-type-mismatch.rs:15:21 | LL | fn other_func() -> dyn TestTrait { | ------------------------- expected `(dyn TestTrait + 'static)` because of return type LL | match Self::func() { LL | None => None, | ^^^^ expected `dyn TestTrait`, found `Option<_>` | = note: expected trait object `(dyn TestTrait + 'static)` found enum `Option<_>` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-e059731fcb212445e7b1affaf5f889a806c148aadabe6fafd7375378950b28ea","title":"","text":"//! contains further primitive shared memory types, including [`atomic`] and //! [`mpsc`], which contains the channel types for message passing. //! //! # Use before and after `main()` //! //! Many parts of the standard library are expected to work before and after `main()`; //! but this is not guaranteed or ensured by tests. It is recommended that you write your own tests //! and run them on each platform you wish to support. //! This means that use of `std` before/after main, especially of features that interact with the //! OS or global state, is exempted from stability and portability guarantees and instead only //! provided on a best-effort basis. Nevertheless bug reports are appreciated. //! //! On the other hand `core` and `alloc` are most likely to work in such environments with //! the caveat that any hookable behavior such as panics, oom handling or allocators will also //! depend on the compatibility of the hooks. //! //! Some features may also behave differently outside main, e.g. stdio could become unbuffered, //! some panics might turn into aborts, backtraces might not get symbolicated or similar. //! //! Non-exhaustive list of known limitations: //! //! - after-main use of thread-locals, which also affects additional features: //! - [`thread::current()`] //! - [`thread::scope()`] //! - [`sync::mpsc`] //! - before-main stdio file descriptors are not guaranteed to be open on unix platforms //! //! //! [I/O]: io //! [`MIN`]: i32::MIN //! [`MAX`]: i32::MAX"} {"_id":"doc-en-rust-366aec0b367c74bc1466d97196e8ad65fb71bfe07fecb94b8fa0d700979176fc","title":"","text":"//! [rust-discord]: https://discord.gg/rust-lang //! [array]: prim@array //! [slice]: prim@slice // To run std tests without x.py without ending up with two copies of std, Miri needs to be // able to \"empty\" this crate. See . // rustc itself never sets the feature, so this line has no effect there."} {"_id":"doc-en-rust-28fbbb4484d9ec82b61cca5dea7fff2b44d7260b62170ed4c77cf7267e3e64b5","title":"","text":"This feature is unstable, so you can enable it by calling Rustdoc with the unstable `rustdoc-scrape-examples` flag: ```bash cargo doc -Zunstable-options -Zrustdoc-scrape-examples=examples cargo doc -Zunstable-options -Zrustdoc-scrape-examples ``` To enable this feature on [docs.rs](https://docs.rs), add this to your Cargo.toml: ```toml [package.metadata.docs.rs] cargo-args = [\"-Zunstable-options\", \"-Zrustdoc-scrape-examples=examples\"] cargo-args = [\"-Zunstable-options\", \"-Zrustdoc-scrape-examples\"] ```"} {"_id":"doc-en-rust-d83a3681ee08891b29c3fcda0334d3ff5aba0da997d5a3f2233beef54b1a9a60","title":"","text":"use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_errors::{Applicability, DiagnosticArgValue, DiagnosticId, IntoDiagnosticArg}; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, PartialRes, PerNS}; use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS}; use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_hir::{BindingAnnotation, PrimTy, TraitCandidate}; use rustc_middle::middle::resolve_bound_vars::Set1;"} {"_id":"doc-en-rust-e2ff204a16cef681c8900790a5ed606f8299ebbcfeb480cad7b2f51d1fea0bf2","title":"","text":"} } fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> bool { fn resolve_and_cache_rustdoc_path(&mut self, path_str: &str, ns: Namespace) -> Option { // FIXME: This caching may be incorrect in case of multiple `macro_rules` // items with the same name in the same module. // Also hygiene is not considered. let mut doc_link_resolutions = std::mem::take(&mut self.r.doc_link_resolutions); let res = doc_link_resolutions let res = *doc_link_resolutions .entry(self.parent_scope.module.nearest_parent_mod().expect_local()) .or_default() .entry((Symbol::intern(path_str), ns))"} {"_id":"doc-en-rust-117747ebaa69e450246318b47d635c0401430b1dbfc06e3473e671781a7bbffa","title":"","text":"return None; } res }) .is_some(); }); self.r.doc_link_resolutions = doc_link_resolutions; res }"} {"_id":"doc-en-rust-48a42f58c7129397c978227ba57ff69fadeeb4dcaae59e7c2b742e2177becc1c","title":"","text":"let mut any_resolved = false; let mut need_assoc = false; for ns in [TypeNS, ValueNS, MacroNS] { if self.resolve_and_cache_rustdoc_path(&path_str, ns) { any_resolved = true; if let Some(res) = self.resolve_and_cache_rustdoc_path(&path_str, ns) { // Rustdoc ignores tool attribute resolutions and attempts // to resolve their prefixes for diagnostics. any_resolved = !matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Tool)); } else if ns != MacroNS { need_assoc = true; }"} {"_id":"doc-en-rust-f94a3648bfb73414e07962ce11a7ae0c7513269ea435a2b3e1c75321960676cc","title":"","text":"Def(kind, id) => Ok(Res::Def(kind, id)), PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))), // e.g. `#[derive]` NonMacroAttr(..) | Err => Result::Err(()), ToolMod | NonMacroAttr(..) | Err => Result::Err(()), other => bug!(\"unrecognized res {:?}\", other), } }"} {"_id":"doc-en-rust-b9700d0b80bab3f0b13206bfa7cbd54bb77518ea765458bd7e0c8117f4cc8fc9","title":"","text":" // Regression test for . // This test ensures that it doesn't crash. #![deny(warnings)] /// #[rustfmt::skip] //~^ ERROR unresolved link to `rustfmt::skip` /// #[clippy::whatever] //~^ ERROR unresolved link to `clippy::whatever` pub fn foo() {} "} {"_id":"doc-en-rust-4279dc8065c2845d320e03414f89e10b6de86fe8bf86d3c8205c2d1b9338ed01","title":"","text":" error: unresolved link to `rustfmt::skip` --> $DIR/issue-111189-resolution-ice.rs:6:7 | LL | /// #[rustfmt::skip] | ^^^^^^^^^^^^^ no item named `rustfmt` in scope | note: the lint level is defined here --> $DIR/issue-111189-resolution-ice.rs:4:9 | LL | #![deny(warnings)] | ^^^^^^^^ = note: `#[deny(rustdoc::broken_intra_doc_links)]` implied by `#[deny(warnings)]` error: unresolved link to `clippy::whatever` --> $DIR/issue-111189-resolution-ice.rs:8:7 | LL | /// #[clippy::whatever] | ^^^^^^^^^^^^^^^^ no item named `clippy` in scope error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-970fd1cc8c33d4c90054806998f776e87033df96b0cb21cd600bd82f75683380","title":"","text":") -> Result, &'static str> { let callee_attrs = self.tcx.codegen_fn_attrs(callsite.callee.def_id()); self.check_codegen_attributes(callsite, callee_attrs)?; let terminator = caller_body[callsite.block].terminator.as_ref().unwrap(); let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() }; let destination_ty = destination.ty(&caller_body.local_decls, self.tcx).ty; for arg in args { if !arg.ty(&caller_body.local_decls, self.tcx).is_sized(self.tcx, self.param_env) { // We do not allow inlining functions with unsized params. Inlining these functions // could create unsized locals, which are unsound and being phased out. return Err(\"Call has unsized argument\"); } } self.check_mir_is_available(caller_body, &callsite.callee)?; let callee_body = try_instance_mir(self.tcx, callsite.callee.def)?; self.check_mir_body(callsite, callee_body, callee_attrs)?;"} {"_id":"doc-en-rust-c36d21d666231ba574ef740974355c6f136da39d03d3eff6860a4f140cb718f9","title":"","text":"// Check call signature compatibility. // Normally, this shouldn't be required, but trait normalization failure can create a // validation ICE. let terminator = caller_body[callsite.block].terminator.as_ref().unwrap(); let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() }; let destination_ty = destination.ty(&caller_body.local_decls, self.tcx).ty; let output_type = callee_body.return_ty(); if !util::is_subtype(self.tcx, self.param_env, output_type, destination_ty) { trace!(?output_type, ?destination_ty);"} {"_id":"doc-en-rust-38c104a35a93aa55bd87f282d5da1ce3109f458debafcfe71f68fb2c4fc7111d","title":"","text":" - // MIR for `caller` before Inline + // MIR for `caller` after Inline fn caller(_1: Box<[i32]>) -> () { debug x => _1; // in scope 0 at $DIR/unsized_argument.rs:+0:11: +0:12 let mut _0: (); // return place in scope 0 at $DIR/unsized_argument.rs:+0:26: +0:26 let _2: (); // in scope 0 at $DIR/unsized_argument.rs:+1:5: +1:15 let mut _3: std::boxed::Box<[i32]>; // in scope 0 at $DIR/unsized_argument.rs:+1:13: +1:14 let mut _4: (); // in scope 0 at $DIR/unsized_argument.rs:+1:14: +1:15 let mut _5: (); // in scope 0 at $DIR/unsized_argument.rs:+1:14: +1:15 let mut _6: (); // in scope 0 at $DIR/unsized_argument.rs:+1:14: +1:15 let mut _7: *const [i32]; // in scope 0 at $DIR/unsized_argument.rs:+1:13: +1:14 bb0: { StorageLive(_2); // scope 0 at $DIR/unsized_argument.rs:+1:5: +1:15 StorageLive(_3); // scope 0 at $DIR/unsized_argument.rs:+1:13: +1:14 _3 = move _1; // scope 0 at $DIR/unsized_argument.rs:+1:13: +1:14 _7 = (((_3.0: std::ptr::Unique<[i32]>).0: std::ptr::NonNull<[i32]>).0: *const [i32]); // scope 0 at $DIR/unsized_argument.rs:+1:5: +1:15 _2 = callee(move (*_7)) -> [return: bb3, unwind: bb4]; // scope 0 at $DIR/unsized_argument.rs:+1:5: +1:15 // mir::Constant // + span: $DIR/unsized_argument.rs:9:5: 9:11 // + literal: Const { ty: fn([i32]) {callee}, val: Value() } } bb1: { StorageDead(_3); // scope 0 at $DIR/unsized_argument.rs:+1:14: +1:15 StorageDead(_2); // scope 0 at $DIR/unsized_argument.rs:+1:15: +1:16 _0 = const (); // scope 0 at $DIR/unsized_argument.rs:+0:26: +2:2 return; // scope 0 at $DIR/unsized_argument.rs:+2:2: +2:2 } bb2 (cleanup): { resume; // scope 0 at $DIR/unsized_argument.rs:+0:1: +2:2 } bb3: { _4 = alloc::alloc::box_free::<[i32], std::alloc::Global>(move (_3.0: std::ptr::Unique<[i32]>), move (_3.1: std::alloc::Global)) -> bb1; // scope 0 at $DIR/unsized_argument.rs:+1:14: +1:15 // mir::Constant // + span: $DIR/unsized_argument.rs:9:14: 9:15 // + literal: Const { ty: unsafe fn(Unique<[i32]>, std::alloc::Global) {alloc::alloc::box_free::<[i32], std::alloc::Global>}, val: Value() } } bb4 (cleanup): { _6 = alloc::alloc::box_free::<[i32], std::alloc::Global>(move (_3.0: std::ptr::Unique<[i32]>), move (_3.1: std::alloc::Global)) -> [return: bb2, unwind terminate]; // scope 0 at $DIR/unsized_argument.rs:+1:14: +1:15 // mir::Constant // + span: $DIR/unsized_argument.rs:9:14: 9:15 // + literal: Const { ty: unsafe fn(Unique<[i32]>, std::alloc::Global) {alloc::alloc::box_free::<[i32], std::alloc::Global>}, val: Value() } } } "} {"_id":"doc-en-rust-f5670384519111571a174627ed7a9b93d09232caf73a74c317418d17943db88f","title":"","text":" // needs-unwind #![feature(unsized_fn_params)] #[inline(always)] fn callee(y: [i32]) {} // EMIT_MIR unsized_argument.caller.Inline.diff fn caller(x: Box<[i32]>) { callee(*x); } fn main() { let b = Box::new([1]); caller(b); } "} {"_id":"doc-en-rust-f94d584074d44f7a3c30d4a54c2bb93e2124dad249c37c195c9c4558264879ca","title":"","text":"} } /// Whether `check_binop` allows overloaded operators to be invoked. /// Whether `check_binop` is part of an assignment or not. /// Used to know wether we allow user overloads and to print /// better messages on error. #[deriving(Eq)] enum AllowOverloadedOperatorsFlag { AllowOverloadedOperators, DontAllowOverloadedOperators, enum IsBinopAssignment{ SimpleBinop, BinopAssignment, } #[deriving(Clone)]"} {"_id":"doc-en-rust-6e7b8d8607e840a8b382ba42d37bb3e1376ce3bcb9e79bc8e160066efa56fdb9","title":"","text":"rhs: @ast::Expr, // Used only in the error case expected_result: Option, allow_overloaded_operators: AllowOverloadedOperatorsFlag is_binop_assignment: IsBinopAssignment ) { let tcx = fcx.ccx.tcx;"} {"_id":"doc-en-rust-89d4df2a6b365f07dd1405a8b3cb19bac793e6985ce0fb274e7d66bf80c4f1bf","title":"","text":"} // Check for overloaded operators if allowed. // Check for overloaded operators if not an assignment. let result_t; if allow_overloaded_operators == AllowOverloadedOperators { if is_binop_assignment == SimpleBinop { result_t = check_user_binop(fcx, callee_id, expr,"} {"_id":"doc-en-rust-590c74ea4f79bde0d1234066f9c05e6041bb35f0eddf48b20770cf4e1d6b53b5","title":"","text":"} else { fcx.type_error_message(expr.span, |actual| { format!(\"binary operation {} cannot be applied to type `{}`\", ast_util::binop_to_str(op), actual) format!(\"binary assignment operation {}= cannot be applied to type `{}`\", ast_util::binop_to_str(op), actual) }, lhs_t, None); check_expr(fcx, rhs); result_t = ty::mk_err(); }"} {"_id":"doc-en-rust-74aa019a9ac0b5dc5d03e0d06016762a5c906039a36ea1371c90c717c4a0ae2e","title":"","text":"lhs, rhs, expected, AllowOverloadedOperators); SimpleBinop); let lhs_ty = fcx.expr_ty(lhs); let rhs_ty = fcx.expr_ty(rhs);"} {"_id":"doc-en-rust-a1ea590a938457e15930dba3bc4229bea302020f7471505c3c5ef44ee337846c","title":"","text":"lhs, rhs, expected, DontAllowOverloadedOperators); BinopAssignment); let lhs_t = fcx.expr_ty(lhs); let result_t = fcx.expr_ty(expr);"} {"_id":"doc-en-rust-8f8e34fa5fe914923bcbb51184334e043faffc48afb6b2b3bde6b95df5c6cab1","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct Foo; fn main() { let mut a = Foo; let ref b = Foo; a += *b; //~ Error: binary assignment operation += cannot be applied to type `Foo` } "} {"_id":"doc-en-rust-819c9da7b6484809ed6b1e7c7d5c67f62eef3ea876b34331ef5defc04771fd90","title":"","text":"// Regression test for issue #5239 fn main() { let x: |int| -> int = |ref x| { x += 1; }; //~ ERROR binary operation + cannot be applied to type `&int` let x: |int| -> int = |ref x| { x += 1; }; //~ ERROR binary assignment operation += cannot be applied to type `&int` }"} {"_id":"doc-en-rust-198696f4d7a070c1ecaea73c381f28d7f2e3690457f22f3bc25ce9d36bb792d1","title":"","text":"} } all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries); if sess.opts.prints.contains(&PrintRequest::NativeStaticLibs) { print_native_static_libs(sess, &all_native_libs, &all_rust_dylibs); }"} {"_id":"doc-en-rust-1c95cae72d04d25b42e9e9c9783402ea3d879991936db311d030afb43a6aa6ff","title":"","text":" include ../tools.mk # ignore-cross-compile # ignore-wasm all: $(RUSTC) --crate-type rlib -lbar_cli bar.rs $(RUSTC) foo.rs -lfoo_cli --crate-type staticlib --print native-static-libs 2>&1 | grep 'note: native-static-libs: ' | sed 's/note: native-static-libs: (.*)/1/' > $(TMPDIR)/libs.txt cat $(TMPDIR)/libs.txt | grep -F \"glib-2.0\" # in bar.rs cat $(TMPDIR)/libs.txt | grep -F \"systemd\" # in foo.rs cat $(TMPDIR)/libs.txt | grep -F \"bar_cli\" cat $(TMPDIR)/libs.txt | grep -F \"foo_cli\" "} {"_id":"doc-en-rust-7c3aea9bb41886c6fff89843a03643be3bf628c305beddea7bb4520bdd884194","title":"","text":" #[no_mangle] pub extern \"C\" fn my_bar_add(left: i32, right: i32) -> i32 { // Obviously makes no sense but... unsafe { g_free(std::ptr::null_mut()); } left + right } #[link(name = \"glib-2.0\")] extern \"C\" { fn g_free(p: *mut ()); } "} {"_id":"doc-en-rust-80ea86fb944658fa96c736d07ed7c34ff0b3b309d9a8506cf98396b656af2c3a","title":"","text":" extern crate bar; #[no_mangle] pub extern \"C\" fn my_foo_add(left: i32, right: i32) -> i32 { // Obviously makes no sense but... unsafe { init(std::ptr::null_mut()); } bar::my_bar_add(left, right) } #[link(name = \"systemd\")] extern \"C\" { fn init(p: *mut ()); } "} {"_id":"doc-en-rust-bc94e5cbab89c508b3dca525b573396f9979ac8063b2c7c1b3cf7727c252753e","title":"","text":" #![feature(inherent_associated_types)] #![allow(incomplete_features)] // Check that we don't crash when printing inherent projections in diagnostics. pub struct Carrier<'a>(&'a ()); pub type User = for<'b> fn(Carrier<'b>::Focus); impl<'a> Carrier<'a> { pub type Focus = &'a mut User; //~ ERROR overflow evaluating associated type } fn main() {} "} {"_id":"doc-en-rust-c40666e3bf8235e04bddc61183e918bee5a0a2744f24b1154c8a028ff0aeb2a6","title":"","text":" error: overflow evaluating associated type `Carrier<'b>::Focus` --> $DIR/issue-111879-0.rs:11:25 | LL | pub type Focus = &'a mut User; | ^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-9c2a02b70ad762a087fc107d73f3d567496a2772e37f2af11e76a1322ddd462f","title":"","text":" #![feature(inherent_associated_types)] #![allow(incomplete_features)] // Check that we don't crash when printing inherent projections in diagnostics. struct Foo(T); impl<'a> Foo { type Assoc = &'a (); } fn main(_: for<'a> fn(Foo::Assoc)) {} //~ ERROR `main` function has wrong type "} {"_id":"doc-en-rust-676ab03fbde2fd1ab5eed40c0e6239693f02ead7f8564879321124b2c12b8f2f","title":"","text":" error[E0580]: `main` function has wrong type --> $DIR/issue-111879-1.rs:12:1 | LL | fn main(_: for<'a> fn(Foo::Assoc)) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ incorrect number of function parameters | = note: expected fn pointer `fn()` found fn pointer `fn(for<'a> fn(Foo::Assoc))` error: aborting due to previous error For more information about this error, try `rustc --explain E0580`. "} {"_id":"doc-en-rust-c622984c5852a3bc0203070d5976ef3ea55c14479cc5e128bce32227f679d364","title":"","text":"continue; } let is_closure = matches!(arg.kind, ExprKind::Closure { .. }); // For this check, we do *not* want to treat async generator closures (async blocks) // as proper closures. Doing so would regress type inference when feeding // the return value of an argument-position async block to an argument-position // closure wrapped in a block. // See . let is_closure = if let ExprKind::Closure(closure) = arg.kind { !tcx.generator_is_async(closure.def_id.to_def_id()) } else { false }; if is_closure != check_closures { continue; }"} {"_id":"doc-en-rust-09d8925e391bd7fe576b2899c15c4c9817099ecd1f432e3ae5b81316742671b0","title":"","text":" // check-pass // edition:2021 use core::future::Future; fn main() { do_async(async { (0,) }, { // closure must be inside block |info| println!(\"{:?}\", info.0) }); } fn do_async(_tokio_fut: Fut, _glib_closure: F) where Fut: Future, F: FnOnce(R), { } "} {"_id":"doc-en-rust-2b7ee6663b90581082f8fa4780b45d472c2c3a592075dde68f5d571899daa858","title":"","text":" // edition:2021 // With the current compiler logic, we cannot have both the `112225-1` case, // and this `112225-2` case working, as the type inference depends on the evaluation // order, and there is some explicit ordering going on. // See the `check_closures` part in `FnCtxt::check_argument_types`. // The `112225-1` case was a regression in real world code, whereas the `112225-2` // case never used to work prior to 1.70. use core::future::Future; fn main() { let x = Default::default(); //~^ ERROR: type annotations needed do_async( async { x.0; }, { || { let _: &(i32,) = &x; } }, ); } fn do_async(_fut: Fut, _val: T, ) {} "} {"_id":"doc-en-rust-b893987da697e45a7d9526d38ffb6286c24b93bd42efac6f3e3b2d0de648f544","title":"","text":" error[E0282]: type annotations needed --> $DIR/issue-112225-2.rs:13:9 | LL | let x = Default::default(); | ^ ... LL | async { x.0; }, | - type must be known at this point | help: consider giving `x` an explicit type | LL | let x: /* Type */ = Default::default(); | ++++++++++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0282`. "} {"_id":"doc-en-rust-9c6d7117e9c4879abb4ce26272d46febdc4c52bd28383e2b3980ce28ca50ccec","title":"","text":"check::CargoMiri, check::MiroptTestTools, check::Rls, check::RustAnalyzer, check::Rustfmt, check::RustAnalyzer, check::Bootstrap ), Kind::Test => describe!("} {"_id":"doc-en-rust-2184f9406ad979ee4f890f3049bac84d7c0f7f24e29838ee81aca2dfffdedf56","title":"","text":"impl Step for RustAnalyzer { type Output = (); const ONLY_HOSTS: bool = true; const DEFAULT: bool = true; const DEFAULT: bool = false; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { run.path(\"src/tools/rust-analyzer\")"} {"_id":"doc-en-rust-f21a6f829d3170d2b423672ecc02b997a50e27a2760480d0e04b2d1d8f124376","title":"","text":"if toml_val is not None: env[\"{}_{}\".format(var_name, host_triple_sanitized)] = toml_val # In src/etc/rust_analyzer_settings.json, we configure rust-analyzer to # pass RUSTC_BOOTSTRAP=1 to all cargo invocations because the standard # library uses unstable Cargo features. Without RUSTC_BOOTSTRAP, # rust-analyzer would fail to fetch workspace layout when the system's # default toolchain is not nightly. # # But that setting has the collateral effect of rust-analyzer also # passing RUSTC_BOOTSTRAP=1 to all x.py invocations too (the various # overrideCommand). For compiling bootstrap, that is unwanted and can # cause spurious rebuilding of bootstrap when rust-analyzer x.py # invocations are interleaved with handwritten ones on the command line. env.pop(\"RUSTC_BOOTSTRAP\", None) # preserve existing RUSTFLAGS env.setdefault(\"RUSTFLAGS\", \"\")"} {"_id":"doc-en-rust-0a2765c25894f0b747d6ae5fa8730ee24d14d002c7411bdb57301580c090a170","title":"","text":"} #[test] #[cfg_attr(target_env = \"sgx\", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31 fn connect_timeout_error() { let socket_addr = next_test_ip4(); let result = TcpStream::connect_timeout(&socket_addr, Duration::MAX); assert!(!matches!(result, Err(e) if e.kind() == ErrorKind::TimedOut)); let _listener = TcpListener::bind(&socket_addr).unwrap(); assert!(TcpStream::connect_timeout(&socket_addr, Duration::MAX).is_ok()); } #[test] fn listen_localhost() { let socket_addr = next_test_ip4(); let listener = t!(TcpListener::bind(&socket_addr));"} {"_id":"doc-en-rust-ea4151463f2fb47d72fae3e94f3e85b294a8c038e3e7afc35ec02ea9ab47b446","title":"","text":"} let mut timeout = c::timeval { tv_sec: timeout.as_secs() as c_long, tv_sec: cmp::min(timeout.as_secs(), c_long::MAX as u64) as c_long, tv_usec: (timeout.subsec_nanos() / 1000) as c_long, };"} {"_id":"doc-en-rust-09c62290b34eebf82c1dfa908ae1810987ee28b0aa02b5455374429eb08f37e9","title":"","text":"} let mut new_abis = Vec::new(); loop { while !p.eat(&token::CloseDelim(Delimiter::Parenthesis)) { match p.parse_str_lit() { Ok(str_lit) => { new_abis.push((str_lit.symbol_unescaped, str_lit.span)); } Err(opt_lit) => { // If the non-string literal is a closing paren then it's the end of the list and is fine if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) { break; } let span = opt_lit.map_or(p.token.span, |lit| lit.span); let mut err = p.sess.span_diagnostic.struct_span_err(span, \"expected string literal\");"} {"_id":"doc-en-rust-fc0175373b7370372d16be534210d2af2f1372491f56ca2caaacf6a76a4b0862","title":"","text":" // needs-asm-support #![feature(asm_const)] use std::arch::{asm, global_asm}; fn main() { let mut foo = 0; let mut bar = 0; unsafe { asm!(); //~^ ERROR requires at least a template string argument asm!(foo); //~^ ERROR asm template must be a string literal asm!(\"{}\" foo); //~^ ERROR expected token: `,` asm!(\"{}\", foo); //~^ ERROR expected operand, clobber_abi, options, or additional template string asm!(\"{}\", in foo); //~^ ERROR expected `(`, found `foo` asm!(\"{}\", in(reg foo)); //~^ ERROR expected `)`, found `foo` asm!(\"{}\", in(reg)); //~^ ERROR expected expression, found end of macro arguments asm!(\"{}\", inout(=) foo => bar); //~^ ERROR expected register class or explicit register asm!(\"{}\", inout(reg) foo =>); //~^ ERROR expected expression, found end of macro arguments asm!(\"{}\", in(reg) foo => bar); //~^ ERROR expected one of `!`, `,`, `.`, `::`, `?`, `{`, or an operator, found `=>` asm!(\"{}\", sym foo + bar); //~^ ERROR expected a path for argument to `sym` asm!(\"\", options(foo)); //~^ ERROR expected one of asm!(\"\", options(nomem foo)); //~^ ERROR expected one of asm!(\"\", options(nomem, foo)); //~^ ERROR expected one of asm!(\"{}\", options(), const foo); //~^ ERROR attempt to use a non-constant value in a constant // test that asm!'s clobber_abi doesn't accept non-string literals // see also https://github.com/rust-lang/rust/issues/112635 asm!(\"\", clobber_abi()); //~^ ERROR at least one abi must be provided asm!(\"\", clobber_abi(foo)); //~^ ERROR expected string literal asm!(\"\", clobber_abi(\"C\" foo)); //~^ ERROR expected one of `)` or `,`, found `foo` asm!(\"\", clobber_abi(\"C\", foo)); //~^ ERROR expected string literal asm!(\"\", clobber_abi(1)); //~^ ERROR expected string literal asm!(\"\", clobber_abi(())); //~^ ERROR expected string literal asm!(\"\", clobber_abi(uwu)); //~^ ERROR expected string literal asm!(\"\", clobber_abi({})); //~^ ERROR expected string literal asm!(\"\", clobber_abi(loop {})); //~^ ERROR expected string literal asm!(\"\", clobber_abi(if)); //~^ ERROR expected string literal asm!(\"\", clobber_abi(do)); //~^ ERROR expected string literal asm!(\"\", clobber_abi(<)); //~^ ERROR expected string literal asm!(\"\", clobber_abi(.)); //~^ ERROR expected string literal asm!(\"{}\", clobber_abi(\"C\"), const foo); //~^ ERROR attempt to use a non-constant value in a constant asm!(\"\", options(), clobber_abi(\"C\")); asm!(\"{}\", options(), clobber_abi(\"C\"), const foo); //~^ ERROR attempt to use a non-constant value in a constant asm!(\"{a}\", a = const foo, a = const bar); //~^ ERROR duplicate argument named `a` //~^^ ERROR argument never used //~^^^ ERROR attempt to use a non-constant value in a constant //~^^^^ ERROR attempt to use a non-constant value in a constant asm!(\"\", options(), \"\"); //~^ ERROR expected one of asm!(\"{}\", in(reg) foo, \"{}\", out(reg) foo); //~^ ERROR expected one of asm!(format!(\"{{{}}}\", 0), in(reg) foo); //~^ ERROR asm template must be a string literal asm!(\"{1}\", format!(\"{{{}}}\", 0), in(reg) foo, out(reg) bar); //~^ ERROR asm template must be a string literal asm!(\"{}\", in(reg) _); //~^ ERROR _ cannot be used for input operands asm!(\"{}\", inout(reg) _); //~^ ERROR _ cannot be used for input operands asm!(\"{}\", inlateout(reg) _); //~^ ERROR _ cannot be used for input operands } } const FOO: i32 = 1; const BAR: i32 = 2; global_asm!(); //~^ ERROR requires at least a template string argument global_asm!(FOO); //~^ ERROR asm template must be a string literal global_asm!(\"{}\" FOO); //~^ ERROR expected token: `,` global_asm!(\"{}\", FOO); //~^ ERROR expected operand, options, or additional template string global_asm!(\"{}\", const); //~^ ERROR expected expression, found end of macro arguments global_asm!(\"{}\", const(reg) FOO); //~^ ERROR expected one of global_asm!(\"\", options(FOO)); //~^ ERROR expected one of global_asm!(\"\", options(nomem FOO)); //~^ ERROR expected one of global_asm!(\"\", options(nomem, FOO)); //~^ ERROR expected one of global_asm!(\"{}\", options(), const FOO); global_asm!(\"\", clobber_abi(FOO)); //~^ ERROR expected string literal global_asm!(\"\", clobber_abi(\"C\" FOO)); //~^ ERROR expected one of `)` or `,`, found `FOO` global_asm!(\"\", clobber_abi(\"C\", FOO)); //~^ ERROR expected string literal global_asm!(\"{}\", clobber_abi(\"C\"), const FOO); //~^ ERROR `clobber_abi` cannot be used with `global_asm!` global_asm!(\"\", options(), clobber_abi(\"C\")); //~^ ERROR `clobber_abi` cannot be used with `global_asm!` global_asm!(\"{}\", options(), clobber_abi(\"C\"), const FOO); //~^ ERROR `clobber_abi` cannot be used with `global_asm!` global_asm!(\"\", clobber_abi(\"C\"), clobber_abi(\"C\")); //~^ ERROR `clobber_abi` cannot be used with `global_asm!` global_asm!(\"{a}\", a = const FOO, a = const BAR); //~^ ERROR duplicate argument named `a` //~^^ ERROR argument never used global_asm!(\"\", options(), \"\"); //~^ ERROR expected one of global_asm!(\"{}\", const FOO, \"{}\", const FOO); //~^ ERROR expected one of global_asm!(format!(\"{{{}}}\", 0), const FOO); //~^ ERROR asm template must be a string literal global_asm!(\"{1}\", format!(\"{{{}}}\", 0), const FOO, const BAR); //~^ ERROR asm template must be a string literal "} {"_id":"doc-en-rust-ec09b8fbe843d4a8afd3ae1e070312559df208ac09559006ba963c5b83f856c5","title":"","text":" error: requires at least a template string argument --> $DIR/parse-error.rs:11:9 | LL | asm!(); | ^^^^^^ error: asm template must be a string literal --> $DIR/parse-error.rs:13:14 | LL | asm!(foo); | ^^^ error: expected token: `,` --> $DIR/parse-error.rs:15:19 | LL | asm!(\"{}\" foo); | ^^^ expected `,` error: expected operand, clobber_abi, options, or additional template string --> $DIR/parse-error.rs:17:20 | LL | asm!(\"{}\", foo); | ^^^ expected operand, clobber_abi, options, or additional template string error: expected `(`, found `foo` --> $DIR/parse-error.rs:19:23 | LL | asm!(\"{}\", in foo); | ^^^ expected `(` error: expected `)`, found `foo` --> $DIR/parse-error.rs:21:27 | LL | asm!(\"{}\", in(reg foo)); | ^^^ expected `)` error: expected expression, found end of macro arguments --> $DIR/parse-error.rs:23:27 | LL | asm!(\"{}\", in(reg)); | ^ expected expression error: expected register class or explicit register --> $DIR/parse-error.rs:25:26 | LL | asm!(\"{}\", inout(=) foo => bar); | ^ error: expected expression, found end of macro arguments --> $DIR/parse-error.rs:27:37 | LL | asm!(\"{}\", inout(reg) foo =>); | ^ expected expression error: expected one of `!`, `,`, `.`, `::`, `?`, `{`, or an operator, found `=>` --> $DIR/parse-error.rs:29:32 | LL | asm!(\"{}\", in(reg) foo => bar); | ^^ expected one of 7 possible tokens error: expected a path for argument to `sym` --> $DIR/parse-error.rs:31:24 | LL | asm!(\"{}\", sym foo + bar); | ^^^^^^^^^ error: expected one of `)`, `att_syntax`, `may_unwind`, `nomem`, `noreturn`, `nostack`, `preserves_flags`, `pure`, `raw`, or `readonly`, found `foo` --> $DIR/parse-error.rs:33:26 | LL | asm!(\"\", options(foo)); | ^^^ expected one of 10 possible tokens error: expected one of `)` or `,`, found `foo` --> $DIR/parse-error.rs:35:32 | LL | asm!(\"\", options(nomem foo)); | ^^^ expected one of `)` or `,` error: expected one of `)`, `att_syntax`, `may_unwind`, `nomem`, `noreturn`, `nostack`, `preserves_flags`, `pure`, `raw`, or `readonly`, found `foo` --> $DIR/parse-error.rs:37:33 | LL | asm!(\"\", options(nomem, foo)); | ^^^ expected one of 10 possible tokens error: at least one abi must be provided as an argument to `clobber_abi` --> $DIR/parse-error.rs:44:30 | LL | asm!(\"\", clobber_abi()); | ^ error: expected string literal --> $DIR/parse-error.rs:46:30 | LL | asm!(\"\", clobber_abi(foo)); | ^^^ not a string literal error: expected one of `)` or `,`, found `foo` --> $DIR/parse-error.rs:48:34 | LL | asm!(\"\", clobber_abi(\"C\" foo)); | ^^^ expected one of `)` or `,` error: expected string literal --> $DIR/parse-error.rs:50:35 | LL | asm!(\"\", clobber_abi(\"C\", foo)); | ^^^ not a string literal error: expected string literal --> $DIR/parse-error.rs:52:30 | LL | asm!(\"\", clobber_abi(1)); | ^ not a string literal error: expected string literal --> $DIR/parse-error.rs:54:30 | LL | asm!(\"\", clobber_abi(())); | ^ not a string literal error: expected string literal --> $DIR/parse-error.rs:56:30 | LL | asm!(\"\", clobber_abi(uwu)); | ^^^ not a string literal error: expected string literal --> $DIR/parse-error.rs:58:30 | LL | asm!(\"\", clobber_abi({})); | ^ not a string literal error: expected string literal --> $DIR/parse-error.rs:60:30 | LL | asm!(\"\", clobber_abi(loop {})); | ^^^^ not a string literal error: expected string literal --> $DIR/parse-error.rs:62:30 | LL | asm!(\"\", clobber_abi(if)); | ^^ not a string literal error: expected string literal --> $DIR/parse-error.rs:64:30 | LL | asm!(\"\", clobber_abi(do)); | ^^ not a string literal error: expected string literal --> $DIR/parse-error.rs:66:30 | LL | asm!(\"\", clobber_abi(<)); | ^ not a string literal error: expected string literal --> $DIR/parse-error.rs:68:30 | LL | asm!(\"\", clobber_abi(.)); | ^ not a string literal error: duplicate argument named `a` --> $DIR/parse-error.rs:76:36 | LL | asm!(\"{a}\", a = const foo, a = const bar); | ------------- ^^^^^^^^^^^^^ duplicate argument | | | previously here error: argument never used --> $DIR/parse-error.rs:76:36 | LL | asm!(\"{a}\", a = const foo, a = const bar); | ^^^^^^^^^^^^^ argument never used | = help: if this argument is intentionally unused, consider using it in an asm comment: `\"/* {1} */\"` error: expected one of `clobber_abi`, `const`, `in`, `inlateout`, `inout`, `lateout`, `options`, `out`, or `sym`, found `\"\"` --> $DIR/parse-error.rs:82:29 | LL | asm!(\"\", options(), \"\"); | ^^ expected one of 9 possible tokens error: expected one of `clobber_abi`, `const`, `in`, `inlateout`, `inout`, `lateout`, `options`, `out`, or `sym`, found `\"{}\"` --> $DIR/parse-error.rs:84:33 | LL | asm!(\"{}\", in(reg) foo, \"{}\", out(reg) foo); | ^^^^ expected one of 9 possible tokens error: asm template must be a string literal --> $DIR/parse-error.rs:86:14 | LL | asm!(format!(\"{{{}}}\", 0), in(reg) foo); | ^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) error: asm template must be a string literal --> $DIR/parse-error.rs:88:21 | LL | asm!(\"{1}\", format!(\"{{{}}}\", 0), in(reg) foo, out(reg) bar); | ^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) error: _ cannot be used for input operands --> $DIR/parse-error.rs:90:28 | LL | asm!(\"{}\", in(reg) _); | ^ error: _ cannot be used for input operands --> $DIR/parse-error.rs:92:31 | LL | asm!(\"{}\", inout(reg) _); | ^ error: _ cannot be used for input operands --> $DIR/parse-error.rs:94:35 | LL | asm!(\"{}\", inlateout(reg) _); | ^ error: requires at least a template string argument --> $DIR/parse-error.rs:101:1 | LL | global_asm!(); | ^^^^^^^^^^^^^ error: asm template must be a string literal --> $DIR/parse-error.rs:103:13 | LL | global_asm!(FOO); | ^^^ error: expected token: `,` --> $DIR/parse-error.rs:105:18 | LL | global_asm!(\"{}\" FOO); | ^^^ expected `,` error: expected operand, options, or additional template string --> $DIR/parse-error.rs:107:19 | LL | global_asm!(\"{}\", FOO); | ^^^ expected operand, options, or additional template string error: expected expression, found end of macro arguments --> $DIR/parse-error.rs:109:24 | LL | global_asm!(\"{}\", const); | ^ expected expression error: expected one of `,`, `.`, `?`, or an operator, found `FOO` --> $DIR/parse-error.rs:111:30 | LL | global_asm!(\"{}\", const(reg) FOO); | ^^^ expected one of `,`, `.`, `?`, or an operator error: expected one of `)`, `att_syntax`, or `raw`, found `FOO` --> $DIR/parse-error.rs:113:25 | LL | global_asm!(\"\", options(FOO)); | ^^^ expected one of `)`, `att_syntax`, or `raw` error: expected one of `)`, `att_syntax`, or `raw`, found `nomem` --> $DIR/parse-error.rs:115:25 | LL | global_asm!(\"\", options(nomem FOO)); | ^^^^^ expected one of `)`, `att_syntax`, or `raw` error: expected one of `)`, `att_syntax`, or `raw`, found `nomem` --> $DIR/parse-error.rs:117:25 | LL | global_asm!(\"\", options(nomem, FOO)); | ^^^^^ expected one of `)`, `att_syntax`, or `raw` error: expected string literal --> $DIR/parse-error.rs:120:29 | LL | global_asm!(\"\", clobber_abi(FOO)); | ^^^ not a string literal error: expected one of `)` or `,`, found `FOO` --> $DIR/parse-error.rs:122:33 | LL | global_asm!(\"\", clobber_abi(\"C\" FOO)); | ^^^ expected one of `)` or `,` error: expected string literal --> $DIR/parse-error.rs:124:34 | LL | global_asm!(\"\", clobber_abi(\"C\", FOO)); | ^^^ not a string literal error: `clobber_abi` cannot be used with `global_asm!` --> $DIR/parse-error.rs:126:19 | LL | global_asm!(\"{}\", clobber_abi(\"C\"), const FOO); | ^^^^^^^^^^^^^^^^ error: `clobber_abi` cannot be used with `global_asm!` --> $DIR/parse-error.rs:128:28 | LL | global_asm!(\"\", options(), clobber_abi(\"C\")); | ^^^^^^^^^^^^^^^^ error: `clobber_abi` cannot be used with `global_asm!` --> $DIR/parse-error.rs:130:30 | LL | global_asm!(\"{}\", options(), clobber_abi(\"C\"), const FOO); | ^^^^^^^^^^^^^^^^ error: `clobber_abi` cannot be used with `global_asm!` --> $DIR/parse-error.rs:132:17 | LL | global_asm!(\"\", clobber_abi(\"C\"), clobber_abi(\"C\")); | ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ error: duplicate argument named `a` --> $DIR/parse-error.rs:134:35 | LL | global_asm!(\"{a}\", a = const FOO, a = const BAR); | ------------- ^^^^^^^^^^^^^ duplicate argument | | | previously here error: argument never used --> $DIR/parse-error.rs:134:35 | LL | global_asm!(\"{a}\", a = const FOO, a = const BAR); | ^^^^^^^^^^^^^ argument never used | = help: if this argument is intentionally unused, consider using it in an asm comment: `\"/* {1} */\"` error: expected one of `clobber_abi`, `const`, `options`, or `sym`, found `\"\"` --> $DIR/parse-error.rs:137:28 | LL | global_asm!(\"\", options(), \"\"); | ^^ expected one of `clobber_abi`, `const`, `options`, or `sym` error: expected one of `clobber_abi`, `const`, `options`, or `sym`, found `\"{}\"` --> $DIR/parse-error.rs:139:30 | LL | global_asm!(\"{}\", const FOO, \"{}\", const FOO); | ^^^^ expected one of `clobber_abi`, `const`, `options`, or `sym` error: asm template must be a string literal --> $DIR/parse-error.rs:141:13 | LL | global_asm!(format!(\"{{{}}}\", 0), const FOO); | ^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) error: asm template must be a string literal --> $DIR/parse-error.rs:143:20 | LL | global_asm!(\"{1}\", format!(\"{{{}}}\", 0), const FOO, const BAR); | ^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:39:37 | LL | let mut foo = 0; | ----------- help: consider using `const` instead of `let`: `const foo` ... LL | asm!(\"{}\", options(), const foo); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:71:44 | LL | let mut foo = 0; | ----------- help: consider using `const` instead of `let`: `const foo` ... LL | asm!(\"{}\", clobber_abi(\"C\"), const foo); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:74:55 | LL | let mut foo = 0; | ----------- help: consider using `const` instead of `let`: `const foo` ... LL | asm!(\"{}\", options(), clobber_abi(\"C\"), const foo); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:76:31 | LL | let mut foo = 0; | ----------- help: consider using `const` instead of `let`: `const foo` ... LL | asm!(\"{a}\", a = const foo, a = const bar); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:76:46 | LL | let mut bar = 0; | ----------- help: consider using `const` instead of `let`: `const bar` ... LL | asm!(\"{a}\", a = const foo, a = const bar); | ^^^ non-constant value error: aborting due to 63 previous errors For more information about this error, try `rustc --explain E0435`. "} {"_id":"doc-en-rust-1772719a0a25f0dfb8f5e14546100f4482418422af2c0f0645db4f329c7e47f1","title":"","text":" // only-x86_64 #![feature(asm_const)] use std::arch::{asm, global_asm}; fn main() { let mut foo = 0; let mut bar = 0; unsafe { asm!(); //~^ ERROR requires at least a template string argument asm!(foo); //~^ ERROR asm template must be a string literal asm!(\"{}\" foo); //~^ ERROR expected token: `,` asm!(\"{}\", foo); //~^ ERROR expected operand, clobber_abi, options, or additional template string asm!(\"{}\", in foo); //~^ ERROR expected `(`, found `foo` asm!(\"{}\", in(reg foo)); //~^ ERROR expected `)`, found `foo` asm!(\"{}\", in(reg)); //~^ ERROR expected expression, found end of macro arguments asm!(\"{}\", inout(=) foo => bar); //~^ ERROR expected register class or explicit register asm!(\"{}\", inout(reg) foo =>); //~^ ERROR expected expression, found end of macro arguments asm!(\"{}\", in(reg) foo => bar); //~^ ERROR expected one of `!`, `,`, `.`, `::`, `?`, `{`, or an operator, found `=>` asm!(\"{}\", sym foo + bar); //~^ ERROR expected a path for argument to `sym` asm!(\"\", options(foo)); //~^ ERROR expected one of asm!(\"\", options(nomem foo)); //~^ ERROR expected one of asm!(\"\", options(nomem, foo)); //~^ ERROR expected one of asm!(\"{}\", options(), const foo); //~^ ERROR attempt to use a non-constant value in a constant asm!(\"\", clobber_abi()); //~^ ERROR at least one abi must be provided asm!(\"\", clobber_abi(foo)); //~^ ERROR expected string literal asm!(\"\", clobber_abi(\"C\" foo)); //~^ ERROR expected one of `)` or `,`, found `foo` asm!(\"\", clobber_abi(\"C\", foo)); //~^ ERROR expected string literal asm!(\"{}\", clobber_abi(\"C\"), const foo); //~^ ERROR attempt to use a non-constant value in a constant asm!(\"\", options(), clobber_abi(\"C\")); asm!(\"{}\", options(), clobber_abi(\"C\"), const foo); //~^ ERROR attempt to use a non-constant value in a constant asm!(\"{a}\", a = const foo, a = const bar); //~^ ERROR duplicate argument named `a` //~^^ ERROR argument never used //~^^^ ERROR attempt to use a non-constant value in a constant //~^^^^ ERROR attempt to use a non-constant value in a constant asm!(\"\", a = in(\"eax\") foo); //~^ ERROR explicit register arguments cannot have names asm!(\"{a}\", in(\"eax\") foo, a = const bar); //~^ ERROR attempt to use a non-constant value in a constant asm!(\"{a}\", in(\"eax\") foo, a = const bar); //~^ ERROR attempt to use a non-constant value in a constant asm!(\"{1}\", in(\"eax\") foo, const bar); //~^ ERROR positional arguments cannot follow named arguments or explicit register arguments //~^^ ERROR attempt to use a non-constant value in a constant asm!(\"\", options(), \"\"); //~^ ERROR expected one of asm!(\"{}\", in(reg) foo, \"{}\", out(reg) foo); //~^ ERROR expected one of asm!(format!(\"{{{}}}\", 0), in(reg) foo); //~^ ERROR asm template must be a string literal asm!(\"{1}\", format!(\"{{{}}}\", 0), in(reg) foo, out(reg) bar); //~^ ERROR asm template must be a string literal asm!(\"{}\", in(reg) _); //~^ ERROR _ cannot be used for input operands asm!(\"{}\", inout(reg) _); //~^ ERROR _ cannot be used for input operands asm!(\"{}\", inlateout(reg) _); //~^ ERROR _ cannot be used for input operands } } const FOO: i32 = 1; const BAR: i32 = 2; global_asm!(); //~^ ERROR requires at least a template string argument global_asm!(FOO); //~^ ERROR asm template must be a string literal global_asm!(\"{}\" FOO); //~^ ERROR expected token: `,` global_asm!(\"{}\", FOO); //~^ ERROR expected operand, options, or additional template string global_asm!(\"{}\", const); //~^ ERROR expected expression, found end of macro arguments global_asm!(\"{}\", const(reg) FOO); //~^ ERROR expected one of global_asm!(\"\", options(FOO)); //~^ ERROR expected one of global_asm!(\"\", options(nomem FOO)); //~^ ERROR expected one of global_asm!(\"\", options(nomem, FOO)); //~^ ERROR expected one of global_asm!(\"{}\", options(), const FOO); global_asm!(\"\", clobber_abi(FOO)); //~^ ERROR expected string literal global_asm!(\"\", clobber_abi(\"C\" FOO)); //~^ ERROR expected one of `)` or `,`, found `FOO` global_asm!(\"\", clobber_abi(\"C\", FOO)); //~^ ERROR expected string literal global_asm!(\"{}\", clobber_abi(\"C\"), const FOO); //~^ ERROR `clobber_abi` cannot be used with `global_asm!` global_asm!(\"\", options(), clobber_abi(\"C\")); //~^ ERROR `clobber_abi` cannot be used with `global_asm!` global_asm!(\"{}\", options(), clobber_abi(\"C\"), const FOO); //~^ ERROR `clobber_abi` cannot be used with `global_asm!` global_asm!(\"\", clobber_abi(\"C\"), clobber_abi(\"C\")); //~^ ERROR `clobber_abi` cannot be used with `global_asm!` global_asm!(\"{a}\", a = const FOO, a = const BAR); //~^ ERROR duplicate argument named `a` //~^^ ERROR argument never used global_asm!(\"\", options(), \"\"); //~^ ERROR expected one of global_asm!(\"{}\", const FOO, \"{}\", const FOO); //~^ ERROR expected one of global_asm!(format!(\"{{{}}}\", 0), const FOO); //~^ ERROR asm template must be a string literal global_asm!(\"{1}\", format!(\"{{{}}}\", 0), const FOO, const BAR); //~^ ERROR asm template must be a string literal "} {"_id":"doc-en-rust-6cb9c25fe5277cc78eb003d75d33c24eb55f5ad670b72097c2c24299e11d7718","title":"","text":" error: requires at least a template string argument --> $DIR/parse-error.rs:11:9 | LL | asm!(); | ^^^^^^ error: asm template must be a string literal --> $DIR/parse-error.rs:13:14 | LL | asm!(foo); | ^^^ error: expected token: `,` --> $DIR/parse-error.rs:15:19 | LL | asm!(\"{}\" foo); | ^^^ expected `,` error: expected operand, clobber_abi, options, or additional template string --> $DIR/parse-error.rs:17:20 | LL | asm!(\"{}\", foo); | ^^^ expected operand, clobber_abi, options, or additional template string error: expected `(`, found `foo` --> $DIR/parse-error.rs:19:23 | LL | asm!(\"{}\", in foo); | ^^^ expected `(` error: expected `)`, found `foo` --> $DIR/parse-error.rs:21:27 | LL | asm!(\"{}\", in(reg foo)); | ^^^ expected `)` error: expected expression, found end of macro arguments --> $DIR/parse-error.rs:23:27 | LL | asm!(\"{}\", in(reg)); | ^ expected expression error: expected register class or explicit register --> $DIR/parse-error.rs:25:26 | LL | asm!(\"{}\", inout(=) foo => bar); | ^ error: expected expression, found end of macro arguments --> $DIR/parse-error.rs:27:37 | LL | asm!(\"{}\", inout(reg) foo =>); | ^ expected expression error: expected one of `!`, `,`, `.`, `::`, `?`, `{`, or an operator, found `=>` --> $DIR/parse-error.rs:29:32 | LL | asm!(\"{}\", in(reg) foo => bar); | ^^ expected one of 7 possible tokens error: expected a path for argument to `sym` --> $DIR/parse-error.rs:31:24 | LL | asm!(\"{}\", sym foo + bar); | ^^^^^^^^^ error: expected one of `)`, `att_syntax`, `may_unwind`, `nomem`, `noreturn`, `nostack`, `preserves_flags`, `pure`, `raw`, or `readonly`, found `foo` --> $DIR/parse-error.rs:33:26 | LL | asm!(\"\", options(foo)); | ^^^ expected one of 10 possible tokens error: expected one of `)` or `,`, found `foo` --> $DIR/parse-error.rs:35:32 | LL | asm!(\"\", options(nomem foo)); | ^^^ expected one of `)` or `,` error: expected one of `)`, `att_syntax`, `may_unwind`, `nomem`, `noreturn`, `nostack`, `preserves_flags`, `pure`, `raw`, or `readonly`, found `foo` --> $DIR/parse-error.rs:37:33 | LL | asm!(\"\", options(nomem, foo)); | ^^^ expected one of 10 possible tokens error: at least one abi must be provided as an argument to `clobber_abi` --> $DIR/parse-error.rs:41:30 | LL | asm!(\"\", clobber_abi()); | ^ error: expected string literal --> $DIR/parse-error.rs:43:30 | LL | asm!(\"\", clobber_abi(foo)); | ^^^ not a string literal error: expected one of `)` or `,`, found `foo` --> $DIR/parse-error.rs:45:34 | LL | asm!(\"\", clobber_abi(\"C\" foo)); | ^^^ expected one of `)` or `,` error: expected string literal --> $DIR/parse-error.rs:47:35 | LL | asm!(\"\", clobber_abi(\"C\", foo)); | ^^^ not a string literal error: duplicate argument named `a` --> $DIR/parse-error.rs:54:36 | LL | asm!(\"{a}\", a = const foo, a = const bar); | ------------- ^^^^^^^^^^^^^ duplicate argument | | | previously here error: argument never used --> $DIR/parse-error.rs:54:36 | LL | asm!(\"{a}\", a = const foo, a = const bar); | ^^^^^^^^^^^^^ argument never used | = help: if this argument is intentionally unused, consider using it in an asm comment: `\"/* {1} */\"` error: explicit register arguments cannot have names --> $DIR/parse-error.rs:59:18 | LL | asm!(\"\", a = in(\"eax\") foo); | ^^^^^^^^^^^^^^^^^ error: positional arguments cannot follow named arguments or explicit register arguments --> $DIR/parse-error.rs:65:36 | LL | asm!(\"{1}\", in(\"eax\") foo, const bar); | ------------- ^^^^^^^^^ positional argument | | | explicit register argument error: expected one of `clobber_abi`, `const`, `in`, `inlateout`, `inout`, `lateout`, `options`, `out`, or `sym`, found `\"\"` --> $DIR/parse-error.rs:68:29 | LL | asm!(\"\", options(), \"\"); | ^^ expected one of 9 possible tokens error: expected one of `clobber_abi`, `const`, `in`, `inlateout`, `inout`, `lateout`, `options`, `out`, or `sym`, found `\"{}\"` --> $DIR/parse-error.rs:70:33 | LL | asm!(\"{}\", in(reg) foo, \"{}\", out(reg) foo); | ^^^^ expected one of 9 possible tokens error: asm template must be a string literal --> $DIR/parse-error.rs:72:14 | LL | asm!(format!(\"{{{}}}\", 0), in(reg) foo); | ^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) error: asm template must be a string literal --> $DIR/parse-error.rs:74:21 | LL | asm!(\"{1}\", format!(\"{{{}}}\", 0), in(reg) foo, out(reg) bar); | ^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) error: _ cannot be used for input operands --> $DIR/parse-error.rs:76:28 | LL | asm!(\"{}\", in(reg) _); | ^ error: _ cannot be used for input operands --> $DIR/parse-error.rs:78:31 | LL | asm!(\"{}\", inout(reg) _); | ^ error: _ cannot be used for input operands --> $DIR/parse-error.rs:80:35 | LL | asm!(\"{}\", inlateout(reg) _); | ^ error: requires at least a template string argument --> $DIR/parse-error.rs:87:1 | LL | global_asm!(); | ^^^^^^^^^^^^^ error: asm template must be a string literal --> $DIR/parse-error.rs:89:13 | LL | global_asm!(FOO); | ^^^ error: expected token: `,` --> $DIR/parse-error.rs:91:18 | LL | global_asm!(\"{}\" FOO); | ^^^ expected `,` error: expected operand, options, or additional template string --> $DIR/parse-error.rs:93:19 | LL | global_asm!(\"{}\", FOO); | ^^^ expected operand, options, or additional template string error: expected expression, found end of macro arguments --> $DIR/parse-error.rs:95:24 | LL | global_asm!(\"{}\", const); | ^ expected expression error: expected one of `,`, `.`, `?`, or an operator, found `FOO` --> $DIR/parse-error.rs:97:30 | LL | global_asm!(\"{}\", const(reg) FOO); | ^^^ expected one of `,`, `.`, `?`, or an operator error: expected one of `)`, `att_syntax`, or `raw`, found `FOO` --> $DIR/parse-error.rs:99:25 | LL | global_asm!(\"\", options(FOO)); | ^^^ expected one of `)`, `att_syntax`, or `raw` error: expected one of `)`, `att_syntax`, or `raw`, found `nomem` --> $DIR/parse-error.rs:101:25 | LL | global_asm!(\"\", options(nomem FOO)); | ^^^^^ expected one of `)`, `att_syntax`, or `raw` error: expected one of `)`, `att_syntax`, or `raw`, found `nomem` --> $DIR/parse-error.rs:103:25 | LL | global_asm!(\"\", options(nomem, FOO)); | ^^^^^ expected one of `)`, `att_syntax`, or `raw` error: expected string literal --> $DIR/parse-error.rs:106:29 | LL | global_asm!(\"\", clobber_abi(FOO)); | ^^^ not a string literal error: expected one of `)` or `,`, found `FOO` --> $DIR/parse-error.rs:108:33 | LL | global_asm!(\"\", clobber_abi(\"C\" FOO)); | ^^^ expected one of `)` or `,` error: expected string literal --> $DIR/parse-error.rs:110:34 | LL | global_asm!(\"\", clobber_abi(\"C\", FOO)); | ^^^ not a string literal error: `clobber_abi` cannot be used with `global_asm!` --> $DIR/parse-error.rs:112:19 | LL | global_asm!(\"{}\", clobber_abi(\"C\"), const FOO); | ^^^^^^^^^^^^^^^^ error: `clobber_abi` cannot be used with `global_asm!` --> $DIR/parse-error.rs:114:28 | LL | global_asm!(\"\", options(), clobber_abi(\"C\")); | ^^^^^^^^^^^^^^^^ error: `clobber_abi` cannot be used with `global_asm!` --> $DIR/parse-error.rs:116:30 | LL | global_asm!(\"{}\", options(), clobber_abi(\"C\"), const FOO); | ^^^^^^^^^^^^^^^^ error: `clobber_abi` cannot be used with `global_asm!` --> $DIR/parse-error.rs:118:17 | LL | global_asm!(\"\", clobber_abi(\"C\"), clobber_abi(\"C\")); | ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ error: duplicate argument named `a` --> $DIR/parse-error.rs:120:35 | LL | global_asm!(\"{a}\", a = const FOO, a = const BAR); | ------------- ^^^^^^^^^^^^^ duplicate argument | | | previously here error: argument never used --> $DIR/parse-error.rs:120:35 | LL | global_asm!(\"{a}\", a = const FOO, a = const BAR); | ^^^^^^^^^^^^^ argument never used | = help: if this argument is intentionally unused, consider using it in an asm comment: `\"/* {1} */\"` error: expected one of `clobber_abi`, `const`, `options`, or `sym`, found `\"\"` --> $DIR/parse-error.rs:123:28 | LL | global_asm!(\"\", options(), \"\"); | ^^ expected one of `clobber_abi`, `const`, `options`, or `sym` error: expected one of `clobber_abi`, `const`, `options`, or `sym`, found `\"{}\"` --> $DIR/parse-error.rs:125:30 | LL | global_asm!(\"{}\", const FOO, \"{}\", const FOO); | ^^^^ expected one of `clobber_abi`, `const`, `options`, or `sym` error: asm template must be a string literal --> $DIR/parse-error.rs:127:13 | LL | global_asm!(format!(\"{{{}}}\", 0), const FOO); | ^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) error: asm template must be a string literal --> $DIR/parse-error.rs:129:20 | LL | global_asm!(\"{1}\", format!(\"{{{}}}\", 0), const FOO, const BAR); | ^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:39:37 | LL | let mut foo = 0; | ----------- help: consider using `const` instead of `let`: `const foo` ... LL | asm!(\"{}\", options(), const foo); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:49:44 | LL | let mut foo = 0; | ----------- help: consider using `const` instead of `let`: `const foo` ... LL | asm!(\"{}\", clobber_abi(\"C\"), const foo); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:52:55 | LL | let mut foo = 0; | ----------- help: consider using `const` instead of `let`: `const foo` ... LL | asm!(\"{}\", options(), clobber_abi(\"C\"), const foo); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:54:31 | LL | let mut foo = 0; | ----------- help: consider using `const` instead of `let`: `const foo` ... LL | asm!(\"{a}\", a = const foo, a = const bar); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:54:46 | LL | let mut bar = 0; | ----------- help: consider using `const` instead of `let`: `const bar` ... LL | asm!(\"{a}\", a = const foo, a = const bar); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:61:46 | LL | let mut bar = 0; | ----------- help: consider using `const` instead of `let`: `const bar` ... LL | asm!(\"{a}\", in(\"eax\") foo, a = const bar); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:63:46 | LL | let mut bar = 0; | ----------- help: consider using `const` instead of `let`: `const bar` ... LL | asm!(\"{a}\", in(\"eax\") foo, a = const bar); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/parse-error.rs:65:42 | LL | let mut bar = 0; | ----------- help: consider using `const` instead of `let`: `const bar` ... LL | asm!(\"{1}\", in(\"eax\") foo, const bar); | ^^^ non-constant value error: aborting due to 59 previous errors For more information about this error, try `rustc --explain E0435`. "} {"_id":"doc-en-rust-c566933f2e8c1c2d70bb9e29f3a95c5584fb3cf64fbcfdf4338bd299d40b87e4","title":"","text":" // only-x86_64 #![feature(asm_const)] use std::arch::asm; fn main() { let mut foo = 0; let mut bar = 0; unsafe { asm!(\"\", a = in(\"eax\") foo); //~^ ERROR explicit register arguments cannot have names asm!(\"{a}\", in(\"eax\") foo, a = const bar); //~^ ERROR attempt to use a non-constant value in a constant asm!(\"{a}\", in(\"eax\") foo, a = const bar); //~^ ERROR attempt to use a non-constant value in a constant asm!(\"{1}\", in(\"eax\") foo, const bar); //~^ ERROR positional arguments cannot follow named arguments or explicit register arguments //~^^ ERROR attempt to use a non-constant value in a constant } } "} {"_id":"doc-en-rust-2272f1d3688f59dbb6a327dc797c420866e094f0b4c19d9ada485100e1b96d35","title":"","text":" error: explicit register arguments cannot have names --> $DIR/x86_64_parse_error.rs:11:18 | LL | asm!(\"\", a = in(\"eax\") foo); | ^^^^^^^^^^^^^^^^^ error: positional arguments cannot follow named arguments or explicit register arguments --> $DIR/x86_64_parse_error.rs:17:36 | LL | asm!(\"{1}\", in(\"eax\") foo, const bar); | ------------- ^^^^^^^^^ positional argument | | | explicit register argument error[E0435]: attempt to use a non-constant value in a constant --> $DIR/x86_64_parse_error.rs:13:46 | LL | let mut bar = 0; | ----------- help: consider using `const` instead of `let`: `const bar` ... LL | asm!(\"{a}\", in(\"eax\") foo, a = const bar); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/x86_64_parse_error.rs:15:46 | LL | let mut bar = 0; | ----------- help: consider using `const` instead of `let`: `const bar` ... LL | asm!(\"{a}\", in(\"eax\") foo, a = const bar); | ^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/x86_64_parse_error.rs:17:42 | LL | let mut bar = 0; | ----------- help: consider using `const` instead of `let`: `const bar` ... LL | asm!(\"{1}\", in(\"eax\") foo, const bar); | ^^^ non-constant value error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0435`. "} {"_id":"doc-en-rust-2f41e0f9b6bcc7d3f2e8b489f59cac8279ec27e72e7d71691f4be3bdcb9435e2","title":"","text":"// They can denote both statically and dynamically-sized byte arrays. let mut pat_ty = ty; if let hir::ExprKind::Lit(Spanned { node: ast::LitKind::ByteStr(..), .. }) = lt.kind { if let ty::Ref(_, inner_ty, _) = *self.structurally_resolved_type(span, expected).kind() && self.structurally_resolved_type(span, inner_ty).is_slice() let expected = self.structurally_resolved_type(span, expected); if let ty::Ref(_, inner_ty, _) = expected.kind() && matches!(inner_ty.kind(), ty::Slice(_)) { let tcx = self.tcx; trace!(?lt.hir_id.local_id, \"polymorphic byte string lit\");"} {"_id":"doc-en-rust-142cbd2f441760273ac422bdd177f4553f113cdf8cdaf0c705fc1104388d6759","title":"","text":" // check-pass fn load() -> Option { todo!() } fn main() { while let Some(tag) = load() { match &tag { b\"NAME\" => {} b\"DATA\" => {} _ => {} } } } "} {"_id":"doc-en-rust-e05e3bbffe787a87195036424df449c0cf0e582aae929fc699d1dbb200a1e6d5","title":"","text":"// compile-flags: -Ztrait-solver=next // check-pass // known-bug: rust-lang/trait-system-refactor-initiative#38 fn test(s: &[u8]) { match &s[0..3] {"} {"_id":"doc-en-rust-91bed283a7f7c6b994b03f5ef924283ba06b1d3bd1c2f99eda093c1c127b8cf4","title":"","text":" error[E0271]: type mismatch resolving `[u8; 3] <: as SliceIndex<[u8]>>::Output` --> $DIR/slice-match-byte-lit.rs:6:9 | LL | match &s[0..3] { | -------- this expression has type `& as SliceIndex<[u8]>>::Output` LL | b\"uwu\" => {} | ^^^^^^ types differ error: aborting due to previous error For more information about this error, try `rustc --explain E0271`. "} {"_id":"doc-en-rust-8c479a4c09917f809cbd5a3a540d870cc8b715167694edc0e507d9be24cea44c","title":"","text":"map.insert(\"toggle-all-docs\".into(), 1); map.insert(\"all-types\".into(), 1); map.insert(\"default-settings\".into(), 1); map.insert(\"rustdoc-vars\".into(), 1); map.insert(\"sidebar-vars\".into(), 1); map.insert(\"copy-path\".into(), 1); map.insert(\"TOC\".into(), 1);"} {"_id":"doc-en-rust-b5d3a4a6b7c7d7ec5a14db675de6da88a9fc1dc7ead7f5c77262b65c7d74aec6","title":"","text":"// Local js definitions: /* global addClass, getCurrentValue, onEachLazy, removeClass, browserSupportsHistoryApi */ /* global updateLocalStorage */ /* global updateLocalStorage, getVar */ \"use strict\"; (function() { const rootPath = document.getElementById(\"rustdoc-vars\").attributes[\"data-root-path\"].value; const rootPath = getVar(\"root-path\"); const NAME_OFFSET = 0; const DIRS_OFFSET = 1;"} {"_id":"doc-en-rust-c06ba14ee1a944b3833eaba5064699bdc843a6b01b88b8dd70e43e75a3c09ead","title":"","text":"// Get a value from the rustdoc-vars div, which is used to convey data from // Rust to the JS. If there is no such element, return null. const getVar = (function getVar(name) { const el = document.getElementById(\"rustdoc-vars\"); const el = document.querySelector(\"head > meta[name='rustdoc-vars']\"); return el ? el.attributes[\"data-\" + name].value : null; });"} {"_id":"doc-en-rust-0ea4f05255ac7fe6d667f3e0b7cbd59d846133cd8f8294921739e541abd1f45f","title":"","text":"{% endfor %} > {# #} {% endif %}
data-root-path=\"{{page.root_path|safe}}\" {#+ #} data-static-root-path=\"{{static_root_path|safe}}\" {#+ #} data-current-crate=\"{{layout.krate}}\" {#+ #}"} {"_id":"doc-en-rust-20dac3b59d7f86f3532139724c41849ab43b263910a190e1fc52c5253e00be3d","title":"","text":"data-theme-dark-css=\"{{files.theme_dark_css}}\" {#+ #} data-theme-ayu-css=\"{{files.theme_ayu_css}}\" {#+ #} > {# #}
{# #}
{# #} {% if page.css_class.contains(\"crate\") %} {# #}"} {"_id":"doc-en-rust-05cd892ba60b1f11832b5d1c5dde7ee04a73830db942af14ac2b76a2817f9f85","title":"","text":"// @has test.css // @has foo/struct.Foo.html // @has - '//*[@id=\"rustdoc-vars\"]/@data-themes' 'test' // @has - '//*[@name=\"rustdoc-vars\"]/@data-themes' 'test' pub struct Foo;"} {"_id":"doc-en-rust-eeca7f90d0bc2f6877b0971e29d5a65c87965ef23e6947f804b63e5b9fde6007","title":"","text":" // check-pass trait A { type Assoc; } impl A for () { // FIXME: it would be nice for this to at least cause a warning. type Assoc = Foo<()>; } struct Foo(T::Assoc); fn main() {} "} {"_id":"doc-en-rust-0d17c7fc4003120bcddd6cd4874e3ddb2c64f7d01f73f3035710231cc83b7215","title":"","text":" // build-fail //~^ ERROR cycle detected when computing layout of `Foo<()>` trait A { type Assoc: ?Sized; } impl A for () { type Assoc = Foo<()>; } struct Foo(T::Assoc); fn main() { let x: Foo<()>; } "} {"_id":"doc-en-rust-3132e2360a27f590b1f71b3f3f0a13f32d71d228bffbd90258630104e449fd02","title":"","text":" error[E0391]: cycle detected when computing layout of `Foo<()>` | = note: ...which requires computing layout of `<() as A>::Assoc`... = note: ...which again requires computing layout of `Foo<()>`, completing the cycle note: cycle used when elaborating drops for `main` --> $DIR/recursive-type-2.rs:11:1 | LL | fn main() { | ^^^^^^^^^ = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0391`. "} {"_id":"doc-en-rust-1c180eb21c9cc904e549546dbdf4e3cfa1501db77373234791060dbaef5f85f8","title":"","text":" // build-fail //~^ ERROR cycle detected when computing layout of `Foo<()>` trait A { type Assoc: ?Sized; } impl A for () { type Assoc = Foo<()>; } struct Foo(T::Assoc); fn main() { let x: Foo<()>; } "} {"_id":"doc-en-rust-59f3f748345581d7128d177e2019bc90586d2ee25733ec49e1dcbfbe0c60d177","title":"","text":" error[E0391]: cycle detected when computing layout of `Foo<()>` | = note: ...which requires computing layout of `<() as A>::Assoc`... = note: ...which again requires computing layout of `Foo<()>`, completing the cycle note: cycle used when elaborating drops for `main` --> $DIR/recursive-type-binding.rs:11:1 | LL | fn main() { | ^^^^^^^^^ = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0391`. "} {"_id":"doc-en-rust-253cfb7485d347113a33a4bd420a98bedeb63d4a1a87b0f93c01b72427b35382","title":"","text":" // build-fail //~^ ERROR cycle detected when computing layout of `Foo<()>` // Regression test for a stack overflow: https://github.com/rust-lang/rust/issues/113197 trait A { type Assoc; } impl A for () { type Assoc = Foo<()>; } struct Foo(T::Assoc); fn main() { Foo::<()>(todo!()); } "} {"_id":"doc-en-rust-10845a2f849a19a1e502fc04ff4115ee63b29cb6b724476d6c8833e5b96d8c48","title":"","text":" error[E0391]: cycle detected when computing layout of `Foo<()>` | = note: ...which requires computing layout of `<() as A>::Assoc`... = note: ...which again requires computing layout of `Foo<()>`, completing the cycle note: cycle used when elaborating drops for `main` --> $DIR/recursive-type-coercion-from-never.rs:14:1 | LL | fn main() { | ^^^^^^^^^ = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0391`. "} {"_id":"doc-en-rust-6bf013b67a1d3fa963f37a24a9821ea3e16c70187052484bdbc9e5404463e0c3","title":"","text":" // check-pass trait A { type Assoc; } impl A for () { // FIXME: it would be nice for this to at least cause a warning. type Assoc = Foo<()>; } struct Foo(T::Assoc); fn main() {} "} {"_id":"doc-en-rust-78a4781a6c1ec37511f45a9601bd7595c174f7788ac327a8d6a48c84aba82916","title":"","text":"use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::def_id::DefId; use rustc_infer::traits::ObligationCauseCode; use rustc_infer::{infer::type_variable::TypeVariableOriginKind, traits::ObligationCauseCode}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor}; use rustc_span::{self, symbol::kw, Span}; use rustc_trait_selection::traits;"} {"_id":"doc-en-rust-31cba1ca9ed761aa60120b3465d8c25e493d7bed8d70b6e884ae475430a3e183","title":"","text":"type BreakTy = ty::GenericArg<'tcx>; fn visit_ty(&mut self, ty: Ty<'tcx>) -> std::ops::ControlFlow { if let Some(origin) = self.0.type_var_origin(ty) && let rustc_infer::infer::type_variable::TypeVariableOriginKind::TypeParameterDefinition(_, def_id) = origin.kind && let TypeVariableOriginKind::TypeParameterDefinition(_, def_id) = origin.kind && let generics = self.0.tcx.generics_of(self.1) && let Some(index) = generics.param_def_id_to_index(self.0.tcx, def_id) && let Some(subst) = ty::GenericArgs::identity_for_item(self.0.tcx, self.1)"} {"_id":"doc-en-rust-b03e9433d8e9c4dbe9fafd9445d6129dbc22743c9faca8b0da011582849610d4","title":"","text":"let ty_vars = infcx_inner.type_variables(); let var_origin = ty_vars.var_origin(ty_vid); if let TypeVariableOriginKind::TypeParameterDefinition(name, def_id) = var_origin.kind && !var_origin.span.from_expansion() && name != kw::SelfUpper && !var_origin.span.from_expansion() { let generics = infcx.tcx.generics_of(infcx.tcx.parent(def_id)); let idx = generics.param_def_id_to_index(infcx.tcx, def_id).unwrap();"} {"_id":"doc-en-rust-248ace96bd6c13f83effef13102a7a3065eb739910afae821d387e16b4e52dcf","title":"","text":"// If there is only one implementation of the trait, suggest using it. // Otherwise, use a placeholder comment for the implementation. let (message, impl_suggestion) = if non_blanket_impl_count == 1 {( \"use the fully-qualified path to the only available implementation\".to_string(), \"use the fully-qualified path to the only available implementation\", format!(\"<{} as \", self.tcx.type_of(impl_def_id).instantiate_identity()) )} else {( format!( \"use a fully-qualified path to a specific available implementation ({} found)\", non_blanket_impl_count ), \" )} else { (\"use a fully-qualified path to a specific available implementation\", \" )}; let mut suggestions = vec![( path.span.shrink_to_lo(),"} {"_id":"doc-en-rust-fc84c64b345d65452853f7fc59dbafeb2aa80cbf8adf15113b9f44a0575034f7","title":"","text":"LL | let cont: u32 = Generator::create(); | ^^^^^^^^^^^^^^^^^ cannot call associated function of trait | help: use a fully-qualified path to a specific available implementation (2 found) help: use a fully-qualified path to a specific available implementation | LL | let cont: u32 = ::create(); | +++++++++++++++++++ +"} {"_id":"doc-en-rust-aa2d41e11d8d37e43b1409cf6d0965e711944bca8f84a0fd529636b7a9bda7d4","title":"","text":"LL | MyTrait2::my_fn(); | ^^^^^^^^^^^^^^^ cannot call associated function of trait | help: use a fully-qualified path to a specific available implementation (2 found) help: use a fully-qualified path to a specific available implementation | LL | ::my_fn(); | +++++++++++++++++++ +"} {"_id":"doc-en-rust-1222dcf95217041e2d317b857acf9917726489938ee8f89da0723c74a8a6d64d","title":"","text":" // Regression test for #113610 where we ICEd when trying to print // inference variables created by instantiating the self type parameter. fn main() { let _ = (Default::default(),); //~^ ERROR cannot call associated function on trait } "} {"_id":"doc-en-rust-552d9a573c8ccd902aa67d284012e81602b6429cb0a9618eb006fb35264a58da","title":"","text":" error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type --> $DIR/infer-var-for-self-param.rs:5:14 | LL | let _ = (Default::default(),); | ^^^^^^^^^^^^^^^^ cannot call associated function of trait | help: use a fully-qualified path to a specific available implementation | LL | let _ = (::default(),); | +++++++++++++++++++ + error: aborting due to previous error For more information about this error, try `rustc --explain E0790`. "} {"_id":"doc-en-rust-1a71604bfd57d1faa92388168017a0cc276e044e362016071949636b49a601c1","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::io; use std::vec; pub struct Container<'a> { reader: &'a mut Reader //~ ERROR explicit lifetime bound required } impl<'a> Container<'a> { pub fn wrap<'s>(reader: &'s mut Reader) -> Container<'s> { Container { reader: reader } } pub fn read_to(&mut self, vec: &mut [u8]) { self.reader.read(vec); } } pub fn for_stdin<'a>() -> Container<'a> { let mut r = io::stdin(); Container::wrap(&mut r as &mut Reader) } fn main() { let mut c = for_stdin(); let mut v = vec::Vec::from_elem(10, 0u8); c.read_to(v.as_mut_slice()); } "} {"_id":"doc-en-rust-f6b8a865d478d697d0fe915083bcb9190b7a963854eca91dd247702e7429a4e8","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn blah() -> int { //~ ERROR not all control paths return a value 1i ; //~ NOTE consider removing this semicolon: } fn main() { } "} {"_id":"doc-en-rust-538ef0579806c1cd6cb4132aec4123ea6b80f2714da15bb250b2fbcc594e3780","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(struct_variant)] mod a { pub enum Enum { EnumStructVariant { x: u8, y: u8, z: u8 } } pub fn get_enum_struct_variant() -> () { EnumStructVariant { x: 1, y: 2, z: 3 } //~^ ERROR mismatched types: expected `()`, found `a::Enum` (expected (), found enum a::Enum) } } mod b { mod test { use a; fn test_enum_struct_variant() { let enum_struct_variant = ::a::get_enum_struct_variant(); match enum_struct_variant { a::EnumStructVariant { x, y, z } => { //~^ ERROR error: mismatched types: expected `()`, found a structure pattern } } } } } fn main() {} "} {"_id":"doc-en-rust-981b13079f89610cb3380d7510b27ea87becc9cffe9e97da3d35926af069623e","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let mut array = [1, 2, 3]; //~^ ERROR cannot determine a type for this local variable: cannot determine the type of this integ let pie_slice = array.slice(1, 2); } "} {"_id":"doc-en-rust-e4f0d7ab599171ebf7a247e1f6171be04c916806753bad3d3706cade46851d3d","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub fn foo(params: Option<&[&str]>) -> uint { params.unwrap().head().unwrap().len() } fn main() { let name = \"Foo\"; let msg = foo(Some(&[name.as_slice()])); //~^ ERROR mismatched types: expected `core::option::Option<&[&str]>` assert_eq!(msg, 3); } "} {"_id":"doc-en-rust-2030b41956f1ac39fb2b551ebc6c5c90f2952cc30e33b3eb995a31630c9caf97","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let v = &[]; //~ ERROR cannot determine a type for this local variable: unconstrained type let it = v.iter(); } "} {"_id":"doc-en-rust-235f3ce6fd3365a857a117f30c0a12690726a1aef3783508005c55dbc99fc383","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:explicit failure pub fn main() { fail!(); println!(\"{}\", 1i); } "} {"_id":"doc-en-rust-2ee95bfe2a013b85a0bbbacbb8d9f9be332f6959bab06d607257453a4d55ba31","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:bad input fn main() { Some(\"foo\").unwrap_or(fail!(\"bad input\")).to_string(); } "} {"_id":"doc-en-rust-e534b90f5239087cc5cbda64b706cf483c4d23cd3617a475aab1bfa016eff022","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub mod two_tuple { trait T {} struct P<'a>(&'a T + 'a, &'a T + 'a); pub fn f<'a>(car: &'a T, cdr: &'a T) -> P<'a> { P(car, cdr) } } pub mod two_fields { trait T {} struct P<'a> { car: &'a T + 'a, cdr: &'a T + 'a } pub fn f<'a>(car: &'a T, cdr: &'a T) -> P<'a> { P{ car: car, cdr: cdr } } } fn main() {} "} {"_id":"doc-en-rust-1bc6d485bcab4deadb19de23dd6f11a5c83c4318e84ec74712df47e324969d38","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { if true { proc(_) {} } else { proc(_: &mut ()) {} }; } "} {"_id":"doc-en-rust-c93742c01435b298dec3a3f4ffcb977ddf28d4046a7e9993eeceacfe5d3ceacd","title":"","text":"} _ => {} } // If someone calls a const fn, they can extract that call out into a separate constant (or a const // block in the future), so we check that to tell them that in the diagnostic. Does not affect typeck. let is_const_fn = match element.kind { // If someone calls a const fn or constructs a const value, they can extract that // out into a separate constant (or a const block in the future), so we check that // to tell them that in the diagnostic. Does not affect typeck. let is_constable = match element.kind { hir::ExprKind::Call(func, _args) => match *self.node_ty(func.hir_id).kind() { ty::FnDef(def_id, _) => tcx.is_const_fn(def_id), _ => false, ty::FnDef(def_id, _) if tcx.is_const_fn(def_id) => traits::IsConstable::Fn, _ => traits::IsConstable::No, }, _ => false, hir::ExprKind::Path(qpath) => { match self.typeck_results.borrow().qpath_res(&qpath, element.hir_id) { Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => traits::IsConstable::Ctor, _ => traits::IsConstable::No, } } _ => traits::IsConstable::No, }; // If the length is 0, we don't create any elements, so we don't copy any. If the length is 1, we // don't copy that one element, we move it. Only check for Copy if the length is larger. if count.try_eval_target_usize(tcx, self.param_env).map_or(true, |len| len > 1) { let lang_item = self.tcx.require_lang_item(LangItem::Copy, None); let code = traits::ObligationCauseCode::RepeatElementCopy { is_const_fn }; let code = traits::ObligationCauseCode::RepeatElementCopy { is_constable, elt_type: element_ty, elt_span: element.span, elt_stmt_span: self .tcx .hir() .parent_iter(element.hir_id) .find_map(|(_, node)| match node { hir::Node::Item(it) => Some(it.span), hir::Node::Stmt(stmt) => Some(stmt.span), _ => None, }) .expect(\"array repeat expressions must be inside an item or statement\"), }; self.require_type_meets(element_ty, element.span, code, lang_item); } }"} {"_id":"doc-en-rust-9a3d8af1526c29d904e9d018f4f90ec1ef41262e8457f48336314b97f6606120","title":"","text":"InlineAsmSized, /// `[expr; N]` requires `type_of(expr): Copy`. RepeatElementCopy { /// If element is a `const fn` we display a help message suggesting to move the /// function call to a new `const` item while saying that `T` doesn't implement `Copy`. is_const_fn: bool, /// If element is a `const fn` or const ctor we display a help message suggesting /// to move it to a new `const` item while saying that `T` doesn't implement `Copy`. is_constable: IsConstable, elt_type: Ty<'tcx>, elt_span: Span, /// Span of the statement/item in which the repeat expression occurs. We can use this to /// place a `const` declaration before it elt_stmt_span: Span, }, /// Types of fields (other than the last, except for packed structs) in a struct must be sized."} {"_id":"doc-en-rust-c8f096fe624823ffc5da71769dbca012ba890e15c37fea544213e2b0d2150df8","title":"","text":"TypeAlias(InternedObligationCauseCode<'tcx>, Span, DefId), } /// Whether a value can be extracted into a const. /// Used for diagnostics around array repeat expressions. #[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)] pub enum IsConstable { No, /// Call to a const fn Fn, /// Use of a const ctor Ctor, } crate::TrivialTypeTraversalAndLiftImpls! { IsConstable, } /// The 'location' at which we try to perform HIR-based wf checking. /// This information is used to obtain an `hir::Ty`, which /// we can walk in order to obtain precise spans for any"} {"_id":"doc-en-rust-d4fb988ffa9ab1a523ae801f87119fce0d38643641c1b5ba3be55d3afb810156","title":"","text":"use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{DefineOpaqueTypes, InferOk, LateBoundRegionConversionTime}; use rustc_middle::hir::map; use rustc_middle::traits::IsConstable; use rustc_middle::ty::error::TypeError::{self, Sorts}; use rustc_middle::ty::{ self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind,"} {"_id":"doc-en-rust-f0afcb08dbd6be256b094d8d512c8d07c51963425aefeaa69a959065e8c5dd43","title":"","text":")); } } ObligationCauseCode::RepeatElementCopy { is_const_fn } => { ObligationCauseCode::RepeatElementCopy { is_constable, elt_type, elt_span, elt_stmt_span } => { err.note( \"the `Copy` trait is required because this value will be copied for each element of the array\", ); if is_const_fn { err.help( \"consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position, like `const VAL: Type = const_fn();` and `let x = [VAL; 42];`\", ); let value_kind = match is_constable { IsConstable::Fn => Some(\"the result of the function call\"), IsConstable::Ctor => Some(\"the result of the constructor\"), _ => None }; let sm = tcx.sess.source_map(); if let Some(value_kind) = value_kind && let Ok(snip) = sm.span_to_snippet(elt_span) { let help_msg = format!( \"consider creating a new `const` item and initializing it with {value_kind} to be used in the repeat position\"); let indentation = sm.indentation_before(elt_stmt_span).unwrap_or_default(); err.multipart_suggestion(help_msg, vec![ (elt_stmt_span.shrink_to_lo(), format!(\"const ARRAY_REPEAT_VALUE: {elt_type} = {snip};n{indentation}\")), (elt_span, \"ARRAY_REPEAT_VALUE\".to_string()) ], Applicability::MachineApplicable); } if self.tcx.sess.is_nightly_build() && is_const_fn { if self.tcx.sess.is_nightly_build() && matches!(is_constable, IsConstable::Fn|IsConstable::Ctor) { err.help( \"create an inline `const` block, see RFC #2920 for more information\","} {"_id":"doc-en-rust-5734842eadc6031254eeeab93379eb5162f4632469c112b6cc976e9f2bb4bf1d","title":"","text":"| = note: required for `Option` to implement `Copy` = note: the `Copy` trait is required because this value will be copied for each element of the array = help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position, like `const VAL: Type = const_fn();` and `let x = [VAL; 42];` = help: create an inline `const` block, see RFC #2920 for more information help: consider annotating `Bar` with `#[derive(Copy)]` | LL + #[derive(Copy)] LL | struct Bar; | help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position | LL ~ const ARRAY_REPEAT_VALUE: Option = no_copy(); LL ~ let _: [Option; 2] = [ARRAY_REPEAT_VALUE; 2]; | error: aborting due to previous error"} {"_id":"doc-en-rust-806d3af03a5089fb114cd4fb06a0558ebe0784ea5214e16ca4c71b82a2c6e112","title":"","text":"LL | #[derive(Copy, Clone)] | ^^^^ unsatisfied trait bound introduced in this `derive` macro = note: the `Copy` trait is required because this value will be copied for each element of the array = help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position, like `const VAL: Type = const_fn();` and `let x = [VAL; 42];` = help: create an inline `const` block, see RFC #2920 for more information = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position | LL ~ const ARRAY_REPEAT_VALUE: Foo = Foo(String::new()); LL ~ [ARRAY_REPEAT_VALUE; 4]; | error: aborting due to previous error"} {"_id":"doc-en-rust-27abea0331d1e2ba5e33bd7275e4be14534f986024a69583d926a6426f652d7f","title":"","text":" static _MAYBE_STRINGS: [Option; 5] = [None; 5]; //~^ ERROR the trait bound `String: Copy` is not satisfied fn main() { // should hint to create an inline `const` block // or to create a new `const` item let strings: [String; 5] = [String::new(); 5]; let _strings: [String; 5] = [String::new(); 5]; //~^ ERROR the trait bound `String: Copy` is not satisfied let _maybe_strings: [Option; 5] = [None; 5]; //~^ ERROR the trait bound `String: Copy` is not satisfied println!(\"{:?}\", strings); }"} {"_id":"doc-en-rust-5c052349a2e92c0c9acd0909e17469e330fb2a98a19809c6c56ab69ee2ecff7a","title":"","text":"error[E0277]: the trait bound `String: Copy` is not satisfied --> $DIR/const-fn-in-vec.rs:4:33 --> $DIR/const-fn-in-vec.rs:1:47 | LL | let strings: [String; 5] = [String::new(); 5]; | ^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` LL | static _MAYBE_STRINGS: [Option; 5] = [None; 5]; | ^^^^ the trait `Copy` is not implemented for `String` | = note: required for `Option` to implement `Copy` = note: the `Copy` trait is required because this value will be copied for each element of the array = help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position, like `const VAL: Type = const_fn();` and `let x = [VAL; 42];` = help: create an inline `const` block, see RFC #2920 for more information help: consider creating a new `const` item and initializing it with the result of the constructor to be used in the repeat position | LL + const ARRAY_REPEAT_VALUE: Option = None; LL ~ static _MAYBE_STRINGS: [Option; 5] = [ARRAY_REPEAT_VALUE; 5]; | error[E0277]: the trait bound `String: Copy` is not satisfied --> $DIR/const-fn-in-vec.rs:7:34 | LL | let _strings: [String; 5] = [String::new(); 5]; | ^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` | = note: the `Copy` trait is required because this value will be copied for each element of the array = help: create an inline `const` block, see RFC #2920 for more information help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position | LL ~ const ARRAY_REPEAT_VALUE: String = String::new(); LL ~ let _strings: [String; 5] = [ARRAY_REPEAT_VALUE; 5]; | error[E0277]: the trait bound `String: Copy` is not satisfied --> $DIR/const-fn-in-vec.rs:9:48 | LL | let _maybe_strings: [Option; 5] = [None; 5]; | ^^^^ the trait `Copy` is not implemented for `String` | = note: required for `Option` to implement `Copy` = note: the `Copy` trait is required because this value will be copied for each element of the array = help: create an inline `const` block, see RFC #2920 for more information help: consider creating a new `const` item and initializing it with the result of the constructor to be used in the repeat position | LL ~ const ARRAY_REPEAT_VALUE: Option = None; LL ~ let _maybe_strings: [Option; 5] = [ARRAY_REPEAT_VALUE; 5]; | error: aborting due to previous error error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0277`."} {"_id":"doc-en-rust-82eabd628763e723df50670a2ec39413433bece53c32d8f79d85d9da977cfa46","title":"","text":"Self::new(List::empty(), self.reveal()) } /// Creates a suitable environment in which to perform trait /// queries on the given value. When type-checking, this is simply /// the pair of the environment plus value. But when reveal is set to /// All, then if `value` does not reference any type parameters, we will /// pair it with the empty environment. This improves caching and is generally /// invisible. /// /// N.B., we preserve the environment when type-checking because it /// is possible for the user to have wacky where-clauses like /// `where Box: Copy`, which are clearly never /// satisfiable. We generally want to behave as if they were true, /// although the surrounding function is never reachable. /// Creates a pair of param-env and value for use in queries. pub fn and>>(self, value: T) -> ParamEnvAnd<'tcx, T> { match self.reveal() { Reveal::UserFacing => ParamEnvAnd { param_env: self, value }, Reveal::All => { if value.is_global() { ParamEnvAnd { param_env: self.without_caller_bounds(), value } } else { ParamEnvAnd { param_env: self, value } } } } ParamEnvAnd { param_env: self, value } } }"} {"_id":"doc-en-rust-ef9c287087cf398f2947c82541b471e3a29a2bbb9d6a8ed60328ecf2376b93a2","title":"","text":" // check-pass trait Bar<'a> { type Assoc: 'static; } impl<'a> Bar<'a> for () { type Assoc = (); } struct ImplsStatic> { d: &'static >::Assoc, } fn caller(b: ImplsStatic<()>) where for<'a> (): Bar<'a> { let _: &<() as Bar<'static>>::Assoc = b.d; } fn main() {} "} {"_id":"doc-en-rust-9d4430bf2753594014c0d728d5d72febecc437fe2c9ff6e44ec6516785894acf","title":"","text":"fn __rust_alloc_error_handler(size: usize, align: usize) -> !; } /// Abort on memory allocation error or failure. /// Signal a memory allocation error. /// /// Callers of memory allocation APIs wishing to abort computation /// Callers of memory allocation APIs wishing to cease execution /// in response to an allocation error are encouraged to call this function, /// rather than directly invoking `panic!` or similar. /// rather than directly invoking [`panic!`] or similar. /// /// The default behavior of this function is to print a message to standard error /// and abort the process. /// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`]. /// This function is guaranteed to diverge (not return normally with a value), but depending on /// global configuration, it may either panic (resulting in unwinding or aborting as per /// configuration for all panics), or abort the process (with no unwinding). /// /// The default behavior is: /// /// * If the binary links against `std` (typically the case), then /// print a message to standard error and abort the process. /// This behavior can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`]. /// Future versions of Rust may panic by default instead. /// /// * If the binary does not link against `std` (all of its crates are marked /// [`#![no_std]`][no_std]), then call [`panic!`] with a message. /// [The panic handler] applies as to any panic. /// /// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html /// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html /// [The panic handler]: https://doc.rust-lang.org/reference/runtime.html#the-panic_handler-attribute /// [no_std]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute #[stable(feature = \"global_alloc\", since = \"1.28.0\")] #[rustc_const_unstable(feature = \"const_alloc_error\", issue = \"92523\")] #[cfg(all(not(no_global_oom_handling), not(test)))]"} {"_id":"doc-en-rust-ea07229a1bed53c64429eb502733fe6943f02340db0c72d468e8bd5e30970641","title":"","text":"/// Registers a custom allocation error hook, replacing any that was previously registered. /// /// The allocation error hook is invoked when an infallible memory allocation fails, before /// the runtime aborts. The default hook prints a message to standard error, /// but this behavior can be customized with the [`set_alloc_error_hook`] and /// [`take_alloc_error_hook`] functions. /// The allocation error hook is invoked when an infallible memory allocation fails — that is, /// as a consequence of calling [`handle_alloc_error`] — before the runtime aborts. /// /// The hook is provided with a `Layout` struct which contains information /// The allocation error hook is a global resource. [`take_alloc_error_hook`] may be used to /// retrieve a previously registered hook and wrap or discard it. /// /// # What the provided `hook` function should expect /// /// The hook function is provided with a [`Layout`] struct which contains information /// about the allocation that failed. /// /// The allocation error hook is a global resource. /// The hook function may choose to panic or abort; in the event that it returns normally, this /// will cause an immediate abort. /// /// Since [`take_alloc_error_hook`] is a safe function that allows retrieving the hook, the hook /// function must be _sound_ to call even if no memory allocations were attempted. /// /// # The default hook /// /// The default hook, used if [`set_alloc_error_hook`] is never called, prints a message to /// standard error (and then returns, causing the runtime to abort the process). /// Compiler options may cause it to panic instead, and the default behavior may be changed /// to panicking in future versions of Rust. /// /// # Examples ///"} {"_id":"doc-en-rust-dd656af25f8f6efab1101dc63cd98c745966da1eb0687b717cc12f32c95b46ee","title":"","text":"tracked!(profile_emit, Some(PathBuf::from(\"abc\"))); tracked!(profile_sample_use, Some(PathBuf::from(\"abc\"))); tracked!(profiler_runtime, \"abc\".to_string()); tracked!(relax_elf_relocations, Some(false)); tracked!(relax_elf_relocations, Some(true)); tracked!(relro_level, Some(RelroLevel::Full)); tracked!(remap_cwd_prefix, Some(PathBuf::from(\"abc\"))); tracked!(report_delayed_bugs, true);"} {"_id":"doc-en-rust-3b1cb4d233d51fc4b4c066163eb945442ed0c37f6a7a23c5a1f983822ef1efee","title":"","text":"mcount: \"mcount\".into(), llvm_mcount_intrinsic: None, llvm_abiname: \"\".into(), relax_elf_relocations: true, relax_elf_relocations: false, llvm_args: cvs![], use_ctors_section: false, eh_frame_header: true,"} {"_id":"doc-en-rust-4d57be745f2b6b368b9df3cb5aef28aec593c979e06d0406e7abe74370550183","title":"","text":"position_independent_executables: true, pre_link_args, override_export_symbols: Some(EXPORT_SYMBOLS.iter().cloned().map(Cow::from).collect()), relax_elf_relocations: true, ..Default::default() }; Target {"} {"_id":"doc-en-rust-df6d743449cc237b201d3f1c38bd8f1e056559596ec3d364cdd0f9d07df96802","title":"","text":"let mut fmt = Cow::Borrowed(fmt); if self.tcx.sess.opts.unstable_opts.flatten_format_args { fmt = flatten_format_args(fmt); fmt = inline_literals(fmt); fmt = self.inline_literals(fmt); } expand_format_args(self, sp, &fmt, allow_const) } /// Try to convert a literal into an interned string fn try_inline_lit(&self, lit: token::Lit) -> Option { match LitKind::from_token_lit(lit) { Ok(LitKind::Str(s, _)) => Some(s), Ok(LitKind::Int(n, ty)) => { match ty { // unsuffixed integer literals are assumed to be i32's LitIntType::Unsuffixed => { (n <= i32::MAX as u128).then_some(Symbol::intern(&n.to_string())) } LitIntType::Signed(int_ty) => { let max_literal = self.int_ty_max(int_ty); (n <= max_literal).then_some(Symbol::intern(&n.to_string())) } LitIntType::Unsigned(uint_ty) => { let max_literal = self.uint_ty_max(uint_ty); (n <= max_literal).then_some(Symbol::intern(&n.to_string())) } } } _ => None, } } /// Get the maximum value of int_ty. It is platform-dependent due to the byte size of isize fn int_ty_max(&self, int_ty: IntTy) -> u128 { match int_ty { IntTy::Isize => self.tcx.data_layout.pointer_size.signed_int_max() as u128, IntTy::I8 => i8::MAX as u128, IntTy::I16 => i16::MAX as u128, IntTy::I32 => i32::MAX as u128, IntTy::I64 => i64::MAX as u128, IntTy::I128 => i128::MAX as u128, } } /// Get the maximum value of uint_ty. It is platform-dependent due to the byte size of usize fn uint_ty_max(&self, uint_ty: UintTy) -> u128 { match uint_ty { UintTy::Usize => self.tcx.data_layout.pointer_size.unsigned_int_max(), UintTy::U8 => u8::MAX as u128, UintTy::U16 => u16::MAX as u128, UintTy::U32 => u32::MAX as u128, UintTy::U64 => u64::MAX as u128, UintTy::U128 => u128::MAX as u128, } } /// Inline literals into the format string. /// /// Turns /// /// `format_args!(\"Hello, {}! {} {}\", \"World\", 123, x)` /// /// into /// /// `format_args!(\"Hello, World! 123 {}\", x)`. fn inline_literals<'fmt>(&self, mut fmt: Cow<'fmt, FormatArgs>) -> Cow<'fmt, FormatArgs> { let mut was_inlined = vec![false; fmt.arguments.all_args().len()]; let mut inlined_anything = false; for i in 0..fmt.template.len() { let FormatArgsPiece::Placeholder(placeholder) = &fmt.template[i] else { continue }; let Ok(arg_index) = placeholder.argument.index else { continue }; let mut literal = None; if let FormatTrait::Display = placeholder.format_trait && placeholder.format_options == Default::default() && let arg = fmt.arguments.all_args()[arg_index].expr.peel_parens_and_refs() && let ExprKind::Lit(lit) = arg.kind { literal = self.try_inline_lit(lit); } if let Some(literal) = literal { // Now we need to mutate the outer FormatArgs. // If this is the first time, this clones the outer FormatArgs. let fmt = fmt.to_mut(); // Replace the placeholder with the literal. fmt.template[i] = FormatArgsPiece::Literal(literal); was_inlined[arg_index] = true; inlined_anything = true; } } // Remove the arguments that were inlined. if inlined_anything { let fmt = fmt.to_mut(); let mut remove = was_inlined; // Don't remove anything that's still used. for_all_argument_indexes(&mut fmt.template, |index| remove[*index] = false); // Drop all the arguments that are marked for removal. let mut remove_it = remove.iter(); fmt.arguments.all_args_mut().retain(|_| remove_it.next() != Some(&true)); // Calculate the mapping of old to new indexes for the remaining arguments. let index_map: Vec = remove .into_iter() .scan(0, |i, remove| { let mapped = *i; *i += !remove as usize; Some(mapped) }) .collect(); // Correct the indexes that refer to arguments that have shifted position. for_all_argument_indexes(&mut fmt.template, |index| *index = index_map[*index]); } fmt } } /// Flattens nested `format_args!()` into one."} {"_id":"doc-en-rust-dde05bef626a8be46a256710a3ff6421d26b190f56809b53e0b7f3b287a6a878","title":"","text":"fmt } /// Inline literals into the format string. /// /// Turns /// /// `format_args!(\"Hello, {}! {} {}\", \"World\", 123, x)` /// /// into /// /// `format_args!(\"Hello, World! 123 {}\", x)`. fn inline_literals(mut fmt: Cow<'_, FormatArgs>) -> Cow<'_, FormatArgs> { let mut was_inlined = vec![false; fmt.arguments.all_args().len()]; let mut inlined_anything = false; for i in 0..fmt.template.len() { let FormatArgsPiece::Placeholder(placeholder) = &fmt.template[i] else { continue }; let Ok(arg_index) = placeholder.argument.index else { continue }; let mut literal = None; if let FormatTrait::Display = placeholder.format_trait && placeholder.format_options == Default::default() && let arg = fmt.arguments.all_args()[arg_index].expr.peel_parens_and_refs() && let ExprKind::Lit(lit) = arg.kind { if let token::LitKind::Str | token::LitKind::StrRaw(_) = lit.kind && let Ok(LitKind::Str(s, _)) = LitKind::from_token_lit(lit) { literal = Some(s); } else if let token::LitKind::Integer = lit.kind && let Ok(LitKind::Int(n, _)) = LitKind::from_token_lit(lit) { literal = Some(Symbol::intern(&n.to_string())); } } if let Some(literal) = literal { // Now we need to mutate the outer FormatArgs. // If this is the first time, this clones the outer FormatArgs. let fmt = fmt.to_mut(); // Replace the placeholder with the literal. fmt.template[i] = FormatArgsPiece::Literal(literal); was_inlined[arg_index] = true; inlined_anything = true; } } // Remove the arguments that were inlined. if inlined_anything { let fmt = fmt.to_mut(); let mut remove = was_inlined; // Don't remove anything that's still used. for_all_argument_indexes(&mut fmt.template, |index| remove[*index] = false); // Drop all the arguments that are marked for removal. let mut remove_it = remove.iter(); fmt.arguments.all_args_mut().retain(|_| remove_it.next() != Some(&true)); // Calculate the mapping of old to new indexes for the remaining arguments. let index_map: Vec = remove .into_iter() .scan(0, |i, remove| { let mapped = *i; *i += !remove as usize; Some(mapped) }) .collect(); // Correct the indexes that refer to arguments that have shifted position. for_all_argument_indexes(&mut fmt.template, |index| *index = index_map[*index]); } fmt } #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] enum ArgumentType { Format(FormatTrait),"} {"_id":"doc-en-rust-48d5a5f29c47369b5e71545a0c300ee07728afa651ed14ae67987a7eb5867e4d","title":"","text":" //@ only-64bit fn main() { format_args!(\"{}\", 0x8f_i8); // issue #115423 //~^ ERROR literal out of range for `i8` format_args!(\"{}\", 0xffff_ffff_u8); // issue #116633 //~^ ERROR literal out of range for `u8` format_args!(\"{}\", 0xffff_ffff_ffff_ffff_ffff_usize); //~^ ERROR literal out of range for `usize` format_args!(\"{}\", 0x8000_0000_0000_0000_isize); //~^ ERROR literal out of range for `isize` format_args!(\"{}\", 0xffff_ffff); // treat unsuffixed literals as i32 //~^ ERROR literal out of range for `i32` } "} {"_id":"doc-en-rust-0910f9d81db3b3a4e4c65637547e0a55e2ba799a39e73827c47a994116558716","title":"","text":" error: literal out of range for `i8` --> $DIR/no-inline-literals-out-of-range.rs:4:24 | LL | format_args!(\"{}\", 0x8f_i8); // issue #115423 | ^^^^^^^ | = note: the literal `0x8f_i8` (decimal `143`) does not fit into the type `i8` and will become `-113i8` = note: `#[deny(overflowing_literals)]` on by default help: consider using the type `u8` instead | LL | format_args!(\"{}\", 0x8f_u8); // issue #115423 | ~~~~~~~ help: to use as a negative number (decimal `-113`), consider using the type `u8` for the literal and cast it to `i8` | LL | format_args!(\"{}\", 0x8f_u8 as i8); // issue #115423 | ~~~~~~~~~~~~~ error: literal out of range for `u8` --> $DIR/no-inline-literals-out-of-range.rs:6:24 | LL | format_args!(\"{}\", 0xffff_ffff_u8); // issue #116633 | ^^^^^^^^^^^^^^ help: consider using the type `u32` instead: `0xffff_ffff_u32` | = note: the literal `0xffff_ffff_u8` (decimal `4294967295`) does not fit into the type `u8` and will become `255u8` error: literal out of range for `usize` --> $DIR/no-inline-literals-out-of-range.rs:8:24 | LL | format_args!(\"{}\", 0xffff_ffff_ffff_ffff_ffff_usize); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the literal `0xffff_ffff_ffff_ffff_ffff_usize` (decimal `1208925819614629174706175`) does not fit into the type `usize` and will become `18446744073709551615usize` error: literal out of range for `isize` --> $DIR/no-inline-literals-out-of-range.rs:10:24 | LL | format_args!(\"{}\", 0x8000_0000_0000_0000_isize); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the literal `0x8000_0000_0000_0000_isize` (decimal `9223372036854775808`) does not fit into the type `isize` and will become `-9223372036854775808isize` error: literal out of range for `i32` --> $DIR/no-inline-literals-out-of-range.rs:12:24 | LL | format_args!(\"{}\", 0xffff_ffff); // treat unsuffixed literals as i32 | ^^^^^^^^^^^ | = note: the literal `0xffff_ffff` (decimal `4294967295`) does not fit into the type `i32` and will become `-1i32` = help: consider using the type `u32` instead help: to use as a negative number (decimal `-1`), consider using the type `u32` for the literal and cast it to `i32` | LL | format_args!(\"{}\", 0xffff_ffffu32 as i32); // treat unsuffixed literals as i32 | ~~~~~~~~~~~~~~~~~~~~~ error: aborting due to 5 previous errors "} {"_id":"doc-en-rust-e56362c2e37cd70fd9fdfc0b804f979a1d9f527b53f632dfee04ee63d1848979","title":"","text":"n /= 10; exponent += 1; } let (added_precision, subtracted_precision) = match f.precision() { Some(fmt_prec) => { // number of decimal digits minus 1"} {"_id":"doc-en-rust-f758eea2d4b3e19deb32760bcc74399c3a3e54e6b57558431a7cab41c53b1e0b","title":"","text":"let rem = n % 10; n /= 10; exponent += 1; // round up last digit if rem >= 5 { // round up last digit, round to even on a tie if rem > 5 || (rem == 5 && (n % 2 != 0 || subtracted_precision > 1 )) { n += 1; // if the digit is rounded to the next power // instead adjust the exponent if n.ilog10() > (n - 1).ilog10() { n /= 10; exponent += 1; } } } (n, exponent, exponent, added_precision)"} {"_id":"doc-en-rust-db3504f6ad791d9bb3fb560c9d567ada57b77faca802ba2ce961f4af1dd51246","title":"","text":"let big_int: u32 = 314_159_265; assert_eq!(format!(\"{big_int:.1e}\"), format!(\"{:.1e}\", f64::from(big_int))); //test adding precision // test adding precision assert_eq!(format!(\"{:.10e}\", i8::MIN), \"-1.2800000000e2\"); assert_eq!(format!(\"{:.10e}\", i16::MIN), \"-3.2768000000e4\"); assert_eq!(format!(\"{:.10e}\", i32::MIN), \"-2.1474836480e9\"); assert_eq!(format!(\"{:.20e}\", i64::MIN), \"-9.22337203685477580800e18\"); assert_eq!(format!(\"{:.40e}\", i128::MIN), \"-1.7014118346046923173168730371588410572800e38\"); //test rounding // test rounding assert_eq!(format!(\"{:.1e}\", i8::MIN), \"-1.3e2\"); assert_eq!(format!(\"{:.1e}\", i16::MIN), \"-3.3e4\"); assert_eq!(format!(\"{:.1e}\", i32::MIN), \"-2.1e9\"); assert_eq!(format!(\"{:.1e}\", i64::MIN), \"-9.2e18\"); assert_eq!(format!(\"{:.1e}\", i128::MIN), \"-1.7e38\"); //test huge precision // test huge precision assert_eq!(format!(\"{:.1000e}\", 1), format!(\"1.{}e0\", \"0\".repeat(1000))); //test zero precision assert_eq!(format!(\"{:.0e}\", 1), format!(\"1e0\",)); assert_eq!(format!(\"{:.0e}\", 35), format!(\"4e1\",)); //test padding with precision (and sign) // test padding with precision (and sign) assert_eq!(format!(\"{:+10.3e}\", 1), \" +1.000e0\"); // test precision remains correct when rounding to next power for i in i16::MIN..=i16::MAX { for p in 0..=5 { assert_eq!( format!(\"{i:.p$e}\"), format!(\"{:.p$e}\", f32::from(i)), \"integer {i} at precision {p}\" ); } } } #[test]"} {"_id":"doc-en-rust-9c2c09d56283577c9fb073afe9d8c6b312113e3dd9f1e7b17c165470daeb0ed0","title":"","text":"#[cfg(unix)] use crate::os::unix::fs::symlink as symlink_junction; #[cfg(windows)] use crate::os::windows::fs::{symlink_dir, symlink_file}; use crate::os::windows::fs::{symlink_dir, symlink_file, OpenOptionsExt}; #[cfg(windows)] use crate::sys::fs::symlink_junction; #[cfg(target_os = \"macos\")]"} {"_id":"doc-en-rust-3d79a8a98cd89cdd92f72ab53d708b249b8570c279d90d858ba075e5798578e5","title":"","text":"assert_eq!(socket_path.try_exists().unwrap(), true); assert_eq!(socket_path.metadata().is_ok(), true); } #[cfg(windows)] #[test] fn test_hidden_file_truncation() { // Make sure that File::create works on an existing hidden file. See #115745. let tmpdir = tmpdir(); let path = tmpdir.join(\"hidden_file.txt\"); // Create a hidden file. const FILE_ATTRIBUTE_HIDDEN: u32 = 2; let mut file = OpenOptions::new() .write(true) .create_new(true) .attributes(FILE_ATTRIBUTE_HIDDEN) .open(&path) .unwrap(); file.write(\"hidden world!\".as_bytes()).unwrap(); file.flush().unwrap(); drop(file); // Create a new file by truncating the existing one. let file = File::create(&path).unwrap(); let metadata = file.metadata().unwrap(); assert_eq!(metadata.len(), 0); } "} {"_id":"doc-en-rust-95afbe1301b98e9d0d22608de847a50dc25b7647e44c022ab44dea856635ecef","title":"","text":"Windows.Win32.Storage.FileSystem.FILE_ADD_FILE Windows.Win32.Storage.FileSystem.FILE_ADD_SUBDIRECTORY Windows.Win32.Storage.FileSystem.FILE_ALL_ACCESS Windows.Win32.Storage.FileSystem.FILE_ALLOCATION_INFO Windows.Win32.Storage.FileSystem.FILE_APPEND_DATA Windows.Win32.Storage.FileSystem.FILE_ATTRIBUTE_ARCHIVE Windows.Win32.Storage.FileSystem.FILE_ATTRIBUTE_COMPRESSED"} {"_id":"doc-en-rust-133535c41c73025975add07868c17349b237e5690e3c94db833856cdf30dd296","title":"","text":"pub type FILE_ACCESS_RIGHTS = u32; pub const FILE_ADD_FILE: FILE_ACCESS_RIGHTS = 2u32; pub const FILE_ADD_SUBDIRECTORY: FILE_ACCESS_RIGHTS = 4u32; #[repr(C)] pub struct FILE_ALLOCATION_INFO { pub AllocationSize: i64, } impl ::core::marker::Copy for FILE_ALLOCATION_INFO {} impl ::core::clone::Clone for FILE_ALLOCATION_INFO { fn clone(&self) -> Self { *self } } pub const FILE_ALL_ACCESS: FILE_ACCESS_RIGHTS = 2032127u32; pub const FILE_APPEND_DATA: FILE_ACCESS_RIGHTS = 4u32; pub const FILE_ATTRIBUTE_ARCHIVE: FILE_FLAGS_AND_ATTRIBUTES = 32u32;"} {"_id":"doc-en-rust-d33991e131441035ed6f6e9fd95903a57a197474af116e18d64472f78c277165","title":"","text":"use crate::os::windows::prelude::*; use crate::borrow::Cow; use crate::ffi::OsString; use crate::ffi::{c_void, OsString}; use crate::fmt; use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom}; use crate::mem::{self, MaybeUninit};"} {"_id":"doc-en-rust-4aa5a3ed554d23c6a3fb8b9b3d94fd83cd19275cedcb81e116ec3b4d0681f06b","title":"","text":"use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::thread; use core::ffi::c_void; use super::path::maybe_verbatim; use super::to_u16s;"} {"_id":"doc-en-rust-18dbf2cd728f93d92f7cf958e5fc2c067fbf169bcf8b3302a7ad0b39bc12d913","title":"","text":"(false, false, false) => c::OPEN_EXISTING, (true, false, false) => c::OPEN_ALWAYS, (false, true, false) => c::TRUNCATE_EXISTING, (true, true, false) => c::CREATE_ALWAYS, // `CREATE_ALWAYS` has weird semantics so we emulate it using // `OPEN_ALWAYS` and a manual truncation step. See #115745. (true, true, false) => c::OPEN_ALWAYS, (_, _, true) => c::CREATE_NEW, }) }"} {"_id":"doc-en-rust-f2721093cc1431b08f9fea4449cbfad92775a8b1c181899015ab38dbbf4152bf","title":"","text":"impl File { pub fn open(path: &Path, opts: &OpenOptions) -> io::Result { let path = maybe_verbatim(path)?; let creation = opts.get_creation_mode()?; let handle = unsafe { c::CreateFileW( path.as_ptr(), opts.get_access_mode()?, opts.share_mode, opts.security_attributes, opts.get_creation_mode()?, creation, opts.get_flags_and_attributes(), ptr::null_mut(), ) }; let handle = unsafe { HandleOrInvalid::from_raw_handle(handle) }; if let Ok(handle) = handle.try_into() { if let Ok(handle) = OwnedHandle::try_from(handle) { // Manual truncation. See #115745. if opts.truncate && creation == c::OPEN_ALWAYS && unsafe { c::GetLastError() } == c::ERROR_ALREADY_EXISTS { unsafe { // Setting the allocation size to zero also sets the // EOF position to zero. let alloc = c::FILE_ALLOCATION_INFO { AllocationSize: 0 }; let result = c::SetFileInformationByHandle( handle.as_raw_handle(), c::FileAllocationInfo, ptr::addr_of!(alloc).cast::(), mem::size_of::() as u32, ); if result == 0 { return Err(io::Error::last_os_error()); } } } Ok(File { handle: Handle::from_inner(handle) }) } else { Err(Error::last_os_error())"} {"_id":"doc-en-rust-9ce8ca936cc8555b3a969f6c82590cd35fb8d9858a94e62042df0dfdf119a161","title":"","text":"/// Shortens the deque, keeping the first `len` elements and dropping /// the rest. /// /// If `len` is greater than the deque's current length, this has no /// effect. /// If `len` is greater or equal to the deque's current length, this has /// no effect. /// /// # Examples ///"} {"_id":"doc-en-rust-8019ee8f3d58b8ad28f072ee05cb8c64b251653e2aca358bd214d23365025260","title":"","text":"/// Shortens the vector, keeping the first `len` elements and dropping /// the rest. /// /// If `len` is greater than the vector's current length, this has no /// effect. /// If `len` is greater or equal to the vector's current length, this has /// no effect. /// /// The [`drain`] method can emulate `truncate`, but causes the excess /// elements to be returned instead of dropped."} {"_id":"doc-en-rust-5fecf9433d05d9962bce9576258953d2c96bc0fc74f349b76f4443f5ecfc5e67","title":"","text":"if libc::sched_getaffinity(0, mem::size_of::(), &mut set) == 0 { let count = libc::CPU_COUNT(&set) as usize; let count = count.min(quota); // SAFETY: affinity mask can't be empty and the quota gets clamped to a minimum of 1 return Ok(NonZeroUsize::new_unchecked(count)); // reported to occur on MIPS kernels older than our minimum supported kernel version for those targets let count = NonZeroUsize::new(count) .expect(\"CPU count must be > 0. This may be a bug in sched_getaffinity(); try upgrading the kernel.\"); return Ok(count); } } }"} {"_id":"doc-en-rust-aeed0c381498b959095585a70d9ba27b1b9c203c46d10041bc0585a3296b8aba","title":"","text":"let reachable_context = ReachableContext::new(tcx, method_map); // Step 1: Seed the worklist with all nodes which were found to be public as // a result of the privacy pass // a result of the privacy pass along with all local lang items. If // other crates link to us, they're going to expect to be able to // use the lang items, so we need to be sure to mark them as // exported. let mut worklist = reachable_context.worklist.borrow_mut(); for &id in exported_items.iter() { let mut worklist = reachable_context.worklist.borrow_mut(); worklist.get().push(id); } for (_, item) in tcx.lang_items.items() { match *item { Some(did) if is_local(did) => { worklist.get().push(did.node); } _ => {} } } drop(worklist); // Step 2: Mark all symbols that the symbols on the worklist touch. reachable_context.propagate();"} {"_id":"doc-en-rust-aab38e0550574c4df03d94a174dea38e54e8a22b13b25fbca201646f55372e83","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[no_std]; #[lang=\"fail_\"] fn fail(_: *i8, _: *i8, _: uint) -> ! { loop {} } #[no_mangle] pub extern \"C\" fn rust_stack_exhausted() {} "} {"_id":"doc-en-rust-877c58cebcc1e0e81d2c85110ec40005de6f5b7410193a93bd3ea90de68d6bd5","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:lang-item-public.rs // ignore-fast // ignore-android #[no_std]; extern crate lang_lib = \"lang-item-public\"; #[cfg(target_os = \"linux\")] #[link(name = \"c\")] extern {} #[cfg(target_os = \"android\")] #[link(name = \"c\")] extern {} #[cfg(target_os = \"freebsd\")] #[link(name = \"execinfo\")] extern {} #[cfg(target_os = \"macos\")] #[link(name = \"System\")] extern {} #[start] fn main(_: int, _: **u8) -> int { 1 % 1 } "} {"_id":"doc-en-rust-368fb706c156a79d18130d9e873e6fa7c1ed3385c03d278411962c767101e893","title":"","text":"/// surprising results upon inspecting the bit patterns, /// as the same calculations might produce NaNs with different bit patterns. /// /// When the number resulting from a primitive operation (addition, /// subtraction, multiplication, or division) on this type is not exactly /// representable as `f32`, it is rounded according to the roundTiesToEven /// direction defined in IEEE 754-2008. That means: /// When a primitive operation (addition, subtraction, multiplication, or /// division) is performed on this type, the result is rounded according to the /// roundTiesToEven direction defined in IEEE 754-2008. That means: /// /// - The result is the representable value closest to the true value, if there /// is a unique closest representable value."} {"_id":"doc-en-rust-05d276cf5287060c1a976440fb7fca5330afe7167ddb22e802e99d730e57be3e","title":"","text":"/// - If the true value's magnitude is ≥ `f32::MAX` + 2(`f32::MAX_EXP` − /// `f32::MANTISSA_DIGITS` − 1), the result is ∞ or −∞ (preserving the /// true value's sign). /// - If the result of a sum exactly equals zero, the outcome is +0.0 unless /// both arguments were negative, then it is -0.0. Subtraction `a - b` is /// regarded as a sum `a + (-b)`. /// /// For more information on floating point numbers, see [Wikipedia][wikipedia]. ///"} {"_id":"doc-en-rust-60313d80c351967ab2138ae60f1140f51e4933a67ee7d518e3ca69b06cffb667","title":"","text":"use cell::RefCell; use intrinsics; use sync::StaticRwLock; use sync::atomic::{AtomicBool, Ordering}; use sys::stdio::Stderr; use sys_common::backtrace; use sys_common::thread_info;"} {"_id":"doc-en-rust-ace591ee3de0d44ed13c372daf74f7154ef99bf8cb95e246631bbc25ee8c4709","title":"","text":"static HANDLER_LOCK: StaticRwLock = StaticRwLock::new(); static mut HANDLER: Handler = Handler::Default; static FIRST_PANIC: AtomicBool = AtomicBool::new(true); /// Registers a custom panic handler, replacing any that was previously /// registered."} {"_id":"doc-en-rust-587c5c7daddee22927905a69b93561408a4a64dda95a385ead57675a4aa61b4c","title":"","text":"let write = |err: &mut ::io::Write| { let _ = writeln!(err, \"thread '{}' panicked at '{}', {}:{}\", name, msg, file, line); if log_backtrace { let _ = backtrace::write(err); } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) { let _ = writeln!(err, \"note: Run with `RUST_BACKTRACE=1` for a backtrace.\"); } };"} {"_id":"doc-en-rust-f49448b36b9dfae7b46c9bfe2983da0e3ab23c1d8d95cf968fee36768e743a3e","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let args: Vec = std::env::args().collect(); if args.len() > 1 && args[1] == \"run_test\" { let _ = std::thread::spawn(|| { panic!(); }).join(); panic!(); } else { let test = std::process::Command::new(&args[0]).arg(\"run_test\").output().unwrap(); assert!(!test.status.success()); let err = String::from_utf8_lossy(&test.stderr); let mut it = err.lines(); assert_eq!(it.next().map(|l| l.starts_with(\"thread '' panicked at\")), Some(true)); assert_eq!(it.next(), Some(\"note: Run with `RUST_BACKTRACE=1` for a backtrace.\")); assert_eq!(it.next().map(|l| l.starts_with(\"thread '
' panicked at\")), Some(true)); assert_eq!(it.next(), None); } } "} {"_id":"doc-en-rust-7fc9640351b248ca289899148f9ef09f7e4a36a999d080a1b74d27c0c503b1bf","title":"","text":" // test for #117058 - check that attributes are validated on various kinds of statements. struct A; fn func() {} fn main() { #[allow(two-words)] //~^ ERROR expected one of `(`, `,`, `::`, or `=`, found `-` if true { } else { } #[allow(two-words)] //~^ ERROR expected one of `(`, `,`, `::`, or `=`, found `-` (1); #[allow(two-words)] //~^ ERROR expected one of `(`, `,`, `::`, or `=`, found `-` match 1 { _ => {} } #[allow(two-words)] //~^ ERROR expected one of `(`, `,`, `::`, or `=`, found `-` while false {} #[allow(two-words)] //~^ ERROR expected one of `(`, `,`, `::`, or `=`, found `-` {} #[allow(two-words)] //~^ ERROR expected one of `(`, `,`, `::`, or `=`, found `-` A {}; #[allow(two-words)] //~^ ERROR expected one of `(`, `,`, `::`, or `=`, found `-` func(); #[allow(two-words)] //~^ ERROR expected one of `(`, `,`, `::`, or `=`, found `-` A; #[allow(two-words)] //~^ ERROR expected one of `(`, `,`, `::`, or `=`, found `-` loop {} } "} {"_id":"doc-en-rust-3554e388a6fd90c6deb3b18994ba4ead9d62d56439a6544efce6cfdbe0d9efde","title":"","text":" error: expected one of `(`, `,`, `::`, or `=`, found `-` --> $DIR/statement-attribute-validation.rs:8:16 | LL | #[allow(two-words)] | ^ expected one of `(`, `,`, `::`, or `=` error: expected one of `(`, `,`, `::`, or `=`, found `-` --> $DIR/statement-attribute-validation.rs:13:16 | LL | #[allow(two-words)] | ^ expected one of `(`, `,`, `::`, or `=` error: expected one of `(`, `,`, `::`, or `=`, found `-` --> $DIR/statement-attribute-validation.rs:16:16 | LL | #[allow(two-words)] | ^ expected one of `(`, `,`, `::`, or `=` error: expected one of `(`, `,`, `::`, or `=`, found `-` --> $DIR/statement-attribute-validation.rs:21:16 | LL | #[allow(two-words)] | ^ expected one of `(`, `,`, `::`, or `=` error: expected one of `(`, `,`, `::`, or `=`, found `-` --> $DIR/statement-attribute-validation.rs:24:16 | LL | #[allow(two-words)] | ^ expected one of `(`, `,`, `::`, or `=` error: expected one of `(`, `,`, `::`, or `=`, found `-` --> $DIR/statement-attribute-validation.rs:27:16 | LL | #[allow(two-words)] | ^ expected one of `(`, `,`, `::`, or `=` error: expected one of `(`, `,`, `::`, or `=`, found `-` --> $DIR/statement-attribute-validation.rs:30:16 | LL | #[allow(two-words)] | ^ expected one of `(`, `,`, `::`, or `=` error: expected one of `(`, `,`, `::`, or `=`, found `-` --> $DIR/statement-attribute-validation.rs:33:16 | LL | #[allow(two-words)] | ^ expected one of `(`, `,`, `::`, or `=` error: expected one of `(`, `,`, `::`, or `=`, found `-` --> $DIR/statement-attribute-validation.rs:36:16 | LL | #[allow(two-words)] | ^ expected one of `(`, `,`, `::`, or `=` error: aborting due to 9 previous errors "} {"_id":"doc-en-rust-f6c3d8e9bba157fdf55a2fd694d4ff2b6a523775b67c3da9b6068f0513079ccd","title":"","text":"expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool { let ty::Adt(adt, args) = found.kind() else { return false }; let ty::Adt(adt, args) = found.kind() else { return false; }; let ret_ty_matches = |diagnostic_item| { if let Some(ret_ty) = self .ret_coercion .as_ref() .map(|c| self.resolve_vars_if_possible(c.borrow().expected_ty())) && let ty::Adt(kind, _) = ret_ty.kind() && self.tcx.get_diagnostic_item(diagnostic_item) == Some(kind.did()) { true } else { false } let Some(sig) = self.body_fn_sig() else { return false; }; let ty::Adt(kind, _) = sig.output().kind() else { return false; }; self.tcx.is_diagnostic_item(diagnostic_item, kind.did()) }; // don't suggest anything like `Ok(ok_val).unwrap()` , `Some(some_val).unwrap()`,"} {"_id":"doc-en-rust-83cae1b55230c6d732187ff098e4f4b93dfee6cbdf3327661b9cd440ff1f2daa","title":"","text":" // edition: 2021 async fn dont_suggest() -> i32 { if false { return Ok(6); //~^ ERROR mismatched types } 5 } async fn do_suggest() -> i32 { if false { let s = Ok(6); return s; //~^ ERROR mismatched types } 5 } fn main() {} "} {"_id":"doc-en-rust-16515145210b6dcc34a603593e76ec34b5a34e032da40b3a8f56b9e398d4b801","title":"","text":" error[E0308]: mismatched types --> $DIR/async-unwrap-suggestion.rs:5:16 | LL | return Ok(6); | ^^^^^ expected `i32`, found `Result<{integer}, _>` | = note: expected type `i32` found enum `Result<{integer}, _>` error[E0308]: mismatched types --> $DIR/async-unwrap-suggestion.rs:15:16 | LL | return s; | ^ expected `i32`, found `Result<{integer}, _>` | = note: expected type `i32` found enum `Result<{integer}, _>` help: consider using `Result::expect` to unwrap the `Result<{integer}, _>` value, panicking if the value is a `Result::Err` | LL | return s.expect(\"REASON\"); | +++++++++++++++++ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-2b6c21dae8e97f3a809e786cc909055a24de6d92be38a615b3b1562f693396f4","title":"","text":"(\"macro_registrar\", Active), (\"log_syntax\", Active), (\"trace_macros\", Active), (\"simd\", Active), // These are used to test this portion of the compiler, they don't actually // mean anything"} {"_id":"doc-en-rust-d361d7982083c8599313f542ba59b77f020916572534e799be58455f9757c25b","title":"","text":"} } ast::ItemStruct(..) => { if attr::contains_name(i.attrs, \"simd\") { self.gate_feature(\"simd\", i.span, \"SIMD types are experimental and possibly buggy\"); } } _ => {} }"} {"_id":"doc-en-rust-e07a7e4520fba5df2a5e48d96ba853b46368b3c5ed42e97c1247421f976869ca","title":"","text":"html_favicon_url = \"http://www.rust-lang.org/favicon.ico\", html_root_url = \"http://static.rust-lang.org/doc/master\")]; #[feature(macro_rules, globs, asm, managed_boxes, thread_local, link_args)]; #[feature(macro_rules, globs, asm, managed_boxes, thread_local, link_args, simd)]; // Don't link to std. We are std. #[no_std]; #[deny(non_camel_case_types)]; #[deny(missing_doc)]; #[allow(unknown_features)]; // When testing libstd, bring in libuv as the I/O backend so tests can print // things and all of the std::io tests have an I/O interface to run on top"} {"_id":"doc-en-rust-a00949b5156a9bdb82aa770e1673980bbd5da333b3c4d1abd76f426bef677256","title":"","text":"#[allow(non_camel_case_types)]; #[experimental] #[simd] pub struct i8x16(i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8, i8); #[experimental] #[simd] pub struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16); #[experimental] #[simd] pub struct i32x4(i32, i32, i32, i32); #[experimental] #[simd] pub struct i64x2(i64, i64); #[experimental] #[simd] pub struct u8x16(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8); #[experimental] #[simd] pub struct u16x8(u16, u16, u16, u16, u16, u16, u16, u16); #[experimental] #[simd] pub struct u32x4(u32, u32, u32, u32); #[experimental] #[simd] pub struct u64x2(u64, u64); #[experimental] #[simd] pub struct f32x4(f32, f32, f32, f32); #[experimental] #[simd] pub struct f64x2(f64, f64);"} {"_id":"doc-en-rust-073539fdab5a94b55341b71b0b2cc61e0d8f6b469dba2a365007de708ad56854","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[simd] pub struct i64x2(i64, i64); //~ ERROR: SIMD types are experimental fn main() {} No newline at end of file"} {"_id":"doc-en-rust-1aa171def1caf30e63eec6d8868e0df9a329d3cf29e944939f490f26fccc7db6","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-test FIXME #11741 tuple structs ignore stability attributes #[deny(experimental)]; use std::unstable::simd; fn main() { let _ = simd::i64x2(0, 0); //~ ERROR: experimental } "} {"_id":"doc-en-rust-296b3c4e8b2d1068de09e15abc924d1b7012ec9e8d8f9cf8b8a8908e0b6a60f1","title":"","text":" #[feature(simd)]; #[simd] struct vec4(T, T, T, T); //~ ERROR SIMD vector cannot be generic"} {"_id":"doc-en-rust-d2c29efb5f088414bc0fc937c514a12fc9c77fd7a3449d78e8287df0a40533a1","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. #[allow(experimental)]; use std::unstable::simd::{i32x4, f32x4}; fn test_int(e: i32) -> i32 {"} {"_id":"doc-en-rust-c72797c1a104285be06b986035a3d21ec4acc777b2878820e36d6655c4744512","title":"","text":" // xfail-fast feature doesn't work #[feature(simd)]; #[simd] struct RGBA { r: f32,"} {"_id":"doc-en-rust-c219e77cf6e61b0be4693886beca5b7a95b464794f8ba948a5d64b0a9b9467a6","title":"","text":"// types are fine though. ty::ConstKind::Value(_) => c.ty().is_primitive(), ty::ConstKind::Unevaluated(..) | ty::ConstKind::Expr(..) => false, // This can happen if evaluation of a constant failed. The result does not matter // much since compilation is doomed. ty::ConstKind::Error(..) => false, // Should not appear in runtime MIR. ty::ConstKind::Infer(..) | ty::ConstKind::Bound(..) | ty::ConstKind::Placeholder(..) | ty::ConstKind::Error(..) => bug!(), | ty::ConstKind::Placeholder(..) => bug!(), }, Const::Unevaluated(..) => false, // If the same slice appears twice in the MIR, we cannot guarantee that we will"} {"_id":"doc-en-rust-637b24e00c829742c52e26fd0c37613fc930931b301f8f7fff6aba47a5bfabc1","title":"","text":" error[E0080]: evaluation of ` as Foo<()>>::BAR` failed --> $DIR/issue-50814-2.rs:16:24 | LL | const BAR: usize = [5, 6, 7][T::BOO]; | ^^^^^^^^^^^^^^^^^ index out of bounds: the length is 3 but the index is 42 note: erroneous constant encountered --> $DIR/issue-50814-2.rs:20:6 | LL | & as Foo>::BAR | ^^^^^^^^^^^^^^^^^^^^^ note: erroneous constant encountered --> $DIR/issue-50814-2.rs:20:5 | LL | & as Foo>::BAR | ^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-ff0bc443c5f1aed86dc9d7635eb60d787b0c8102b108679f14e17b52cc8f56d0","title":"","text":" error[E0080]: evaluation of ` as Foo<()>>::BAR` failed --> $DIR/issue-50814-2.rs:16:24 | LL | const BAR: usize = [5, 6, 7][T::BOO]; | ^^^^^^^^^^^^^^^^^ index out of bounds: the length is 3 but the index is 42 note: erroneous constant encountered --> $DIR/issue-50814-2.rs:20:6 | LL | & as Foo>::BAR | ^^^^^^^^^^^^^^^^^^^^^ note: the above error was encountered while instantiating `fn foo::<()>` --> $DIR/issue-50814-2.rs:32:22 | LL | println!(\"{:x}\", foo::<()>() as *const usize as usize); | ^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-ab13d67edf4122f93cbe71c1bccf03afdd9ea22b6ffcd5eed09be15ebcca6c32","title":"","text":"// build-fail // revisions: normal mir-opt // [mir-opt]compile-flags: -Zmir-opt-level=4 trait C { const BOO: usize;"} {"_id":"doc-en-rust-2e0014a4def1d07a5768533842e892892c8fcd9ad282d235ca4585acef81eaf9","title":"","text":" error[E0080]: evaluation of ` as Foo<()>>::BAR` failed --> $DIR/issue-50814-2.rs:14:24 | LL | const BAR: usize = [5, 6, 7][T::BOO]; | ^^^^^^^^^^^^^^^^^ index out of bounds: the length is 3 but the index is 42 note: erroneous constant encountered --> $DIR/issue-50814-2.rs:18:6 | LL | & as Foo>::BAR | ^^^^^^^^^^^^^^^^^^^^^ note: the above error was encountered while instantiating `fn foo::<()>` --> $DIR/issue-50814-2.rs:30:22 | LL | println!(\"{:x}\", foo::<()>() as *const usize as usize); | ^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-83fd8e06f93d779b3b16ba557148cac731769dd10db8fd30ae608db28225081e","title":"","text":"// - use std::lazy for `Lazy` // - use std::cell for `OnceCell` // Once they get stabilized and reach beta. use build_helper::ci::CiEnv; use clap::ValueEnum; use once_cell::sync::{Lazy, OnceCell};"} {"_id":"doc-en-rust-4aa688f32ab4e345431b78eed199f7c68b17b1ca81f4200ddd4333e60df86c90","title":"","text":"self.clear_if_dirty(&out_dir, &backend); } if cmd == \"doc\" || cmd == \"rustdoc\" { if cmd == \"doc\" || cmd == \"rustdoc\" // FIXME: We shouldn't need to check this. // ref https://github.com/rust-lang/rust/issues/117430#issuecomment-1788160523 && !CiEnv::is_ci() { let my_out = match mode { // This is the intended out directory for compiler documentation. Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),"} {"_id":"doc-en-rust-9e5d7289011f8999ce5432013c75bc5f0889ffe3e477e5bc1000ae042533557a","title":"","text":"} fn run(self, builder: &Builder<'_>) -> Option { if builder.config.dry_run() { return None; } // This prevents rustc_codegen_cranelift from being built for \"dist\" // or \"install\" on the stable/beta channels. It is not yet stable and // should not be included."} {"_id":"doc-en-rust-f7148cabb0c81dcad86db8f280d30f9622240bc4fd88a102779d71fe0c48243d","title":"","text":"return None; } if !builder.config.rust_codegen_backends.contains(&self.backend) { return None; } if self.backend == \"cranelift\" { if !target_supports_cranelift_backend(self.compiler.host) { builder.info(\"target not supported by rustc_codegen_cranelift. skipping\");"} {"_id":"doc-en-rust-9ad1bf6728eeb25be9bb4b7cc6be73050042ce36d9af53001fdd49c0d505f498","title":"","text":"let backends_dst = PathBuf::from(\"lib\").join(&backends_rel); let backend_name = format!(\"rustc_codegen_{}\", backend); let mut found_backend = false; for backend in fs::read_dir(&backends_src).unwrap() { let file_name = backend.unwrap().file_name(); if file_name.to_str().unwrap().contains(&backend_name) { tarball.add_file(backends_src.join(file_name), &backends_dst, 0o644); found_backend = true; } } assert!(found_backend); Some(tarball.generate()) }"} {"_id":"doc-en-rust-365bd2403390a99634ef3f46b12c42107b6d707d2268c5f1c7e82130896d7d56","title":"","text":"--env DIST_TRY_BUILD --env PR_CI_JOB --env OBJDIR_ON_HOST=\"$objdir\" --env CODEGEN_BACKENDS --init --rm rust-ci "} {"_id":"doc-en-rust-f356b4f9c44862f1886c5da3d1585046cbc6dec5fc763610083bc9d8a4dd7695","title":"","text":"match err { LayoutError::Unknown(..) | LayoutError::ReferencesError(..) => Self::UnknownLayout, LayoutError::SizeOverflow(..) => Self::SizeOverflow, LayoutError::Cycle(err) => Self::TypeError(*err), err => unimplemented!(\"{:?}\", err), } }"} {"_id":"doc-en-rust-ed424166c1a980e539c030ce9f9992c39a4f81bca3f042d470d5325fe3853969","title":"","text":" //~ ERROR: cycle detected //! Safe transmute did not handle cycle errors that could occur during //! layout computation. This test checks that we do not ICE in such //! situations (see #117491). #![crate_type = \"lib\"] #![feature(transmutability)] #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { use std::mem::{Assume, BikeshedIntrinsicFrom}; pub struct Context; pub fn is_maybe_transmutable() where Dst: BikeshedIntrinsicFrom, { } } fn should_pad_explicitly_packed_field() { #[repr(C)] struct ExplicitlyPadded(ExplicitlyPadded); //~^ ERROR: recursive type assert::is_maybe_transmutable::(); } "} {"_id":"doc-en-rust-5452f8adc9678a4aa9e1bb2434a4a800a3f16ca6b9e6b63caa921b03590739de","title":"","text":" error[E0072]: recursive type `ExplicitlyPadded` has infinite size --> $DIR/transmute_infinitely_recursive_type.rs:22:5 | LL | struct ExplicitlyPadded(ExplicitlyPadded); | ^^^^^^^^^^^^^^^^^^^^^^^ ---------------- recursive without indirection | help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle | LL | struct ExplicitlyPadded(Box); | ++++ + error[E0391]: cycle detected when computing layout of `should_pad_explicitly_packed_field::ExplicitlyPadded` | = note: ...which immediately requires computing layout of `should_pad_explicitly_packed_field::ExplicitlyPadded` again = note: cycle used when evaluating trait selection obligation `(): core::mem::transmutability::BikeshedIntrinsicFrom` = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information error: aborting due to 2 previous errors Some errors have detailed explanations: E0072, E0391. For more information about an error, try `rustc --explain E0072`. "} {"_id":"doc-en-rust-c106d33bf791487f1d4557754cfa78c124576b9daab36c1d26eb3a4bd8bc2aba","title":"","text":"span, if span_to_replace.is_some() { constraint.clone() } else if constraint.starts_with(\"<\") { constraint.to_string() } else if bound_list_non_empty { format!(\" + {constraint}\") } else {"} {"_id":"doc-en-rust-4430da1a9ecec1ca8935ec32d78a057df45ce708599cf7ed8117a02702b0f8e8","title":"","text":" // run-rustfix pub trait MyTrait { type T; fn bar(self) -> Self::T; } pub fn foo, B>(a: A) -> B { return a.bar(); //~ ERROR mismatched types } fn main() {} "} {"_id":"doc-en-rust-0ce9c4794787edf9e01bb9acdd93eeae3eb0fd5ec44db2fdb22d668a3a69fde0","title":"","text":" // run-rustfix pub trait MyTrait { type T; fn bar(self) -> Self::T; } pub fn foo(a: A) -> B { return a.bar(); //~ ERROR mismatched types } fn main() {} "} {"_id":"doc-en-rust-0ffc4093c075ea0ef590b05a7b8f3a284873bb61d4be1ceb17ef4778347bb8f3","title":"","text":" error[E0308]: mismatched types --> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12 | LL | pub fn foo(a: A) -> B { | - - expected `B` because of return type | | | expected this type parameter LL | return a.bar(); | ^^^^^^^ expected type parameter `B`, found associated type | = note: expected type parameter `B` found associated type `::T` help: consider further restricting this bound | LL | pub fn foo, B>(a: A) -> B { | +++++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-fcb955d75d7e829a8f7685515c2d34df798e5a1d9a6672bac343490d01930c0f","title":"","text":"use super::{BorrowedBuf, BufReader, BufWriter, Read, Result, Write, DEFAULT_BUF_SIZE}; use crate::alloc::Allocator; use crate::cmp; use crate::cmp::min; use crate::collections::VecDeque; use crate::io::IoSlice; use crate::mem::MaybeUninit;"} {"_id":"doc-en-rust-3403d1b6345a61774b40698c3ba2da67c6b9afefc9720208ffcfdb7bb9ef7bc5","title":"","text":"fn copy_from(&mut self, reader: &mut R) -> Result { let mut bytes = 0; // avoid allocating before we have determined that there's anything to read if self.capacity() == 0 { bytes = stack_buffer_copy(&mut reader.take(DEFAULT_BUF_SIZE as u64), self)?; if bytes == 0 { return Ok(0); // avoid inflating empty/small vecs before we have determined that there's anything to read if self.capacity() < DEFAULT_BUF_SIZE { let stack_read_limit = DEFAULT_BUF_SIZE as u64; bytes = stack_buffer_copy(&mut reader.take(stack_read_limit), self)?; // fewer bytes than requested -> EOF reached if bytes < stack_read_limit { return Ok(bytes); } } // don't immediately offer the vec's whole spare capacity, otherwise // we might have to fully initialize it if the reader doesn't have a custom read_buf() impl let mut max_read_size = DEFAULT_BUF_SIZE; loop { self.reserve(DEFAULT_BUF_SIZE); let mut buf: BorrowedBuf<'_> = self.spare_capacity_mut().into(); match reader.read_buf(buf.unfilled()) { Ok(()) => {} Err(e) if e.is_interrupted() => continue, Err(e) => return Err(e), }; let mut initialized_spare_capacity = 0; let read = buf.filled().len(); if read == 0 { break; } loop { let buf = self.spare_capacity_mut(); let read_size = min(max_read_size, buf.len()); let mut buf = BorrowedBuf::from(&mut buf[..read_size]); // SAFETY: init is either 0 or the init_len from the previous iteration. unsafe { buf.set_init(initialized_spare_capacity); } match reader.read_buf(buf.unfilled()) { Ok(()) => { let bytes_read = buf.len(); // SAFETY: BorrowedBuf guarantees all of its filled bytes are init // and the number of read bytes can't exceed the spare capacity since // that's what the buffer is borrowing from. unsafe { self.set_len(self.len() + read) }; bytes += read as u64; } // EOF if bytes_read == 0 { return Ok(bytes); } Ok(bytes) // the reader is returning short reads but it doesn't call ensure_init() if buf.init_len() < buf.capacity() { max_read_size = usize::MAX; } // the reader hasn't returned short reads so far if bytes_read == buf.capacity() { max_read_size *= 2; } initialized_spare_capacity = buf.init_len() - bytes_read; bytes += bytes_read as u64; // SAFETY: BorrowedBuf guarantees all of its filled bytes are init // and the number of read bytes can't exceed the spare capacity since // that's what the buffer is borrowing from. unsafe { self.set_len(self.len() + bytes_read) }; // spare capacity full, reserve more if self.len() == self.capacity() { break; } } Err(e) if e.is_interrupted() => continue, Err(e) => return Err(e), } } } } }"} {"_id":"doc-en-rust-1f61d149bfe4d2efec8cc0f4e1fe36f5334007160327ff5c140962ce94bd4657","title":"","text":"// Equate the headers to find their intersection (the general type, with infer vars, // that may apply both impls). let Some(_equate_obligations) = let Some(equate_obligations) = equate_impl_headers(infcx, param_env, &impl1_header, &impl2_header) else { return false;"} {"_id":"doc-en-rust-02590f15a97a97f0c28325f27370deed2134a7f714c540ef999013007763b0f3","title":"","text":"plug_infer_with_placeholders(infcx, universe, (impl1_header.impl_args, impl2_header.impl_args)); // FIXME(with_negative_coherence): the infcx has constraints from equating // the impl headers. We should use these constraints as assumptions, not as // requirements, when proving the negated where clauses below. drop(equate_obligations); drop(infcx.take_registered_region_obligations()); drop(infcx.take_and_reset_region_constraints()); util::elaborate(tcx, tcx.predicates_of(impl2_def_id).instantiate(tcx, impl2_header.impl_args)) .any(|(clause, _)| try_prove_negated_where_clause(infcx, clause, param_env)) }"} {"_id":"doc-en-rust-1e332ff1f6a4bf23d7e2977fa03cac0dbfe253a282e1b2ef780741961a27d9a3","title":"","text":"return false; }; // FIXME(with_negative_coherence): the infcx has region contraints from equating // the impl headers as requirements. Given that the only region constraints we // get are involving inference regions in the root, it shouldn't matter, but // still sus. // // We probably should just throw away the region obligations registered up until // now, or ideally use them as assumptions when proving the region obligations // that we get from proving the negative predicate below. let ref infcx = root_infcx.fork(); let ocx = ObligationCtxt::new(infcx);"} {"_id":"doc-en-rust-883450e770135c33dce9e8411cb042e1188f5ae62366bee807f8898992d35f34","title":"","text":" error: conflicting implementations of trait `FnMarker` for type `fn(&_)` --> $DIR/negative-coherence-placeholder-region-constraints-on-unification.rs:21:1 | LL | impl FnMarker for fn(T) {} | ------------------------------------------- first implementation here LL | impl FnMarker for fn(&T) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `fn(&_)` | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #56105 = note: this behavior recently changed as a result of a bug fix; see rust-lang/rust#56105 for details note: the lint level is defined here --> $DIR/negative-coherence-placeholder-region-constraints-on-unification.rs:4:11 | LL | #![forbid(coherence_leak_check)] | ^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-9ea2ce22a36061aa0710fea17ad3282d08bf9fc6ff5c2fd43f75d1f6ce1445cf","title":"","text":" // revisions: explicit implicit //[implicit] check-pass #![forbid(coherence_leak_check)] #![feature(negative_impls, with_negative_coherence)] pub trait Marker {} #[cfg(implicit)] impl !Marker for &T {} #[cfg(explicit)] impl<'a, T: ?Sized + 'a> !Marker for &'a T {} trait FnMarker {} // Unifying these two impls below results in a `T: '!0` obligation // that we shouldn't need to care about. Ideally, we'd treat that // as an assumption when proving `&'!0 T: Marker`... impl FnMarker for fn(T) {} impl FnMarker for fn(&T) {} //[explicit]~^ ERROR conflicting implementations of trait `FnMarker` for type `fn(&_)` //[explicit]~| WARN this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! fn main() {} "} {"_id":"doc-en-rust-17c219d66f60917d2ecf8f323d10d535cd8be6b2fcac0ecef438379d0aeceee3","title":"","text":"let (param_env, unevaluated) = unevaluated.prepare_for_eval(tcx, param_env); // try to resolve e.g. associated constants to their definition on an impl, and then // evaluate the const. let c = tcx.const_eval_resolve_for_typeck(param_env, unevaluated, span)?; Ok(c.expect(\"`ty::Const::eval` called on a non-valtree-compatible type\")) let Some(c) = tcx.const_eval_resolve_for_typeck(param_env, unevaluated, span)? else { // This can happen when we run on ill-typed code. let e = tcx.sess.span_delayed_bug( span.unwrap_or(DUMMY_SP), \"`ty::Const::eval` called on a non-valtree-compatible type\", ); return Err(e.into()); }; Ok(c) } ConstKind::Value(val) => Ok(val), ConstKind::Error(g) => Err(g.into()),"} {"_id":"doc-en-rust-fe59cc9ed54744aee27563f7c80b6ad07c0b6a8144642e9eacc712406086007f","title":"","text":" struct Checked bool>; //~^ ERROR function pointers as const generic parameters is forbidden fn not_one(val: usize) -> bool { val != 1 } const _: Checked = Checked::; fn main() {} "} {"_id":"doc-en-rust-5cc0a12b61d5e1581eebc529f4e9a4130583da58aed04d74659a925bf9e84f77","title":"","text":" error: using function pointers as const generic parameters is forbidden --> $DIR/ice-118285-fn-ptr-value.rs:1:25 | LL | struct Checked bool>; | ^^^^^^^^^^^^^^^^^ | = note: the only supported types are integers, `bool` and `char` error: aborting due to 1 previous error "} {"_id":"doc-en-rust-5e6ae733304d448c9cc31431d251ebfcf3d083b73e23fde25cc59a575da46781","title":"","text":"} } } else { if matches!(def_kind, DefKind::AnonConst) && tcx.features().generic_const_exprs { let hir_id = tcx.local_def_id_to_hir_id(def_id); let parent_def_id = tcx.hir().get_parent_item(hir_id); if let Some(defaulted_param_def_id) = tcx.hir().opt_const_param_default_param_def_id(hir_id) { // In `generics_of` we set the generics' parent to be our parent's parent which means that // we lose out on the predicates of our actual parent if we dont return those predicates here. // (See comment in `generics_of` for more information on why the parent shenanigans is necessary) // // struct Foo::ASSOC }>(T) where T: Trait; // ^^^ ^^^^^^^^^^^^^^^^^^^^^^^ the def id we are calling // ^^^ explicit_predicates_of on // parent item we dont have set as the // parent of generics returned by `generics_of` // // In the above code we want the anon const to have predicates in its param env for `T: Trait` // and we would be calling `explicit_predicates_of(Foo)` here let parent_preds = tcx.explicit_predicates_of(parent_def_id); // If we dont filter out `ConstArgHasType` predicates then every single defaulted const parameter // will ICE because of #106994. FIXME(generic_const_exprs): remove this when a more general solution // to #106994 is implemented. let filtered_predicates = parent_preds .predicates .into_iter() .filter(|(pred, _)| { if let ty::ClauseKind::ConstArgHasType(ct, _) = pred.kind().skip_binder() { match ct.kind() { ty::ConstKind::Param(param_const) => { let defaulted_param_idx = tcx .generics_of(parent_def_id) .param_def_id_to_index[&defaulted_param_def_id.to_def_id()]; param_const.index < defaulted_param_idx } _ => bug!( \"`ConstArgHasType` in `predicates_of` that isn't a `Param` const\" ), if matches!(def_kind, DefKind::AnonConst) && tcx.features().generic_const_exprs && let Some(defaulted_param_def_id) = tcx.hir().opt_const_param_default_param_def_id(tcx.local_def_id_to_hir_id(def_id)) { // In `generics_of` we set the generics' parent to be our parent's parent which means that // we lose out on the predicates of our actual parent if we dont return those predicates here. // (See comment in `generics_of` for more information on why the parent shenanigans is necessary) // // struct Foo::ASSOC }>(T) where T: Trait; // ^^^ ^^^^^^^^^^^^^^^^^^^^^^^ the def id we are calling // ^^^ explicit_predicates_of on // parent item we dont have set as the // parent of generics returned by `generics_of` // // In the above code we want the anon const to have predicates in its param env for `T: Trait` // and we would be calling `explicit_predicates_of(Foo)` here let parent_def_id = tcx.local_parent(def_id); let parent_preds = tcx.explicit_predicates_of(parent_def_id); // If we dont filter out `ConstArgHasType` predicates then every single defaulted const parameter // will ICE because of #106994. FIXME(generic_const_exprs): remove this when a more general solution // to #106994 is implemented. let filtered_predicates = parent_preds .predicates .into_iter() .filter(|(pred, _)| { if let ty::ClauseKind::ConstArgHasType(ct, _) = pred.kind().skip_binder() { match ct.kind() { ty::ConstKind::Param(param_const) => { let defaulted_param_idx = tcx .generics_of(parent_def_id) .param_def_id_to_index[&defaulted_param_def_id.to_def_id()]; param_const.index < defaulted_param_idx } } else { true _ => bug!( \"`ConstArgHasType` in `predicates_of` that isn't a `Param` const\" ), } }) .cloned(); return GenericPredicates { parent: parent_preds.parent, predicates: { tcx.arena.alloc_from_iter(filtered_predicates) }, }; } let parent_def_kind = tcx.def_kind(parent_def_id); if matches!(parent_def_kind, DefKind::OpaqueTy) { // In `instantiate_identity` we inherit the predicates of our parent. // However, opaque types do not have a parent (see `gather_explicit_predicates_of`), which means // that we lose out on the predicates of our actual parent if we dont return those predicates here. // // // fn foo() -> impl Iterator::ASSOC }> > { todo!() } // ^^^^^^^^^^^^^^^^^^^ the def id we are calling // explicit_predicates_of on // // In the above code we want the anon const to have predicates in its param env for `T: Trait`. // However, the anon const cannot inherit predicates from its parent since it's opaque. // // To fix this, we call `explicit_predicates_of` directly on `foo`, the parent's parent. // In the above example this is `foo::{opaque#0}` or `impl Iterator` let parent_hir_id = tcx.local_def_id_to_hir_id(parent_def_id.def_id); // In the above example this is the function `foo` let item_def_id = tcx.hir().get_parent_item(parent_hir_id); // In the above code example we would be calling `explicit_predicates_of(foo)` here return tcx.explicit_predicates_of(item_def_id); } } else { true } }) .cloned(); return GenericPredicates { parent: parent_preds.parent, predicates: { tcx.arena.alloc_from_iter(filtered_predicates) }, }; } gather_explicit_predicates_of(tcx, def_id) }"} {"_id":"doc-en-rust-2c5d80a37735cf3602143d3a4e00d9cb37f5e1d90edceab981f6b985088a6c3a","title":"","text":" //@ known-bug: #118403 #![feature(generic_const_exprs)] pub struct X {} impl X { pub fn y<'a, U: 'a>(&'a self) -> impl Iterator + '_> { (0..1).map(move |_| (0..1).map(move |_| loop {})) } } "} {"_id":"doc-en-rust-caa378ae6b17a1433b3c76c47731782f25a98a9f0f21567eb3ccc0726cfeb368","title":"","text":" //@ known-bug: #121574 #![feature(generic_const_exprs)] pub struct DimName {} impl X { pub fn y<'a, U: 'a>(&'a self) -> impl Iterator + '_> { \"0\".as_bytes(move |_| (0..1).map(move |_| loop {})) } } "} {"_id":"doc-en-rust-1d63d5d762c7a9bdb55d563bcae97ae3d1f4825e5786e9487099199db48efad9","title":"","text":" //@ known-bug: #121574 #![feature(generic_const_exprs)] impl X { pub fn y<'a, U: 'a>(&'a self) -> impl Iterator + '_> {} } "} {"_id":"doc-en-rust-0b37dc7a4dfe7d31a761b6afa0d2b220975f98318032609c82554285d0397d24","title":"","text":" //@ check-pass #![feature(generic_const_exprs)] //~^ WARN the feature `generic_const_exprs` is incomplete and may not be safe to use pub fn y<'a, U: 'a>() -> impl IntoIterator + 'a> { [[[1, 2, 3]]] } // Make sure that the `predicates_of` for `{ 1 + 2 }` don't mention the duplicated lifetimes of // the *outer* iterator. Whether they should mention the duplicated lifetimes of the *inner* // iterator are another question, but not really something we need to answer immediately. fn main() {} "} {"_id":"doc-en-rust-fa62b2f39b5f36c0c95d44ac0fba34e22558edf44bcb4f22b1c3cea25694efc6","title":"","text":" warning: the feature `generic_const_exprs` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/double-opaque-parent-predicates.rs:3:12 | LL | #![feature(generic_const_exprs)] | ^^^^^^^^^^^^^^^^^^^ | = note: see issue #76560 for more information = note: `#[warn(incomplete_features)]` on by default warning: 1 warning emitted "} {"_id":"doc-en-rust-ccbb35ca0cca62e4b7d411ea6a49c70b4756afa5b3c365fc6961da9e95354761","title":"","text":"use std::fs::File; use std::io; use std::iter; use std::mem::ManuallyDrop; use std::path::Path; use std::slice; use std::sync::Arc;"} {"_id":"doc-en-rust-2e17e64c458a691ea932322b56eab4e3b720d5e0f9ee06349e27475ae9c85455","title":"","text":"let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names); let llmod_raw = parse_module(llcx, module_name, thin_module.data(), &diag_handler)? as *const _; let mut module = ModuleCodegen { module_llvm: ModuleLlvm { llmod_raw, llcx, tm }, module_llvm: ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }, name: thin_module.name().to_string(), kind: ModuleKind::Regular, };"} {"_id":"doc-en-rust-91042ed7ecec5844fdabbb3cfbf8582137674f60ae9eadd006a8224a878eac52","title":"","text":"use std::any::Any; use std::ffi::CStr; use std::io::Write; use std::mem::ManuallyDrop; mod back { pub mod archive;"} {"_id":"doc-en-rust-0b65cc21687d6faaa2e6aeae2986ab4c45e52a728380ad1002ae395bdffbe876","title":"","text":"llcx: &'static mut llvm::Context, llmod_raw: *const llvm::Module, // independent from llcx and llmod_raw, resources get disposed by drop impl tm: OwnedTargetMachine, // This field is `ManuallyDrop` because it is important that the `TargetMachine` // is disposed prior to the `Context` being disposed otherwise UAFs can occur. tm: ManuallyDrop, } unsafe impl Send for ModuleLlvm {}"} {"_id":"doc-en-rust-a90e1e277952f363ddbf3b779b57e95e4dbceed52c1bf6e266f31ea98df1f4bf","title":"","text":"unsafe { let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names()); let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _; ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) } ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)), } } }"} {"_id":"doc-en-rust-c86f2c7b2522496b52ac09439c6d6316491575073a3d9e7d33201ce856367a7f","title":"","text":"unsafe { let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names()); let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _; ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) } ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess)), } } }"} {"_id":"doc-en-rust-6074e80a80a2663ee000783f36cd552e0a7672975a1615235426bf24cd3de058","title":"","text":"} }; Ok(ModuleLlvm { llmod_raw, llcx, tm }) Ok(ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }) } }"} {"_id":"doc-en-rust-7fd0e40d8a0cfde178dab10d940b645137c2fc7dbdd5a3ee0fc770068a53c681","title":"","text":"impl Drop for ModuleLlvm { fn drop(&mut self) { unsafe { ManuallyDrop::drop(&mut self.tm); llvm::LLVMContextDispose(&mut *(self.llcx as *mut _)); } }"} {"_id":"doc-en-rust-281e680678bd4dd568b0a630fa889b568ccf3d7e9da2e5f6a09fe0627153955b","title":"","text":"// current number of evaluated terminators is a power of 2. The latter gives us a cheap // way to implement exponential backoff. let span = ecx.cur_span(); ecx.tcx.dcx().emit_warn(LongRunningWarn { span, item_span: ecx.tcx.span }); // We store a unique number in `force_duplicate` to evade `-Z deduplicate-diagnostics`. // `new_steps` is guaranteed to be unique because `ecx.machine.num_evaluated_steps` is // always increasing. ecx.tcx.dcx().emit_warn(LongRunningWarn { span, item_span: ecx.tcx.span, force_duplicate: new_steps, }); } }"} {"_id":"doc-en-rust-8ba10a933f1024b1d04123617d2c0b434e90b7dd124fccc3e24d0640d980d87a","title":"","text":"pub span: Span, #[help] pub item_span: Span, // Used for evading `-Z deduplicate-diagnostics`. pub force_duplicate: usize, } #[derive(Subdiagnostic)]"} {"_id":"doc-en-rust-6f7c38dbd0954dbe804cb332613c5a9adb76ba42f5b8c5be220b9580e327091d","title":"","text":" //@ check-pass #![allow(long_running_const_eval)] //@ compile-flags: -Z tiny-const-eval-limit -Z deduplicate-diagnostics=yes const FOO: () = { let mut i = 0; loop { //~^ WARN is taking a long time //~| WARN is taking a long time //~| WARN is taking a long time //~| WARN is taking a long time //~| WARN is taking a long time if i == 1000 { break; } else { i += 1; } } }; fn main() { FOO } "} {"_id":"doc-en-rust-1df11cab7b25e80d2ac8dd75396e46f65fa642f1b736bd311f548643eb220c83","title":"","text":" warning: constant evaluation is taking a long time --> $DIR/evade-deduplication-issue-118612.rs:8:5 | LL | / loop { LL | | LL | | LL | | ... | LL | | } LL | | } | |_____^ the const evaluator is currently interpreting this expression | help: the constant being evaluated --> $DIR/evade-deduplication-issue-118612.rs:6:1 | LL | const FOO: () = { | ^^^^^^^^^^^^^ warning: constant evaluation is taking a long time --> $DIR/evade-deduplication-issue-118612.rs:8:5 | LL | / loop { LL | | LL | | LL | | ... | LL | | } LL | | } | |_____^ the const evaluator is currently interpreting this expression | help: the constant being evaluated --> $DIR/evade-deduplication-issue-118612.rs:6:1 | LL | const FOO: () = { | ^^^^^^^^^^^^^ warning: constant evaluation is taking a long time --> $DIR/evade-deduplication-issue-118612.rs:8:5 | LL | / loop { LL | | LL | | LL | | ... | LL | | } LL | | } | |_____^ the const evaluator is currently interpreting this expression | help: the constant being evaluated --> $DIR/evade-deduplication-issue-118612.rs:6:1 | LL | const FOO: () = { | ^^^^^^^^^^^^^ warning: constant evaluation is taking a long time --> $DIR/evade-deduplication-issue-118612.rs:8:5 | LL | / loop { LL | | LL | | LL | | ... | LL | | } LL | | } | |_____^ the const evaluator is currently interpreting this expression | help: the constant being evaluated --> $DIR/evade-deduplication-issue-118612.rs:6:1 | LL | const FOO: () = { | ^^^^^^^^^^^^^ warning: constant evaluation is taking a long time --> $DIR/evade-deduplication-issue-118612.rs:8:5 | LL | / loop { LL | | LL | | LL | | ... | LL | | } LL | | } | |_____^ the const evaluator is currently interpreting this expression | help: the constant being evaluated --> $DIR/evade-deduplication-issue-118612.rs:6:1 | LL | const FOO: () = { | ^^^^^^^^^^^^^ warning: 5 warnings emitted "} {"_id":"doc-en-rust-1517812cc3d4bcecc301f0e461544b1c229d684387ac68b2e870982a3512173d","title":"","text":"} .item-info .stab { /* This min-height is needed to unify the height of the stab elements because some of them have emojis. */ min-height: 36px; display: flex; display: block; padding: 3px; margin-bottom: 5px; align-items: center; vertical-align: text-bottom; } .item-name .stab { margin-left: 0.3125em;"} {"_id":"doc-en-rust-586ce0416eb419aa018dd4e26c65caaea40bc8bdbe54d52568feb5babd7ddf94","title":"","text":"color: var(--stab-code-color); } .stab .emoji { .stab .emoji, .item-info .stab::before { font-size: 1.25rem; } .stab .emoji { margin-right: 0.3rem; } .item-info .stab::before { /* ensure badges with emoji and without it have same height */ content: \"0\"; width: 0; display: inline-block; color: transparent; } /* Black one-pixel outline around emoji shapes */ .emoji { text-shadow: 1px 0 0 black, -1px 0 0 black, 0 1px 0 black, 0 1px 0 black, 0 -1px 0 black; }"} {"_id":"doc-en-rust-03b9cc3b2e867d3d80dfd868e7d53f1730d4f6574fe7cd4f44ce804b823b36c6","title":"","text":"assert-size: (\".item-info .stab\", {\"width\": 289}) assert-position: (\".item-info .stab\", {\"x\": 245}) // We check that the display of the feature elements is not broken. It serves as regression // test for . set-window-size: (850, 800) store-position: ( \"//*[@class='stab portability']//code[text()='Win32_System']\", {\"x\": first_line_x, \"y\": first_line_y}, ) store-position: ( \"//*[@class='stab portability']//code[text()='Win32_System_Diagnostics']\", {\"x\": second_line_x, \"y\": second_line_y}, ) assert: |first_line_x| != |second_line_x| && |first_line_x| == 516 && |second_line_x| == 272 assert: |first_line_y| != |second_line_y| && |first_line_y| == 688 && |second_line_y| == 711 // Now we ensure that they're not rendered on the same line. set-window-size: (1100, 800) go-to: \"file://\" + |DOC_PATH| + \"/lib2/trait.Trait.html\" // We first ensure that there are two item info on the trait. assert-count: (\"#main-content > .item-info .stab\", 2)"} {"_id":"doc-en-rust-4e88570f0a164e9449a66ed4b8497bc66e20e4599c09dde7e230a652790e5ba9","title":"","text":"[lib] path = \"lib.rs\" [features] Win32 = [\"Win32_System\"] Win32_System = [\"Win32_System_Diagnostics\"] Win32_System_Diagnostics = [\"Win32_System_Diagnostics_Debug\"] Win32_System_Diagnostics_Debug = [] default = [\"Win32\"] [dependencies] implementors = { path = \"./implementors\" } http = { path = \"./http\" }"} {"_id":"doc-en-rust-4d4cff39333a45042e5e8c83fd0c7590706c462d1b74995643bd9429ed91af1f","title":"","text":"// ignore-tidy-linelength #![feature(doc_cfg)] #![feature(doc_auto_cfg)] pub mod another_folder; pub mod another_mod;"} {"_id":"doc-en-rust-4b910d22a0deca1c1b31a3ba768925bebc6ce5e1204e22d84f25f25d1b694f88","title":"","text":"/// Some documentation /// # A Heading pub fn a_method(&self) {} #[cfg(all( feature = \"Win32\", feature = \"Win32_System\", feature = \"Win32_System_Diagnostics\", feature = \"Win32_System_Diagnostics_Debug\" ))] pub fn lot_of_features() {} } #[doc(cfg(feature = \"foo-method\"))]"} {"_id":"doc-en-rust-256fa959aa7ee708685bcd7f40498fda9ba80898b43d090bfaa104c6834a3925","title":"","text":"return; } }; let (sig, map) = tcx.instantiate_bound_regions(sig, |br| { let (unnormalized_sig, map) = tcx.instantiate_bound_regions(sig, |br| { use crate::renumber::RegionCtxt; let region_ctxt_fn = || {"} {"_id":"doc-en-rust-25bd64db2ce2e460b55c407dc974551fbef355198a903eea0434e5a3feb88f53","title":"","text":"region_ctxt_fn, ) }); debug!(?sig); debug!(?unnormalized_sig); // IMPORTANT: We have to prove well formed for the function signature before // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc` // get normalized away, causing us to ignore the `'b: 'a` bound used by the function."} {"_id":"doc-en-rust-597f5444e94753f6cc13498508357cb412e65b4911259ceb2639fcd7d7f1a1d2","title":"","text":"// // See #91068 for an example. self.prove_predicates( sig.inputs_and_output.iter().map(|ty| { unnormalized_sig.inputs_and_output.iter().map(|ty| { ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed( ty.into(), )))"} {"_id":"doc-en-rust-9a3a5d54df7a4f0f0b5a9bf9e8b39c54120ff9c10768cb4013a0f337e8e93026","title":"","text":"term_location.to_locations(), ConstraintCategory::Boring, ); let sig = self.normalize(sig, term_location); let sig = self.normalize(unnormalized_sig, term_location); // HACK(#114936): `WF(sig)` does not imply `WF(normalized(sig))` // with built-in `Fn` implementations, since the impl may not be // well-formed itself. if sig != unnormalized_sig { self.prove_predicates( sig.inputs_and_output.iter().map(|ty| { ty::Binder::dummy(ty::PredicateKind::Clause( ty::ClauseKind::WellFormed(ty.into()), )) }), term_location.to_locations(), ConstraintCategory::Boring, ); } self.check_call_dest(body, term, &sig, *destination, *target, term_location); // The ordinary liveness rules will ensure that all"} {"_id":"doc-en-rust-b27bc0c8c0c31a771e387a12370bab75454de050ee36f37ad3a7c324ad51e1cb","title":"","text":" // fn whoops( s: String, f: impl for<'s> FnOnce(&'s str) -> (&'static str, [&'static &'s (); 0]), ) -> &'static str { f(&s).0 //~^ ERROR `s` does not live long enough } // fn extend(input: &T) -> &'static T { struct Bounded<'a, 'b: 'static, T>(&'a T, [&'b (); 0]); let n: Box Bounded<'static, '_, T>> = Box::new(|x| Bounded(x, [])); n(input).0 //~^ ERROR borrowed data escapes outside of function } // fn extend_mut<'a, T>(input: &'a mut T) -> &'static mut T { struct Bounded<'a, 'b: 'static, T>(&'a mut T, [&'b (); 0]); let mut n: Box Bounded<'static, '_, T>> = Box::new(|x| Bounded(x, [])); n(input).0 //~^ ERROR borrowed data escapes outside of function } fn main() {} "} {"_id":"doc-en-rust-845f15e032a32ccafbb42a11825b3ecb1205bc128c545b3fe71dc21dc9f0a60a","title":"","text":" error[E0597]: `s` does not live long enough --> $DIR/check-normalized-sig-for-wf.rs:7:7 | LL | s: String, | - binding `s` declared here ... LL | f(&s).0 | --^^- | | | | | borrowed value does not live long enough | argument requires that `s` is borrowed for `'static` LL | LL | } | - `s` dropped here while still borrowed error[E0521]: borrowed data escapes outside of function --> $DIR/check-normalized-sig-for-wf.rs:15:5 | LL | fn extend(input: &T) -> &'static T { | ----- - let's call the lifetime of this reference `'1` | | | `input` is a reference that is only valid in the function body ... LL | n(input).0 | ^^^^^^^^ | | | `input` escapes the function body here | argument requires that `'1` must outlive `'static` error[E0521]: borrowed data escapes outside of function --> $DIR/check-normalized-sig-for-wf.rs:23:5 | LL | fn extend_mut<'a, T>(input: &'a mut T) -> &'static mut T { | -- ----- `input` is a reference that is only valid in the function body | | | lifetime `'a` defined here ... LL | n(input).0 | ^^^^^^^^ | | | `input` escapes the function body here | argument requires that `'a` must outlive `'static` error: aborting due to 3 previous errors Some errors have detailed explanations: E0521, E0597. For more information about an error, try `rustc --explain E0521`. "} {"_id":"doc-en-rust-0b8df9c6802a56fdc47f41915fef542f1b28ca38e41193334b63117ac6f80826","title":"","text":"id: NodeId, parent_prefix: &[Segment], nested: bool, list_stem: bool, // The whole `use` item item: &Item, vis: ty::Visibility,"} {"_id":"doc-en-rust-c5d23dbfd241890c68d44863dd40eb9cbdd653b6371deaf8b90b869e353e58ca","title":"","text":"parent_prefix, use_tree, nested ); if nested { // Top level use tree reuses the item's id and list stems reuse their parent // use tree's ids, so in both cases their visibilities are already filled. if nested && !list_stem { self.r.feed_visibility(self.r.local_def_id(id), vis); }"} {"_id":"doc-en-rust-7e9a5aa9d9955b646d1fc1f3c2dff036172f18dc11ba7028a03b639051f78cc2","title":"","text":"for &(ref tree, id) in items { self.build_reduced_graph_for_use_tree( // This particular use tree tree, id, &prefix, true, // The whole `use` item tree, id, &prefix, true, false, // The whole `use` item item, vis, root_span, ); }"} {"_id":"doc-en-rust-1889f9c49177c975086c2db71a6292992f9db4cb9b1ca1657539baf37ad7bd4f","title":"","text":"id, &prefix, true, true, // The whole `use` item item, ty::Visibility::Restricted("} {"_id":"doc-en-rust-ff9acc48503a199d68296afe739ed800415244d7fd4ea05ea9907e1d08f34715","title":"","text":"item.id, &[], false, false, // The whole `use` item item, vis,"} {"_id":"doc-en-rust-253a11efa4c1f21620924ca83fe60e7daa246317506343a90ead9914e4130b87","title":"","text":" // check-pass // edition: 2018 mod outer { mod inner { pub mod inner2 {} } pub(crate) use inner::{}; pub(crate) use inner::{{}}; pub(crate) use inner::{inner2::{}}; pub(crate) use inner::{inner2::{{}}}; } fn main() {} "} {"_id":"doc-en-rust-11c060a72ac029d9debb9c9c0b0b99841ef28fca3617cdd0a2ccafcea37beef3","title":"","text":"/// Whether the layout is from a type that implements [`std::marker::PointerLike`]. /// /// Currently, that means that the type is pointer-sized, pointer-aligned, /// and has a scalar ABI. /// and has a initialized (non-union), scalar ABI. pub fn is_pointer_like(self, data_layout: &TargetDataLayout) -> bool { self.size() == data_layout.pointer_size && self.align().abi == data_layout.pointer_align.abi && matches!(self.abi(), Abi::Scalar(..)) && matches!(self.abi(), Abi::Scalar(Scalar::Initialized { .. })) } }"} {"_id":"doc-en-rust-5272883e034c7cf395c4d82fb63cd91e11eb8d8f24ade3b306240a11d33fa76c","title":"","text":" #![feature(dyn_star)] //~^ WARN the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes union Union { x: usize, } trait Trait {} impl Trait for Union {} fn bar(_: dyn* Trait) {} fn main() { bar(Union { x: 0usize }); //~^ ERROR `Union` needs to have the same ABI as a pointer } "} {"_id":"doc-en-rust-802984cc21f5607d21a9a636c7c461a3fa18bd7c9e24bd140eef0eefe8bd65fb","title":"","text":" warning: the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/union.rs:1:12 | LL | #![feature(dyn_star)] | ^^^^^^^^ | = note: see issue #102425 for more information = note: `#[warn(incomplete_features)]` on by default error[E0277]: `Union` needs to have the same ABI as a pointer --> $DIR/union.rs:14:9 | LL | bar(Union { x: 0usize }); | ^^^^^^^^^^^^^^^^^^^ `Union` needs to be a pointer-like type | = help: the trait `PointerLike` is not implemented for `Union` error: aborting due to 1 previous error; 1 warning emitted For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-f5a97b8f0e390eab6bfab2f9b3468517a1861d95d79ee3d498005dd36b656ca5","title":"","text":"- [wasm32-wasip1](platform-support/wasm32-wasip1.md) - [wasm32-wasip1-threads](platform-support/wasm32-wasip1-threads.md) - [wasm32-wasip2](platform-support/wasm32-wasip2.md) - [wasm32-unknown-unknown](platform-support/wasm32-unknown-unknown.md) - [wasm64-unknown-unknown](platform-support/wasm64-unknown-unknown.md) - [*-win7-windows-msvc](platform-support/win7-windows-msvc.md) - [x86_64-fortanix-unknown-sgx](platform-support/x86_64-fortanix-unknown-sgx.md)"} {"_id":"doc-en-rust-216389043891c4ac8ce218cfdba629e44982157ea68bad4479077bbe88784d37","title":"","text":"[`thumbv8m.main-none-eabi`](platform-support/thumbv8m.main-none-eabi.md) | * | Bare Armv8-M Mainline [`thumbv8m.main-none-eabihf`](platform-support/thumbv8m.main-none-eabi.md) | * | Bare Armv8-M Mainline, hardfloat `wasm32-unknown-emscripten` | ✓ | WebAssembly via Emscripten `wasm32-unknown-unknown` | ✓ | WebAssembly [`wasm32-unknown-unknown`](platform-support/wasm32-unknown-unknown.md) | ✓ | WebAssembly `wasm32-wasi` | ✓ | WebAssembly with WASI (undergoing a [rename to `wasm32-wasip1`][wasi-rename]) [`wasm32-wasip1`](platform-support/wasm32-wasip1.md) | ✓ | WebAssembly with WASI [`wasm32-wasip1-threads`](platform-support/wasm32-wasip1-threads.md) | ✓ | WebAssembly with WASI Preview 1 and threads"} {"_id":"doc-en-rust-1f9e47b025f2d2032fc9b1822395a7a6f0fdd51bceba8315e8f24a2f72c79a80","title":"","text":" # `wasm32-unknown-unknown` **Tier: 2** The `wasm32-unknown-unknown` target is a WebAssembly compilation target which does not import any functions from the host for the standard library. This is the \"minimal\" WebAssembly in the sense of making the fewest assumptions about the host environment. This target is often used when compiling to the web or JavaScript environments as there is no standard for what functions can be imported on the web. This target can also be useful for creating minimal or bare-bones WebAssembly binaries. The `wasm32-unknown-unknown` target has support for the Rust standard library but many parts of the standard library do not work and return errors. For example `println!` does nothing, `std::fs` always return errors, and `std::thread::spawn` will panic. There is no means by which this can be overridden. For a WebAssembly target that more fully supports the standard library see the [`wasm32-wasip1`](./wasm32-wasip1.md) or [`wasm32-wasip2`](./wasm32-wasip2.md) targets. The `wasm32-unknown-unknown` target has full support for the `core` and `alloc` crates. It additionally supports the `HashMap` type in the `std` crate, although hash maps are not randomized like they are on other platforms. One existing user of this target (please feel free to edit and expand this list too) is the [`wasm-bindgen` project](https://github.com/rustwasm/wasm-bindgen) which facilitates Rust code interoperating with JavaScript code. Note, though, that not all uses of `wasm32-unknown-unknown` are using JavaScript and the web. ## Target maintainers When this target was added to the compiler platform-specific documentation here was not maintained at that time. This means that the list below is not exhaustive and there are more interested parties in this target. That being said since when this document was last updated those interested in maintaining this target are: - Alex Crichton, https://github.com/alexcrichton ## Requirements This target is cross-compiled. The target includes support for `std` itself, but as mentioned above many pieces of functionality that require an operating system do not work and will return errors. This target currently has no equivalent in C/C++. There is no C/C++ toolchain for this target. While interop is theoretically possible it's recommended to instead use one of: * `wasm32-unknown-emscripten` - for web-based use cases the Emscripten toolchain is typically chosen for running C/C++. * [`wasm32-wasip1`](./wasm32-wasip1.md) - the wasi-sdk toolchain is used to compile C/C++ on this target and can interop with Rust code. WASI works on the web so far as there's no blocker, but an implementation of WASI APIs must be either chosen or reimplemented. This target has no build requirements beyond what's in-tree in the Rust repository. Linking binaries requires LLD to be enabled for the `wasm-ld` driver. This target uses the `dlmalloc` crate as the default global allocator. ## Building the target Building this target can be done by: * Configure the `wasm32-unknown-unknown` target to get built. * Configure LLD to be built. * Ensure the `WebAssembly` target backend is not disabled in LLVM. These are all controlled through `config.toml` options. It should be possible to build this target on any platform. ## Building Rust programs Rust programs can be compiled by adding this target via rustup: ```sh $ rustup target add wasm32-unknown-unknown ``` and then compiling with the target: ```sh $ rustc foo.rs --target wasm32-unknown-unknown $ file foo.wasm ``` ## Cross-compilation This target can be cross-compiled from any host. ## Testing This target is not tested in CI for the rust-lang/rust repository. Many tests must be disabled to run on this target and failures are non-obvious because `println!` doesn't work in the standard library. It's recommended to test the `wasm32-wasip1` target instead for WebAssembly compatibility. ## Conditionally compiling code It's recommended to conditionally compile code for this target with: ```text #[cfg(all(target_family = \"wasm\", target_os = \"unknown\"))] ``` Note that there is no way to tell via `#[cfg]` whether code will be running on the web or not. ## Enabled WebAssembly features WebAssembly is an evolving standard which adds new features such as new instructions over time. This target's default set of supported WebAssembly features will additionally change over time. The `wasm32-unknown-unknown` target inherits the default settings of LLVM which typically matches the default settings of Emscripten as well. Changes to WebAssembly go through a [proposals process][proposals] but reaching the final stage (stage 5) does not automatically mean that the feature will be enabled in LLVM and Rust by default. At this time the general guidance is that features must be present in most engines for a \"good chunk of time\" before they're enabled in LLVM by default. There is currently no exact number of months or engines that are required to enable features by default. [proposals]: https://github.com/WebAssembly/proposals As of the time of this writing the proposals that are enabled by default (the `generic` CPU in LLVM terminology) are: * `multivalue` * `mutable-globals` * `reference-types` * `sign-ext` If you're compiling WebAssembly code for an engine that does not support a feature in LLVM's default feature set then the feature must be disabled at compile time. Note, though, that enabled features may be used in the standard library or precompiled libraries shipped via rustup. This means that not only does your own code need to be compiled with the correct set of flags but the Rust standard library additionally must be recompiled. Compiling all code for the initial release of WebAssembly looks like: ```sh $ export RUSTFLAGS=-Ctarget-cpu=mvp $ cargo +nightly build -Zbuild-std=panic_abort,std --target wasm32-unknown-unknown ``` Here the `mvp` \"cpu\" is a placeholder in LLVM for disabling all supported features by default. Cargo's `-Zbuild-std` feature, a Nightly Rust feature, is then used to recompile the standard library in addition to your own code. This will produce a binary that uses only the original WebAssembly features by default and no proposals since its inception. To enable individual features it can be done with `-Ctarget-feature=+foo`. Available features for Rust code itself are documented in the [reference] and can also be found through: ```sh $ rustc -Ctarget-feature=help --target wasm32-unknown-unknown ``` You'll need to consult your WebAssembly engine's documentation to learn more about the supported WebAssembly features the engine has. [reference]: https://doc.rust-lang.org/reference/attributes/codegen.html#wasm32-or-wasm64 Note that it is still possible for Rust crates and libraries to enable WebAssembly features on a per-function level. This means that the build command above may not be sufficient to disable all WebAssembly features. If the final binary still has SIMD instructions, for example, the function in question will need to be found and the crate in question will likely contain something like: ```rust,ignore (not-always-compiled-to-wasm) #[target_feature(enable = \"simd128\")] fn foo() { // ... } ``` In this situation there is no compiler flag to disable emission of SIMD instructions and the crate must instead be modified to not include this function at compile time either by default or through a Cargo feature. For crate authors it's recommended to avoid `#[target_feature(enable = \"...\")]` except where necessary and instead use: ```rust,ignore (not-always-compiled-to-wasm) #[cfg(target_feature = \"simd128\")] fn foo() { // ... } ``` That is to say instead of enabling target features it's recommended to conditionally compile code instead. This is notably different to the way native platforms such as x86_64 work, and this is due to the fact that WebAssembly binaries must only contain code the engine understands. Native binaries work so long as the CPU doesn't execute unknown code dynamically at runtime. "} {"_id":"doc-en-rust-b4ca640f7e5d05cd2276b4836b8decfc60f429fe7eec3450650c181d8dc91dc7","title":"","text":"Prior to Rust 1.80 the `target_env = \"p1\"` key was not set. Currently the `target_feature = \"atomics\"` is Nightly-only. Note that the precise `#[cfg]` necessary to detect this target may change as the target becomes more stable. ## Enabled WebAssembly features The default set of WebAssembly features enabled for compilation includes two more features in addition to that which [`wasm32-unknown-unknown`](./wasm32-unknown-unknown.md) enables: * `bulk-memory` * `atomics` For more information about features see the documentation for [`wasm32-unknown-unknown`](./wasm32-unknown-unknown.md), but note that the `mvp` CPU in LLVM does not support this target as it's required that `bulk-memory`, `atomics`, and `mutable-globals` are all enabled. "} {"_id":"doc-en-rust-a7a0e47a62b72c6be00e604fea5a87e04d07904872750479fd6ded004bf8d993","title":"","text":"Note that the `target_env = \"p1\"` condition first appeared in Rust 1.80. Prior to Rust 1.80 the `target_env` condition was not set. ## Enabled WebAssembly features The default set of WebAssembly features enabled for compilation is currently the same as [`wasm32-unknown-unknown`](./wasm32-unknown-unknown.md). See the documentation there for more information. "} {"_id":"doc-en-rust-3ee5fbaaec92ccdf8fbdeec8b4fbc842f5d784c746b41435822826f3042587d0","title":"","text":"```text #[cfg(all(target_os = \"wasi\", target_env = \"p2\"))] ``` ## Enabled WebAssembly features The default set of WebAssembly features enabled for compilation is currently the same as [`wasm32-unknown-unknown`](./wasm32-unknown-unknown.md). See the documentation there for more information. "} {"_id":"doc-en-rust-1b51f16820e2430ecf71b9a3fd2a1d2db108bf4627331fa96dc0fd89ba6201ce","title":"","text":"| ProjectionElem::Subtype(_) | ProjectionElem::Downcast(_, _) | ProjectionElem::Field(_, _) => { write!(fmt, \"(\").unwrap(); write!(fmt, \"(\")?; } ProjectionElem::Deref => { write!(fmt, \"(*\").unwrap(); write!(fmt, \"(*\")?; } ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. }"} {"_id":"doc-en-rust-cc67aa5242e7337c91b0661ec3598a9dd2c719a039692920a123d2782b6d9466","title":"","text":"// but there's already an item with the same namespace and same name. Rust gives // priority to the not-imported one, so we should, too. items.extend(doc.items.values().flat_map(|(item, renamed, import_id)| { // First, lower everything other than imports. // First, lower everything other than glob imports. if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) { return Vec::new(); }"} {"_id":"doc-en-rust-42df2f9dab7a0b149e79e816079724d4b383388b63cb43e87dbc0e2c0da21e44","title":"","text":"use rustc_hir::HirId; use rustc_lint_defs::Applicability; use rustc_resolve::rustdoc::source_span_for_markdown_range; use rustc_span::def_id::DefId; use rustc_span::Symbol; use crate::clean::utils::find_nearest_parent_module;"} {"_id":"doc-en-rust-9abf5b30f2572eff14c920729b7c0b0f93b7d64642a7e13aa98986cd68483487","title":"","text":"return; } if item.link_names(&cx.cache).is_empty() { // If there's no link names in this item, // then we skip resolution querying to // avoid from panicking. return; if let Some(item_id) = item.def_id() { check_redundant_explicit_link_for_did(cx, item, item_id, hir_id, &doc); } if let Some(item_id) = item.inline_stmt_id { check_redundant_explicit_link_for_did(cx, item, item_id, hir_id, &doc); } } let Some(item_id) = item.def_id() else { return; }; let Some(local_item_id) = item_id.as_local() else { fn check_redundant_explicit_link_for_did<'md>( cx: &DocContext<'_>, item: &Item, did: DefId, hir_id: HirId, doc: &'md str, ) { let Some(local_item_id) = did.as_local() else { return; };"} {"_id":"doc-en-rust-26b582a8f457442b7798beac2dd87193bc74a79934212e4395a835e869516514","title":"","text":"return; } let is_private = !cx.render_options.document_private && !cx.cache.effective_visibilities.is_directly_public(cx.tcx, item_id); && !cx.cache.effective_visibilities.is_directly_public(cx.tcx, did); if is_private { return; } check_redundant_explicit_link(cx, item, hir_id, &doc); let module_id = match cx.tcx.def_kind(did) { DefKind::Mod if item.inner_docs(cx.tcx) => did, _ => find_nearest_parent_module(cx.tcx, did).unwrap(), }; let Some(resolutions) = cx.tcx.resolutions(()).doc_link_resolutions.get(&module_id.expect_local()) else { // If there's no resolutions in this module, // then we skip resolution querying to // avoid from panicking. return; }; check_redundant_explicit_link(cx, item, hir_id, &doc, &resolutions); } fn check_redundant_explicit_link<'md>("} {"_id":"doc-en-rust-1cb06804fd15e9c72367194a679e3df6b826d0c66aeedb1d43873d0a97e9e24b","title":"","text":"item: &Item, hir_id: HirId, doc: &'md str, resolutions: &DocLinkResMap, ) -> Option<()> { let mut broken_line_callback = |link: BrokenLink<'md>| Some((link.reference, \"\".into())); let mut offset_iter = Parser::new_with_broken_link_callback("} {"_id":"doc-en-rust-3c93a9d60f4e717229d8603751d7f0e327fd98f0d36f32cb4d368f7fc2897aa3","title":"","text":"Some(&mut broken_line_callback), ) .into_offset_iter(); let item_id = item.def_id()?; let module_id = match cx.tcx.def_kind(item_id) { DefKind::Mod if item.inner_docs(cx.tcx) => item_id, _ => find_nearest_parent_module(cx.tcx, item_id).unwrap(), }; let resolutions = cx.tcx.doc_link_resolutions(module_id); while let Some((event, link_range)) = offset_iter.next() { match event {"} {"_id":"doc-en-rust-7bb1fff9c3897a168bfa6313ce8218a895dda079d0a4401eed7bb5b180352bfb","title":"","text":" // compile-flags: --document-private-items #![deny(rustdoc::redundant_explicit_links)] mod webdavfs { pub struct A; pub struct B; } /// [`Vfs`][crate::Vfs] pub use webdavfs::A; //~^^ error: redundant explicit link target /// [`Vfs`] pub use webdavfs::B; pub struct Vfs; "} {"_id":"doc-en-rust-6837a907910a104363fc74e93629bad12aa30909a05184062509c9dac7f6c990","title":"","text":" error: redundant explicit link target --> $DIR/issue-120444-1.rs:10:13 | LL | /// [`Vfs`][crate::Vfs] | ----- ^^^^^^^^^^ explicit target is redundant | | | because label contains path that resolves to same destination | = note: when a link's destination is not specified, the label is used to resolve intra-doc links note: the lint level is defined here --> $DIR/issue-120444-1.rs:3:9 | LL | #![deny(rustdoc::redundant_explicit_links)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove explicit link target | LL | /// [`Vfs`] | ~~~~~~~ error: aborting due to 1 previous error "} {"_id":"doc-en-rust-b4801b3c4130e777153ff822c16193018945adc3907defd42289f7bde66f9527","title":"","text":" // compile-flags: --document-private-items #![deny(rustdoc::redundant_explicit_links)] pub mod webdavfs { pub struct A; pub struct B; } /// [`Vfs`][crate::Vfs] pub use webdavfs::A; //~^^ error: redundant explicit link target /// [`Vfs`] pub use webdavfs::B; pub struct Vfs; "} {"_id":"doc-en-rust-e5b41a9887b3409483377fce6e57fa843a82cae450a81f241353884d1950be6c","title":"","text":" error: redundant explicit link target --> $DIR/issue-120444-2.rs:10:13 | LL | /// [`Vfs`][crate::Vfs] | ----- ^^^^^^^^^^ explicit target is redundant | | | because label contains path that resolves to same destination | = note: when a link's destination is not specified, the label is used to resolve intra-doc links note: the lint level is defined here --> $DIR/issue-120444-2.rs:3:9 | LL | #![deny(rustdoc::redundant_explicit_links)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove explicit link target | LL | /// [`Vfs`] | ~~~~~~~ error: aborting due to 1 previous error "} {"_id":"doc-en-rust-b53be2f8e483b6864032ff0d8f638bd0474d74e2bac56c18251b8945aef93672","title":"","text":"\"arch\": \"x86_64\", \"cpu\": \"x86-64\", \"crt-static-respected\": true, \"data-layout\": \"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128\", \"data-layout\": \"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128\", \"dynamic-linking\": true, \"env\": \"gnu\", \"has-rpath\": true,"} {"_id":"doc-en-rust-a47f45326d665d88440f337adc838c3c9e08a0c03fdadc0eb8672871d5a4b122","title":"","text":"\"arch\": \"x86_64\", \"cpu\": \"x86-64\", \"crt-static-respected\": true, \"data-layout\": \"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128\", \"data-layout\": \"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128\", \"dynamic-linking\": true, \"env\": \"gnu\", \"executables\": true,"} {"_id":"doc-en-rust-0b5de7963f6f9795dcdacb065060c6ddf345e190c8e963dd20430700cb5d9c51","title":"","text":"{ \"data-layout\": \"e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-f64:32:64-f80:32-n8:16:32-S128\", \"data-layout\": \"e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-i128:128-f64:32:64-f80:32-n8:16:32-S128\", \"linker-flavor\": \"gcc\", \"llvm-target\": \"i686-unknown-linux-gnu\", \"target-endian\": \"little\","} {"_id":"doc-en-rust-5ec8c07e73b2a4e3d398a7d4036023ba9bd8c392e097168d2e477118ff4dcf40","title":"","text":"{ \"pre-link-args\": {\"gcc\": [\"-m64\"]}, \"data-layout\": \"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128\", \"data-layout\": \"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128\", \"linker-flavor\": \"gcc\", \"llvm-target\": \"x86_64-unknown-linux-gnu\", \"target-endian\": \"little\","} {"_id":"doc-en-rust-362cffde54b5f5f429c848babcb2c36958d881fab9d5b03cab1fdf4d0ca10800","title":"","text":"} } fn install_llvm_file(builder: &Builder<'_>, source: &Path, destination: &Path) { fn install_llvm_file( builder: &Builder<'_>, source: &Path, destination: &Path, install_symlink: bool, ) { if builder.config.dry_run() { return; } builder.install(source, destination, 0o644); if source.is_symlink() { // If we have a symlink like libLLVM-18.so -> libLLVM.so.18.1, install the target of the // symlink, which is what will actually get loaded at runtime. builder.install(&t!(fs::canonicalize(source)), destination, 0o644); if install_symlink { // If requested, also install the symlink. This is used by download-ci-llvm. let full_dest = destination.join(source.file_name().unwrap()); builder.copy(&source, &full_dest); } } else { builder.install(&source, destination, 0o644); } } /// Maybe add LLVM object files to the given destination lib-dir. Allows either static or dynamic linking. /// /// Returns whether the files were actually copied. fn maybe_install_llvm(builder: &Builder<'_>, target: TargetSelection, dst_libdir: &Path) -> bool { fn maybe_install_llvm( builder: &Builder<'_>, target: TargetSelection, dst_libdir: &Path, install_symlink: bool, ) -> bool { // If the LLVM was externally provided, then we don't currently copy // artifacts into the sysroot. This is not necessarily the right // choice (in particular, it will require the LLVM dylib to be in"} {"_id":"doc-en-rust-4348c4ad16871c215f49427ce9673ec43a964e9793e7b167250141b1b06025af","title":"","text":"} else { PathBuf::from(file) }; install_llvm_file(builder, &file, dst_libdir); install_llvm_file(builder, &file, dst_libdir, install_symlink); } !builder.config.dry_run() } else {"} {"_id":"doc-en-rust-d0c8fbb72849790c20aafa37de0a0fe7ff5904b41f18fa63ba9100d652b37223","title":"","text":"// dynamically linked; it is already included into librustc_llvm // statically. if builder.llvm_link_shared() { maybe_install_llvm(builder, target, &dst_libdir); maybe_install_llvm(builder, target, &dst_libdir, false); } }"} {"_id":"doc-en-rust-988a4cb06e4a0195fd1e253172c761c66a4b13bec8e08e2dcc34e7c6dcdccf66","title":"","text":"let mut tarball = Tarball::new(builder, \"rust-dev\", &target.triple); tarball.set_overlay(OverlayKind::LLVM); // LLVM requires a shared object symlink to exist on some platforms. tarball.permit_symlinks(true); builder.ensure(crate::core::build_steps::llvm::Llvm { target });"} {"_id":"doc-en-rust-6de69da82fe35cd2a7b67aff0af8e3d039a00a26bed7a218bcc8bc427ebfc44d","title":"","text":"// of `rustc-dev` to support the inherited `-lLLVM` when using the // compiler libraries. let dst_libdir = tarball.image_dir().join(\"lib\"); maybe_install_llvm(builder, target, &dst_libdir); maybe_install_llvm(builder, target, &dst_libdir, true); let link_type = if builder.llvm_link_shared() { \"dynamic\" } else { \"static\" }; t!(std::fs::write(tarball.image_dir().join(\"link-type.txt\"), link_type), dst_libdir);"} {"_id":"doc-en-rust-b9cc0f1354b1e8317757ce1a9c902047e480fcc816ebc8d0b67176dd393efbc8","title":"","text":"let out_dir = builder.llvm_out(target); let mut llvm_config_ret_dir = builder.llvm_out(builder.config.build); if (!builder.config.build.is_msvc() || builder.ninja()) && !builder.config.llvm_from_ci { llvm_config_ret_dir.push(\"build\"); } llvm_config_ret_dir.push(\"bin\"); let build_llvm_config = llvm_config_ret_dir.join(exe(\"llvm-config\", builder.config.build)); let llvm_cmake_dir = out_dir.join(\"lib/cmake/llvm\");"} {"_id":"doc-en-rust-d762eda0e70bc3639fe4fa8f8abbfc759725be3b1f0c36ab643fa5315004e487","title":"","text":" Subproject commit 9ea7f739f257b049a65deeb1f2455bb2ea021cfa Subproject commit 7973f3560287d750500718314a0fd4025bd8ac0e "} {"_id":"doc-en-rust-354431a59a9300c89b53bead029639a778e8049b38ecbd9640c4a5f7c0fc9df6","title":"","text":"})?; let libdir = env.build_artifacts().join(\"stage2\").join(\"lib\"); let llvm_lib = io::find_file_in_dir(&libdir, \"libLLVM\", \".so\")?; // The actual name will be something like libLLVM.so.18.1-rust-dev. let llvm_lib = io::find_file_in_dir(&libdir, \"libLLVM.so\", \"\")?; log::info!(\"Optimizing {llvm_lib} with BOLT\");"} {"_id":"doc-en-rust-969fd0cc1d039310f255de29def1aa40c109144ab184014af1342ab19594a5f3","title":"","text":"resolve_consider_marking_as_pub = consider marking `{$ident}` as `pub` in the imported module resolve_consider_move_macro_position = consider moving the definition of `{$ident}` before this call resolve_const_not_member_of_trait = const `{$const_}` is not a member of trait `{$trait_}` .label = not a member of trait `{$trait_}`"} {"_id":"doc-en-rust-f51ff4fe3b760bcb7bb6a654329771a166581053a6e8c77764db87e774206317","title":"","text":"attempt to use a non-constant value in a constant .suggestion = try using `Self` resolve_macro_defined_later = a macro with the same name exists, but it appears later at here resolve_macro_expected_found = expected {$expected}, found {$found} `{$macro_path}`"} {"_id":"doc-en-rust-9101940946c343904bc40b46fe0cbdb723d1f291ac9c41e32b6b4c29bfaf0f1b","title":"","text":"use thin_vec::{thin_vec, ThinVec}; use crate::errors::{AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion}; use crate::errors::{ConsiderAddingADerive, ExplicitUnsafeTraits, MaybeMissingMacroRulesName}; use crate::errors::{ ConsiderAddingADerive, ExplicitUnsafeTraits, MacroDefinedLater, MacroSuggMovePosition, MaybeMissingMacroRulesName, }; use crate::imports::{Import, ImportKind}; use crate::late::{PatternSource, Rib}; use crate::{errors as errs, BindingKey};"} {"_id":"doc-en-rust-93c1673ef84ee86430ef5b733ff5869de94f3a556d23516ab31711e68fc8253a","title":"","text":"return; } let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| { if unused_ident.name == ident.name { Some((def_id.clone(), unused_ident.clone())) } else { None } }); if let Some((def_id, unused_ident)) = unused_macro { let scope = self.local_macro_def_scopes[&def_id]; let parent_nearest = parent_scope.module.nearest_parent_mod(); if Some(parent_nearest) == scope.opt_def_id() { err.subdiagnostic(self.dcx(), MacroDefinedLater { span: unused_ident.span }); err.subdiagnostic(self.dcx(), MacroSuggMovePosition { span: ident.span, ident }); return; } } if self.macro_names.contains(&ident.normalize_to_macros_2_0()) { err.subdiagnostic(self.dcx(), AddedMacroUse); return;"} {"_id":"doc-en-rust-c853a297983c54e9e2ef7e5fabee5f808ba821041840cc22e36f04323f48752a","title":"","text":"} #[derive(Subdiagnostic)] #[note(resolve_macro_defined_later)] pub(crate) struct MacroDefinedLater { #[primary_span] pub(crate) span: Span, } #[derive(Subdiagnostic)] #[label(resolve_consider_move_macro_position)] pub(crate) struct MacroSuggMovePosition { #[primary_span] pub(crate) span: Span, pub(crate) ident: Ident, } #[derive(Subdiagnostic)] #[note(resolve_missing_macro_rules_name)] pub(crate) struct MaybeMissingMacroRulesName { #[primary_span]"} {"_id":"doc-en-rust-1cda3c2f87f32d37b2a43829f62ef353d341638181c30e01dd2dada9cec18b0f","title":"","text":" mod demo { fn hello() { something_later!(); //~ ERROR cannot find macro `something_later` in this scope } macro_rules! something_later { () => { println!(\"successfully expanded!\"); }; } } fn main() {} "} {"_id":"doc-en-rust-9bade7b6c526bae56a4c988e5028989593e107fe060105395125f61a378aa677","title":"","text":" error: cannot find macro `something_later` in this scope --> $DIR/defined-later-issue-121061-2.rs:3:9 | LL | something_later!(); | ^^^^^^^^^^^^^^^ consider moving the definition of `something_later` before this call | note: a macro with the same name exists, but it appears later at here --> $DIR/defined-later-issue-121061-2.rs:6:18 | LL | macro_rules! something_later { | ^^^^^^^^^^^^^^^ error: aborting due to 1 previous error "} {"_id":"doc-en-rust-e3df51e71a74896f4d81e03b17ccbe35bd943262809543c72aa8de00fddf58ba","title":"","text":" fn main() { something_later!(); //~ ERROR cannot find macro `something_later` in this scope } macro_rules! something_later { () => { println!(\"successfully expanded!\"); }; } "} {"_id":"doc-en-rust-d6c427851beb6b862bee3f647ceeb310a1dbb5b3817cd283baa744f509b6a4c8","title":"","text":" error: cannot find macro `something_later` in this scope --> $DIR/defined-later-issue-121061.rs:2:5 | LL | something_later!(); | ^^^^^^^^^^^^^^^ consider moving the definition of `something_later` before this call | note: a macro with the same name exists, but it appears later at here --> $DIR/defined-later-issue-121061.rs:5:14 | LL | macro_rules! something_later { | ^^^^^^^^^^^^^^^ error: aborting due to 1 previous error "} {"_id":"doc-en-rust-2f62e9fdd6a51894f56719194b2fe906b11d30d91bb224022ce2a67d3d09ea30","title":"","text":"ItemId { owner_id: self.owner_id } } /// Check if this is an [`ItemKind::Enum`], [`ItemKind::Struct`] or /// [`ItemKind::Union`]. pub fn is_adt(&self) -> bool { matches!(self.kind, ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..)) } expect_methods_self_kind! { expect_extern_crate, Option, ItemKind::ExternCrate(s), *s;"} {"_id":"doc-en-rust-ec6ead8cbd5a4ec3304c4aa41dfe004811f42d28f6d0a4e8e9e94e44adce68a7","title":"","text":"hir_analysis_invalid_union_field_sugg = wrap the field type in `ManuallyDrop<...>` hir_analysis_invalid_unnamed_field_ty = unnamed fields can only have struct or union types hir_analysis_late_bound_const_in_apit = `impl Trait` can only mention const parameters from an fn or impl .label = const parameter declared here"} {"_id":"doc-en-rust-f8c91bb8a5df49bd0d8f14e6da7631464b4dac091d61d88d4ff5cdb70541b54e","title":"","text":"for field in variant.fields.iter().filter(|f| f.is_unnamed()) { let field_ty = tcx.type_of(field.did).instantiate_identity(); if let Some(adt) = field_ty.ty_adt_def() && !adt.is_anonymous() && !adt.repr().c() && !adt.is_enum() { let field_ty_span = tcx.def_span(adt.did()); tcx.dcx().emit_err(errors::UnnamedFieldsRepr::FieldMissingReprC { span: tcx.def_span(field.did), field_ty_span, field_ty, field_adt_kind: adt.descr(), sugg_span: field_ty_span.shrink_to_lo(), }); if !adt.is_anonymous() && !adt.repr().c() { let field_ty_span = tcx.def_span(adt.did()); tcx.dcx().emit_err(errors::UnnamedFieldsRepr::FieldMissingReprC { span: tcx.def_span(field.did), field_ty_span, field_ty, field_adt_kind: adt.descr(), sugg_span: field_ty_span.shrink_to_lo(), }); } } else { tcx.dcx().emit_err(errors::InvalidUnnamedFieldTy { span: tcx.def_span(field.did) }); } } }"} {"_id":"doc-en-rust-057e1b4492e712a6636f211188e03cd87301095e22d69cfea82ed2f92858a200","title":"","text":"} } hir::TyKind::Path(hir::QPath::Resolved(_, hir::Path { res, .. })) => { self.check_field_in_nested_adt(self.tcx.adt_def(res.def_id()), field.span); // If this is a direct path to an ADT, we can check it // If this is a type alias or non-ADT, `check_unnamed_fields` should verify it if let Some(def_id) = res.opt_def_id() && let Some(local) = def_id.as_local() && let Node::Item(item) = self.tcx.hir_node_by_def_id(local) && item.is_adt() { self.check_field_in_nested_adt(self.tcx.adt_def(def_id), field.span); } } // Abort due to errors (there must be an error if an unnamed field // has any type kind other than an anonymous adt or a named adt)"} {"_id":"doc-en-rust-fdb877b11a47b75ae64eee3e79ed84e19d90068d5f72ca175b0cf8856a4c49f9","title":"","text":"} #[derive(Diagnostic)] #[diag(hir_analysis_invalid_unnamed_field_ty)] pub struct InvalidUnnamedFieldTy { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(hir_analysis_return_type_notation_on_non_rpitit)] pub(crate) struct ReturnTypeNotationOnNonRpitit<'tcx> { #[primary_span]"} {"_id":"doc-en-rust-e53de5dab4f73f64937420b6f3a1503cf834057d61135f7c4d915c5729c40ac0","title":"","text":" #[repr(C)] pub struct GoodStruct(()); pub struct BadStruct(()); pub enum BadEnum { A, B, } #[repr(C)] pub enum BadEnum2 { A, B, } pub type GoodAlias = GoodStruct; pub type BadAlias = i32; "} {"_id":"doc-en-rust-a75f09448ce31254197ab73270b249d82e507b01786f5927174c7b58034de3a9","title":"","text":" //@ aux-build:dep.rs // test for #121151 #![allow(incomplete_features)] #![feature(unnamed_fields)] extern crate dep; #[repr(C)] struct A { a: u8, } enum BadEnum { A, B, } #[repr(C)] enum BadEnum2 { A, B, } type MyStruct = A; type MyI32 = i32; #[repr(C)] struct L { _: i32, //~ ERROR unnamed fields can only have struct or union types _: MyI32, //~ ERROR unnamed fields can only have struct or union types _: BadEnum, //~ ERROR unnamed fields can only have struct or union types _: BadEnum2, //~ ERROR unnamed fields can only have struct or union types _: MyStruct, _: dep::BadStruct, //~ ERROR named type of unnamed field must have `#[repr(C)]` representation _: dep::BadEnum, //~ ERROR unnamed fields can only have struct or union types _: dep::BadEnum2, //~ ERROR unnamed fields can only have struct or union types _: dep::BadAlias, //~ ERROR unnamed fields can only have struct or union types _: dep::GoodAlias, _: dep::GoodStruct, } fn main() {} "} {"_id":"doc-en-rust-94745f05496a53e8c7c18fa92f575291c95ffad51d30b797ba5dab3ca3cb22c2","title":"","text":" error: unnamed fields can only have struct or union types --> $DIR/restrict_type_hir.rs:31:5 | LL | _: i32, | ^^^^^^ error: unnamed fields can only have struct or union types --> $DIR/restrict_type_hir.rs:32:5 | LL | _: MyI32, | ^^^^^^^^ error: unnamed fields can only have struct or union types --> $DIR/restrict_type_hir.rs:33:5 | LL | _: BadEnum, | ^^^^^^^^^^ error: unnamed fields can only have struct or union types --> $DIR/restrict_type_hir.rs:34:5 | LL | _: BadEnum2, | ^^^^^^^^^^^ error: named type of unnamed field must have `#[repr(C)]` representation --> $DIR/restrict_type_hir.rs:36:5 | LL | _: dep::BadStruct, | ^^^^^^^^^^^^^^^^^ unnamed field defined here | ::: $DIR/auxiliary/dep.rs:4:1 | LL | pub struct BadStruct(()); | -------------------- `BadStruct` defined here | help: add `#[repr(C)]` to this struct --> $DIR/auxiliary/dep.rs:4:1 | LL + #[repr(C)] LL | pub struct BadStruct(()); | error: unnamed fields can only have struct or union types --> $DIR/restrict_type_hir.rs:37:5 | LL | _: dep::BadEnum, | ^^^^^^^^^^^^^^^ error: unnamed fields can only have struct or union types --> $DIR/restrict_type_hir.rs:38:5 | LL | _: dep::BadEnum2, | ^^^^^^^^^^^^^^^^ error: unnamed fields can only have struct or union types --> $DIR/restrict_type_hir.rs:39:5 | LL | _: dep::BadAlias, | ^^^^^^^^^^^^^^^^ error: aborting due to 8 previous errors "} {"_id":"doc-en-rust-2b42d6e0340a2d88e7df4280c1e76e03e955ef5e67590a53874af43e60350766","title":"","text":"let func_ty = func.ty(body, tcx); if let ty::FnDef(callee, args) = *func_ty.kind() { let normalized_args = tcx.normalize_erasing_regions(param_env, args); let Ok(normalized_args) = tcx.try_normalize_erasing_regions(param_env, args) else { return false; }; let (callee, call_args) = if let Ok(Some(instance)) = Instance::resolve(tcx, param_env, callee, normalized_args) {"} {"_id":"doc-en-rust-1b969c291443a09aa1789cbd60ab19f884ffb559050b2d7ee99f6a977b85eae5","title":"","text":" fn problematic_function(material_surface_element: ()) where DefaultAllocator: FiniteElementAllocator<(), Space>, { let _: Point2 = material_surface_element.map_reference_coords().into(); } impl Allocator for DefaultAllocator where R::Value: DimName, //~ ERROR: `Value` not found for `R` { type Buffer = (); } impl Allocator for DefaultAllocator {} //~^ ERROR: conflicting implementations impl DimName for () {} impl DimName for u32 {} impl From> for Point { fn from(_: VectorN) -> Self { todo!() } } impl FiniteElement for () {} type VectorN = Matrix<>::Buffer>; type Point2 = Point; struct DefaultAllocator; struct Matrix(S); struct Point(N, D); trait Allocator { type Buffer; } trait DimName {} trait FiniteElementAllocator: Allocator + Allocator { } trait FiniteElement { fn map_reference_coords(&self) -> VectorN { todo!() } } fn main() {} "} {"_id":"doc-en-rust-c5a3b267d62e8ac7c1c49f768a1ad07322cd1aed3c48f4326b555069367ac2a6","title":"","text":" error[E0220]: associated type `Value` not found for `R` --> $DIR/normalize-conflicting-impls.rs:10:8 | LL | R::Value: DimName, | ^^^^^ associated type `Value` not found error[E0119]: conflicting implementations of trait `Allocator<_, ()>` for type `DefaultAllocator` --> $DIR/normalize-conflicting-impls.rs:14:1 | LL | / impl Allocator for DefaultAllocator LL | | where LL | | R::Value: DimName, | |______________________- first implementation here ... LL | impl Allocator for DefaultAllocator {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `DefaultAllocator` error: aborting due to 2 previous errors Some errors have detailed explanations: E0119, E0220. For more information about an error, try `rustc --explain E0119`. "} {"_id":"doc-en-rust-b5b64d9060e5f594e3b32ab3eee59689eec2b863179801e322b57b5090ca15eb","title":"","text":"#![allow(rustc::untranslatable_diagnostic)] use either::Either; use hir::ClosureKind; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag, MultiSpan};"} {"_id":"doc-en-rust-409f47c5f5bcfe300e2012c02feae4be96eff16a78e69b11439659d177d53052","title":"","text":"} else if let UseSpans::FnSelfUse { kind: CallKind::Normal { .. }, .. } = move_spans { // We already suggest cloning for these cases in `explain_captures`. } else if let UseSpans::ClosureUse { closure_kind: ClosureKind::Coroutine(CoroutineKind::Desugared(_, CoroutineSource::Block)), args_span: _, capture_kind_span: _, path_span, } = move_spans { self.suggest_cloning(err, ty, expr, path_span); } else if self.suggest_hoisting_call_outside_loop(err, expr) { // The place where the the type moves would be misleading to suggest clone. // #121466"} {"_id":"doc-en-rust-3c1f3cf9eec3d0b3d7bb299de038256e5923808814b5c4bd38dba351969290f4","title":"","text":"} // FIXME: We make sure that this is a normal top-level binding, // but we could suggest `todo!()` for all uninitalized bindings in the pattern pattern // but we could suggest `todo!()` for all uninitialized bindings in the pattern pattern if let hir::StmtKind::Let(hir::LetStmt { span, ty, init: None, pat, .. }) = &ex.kind && let hir::PatKind::Binding(..) = pat.kind"} {"_id":"doc-en-rust-cef54e1b91a40dbb60ff5b7e8a2ca89461d3cd4460fa89b306d83ef9312c90a4","title":"","text":"true } /// In a move error that occurs on a call wihtin a loop, we try to identify cases where cloning /// In a move error that occurs on a call within a loop, we try to identify cases where cloning /// the value would lead to a logic error. We infer these cases by seeing if the moved value is /// part of the logic to break the loop, either through an explicit `break` or if the expression /// is part of a `while let`."} {"_id":"doc-en-rust-a60addf36c3f7bda8274153931fb465bd6d9337e6d669790ce1b791cc0c97b6e","title":"","text":"{ // FIXME: We could check that the call's *parent* takes `&mut val` to make the // suggestion more targeted to the `mk_iter(val).next()` case. Maybe do that only to // check for wheter to suggest `let value` or `let mut value`. // check for whether to suggest `let value` or `let mut value`. let span = in_loop.span; if !finder.found_breaks.is_empty()"} {"_id":"doc-en-rust-d2bfcd116f9e9ecff13cfaad405983acbf185d1e159a055bc5da099f71524a4a","title":"","text":" //@ edition:2021 async fn clone_async_block(value: String) { for _ in 0..10 { async { //~ ERROR: use of moved value: `value` [E0382] drop(value); //~^ HELP: consider cloning the value if the performance cost is acceptable }.await } } fn main() {} "} {"_id":"doc-en-rust-daa75c6ad631ae958e1b60eda720a89948583d5e3b97c42d25d4c08747cd02a9","title":"","text":" error[E0382]: use of moved value: `value` --> $DIR/cloning-in-async-block-121547.rs:5:9 | LL | async fn clone_async_block(value: String) { | ----- move occurs because `value` has type `String`, which does not implement the `Copy` trait LL | for _ in 0..10 { | -------------- inside of this loop LL | / async { LL | | drop(value); | | ----- use occurs due to use in coroutine LL | | LL | | }.await | |_________^ value moved here, in previous iteration of loop | help: consider cloning the value if the performance cost is acceptable | LL | drop(value.clone()); | ++++++++ error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0382`. "} {"_id":"doc-en-rust-1d26127a37297f94c5109c4bf93b1b5634ee1d3e989db258f792953871186984","title":"","text":"/// `ManuallyDrop` to control drop order (needs to be dropped after all the nodes). pub(super) alloc: ManuallyDrop, // For dropck; the `Box` avoids making the `Unpin` impl more strict than before _marker: PhantomData>, _marker: PhantomData>, } #[stable(feature = \"btree_drop\", since = \"1.7.0\")]"} {"_id":"doc-en-rust-58b695892a42094c6ebe18ace508ecb5a64a62206f3e15b0936425f11a353752","title":"","text":"// If we have a symlink like libLLVM-18.so -> libLLVM.so.18.1, install the target of the // symlink, which is what will actually get loaded at runtime. builder.install(&t!(fs::canonicalize(source)), destination, 0o644); let full_dest = destination.join(source.file_name().unwrap()); if install_symlink { // If requested, also install the symlink. This is used by download-ci-llvm. let full_dest = destination.join(source.file_name().unwrap()); // For download-ci-llvm, also install the symlink, to match what LLVM does. Using a // symlink is fine here, as this is not a rustup component. builder.copy(&source, &full_dest); } else { // Otherwise, replace the symlink with an equivalent linker script. This is used when // projects like miri link against librustc_driver.so. We don't use a symlink, as // these are not allowed inside rustup components. let link = t!(fs::read_link(source)); t!(std::fs::write(full_dest, format!(\"INPUT({})n\", link.display()))); } } else { builder.install(&source, destination, 0o644);"} {"_id":"doc-en-rust-cac7414a63918b92c9851b33a8806324d3eaf1d50db8ac3ef791dd50409ab2aa","title":"","text":" Subproject commit 7973f3560287d750500718314a0fd4025bd8ac0e Subproject commit 84f190a4abf58bbd5301c0fc831f7a96acea246f "} {"_id":"doc-en-rust-b249af3ca5f28b15b5e56b40959909f68799cd95ef4d6892f3d6edd0ac1d8cea","title":"","text":"let suggest_eq = if self.token.kind == token::Dot && let _ = self.bump() && let mut snapshot = self.create_snapshot_for_diagnostic() && let Ok(_) = snapshot.parse_dot_suffix_expr( colon_sp, self.mk_expr_err( && let Ok(_) = snapshot .parse_dot_suffix_expr( colon_sp, self.dcx().delayed_bug(\"error during `:` -> `=` recovery\"), ), ) { self.mk_expr_err( colon_sp, self.dcx() .delayed_bug(\"error during `:` -> `=` recovery\"), ), ) .map_err(Diag::cancel) { true } else if let Some(op) = self.check_assoc_op() && op.node.can_continue_expr_unambiguously()"} {"_id":"doc-en-rust-92f31a331582dc0c595f1e67964deaa968fd1ceab95c55461d1f1c9a6ab224bc","title":"","text":" #![allow(unused)] fn test_122112() { // Make sure we don't ICE if parsing in recovery fails let _: std::env::temp_dir().join(&self, push: Box); //~ ERROR expected one of } fn main() { let _: std::env::temp_dir().join(\"foo\"); //~ ERROR expected one of }"} {"_id":"doc-en-rust-cae1c9a559ba26057182f8084bb1794fc8b328c2e752202757a0c4542d86cda1","title":"","text":"error: expected one of `!`, `+`, `->`, `::`, `;`, or `=`, found `.` --> $DIR/recover-colon-instead-of-eq-in-local.rs:2:32 --> $DIR/recover-colon-instead-of-eq-in-local.rs:5:32 | LL | let _: std::env::temp_dir().join(&self, push: Box); | - ^ expected one of `!`, `+`, `->`, `::`, `;`, or `=` | | | while parsing the type for `_` error: expected one of `!`, `+`, `->`, `::`, `;`, or `=`, found `.` --> $DIR/recover-colon-instead-of-eq-in-local.rs:9:32 | LL | let _: std::env::temp_dir().join(\"foo\"); | - ^ expected one of `!`, `+`, `->`, `::`, `;`, or `=`"} {"_id":"doc-en-rust-986113bf396a64edbb6c35fa1b4b62b16e1d715857d823189343de447d9aeea7","title":"","text":"| while parsing the type for `_` | help: use `=` if you meant to assign error: aborting due to 1 previous error error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-c117fc6fe1346a9b57a6cc5e194308dba3b07dc866e583b7ebe6d030ce1bee23","title":"","text":"kind: hir::GenericParamKind::Type { default: Some(ty), .. }, .. }) => vec![*ty], hir::Node::AnonConst(_) if let Some(const_param_id) = tcx.hir().opt_const_param_default_param_def_id(hir_id) && let hir::Node::GenericParam(hir::GenericParam { kind: hir::GenericParamKind::Const { ty, .. }, .. }) = tcx.hir_node_by_def_id(const_param_id) => { vec![*ty] } ref node => bug!(\"Unexpected node {:?}\", node), }, WellFormedLoc::Param { function: _, param_idx } => {"} {"_id":"doc-en-rust-92f743165cf1f5bb193bda611b78f8c63e6d4dc18880a06ed32f3d0324b97236","title":"","text":" trait Trait { //~^ ERROR cannot find value `bar` in this scope //~| ERROR cycle detected when computing type of `Trait::N` //~| ERROR cycle detected when computing type of `Trait::N` //~| ERROR `(dyn Trait<{const error}> + 'static)` is forbidden as the type of a const generic parameter //~| WARN trait objects without an explicit `dyn` are deprecated //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! fn fnc(&self) { } } fn main() {} "} {"_id":"doc-en-rust-0415cb5e6afec142882590e8b6827ef798050539582ca09187a62eeb4b6fd7e0","title":"","text":" error[E0425]: cannot find value `bar` in this scope --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:30 | LL | trait Trait { | ^^^ not found in this scope warning: trait objects without an explicit `dyn` are deprecated --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:22 | LL | trait Trait { | ^^^^^ | = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! = note: for more information, see = note: `#[warn(bare_trait_objects)]` on by default help: if this is an object-safe trait, use `dyn` | LL | trait Trait { | +++ error[E0391]: cycle detected when computing type of `Trait::N` --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:22 | LL | trait Trait { | ^^^^^ | = note: ...which immediately requires computing type of `Trait::N` again note: cycle used when computing explicit predicates of trait `Trait` --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:1 | LL | trait Trait { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information error[E0391]: cycle detected when computing type of `Trait::N` --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:13 | LL | trait Trait { | ^^^^^^^^^^^^^^^^^^^^ | = note: ...which immediately requires computing type of `Trait::N` again note: cycle used when computing explicit predicates of trait `Trait` --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:1 | LL | trait Trait { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information error: `(dyn Trait<{const error}> + 'static)` is forbidden as the type of a const generic parameter --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:22 | LL | trait Trait { | ^^^^^ | = note: the only supported types are integers, `bool` and `char` error: aborting due to 4 previous errors; 1 warning emitted Some errors have detailed explanations: E0391, E0425. For more information about an error, try `rustc --explain E0391`. "} {"_id":"doc-en-rust-ba78adb197cc37d12d9ebdeb210d224b6c964fe16ef68c0633014ecc54e0370c","title":"","text":"trait Trait { //~^ ERROR cannot find value `bar` in this scope //~| ERROR cycle detected when computing type of `Trait::N` //~| ERROR cycle detected when computing type of `Trait::N` //~| ERROR `(dyn Trait<{const error}> + 'static)` is forbidden as the type of a const generic parameter //~| WARN trait objects without an explicit `dyn` are deprecated //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! fn fnc(&self) { //~^ ERROR cannot find value `bar` in this scope //~| ERROR cycle detected when computing type of `Trait::N` //~| ERROR cycle detected when computing type of `Trait::N` //~| ERROR the trait `Trait` cannot be made into an object //~| ERROR the trait `Trait` cannot be made into an object //~| ERROR the trait `Trait` cannot be made into an object //~| ERROR `(dyn Trait<{const error}> + 'static)` is forbidden as the type of a const generic parameter //~| WARN trait objects without an explicit `dyn` are deprecated [bare_trait_objects] //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! //~| WARN trait objects without an explicit `dyn` are deprecated [bare_trait_objects] //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! fn fnc(&self) -> Trait { //~^ ERROR the name `N` is already used for a generic parameter in this item's generic parameters //~| ERROR expected value, found builtin type `u32` //~| ERROR defaults for const parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions //~| ERROR associated item referring to unboxed trait object for its own trait //~| ERROR the trait `Trait` cannot be made into an object //~| ERROR `(dyn Trait<{const error}> + 'static)` is forbidden as the type of a const generic parameter //~| WARN trait objects without an explicit `dyn` are deprecated [bare_trait_objects] //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! //~| WARN trait objects without an explicit `dyn` are deprecated [bare_trait_objects] //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! //~| WARN trait objects without an explicit `dyn` are deprecated [bare_trait_objects] //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! bar //~^ ERROR cannot find value `bar` in this scope } }"} {"_id":"doc-en-rust-c82ca42a1cac968b781d07fc24f5919a19cb0b7551dd52f6c550a2221fbda3c8","title":"","text":" error[E0403]: the name `N` is already used for a generic parameter in this item's generic parameters --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:18 | LL | trait Trait { | - first use of `N` ... LL | fn fnc(&self) -> Trait { | ^ already used error[E0425]: cannot find value `bar` in this scope --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:30 | LL | trait Trait { | ^^^ not found in this scope error[E0423]: expected value, found builtin type `u32` --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:29 | LL | fn fnc(&self) -> Trait { | ^^^ not a value error[E0425]: cannot find value `bar` in this scope --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:26:9 | LL | bar | ^^^ not found in this scope warning: trait objects without an explicit `dyn` are deprecated --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:22 |"} {"_id":"doc-en-rust-d63f696f802b42ec174b0eaca5200020c7f9745006b975ebc5d8ddb8bd7e5e15","title":"","text":"| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information error: defaults for const parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:12 | LL | fn fnc(&self) -> Trait { | ^^^^^^^^^^^^^^^^^^^^ warning: trait objects without an explicit `dyn` are deprecated --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:21 | LL | fn fnc(&self) -> Trait { | ^^^^^ | = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! = note: for more information, see help: if this is an object-safe trait, use `dyn` | LL | fn fnc(&self) -> Trait { | +++ warning: trait objects without an explicit `dyn` are deprecated --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:44 | LL | fn fnc(&self) -> Trait { | ^^^^^ | = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! = note: for more information, see help: if this is an object-safe trait, use `dyn` | LL | fn fnc(&self) -> dyn Trait { | +++ warning: trait objects without an explicit `dyn` are deprecated --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:22 | LL | trait Trait { | ^^^^^ | = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! = note: for more information, see = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` help: if this is an object-safe trait, use `dyn` | LL | trait Trait { | +++ error[E0038]: the trait `Trait` cannot be made into an object --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:22 | LL | trait Trait { | ^^^^^ `Trait` cannot be made into an object | note: for a trait to be \"object safe\" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:8 | LL | trait Trait { | ----- this trait cannot be made into an object... ... LL | fn fnc(&self) -> Trait { | ^^^ ...because method `fnc` has generic type parameters = help: consider moving `fnc` to another trait error[E0038]: the trait `Trait` cannot be made into an object --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:13 | LL | trait Trait { | ^^^^^^^^^^^^^^^^^^^^ `Trait` cannot be made into an object | note: for a trait to be \"object safe\" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:8 | LL | trait Trait { | ----- this trait cannot be made into an object... ... LL | fn fnc(&self) -> Trait { | ^^^ ...because method `fnc` has generic type parameters = help: consider moving `fnc` to another trait error: `(dyn Trait<{const error}> + 'static)` is forbidden as the type of a const generic parameter --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:22 |"} {"_id":"doc-en-rust-ca2bdf5458fd682f55038d981b90eb8bff27b7fc1254989ca91413448c870409","title":"","text":"| = note: the only supported types are integers, `bool` and `char` error: aborting due to 4 previous errors; 1 warning emitted error: associated item referring to unboxed trait object for its own trait --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:44 | LL | trait Trait { | ----- in this trait ... LL | fn fnc(&self) -> Trait { | ^^^^^ | help: you might have meant to use `Self` to refer to the implementing type | LL | fn fnc(&self) -> Self { | ~~~~ warning: trait objects without an explicit `dyn` are deprecated --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:21 | LL | fn fnc(&self) -> Trait { | ^^^^^ | = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! = note: for more information, see = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` help: if this is an object-safe trait, use `dyn` | LL | fn fnc(&self) -> Trait { | +++ error[E0038]: the trait `Trait` cannot be made into an object --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:21 | LL | fn fnc(&self) -> Trait { | ^^^^^ `Trait` cannot be made into an object | note: for a trait to be \"object safe\" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:8 | LL | trait Trait { | ----- this trait cannot be made into an object... ... LL | fn fnc(&self) -> Trait { | ^^^ ...because method `fnc` has generic type parameters = help: consider moving `fnc` to another trait error[E0038]: the trait `Trait` cannot be made into an object --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:1:13 | LL | trait Trait { | ^^^^^^^^^^^^^^^^^^^^ `Trait` cannot be made into an object | note: for a trait to be \"object safe\" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:8 | LL | trait Trait { | ----- this trait cannot be made into an object... ... LL | fn fnc(&self) -> Trait { | ^^^ ...because method `fnc` has generic type parameters = help: consider moving `fnc` to another trait = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: `(dyn Trait<{const error}> + 'static)` is forbidden as the type of a const generic parameter --> $DIR/ice-hir-wf-check-anon-const-issue-122199.rs:13:21 | LL | fn fnc(&self) -> Trait { | ^^^^^ | = note: the only supported types are integers, `bool` and `char` error: aborting due to 14 previous errors; 5 warnings emitted Some errors have detailed explanations: E0391, E0425. For more information about an error, try `rustc --explain E0391`. Some errors have detailed explanations: E0038, E0391, E0403, E0423, E0425. For more information about an error, try `rustc --explain E0038`. "} {"_id":"doc-en-rust-51addcf701c99d0cc6e215043500e871039c907816b052c9dd86000f3f7eb841","title":"","text":"use middle::freevars; use middle::pat_util; use middle::ty; use middle::typeck::MethodCall; use middle::typeck::{MethodCall, MethodObject, MethodOrigin, MethodParam}; use middle::typeck::{MethodStatic}; use middle::typeck; use syntax::ast; use syntax::codemap::{Span}; use util::ppaux::Repr; use std::gc::Gc; use syntax::ast; use syntax::codemap::Span; /////////////////////////////////////////////////////////////////////////// // The Delegate trait"} {"_id":"doc-en-rust-865d0fe2d197203290d0d84bc5c50ccc2517bf935f2ba43c34cd0e8874291a37","title":"","text":"WriteAndRead, // x += y } enum OverloadedCallType { FnOverloadedCall, FnMutOverloadedCall, FnOnceOverloadedCall, } impl OverloadedCallType { fn from_trait_id(tcx: &ty::ctxt, trait_id: ast::DefId) -> OverloadedCallType { for &(maybe_function_trait, overloaded_call_type) in [ (tcx.lang_items.fn_once_trait(), FnOnceOverloadedCall), (tcx.lang_items.fn_mut_trait(), FnMutOverloadedCall), (tcx.lang_items.fn_trait(), FnOverloadedCall) ].iter() { match maybe_function_trait { Some(function_trait) if function_trait == trait_id => { return overloaded_call_type } _ => continue, } } tcx.sess.bug(\"overloaded call didn't map to known function trait\") } fn from_method_id(tcx: &ty::ctxt, method_id: ast::DefId) -> OverloadedCallType { let method_descriptor = match tcx.methods.borrow_mut().find(&method_id) { None => { tcx.sess.bug(\"overloaded call method wasn't in method map\") } Some(ref method_descriptor) => (*method_descriptor).clone(), }; let impl_id = match method_descriptor.container { ty::TraitContainer(_) => { tcx.sess.bug(\"statically resolved overloaded call method belonged to a trait?!\") } ty::ImplContainer(impl_id) => impl_id, }; let trait_ref = match ty::impl_trait_ref(tcx, impl_id) { None => { tcx.sess.bug(\"statically resolved overloaded call impl didn't implement a trait?!\") } Some(ref trait_ref) => (*trait_ref).clone(), }; OverloadedCallType::from_trait_id(tcx, trait_ref.def_id) } fn from_method_origin(tcx: &ty::ctxt, origin: &MethodOrigin) -> OverloadedCallType { match *origin { MethodStatic(def_id) => { OverloadedCallType::from_method_id(tcx, def_id) } MethodParam(ref method_param) => { OverloadedCallType::from_trait_id(tcx, method_param.trait_id) } MethodObject(ref method_object) => { OverloadedCallType::from_trait_id(tcx, method_object.trait_id) } } } } /////////////////////////////////////////////////////////////////////////// // The ExprUseVisitor type //"} {"_id":"doc-en-rust-e41921f7dc90fed33c65fc9fa5c99a12f8e8b577902ebfe76a5bf30cd256609d","title":"","text":"} } _ => { match self.tcx() .method_map .borrow() .find(&MethodCall::expr(call.id)) { Some(_) => { // FIXME(#14774, pcwalton): Implement this. let overloaded_call_type = match self.tcx() .method_map .borrow() .find(&MethodCall::expr(call.id)) { Some(ref method_callee) => { OverloadedCallType::from_method_origin( self.tcx(), &method_callee.origin) } None => { self.tcx().sess.span_bug( callee.span, format!(\"unexpected callee type {}\", callee_ty.repr(self.tcx())).as_slice()); callee_ty.repr(self.tcx())).as_slice()) } }; match overloaded_call_type { FnMutOverloadedCall => { self.borrow_expr(callee, ty::ReScope(call.id), ty::MutBorrow, ClosureInvocation); } FnOverloadedCall => { self.borrow_expr(callee, ty::ReScope(call.id), ty::ImmBorrow, ClosureInvocation); } FnOnceOverloadedCall => self.consume_expr(callee), } } }"} {"_id":"doc-en-rust-e0f2477cc0a13132c6a6871d91660c7b5abddfe131ead6c62af5f4e16fc766b1","title":"","text":" // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(overloaded_calls)] use std::ops::{Fn, FnMut, FnOnce}; struct SFn { x: int, y: int, } impl Fn<(int,),int> for SFn { fn call(&self, (z,): (int,)) -> int { self.x * self.y * z } } struct SFnMut { x: int, y: int, } impl FnMut<(int,),int> for SFnMut { fn call_mut(&mut self, (z,): (int,)) -> int { self.x * self.y * z } } struct SFnOnce { x: String, } impl FnOnce<(String,),uint> for SFnOnce { fn call_once(self, (z,): (String,)) -> uint { self.x.len() + z.len() } } fn f() { let mut s = SFn { x: 1, y: 2, }; let sp = &mut s; s(3); //~ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable //~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable } fn g() { let s = SFnMut { x: 1, y: 2, }; s(3); //~ ERROR cannot borrow immutable local variable `s` as mutable } fn h() { let s = SFnOnce { x: \"hello\".to_string(), }; s(\" world\".to_string()); s(\" world\".to_string()); //~ ERROR use of moved value: `s` } fn main() {} "} {"_id":"doc-en-rust-ce861884c52ca28ee60572a10155caa11c72f20a122aa9cccf9e07d0b081ddb4","title":"","text":"pub UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, Warn, \"unrecognized or malformed diagnostic attribute\", @feature_gate = sym::diagnostic_namespace; } declare_lint! {"} {"_id":"doc-en-rust-9993eaa73a3a6f8380d3821183b78601ea72bbcc45edb54292ce593c6d988fd0","title":"","text":" #![deny(unknown_or_malformed_diagnostic_attributes)] #[diagnostic::unknown_attribute] //~^ERROR unknown diagnostic attribute struct Foo; fn main() {} "} {"_id":"doc-en-rust-495cd4565328bad16c4ffede6ce21bfc827d581129161057d5ed85af6f6c2f0d","title":"","text":" error: unknown diagnostic attribute --> $DIR/deny_malformed_attribute.rs:3:15 | LL | #[diagnostic::unknown_attribute] | ^^^^^^^^^^^^^^^^^ | note: the lint level is defined here --> $DIR/deny_malformed_attribute.rs:1:9 | LL | #![deny(unknown_or_malformed_diagnostic_attributes)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error "} {"_id":"doc-en-rust-5b18900581b3d5ab65f62cfe9dcde69f6271f80eff2477354f81337599f3193d","title":"","text":"generics_of => { table } inferred_outlives_of => { table_defaulted_array } super_predicates_of => { table } implied_predicates_of => { table } type_of => { table } type_alias_is_lazy => { cdata.root.tables.type_alias_is_lazy.get(cdata, def_id.index) } variances_of => { table }"} {"_id":"doc-en-rust-dea68d556942d1a052c2248de5963ab421b185e45a50815d2a71c075215f89b0","title":"","text":".map(|lazy| lazy.decode((cdata, tcx))) .process_decoded(tcx, || panic!(\"{def_id:?} does not have trait_impl_trait_tys\"))) } implied_predicates_of => { cdata .root .tables .implied_predicates_of .get(cdata, def_id.index) .map(|lazy| lazy.decode((cdata, tcx))) .unwrap_or_else(|| { debug_assert_eq!(tcx.def_kind(def_id), DefKind::Trait); tcx.super_predicates_of(def_id) }) } associated_types_for_impl_traits_in_associated_fn => { table_defaulted_array }"} {"_id":"doc-en-rust-2782c47b5ac722cf97c57720a810c0619139cd0080f7faff1698f5898b45fc9c","title":"","text":"if let DefKind::Trait = def_kind { record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id)); record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id)); record!(self.tables.implied_predicates_of[def_id] <- self.tcx.implied_predicates_of(def_id)); let module_children = self.tcx.module_children_local(local_id); record_array!(self.tables.module_children_non_reexports[def_id] <-"} {"_id":"doc-en-rust-9c973633c63d645c0de540c346f0fb7d566b555b01b7ffce3a078ac27910736e","title":"","text":" pub trait Bar: Super {} pub trait Super { type SuperAssoc; } pub trait Bound {} "} {"_id":"doc-en-rust-24e05572bc32be741f57a94cd225572b6bb9c6933f06334c60cc34d6718e6031","title":"","text":" //@ aux-build:implied-predicates.rs //@ check-pass extern crate implied_predicates; use implied_predicates::Bar; fn bar() {} fn main() {} "} {"_id":"doc-en-rust-38c111d96b22b7d0c2d9b042cd82676bde3a35a8e8252e2342d2877b5176e813","title":"","text":" // Don't panic when iterating through the `hir::Map::parent_iter` of an RPITIT. pub trait Foo { fn demo() -> impl Foo //~^ ERROR the trait bound `String: Copy` is not satisfied where String: Copy; //~^ ERROR the trait bound `String: Copy` is not satisfied } fn main() {} "} {"_id":"doc-en-rust-fe77f07fe4200529d750fc356303ec66d634c969beb2eb60fa1f535639beba95","title":"","text":" error[E0277]: the trait bound `String: Copy` is not satisfied --> $DIR/synthetic-hir-has-parent.rs:7:9 | LL | String: Copy; | ^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` | = help: see issue #48214 help: add `#![feature(trivial_bounds)]` to the crate attributes to enable | LL + #![feature(trivial_bounds)] | error[E0277]: the trait bound `String: Copy` is not satisfied --> $DIR/synthetic-hir-has-parent.rs:4:18 | LL | fn demo() -> impl Foo | ^^^^^^^^ the trait `Copy` is not implemented for `String` | = help: see issue #48214 help: add `#![feature(trivial_bounds)]` to the crate attributes to enable | LL + #![feature(trivial_bounds)] | error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-8ed2cbb1d986be7be00b9f3d371be3c8c76999d42aa976188e401ffa7c88cba1","title":"","text":"pat: &'tcx hir::Pat<'tcx>, ty: Ty<'tcx>, ) { struct V<'tcx> { tcx: TyCtxt<'tcx>, struct V { pat_hir_ids: Vec, } impl<'tcx> Visitor<'tcx> for V<'tcx> { type NestedFilter = rustc_middle::hir::nested_filter::All; fn nested_visit_map(&mut self) -> Self::Map { self.tcx.hir() } impl<'tcx> Visitor<'tcx> for V { fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { self.pat_hir_ids.push(p.hir_id); hir::intravisit::walk_pat(self, p);"} {"_id":"doc-en-rust-8aecd7cac443c467e6c58a2eb9439424a5c4f74410063064df2f451121341dc2","title":"","text":"let err = Ty::new_error(self.tcx, guar); self.write_ty(hir_id, err); self.write_ty(pat.hir_id, err); let mut visitor = V { tcx: self.tcx, pat_hir_ids: vec![] }; let mut visitor = V { pat_hir_ids: vec![] }; hir::intravisit::walk_pat(&mut visitor, pat); // Mark all the subpatterns as `{type error}` as well. This allows errors for specific // subpatterns to be silenced."} {"_id":"doc-en-rust-f6ac8de6c867ecdc1742233abdbb8d06fd8d4e7e555bb2e6b4b3d86cfc269bf2","title":"","text":" fn main() { let str::<{fn str() { let str::T>>::as_bytes; }}, T>::as_bytes; //~^ ERROR expected a pattern, found an expression //~| ERROR cannot find type `T` in this scope //~| ERROR type and const arguments are not allowed on builtin type `str` //~| ERROR expected unit struct, unit variant or constant, found associated function `str<, T>::as_bytes` } "} {"_id":"doc-en-rust-8ebbd5026cb072e9046fb015b6f15aaedfc77c441aa7030d87c5610425ad6abb","title":"","text":" error: expected a pattern, found an expression --> $DIR/ensure-overriding-bindings-in-pattern-with-ty-err-doesnt-ice.rs:2:31 | LL | let str::<{fn str() { let str::T>>::as_bytes; }}, T>::as_bytes; | ^^^^^^^^^^^^^^^^^^ arbitrary expressions are not allowed in patterns error[E0412]: cannot find type `T` in this scope --> $DIR/ensure-overriding-bindings-in-pattern-with-ty-err-doesnt-ice.rs:2:55 | LL | let str::<{fn str() { let str::T>>::as_bytes; }}, T>::as_bytes; | ^ not found in this scope error[E0109]: type and const arguments are not allowed on builtin type `str` --> $DIR/ensure-overriding-bindings-in-pattern-with-ty-err-doesnt-ice.rs:2:15 | LL | let str::<{fn str() { let str::T>>::as_bytes; }}, T>::as_bytes; | --- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^ type and const arguments not allowed | | | not allowed on builtin type `str` | help: primitive type `str` doesn't have generic parameters | LL - let str::<{fn str() { let str::T>>::as_bytes; }}, T>::as_bytes; LL + let str::as_bytes; | error[E0533]: expected unit struct, unit variant or constant, found associated function `str<, T>::as_bytes` --> $DIR/ensure-overriding-bindings-in-pattern-with-ty-err-doesnt-ice.rs:2:9 | LL | let str::<{fn str() { let str::T>>::as_bytes; }}, T>::as_bytes; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not a unit struct, unit variant or constant error: aborting due to 4 previous errors Some errors have detailed explanations: E0109, E0412, E0533. For more information about an error, try `rustc --explain E0109`. "} {"_id":"doc-en-rust-29db9c75bc544bdb27e0772dbfa24e3c318c6a7f8c09308087cb87d48b9e6ee2","title":"","text":"impl_clone! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 f16 f32 f64 f128 bool char }"} {"_id":"doc-en-rust-faeba91f66b3aba882d45612db4e20899a8cbe595c7bcdf5e6f18659e668f377","title":"","text":"} partial_eq_impl! { bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f16 f32 f64 f128 } macro_rules! eq_impl {"} {"_id":"doc-en-rust-306fb1502cfa479e4907e0d76d14768ae47ae72cea1666ea57add655ceb64f9a","title":"","text":"} } partial_ord_impl! { f32 f64 } partial_ord_impl! { f16 f32 f64 f128 } macro_rules! ord_impl { ($($t:ty)*) => ($("} {"_id":"doc-en-rust-7ed53632cbca982385029223aa69ede85d60daa5e3ec72dd962bdb7438ffa812","title":"","text":"default_impl! { i64, 0, \"Returns the default value of `0`\" } default_impl! { i128, 0, \"Returns the default value of `0`\" } #[cfg(not(bootstrap))] default_impl! { f16, 0.0f16, \"Returns the default value of `0.0`\" } default_impl! { f32, 0.0f32, \"Returns the default value of `0.0`\" } default_impl! { f64, 0.0f64, \"Returns the default value of `0.0`\" } #[cfg(not(bootstrap))] default_impl! { f128, 0.0f128, \"Returns the default value of `0.0`\" } "} {"_id":"doc-en-rust-fdfc29f596faddba258e755c661a1007e34bc7c3f9b8f03c7cfc93814c382ed3","title":"","text":"#![feature(doc_notable_trait)] #![feature(effects)] #![feature(extern_types)] #![feature(f128)] #![feature(f16)] #![feature(freeze_impls)] #![feature(fundamental)] #![feature(generic_arg_infer)]"} {"_id":"doc-en-rust-949418b1fa6bd9f413e0e00abbffc9196a2ef4899bd5c0eab64272543caae28e","title":"","text":"Copy for usize, u8, u16, u32, u64, u128, isize, i8, i16, i32, i64, i128, f32, f64, f16, f32, f64, f128, bool, char, {T: ?Sized} *const T, {T: ?Sized} *mut T,"} {"_id":"doc-en-rust-8aceb90fdfe935edbf0b69f24cb1b7c0c071a8dad2506be00136721c63ea847d","title":"","text":"| = help: the trait `PartialEq` is not implemented for `&&{integer}` = help: the following other types implement trait `PartialEq`: f128 f16 f32 f64 i128 i16 i32 i64 i8 isize and 6 others and 8 others error[E0369]: binary operation `==` cannot be applied to type `Foo` --> $DIR/binary-op-suggest-deref.rs:60:13"} {"_id":"doc-en-rust-d415180b269604fd77637d75b502b15067124b68ee2e55f4567623a18f6fc6d1","title":"","text":"| = help: the trait `PartialOrd` is not implemented for `{integer}` = help: the following other types implement trait `PartialOrd`: f128 f16 f32 f64 i128 i16 i32 i64 i8 isize and 6 others and 8 others error[E0277]: can't compare `{integer}` with `Result<{integer}, _>` --> $DIR/binops.rs:7:7"} {"_id":"doc-en-rust-5122621d8b92e8736e791210f6595ac29ba28a897134ff095df56bf93b039578","title":"","text":"| = help: the trait `PartialEq>` is not implemented for `{integer}` = help: the following other types implement trait `PartialEq`: f128 f16 f32 f64 i128 i16 i32 i64 i8 isize and 6 others and 8 others error: aborting due to 6 previous errors"} {"_id":"doc-en-rust-399016b6a04b7613eab1c6fc704d04bfbefbc11c54caec1fdc3119688bb61bfc","title":"","text":"let expn_data = prefix_span.ctxt().outer_expn_data(); if expn_data.edition >= Edition::Edition2021 { let mut silence = false; // In Rust 2021, this is a hard error. let sugg = if prefix == \"rb\" { Some(errors::UnknownPrefixSugg::UseBr(prefix_span))"} {"_id":"doc-en-rust-4eb160549a8b0bc6ffa20bbdc16cfa938ba08b339c8a65298f8b85ae2ae81929","title":"","text":"if self.cursor.first() == ''' && let Some(start) = self.last_lifetime && self.cursor.third() != ''' && let end = self.mk_sp(self.pos, self.pos + BytePos(1)) && !self.psess.source_map().is_multiline(start.until(end)) { // An \"unclosed `char`\" error will be emitted already, silence redundant error. silence = true; Some(errors::UnknownPrefixSugg::MeantStr { start, end: self.mk_sp(self.pos, self.pos + BytePos(1)), }) // FIXME: An \"unclosed `char`\" error will be emitted already in some cases, // but it's hard to silence this error while not also silencing important cases // too. We should use the error stashing machinery instead. Some(errors::UnknownPrefixSugg::MeantStr { start, end }) } else { Some(errors::UnknownPrefixSugg::Whitespace(prefix_span.shrink_to_hi())) } } else { None }; let err = errors::UnknownPrefix { span: prefix_span, prefix, sugg }; if silence { self.dcx().create_err(err).delay_as_bug(); } else { self.dcx().emit_err(err); } self.dcx().emit_err(errors::UnknownPrefix { span: prefix_span, prefix, sugg }); } else { // Before Rust 2021, only emit a lint for migration. self.psess.buffer_lint_with_diagnostic("} {"_id":"doc-en-rust-d018f0aab1c7fe2ecb9df4909e37e1ac17b7ba2e77a4ada893791bf3dac73572","title":"","text":" //@ edition:2021 macro_rules! a { ( ) => { impl<'b> c for d { e:: //~ ERROR prefix `f` is unknown } }; } fn main() {} "} {"_id":"doc-en-rust-f0c63ed35c906c054b6913cba63bb2f3cdc010a947be63d3dd5ac73b701c3cc6","title":"","text":" error: prefix `f` is unknown --> $DIR/dont-ice-on-invalid-lifetime-in-macro-definition.rs:5:17 | LL | e:: | ^ unknown prefix | = note: prefixed identifiers and literals are reserved since Rust 2021 help: consider inserting whitespace here | LL | e:: | + error: aborting due to 1 previous error "} {"_id":"doc-en-rust-0d16cedddbfede40fe5bd738e16658839441e79139cd48967347cbd0d866d385","title":"","text":"//@[rust2021] edition:2021 fn main() { println!('hello world'); //[rust2015,rust2018,rust2021]~^ ERROR unterminated character literal //~^ ERROR unterminated character literal //[rust2021]~| ERROR prefix `world` is unknown }"} {"_id":"doc-en-rust-49472db796da5bbf030fc4d563dcf7893fcf450e4291a852017b715be8d71d45","title":"","text":" error: prefix `world` is unknown --> $DIR/lex-bad-str-literal-as-char-3.rs:5:21 | LL | println!('hello world'); | ^^^^^ unknown prefix | = note: prefixed identifiers and literals are reserved since Rust 2021 help: if you meant to write a string literal, use double quotes | LL | println!(\"hello world\"); | ~ ~ error[E0762]: unterminated character literal --> $DIR/lex-bad-str-literal-as-char-3.rs:5:26 |"} {"_id":"doc-en-rust-8fa9b58a2688bc2e58a2ac23de2b9199e36bc4405ae0d5c5f38e72e2f522b1a3","title":"","text":"LL | println!(\"hello world\"); | ~ ~ error: aborting due to 1 previous error error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0762`."} {"_id":"doc-en-rust-c9f23288d747730f8bc41609e334dbdbf9b597c2dfac94c28aa1044f3f5a8759","title":"","text":" //@edition:2021 macro_rules! foo { () => { println!('hello world'); //~^ ERROR unterminated character literal //~| ERROR prefix `world` is unknown } } fn main() {} "} {"_id":"doc-en-rust-e5cc6500863551cbc02e536cec502a79604dfb175e013d7208689b70e982809f","title":"","text":" error: prefix `world` is unknown --> $DIR/lex-bad-str-literal-as-char-4.rs:4:25 | LL | println!('hello world'); | ^^^^^ unknown prefix | = note: prefixed identifiers and literals are reserved since Rust 2021 help: if you meant to write a string literal, use double quotes | LL | println!(\"hello world\"); | ~ ~ error[E0762]: unterminated character literal --> $DIR/lex-bad-str-literal-as-char-4.rs:4:30 | LL | println!('hello world'); | ^^^ | help: if you meant to write a string literal, use double quotes | LL | println!(\"hello world\"); | ~ ~ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0762`. "} {"_id":"doc-en-rust-025dbbf28608e3039af413b1412856f4237b3c411781254cf0d17a38c3a13e74","title":"","text":"ast::Path { span, segments, tokens: None } } pub fn macro_call( &self, span: Span, path: ast::Path, delim: ast::token::Delimiter, tokens: ast::tokenstream::TokenStream, ) -> P { P(ast::MacCall { path, args: P(ast::DelimArgs { dspan: ast::tokenstream::DelimSpan { open: span, close: span }, delim, tokens, }), }) } pub fn ty_mt(&self, ty: P, mutbl: ast::Mutability) -> ast::MutTy { ast::MutTy { ty, mutbl } }"} {"_id":"doc-en-rust-31782d9a667c924ef28d20b87ad067e10910658551613d29319285eca3ce236e","title":"","text":"self.expr(span, ast::ExprKind::Field(expr, field)) } pub fn expr_macro_call(&self, span: Span, call: P) -> P { self.expr(span, ast::ExprKind::MacCall(call)) } pub fn expr_binary( &self, sp: Span,"} {"_id":"doc-en-rust-da16b46f43e6cb5334f9d5b775b45c75a766ae0d031db885ca51f721390fea23","title":"","text":"self.expr(sp, ast::ExprKind::Tup(exprs)) } pub fn expr_fail(&self, span: Span, msg: Symbol) -> P { self.expr_call_global( pub fn expr_unreachable(&self, span: Span) -> P { self.expr_macro_call( span, [sym::std, sym::rt, sym::begin_panic].iter().map(|s| Ident::new(*s, span)).collect(), thin_vec![self.expr_str(span, msg)], self.macro_call( span, self.path_global( span, [sym::std, sym::unreachable].map(|s| Ident::new(s, span)).to_vec(), ), ast::token::Delimiter::Parenthesis, ast::tokenstream::TokenStream::default(), ), ) } pub fn expr_unreachable(&self, span: Span) -> P { self.expr_fail(span, Symbol::intern(\"internal error: entered unreachable code\")) } pub fn expr_ok(&self, sp: Span, expr: P) -> P { let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]); self.expr_call_global(sp, ok, thin_vec![expr])"} {"_id":"doc-en-rust-8e0514a8e70dc8dbc0700987a8f41ac4a48f94226f63f4336b86101dab92d52b","title":"","text":" #![crate_type = \"lib\"] pub trait Decoder { type Error; fn read_enum(&mut self, name: &str, f: F) -> Result where F: FnOnce(&mut Self) -> Result; fn read_enum_variant(&mut self, names: &[&str], f: F) -> Result where F: FnMut(&mut Self, usize) -> Result; } pub trait Decodable: Sized { fn decode(d: &mut D) -> Result; } "} {"_id":"doc-en-rust-d01dfe42fb6e4b518af1d70f31dd1d11aa678e46560f0c382449d70987d56702","title":"","text":" //@ check-pass //@ edition:2021 //@ aux-build:rustc-serialize.rs #![crate_type = \"lib\"] #![allow(deprecated, soft_unstable)] extern crate rustc_serialize; #[derive(RustcDecodable)] pub enum Foo {} "} {"_id":"doc-en-rust-2af954f435232677e362535acb6c520d7284c4538e281bde82b57d0303bea1e5","title":"","text":" Future incompatibility report: Future breakage diagnostic: warning: use of unstable library feature 'rustc_encodable_decodable': derive macro for `rustc-serialize`; should not be used in new code --> $DIR/rustc-decodable-issue-123156.rs:10:10 | LL | #[derive(RustcDecodable)] | ^^^^^^^^^^^^^^ | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #64266 "} {"_id":"doc-en-rust-d707939a1d30652bcba1cde9cb296eb9d17af9ba9cee3c364b971bc1529516e9","title":"","text":"/// Returns an iterator over the remaining elements of the original iterator /// that are not going to be returned by this iterator. The returned /// iterator will yield at most `N-1` elements. /// /// # Example /// ``` /// # // Also serves as a regression test for https://github.com/rust-lang/rust/issues/123333 /// # #![feature(iter_array_chunks)] /// let x = [1,2,3,4,5].into_iter().array_chunks::<2>(); /// let mut rem = x.into_remainder().unwrap(); /// assert_eq!(rem.next(), Some(5)); /// assert_eq!(rem.next(), None); /// ``` #[unstable(feature = \"iter_array_chunks\", reason = \"recently added\", issue = \"100450\")] #[inline] pub fn into_remainder(self) -> Option> { pub fn into_remainder(mut self) -> Option> { if self.remainder.is_none() { while let Some(_) = self.next() {} } self.remainder } }"} {"_id":"doc-en-rust-81b932e2ca1b79222708319bd5812a951676c73751074da2b03ebbef916498e2","title":"","text":"/// Set the maximum pattern complexity allowed (not limited by default). (internal, pattern_complexity, \"1.78.0\", None), /// Allows using pattern types. (internal, pattern_types, \"CURRENT_RUSTC_VERSION\", Some(54882)), (internal, pattern_types, \"CURRENT_RUSTC_VERSION\", Some(123646)), /// Allows using `#[prelude_import]` on glob `use` items. (internal, prelude_import, \"1.2.0\", None), /// Used to identify crates that contain the profiler runtime."} {"_id":"doc-en-rust-5e678a6bdd632ef2b6323226128691bffe77bee1fc02d4fd43341306fdde1c62","title":"","text":"Ty::new_pat(tcx, ty, pat) } hir::PatKind::Err(e) => Ty::new_error(tcx, e), _ => span_bug!(pat.span, \"unsupported pattern for pattern type: {pat:#?}\"), _ => Ty::new_error_with_message( tcx, pat.span, format!(\"unsupported pattern for pattern type: {pat:#?}\"), ), }; self.record_ty(pat.hir_id, ty, pat.span); pat_ty"} {"_id":"doc-en-rust-6b761594cd708182be7b9649f0c5a1f79bda59c1ce5f04e839ec6f889ec32f14","title":"","text":" //! This test ensures we do not ICE for unimplemented //! patterns unless the feature gate is enabled. #![feature(core_pattern_type)] #![feature(core_pattern_types)] use std::pat::pattern_type; type Always = pattern_type!(Option is Some(_)); //~^ ERROR: pattern types are unstable type Binding = pattern_type!(Option is x); //~^ ERROR: pattern types are unstable fn main() {} "} {"_id":"doc-en-rust-07f989f67167b50a44d866f5991a423d89d9670cf9f16c30ba8adeac7df7a3c8","title":"","text":" error[E0658]: pattern types are unstable --> $DIR/unimplemented_pat.rs:9:15 | LL | type Always = pattern_type!(Option is Some(_)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #123646 for more information = help: add `#![feature(pattern_types)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0658]: pattern types are unstable --> $DIR/unimplemented_pat.rs:12:16 | LL | type Binding = pattern_type!(Option is x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #123646 for more information = help: add `#![feature(pattern_types)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0658`. "} {"_id":"doc-en-rust-288b00024b7d82265e93ab13bd867789c188ea37fa3b44a49e519789595e7147","title":"","text":"// Don't leak types into signatures unless they're nameable! // For example, if a function returns itself, we don't want that // recursive function definition to leak out into the fn sig. let mut should_recover = false; let mut recovered_ret_ty = None; if let Some(ret_ty) = ret_ty.make_suggestable(tcx, false, None) { if let Some(suggestable_ret_ty) = ret_ty.make_suggestable(tcx, false, None) { diag.span_suggestion( ty.span, \"replace with the correct return type\", ret_ty, suggestable_ret_ty, Applicability::MachineApplicable, ); should_recover = true; recovered_ret_ty = Some(suggestable_ret_ty); } else if let Some(sugg) = suggest_impl_trait(&tcx.infer_ctxt().build(), tcx.param_env(def_id), ret_ty) {"} {"_id":"doc-en-rust-a4a28fe701d946998add9698bd41308b10fe3bbd5c52db0276491a54503d2dab","title":"","text":"} let guar = diag.emit(); if should_recover { ty::Binder::dummy(fn_sig) } else { ty::Binder::dummy(tcx.mk_fn_sig( fn_sig.inputs().iter().copied(), Ty::new_error(tcx, guar), fn_sig.c_variadic, fn_sig.unsafety, fn_sig.abi, )) } ty::Binder::dummy(tcx.mk_fn_sig( fn_sig.inputs().iter().copied(), recovered_ret_ty.unwrap_or_else(|| Ty::new_error(tcx, guar)), fn_sig.c_variadic, fn_sig.unsafety, fn_sig.abi, )) } None => icx.lowerer().lower_fn_ty( hir_id,"} {"_id":"doc-en-rust-9c13b406cac72125dd4d4f9f74505ab4a2a539f318d9da09001f1d2db33a546d","title":"","text":"} ty::FnDef(..) | ty::Coroutine(..) | ty::Closure(..) | ty::CoroutineClosure(..) => { bug!(\"Unexpected coroutine/closure type in variance computation\"); bug!(\"Unexpected unnameable type in variance computation: {ty}\"); } ty::Ref(region, ty, mutbl) => {"} {"_id":"doc-en-rust-93c525d480a05bf7ec126d28841d5b3f07ed0de91fb31a99ba248de354cb5471","title":"","text":" // Test variance computation doesn't explode when we leak unnameable // types due to `-> _` recovery. pub struct Type<'a>(&'a ()); pub fn g() {} pub fn f() -> _ { //~^ ERROR the placeholder `_` is not allowed within types on item signatures g } fn main() {} "} {"_id":"doc-en-rust-1ce421402d97bc6c51b46f0f1989bb5a7becb3e7f0cc30f4943c38bbe489241d","title":"","text":" error[E0121]: the placeholder `_` is not allowed within types on item signatures for return types --> $DIR/leaking-unnameables.rs:8:18 | LL | pub fn f() -> _ { | ^ | | | not allowed in type signatures | help: replace with the correct return type: `fn()` error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0121`. "} {"_id":"doc-en-rust-20087dd6763be79f4a2d13d68de4af375a12ce82804b481a7ad827999da749ee","title":"","text":"submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen, }; use crate::common::{self, IntPredicate, RealPredicate, TypeKind}; use crate::meth::load_vtable; use crate::mir::operand::OperandValue; use crate::mir::place::PlaceRef; use crate::traits::*;"} {"_id":"doc-en-rust-6f2f4a1b87b2129eab5b8b9a3a2f207976b7a7fd54693a719281932b42f1c52c","title":"","text":"if let Some(entry_idx) = vptr_entry_idx { let ptr_size = bx.data_layout().pointer_size; let ptr_align = bx.data_layout().pointer_align.abi; let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes(); let gep = bx.inbounds_ptradd(old_info, bx.const_usize(vtable_byte_offset)); let new_vptr = bx.load(bx.type_ptr(), gep, ptr_align); bx.nonnull_metadata(new_vptr); // VTable loads are invariant. bx.set_invariant_load(new_vptr); new_vptr load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true) } else { old_info }"} {"_id":"doc-en-rust-380d74364587dc41466cd33acb9ba69c9988ad7ae1617b281da93f01df011e36","title":"","text":"let llty = bx.fn_ptr_backend_type(fn_abi); let ptr_size = bx.data_layout().pointer_size; let ptr_align = bx.data_layout().pointer_align.abi; let vtable_byte_offset = self.0 * ptr_size.bytes(); if bx.cx().sess().opts.unstable_opts.virtual_function_elimination && bx.cx().sess().lto() == Lto::Fat { let typeid = bx .typeid_metadata(typeid_for_trait_ref(bx.tcx(), expect_dyn_trait_in_self(ty))) .unwrap(); let func = bx.type_checked_load(llvtable, vtable_byte_offset, typeid); func } else { let gep = bx.inbounds_ptradd(llvtable, bx.const_usize(vtable_byte_offset)); let ptr = bx.load(llty, gep, ptr_align); // VTable loads are invariant. bx.set_invariant_load(ptr); if nonnull { bx.nonnull_metadata(ptr); } ptr } load_vtable(bx, llvtable, llty, vtable_byte_offset, ty, nonnull) } pub(crate) fn get_optional_fn>("} {"_id":"doc-en-rust-3e056fe1fb2daa7f57b97b40d4dbc0c728040d95fb266b76aba2c2de32414f59","title":"","text":"self, bx: &mut Bx, llvtable: Bx::Value, ty: Ty<'tcx>, ) -> Bx::Value { // Load the data pointer from the object. debug!(\"get_int({:?}, {:?})\", llvtable, self); let llty = bx.type_isize(); let ptr_size = bx.data_layout().pointer_size; let ptr_align = bx.data_layout().pointer_align.abi; let vtable_byte_offset = self.0 * ptr_size.bytes(); let gep = bx.inbounds_ptradd(llvtable, bx.const_usize(vtable_byte_offset)); let ptr = bx.load(llty, gep, ptr_align); // VTable loads are invariant. bx.set_invariant_load(ptr); ptr load_vtable(bx, llvtable, llty, vtable_byte_offset, ty, false) } } /// This takes a valid `self` receiver type and extracts the principal trait /// ref of the type. fn expect_dyn_trait_in_self(ty: Ty<'_>) -> ty::PolyExistentialTraitRef<'_> { /// ref of the type. Return `None` if there is no principal trait. fn dyn_trait_in_self(ty: Ty<'_>) -> Option> { for arg in ty.peel_refs().walk() { if let GenericArgKind::Type(ty) = arg.unpack() && let ty::Dynamic(data, _, _) = ty.kind() { return data.principal().expect(\"expected principal trait object\"); return data.principal(); } }"} {"_id":"doc-en-rust-9338085691ca443f5fa41514200acda245f37f9b7989dbb4e0f8aa2f3e62fb9f","title":"","text":"cx.vtables().borrow_mut().insert((ty, trait_ref), vtable); vtable } /// Call this function whenever you need to load a vtable. pub(crate) fn load_vtable<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx: &mut Bx, llvtable: Bx::Value, llty: Bx::Type, vtable_byte_offset: u64, ty: Ty<'tcx>, nonnull: bool, ) -> Bx::Value { let ptr_align = bx.data_layout().pointer_align.abi; if bx.cx().sess().opts.unstable_opts.virtual_function_elimination && bx.cx().sess().lto() == Lto::Fat { if let Some(trait_ref) = dyn_trait_in_self(ty) { let typeid = bx.typeid_metadata(typeid_for_trait_ref(bx.tcx(), trait_ref)).unwrap(); let func = bx.type_checked_load(llvtable, vtable_byte_offset, typeid); return func; } else if nonnull { bug!(\"load nonnull value from a vtable without a principal trait\") } } let gep = bx.inbounds_ptradd(llvtable, bx.const_usize(vtable_byte_offset)); let ptr = bx.load(llty, gep, ptr_align); // VTable loads are invariant. bx.set_invariant_load(ptr); if nonnull { bx.nonnull_metadata(ptr); } ptr } "} {"_id":"doc-en-rust-5c35054f2ac56f02d0e87e857bf09576d2eb65ae50f0cc2a549a3c55404515a4","title":"","text":"sym::vtable_align => ty::COMMON_VTABLE_ENTRIES_ALIGN, _ => bug!(), }; let value = meth::VirtualIndex::from_index(idx).get_usize(bx, vtable); let value = meth::VirtualIndex::from_index(idx).get_usize(bx, vtable, callee_ty); match name { // Size is always <= isize::MAX. sym::vtable_size => {"} {"_id":"doc-en-rust-e57237dd1a9e971627efc42f1f6c7ea923af85aa5039086e78b9b57a09603d95","title":"","text":"// Load size/align from vtable. let vtable = info.unwrap(); let size = meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_SIZE) .get_usize(bx, vtable); .get_usize(bx, vtable, t); let align = meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_ALIGN) .get_usize(bx, vtable); .get_usize(bx, vtable, t); // Size is always <= isize::MAX. let size_bound = bx.data_layout().ptr_sized_integer().signed_max() as u128;"} {"_id":"doc-en-rust-2db546706b2b96927a3da5bbe78f89c8b0409d1cdb853e8c1a4bd4b93a2a58b6","title":"","text":" //@ known-bug: #123955 //@ compile-flags: -Clto -Zvirtual-function-elimination //@ only-x86_64 pub fn main() { _ = Box::new(()) as Box; } "} {"_id":"doc-en-rust-f965de4ef176114e853a40bd6ef9439fc3d5c8ea147c2a858e8b5f6143d10a98","title":"","text":" //@ known-bug: #124092 //@ compile-flags: -Zvirtual-function-elimination=true -Clto=true //@ only-x86_64 const X: for<'b> fn(&'b ()) = |&()| (); fn main() { let dyn_debug = Box::new(X) as Box as Box; } "} {"_id":"doc-en-rust-6336790a29b442ffab00899b497fd02088c97e446e0970c42f6133f9a75fe2f8","title":"","text":" //@ build-pass //@ compile-flags: -Zvirtual-function-elimination=true -Clto=true //@ only-x86_64 //@ no-prefer-dynamic // issue #123955 pub fn test0() { _ = Box::new(()) as Box; } // issue #124092 const X: for<'b> fn(&'b ()) = |&()| (); pub fn test1() { let _dyn_debug = Box::new(X) as Box as Box; } fn main() {} "} {"_id":"doc-en-rust-9c3e68f70b84497ea78e53c228f057c0f085acaa6c00e7ebe18211c652cfbb6c","title":"","text":"} #[inline(always)] pub unsafe fn init(_argc: isize, _argv: *const *const u8) { // On Linux-GNU, we rely on `ARGV_INIT_ARRAY` below to initialize // `ARGC` and `ARGV`. But in Miri that does not actually happen so we // still initialize here. #[cfg(any(miri, not(all(target_os = \"linux\", target_env = \"gnu\"))))] really_init(_argc, _argv); pub unsafe fn init(argc: isize, argv: *const *const u8) { // on GNU/Linux if we are main then we will init argv and argc twice, it \"duplicates work\" // BUT edge-cases are real: only using .init_array can break most emulators, dlopen, etc. really_init(argc, argv); } /// glibc passes argc, argv, and envp to functions in .init_array, as a non-standard extension."} {"_id":"doc-en-rust-cef640a73e631b94817ec97fbd1945b888ac4ff39f90443ad25203e61f926cb4","title":"","text":"self.space(); } MatchKind::Postfix => { self.print_expr_as_cond(expr); self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX, fixup); self.word_nbsp(\".match\"); } }"} {"_id":"doc-en-rust-a37d7af0137ab34c82bd45cee70961b3e9c7891cd77cadb537a6e1e6923282c6","title":"","text":" #![feature(postfix_match)] fn main() { let val = Some(42); val.match { Some(_) => 2, _ => 1 }; Some(2).match { Some(_) => true, None => false }.match { false => \"ferris is cute\", true => \"I turn cats in to petted cats\", }.match { _ => (), } } "} {"_id":"doc-en-rust-bc7b1cc038bcd618f09817e39dc540964994393ba65da4c24b5a1cfc75d13c80","title":"","text":" #![feature(prelude_import)] #![no_std] #![feature(postfix_match)] #[prelude_import] use ::std::prelude::rust_2015::*; #[macro_use] extern crate std; use std::ops::Add; //@ pretty-mode:expanded //@ pp-exact:precedence.pp macro_rules! repro { ($e:expr) => { $e.match { _ => {} } }; } struct Struct {} impl Add for usize { type Output = (); fn add(self, _: Struct) -> () { () } } pub fn main() { let a; ( { 1 } + 1).match { _ => {} }; (4 as usize).match { _ => {} }; (return).match { _ => {} }; (a = 42).match { _ => {} }; (|| {}).match { _ => {} }; (42..101).match { _ => {} }; (1 + Struct {}).match { _ => {} }; } "} {"_id":"doc-en-rust-c3e3e8828d33ba1b5a6a22ef26854b10b192310c9ebe9273457e1073f2cb772f","title":"","text":" #![feature(postfix_match)] use std::ops::Add; //@ pretty-mode:expanded //@ pp-exact:precedence.pp macro_rules! repro { ($e:expr) => { $e.match { _ => {} } }; } struct Struct {} impl Add for usize { type Output = (); fn add(self, _: Struct) -> () { () } } pub fn main() { let a; repro!({ 1 } + 1); repro!(4 as usize); repro!(return); repro!(a = 42); repro!(|| {}); repro!(42..101); repro!(1 + Struct {}); } "} {"_id":"doc-en-rust-7c32caf57959701590d8d703fa8784d7d62d91b4a741466393a328327270fa79","title":"","text":" #![feature(postfix_match)] fn main() { let val = Some(42); val.match { Some(_) => 2, _ => 1 }; Some(2).match { Some(_) => true, None => false }.match { false => \"ferris is cute\", true => \"I turn cats in to petted cats\", }.match { _ => (), } } "} {"_id":"doc-en-rust-26711a4be1b30e61729ade6f9c3747487e0bc67e71e9d77952633ac70ac946bb","title":"","text":"use std::str; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock}; use std::time::{Instant, SystemTime}; use std::time::{Duration, Instant, SystemTime}; use time::OffsetDateTime; use tracing::trace;"} {"_id":"doc-en-rust-5358e74b84d096562ac437709df4b096f2a6cf9989aeb3ab76b779f1779438a4","title":"","text":"pub fn install_ctrlc_handler() { #[cfg(not(target_family = \"wasm\"))] ctrlc::set_handler(move || { // Indicate that we have been signaled to stop. If we were already signaled, exit // immediately. In our interpreter loop we try to consult this value often, but if for // whatever reason we don't get to that check or the cleanup we do upon finding that // this bool has become true takes a long time, the exit here will promptly exit the // process on the second Ctrl-C. if CTRL_C_RECEIVED.swap(true, Ordering::Relaxed) { std::process::exit(1); } // Indicate that we have been signaled to stop, then give the rest of the compiler a bit of // time to check CTRL_C_RECEIVED and run its own shutdown logic, but after a short amount // of time exit the process. This sleep+exit ensures that even if nobody is checking // CTRL_C_RECEIVED, the compiler exits reasonably promptly. CTRL_C_RECEIVED.store(true, Ordering::Relaxed); std::thread::sleep(Duration::from_millis(100)); std::process::exit(1); }) .expect(\"Unable to install ctrlc handler\"); }"} {"_id":"doc-en-rust-7ca8e08c5576620c6b6fac4a49e798056f866396876624b41dfc669fb230e7df","title":"","text":"//! //! The corresponding [`Sync`] version of `OnceCell` is [`OnceLock`]. //! //! ## `LazyCell` //! //! A common pattern with OnceCell is, for a given OnceCell, to use the same function on every //! call to [`OnceCell::get_or_init`] with that cell. This is what is offered by [`LazyCell`], //! which pairs cells of `T` with functions of `F`, and always calls `F` before it yields `&T`. //! This happens implicitly by simply attempting to dereference the LazyCell to get its contents, //! so its use is much more transparent with a place which has been initialized by a constant. //! //! More complicated patterns that don't fit this description can be built on `OnceCell` instead. //! //! `LazyCell` works by providing an implementation of `impl Deref` that calls the function, //! so you can just use it by dereference (e.g. `*lazy_cell` or `lazy_cell.deref()`). //! //! The corresponding [`Sync`] version of `LazyCell` is [`LazyLock`]. //! //! # When to choose interior mutability //!"} {"_id":"doc-en-rust-f02b93c92716b3104d81a66ec075259c62afa806b67c0d5dbde699519771dcc2","title":"","text":"//! [`RwLock`]: ../../std/sync/struct.RwLock.html //! [`Mutex`]: ../../std/sync/struct.Mutex.html //! [`OnceLock`]: ../../std/sync/struct.OnceLock.html //! [`LazyLock`]: ../../std/sync/struct.LazyLock.html //! [`Sync`]: ../../std/marker/trait.Sync.html //! [`atomic`]: crate::sync::atomic"} {"_id":"doc-en-rust-f6e903694529cfa5d9031f200b2e5f688ca8c5d632ff72d5320c84e5a595ea81","title":"","text":"/// # Examples /// /// Initialize static variables with `LazyLock`. /// /// ``` /// use std::collections::HashMap; /// /// use std::sync::LazyLock; /// /// static HASHMAP: LazyLock> = LazyLock::new(|| { /// println!(\"initializing\"); /// let mut m = HashMap::new(); /// m.insert(13, \"Spica\".to_string()); /// m.insert(74, \"Hoyten\".to_string()); /// m /// // n.b. static items do not call [`Drop`] on program termination, so this won't be deallocated. /// // this is fine, as the OS can deallocate the terminated program faster than we can free memory /// // but tools like valgrind might report \"memory leaks\" as it isn't obvious this is intentional. /// static DEEP_THOUGHT: LazyLock = LazyLock::new(|| { /// # mod another_crate { /// # pub fn great_question() -> String { \"42\".to_string() } /// # } /// // M3 Ultra takes about 16 million years in --release config /// another_crate::great_question() /// }); /// /// fn main() { /// println!(\"ready\"); /// std::thread::spawn(|| { /// println!(\"{:?}\", HASHMAP.get(&13)); /// }).join().unwrap(); /// println!(\"{:?}\", HASHMAP.get(&74)); /// /// // Prints: /// // ready /// // initializing /// // Some(\"Spica\") /// // Some(\"Hoyten\") /// } /// // The `String` is built, stored in the `LazyLock`, and returned as `&String`. /// let _ = &*DEEP_THOUGHT; /// // The `String` is retrieved from the `LazyLock` and returned as `&String`. /// let _ = &*DEEP_THOUGHT; /// ``` /// /// Initialize fields with `LazyLock`. /// ``` /// use std::sync::LazyLock;"} {"_id":"doc-en-rust-3772351a4c0d83a447b527c90de9d15b6634c1714765e6d219e8e6832cd6229d","title":"","text":"//! - [`Once`]: Used for a thread-safe, one-time global initialization routine //! //! - [`OnceLock`]: Used for thread-safe, one-time initialization of a //! global variable. //! variable, with potentially different initializers based on the caller. //! //! - [`LazyLock`]: Used for thread-safe, one-time initialization of a //! variable, using one nullary initializer function provided at creation. //! //! - [`RwLock`]: Provides a mutual exclusion mechanism which allows //! multiple readers at the same time, while allowing only one"} {"_id":"doc-en-rust-1bec35ee375c81f48f8f2831ee0f27e3090162bcec71187cee611420a0d976f6","title":"","text":"/// A synchronization primitive which can be written to only once. /// /// This type is a thread-safe [`OnceCell`], and can be used in statics. /// In many simple cases, you can use [`LazyLock`] instead to get the benefits of this type /// with less effort: `LazyLock` \"looks like\" `&T` because it initializes with `F` on deref! /// Where OnceLock shines is when LazyLock is too simple to support a given case, as LazyLock /// doesn't allow additional inputs to its function after you call [`LazyLock::new(|| ...)`]. /// /// [`OnceCell`]: crate::cell::OnceCell /// [`LazyLock`]: crate::sync::LazyLock /// [`LazyLock::new(|| ...)`]: crate::sync::LazyLock::new /// /// # Examples /// /// Using `OnceLock` to store a function’s previously computed value (a.k.a. /// ‘lazy static’ or ‘memoizing’): /// /// ``` /// use std::sync::OnceLock; /// /// struct DeepThought { /// answer: String, /// } /// /// impl DeepThought { /// # fn great_question() -> String { /// # \"42\".to_string() /// # } /// # /// fn new() -> Self { /// Self { /// // M3 Ultra takes about 16 million years in --release config /// answer: Self::great_question(), /// } /// } /// } /// /// fn computation() -> &'static DeepThought { /// // n.b. static items do not call [`Drop`] on program termination, so if /// // [`DeepThought`] impls Drop, that will not be used for this instance. /// static COMPUTATION: OnceLock = OnceLock::new(); /// COMPUTATION.get_or_init(|| DeepThought::new()) /// } /// /// // The `DeepThought` is built, stored in the `OnceLock`, and returned. /// let _ = computation().answer; /// // The `DeepThought` is retrieved from the `OnceLock` and returned. /// let _ = computation().answer; /// ``` /// /// Writing to a `OnceLock` from a separate thread: /// /// ```"} {"_id":"doc-en-rust-fe9cbc0b641a2deeb39fb2bc1ec2447b5e809842654ab87a2c22ffb1c88cf25e","title":"","text":"/// Some(&12345), /// ); /// ``` /// /// You can use `OnceLock` to implement a type that requires \"append-only\" logic: /// /// ``` /// use std::sync::{OnceLock, atomic::{AtomicU32, Ordering}}; /// use std::thread; /// /// struct OnceList { /// data: OnceLock, /// next: OnceLock>>, /// } /// impl OnceList { /// const fn new() -> OnceList { /// OnceList { data: OnceLock::new(), next: OnceLock::new() } /// } /// fn push(&self, value: T) { /// // FIXME: this impl is concise, but is also slow for long lists or many threads. /// // as an exercise, consider how you might improve on it while preserving the behavior /// if let Err(value) = self.data.set(value) { /// let next = self.next.get_or_init(|| Box::new(OnceList::new())); /// next.push(value) /// }; /// } /// fn contains(&self, example: &T) -> bool /// where /// T: PartialEq, /// { /// self.data.get().map(|item| item == example).filter(|v| *v).unwrap_or_else(|| { /// self.next.get().map(|next| next.contains(example)).unwrap_or(false) /// }) /// } /// } /// /// // Let's exercise this new Sync append-only list by doing a little counting /// static LIST: OnceList = OnceList::new(); /// static COUNTER: AtomicU32 = AtomicU32::new(0); /// /// let vec = (0..thread::available_parallelism().unwrap().get()).map(|_| thread::spawn(|| { /// while let i @ 0..=1000 = COUNTER.fetch_add(1, Ordering::Relaxed) { /// LIST.push(i); /// } /// })).collect::>>(); /// vec.into_iter().for_each(|handle| handle.join().unwrap()); /// /// for i in 0..=1000 { /// assert!(LIST.contains(&i)); /// } /// /// ``` #[stable(feature = \"once_cell\", since = \"1.70.0\")] pub struct OnceLock { once: Once,"} {"_id":"doc-en-rust-3f19086fcb897b6ddd8d2eee6042b8f84be1308e98e761f63c92af372a153a71","title":"","text":"// Get the arguments for the found method, only specifying that `Self` is the receiver type. let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return }; let args = GenericArgs::for_item(tcx, method_def_id, |param, _| { if param.index == 0 { if let ty::GenericParamDefKind::Lifetime = param.kind { tcx.lifetimes.re_erased.into() } else if param.index == 0 && param.name == kw::SelfUpper { possible_rcvr_ty.into() } else if param.index == closure_param.index { closure_ty.into()"} {"_id":"doc-en-rust-dec2cfa99cd9b2f86124fef9dc53c358dc94d1841c5b1fe70125867d3be762d8","title":"","text":"Obligation::misc(tcx, span, self.mir_def_id(), self.param_env, pred) })); if ocx.select_all_or_error().is_empty() { if ocx.select_all_or_error().is_empty() && count > 0 { diag.span_suggestion_verbose( tcx.hir().body(*body).value.peel_blocks().span.shrink_to_lo(), \"dereference the return value\","} {"_id":"doc-en-rust-3cdb716568947800dc660665d46637966e4ec7ae4633aad377ba78cbad116ae9","title":"","text":" //@ known-bug: rust-lang/rust#124563 use std::marker::PhantomData; pub trait Trait {} pub trait Foo { type Trait: Trait; type Bar: Bar; fn foo(&mut self); } pub struct FooImpl<'a, 'b, A: Trait>(PhantomData<&'a &'b A>); impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> where T: Trait, { type Trait = T; type Bar = BarImpl<'a, 'b, T>; fn foo(&mut self) { self.enter_scope(|ctx| { BarImpl(ctx); }); } } impl<'a, 'b, T> FooImpl<'a, 'b, T> where T: Trait, { fn enter_scope(&mut self, _scope: impl FnOnce(&mut Self)) {} } pub trait Bar { type Foo: Foo; } pub struct BarImpl<'a, 'b, T: Trait>(&'b mut FooImpl<'a, 'b, T>); impl<'a, 'b, T> Bar for BarImpl<'a, 'b, T> where T: Trait, { type Foo = FooImpl<'a, 'b, T>; } "} {"_id":"doc-en-rust-35a5c0249ea42732e8d74ef0a7471e5d9f5e2e32dbc1ada67b3a2dfd2a739cc4","title":"","text":" // #125634 struct Thing; // Invariant in 'a, Covariant in 'b struct TwoThings<'a, 'b>(*mut &'a (), &'b mut ()); impl Thing { fn enter_scope<'a>(self, _scope: impl for<'b> FnOnce(TwoThings<'a, 'b>)) {} } fn foo() { Thing.enter_scope(|ctx| { SameLifetime(ctx); //~ ERROR lifetime may not live long enough }); } struct SameLifetime<'a>(TwoThings<'a, 'a>); fn main() {} "} {"_id":"doc-en-rust-aa7551e493e8d0fecf8642bffeeb8c063538847a42ef8d5729276952fd011fb4","title":"","text":" error: lifetime may not live long enough --> $DIR/account-for-lifetimes-in-closure-suggestion.rs:13:22 | LL | Thing.enter_scope(|ctx| { | --- | | | has type `TwoThings<'_, '1>` | has type `TwoThings<'2, '_>` LL | SameLifetime(ctx); | ^^^ this usage requires that `'1` must outlive `'2` | = note: requirement occurs because of the type `TwoThings<'_, '_>`, which makes the generic argument `'_` invariant = note: the struct `TwoThings<'a, 'b>` is invariant over the parameter `'a` = help: see for more information about variance error: aborting due to 1 previous error "} {"_id":"doc-en-rust-9fcf30aae380e0b344e6962951ecdbae3316d6ab725ff821f65d1319407ae067","title":"","text":" // #124563 use std::marker::PhantomData; pub trait Trait {} pub trait Foo { type Trait: Trait; type Bar: Bar; fn foo(&mut self); } pub struct FooImpl<'a, 'b, A: Trait>(PhantomData<&'a &'b A>); impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> where T: Trait, { type Trait = T; type Bar = BarImpl<'a, 'b, T>; //~ ERROR lifetime bound not satisfied fn foo(&mut self) { self.enter_scope(|ctx| { //~ ERROR lifetime may not live long enough BarImpl(ctx); //~ ERROR lifetime may not live long enough }); } } impl<'a, 'b, T> FooImpl<'a, 'b, T> where T: Trait, { fn enter_scope(&mut self, _scope: impl FnOnce(&mut Self)) {} } pub trait Bar { type Foo: Foo; } pub struct BarImpl<'a, 'b, T: Trait>(&'b mut FooImpl<'a, 'b, T>); impl<'a, 'b, T> Bar for BarImpl<'a, 'b, T> where T: Trait, { type Foo = FooImpl<'a, 'b, T>; } fn main() {} "} {"_id":"doc-en-rust-915c9a2973d1864c4d78fecd55efdeb2f3cafc35584cbbe7774339ffb97b5ad6","title":"","text":" error[E0478]: lifetime bound not satisfied --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:19:16 | LL | type Bar = BarImpl<'a, 'b, T>; | ^^^^^^^^^^^^^^^^^^ | note: lifetime parameter instantiated with the lifetime `'a` as defined here --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:14:6 | LL | impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> | ^^ note: but lifetime parameter must outlive the lifetime `'b` as defined here --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:14:10 | LL | impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> | ^^ error: lifetime may not live long enough --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:23:21 | LL | self.enter_scope(|ctx| { | --- | | | has type `&'1 mut FooImpl<'_, '_, T>` | has type `&mut FooImpl<'2, '_, T>` LL | BarImpl(ctx); | ^^^ this usage requires that `'1` must outlive `'2` error: lifetime may not live long enough --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:22:9 | LL | impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> | -- -- lifetime `'b` defined here | | | lifetime `'a` defined here ... LL | / self.enter_scope(|ctx| { LL | | BarImpl(ctx); LL | | }); | |__________^ argument requires that `'a` must outlive `'b` | = help: consider adding the following bound: `'a: 'b` = note: requirement occurs because of a mutable reference to `FooImpl<'_, '_, T>` = note: mutable references are invariant over their type parameter = help: see for more information about variance error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0478`. "} {"_id":"doc-en-rust-0a99a285e7ac3914b3d61861da40db981efced525063cd82de948ceb5c475ce7","title":"","text":" // Test a method call where the parameter `B` would (illegally) be // inferred to a region bound in the method argument. If this program // were accepted, then the closure passed to `s.f` could escape its // argument. //@ run-rustfix struct S; impl S { fn f(&self, _: F) where F: FnOnce(&i32) -> B { } } fn main() { let s = S; s.f(|p| *p) //~ ERROR lifetime may not live long enough } "} {"_id":"doc-en-rust-e35d504d55df20bda2e4739b259773cb51a056cd477d85fb58cf160d50dbd968","title":"","text":"// inferred to a region bound in the method argument. If this program // were accepted, then the closure passed to `s.f` could escape its // argument. //@ run-rustfix struct S;"} {"_id":"doc-en-rust-9149a8334bf96711483d753411c4bbf57175d981daa3ca2cc442c67a4ede7dab","title":"","text":"error: lifetime may not live long enough --> $DIR/regions-escape-method.rs:15:13 --> $DIR/regions-escape-method.rs:16:13 | LL | s.f(|p| p) | -- ^ returning this value requires that `'1` must outlive `'2` | || | |return type of closure is &'2 i32 | has type `&'1 i32` | help: dereference the return value | LL | s.f(|p| *p) | + error: aborting due to 1 previous error"} {"_id":"doc-en-rust-565bd6cd5e8ced10c98131b2e2d9328a83c983a8a0d96136fdcf7f4624882679","title":"","text":".bounds = `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type .exception = items in an anonymous const item (`const _: () = {\"{\"} ... {\"}\"}`) are treated as in the same scope as the anonymous const's declaration .const_anon = use a const-anon item to suppress this lint .macro_to_change = the {$macro_kind} `{$macro_to_change}` defines the non-local `impl`, and may need to be changed lint_non_local_definitions_impl_move_help = move the `impl` block outside of this {$body_kind_descr} {$depth ->"} {"_id":"doc-en-rust-cca80fb88481799c40c6ae58c426046dc4ba3476162309d43f6032ee34b8ae76","title":"","text":"has_trait: bool, self_ty_str: String, of_trait_str: Option, macro_to_change: Option<(String, &'static str)>, }, MacroRules { depth: u32,"} {"_id":"doc-en-rust-070ebed415772ca29ce3aaba01377e2be59849ec06a2d002f36339c83627a327","title":"","text":"has_trait, self_ty_str, of_trait_str, macro_to_change, } => { diag.primary_message(fluent::lint_non_local_definitions_impl); diag.arg(\"depth\", depth);"} {"_id":"doc-en-rust-5eac3c3a8da1ec9bff7bee2aeddbf4184d7b7c43a8fdb2d4e2a113beabd47779","title":"","text":"diag.arg(\"of_trait_str\", of_trait_str); } if let Some((macro_to_change, macro_kind)) = macro_to_change { diag.arg(\"macro_to_change\", macro_to_change); diag.arg(\"macro_kind\", macro_kind); diag.note(fluent::lint_macro_to_change); } if let Some(cargo_update) = cargo_update { diag.subdiagnostic(&diag.dcx, cargo_update); } if has_trait { diag.note(fluent::lint_bounds); diag.note(fluent::lint_with_trait);"} {"_id":"doc-en-rust-859dca01415cab21a9fe8a3bba23df7e78327b99c08f8f8d812fbeb8f98c87a1","title":"","text":"); } if let Some(cargo_update) = cargo_update { diag.subdiagnostic(&diag.dcx, cargo_update); } if let Some(const_anon) = const_anon { diag.note(fluent::lint_exception); if let Some(const_anon) = const_anon {"} {"_id":"doc-en-rust-0c9702e7f6dcefa2ef230b41f5349d14492408bb8cfb859f75bfd68259429fbd","title":"","text":"Some((cx.tcx.def_span(parent), may_move)) }; let macro_to_change = if let ExpnKind::Macro(kind, name) = item.span.ctxt().outer_expn_data().kind { Some((name.to_string(), kind.descr())) } else { None }; cx.emit_span_lint( NON_LOCAL_DEFINITIONS, ms,"} {"_id":"doc-en-rust-ed7468e5aa346a5ca366dda2c15199a08f3a14ff091645d86ea4446fa7b89b86","title":"","text":"move_to, may_remove, has_trait: impl_.of_trait.is_some(), macro_to_change, }, ) }"} {"_id":"doc-en-rust-d9e6f549e7b1dfdb0ea062d3c39b1d8cd6a095264e9bef8656cb2962c57dc8f9","title":"","text":"| `Debug` is not local | move the `impl` block outside of this constant `_IMPL_DEBUG` | = note: the macro `non_local_macro::non_local_impl` defines the non-local `impl`, and may need to be changed = note: the macro `non_local_macro::non_local_impl` may come from an old version of the `non_local_macro` crate, try updating your dependency with `cargo update -p non_local_macro` = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: the macro `non_local_macro::non_local_impl` may come from an old version of the `non_local_macro` crate, try updating your dependency with `cargo update -p non_local_macro` = note: items in an anonymous const item (`const _: () = { ... }`) are treated as in the same scope as the anonymous const's declaration = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue = note: `#[warn(non_local_definitions)]` on by default"} {"_id":"doc-en-rust-8b0a70585003a2e2e29314e34e97883ba31000a63a21a2f293208cf4c9583214","title":"","text":"LL | m!(); | ---- in this macro invocation | = note: the macro `m` defines the non-local `impl`, and may need to be changed = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue "} {"_id":"doc-en-rust-e5eaacc55742ef6d8ef918df2594dbf1a6efa45bab9bd2b764b4890e14cceec9","title":"","text":"variant_index: VariantIdx, ) -> InterpResult<'tcx, Option<(ScalarInt, usize)>> { match self.layout_of(ty)?.variants { abi::Variants::Single { index } => { assert_eq!(index, variant_index); Ok(None) } abi::Variants::Single { .. } => Ok(None), abi::Variants::Multiple { tag_encoding: TagEncoding::Direct,"} {"_id":"doc-en-rust-0c6b1623c0985b4091675838c84efb18f6eecd35fa43303d48cfddbb088ceefc","title":"","text":"assert!(def.is_enum()); let layout = ty_and_layout.layout; if let Variants::Multiple { tag_field, .. } = layout.variants() { // For enums (but not coroutines), the tag field is // currently always the first field of the layout. assert_eq!(*tag_field, 0); } // Computes the variant of a given index. let layout_of_variant = |index| { let tag = cx.tcx.tag_for_variant((ty_and_layout.ty, index)); let variant_def = Def::Variant(def.variant(index)); let variant_ty_and_layout = ty_and_layout.for_variant(&cx, index); Self::from_variant(variant_def, tag, variant_ty_and_layout, layout.size, cx) }; let variants = def.discriminants(cx.tcx()).try_fold( Self::uninhabited(), |variants, (idx, ref discriminant)| { let tag = cx.tcx.tag_for_variant((ty_and_layout.ty, idx)); let variant_def = Def::Variant(def.variant(idx)); let variant_ty_and_layout = ty_and_layout.for_variant(&cx, idx); let variant = Self::from_variant( variant_def, tag, variant_ty_and_layout, layout.size, cx, // We consider three kinds of enums, each demanding a different // treatment of their layout computation: // 1. enums that are uninhabited // 2. enums for which all but one variant is uninhabited // 3. enums with multiple inhabited variants match layout.variants() { _ if layout.abi.is_uninhabited() => { // Uninhabited enums are usually (always?) zero-sized. In // the (unlikely?) event that an uninhabited enum is // non-zero-sized, this assert will trigger an ICE, and this // code should be modified such that a `layout.size` amount // of uninhabited bytes is returned instead. // // Uninhabited enums are currently implemented such that // their layout is described with `Variants::Single`, even // though they don't necessarily have a 'single' variant to // defer to. That said, we don't bother specifically // matching on `Variants::Single` in this arm because the // behavioral principles here remain true even if, for // whatever reason, the compiler describes an uninhabited // enum with `Variants::Multiple`. assert_eq!(layout.size, Size::ZERO); Ok(Self::uninhabited()) } Variants::Single { index } => { // `Variants::Single` on non-uninhabited enums denotes that // the enum delegates its layout to the variant at `index`. layout_of_variant(*index) } Variants::Multiple { tag_field, .. } => { // `Variants::Multiple` denotes an enum with multiple // inhabited variants. The layout of such an enum is the // disjunction of the layouts of its tagged variants. // For enums (but not coroutines), the tag field is // currently always the first field of the layout. assert_eq!(*tag_field, 0); let variants = def.discriminants(cx.tcx()).try_fold( Self::uninhabited(), |variants, (idx, ref discriminant)| { let variant = layout_of_variant(idx)?; Result::::Ok(variants.or(variant)) }, )?; Result::::Ok(variants.or(variant)) }, )?; return Ok(Self::def(Def::Adt(def)).then(variants)); return Ok(Self::def(Def::Adt(def)).then(variants)); } } } /// Constructs a `Tree` from a 'variant-like' layout."} {"_id":"doc-en-rust-62244f19e3140c7efa0af0ae2c96b1f8b33006383a1a001a51f43cc0d07a9492","title":"","text":" //@ known-bug: rust-lang/rust#125811 mod assert { use std::mem::{Assume, BikeshedIntrinsicFrom}; pub fn is_transmutable() where Dst: BikeshedIntrinsicFrom, { } } #[repr(C)] struct Zst; enum V0 { B(!), } enum V2 { V = 2, } enum Lopsided { Smol(Zst), Lorg(V0), } #[repr(C)] #[repr(C)] struct Dst(Lopsided, V2); fn should_pad_variants() { assert::is_transmutable::(); } "} {"_id":"doc-en-rust-c6cad64d3f6c7e903f38fd19d61245a26ec8e6887c0a83e73a6c291f1b392a29","title":"","text":" //@ check-pass //! Tests that we do not regress rust-lang/rust#125811 #![feature(transmutability)] fn assert_transmutable() where (): std::mem::BikeshedIntrinsicFrom {} enum Uninhabited {} enum SingleInhabited { X, Y(Uninhabited) } enum SingleUninhabited { X(Uninhabited), Y(Uninhabited), } fn main() { assert_transmutable::(); assert_transmutable::(); assert_transmutable::(); } "} {"_id":"doc-en-rust-718a7db88faff79d5ece89a3215c297a2167646b5ae632f2ff35d8e66d2d9de8","title":"","text":"pub(super) fn parse_ty_for_where_clause(&mut self) -> PResult<'a, P> { self.parse_ty_common( AllowPlus::Yes, AllowCVariadic::Yes, AllowCVariadic::No, RecoverQPath::Yes, RecoverReturnSign::OnlyFatArrow, None,"} {"_id":"doc-en-rust-a4ddc9aeab7a95e366d4f4ac92a877de969399b2af8d2b8d2693c974f94024f2","title":"","text":"match allow_c_variadic { AllowCVariadic::Yes => TyKind::CVarArgs, AllowCVariadic::No => { // FIXME(Centril): Should we just allow `...` syntactically // FIXME(c_variadic): Should we just allow `...` syntactically // anywhere in a type and use semantic restrictions instead? // NOTE: This may regress certain MBE calls if done incorrectly. let guar = self .dcx() .emit_err(NestedCVariadicType { span: lo.to(self.prev_token.span) });"} {"_id":"doc-en-rust-0398874990816606b6fc8ba2112e54bf3a4731157f5dc82518763270513f9175","title":"","text":" // A bare `...` represents `CVarArgs` (`VaListImpl<'_>`) in function argument type // position without being a proper type syntactically. // This test ensures that we do not regress certain MBE calls would we ever promote // `...` to a proper type syntactically. //@ check-pass macro_rules! ck { ($ty:ty) => { compile_error!(\"\"); }; (...) => {}; } ck!(...); fn main() {} "} {"_id":"doc-en-rust-48b0a963a3f9823fc65f50e96fbb81b566ddb58fae126d6d6a53e8327301ae54","title":"","text":"fn f2<'a>(x: u8, y: Vec<&'a ...>) {} //~^ ERROR C-variadic type `...` may not be nested inside another type // Regression test for issue #125847. fn f3() where for<> ...: {} //~^ ERROR C-variadic type `...` may not be nested inside another type fn main() { let _recovery_witness: () = 0; //~^ ERROR: mismatched types"} {"_id":"doc-en-rust-8ce98688e6e4212353a200dbbd5312f4af50dd2ddc4e9308aabbc548ffb9c4ab","title":"","text":"LL | fn f2<'a>(x: u8, y: Vec<&'a ...>) {} | ^^^ error[E0743]: C-variadic type `...` may not be nested inside another type --> $DIR/variadic-ffi-nested-syntactic-fail.rs:8:21 | LL | fn f3() where for<> ...: {} | ^^^ error[E0308]: mismatched types --> $DIR/variadic-ffi-nested-syntactic-fail.rs:8:33 --> $DIR/variadic-ffi-nested-syntactic-fail.rs:12:33 | LL | let _recovery_witness: () = 0; | -- ^ expected `()`, found integer | | | expected due to this error: aborting due to 3 previous errors error: aborting due to 4 previous errors Some errors have detailed explanations: E0308, E0743. For more information about an error, try `rustc --explain E0308`."} {"_id":"doc-en-rust-2c2f11b6104419a4d8792394a71d35b500d66826a69c897371f09b834b98a511","title":"","text":"{ write!(f, \"n{}\", Indent(n + 4))?; } let last_input_index = self.inputs.values.len().checked_sub(1); for (i, input) in self.inputs.values.iter().enumerate() { if i > 0 { match line_wrapping_indent { None => write!(f, \", \")?, Some(n) => write!(f, \",n{}\", Indent(n + 4))?, }; } if let Some(selfty) = input.to_self() { match selfty { clean::SelfValue => {"} {"_id":"doc-en-rust-a874097ce97f771c22ce166447db71cc5b557b7f8d25cc91ab71613b134166d9","title":"","text":"write!(f, \"{}: \", input.name)?; input.type_.print(cx).fmt(f)?; } match (line_wrapping_indent, last_input_index) { (_, None) => (), (None, Some(last_i)) if i != last_i => write!(f, \", \")?, (None, Some(_)) => (), (Some(n), Some(last_i)) if i != last_i => write!(f, \",n{}\", Indent(n + 4))?, (Some(_), Some(_)) => write!(f, \",n\")?, } } if self.c_variadic { match line_wrapping_indent { None => write!(f, \", ...\")?, Some(n) => write!(f, \"n{}...\", Indent(n + 4))?, Some(n) => write!(f, \"{}...n\", Indent(n + 4))?, }; } match line_wrapping_indent { None => write!(f, \")\")?, Some(n) => write!(f, \"n{})\", Indent(n))?, Some(n) => write!(f, \"{})\", Indent(n))?, }; self.print_output(cx).fmt(f)"} {"_id":"doc-en-rust-6dd7e68474ebb8199ed4c92b47421b980d052825ef3c51c694dcec6bc0a886bb","title":"","text":"impl Foo { // @has async_fn/struct.Foo.html // @has - '//*[@class=\"method\"]' 'pub async fn complicated_lifetimes( &self, context: &impl Bar ) -> impl Iterator' // @has - '//*[@class=\"method\"]' 'pub async fn complicated_lifetimes( &self, context: &impl Bar, ) -> impl Iterator' pub async fn complicated_lifetimes(&self, context: &impl Bar) -> impl Iterator { [0].iter() }"} {"_id":"doc-en-rust-f6880aad3dffbb273f15543e5baf91d517cc2e0e2af1943b5f16971779d54e82","title":"","text":"
pub fn create( ) -> Padding00000000000000000000000000000000000000000000000000000000000000000000000000000000
No newline at end of file
pub fn create() -> Padding00000000000000000000000000000000000000000000000000000000000000000000000000000000
No newline at end of file"} {"_id":"doc-en-rust-7696d67b22dab9b9e012e7baa6930df4ef882783dacf52b80b4fa4f3569ba258","title":"","text":"fn poll_write( self, cx: &mut Option<String>, buf: &mut [usize] buf: &mut [usize], ) -> Option<Result<usize, Error>>; fn poll_flush(self, cx: &mut Option<String>) -> Option<Result<(), Error>>; fn poll_close(self, cx: &mut Option<String>) -> Option<Result<(), Error>>;"} {"_id":"doc-en-rust-de4a7516747ebd0725ec2e0dd975eb2bbadb7839a39466e8298be36f785d89c0","title":"","text":"fn poll_write_vectored( self, cx: &mut Option<String>, bufs: &[usize] bufs: &[usize], ) -> Option<Result<usize, Error>> { ... } } No newline at end of file"} {"_id":"doc-en-rust-0271977ebf9a9ee7b7930981f07037c35915917ce35700e42d52f53638d11e26","title":"","text":"// @has impl_trait/fn.func2.html // @has - '//pre[@class=\"rust item-decl\"]' \"func2(\" // @has - '//pre[@class=\"rust item-decl\"]' \"_x: impl Deref> + Iterator,\" // @has - '//pre[@class=\"rust item-decl\"]' \"_y: impl Iterator )\" // @has - '//pre[@class=\"rust item-decl\"]' \"_y: impl Iterator, )\" // @!has - '//pre[@class=\"rust item-decl\"]' 'where' pub use impl_trait_aux::func2;"} {"_id":"doc-en-rust-86c2428ae18340819fa5bcc497878f1b2b9ba35a5d365b80708c6038b222281e","title":"","text":"// @matches foo/fn.function_with_a_really_long_name.html '//*[@class=\"rust item-decl\"]//code' \" // function_with_a_really_long_name(n // parameter_one: i32,n // parameter_two: i32n // parameter_two: i32,n // ) -> Option$\" pub fn function_with_a_really_long_name(parameter_one: i32, parameter_two: i32) -> Option { Some(parameter_one + parameter_two)"} {"_id":"doc-en-rust-a4b6cf572f02e441d492f8f9dbb9d26de5067c3c6a98f880b0bd9a58727d6993","title":"","text":"pub use reexports::foo; // @has 'foo/outer/inner/fn.foo_crate.html' '//pre[@class=\"rust item-decl\"]' 'pub(crate) fn foo_crate()' pub(crate) use reexports::foo_crate; // @has 'foo/outer/inner/fn.foo_super.html' '//pre[@class=\"rust item-decl\"]' 'pub(in outer) fn foo_super( )' // @has 'foo/outer/inner/fn.foo_super.html' '//pre[@class=\"rust item-decl\"]' 'pub(in outer) fn foo_super()' pub(super) use::reexports::foo_super; // @!has 'foo/outer/inner/fn.foo_self.html' pub(self) use reexports::foo_self;"} {"_id":"doc-en-rust-dc49156d4be925276b88fe71e34f0380a2a337fa54b626e1920fadaebf0ae32d","title":"","text":"use rustc_span::symbol::{kw, Symbol}; use rustc_span::Span; #[instrument(level = \"debug\", skip(tcx))] pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { use rustc_hir::*;"} {"_id":"doc-en-rust-20a4a46b643fb841d3ab99e983f76aa8b2f1cd845622876e63915ff327e63ef5","title":"","text":"// FIXME(#43408) always enable this once `lazy_normalization` is // stable enough and does not need a feature gate anymore. Node::AnonConst(_) => { let parent_def_id = tcx.hir().get_parent_item(hir_id); let parent_did = tcx.parent(def_id.to_def_id()); // We don't do this unconditionally because the `DefId` parent of an anon const // might be an implicitly created closure during `async fn` desugaring. This would // have the wrong generics. // // i.e. `async fn foo<'a>() { let a = [(); { 1 + 2 }]; bar().await() }` // would implicitly have a closure in its body that would be the parent of // the `{ 1 + 2 }` anon const. This closure's generics is simply a witness // instead of `['a]`. let parent_did = if let DefKind::AnonConst = tcx.def_kind(parent_did) { parent_did } else { tcx.hir().get_parent_item(hir_id).to_def_id() }; debug!(?parent_did); let mut in_param_ty = false; for (_parent, node) in tcx.hir().parent_iter(hir_id) {"} {"_id":"doc-en-rust-22338b6a5c9eee85281a8f32192e39d04aacba3943bd458bd449a26e0e2d87ab","title":"","text":"// // This has some implications for how we get the predicates available to the anon const // see `explicit_predicates_of` for more information on this let generics = tcx.generics_of(parent_def_id.to_def_id()); let generics = tcx.generics_of(parent_did); let param_def_idx = generics.param_def_id_to_index[¶m_id.to_def_id()]; // In the above example this would be .params[..N#0] let own_params = generics.params_to(param_def_idx as usize, tcx).to_owned();"} {"_id":"doc-en-rust-cf1672bea85fdfcdddce83223281920f4f52efc86bb66d45b242df80407f9d7d","title":"","text":"// // Note that we do not supply the parent generics when using // `min_const_generics`. Some(parent_def_id.to_def_id()) Some(parent_did) } } else { let parent_node = tcx.parent_hir_node(hir_id);"} {"_id":"doc-en-rust-60f2731a2f98eb3d8f13065034214f2603f7ee2f1ecf1cc98f81055ea635be21","title":"","text":"Node::Expr(Expr { kind: ExprKind::Repeat(_, constant), .. }) if constant.hir_id() == hir_id => { Some(parent_def_id.to_def_id()) Some(parent_did) } // Exclude `GlobalAsm` here which cannot have generics. Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })"} {"_id":"doc-en-rust-c3837498931aaad410afadea2c77b4cb3ad1fc55d0062d51d5801b1fa1742917","title":"","text":"_ => false, }) => { Some(parent_def_id.to_def_id()) Some(parent_did) } _ => None, }"} {"_id":"doc-en-rust-923ca0f863308f25a692519aad95a06ee76ce2387c1712be6f97b23b4c8e3462","title":"","text":" // Given an anon const `a`: `{ N }` and some anon const `b` which references the // first anon const: `{ [1; a] }`. `b` should not have any generics as it is not // a simple `N` argument nor is it a repeat expr count. // // On the other hand `b` *is* a repeat expr count and so it should inherit its // parents generics as part of the `const_evaluatable_unchecked` fcw (#76200). // // In this specific case however `b`'s parent should be `a` and so it should wind // up not having any generics after all. If `a` were to inherit its generics from // the enclosing item then the reference to `a` from `b` would contain generic // parameters not usable by `b` which would cause us to ICE. fn bar() {} fn foo() { bar::<{ [1; N] }>(); //~^ ERROR: generic parameters may not be used in const operations } fn main() {} "} {"_id":"doc-en-rust-21a2d9255f0852bc91ed0304c9cbc19e401e9f9a36823fa7e2f66873215ef38e","title":"","text":" error: generic parameters may not be used in const operations --> $DIR/repeat_expr_hack_gives_right_generics.rs:16:17 | LL | bar::<{ [1; N] }>(); | ^ cannot perform const operation using `N` | = help: const parameters may only be used as standalone arguments, i.e. `N` = help: add `#![feature(generic_const_exprs)]` to allow generic const expressions error: aborting due to 1 previous error "} {"_id":"doc-en-rust-2b108ff6ef9b158c7324300c0912b0824eefda11cf7710afb70efcafe1a9a438","title":"","text":"}; use rustc_session::config::{self, DebugInfo, Lto}; use rustc_span::symbol::Symbol; use rustc_span::FileName; use rustc_span::{hygiene, FileName, DUMMY_SP}; use rustc_span::{FileNameDisplayPreference, SourceFile}; use rustc_symbol_mangling::typeid_for_trait_ref; use rustc_target::abi::{Align, Size};"} {"_id":"doc-en-rust-63dcec5460da50fee3007e77a33bdf5463bf0c5f8d2f636f9cdb9ffdd799e017","title":"","text":"// We may want to remove the namespace scope if we're in an extern block (see // https://github.com/rust-lang/rust/pull/46457#issuecomment-351750952). let var_scope = get_namespace_for_item(cx, def_id); let span = tcx.def_span(def_id); let span = hygiene::walk_chain_collapsed(tcx.def_span(def_id), DUMMY_SP); let (file_metadata, line_number) = if !span.is_dummy() { let loc = cx.lookup_debug_loc(span.lo());"} {"_id":"doc-en-rust-d4b5e1e6a52fc101da63e6c8a6599e5da55677487d3742c54b7c38093a0e8c91","title":"","text":" //@ ignore-lldb // Test that static debug info is not collapsed with #[collapse_debuginfo(external)] //@ compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:info line collapse_debuginfo_static_external::FOO // gdb-check:[...]Line 15[...] #[collapse_debuginfo(external)] macro_rules! decl_foo { () => { static FOO: u32 = 0; }; } decl_foo!(); fn main() { // prevent FOO from getting optimized out std::hint::black_box(&FOO); } "} {"_id":"doc-en-rust-6734fa637561b1ce6f8f13b21b3f230c32b1a49fbf6b126021433435fe0c3d31","title":"","text":" //@ ignore-lldb // Test that static debug info is collapsed with #[collapse_debuginfo(yes)] //@ compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:info line collapse_debuginfo_static::FOO // gdb-check:[...]Line 19[...] #[collapse_debuginfo(yes)] macro_rules! decl_foo { () => { static FOO: u32 = 0; }; } decl_foo!(); fn main() { // prevent FOO from getting optimized out std::hint::black_box(&FOO); } "} {"_id":"doc-en-rust-5f33d1a17fe6e148ce7db81ad18194fdf51a9f4742f786bd56cdfd43378f2d2c","title":"","text":"} // Resolve any lifetime variables that may have been introduced during normalization. let Ok((trait_bounds, impl_bounds)) = infcx.fully_resolve((trait_bounds, impl_bounds)) else { // This code path is not reached in any tests, but may be reachable. If // this is triggered, it should be converted to `delayed_bug` and the // triggering case turned into a test. tcx.dcx().bug(\"encountered errors when checking RPITIT refinement (resolution)\"); // If resolution didn't fully complete, we cannot continue checking RPITIT refinement, and // delay a bug as the original code contains load-bearing errors. tcx.dcx().delayed_bug(\"encountered errors when checking RPITIT refinement (resolution)\"); return; }; // For quicker lookup, use an `IndexSet` (we don't use one earlier because"} {"_id":"doc-en-rust-902ba9ef4ad14f33d8d4554951df8381191cbd5edde10a1f84345ea883a9dede","title":"","text":" // This is a non-regression test for issue #126670 where RPITIT refinement checking encountered // errors during resolution and ICEd. //@ edition: 2018 pub trait Mirror { type Assoc; } impl Mirror for () { //~^ ERROR the type parameter `T` is not constrained type Assoc = T; } pub trait First { async fn first() -> <() as Mirror>::Assoc; //~^ ERROR type annotations needed } impl First for () { async fn first() {} } fn main() {} "} {"_id":"doc-en-rust-4b79dcb484ba1338f8fd9831a26047cc3d44b430d64e5e44131ecffc400b55d1","title":"","text":" error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates --> $DIR/refine-resolution-errors.rs:9:6 | LL | impl Mirror for () { | ^ unconstrained type parameter error[E0282]: type annotations needed --> $DIR/refine-resolution-errors.rs:15:5 | LL | async fn first() -> <() as Mirror>::Assoc; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type error: aborting due to 2 previous errors Some errors have detailed explanations: E0207, E0282. For more information about an error, try `rustc --explain E0207`. "} {"_id":"doc-en-rust-36024c19c57e7d874954ce34c6dce60a0bea0a3a2ad4c88b32cf8dfbe6bacf97","title":"","text":"#[inline] pub(crate) fn extend_from_slice(&mut self, other: &[u8]) { self.bytes.extend_from_slice(other); self.is_known_utf8 = self.is_known_utf8 || self.next_surrogate(0).is_none(); self.is_known_utf8 = false; } }"} {"_id":"doc-en-rust-b9d416c132b27bef98ca696c9bc400aba1846c0767e2bc26588ea0715d0c476a","title":"","text":"string.push(CodePoint::from_u32(0xD800).unwrap()); check_utf8_boundary(&string, 3); } #[test] fn wobbled_wtf8_plus_bytes_isnt_utf8() { let mut string: Wtf8Buf = unsafe { Wtf8::from_bytes_unchecked(b\"xEDxA0x80\").to_owned() }; assert!(!string.is_known_utf8); string.extend_from_slice(b\"some utf-8\"); assert!(!string.is_known_utf8); } #[test] fn wobbled_wtf8_plus_str_isnt_utf8() { let mut string: Wtf8Buf = unsafe { Wtf8::from_bytes_unchecked(b\"xEDxA0x80\").to_owned() }; assert!(!string.is_known_utf8); string.push_str(\"some utf-8\"); assert!(!string.is_known_utf8); } #[test] fn unwobbly_wtf8_plus_utf8_is_utf8() { let mut string: Wtf8Buf = Wtf8Buf::from_str(\"hello world\"); assert!(string.is_known_utf8); string.push_str(\"some utf-8\"); assert!(string.is_known_utf8); } "} {"_id":"doc-en-rust-73822a6b3c77b8a34e54916f7a28d2e47119ebc81d58cb380899c9f4ce7c7182","title":"","text":"for print in &sess.opts.prints { if print.kind == PrintKind::LinkArgs { let content = format!(\"{cmd:?}\"); let content = format!(\"{cmd:?}n\"); print.out.overwrite(&content, sess); } }"} {"_id":"doc-en-rust-835e7caea8f380ddc18653d400aa0677552541fd187f0213e1d527b794e14d74","title":"","text":".run_unchecked(); out.assert_stdout_contains(\"lfoo\"); out.assert_stdout_contains(\"lbar\"); assert!(out.stdout_utf8().ends_with('n')); }"} {"_id":"doc-en-rust-023d56b9a6a7a506920a60ad200e184151946a68e49a26f7010694cf0e44fc26","title":"","text":"false } } } else if tcx.trait_is_auto(trait_ref.def_id) { tcx.dcx().span_delayed_bug( tcx.def_span(obligation.predicate.def_id), \"associated types not allowed on auto traits\", ); false } else { bug!(\"unexpected builtin trait with associated type: {trait_ref:?}\") }"} {"_id":"doc-en-rust-2d586c3d731b670f9e81a47a088a9fb675d4b0ba3e1032ea667aa007bf54071c","title":"","text":" //@ known-bug: #117829 #![feature(auto_traits)] trait B {} auto trait Z where T: Z, >::W: B, { type W; } fn main() {} "} {"_id":"doc-en-rust-43d4486178e58b9387798599b4e9b5ff8280591b0f124d94da27dd5bf4ce80d3","title":"","text":" //@ known-bug: #117829 auto trait Z<'a, T: ?Sized> where T: Z<'a, u16>, for<'b> >::W: Clone, { type W: ?Sized; } "} {"_id":"doc-en-rust-ba15d14bb8f33394d4426c34d59608ef336bf28ca42275e0439524df852c3725","title":"","text":" error[E0380]: auto traits cannot have associated items --> $DIR/assoc-ty.rs:10:10 | LL | auto trait Trait { | ----- auto traits cannot have associated items LL | LL | type Output; | -----^^^^^^- help: remove these associated items error[E0658]: auto traits are experimental and possibly buggy --> $DIR/assoc-ty.rs:8:1 | LL | / auto trait Trait { LL | | LL | | type Output; LL | | LL | | } | |_^ | = note: see issue #13231 for more information = help: add `#![feature(auto_traits)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0308]: mismatched types --> $DIR/assoc-ty.rs:15:36 | LL | let _: <() as Trait>::Output = (); | --------------------- ^^ expected associated type, found `()` | | | expected due to this | = note: expected associated type `<() as Trait>::Output` found unit type `()` = help: consider constraining the associated type `<() as Trait>::Output` to `()` or calling a method that returns `<() as Trait>::Output` = note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html error: aborting due to 3 previous errors Some errors have detailed explanations: E0308, E0380, E0658. For more information about an error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-4428ce4d5855c34dff4f0f2948a29e03e5747c76828f5072610f58ce6e91634a","title":"","text":" error[E0380]: auto traits cannot have associated items --> $DIR/assoc-ty.rs:10:10 | LL | auto trait Trait { | ----- auto traits cannot have associated items LL | LL | type Output; | -----^^^^^^- help: remove these associated items error[E0658]: auto traits are experimental and possibly buggy --> $DIR/assoc-ty.rs:8:1 | LL | / auto trait Trait { LL | | LL | | type Output; LL | | LL | | } | |_^ | = note: see issue #13231 for more information = help: add `#![feature(auto_traits)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0308]: mismatched types --> $DIR/assoc-ty.rs:15:36 | LL | let _: <() as Trait>::Output = (); | --------------------- ^^ types differ | | | expected due to this | = note: expected associated type `<() as Trait>::Output` found unit type `()` = help: consider constraining the associated type `<() as Trait>::Output` to `()` or calling a method that returns `<() as Trait>::Output` = note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html error: aborting due to 3 previous errors Some errors have detailed explanations: E0308, E0380, E0658. For more information about an error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-5f107f8a968a54eeda789cc5c323a3902d61afbb4551af9e0a12a923f4903676","title":"","text":" //@ revisions: current next //@[next] compile-flags: -Znext-solver //@ ignore-compare-mode-next-solver (explicit revisions) // Tests that projection doesn't explode if we accidentally // put an associated type on an auto trait. auto trait Trait { //~^ ERROR auto traits are experimental and possibly buggy type Output; //~^ ERROR auto traits cannot have associated items } fn main() { let _: <() as Trait>::Output = (); //~^ ERROR mismatched types } "} {"_id":"doc-en-rust-210ac3a4a9463d43185b5cb61741763156807e8863e0e0596ac1bd09e10b43b2","title":"","text":"} #[inline(always)] pub fn local_def_path_hash_to_def_id( &self, hash: DefPathHash, err_msg: &dyn std::fmt::Debug, ) -> LocalDefId { /// Returns `None` if the `DefPathHash` does not correspond to a `LocalDefId` /// in the current compilation session. This can legitimately happen if the /// `DefPathHash` is from a `DefId` in an upstream crate or, during incr. comp., /// if the `DefPathHash` is from a previous compilation session and /// the def-path does not exist anymore. pub fn local_def_path_hash_to_def_id(&self, hash: DefPathHash) -> Option { debug_assert!(hash.stable_crate_id() == self.table.stable_crate_id); #[cold] #[inline(never)] fn err(err_msg: &dyn std::fmt::Debug) -> ! { panic!(\"{err_msg:?}\") } self.table .def_path_hash_to_index .get(&hash.local_hash()) .map(|local_def_index| LocalDefId { local_def_index }) .unwrap_or_else(|| err(err_msg)) } pub fn def_path_hash_to_def_index_map(&self) -> &DefPathHashMap {"} {"_id":"doc-en-rust-cf78cfc42a2710f0b001a2b5daa186533fb1b9d4aaed110b51891092da8ff279","title":"","text":"/// has been removed. fn extract_def_id(&self, tcx: TyCtxt<'_>) -> Option { if tcx.fingerprint_style(self.kind) == FingerprintStyle::DefPathHash { Some(tcx.def_path_hash_to_def_id( DefPathHash(self.hash.into()), &(\"Failed to extract DefId\", self.kind, self.hash), )) tcx.def_path_hash_to_def_id(DefPathHash(self.hash.into())) } else { None }"} {"_id":"doc-en-rust-2f0cb3eef4ef2cf1910fe7538326a43d016f2609380a8581a0e0f368cb24a4e5","title":"","text":"if tcx.fingerprint_style(dep_node.kind) == FingerprintStyle::HirId { let (local_hash, local_id) = Fingerprint::from(dep_node.hash).split(); let def_path_hash = DefPathHash::new(tcx.stable_crate_id(LOCAL_CRATE), local_hash); let def_id = tcx .def_path_hash_to_def_id( def_path_hash, &(\"Failed to extract HirId\", dep_node.kind, dep_node.hash), ) .expect_local(); let def_id = tcx.def_path_hash_to_def_id(def_path_hash)?.expect_local(); let local_id = local_id .as_u64() .try_into()"} {"_id":"doc-en-rust-f29b980c9ec237f451ec8ba7c27ee4043719bdd753fb56fa7d07d2b65c210c71","title":"","text":"// If we get to this point, then all of the query inputs were green, // which means that the definition with this hash is guaranteed to // still exist in the current compilation session. self.tcx.def_path_hash_to_def_id( def_path_hash, &(\"Failed to convert DefPathHash\", def_path_hash), ) match self.tcx.def_path_hash_to_def_id(def_path_hash) { Some(r) => r, None => panic!(\"Failed to convert DefPathHash {def_path_hash:?}\"), } } fn decode_attr_id(&mut self) -> rustc_span::AttrId {"} {"_id":"doc-en-rust-0fb746c0e146ed9e876ff7e62879b93e3cccf5fa135038c80652cff3edc1f733","title":"","text":"/// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation /// session, if it still exists. This is used during incremental compilation to /// turn a deserialized `DefPathHash` into its current `DefId`. pub fn def_path_hash_to_def_id( self, hash: DefPathHash, err_msg: &dyn std::fmt::Debug, ) -> DefId { pub fn def_path_hash_to_def_id(self, hash: DefPathHash) -> Option { debug!(\"def_path_hash_to_def_id({:?})\", hash); let stable_crate_id = hash.stable_crate_id();"} {"_id":"doc-en-rust-04a7538069c4f4503d523365962dac8c83d53d545dfdd3a99edec34dbe026fd7","title":"","text":"// If this is a DefPathHash from the local crate, we can look up the // DefId in the tcx's `Definitions`. if stable_crate_id == self.stable_crate_id(LOCAL_CRATE) { self.untracked .definitions .read() .local_def_path_hash_to_def_id(hash, err_msg) .to_def_id() Some(self.untracked.definitions.read().local_def_path_hash_to_def_id(hash)?.to_def_id()) } else { self.def_path_hash_to_def_id_extern(hash, stable_crate_id) Some(self.def_path_hash_to_def_id_extern(hash, stable_crate_id)) } }"} {"_id":"doc-en-rust-75283e4d3daced2e6f63df9b1ef6cef3dbec2b48f96785d5fabbe0d13aaeb042","title":"","text":"} /// Try to force a dep node to execute and see if it's green. /// /// Returns true if the query has actually been forced. It is valid that a query /// fails to be forced, e.g. when the query key cannot be reconstructed from the /// dep-node or when the query kind outright does not support it. #[inline] #[instrument(skip(self, frame), level = \"debug\")] fn try_force_from_dep_node(self, dep_node: DepNode, frame: Option<&MarkFrame<'_>>) -> bool { let cb = self.dep_kind_info(dep_node.kind); if let Some(f) = cb.force_from_dep_node { if let Err(value) = panic::catch_unwind(panic::AssertUnwindSafe(|| { f(self, dep_node); })) { if !value.is::() { print_markframe_trace(self.dep_graph(), frame); match panic::catch_unwind(panic::AssertUnwindSafe(|| f(self, dep_node))) { Err(value) => { if !value.is::() { print_markframe_trace(self.dep_graph(), frame); } panic::resume_unwind(value) } panic::resume_unwind(value) Ok(query_has_been_forced) => query_has_been_forced, } true } else { false }"} {"_id":"doc-en-rust-240d676b7b36361160604bce88b13e99f4a11e02cfc381c35303e153465140ae","title":"","text":" // If it is impossible to find query arguments just from the hash // compiler should treat the node as red // In this test prior to fixing compiler was having problems figuring out // drop impl for T inside of m //@ revisions:cfail1 cfail2 //@ compile-flags: --crate-type=lib //@ build-pass pub trait P { type A; } struct S; impl P for S { type A = C; } struct T(D::A, Z); struct Z(D::A, String); impl T { pub fn i() -> Self { loop {} } } enum C { #[cfg(cfail1)] Up(()), #[cfg(cfail2)] Lorry(()), } pub fn m() { T::::i(); } "} {"_id":"doc-en-rust-2483d863943b6aa71d4fa027394680bd88fb2d6e978e117ae611e32d2f7eb360","title":"","text":"#[diag(parse_use_eq_instead)] pub(crate) struct UseEqInstead { #[primary_span] #[suggestion(style = \"verbose\", applicability = \"machine-applicable\", code = \"=\")] pub span: Span, #[suggestion(style = \"verbose\", applicability = \"machine-applicable\", code = \"\")] pub suggestion: Span, } #[derive(Diagnostic)]"} {"_id":"doc-en-rust-59875191696b7b8791c26a35835b30fda297b8165c2460b3c64ff563117fbc4c","title":"","text":"&& expected.iter().any(|tok| matches!(tok, TokenType::Token(TokenKind::Eq))) { // Likely typo: `=` → `==` in let expr or enum item return Err(self.dcx().create_err(UseEqInstead { span: self.token.span, suggestion: self.token.span.with_lo(self.token.span.lo() + BytePos(1)), })); return Err(self.dcx().create_err(UseEqInstead { span: self.token.span })); } if self.token.is_keyword(kw::Move) && self.prev_token.is_keyword(kw::Async) {"} {"_id":"doc-en-rust-82d1d7cb0f27c108e4a8de86564bd9f6d29e88aa89b7a8462c2ed2e82e74bb76","title":"","text":"= help: enum variants can be `Variant`, `Variant = `, `Variant(Type, ..., TypeN)` or `Variant { fields: Types }` help: try using `=` instead | LL - B == 2 LL + B = 2 | LL | B = 2 | ~ error: expected item, found `==` --> $DIR/issue-101477-enum.rs:6:7"} {"_id":"doc-en-rust-b21eaad0d9b587eda69f4d3819fdce4ea65545a15f2fb7d0aa43c5b4012da202","title":"","text":"| help: try using `=` instead | LL - let x == 2; LL + let x = 2; | LL | let x = 2; | ~ error: aborting due to 1 previous error"} {"_id":"doc-en-rust-7144bcefea915c03e5dfd35df1670c127d3ce4e874603d1e721e39e25ffbe2eb","title":"","text":" const A: usize ⩵ 2; //~^ ERROR unknown start of token: u{2a75} //~| ERROR unexpected `==` "} {"_id":"doc-en-rust-df70fb20dc8e30beb1669f009f0f872023d56005d496ec1ac96107ef1ec33e5c","title":"","text":" error: unknown start of token: u{2a75} --> $DIR/unicode-double-equals-recovery.rs:1:16 | LL | const A: usize ⩵ 2; | ^ | help: Unicode character '⩵' (Two Consecutive Equals Signs) looks like '==' (Double Equals Sign), but it is not | LL | const A: usize == 2; | ~~ error: unexpected `==` --> $DIR/unicode-double-equals-recovery.rs:1:16 | LL | const A: usize ⩵ 2; | ^ | help: try using `=` instead | LL | const A: usize = 2; | ~ error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-c36478ef51b8cdc2901fe55d26d1e76e8a1fad9a822610f933bee9e04e1724c6","title":"","text":".label = declared `#[non_exhaustive]` here .help = consider a manual implementation of `Default` builtin_macros_non_generic_pointee = the `#[pointee]` attribute may only be used on generic parameters builtin_macros_non_unit_default = the `#[default]` attribute may only be used on unit enum variants .help = consider a manual implementation of `Default`"} {"_id":"doc-en-rust-c383bb1a89938fbf4c4c139f6436d9de40a0d581ac935ba72e0335c486c70bbe","title":"","text":"use rustc_span::{Span, Symbol}; use thin_vec::{ThinVec, thin_vec}; use crate::errors; macro_rules! path { ($span:expr, $($part:ident)::*) => { vec![$(Ident::new(sym::$part, $span),)*] } }"} {"_id":"doc-en-rust-a532b00854c191ebbe21c2e23a38d9e3a1dbe279cf86bccca146dc8456f428e2","title":"","text":"push: &mut dyn FnMut(Annotatable), _is_const: bool, ) { item.visit_with(&mut DetectNonGenericPointeeAttr { cx }); let (name_ident, generics) = if let Annotatable::Item(aitem) = item && let ItemKind::Struct(struct_data, g) = &aitem.kind {"} {"_id":"doc-en-rust-b263fc2bb556d9599974d4083b3425312a89eb33763fbccb35daf3784ff0316c","title":"","text":"} } } struct DetectNonGenericPointeeAttr<'a, 'b> { cx: &'a ExtCtxt<'b>, } impl<'a, 'b> rustc_ast::visit::Visitor<'a> for DetectNonGenericPointeeAttr<'a, 'b> { fn visit_attribute(&mut self, attr: &'a rustc_ast::Attribute) -> Self::Result { if attr.has_name(sym::pointee) { self.cx.dcx().emit_err(errors::NonGenericPointee { span: attr.span }); } } fn visit_generic_param(&mut self, param: &'a rustc_ast::GenericParam) -> Self::Result { let mut error_on_pointee = AlwaysErrorOnGenericParam { cx: self.cx }; match ¶m.kind { GenericParamKind::Type { default } => { // The `default` may end up containing a block expression. // The problem is block expressions may define structs with generics. // A user may attach a #[pointee] attribute to one of these generics // We want to catch that. The simple solution is to just // always raise a `NonGenericPointee` error when this happens. // // This solution does reject valid rust programs but, // such a code would have to, in order: // - Define a smart pointer struct. // - Somewhere in this struct definition use a type with a const generic argument. // - Calculate this const generic in a expression block. // - Define a new smart pointer type in this block. // - Have this smart pointer type have more than 1 generic type. // In this case, the inner smart pointer derive would be complaining that it // needs a pointer attribute. Meanwhile, the outer macro would be complaining // that we attached a #[pointee] to a generic type argument while helpfully // informing the user that #[pointee] can only be attached to generic pointer arguments rustc_ast::visit::visit_opt!(error_on_pointee, visit_ty, default); } GenericParamKind::Const { .. } | GenericParamKind::Lifetime => { rustc_ast::visit::walk_generic_param(&mut error_on_pointee, param); } } } fn visit_ty(&mut self, t: &'a rustc_ast::Ty) -> Self::Result { let mut error_on_pointee = AlwaysErrorOnGenericParam { cx: self.cx }; error_on_pointee.visit_ty(t) } } struct AlwaysErrorOnGenericParam<'a, 'b> { cx: &'a ExtCtxt<'b>, } impl<'a, 'b> rustc_ast::visit::Visitor<'a> for AlwaysErrorOnGenericParam<'a, 'b> { fn visit_attribute(&mut self, attr: &'a rustc_ast::Attribute) -> Self::Result { if attr.has_name(sym::pointee) { self.cx.dcx().emit_err(errors::NonGenericPointee { span: attr.span }); } } } "} {"_id":"doc-en-rust-fc708d83e83871c66597145111b5def2182f5017952ce28d19ae63c5536fba00","title":"","text":"#[label] pub testing_span: Span, } #[derive(Diagnostic)] #[diag(builtin_macros_non_generic_pointee)] pub(crate) struct NonGenericPointee { #[primary_span] pub span: Span, } "} {"_id":"doc-en-rust-5c5739eb7f7cf787716e1d219b5a1cf20698229e2434dd8b86a0535edfed988e","title":"","text":"ptr: &'a T, } #[derive(SmartPointer)] #[repr(transparent)] struct PointeeOnField<'a, #[pointee] T: ?Sized> { #[pointee] //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters ptr: &'a T } #[derive(SmartPointer)] #[repr(transparent)] struct PointeeInTypeConstBlock<'a, T: ?Sized = [u32; const { struct UhOh<#[pointee] T>(T); 10 }]> { //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters ptr: &'a T, } #[derive(SmartPointer)] #[repr(transparent)] struct PointeeInConstConstBlock< 'a, T: ?Sized, const V: u32 = { struct UhOh<#[pointee] T>(T); 10 }> //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters { ptr: &'a T, } #[derive(SmartPointer)] #[repr(transparent)] struct PointeeInAnotherTypeConstBlock<'a, #[pointee] T: ?Sized> { ptr: PointeeInConstConstBlock<'a, T, { struct UhOh<#[pointee] T>(T); 0 }> //~^ ERROR: the `#[pointee]` attribute may only be used on generic parameters } // However, reordering attributes should work nevertheless. #[repr(transparent)] #[derive(SmartPointer)]"} {"_id":"doc-en-rust-d021f9efe50c09214bc93c4515f108dfbc30515558cfc4059bbe34f21b2e2f5a","title":"","text":"LL | struct NoMaybeSized<'a, #[pointee] T> { | ^ error: the `#[pointee]` attribute may only be used on generic parameters --> $DIR/deriving-smart-pointer-neg.rs:59:5 | LL | #[pointee] | ^^^^^^^^^^ error: the `#[pointee]` attribute may only be used on generic parameters --> $DIR/deriving-smart-pointer-neg.rs:66:74 | LL | struct PointeeInTypeConstBlock<'a, T: ?Sized = [u32; const { struct UhOh<#[pointee] T>(T); 10 }]> { | ^^^^^^^^^^ error: the `#[pointee]` attribute may only be used on generic parameters --> $DIR/deriving-smart-pointer-neg.rs:76:34 | LL | const V: u32 = { struct UhOh<#[pointee] T>(T); 10 }> | ^^^^^^^^^^ error: the `#[pointee]` attribute may only be used on generic parameters --> $DIR/deriving-smart-pointer-neg.rs:85:56 | LL | ptr: PointeeInConstConstBlock<'a, T, { struct UhOh<#[pointee] T>(T); 0 }> | ^^^^^^^^^^ error[E0392]: lifetime parameter `'a` is never used --> $DIR/deriving-smart-pointer-neg.rs:15:16 |"} {"_id":"doc-en-rust-01fd467a0cb2b1b6268f5f43c1f57a4afeca184918aadce46b00d7110a7fdfc6","title":"","text":"| = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData` error: aborting due to 12 previous errors error: aborting due to 16 previous errors For more information about this error, try `rustc --explain E0392`."} {"_id":"doc-en-rust-dd467e108184db2e3861333054f0a67946172bf48c382ec33d046ffad1bd27f2","title":"","text":"for debug_info in body.var_debug_info.iter_mut() { if let VarDebugInfoContents::Place(place) = &mut debug_info.value { let mut new_projections: Option> = None; let mut last_deref = 0; for (i, (base, elem)) in place.iter_projections().enumerate() { for (base, elem) in place.iter_projections() { let base_ty = base.ty(&body.local_decls, tcx).ty; if elem == PlaceElem::Deref && base_ty.is_box() { let new_projections = new_projections.get_or_insert_default(); // Clone the projections before us, since now we need to mutate them. let new_projections = new_projections.get_or_insert_with(|| base.projection.to_vec()); let (unique_ty, nonnull_ty, ptr_ty) = build_ptr_tys(tcx, base_ty.boxed_ty(), unique_did, nonnull_did); new_projections.extend_from_slice(&base.projection[last_deref..]); new_projections.extend_from_slice(&build_projection( unique_ty, nonnull_ty, ptr_ty, )); new_projections.push(PlaceElem::Deref); last_deref = i; } else if let Some(new_projections) = new_projections.as_mut() { // Keep building up our projections list once we've started it. new_projections.push(elem); } } if let Some(mut new_projections) = new_projections { new_projections.extend_from_slice(&place.projection[last_deref..]); // Store the mutated projections if we actually changed something. if let Some(new_projections) = new_projections { place.projection = tcx.mk_place_elems(&new_projections); } }"} {"_id":"doc-en-rust-a967a0200e8e3efd8843606cbaa731537dc6692a526a0845314cb4bb2bd260f4","title":"","text":" - // MIR for `pointee` before ElaborateBoxDerefs + // MIR for `pointee` after ElaborateBoxDerefs fn pointee(_1: Box) -> () { - debug foo => (*_1); + debug foo => (*(((_1.0: std::ptr::Unique).0: std::ptr::NonNull).0: *const i32)); let mut _0: (); bb0: { return; } } "} {"_id":"doc-en-rust-7a93e362aa38c93b55e96e0fd3f563ed4dd9f5f7a4595e49de88a528f83d17f6","title":"","text":" // skip-filecheck //@ test-mir-pass: ElaborateBoxDerefs #![feature(custom_mir, core_intrinsics)] extern crate core; use core::intrinsics::mir::*; // EMIT_MIR elaborate_box_deref_in_debuginfo.pointee.ElaborateBoxDerefs.diff #[custom_mir(dialect = \"built\")] fn pointee(opt: Box) { mir!( debug foo => *opt; { Return() } ) } fn main() {} "} {"_id":"doc-en-rust-838b7ba8f410c08dc359601dfb17469c41db51d63a864709ff7a07693638bb60","title":"","text":" //@ aux-build:block-on.rs //@ edition:2021 //@ run-pass #![feature(async_closure)] extern crate block_on; pub trait Trait { fn callback(&mut self); } impl Trait for (i32,) { fn callback(&mut self) { println!(\"hi {}\", self.0); self.0 += 1; } } async fn call_once(f: impl async FnOnce()) { f().await; } async fn run(mut loader: Box) { let f = async move || { loader.callback(); loader.callback(); }; call_once(f).await; } fn main() { block_on::block_on(async { run(Box::new((42,))).await; }); } "} {"_id":"doc-en-rust-c2d14a58e8713da4dd159dc105a41cbe05ef8dd688b73aaaa81f2730dc9a0c0c","title":"","text":" Subproject commit 57ae1a3474057fead2c438928ed368b3740bf0ec Subproject commit ccf4c38bdd73f1a37ec266c73bdaef80e39f8cf6 "} {"_id":"doc-en-rust-ad78282b72a5b859b730cb209cf71380463018deb62c5fa7451d3ebc921f5065","title":"","text":"/// /// # Panics /// /// This function will panic if `rhs` is 0 or if `self` is -1 and `rhs` is /// `Self::MIN`. This behavior is not affected by the `overflow-checks` flag. /// This function will panic if `rhs` is 0 or if `self` is `Self::MIN` and /// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. /// /// # Examples ///"} {"_id":"doc-en-rust-bbd7365e50b60b71c5cfbf0c1fa4923915a2bc95f3d744c32e6e8d1988c45792","title":"","text":"/// assert_eq!(a.rem_euclid(-b), 3); /// assert_eq!((-a).rem_euclid(-b), 1); /// ``` /// /// This will panic: /// ```should_panic #[doc = concat!(\"let _ = \", stringify!($SelfT), \"::MIN.rem_euclid(-1);\")] /// ``` #[doc(alias = \"modulo\", alias = \"mod\")] #[stable(feature = \"euclidean_division\", since = \"1.38.0\")] #[rustc_const_stable(feature = \"const_euclidean_int_methods\", since = \"1.52.0\")]"} {"_id":"doc-en-rust-9ba6adab01593444776a1cdeadfef0aa02c38ce8c950a315ac0d010883bf21a6","title":"","text":"/// /// # Panics /// /// This function will panic if `rhs` is 0 or if `self` is -1 and `rhs` is /// `Self::MIN`. This behavior is not affected by the `overflow-checks` flag. /// This function will panic if `rhs` is 0 or if `self` is `Self::MIN` /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. /// /// # Examples ///"} {"_id":"doc-en-rust-f63a7e31527f5adbd85bdc5aec0bcf0fc67c5abf5c92ba7dd5aa08339307c75f","title":"","text":"use rustc_middle::ty::{self, InstanceKind, Ty, TyCtxt, TypeVisitableExt}; use rustc_target::abi::{FieldIdx, VariantIdx}; use crate::pass_manager::validate_body; pub struct ByMoveBody; impl<'tcx> MirPass<'tcx> for ByMoveBody {"} {"_id":"doc-en-rust-594093542e3c642917fb955132a01cdab08176daf2ced3955ffc5d9d1280df05","title":"","text":"|(parent_field_idx, parent_capture), (child_field_idx, child_capture)| { // Store this set of additional projections (fields and derefs). // We need to re-apply them later. let child_precise_captures = &child_capture.place.projections[parent_capture.place.projections.len()..]; let mut child_precise_captures = child_capture.place.projections [parent_capture.place.projections.len()..] .to_vec(); // If the parent captures by-move, and the child captures by-ref, then we // need to peel an additional `deref` off of the body of the child. let needs_deref = child_capture.is_by_ref() && !parent_capture.is_by_ref(); if needs_deref { assert_ne!( coroutine_kind, ty::ClosureKind::FnOnce, // If the parent capture is by-ref, then we need to apply an additional // deref before applying any further projections to this place. if parent_capture.is_by_ref() { child_precise_captures.insert( 0, Projection { ty: parent_capture.place.ty(), kind: ProjectionKind::Deref }, ); } // If the child capture is by-ref, then we need to apply a \"ref\" // projection (i.e. `&`) at the end. But wait! We don't have that // as a projection kind. So instead, we can apply its dual and // *peel* a deref off of the place when it shows up in the MIR body. // Luckily, by construction this is always possible. let peel_deref = if child_capture.is_by_ref() { assert!( parent_capture.is_by_ref() || coroutine_kind != ty::ClosureKind::FnOnce, \"`FnOnce` coroutine-closures return coroutines that capture from their body; it will always result in a borrowck error!\" ); } true } else { false }; // Regarding the behavior above, you may think that it's redundant to both // insert a deref and then peel a deref if the parent and child are both // captured by-ref. This would be correct, except for the case where we have // precise capturing projections, since the inserted deref is to the *beginning* // and the peeled deref is at the *end*. I cannot seem to actually find a // case where this happens, though, but let's keep this code flexible. // Finally, store the type of the parent's captured place. We need // this when building the field projection in the MIR body later on."} {"_id":"doc-en-rust-bb26df226fd43cd78a7ed6e05ee162798be02cc409cf476ee3494e0e1db5694c","title":"","text":"( FieldIdx::from_usize(parent_field_idx + num_args), parent_capture_ty, needs_deref, peel_deref, child_precise_captures, ), )"} {"_id":"doc-en-rust-0acb37b8ab0e7e749f6ebd7122c218acbf0a8b8a4104886d1867572fa9f6704a","title":"","text":"let mut by_move_body = body.clone(); MakeByMoveBody { tcx, field_remapping, by_move_coroutine_ty }.visit_body(&mut by_move_body); dump_mir(tcx, false, \"coroutine_by_move\", &0, &by_move_body, |_, _| Ok(())); // Let's just always validate this body. validate_body(tcx, &mut by_move_body, \"Initial coroutine_by_move body\".to_string()); // FIXME: use query feeding to generate the body right here and then only store the `DefId` of the new body. by_move_body.source = mir::MirSource::from_instance(InstanceKind::CoroutineKindShim { coroutine_def_id: coroutine_def_id.to_def_id(),"} {"_id":"doc-en-rust-246971c6fa7db8f5d49339f1338d510e8e8a03f2754021c978b401b196d3c002","title":"","text":"struct MakeByMoveBody<'tcx> { tcx: TyCtxt<'tcx>, field_remapping: UnordMap, bool, &'tcx [Projection<'tcx>])>, field_remapping: UnordMap, bool, Vec>)>, by_move_coroutine_ty: Ty<'tcx>, }"} {"_id":"doc-en-rust-6af7ba850bbb460e71f617d3fc40915755373497f54c982175763db38f1b9575","title":"","text":"if place.local == ty::CAPTURE_STRUCT_LOCAL && let Some((&mir::ProjectionElem::Field(idx, _), projection)) = place.projection.split_first() && let Some(&(remapped_idx, remapped_ty, needs_deref, bridging_projections)) = && let Some(&(remapped_idx, remapped_ty, peel_deref, ref bridging_projections)) = self.field_remapping.get(&idx) { // As noted before, if the parent closure captures a field by value, and // the child captures a field by ref, then for the by-move body we're // generating, we also are taking that field by value. Peel off a deref, // since a layer of ref'ing has now become redundant. let final_projections = if needs_deref { let final_projections = if peel_deref { let Some((mir::ProjectionElem::Deref, projection)) = projection.split_first() else { bug!("} {"_id":"doc-en-rust-5576f553d29e35bc22eaf008d14385dd29c6cb5bafedbc508b73f4cb34a8ffda","title":"","text":" //@ compile-flags: -Zvalidate-mir //@ edition: 2021 #![feature(async_closure)] // NOT copy. struct Ty; fn hello(x: &Ty) { let c = async || { *x; //~^ ERROR cannot move out of `*x` which is behind a shared reference }; } fn main() {} "} {"_id":"doc-en-rust-bd0a90bae463ec02f6cc61cb5fc3248680c13f6b3323ef184a72b665a90449e2","title":"","text":" error[E0507]: cannot move out of `*x` which is behind a shared reference --> $DIR/move-out-of-ref.rs:11:9 | LL | *x; | ^^ move occurs because `*x` has type `Ty`, which does not implement the `Copy` trait | note: if `Ty` implemented `Clone`, you could clone the value --> $DIR/move-out-of-ref.rs:7:1 | LL | struct Ty; | ^^^^^^^^^ consider implementing `Clone` for this type ... LL | *x; | -- you could clone this value error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0507`. "} {"_id":"doc-en-rust-9c96de633a8dacb3a8388c6d099abb09a902aba100c04fb98598ffba2a73c39b","title":"","text":"// the string \"false\". Now it is disabled by absence of the attribute. to_add.push(llvm::CreateAttrStringValue(cx.llcx, \"branch-target-enforcement\", \"false\")); } } else if llvm_util::get_version() >= (19, 0, 0) { // For non-naked functions, set branch protection attributes on aarch64. if let Some(BranchProtection { bti, pac_ret }) = cx.sess().opts.unstable_opts.branch_protection { assert!(cx.sess().target.arch == \"aarch64\"); if bti { to_add.push(llvm::CreateAttrString(cx.llcx, \"branch-target-enforcement\")); } if let Some(PacRet { leaf, key }) = pac_ret { to_add.push(llvm::CreateAttrStringValue( cx.llcx, \"sign-return-address\", if leaf { \"all\" } else { \"non-leaf\" }, )); to_add.push(llvm::CreateAttrStringValue( cx.llcx, \"sign-return-address-key\", if key == PAuthKey::A { \"a_key\" } else { \"b_key\" }, )); } else { // Do not set sanitizer attributes for naked functions. to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize)); if llvm_util::get_version() >= (19, 0, 0) { // For non-naked functions, set branch protection attributes on aarch64. if let Some(BranchProtection { bti, pac_ret }) = cx.sess().opts.unstable_opts.branch_protection { assert!(cx.sess().target.arch == \"aarch64\"); if bti { to_add.push(llvm::CreateAttrString(cx.llcx, \"branch-target-enforcement\")); } if let Some(PacRet { leaf, key }) = pac_ret { to_add.push(llvm::CreateAttrStringValue( cx.llcx, \"sign-return-address\", if leaf { \"all\" } else { \"non-leaf\" }, )); to_add.push(llvm::CreateAttrStringValue( cx.llcx, \"sign-return-address-key\", if key == PAuthKey::A { \"a_key\" } else { \"b_key\" }, )); } } } }"} {"_id":"doc-en-rust-2026f0981782b64b5b2a0aebb4d5182804420662823d761d730c9594a30762bb","title":"","text":"if let Some(backchain) = backchain_attr(cx) { to_add.push(backchain); } to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize)); to_add.extend(patchable_function_entry_attrs(cx, codegen_fn_attrs.patchable_function_entry)); // Always annotate functions with the target-cpu they are compiled for."} {"_id":"doc-en-rust-87987e181184955aa4ce20d7be5281cce0463fa889d13842596077a03d17021d","title":"","text":" // Make sure we do not request sanitizers for naked functions. //@ only-x86_64 //@ needs-sanitizer-address //@ compile-flags: -Zsanitizer=address -Ctarget-feature=-crt-static #![crate_type = \"lib\"] #![no_std] #![feature(abi_x86_interrupt, naked_functions)] // CHECK: define x86_intrcc void @page_fault_handler(ptr {{.*}}%0, i64 {{.*}}%1){{.*}}#[[ATTRS:[0-9]+]] { // CHECK-NOT: memcpy #[naked] #[no_mangle] pub extern \"x86-interrupt\" fn page_fault_handler(_: u64, _: u64) { unsafe { core::arch::asm!(\"ud2\", options(noreturn)); } } // CHECK: #[[ATTRS]] = // CHECK-NOT: sanitize_address "} {"_id":"doc-en-rust-2b96983ec90e878484a341e57676c9abb8ba89ef3da07a3da009e313c732fbd4","title":"","text":"let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig); if let Err(terr) = self.eq_types( *ty, if let Err(terr) = self.sub_types( ty_fn_ptr_from, *ty, location.to_locations(), ConstraintCategory::Cast { unsize_to: None }, ) {"} {"_id":"doc-en-rust-667c8dabd338c2afbcf673e9e0e74b2a5c56ece28754f1de1c5bc1f89724a3da","title":"","text":" //@ check-pass fn higher_ranked_fndef(ctx: &mut ()) {} fn test(higher_ranked_fnptr: fn(&mut ())) { fn as_unsafe(_: unsafe fn(T)) {} // Make sure that we can cast higher-ranked fn items and pointers to // a non-higher-ranked target. as_unsafe(higher_ranked_fndef); as_unsafe(higher_ranked_fnptr); } fn main() {} "} {"_id":"doc-en-rust-195b524e255a3c29b6a82717d9486970a337b7923608bed24ec2cb0f2ee3b6e6","title":"","text":") -> DefId { let body = tcx.mir_built(coroutine_def_id).borrow(); // If the typeck results are tainted, no need to make a by-ref body. if body.tainted_by_errors.is_some() { return coroutine_def_id.to_def_id(); } let Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure)) = tcx.coroutine_kind(coroutine_def_id) else {"} {"_id":"doc-en-rust-ae15a8fa492b329292f0395503d64b74f329132acc869fffff62231fee12f126","title":"","text":"// the MIR body will be constructed well. let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty; let ty::Coroutine(_, args) = *coroutine_ty.kind() else { bug!(\"{body:#?}\") }; let ty::Coroutine(_, args) = *coroutine_ty.kind() else { bug!(\"tried to create by-move body of non-coroutine receiver\"); }; let args = args.as_coroutine(); let coroutine_kind = args.kind_ty().to_opt_closure_kind().unwrap();"} {"_id":"doc-en-rust-9abb73820cedad68a8605de79954cab92ba723b0c0f3f8a5a1b9109bcbbc0629","title":"","text":"let ty::CoroutineClosure(_, parent_args) = *tcx.type_of(parent_def_id).instantiate_identity().kind() else { bug!(); bug!(\"coroutine's parent was not a coroutine-closure\"); }; if parent_args.references_error() { return coroutine_def_id.to_def_id();"} {"_id":"doc-en-rust-ed86969ce1f5fe9f315286492fcc9312e8df501249c714f2d91530301983536e","title":"","text":" //@ edition: 2021 #![feature(async_closure)] // Ensure that building a by-ref async closure body doesn't ICE when the parent // body is tainted. fn main() { missing; //~^ ERROR cannot find value `missing` in this scope // We don't do numerical inference fallback when the body is tainted. // This leads to writeback folding the type of the coroutine-closure // into an error type, since its signature contains that numerical // infer var. let c = async |_| {}; c(1); } "} {"_id":"doc-en-rust-2b59ef0484e1934e65811906f31e7a627cf2f93311a4e1d8d301470679300f0d","title":"","text":" error[E0425]: cannot find value `missing` in this scope --> $DIR/tainted-body-2.rs:9:5 | LL | missing; | ^^^^^^^ not found in this scope error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0425`. "} {"_id":"doc-en-rust-ab87e9104d653f8b92549af0f7c9f6a1d4a187a5a92164d4ca135847cb6cc0ae","title":"","text":"let mut span = None; let mut accum = 0u64; for (index, arg_def) in fn_sig.inputs().iter().enumerate() { let layout = tcx.layout_of(ParamEnv::reveal_all().and(*arg_def.skip_binder()))?; // this type is only used for layout computation, which does not rely on regions let fn_sig = tcx.instantiate_bound_regions_with_erased(fn_sig); for (index, ty) in fn_sig.inputs().iter().enumerate() { let layout = tcx.layout_of(ParamEnv::reveal_all().and(*ty))?; let align = layout.layout.align().abi.bytes(); let size = layout.layout.size().bytes();"} {"_id":"doc-en-rust-f64453506f8b7b7666fda53b63f3622fbe3b6a2241275b9a5c18725402a10985","title":"","text":"tcx: TyCtxt<'tcx>, fn_sig: ty::PolyFnSig<'tcx>, ) -> Result> { let mut ret_ty = fn_sig.output().skip_binder(); // this type is only used for layout computation, which does not rely on regions let fn_sig = tcx.instantiate_bound_regions_with_erased(fn_sig); let mut ret_ty = fn_sig.output(); let layout = tcx.layout_of(ParamEnv::reveal_all().and(ret_ty))?; let size = layout.layout.size().bytes();"} {"_id":"doc-en-rust-d6555ca75d9341c03aace7b0807ccce581ed5bdba82babe431bd2557da5c29a9","title":"","text":"struct Wrapper(T); struct Test { f1: extern \"C-cmse-nonsecure-call\" fn(U, u32, u32, u32) -> u64, //~ ERROR cannot find type `U` in this scope //~^ ERROR function pointer types may not have generic parameters f1: extern \"C-cmse-nonsecure-call\" fn(U, u32, u32, u32) -> u64, //~^ ERROR cannot find type `U` in this scope //~| ERROR function pointer types may not have generic parameters f2: extern \"C-cmse-nonsecure-call\" fn(impl Copy, u32, u32, u32) -> u64, //~^ ERROR `impl Trait` is not allowed in `fn` pointer parameters f3: extern \"C-cmse-nonsecure-call\" fn(T, u32, u32, u32) -> u64, //~ ERROR [E0798] f4: extern \"C-cmse-nonsecure-call\" fn(Wrapper, u32, u32, u32) -> u64, //~ ERROR [E0798] } type WithReference = extern \"C-cmse-nonsecure-call\" fn(&usize); trait Trait {} type WithTraitObject = extern \"C-cmse-nonsecure-call\" fn(&dyn Trait) -> &dyn Trait; //~^ ERROR return value of `\"C-cmse-nonsecure-call\"` function too large to pass via registers [E0798] type WithStaticTraitObject = extern \"C-cmse-nonsecure-call\" fn(&'static dyn Trait) -> &'static dyn Trait; //~^ ERROR return value of `\"C-cmse-nonsecure-call\"` function too large to pass via registers [E0798] #[repr(transparent)] struct WrapperTransparent<'a>(&'a dyn Trait); type WithTransparentTraitObject = extern \"C-cmse-nonsecure-call\" fn(WrapperTransparent) -> WrapperTransparent; //~^ ERROR return value of `\"C-cmse-nonsecure-call\"` function too large to pass via registers [E0798] type WithVarArgs = extern \"C-cmse-nonsecure-call\" fn(u32, ...); //~^ ERROR C-variadic function must have a compatible calling convention, like `C` or `cdecl` [E0045] "} {"_id":"doc-en-rust-f231daaa99862eff128573c58507909f093546aab8bcc48857110ad541219fd3","title":"","text":"| +++ error[E0562]: `impl Trait` is not allowed in `fn` pointer parameters --> $DIR/generics.rs:17:43 --> $DIR/generics.rs:18:43 | LL | f2: extern \"C-cmse-nonsecure-call\" fn(impl Copy, u32, u32, u32) -> u64, | ^^^^^^^^^"} {"_id":"doc-en-rust-51d36013277a2150cff5ecb7e97ebfcdc9d42abf388f276efffc13781a598ca5","title":"","text":"= note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0798]: function pointers with the `\"C-cmse-nonsecure-call\"` ABI cannot contain generics in their type --> $DIR/generics.rs:19:9 --> $DIR/generics.rs:20:9 | LL | f3: extern \"C-cmse-nonsecure-call\" fn(T, u32, u32, u32) -> u64, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0798]: function pointers with the `\"C-cmse-nonsecure-call\"` ABI cannot contain generics in their type --> $DIR/generics.rs:20:9 --> $DIR/generics.rs:21:9 | LL | f4: extern \"C-cmse-nonsecure-call\" fn(Wrapper, u32, u32, u32) -> u64, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 5 previous errors error[E0798]: return value of `\"C-cmse-nonsecure-call\"` function too large to pass via registers --> $DIR/generics.rs:27:73 | LL | type WithTraitObject = extern \"C-cmse-nonsecure-call\" fn(&dyn Trait) -> &dyn Trait; | ^^^^^^^^^^ this type doesn't fit in the available registers | = note: functions with the `\"C-cmse-nonsecure-call\"` ABI must pass their result via the available return registers = note: the result must either be a (transparently wrapped) i64, u64 or f64, or be at most 4 bytes in size error[E0798]: return value of `\"C-cmse-nonsecure-call\"` function too large to pass via registers --> $DIR/generics.rs:31:62 | LL | extern \"C-cmse-nonsecure-call\" fn(&'static dyn Trait) -> &'static dyn Trait; | ^^^^^^^^^^^^^^^^^^ this type doesn't fit in the available registers | = note: functions with the `\"C-cmse-nonsecure-call\"` ABI must pass their result via the available return registers = note: the result must either be a (transparently wrapped) i64, u64 or f64, or be at most 4 bytes in size error[E0798]: return value of `\"C-cmse-nonsecure-call\"` function too large to pass via registers --> $DIR/generics.rs:38:62 | LL | extern \"C-cmse-nonsecure-call\" fn(WrapperTransparent) -> WrapperTransparent; | ^^^^^^^^^^^^^^^^^^ this type doesn't fit in the available registers | = note: functions with the `\"C-cmse-nonsecure-call\"` ABI must pass their result via the available return registers = note: the result must either be a (transparently wrapped) i64, u64 or f64, or be at most 4 bytes in size error[E0045]: C-variadic function must have a compatible calling convention, like `C` or `cdecl` --> $DIR/generics.rs:41:20 | LL | type WithVarArgs = extern \"C-cmse-nonsecure-call\" fn(u32, ...); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ C-variadic function must have a compatible calling convention error: aborting due to 9 previous errors Some errors have detailed explanations: E0412, E0562, E0798. For more information about an error, try `rustc --explain E0412`. Some errors have detailed explanations: E0045, E0412, E0562, E0798. For more information about an error, try `rustc --explain E0045`. "} {"_id":"doc-en-rust-65ad448162ffbe927c855a43f2d3d58f89d00cc5813678b331e74ee120ab5043","title":"","text":"cmd_finder.must_have(s); } // this warning is useless in CI, // and CI probably won't have the right branches anyway. if !build_helper::ci::CiEnv::is_ci() { if let Err(e) = warn_old_master_branch(&build.config.git_config(), &build.config.src) .map_err(|e| e.to_string()) { eprintln!(\"unable to check if upstream branch is old: {e}\"); } } warn_old_master_branch(&build.config.git_config(), &build.config.src); }"} {"_id":"doc-en-rust-7c53f53a5b1696c94e40c40866af87881c690de0050e4903796f7df2720f1441","title":"","text":"/// /// This can result in formatting thousands of files instead of a dozen, /// so we should warn the user something is wrong. pub fn warn_old_master_branch( config: &GitConfig<'_>, git_dir: &Path, ) -> Result<(), Box> { use std::time::Duration; const WARN_AFTER: Duration = Duration::from_secs(60 * 60 * 24 * 10); let updated_master = updated_master_branch(config, Some(git_dir))?; let branch_path = git_dir.join(\".git/refs/remotes\").join(&updated_master); match std::fs::metadata(branch_path) { Ok(meta) => { if meta.modified()?.elapsed()? > WARN_AFTER { eprintln!(\"warning: {updated_master} has not been updated in 10 days\"); } else { return Ok(()); pub fn warn_old_master_branch(config: &GitConfig<'_>, git_dir: &Path) { if crate::ci::CiEnv::is_ci() { // this warning is useless in CI, // and CI probably won't have the right branches anyway. return; } // this will be overwritten by the actual name, if possible let mut updated_master = \"the upstream master branch\".to_string(); match warn_old_master_branch_(config, git_dir, &mut updated_master) { Ok(branch_is_old) => { if !branch_is_old { return; } // otherwise fall through and print the rest of the warning } Err(err) => { eprintln!(\"warning: unable to check if {updated_master} is old due to error: {err}\")"} {"_id":"doc-en-rust-33c1852cb498b6cb3cd43fedbfe5045f43b48324a451b338090af43f12e00932","title":"","text":"} eprintln!( \"warning: {updated_master} is used to determine if files have been modifiedn warning: if it is not updated, this may cause files to be needlessly reformatted\" warning: if it is not updated, this may cause files to be needlessly reformatted\" ); Ok(()) } pub fn warn_old_master_branch_( config: &GitConfig<'_>, git_dir: &Path, updated_master: &mut String, ) -> Result> { use std::time::Duration; *updated_master = updated_master_branch(config, Some(git_dir))?; let branch_path = git_dir.join(\".git/refs/remotes\").join(&updated_master); const WARN_AFTER: Duration = Duration::from_secs(60 * 60 * 24 * 10); let meta = match std::fs::metadata(&branch_path) { Ok(meta) => meta, Err(err) => { let gcd = git_common_dir(&git_dir)?; if branch_path.starts_with(&gcd) { return Err(Box::new(err)); } std::fs::metadata(Path::new(&gcd).join(\"refs/remotes\").join(&updated_master))? } }; if meta.modified()?.elapsed()? > WARN_AFTER { eprintln!(\"warning: {updated_master} has not been updated in 10 days\"); Ok(true) } else { Ok(false) } } fn git_common_dir(dir: &Path) -> Result { output_result(Command::new(\"git\").arg(\"-C\").arg(dir).arg(\"rev-parse\").arg(\"--git-common-dir\")) .map(|x| x.trim().to_string()) }"} {"_id":"doc-en-rust-07552713ebecdb5d8e43cb04b7e6d895c6cbbf1b5b050102b58e302082c5e6b3","title":"","text":"} #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub struct ExitCode(bool); pub struct ExitCode(u8); impl ExitCode { pub const SUCCESS: ExitCode = ExitCode(false); pub const FAILURE: ExitCode = ExitCode(true); pub const SUCCESS: ExitCode = ExitCode(0); pub const FAILURE: ExitCode = ExitCode(1); pub fn as_i32(&self) -> i32 { self.0 as i32"} {"_id":"doc-en-rust-c5e7386c13767f7391649ff2b14dfc46ad5fc3e24fb41058ff6bf93f520af181","title":"","text":"impl From for ExitCode { fn from(code: u8) -> Self { match code { 0 => Self::SUCCESS, 1..=255 => Self::FAILURE, } Self(code) } }"} {"_id":"doc-en-rust-befadc9d8ae18c2bd54af358547081737beef636f0fd03bf2167214e048233bf","title":"","text":"// if a test does not crash, consider it an error if proc_res.status.success() || matches!(proc_res.status.code(), Some(1 | 0)) { self.fatal(&format!( \"crashtest no longer crashes/triggers ICE, horray! Please give it a meaningful name, add a doc-comment to the start of the test explaining why it exists and move it to tests/ui or wherever you see fit. Adding 'Fixes #' to your PR description ensures that the corresponding ticket is auto-closed upon merge.\" \"crashtest no longer crashes/triggers ICE, horray! Please give it a meaningful name, add a doc-comment to the start of the test explaining why it exists and move it to tests/ui or wherever you see fit. Adding 'Fixes #' to your PR description ensures that the corresponding ticket is auto-closed upon merge. If you want to see verbose output, set `COMPILETEST_VERBOSE_CRASHES=1`.\" )); } }"} {"_id":"doc-en-rust-e313692c0c80505b75f33de0bd915a307942b283b2523300357279c68d4fb2b1","title":"","text":"} .docblock li { margin-bottom: .8em; margin-bottom: .4em; } .docblock li p { margin-bottom: .1em; .docblock li p:not(:last-child) { /* This margin is voluntarily smaller than `.docblock li` to keep the visual list element items separated while also having a visual separation (although smaller) for paragraphs. */ margin-bottom: .3em; } /* \"where ...\" clauses with block display are also smaller */"} {"_id":"doc-en-rust-410fb58c600aed9f7df4684266b82369eacda9a9e6a090ae7fe014c1c0efa1e8","title":"","text":" // This test ensures that the documentation list markers are correctly placed. // It also serves as a regression test for . go-to: \"file://\" + |DOC_PATH| + \"/test_docs/long_list/index.html\" show-text: true // 0.3em assert-css: (\".docblock li p:not(last-child)\", {\"margin-bottom\": \"4.8px\"}) assert-css: (\".docblock li p + p:last-child\", {\"margin-bottom\": \"0px\"}) // 0.4em assert-css: (\".docblock li\", {\"margin-bottom\": \"6.4px\"}) "} {"_id":"doc-en-rust-9267cc74dc79a7f665ea78fdd8ced5df0fb05824faba881d0fa938c06feb2dc0","title":"","text":"/// subt_vec_num(x: &[f64], y: f64) pub fn subt_vec_num() {} } pub mod long_list { //! bla //! //! * Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et libero ut leo //! interdum laoreet vitae a mi. Aliquam erat volutpat. Suspendisse volutpat non quam non //! commodo. //! //! Praesent enim neque, imperdiet sed nisl at, lobortis egestas augue. Sed vitae tristique //! augue. Phasellus vel pretium lectus. //! * Praesent enim neque, imperdiet sed nisl at, lobortis egestas augue. Sed vitae tristique //! augue. Phasellus vel pretium lectus. //! * Praesent enim neque, imperdiet sed nisl at, lobortis egestas augue. Sed vitae tristique //! augue. Phasellus vel pretium lectus. //! //! Another list: //! //! * [`TryFromBytes`](#a) indicates that a type may safely be converted from certain byte //! sequence (conditional on runtime checks) //! * [`FromZeros`](#a) indicates that a sequence of zero bytes represents a valid instance of //! a type //! * [`FromBytes`](#a) indicates that a type may safely be converted from an arbitrary byte //! sequence } "} {"_id":"doc-en-rust-b08164a05d3b8e28d4e474af16a85e92d7a78d5f268e59bbb44dcce1ac693467","title":"","text":"} macro_rules! tool_check_step { ($name:ident, $path:literal, $($alias:literal, )* $source_type:path $(, $default:literal )?) => { ( $name:ident, $display_name:literal, $path:literal, $($alias:literal, )* $source_type:path $(, $default:literal )? ) => { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct $name { pub target: TargetSelection,"} {"_id":"doc-en-rust-fc8d1ffdd12b60843f644abbf7f001671b6e439b5e174029ec4f71a1177665d1","title":"","text":"cargo.arg(\"--all-targets\"); } let _guard = builder.msg_check(&concat!(stringify!($name), \" artifacts\").to_lowercase(), target); let _guard = builder.msg_check(&format!(\"{} artifacts\", $display_name), target); run_cargo( builder, cargo,"} {"_id":"doc-en-rust-7b2a1fa9bc7af9b1ee54931eab4f360a2f01dd7f21cf6d0d248f0781e9ceda86","title":"","text":"}; } tool_check_step!(Rustdoc, \"src/tools/rustdoc\", \"src/librustdoc\", SourceType::InTree); tool_check_step!(Rustdoc, \"rustdoc\", \"src/tools/rustdoc\", \"src/librustdoc\", SourceType::InTree); // Clippy, miri and Rustfmt are hybrids. They are external tools, but use a git subtree instead // of a submodule. Since the SourceType only drives the deny-warnings // behavior, treat it as in-tree so that any new warnings in clippy will be // rejected. tool_check_step!(Clippy, \"src/tools/clippy\", SourceType::InTree); tool_check_step!(Miri, \"src/tools/miri\", SourceType::InTree); tool_check_step!(CargoMiri, \"src/tools/miri/cargo-miri\", SourceType::InTree); tool_check_step!(Rls, \"src/tools/rls\", SourceType::InTree); tool_check_step!(Rustfmt, \"src/tools/rustfmt\", SourceType::InTree); tool_check_step!(MiroptTestTools, \"src/tools/miropt-test-tools\", SourceType::InTree); tool_check_step!(TestFloatParse, \"src/etc/test-float-parse\", SourceType::InTree); tool_check_step!(Bootstrap, \"src/bootstrap\", SourceType::InTree, false); tool_check_step!(Clippy, \"clippy\", \"src/tools/clippy\", SourceType::InTree); tool_check_step!(Miri, \"miri\", \"src/tools/miri\", SourceType::InTree); tool_check_step!(CargoMiri, \"cargo-miri\", \"src/tools/miri/cargo-miri\", SourceType::InTree); tool_check_step!(Rls, \"rls\", \"src/tools/rls\", SourceType::InTree); tool_check_step!(Rustfmt, \"rustfmt\", \"src/tools/rustfmt\", SourceType::InTree); tool_check_step!( MiroptTestTools, \"miropt-test-tools\", \"src/tools/miropt-test-tools\", SourceType::InTree ); tool_check_step!( TestFloatParse, \"test-float-parse\", \"src/etc/test-float-parse\", SourceType::InTree ); tool_check_step!(Bootstrap, \"bootstrap\", \"src/bootstrap\", SourceType::InTree, false); /// Cargo's output path for the standard library in a given stage, compiled /// by a particular compiler for the specified target."} {"_id":"doc-en-rust-c3c39c461d1f3023a525d970bba5f909feaca461f2dbab1cc34571bcc8de54bd","title":"","text":"}); } function escape(content) { return $('

').text(content).html(); } function showResults(results) { var output, shown, query = getQuery(); currentResults = query.id; output = '

Results for ' + query.query + (query.type ? ' (type: ' + query.type + ')' : '') + '

';
output = '

Results for ' + escape(query.query) + (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '

';
output += ''; if (results.length > 0) {"} {"_id":"doc-en-rust-69c99b0346395fef1d45d325013b6bf1f8c94c5bc6c852a44e70fd37fbbbf49b","title":"","text":"TcpWatcher { home: home, handle: handle, stream: StreamWatcher::new(handle), stream: StreamWatcher::new(handle, true), refcount: Refcount::new(), read_access: AccessTimeout::new(), write_access: AccessTimeout::new(),"} {"_id":"doc-en-rust-a6966750d305edc18f9bef57fd91898b1f7681fc228c3e1f887d4ea776f67318","title":"","text":"fn clone(&self) -> Box { box TcpWatcher { handle: self.handle, stream: StreamWatcher::new(self.handle), stream: StreamWatcher::new(self.handle, false), home: self.home.clone(), refcount: self.refcount.clone(), read_access: self.read_access.clone(),"} {"_id":"doc-en-rust-61369d386a602974940cb3d5c0243dae273ac82922ee5c3ca0830346607f467d","title":"","text":"handle }; PipeWatcher { stream: StreamWatcher::new(handle), stream: StreamWatcher::new(handle, true), home: home, defused: false, refcount: Refcount::new(),"} {"_id":"doc-en-rust-ba5aca8f6af0328216fafc04040254a94beca92d09fe1a9511362abb510abe3c","title":"","text":"fn clone(&self) -> Box { box PipeWatcher { stream: StreamWatcher::new(self.stream.handle), stream: StreamWatcher::new(self.stream.handle, false), defused: false, home: self.home.clone(), refcount: self.refcount.clone(),"} {"_id":"doc-en-rust-43905e2bbb9233151e330faa6ff124ca67cfb3797e0bc36161de37f3f2507c43","title":"","text":"// will be manipulated on each of the methods called on this watcher. // Wrappers should ensure to always reset the field to an appropriate value // if they rely on the field to perform an action. pub fn new(stream: *mut uvll::uv_stream_t) -> StreamWatcher { unsafe { uvll::set_data_for_uv_handle(stream, 0 as *mut int) } pub fn new(stream: *mut uvll::uv_stream_t, init: bool) -> StreamWatcher { if init { unsafe { uvll::set_data_for_uv_handle(stream, 0 as *mut int) } } StreamWatcher { handle: stream, last_write_req: None,"} {"_id":"doc-en-rust-c39de5c1788921b6616f1eb49366f13163b93ff472493386115cadc9684b851f","title":"","text":"let handle = UvHandle::alloc(None::, uvll::UV_TTY); let mut watcher = TtyWatcher { tty: handle, stream: StreamWatcher::new(handle), stream: StreamWatcher::new(handle, true), home: io.make_handle(), fd: fd, };"} {"_id":"doc-en-rust-f500210e006521a4e86437440665632bb5aa7fe82f4750e0111ca6860035e1e4","title":"","text":"rx2.recv(); }) iotest!(fn clone_while_reading() { let addr = next_test_ip6(); let listen = TcpListener::bind(addr.ip.to_str().as_slice(), addr.port); let mut accept = listen.listen().unwrap(); // Enqueue a task to write to a socket let (tx, rx) = channel(); let (txdone, rxdone) = channel(); let txdone2 = txdone.clone(); spawn(proc() { let mut tcp = TcpStream::connect(addr.ip.to_str().as_slice(), addr.port).unwrap(); rx.recv(); tcp.write_u8(0).unwrap(); txdone2.send(()); }); // Spawn off a reading clone let tcp = accept.accept().unwrap(); let tcp2 = tcp.clone(); let txdone3 = txdone.clone(); spawn(proc() { let mut tcp2 = tcp2; tcp2.read_u8().unwrap(); txdone3.send(()); }); // Try to ensure that the reading clone is indeed reading for _ in range(0i, 50) { ::task::deschedule(); } // clone the handle again while it's reading, then let it finish the // read. let _ = tcp.clone(); tx.send(()); rxdone.recv(); rxdone.recv(); }) }"} {"_id":"doc-en-rust-c9de5aa0299c0939df8a387a4d5fbc71f98b83b98e5b06048dce63cd75fb951a","title":"","text":"use std::io::timer; use mem; let mut tb = TaskBuilder::new(); let tb = TaskBuilder::new(); let rx = tb.try_future(proc() {}); mem::drop(rx); timer::sleep(1000);"} {"_id":"doc-en-rust-a09bf7a8e75d06042658e2778c9b9c15a3e36eb32ef6717c94ea32ba7c360e1d","title":"","text":"gimli.debug = 0 miniz_oxide.debug = 0 object.debug = 0 rustc-demangle.debug = 0 # These are very thin wrappers around executing lld with the right binary name. # Basically nothing within them can go wrong without having been explicitly logged anyway."} {"_id":"doc-en-rust-c72addacf44a5537404c0e4be2a2fccd47fb92e3c1292469b8f8f908eb4e662a","title":"","text":" use crate::ffi::OsStr; use crate::ffi::{OsStr, OsString}; use crate::fmt; use crate::io; use crate::marker::PhantomData; use crate::num::NonZero; use crate::path::Path; use crate::sys::fs::File;"} {"_id":"doc-en-rust-8a8e239d876b56c40a355b52855a80e47e514eb6561968dd1aea4c739cc5f044","title":"","text":"//////////////////////////////////////////////////////////////////////////////// pub struct Command { program: OsString, args: Vec, env: CommandEnv, cwd: Option, stdin: Option, stdout: Option, stderr: Option, } // passed back to std::process with the pipes connected to the child, if any"} {"_id":"doc-en-rust-2b046f497506dfdda8ce696fa63944599ee8fcf3164a51fb494934fe83e16dba","title":"","text":"pub stderr: Option, } // FIXME: This should be a unit struct, so we can always construct it // The value here should be never used, since we cannot spawn processes. #[derive(Debug)] pub enum Stdio { Inherit, Null, MakePipe, ParentStdout, ParentStderr, #[allow(dead_code)] // This variant exists only for the Debug impl InheritFile(File), } impl Command { pub fn new(_program: &OsStr) -> Command { Command { env: Default::default() } pub fn new(program: &OsStr) -> Command { Command { program: program.to_owned(), args: vec![program.to_owned()], env: Default::default(), cwd: None, stdin: None, stdout: None, stderr: None, } } pub fn arg(&mut self, _arg: &OsStr) {} pub fn arg(&mut self, arg: &OsStr) { self.args.push(arg.to_owned()); } pub fn env_mut(&mut self) -> &mut CommandEnv { &mut self.env } pub fn cwd(&mut self, _dir: &OsStr) {} pub fn cwd(&mut self, dir: &OsStr) { self.cwd = Some(dir.to_owned()); } pub fn stdin(&mut self, _stdin: Stdio) {} pub fn stdin(&mut self, stdin: Stdio) { self.stdin = Some(stdin); } pub fn stdout(&mut self, _stdout: Stdio) {} pub fn stdout(&mut self, stdout: Stdio) { self.stdout = Some(stdout); } pub fn stderr(&mut self, _stderr: Stdio) {} pub fn stderr(&mut self, stderr: Stdio) { self.stderr = Some(stderr); } pub fn get_program(&self) -> &OsStr { panic!(\"unsupported\") &self.program } pub fn get_args(&self) -> CommandArgs<'_> { CommandArgs { _p: PhantomData } let mut iter = self.args.iter(); iter.next(); CommandArgs { iter } } pub fn get_envs(&self) -> CommandEnvs<'_> {"} {"_id":"doc-en-rust-4886a7c872846bc5d070912d47291e9bbcef56857f40623677a51355cb251cc8","title":"","text":"} pub fn get_current_dir(&self) -> Option<&Path> { None self.cwd.as_ref().map(|cs| Path::new(cs)) } pub fn spawn("} {"_id":"doc-en-rust-7a9a6ad2edf0980dc653be7abaf45c4d8cfa4379f8055b9f81a0115ca1555330","title":"","text":"impl From for Stdio { fn from(_: io::Stdout) -> Stdio { // FIXME: This is wrong. // Instead, the Stdio we have here should be a unit struct. panic!(\"unsupported\") Stdio::ParentStdout } } impl From for Stdio { fn from(_: io::Stderr) -> Stdio { // FIXME: This is wrong. // Instead, the Stdio we have here should be a unit struct. panic!(\"unsupported\") Stdio::ParentStderr } } impl From for Stdio { fn from(_file: File) -> Stdio { // FIXME: This is wrong. // Instead, the Stdio we have here should be a unit struct. panic!(\"unsupported\") fn from(file: File) -> Stdio { Stdio::InheritFile(file) } } impl fmt::Debug for Command { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) // show all attributes fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if f.alternate() { let mut debug_command = f.debug_struct(\"Command\"); debug_command.field(\"program\", &self.program).field(\"args\", &self.args); if !self.env.is_unchanged() { debug_command.field(\"env\", &self.env); } if self.cwd.is_some() { debug_command.field(\"cwd\", &self.cwd); } if self.stdin.is_some() { debug_command.field(\"stdin\", &self.stdin); } if self.stdout.is_some() { debug_command.field(\"stdout\", &self.stdout); } if self.stderr.is_some() { debug_command.field(\"stderr\", &self.stderr); } debug_command.finish() } else { if let Some(ref cwd) = self.cwd { write!(f, \"cd {cwd:?} && \")?; } if self.env.does_clear() { write!(f, \"env -i \")?; // Altered env vars will be printed next, that should exactly work as expected. } else { // Removed env vars need the command to be wrapped in `env`. let mut any_removed = false; for (key, value_opt) in self.get_envs() { if value_opt.is_none() { if !any_removed { write!(f, \"env \")?; any_removed = true; } write!(f, \"-u {} \", key.to_string_lossy())?; } } } // Altered env vars can just be added in front of the program. for (key, value_opt) in self.get_envs() { if let Some(value) = value_opt { write!(f, \"{}={value:?} \", key.to_string_lossy())?; } } if self.program != self.args[0] { write!(f, \"[{:?}] \", self.program)?; } write!(f, \"{:?}\", self.args[0])?; for arg in &self.args[1..] { write!(f, \" {:?}\", arg)?; } Ok(()) } } }"} {"_id":"doc-en-rust-a6fe3bafd01fae3ac4a02ac22db5ddc8ff79ae3b4bd1184500a84cf7e10d66e5","title":"","text":"} pub struct CommandArgs<'a> { _p: PhantomData<&'a ()>, iter: crate::slice::Iter<'a, OsString>, } impl<'a> Iterator for CommandArgs<'a> { type Item = &'a OsStr; fn next(&mut self) -> Option<&'a OsStr> { None self.iter.next().map(|os| &**os) } fn size_hint(&self) -> (usize, Option) { (0, Some(0)) self.iter.size_hint() } } impl<'a> ExactSizeIterator for CommandArgs<'a> {} impl<'a> ExactSizeIterator for CommandArgs<'a> { fn len(&self) -> usize { self.iter.len() } fn is_empty(&self) -> bool { self.iter.is_empty() } } impl<'a> fmt::Debug for CommandArgs<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().finish() f.debug_list().entries(self.iter.clone()).finish() } }"} {"_id":"doc-en-rust-f30a4a313f877b3bbcc8c6bf08f0e468ccaa46514db69c115a3d06715268e1fc","title":"","text":"rustup toolchain install --profile minimal nightly-${TOOLCHAIN} # Sanity check to see if the nightly exists echo nightly-${TOOLCHAIN} > rust-toolchain echo \"=> Uninstalling all old nighlies\" echo \"=> Uninstalling all old nightlies\" for nightly in $(rustup toolchain list | grep nightly | grep -v $TOOLCHAIN | grep -v nightly-x86_64); do rustup toolchain uninstall $nightly done"} {"_id":"doc-en-rust-fa97511fc84407f97ba67ed8588da43662921b63736c56e7fbc97dd7e13f6fcb","title":"","text":"} fn check_expr(&mut self, cx: &Context, e: &ast::Expr) { // if the expression was produced by a macro expansion, if e.span.expn_info.is_some() { return } let id = match e.node { ast::ExprPath(..) | ast::ExprStruct(..) => { match cx.tcx.def_map.borrow().find(&e.id) {"} {"_id":"doc-en-rust-dca8d2db27537846c6ae5be342b781149db8fce8624a6eeb73d7b83dbf5bb14a","title":"","text":"#![crate_id=\"lint_stability#0.1\"] #![crate_type = \"lib\"] #![feature(macro_rules)] #![macro_escape] #[deprecated] pub fn deprecated() {} #[deprecated=\"text\"]"} {"_id":"doc-en-rust-38bf42335233800f879f3274aa31cd9a8737384d8af7759f58f240b6d6cb9c52","title":"","text":"pub struct FrozenTupleStruct(pub int); #[locked] pub struct LockedTupleStruct(pub int); #[macro_export] macro_rules! macro_test( () => (deprecated()); ) "} {"_id":"doc-en-rust-f28a2dcadd1808e007e7abcf609702f883dbdb6f28a884598351dc8f8154e1aa","title":"","text":"// aux-build:lint_stability.rs // aux-build:inherited_stability.rs #![feature(globs)] #![feature(globs, phase)] #![deny(unstable)] #![deny(deprecated)] #![deny(experimental)] #![allow(dead_code)] mod cross_crate { #[phase(plugin, link)] extern crate lint_stability; use self::lint_stability::*;"} {"_id":"doc-en-rust-171f1bafcd5632b45f992c8400344934181b61f0ceb93760bdc338bff4425ac4","title":"","text":"foo.method_locked_text(); foo.trait_locked_text(); let _ = DeprecatedStruct { i: 0 }; //~ ERROR use of deprecated item let _ = ExperimentalStruct { i: 0 }; //~ ERROR use of experimental item let _ = UnstableStruct { i: 0 }; //~ ERROR use of unstable item"} {"_id":"doc-en-rust-67d5d1fb8ecc6105712f9767d62104ce4bb42a1ddc5c2c05eed3c61b26b77152","title":"","text":"let _ = StableTupleStruct (1); let _ = FrozenTupleStruct (1); let _ = LockedTupleStruct (1); // At the moment, the following just checks that the stability // level of expanded code does not trigger the // lint. Eventually, we will want to lint the contents of the // macro in the module *defining* it. Also, stability levels // on macros themselves are not yet linted. macro_test!(); } fn test_method_param(foo: F) {"} {"_id":"doc-en-rust-19132abfb27af4f49ca30d8e2d0e18e3a621078a8576851670f89aa7943f27a1","title":"","text":"**Source:** https://github.com/rust-lang/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs[config.rs] The <<_installation,Installation>> section contains details on configuration for some of the editors. The <> section contains details on configuration for some of the editors. In general `rust-analyzer` is configured via LSP messages, which means that it's up to the editor to decide on the exact format and location of configuration files. Some clients, such as <> or <> provide `rust-analyzer` specific configuration UIs. Others may require you to know a bit more about the interaction with `rust-analyzer`."} {"_id":"doc-en-rust-3a13f4e82989fa9bc0f5dc937c7ad0d6be041b16be175447b8d6cee61b0df1da","title":"","text":"crate_name: crate_name.to_string(), deriving_hash_type_parameter: sess.features.borrow().default_type_params, enable_quotes: sess.features.borrow().quote, recursion_limit: sess.recursion_limit.get(), }; let ret = syntax::ext::expand::expand_crate(&sess.parse_sess, cfg,"} {"_id":"doc-en-rust-20ae223fc3ca67f778b888c282276cf3de0561a1a96031af51308dd11dbd3976","title":"","text":"pub exported_macros: Vec>, pub syntax_env: SyntaxEnv, pub recursion_count: uint, } impl<'a> ExtCtxt<'a> {"} {"_id":"doc-en-rust-8ac2c8d4194f419b0a0b8d3e13a5fb1e49a45ead5ab684d7b8bb1995aee14a77","title":"","text":"trace_mac: false, exported_macros: Vec::new(), syntax_env: env, recursion_count: 0, } }"} {"_id":"doc-en-rust-b317f7a61098e70241000964679799ee3dccca0bd7f77c30d8b794bfb270e3ef","title":"","text":"return v; } pub fn bt_push(&mut self, ei: ExpnInfo) { self.recursion_count += 1; if self.recursion_count > self.ecfg.recursion_limit { self.span_fatal(ei.call_site, format!(\"Recursion limit reached while expanding the macro `{}`\", ei.callee.name).as_slice()); } let mut call_site = ei.call_site; call_site.expn_id = self.backtrace; self.backtrace = self.codemap().record_expansion(ExpnInfo {"} {"_id":"doc-en-rust-ff45fb22407d42777a3f26a160c3a214a7e1f0c1a40ef7fcf6b3c84c9fe4b384","title":"","text":"match self.backtrace { NO_EXPANSION => self.bug(\"tried to pop without a push\"), expn_id => { self.recursion_count -= 1; self.backtrace = self.codemap().with_expn_info(expn_id, |expn_info| { expn_info.map_or(NO_EXPANSION, |ei| ei.call_site.expn_id) });"} {"_id":"doc-en-rust-cae5a9154d6f2e5beecfe96ba0759d6033b9eca79dfe642b9cd1abb1385a9461","title":"","text":"pub crate_name: String, pub deriving_hash_type_parameter: bool, pub enable_quotes: bool, pub recursion_limit: uint, } impl ExpansionConfig {"} {"_id":"doc-en-rust-d7a48f8a4fff0307c0223a7dcc30775d4f56901a9f358ca0eb030d07c815a3ac","title":"","text":"crate_name: crate_name, deriving_hash_type_parameter: false, enable_quotes: false, recursion_limit: 64, } } }"} {"_id":"doc-en-rust-c288910a75efd19f16028b5626cad998d02efedb3725ee6efd7485a67d21dabe","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(macro_rules)] macro_rules! recursive( () => ( recursive!() //~ ERROR Recursion limit reached while expanding the macro `recursive` ) ) fn main() { recursive!() } "} {"_id":"doc-en-rust-5e2a2f302cafae82b8dd49aaba7eceb7f0b435a6408ab96363275cea19413784","title":"","text":"# } fn compute_area(shape: &Shape) -> f64 { match *shape { Circle(_, radius) => 2.0 * std::f64::consts::PI * radius * radius, Circle(_, radius) => std::f64::consts::PI * radius * radius, Rectangle(_, ref size) => size.w * size.h } }"} {"_id":"doc-en-rust-2af82054ea4aaa75cebf9c5651d918e9c5b8ab0856ec091de4879c5937bcf421","title":"","text":"self.span_err(ty.span, \"`virtual` structs have been removed from the language\"); } self.parse_where_clause(&mut generics); // There is a special case worth noting here, as reported in issue #17904. // If we are parsing a tuple struct it is the case that the where clause // should follow the field list. Like so: // // struct Foo(T) where T: Copy; // // If we are parsing a normal record-style struct it is the case // that the where clause comes before the body, and after the generics. // So if we look ahead and see a brace or a where-clause we begin // parsing a record style struct. // // Otherwise if we look ahead and see a paren we parse a tuple-style // struct. let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) { self.parse_where_clause(&mut generics); if self.eat(&token::Semi) { // If we see a: `struct Foo where T: Copy;` style decl. (Vec::new(), Some(ast::DUMMY_NODE_ID)) } else { // If we see: `struct Foo where T: Copy { ... }` (self.parse_record_struct_body(&class_name), None) } // No `where` so: `struct Foo;` } else if self.eat(&token::Semi) { (Vec::new(), Some(ast::DUMMY_NODE_ID)) // Record-style struct definition } else if self.token == token::OpenDelim(token::Brace) { let fields = self.parse_record_struct_body(&class_name); (fields, None) // Tuple-style struct definition with optional where-clause. } else { let fields = self.parse_tuple_struct_body(&class_name, &mut generics); (fields, Some(ast::DUMMY_NODE_ID)) }; let mut fields: Vec; let is_tuple_like; (class_name, ItemStruct(P(ast::StructDef { fields: fields, ctor_id: ctor_id, }), generics), None) } pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec { let mut fields = Vec::new(); if self.eat(&token::OpenDelim(token::Brace)) { // It's a record-like struct. is_tuple_like = false; fields = Vec::new(); while self.token != token::CloseDelim(token::Brace) { fields.push(self.parse_struct_decl_field(true)); } if fields.len() == 0 { self.fatal(format!(\"unit-like struct definition should be written as `struct {};`\", token::get_ident(class_name))[]); written as `struct {};`\", token::get_ident(class_name.clone()))[]); } self.bump(); } else if self.check(&token::OpenDelim(token::Paren)) { // It's a tuple-like struct. is_tuple_like = true; fields = self.parse_unspanned_seq( } else { let token_str = self.this_token_to_string(); self.fatal(format!(\"expected `where`, or `{}` after struct name, found `{}`\", \"{\", token_str)[]); } fields } pub fn parse_tuple_struct_body(&mut self, class_name: &ast::Ident, generics: &mut ast::Generics) -> Vec { // This is the case where we find `struct Foo(T) where T: Copy;` if self.check(&token::OpenDelim(token::Paren)) { let fields = self.parse_unspanned_seq( &token::OpenDelim(token::Paren), &token::CloseDelim(token::Paren), seq_sep_trailing_allowed(token::Comma), |p| { let attrs = p.parse_outer_attributes(); let lo = p.span.lo; let struct_field_ = ast::StructField_ { kind: UnnamedField(p.parse_visibility()), id: ast::DUMMY_NODE_ID, ty: p.parse_ty_sum(), attrs: attrs, }; spanned(lo, p.span.hi, struct_field_) }); let attrs = p.parse_outer_attributes(); let lo = p.span.lo; let struct_field_ = ast::StructField_ { kind: UnnamedField(p.parse_visibility()), id: ast::DUMMY_NODE_ID, ty: p.parse_ty_sum(), attrs: attrs, }; spanned(lo, p.span.hi, struct_field_) }); if fields.len() == 0 { self.fatal(format!(\"unit-like struct definition should be written as `struct {};`\", token::get_ident(class_name))[]); written as `struct {};`\", token::get_ident(class_name.clone()))[]); } self.parse_where_clause(generics); self.expect(&token::Semi); } else if self.eat(&token::Semi) { // It's a unit-like struct. is_tuple_like = true; fields = Vec::new(); fields // This is the case where we just see struct Foo where T: Copy; } else if self.token.is_keyword(keywords::Where) { self.parse_where_clause(generics); self.expect(&token::Semi); Vec::new() // This case is where we see: `struct Foo;` } else { let token_str = self.this_token_to_string(); self.fatal(format!(\"expected `{}`, `(`, or `;` after struct name, found `{}`\", \"{\", token_str)[]) self.fatal(format!(\"expected `where`, `{}`, `(`, or `;` after struct name, found `{}`\", \"{\", token_str)[]); } let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug. let new_id = ast::DUMMY_NODE_ID; (class_name, ItemStruct(P(ast::StructDef { fields: fields, ctor_id: if is_tuple_like { Some(new_id) } else { None }, }), generics), None) } /// Parse a structure field declaration"} {"_id":"doc-en-rust-6ffb42fc68529e5c23e301ceace4ace6a4994baadace1be2eca5f88985112523","title":"","text":"span: codemap::Span) -> IoResult<()> { try!(self.print_ident(ident)); try!(self.print_generics(generics)); try!(self.print_where_clause(generics)); if ast_util::struct_def_is_tuple_like(struct_def) { if !struct_def.fields.is_empty() { try!(self.popen());"} {"_id":"doc-en-rust-d2e5602c904006026eb09df521724771b6e52e78751fddc8d025debe0bf85572","title":"","text":")); try!(self.pclose()); } try!(self.print_where_clause(generics)); try!(word(&mut self.s, \";\")); try!(self.end()); self.end() // close the outer-box } else { try!(self.print_where_clause(generics)); try!(self.nbsp()); try!(self.bopen()); try!(self.hardbreak_if_not_bol());"} {"_id":"doc-en-rust-c01f35b083599cb57ea69934de8af8a985a0246c9680bd10b6812c08f4559765","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct Baz where U: Eq(U); //This is parsed as the new Fn* style parenthesis syntax. struct Baz where U: Eq(U) -> R; // Notice this parses as well. struct Baz(U) where U: Eq; // This rightfully signals no error as well. struct Foo where T: Copy, (T); //~ ERROR unexpected token in `where` clause struct Bar { x: T } where T: Copy //~ ERROR expected item, found `where` fn main() {} "} {"_id":"doc-en-rust-a659fe91291ede3e314836d4906b7391908fad82e0cf84a96d8a1c8367c9e664","title":"","text":"// Test syntax checks for `type` keyword. struct S1 for type; //~ ERROR expected `{`, `(`, or `;` after struct name, found `for` struct S1 for type; //~ ERROR expected `where`, `{`, `(`, or `;` after struct name, found `for` pub fn main() { }"} {"_id":"doc-en-rust-922d7729d23b2327a3b021c45866989e6c017119de00e86a16e8651ffc9c66f7","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct Foo where T: Copy; struct Bar(T) where T: Copy; struct Bleh(T, U) where T: Copy, U: Sized; struct Baz where T: Copy { field: T } fn main() {} "} {"_id":"doc-en-rust-ad621a0630ceaf1e95da71b210b68bdb618a137637be42ba614edbdd5beb66f7","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. impl Undefined {} //~^ ERROR use of undeclared type name `Undefined` fn main() {} "} {"_id":"doc-en-rust-786dcf8e0c9e6b32959e7235f7183ccd5aa32980e13fccaeb9741dd759f451ed","title":"","text":"AssignmentLhsSized, // L = X implies that L is Sized StructInitializerSized, // S { ... } must be Sized VariableType(ast::NodeId), // Type of each variable must be Sized ReturnType, // Return type must be Sized RepeatVec, // [T,..n] --> T must be Copy // Captures of variable the given id by a closure (span is the"} {"_id":"doc-en-rust-4fdfa15654a64cfcadaa9b33a890fe0405ce5126501d704aef598646b728f704","title":"","text":"// Remember return type so that regionck can access it later. let fn_sig_tys: Vec = arg_tys.iter() .chain([ret_ty].iter()) .map(|&ty| ty) .collect(); arg_tys.iter().chain([ret_ty].iter()).map(|&ty| ty).collect(); debug!(\"fn-sig-map: fn_id={} fn_sig_tys={}\", fn_id, fn_sig_tys.repr(tcx)); inherited.fn_sig_map .borrow_mut() .insert(fn_id, fn_sig_tys); inherited.fn_sig_map.borrow_mut().insert(fn_id, fn_sig_tys); { let mut visit = GatherLocalsVisitor { fcx: &fcx, };"} {"_id":"doc-en-rust-8ebbd18b7595738d2bf5bf1d6e8f9a4fff225678dc8cd0ecc0328191edce81f6","title":"","text":"visit.visit_block(body); } fcx.require_type_is_sized(ret_ty, decl.output.span, traits::ReturnType); check_block_with_expected(&fcx, body, ExpectHasType(ret_ty));"} {"_id":"doc-en-rust-a497242f111f376b5d82038348f459aebf21277bb68683b74471fbaaff1e129a","title":"","text":"traits::RepeatVec => { tcx.sess.span_note( obligation.cause.span, format!( \"the `Copy` trait is required because the repeated element will be copied\").as_slice()); \"the `Copy` trait is required because the repeated element will be copied\"); } traits::VariableType(_) => { tcx.sess.span_note( obligation.cause.span, \"all local variables must have a statically known size\"); } traits::ReturnType => { tcx.sess.span_note( obligation.cause.span, \"the return type of a function must have a statically known size\"); } traits::AssignmentLhsSized => { tcx.sess.span_note( obligation.cause.span,"} {"_id":"doc-en-rust-dac159af613437add442839fa2b649c5f8c5e7e713c2c024ecad252a9d0dc4c1","title":"","text":"#![no_std] #![feature(lang_items)] #[lang=\"sized\"] pub trait Sized for Sized? {} #[lang=\"fail\"] fn fail(_: &(&'static str, &'static str, uint)) -> ! { loop {} }"} {"_id":"doc-en-rust-4b6e0bebba756f77eb9fc09ba44f473a365ac2166f3aa2d411d5578bfe168024","title":"","text":"C([Box]), } fn c(c:char) -> A { B(c) //~ ERROR cannot move a value of type A: the size of A cannot be statically determined fn c(c:char) { B(c); //~^ ERROR cannot move a value of type A: the size of A cannot be statically determined } pub fn main() {}"} {"_id":"doc-en-rust-45922678c6cd755ce6ecfaa0e30bc4c92cbbe26c66d7b2eec5bc0a0213c1a5c5","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait AbstractRenderer {} fn _create_render(_: &()) -> AbstractRenderer //~^ ERROR: the trait `core::kinds::Sized` is not implemented { match 0u { _ => unimplemented!() } } fn main() { } "} {"_id":"doc-en-rust-41396f09f31ee4ad3b6759a18710504407a874f360bd9cb5cf912304b2bb9f20","title":"","text":"r: A+'static } fn new_struct(r: A+'static) -> Struct { fn new_struct(r: A+'static) -> Struct { //~^ ERROR the trait `core::kinds::Sized` is not implemented //~^ ERROR the trait `core::kinds::Sized` is not implemented Struct { r: r } //~^ ERROR the trait `core::kinds::Sized` is not implemented"} {"_id":"doc-en-rust-c6d37609080ed01aa382e18532048947735ab7c069f088308a4746692743ad50","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(globs)] #![feature(globs, lang_items)] #![no_std] // makes debugging this test *a lot* easier (during resolve) #[lang = \"sized\"] pub trait Sized for Sized? {} // Test to make sure that private items imported through globs remain private // when they're used."} {"_id":"doc-en-rust-d82663572df538e91ca980c6f04f2038f2784a99b3856e925a9d798ef81db781","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(lang_items)] #![no_std] #[lang=\"sized\"] pub trait Sized for Sized? {} // error-pattern:requires `start` lang_item fn main() {}"} {"_id":"doc-en-rust-69660b82d833da962773a9a699579d327f34831cf8a71fba5d46a974b45ee7c5","title":"","text":"#[inline] unsafe fn into_ascii_nocheck(self) -> Vec { let v: Vec = mem::transmute(self); v.into_ascii_nocheck() self.into_bytes().into_ascii_nocheck() } }"} {"_id":"doc-en-rust-47fa2209c66d571d58ac52aaddf708f32354d91ecde0eab556e6e443b87e1801","title":"","text":"#[inline] unsafe fn into_ascii_nocheck(self) -> Vec { mem::transmute(self) let v = Vec::from_raw_parts(self.len(), self.capacity(), mem::transmute(self.as_ptr())); // We forget `self` to avoid freeing it at the end of the scope // Otherwise, the returned `Vec` would point to freed memory mem::forget(self); v } }"} {"_id":"doc-en-rust-b170396564709477e0384f80b6ffac920af2dbd97b6019b987565a7c60975b40","title":"","text":"impl IntoBytes for Vec { fn into_bytes(self) -> Vec { unsafe { mem::transmute(self) } unsafe { let v = Vec::from_raw_parts(self.len(), self.capacity(), mem::transmute(self.as_ptr())); // We forget `self` to avoid freeing it at the end of the scope // Otherwise, the returned `Vec` would point to freed memory mem::forget(self); v } } }"} {"_id":"doc-en-rust-713cf682d473c55416addf4a25f6b43219978f5443c57292a0008d399214a9db","title":"","text":"let const_did = tcx.def_map.borrow().get_copy(&pat.id).def_id(); let const_pty = ty::lookup_item_type(tcx, const_did); fcx.write_ty(pat.id, const_pty.ty); demand::eqtype(fcx, pat.span, expected, const_pty.ty); demand::suptype(fcx, pat.span, expected, const_pty.ty); } ast::PatIdent(bm, ref path, ref sub) if pat_is_binding(&tcx.def_map, pat) => { let typ = fcx.local_ty(pat.span, pat.id);"} {"_id":"doc-en-rust-e25ce2f84f88c079057c38fee1f03493d65325b9820361792f887a7332fc1b56","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. const X: &'static str = \"12345\"; fn test(s: String) -> bool { match s.as_slice() { X => true, _ => false } } fn main() { assert!(test(\"12345\".to_string())); } "} {"_id":"doc-en-rust-1219ea0f09812c049c41268f600f0fceda2851fb602e3dc3a9d97f9fe8bf0c9f","title":"","text":"use {uint, u8, u16, u32, u64}; use {f32, f64}; use clone::Clone; use cmp::{PartialEq, PartialOrd}; use cmp::{Ord, PartialEq, PartialOrd}; use kinds::Copy; use mem::size_of; use ops::{Add, Sub, Mul, Div, Rem, Neg};"} {"_id":"doc-en-rust-19c01a8e5197c9036e765b10f47271a27c49115ef3045f4cb597bfd899de8de6","title":"","text":"/// A primitive signed or unsigned integer equipped with various bitwise /// operators, bit counting methods, and endian conversion functions. pub trait Int: Primitive + Ord + CheckedAdd + CheckedSub + CheckedMul"} {"_id":"doc-en-rust-6f97680750bf67eb00f18a5df6ff0ea74ce080f64bd0207e2167d714bc0ace37","title":"","text":"/// ``` #[macro_export] macro_rules! unreachable( () => (panic!(\"internal error: entered unreachable code\")) () => ({ panic!(\"internal error: entered unreachable code\") }); ($msg:expr) => ({ unreachable!(\"{}\", $msg) }); ($fmt:expr, $($arg:tt)*) => ({ panic!(concat!(\"internal error: entered unreachable code: \", $fmt), $($arg)*) }); ) /// A standardised placeholder for marking unfinished code. It panics with the"} {"_id":"doc-en-rust-83feb6a6979a9cf0cdca92c81d10b25502618683a67a1b629e6e330722013eab","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:internal error: entered unreachable code: 6 is not prime fn main() { unreachable!(\"{} is not {}\", 6u32, \"prime\"); } "} {"_id":"doc-en-rust-0f2bf779d733788feb2b1df03b0c7a371b162b1ae32b062f151edc764319cc2f","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:internal error: entered unreachable code fn main() { unreachable!() } "} {"_id":"doc-en-rust-d6774eab12f7a46676a70ed1556fcbf2b9b4a24067052b11de00394c67f6c2f3","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:internal error: entered unreachable code: uhoh fn main() { unreachable!(\"uhoh\") } "} {"_id":"doc-en-rust-913ef8690369dcd0be20e4bccce72831286f7bfa74d327d8b9658b608f9aae27","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:internal error: entered unreachable code fn main() { unreachable!() } "} {"_id":"doc-en-rust-1d2f25a34c4d865b1d9eed7d4ff667a8324effc948f10bdb491886539247a2e9","title":"","text":"/// context it's calculated within. This is used by the `type_id` intrinsic. pub fn hash_crate_independent(tcx: &ctxt, ty: Ty, svh: &Svh) -> u64 { let mut state = sip::SipState::new(); macro_rules! byte( ($b:expr) => { ($b as u8).hash(&mut state) } ); macro_rules! hash( ($e:expr) => { $e.hash(&mut state) } ); let region = |_state: &mut sip::SipState, r: Region| { match r { ReStatic => {} ReEmpty | ReEarlyBound(..) | ReLateBound(..) | ReFree(..) | ReScope(..) | ReInfer(..) => { tcx.sess.bug(\"non-static region found when hashing a type\") helper(tcx, ty, svh, &mut state); return state.result(); fn helper(tcx: &ctxt, ty: Ty, svh: &Svh, state: &mut sip::SipState) { macro_rules! byte( ($b:expr) => { ($b as u8).hash(state) } ); macro_rules! hash( ($e:expr) => { $e.hash(state) } ); let region = |state: &mut sip::SipState, r: Region| { match r { ReStatic => {} ReLateBound(db, BrAnon(i)) => { db.hash(state); i.hash(state); } ReEmpty | ReEarlyBound(..) | ReLateBound(..) | ReFree(..) | ReScope(..) | ReInfer(..) => { tcx.sess.bug(\"unexpected region found when hashing a type\") } } } }; let did = |state: &mut sip::SipState, did: DefId| { let h = if ast_util::is_local(did) { svh.clone() } else { tcx.sess.cstore.get_crate_hash(did.krate) }; h.as_str().hash(state); did.node.hash(state); }; let mt = |state: &mut sip::SipState, mt: mt| { mt.mutbl.hash(state); }; ty::walk_ty(ty, |ty| { match ty.sty { ty_bool => byte!(2), ty_char => byte!(3), ty_int(i) => { byte!(4); hash!(i); } ty_uint(u) => { byte!(5); hash!(u); } ty_float(f) => { byte!(6); hash!(f); } ty_str => { byte!(7); } ty_enum(d, _) => { byte!(8); did(&mut state, d); } ty_uniq(_) => { byte!(9); } ty_vec(_, Some(n)) => { byte!(10); n.hash(&mut state); } ty_vec(_, None) => { byte!(11); } ty_ptr(m) => { byte!(12); mt(&mut state, m); } ty_rptr(r, m) => { byte!(13); region(&mut state, r); mt(&mut state, m); } ty_bare_fn(ref b) => { byte!(14); hash!(b.unsafety); hash!(b.abi); let did = |state: &mut sip::SipState, did: DefId| { let h = if ast_util::is_local(did) { svh.clone() } else { tcx.sess.cstore.get_crate_hash(did.krate) }; h.as_str().hash(state); did.node.hash(state); }; let mt = |state: &mut sip::SipState, mt: mt| { mt.mutbl.hash(state); }; let fn_sig = |state: &mut sip::SipState, sig: &FnSig| { let sig = anonymize_late_bound_regions(tcx, sig); for a in sig.inputs.iter() { helper(tcx, *a, svh, state); } if let ty::FnConverging(output) = sig.output { helper(tcx, output, svh, state); } ty_closure(ref c) => { byte!(15); hash!(c.unsafety); hash!(c.onceness); hash!(c.bounds); match c.store { UniqTraitStore => byte!(0), RegionTraitStore(r, m) => { byte!(1) region(&mut state, r); assert_eq!(m, ast::MutMutable); }; maybe_walk_ty(ty, |ty| { match ty.sty { ty_bool => byte!(2), ty_char => byte!(3), ty_int(i) => { byte!(4); hash!(i); } ty_uint(u) => { byte!(5); hash!(u); } ty_float(f) => { byte!(6); hash!(f); } ty_str => { byte!(7); } ty_enum(d, _) => { byte!(8); did(state, d); } ty_uniq(_) => { byte!(9); } ty_vec(_, Some(n)) => { byte!(10); n.hash(state); } ty_vec(_, None) => { byte!(11); } ty_ptr(m) => { byte!(12); mt(state, m); } ty_rptr(r, m) => { byte!(13); region(state, r); mt(state, m); } ty_bare_fn(ref b) => { byte!(14); hash!(b.unsafety); hash!(b.abi); fn_sig(state, &b.sig); return false; } ty_closure(ref c) => { byte!(15); hash!(c.unsafety); hash!(c.onceness); hash!(c.bounds); match c.store { UniqTraitStore => byte!(0), RegionTraitStore(r, m) => { byte!(1); region(state, r); assert_eq!(m, ast::MutMutable); } } fn_sig(state, &c.sig); return false; } } ty_trait(box TyTrait { ref principal, bounds }) => { byte!(17); did(&mut state, principal.def_id); hash!(bounds); } ty_struct(d, _) => { byte!(18); did(&mut state, d); } ty_tup(ref inner) => { byte!(19); hash!(inner.len()); } ty_param(p) => { byte!(20); hash!(p.idx); did(&mut state, p.def_id); } ty_open(_) => byte!(22), ty_infer(_) => unreachable!(), ty_err => byte!(23), ty_unboxed_closure(d, r, _) => { byte!(24); did(&mut state, d); region(&mut state, r); } } }); ty_trait(box TyTrait { ref principal, bounds }) => { byte!(17); did(state, principal.def_id); hash!(bounds); let principal = anonymize_late_bound_regions(tcx, principal); for subty in principal.substs.types.iter() { helper(tcx, *subty, svh, state); } state.result() return false; } ty_struct(d, _) => { byte!(18); did(state, d); } ty_tup(ref inner) => { byte!(19); hash!(inner.len()); } ty_param(p) => { byte!(20); hash!(p.idx); did(state, p.def_id); } ty_open(_) => byte!(22), ty_infer(_) => unreachable!(), ty_err => byte!(23), ty_unboxed_closure(d, r, _) => { byte!(24); did(state, d); region(state, r); } } true }); } } impl Variance {"} {"_id":"doc-en-rust-1476952c0e31f4d798aba2a64caf6b80cd9dc9449c5bbee1b353525a93565783","title":"","text":"replace_late_bound_regions(tcx, value, |_, _| ty::ReStatic).0 } /// Rewrite any late-bound regions so that they are anonymous. Region numbers are /// assigned starting at 1 and increasing monotonically in the order traversed /// by the fold operation. /// /// The chief purpose of this function is to canonicalize regions so that two /// `FnSig`s or `TraitRef`s which are equivalent up to region naming will become /// structurally identical. For example, `for<'a, 'b> fn(&'a int, &'b int)` and /// `for<'a, 'b> fn(&'b int, &'a int)` will become identical after anonymization. pub fn anonymize_late_bound_regions<'tcx, HR>(tcx: &ctxt<'tcx>, sig: &HR) -> HR where HR: HigherRankedFoldable<'tcx> { let mut counter = 0; replace_late_bound_regions(tcx, sig, |_, db| { counter += 1; ReLateBound(db, BrAnon(counter)) }).0 } /// Replaces the late-bound-regions in `value` that are bound by `value`. pub fn replace_late_bound_regions<'tcx, HR, F>( tcx: &ty::ctxt<'tcx>,"} {"_id":"doc-en-rust-8bf125453043bb6024ea7a1b0717f03edbaf63c1056c55d119d7cb767c6c80de","title":"","text":"fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> { if !t.bound_lifetimes.is_empty() { try!(word(&mut self.s, \"for<\")); let mut comma = false; for lifetime_def in t.bound_lifetimes.iter() { if comma { try!(self.word_space(\",\")) } try!(self.print_lifetime_def(lifetime_def)); comma = true; } try!(word(&mut self.s, \">\")); }"} {"_id":"doc-en-rust-0f1969ccea2bc6f79dacef9394c7cb524472df090530ce94f76790a27d768461","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that type IDs correctly account for higher-rank lifetimes // Also acts as a regression test for an ICE (issue #19791) #![feature(unboxed_closures)] use std::intrinsics::TypeId; fn main() { // Bare fns { let a = TypeId::of::(); let b = TypeId::of:: fn(&'static int, &'a int)>(); let c = TypeId::of:: fn(&'a int, &'b int)>(); let d = TypeId::of:: fn(&'b int, &'a int)>(); assert!(a != b); assert!(a != c); assert!(a != d); assert!(b != c); assert!(b != d); assert_eq!(c, d); // Make sure De Bruijn indices are handled correctly let e = TypeId::of:: fn(fn(&'a int) -> &'a int)>(); let f = TypeId::of:: fn(&'a int) -> &'a int)>(); assert!(e != f); } // Stack closures { let a = TypeId::of::<|&'static int, &'static int|>(); let b = TypeId::of:: |&'static int, &'a int|>(); let c = TypeId::of:: |&'a int, &'b int|>(); let d = TypeId::of:: |&'b int, &'a int|>(); assert!(a != b); assert!(a != c); assert!(a != d); assert!(b != c); assert!(b != d); assert_eq!(c, d); // Make sure De Bruijn indices are handled correctly let e = TypeId::of:: |(|&'a int| -> &'a int)|>(); let f = TypeId::of::<|for<'a> |&'a int| -> &'a int|>(); assert!(e != f); } // Boxed unboxed closures { let a = TypeId::of::>(); let b = TypeId::of:: Fn(&'static int, &'a int)>>(); let c = TypeId::of:: Fn(&'a int, &'b int)>>(); let d = TypeId::of:: Fn(&'b int, &'a int)>>(); assert!(a != b); assert!(a != c); assert!(a != d); assert!(b != c); assert!(b != d); assert_eq!(c, d); // Make sure De Bruijn indices are handled correctly let e = TypeId::of:: Fn(Box &'a int>)>>(); let f = TypeId::of:: Fn(&'a int) -> &'a int>)>>(); assert!(e != f); } // Raw unboxed closures // Note that every unboxed closure has its own anonymous type, // so no two IDs should equal each other, even when compatible { let a = id(|&: _: &int, _: &int| {}); let b = id(|&: _: &int, _: &int| {}); assert!(a != b); } fn id(_: T) -> TypeId { TypeId::of::() } } "} {"_id":"doc-en-rust-3c70c66683ce3fe5106a5733f90e5cbbf52aefa73655ed4cd137b11264f1188b","title":"","text":"* [Iterators](iterators.md) * [Generics](generics.md) * [Traits](traits.md) * [Threads](threads.md) * [Concurrency](concurrency.md) * [Error Handling](error-handling.md) * [Documentation](documentation.md) * [III: Advanced Topics](advanced.md)"} {"_id":"doc-en-rust-710f60b94f246edd8d1926b4bd6b40261fd3c12211008028d7bde02d2c8b9226","title":"","text":" % Concurrency Concurrency and parallelism are incredibly important topics in computer science, and are also a hot topic in industry today. Computers are gaining more and more cores, yet many programmers aren't prepared to fully utilize them. Rust's memory safety features also apply to its concurrency story too. Even concurrent Rust programs must be memory safe, having no data races. Rust's type system is up to the task, and gives you powerful ways to reason about concurrent code at compile time. Before we talk about the concurrency features that come with Rust, it's important to understand something: Rust is low-level enough that all of this is provided by the standard library, not by the language. This means that if you don't like some aspect of the way Rust handles concurrency, you can implement an alternative way of doing things. [mio](https://github.com/carllerche/mio) is a real-world example of this principle in action. ## Background: `Send` and `Sync` Concurrency is difficult to reason about. In Rust, we have a strong, static type system to help us reason about our code. As such, Rust gives us two traits to help us make sense of code that can possibly be concurrent. ### `Send` The first trait we're going to talk about is [`Send`](../std/marker/trait.Send.html). When a type `T` implements `Send`, it indicates to the compiler that something of this type is able to have ownership transferred safely between threads. This is important to enforce certain restrictions. For example, if we have a channel connecting two threads, we would want to be able to send some data down the channel and to the other thread. Therefore, we'd ensure that `Send` was implemented for that type. In the opposite way, if we were wrapping a library with FFI that isn't threadsafe, we wouldn't want to implement `Send`, and so the compiler will help us enforce that it can't leave the current thread. ### `Sync` The second of these two trait is called [`Sync`](../std/marker/trait.Sync.html). When a type `T` implements `Sync`, it indicates to the compiler that something of this type has no possibility of introducing memory unsafety when used from multiple threads concurrently. For example, sharing immutable data with an atomic reference count is threadsafe. Rust provides a type like this, `Arc`, and it implements `Sync`, so that it could be safely shared between threads. These two traits allow you to use the type system to make strong guarantees about the properties of your code under concurrency. Before we demonstrate why, we need to learn how to create a concurrent Rust program in the first place! ## Threads Rust's standard library provides a library for 'threads', which allow you to run Rust code in parallel. Here's a basic example of using `Thread`: ``` use std::thread::Thread; fn main() { Thread::scoped(|| { println!(\"Hello from a thread!\"); }); } ``` The `Thread::scoped()` method accepts a closure, which is executed in a new thread. It's called `scoped` because this thread returns a join guard: ``` use std::thread::Thread; fn main() { let guard = Thread::scoped(|| { println!(\"Hello from a thread!\"); }); // guard goes out of scope here } ``` When `guard` goes out of scope, it will block execution until the thread is finished. If we didn't want this behaviour, we could use `Thread::spawn()`: ``` use std::thread::Thread; use std::old_io::timer; use std::time::Duration; fn main() { Thread::spawn(|| { println!(\"Hello from a thread!\"); }); timer::sleep(Duration::milliseconds(50)); } ``` Or call `.detach()`: ``` use std::thread::Thread; use std::old_io::timer; use std::time::Duration; fn main() { let guard = Thread::scoped(|| { println!(\"Hello from a thread!\"); }); guard.detach(); timer::sleep(Duration::milliseconds(50)); } ``` We need to `sleep` here because when `main()` ends, it kills all of the running threads. [`scoped`](std/thread/struct.Builder.html#method.scoped) has an interesting type signature: ```text fn scoped<'a, T, F>(self, f: F) -> JoinGuard<'a, T> where T: Send + 'a, F: FnOnce() -> T, F: Send + 'a ``` Specifically, `F`, the closure that we pass to execute in the new thread. It has two restrictions: It must be a `FnOnce` from `()` to `T`. Using `FnOnce` allows the closure to take ownership of any data it mentions from the parent thread. The other restriction is that `F` must be `Send`. We aren't allowed to transfer this ownership unless the type thinks that's okay. Many languages have the ability to execute threads, but it's wildly unsafe. There are entire books about how to prevent errors that occur from shared mutable state. Rust helps out with its type system here as well, by preventing data races at compile time. Let's talk about how you actually share things between threads. ## Safe Shared Mutable State Due to Rust's type system, we have a concept that sounds like a lie: \"safe shared mutable state.\" Many programmers agree that shared mutable state is very, very bad. Someone once said this: > Shared mutable state is the root of all evil. Most languages attempt to deal > with this problem through the 'mutable' part, but Rust deals with it by > solving the 'shared' part. The same [ownership system](ownership.html) that helps prevent using pointers incorrectly also helps rule out data races, one of the worst kinds of concurrency bugs. As an example, here is a Rust program that would have a data race in many languages. It will not compile: ```ignore use std::thread::Thread; use std::old_io::timer; use std::time::Duration; fn main() { let mut data = vec![1u32, 2, 3]; for i in 0 .. 2 { Thread::spawn(move || { data[i] += 1; }); } timer::sleep(Duration::milliseconds(50)); } ``` This gives us an error: ```text 12:17 error: capture of moved value: `data` data[i] += 1; ^~~~ ``` In this case, we know that our code _should_ be safe, but Rust isn't sure. And it's actually not safe: if we had a reference to `data` in each thread, and the thread takes ownership of the reference, we have three owners! That's bad. We can fix this by using the `Arc` type, which is an atomic reference counted pointer. The 'atomic' part means that it's safe to share across threads. `Arc` assumes one more property about its contents to ensure that it is safe to share across threads: it assumes its contents are `Sync`. But in our case, we want to be able to mutate the value. We need a type that can ensure only one person at a time can mutate what's inside. For that, we can use the `Mutex` type. Here's the second version of our code. It still doesn't work, but for a different reason: ```ignore use std::thread::Thread; use std::old_io::timer; use std::time::Duration; use std::sync::Mutex; fn main() { let mut data = Mutex::new(vec![1u32, 2, 3]); for i in 0 .. 2 { let data = data.lock().unwrap(); Thread::spawn(move || { data[i] += 1; }); } timer::sleep(Duration::milliseconds(50)); } ``` Here's the error: ```text :11:9: 11:22 error: the trait `core::marker::Send` is not implemented for the type `std::sync::mutex::MutexGuard<'_, collections::vec::Vec>` [E0277] :11 Thread::spawn(move || { ^~~~~~~~~~~~~ :11:9: 11:22 note: `std::sync::mutex::MutexGuard<'_, collections::vec::Vec>` cannot be sent between threads safely :11 Thread::spawn(move || { ^~~~~~~~~~~~~ ``` You see, [`Mutex`](std/sync/struct.Mutex.html) has a [`lock`](http://doc.rust-lang.org/nightly/std/sync/struct.Mutex.html#method.lock) method which has this signature: ```ignore fn lock(&self) -> LockResult> ``` If we [look at the code for MutexGuard](https://github.com/rust-lang/rust/blob/ca4b9674c26c1de07a2042cb68e6a062d7184cef/src/libstd/sync/mutex.rs#L172), we'll see this: ```ignore __marker: marker::NoSend, ``` Because our guard is `NoSend`, it's not `Send`. Which means we can't actually transfer the guard across thread boundaries, which gives us our error. We can use `Arc` to fix this. Here's the working version: ``` use std::sync::{Arc, Mutex}; use std::thread::Thread; use std::old_io::timer; use std::time::Duration; fn main() { let data = Arc::new(Mutex::new(vec![1u32, 2, 3])); for i in (0us..2) { let data = data.clone(); Thread::spawn(move || { let mut data = data.lock().unwrap(); data[i] += 1; }); } timer::sleep(Duration::milliseconds(50)); } ``` We now call `clone()` on our `Arc`, which increases the internal count. This handle is then moved into the new thread. Let's examine the body of the thread more closely: ``` # use std::sync::{Arc, Mutex}; # use std::thread::Thread; # use std::old_io::timer; # use std::time::Duration; # fn main() { # let data = Arc::new(Mutex::new(vec![1u32, 2, 3])); # for i in (0us..2) { # let data = data.clone(); Thread::spawn(move || { let mut data = data.lock().unwrap(); data[i] += 1; }); # } # } ``` First, we call `lock()`, which acquires the mutex's lock. Because this may fail, it returns an `Result`, and because this is just an example, we `unwrap()` it to get a reference to the data. Real code would have more robust error handling here. We're then free to mutate it, since we have the lock. This timer bit is a bit awkward, however. We have picked a reasonable amount of time to wait, but it's entirely possible that we've picked too high, and that we could be taking less time. It's also possible that we've picked too low, and that we aren't actually finishing this computation. Rust's standard library provides a few more mechanisms for two threads to synchronize with each other. Let's talk about one: channels. ## Channels Here's a version of our code that uses channels for synchronization, rather than waiting for a specific time: ``` use std::sync::{Arc, Mutex}; use std::thread::Thread; use std::sync::mpsc; fn main() { let data = Arc::new(Mutex::new(0u32)); let (tx, rx) = mpsc::channel(); for _ in (0..10) { let (data, tx) = (data.clone(), tx.clone()); Thread::spawn(move || { let mut data = data.lock().unwrap(); *data += 1; tx.send(()); }); } for _ in 0 .. 10 { rx.recv(); } } ``` We use the `mpsc::channel()` method to construct a new channel. We just `send` a simple `()` down the channel, and then wait for ten of them to come back. While this channel is just sending a generic signal, we can send any data that is `Send` over the channel! ``` use std::sync::{Arc, Mutex}; use std::thread::Thread; use std::sync::mpsc; fn main() { let (tx, rx) = mpsc::channel(); for _ in range(0, 10) { let tx = tx.clone(); Thread::spawn(move || { let answer = 42u32; tx.send(answer); }); } rx.recv().ok().expect(\"Could not recieve answer\"); } ``` A `u32` is `Send` because we can make a copy. So we create a thread, ask it to calculate the answer, and then it `send()`s us the answer over the channel. ## Panics A `panic!` will crash the currently executing thread. You can use Rust's threads as a simple isolation mechanism: ``` use std::thread::Thread; let result = Thread::scoped(move || { panic!(\"oops!\"); }).join(); assert!(result.is_err()); ``` Our `Thread` gives us a `Result` back, which allows us to check if the thread has panicked or not. "} {"_id":"doc-en-rust-3df348ac45a59bf82c443fa76a0f24e60a2b3cc37dd1d5e85051d634142285fb","title":"","text":" % The Rust Threads and Communication Guide **NOTE** This guide is badly out of date and needs to be rewritten. # Introduction Rust provides safe concurrent abstractions through a number of core library primitives. This guide will describe the concurrency model in Rust, how it relates to the Rust type system, and introduce the fundamental library abstractions for constructing concurrent programs. Threads provide failure isolation and recovery. When a fatal error occurs in Rust code as a result of an explicit call to `panic!()`, an assertion failure, or another invalid operation, the runtime system destroys the entire thread. Unlike in languages such as Java and C++, there is no way to `catch` an exception. Instead, threads may monitor each other to see if they panic. Threads use Rust's type system to provide strong memory safety guarantees. In particular, the type system guarantees that threads cannot induce a data race from shared mutable state. # Basics At its simplest, creating a thread is a matter of calling the `spawn` function with a closure argument. `spawn` executes the closure in the new thread. ```{rust,ignore} # use std::thread::spawn; // Print something profound in a different thread using a named function fn print_message() { println!(\"I am running in a different thread!\"); } spawn(print_message); // Alternatively, use a `move ||` expression instead of a named function. // `||` expressions evaluate to an unnamed closure. The `move` keyword // indicates that the closure should take ownership of any variables it // touches. spawn(move || println!(\"I am also running in a different thread!\")); ``` In Rust, a thread is not a concept that appears in the language semantics. Instead, Rust's type system provides all the tools necessary to implement safe concurrency: particularly, ownership. The language leaves the implementation details to the standard library. The `spawn` function has the type signature: `fn spawn(f: F)`. This indicates that it takes as argument a closure (of type `F`) that it will run exactly once. This closure is limited to capturing `Send`-able data from its environment (that is, data which is deeply owned). Limiting the closure to `Send` ensures that `spawn` can safely move the entire closure and all its associated state into an entirely different thread for execution. ```rust use std::thread::Thread; fn generate_thread_number() -> i32 { 4 } // a very simple generation // Generate some state locally let child_thread_number = generate_thread_number(); Thread::spawn(move || { // Capture it in the remote thread. The `move` keyword indicates // that this closure should move `child_thread_number` into its // environment, rather than capturing a reference into the // enclosing stack frame. println!(\"I am child number {}\", child_thread_number); }); ``` ## Communication Now that we have spawned a new thread, it would be nice if we could communicate with it. For this, we use *channels*. A channel is simply a pair of endpoints: one for sending messages and another for receiving messages. The simplest way to create a channel is to use the `channel` function to create a `(Sender, Receiver)` pair. In Rust parlance, a *sender* is a sending endpoint of a channel, and a *receiver* is the receiving endpoint. Consider the following example of calculating two results concurrently: ```rust use std::thread::Thread; use std::sync::mpsc; let (tx, rx): (mpsc::Sender, mpsc::Receiver) = mpsc::channel(); Thread::spawn(move || { let result = some_expensive_computation(); tx.send(result); }); some_other_expensive_computation(); let result = rx.recv(); fn some_expensive_computation() -> u32 { 42 } // very expensive ;) fn some_other_expensive_computation() {} // even more so ``` Let's examine this example in detail. First, the `let` statement creates a stream for sending and receiving integers (the left-hand side of the `let`, `(tx, rx)`, is an example of a destructuring let: the pattern separates a tuple into its component parts). ```rust # use std::sync::mpsc; let (tx, rx): (mpsc::Sender, mpsc::Receiver) = mpsc::channel(); ``` The child thread will use the sender to send data to the parent thread, which will wait to receive the data on the receiver. The next statement spawns the child thread. ```rust # use std::thread::Thread; # use std::sync::mpsc; # fn some_expensive_computation() -> u32 { 42 } # let (tx, rx) = mpsc::channel(); Thread::spawn(move || { let result = some_expensive_computation(); tx.send(result); }); ``` Notice that the creation of the thread closure transfers `tx` to the child thread implicitly: the closure captures `tx` in its environment. Both `Sender` and `Receiver` are sendable types and may be captured into threads or otherwise transferred between them. In the example, the child thread runs an expensive computation, then sends the result over the captured channel. Finally, the parent continues with some other expensive computation, then waits for the child's result to arrive on the receiver: ```rust # use std::sync::mpsc; # fn some_other_expensive_computation() {} # let (tx, rx) = mpsc::channel::(); # tx.send(0); some_other_expensive_computation(); let result = rx.recv(); ``` The `Sender` and `Receiver` pair created by `channel` enables efficient communication between a single sender and a single receiver, but multiple senders cannot use a single `Sender` value, and multiple receivers cannot use a single `Receiver` value. What if our example needed to compute multiple results across a number of threads? The following program is ill-typed: ```{rust,ignore} # use std::sync::mpsc; # fn some_expensive_computation() -> u32 { 42 } let (tx, rx) = mpsc::channel(); spawn(move || { tx.send(some_expensive_computation()); }); // ERROR! The previous spawn statement already owns the sender, // so the compiler will not allow it to be captured again spawn(move || { tx.send(some_expensive_computation()); }); ``` Instead we can clone the `tx`, which allows for multiple senders. ```rust use std::thread::Thread; use std::sync::mpsc; let (tx, rx) = mpsc::channel(); for init_val in 0 .. 3 { // Create a new channel handle to distribute to the child thread let child_tx = tx.clone(); Thread::spawn(move || { child_tx.send(some_expensive_computation(init_val)); }); } let result = rx.recv().unwrap() + rx.recv().unwrap() + rx.recv().unwrap(); # fn some_expensive_computation(_i: i32) -> i32 { 42 } ``` Cloning a `Sender` produces a new handle to the same channel, allowing multiple threads to send data to a single receiver. It upgrades the channel internally in order to allow this functionality, which means that channels that are not cloned can avoid the overhead required to handle multiple senders. But this fact has no bearing on the channel's usage: the upgrade is transparent. Note that the above cloning example is somewhat contrived since you could also simply use three `Sender` pairs, but it serves to illustrate the point. For reference, written with multiple streams, it might look like the example below. ```rust use std::thread::Thread; use std::sync::mpsc; // Create a vector of ports, one for each child thread let rxs = (0 .. 3).map(|&:init_val| { let (tx, rx) = mpsc::channel(); Thread::spawn(move || { tx.send(some_expensive_computation(init_val)); }); rx }).collect::>(); // Wait on each port, accumulating the results let result = rxs.iter().fold(0, |&:accum, rx| accum + rx.recv().unwrap() ); # fn some_expensive_computation(_i: i32) -> i32 { 42 } ``` ## Backgrounding computations: Futures With `sync::Future`, rust has a mechanism for requesting a computation and getting the result later. The basic example below illustrates this. ```{rust,ignore} # #![allow(deprecated)] use std::sync::Future; # fn main() { # fn make_a_sandwich() {}; fn fib(n: u64) -> u64 { // lengthy computation returning an 64 12586269025 } let mut delayed_fib = Future::spawn(move || fib(50)); make_a_sandwich(); println!(\"fib(50) = {}\", delayed_fib.get()) # } ``` The call to `future::spawn` immediately returns a `future` object regardless of how long it takes to run `fib(50)`. You can then make yourself a sandwich while the computation of `fib` is running. The result of the execution of the method is obtained by calling `get` on the future. This call will block until the value is available (*i.e.* the computation is complete). Note that the future needs to be mutable so that it can save the result for next time `get` is called. Here is another example showing how futures allow you to background computations. The workload will be distributed on the available cores. ```{rust,ignore} # #![allow(deprecated)] # use std::num::Float; # use std::sync::Future; fn partial_sum(start: u64) -> f64 { let mut local_sum = 0f64; for num in range(start*100000, (start+1)*100000) { local_sum += (num as f64 + 1.0).powf(-2.0); } local_sum } fn main() { let mut futures = Vec::from_fn(200, |ind| Future::spawn(move || partial_sum(ind))); let mut final_res = 0f64; for ft in futures.iter_mut() { final_res += ft.get(); } println!(\"π^2/6 is not far from : {}\", final_res); } ``` ## Sharing without copying: Arc To share data between threads, a first approach would be to only use channel as we have seen previously. A copy of the data to share would then be made for each thread. In some cases, this would add up to a significant amount of wasted memory and would require copying the same data more than necessary. To tackle this issue, one can use an Atomically Reference Counted wrapper (`Arc`) as implemented in the `sync` library of Rust. With an Arc, the data will no longer be copied for each thread. The Arc acts as a reference to the shared data and only this reference is shared and cloned. Here is a small example showing how to use Arcs. We wish to run concurrently several computations on a single large vector of floats. Each thread needs the full vector to perform its duty. ```{rust,ignore} use std::num::Float; use std::rand; use std::sync::Arc; fn pnorm(nums: &[f64], p: u64) -> f64 { nums.iter().fold(0.0, |a, b| a + b.powf(p as f64)).powf(1.0 / (p as f64)) } fn main() { let numbers = Vec::from_fn(1000000, |_| rand::random::()); let numbers_arc = Arc::new(numbers); for num in range(1, 10) { let thread_numbers = numbers_arc.clone(); spawn(move || { println!(\"{}-norm = {}\", num, pnorm(thread_numbers.as_slice(), num)); }); } } ``` The function `pnorm` performs a simple computation on the vector (it computes the sum of its items at the power given as argument and takes the inverse power of this value). The Arc on the vector is created by the line: ```{rust,ignore} # use std::rand; # use std::sync::Arc; # fn main() { # let numbers = Vec::from_fn(1000000, |_| rand::random::()); let numbers_arc = Arc::new(numbers); # } ``` and a clone is captured for each thread via a procedure. This only copies the wrapper and not its contents. Within the thread's procedure, the captured Arc reference can be used as a shared reference to the underlying vector as if it were local. ```{rust,ignore} # use std::rand; # use std::sync::Arc; # fn pnorm(nums: &[f64], p: u64) -> f64 { 4.0 } # fn main() { # let numbers=Vec::from_fn(1000000, |_| rand::random::()); # let numbers_arc = Arc::new(numbers); # let num = 4; let thread_numbers = numbers_arc.clone(); spawn(move || { // Capture thread_numbers and use it as if it was the underlying vector println!(\"{}-norm = {}\", num, pnorm(thread_numbers.as_slice(), num)); }); # } ``` # Handling thread panics Rust has a built-in mechanism for raising exceptions. The `panic!()` macro (which can also be written with an error string as an argument: `panic!( ~reason)`) and the `assert!` construct (which effectively calls `panic!()` if a boolean expression is false) are both ways to raise exceptions. When a thread raises an exception, the thread unwinds its stack—running destructors and freeing memory along the way—and then exits. Unlike exceptions in C++, exceptions in Rust are unrecoverable within a single thread: once a thread panics, there is no way to \"catch\" the exception. While it isn't possible for a thread to recover from panicking, threads may notify each other if they panic. The simplest way of handling a panic is with the `try` function, which is similar to `spawn`, but immediately blocks and waits for the child thread to finish. `try` returns a value of type `Result>`. `Result` is an `enum` type with two variants: `Ok` and `Err`. In this case, because the type arguments to `Result` are `i32` and `()`, callers can pattern-match on a result to check whether it's an `Ok` result with an `i32` field (representing a successful result) or an `Err` result (representing termination with an error). ```{rust,ignore} # use std::thread::Thread; # fn some_condition() -> bool { false } # fn calculate_result() -> i32 { 0 } let result: Result> = Thread::spawn(move || { if some_condition() { calculate_result() } else { panic!(\"oops!\"); } }).join(); assert!(result.is_err()); ``` Unlike `spawn`, the function spawned using `try` may return a value, which `try` will dutifully propagate back to the caller in a [`Result`] enum. If the child thread terminates successfully, `try` will return an `Ok` result; if the child thread panics, `try` will return an `Error` result. [`Result`]: ../std/result/index.html > *Note:* A panicked thread does not currently produce a useful error > value (`try` always returns `Err(())`). In the > future, it may be possible for threads to intercept the value passed to > `panic!()`. But not all panics are created equal. In some cases you might need to abort the entire program (perhaps you're writing an assert which, if it trips, indicates an unrecoverable logic error); in other cases you might want to contain the panic at a certain boundary (perhaps a small piece of input from the outside world, which you happen to be processing in parallel, is malformed such that the processing thread cannot proceed). "} {"_id":"doc-en-rust-d9b3d5018dc9e274ddf5c6cd286230fd47f24be6ce9381708888608eb6c8c712","title":"","text":"pub fn set(stack_bounds: (uint, uint), stack_guard: uint, thread: Thread) { THREAD_INFO.with(|c| assert!(c.borrow().is_none())); match thread.name() { Some(name) => unsafe { ::sys::thread::set_name(name); }, None => {} } THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo{ stack_bounds: stack_bounds, stack_guard: stack_guard,"} {"_id":"doc-en-rust-960e2ed291ce1fcd7b18513439b141762d32371d93aadfbfbf77e902f2753ac3","title":"","text":"use option::Option::{self, Some, None}; use result::Result::{Err, Ok}; use sync::{Mutex, Condvar, Arc}; use str::Str; use string::String; use rt::{self, unwind}; use old_io::{Writer, stdio};"} {"_id":"doc-en-rust-f97bd8bc28e68710d1dfd40778b8aa1351debe88c607b1f5e2e9a255775b6700","title":"","text":"unsafe { stack::record_os_managed_stack_bounds(my_stack_bottom, my_stack_top); } match their_thread.name() { Some(name) => unsafe { imp::set_name(name.as_slice()); }, None => {} } thread_info::set( (my_stack_bottom, my_stack_top), unsafe { imp::guard::current() },"} {"_id":"doc-en-rust-eff4ab1745ca288c2c894f72ee23285603eacdca8a466ba28c17e3deb2e9b93e","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Trait { type A; type B; } fn foo>() { } //~^ ERROR: unsupported cyclic reference between types/traits detected fn main() { } "} {"_id":"doc-en-rust-8d80eaed92d4f217b572add154eb183b72141a975d5fd7445481057ee55fee06","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn foo(t: U) { let y = t(); //~^ ERROR: expected function, found `U` } struct Bar; pub fn some_func() { let f = Bar(); //~^ ERROR: expected function, found `Bar` } fn main() { foo(|| { 1 }); } "} {"_id":"doc-en-rust-883d00add2809de358a9955f82c62f518615a99960bc1d700e56a1e957874f3a","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait A { type Output; fn a(&self) -> ::X; //~^ ERROR: use of undeclared associated type `A::X` } impl A for u32 { type Output = u32; fn a(&self) -> u32 { 0 } } fn main() { let a: u32 = 0; let b: u32 = a.a(); } "} {"_id":"doc-en-rust-872af9d980804f24c534df803d1c9d945fbe39f5bfe69660caaabc7db4ba75ff","title":"","text":" -include ../tools.mk # Test output to be four # The original error only occurred when printing, not when comparing using assert! all: $(RUSTC) foo.rs -O [ `$(call RUN,foo)` = \"4\" ] "} {"_id":"doc-en-rust-145fc9dae61fc0ea27c2555c6e5a88444324c5e445745a9a2caf6cf7cae6bd95","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn identity(a: &u32) -> &u32 { a } fn print_foo(f: &fn(&u32) -> &u32, x: &u32) { print!(\"{}\", (*f)(x)); } fn main() { let x = &4; let f: fn(&u32) -> &u32 = identity; // Didn't print 4 on optimized builds print_foo(&f, x); } "} {"_id":"doc-en-rust-437a88cc7bdddfd8ba8add1844d77dbc4e3feaa9f3cbec1f03691f8d80863c44","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(core)] extern crate core; use core::marker::Sync; static SARRAY: [i32; 1] = [11]; struct MyStruct { pub arr: *const [i32], } unsafe impl Sync for MyStruct {} static mystruct: MyStruct = MyStruct { arr: &SARRAY }; fn main() {} "} {"_id":"doc-en-rust-4dfd27ea5764a27b6a5574bdadd8dda97d5d7f8fe961e3b6d0578a76a25276b1","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::ops::Add; fn f(a: T, b: T) -> ::Output { a + b } fn main() { println!(\"a + b is {}\", f::(100f32, 200f32)); } "} {"_id":"doc-en-rust-4b5e11890484a5a1148e3fe260e08a9b3c379d2d7bf04219d56e3ab3bad338b9","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. macro_rules! items { () => { type A = (); fn a() {} } } trait Foo { type A; fn a(); } impl Foo for () { items!(); } fn main() { } "} {"_id":"doc-en-rust-c846f7be92dd23d872dce556725d6d6250338b62a6e74e8353a5430c19c629fc","title":"","text":"// except according to those terms. /// Creates a `Vec` containing the arguments. /// /// `vec!` allows `Vec`s to be defined with the same syntax as array expressions. /// There are two forms of this macro: /// /// - Create a `Vec` containing a given list of elements: /// /// ``` /// let v = vec![1, 2, 3]; /// assert_eq!(v[0], 1); /// assert_eq!(v[1], 2); /// assert_eq!(v[2], 3); /// ``` /// /// - Create a `Vec` from a given element and size: /// /// ``` /// let v = vec![1; 3]; /// assert_eq!(v, vec![1, 1, 1]); /// ``` /// /// Note that unlike array expressions this syntax supports all elements /// which implement `Clone` and the number of elements doesn't have to be /// a constant. #[macro_export] #[stable(feature = \"rust1\", since = \"1.0.0\")] macro_rules! vec { ($x:expr; $y:expr) => ( <[_] as $crate::slice::SliceExt>::into_vec( $crate::boxed::Box::new([$x; $y])) ($elem:expr; $n:expr) => ( $crate::vec::from_elem($elem, $n) ); ($($x:expr),*) => ( <[_] as $crate::slice::SliceExt>::into_vec("} {"_id":"doc-en-rust-a1f6ae7722aba151ed6c38dc4da927a6481a1bda96277ae3230685ddb69c4653","title":"","text":"} } #[doc(hidden)] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub fn from_elem(elem: T, n: usize) -> Vec { unsafe { let mut v = Vec::with_capacity(n); let mut ptr = v.as_mut_ptr(); // Write all elements except the last one for i in 1..n { ptr::write(ptr, Clone::clone(&elem)); ptr = ptr.offset(1); v.set_len(i); // Increment the length in every step in case Clone::clone() panics } if n > 0 { // We can write the last element directly without cloning needlessly ptr::write(ptr, elem); v.set_len(n); } v } } //////////////////////////////////////////////////////////////////////////////// // Common trait implementations for Vec ////////////////////////////////////////////////////////////////////////////////"} {"_id":"doc-en-rust-092e4cb5fdaa34b9d0e9d374311f0cc4b40bfcd9aafe8749a3704875db8510bb","title":"","text":"assert_eq!(vec![1; 2], vec![1, 1]); assert_eq!(vec![1; 1], vec![1]); assert_eq!(vec![1; 0], vec![]); // from_elem syntax (see RFC 832) let el = Box::new(1); let n = 3; assert_eq!(vec![el; n], vec![Box::new(1), Box::new(1), Box::new(1)]); }"} {"_id":"doc-en-rust-361c42c51421526fea9fc1c5134c88cb666bdd8d9bfd5483047ba39e61987e20","title":"","text":"err.set_primary_message( \"cannot initialize a tuple struct which contains private fields\", ); if !def_id.is_local() && self .r .tcx .inherent_impls(def_id) .iter() .flat_map(|impl_def_id| { self.r.tcx.provided_trait_methods(*impl_def_id) }) .any(|assoc| !assoc.fn_has_self_parameter && assoc.name == sym::new) { // FIXME: look for associated functions with Self return type, // instead of relying only on the name and lack of self receiver. err.span_suggestion_verbose( span.shrink_to_hi(), \"you might have meant to use the `new` associated function\", \"::new\".to_string(), Applicability::MaybeIncorrect, ); } // Use spans of the tuple struct definition. self.r.field_def_ids(def_id).map(|field_ids| { field_ids"} {"_id":"doc-en-rust-b10973cba529967a311942b7fa3dcae9ab76746f476a48735eb5068d4461f9f9","title":"","text":" // run-rustfix #![allow(dead_code)] struct U { wtf: Option>>, x: T, } fn main() { U { wtf: Some(Box::new(U { //~ ERROR cannot initialize a tuple struct which contains private fields wtf: None, x: (), })), x: () }; } "} {"_id":"doc-en-rust-480784e19324533b281f2f5f94ec9acd74843136e28f65aa12ef30ece8925688","title":"","text":" // run-rustfix #![allow(dead_code)] struct U { wtf: Option>>, x: T, } fn main() { U { wtf: Some(Box(U { //~ ERROR cannot initialize a tuple struct which contains private fields wtf: None, x: (), })), x: () }; } "} {"_id":"doc-en-rust-5fd3ece0b09d2d1b6cbf911345f4cc6b13765b696fa4281353aca1ca9599f1f7","title":"","text":" error[E0423]: cannot initialize a tuple struct which contains private fields --> $DIR/suggest-box-new.rs:9:19 | LL | wtf: Some(Box(U { | ^^^ | note: constructor is not visible here due to private fields --> $SRC_DIR/alloc/src/boxed.rs:LL:COL | = note: private field | = note: private field help: you might have meant to use the `new` associated function | LL | wtf: Some(Box::new(U { | +++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0423`. "} {"_id":"doc-en-rust-7ae05d49d538852d2c81389c5234934104105cb69382c90b8f5a3765d934716c","title":"","text":"Exercise: use macros to reduce duplication in the above definition of the `bct!` macro. # Common macros Here are some common macros you’ll see in Rust code. ## panic! This macro causes the current thread to panic. You can give it a message to panic with: ```rust,no_run panic!(\"oh no!\"); ``` ## vec! The `vec!` macro is used throughout the book, so you’ve probably seen it already. It creates `Vec`s with ease: ```rust let v = vec![1, 2, 3, 4, 5]; ``` It also lets you make vectors with repeating values. For example, a hundred zeroes: ```rust let v = vec![0; 100]; ``` ## assert! and assert_eq! These two macros are used in tests. `assert!` takes a boolean, and `assert_eq!` takes two values and compares them. Truth passes, success `panic!`s. Like this: ```rust,no_run // A-ok! assert!(true); assert_eq!(5, 3 + 2); // nope :( assert!(5 < 3); assert_eq!(5, 3); ``` ## try! `try!` is used for error handling. It takes something that can return a `Result`, and gives `T` if it’s a `Ok`, and `return`s with the `Err(E)` if it’s that. Like this: ```rust,no_run use std::fs::File; fn foo() -> std::io::Result<()> { let f = try!(File::create(\"foo.txt\")); Ok(()) } ``` This is cleaner than doing this: ```rust,no_run use std::fs::File; fn foo() -> std::io::Result<()> { let f = File::create(\"foo.txt\"); let f = match f { Ok(t) => t, Err(e) => return Err(e), }; Ok(()) } ``` ## unreachable! This macro is used when you think some code should never execute: ```rust if false { unreachable!(); } ``` Sometimes, the compiler may make you have a different branch that you know will never, ever run. In these cases, use this macro, so that if you end up wrong, you’ll get a `panic!` about it. ```rust let x: Option = None; match x { Some(_) => unreachable!(), None => println!(\"I know x is None!\"), } ``` ## unimplemented! The `unimplemented!` macro can be used when you’re trying to get your functions to typecheck, and don’t want to worry about writing out the body of the function. One example of this situation is implementing a trait with multiple required methods, where you want to tackle one at a time. Define the others as `unimplemented!` until you’re ready to write them. # Procedural macros If Rust's macro system can't do what you need, you may want to write a"} {"_id":"doc-en-rust-c5135c5202bb8e7d46e48aab9691b4089765f5c8cc90127dc163813b33b71cfd","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Expr : PartialEq { //~^ ERROR: unsupported cyclic reference between types/traits detected type Item = Expr; } fn main() {} "} {"_id":"doc-en-rust-d31493c45816240e4bcef29eff24b0eb3663c8c29973ba291ab5ae87fa5427c9","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that `quote`-related macro are gated by `quote` feature gate. // (To sanity-check the code, uncomment this.) // #![feature(quote)] // FIXME the error message that is current emitted seems pretty bad. #![feature(rustc_private)] #![allow(dead_code, unused_imports, unused_variables)] #[macro_use] extern crate syntax; use syntax::ast; use syntax::codemap::Span; use syntax::parse; struct ParseSess; impl ParseSess { fn cfg(&self) -> ast::CrateConfig { loop { } } fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { loop { } } fn call_site(&self) -> Span { loop { } } fn ident_of(&self, st: &str) -> ast::Ident { loop { } } fn name_of(&self, st: &str) -> ast::Name { loop { } } } pub fn main() { let ecx = &ParseSess; let x = quote_tokens!(ecx, 3); //~ ERROR macro undefined: 'quote_tokens!' let x = quote_expr!(ecx, 3); //~ ERROR macro undefined: 'quote_expr!' let x = quote_ty!(ecx, 3); //~ ERROR macro undefined: 'quote_ty!' let x = quote_method!(ecx, 3); //~ ERROR macro undefined: 'quote_method!' let x = quote_item!(ecx, 3); //~ ERROR macro undefined: 'quote_item!' let x = quote_pat!(ecx, 3); //~ ERROR macro undefined: 'quote_pat!' let x = quote_arm!(ecx, 3); //~ ERROR macro undefined: 'quote_arm!' let x = quote_stmt!(ecx, 3); //~ ERROR macro undefined: 'quote_stmt!' let x = quote_matcher!(ecx, 3); //~ ERROR macro undefined: 'quote_matcher!' let x = quote_attr!(ecx, 3); //~ ERROR macro undefined: 'quote_attr!' } "} {"_id":"doc-en-rust-e29063216d9571f579e98388cea979d26d42e33f7cc9c9f3407ee8a216618ab4","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that `#[link_args]` attribute is gated by `link_args` // feature gate. #[link_args = \"aFdEfSeVEEE\"] extern {} //~^ ERROR the `link_args` attribute is not portable across platforms //~| HELP add #![feature(link_args)] to the crate attributes to enable fn main() { } "} {"_id":"doc-en-rust-9c3bfe185f25344abecb65dcd699bfbd6b2df68b42925229c0415bef6c2ba5a1","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern { #[link_name = \"llvm.sqrt.f32\"] fn sqrt(x: f32) -> f32; //~^ ERROR linking to LLVM intrinsics is experimental //~| HELP add #![feature(link_llvm_intrinsics)] to the crate attributes } fn main(){ } "} {"_id":"doc-en-rust-a6db0b96f36c71752304dc0a0d6b0bfe5b4e68e907c4228c9a5a699bc61ceb6b","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. // Test that `#[plugin_registrar]` attribute is gated by `plugin_registrar` // feature gate. // the registration function isn't typechecked yet #[plugin_registrar] pub fn registrar() {} //~ ERROR compiler plugins are experimental pub fn registrar() {} //~^ ERROR compiler plugins are experimental //~| HELP add #![feature(plugin_registrar)] to the crate attributes to enable fn main() {}"} {"_id":"doc-en-rust-fea19db7908c1ea6bb6da5449e9947346ee1cbc496b6e0917b68c197e598e238","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that `#[thread_local]` attribute is gated by `thread_local` // feature gate. // // (Note that the `thread_local!` macro is explicitly *not* gated; it // is given permission to expand into this unstable attribute even // when the surrounding context does not have permission to use it.) #[thread_local] //~ ERROR `#[thread_local]` is an experimental feature static FOO: i32 = 3; pub fn main() { FOO.with(|x| { println!(\"x: {}\", x); }); } "} {"_id":"doc-en-rust-aae6c574fcfc9f67407dd092d3493dc1d299bcf4a19e17179714d3613411b9c6","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that `#[unsafe_destructor]` attribute is gated by `unsafe_destructor` // feature gate. struct D<'a>(&'a u32); #[unsafe_destructor] impl<'a> Drop for D<'a> { //~^ ERROR `#[unsafe_destructor]` allows too many unsafe patterns fn drop(&mut self) { } } //~^ HELP: add #![feature(unsafe_destructor)] to the crate attributes to enable pub fn main() { } "} {"_id":"doc-en-rust-dd7cac15d7bdada0d257bd23450c7701b0836b090228c3d43de2eb5d20e5199e","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that macro reexports item are gated by `macro_reexport` feature gate. // aux-build:macro_reexport_1.rs // ignore-stage1 #![crate_type = \"dylib\"] #[macro_reexport(reexported)] #[macro_use] #[no_link] extern crate macro_reexport_1; //~^ ERROR macros reexports are experimental and possibly buggy //~| HELP add #![feature(macro_reexport)] to the crate attributes to enable "} {"_id":"doc-en-rust-adf7055a76fa6d500a2e0433e82ab39072f166eb2c18e9461e7fdcab07053f0b","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that patterns including the box syntax are gated by `box_patterns` feature gate. fn main() { let x = Box::new(1); match x { box 1 => (), //~^ box pattern syntax is experimental //~| add #![feature(box_patterns)] to the crate attributes to enable _ => () }; } "} {"_id":"doc-en-rust-1e20bd17d08dbf7dc5e37d4e6082650fd63ecd2f22d146357f67ed33bcd1e629","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that the use of the box syntax is gated by `box_syntax` feature gate. fn main() { let x = box 3; //~^ ERROR box expression syntax is experimental; you can call `Box::new` instead. //~| HELP add #![feature(box_syntax)] to the crate attributes to enable } "} {"_id":"doc-en-rust-f26dde2dd70ba352c4083756d14f8b95d87c01e2f8d05f32c935e7ea04bbe898","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that the use of smid types in the ffi is gated by `smid_ffi` feature gate. #![feature(simd)] #[repr(C)] #[derive(Copy)] #[simd] pub struct f32x4(f32, f32, f32, f32); #[allow(dead_code)] extern { fn foo(x: f32x4); //~^ ERROR use of SIMD type `f32x4` in FFI is highly experimental and may result in invalid code //~| HELP add #![feature(simd_ffi)] to the crate attributes to enable } fn main() {} "} {"_id":"doc-en-rust-eb52f6d7b855c198e6886991ef039f6a62a9de867d1b2e0f27ab801a08bbaa5f","title":"","text":"```rust let captured_var = 10; let closure_no_args = |&:| println!(\"captured_var={}\", captured_var); let closure_no_args = || println!(\"captured_var={}\", captured_var); let closure_args = |&: arg: i32| -> i32 { let closure_args = |arg: i32| -> i32 { println!(\"captured_var={}, arg={}\", captured_var, arg); arg // Note lack of semicolon after 'arg' };"} {"_id":"doc-en-rust-730051034c93414da028693cb3e8eb463fae90d7915b8a1d18fc6e96f93d0242","title":"","text":"} } (Ok(const_int(a)), Ok(const_int(b))) => { let is_a_min_value = |&:| { let is_a_min_value = || { let int_ty = match ty::expr_ty_opt(tcx, e).map(|ty| &ty.sty) { Some(&ty::ty_int(int_ty)) => int_ty, _ => return false"} {"_id":"doc-en-rust-b55d712815a18283d2dcbe0a0e8d0716db2fa1b2ab6999bdd3a6aabe71fe9eb9","title":"","text":"scope: region::CodeExtent, depth: uint) { let origin = |&:| infer::SubregionOrigin::SafeDestructor(span); let origin = || infer::SubregionOrigin::SafeDestructor(span); let mut walker = ty_root.walk(); let opt_phantom_data_def_id = rcx.tcx().lang_items.phantom_data();"} {"_id":"doc-en-rust-0bb69faf6b95e298f3c43a88907e094361939f4ef43f91a87bd1954b95c76a21","title":"","text":"// file descriptor. Otherwise, the first file descriptor opened // up in the child would be numbered as one of the stdio file // descriptors, which is likely to wreak havoc. let setup = |&: src: Option, dst: c_int| { let setup = |src: Option, dst: c_int| { let src = match src { None => { let flags = if dst == libc::STDIN_FILENO {"} {"_id":"doc-en-rust-b637ed6a889124da6cc3fcf9b9c090378e96d4aba248c7fb68a0788dbf6cda83","title":"","text":"// Similarly to unix, we don't actually leave holes for the stdio file // descriptors, but rather open up /dev/null equivalents. These // equivalents are drawn from libuv's windows process spawning. let set_fd = |&: fd: &Option, slot: &mut HANDLE, let set_fd = |fd: &Option, slot: &mut HANDLE, is_stdin: bool| { match *fd { None => {"} {"_id":"doc-en-rust-5ba22cc6ff5d84b46968de9824c6eef8671a8581b275f63e3bdba5a98ba790d2","title":"","text":"{ self.bump(); self.bump(); return; } else if self.eat(&token::Colon) {"} {"_id":"doc-en-rust-6230f36e278a3028cb11912e51c13a4c19b13694441ad5032e147a79185506d6","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we generate obsolete syntax errors around usages of closure kinds: `|:|`, `|&:|` and // `|&mut:|`. fn main() { let a = |:| {}; //~ ERROR obsolete syntax: `:`, `&mut:`, or `&:` let a = |&:| {}; //~ ERROR obsolete syntax: `:`, `&mut:`, or `&:` let a = |&mut:| {}; //~ ERROR obsolete syntax: `:`, `&mut:`, or `&:` } "} {"_id":"doc-en-rust-bf73397461845389dcf6fc88876b35f047d391dd775c45392a4c75e7111fdbe4","title":"","text":"f: F, /// The current internal state to be passed to the closure next. #[unstable(feature = \"core\")] pub state: St, }"} {"_id":"doc-en-rust-1b265879b04041cf8fef82054788bc3542ac2ded12cce4ac458a26270b9a0fdd","title":"","text":"pub struct Unfold { f: F, /// Internal state that will be passed to the closure on the next iteration #[unstable(feature = \"core\")] pub state: St, }"} {"_id":"doc-en-rust-054c94343f5b52a85a239c8807841fa61820e504130e3eafc83ffdcf558aeeac","title":"","text":"if i < 0 || buf[i as usize] == b'-' || buf[i as usize] == b'+' { for j in (i as usize + 1..end).rev() { for j in ((i + 1) as usize..end).rev() { buf[j + 1] = buf[j]; } buf[(i + 1) as usize] = value2ascii(1);"} {"_id":"doc-en-rust-76171e322521b4246b66ed6bf542b5dba2617ff49bf90545c0db4643fe492cfd","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[test] fn test_format_float() { assert!(\"1\" == format!(\"{:.0}\", 1.0f64)); assert!(\"9\" == format!(\"{:.0}\", 9.4f64)); assert!(\"10\" == format!(\"{:.0}\", 9.9f64)); assert!(\"9.9\" == format!(\"{:.1}\", 9.85f64)); } "} {"_id":"doc-en-rust-586a1636d394df37fd0661138bd1a8c04a66644988fe29d113847368b542170e","title":"","text":"// empty. } unsafe impl Send for .. { } impl !Send for *const T { } impl !Send for *mut T { } impl !Send for Managed { }"} {"_id":"doc-en-rust-49d62629c6dcde77b9ff137409ebd55c5390a31120febb4cf9fb826c7ee20709","title":"","text":"// Empty } unsafe impl Sync for .. { } impl !Sync for *const T { } impl !Sync for *mut T { } impl !Sync for Managed { }"} {"_id":"doc-en-rust-d4ecd17484efe6445398260a64b8a1d258a2dd73a4881e4d3da5a985f4d35d1c","title":"","text":"pub fn trait_has_default_impl(tcx: &ctxt, trait_def_id: DefId) -> bool { populate_implementations_for_trait_if_necessary(tcx, trait_def_id); match tcx.lang_items.to_builtin_kind(trait_def_id) { Some(BoundSend) | Some(BoundSync) => true, _ => tcx.traits_with_default_impls.borrow().contains_key(&trait_def_id), } tcx.traits_with_default_impls.borrow().contains_key(&trait_def_id) } /// Records a trait-to-implementation mapping."} {"_id":"doc-en-rust-f6fdd56a14d6a157a423e10a48032a20b49deae9a04717d72c470e96428e1a23","title":"","text":"tcx: &'cx ty::ctxt<'tcx> } impl<'cx, 'tcx,'v> visit::Visitor<'v> for UnsafetyChecker<'cx, 'tcx> { fn visit_item(&mut self, item: &'v ast::Item) { match item.node { ast::ItemImpl(unsafety, polarity, _, _, _, _) => { match ty::impl_trait_ref(self.tcx, ast_util::local_def(item.id)) { None => { // Inherent impl. match unsafety { ast::Unsafety::Normal => { /* OK */ } ast::Unsafety::Unsafe => { span_err!(self.tcx.sess, item.span, E0197, \"inherent impls cannot be declared as unsafe\"); } } impl<'cx, 'tcx, 'v> UnsafetyChecker<'cx, 'tcx> { fn check_unsafety_coherence(&mut self, item: &'v ast::Item, unsafety: ast::Unsafety, polarity: ast::ImplPolarity) { match ty::impl_trait_ref(self.tcx, ast_util::local_def(item.id)) { None => { // Inherent impl. match unsafety { ast::Unsafety::Normal => { /* OK */ } ast::Unsafety::Unsafe => { span_err!(self.tcx.sess, item.span, E0197, \"inherent impls cannot be declared as unsafe\"); } } } Some(trait_ref) => { let trait_def = ty::lookup_trait_def(self.tcx, trait_ref.def_id); match (trait_def.unsafety, unsafety, polarity) { (ast::Unsafety::Unsafe, ast::Unsafety::Unsafe, ast::ImplPolarity::Negative) => { span_err!(self.tcx.sess, item.span, E0198, \"negative implementations are not unsafe\"); } Some(trait_ref) => { let trait_def = ty::lookup_trait_def(self.tcx, trait_ref.def_id); match (trait_def.unsafety, unsafety, polarity) { (ast::Unsafety::Unsafe, ast::Unsafety::Unsafe, ast::ImplPolarity::Negative) => { span_err!(self.tcx.sess, item.span, E0198, \"negative implementations are not unsafe\"); } (ast::Unsafety::Normal, ast::Unsafety::Unsafe, _) => { span_err!(self.tcx.sess, item.span, E0199, \"implementing the trait `{}` is not unsafe\", trait_ref.user_string(self.tcx)); } (ast::Unsafety::Normal, ast::Unsafety::Unsafe, _) => { span_err!(self.tcx.sess, item.span, E0199, \"implementing the trait `{}` is not unsafe\", trait_ref.user_string(self.tcx)); } (ast::Unsafety::Unsafe, ast::Unsafety::Normal, ast::ImplPolarity::Positive) => { span_err!(self.tcx.sess, item.span, E0200, \"the trait `{}` requires an `unsafe impl` declaration\", trait_ref.user_string(self.tcx)); } (ast::Unsafety::Unsafe, ast::Unsafety::Normal, ast::ImplPolarity::Positive) => { span_err!(self.tcx.sess, item.span, E0200, \"the trait `{}` requires an `unsafe impl` declaration\", trait_ref.user_string(self.tcx)); } (ast::Unsafety::Unsafe, ast::Unsafety::Normal, ast::ImplPolarity::Negative) | (ast::Unsafety::Unsafe, ast::Unsafety::Unsafe, ast::ImplPolarity::Positive) | (ast::Unsafety::Normal, ast::Unsafety::Normal, _) => { /* OK */ } } (ast::Unsafety::Unsafe, ast::Unsafety::Normal, ast::ImplPolarity::Negative) | (ast::Unsafety::Unsafe, ast::Unsafety::Unsafe, ast::ImplPolarity::Positive) | (ast::Unsafety::Normal, ast::Unsafety::Normal, _) => { /* OK */ } } } } } } impl<'cx, 'tcx,'v> visit::Visitor<'v> for UnsafetyChecker<'cx, 'tcx> { fn visit_item(&mut self, item: &'v ast::Item) { match item.node { ast::ItemDefaultImpl(unsafety, _) => { self.check_unsafety_coherence(item, unsafety, ast::ImplPolarity::Positive); } ast::ItemImpl(unsafety, polarity, _, _, _, _) => { self.check_unsafety_coherence(item, unsafety, polarity); } _ => { } }"} {"_id":"doc-en-rust-e41bdaa6ab10b2ee0f3a88451c117ce1d585eb5601f101f1eb47cb0b6dc36b3e","title":"","text":"} } ast::ItemDefaultImpl(..) => { self.gate_feature(\"optin_builtin_traits\", i.span, \"default trait implementations are experimental and possibly buggy\"); } ast::ItemImpl(_, polarity, _, _, _, _) => { match polarity { ast::ImplPolarity::Negative => {"} {"_id":"doc-en-rust-2984e516067f32d1d0ded9c71f6ebaf5eb83cc3adf8d8c1185384f8bd5cfe1de","title":"","text":"impl MyTrait for .. {} //~^ ERROR conflicting implementations for trait `MyTrait` trait MySafeTrait: MarkerTrait {} unsafe impl MySafeTrait for .. {} //~^ ERROR implementing the trait `MySafeTrait` is not unsafe unsafe trait MyUnsafeTrait: MarkerTrait {} impl MyUnsafeTrait for .. {} //~^ ERROR the trait `MyUnsafeTrait` requires an `unsafe impl` declaration fn main() {}"} {"_id":"doc-en-rust-790914d60fc0202a9ef37e372fbf0f6643d5ec7e4b6b381d108a8df57c295f32","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(optin_builtin_traits)] pub mod bar { use std::marker;"} {"_id":"doc-en-rust-bb44090c801037fe00c51799eda7ea9ba0fbc3c5909a5b3ff374a62f89a7d224","title":"","text":"* Sending signals * Accessing/modifying the file system * Unsigned integer overflow (well-defined as wrapping) * Signed integer overflow (well-defined as two's complement representation * Signed integer overflow (well-defined as two’s complement representation wrapping) #### Diverging functions"} {"_id":"doc-en-rust-a40511bef2467e3f0def4b25e24916b6a3303b9572438f1849a08524256b8bf5","title":"","text":": Exclusive or. Calls the `bitxor` method of the `std::ops::BitXor` trait. * `<<` : Logical left shift. : Left shift. Calls the `shl` method of the `std::ops::Shl` trait. * `>>` : Logical right shift. : Right shift. Calls the `shr` method of the `std::ops::Shr` trait. #### Lazy boolean operators"} {"_id":"doc-en-rust-c9f64eaf4ac61510417c6247aabeae7f721d6d2a51c65296408c24ce9998fa7d","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] pub fn create_dir_all(path: &P) -> io::Result<()> { let path = path.as_path(); if path.is_dir() { return Ok(()) } if path == Path::new(\"\") || path.is_dir() { return Ok(()) } if let Some(p) = path.parent() { try!(create_dir_all(p)) } create_dir(path) }"} {"_id":"doc-en-rust-5b1d073da4ac68aeed71af3b5fa4652bd40aa4db9e251f2354758b6d5cb24ba1","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::env; use std::fs::{self, TempDir}; fn main() { let td = TempDir::new(\"create-dir-all-bare\").unwrap(); env::set_current_dir(td.path()).unwrap(); fs::create_dir_all(\"create-dir-all-bare\").unwrap(); } "} {"_id":"doc-en-rust-79cac1470f473535a3844d271c6392c4b74bebd34375a2d1bd56d8e43b15c2bf","title":"","text":"/// ``` #[macro_export] macro_rules! write { ($dst:expr, $($arg:tt)*) => ((&mut *$dst).write_fmt(format_args!($($arg)*))) ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*))) } /// Equivalent to the `write!` macro, except that a newline is appended after"} {"_id":"doc-en-rust-4722ef90b5a35d7a9491125aa9d783baffde0367c04d6dc0dc2bee34127cbccf","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![crate_name = \"foo\"] #[doc(hidden)] pub trait Foo {} trait Dark {} pub trait Bam {} pub struct Bar; struct Hidden; // @!has foo/struct.Bar.html '//*[@id=\"impl-Foo\"]' 'impl Foo for Bar' impl Foo for Bar {} // @!has foo/struct.Bar.html '//*[@id=\"impl-Dark\"]' 'impl Dark for Bar' impl Dark for Bar {} // @has foo/struct.Bar.html '//*[@id=\"impl-Bam\"]' 'impl Bam for Bar' // @has foo/trait.Bam.html '//*[@id=\"implementors-list\"]' 'impl Bam for Bar' impl Bam for Bar {} // @!has foo/trait.Bam.html '//*[@id=\"implementors-list\"]' 'impl Bam for Hidden' impl Bam for Hidden {} "} {"_id":"doc-en-rust-0b9f32b924d86e44c3c535cd7de6a972c4ad5f11f5d77d8a273356f2eda9298d","title":"","text":"- name: install WIX run: src/ci/scripts/install-wix.sh if: success() && !env.SKIP_JOB - name: install InnoSetup run: src/ci/scripts/install-innosetup.sh if: success() && !env.SKIP_JOB - name: ensure the build happens on a partition with enough space run: src/ci/scripts/symlink-build-dir.sh if: success() && !env.SKIP_JOB"} {"_id":"doc-en-rust-e00b96053621cfb71625b9687db2edd0433ea2403764ad129a4e23dd6d867981","title":"","text":"prepare(\"rust-mingw\"); } builder.install(&xform(&etc.join(\"exe/rust.iss\")), &exe, 0o644); builder.install(&etc.join(\"exe/modpath.iss\"), &exe, 0o644); builder.install(&etc.join(\"exe/upgrade.iss\"), &exe, 0o644); builder.install(&etc.join(\"gfx/rust-logo.ico\"), &exe, 0o644); builder.create(&exe.join(\"LICENSE.txt\"), &license); // Generate exe installer builder.info(\"building `exe` installer with `iscc`\"); let mut cmd = Command::new(\"iscc\"); cmd.arg(\"rust.iss\").arg(\"/Q\").current_dir(&exe); if target.contains(\"windows-gnu\") { cmd.arg(\"/dMINGW\"); } add_env(builder, &mut cmd, target); let time = timeit(builder); builder.run(&mut cmd); drop(time); builder.install( &exe.join(format!(\"{}-{}.exe\", pkgname(builder, \"rust\"), target)), &distdir(builder), 0o755, ); // Generate msi installer let wix = PathBuf::from(env::var_os(\"WIX\").unwrap());"} {"_id":"doc-en-rust-08c0967057c6b67760883abf3d876fbbbc42a1812cce0c29846d8250230f3330","title":"","text":"displayName: Install wix condition: and(succeeded(), not(variables.SKIP_JOB)) - bash: src/ci/scripts/install-innosetup.sh displayName: Install InnoSetup condition: and(succeeded(), not(variables.SKIP_JOB)) - bash: src/ci/scripts/symlink-build-dir.sh displayName: Ensure the build happens on a partition with enough space condition: and(succeeded(), not(variables.SKIP_JOB))"} {"_id":"doc-en-rust-be15c1b9144a047f4658c626b1c50d398ccb960aefd6b356fad726d3caa1ee03","title":"","text":"run: src/ci/scripts/install-wix.sh <<: *step - name: install InnoSetup run: src/ci/scripts/install-innosetup.sh <<: *step - name: ensure the build happens on a partition with enough space run: src/ci/scripts/symlink-build-dir.sh <<: *step"} {"_id":"doc-en-rust-6c02937cf93e998557f543b0132d2407cbb945a0065cca61d07cc2ba98dea010","title":"","text":" #!/bin/bash # We use InnoSetup and its `iscc` program to also create combined installers. # Honestly at this point WIX above and `iscc` are just holdovers from # oh-so-long-ago and are required for creating installers on Windows. I think # one is MSI installers and one is EXE, but they're not used so frequently at # this point anyway so perhaps it's a wash! set -euo pipefail IFS=$'nt' source \"$(cd \"$(dirname \"$0\")\" && pwd)/../shared.sh\" if isWindows; then curl.exe -o is-install.exe \"${MIRRORS_BASE}/2017-08-22-is.exe\" cmd.exe //c \"is-install.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-\" ciCommandAddPath \"C:Program Files (x86)Inno Setup 5\" fi "} {"_id":"doc-en-rust-bd66ea05d2817cf50ef12f45fbf676262c471a449caab3878ab1ef1c357514d8","title":"","text":" // ---------------------------------------------------------------------------- // // Inno Setup Ver:\t5.4.2 // Script Version:\t1.4.1 // Author:\t\t\tJared Breland // Homepage:\t\thttp://www.legroom.net/software // License:\t\t\tGNU Lesser General Public License (LGPL), version 3 //\t\t\t\t\t\thttp://www.gnu.org/licenses/lgpl.html // // Script Function: //\tAllow modification of environmental path directly from Inno Setup installers // // Instructions: //\tCopy modpath.iss to the same directory as your setup script // //\tAdd this statement to your [Setup] section //\t\tChangesEnvironment=true // //\tAdd this statement to your [Tasks] section //\tYou can change the Description or Flags //\tYou can change the Name, but it must match the ModPathName setting below //\t\tName: modifypath; Description: &Add application directory to your environmental path; Flags: unchecked // //\tAdd the following to the end of your [Code] section //\tModPathName defines the name of the task defined above //\tModPathType defines whether the 'user' or 'system' path will be modified; //\t\tthis will default to user if anything other than system is set //\tsetArrayLength must specify the total number of dirs to be added //\tResult[0] contains first directory, Result[1] contains second, etc. //\t\tconst //\t\t\tModPathName = 'modifypath'; //\t\t\tModPathType = 'user'; // //\t\tfunction ModPathDir(): TArrayOfString; //\t\tbegin //\t\t\tsetArrayLength(Result, 1); //\t\t\tResult[0] := ExpandConstant('{app}'); //\t\tend; //\t\t#include \"modpath.iss\" // ---------------------------------------------------------------------------- procedure ModPath(); var oldpath:\tString; newpath:\tString; updatepath:\tBoolean; pathArr:\tTArrayOfString; aExecFile:\tString; aExecArr:\tTArrayOfString; i, d:\t\tInteger; pathdir:\tTArrayOfString; regroot:\tInteger; regpath:\tString; begin // Get constants from main script and adjust behavior accordingly // ModPathType MUST be 'system' or 'user'; force 'user' if invalid if ModPathType = 'system' then begin regroot := HKEY_LOCAL_MACHINE; regpath := 'SYSTEMCurrentControlSetControlSession ManagerEnvironment'; end else begin regroot := HKEY_CURRENT_USER; regpath := 'Environment'; end; // Get array of new directories and act on each individually pathdir := ModPathDir(); for d := 0 to GetArrayLength(pathdir)-1 do begin updatepath := true; // Modify WinNT path if UsingWinNT() = true then begin // Get current path, split into an array RegQueryStringValue(regroot, regpath, 'Path', oldpath); oldpath := oldpath + ';'; i := 0; while (Pos(';', oldpath) > 0) do begin SetArrayLength(pathArr, i+1); pathArr[i] := Copy(oldpath, 0, Pos(';', oldpath)-1); oldpath := Copy(oldpath, Pos(';', oldpath)+1, Length(oldpath)); i := i + 1; // Check if current directory matches app dir if pathdir[d] = pathArr[i-1] then begin // if uninstalling, remove dir from path if IsUninstaller() = true then begin continue; // if installing, flag that dir already exists in path end else begin updatepath := false; end; end; // Add current directory to new path if i = 1 then begin newpath := pathArr[i-1]; end else begin newpath := newpath + ';' + pathArr[i-1]; end; end; // Append app dir to path if not already included if (IsUninstaller() = false) AND (updatepath = true) then newpath := newpath + ';' + pathdir[d]; // Write new path RegWriteStringValue(regroot, regpath, 'Path', newpath); // Modify Win9x path end else begin // Convert to shortened dirname pathdir[d] := GetShortName(pathdir[d]); // If autoexec.bat exists, check if app dir already exists in path aExecFile := 'C:AUTOEXEC.BAT'; if FileExists(aExecFile) then begin LoadStringsFromFile(aExecFile, aExecArr); for i := 0 to GetArrayLength(aExecArr)-1 do begin if IsUninstaller() = false then begin // If app dir already exists while installing, skip add if (Pos(pathdir[d], aExecArr[i]) > 0) then updatepath := false; break; end else begin // If app dir exists and = what we originally set, then delete at uninstall if aExecArr[i] = 'SET PATH=%PATH%;' + pathdir[d] then aExecArr[i] := ''; end; end; end; // If app dir not found, or autoexec.bat didn't exist, then (create and) append to current path if (IsUninstaller() = false) AND (updatepath = true) then begin SaveStringToFile(aExecFile, #13#10 + 'SET PATH=%PATH%;' + pathdir[d], True); // If uninstalling, write the full autoexec out end else begin SaveStringsToFile(aExecFile, aExecArr, False); end; end; end; end; // Split a string into an array using passed delimiter procedure Explode(var Dest: TArrayOfString; Text: String; Separator: String); var i: Integer; begin i := 0; repeat SetArrayLength(Dest, i+1); if Pos(Separator,Text) > 0 then\tbegin Dest[i] := Copy(Text, 1, Pos(Separator, Text)-1); Text := Copy(Text, Pos(Separator,Text) + Length(Separator), Length(Text)); i := i + 1; end else begin Dest[i] := Text; Text := ''; end; until Length(Text)=0; end; procedure ModPathCurStepChanged(CurStep: TSetupStep); var taskname:\tString; begin taskname := ModPathName; if CurStep = ssPostInstall then if IsTaskSelected(taskname) then ModPath(); end; procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); var aSelectedTasks:\tTArrayOfString; i:\t\t\t\tInteger; taskname:\t\tString; regpath:\t\tString; regstring:\t\tString; appid:\t\t\tString; begin // only run during actual uninstall if CurUninstallStep = usUninstall then begin // get list of selected tasks saved in registry at install time appid := '{#emit SetupSetting(\"AppId\")}'; if appid = '' then appid := '{#emit SetupSetting(\"AppName\")}'; regpath := ExpandConstant('SoftwareMicrosoftWindowsCurrentVersionUninstall'+appid+'_is1'); RegQueryStringValue(HKLM, regpath, 'Inno Setup: Selected Tasks', regstring); if regstring = '' then RegQueryStringValue(HKCU, regpath, 'Inno Setup: Selected Tasks', regstring); // check each task; if matches modpath taskname, trigger patch removal if regstring <> '' then begin taskname := ModPathName; Explode(aSelectedTasks, regstring, ','); if GetArrayLength(aSelectedTasks) > 0 then begin for i := 0 to GetArrayLength(aSelectedTasks)-1 do begin if comparetext(aSelectedTasks[i], taskname) = 0 then ModPath(); end; end; end; end; end; function NeedRestart(): Boolean; var taskname:\tString; begin taskname := ModPathName; if IsTaskSelected(taskname) and not UsingWinNT() then begin Result := True; end else begin Result := False; end; end; "} {"_id":"doc-en-rust-ae5f00ddff053ca69f1d2a5e73c22fb23adc81db6c652adcd10ab4cf1395db4b","title":"","text":" #define CFG_RELEASE_NUM GetEnv(\"CFG_RELEASE_NUM\") #define CFG_RELEASE GetEnv(\"CFG_RELEASE\") #define CFG_PACKAGE_NAME GetEnv(\"CFG_PACKAGE_NAME\") #define CFG_BUILD GetEnv(\"CFG_BUILD\") [Setup] SetupIconFile=rust-logo.ico AppName=Rust AppVersion={#CFG_RELEASE} AppCopyright=Copyright (C) 2006-2014 Mozilla Foundation, MIT license AppPublisher=Mozilla Foundation AppPublisherURL=http://www.rust-lang.org VersionInfoVersion={#CFG_RELEASE_NUM} LicenseFile=LICENSE.txt PrivilegesRequired=lowest DisableWelcomePage=true DisableProgramGroupPage=true DisableReadyPage=true DisableStartupPrompt=true OutputDir=. SourceDir=. OutputBaseFilename={#CFG_PACKAGE_NAME}-{#CFG_BUILD} DefaultDirName={sd}Rust Compression=lzma2/normal InternalCompressLevel=normal SolidCompression=no ChangesEnvironment=true ChangesAssociations=no AllowUNCPath=false AllowNoIcons=true Uninstallable=yes [Tasks] Name: modifypath; Description: &Add {app}bin to your PATH (recommended) [Components] Name: rust; Description: \"Rust compiler and standard crates\"; Types: full compact custom; Flags: fixed #ifdef MINGW Name: gcc; Description: \"Linker and platform libraries\"; Types: full #endif Name: docs; Description: \"HTML documentation\"; Types: full Name: cargo; Description: \"Cargo, the Rust package manager\"; Types: full Name: std; Description: \"The Rust Standard Library\"; Types: full // tool-rls-start Name: rls; Description: \"RLS, the Rust Language Server\" // tool-rls-end [Files] Source: \"rustc/*.*\"; DestDir: \"{app}\"; Flags: ignoreversion recursesubdirs; Components: rust #ifdef MINGW Source: \"rust-mingw/*.*\"; DestDir: \"{app}\"; Flags: ignoreversion recursesubdirs; Components: gcc #endif Source: \"rust-docs/*.*\"; DestDir: \"{app}\"; Flags: ignoreversion recursesubdirs; Components: docs Source: \"cargo/*.*\"; DestDir: \"{app}\"; Flags: ignoreversion recursesubdirs; Components: cargo Source: \"rust-std/*.*\"; DestDir: \"{app}\"; Flags: ignoreversion recursesubdirs; Components: std // tool-rls-start Source: \"rls/*.*\"; DestDir: \"{app}\"; Flags: ignoreversion recursesubdirs; Components: rls Source: \"rust-analysis/*.*\"; DestDir: \"{app}\"; Flags: ignoreversion recursesubdirs; Components: rls // tool-rls-end [Code] const ModPathName = 'modifypath'; ModPathType = 'user'; function ModPathDir(): TArrayOfString; begin setArrayLength(Result, 1) Result[0] := ExpandConstant('{app}bin'); end; #include \"modpath.iss\" #include \"upgrade.iss\" // Both modpath.iss and upgrade.iss want to overload CurStepChanged. // This version does the overload then delegates to each. procedure CurStepChanged(CurStep: TSetupStep); begin UpgradeCurStepChanged(CurStep); ModPathCurStepChanged(CurStep); end; "} {"_id":"doc-en-rust-0137539a8c321a6e4d180d0eb9103a84166a2fd3afebac54d06aec1d1cc20b07","title":"","text":" // The following code taken from https://stackoverflow.com/questions/2000296/innosetup-how-to-automatically-uninstall-previous-installed-version // It performs upgrades by running the uninstaller before the install ///////////////////////////////////////////////////////////////////// function GetUninstallString(): String; var sUnInstPath: String; sUnInstallString: String; begin sUnInstPath := ExpandConstant('SoftwareMicrosoftWindowsCurrentVersionUninstallRust_is1'); sUnInstallString := ''; if not RegQueryStringValue(HKLM, sUnInstPath, 'UninstallString', sUnInstallString) then RegQueryStringValue(HKCU, sUnInstPath, 'UninstallString', sUnInstallString); Result := sUnInstallString; end; ///////////////////////////////////////////////////////////////////// function IsUpgrade(): Boolean; begin Result := (GetUninstallString() <> ''); end; ///////////////////////////////////////////////////////////////////// function UnInstallOldVersion(): Integer; var sUnInstallString: String; iResultCode: Integer; begin // Return Values: // 1 - uninstall string is empty // 2 - error executing the UnInstallString // 3 - successfully executed the UnInstallString // default return value Result := 0; // get the uninstall string of the old app sUnInstallString := GetUninstallString(); if sUnInstallString <> '' then begin sUnInstallString := RemoveQuotes(sUnInstallString); if Exec(sUnInstallString, '/SILENT /NORESTART /SUPPRESSMSGBOXES','', SW_HIDE, ewWaitUntilTerminated, iResultCode) then Result := 3 else Result := 2; end else Result := 1; end; ///////////////////////////////////////////////////////////////////// procedure UpgradeCurStepChanged(CurStep: TSetupStep); begin if (CurStep=ssInstall) then begin if (IsUpgrade()) then begin UnInstallOldVersion(); end; end; end; "} {"_id":"doc-en-rust-f17609927fc8fc0066f7b7080ee163c49a0a93c6b1cdd1443563a9455d092f1c","title":"","text":"Repeat{element: elt} } /// An iterator that yields nothing. #[unstable(feature=\"iter_empty\", reason = \"new addition\")] pub struct Empty(marker::PhantomData); #[unstable(feature=\"iter_empty\", reason = \"new addition\")] impl Iterator for Empty { type Item = T; fn next(&mut self) -> Option { None } fn size_hint(&self) -> (usize, Option){ (0, Some(0)) } } #[unstable(feature=\"iter_empty\", reason = \"new addition\")] impl DoubleEndedIterator for Empty { fn next_back(&mut self) -> Option { None } } #[unstable(feature=\"iter_empty\", reason = \"new addition\")] impl ExactSizeIterator for Empty { fn len(&self) -> usize { 0 } } // not #[derive] because that adds a Clone bound on T, // which isn't necessary. #[unstable(feature=\"iter_empty\", reason = \"new addition\")] impl Clone for Empty { fn clone(&self) -> Empty { Empty(marker::PhantomData) } } // not #[derive] because that adds a Default bound on T, // which isn't necessary. #[unstable(feature=\"iter_empty\", reason = \"new addition\")] impl Default for Empty { fn default() -> Empty { Empty(marker::PhantomData) } } /// Creates an iterator that yields nothing. #[unstable(feature=\"iter_empty\", reason = \"new addition\")] pub fn empty() -> Empty { Empty(marker::PhantomData) } /// An iterator that yields an element exactly once. #[unstable(feature=\"iter_once\", reason = \"new addition\")] pub struct Once { inner: ::option::IntoIter } #[unstable(feature=\"iter_once\", reason = \"new addition\")] impl Iterator for Once { type Item = T; fn next(&mut self) -> Option { self.inner.next() } fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } #[unstable(feature=\"iter_once\", reason = \"new addition\")] impl DoubleEndedIterator for Once { fn next_back(&mut self) -> Option { self.inner.next_back() } } #[unstable(feature=\"iter_once\", reason = \"new addition\")] impl ExactSizeIterator for Once { fn len(&self) -> usize { self.inner.len() } } /// Creates an iterator that yields an element exactly once. #[unstable(feature=\"iter_once\", reason = \"new addition\")] pub fn once(value: T) -> Once { Once { inner: Some(value).into_iter() } } /// Functions for lexicographical ordering of sequences. /// /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires"} {"_id":"doc-en-rust-4d8ba1096065066b061a3665dac76c4d946596623782cd7de62f9f3bf80e1f6d","title":"","text":"// Can't check len now because count consumes. } #[test] fn test_once() { let mut it = once(42); assert_eq!(it.next(), Some(42)); assert_eq!(it.next(), None); } #[test] fn test_empty() { let mut it = empty::(); assert_eq!(it.next(), None); } #[bench] fn bench_rposition(b: &mut Bencher) { let it: Vec = (0..300).collect();"} {"_id":"doc-en-rust-f188e6cdffa42f0fdbaea4e1cf31e78b8d2591a5bd94ada1e8cd76c2e2f91c29","title":"","text":"#![feature(slice_patterns)] #![feature(float_from_str_radix)] #![feature(cell_extras)] #![feature(iter_empty)] #![feature(iter_once)] extern crate core; extern crate test;"} {"_id":"doc-en-rust-4f3d61fe6bfa170844161dcc1793b19fd45d92572cec5122e5704f56b17b5b48","title":"","text":"T=$(command -v $P 2>&1) if [ $? -eq 0 ] then VER0=$($P --version 2>/dev/null | head -1 | sed -e 's/[^0-9]*([vV]?[0-9.]+[^ ]*).*/1/' ) VER0=$($P --version 2>/dev/null | grep -o '[vV]?[0-9][0-9.][a-z0-9.-]*' | head -1 ) if [ $? -eq 0 -a \"x${VER0}\" != \"x\" ] then VER=\"($VER0)\""} {"_id":"doc-en-rust-5dd18e77e47aff97a9178011681c8494e06d4bb02db95bcffefe759830d4c7b4","title":"","text":"probe_need CFG_GIT git fi # Use `md5sum` on GNU platforms, or `md5 -q` on BSD probe CFG_MD5 md5 probe CFG_MD5SUM md5sum if [ -n \"$CFG_MD5\" ] then CFG_HASH_COMMAND=\"$CFG_MD5 -q | head -c 8\" elif [ -n \"$CFG_MD5SUM\" ] then CFG_HASH_COMMAND=\"$CFG_MD5SUM | head -c 8\" else err 'could not find one of: md5 md5sum' fi putvar CFG_HASH_COMMAND probe CFG_CLANG clang++ probe CFG_CCACHE ccache probe CFG_GCC gcc"} {"_id":"doc-en-rust-33a40b934c320512e17b315aa53c13cb07d05fef62770302dbe2b3c0a520d58c","title":"","text":"# versions (section 9) CFG_PRERELEASE_VERSION=.1 CFG_FILENAME_EXTRA=4e7c5e5c # Append a version-dependent hash to each library, so we can install different # versions in the same place CFG_FILENAME_EXTRA=$(shell printf '%s' $(CFG_RELEASE) | $(CFG_HASH_COMMAND)) ifeq ($(CFG_RELEASE_CHANNEL),stable) # This is the normal semver version string, e.g. \"0.12.0\", \"0.12.0-nightly\""} {"_id":"doc-en-rust-608b9371792d9c284099bb78f03a55b040cf810f0df84aa62eca3fe5810ad254","title":"","text":"$(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # As above but don't bother running tidy. check-notidy: cleantmptestlogs cleantestlibs all check-stage2 check-notidy: check-sanitycheck cleantmptestlogs cleantestlibs all check-stage2 $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # A slightly smaller set of tests for smoke testing. check-lite: cleantestlibs cleantmptestlogs check-lite: check-sanitycheck cleantestlibs cleantmptestlogs $(foreach crate,$(TEST_TARGET_CRATES),check-stage2-$(crate)) check-stage2-rpass check-stage2-rpass-valgrind check-stage2-rfail check-stage2-cfail check-stage2-pfail check-stage2-rmake $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # Only check the 'reference' tests: rpass/cfail/rfail/rmake. check-ref: cleantestlibs cleantmptestlogs check-stage2-rpass check-stage2-rpass-valgrind check-stage2-rfail check-stage2-cfail check-stage2-pfail check-stage2-rmake check-ref: check-sanitycheck cleantestlibs cleantmptestlogs check-stage2-rpass check-stage2-rpass-valgrind check-stage2-rfail check-stage2-cfail check-stage2-pfail check-stage2-rmake $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # Only check the docs. check-docs: cleantestlibs cleantmptestlogs check-stage2-docs check-docs: check-sanitycheck cleantestlibs cleantmptestlogs check-stage2-docs $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # Some less critical tests that are not prone to breakage."} {"_id":"doc-en-rust-10b0b1aaa87a6df07850963c92573cc451c98eaa67e69935c9138f3c714da08f","title":"","text":"# except according to those terms. import os import subprocess import sys import functools STATUS = 0 def error_unless_permitted(env_var, message): global STATUS if not os.getenv(env_var): sys.stderr.write(message) STATUS = 1 def only_on(platforms): def decorator(func): @functools.wraps(func)"} {"_id":"doc-en-rust-0ddc47e15e5af66665f55c0a517e81672886c2542fa7eea2ad60001108d02a93","title":"","text":"return inner return decorator @only_on(('linux', 'darwin', 'freebsd', 'openbsd')) @only_on(['linux', 'darwin', 'freebsd', 'openbsd']) def check_rlimit_core(): import resource soft, hard = resource.getrlimit(resource.RLIMIT_CORE)"} {"_id":"doc-en-rust-35a4e777b0275bac4686946b4774dfa9479ef38b978286a61b7de57c8fe6cccd","title":"","text":"set ALLOW_NONZERO_RLIMIT_CORE to ignore this warning \"\"\" % (soft)) @only_on(['win32']) def check_console_code_page(): if '65001' not in subprocess.check_output(['cmd', '/c', 'chcp']): sys.stderr.write('Warning: the console output code page is not UTF-8, some tests may fail. Use `cmd /c \"chcp 65001\"` to setup UTF-8 code page.n') def main(): check_console_code_page() check_rlimit_core() if __name__ == '__main__':"} {"_id":"doc-en-rust-8f1afcfed9240aec8a236fad7d8fcc11089c3849b77c5b1ed7e4c916aca74941","title":"","text":" // Copyright (c) 2015 Anders Kaseorg // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // “Software”), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //! This crate exports a macro `enum_from_primitive!` that wraps an //! `enum` declaration and automatically adds an implementation of //! `num::FromPrimitive` (reexported here), to allow conversion from //! primitive integers to the enum. It therefore provides an //! alternative to the built-in `#[derive(FromPrimitive)]`, which //! requires the unstable `std::num::FromPrimitive` and is disabled in //! Rust 1.0. //! //! # Example //! //! ``` //! #[macro_use] extern crate enum_primitive; //! extern crate num_traits; //! use num_traits::FromPrimitive; //! //! enum_from_primitive! { //! #[derive(Debug, PartialEq)] //! enum FooBar { //! Foo = 17, //! Bar = 42, //! Baz, //! } //! } //! //! fn main() { //! assert_eq!(FooBar::from_i32(17), Some(FooBar::Foo)); //! assert_eq!(FooBar::from_i32(42), Some(FooBar::Bar)); //! assert_eq!(FooBar::from_i32(43), Some(FooBar::Baz)); //! assert_eq!(FooBar::from_i32(91), None); //! } //! ``` pub mod num_traits { pub trait FromPrimitive: Sized { fn from_i64(n: i64) -> Option; fn from_u64(n: u64) -> Option; } } pub use std::option::Option; pub use num_traits::FromPrimitive; /// Helper macro for internal use by `enum_from_primitive!`. #[macro_export] macro_rules! enum_from_primitive_impl_ty { ($meth:ident, $ty:ty, $name:ident, $( $variant:ident )*) => { #[allow(non_upper_case_globals, unused)] fn $meth(n: $ty) -> $crate::Option { $( if n == $name::$variant as $ty { $crate::Option::Some($name::$variant) } else )* { $crate::Option::None } } }; } /// Helper macro for internal use by `enum_from_primitive!`. #[macro_export] #[macro_use(enum_from_primitive_impl_ty)] macro_rules! enum_from_primitive_impl { ($name:ident, $( $variant:ident )*) => { impl $crate::FromPrimitive for $name { enum_from_primitive_impl_ty! { from_i64, i64, $name, $( $variant )* } enum_from_primitive_impl_ty! { from_u64, u64, $name, $( $variant )* } } }; } /// Wrap this macro around an `enum` declaration to get an /// automatically generated implementation of `num::FromPrimitive`. #[macro_export] #[macro_use(enum_from_primitive_impl)] macro_rules! enum_from_primitive { ( $( #[$enum_attr:meta] )* enum $name:ident { $( $( #[$variant_attr:meta] )* $variant:ident ),+ $( = $discriminator:expr, $( $( #[$variant_two_attr:meta] )* $variant_two:ident ),+ )* } ) => { $( #[$enum_attr] )* enum $name { $( $( #[$variant_attr] )* $variant ),+ $( = $discriminator, $( $( #[$variant_two_attr] )* $variant_two ),+ )* } enum_from_primitive_impl! { $name, $( $variant )+ $( $( $variant_two )+ )* } }; ( $( #[$enum_attr:meta] )* enum $name:ident { $( $( $( #[$variant_attr:meta] )* $variant:ident ),+ = $discriminator:expr ),* } ) => { $( #[$enum_attr] )* enum $name { $( $( $( #[$variant_attr] )* $variant ),+ = $discriminator ),* } enum_from_primitive_impl! { $name, $( $( $variant )+ )* } }; ( $( #[$enum_attr:meta] )* enum $name:ident { $( $( #[$variant_attr:meta] )* $variant:ident ),+ $( = $discriminator:expr, $( $( #[$variant_two_attr:meta] )* $variant_two:ident ),+ )*, } ) => { $( #[$enum_attr] )* enum $name { $( $( #[$variant_attr] )* $variant ),+ $( = $discriminator, $( $( #[$variant_two_attr] )* $variant_two ),+ )*, } enum_from_primitive_impl! { $name, $( $variant )+ $( $( $variant_two )+ )* } }; ( $( #[$enum_attr:meta] )* enum $name:ident { $( $( $( #[$variant_attr:meta] )* $variant:ident ),+ = $discriminator:expr ),+, } ) => { $( #[$enum_attr] )* enum $name { $( $( $( #[$variant_attr] )* $variant ),+ = $discriminator ),+, } enum_from_primitive_impl! { $name, $( $( $variant )+ )+ } }; ( $( #[$enum_attr:meta] )* pub enum $name:ident { $( $( #[$variant_attr:meta] )* $variant:ident ),+ $( = $discriminator:expr, $( $( #[$variant_two_attr:meta] )* $variant_two:ident ),+ )* } ) => { $( #[$enum_attr] )* pub enum $name { $( $( #[$variant_attr] )* $variant ),+ $( = $discriminator, $( $( #[$variant_two_attr] )* $variant_two ),+ )* } enum_from_primitive_impl! { $name, $( $variant )+ $( $( $variant_two )+ )* } }; ( $( #[$enum_attr:meta] )* pub enum $name:ident { $( $( $( #[$variant_attr:meta] )* $variant:ident ),+ = $discriminator:expr ),* } ) => { $( #[$enum_attr] )* pub enum $name { $( $( $( #[$variant_attr] )* $variant ),+ = $discriminator ),* } enum_from_primitive_impl! { $name, $( $( $variant )+ )* } }; ( $( #[$enum_attr:meta] )* pub enum $name:ident { $( $( #[$variant_attr:meta] )* $variant:ident ),+ $( = $discriminator:expr, $( $( #[$variant_two_attr:meta] )* $variant_two:ident ),+ )*, } ) => { $( #[$enum_attr] )* pub enum $name { $( $( #[$variant_attr] )* $variant ),+ $( = $discriminator, $( $( #[$variant_two_attr] )* $variant_two ),+ )*, } enum_from_primitive_impl! { $name, $( $variant )+ $( $( $variant_two )+ )* } }; ( $( #[$enum_attr:meta] )* pub enum $name:ident { $( $( $( #[$variant_attr:meta] )* $variant:ident ),+ = $discriminator:expr ),+, } ) => { $( #[$enum_attr] )* pub enum $name { $( $( $( #[$variant_attr] )* $variant ),+ = $discriminator ),+, } enum_from_primitive_impl! { $name, $( $( $variant )+ )+ } }; } "} {"_id":"doc-en-rust-dfa4102ff6222a71a7b89173e991bf2fab12373c7968af4202317b53d7b80716","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ensure this code doesn't stack overflow // aux-build:enum_primitive.rs #[macro_use] extern crate enum_primitive; enum_from_primitive! { pub enum Test { A1,A2,A3,A4,A5,A6, B1,B2,B3,B4,B5,B6, C1,C2,C3,C4,C5,C6, D1,D2,D3,D4,D5,D6, E1,E2,E3,E4,E5,E6, F1,F2,F3,F4,F5,F6, G1,G2,G3,G4,G5,G6, H1,H2,H3,H4,H5,H6, I1,I2,I3,I4,I5,I6, J1,J2,J3,J4,J5,J6, K1,K2,K3,K4,K5,K6, L1,L2,L3,L4,L5,L6, M1,M2,M3,M4,M5,M6, N1,N2,N3,N4,N5,N6, O1,O2,O3,O4,O5,O6, P1,P2,P3,P4,P5,P6, Q1,Q2,Q3,Q4,Q5,Q6, R1,R2,R3,R4,R5,R6, S1,S2,S3,S4,S5,S6, T1,T2,T3,T4,T5,T6, U1,U2,U3,U4,U5,U6, V1,V2,V3,V4,V5,V6, W1,W2,W3,W4,W5,W6, X1,X2,X3,X4,X5,X6, Y1,Y2,Y3,Y4,Y5,Y6, Z1,Z2,Z3,Z4,Z5,Z6, } } "} {"_id":"doc-en-rust-980d16551535058b252144ed55933a83736a76332482d562b53ba2ec5a35e00d","title":"","text":"If you're on Windows, please download either the [32-bit installer][win32] or the [64-bit installer][win64] and run it. [win32]: https://static.rust-lang.org/dist/rust-1.0.0-beta-i686-pc-windows-gnu.msi [win64]: https://static.rust-lang.org/dist/rust-1.0.0-beta-x86_64-pc-windows-gnu.msi [win32]: https://static.rust-lang.org/dist/rust-1.0.0-i686-pc-windows-gnu.msi [win64]: https://static.rust-lang.org/dist/rust-1.0.0-x86_64-pc-windows-gnu.msi ## Uninstalling"} {"_id":"doc-en-rust-bf030d006d69ecd5b70d294b68229391c62cc6d24e30b2c599fac96eea97ab60","title":"","text":"You should see the version number, commit hash, commit date and build date: ```bash rustc 1.0.0-beta (9854143cb 2015-04-02) (built 2015-04-02) rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14) ``` If you did, Rust has been installed successfully! Congrats!"} {"_id":"doc-en-rust-fc3e28979841059d20aeac5ff9b8453d8eab8718224f166cb7e9f735fa1fd299","title":"","text":"str::from_utf8(&child_output.stdout).unwrap(), str::from_utf8(&child_output.stderr).unwrap())); fs::remove_dir_all(&child_dir).unwrap(); let res = fs::remove_dir_all(&child_dir); if res.is_err() { // On Windows deleting just executed mytest.exe can fail because it's still locked std::thread::sleep_ms(1000); fs::remove_dir_all(&child_dir).unwrap(); } }"} {"_id":"doc-en-rust-867a2c298f618b229d8cea56d1238c0cc3aaf7a673d999e9dae2859b30dcdf98","title":"","text":".TP fBRUST_TEST_THREADSfR The test framework Rust provides executes tests in parallel. This variable sets the maximum number of threads used for this purpose. the maximum number of threads used for this purpose. This setting is overridden by the --test-threads option. .TP fBRUST_TEST_NOCAPTUREfR"} {"_id":"doc-en-rust-7d46f3f64749588256cc7aaa9b2d1d64668f4b689bc13d3999f40bf102f44871","title":"","text":"pub nocapture: bool, pub color: ColorConfig, pub quiet: bool, pub test_threads: Option, } impl TestOpts {"} {"_id":"doc-en-rust-0cda0587325a7c86549a45eed913eb6ab5410083be5f88baef35f29a325442b7","title":"","text":"nocapture: false, color: AutoColor, quiet: false, test_threads: None, } } }"} {"_id":"doc-en-rust-05f89f5104e0b34409524693a9a97ae36e32e045e5d470bb7134719c6b6e97a0","title":"","text":"of stdout\", \"PATH\"), getopts::optflag(\"\", \"nocapture\", \"don't capture stdout/stderr of each task, allow printing directly\"), getopts::optopt(\"\", \"test-threads\", \"Number of threads used for running tests in parallel\", \"n_threads\"), getopts::optflag(\"q\", \"quiet\", \"Display one character per test instead of one line\"), getopts::optopt(\"\", \"color\", \"Configure coloring of output: auto = colorize if stdout is a tty and tests are run on serially (default);"} {"_id":"doc-en-rust-52f05871826fb43180317b06ced45dece41da74bf3de4f75359b2a6f9e191b7c","title":"","text":"tests whose names contain the filter are run. By default, all tests are run in parallel. This can be altered with the RUST_TEST_THREADS environment variable when running tests (set it to 1). --test-threads flag or the RUST_TEST_THREADS environment variable when running tests (set it to 1). All tests have their standard output and standard error captured by default. This can be overridden with the --nocapture flag or setting RUST_TEST_NOCAPTURE"} {"_id":"doc-en-rust-e75ae8e3a5e916f9aeb0fdd54640f3dffc5d88ab5f199543ff4b482adee5c4da","title":"","text":"}; } let test_threads = match matches.opt_str(\"test-threads\") { Some(n_str) => match n_str.parse::() { Ok(n) => Some(n), Err(e) => return Some(Err(format!(\"argument for --test-threads must be a number > 0 (error: {})\", e))) }, None => None, }; let color = match matches.opt_str(\"color\").as_ref().map(|s| &**s) { Some(\"auto\") | None => AutoColor, Some(\"always\") => AlwaysColor,"} {"_id":"doc-en-rust-c765050c3098f8c66a3a0dd0d8747dd1166c534f8766d748c0788521841c75af","title":"","text":"nocapture: nocapture, color: color, quiet: quiet, test_threads: test_threads, }; Some(Ok(test_opts))"} {"_id":"doc-en-rust-1a223a49905840ab7cb2d7456d1be75ed030f47e9fb76a5048086eef8516f1b7","title":"","text":"} }); // It's tempting to just spawn all the tests at once, but since we have // many tests that run in other processes we would be making a big mess. let concurrency = get_concurrency(); let concurrency = match opts.test_threads { Some(n) => n, None => get_concurrency(), }; let mut remaining = filtered_tests; remaining.reverse();"} {"_id":"doc-en-rust-d28bb243a8b0b40620fbb519a5381c7f3fec3b12985cb86f77cba7667a9d43a7","title":"","text":"Err(_) => false }, color: test::AutoColor, test_threads: None, } }"} {"_id":"doc-en-rust-7265c61777a4d68a9065440f846a8ae0f069203bc7b56f089c6b5980db02f946","title":"","text":"dist-install-dir-$(1): PREPARE_LIB_CMD=$(DEFAULT_PREPARE_LIB_CMD) dist-install-dir-$(1): PREPARE_MAN_CMD=$(DEFAULT_PREPARE_MAN_CMD) dist-install-dir-$(1): PREPARE_CLEAN=true dist-install-dir-$(1): prepare-base-dir-$(1) docs compiler-docs dist-install-dir-$(1): prepare-base-dir-$(1) docs $$(Q)mkdir -p $$(PREPARE_DEST_DIR)/share/doc/rust $$(Q)$$(PREPARE_MAN_CMD) $$(S)COPYRIGHT $$(PREPARE_DEST_DIR)/share/doc/rust $$(Q)$$(PREPARE_MAN_CMD) $$(S)LICENSE-APACHE $$(PREPARE_DEST_DIR)/share/doc/rust"} {"_id":"doc-en-rust-e0d6baa0c9addd5f46c2915f88e643964fae78a24fae9b0045ece7fb89724584","title":"","text":"--legacy-manifest-dirs=rustlib,cargo $$(Q)rm -R tmp/dist/$$(PKG_NAME)-$(1)-image dist-doc-install-dir-$(1): docs compiler-docs dist-doc-install-dir-$(1): docs $$(Q)mkdir -p tmp/dist/$$(DOC_PKG_NAME)-$(1)-image/share/doc/rust $$(Q)cp -r doc tmp/dist/$$(DOC_PKG_NAME)-$(1)-image/share/doc/rust/html"} {"_id":"doc-en-rust-c0d4605753e0b6c0dabd7d47abd674b6740317e14b49dfff254d8d7e219086b4","title":"","text":"# Just copy the docs to a folder under dist with the appropriate name # for uploading to S3 dist-docs: docs compiler-docs dist-docs: docs $(Q) rm -Rf dist/doc $(Q) mkdir -p dist/doc/ $(Q) cp -r doc dist/doc/$(CFG_PACKAGE_VERS)"} {"_id":"doc-en-rust-3f6b1c2293b488207f92f263f7339566c369307012f3f51fb0570404f0fa1a60","title":"","text":"[tuples]: primitive-types.html#tuples [enums]: enums.html # Ignoring bindings You can use `_` in a pattern to disregard the value. For example, here’s a `match` against a `Result`: ```rust # let some_value: Result = Err(\"There was an error\"); match some_value { Ok(value) => println!(\"got a value: {}\", value), Err(_) => println!(\"an error occurred\"), } ``` In the first arm, we bind the value inside the `Ok` variant to `value`. But in the `Err` arm, we use `_` to disregard the specific error, and just print a general error message. `_` is valid in any pattern that creates a binding. This can be useful to ignore parts of a larger structure: ```rust fn coordinate() -> (i32, i32, i32) { // generate and return some sort of triple tuple # (1, 2, 3) } let (x, _, z) = coordinate(); ``` Here, we bind the first and last element of the tuple to `x` and `z`, but ignore the middle element. # Mix and Match Whew! That’s a lot of different ways to match things, and they can all be"} {"_id":"doc-en-rust-1b295570eed3794af18f3d83e1b73df5346319413392222509122aab1d3ae319","title":"","text":"use build_helper::output; #[cfg(not(target_os = \"solaris\"))] const SH_CMD: &'static str = \"sh\"; // On Solaris, sh is the historical bourne shell, not a POSIX shell, or bash. #[cfg(target_os = \"solaris\")] const SH_CMD: &'static str = \"bash\"; use {Build, Compiler, Mode}; use util::{cp_r, libdir, is_dylib, cp_filtered, copy};"} {"_id":"doc-en-rust-45e30ca4485191aafeabb038a9b47106e1c843316f98705c246de12ad04286e6","title":"","text":"let src = build.out.join(host).join(\"doc\"); cp_r(&src, &dst); let mut cmd = Command::new(\"sh\"); let mut cmd = Command::new(SH_CMD); cmd.arg(sanitize_sh(&build.src.join(\"src/rust-installer/gen-installer.sh\"))) .arg(\"--product-name=Rust-Documentation\") .arg(\"--rel-manifest-dir=rustlib\")"} {"_id":"doc-en-rust-7edc7ea3577dcbd0fb7102a4837f4b29f74ff31f856e0553f2995fd7f983e3b9","title":"","text":".arg(host); build.run(&mut cmd); let mut cmd = Command::new(\"sh\"); let mut cmd = Command::new(SH_CMD); cmd.arg(sanitize_sh(&build.src.join(\"src/rust-installer/gen-installer.sh\"))) .arg(\"--product-name=Rust-MinGW\") .arg(\"--rel-manifest-dir=rustlib\")"} {"_id":"doc-en-rust-1efb29c704e18d4c9d8036c4b3edd1571347dd28bf16e02b81fb6cd06eee3d01","title":"","text":"} // Finally, wrap everything up in a nice tarball! let mut cmd = Command::new(\"sh\"); let mut cmd = Command::new(SH_CMD); cmd.arg(sanitize_sh(&build.src.join(\"src/rust-installer/gen-installer.sh\"))) .arg(\"--product-name=Rust\") .arg(\"--rel-manifest-dir=rustlib\")"} {"_id":"doc-en-rust-be39f677f933f657953bccf622ec2c42f60324df4bd021b7a5636cfb278cbd7e","title":"","text":"let src = build.sysroot(compiler).join(\"lib/rustlib\"); cp_r(&src.join(target), &dst); let mut cmd = Command::new(\"sh\"); let mut cmd = Command::new(SH_CMD); cmd.arg(sanitize_sh(&build.src.join(\"src/rust-installer/gen-installer.sh\"))) .arg(\"--product-name=Rust\") .arg(\"--rel-manifest-dir=rustlib\")"} {"_id":"doc-en-rust-c79a1c03086cbc5084e70c0cf2ce749ab762b65da229b2cd12d0b125322d0e9f","title":"","text":"let image_src = src.join(\"save-analysis\"); let dst = image.join(\"lib/rustlib\").join(target).join(\"analysis\"); t!(fs::create_dir_all(&dst)); println!(\"image_src: {:?}, dst: {:?}\", image_src, dst); cp_r(&image_src, &dst); let mut cmd = Command::new(\"sh\"); let mut cmd = Command::new(SH_CMD); cmd.arg(sanitize_sh(&build.src.join(\"src/rust-installer/gen-installer.sh\"))) .arg(\"--product-name=Rust\") .arg(\"--rel-manifest-dir=rustlib\")"} {"_id":"doc-en-rust-3842a4aabcb125995163f606a8707fce68e57982c2897f418a6d2792d8d42f55","title":"","text":"build.run(&mut cmd); // Create source tarball in rust-installer format let mut cmd = Command::new(\"sh\"); let mut cmd = Command::new(SH_CMD); cmd.arg(sanitize_sh(&build.src.join(\"src/rust-installer/gen-installer.sh\"))) .arg(\"--product-name=Rust\") .arg(\"--rel-manifest-dir=rustlib\")"} {"_id":"doc-en-rust-61e3194d1c023e8f2af453bebf6d80da062ab6e4a0c50f742f3c0bcf2293e6f7","title":"","text":"input_tarballs.push_str(&sanitize_sh(&mingw_installer)); } let mut cmd = Command::new(\"sh\"); let mut cmd = Command::new(SH_CMD); cmd.arg(sanitize_sh(&build.src.join(\"src/rust-installer/combine-installers.sh\"))) .arg(\"--product-name=Rust\") .arg(\"--rel-manifest-dir=rustlib\")"} {"_id":"doc-en-rust-c8ff925b7c45e9222d9052aafac3aa2ab2f64baa305c5a977e8a0dc987b56173","title":"","text":"This emphasizes that we have to go through the whole list of `chars`. ## Slicing You can get a slice of a string with slicing syntax: ```rust let dog = \"hachiko\"; let hachi = &dog[0..5]; ``` But note that these are _byte_ offsets, not _character_ offsets. So this will fail at runtime: ```rust,should_panic let dog = \"忠犬ハチ公\"; let hachi = &dog[0..2]; ``` with this error: ```text thread '
' panicked at 'index 0 and/or 2 in `忠犬ハチ公` do not lie on character boundary' ``` ## Concatenation If you have a `String`, you can concatenate a `&str` to the end of it:"} {"_id":"doc-en-rust-4d0314f589e1b2147f1df3961587bd01da7b29821774c3acfba089705ac693aa","title":"","text":"} } // Format a number with thousands separators fn fmt_thousands_sep(mut n: usize, sep: char) -> String { use std::fmt::Write; let mut output = String::new(); let mut first = true; for &pow in &[9, 6, 3, 0] { let base = 10_usize.pow(pow); if pow == 0 || n / base != 0 { if first { output.write_fmt(format_args!(\"{}\", n / base)).unwrap(); } else { output.write_fmt(format_args!(\"{:03}\", n / base)).unwrap(); } if pow != 0 { output.push(sep); } first = false; } n %= base; } output } pub fn fmt_bench_samples(bs: &BenchSamples) -> String { use std::fmt::Write; let mut output = String::new(); let median = bs.ns_iter_summ.median as usize; let deviation = (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize; output.write_fmt(format_args!(\"{:>11} ns/iter (+/- {})\", fmt_thousands_sep(median, ','), fmt_thousands_sep(deviation, ','))).unwrap(); if bs.mb_s != 0 { format!(\"{:>9} ns/iter (+/- {}) = {} MB/s\", bs.ns_iter_summ.median as usize, (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize, bs.mb_s) } else { format!(\"{:>9} ns/iter (+/- {})\", bs.ns_iter_summ.median as usize, (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize) output.write_fmt(format_args!(\" = {} MB/s\", bs.mb_s)).unwrap(); } output } // A simple console test runner"} {"_id":"doc-en-rust-fc4f84c06c1c68f95044a5e6a3084b8a0e79408bae86f6b7ee66a5e010bd28bf","title":"","text":"branches: - 'master' schedule: - cron: '5 15 * * *' # At 15:05 UTC every day. - cron: '6 6 * * *' # At 6:06 UTC every day. env: CARGO_UNSTABLE_SPARSE_REGISTRY: 'true'"} {"_id":"doc-en-rust-d9b770191cb5e7a5c1ec3bac5b9b42e175df06aafd7d02f9b30c0b8d043c83d1","title":"","text":"strategy: fail-fast: false matrix: build: [linux64, macos, win32] include: - build: linux64 os: ubuntu-latest - os: ubuntu-latest host_target: x86_64-unknown-linux-gnu - build: macos os: macos-latest - os: macos-latest host_target: x86_64-apple-darwin - build: win32 os: windows-latest - os: windows-latest host_target: i686-pc-windows-msvc steps: - uses: actions/checkout@v3"} {"_id":"doc-en-rust-25dee9d104e605e8bddf1ccfbd09218807aee99dcb2ed7270325509b5612c6ef","title":"","text":";; i686-pc-windows-msvc) MIRI_TEST_TARGET=x86_64-unknown-linux-gnu run_tests MIRI_TEST_TARGET=x86_64-pc-windows-gnu run_tests ;; *) echo \"FATAL: unknown OS\""} {"_id":"doc-en-rust-b28fc8d65873fada6c4fe2352a13caca182208dd1552ba72dd1259a8bb99c67e","title":"","text":"mir, ty::{self, FloatTy, Ty}, }; use rustc_target::abi::Integer; use rustc_target::abi::{Integer, Size}; use crate::*; use atomic::EvalContextExt as _;"} {"_id":"doc-en-rust-c0b676710a0a2cfa874aad330713591dc9b5027e608e1ca8010ba064c1c3ab24","title":"","text":"this.write_bytes_ptr(ptr, iter::repeat(val_byte).take(byte_count.bytes_usize()))?; } \"ptr_mask\" => { let [ptr, mask] = check_arg_count(args)?; let ptr = this.read_pointer(ptr)?; let mask = this.read_scalar(mask)?.to_machine_usize(this)?; let masked_addr = Size::from_bytes(ptr.addr().bytes() & mask); this.write_pointer(Pointer::new(ptr.provenance, masked_addr), dest)?; } // Floating-point operations \"fabsf32\" => { let [f] = check_arg_count(args)?;"} {"_id":"doc-en-rust-ed8d7ac91097fd1579e64cf9c6f50c0e21de6411f72296baaeeaa141f040dce5","title":"","text":"let [name] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; let thread = this.pthread_self()?; let max_len = this.eval_libc(\"MAXTHREADNAMESIZE\")?.to_machine_usize(this)?; this.pthread_setname_np( let res = this.pthread_setname_np( thread, this.read_scalar(name)?, max_len.try_into().unwrap(), )?; // Contrary to the manpage, `pthread_setname_np` on macOS still // returns an integer indicating success. this.write_scalar(res, dest)?; } \"pthread_getname_np\" => { let [thread, name, len] ="} {"_id":"doc-en-rust-5bff63534bdcded8675498aba84f3ee62bc3425c0665984bdd60332ae407645f","title":"","text":"//@ignore-target-windows: No libc on Windows #![feature(cstr_from_bytes_until_nul)] use std::ffi::CStr; use std::ffi::{CStr, CString}; use std::thread; fn main() {"} {"_id":"doc-en-rust-4b6f60e842f45fedd49595494f6a25367a8fcc112672ab80bcc6532a02611451","title":"","text":".chain(std::iter::repeat(\" yada\").take(100)) .collect::(); fn set_thread_name(name: &CStr) -> i32 { #[cfg(target_os = \"linux\")] return unsafe { libc::pthread_setname_np(libc::pthread_self(), name.as_ptr().cast()) }; #[cfg(target_os = \"macos\")] return unsafe { libc::pthread_setname_np(name.as_ptr().cast()) }; } let result = thread::Builder::new().name(long_name.clone()).spawn(move || { // Rust remembers the full thread name itself. assert_eq!(thread::current().name(), Some(long_name.as_str()));"} {"_id":"doc-en-rust-20b7de66b44428d40124adf75d6e6689e7e28e588d28d49957d8c4a27ba332a7","title":"","text":"// But the system is limited -- make sure we successfully set a truncation. let mut buf = vec![0u8; long_name.len() + 1]; unsafe { libc::pthread_getname_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len()); } libc::pthread_getname_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len()) }; let cstr = CStr::from_bytes_until_nul(&buf).unwrap(); assert!(cstr.to_bytes().len() >= 15); // POSIX seems to promise at least 15 chars assert!(long_name.as_bytes().starts_with(cstr.to_bytes())); // Also test directly calling pthread_setname to check its return value. assert_eq!(set_thread_name(&cstr), 0); // But with a too long name it should fail. assert_ne!(set_thread_name(&CString::new(long_name).unwrap()), 0); }); result.unwrap().join().unwrap(); }"} {"_id":"doc-en-rust-18d3a807f0f67c8e30a2fa67453566c7100ecd999565a0ba85a30b89eff4268d","title":"","text":" #![feature(ptr_mask)] #![feature(strict_provenance)] fn main() { let v: u32 = 0xABCDABCD; let ptr: *const u32 = &v; // u32 is 4 aligned, // so the lower `log2(4) = 2` bits of the address are always 0 assert_eq!(ptr.addr() & 0b11, 0); let tagged_ptr = ptr.map_addr(|a| a | 0b11); let tag = tagged_ptr.addr() & 0b11; let masked_ptr = tagged_ptr.mask(!0b11); assert_eq!(tag, 0b11); assert_eq!(unsafe { *masked_ptr }, 0xABCDABCD); } "} {"_id":"doc-en-rust-c4689ce0662fdf38650c4d7d45a5030afac36bf7bfe7b0f33758af7b099c153e","title":"","text":"concurrent code at compile time. Before we talk about the concurrency features that come with Rust, it's important to understand something: Rust is low-level enough that all of this is provided by the standard library, not by the language. This means that if you don't like some aspect of the way Rust handles concurrency, you can implement an alternative way of doing things. [mio](https://github.com/carllerche/mio) is a real-world example of this principle in action. to understand something: Rust is low-level enough that the vast majority of this is provided by the standard library, not by the language. This means that if you don't like some aspect of the way Rust handles concurrency, you can implement an alternative way of doing things. [mio](https://github.com/carllerche/mio) is a real-world example of this principle in action. ## Background: `Send` and `Sync`"} {"_id":"doc-en-rust-1a6fd57adf6ee67e88d9279b4503920b92c8e528bd0fdbb654f3f513d048f8ca","title":"","text":"repr: Repr, } #[derive(Debug)] enum Repr { Os(i32), Custom(Box),"} {"_id":"doc-en-rust-f40e41f1312a36e1c9776d87d5566d29cc494c28f317dc49c5886ba082e6f2e1","title":"","text":"} } impl fmt::Debug for Repr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { &Repr::Os(ref code) => fmt.debug_struct(\"Os\").field(\"code\", code) .field(\"message\", &sys::os::error_string(*code)).finish(), &Repr::Custom(ref c) => fmt.debug_tuple(\"Custom\").field(c).finish(), } } } #[stable(feature = \"rust1\", since = \"1.0.0\")] impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {"} {"_id":"doc-en-rust-36f2d9b434b282aba7ade3a9a02e991ad8f2c0d61315857129d2ca45f3f9d460","title":"","text":"use error; use error::Error as error_Error; use fmt; use sys::os::error_string; #[test] fn test_debug_error() { let code = 6; let msg = error_string(code); let err = Error { repr: super::Repr::Os(code) }; let expected = format!(\"Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}\", code, msg); assert_eq!(format!(\"{:?}\", err), expected); } #[test] fn test_downcasting() {"} {"_id":"doc-en-rust-4d2c2d14b958542c68f6d6c140fd6847be997f789d91dab67aed3e25b6df1887","title":"","text":"/// A macro which expands to the line number on which it was invoked. /// /// The expanded expression has type `usize`, and the returned line is not /// The expanded expression has type `u32`, and the returned line is not /// the invocation of the `line!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `line!()` macro. ///"} {"_id":"doc-en-rust-e7aadf6091a005aac5e8af0700197c45fa31d7f27a33a77c9e55d8e104ed73fe","title":"","text":"/// A macro which expands to the column number on which it was invoked. /// /// The expanded expression has type `usize`, and the returned column is not /// The expanded expression has type `u32`, and the returned column is not /// the invocation of the `column!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `column!()` macro. ///"} {"_id":"doc-en-rust-3bc899acadd1bc9df9063561bc84e6a7b306bb8e8522fffb8d2040117749a386","title":"","text":"/// /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. /// /// When this trait is `derive`d, it produces a lexicographic ordering. #[stable(feature = \"rust1\", since = \"1.0.0\")] pub trait Ord: Eq + PartialOrd { /// This method returns an `Ordering` between `self` and `other`."} {"_id":"doc-en-rust-139522a372408f2a87984a07744db8bf425107d50d72b7fb488e6ba0a28817c8","title":"","text":"encode_item_sort(rbml_w, 't'); encode_family(rbml_w, 'y'); if let Some(ty) = associated_type.ty { encode_type(ecx, rbml_w, ty); } is_nonstatic_method = false; } }"} {"_id":"doc-en-rust-9dff2bafd64a7bc73325390dc4ebd6862ffd38a3a3aff123b1827f5f8dbbf789","title":"","text":"// ought to be reported by the type checker method // `check_impl_items_against_trait`, so here we // just return TyError. debug!(\"confirm_impl_candidate: no associated type {:?} for {:?}\", assoc_ty.name, trait_ref); return (selcx.tcx().types.err, vec!()); } }"} {"_id":"doc-en-rust-66127c93af5269569b49c9b8eb13300d453d8ce65cd8159292ac581ae312a073","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait Foo { type Input = usize; fn bar(&self, _: Self::Input) {} } impl Foo for () {} "} {"_id":"doc-en-rust-106f62c6fcd8ee6bea1570c00af49aef4bbb2e27bb386a95332ae5e9d1b7f248","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:xcrate_associated_type_defaults.rs extern crate xcrate_associated_type_defaults; use xcrate_associated_type_defaults::Foo; fn main() { ().bar(5); } "} {"_id":"doc-en-rust-72ba153c93a54b7223298ca099b624aa307dbcf1080bc610685455b66359dcb8","title":"","text":"match base_cmt.cat { mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) | mc::cat_local(vid) => { self.reassigned |= self.node == vid && Some(field) == self.field self.reassigned |= self.node == vid && (self.field.is_none() || Some(field) == self.field) }, _ => {} }"} {"_id":"doc-en-rust-3033ba76e479c58b80f460be40e580316762a63765a63214ad159013475cc53f","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let mut c = (1, \"\".to_owned()); match c { c2 => { c.0 = 2; assert_eq!(c2.0, 1); } } } "} {"_id":"doc-en-rust-58daeb2e9bb2ab602d4ffd86a2cf6462c791e0e165ec9fa9cac497809bd8d2b6","title":"","text":"// FOREIGN STATIC ITEM return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?)); } if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) { if self.check_keyword(keywords::Fn) { // FOREIGN FUNCTION ITEM return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?)); }"} {"_id":"doc-en-rust-c6335d52b927602e9ee91d78a6b8f209cc39e5c2f2fbf857a4ac6a906cc122ca","title":"","text":"// compile-flags: -Z parse-only extern { f(); //~ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `f` f(); //~ ERROR expected one of `fn`, `pub`, `static`, or `}`, found `f` } fn main() {"} {"_id":"doc-en-rust-ed4334435b4d27429bd0815f695e47b7672cce5f5e3cd0c8156e7cb9fdfd937f","title":"","text":"extern { const i: isize; //~^ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `const` //~^ ERROR expected one of `fn`, `pub`, `static`, or `}`, found `const` }"} {"_id":"doc-en-rust-41e51ec993b342847b81928262ef8f5dbc0eaed80f9390f278a455d4f262c9a6","title":"","text":"/// Inserts the given element just after the element most recently returned by `.next()`. /// The inserted element does not appear in the iteration. /// /// # Examples /// /// ``` /// #![feature(linked_list_extras)] /// /// use std::collections::LinkedList; /// /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect(); /// /// { /// let mut it = list.iter_mut(); /// assert_eq!(it.next().unwrap(), &1); /// // insert `2` after `1` /// it.insert_next(2); /// } /// { /// let vec: Vec<_> = list.into_iter().collect(); /// assert_eq!(vec, [1, 2, 3, 4]); /// } /// ``` /// This method will be removed soon. #[inline] #[unstable( feature = \"linked_list_extras\", reason = \"this is probably better handled by a cursor type -- we'll see\", issue = \"27794\" )] #[rustc_deprecated( reason = \"Deprecated in favor of CursorMut methods. This method will be removed soon.\", since = \"1.47.0\" )] pub fn insert_next(&mut self, element: T) { match self.head { // `push_back` is okay with aliasing `element` references"} {"_id":"doc-en-rust-0acfa697b7470d22994f7850941e450f0bc7c373dd4e1de2acbd81351ccdb754","title":"","text":"/// Provides a reference to the next element, without changing the iterator. /// /// # Examples /// /// ``` /// #![feature(linked_list_extras)] /// /// use std::collections::LinkedList; /// /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect(); /// /// let mut it = list.iter_mut(); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.peek_next().unwrap(), &2); /// // We just peeked at 2, so it was not consumed from the iterator. /// assert_eq!(it.next().unwrap(), &2); /// ``` /// This method will be removed soon. #[inline] #[unstable( feature = \"linked_list_extras\", reason = \"this is probably better handled by a cursor type -- we'll see\", issue = \"27794\" )] #[rustc_deprecated( reason = \"Deprecated in favor of CursorMut methods. This method will be removed soon.\", since = \"1.47.0\" )] pub fn peek_next(&mut self) -> Option<&mut T> { if self.len == 0 { None"} {"_id":"doc-en-rust-db47a3a81fb25712004f07412af2e49e8aa8dd061a89f8baa550f791542ae69e","title":"","text":"} #[test] fn test_insert_prev() { let mut m = list_from(&[0, 2, 4, 6, 8]); let len = m.len(); { let mut it = m.iter_mut(); it.insert_next(-2); loop { match it.next() { None => break, Some(elt) => { it.insert_next(*elt + 1); match it.peek_next() { Some(x) => assert_eq!(*x, *elt + 2), None => assert_eq!(8, *elt), } } } } it.insert_next(0); it.insert_next(1); } check_links(&m); assert_eq!(m.len(), 3 + len * 2); assert_eq!(m.into_iter().collect::>(), [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]); } #[test] #[cfg_attr(target_os = \"emscripten\", ignore)] fn test_send() { let n = list_from(&[1, 2, 3]);"} {"_id":"doc-en-rust-2a7e188186ea1fcca321b98b9937bb2944d22065d007293f0c3fe68eec65bd59","title":"","text":"#[stable(feature = \"fused\", since = \"1.26.0\")] impl FusedIterator for IterMut<'_, T> {} impl IterMut<'_, T> { /// Inserts the given element just after the element most recently returned by `.next()`. /// The inserted element does not appear in the iteration. /// /// This method will be removed soon. #[inline] #[unstable( feature = \"linked_list_extras\", reason = \"this is probably better handled by a cursor type -- we'll see\", issue = \"27794\" )] #[rustc_deprecated( reason = \"Deprecated in favor of CursorMut methods. This method will be removed soon.\", since = \"1.47.0\" )] pub fn insert_next(&mut self, element: T) { match self.head { // `push_back` is okay with aliasing `element` references None => self.list.push_back(element), Some(head) => unsafe { let prev = match head.as_ref().prev { // `push_front` is okay with aliasing nodes None => return self.list.push_front(element), Some(prev) => prev, }; let node = Some( Box::leak(box Node { next: Some(head), prev: Some(prev), element }).into(), ); // Not creating references to entire nodes to not invalidate the // reference to `element` we handed to the user. (*prev.as_ptr()).next = node; (*head.as_ptr()).prev = node; self.list.len += 1; }, } } /// Provides a reference to the next element, without changing the iterator. /// /// This method will be removed soon. #[inline] #[unstable( feature = \"linked_list_extras\", reason = \"this is probably better handled by a cursor type -- we'll see\", issue = \"27794\" )] #[rustc_deprecated( reason = \"Deprecated in favor of CursorMut methods. This method will be removed soon.\", since = \"1.47.0\" )] pub fn peek_next(&mut self) -> Option<&mut T> { if self.len == 0 { None } else { unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) } } } } /// A cursor over a `LinkedList`. /// /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth."} {"_id":"doc-en-rust-94bd36f9b37df26ce54f18f2392fd72d126065c7a835b004c76323f0b31bab49","title":"","text":"for arg in &fd.inputs { match arg.pat.node { hir::PatIdent(hir::BindByValue(hir::MutImmutable), _, None) => {} hir::PatWild(_) => {} _ => { span_err!(self.tcx.sess, arg.pat.span, E0022, \"arguments of constant functions can only "} {"_id":"doc-en-rust-a0cd8b74124e43ad5b25d6de3df099987bc40146131e973762ff46852ba1cce2","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] fn main() {} const fn size_ofs(_: usize) {} const fn size_ofs2(_foo: usize) {} "} {"_id":"doc-en-rust-aa48d710fd4614d47d0c6322ed8e7689d01ccc63afdb8696e7d46bbc1c8e5494","title":"","text":".rusttest { display: none; } pre.rust { position: relative; } .test-arrow { a.test-arrow { display: inline-block; position: absolute; top: 0; right: 10px; font-size: 150%; -webkit-transform: scaleX(-1); transform: scaleX(-1); background-color: #4e8bca; color: #f5f5f5; padding: 5px 10px 5px 10px; border-radius: 5px; font-size: 130%; top: 5px; right: 5px; } .methods .section-header {"} {"_id":"doc-en-rust-eaf235ad7691162fab4eb923fc26a92884f960b0d44ec131f2fa616affa0727b","title":"","text":"} var a = document.createElement('a'); a.textContent = '⇱'; a.setAttribute('class', 'test-arrow'); a.textContent = 'Run'; var code = el.previousElementSibling.textContent;"} {"_id":"doc-en-rust-afa300880b832834f232dee5a90839a31544b2b08909117fba6f63288bf73a45","title":"","text":"let s = s.as_bytes(); let (integral, s) = eat_digits(s); match s.first() { None => Valid(Decimal::new(integral, b\"\", 0)), None => { if integral.is_empty() { return Invalid; // No digits at all } Valid(Decimal::new(integral, b\"\", 0)) } Some(&b'e') | Some(&b'E') => { if integral.is_empty() { return Invalid; // No digits before 'e'"} {"_id":"doc-en-rust-762a9cdc49420cf56d5d572226f88cd661905499f2bae5d71d039673b67b701e","title":"","text":"} #[test] fn lonely_sign() { assert!(\"+\".parse::().is_err()); assert!(\"-\".parse::().is_err()); } #[test] fn whitespace() { assert!(\" 1.0\".parse::().is_err()); assert!(\"1.0 \".parse::().is_err()); } #[test] fn nan() { assert!(\"NaN\".parse::().unwrap().is_nan()); assert!(\"NaN\".parse::().unwrap().is_nan());"} {"_id":"doc-en-rust-f592d0721851853b7abd20faac7ab48d926f9de9f10d056e3b7a6883e4ea3cbb","title":"","text":"_ => { if ascii_only && first_source_char > 'x7F' { let last_pos = self.last_pos; self.err_span_char(start, last_pos, \"byte constant must be ASCII. Use a xHH escape for a non-ASCII byte\", first_source_char); self.err_span_(start, last_pos, \"byte constant must be ASCII. Use a xHH escape for a non-ASCII byte\"); return false; } }"} {"_id":"doc-en-rust-f4d6ec07215a1a32663b89912b6987b6ce425def3d306872ad55a6423dedac7f","title":"","text":"``` ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType` ``` Note that this does not move `v` (unlike `transmute`), and may need a call to `mem::forget(v)` in case you want to avoid destructors being called. \"##, E0152: r##\""} {"_id":"doc-en-rust-4bca4712685d8ebdec7462a6e737271ee6f18e1db07c23814454eb7db6625961","title":"","text":"fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box { static NUMERALS: &'static [(&'static str, u32)] = &[ static NUMERALS: &'static [(&'static str, usize)] = &[ (\"M\", 1000), (\"CM\", 900), (\"D\", 500), (\"CD\", 400), (\"C\", 100), (\"XC\", 90), (\"L\", 50), (\"XL\", 40), (\"X\", 10), (\"IX\", 9), (\"V\", 5), (\"IV\", 4), (\"I\", 1)]; let text = match args { [TokenTree::Token(_, token::Ident(s, _))] => s.to_string(), if args.len() != 1 { cx.span_err( sp, &format!(\"argument should be a single identifier, but got {} arguments\", args.len())); return DummyResult::any(sp); } let text = match args[0] { TokenTree::Token(_, token::Ident(s, _)) => s.to_string(), _ => { cx.span_err(sp, \"argument should be a single identifier\"); return DummyResult::any(sp);"} {"_id":"doc-en-rust-bcd99e38f67b3c4e38de0169ac4e0915fd1406f43a8f353309a6adce1bc1c6aa","title":"","text":"} } MacEager::expr(cx.expr_u32(sp, total)) MacEager::expr(cx.expr_usize(sp, total)) } #[plugin_registrar]"} {"_id":"doc-en-rust-4fb46e073835c3240f4df71cea502d3d504a77b575dd5481c67e7157896f55be","title":"","text":"(\"X\", 10), (\"IX\", 9), (\"V\", 5), (\"IV\", 4), (\"I\", 1)]; let text = match args { [TokenTree::Token(_, token::Ident(s, _))] => s.to_string(), if args.len() != 1 { cx.span_err( sp, &format!(\"argument should be a single identifier, but got {} arguments\", args.len())); return DummyResult::any(sp); } let text = match args[0] { TokenTree::Token(_, token::Ident(s, _)) => s.to_string(), _ => { cx.span_err(sp, \"argument should be a single identifier\"); return DummyResult::any(sp);"} {"_id":"doc-en-rust-8c5649561364358f77e6b19e81f4181b3c3b9ecc862fe52b27005669f901e437","title":"","text":"let path = match def.full_def() { def::DefStruct(def_id) => def_to_path(tcx, def_id), def::DefVariant(_, variant_did, _) => def_to_path(tcx, variant_did), def::DefFn(..) => return P(hir::Pat { id: expr.id, node: hir::PatLit(P(expr.clone())), span: span, }), _ => unreachable!() }; let pats = args.iter().map(|expr| const_expr_to_pat(tcx, &**expr, span)).collect();"} {"_id":"doc-en-rust-90bf803f3b133e166a9ee9f8eb33c631a61cb28e38019e40e1420a678a113660","title":"","text":"_ => signal!(e, NonConstPath), }, Some(ast_map::NodeTraitItem(..)) => signal!(e, NonConstPath), Some(_) => unimplemented!(), Some(_) => signal!(e, UnimplementedConstVal(\"calling struct, tuple or variant\")), } }"} {"_id":"doc-en-rust-5f06788a0239870d55552ed1e08fd4965929de505299161ea72dc5eddb359c0e","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] enum Cake { BlackForest, Marmor, } use Cake::*; const BOO: (Cake, Cake) = (Marmor, BlackForest); //~^ ERROR: constant evaluation error: non-constant path in constant expression [E0471] const FOO: Cake = BOO.1; const fn foo() -> Cake { Marmor //~ ERROR: constant evaluation error: non-constant path in constant expression [E0471] //~^ ERROR: non-constant path in constant expression } const WORKS: Cake = Marmor; const GOO: Cake = foo(); fn main() { match BlackForest { FOO => println!(\"hi\"), //~ NOTE: in pattern here GOO => println!(\"meh\"), //~ NOTE: in pattern here WORKS => println!(\"möp\"), _ => println!(\"bye\"), } } "} {"_id":"doc-en-rust-c82cbc185771c2f85ad75e4852f6bd36cae724046a3d511f627bea71be05dfb3","title":"","text":" // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //"} {"_id":"doc-en-rust-f3ef24a317545055a270f3d86422fbcaf8b2bf605966d2ebc2961b6d77f70d17","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] const FOO: isize = 10; const BAR: isize = 3; const fn foo() -> isize { 4 } const BOO: isize = foo(); pub fn main() { let x: isize = 3; let y = match x { FOO => 1, BAR => 2, BOO => 4, _ => 3 }; assert_eq!(y, 2);"} {"_id":"doc-en-rust-780a0125de280190c8bf0e55b5b2dd13ea94ca29a3a82c518e1ee1baee94e0ac","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] const fn f() -> usize { 5 } struct A { field: usize, } fn main() { let _ = [0; f()]; } "} {"_id":"doc-en-rust-7ee2425eef9a97e18ab55a314d7b8dd85f5428397fc9d3bf86c078b20e6cb8ee","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] struct A { field: usize, } const fn f() -> usize { 5 } fn main() { let _ = [0; f()]; } "} {"_id":"doc-en-rust-54eb03b5f22362ecfcfa2807f0be11c7b2112d5ada200ee605ae48bea5bf566f","title":"","text":"function name will expand to either `::increment` or `::mylib::increment`. To keep this system simple and correct, `#[macro_use] extern crate ...` may only appear at the root of your crate, not inside `mod`. This ensures that `$crate` is a single identifier. only appear at the root of your crate, not inside `mod`. # The deep end"} {"_id":"doc-en-rust-e5e7499cbe44e2669987ced0191bfce62d38b8227b8f81ce2b40ccbe37778c32","title":"","text":"use fmt; use hash::{Hash, self}; use iter::IntoIterator; use marker::{Sized, Unsize}; use marker::{Copy, Sized, Unsize}; use option::Option; use slice::{Iter, IterMut, SliceExt};"} {"_id":"doc-en-rust-af39811f6c82552558de56b6553d0fb85c45c7988a93397483c9ca3f8e042abb","title":"","text":"} #[stable(feature = \"rust1\", since = \"1.0.0\")] impl Clone for [T; $N] { fn clone(&self) -> [T; $N] { *self } } #[stable(feature = \"rust1\", since = \"1.0.0\")] impl Hash for [T; $N] { fn hash(&self, state: &mut H) { Hash::hash(&self[..], state)"} {"_id":"doc-en-rust-f10fbe1bace21f3c98411080581f323828237f52c6c38311646f29c2f8cb0828","title":"","text":"} array_impl_default!{32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T} macro_rules! array_impl_clone { {$n:expr, $i:expr, $($idx:expr,)*} => { #[stable(feature = \"rust1\", since = \"1.0.0\")] impl Clone for [T; $n] { fn clone(&self) -> [T; $n] { [self[$i-$i].clone(), $(self[$i-$idx].clone()),*] } } array_impl_clone!{$i, $($idx,)*} }; {$n:expr,} => { #[stable(feature = \"rust1\", since = \"1.0.0\")] impl Clone for [T; 0] { fn clone(&self) -> [T; 0] { [] } } }; } array_impl_clone! { 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, } "} {"_id":"doc-en-rust-d6e6435e4839cccbb28ae1b7acfcade5f29aa205bef5911310d184823fadf400","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // test for issue #30244 #[derive(Copy, Clone)] struct Array { arr: [[u8; 256]; 4] } pub fn main() {} "} {"_id":"doc-en-rust-925930760c1a0c4bd17e89d0fd57ce56140bb3ba1bba7061aa247777e934ad20","title":"","text":"use self::Destination::*; use codemap::{self, COMMAND_LINE_SP, COMMAND_LINE_EXPN, Pos, Span}; use codemap::{self, COMMAND_LINE_SP, COMMAND_LINE_EXPN, DUMMY_SP, Pos, Span}; use diagnostics; use errors::{Level, RenderSpan, DiagnosticBuilder};"} {"_id":"doc-en-rust-d3711ff1d468e3453efab83403e27e0c9757586f039a9531ba43e6def0653e82","title":"","text":"lvl: Level) { let error = match sp { Some(COMMAND_LINE_SP) => self.emit_(FileLine(COMMAND_LINE_SP), msg, code, lvl), Some(DUMMY_SP) | None => print_diagnostic(&mut self.dst, \"\", lvl, msg, code), Some(sp) => self.emit_(FullSpan(sp), msg, code, lvl), None => print_diagnostic(&mut self.dst, \"\", lvl, msg, code), }; if let Err(e) = error {"} {"_id":"doc-en-rust-21970372081cd4ca6e62269552918bea2e1f99df514dec4386659c1aa0fbdc5f","title":"","text":"ex = ExprBreak(None); } hi = self.last_span.hi; } else if self.token.is_keyword(keywords::Let) { // Catch this syntax error here, instead of in `check_strict_keywords`, so // that we can explicitly mention that let is not to be used as an expression let mut db = self.fatal(\"expected expression, found statement (`let`)\"); db.note(\"variable declaration using `let` is a statement\"); return Err(db); } else if self.check(&token::ModSep) || self.token.is_ident() && !self.check_keyword(keywords::True) &&"} {"_id":"doc-en-rust-25585000a526ce72a6295267d520c97dcaef1936575169746ca45a593d5a6558","title":"","text":"// ignore-cross-compile // error-pattern:expected identifier, found keyword `let` // error-pattern:expected expression, found statement (`let`) #![feature(quote, rustc_private)]"} {"_id":"doc-en-rust-6e59e27e0adeab04a756c070f223dc2f8fa7d98f80db4e1f9ea4b32ce7e5c0e5","title":"","text":"} } #[stable(feature = \"mpsc_debug\", since = \"1.7.0\")] impl fmt::Debug for Sender { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, \"Sender {{ .. }}\") } } //////////////////////////////////////////////////////////////////////////////// // SyncSender ////////////////////////////////////////////////////////////////////////////////"} {"_id":"doc-en-rust-88e024a9c8258c2a3b467e0180c2c972a14eea0ff1a059a86bfb5d77ca293799","title":"","text":"} } #[stable(feature = \"mpsc_debug\", since = \"1.7.0\")] impl fmt::Debug for SyncSender { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, \"SyncSender {{ .. }}\") } } //////////////////////////////////////////////////////////////////////////////// // Receiver ////////////////////////////////////////////////////////////////////////////////"} {"_id":"doc-en-rust-9555cc0dd489dcafe43922cc32187d1391f81331dfa6fa17c0196f54f2e9d9d6","title":"","text":"} } #[stable(feature = \"mpsc_debug\", since = \"1.7.0\")] impl fmt::Debug for Receiver { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, \"Receiver {{ .. }}\") } } #[stable(feature = \"rust1\", since = \"1.0.0\")] impl fmt::Debug for SendError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {"} {"_id":"doc-en-rust-31fbbf6d199e1920c12bce5433eab36d5d5c409bf9ceb3cabb01bbe119743568","title":"","text":"repro() } } #[test] fn fmt_debug_sender() { let (tx, _) = channel::(); assert_eq!(format!(\"{:?}\", tx), \"Sender { .. }\"); } #[test] fn fmt_debug_recv() { let (_, rx) = channel::(); assert_eq!(format!(\"{:?}\", rx), \"Receiver { .. }\"); } #[test] fn fmt_debug_sync_sender() { let (tx, _) = sync_channel::(1); assert_eq!(format!(\"{:?}\", tx), \"SyncSender { .. }\"); } }"} {"_id":"doc-en-rust-0492a841d8c288c61667816aa066b7cf6c518277dfc682b2bba8b2e3d44a0407","title":"","text":"issue = \"27800\")] use fmt; use core::cell::{Cell, UnsafeCell}; use core::marker; use core::ptr;"} {"_id":"doc-en-rust-7662ca2df535eaa7c360c35cceb7a5a19ddc5be7e806d21e6d7b1743051de3bf","title":"","text":"} } #[stable(feature = \"mpsc_debug\", since = \"1.7.0\")] impl fmt::Debug for Select { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, \"Select {{ .. }}\") } } #[stable(feature = \"mpsc_debug\", since = \"1.7.0\")] impl<'rx, T:Send+'rx> fmt::Debug for Handle<'rx, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, \"Handle {{ .. }}\") } } #[cfg(test)] #[allow(unused_imports)] mod tests {"} {"_id":"doc-en-rust-861d23dc0d6f0718722015004c7704f3090d7081ecf6ff084f23c75357b8aca4","title":"","text":"} } } #[test] fn fmt_debug_select() { let sel = Select::new(); assert_eq!(format!(\"{:?}\", sel), \"Select { .. }\"); } #[test] fn fmt_debug_handle() { let (_, rx) = channel::(); let sel = Select::new(); let mut handle = sel.handle(&rx); assert_eq!(format!(\"{:?}\", handle), \"Handle { .. }\"); } }"} {"_id":"doc-en-rust-2447340192c6ffc7a1713199e0c40f19a6b931c22b0c3a960d8c33b68a335d3f","title":"","text":"operand: OperandRef<'tcx>) { debug!(\"store_operand: operand={}\", operand.repr(bcx)); // Avoid generating stores of zero-sized values, because the only way to have a zero-sized // value is through `undef`, and store itself is useless. if common::type_is_zero_size(bcx.ccx(), operand.ty) { return; } match operand.val { OperandValue::Ref(r) => base::memcpy_ty(bcx, lldest, r, operand.ty), OperandValue::Immediate(s) => base::store_ty(bcx, s, lldest, operand.ty),"} {"_id":"doc-en-rust-2a810bfebf5070028ac32a47de42f8f66e87ec6cd118d37d5aed25d970a9e7d0","title":"","text":"}, _ => { for (i, operand) in operands.iter().enumerate() { // Note: perhaps this should be StructGep, but // note that in some cases the values here will // not be structs but arrays. let lldest_i = build::GEPi(bcx, dest.llval, &[0, i]); self.trans_operand_into(bcx, lldest_i, operand); let op = self.trans_operand(bcx, operand); // Do not generate stores and GEPis for zero-sized fields. if !common::type_is_zero_size(bcx.ccx(), op.ty) { // Note: perhaps this should be StructGep, but // note that in some cases the values here will // not be structs but arrays. let dest = build::GEPi(bcx, dest.llval, &[0, i]); self.store_operand(bcx, dest, op); } } } }"} {"_id":"doc-en-rust-5c09b9de3f491ec65a0014babe09ea65d481f36dae48fab6b5f01a023b0b1b69","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -C no-prepopulate-passes #![feature(rustc_attrs)] #![crate_type = \"lib\"] use std::marker::PhantomData; struct Zst { phantom: PhantomData } // CHECK-LABEL: @mir #[no_mangle] #[rustc_mir] fn mir(){ // CHECK-NOT: getelementptr // CHECK-NOT: store{{.*}}undef let x = Zst { phantom: PhantomData }; } "} {"_id":"doc-en-rust-4c8ea6e976b94b40d20a3a4523ef811a6fd8c61ff14366c01cf1689686e9420c","title":"","text":"impl io::Read for Maybe { fn read(&mut self, buf: &mut [u8]) -> io::Result { match *self { Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), buf.len()), Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0), Maybe::Fake => Ok(0) } }"} {"_id":"doc-en-rust-6c0d2fe607ad05de9b888a8f7156c41fd69324d720962869e2dd26e3a2f5b954","title":"","text":"impl Stdio { fn to_handle(&self, stdio_id: c::DWORD) -> io::Result { match *self { // If no stdio handle is available, then inherit means that it // should still be unavailable so propagate the // INVALID_HANDLE_VALUE. Stdio::Inherit => { stdio::get(stdio_id).and_then(|io| { io.handle().duplicate(0, true, c::DUPLICATE_SAME_ACCESS) }) match stdio::get(stdio_id) { Ok(io) => io.handle().duplicate(0, true, c::DUPLICATE_SAME_ACCESS), Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)), } } Stdio::Raw(handle) => { RawHandle::new(handle).duplicate(0, true, c::DUPLICATE_SAME_ACCESS)"} {"_id":"doc-en-rust-028ea6fb6aca8f4353a3dc3e3a69bdd09a99367333dfe86fd776789c543a376f","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(libc)] extern crate libc; use std::process::{Command, Stdio}; use std::env; use std::io::{self, Read, Write}; #[cfg(unix)] unsafe fn without_stdio R>(f: F) -> R { let doit = |a| { let r = libc::dup(a); assert!(r >= 0); return r }; let a = doit(0); let b = doit(1); let c = doit(2); assert!(libc::close(0) >= 0); assert!(libc::close(1) >= 0); assert!(libc::close(2) >= 0); let r = f(); assert!(libc::dup2(a, 0) >= 0); assert!(libc::dup2(b, 1) >= 0); assert!(libc::dup2(c, 2) >= 0); return r } #[cfg(windows)] unsafe fn without_stdio R>(f: F) -> R { type DWORD = u32; type HANDLE = *mut u8; type BOOL = i32; const STD_INPUT_HANDLE: DWORD = -10i32 as DWORD; const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD; const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD; const INVALID_HANDLE_VALUE: HANDLE = !0 as HANDLE; extern \"system\" { fn GetStdHandle(which: DWORD) -> HANDLE; fn SetStdHandle(which: DWORD, handle: HANDLE) -> BOOL; } let doit = |id| { let handle = GetStdHandle(id); assert!(handle != INVALID_HANDLE_VALUE); assert!(SetStdHandle(id, INVALID_HANDLE_VALUE) != 0); return handle }; let a = doit(STD_INPUT_HANDLE); let b = doit(STD_OUTPUT_HANDLE); let c = doit(STD_ERROR_HANDLE); let r = f(); let doit = |id, handle| { assert!(SetStdHandle(id, handle) != 0); }; doit(STD_INPUT_HANDLE, a); doit(STD_OUTPUT_HANDLE, b); doit(STD_ERROR_HANDLE, c); return r } fn main() { if env::args().len() > 1 { println!(\"test\"); assert!(io::stdout().write(b\"testn\").is_ok()); assert!(io::stderr().write(b\"testn\").is_ok()); assert_eq!(io::stdin().read(&mut [0; 10]).unwrap(), 0); return } // First, make sure reads/writes without stdio work if stdio itself is // missing. let (a, b, c) = unsafe { without_stdio(|| { let a = io::stdout().write(b\"testn\"); let b = io::stderr().write(b\"testn\"); let c = io::stdin().read(&mut [0; 10]); (a, b, c) }) }; assert_eq!(a.unwrap(), 5); assert_eq!(b.unwrap(), 5); assert_eq!(c.unwrap(), 0); // Second, spawn a child and do some work with \"null\" descriptors to make // sure it's ok let me = env::current_exe().unwrap(); let status = Command::new(&me) .arg(\"next\") .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .status().unwrap(); assert!(status.success(), \"{:?} isn't a success\", status); // Finally, close everything then spawn a child to make sure everything is // *still* ok. let status = unsafe { without_stdio(|| Command::new(&me).arg(\"next\").status()) }.unwrap(); assert!(status.success(), \"{:?} isn't a success\", status); } "} {"_id":"doc-en-rust-26de3772cd678f1e2b3c357b27f7e0ae0f6a5510ea4fff1e05ef4de01a82ee61","title":"","text":"repair, or remove installation\" page and ensure \"Add to PATH\" is installed on the local hard drive. Rust does not do its own linking, and so you’ll need to have a linker installed. Doing so will depend on your specific system, consult its documentation for more details. If not, there are a number of places where we can get help. The easiest is [the #rust IRC channel on irc.mozilla.org][irc], which we can access through [Mibbit][mibbit]. Click that link, and we'll be chatting with other Rustaceans"} {"_id":"doc-en-rust-2aee2c541d7ce81ddb1afe129b06914cb6acbfea4f2859b705f5e73ce896e467","title":"","text":"[expect]: ../std/option/enum.Option.html#method.expect [panic]: error-handling.html If we leave off calling these two methods, our program will compile, but If we leave off calling this method, our program will compile, but we’ll get a warning: ```bash"} {"_id":"doc-en-rust-f582056ed1cde8e9e1c235851695f5513cb02ceb1c2dcc47996c3e1fe2c1d133","title":"","text":"} ``` The new three lines: The new two lines: ```rust,ignore let guess: u32 = guess.trim().parse()"} {"_id":"doc-en-rust-a482422ed8a19cdf4278f5dd15bedaf45ad172c9ca59decb3fdc835eeece68f4","title":"","text":"/// // got a false, take_while() isn't used any more /// assert_eq!(iter.next(), None); /// ``` /// /// Because `take_while()` needs to look at the value in order to see if it /// should be included or not, consuming iterators will see that it is /// removed: /// /// ``` /// let a = [1, 2, 3, 4]; /// let mut iter = a.into_iter(); /// /// let result: Vec = iter.by_ref() /// .take_while(|n| **n != 3) /// .cloned() /// .collect(); /// /// assert_eq!(result, &[1, 2]); /// /// let result: Vec = iter.cloned().collect(); /// /// assert_eq!(result, &[4]); /// ``` /// /// The `3` is no longer there, because it was consumed in order to see if /// the iteration should stop, but wasn't placed back into the iterator or /// some similar thing. #[inline] #[stable(feature = \"rust1\", since = \"1.0.0\")] fn take_while

(self, predicate: P) -> TakeWhile where"} {"_id":"doc-en-rust-50ce1d9db8285766b8ba24a9d8f5e3936f442126ac0d100b9b59c1aa30aa483f","title":"","text":"run_lints!(cx, check_item, late_passes, it); cx.visit_ids(|v| v.visit_item(it)); hir_visit::walk_item(cx, it); run_lints!(cx, check_item_post, late_passes, it); }) }"} {"_id":"doc-en-rust-f54e9d6e2df47a9881b8318482ffcc780064def6d71bafd0519b33bbb9bf8126","title":"","text":"fn visit_block(&mut self, b: &hir::Block) { run_lints!(self, check_block, late_passes, b); hir_visit::walk_block(self, b); run_lints!(self, check_block_post, late_passes, b); } fn visit_arm(&mut self, a: &hir::Arm) {"} {"_id":"doc-en-rust-5ca167bf9327db5cef394580410f3b57c95521b53c1462fef32c2811c6487bfd","title":"","text":"run_lints!(cx, check_item, early_passes, it); cx.visit_ids(|v| v.visit_item(it)); ast_visit::walk_item(cx, it); run_lints!(cx, check_item_post, early_passes, it); }) }"} {"_id":"doc-en-rust-137932b32ff0c6f0d2d11734538d82203259d9890a9c323fa50270beec1c15b2","title":"","text":"fn visit_block(&mut self, b: &ast::Block) { run_lints!(self, check_block, early_passes, b); ast_visit::walk_block(self, b); run_lints!(self, check_block_post, early_passes, b); } fn visit_arm(&mut self, a: &ast::Arm) {"} {"_id":"doc-en-rust-3c12f952c9d55e9e36dd347e88a36a205bb28413d7a703a6e2100685dff3bc4f","title":"","text":"run_lints!(cx, check_crate, late_passes, krate); hir_visit::walk_crate(cx, krate); run_lints!(cx, check_crate_post, late_passes, krate); }); // If we missed any lints added to the session, then there's a bug somewhere"} {"_id":"doc-en-rust-754a55dbe08bc4a174e942e3218ef7ea1a028a19cdc7d46551790394755aa3cd","title":"","text":"run_lints!(cx, check_crate, early_passes, krate); ast_visit::walk_crate(cx, krate); run_lints!(cx, check_crate_post, early_passes, krate); }); // Put the lint store back in the session."} {"_id":"doc-en-rust-f50b4c07fac902455c158062996d1f20208ed3cd6764920ead25e3bcb149537e","title":"","text":"pub trait LateLintPass: LintPass { fn check_name(&mut self, _: &LateContext, _: Span, _: ast::Name) { } fn check_crate(&mut self, _: &LateContext, _: &hir::Crate) { } fn check_crate_post(&mut self, _: &LateContext, _: &hir::Crate) { } fn check_mod(&mut self, _: &LateContext, _: &hir::Mod, _: Span, _: ast::NodeId) { } fn check_foreign_item(&mut self, _: &LateContext, _: &hir::ForeignItem) { } fn check_item(&mut self, _: &LateContext, _: &hir::Item) { } fn check_item_post(&mut self, _: &LateContext, _: &hir::Item) { } fn check_local(&mut self, _: &LateContext, _: &hir::Local) { } fn check_block(&mut self, _: &LateContext, _: &hir::Block) { } fn check_block_post(&mut self, _: &LateContext, _: &hir::Block) { } fn check_stmt(&mut self, _: &LateContext, _: &hir::Stmt) { } fn check_arm(&mut self, _: &LateContext, _: &hir::Arm) { } fn check_pat(&mut self, _: &LateContext, _: &hir::Pat) { }"} {"_id":"doc-en-rust-7a23e3f0611bbf4011dccc24544be993c4a3a8a117d4365d04bedbe454d496ac","title":"","text":"pub trait EarlyLintPass: LintPass { fn check_ident(&mut self, _: &EarlyContext, _: Span, _: ast::Ident) { } fn check_crate(&mut self, _: &EarlyContext, _: &ast::Crate) { } fn check_crate_post(&mut self, _: &EarlyContext, _: &ast::Crate) { } fn check_mod(&mut self, _: &EarlyContext, _: &ast::Mod, _: Span, _: ast::NodeId) { } fn check_foreign_item(&mut self, _: &EarlyContext, _: &ast::ForeignItem) { } fn check_item(&mut self, _: &EarlyContext, _: &ast::Item) { } fn check_item_post(&mut self, _: &EarlyContext, _: &ast::Item) { } fn check_local(&mut self, _: &EarlyContext, _: &ast::Local) { } fn check_block(&mut self, _: &EarlyContext, _: &ast::Block) { } fn check_block_post(&mut self, _: &EarlyContext, _: &ast::Block) { } fn check_stmt(&mut self, _: &EarlyContext, _: &ast::Stmt) { } fn check_arm(&mut self, _: &EarlyContext, _: &ast::Arm) { } fn check_pat(&mut self, _: &EarlyContext, _: &ast::Pat) { }"} {"_id":"doc-en-rust-05794d08531f79a61c28863dd98520c274ceb6e974f5b783c286d6975ea35b5f","title":"","text":"tmp } /// Variant of read_and_zero that writes the specific drop-flag byte /// (which may be more appropriate than zero). #[allow(missing_docs)] #[inline(always)] #[unstable(feature = \"filling_drop\", reason = \"may play a larger role in std::ptr future extensions\","} {"_id":"doc-en-rust-a824613b3215dd37aeb9fa0bffcf38d7c334edd2418da6cc3b8688d153934b0c","title":"","text":"use prelude::v1::*; use cmp; use ffi::{CStr, CString}; use fmt; use io::{self, Error, ErrorKind};"} {"_id":"doc-en-rust-2d0578296c8337e421d4804be3940bf95a62c077e2947b778838014e06c4f77d","title":"","text":"} pub fn write(&self, buf: &[u8]) -> io::Result { let len = cmp::min(buf.len(), ::max_value() as usize) as wrlen_t; let ret = try!(cvt(unsafe { c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, buf.len() as wrlen_t, len, 0) })); Ok(ret as usize)"} {"_id":"doc-en-rust-33ece65ce1bde9563358e4565b76dd836ad5a4e5b39666fd878e0116daaafae1","title":"","text":"pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() }; let mut addrlen = mem::size_of_val(&storage) as c::socklen_t; let len = cmp::min(buf.len(), ::max_value() as usize) as wrlen_t; let n = try!(cvt(unsafe { c::recvfrom(*self.inner.as_inner(), buf.as_mut_ptr() as *mut c_void, buf.len() as wrlen_t, 0, len, 0, &mut storage as *mut _ as *mut _, &mut addrlen) })); Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize)))) } pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result { let len = cmp::min(buf.len(), ::max_value() as usize) as wrlen_t; let (dstp, dstlen) = dst.into_inner(); let ret = try!(cvt(unsafe { c::sendto(*self.inner.as_inner(), buf.as_ptr() as *const c_void, buf.len() as wrlen_t, buf.as_ptr() as *const c_void, len, 0, dstp, dstlen) })); Ok(ret as usize)"} {"_id":"doc-en-rust-9202ff78fd59f34017409006f251b923474d9490a4c1fb916e4d50c77c91823a","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. use cmp; use io; use libc::{c_int, c_void}; use mem;"} {"_id":"doc-en-rust-e7d814148def1361119c101aaa22d0657b69ee7acbba2aebc180727c49fd24e8","title":"","text":"pub fn read(&self, buf: &mut [u8]) -> io::Result { // On unix when a socket is shut down all further reads return 0, so we // do the same on windows to map a shut down socket to returning EOF. let len = cmp::min(buf.len(), i32::max_value() as usize) as i32; unsafe { match c::recv(self.0, buf.as_mut_ptr() as *mut c_void, buf.len() as i32, 0) { match c::recv(self.0, buf.as_mut_ptr() as *mut c_void, len, 0) { -1 if c::WSAGetLastError() == c::WSAESHUTDOWN => Ok(0), -1 => Err(last_error()), n => Ok(n as usize)"} {"_id":"doc-en-rust-2ddcdc59ae146e34d046c59a162d075221009031d9afc657784d4803d3777244","title":"","text":"// Define the name or return the existing binding if there is a collision. pub fn try_define_child(&self, name: Name, ns: Namespace, binding: NameBinding<'a>) -> Result<(), &'a NameBinding<'a>> { if self.resolutions.borrow_state() != ::std::cell::BorrowState::Unused { return Ok(()); } self.update_resolution(name, ns, |resolution| { resolution.try_define(self.arenas.alloc_name_binding(binding)) })"} {"_id":"doc-en-rust-2ec7962c1fb5fcd0f965c11528f818cb5b51f4e82493667570acf2e3becdfa5d","title":"","text":"fn update_resolution(&self, name: Name, ns: Namespace, update: F) -> T where F: FnOnce(&mut NameResolution<'a>) -> T { let mut resolution = &mut *self.resolution(name, ns).borrow_mut(); let was_known = resolution.binding().is_some(); let t = update(resolution); if !was_known { if let Some(binding) = resolution.binding() { self.define_in_glob_importers(name, ns, binding); // Ensure that `resolution` isn't borrowed during `define_in_glob_importers`, // where it might end up getting re-defined via a glob cycle. let (new_binding, t) = { let mut resolution = &mut *self.resolution(name, ns).borrow_mut(); let was_known = resolution.binding().is_some(); let t = update(resolution); if was_known { return t; } match resolution.binding() { Some(binding) => (binding, t), None => return t, } } }; self.define_in_glob_importers(name, ns, new_binding); t }"} {"_id":"doc-en-rust-0581ef0de325b64cc5d84b02a21e4f64f43c2722a396800fa693a4a58110eda3","title":"","text":"// Add to target_module's glob_importers target_module.glob_importers.borrow_mut().push((module_, directive)); for (&(name, ns), resolution) in target_module.resolutions.borrow().iter() { if let Some(binding) = resolution.borrow().binding() { if binding.defined_with(DefModifiers::IMPORTABLE | DefModifiers::PUBLIC) { let _ = module_.try_define_child(name, ns, directive.import(binding, None)); } // Ensure that `resolutions` isn't borrowed during `try_define_child`, // since it might get updated via a glob cycle. let bindings = target_module.resolutions.borrow().iter().filter_map(|(name, resolution)| { resolution.borrow().binding().map(|binding| (*name, binding)) }).collect::>(); for ((name, ns), binding) in bindings { if binding.defined_with(DefModifiers::IMPORTABLE | DefModifiers::PUBLIC) { let _ = module_.try_define_child(name, ns, directive.import(binding, None)); } }"} {"_id":"doc-en-rust-02a5f3e412be980f717be01321602bd695a96139fac82ad489c6773aedc0f0bb","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. mod foo { pub use bar::*; pub use main as f; //~ ERROR has already been imported } mod bar { pub use foo::*; } pub use foo::*; pub use baz::*; //~ ERROR has already been imported mod baz { pub use super::*; } pub fn main() {} "} {"_id":"doc-en-rust-36091a81d861407b2f7843e0cf34c2c010159f0504dad8d8876c2d52d4a3f9c2","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub use bar::*; mod bar { pub use super::*; } pub use baz::*; //~ ERROR already been imported mod baz { pub use main as f; } pub fn main() {} "} {"_id":"doc-en-rust-ca5427edaaf18e0084c72ff9aff409e5ef061c1c05c1d0b08f052edafd7190b0","title":"","text":" // Test to ensure that trait bounds are propertly // checked on specializable associated types #![allow(incomplete_features)] #![feature(specialization)] trait UncheckedCopy: Sized { type Output: From + Copy + Into; } impl UncheckedCopy for T { default type Output = Self; //~^ ERROR: the trait bound `T: Copy` is not satisfied } fn unchecked_copy(other: &T::Output) -> T { (*other).into() } fn bug(origin: String) { // Turn the String into it's Output type... // Which we can just do by `.into()`, the assoc type states `From`. let origin_output = origin.into(); // Make a copy of String::Output, which is a String... let mut copy: String = unchecked_copy::(&origin_output); // Turn the Output type into a String again, // Which we can just do by `.into()`, the assoc type states `Into`. let mut origin: String = origin_output.into(); // assert both Strings use the same buffer. assert_eq!(copy.as_ptr(), origin.as_ptr()); // Any use of the copy we made becomes invalid, drop(origin); // OH NO! UB UB UB UB! copy.push_str(\" world!\"); println!(\"{}\", copy); } fn main() { bug(String::from(\"hello\")); } "} {"_id":"doc-en-rust-2f7c82e1121b44f8c50211ef9b8ceeb3aa29225e7e76313d3926f966aa63707d","title":"","text":" error[E0277]: the trait bound `T: Copy` is not satisfied --> $DIR/issue-33017.rs:12:5 | LL | type Output: From + Copy + Into; | ---- required by this bound in `UncheckedCopy::Output` ... LL | default type Output = Self; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `T` | help: consider restricting type parameter `T` | LL | impl UncheckedCopy for T { | ^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-a60b3f03323e196ecb04420a867e8b64b497062c66e0d7f93fb6dcf71f2ce53d","title":"","text":" #![allow(incomplete_features)] #![feature(const_generics)] #![feature(const_evaluatable_checked)] #![feature(specialization)] pub trait Trait { type Type; } impl Trait for T { default type Type = [u8; 1]; } impl Trait for *const T { type Type = [u8; std::mem::size_of::<::Type>()]; //~^ ERROR: unconstrained generic constant } fn main() {} "} {"_id":"doc-en-rust-dcd73cf38605f5d4ad8d7798e9784cfc16c8f6c372945d9f7681ac2ec5a754eb","title":"","text":" error: unconstrained generic constant --> $DIR/issue-51892.rs:15:5 | LL | type Type = [u8; std::mem::size_of::<::Type>()]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: try adding a `where` bound using this expression: `where [(); std::mem::size_of::<::Type>()]:` error: aborting due to previous error "} {"_id":"doc-en-rust-1e85c953e0b7aba2aa42befaafa6eb67adfc022a22da6c3b042da52093bbbaf9","title":"","text":"Ok(()) } fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink) -> fmt::Result { if let Some(s) = item.doc_value() { let markdown = if s.contains('n') { format!(\"{} [Read more]({})\", &plain_summary_line(Some(s)), naive_assoc_href(item, link)) } else { format!(\"{}\", &plain_summary_line(Some(s))) }; write!(w, \"

{}
\", Markdown(&markdown))?; } Ok(()) } fn item_module(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, items: &[clean::Item]) -> fmt::Result { document(w, cx, item)?;"} {"_id":"doc-en-rust-55ae39679947601bec10e3fb4aac508854903ac6fab018ff1628943ba435e8fa","title":"","text":"} fn doctraititem(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, link: AssocItemLink, render_static: bool, is_default_item: bool, outer_version: Option<&str>) -> fmt::Result { link: AssocItemLink, render_static: bool, is_default_item: bool, outer_version: Option<&str>, trait_: Option<&clean::Trait>) -> fmt::Result { let shortty = shortty(item); let name = item.name.as_ref().unwrap();"} {"_id":"doc-en-rust-788245b218cbccc42e40ba7c2142204adbf9f4ec0da107aabdd87ac6aab86aa8","title":"","text":"_ => panic!(\"can't make docs for trait item with name {:?}\", item.name) } if !is_default_item && (!is_static || render_static) { document(w, cx, item) } else { Ok(()) if !is_static || render_static { if !is_default_item { if item.doc_value().is_some() { document(w, cx, item)?; } else { // In case the item isn't documented, // provide short documentation from the trait if let Some(t) = trait_ { if let Some(it) = t.items.iter() .find(|i| i.name == item.name) { document_short(w, it, link)?; } } } } else { document_short(w, item, link)?; } } Ok(()) } let traits = &cache().traits; let trait_ = i.trait_did().and_then(|did| traits.get(&did)); write!(w, \"
\")?; for trait_item in &i.inner_impl().items { doctraititem(w, cx, trait_item, link, render_header, false, outer_version)?; doctraititem(w, cx, trait_item, link, render_header, false, outer_version, trait_)?; } fn render_default_items(w: &mut fmt::Formatter,"} {"_id":"doc-en-rust-22fd2e41322e0382ed825f04e6a8cfdceb0de95d7253059f6eefdb632239a870","title":"","text":"let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods); doctraititem(w, cx, trait_item, assoc_link, render_static, true, outer_version)?; outer_version, None)?; } Ok(()) } // If we've implemented a trait, then also emit documentation for all // default items which weren't overridden in the implementation block. if let Some(did) = i.trait_did() { if let Some(t) = cache().traits.get(&did) { render_default_items(w, cx, t, &i.inner_impl(), render_header, outer_version)?; } if let Some(t) = trait_ { render_default_items(w, cx, t, &i.inner_impl(), render_header, outer_version)?; } write!(w, \"
\")?; Ok(())"} {"_id":"doc-en-rust-81d651e1dc5b87a64189b437443e094860a340eb64d0c1c090b1e19451300400","title":"","text":"fn b_method(&self) -> usize { self.a_method() } /// Docs associated with the trait c_method definition. /// /// There is another line fn c_method(&self) -> usize { self.a_method() } } // @has manual_impl/struct.S1.html '//*[@class=\"trait\"]' 'T' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the S1 trait implementation.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the S1 trait a_method implementation.' // @!has - '//*[@class=\"docblock\"]' 'Docs associated with the trait a_method definition.' // @!has - '//*[@class=\"docblock\"]' 'Docs associated with the trait b_method definition.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the trait b_method definition.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the trait b_method definition.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the trait c_method definition.' // @!has - '//*[@class=\"docblock\"]' 'There is another line' // @has - '//*[@class=\"docblock\"]' 'Read more' pub struct S1(usize); /// Docs associated with the S1 trait implementation."} {"_id":"doc-en-rust-5518394ab2a5be64af9da3a95da7385fda01eb525e926b13595f93eff8e494a5","title":"","text":"// @has manual_impl/struct.S2.html '//*[@class=\"trait\"]' 'T' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the S2 trait implementation.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the S2 trait a_method implementation.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the S2 trait b_method implementation.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the S2 trait c_method implementation.' // @!has - '//*[@class=\"docblock\"]' 'Docs associated with the trait a_method definition.' // @!has - '//*[@class=\"docblock\"]' 'Docs associated with the trait b_method definition.' // @!has - '//*[@class=\"docblock\"]' 'Docs associated with the trait c_method definition.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the trait b_method definition.' // @!has - '//*[@class=\"docblock\"]' 'Read more' pub struct S2(usize); /// Docs associated with the S2 trait implementation."} {"_id":"doc-en-rust-20a95cf5f3ec40863dab199c2720b55f92ea67336161ab59f3242bfc97a64655","title":"","text":"self.0 } /// Docs associated with the S2 trait b_method implementation. fn b_method(&self) -> usize { /// Docs associated with the S2 trait c_method implementation. fn c_method(&self) -> usize { 5 } }"} {"_id":"doc-en-rust-eee5a7d43ac2bf72fbc04552ba84ac5e9ed8a7153671f222cb0d244b3c043b99","title":"","text":"// @has manual_impl/struct.S3.html '//*[@class=\"trait\"]' 'T' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the S3 trait implementation.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the S3 trait b_method implementation.' // @!has - '//*[@class=\"docblock\"]' 'Docs associated with the trait a_method definition.' // @has - '//*[@class=\"docblock\"]' 'Docs associated with the trait a_method definition.' pub struct S3(usize); /// Docs associated with the S3 trait implementation."} {"_id":"doc-en-rust-2eeee177e5d37fe98622e8bc3273748265e1272d8d8172e66fdc2562674a40d7","title":"","text":"use super::FnCtxt; use hir::def_id::DefId; use rustc::ty::{Ty, TypeFoldable, PreferMutLvalue}; use rustc::ty::{Ty, TypeFoldable, PreferMutLvalue, TypeVariants}; use rustc::infer::type_variable::TypeVariableOrigin; use syntax::ast; use syntax::symbol::Symbol;"} {"_id":"doc-en-rust-40bcda27da7e54a55a21ca21afc9a721ab0078dd7f3de69e08f789b7b667c67c","title":"","text":"\"binary operation `{}` cannot be applied to type `{}`\", op.node.as_str(), lhs_ty); if let TypeVariants::TyRef(_, ref ty_mut) = lhs_ty.sty { if !self.infcx.type_moves_by_default(ty_mut.ty, lhs_expr.span) && self.lookup_op_method(expr, ty_mut.ty, vec![rhs_ty_var], Symbol::intern(name), trait_def_id, lhs_expr).is_ok() { err.span_note( lhs_expr.span, &format!( \"this is a reference of type that `{}` can be applied to, you need to dereference this variable once for this operation to work\", op.node.as_str())); } } let missing_trait = match op.node { hir::BiAdd => Some(\"std::ops::Add\"), hir::BiSub => Some(\"std::ops::Sub\"),"} {"_id":"doc-en-rust-911da902aa7268ef7596cf03eb3f9954e1d65f906b41b8106f12062a6482858a","title":"","text":" // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; let vr = v.iter().filter(|x| { x % 2 == 0 //~^ ERROR binary operation `%` cannot be applied to type `&&{integer}` //~| NOTE this is a reference of type that `%` can be applied to //~| NOTE an implementation of `std::ops::Rem` might be missing for `&&{integer}` }); println!(\"{:?}\", vr); } "} {"_id":"doc-en-rust-b7feb2dd1a986cbe3f9ce7d1be3c2f11d40db6b556aa51cc8ca00fae295f1b0b","title":"","text":" // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let a: &String = &\"1\".to_owned(); let b: &str = &\"2\"; let c = a + b; //~^ ERROR binary operation `+` cannot be applied to type `&std::string::String` //~| NOTE an implementation of `std::ops::Add` might be missing for `&std::string::String` println!(\"{:?}\", c); } "} {"_id":"doc-en-rust-3c751521c069dbf8203c1333e608c36d992d83c87fe0eb3bf2d67ebade2b0dde","title":"","text":"// Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = self.borrow.get(); debug_assert!(borrow != WRITING && borrow != UNUSED); debug_assert!(borrow != UNUSED); // Prevent the borrow counter from overflowing. assert!(borrow != WRITING); self.borrow.set(borrow + 1); BorrowRef { borrow: self.borrow } }"} {"_id":"doc-en-rust-833563be1e27ba43ea1edf389e3c88451cb9b1ddcaabbca995c1cd611a6dca41","title":"","text":"the compiler. They are accessible via the `--explain` flag. Each explanation comes with an example of how to trigger it and advice on how to fix it. Please read [RFC 1567](https://github.com/rust-lang/rfcs/blob/master/text/1567-long-error-codes-explanation-normalization.md) for details on how to format and write long error codes. * All of them are accessible [online](http://doc.rust-lang.org/error-index.html), which are auto-generated from rustc source code in different places: [librustc](https://github.com/rust-lang/rust/blob/master/src/librustc/diagnostics.rs), [libsyntax](https://github.com/rust-lang/rust/blob/master/src/libsyntax/diagnostics.rs), [librustc_borrowck](https://github.com/rust-lang/rust/blob/master/src/librustc_borrowck/diagnostics.rs), [librustc_const_eval](https://github.com/rust-lang/rust/blob/master/src/librustc_const_eval/diagnostics.rs), [librustc_lint](https://github.com/rust-lang/rust/blob/master/src/librustc_lint/types.rs), [librustc_metadata](https://github.com/rust-lang/rust/blob/master/src/librustc_metadata/diagnostics.rs), [librustc_mir](https://github.com/rust-lang/rust/blob/master/src/librustc_mir/diagnostics.rs), [librustc_passes](https://github.com/rust-lang/rust/blob/master/src/librustc_passes/diagnostics.rs), [librustc_privacy](https://github.com/rust-lang/rust/blob/master/src/librustc_privacy/diagnostics.rs), [librustc_resolve](https://github.com/rust-lang/rust/blob/master/src/librustc_resolve/diagnostics.rs), [librustc_trans](https://github.com/rust-lang/rust/blob/master/src/librustc_trans/diagnostics.rs), [librustc_plugin](https://github.com/rust-lang/rust/blob/master/src/librustc_plugin/diagnostics.rs), [librustc_typeck](https://github.com/rust-lang/rust/blob/master/src/librustc_typeck/diagnostics.rs). * Explanations have full markdown support. Use it, especially to highlight code with backticks."} {"_id":"doc-en-rust-9cb6d5a91afb4ea45ae9d6bb1c96aab96c1cc336b1ac77372d42d24bb2e2e435","title":"","text":"* Flags should be orthogonal to each other. For example, if we'd have a json-emitting variant of multiple actions `foo` and `bar`, an additional --json flag is better than adding `--foo-json` and `--bar-json`. * Always give options a long descriptive name, if only for better * Always give options a long descriptive name, if only for more understandable compiler scripts. * The `--verbose` flag is for adding verbose information to `rustc` output when not compiling a program. For example, using it with the `--version` flag"} {"_id":"doc-en-rust-40f25d5d4ec605faffb691cbc734f0f1fcd713089cae12f59f6e6dce30adb304","title":"","text":"let mut base = self; let mut acc = 1; let mut prev_base = self; let mut base_oflo = false; while exp > 0 { while exp > 1 { if (exp & 1) == 1 { if base_oflo { // ensure overflow occurs in the same manner it // would have otherwise (i.e. signal any exception // it would have otherwise). acc = acc * (prev_base * prev_base); } else { acc = acc * base; } acc = acc * base; } prev_base = base; let (new_base, new_base_oflo) = base.overflowing_mul(base); base = new_base; base_oflo = new_base_oflo; exp /= 2; base = base * base; } // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { acc = acc * base; } acc }"} {"_id":"doc-en-rust-25de414261b95ecc468b45e0652f27cedf2748002401d733d5b5f1e140032107","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:thread 'main' panicked at 'attempt to multiply with overflow' // compile-flags: -C debug-assertions fn main() { let _x = 2i32.pow(1024); } "} {"_id":"doc-en-rust-c0e5b51e07d0268b2b409a33a39184423c4cdcb72795fd2bc8c566bb33428a7b","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:thread 'main' panicked at 'attempt to multiply with overflow' // compile-flags: -C debug-assertions fn main() { let _x = 2u32.pow(1024); } "} {"_id":"doc-en-rust-ab3835b087aaff909b6f2ea083744e5b914961e7c71d67f448ca3f6e81774506","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:thread 'main' panicked at 'attempt to multiply with overflow' // compile-flags: -C debug-assertions fn main() { let _x = 2i32.pow(1024); } "} {"_id":"doc-en-rust-c0c7f9729c8044c344734bce9a2237ca864a8c5c8c4e027fa86fad434a0ba0d2","title":"","text":"// each trait in the system to its implementations. use metadata::csearch::{each_impl, get_impl_trait}; use metadata::csearch::{each_impl, get_impl_trait, each_implementation_for_trait}; use metadata::csearch; use middle::ty::get; use middle::ty::{ImplContainer, lookup_item_type, subst};"} {"_id":"doc-en-rust-2edbee47bca8cc8274d00e6e68c2ffd8589a27f3c9a9769c7f86699faeb195f3","title":"","text":"pub fn check_implementation_coherence_of(&self, trait_def_id: DefId) { // Unify pairs of polytypes. self.iter_impls_of_trait(trait_def_id, |a| { self.iter_impls_of_trait_local(trait_def_id, |a| { let implementation_a = a; let polytype_a = self.get_self_type_for_implementation(implementation_a);"} {"_id":"doc-en-rust-d652db6d0e36e6786eca54639948a6de9efa6dc7553fb2f3f3dc80cf58d89dd4","title":"","text":"if self.polytypes_unify(polytype_a.clone(), polytype_b) { let session = self.crate_context.tcx.sess; session.span_err( self.span_of_impl(implementation_b), self.span_of_impl(implementation_a), format!(\"conflicting implementations for trait `{}`\", ty::item_path_str(self.crate_context.tcx, trait_def_id))); session.span_note(self.span_of_impl(implementation_a), \"note conflicting implementation here\"); if implementation_b.did.crate == LOCAL_CRATE { session.span_note(self.span_of_impl(implementation_b), \"note conflicting implementation here\"); } else { let crate_store = self.crate_context.tcx.sess.cstore; let cdata = crate_store.get_crate_data(implementation_b.did.crate); session.note( \"conflicting implementation in crate `\" + cdata.name + \"`\"); } } } })"} {"_id":"doc-en-rust-57766293cad0d0e83358f5599b3f6cd3b14de53543601dc42eaef4058e725f7e","title":"","text":"} pub fn iter_impls_of_trait(&self, trait_def_id: DefId, f: |@Impl|) { self.iter_impls_of_trait_local(trait_def_id, |x| f(x)); if trait_def_id.crate == LOCAL_CRATE { return; } let crate_store = self.crate_context.tcx.sess.cstore; csearch::each_implementation_for_trait(crate_store, trait_def_id, |impl_def_id| { let implementation = @csearch::get_impl(self.crate_context.tcx, impl_def_id); let _ = lookup_item_type(self.crate_context.tcx, implementation.did); f(implementation); }); } pub fn iter_impls_of_trait_local(&self, trait_def_id: DefId, f: |@Impl|) { let trait_impls = self.crate_context.tcx.trait_impls.borrow(); match trait_impls.get().find(&trait_def_id) { Some(impls) => {"} {"_id":"doc-en-rust-22266463a75cef8c2aedf4962b19664d1bc028a22ae7f4e31c844ae895e310aa","title":"","text":" // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait Foo { } impl Foo for int { } "} {"_id":"doc-en-rust-f0f1e83ed8fc0e2f7fa99ace56e1dc8c12ec0c283af51cfe8f075fb8311dadd2","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for #3512 - conflicting trait impls in different crates should give a // 'conflicting implementations' error message. // aux-build:trait_impl_conflict.rs extern mod trait_impl_conflict; use trait_impl_conflict::Foo; impl
Foo for A { //~^ ERROR conflicting implementations for trait `trait_impl_conflict::Foo` //~^^ ERROR cannot provide an extension implementation where both trait and type are not defined in this crate } fn main() { } "} {"_id":"doc-en-rust-4c63558cc9d3a7d49de2099dde6fed65293235d399582099d4ea5d910ad53337","title":"","text":"let &(ref first_arm_pats, _) = &arms[0]; let first_pat = &first_arm_pats[0]; let span = first_pat.span; span_err!(cx.tcx.sess, span, E0165, \"irrefutable while-let pattern\"); struct_span_err!(cx.tcx.sess, span, E0165, \"irrefutable while-let pattern\") .span_label(span, &format!(\"irrefutable pattern\")) .emit(); }, hir::MatchSource::ForLoopDesugar => {"} {"_id":"doc-en-rust-8b08f0d27415a104fa48b934f0765a0355d43ca6fc67afd713dc36a5a957c834","title":"","text":"tcx.sess.add_lint(lint::builtin::MATCH_OF_UNIT_VARIANT_VIA_PAREN_DOTDOT, pat.id, pat.span, msg); } else { span_err!(tcx.sess, pat.span, E0164, \"{}\", msg); struct_span_err!(tcx.sess, pat.span, E0164, \"{}\", msg) .span_label(pat.span, &format!(\"not a tuple variant or struct\")).emit(); on_error(); } };"} {"_id":"doc-en-rust-ff8270d0215ddbada1cc300e82fad9e762a3ece3b4bbee04e4bcb0dce691dc6b","title":"","text":".emit(); } Err(CopyImplementationError::HasDestructor) => { span_err!(tcx.sess, span, E0184, struct_span_err!(tcx.sess, span, E0184, \"the trait `Copy` may not be implemented for this type; the type has a destructor\"); the type has a destructor\") .span_label(span, &format!(\"Copy not allowed on types with destructors\")) .emit(); } } });"} {"_id":"doc-en-rust-89b81bc2ced1e642ad37d83220c291f95b6679f99542f755cb9e538c06b880f2","title":"","text":"fn bar(foo: Foo) -> u32 { match foo { Foo::B(i) => i, //~ ERROR E0164 //~| NOTE not a tuple variant or struct } }"} {"_id":"doc-en-rust-5ac9244c3a6c15fbdae0e13a10f6fd45a8109f654a92720dd619ed7e268a3979","title":"","text":"fn main() { let irr = Irrefutable(0); while let Irrefutable(x) = irr { //~ ERROR E0165 //~| irrefutable pattern // ... } }"} {"_id":"doc-en-rust-2c8aa37c87b67ffc2fb3043a235cfa0e3690b6a6bb14675adbdd13e85870289f","title":"","text":"// except according to those terms. #[derive(Copy)] //~ ERROR E0184 //~| NOTE Copy not allowed on types with destructors //~| NOTE in this expansion of #[derive(Copy)] struct Foo; impl Drop for Foo {"} {"_id":"doc-en-rust-592884341fb30d497dc5b58af9f9e620642125b395062590d792c2da15cb5bbe","title":"","text":"return Error(span, \"missing fragment specifier\".to_string()); } } TokenTree::MetaVarDecl(..) => { TokenTree::MetaVarDecl(_, _, id) => { // Built-in nonterminals never start with these tokens, // so we can eliminate them from consideration. match *token { token::CloseDelim(_) => {}, _ => bb_eis.push(ei), if may_begin_with(&*id.name.as_str(), token) { bb_eis.push(ei); } } seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, DocComment(..)) => {"} {"_id":"doc-en-rust-bfec328db0155d500fac5884264b1c54a94fcb3b40409b1aea2abe7833398e6e","title":"","text":"} } /// Checks whether a non-terminal may begin with a particular token. /// /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with that /// token. Be conservative (return true) if not sure. fn may_begin_with(name: &str, token: &Token) -> bool { /// Checks whether the non-terminal may contain a single (non-keyword) identifier. fn may_be_ident(nt: &token::Nonterminal) -> bool { match *nt { token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) => false, _ => true, } } match name { \"expr\" => token.can_begin_expr(), \"ty\" => token.can_begin_type(), \"ident\" => token.is_ident(), \"vis\" => match *token { // The follow-set of :vis + \"priv\" keyword + interpolated Token::Comma | Token::Ident(_) | Token::Interpolated(_) => true, _ => token.can_begin_type(), }, \"block\" => match *token { Token::OpenDelim(token::Brace) => true, Token::Interpolated(ref nt) => match nt.0 { token::NtItem(_) | token::NtPat(_) | token::NtTy(_) | token::NtIdent(_) | token::NtMeta(_) | token::NtPath(_) | token::NtVis(_) => false, // none of these may start with '{'. _ => true, }, _ => false, }, \"path\" | \"meta\" => match *token { Token::ModSep | Token::Ident(_) => true, Token::Interpolated(ref nt) => match nt.0 { token::NtPath(_) | token::NtMeta(_) => true, _ => may_be_ident(&nt.0), }, _ => false, }, \"pat\" => match *token { Token::Ident(_) | // box, ref, mut, and other identifiers (can stricten) Token::OpenDelim(token::Paren) | // tuple pattern Token::OpenDelim(token::Bracket) | // slice pattern Token::BinOp(token::And) | // reference Token::BinOp(token::Minus) | // negative literal Token::AndAnd | // double reference Token::Literal(..) | // literal Token::DotDot | // range pattern (future compat) Token::DotDotDot | // range pattern (future compat) Token::ModSep | // path Token::Lt | // path (UFCS constant) Token::BinOp(token::Shl) | // path (double UFCS) Token::Underscore => true, // placeholder Token::Interpolated(ref nt) => may_be_ident(&nt.0), _ => false, }, _ => match *token { token::CloseDelim(_) => false, _ => true, }, } } fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal { if name == \"tt\" { return token::NtTT(p.parse_token_tree());"} {"_id":"doc-en-rust-e130950d89df032312409a5bff0bb0d8d0cc74299da955820234065ca2c344d9","title":"","text":"// except according to those terms. fn main() { panic!(@); //~ ERROR expected expression, found `@` panic!(@); //~ ERROR no rules expected the token `@` }"} {"_id":"doc-en-rust-59e629907a9828b1d4b83a580ba24531a5ebd0f4286fae62b4115aba0d786525","title":"","text":"// except according to those terms. pub fn main() { vec![,]; //~ ERROR expected expression, found `,` vec![,]; //~ ERROR no rules expected the token `,` }"} {"_id":"doc-en-rust-f4fe0fd75586faba8219094f2f96f7d9ff8177dd3da2e5769daee3cd009a49ff","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(macro_vis_matcher)] //{{{ issue 40569 ============================================================== macro_rules! my_struct { ($(#[$meta:meta])* $ident:ident) => { $(#[$meta])* struct $ident; } } my_struct!(#[derive(Debug, PartialEq)] Foo40569); fn test_40569() { assert_eq!(Foo40569, Foo40569); } //}}} //{{{ issue 26444 ============================================================== macro_rules! foo_26444 { ($($beginning:ident),*; $middle:ident; $($end:ident),*) => { stringify!($($beginning,)* $middle $(,$end)*) } } fn test_26444() { assert_eq!(\"a , b , c , d , e\", foo_26444!(a, b; c; d, e)); assert_eq!(\"f\", foo_26444!(; f ;)); } macro_rules! pat_26444 { ($fname:ident $($arg:pat)* =) => {} } pat_26444!(foo 1 2 5...7 =); pat_26444!(bar Some(ref x) Ok(ref mut y) &(w, z) =); //}}} //{{{ issue 40984 ============================================================== macro_rules! thread_local_40984 { () => {}; ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => { thread_local_40984!($($rest)*); }; ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => {}; } thread_local_40984! { // no docs #[allow(unused)] static FOO: i32 = 42; /// docs pub static BAR: String = String::from(\"bar\"); // look at these restrictions!! pub(crate) static BAZ: usize = 0; pub(in foo) static QUUX: usize = 0; } //}}} //{{{ issue 35650 ============================================================== macro_rules! size { ($ty:ty) => { std::mem::size_of::<$ty>() }; ($size:tt) => { $size }; } fn test_35650() { assert_eq!(size!(u64), 8); assert_eq!(size!(5), 5); } //}}} //{{{ issue 27832 ============================================================== macro_rules! m { ( $i:ident ) => (); ( $t:tt $j:tt ) => (); } m!(c); m!(t 9); m!(0 9); m!(struct); m!(struct Foo); macro_rules! m2 { ( $b:expr ) => (); ( $t:tt $u:tt ) => (); } m2!(3); m2!(1 2); m2!(_ 1); m2!(enum Foo); //}}} //{{{ issue 39964 ============================================================== macro_rules! foo_39964 { ($a:ident) => {}; (_) => {}; } foo_39964!(_); //}}} //{{{ issue 34030 ============================================================== macro_rules! foo_34030 { ($($t:ident),* /) => {}; } foo_34030!(a, b/); foo_34030!(a/); foo_34030!(/); //}}} //{{{ issue 24189 ============================================================== macro_rules! foo_24189 { ( pub enum $name:ident { $( #[$attr:meta] )* $var:ident } ) => { pub enum $name { $( #[$attr] )* $var } }; } foo_24189! { pub enum Foo24189 { #[doc = \"Bar\"] Baz } } macro_rules! serializable { ( $(#[$struct_meta:meta])* pub struct $name:ident { $( $(#[$field_meta:meta])* $field:ident: $type_:ty ),* , } ) => { $(#[$struct_meta])* pub struct $name { $( $(#[$field_meta])* $field: $type_ ),* , } } } serializable! { #[allow(dead_code)] /// This is a test pub struct Tester { #[allow(dead_code)] name: String, } } macro_rules! foo_24189_c { ( $( > )* $x:ident ) => { }; } foo_24189_c!( > a ); fn test_24189() { let _ = Foo24189::Baz; let _ = Tester { name: \"\".to_owned() }; } //}}} //{{{ some more tests ========================================================== macro_rules! test_block { (< $($b:block)* >) => {} } test_block!(<>); test_block!(<{}>); test_block!(<{1}{2}>); macro_rules! test_ty { ($($t:ty),* $(,)*) => {} } test_ty!(); test_ty!(,); test_ty!(u8); test_ty!(u8,); macro_rules! test_path { ($($t:path),* $(,)*) => {} } test_path!(); test_path!(,); test_path!(::std); test_path!(std::u8,); test_path!(any, super, super::super::self::path, X::Z<'a, T=U>); macro_rules! test_meta_block { ($($m:meta)* $b:block) => {}; } test_meta_block!(windows {}); //}}} fn main() { test_26444(); test_40569(); test_35650(); test_24189(); } "} {"_id":"doc-en-rust-2ab8659868cb4d432b4d06877128b7d3aedf46504844771077cffaf6e829e612","title":"","text":"/// Returns the path to the C++ compiler for the target specified, may panic /// if no C++ compiler was configured for the target. fn cxx(&self, target: &str) -> &Path { self.cxx[target].path() match self.cxx.get(target) { Some(p) => p.path(), None => panic!(\"nntarget `{}` is not configured as a host, only as a targetnn\", target), } } /// Returns flags to pass to the compiler to generate code for `target`."} {"_id":"doc-en-rust-d0c7b6e6760a0f94341de49bd2ea96f5a0a5a48fc1e78f6bdb8b9ac13d9f62a6","title":"","text":"\"codegen-units\"); suite(\"check-incremental\", \"src/test/incremental\", \"incremental\", \"incremental\"); suite(\"check-ui\", \"src/test/ui\", \"ui\", \"ui\"); } if build.config.build.contains(\"msvc\") {"} {"_id":"doc-en-rust-63d61066552c9f09f8bc311a8c0fde7f5c083b3aa44ab94aed15577760419e06","title":"","text":"}); }; suite(\"check-ui\", \"src/test/ui\", \"ui\", \"ui\"); suite(\"check-rpass-full\", \"src/test/run-pass-fulldeps\", \"run-pass\", \"run-pass-fulldeps\"); suite(\"check-rfail-full\", \"src/test/run-fail-fulldeps\","} {"_id":"doc-en-rust-a9b1c088366f84feee45d9b557079a97b1437cd930e93f0c149eb84d08137550","title":"","text":"assert!(plan.iter().any(|s| s.name.contains(\"-ui\"))); assert!(plan.iter().any(|s| s.name.contains(\"cfail\"))); assert!(plan.iter().any(|s| s.name.contains(\"cfail\"))); assert!(plan.iter().any(|s| s.name.contains(\"cfail-full\"))); assert!(plan.iter().any(|s| s.name.contains(\"codegen-units\"))); assert!(plan.iter().any(|s| s.name.contains(\"debuginfo\")));"} {"_id":"doc-en-rust-d9d3fae0d6fbea44c35737d9e3a76d037009bca2d68481b2c88a7c7625faeccc","title":"","text":"assert!(plan.iter().all(|s| s.host == \"A\")); assert!(plan.iter().all(|s| s.target == \"C\")); assert!(plan.iter().any(|s| s.name.contains(\"-ui\"))); assert!(plan.iter().any(|s| s.name.contains(\"cfail\"))); assert!(!plan.iter().any(|s| s.name.contains(\"-ui\"))); assert!(plan.iter().any(|s| s.name.contains(\"cfail\"))); assert!(!plan.iter().any(|s| s.name.contains(\"cfail-full\"))); assert!(plan.iter().any(|s| s.name.contains(\"codegen-units\")));"} {"_id":"doc-en-rust-b3e229b23299343327ea42bdbcd6c3ecee4f75ff76db94a5bc158df0a3bb031d","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // no-prefer-dynamic #![crate_type = \"proc-macro\"] #![feature(proc_macro, proc_macro_lib)] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(Foo)] pub fn derive_foo(input: TokenStream) -> TokenStream { input } #[proc_macro_derive(Bar)] pub fn derive_bar(input: TokenStream) -> TokenStream { panic!(\"lolnope\"); } "} {"_id":"doc-en-rust-2a6d4ebccddc1ed6485ffea932a91eb7a0e9d78b7b391e258872ebf00f9adaed","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:plugin.rs #![feature(proc_macro)] #[macro_use] extern crate plugin; #[derive(Foo, Bar)] struct Baz { a: i32, b: i32, } fn main() {} "} {"_id":"doc-en-rust-ecf218e9334e8a852efb63b6f1880e47d1ee228186d96c74a090c6aa7ec5ef1f","title":"","text":" error: custom derive attribute panicked --> $DIR/issue-36935.rs:17:15 | 17 | #[derive(Foo, Bar)] | ^^^ | = help: message: lolnope "} {"_id":"doc-en-rust-06ce30c508fa23ce752b2b0fc794a87bfc53e0d6beff79a0544d3d2de63013c9","title":"","text":"use schema::{METADATA_HEADER, rustc_version}; use rustc::hir::svh::Svh; use rustc::session::Session; use rustc::session::{config, Session}; use rustc::session::filesearch::{FileSearch, FileMatches, FileDoesntMatch}; use rustc::session::search_paths::PathKind; use rustc::util::common;"} {"_id":"doc-en-rust-d7deb48ae998a85c50aad49d9c4f0138a61da29f8e702c5533d5de98ca0de447","title":"","text":"\"can't find crate for `{}`{}\", self.ident, add); if (self.ident == \"std\" || self.ident == \"core\") && self.triple != config::host_triple() { err.note(&format!(\"the `{}` target may not be installed\", self.triple)); } err.span_label(self.span, &format!(\"can't find crate\")); err };"} {"_id":"doc-en-rust-c545b3ece583d9e7825358abd42ce55a2a179bbdd0ac3aca7f2f499f3794894a","title":"","text":" // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Tests that compiling for a target which is not installed will result in a helpful // error message. // compile-flags: --target=s390x-unknown-linux-gnu // ignore s390x // error-pattern:target may not be installed fn main() { } "} {"_id":"doc-en-rust-235a476efe21034649b04984074d0eecc06c53585f40a63fbfd8f99dc311d335","title":"","text":"// FIXME (#9639): This needs to handle non-utf8 paths let mut args = vec![input_file.to_str().unwrap().to_owned(), \"-L\".to_owned(), self.config.build_base.to_str().unwrap().to_owned(), format!(\"--target={}\", target)]; self.config.build_base.to_str().unwrap().to_owned()]; // Optionally prevent default --target if specified in test compile-flags. let custom_target = self.props.compile_flags .iter() .fold(false, |acc, ref x| acc || x.starts_with(\"--target\")); if !custom_target { args.extend(vec![ format!(\"--target={}\", target), ]); } if let Some(revision) = self.revision { args.extend(vec!["} {"_id":"doc-en-rust-6f29eab5c4eba99c0eea6574c4adb3e0c8863a164e2dc8bb4fa6d69812af0d76","title":"","text":"use std::str; pub const MAX_BASE: u64 = 64; pub const ALPHANUMERIC_ONLY: u64 = 62; const BASE_64: &'static [u8; MAX_BASE as usize] = b\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$\";"} {"_id":"doc-en-rust-f194cd439418506fe44f4d24e56933fc5c2b39c4abbef91ebe5083661b679411","title":"","text":"let mut name = String::with_capacity(prefix.len() + 6); name.push_str(prefix); name.push_str(\".\"); base_n::push_str(idx as u64, base_n::MAX_BASE, &mut name); base_n::push_str(idx as u64, base_n::ALPHANUMERIC_ONLY, &mut name); name } }"} {"_id":"doc-en-rust-0c60f965108a0d513566a80eb3eeb6dc69f6df4804f79dd73b7f9ace7de5c10f","title":"","text":"} } #[derive(Copy, Clone)] #[derive(Copy, Clone, PartialEq)] enum PathScope { Global, Lexical,"} {"_id":"doc-en-rust-baa66de69a1108c2f80d978361c77b8154dab8bda147864dc400b08f0f688592","title":"","text":"// // Such behavior is required for backward compatibility. // The same fallback is used when `a` resolves to nothing. _ if self.primitive_type_table.primitive_types.contains_key(&path[0].name) => { PathResult::Module(..) | PathResult::Failed(..) if scope == PathScope::Lexical && (ns == TypeNS || path.len() > 1) && self.primitive_type_table.primitive_types.contains_key(&path[0].name) => { PathResolution { base_def: Def::PrimTy(self.primitive_type_table.primitive_types[&path[0].name]), depth: segments.len() - 1,"} {"_id":"doc-en-rust-bcd24b48389024dcf5f4052aad3e529bf9c4848c63289df7cc8388eb3aff3765","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { // Make sure primitive type fallback doesn't work in value namespace std::mem::size_of(u16); //~^ ERROR unresolved name `u16` //~| ERROR this function takes 0 parameters but 1 parameter was supplied // Make sure primitive type fallback doesn't work with global paths let _: ::u8; //~^ ERROR type name `u8` is undefined or not in scope } "} {"_id":"doc-en-rust-ca8415d04f000da1d431d155dcee6cde9bd092a62f1ca1598356ae42121547e6","title":"","text":"impl<'a> Resolver<'a> { fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace) -> &'a RefCell> { let ident = ident.unhygienize(); *module.resolutions.borrow_mut().entry((ident, ns)) .or_insert_with(|| self.arenas.alloc_name_resolution()) }"} {"_id":"doc-en-rust-4b5dd3ac62cfca71b55442acac5afbe69077ec04c931fb09c3df0111e18c4ff3","title":"","text":"ignore_unresolved_invocations: bool, record_used: Option) -> Result<&'a NameBinding<'a>, Determinacy> { let ident = ident.unhygienize(); self.populate_module_if_necessary(module); let resolution = self.resolution(module, ident, ns)"} {"_id":"doc-en-rust-04d6001b7ed9f321de40799c1baadfc3a915d3e5f9abe9198feee0b08527ec28","title":"","text":"ns: Namespace, binding: &'a NameBinding<'a>) -> Result<(), &'a NameBinding<'a>> { let ident = ident.unhygienize(); self.update_resolution(module, ident, ns, |this, resolution| { if let Some(old_binding) = resolution.binding { if binding.is_glob_import() {"} {"_id":"doc-en-rust-76049f8c8d7104fd9212bcf83cabab458007d2ec041d480891d2e37a47e51320","title":"","text":"view_path.map(|Spanned {node, span}| Spanned { node: match node { ViewPathSimple(ident, path) => { ViewPathSimple(ident, fld.fold_path(path)) ViewPathSimple(fld.fold_ident(ident), fld.fold_path(path)) } ViewPathGlob(path) => { ViewPathGlob(fld.fold_path(path)) } ViewPathList(path, path_list_idents) => { ViewPathList(fld.fold_path(path), path_list_idents.move_map(|path_list_ident| { Spanned { node: PathListItem_ { id: fld.new_id(path_list_ident.node.id), rename: path_list_ident.node.rename, name: path_list_ident.node.name, }, span: fld.new_span(path_list_ident.span) } })) let path = fld.fold_path(path); let path_list_idents = path_list_idents.move_map(|path_list_ident| Spanned { node: PathListItem_ { id: fld.new_id(path_list_ident.node.id), rename: path_list_ident.node.rename.map(|ident| fld.fold_ident(ident)), name: fld.fold_ident(path_list_ident.node.name), }, span: fld.new_span(path_list_ident.span) }); ViewPathList(path, path_list_idents) } }, span: fld.new_span(span)"} {"_id":"doc-en-rust-ed6cfa4c7e125b04a12b43366549cd4a666efc4c866ee05d0481b399fcc5a16f","title":"","text":"pub fn noop_fold_ty_binding(b: TypeBinding, fld: &mut T) -> TypeBinding { TypeBinding { id: fld.new_id(b.id), ident: b.ident, ident: fld.fold_ident(b.ident), ty: fld.fold_ty(b.ty), span: fld.new_span(b.span), }"} {"_id":"doc-en-rust-0b24c7d3674feecb6fc764eba08f99f7b7926edee270140f7a19d8b606506c66","title":"","text":".collect::>() .into(), id: fld.new_id(id), ident: ident, ident: fld.fold_ident(ident), bounds: fld.fold_bounds(bounds), default: default.map(|x| fld.fold_ty(x)), span: span"} {"_id":"doc-en-rust-2c3514289967299a9cafdd1a66fcbde0f5bd1db6627654cd464ffb8d57ce2982","title":"","text":"let fs = fields.move_map(|f| { Spanned { span: folder.new_span(f.span), node: ast::FieldPat { ident: f.node.ident, ident: folder.fold_ident(f.node.ident), pat: folder.fold_pat(f.node.pat), is_shorthand: f.node.is_shorthand, }}"} {"_id":"doc-en-rust-cdfefbc968bc8d7edb153aae4c5d9950acb5e3bbf7b070f79d823d4a1f577827","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct Foo; macro_rules! reexport { () => { use Foo as Bar; } } reexport!(); fn main() { use Bar; fn f(_: Bar) {} } "} {"_id":"doc-en-rust-eae0f0a641671ef3ce07a382911040394ceb946700e208b0807db78142d13562","title":"","text":"/// Sets the child process's user ID. This translates to a /// `setuid` call in the child process. Failure in the `setuid` /// call will cause the spawn to fail. /// /// # Notes /// /// This will also trigger a call to `setgroups(0, NULL)` in the child /// process if no groups have been specified. /// This removes supplementary groups that might have given the child /// unwanted permissions. #[stable(feature = \"rust1\", since = \"1.0.0\")] fn uid(&mut self, id: UserId) -> &mut process::Command;"} {"_id":"doc-en-rust-eadb004e2279ab0fcd860ca5c8672b18b5a674b7e2854b7cbe5372c99c7ba1fe","title":"","text":"if let Some(u) = self.get_uid() { // When dropping privileges from root, the `setgroups` call // will remove any extraneous groups. We only drop groups // if the current uid is 0 and we weren't given an explicit // if we have CAP_SETGID and we weren't given an explicit // set of groups. If we don't call this, then even though our // uid has dropped, we may still have groups that enable us to // do super-user things. //FIXME: Redox kernel does not support setgroups yet #[cfg(not(target_os = \"redox\"))] if libc::getuid() == 0 && self.get_groups().is_none() { cvt(libc::setgroups(0, crate::ptr::null()))?; if self.get_groups().is_none() { let res = cvt(libc::setgroups(0, crate::ptr::null())); if let Err(e) = res { // Here we ignore the case of not having CAP_SETGID. // An alternative would be to require CAP_SETGID (in // addition to CAP_SETUID) for setting the UID. if e.raw_os_error() != Some(libc::EPERM) { return Err(e.into()); } } } cvt(libc::setuid(u as uid_t))?; }"} {"_id":"doc-en-rust-423e24357dd4617901b861c193b4b432e999b4477dbb664c55e9341034877f06","title":"","text":"## `Cell` [`Cell`][cell] is a type that provides zero-cost interior mutability, but only for `Copy` types. [`Cell`][cell] is a type that provides zero-cost interior mutability by moving data in and out of the cell. Since the compiler knows that all the data owned by the contained value is on the stack, there's no worry of leaking any data behind references (or worse!) by simply replacing the data."} {"_id":"doc-en-rust-dcce4e289ef7af3610064a47e3561fe3b9b258f5f06846d96d682055d1bc2645","title":"","text":"unnecessary. However, this also relaxes the guarantees that the restriction provides; so if your invariants depend on data stored within `Cell`, you should be careful. This is useful for mutating primitives and other `Copy` types when there is no easy way of This is useful for mutating primitives and other types when there is no easy way of doing it in line with the static rules of `&` and `&mut`. `Cell` does not let you obtain interior references to the data, which makes it safe to freely"} {"_id":"doc-en-rust-0e774ba7005d8705090e3cc31aac0fab8a7041cf7d25ad5bdf2fd1e31354d6f1","title":"","text":"#### Cost There is no runtime cost to using `Cell`, however if you are using it to wrap larger (`Copy`) There is no runtime cost to using `Cell`, however if you are using it to wrap larger structs, it might be worthwhile to instead wrap individual fields in `Cell` since each write is otherwise a full copy of the struct. ## `RefCell` [`RefCell`][refcell] also provides interior mutability, but isn't restricted to `Copy` types. [`RefCell`][refcell] also provides interior mutability, but doesn't move data in and out of the cell. Instead, it has a runtime cost. `RefCell` enforces the read-write lock pattern at runtime (it's However, it has a runtime cost. `RefCell` enforces the read-write lock pattern at runtime (it's like a single-threaded mutex), unlike `&T`/`&mut T` which do so at compile time. This is done by the `borrow()` and `borrow_mut()` functions, which modify an internal reference count and return smart pointers which can be dereferenced immutably and mutably respectively. The refcount is restored when"} {"_id":"doc-en-rust-62a28b15b234281d7a074aa1810d4a7b84416be72206d1940ee851ae19ab899b","title":"","text":"//! references. We say that `Cell` and `RefCell` provide 'interior mutability', in contrast //! with typical Rust types that exhibit 'inherited mutability'. //! //! Cell types come in two flavors: `Cell` and `RefCell`. `Cell` provides `get` and `set` //! methods that change the interior value with a single method call. `Cell` though is only //! compatible with types that implement `Copy`. For other types, one must use the `RefCell` //! type, acquiring a write lock before mutating. //! Cell types come in two flavors: `Cell` and `RefCell`. `Cell` implements interior //! mutability by moving values in and out of the `Cell`. To use references instead of values, //! one must use the `RefCell` type, acquiring a write lock before mutating. `Cell` provides //! methods to retrieve and change the current interior value: //! //! - For types that implement `Copy`, the `get` method retrieves the current interior value. //! - For types that implement `Default`, the `take` method replaces the current interior value //! with `Default::default()` and returns the replaced value. //! - For all types, the `replace` method replaces the current interior value and returns the //! replaced value and the `into_inner` method consumes the `Cell` and returns the interior //! value. Additionally, the `set` method replaces the interior value, dropping the replaced //! value. //! //! `RefCell` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can //! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell`s are"} {"_id":"doc-en-rust-4ffe89fedc37c27e64db8da49f3b6d89efaf6b5ee259fb1cd62ea6d2bee0b28f","title":"","text":"use cmp::Ordering; use fmt::{self, Debug, Display}; use marker::Unsize; use mem; use ops::{Deref, DerefMut, CoerceUnsized}; /// A mutable memory location that admits only `Copy` data. /// A mutable memory location. /// /// See the [module-level documentation](index.html) for more. #[stable(feature = \"rust1\", since = \"1.0.0\")]"} {"_id":"doc-en-rust-7bbcc52639ecd5243b9a99873e44dba8dee4b2b973d5e0dca404a741557e578a","title":"","text":"} impl Cell { /// Creates a new `Cell` containing the given value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// ``` #[stable(feature = \"rust1\", since = \"1.0.0\")] #[inline] pub const fn new(value: T) -> Cell { Cell { value: UnsafeCell::new(value), } } /// Returns a copy of the contained value. /// /// # Examples"} {"_id":"doc-en-rust-0e019692733b798a8a5461eff4f0c41bf3e590a19034f06c7a51164776fdedf5","title":"","text":"unsafe{ *self.value.get() } } /// Sets the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// c.set(10); /// ``` #[inline] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } /// Returns a reference to the underlying `UnsafeCell`. /// /// # Examples"} {"_id":"doc-en-rust-1085d160d056a088f9f1759dbda9d61670353caa3eda5fd3d71cdc8919c52739","title":"","text":"} } impl Cell { /// Creates a new `Cell` containing the given value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// ``` #[stable(feature = \"rust1\", since = \"1.0.0\")] #[inline] pub const fn new(value: T) -> Cell { Cell { value: UnsafeCell::new(value), } } /// Sets the contained value. /// /// # Examples /// /// ``` /// use std::cell::Cell; /// /// let c = Cell::new(5); /// /// c.set(10); /// ``` #[inline] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub fn set(&self, val: T) { let old = self.replace(val); drop(old); } /// Replaces the contained value. /// /// # Examples /// /// ``` /// #![feature(move_cell)] /// use std::cell::Cell; /// /// let c = Cell::new(5); /// let old = c.replace(10); /// /// assert_eq!(5, old); /// ``` #[unstable(feature = \"move_cell\", issue = \"39264\")] pub fn replace(&self, val: T) -> T { mem::replace(unsafe { &mut *self.value.get() }, val) } /// Unwraps the value. /// /// # Examples /// /// ``` /// #![feature(move_cell)] /// use std::cell::Cell; /// /// let c = Cell::new(5); /// let five = c.into_inner(); /// /// assert_eq!(five, 5); /// ``` #[unstable(feature = \"move_cell\", issue = \"39264\")] pub fn into_inner(self) -> T { unsafe { self.value.into_inner() } } } impl Cell { /// Takes the value of the cell, leaving `Default::default()` in its place. /// /// # Examples /// /// ``` /// #![feature(move_cell)] /// use std::cell::Cell; /// /// let c = Cell::new(5); /// let five = c.take(); /// /// assert_eq!(five, 5); /// assert_eq!(c.into_inner(), 0); /// ``` #[unstable(feature = \"move_cell\", issue = \"39264\")] pub fn take(&self) -> T { self.replace(Default::default()) } } #[unstable(feature = \"coerce_unsized\", issue = \"27732\")] impl, U> CoerceUnsized> for Cell {}"} {"_id":"doc-en-rust-4bc4f6d14b619b23a0fba302e13a0c3882b82f7cd146b845182e30863a826f9c","title":"","text":"} #[test] fn cell_set() { let cell = Cell::new(10); cell.set(20); assert_eq!(20, cell.get()); let cell = Cell::new(\"Hello\".to_owned()); cell.set(\"World\".to_owned()); assert_eq!(\"World\".to_owned(), cell.into_inner()); } #[test] fn cell_replace() { let cell = Cell::new(10); assert_eq!(10, cell.replace(20)); assert_eq!(20, cell.get()); let cell = Cell::new(\"Hello\".to_owned()); assert_eq!(\"Hello\".to_owned(), cell.replace(\"World\".to_owned())); assert_eq!(\"World\".to_owned(), cell.into_inner()); } #[test] fn cell_into_inner() { let cell = Cell::new(10); assert_eq!(10, cell.into_inner()); let cell = Cell::new(\"Hello world\".to_owned()); assert_eq!(\"Hello world\".to_owned(), cell.into_inner()); } #[test] fn refcell_default() { let cell: RefCell = Default::default(); assert_eq!(0, *cell.borrow());"} {"_id":"doc-en-rust-3c10e267167c923022826c5ee75f239813b713a0af2312480e38900dd1b80848","title":"","text":"#![feature(ordering_chaining)] #![feature(result_unwrap_or_default)] #![feature(ptr_unaligned)] #![feature(move_cell)] extern crate core; extern crate test;"} {"_id":"doc-en-rust-0128ed7a4961719321cedf8f3893f54b337caa08522b3c3b1a1f15b7c46b2e3e","title":"","text":"ostype += 'abi64' elif cputype in {'powerpc', 'ppc', 'ppc64'}: cputype = 'powerpc' elif cputype == 'sparcv9': pass elif cputype in {'amd64', 'x86_64', 'x86-64', 'x64'}: cputype = 'x86_64' else:"} {"_id":"doc-en-rust-64782bbb3cb0b1a00b9aacbe325fede7e81013f8af4dc2de21eab030f1c5c83a","title":"","text":"// compiler-rt's build system already cfg.flag(\"-fno-builtin\"); cfg.flag(\"-fvisibility=hidden\"); cfg.flag(\"-fomit-frame-pointer\"); // Accepted practice on Solaris is to never omit frame pointer so that // system observability tools work as expected. In addition, at least // on Solaris, -fomit-frame-pointer on sparcv9 appears to generate // references to data outside of the current stack frame. A search of // the gcc bug database provides a variety of issues surrounding // -fomit-frame-pointer on non-x86 platforms. if !target.contains(\"solaris\") && !target.contains(\"sparc\") { cfg.flag(\"-fomit-frame-pointer\"); } cfg.flag(\"-ffreestanding\"); cfg.define(\"VISIBILITY_HIDDEN\", None); }"} {"_id":"doc-en-rust-9537459d551adc68d17923e42928b51a7aaa6ec635ec84759bdd0ffe3347357d","title":"","text":"(\"armv7s-apple-ios\", armv7s_apple_ios), (\"x86_64-sun-solaris\", x86_64_sun_solaris), (\"sparcv9-sun-solaris\", sparcv9_sun_solaris), (\"x86_64-pc-windows-gnu\", x86_64_pc_windows_gnu), (\"i686-pc-windows-gnu\", i686_pc_windows_gnu),"} {"_id":"doc-en-rust-ae781d732f4bed30bf1dfba933c6d4459646b70ff350423a5876a8be1c2245fe","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use target::{Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::solaris_base::opts(); base.pre_link_args.push(\"-m64\".to_string()); // llvm calls this \"v9\" base.cpu = \"v9\".to_string(); base.max_atomic_width = Some(64); Ok(Target { llvm_target: \"sparcv9-sun-solaris\".to_string(), target_endian: \"big\".to_string(), target_pointer_width: \"64\".to_string(), data_layout: \"E-m:e-i64:64-n32:64-S128\".to_string(), // Use \"sparc64\" instead of \"sparcv9\" here, since the former is already // used widely in the source base. If we ever needed ABI // differentiation from the sparc64, we could, but that would probably // just be confusing. arch: \"sparc64\".to_string(), target_os: \"solaris\".to_string(), target_env: \"\".to_string(), target_vendor: \"sun\".to_string(), options: base, }) } "} {"_id":"doc-en-rust-93042a5e03d39eb7515def0b728006dd0a31f0ada1fd69df302d15fce2ada081","title":"","text":"// // match { // => , // [_ if => ,] // _ => [ | ()] // }"} {"_id":"doc-en-rust-9529c454ac9cf286826b6d3f3bec2bbc3dbf71c109033875c04decfac8c5c64d","title":"","text":"arms.push(self.arm(hir_vec![pat], body_expr)); } // `[_ if => ,]` // `_ => [ | ()]` // _ => [|()] { let mut current: Option<&Expr> = else_opt.as_ref().map(|p| &**p); let mut else_exprs: Vec> = vec![current]; // First, we traverse the AST and recursively collect all // `else` branches into else_exprs, e.g.: // // if let Some(_) = x { // ... // } else if ... { // Expr1 // ... // } else if ... { // Expr2 // ... // } else { // Expr3 // ... // } // // ... results in else_exprs = [Some(&Expr1), // Some(&Expr2), // Some(&Expr3)] // // Because there also the case there is no `else`, these // entries can also be `None`, as in: // // if let Some(_) = x { // ... // } else if ... { // Expr1 // ... // } else if ... { // Expr2 // ... // } // // ... results in else_exprs = [Some(&Expr1), // Some(&Expr2), // None] // // The last entry in this list is always translated into // the final \"unguard\" wildcard arm of the `match`. In the // case of a `None`, it becomes `_ => ()`. loop { if let Some(e) = current { // There is an else branch at this level if let ExprKind::If(_, _, ref else_opt) = e.node { // The else branch is again an if-expr current = else_opt.as_ref().map(|p| &**p); else_exprs.push(current); } else { // The last item in the list is not an if-expr, // stop here break } } else { // We have no more else branch break } } // Now translate the list of nested else-branches into the // arms of the match statement. for else_expr in else_exprs { if let Some(else_expr) = else_expr { let (guard, body) = if let ExprKind::If(ref cond, ref then, _) = else_expr.node { let then = self.lower_block(then, false); (Some(cond), self.expr_block(then, ThinVec::new())) } else { (None, self.lower_expr(else_expr)) }; arms.push(hir::Arm { attrs: hir_vec![], pats: hir_vec![self.pat_wild(e.span)], guard: guard.map(|e| P(self.lower_expr(e))), body: P(body), }); } else { // There was no else-branch, push a noop let pat_under = self.pat_wild(e.span); let unit = self.expr_tuple(e.span, hir_vec![]); arms.push(self.arm(hir_vec![pat_under], unit)); } } let wildcard_arm: Option<&Expr> = else_opt.as_ref().map(|p| &**p); let wildcard_pattern = self.pat_wild(e.span); let body = if let Some(else_expr) = wildcard_arm { P(self.lower_expr(else_expr)) } else { self.expr_tuple(e.span, hir_vec![]) }; arms.push(self.arm(hir_vec![wildcard_pattern], body)); } let contains_else_clause = else_opt.is_some();"} {"_id":"doc-en-rust-9f98d6fa17e03e2c81f14d992f6fbb4598c82fccaef212cc3374dfbf20d026f0","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct Foo; impl Foo { fn bar(&mut self) -> bool { true } } fn error(foo: &mut Foo) { if let Some(_) = Some(true) { } else if foo.bar() {} } fn ok(foo: &mut Foo) { if let Some(_) = Some(true) { } else { if foo.bar() {} } } fn main() {} "} {"_id":"doc-en-rust-d18fd7e278b9abf554a18bb410b5712cf61605e93a68203705164daa028d8646","title":"","text":"# 32/64-bit MinGW builds. # # The MinGW builds unfortunately have to both download a custom toolchain and # avoid the one installed by AppVeyor by default. Interestingly, though, for # different reasons! # We are using MinGW with posix threads since LLVM does not compile with # the win32 threads version due to missing support for C++'s std::thread. # # For 32-bit the installed gcc toolchain on AppVeyor uses the pthread # threading model. This is unfortunately not what we want, and if we compile # with it then there's lots of link errors in the standard library (undefined # references to pthread symbols). # # For 64-bit the installed gcc toolchain is currently 5.3.0 which # unfortunately segfaults on Windows with --enable-llvm-assertions (segfaults # in LLVM). See rust-lang/rust#28445 for more information, but to work around # this we go back in time to 4.9.2 specifically. # Instead of relying on the MinGW version installed on appveryor we download # and install one ourselves so we won't be surprised by changes to appveyor's # build image. # # Finally, note that the downloads below are all in the `rust-lang-ci` S3 # bucket, but they cleraly didn't originate there! The downloads originally # came from the mingw-w64 SourceForge download site. Unfortunately # SourceForge is notoriously flaky, so we mirror it on our own infrastructure. # # And as a final point of note, the 32-bit MinGW build using the makefiles do # *not* use debug assertions and llvm assertions. This is because they take # too long on appveyor and this is tested by rustbuild below. - MSYS_BITS: 32 RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu --enable-ninja SCRIPT: python x.py test MINGW_URL: https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror MINGW_ARCHIVE: i686-6.2.0-release-win32-dwarf-rt_v5-rev1.7z MINGW_ARCHIVE: i686-6.2.0-release-posix-dwarf-rt_v5-rev1.7z MINGW_DIR: mingw32 - MSYS_BITS: 64 SCRIPT: python x.py test RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-gnu --enable-ninja MINGW_URL: https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror MINGW_ARCHIVE: x86_64-6.2.0-release-win32-seh-rt_v5-rev1.7z MINGW_ARCHIVE: x86_64-6.2.0-release-posix-seh-rt_v5-rev1.7z MINGW_DIR: mingw64 # 32/64 bit MSVC and GNU deployment"} {"_id":"doc-en-rust-86c9ada332e896c4b394c1dc84129b46150cb8b4cad0e432f434f65e092a631e","title":"","text":"RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu --enable-extended --enable-ninja SCRIPT: python x.py dist MINGW_URL: https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror MINGW_ARCHIVE: i686-6.2.0-release-win32-dwarf-rt_v5-rev1.7z MINGW_ARCHIVE: i686-6.2.0-release-posix-dwarf-rt_v5-rev1.7z MINGW_DIR: mingw32 DEPLOY: 1 - MSYS_BITS: 64 SCRIPT: python x.py dist RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-gnu --enable-extended --enable-ninja MINGW_URL: https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror MINGW_ARCHIVE: x86_64-6.2.0-release-win32-seh-rt_v5-rev1.7z MINGW_ARCHIVE: x86_64-6.2.0-release-posix-seh-rt_v5-rev1.7z MINGW_DIR: mingw64 DEPLOY: 1"} {"_id":"doc-en-rust-238898a81af0a37e967a4f51c683700e990139c60885063d123bcc0382fead25","title":"","text":"COPY build-emscripten.sh /tmp/ RUN ./build-emscripten.sh ENV PATH=$PATH:/tmp/emsdk_portable ENV PATH=$PATH:/tmp/emsdk_portable/clang/tag-e1.37.1/build_tag-e1.37.1_32/bin ENV PATH=$PATH:/tmp/emsdk_portable/clang/tag-e1.37.10/build_tag-e1.37.10_32/bin ENV PATH=$PATH:/tmp/emsdk_portable/node/4.1.1_32bit/bin ENV PATH=$PATH:/tmp/emsdk_portable/emscripten/tag-1.37.1 ENV EMSCRIPTEN=/tmp/emsdk_portable/emscripten/tag-1.37.1 ENV PATH=$PATH:/tmp/emsdk_portable/emscripten/tag-1.37.10 ENV EMSCRIPTEN=/tmp/emsdk_portable/emscripten/tag-1.37.10 ENV RUST_CONFIGURE_ARGS --target=asmjs-unknown-emscripten"} {"_id":"doc-en-rust-8fe75fbb11c04942f7d65cded5756fd3387a3556d61e0a1e5acb5930fcd41ab9","title":"","text":"source emsdk_portable/emsdk_env.sh hide_output emsdk update hide_output emsdk install --build=Release sdk-tag-1.37.1-32bit hide_output emsdk activate --build=Release sdk-tag-1.37.1-32bit hide_output emsdk install --build=Release sdk-tag-1.37.10-32bit hide_output emsdk activate --build=Release sdk-tag-1.37.10-32bit "} {"_id":"doc-en-rust-f1b0fae89bfd07c38c7b05307750bdd1d168d4d8c7858077dd60f3b0297dd2aa","title":"","text":" Subproject commit d30da544a8afc5d78391dee270bdf40e74a215d3 Subproject commit c8a8767c56ad3d3f4eb45c87b95026936fb9aa35 "} {"_id":"doc-en-rust-6378e4243879e5441538c532ac808304722e5ce5710e3f279813a36e589c892d","title":"","text":"} if target.contains(\"arm\") && !target.contains(\"ios\") { // (At least) udivsi3.S is broken for Thumb 1 which our gcc uses by // default, we don't want Thumb 2 since it isn't supported on some // devices, so disable thumb entirely. // Upstream bug: https://bugs.llvm.org/show_bug.cgi?id=32492 cfg.define(\"__ARM_ARCH_ISA_THUMB\", Some(\"0\")); sources.extend(&[\"arm/aeabi_cdcmp.S\", \"arm/aeabi_cdcmpeq_check_nan.c\", \"arm/aeabi_cfcmp.S\","} {"_id":"doc-en-rust-89e22bae5332f73ea20ef3121dae357c44e7260e05c457ddc5f3319f097fddc9","title":"","text":" Subproject commit 2e951c3ae354bcbd2e50b30798e232949a926b75 Subproject commit a884d21cc5f0b23a1693d1e872fd8998a4fdd17f "} {"_id":"doc-en-rust-7afe46694c3b1903fd54d0e3d88360b36d31b67d328e15109129e4c7d2a0c1de","title":"","text":"// write_volatile causes an LLVM assert with composite types // ignore-emscripten See #41299: probably a bad optimization #![feature(volatile)] use std::ptr::{read_volatile, write_volatile};"} {"_id":"doc-en-rust-1c7c8d034747add611cd3f38fc9ab26ac979126aabff85727b4f8574b4a1b427","title":"","text":"exit_success_if_unwind::bar(do_panic); } } let s = Command::new(env::args_os().next().unwrap()).arg(\"foo\").status(); let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg(\"foo\"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = \"arm\") && cfg!(target_env = \"gnu\") { cmd.env(\"RUST_BACKTRACE\", \"0\"); } let s = cmd.status(); assert!(s.unwrap().code() != Some(0)); }"} {"_id":"doc-en-rust-ed315265e3ba100fe5c8b0cb7cc1ee128edff47bd774ddaf806ba9b7eb66f620","title":"","text":"panic!(\"try to catch me\"); } } let s = Command::new(env::args_os().next().unwrap()).arg(\"foo\").status(); let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg(\"foo\"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = \"arm\") && cfg!(target_env = \"gnu\") { cmd.env(\"RUST_BACKTRACE\", \"0\"); } let s = cmd.status(); assert!(s.unwrap().code() != Some(0)); }"} {"_id":"doc-en-rust-bf28373ac496849ad71b1bdd2d7ebb40eb548bc1da298be84db2d97ea595d5ff","title":"","text":"// So peel off one-level, turning the &T into T. match base_ty.builtin_deref(false, ty::NoPreference) { Some(t) => t.ty, None => { return Err(()); } None => { debug!(\"By-ref binding of non-derefable type {:?}\", base_ty); return Err(()); } } } _ => base_ty,"} {"_id":"doc-en-rust-68f5989759e20f246b33a99a09808858561a5586fa828db1008f6269f4fa6099","title":"","text":"match base_cmt.ty.builtin_index() { Some(ty) => (ty, ElementKind::VecElement), None => { debug!(\"Explicit index of non-indexable type {:?}\", base_cmt); return Err(()); } }"} {"_id":"doc-en-rust-a54b9bf1555b63c76a9ac625bde17582b0b54ff5ba302b506d385cad7d5b21dc","title":"","text":"PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) | PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => { match path.def { Def::Err => return Err(()), Def::Err => { debug!(\"access to unresolvable pattern {:?}\", pat); return Err(()) } Def::Variant(variant_did) | Def::VariantCtor(variant_did, ..) => { // univariant enums do not need downcasts"} {"_id":"doc-en-rust-535c38de01cf9385a0b205c0499bc734450ed88db00f97223e360a8b2338e798","title":"","text":"panic!(ExplicitBug); } pub fn delay_span_bug>(&self, sp: S, msg: &str) { if self.treat_err_as_bug { self.span_bug(sp, msg); } let mut delayed = self.delayed_span_bug.borrow_mut(); *delayed = Some((sp.into(), msg.to_string())); }"} {"_id":"doc-en-rust-08504fe507f0224aadf28ae859a561f514a8de7438a39bd907b4db09bf909429","title":"","text":"}; let index_expr_ty = self.node_ty(index_expr.id); let adjusted_base_ty = self.resolve_type_vars_if_possible(&adjusted_base_ty); let index_expr_ty = self.resolve_type_vars_if_possible(&index_expr_ty); let result = self.try_index_step(ty::MethodCall::expr(expr.id), expr,"} {"_id":"doc-en-rust-37e41b49c8abacf8b657d5f56578dfc4672726f1787fbf7ff253be8bc2e0545e","title":"","text":"let expr_ty = self.node_ty(expr.id); self.demand_suptype(expr.span, expr_ty, return_ty); } else { // We could not perform a mutable index. Re-apply the // immutable index adjustments - borrowck will detect // this as an error. if let Some(adjustment) = adjustment { self.apply_adjustment(expr.id, adjustment); } self.tcx.sess.delay_span_bug( expr.span, \"convert_lvalue_derefs_to_mutable failed\"); } } hir::ExprUnary(hir::UnDeref, ref base_expr) => {"} {"_id":"doc-en-rust-8a6bf928d2775a48e8eb2edda5c614fed0cf1ef76703ea8248e8c42db9ab9d52","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // regression test for issue #41498. struct S; impl S { fn mutate(&mut self) {} } fn call_and_ref T>(x: &mut Option, f: F) -> &mut T { *x = Some(f()); x.as_mut().unwrap() } fn main() { let mut n = None; call_and_ref(&mut n, || [S])[0].mutate(); } "} {"_id":"doc-en-rust-df0968c1deabc9e1f6afb9559c03e5b0481b8ed34cdf957cfe1722e3efd6a988","title":"","text":"use rustc::mir::*; use rustc::mir::transform::{MirSuite, MirPassIndex, MirSource}; use rustc::ty::TyCtxt; use rustc::ty::item_path; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::indexed_vec::{Idx}; use std::fmt::Display;"} {"_id":"doc-en-rust-13e7c8c2090d396a0f8bf9f6a6214a283404dca3e5874951f16d213eeaaefb98","title":"","text":"return; } let node_path = tcx.item_path_str(tcx.hir.local_def_id(source.item_id())); let node_path = item_path::with_forced_impl_filename_line(|| { // see notes on #41697 below tcx.item_path_str(tcx.hir.local_def_id(source.item_id())) }); dump_matched_mir_node(tcx, pass_num, pass_name, &node_path, disambiguator, source, mir); for (index, promoted_mir) in mir.promoted.iter_enumerated() {"} {"_id":"doc-en-rust-54e131ad2f75c250515da966cd46b197f3787ffc426175bda9f99fea268c88be","title":"","text":"Some(ref filters) => filters, }; let node_id = source.item_id(); let node_path = tcx.item_path_str(tcx.hir.local_def_id(node_id)); let node_path = item_path::with_forced_impl_filename_line(|| { // see notes on #41697 below tcx.item_path_str(tcx.hir.local_def_id(node_id)) }); filters.split(\"&\") .any(|filter| { filter == \"all\" ||"} {"_id":"doc-en-rust-a6191f0a9e196cca26f6a3c58b2fda7c4476e8ae9499e7b1646f2d72a968d2be","title":"","text":"}) } // #41697 -- we use `with_forced_impl_filename_line()` because // `item_path_str()` would otherwise trigger `type_of`, and this can // run while we are already attempting to evaluate `type_of`. fn dump_matched_mir_node<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, pass_num: Option<(MirSuite, MirPassIndex)>, pass_name: &str,"} {"_id":"doc-en-rust-1dfe82c268a9352910ae1cfdf938896ceacb078657dd8fb1064831238f8a5186","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags:-Zdump-mir=NEVER_MATCHED // Regression test for #41697. Using dump-mir was triggering // artificial cycles: during type-checking, we had to get the MIR for // the constant expressions in `[u8; 2]`, which in turn would trigger // an attempt to get the item-path, which in turn would request the // types of the impl, which would trigger a cycle. We supressed this // cycle now by forcing mir-dump to avoid asking for types of an impl. #![feature(rustc_attrs)] use std::sync::Arc; trait Foo { fn get(&self) -> [u8; 2]; } impl Foo for [u8; 2] { fn get(&self) -> [u8; 2] { *self } } struct Bar(T); fn unsize_fat_ptr<'a>(x: &'a Bar) -> &'a Bar { x } fn unsize_nested_fat_ptr(x: Arc) -> Arc { x } fn main() { let x: Box> = Box::new(Bar([1,2])); assert_eq!(unsize_fat_ptr(&*x).0.get(), [1, 2]); let x: Arc = Arc::new([3, 4]); assert_eq!(unsize_nested_fat_ptr(x).get(), [3, 4]); } "} {"_id":"doc-en-rust-62191fcdfe8176218393d6258454e8b3f7bae7984705ab4ebdd0694238d10877","title":"","text":"output: $output:tt) => { define_map_struct! { tcx: $tcx, ready: ([pub] $attrs $name), ready: ([] $attrs $name), input: ($($input)*), output: $output }"} {"_id":"doc-en-rust-ae8a6350fb7d40d20ba2102bcad3c43084637510446a9593a45e85136c65c9b0","title":"","text":"MirSource::Promoted(_, i) => write!(w, \"{:?} in\", i)? } write!(w, \" {}\", tcx.node_path_str(src.item_id()))?; item_path::with_forced_impl_filename_line(|| { // see notes on #41697 elsewhere write!(w, \" {}\", tcx.node_path_str(src.item_id())) })?; if let MirSource::Fn(_) = src { write!(w, \"(\")?;"} {"_id":"doc-en-rust-65a28427c24e447d35fd97c0fe257b0e8c2f88abfd4782bbc2a49fad6430b787","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for #41697. Using dump-mir was triggering // artificial cycles: during type-checking, we had to get the MIR for // the constant expressions in `[u8; 2]`, which in turn would trigger // an attempt to get the item-path, which in turn would request the // types of the impl, which would trigger a cycle. We supressed this // cycle now by forcing mir-dump to avoid asking for types of an impl. #![feature(rustc_attrs)] use std::sync::Arc; trait Foo { fn get(&self) -> [u8; 2]; } impl Foo for [u8; 2] { fn get(&self) -> [u8; 2] { *self } } struct Bar(T); fn unsize_fat_ptr<'a>(x: &'a Bar) -> &'a Bar { x } fn unsize_nested_fat_ptr(x: Arc) -> Arc { x } fn main() { let x: Box> = Box::new(Bar([1,2])); assert_eq!(unsize_fat_ptr(&*x).0.get(), [1, 2]); let x: Arc = Arc::new([3, 4]); assert_eq!(unsize_nested_fat_ptr(x).get(), [3, 4]); } "} {"_id":"doc-en-rust-88024cf21ca031fc6570096588250a9d1caf0c318be091e3ef203cfb468b444f","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags:-Zdump-mir=NEVER_MATCHED // Regression test for #41697. Using dump-mir was triggering // artificial cycles: during type-checking, we had to get the MIR for // the constant expressions in `[u8; 2]`, which in turn would trigger // an attempt to get the item-path, which in turn would request the // types of the impl, which would trigger a cycle. We supressed this // cycle now by forcing mir-dump to avoid asking for types of an impl. #![feature(rustc_attrs)] use std::sync::Arc; trait Foo { fn get(&self) -> [u8; 2]; } impl Foo for [u8; 2] { fn get(&self) -> [u8; 2] { *self } } struct Bar(T); fn unsize_fat_ptr<'a>(x: &'a Bar) -> &'a Bar { x } fn unsize_nested_fat_ptr(x: Arc) -> Arc { x } fn main() { let x: Box> = Box::new(Bar([1,2])); assert_eq!(unsize_fat_ptr(&*x).0.get(), [1, 2]); let x: Arc = Arc::new([3, 4]); assert_eq!(unsize_nested_fat_ptr(x).get(), [3, 4]); } "} {"_id":"doc-en-rust-501c5a0a1d52b1809b66e2598c70424412da5cb9f90478b670798641a84366b4","title":"","text":"let path = @{span: span, global: false, idents: ~[nm], rp: None, types: ~[]}; @{id: self.next_id(), node: ast::pat_ident(ast::bind_by_implicit_ref, node: ast::pat_ident(ast::bind_by_ref(ast::m_imm), path, None), span: span}"} {"_id":"doc-en-rust-3ae1028ce24836dc6476a0641471b3a360051aabf914c5746407c602a9ebd91e","title":"","text":"let pat_node = if pats.is_empty() { ast::pat_ident( ast::bind_by_implicit_ref, ast::bind_by_ref(ast::m_imm), cx.path(span, ~[v_name]), None )"} {"_id":"doc-en-rust-e3a9e1b99f81cd84518372fef248726775279991127b30bb177a195d0d5fb5ed","title":"","text":" #[forbid(deprecated_pattern)]; extern mod std; // These tests used to be separate files, but I wanted to refactor all"} {"_id":"doc-en-rust-d89fb24f9742aade4920839ff4bc0d2f31c9607459a61d8b2b89602c80bd6894","title":"","text":"let ebml_w = &EBWriter::Serializer(wr); a1.serialize(ebml_w) }; let d = EBReader::Doc(@bytes); let d = EBReader::Doc(@move bytes); let a2: A = deserialize(&EBReader::Deserializer(d)); assert *a1 == a2; }"} {"_id":"doc-en-rust-73ab323806371a581397fa631bbb750f4501e504e57a004924eb0457688741e5","title":"","text":"#![feature(core_intrinsics)] #![feature(dropck_eyepatch)] #![feature(generic_param_attrs)] #![feature(needs_drop)] #![cfg_attr(test, feature(test))] #![allow(deprecated)]"} {"_id":"doc-en-rust-ef0f1f6f58d11f91ec094804a6b6ed91fd814107d28b71c4271e66aaed2cf1d1","title":"","text":"/// Here's an example of how a collection might make use of needs_drop: /// /// ``` /// #![feature(needs_drop)] /// use std::{mem, ptr}; /// /// pub struct MyCollection {"} {"_id":"doc-en-rust-a8b80d969187c47a560980fd8c57f81132695ae314daf2a2c044f58e2169fd41","title":"","text":"/// } /// ``` #[inline] #[unstable(feature = \"needs_drop\", issue = \"41890\")] #[stable(feature = \"needs_drop\", since = \"1.22.0\")] pub fn needs_drop() -> bool { unsafe { intrinsics::needs_drop::() } }"} {"_id":"doc-en-rust-b8dc7ba19862b3165d4699481d1755740e38cc72b9d212454469c4fee7c1ff07","title":"","text":"#![feature(macro_reexport)] #![feature(macro_vis_matcher)] #![feature(needs_panic_runtime)] #![feature(needs_drop)] #![feature(never_type)] #![feature(num_bits_bytes)] #![feature(old_wrapping)]"} {"_id":"doc-en-rust-18057383635020510e58ee61e7e7b34f1653718fdc8b51a8e331c3326e4db638","title":"","text":"TokenTree::Sequence(span, ref seq) => { if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| { match *seq_tt { TokenTree::MetaVarDecl(_, _, id) => id.name == \"vis\", TokenTree::Sequence(_, ref sub_seq) => sub_seq.op == quoted::KleeneOp::ZeroOrMore, _ => false,"} {"_id":"doc-en-rust-b20d962feb4247da36b60b6183e5147f320085a6e7974510e620d8baa69f51ef","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(macro_vis_matcher)] macro_rules! foo { ($($p:vis)*) => {} //~ ERROR repetition matches empty token tree } foo!(a); "} {"_id":"doc-en-rust-39693079c7326e06379c5944caceb2b202874a67d9b4c979d3cc1f49f7fe85e3","title":"","text":"// #[repr(simd)], even if we don't actually use this struct directly. // // FIXME repr(simd) broken on emscripten and redox // It's also broken on big-endian powerpc64 and s390x. #42778 #[cfg_attr(not(any(target_os = \"emscripten\", target_os = \"redox\", target_endian = \"big\")), repr(simd))] #[cfg_attr(not(any(target_os = \"emscripten\", target_os = \"redox\")), repr(simd))] struct Block(u64, u64, u64, u64); struct UnalignedBlock(u64, u64, u64, u64);"} {"_id":"doc-en-rust-d4b26411305fb613a8efb6d0609865bb7be84b96efc9b6c58cd5dcb2ad54c0a8","title":"","text":"trait_obj.method_two(); ``` You can read more about trait objects in the Trait Object section of the Reference: You can read more about trait objects in the [Trait Objects] section of the Reference. https://doc.rust-lang.org/reference.html#trait-objects [Trait Objects]: https://doc.rust-lang.org/reference/types.html#trait-objects \"##, E0034: r##\""} {"_id":"doc-en-rust-0f7818bfc8c1d9173ba75e5817c16350d075f6ad0fe5e5af3b665420edd64bdb","title":"","text":"optional namespacing), a dereference, an indexing expression or a field reference. More details can be found here: https://doc.rust-lang.org/reference.html#lvalues-rvalues-and-temporaries More details can be found in the [Expressions] section of the Reference. [Expressions]: https://doc.rust-lang.org/reference/expressions.html#lvalues-rvalues-and-temporaries Now, we can go further. Here are some erroneous code examples:"} {"_id":"doc-en-rust-09e4da4bbedab300815d213cdf2468abb0eb6e08c05fa5c6327f508e794ba719","title":"","text":"} ``` PhantomData can also be used to express information about unused type parameters. You can read more about it in the API documentation: [PhantomData] can also be used to express information about unused type parameters. https://doc.rust-lang.org/std/marker/struct.PhantomData.html [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html \"##, E0393: r##\""} {"_id":"doc-en-rust-5396f16999d800ae76db9ec63165cf07587661e3d585928c59e56c1eed794da0","title":"","text":"println!(\"x: {}, y: {}\", variable.x, variable.y); ``` For more information see The Rust Book: https://doc.rust-lang.org/book/ For more information about primitives and structs, take a look at The Book: https://doc.rust-lang.org/book/first-edition/primitive-types.html https://doc.rust-lang.org/book/first-edition/structs.html \"##, E0611: r##\""} {"_id":"doc-en-rust-9d0b35535ff721df9eff1a78b855ff85ae12e30075c92766c44a7c183540880b","title":"","text":"} ``` To fix this error, you need to pass variables corresponding to C types as much as possible. For better explanations, see The Rust Book: https://doc.rust-lang.org/book/ Certain Rust types must be cast before passing them to a variadic function, because of arcane ABI rules dictated by the C standard. To fix the error, cast the value to the type specified by the error message (which you may need to import from `std::os::raw`). \"##, E0618: r##\""} {"_id":"doc-en-rust-51509258937a66dddc7a824f610af1b270c2d6bcd11b9c7ec79772b10901899a","title":"","text":"- [Command-line arguments](command-line-arguments.md) - [The `#[doc]` attribute](the-doc-attribute.md) - [Documentation tests](documentation-tests.md) - [Linking to items by name](linking-to-items-by-name.md) - [Lints](lints.md) - [Passes](passes.md) - [Advanced Features](advanced-features.md)"} {"_id":"doc-en-rust-31ae49ec6dae202d6e6b8ef1508b56d424e48fff65a7aad7961063bc834ed322","title":"","text":" # Linking to items by name Rustdoc is capable of directly linking to other rustdoc pages in Markdown documentation using the path of item as a link. For example, in the following code all of the links will link to the rustdoc page for `Bar`: ```rust /// This struct is not [Bar] pub struct Foo1; /// This struct is also not [bar](Bar) pub struct Foo2; /// This struct is also not [bar][b] /// /// [b]: Bar pub struct Foo3; /// This struct is also not [`Bar`] pub struct Foo4; pub struct Bar; ``` You can refer to anything in scope, and use paths, including `Self`, `self`, `super`, and `crate`. You may also use `foo()` and `foo!()` to refer to methods/functions and macros respectively. Backticks around the link will be stripped. ```rust,edition2018 use std::sync::mpsc::Receiver; /// This is an version of [`Receiver`], with support for [`std::future`]. /// /// You can obtain a [`std::future::Future`] by calling [`Self::recv()`]. pub struct AsyncReceiver { sender: Receiver } impl AsyncReceiver { pub async fn recv() -> T { unimplemented!() } } ``` You can also link to sections using URL fragment specifiers: ```rust /// This is a special implementation of [positional parameters] /// /// [positional parameters]: std::fmt#formatting-parameters struct MySpecialFormatter; ``` Paths in Rust have three namespaces: type, value, and macro. Items from these namespaces are allowed to overlap. In case of ambiguity, rustdoc will warn about the ambiguity and ask you to disambiguate, which can be done by using a prefix like `struct@`, `enum@`, `type@`, `trait@`, `union@`, `const@`, `static@`, `value@`, `function@`, `mod@`, `fn@`, `module@`, `method@`, `prim@`, `primitive@`, `macro@`, or `derive@`:: ```rust /// See also: [`Foo`](struct@Foo) struct Bar; /// This is different from [`Foo`](fn@Foo) struct Foo {} fn Foo() {} ``` Note: Because of how `macro_rules` macros are scoped in Rust, the intra-doc links of a `macro_rules` macro will be resolved relative to the crate root, as opposed to the module it is defined in. "} {"_id":"doc-en-rust-d2575c1585d962b6fe6958034585cc4290ed6a8b7f668c575f48a765676f80ff","title":"","text":"## broken_intra_doc_links This lint **warns by default** and is **nightly-only**. This lint detects when an intra-doc link fails to get resolved. For example: This lint **warns by default**. This lint detects when an [intra-doc link] fails to get resolved. For example: [intra-doc link]: linking-to-items-by-name.html ```rust /// I want to link to [`Inexistent`] but it doesn't exist! /// I want to link to [`Nonexistent`] but it doesn't exist! pub fn foo() {} ``` You'll get a warning saying: ```text error: `[`Inexistent`]` cannot be resolved, ignoring it... warning: unresolved link to `Nonexistent` --> test.rs:1:24 | 1 | /// I want to link to [`Nonexistent`] but it doesn't exist! | ^^^^^^^^^^^^^ no item named `Nonexistent` in `test` ``` It will also warn when there is an ambiguity and suggest how to disambiguate: ```rust /// [`Foo`] pub fn function() {} pub enum Foo {} pub fn Foo(){} ``` ```text warning: `Foo` is both an enum and a function --> test.rs:1:6 | 1 | /// [`Foo`] | ^^^^^ ambiguous link | = note: `#[warn(broken_intra_doc_links)]` on by default help: to link to the enum, prefix with the item type | 1 | /// [`enum@Foo`] | ^^^^^^^^^^ help: to link to the function, add parentheses | 1 | /// [`Foo()`] | ^^^^^^^ ``` ## missing_docs"} {"_id":"doc-en-rust-093e1e15e21ad70755e9d9d4b04120a890e0d664e05192b421de7c0754642e41","title":"","text":"Attempting to use these error numbers on stable will result in the code sample being interpreted as plain text. ### Linking to items by name Rustdoc is capable of directly linking to other rustdoc pages in Markdown documentation using the path of item as a link. For example, in the following code all of the links will link to the rustdoc page for `Bar`: ```rust /// This struct is not [Bar] pub struct Foo1; /// This struct is also not [bar](Bar) pub struct Foo2; /// This struct is also not [bar][b] /// /// [b]: Bar pub struct Foo3; /// This struct is also not [`Bar`] pub struct Foo4; pub struct Bar; ``` You can refer to anything in scope, and use paths, including `Self`. You may also use `foo()` and `foo!()` to refer to methods/functions and macros respectively. ```rust,edition2018 use std::sync::mpsc::Receiver; /// This is an version of [`Receiver`], with support for [`std::future`]. /// /// You can obtain a [`std::future::Future`] by calling [`Self::recv()`]. pub struct AsyncReceiver { sender: Receiver } impl AsyncReceiver { pub async fn recv() -> T { unimplemented!() } } ``` Paths in Rust have three namespaces: type, value, and macro. Items from these namespaces are allowed to overlap. In case of ambiguity, rustdoc will warn about the ambiguity and ask you to disambiguate, which can be done by using a prefix like `struct@`, `enum@`, `type@`, `trait@`, `union@`, `const@`, `static@`, `value@`, `function@`, `mod@`, `fn@`, `module@`, `method@`, `prim@`, `primitive@`, `macro@`, or `derive@`: ```rust /// See also: [`Foo`](struct@Foo) struct Bar; /// This is different from [`Foo`](fn@Foo) struct Foo {} fn Foo() {} ``` Note: Because of how `macro_rules` macros are scoped in Rust, the intra-doc links of a `macro_rules` macro will be resolved relative to the crate root, as opposed to the module it is defined in. ## Extensions to the `#[doc]` attribute These features operate by extending the `#[doc]` attribute, and thus can be caught by the compiler"} {"_id":"doc-en-rust-b79e485763a4b7f4f651da0ca650c7e710ea70b8f3e61516ba8852fe6e78f708","title":"","text":"use rustc_data_structures::stable_set::FxHashSet; use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_expand::base::SyntaxExtensionKind; use rustc_feature::UnstableFeatures; use rustc_hir as hir; use rustc_hir::def::{ DefKind,"} {"_id":"doc-en-rust-c458feea940e95e39bdac1c2e819b4042f40ae3a13dcffa1e513e4950524fe79","title":"","text":"}; pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate { if !UnstableFeatures::from_environment().is_nightly_build() { krate } else { let mut coll = LinkCollector::new(cx); coll.fold_crate(krate) } let mut coll = LinkCollector::new(cx); coll.fold_crate(krate) } enum ErrorKind<'a> {"} {"_id":"doc-en-rust-ebafdaab651386849b5c956a3a82adc8e603f2d415fc6211366f1e0c1faf0c4b","title":"","text":"/// println!(\"{:?}\", Foo { bar: 10, baz: \"Hello World\".to_string() }); /// ``` #[stable(feature = \"debug_builders\", since = \"1.2.0\")] #[inline] pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a> { builders::debug_struct_new(self, name) }"} {"_id":"doc-en-rust-674cc81bd82d8731a967556c6727f979237307e2ea695f7e2acdece978058209","title":"","text":"/// println!(\"{:?}\", Foo(10, \"Hello World\".to_string())); /// ``` #[stable(feature = \"debug_builders\", since = \"1.2.0\")] #[inline] pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a> { builders::debug_tuple_new(self, name) }"} {"_id":"doc-en-rust-1ac50255539b3d8913d6292f2c4a7c1f9632950764f450655d5f1d9f32d44a96","title":"","text":"/// println!(\"{:?}\", Foo(vec![10, 11])); /// ``` #[stable(feature = \"debug_builders\", since = \"1.2.0\")] #[inline] pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a> { builders::debug_list_new(self) }"} {"_id":"doc-en-rust-ff85422b3a0e79775dbd0133c0270330407f77dbe331656106c37ff3c2922c21","title":"","text":"/// println!(\"{:?}\", Foo(vec![10, 11])); /// ``` #[stable(feature = \"debug_builders\", since = \"1.2.0\")] #[inline] pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a> { builders::debug_set_new(self) }"} {"_id":"doc-en-rust-1e1d93fced3d9fbeda6dcb30bc66fc7460f9a8f7eec94281c1a68ecef942346f","title":"","text":"/// println!(\"{:?}\", Foo(vec![(\"A\".to_string(), 10), (\"B\".to_string(), 11)])); /// ``` #[stable(feature = \"debug_builders\", since = \"1.2.0\")] #[inline] pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a> { builders::debug_map_new(self) }"} {"_id":"doc-en-rust-887a3ce2481d125913767ab0a1d337c3f6294683378af72c555ec00cf85dbae3","title":"","text":"declare_lint! { pub UNUSED_EXTERN_CRATES, Warn, Allow, \"extern crates that are never used\" }"} {"_id":"doc-en-rust-baa2502cdf6d39f365aba4b73251991ec79f1fc87d118d581a2a0a4fc82530c9","title":"","text":" Subproject commit d9e7d2696e41983b6b5a0b4fac604b4e548a84d3 Subproject commit c7a16bd57c2a9c643a52f0cebecdaf0b6a996da1 "} {"_id":"doc-en-rust-6689207a51413b89f3ac01f4a89275b0e6b69d068cae9e689582ce00d5e1d740","title":"","text":"unsafe { ::sys::abort_internal() }; } /// Returns the OS-assigned process identifier associated with this process. /// /// # Examples /// /// Basic usage: /// /// ```no_run /// #![feature(getpid)] /// use std::process; /// /// println!(\"My pid is {}\", process::id()); /// ``` /// /// #[unstable(feature = \"getpid\", issue = \"44971\", reason = \"recently added\")] pub fn id() -> u32 { ::sys::os::getpid() } #[cfg(all(test, not(target_os = \"emscripten\")))] mod tests { use io::prelude::*;"} {"_id":"doc-en-rust-bd4d7b5f9913fcaf374dcc7cf818c4b5ea0b37b0e70e57356717a965aa55ab83","title":"","text":"let _ = syscall::exit(code as usize); unreachable!(); } pub fn getpid() -> u32 { syscall::getpid().unwrap() as u32 } "} {"_id":"doc-en-rust-464fbe097d91df31b9ed18785015e90a866e60fdd66bc13752456982936140b7","title":"","text":"pub fn exit(code: i32) -> ! { unsafe { libc::exit(code as c_int) } } pub fn getpid() -> u32 { unsafe { libc::getpid() as u32 } } "} {"_id":"doc-en-rust-4e73b10618b3fa796517a7b92ac93dd74017ea9af61f272783e029ae312885a5","title":"","text":"unsafe { c::ExitProcess(code as c::UINT) } } pub fn getpid() -> u32 { unsafe { c::GetCurrentProcessId() as u32 } } #[cfg(test)] mod tests { use io::Error;"} {"_id":"doc-en-rust-8dc8aba88e6c7bb7b49d451eaf4a768912d7ba8f194d7ddd95bcbfdb477e8165","title":"","text":"struct Void { _priv: (), /// Erases all oibits, because `Void` erases the type of the object that /// will be used to produce formatted output. Since we do not know what /// oibits the real types have (and they can have any or none), we need to /// take the most conservative approach and forbid all oibits. /// /// It was added after #45197 showed that one could share a `!Sync` /// object across threads by passing it into `format_args!`. _oibit_remover: PhantomData<*mut Fn()>, } /// This struct represents the generic \"argument\" which is taken by the Xprintf"} {"_id":"doc-en-rust-4ab1218c247aecbed17399fab7b69d7225716a6b382463c6e438cae03482d555","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn send(_: T) {} fn sync(_: T) {} fn main() { // `Cell` is not `Sync`, so `&Cell` is neither `Sync` nor `Send`, // `std::fmt::Arguments` used to forget this... let c = std::cell::Cell::new(42); send(format_args!(\"{:?}\", c)); sync(format_args!(\"{:?}\", c)); } "} {"_id":"doc-en-rust-a5018cb26734374b5d20f661856821930044342a6bd820645c2e5a37832134d5","title":"","text":" error[E0277]: the trait bound `*mut std::ops::Fn() + 'static: std::marker::Sync` is not satisfied in `[std::fmt::ArgumentV1<'_>]` --> $DIR/send-sync.rs:18:5 | 18 | send(format_args!(\"{:?}\", c)); | ^^^^ `*mut std::ops::Fn() + 'static` cannot be shared between threads safely | = help: within `[std::fmt::ArgumentV1<'_>]`, the trait `std::marker::Sync` is not implemented for `*mut std::ops::Fn() + 'static` = note: required because it appears within the type `std::marker::PhantomData<*mut std::ops::Fn() + 'static>` = note: required because it appears within the type `core::fmt::Void` = note: required because it appears within the type `&core::fmt::Void` = note: required because it appears within the type `std::fmt::ArgumentV1<'_>` = note: required because it appears within the type `[std::fmt::ArgumentV1<'_>]` = note: required because of the requirements on the impl of `std::marker::Send` for `&[std::fmt::ArgumentV1<'_>]` = note: required because it appears within the type `std::fmt::Arguments<'_>` = note: required by `send` error[E0277]: the trait bound `*mut std::ops::Fn() + 'static: std::marker::Sync` is not satisfied in `std::fmt::Arguments<'_>` --> $DIR/send-sync.rs:19:5 | 19 | sync(format_args!(\"{:?}\", c)); | ^^^^ `*mut std::ops::Fn() + 'static` cannot be shared between threads safely | = help: within `std::fmt::Arguments<'_>`, the trait `std::marker::Sync` is not implemented for `*mut std::ops::Fn() + 'static` = note: required because it appears within the type `std::marker::PhantomData<*mut std::ops::Fn() + 'static>` = note: required because it appears within the type `core::fmt::Void` = note: required because it appears within the type `&core::fmt::Void` = note: required because it appears within the type `std::fmt::ArgumentV1<'_>` = note: required because it appears within the type `[std::fmt::ArgumentV1<'_>]` = note: required because it appears within the type `&[std::fmt::ArgumentV1<'_>]` = note: required because it appears within the type `std::fmt::Arguments<'_>` = note: required by `sync` error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-622573683ffa048603de927952390f1548fdeb6fcf76a9e380e950202a1880f7","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] #[macro_export] #[cfg(dox)] macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ }) } macro_rules! format_args { ($fmt:expr) => ({ /* compiler built-in */ }); ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ }); } /// Inspect an environment variable at compile time. ///"} {"_id":"doc-en-rust-5942075405f0fed830a33197cb2a3bf73cbb9fc59855920db87021817abb3dd9","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] #[macro_export] #[cfg(dox)] macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) } macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }); ($name:expr,) => ({ /* compiler built-in */ }); } /// Optionally inspect an environment variable at compile time. ///"} {"_id":"doc-en-rust-4e9486c540b1cb94190446e9a783c27409b4f31ec5379fc8440ae81704492f70","title":"","text":"#[macro_export] #[cfg(dox)] macro_rules! concat_idents { ($($e:ident),*) => ({ /* compiler built-in */ }) ($($e:ident),*) => ({ /* compiler built-in */ }); ($($e:ident,)*) => ({ /* compiler built-in */ }); } /// Concatenates literals into a static string slice."} {"_id":"doc-en-rust-53c477a99aec5d655d4b4c602f949ff7be16a3c4f6c3f66930b1271eaf79f336","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] #[macro_export] #[cfg(dox)] macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) } macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }); ($($e:expr,)*) => ({ /* compiler built-in */ }); } /// A macro which expands to the line number on which it was invoked. ///"} {"_id":"doc-en-rust-749faed53f7c073ff9e886fb24d1d8c82f31b7906ea6de0745044b1cff9c119d","title":"","text":"/// ``` #[stable(feature = \"rust1\", since = \"1.0.0\")] #[macro_export] macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ }) } macro_rules! format_args { ($fmt:expr) => ({ /* compiler built-in */ }); ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ }); } /// Inspect an environment variable at compile time. ///"} {"_id":"doc-en-rust-16610e2d2bdbf4173a2f8b4c9736bbf426be4a93fb7911378a6de6a82ceba336","title":"","text":"/// ``` #[stable(feature = \"rust1\", since = \"1.0.0\")] #[macro_export] macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) } macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }); ($name:expr,) => ({ /* compiler built-in */ }); } /// Optionally inspect an environment variable at compile time. ///"} {"_id":"doc-en-rust-24d8cc121302451a85c53437d038b377a1fa32ea82f1fe503f7f1f2ba1493f9d","title":"","text":"#[unstable(feature = \"concat_idents_macro\", issue = \"29599\")] #[macro_export] macro_rules! concat_idents { ($($e:ident),*) => ({ /* compiler built-in */ }) ($($e:ident),*) => ({ /* compiler built-in */ }); ($($e:ident,)*) => ({ /* compiler built-in */ }); } /// Concatenates literals into a static string slice."} {"_id":"doc-en-rust-3176ec723acb8e2ad906b2b78d64dd64704083f921c032d4cb3a34b942c8d4c3","title":"","text":"/// ``` #[stable(feature = \"rust1\", since = \"1.0.0\")] #[macro_export] macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) } macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }); ($($e:expr,)*) => ({ /* compiler built-in */ }); } /// A macro which expands to the line number on which it was invoked. ///"} {"_id":"doc-en-rust-80f90d0adb6a2cb0792004b33cece8a498c6c9eb678b501176eed0c396525e2a","title":"","text":"self.search_mut(k).into_occupied_bucket().map(|bucket| pop_internal(bucket).1) } /// Removes a key from the map, returning the stored key and value if the /// key was previously in the map. /// /// The key may be any borrowed form of the map's key type, but /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for /// the key type. /// /// [`Eq`]: ../../std/cmp/trait.Eq.html /// [`Hash`]: ../../std/hash/trait.Hash.html /// /// # Examples /// /// ``` /// #![feature(hash_map_remove_entry)] /// use std::collections::HashMap; /// /// # fn main() { /// let mut map = HashMap::new(); /// map.insert(1, \"a\"); /// assert_eq!(map.remove_entry(&1), Some((1, \"a\"))); /// assert_eq!(map.remove(&1), None); /// # } /// ``` #[unstable(feature = \"hash_map_remove_entry\", issue = \"46344\")] pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> where K: Borrow, Q: Hash + Eq { if self.table.size() == 0 { return None; } self.search_mut(k) .into_occupied_bucket() .map(|bucket| { let (k, v, _) = pop_internal(bucket); (k, v) }) } /// Retains only the elements specified by the predicate. /// /// In other words, remove all pairs `(k, v)` such that `f(&k,&mut v)` returns `false`."} {"_id":"doc-en-rust-bf13118b0889f90f379cb96a04f50df00f9b52fcea5b06fd3ce56fdc00ee8b74","title":"","text":"} #[test] fn test_pop() { fn test_remove() { let mut m = HashMap::new(); m.insert(1, 2); assert_eq!(m.remove(&1), Some(2));"} {"_id":"doc-en-rust-ef62f8d48d655553501497a084ca68078e2417aa5c9ea7860a55f641c86c6346","title":"","text":"} #[test] fn test_remove_entry() { let mut m = HashMap::new(); m.insert(1, 2); assert_eq!(m.remove_entry(&1), Some((1, 2))); assert_eq!(m.remove(&1), None); } #[test] fn test_iterate() { let mut m = HashMap::with_capacity(4); for i in 0..32 {"} {"_id":"doc-en-rust-1b6498d64f2df516330c11510c93a121c360473cb68481dc5074bd6b6fc38f00","title":"","text":"unsafe { let g = get_static(cx, def_id); let v = match ::mir::codegen_static_initializer(cx, def_id) { let (v, alloc) = match ::mir::codegen_static_initializer(cx, def_id) { Ok(v) => v, // Error has already been reported Err(_) => return,"} {"_id":"doc-en-rust-58034db7c293b7c76a26bf6916ea560733c6aa5f5366b86b932b8c5986bf8798","title":"","text":"if attr::contains_name(attrs, \"thread_local\") { llvm::set_thread_local_mode(g, cx.tls_model); // Do not allow LLVM to change the alignment of a TLS on macOS. // // By default a global's alignment can be freely increased. // This allows LLVM to generate more performant instructions // e.g. using load-aligned into a SIMD register. // // However, on macOS 10.10 or below, the dynamic linker does not // respect any alignment given on the TLS (radar 24221680). // This will violate the alignment assumption, and causing segfault at runtime. // // This bug is very easy to trigger. In `println!` and `panic!`, // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS, // which the values would be `mem::replace`d on initialization. // The implementation of `mem::replace` will use SIMD // whenever the size is 32 bytes or higher. LLVM notices SIMD is used // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary, // which macOS's dyld disregarded and causing crashes // (see issues #51794, #51758, #50867, #48866 and #44056). // // To workaround the bug, we trick LLVM into not increasing // the global's alignment by explicitly assigning a section to it // (equivalent to automatically generating a `#[link_section]` attribute). // See the comment in the `GlobalValue::canIncreaseAlignment()` function // of `lib/IR/Globals.cpp` for why this works. // // When the alignment is not increased, the optimized `mem::replace` // will use load-unaligned instructions instead, and thus avoiding the crash. // // We could remove this hack whenever we decide to drop macOS 10.10 support. if cx.tcx.sess.target.target.options.is_like_osx { let sect_name = if alloc.bytes.iter().all(|b| *b == 0) { CStr::from_bytes_with_nul_unchecked(b\"__DATA,__thread_bss0\") } else { CStr::from_bytes_with_nul_unchecked(b\"__DATA,__thread_data0\") }; llvm::LLVMSetSection(g, sect_name.as_ptr()); } } base::set_link_section(cx, g, attrs);"} {"_id":"doc-en-rust-35c67e5fe57b9186bb62742fac6700f1804c45f3d708d86104451fe19ecfb640","title":"","text":"pub fn codegen_static_initializer<'a, 'tcx>( cx: &CodegenCx<'a, 'tcx>, def_id: DefId) -> Result>> -> Result<(ValueRef, &'tcx Allocation), Lrc>> { let instance = ty::Instance::mono(cx.tcx, def_id); let cid = GlobalId {"} {"_id":"doc-en-rust-f8c50fc4fff2dfc4e0d2f788d548d9edc9ee7559afa8745fc145e4b4f9e989d0","title":"","text":"ConstValue::ByRef(alloc, n) if n.bytes() == 0 => alloc, _ => bug!(\"static const eval returned {:#?}\", static_), }; Ok(const_alloc_to_llvm(cx, alloc)) Ok((const_alloc_to_llvm(cx, alloc), alloc)) } impl<'a, 'tcx> FunctionCx<'a, 'tcx> {"} {"_id":"doc-en-rust-fa4fd92f0258c5365df578ba3ef0b6ee40ae91c9eb46c9b13ec017ec59d27c9c","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-tidy-linelength // only-macos // no-system-llvm // min-llvm-version 6.0 // compile-flags: -O #![crate_type = \"rlib\"] #![feature(thread_local)] // CHECK: @STATIC_VAR_1 = internal thread_local unnamed_addr global <{ [32 x i8] }> zeroinitializer, section \"__DATA,__thread_bss\", align 4 #[no_mangle] #[allow(private_no_mangle_statics)] #[thread_local] static mut STATIC_VAR_1: [u32; 8] = [0; 8]; // CHECK: @STATIC_VAR_2 = internal thread_local unnamed_addr global <{ [32 x i8] }> <{{[^>]*}}>, section \"__DATA,__thread_data\", align 4 #[no_mangle] #[allow(private_no_mangle_statics)] #[thread_local] static mut STATIC_VAR_2: [u32; 8] = [4; 8]; #[no_mangle] pub unsafe fn f(x: &mut [u32; 8]) { std::mem::swap(x, &mut STATIC_VAR_1) } #[no_mangle] pub unsafe fn g(x: &mut [u32; 8]) { std::mem::swap(x, &mut STATIC_VAR_2) } "} {"_id":"doc-en-rust-94142aa0f79a6a7a31a5c4cfa05a89738f1e16b3c035a940a1d86ddd1a8b57a3","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // only-x86_64 // no-prefer-dynamic // compile-flags: -Ctarget-feature=+avx -Clto fn main() {} "} {"_id":"doc-en-rust-be8d7951afd48320d53ad23b8bb838a4ad48231ebb1950b9ab740b3ab4053c9c","title":"","text":"self.cx } fn do_not_inline(&mut self, _llret: RValue<'gcc>) { fn apply_attrs_to_cleanup_callsite(&mut self, _llret: RValue<'gcc>) { unimplemented!(); }"} {"_id":"doc-en-rust-05092cfbf38dde0ef4a8d3ca0517c1a819cd860ee738a3a61089243a9d363d83","title":"","text":"unsafe { llvm::LLVMBuildZExt(self.llbuilder, val, dest_ty, UNNAMED) } } fn do_not_inline(&mut self, llret: &'ll Value) { llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret); fn apply_attrs_to_cleanup_callsite(&mut self, llret: &'ll Value) { // Cleanup is always the cold path. llvm::Attribute::Cold.apply_callsite(llvm::AttributePlace::Function, llret); // In LLVM versions with deferred inlining (currently, system LLVM < 14), // inlining drop glue can lead to exponential size blowup, see #41696 and #92110. if !llvm_util::is_rust_llvm() && llvm_util::get_version() < (14, 0, 0) { llvm::Attribute::NoInline.apply_callsite(llvm::AttributePlace::Function, llret); } } }"} {"_id":"doc-en-rust-c318b0b57b40398c3558d6bd1976646172eb9d62fab7464e6c5ee8e01a019b38","title":"","text":"pub fn LLVMRustVersionMinor() -> u32; pub fn LLVMRustVersionPatch() -> u32; pub fn LLVMRustIsRustLLVM() -> bool; pub fn LLVMRustAddModuleFlag(M: &Module, name: *const c_char, value: u32); pub fn LLVMRustMetadataAsValue<'a>(C: &'a Context, MD: &'a Metadata) -> &'a Value;"} {"_id":"doc-en-rust-56bb8d355ca0fe63a60a8f6da31993ec2c262253d74a7385973e8e3518a11c19","title":"","text":"} } /// Returns `true` if this LLVM is Rust's bundled LLVM (and not system LLVM). pub fn is_rust_llvm() -> bool { // Can be called without initializing LLVM unsafe { llvm::LLVMRustIsRustLLVM() } } pub fn print_passes() { // Can be called without initializing LLVM unsafe {"} {"_id":"doc-en-rust-05ce6c97143dc4c1d3ee963fcdd27d7180210c746f109acc313c9db3db327650","title":"","text":"let llret = bx.call(fn_ty, fn_ptr, &llargs, self.funclet(fx)); bx.apply_attrs_callsite(&fn_abi, llret); if fx.mir[self.bb].is_cleanup { // Cleanup is always the cold path. Don't inline // drop glue. Also, when there is a deeply-nested // struct, there are \"symmetry\" issues that cause // exponential inlining - see issue #41696. bx.do_not_inline(llret); bx.apply_attrs_to_cleanup_callsite(llret); } if let Some((ret_dest, target)) = destination {"} {"_id":"doc-en-rust-7744edff9c1fa950f3e15c72095cec46419107f6f2d2fac2890c714d122c8b27","title":"","text":") -> Self::Value; fn zext(&mut self, val: Self::Value, dest_ty: Self::Type) -> Self::Value; fn do_not_inline(&mut self, llret: Self::Value); fn apply_attrs_to_cleanup_callsite(&mut self, llret: Self::Value); }"} {"_id":"doc-en-rust-a269d99deba67795a2ab1583f8defd84947d75c42143bfb1f14ac7a771cc5ea7","title":"","text":"extern \"C\" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; } extern \"C\" bool LLVMRustIsRustLLVM() { #ifdef LLVM_RUSTLLVM return true; #else return false; #endif } extern \"C\" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name, uint32_t Value) { unwrap(M)->addModuleFlag(Module::Warning, Name, Value);"} {"_id":"doc-en-rust-c4a7ecc8f3457bb1e4650efb6538f97718d6434779625e434ef1cc21ed5d6164","title":"","text":" // no-system-llvm: needs #92110 // compile-flags: -Cno-prepopulate-passes #![crate_type = \"lib\"] // This test checks that drop calls in unwind landing pads // get the `cold` attribute. // CHECK-LABEL: @check_cold // CHECK: call void {{.+}}drop_in_place{{.+}} [[ATTRIBUTES:#[0-9]+]] // CHECK: attributes [[ATTRIBUTES]] = { cold } #[no_mangle] pub fn check_cold(f: fn(), x: Box) { // this may unwind f(); } "} {"_id":"doc-en-rust-48a597f693a207bdb0239643e4dd0a55f1f7a61e2ac706f85315713300f1bbe1","title":"","text":" // no-system-llvm: needs #92110 + patch for Rust alloc/dealloc functions // compile-flags: -Copt-level=3 #![crate_type = \"lib\"] // This test checks that we can inline drop_in_place in // unwind landing pads. // Without inlining, the box pointers escape via the call to drop_in_place, // and LLVM will not optimize out the pointer comparison. // With inlining, everything should be optimized out. // See https://github.com/rust-lang/rust/issues/46515 // CHECK-LABEL: @check_no_escape_in_landingpad // CHECK: start: // CHECK-NEXT: ret void #[no_mangle] pub fn check_no_escape_in_landingpad(f: fn()) { let x = &*Box::new(0); let y = &*Box::new(0); if x as *const _ == y as *const _ { f(); } } // Without inlining, the compiler can't tell that // dropping an empty string (in a landing pad) does nothing. // With inlining, the landing pad should be optimized out. // See https://github.com/rust-lang/rust/issues/87055 // CHECK-LABEL: @check_eliminate_noop_drop // CHECK: start: // CHECK-NEXT: call void %g() // CHECK-NEXT: ret void #[no_mangle] pub fn check_eliminate_noop_drop(g: fn()) { let _var = String::new(); g(); } "} {"_id":"doc-en-rust-88f437e0935045a6b06b9848cd82b7f2b88a70ca156246bc905dc41121407b94","title":"","text":"pub fn span_err(&self, sp: Span, m: &str) { self.sess.span_diagnostic.span_err(sp, m) } pub fn struct_span_err(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> { self.sess.span_diagnostic.struct_span_err(sp, m) } pub fn span_err_help(&self, sp: Span, m: &str, h: &str) { let mut err = self.sess.span_diagnostic.mut_span_err(sp, m); err.help(h);"} {"_id":"doc-en-rust-8ef35b8315ec14874faf603b9aa8bfc831497cc339609a4a46dde65e987dab64","title":"","text":"let lo = self.span; let hi; if self.check(&token::DotDot) { if self.check(&token::DotDot) || self.token == token::DotDotDot { if self.token == token::DotDotDot { // Issue #46718 let mut err = self.struct_span_err(self.span, \"expected field pattern, found `...`\"); err.span_suggestion(self.span, \"to omit remaining fields, use one fewer `.`\", \"..\".to_owned()); err.emit(); } self.bump(); if self.token != token::CloseDelim(token::Brace) { let token_str = self.this_token_to_string();"} {"_id":"doc-en-rust-f9d5eab9f84c50bab35d6e099e86fc7b6c7cfd67a7aab63ea606173a9f2d4360","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unused)] struct PersonalityInventory { expressivity: f32, instrumentality: f32 } impl PersonalityInventory { fn expressivity(&self) -> f32 { match *self { PersonalityInventory { expressivity: exp, ... } => exp //~^ ERROR expected field pattern, found `...` } } } fn main() {} "} {"_id":"doc-en-rust-63623d14d4deb8ff00b9c19e89ea01505680d500292eaddf2d4d568c2aebc510","title":"","text":" error: expected field pattern, found `...` --> $DIR/issue-46718-struct-pattern-dotdotdot.rs:21:55 | 21 | PersonalityInventory { expressivity: exp, ... } => exp | ^^^ help: to omit remaining fields, use one fewer `.`: `..` error: aborting due to previous error "} {"_id":"doc-en-rust-8552b4bbca2681b16494e8df3f134a033220353a7449805cdd3fc55b570dd355","title":"","text":"} #[unstable(feature = \"control_flow_enum\", reason = \"new API\", issue = \"75744\")] #[cfg(bootstrap)] impl ops::TryV1 for ControlFlow { type Output = C; type Error = B;"} {"_id":"doc-en-rust-03cde51af3d118e06d85440924d13146b78ed4afad2d81c9c72e63a6d0bf793a","title":"","text":"mod generator; mod index; mod range; #[cfg(bootstrap)] mod r#try; mod try_trait; mod unsize;"} {"_id":"doc-en-rust-3a2b56a2b0ddc2e798486acb8d5da9fddb83e81adaca214fb1e1643642df2b82","title":"","text":"pub use self::r#try::Try; #[unstable(feature = \"try_trait_transition\", reason = \"for bootstrap\", issue = \"none\")] #[cfg(bootstrap)] pub(crate) use self::r#try::Try as TryV1; #[unstable(feature = \"try_trait_v2\", issue = \"84277\")]"} {"_id":"doc-en-rust-67a483e5a182416a99b7e0eb0dcb07f6cc657d164ed16c9ce0c4e4691cf72258","title":"","text":"#[rustc_diagnostic_item = \"none_error\"] #[unstable(feature = \"try_trait\", issue = \"42327\")] #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] #[cfg(bootstrap)] pub struct NoneError; #[unstable(feature = \"try_trait\", issue = \"42327\")] #[cfg(bootstrap)] impl ops::TryV1 for Option { type Output = T; type Error = NoneError;"} {"_id":"doc-en-rust-8a99df5fc223329771fa1714a462b1325c70a8f9aadedaff8e0fb3f4b9c4b023","title":"","text":"} #[unstable(feature = \"try_trait\", issue = \"42327\")] #[cfg(bootstrap)] impl ops::TryV1 for Result { type Output = T; type Error = E;"} {"_id":"doc-en-rust-3365424a26fca5b24278e780012dbb520467165bd7f11e905c67b5ae2db5164a","title":"","text":"} #[stable(feature = \"futures_api\", since = \"1.36.0\")] #[cfg(bootstrap)] impl ops::TryV1 for Poll> { type Output = Poll; type Error = E;"} {"_id":"doc-en-rust-f95b0b6cba1b8b8899521ede3ba73cd900d8205242043cb52c4704d50e4dca0e","title":"","text":"} #[stable(feature = \"futures_api\", since = \"1.36.0\")] #[cfg(bootstrap)] impl ops::TryV1 for Poll>> { type Output = Poll>; type Error = E;"} {"_id":"doc-en-rust-9e5adc2aadc7f6813d67e7abb44b376b310b7457137f0c551d556da6c26859e0","title":"","text":"#![feature(str_internals)] #![feature(test)] #![feature(trusted_len)] #![feature(try_trait)] #![feature(try_trait_v2)] #![feature(slice_internals)] #![feature(slice_partition_dedup)]"} {"_id":"doc-en-rust-7fe509292d390edc241c3fb8c8ca824f9cb73ba1ff66eb30bc633b241e4ba585","title":"","text":"/// types inside a `Vec`, it will not allocate space for them. *Note that in this case /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only /// if [`mem::size_of::`]`() * capacity() > 0`. In general, `Vec`'s allocation /// details are subtle enough that it is strongly recommended that you only /// free memory allocated by a `Vec` by creating a new `Vec` and dropping it. /// details are very subtle — if you intend to allocate memory using a `Vec` /// and use it for something else (either to pass to unsafe code, or to build your /// own memory-backed collection), be sure to deallocate this memory by using /// `from_raw_parts` to recover the `Vec` and then dropping it. /// /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap /// (as defined by the allocator Rust is configured to use by default), and its"} {"_id":"doc-en-rust-b300871df0a0886d90c105ee94d301301842ca0562447edd3f30f029389f1c71","title":"","text":"res.recv(); } #[test] #[should_fail] #[ignore(cfg(windows))] #[test] #[should_fail] #[ignore(reason = \"random red\")] pub fn exclusive_unwrap_conflict() { let x = exclusive(~~\"hello\"); let x2 = ~mut Some(x.clone());"} {"_id":"doc-en-rust-58ceae4e766a3d946787e1d99a754d5b72f60879799106646de421d2d26dfa85","title":"","text":"#[cfg(not(test))] pub fn init() { // The standard streams might be closed on application startup. To prevent // std::io::{stdin, stdout,stderr} objects from using other unrelated file // resources opened later, we reopen standards streams when they are closed. unsafe { sanitize_standard_fds(); } // By default, some platforms will send a *signal* when an EPIPE error // would otherwise be delivered. This runtime doesn't install a SIGPIPE // handler, causing it to kill the program, which isn't exactly what we"} {"_id":"doc-en-rust-9178605905302613c7be437c27e222331862f8d45f89df0660bbed35fa739844","title":"","text":"reset_sigpipe(); } // In the case when all file descriptors are open, the poll has been // observed to perform better than fcntl (on GNU/Linux). #[cfg(not(any( miri, target_os = \"emscripten\", target_os = \"fuchsia\", // The poll on Darwin doesn't set POLLNVAL for closed fds. target_os = \"macos\", target_os = \"ios\", target_os = \"redox\", )))] unsafe fn sanitize_standard_fds() { use crate::sys::os::errno; let pfds: &mut [_] = &mut [ libc::pollfd { fd: 0, events: 0, revents: 0 }, libc::pollfd { fd: 1, events: 0, revents: 0 }, libc::pollfd { fd: 2, events: 0, revents: 0 }, ]; while libc::poll(pfds.as_mut_ptr(), 3, 0) == -1 { if errno() == libc::EINTR { continue; } libc::abort(); } for pfd in pfds { if pfd.revents & libc::POLLNVAL == 0 { continue; } if libc::open(\"/dev/null0\".as_ptr().cast(), libc::O_RDWR, 0) == -1 { // If the stream is closed but we failed to reopen it, abort the // process. Otherwise we wouldn't preserve the safety of // operations on the corresponding Rust object Stdin, Stdout, or // Stderr. libc::abort(); } } } #[cfg(any(target_os = \"macos\", target_os = \"ios\", target_os = \"redox\"))] unsafe fn sanitize_standard_fds() { use crate::sys::os::errno; for fd in 0..3 { if libc::fcntl(fd, libc::F_GETFD) == -1 && errno() == libc::EBADF { if libc::open(\"/dev/null0\".as_ptr().cast(), libc::O_RDWR, 0) == -1 { libc::abort(); } } } } #[cfg(any( // The standard fds are always available in Miri. miri, target_os = \"emscripten\", target_os = \"fuchsia\"))] unsafe fn sanitize_standard_fds() {} #[cfg(not(any(target_os = \"emscripten\", target_os = \"fuchsia\")))] unsafe fn reset_sigpipe() { assert!(signal(libc::SIGPIPE, libc::SIG_IGN) != libc::SIG_ERR);"} {"_id":"doc-en-rust-5e6e216a450ff4e78146a044fb150923fbaadb7ff04f7c2c04c68b2235049db7","title":"","text":"return r } #[cfg(unix)] fn assert_fd_is_valid(fd: libc::c_int) { if unsafe { libc::fcntl(fd, libc::F_GETFD) == -1 } { panic!(\"file descriptor {} is not valid: {}\", fd, io::Error::last_os_error()); } } #[cfg(windows)] fn assert_fd_is_valid(_fd: libc::c_int) {} #[cfg(windows)] unsafe fn without_stdio R>(f: F) -> R { type DWORD = u32;"} {"_id":"doc-en-rust-10955d1a056df244f67e7b6ed7dc556b2faf8372095677fed1cf2969d07d865a","title":"","text":"fn main() { if env::args().len() > 1 { // Writing to stdout & stderr should not panic. println!(\"test\"); assert!(io::stdout().write(b\"testn\").is_ok()); assert!(io::stderr().write(b\"testn\").is_ok()); // Stdin should be at EOF. assert_eq!(io::stdin().read(&mut [0; 10]).unwrap(), 0); // Standard file descriptors should be valid on UNIX: assert_fd_is_valid(0); assert_fd_is_valid(1); assert_fd_is_valid(2); return }"} {"_id":"doc-en-rust-553a72461ab4599584323b0ea5ffd75172b65acc206ff2fa8f827934ba599249","title":"","text":".stdout(Stdio::null()) .stderr(Stdio::null()) .status().unwrap(); assert!(status.success(), \"{:?} isn't a success\", status); assert!(status.success(), \"{} isn't a success\", status); // Finally, close everything then spawn a child to make sure everything is // *still* ok. let status = unsafe { without_stdio(|| Command::new(&me).arg(\"next\").status()) }.unwrap(); assert!(status.success(), \"{:?} isn't a success\", status); assert!(status.success(), \"{} isn't a success\", status); }"} {"_id":"doc-en-rust-85ae90fc152b8170f5529441cac0dbbc36f37c328d2f4362d9cd0725eba757b4","title":"","text":"end: RangeEnd, }, /// matches against a slice, checking the length and extracting elements /// matches against a slice, checking the length and extracting elements. /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty. /// e.g. `&[ref xs..]`. Slice { prefix: Vec>, slice: Option>,"} {"_id":"doc-en-rust-d53fdb8236224f3e71e942ffe37c9ed3bc0f4b8c70a032269a15d3abcb5d5b9e","title":"","text":"Err(match_pair) } PatternKind::Range { .. } | PatternKind::Slice { .. } => { PatternKind::Range { .. } => { Err(match_pair) } PatternKind::Slice { ref prefix, ref slice, ref suffix } => { if prefix.is_empty() && slice.is_some() && suffix.is_empty() { // irrefutable self.prefix_slice_suffix(&mut candidate.match_pairs, &match_pair.place, prefix, slice.as_ref(), suffix); Ok(()) } else { Err(match_pair) } } PatternKind::Variant { adt_def, substs, variant_index, ref subpatterns } => { let irrefutable = adt_def.variants.iter().enumerate().all(|(i, v)| { i == variant_index || {"} {"_id":"doc-en-rust-6a9992d9603d4cff194241164f916337acf81cc9955cdeac52a4785d35eb507b","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // #47096 #![feature(slice_patterns)] fn foo(s: &[i32]) -> &[i32] { let &[ref xs..] = s; xs } fn main() { let x = [1, 2, 3]; let y = foo(&x); assert_eq!(x, y); } "} {"_id":"doc-en-rust-9762910d2b6f19293d73d3cc756c6409f3364162c3f3beea52f64e00319423c2","title":"","text":"#[test] #[should_fail] fn test_ascii_fail_char_slice() { 'λ'.to_ascii(); } #[test] fn test_opt() { assert_eq!(65u8.to_ascii_opt(), Some(Ascii { chr: 65u8 })); assert_eq!(255u8.to_ascii_opt(), None);"} {"_id":"doc-en-rust-4f364c3a7ac175416d7de0bfa548fe5d035aa34591deab75c6e92ce09a5b477d","title":"","text":"#[cfg(test)] mod test { use super::*; use io::net::ip::{Ipv4Addr, SocketAddr}; use io::net::ip::{SocketAddr}; use io::*; use io::test::*; use prelude::*; iotest!(fn bind_error() {"} {"_id":"doc-en-rust-5d110b67007dd1a09594f98d99756e0d9851fbde36fd5df6266cdafb756c65b0","title":"","text":"use unstable::run_in_bare_thread; use super::*; use rt::task::Task; use rt::local_ptr; #[test] fn thread_local_task_smoke_test() {"} {"_id":"doc-en-rust-32df046ed9398822e0a52403416862c280c77878d1c4aa46da47d15f25d4e043","title":"","text":"fn visit_estr_uniq(&mut self) -> bool { true } fn visit_estr_slice(&mut self) -> bool { true } fn visit_estr_fixed(&mut self, _sz: uint, _sz: uint, _sz: uint, _sz2: uint, _align: uint) -> bool { true } fn visit_box(&mut self, _mtbl: uint, _inner: *TyDesc) -> bool { true }"} {"_id":"doc-en-rust-abe1f8d82e63f3230f48cf2b8b49040ac3b2df93dc9d1df00f735c9c4469e5e7","title":"","text":"&substs[..] )); } DefiningTy::Const(ty) => { DefiningTy::Const(def_id, substs) => { err.note(&format!( \"defining type: {:?}\", ty \"defining constant type: {:?} with substs {:#?}\", def_id, &substs[..] )); } }"} {"_id":"doc-en-rust-11ca6763e7e4dd0f68516f4836e5245586ad766c258c17984ea0f58522514cfc","title":"","text":"/// The MIR represents some form of constant. The signature then /// is that it has no inputs and a single return value, which is /// the value of the constant. Const(Ty<'tcx>), Const(DefId, &'tcx Substs<'tcx>), } #[derive(Debug)]"} {"_id":"doc-en-rust-cedd8f1d965016247bbf172aba191e26648da5a28c164eb03b17bfdc3ad159cc","title":"","text":"/// see `DefiningTy` for details. fn defining_ty(&self) -> DefiningTy<'tcx> { let tcx = self.infcx.tcx; let closure_base_def_id = tcx.closure_base_def_id(self.mir_def_id); let defining_ty = if self.mir_def_id == closure_base_def_id { tcx.type_of(closure_base_def_id) } else { let tables = tcx.typeck_tables_of(self.mir_def_id); tables.node_id_to_type(self.mir_hir_id) }; let defining_ty = self.infcx .replace_free_regions_with_nll_infer_vars(FR, &defining_ty); match tcx.hir.body_owner_kind(self.mir_node_id) { BodyOwnerKind::Fn => match defining_ty.sty { ty::TyClosure(def_id, substs) => DefiningTy::Closure(def_id, substs), ty::TyGenerator(def_id, substs, interior) => { DefiningTy::Generator(def_id, substs, interior) BodyOwnerKind::Fn => { let defining_ty = if self.mir_def_id == closure_base_def_id { tcx.type_of(closure_base_def_id) } else { let tables = tcx.typeck_tables_of(self.mir_def_id); tables.node_id_to_type(self.mir_hir_id) }; let defining_ty = self.infcx .replace_free_regions_with_nll_infer_vars(FR, &defining_ty); match defining_ty.sty { ty::TyClosure(def_id, substs) => DefiningTy::Closure(def_id, substs), ty::TyGenerator(def_id, substs, interior) => { DefiningTy::Generator(def_id, substs, interior) } ty::TyFnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs), _ => span_bug!( tcx.def_span(self.mir_def_id), \"expected defining type for `{:?}`: `{:?}`\", self.mir_def_id, defining_ty ), } ty::TyFnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs), _ => span_bug!( tcx.def_span(self.mir_def_id), \"expected defining type for `{:?}`: `{:?}`\", self.mir_def_id, defining_ty ), }, BodyOwnerKind::Const | BodyOwnerKind::Static(..) => DefiningTy::Const(defining_ty), } BodyOwnerKind::Const | BodyOwnerKind::Static(..) => { assert_eq!(closure_base_def_id, self.mir_def_id); let identity_substs = Substs::identity_for_item(tcx, closure_base_def_id); let substs = self.infcx .replace_free_regions_with_nll_infer_vars(FR, &identity_substs); DefiningTy::Const(self.mir_def_id, substs) } } }"} {"_id":"doc-en-rust-ab5394f6f844e8f0bb1918668550975fa12034384454bbf5a6919a3ef1bd21d5","title":"","text":"substs.substs } DefiningTy::FnDef(_, substs) => substs, // When we encounter a constant body, just return whatever // substitutions are in scope for that constant. DefiningTy::Const(_) => { identity_substs } DefiningTy::FnDef(_, substs) | DefiningTy::Const(_, substs) => substs, }; let global_mapping = iter::once((gcx.types.re_static, fr_static));"} {"_id":"doc-en-rust-fbfc9c9274e50b04a09269c27af72437cc912cf11c0fafd6d9644b1e79949817","title":"","text":"sig.inputs_and_output() } // For a constant body, there are no inputs, and one // \"output\" (the type of the constant). DefiningTy::Const(ty) => ty::Binder::dummy(tcx.mk_type_list(iter::once(ty))), DefiningTy::Const(def_id, _) => { // For a constant body, there are no inputs, and one // \"output\" (the type of the constant). assert_eq!(self.mir_def_id, def_id); let ty = tcx.type_of(def_id); let ty = indices.fold_to_region_vids(tcx, &ty); ty::Binder::dummy(tcx.mk_type_list(iter::once(ty))) } } }"} {"_id":"doc-en-rust-0c24c035f54cd0270ce632b5c82f3bd4a2fa478dd1570e806d1530afc4cd581e","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test cases where we put various lifetime constraints on trait // associated constants. #![feature(rustc_attrs)] use std::option::Option; trait Anything<'a: 'b, 'b> { const AC: Option<&'b str>; } struct OKStruct { } impl<'a: 'b, 'b> Anything<'a, 'b> for OKStruct { const AC: Option<&'b str> = None; } struct FailStruct1 { } impl<'a: 'b, 'b, 'c> Anything<'a, 'b> for FailStruct1 { const AC: Option<&'c str> = None; //~^ ERROR: mismatched types } struct FailStruct2 { } impl<'a: 'b, 'b> Anything<'a, 'b> for FailStruct2 { const AC: Option<&'a str> = None; //~^ ERROR: mismatched types } fn main() {} "} {"_id":"doc-en-rust-f1eee7ab3b4ebe8597f9879fedb6d14f2d3da9a641c2e16c1bea0259c6c1cc5e","title":"","text":" error[E0308]: mismatched types --> $DIR/trait-associated-constant.rs:31:5 | 31 | const AC: Option<&'c str> = None; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch | = note: expected type `std::option::Option<&'b str>` found type `std::option::Option<&'c str>` note: the lifetime 'c as defined on the impl at 30:1... --> $DIR/trait-associated-constant.rs:30:1 | 30 | impl<'a: 'b, 'b, 'c> Anything<'a, 'b> for FailStruct1 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: ...does not necessarily outlive the lifetime 'b as defined on the impl at 30:1 --> $DIR/trait-associated-constant.rs:30:1 | 30 | impl<'a: 'b, 'b, 'c> Anything<'a, 'b> for FailStruct1 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0308]: mismatched types --> $DIR/trait-associated-constant.rs:38:5 | 38 | const AC: Option<&'a str> = None; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch | = note: expected type `std::option::Option<&'b str>` found type `std::option::Option<&'a str>` note: the lifetime 'a as defined on the impl at 37:1... --> $DIR/trait-associated-constant.rs:37:1 | 37 | impl<'a: 'b, 'b> Anything<'a, 'b> for FailStruct2 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: ...does not necessarily outlive the lifetime 'b as defined on the impl at 37:1 --> $DIR/trait-associated-constant.rs:37:1 | 37 | impl<'a: 'b, 'b> Anything<'a, 'b> for FailStruct2 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-e5e9c71310a95f763f2f0377e27cc3dc83c21c9ae2c013f5eb7ae4bbb102c63e","title":"","text":"} OptLevel::Default } else { match ( cg.opt_level.as_ref().map(String::as_ref), nightly_options::is_nightly_build(), ) { (None, _) => OptLevel::No, (Some(\"0\"), _) => OptLevel::No, (Some(\"1\"), _) => OptLevel::Less, (Some(\"2\"), _) => OptLevel::Default, (Some(\"3\"), _) => OptLevel::Aggressive, (Some(\"s\"), true) => OptLevel::Size, (Some(\"z\"), true) => OptLevel::SizeMin, (Some(\"s\"), false) | (Some(\"z\"), false) => { early_error( error_format, &format!( \"the optimizations s or z are only accepted on the nightly compiler\" ), ); } (Some(arg), _) => { match cg.opt_level.as_ref().map(String::as_ref) { None => OptLevel::No, Some(\"0\") => OptLevel::No, Some(\"1\") => OptLevel::Less, Some(\"2\") => OptLevel::Default, Some(\"3\") => OptLevel::Aggressive, Some(\"s\") => OptLevel::Size, Some(\"z\") => OptLevel::SizeMin, Some(arg) => { early_error( error_format, &format!("} {"_id":"doc-en-rust-3559168aea93e302adde5406e73f68afaeaf0bb160ec90cd850b417eb01f1e03","title":"","text":"pub use run::{cmd, run, run_fail, run_with_args}; /// Helpers for checking target information. pub use targets::{is_darwin, is_msvc, is_windows, llvm_components_contain, target, uname}; pub use targets::{is_darwin, is_msvc, is_windows, llvm_components_contain, target, uname, apple_os}; /// Helpers for building names of output artifacts that are potentially target-specific. pub use artifact_names::{"} {"_id":"doc-en-rust-8aedff545db014c3ef22da1aa04c708a69c31352ac18e2e6f0e1def42499d373","title":"","text":"target().contains(\"darwin\") } /// Get the target OS on Apple operating systems. #[must_use] pub fn apple_os() -> &'static str { if target().contains(\"darwin\") { \"macos\" } else if target().contains(\"ios\") { \"ios\" } else if target().contains(\"tvos\") { \"tvos\" } else if target().contains(\"watchos\") { \"watchos\" } else if target().contains(\"visionos\") { \"visionos\" } else { panic!(\"not an Apple OS\") } } /// Check if `component` is within `LLVM_COMPONENTS` #[must_use] pub fn llvm_components_contain(component: &str) -> bool {"} {"_id":"doc-en-rust-526637e713067f40f09a494a041d65ac005826783c4537e5b116d11878fa1343","title":"","text":"run-make/issue-84395-lto-embed-bitcode/Makefile run-make/jobserver-error/Makefile run-make/libs-through-symlinks/Makefile run-make/macos-deployment-target/Makefile run-make/split-debuginfo/Makefile run-make/symbol-mangling-hashed/Makefile run-make/translation/Makefile"} {"_id":"doc-en-rust-3b96216a4f07be510bdf607eb604a6e4d81c808a73f62dd025ac56efd69e276d","title":"","text":" //! Test codegen when setting deployment targets on Apple platforms. //! //! This is important since its a compatibility hazard. The linker will //! generate load commands differently based on what minimum OS it can assume. //! //! See https://github.com/rust-lang/rust/pull/105123. //@ only-apple use run_make_support::{apple_os, cmd, run_in_tmpdir, rustc, target}; /// Run vtool to check the `minos` field in LC_BUILD_VERSION. /// /// On lower deployment targets, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS and similar /// are used instead of LC_BUILD_VERSION - these have a `version` field, so also check that. #[track_caller] fn minos(file: &str, version: &str) { cmd(\"vtool\") .arg(\"-show-build\") .arg(file) .run() .assert_stdout_contains_regex(format!(\"(minos|version) {version}\")); } fn main() { // These versions should generally be higher than the default versions let (env_var, example_version, higher_example_version) = match apple_os() { \"macos\" => (\"MACOSX_DEPLOYMENT_TARGET\", \"12.0\", \"13.0\"), // armv7s-apple-ios and i386-apple-ios only supports iOS 10.0 \"ios\" if target() == \"armv7s-apple-ios\" || target() == \"i386-apple-ios\" => { (\"IPHONEOS_DEPLOYMENT_TARGET\", \"10.0\", \"10.0\") } \"ios\" => (\"IPHONEOS_DEPLOYMENT_TARGET\", \"15.0\", \"16.0\"), \"watchos\" => (\"WATCHOS_DEPLOYMENT_TARGET\", \"7.0\", \"9.0\"), \"tvos\" => (\"TVOS_DEPLOYMENT_TARGET\", \"14.0\", \"15.0\"), \"visionos\" => (\"XROS_DEPLOYMENT_TARGET\", \"1.1\", \"1.2\"), _ => unreachable!(), }; let default_version = rustc().target(target()).env_remove(env_var).print(\"deployment-target\").run().stdout_utf8(); let default_version = default_version.strip_prefix(\"deployment_target=\").unwrap().trim(); // Test that version makes it to the object file. run_in_tmpdir(|| { let rustc = || { let mut rustc = rustc(); rustc.target(target()); rustc.crate_type(\"lib\"); rustc.emit(\"obj\"); rustc.input(\"foo.rs\"); rustc.output(\"foo.o\"); rustc }; rustc().env(env_var, example_version).run(); minos(\"foo.o\", example_version); // FIXME(madsmtm): Doesn't work on Mac Catalyst and the simulator. if !target().contains(\"macabi\") && !target().contains(\"sim\") { rustc().env_remove(env_var).run(); minos(\"foo.o\", default_version); } }); // Test that version makes it to the linker when linking dylibs. run_in_tmpdir(|| { // Certain watchOS targets don't support dynamic linking, so we disable the test on those. if apple_os() == \"watchos\" { return; } let rustc = || { let mut rustc = rustc(); rustc.target(target()); rustc.crate_type(\"dylib\"); rustc.input(\"foo.rs\"); rustc.output(\"libfoo.dylib\"); rustc }; rustc().env(env_var, example_version).run(); minos(\"libfoo.dylib\", example_version); // FIXME(madsmtm): Deployment target is not currently passed properly to linker // rustc().env_remove(env_var).run(); // minos(\"libfoo.dylib\", default_version); // Test with ld64 instead rustc().arg(\"-Clinker-flavor=ld\").env(env_var, example_version).run(); minos(\"libfoo.dylib\", example_version); rustc().arg(\"-Clinker-flavor=ld\").env_remove(env_var).run(); minos(\"libfoo.dylib\", default_version); }); // Test that version makes it to the linker when linking executables. run_in_tmpdir(|| { let rustc = || { let mut rustc = rustc(); rustc.target(target()); rustc.crate_type(\"bin\"); rustc.input(\"foo.rs\"); rustc.output(\"foo\"); rustc }; // FIXME(madsmtm): Doesn't work on watchOS for some reason? if !target().contains(\"watchos\") { rustc().env(env_var, example_version).run(); minos(\"foo\", example_version); // FIXME(madsmtm): Deployment target is not currently passed properly to linker // rustc().env_remove(env_var).run(); // minos(\"foo\", default_version); } // Test with ld64 instead rustc().arg(\"-Clinker-flavor=ld\").env(env_var, example_version).run(); minos(\"foo\", example_version); rustc().arg(\"-Clinker-flavor=ld\").env_remove(env_var).run(); minos(\"foo\", default_version); }); // Test that changing the deployment target busts the incremental cache. run_in_tmpdir(|| { let rustc = || { let mut rustc = rustc(); rustc.target(target()); rustc.incremental(\"incremental\"); rustc.crate_type(\"lib\"); rustc.emit(\"obj\"); rustc.input(\"foo.rs\"); rustc.output(\"foo.o\"); rustc }; // FIXME(madsmtm): Incremental cache is not yet busted // https://github.com/rust-lang/rust/issues/118204 let higher_example_version = example_version; let default_version = example_version; rustc().env(env_var, example_version).run(); minos(\"foo.o\", example_version); rustc().env(env_var, higher_example_version).run(); minos(\"foo.o\", higher_example_version); // FIXME(madsmtm): Doesn't work on Mac Catalyst and the simulator. if !target().contains(\"macabi\") && !target().contains(\"sim\") { rustc().env_remove(env_var).run(); minos(\"foo.o\", default_version); } }); } "} {"_id":"doc-en-rust-6e80604eeae16ad6a8bca2c1f7a11ed8048968f8bd616173e2f7c0ddd0983016","title":"","text":" # only-macos # # Check that a set deployment target actually makes it to the linker. # This is important since its a compatibility hazard. The linker will # generate load commands differently based on what minimum OS it can assume. include ../tools.mk ifeq ($(strip $(shell uname -m)),arm64) GREP_PATTERN = \"minos 11.0\" else GREP_PATTERN = \"version 10.13\" endif OUT_FILE=$(TMPDIR)/with_deployment_target.dylib all: env MACOSX_DEPLOYMENT_TARGET=10.13 $(RUSTC) with_deployment_target.rs -o $(OUT_FILE) # XXX: The check is for either the x86_64 minimum OR the aarch64 minimum (M1 starts at macOS 11). # They also use different load commands, so we let that change with each too. The aarch64 check # isn't as robust as the x86 one, but testing both seems unneeded. vtool -show-build $(OUT_FILE) | $(CGREP) -e $(GREP_PATTERN) "} {"_id":"doc-en-rust-eea61b8e439907a97a1bf007dee4f6dfcf8c6cbb9386426e0af52d7750102253","title":"","text":" #![crate_type = \"cdylib\"] #[allow(dead_code)] fn something_and_nothing() {} "} {"_id":"doc-en-rust-9097b8a45bac3c90f70312340b854da9e35800503b65cb54ec7d30b931e4ebeb","title":"","text":")*) } step_impl_unsigned!(usize u8 u16 u32); step_impl_signed!([isize: usize] [i8: u8] [i16: u16] [i32: u32]); step_impl_unsigned!(usize u8 u16); #[cfg(not(target_pointer_witdth = \"16\"))] step_impl_unsigned!(u32); #[cfg(target_pointer_witdth = \"16\")] step_impl_no_between!(u32); step_impl_signed!([isize: usize] [i8: u8] [i16: u16]); #[cfg(not(target_pointer_witdth = \"16\"))] step_impl_signed!([i32: u32]); #[cfg(target_pointer_witdth = \"16\")] step_impl_no_between!(i32); #[cfg(target_pointer_width = \"64\")] step_impl_unsigned!(u64); #[cfg(target_pointer_width = \"64\")]"} {"_id":"doc-en-rust-d7cf68e03cc08eb0497837fd88ba437385b86174b4c16a541d16b66e2ec2e920","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(step_trait)] use std::iter::Step; #[cfg(target_pointer_width = \"16\")] fn main() { assert!(Step::steps_between(&0u32, &::std::u32::MAX).is_none()); } #[cfg(any(target_pointer_width = \"32\", target_pointer_width = \"64\"))] fn main() { assert!(Step::steps_between(&0u32, &::std::u32::MAX).is_some()); } "} {"_id":"doc-en-rust-f639295df9bd378e7048a0c34e33364f85360f91286c169e7d788fff75bccade","title":"","text":"cfg.file(\"../rustllvm/PassWrapper.cpp\") .file(\"../rustllvm/RustWrapper.cpp\") .file(\"../rustllvm/ArchiveWrapper.cpp\") .file(\"../rustllvm/Linker.cpp\") .cpp(true) .cpp_link_stdlib(None) // we handle this below .compile(\"rustllvm\");"} {"_id":"doc-en-rust-e92f6773c938b7f151b8f7097af8ee95d360c08d86c5b4163ae4c599039588bf","title":"","text":"#[allow(missing_copy_implementations)] pub enum OperandBundleDef_opaque {} pub type OperandBundleDefRef = *mut OperandBundleDef_opaque; #[allow(missing_copy_implementations)] pub enum Linker_opaque {} pub type LinkerRef = *mut Linker_opaque; pub type DiagnosticHandler = unsafe extern \"C\" fn(DiagnosticInfoRef, *mut c_void); pub type InlineAsmDiagHandler = unsafe extern \"C\" fn(SMDiagnosticRef, *const c_void, c_uint);"} {"_id":"doc-en-rust-d62d16b9035a2079a4029414dfae1dd512cf94c42945ef0ff5b76ff998e37662","title":"","text":"pub fn LLVMRustPrintPasses(); pub fn LLVMRustSetNormalizedTarget(M: ModuleRef, triple: *const c_char); pub fn LLVMRustAddAlwaysInlinePass(P: PassManagerBuilderRef, AddLifetimes: bool); pub fn LLVMRustLinkInExternalBitcode(M: ModuleRef, bc: *const c_char, len: size_t) -> bool; pub fn LLVMRustRunRestrictionPass(M: ModuleRef, syms: *const *const c_char, len: size_t); pub fn LLVMRustMarkAllFunctionsNounwind(M: ModuleRef);"} {"_id":"doc-en-rust-ae1b295185e2054c7d1a5275e5347a1773c644485556cfc458cdf9f5ebb86c03","title":"","text":"CU2: *mut *mut c_void); pub fn LLVMRustThinLTOPatchDICompileUnit(M: ModuleRef, CU: *mut c_void); pub fn LLVMRustThinLTORemoveAvailableExternally(M: ModuleRef); pub fn LLVMRustLinkerNew(M: ModuleRef) -> LinkerRef; pub fn LLVMRustLinkerAdd(linker: LinkerRef, bytecode: *const c_char, bytecode_len: usize) -> bool; pub fn LLVMRustLinkerFree(linker: LinkerRef); }"} {"_id":"doc-en-rust-ddc9a7ca9f860b8334becadfc7c187c3d0a5e56291d918fb0e8eff2c6fab2cee","title":"","text":"// know much about the memory management here so we err on the side of being // save and persist everything with the original module. let mut serialized_bitcode = Vec::new(); let mut linker = Linker::new(llmod); for (bc_decoded, name) in serialized_modules { info!(\"linking {:?}\", name); time(cgcx.time_passes, &format!(\"ll link {:?}\", name), || unsafe { time(cgcx.time_passes, &format!(\"ll link {:?}\", name), || { let data = bc_decoded.data(); if llvm::LLVMRustLinkInExternalBitcode(llmod, data.as_ptr() as *const libc::c_char, data.len() as libc::size_t) { Ok(()) } else { linker.add(&data).map_err(|()| { let msg = format!(\"failed to load bc of {:?}\", name); Err(write::llvm_err(&diag_handler, msg)) } write::llvm_err(&diag_handler, msg) }) })?; timeline.record(&format!(\"link {:?}\", name)); serialized_bitcode.push(bc_decoded); } drop(linker); cgcx.save_temp_bitcode(&module, \"lto.input\"); // Internalize everything that *isn't* in our whitelist to help strip out"} {"_id":"doc-en-rust-677854bd1a48e183a3f0017d24fc50ea5cc3c6912a4c9ca1b57bdc94009e63b8","title":"","text":"}]) } struct Linker(llvm::LinkerRef); impl Linker { fn new(llmod: ModuleRef) -> Linker { unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) } } fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> { unsafe { if llvm::LLVMRustLinkerAdd(self.0, bytecode.as_ptr() as *const libc::c_char, bytecode.len()) { Ok(()) } else { Err(()) } } } } impl Drop for Linker { fn drop(&mut self) { unsafe { llvm::LLVMRustLinkerFree(self.0); } } } /// Prepare \"thin\" LTO to get run on these modules. /// /// The general structure of ThinLTO is quite different from the structure of"} {"_id":"doc-en-rust-0c3ee09cb802fcb50328876b81c79d0d7478ff2073f9856f8e409e3f9f424355","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #include \"llvm/Linker/Linker.h\" #include \"rustllvm.h\" using namespace llvm; struct RustLinker { Linker L; LLVMContext &Ctx; RustLinker(Module &M) : L(M), Ctx(M.getContext()) {} }; extern \"C\" RustLinker* LLVMRustLinkerNew(LLVMModuleRef DstRef) { Module *Dst = unwrap(DstRef); auto Ret = llvm::make_unique(*Dst); return Ret.release(); } extern \"C\" void LLVMRustLinkerFree(RustLinker *L) { delete L; } extern \"C\" bool LLVMRustLinkerAdd(RustLinker *L, char *BC, size_t Len) { std::unique_ptr Buf = MemoryBuffer::getMemBufferCopy(StringRef(BC, Len)); #if LLVM_VERSION_GE(4, 0) Expected> SrcOrError = llvm::getLazyBitcodeModule(Buf->getMemBufferRef(), L->Ctx); if (!SrcOrError) { LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str()); return false; } auto Src = std::move(*SrcOrError); #else ErrorOr> Src = llvm::getLazyBitcodeModule(std::move(Buf), L->Ctx); if (!Src) { LLVMRustSetLastError(Src.getError().message().c_str()); return false; } #endif #if LLVM_VERSION_GE(4, 0) if (L->L.linkInModule(std::move(Src))) { #else if (L->L.linkInModule(std::move(Src.get()))) { #endif LLVMRustSetLastError(\"\"); return false; } return true; } "} {"_id":"doc-en-rust-19534572d4ab632138e20861f3ff6d2fb0a77df40f4a045e67efba8f1229c845","title":"","text":"} } extern \"C\" bool LLVMRustLinkInExternalBitcode(LLVMModuleRef DstRef, char *BC, size_t Len) { Module *Dst = unwrap(DstRef); std::unique_ptr Buf = MemoryBuffer::getMemBufferCopy(StringRef(BC, Len)); #if LLVM_VERSION_GE(4, 0) Expected> SrcOrError = llvm::getLazyBitcodeModule(Buf->getMemBufferRef(), Dst->getContext()); if (!SrcOrError) { LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str()); return false; } auto Src = std::move(*SrcOrError); #else ErrorOr> Src = llvm::getLazyBitcodeModule(std::move(Buf), Dst->getContext()); if (!Src) { LLVMRustSetLastError(Src.getError().message().c_str()); return false; } #endif std::string Err; raw_string_ostream Stream(Err); DiagnosticPrinterRawOStream DP(Stream); #if LLVM_VERSION_GE(4, 0) if (Linker::linkModules(*Dst, std::move(Src))) { #else if (Linker::linkModules(*Dst, std::move(Src.get()))) { #endif LLVMRustSetLastError(Err.c_str()); return false; } return true; } // Note that the two following functions look quite similar to the // LLVMGetSectionName function. Sadly, it appears that this function only // returns a char* pointer, which isn't guaranteed to be null-terminated. The"} {"_id":"doc-en-rust-daf3c895c92e1d62affabb33376f4865f9331fbb7ac8c073c1d4e829148269a5","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // revisions: lxl nll #![cfg_attr(nll, feature(nll))] struct Foo { x: u32 } impl Foo { fn twiddle(&mut self) -> &mut Self { self } fn twaddle(&mut self) -> &mut Self { self } fn emit(&mut self) { self.x += 1; } } fn main() { let mut foo = Foo { x: 0 }; match 22 { 22 => &mut foo, 44 => foo.twiddle(), _ => foo.twaddle(), }.emit(); } "} {"_id":"doc-en-rust-c17c4568f9974a9c03328f640523a5e783562b3c966b102b31693d909e758eb1","title":"","text":"FileType(self.0.file_type()) } /// Returns whether this metadata is for a directory. /// Returns whether this metadata is for a directory. The /// result is mutually exclusive to the result of /// [`is_file`], and will be false for symlink metadata /// obtained from [`symlink_metadata`]. /// /// [`is_file`]: struct.Metadata.html#method.is_file /// [`symlink_metadata`]: fn.symlink_metadata.html /// /// # Examples ///"} {"_id":"doc-en-rust-4b225942ba6f6ef447ab2c46650a514217443589412302e9d1c783d6f08c0b90","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] pub fn is_dir(&self) -> bool { self.file_type().is_dir() } /// Returns whether this metadata is for a regular file. /// Returns whether this metadata is for a regular file. The /// result is mutually exclusive to the result of /// [`is_dir`], and will be false for symlink metadata /// obtained from [`symlink_metadata`]. /// /// [`is_dir`]: struct.Metadata.html#method.is_dir /// [`symlink_metadata`]: fn.symlink_metadata.html /// /// # Examples ///"} {"_id":"doc-en-rust-75391dfc100be62894a8d8ed6ba5006fd5f99155c8116acf48ebf736af74fe60","title":"","text":"} impl FileType { /// Test whether this file type represents a directory. /// Test whether this file type represents a directory. The /// result is mutually exclusive to the results of /// [`is_file`] and [`is_symlink`]; only zero or one of these /// tests may pass. /// /// [`is_file`]: struct.FileType.html#method.is_file /// [`is_symlink`]: struct.FileType.html#method.is_symlink /// /// # Examples ///"} {"_id":"doc-en-rust-8b68e3ab86d85198afd156d6f26ddb2983d40b93433b1a06c7ffe06a0ad45edf","title":"","text":"pub fn is_dir(&self) -> bool { self.0.is_dir() } /// Test whether this file type represents a regular file. /// The result is mutually exclusive to the results of /// [`is_dir`] and [`is_symlink`]; only zero or one of these /// tests may pass. /// /// [`is_dir`]: struct.FileType.html#method.is_dir /// [`is_symlink`]: struct.FileType.html#method.is_symlink /// /// # Examples ///"} {"_id":"doc-en-rust-288de0beb712496a5ce473b849eb6e23b69a65e5183ee4df2ad17773e1743d87","title":"","text":"pub fn is_file(&self) -> bool { self.0.is_file() } /// Test whether this file type represents a symbolic link. /// The result is mutually exclusive to the results of /// [`is_dir`] and [`is_file`]; only zero or one of these /// tests may pass. /// /// The underlying [`Metadata`] struct needs to be retrieved /// with the [`fs::symlink_metadata`] function and not the"} {"_id":"doc-en-rust-840a775eacf6eba96a10eadd30e82887dc901ea7fe96b648abd39ef50641f1db","title":"","text":"/// [`Metadata`]: struct.Metadata.html /// [`fs::metadata`]: fn.metadata.html /// [`fs::symlink_metadata`]: fn.symlink_metadata.html /// [`is_dir`]: struct.FileType.html#method.is_dir /// [`is_file`]: struct.FileType.html#method.is_file /// [`is_symlink`]: struct.FileType.html#method.is_symlink /// /// # Examples"} {"_id":"doc-en-rust-379ad63aafec8abcf1b597422071c535ed2823557aa4180060cac8b1cc0bd165","title":"","text":"#[lang=\"return_to_mut\"] #[inline(always)] pub unsafe fn return_to_mut(a: *u8) { let a: *mut BoxRepr = transmute(a); (*a).header.ref_count &= !FROZEN_BIT; // Sometimes the box is null, if it is conditionally frozen. // See e.g. #4904. if !a.is_null() { let a: *mut BoxRepr = transmute(a); (*a).header.ref_count &= !FROZEN_BIT; } } #[lang=\"check_not_borrowed\"]"} {"_id":"doc-en-rust-f32d436173e3aac9fedf0058d71da08bc8693a2e16f37b98d275f99e45efc1d2","title":"","text":"/// # Examples /// /// ``` /// #![feature(path_ancestors)] /// /// use std::path::Path; /// /// let path = Path::new(\"/foo/bar\");"} {"_id":"doc-en-rust-c12687901c4f1c3f5a9627fb2d1f0317054d75b36104c6f241ea37b3713df337","title":"","text":"/// [`ancestors`]: struct.Path.html#method.ancestors /// [`Path`]: struct.Path.html #[derive(Copy, Clone, Debug)] #[unstable(feature = \"path_ancestors\", issue = \"48581\")] #[stable(feature = \"path_ancestors\", since = \"1.28.0\")] pub struct Ancestors<'a> { next: Option<&'a Path>, } #[unstable(feature = \"path_ancestors\", issue = \"48581\")] #[stable(feature = \"path_ancestors\", since = \"1.28.0\")] impl<'a> Iterator for Ancestors<'a> { type Item = &'a Path;"} {"_id":"doc-en-rust-02f1ca640ca29f1a01bcdb1f9b86d136662247bd7e71d8039d14b263dc6a4d5e","title":"","text":"} } #[unstable(feature = \"path_ancestors\", issue = \"48581\")] #[stable(feature = \"path_ancestors\", since = \"1.28.0\")] impl<'a> FusedIterator for Ancestors<'a> {} ////////////////////////////////////////////////////////////////////////////////"} {"_id":"doc-en-rust-f563d20e06d48655a156e277e71359ee00f116779aea5fbe553ae55b50f7189b","title":"","text":"/// # Examples /// /// ``` /// #![feature(path_ancestors)] /// /// use std::path::Path; /// /// let mut ancestors = Path::new(\"/foo/bar\").ancestors();"} {"_id":"doc-en-rust-087185a6b180bed7c52bc20838b4182eeb9380771116efab8d35cdc99aeebf13","title":"","text":"/// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// [`parent`]: struct.Path.html#method.parent #[unstable(feature = \"path_ancestors\", issue = \"48581\")] #[stable(feature = \"path_ancestors\", since = \"1.28.0\")] pub fn ancestors(&self) -> Ancestors { Ancestors { next: Some(&self),"} {"_id":"doc-en-rust-ba999c0490d8d05204546fec4646a8861536acffd9c5d7b9bf3e8b36e7feee48","title":"","text":"use ich::{self, CachingCodemapView, Fingerprint}; use middle::cstore::CrateStore; use ty::{TyCtxt, fast_reject}; use mir::interpret::AllocId; use session::Session; use std::cmp::Ord;"} {"_id":"doc-en-rust-7faaf72f7626e142611516858132d8d2b8944556324a8f18e59f29db686e89cc","title":"","text":"// CachingCodemapView, so we initialize it lazily. raw_codemap: &'a CodeMap, caching_codemap: Option>, pub(super) alloc_id_recursion_tracker: FxHashSet, } #[derive(PartialEq, Eq, Clone, Copy)]"} {"_id":"doc-en-rust-0cc14e5b5e31ab7300b8ef6896a27113870058906259285f7361099d1f2221eb","title":"","text":"hash_spans: hash_spans_initial, hash_bodies: true, node_id_hashing_mode: NodeIdHashingMode::HashDefPath, alloc_id_recursion_tracker: Default::default(), } }"} {"_id":"doc-en-rust-ddecf83d0e8f32f368a93bd9390748a36681fddbfc7b55fcaf2cacff3e2edeb3","title":"","text":"}); enum AllocDiscriminant { Static, Constant, Alloc, ExternStatic, Function, } impl_stable_hash_for!(enum self::AllocDiscriminant { Static, Constant, Alloc, ExternStatic, Function });"} {"_id":"doc-en-rust-81cc0a58b59bda2c713c2c7504eacc52bdd2584f5bbe139d6adacbf72330def2","title":"","text":") { ty::tls::with_opt(|tcx| { let tcx = tcx.expect(\"can't hash AllocIds during hir lowering\"); if let Some(def_id) = tcx.interpret_interner.get_corresponding_static_def_id(*self) { AllocDiscriminant::Static.hash_stable(hcx, hasher); // statics are unique via their DefId def_id.hash_stable(hcx, hasher); } else if let Some(alloc) = tcx.interpret_interner.get_alloc(*self) { // not a static, can't be recursive, hash the allocation AllocDiscriminant::Constant.hash_stable(hcx, hasher); alloc.hash_stable(hcx, hasher); if let Some(alloc) = tcx.interpret_interner.get_alloc(*self) { AllocDiscriminant::Alloc.hash_stable(hcx, hasher); if !hcx.alloc_id_recursion_tracker.insert(*self) { tcx .interpret_interner .get_corresponding_static_def_id(*self) .hash_stable(hcx, hasher); alloc.hash_stable(hcx, hasher); assert!(hcx.alloc_id_recursion_tracker.remove(self)); } } else if let Some(inst) = tcx.interpret_interner.get_fn(*self) { AllocDiscriminant::Function.hash_stable(hcx, hasher); inst.hash_stable(hcx, hasher); } else if let Some(def_id) = tcx.interpret_interner .get_corresponding_static_def_id(*self) { AllocDiscriminant::ExternStatic.hash_stable(hcx, hasher); def_id.hash_stable(hcx, hasher); } else { bug!(\"no allocation for {}\", self); }"} {"_id":"doc-en-rust-6260ae088883d08c6d357991a7ebe6ab1b15c8d1fe94b671df09c969080f8fc3","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // https://github.com/rust-lang/rust/issues/49081 // revisions:rpass1 rpass2 #[cfg(rpass1)] pub static A: &str = \"hello\"; #[cfg(rpass2)] pub static A: &str = \"xxxxx\"; #[cfg(rpass1)] fn main() { assert_eq!(A, \"hello\"); } #[cfg(rpass2)] fn main() { assert_eq!(A, \"xxxxx\"); } "} {"_id":"doc-en-rust-c5230380a4b8fe056ef59c974448443d957682ff6f2fc7e1dfb582dcb5f3337c","title":"","text":"/// [`Release`]: http://llvm.org/docs/Atomics.html#release #[stable(feature = \"rust1\", since = \"1.0.0\")] Acquire, /// When coupled with a load, uses [`Acquire`] ordering, and with a store /// [`Release`] ordering. /// Has the effects of both [`Acquire`] and [`Release`] together. /// /// This ordering is only applicable for operations that combine both loads and stores. /// /// For loads it uses [`Acquire`] ordering. For stores it uses the [`Release`] ordering. /// /// [`Acquire`]: http://llvm.org/docs/Atomics.html#acquire /// [`Release`]: http://llvm.org/docs/Atomics.html#release"} {"_id":"doc-en-rust-1057eab5efca42a65308c01776775761737cef413571f1dcf574c4944e545527","title":"","text":"} if let PatKind::Binding(_, _, name, None) = fieldpat.node.pat.node { if name.node == fieldpat.node.name { if let Some(_) = fieldpat.span.ctxt().outer().expn_info() { // Don't lint if this is a macro expansion: macro authors // shouldn't have to worry about this kind of style issue // (Issue #49588) return; } let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span, &format!(\"the `{}:` in this pattern is redundant\","} {"_id":"doc-en-rust-fbb37b7cb07f25d7dcfbc67c30ca8c2507e1eedf5fd4c9ba849984139a07e9dc","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(non_shorthand_field_patterns)] pub struct Value { pub value: A } #[macro_export] macro_rules! pat { ($a:pat) => { Value { value: $a } }; } fn main() { let pat!(value) = Value { value: () }; } "} {"_id":"doc-en-rust-d294cef40243cfe046cd41f4efbcdb8f76ebdfcd97554dbdebe740d9459ee9ea","title":"","text":"} // unsigned to signed (only positive bound) #[cfg(any(target_pointer_width = \"32\", target_pointer_width = \"64\"))] macro_rules! try_from_upper_bounded { ($($target:ty),*) => {$( impl PrivateTryFromUsize for $target {"} {"_id":"doc-en-rust-1d2dca20d928e5886afdcc66c9796c6abe0df2f2afce9e34fefbfbbce029086b","title":"","text":"// all span information. // // As a result, some AST nodes are annotated with the token // stream they came from. Attempt to extract these lossless // token streams before we fall back to the stringification. // stream they came from. Here we attempt to extract these // lossless token streams before we fall back to the // stringification. // // During early phases of the compiler, though, the AST could // get modified directly (e.g. attributes added or removed) and // the internal cache of tokens my not be invalidated or // updated. Consequently if the \"lossless\" token stream // disagrees with our actuall stringification (which has // historically been much more battle-tested) then we go with // the lossy stream anyway (losing span information). let mut tokens = None; match nt.0 {"} {"_id":"doc-en-rust-a35cb392b3de8d12b62acb9b6ccc5d65d1ee55d857dcd95f6157ff27973fbde1","title":"","text":"_ => {} } tokens.unwrap_or_else(|| { nt.1.force(|| { // FIXME(jseyfried): Avoid this pretty-print + reparse hack let source = pprust::token_to_string(self); parse_stream_from_source_str(FileName::MacroExpansion, source, sess, Some(span)) }) }) let tokens_for_real = nt.1.force(|| { // FIXME(#43081): Avoid this pretty-print + reparse hack let source = pprust::token_to_string(self); parse_stream_from_source_str(FileName::MacroExpansion, source, sess, Some(span)) }); if let Some(tokens) = tokens { if tokens.eq_unspanned(&tokens_for_real) { return tokens } } return tokens_for_real } }"} {"_id":"doc-en-rust-9c82eab5c6f34272d4e7be0e6148f880dbc6e058da0a285c51801e6a04510a14","title":"","text":"(&TokenTree::Token(_, ref tk), &TokenTree::Token(_, ref tk2)) => tk == tk2, (&TokenTree::Delimited(_, ref dl), &TokenTree::Delimited(_, ref dl2)) => { dl.delim == dl2.delim && dl.stream().trees().zip(dl2.stream().trees()).all(|(tt, tt2)| tt.eq_unspanned(&tt2)) dl.stream().eq_unspanned(&dl2.stream()) } (_, _) => false, }"} {"_id":"doc-en-rust-b5f1c8324b1498aeec65b699737e8cb58aafca2769cad090bf5db06d2ab2a133","title":"","text":"/// Compares two TokenStreams, checking equality without regarding span information. pub fn eq_unspanned(&self, other: &TokenStream) -> bool { for (t1, t2) in self.trees().zip(other.trees()) { let mut t1 = self.trees(); let mut t2 = other.trees(); for (t1, t2) in t1.by_ref().zip(t2.by_ref()) { if !t1.eq_unspanned(&t2) { return false; } } true t1.next().is_none() && t2.next().is_none() } /// Precondition: `self` consists of a single token tree."} {"_id":"doc-en-rust-a8ecd5c7aab5fd460bf25c2bab05ce4570d7a848e94354971f259738f6935b09","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // no-prefer-dynamic #![crate_type = \"proc-macro\"] #![feature(proc_macro)] extern crate proc_macro; use proc_macro::*; #[proc_macro_attribute] pub fn assert1(_a: TokenStream, b: TokenStream) -> TokenStream { assert_eq(b.clone(), \"pub fn foo() {}\".parse().unwrap()); b } #[proc_macro_derive(Foo, attributes(foo))] pub fn assert2(a: TokenStream) -> TokenStream { assert_eq(a, \"pub struct MyStructc { _a: i32, }\".parse().unwrap()); TokenStream::empty() } fn assert_eq(a: TokenStream, b: TokenStream) { let mut a = a.into_iter(); let mut b = b.into_iter(); for (a, b) in a.by_ref().zip(&mut b) { match (a, b) { (TokenTree::Group(a), TokenTree::Group(b)) => { assert_eq!(a.delimiter(), b.delimiter()); assert_eq(a.stream(), b.stream()); } (TokenTree::Op(a), TokenTree::Op(b)) => { assert_eq!(a.op(), b.op()); assert_eq!(a.spacing(), b.spacing()); } (TokenTree::Literal(a), TokenTree::Literal(b)) => { assert_eq!(a.to_string(), b.to_string()); } (TokenTree::Term(a), TokenTree::Term(b)) => { assert_eq!(a.to_string(), b.to_string()); } (a, b) => panic!(\"{:?} != {:?}\", a, b), } } assert!(a.next().is_none()); assert!(b.next().is_none()); } "} {"_id":"doc-en-rust-96041a3dfe709615549233b2094a6bc5c9623f93e7ac23c4a0d2f64477d39c81","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:modify-ast.rs #![feature(proc_macro)] extern crate modify_ast; use modify_ast::*; #[derive(Foo)] pub struct MyStructc { #[cfg_attr(my_cfg, foo)] _a: i32, } macro_rules! a { ($i:item) => ($i) } a! { #[assert1] pub fn foo() {} } fn main() { let _a = MyStructc { _a: 0 }; foo(); } "} {"_id":"doc-en-rust-318412e66191c766f55662361e302d9cdcc1cad734406591a9dc715506109e11","title":"","text":"} #[test] fn test_str_slice_rangetoinclusive_ok() { let s = \"abcαβγ\"; assert_eq!(&s[..=2], \"abc\"); assert_eq!(&s[..=4], \"abcα\"); } #[test] #[should_panic] fn test_str_slice_rangetoinclusive_notok() { let s = \"abcαβγ\"; &s[..=3]; } #[test] fn test_str_slicemut_rangetoinclusive_ok() { let mut s = \"abcαβγ\".to_owned(); let s: &mut str = &mut s; assert_eq!(&mut s[..=2], \"abc\"); assert_eq!(&mut s[..=4], \"abcα\"); } #[test] #[should_panic] fn test_str_slicemut_rangetoinclusive_notok() { let mut s = \"abcαβγ\".to_owned(); let s: &mut str = &mut s; &mut s[..=3]; } #[test] fn test_is_char_boundary() { let s = \"ศไทย中华Việt Nam β-release 🐱123\"; assert!(s.is_char_boundary(0));"} {"_id":"doc-en-rust-516a6c446f15de53052759a06f075c1dea64337d561045f705c417e957c6e78b","title":"","text":"fn index(self, slice: &str) -> &Self::Output { assert!(self.end != usize::max_value(), \"attempted to index str up to maximum usize\"); let end = self.end + 1; self.get(slice).unwrap_or_else(|| super::slice_error_fail(slice, 0, end)) (..self.end+1).index(slice) } #[inline] fn index_mut(self, slice: &mut str) -> &mut Self::Output { assert!(self.end != usize::max_value(), \"attempted to index str up to maximum usize\"); if slice.is_char_boundary(self.end) { unsafe { self.get_unchecked_mut(slice) } } else { super::slice_error_fail(slice, 0, self.end + 1) } (..self.end+1).index_mut(slice) } }"} {"_id":"doc-en-rust-ac438aae3c57c09f244887e754d3307745bd008a10134095b6c139d9f50db20f","title":"","text":"continue; } let result = select.select(&Obligation::new(dummy_cause.clone(), new_env, pred)); // Call infcx.resolve_type_vars_if_possible to see if we can // get rid of any inference variables. let obligation = infcx.resolve_type_vars_if_possible( &Obligation::new(dummy_cause.clone(), new_env, pred) ); let result = select.select(&obligation); match &result { &Ok(Some(ref vtable)) => {"} {"_id":"doc-en-rust-8cc47c721a66ed6034815dbbc62ed622e744b4107ea43e7c36cd136bcf9801c5","title":"","text":"} &Ok(None) => {} &Err(SelectionError::Unimplemented) => { if self.is_of_param(pred.skip_binder().trait_ref.substs) { if self.is_param_no_infer(pred.skip_binder().trait_ref.substs) { already_visited.remove(&pred); self.add_user_pred( &mut user_computed_preds,"} {"_id":"doc-en-rust-a73c4dc3a6d1cccb98e44c0102d2c67c612b20724f550820ef7ce1748781739e","title":"","text":"finished_map } pub fn is_of_param(&self, substs: &Substs<'_>) -> bool { if substs.is_noop() { return false; } fn is_param_no_infer(&self, substs: &Substs<'_>) -> bool { return self.is_of_param(substs.type_at(0)) && !substs.types().any(|t| t.has_infer_types()); } return match substs.type_at(0).sty { pub fn is_of_param(&self, ty: Ty<'_>) -> bool { return match ty.sty { ty::Param(_) => true, ty::Projection(p) => self.is_of_param(p.substs), ty::Projection(p) => self.is_of_param(p.self_ty()), _ => false, }; } fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'_>) -> bool { match p.ty().skip_binder().sty { ty::Projection(proj) if proj == p.skip_binder().projection_ty => { true }, _ => false } } pub fn evaluate_nested_obligations< 'b, 'c,"} {"_id":"doc-en-rust-f256a431c8ba44aefa176c89540ed4eb6ed77f1f18890050522654ede312ebe4","title":"","text":") -> bool { let dummy_cause = ObligationCause::misc(DUMMY_SP, ast::DUMMY_NODE_ID); for (obligation, predicate) in nested .filter(|o| o.recursion_depth == 1) for (obligation, mut predicate) in nested .map(|o| (o.clone(), o.predicate.clone())) { let is_new_pred = fresh_preds.insert(self.clean_pred(select.infcx(), predicate.clone())); // Resolve any inference variables that we can, to help selection succeed predicate = select.infcx().resolve_type_vars_if_possible(&predicate); // We only add a predicate as a user-displayable bound if // it involves a generic parameter, and doesn't contain // any inference variables. // // Displaying a bound involving a concrete type (instead of a generic // parameter) would be pointless, since it's always true // (e.g. u8: Copy) // Displaying an inference variable is impossible, since they're // an internal compiler detail without a defined visual representation // // We check this by calling is_of_param on the relevant types // from the various possible predicates match &predicate { &ty::Predicate::Trait(ref p) => { let substs = &p.skip_binder().trait_ref.substs; if self.is_param_no_infer(p.skip_binder().trait_ref.substs) && !only_projections && is_new_pred { if self.is_of_param(substs) && !only_projections && is_new_pred { self.add_user_pred(computed_preds, predicate); } predicates.push_back(p.clone()); } &ty::Predicate::Projection(p) => { // If the projection isn't all type vars, then // we don't want to add it as a bound if self.is_of_param(p.skip_binder().projection_ty.substs) && is_new_pred { self.add_user_pred(computed_preds, predicate); } else { debug!(\"evaluate_nested_obligations: examining projection predicate {:?}\", predicate); // As described above, we only want to display // bounds which include a generic parameter but don't include // an inference variable. // Additionally, we check if we've seen this predicate before, // to avoid rendering duplicate bounds to the user. if self.is_param_no_infer(p.skip_binder().projection_ty.substs) && !p.ty().skip_binder().is_ty_infer() && is_new_pred { debug!(\"evaluate_nested_obligations: adding projection predicate to computed_preds: {:?}\", predicate); // Under unusual circumstances, we can end up with a self-refeential // projection predicate. For example: // ::Value == ::Value // Not only is displaying this to the user pointless, // having it in the ParamEnv will cause an issue if we try to call // poly_project_and_unify_type on the predicate, since this kind of // predicate will normally never end up in a ParamEnv. // // For these reasons, we ignore these weird predicates, // ensuring that we're able to properly synthesize an auto trait impl if self.is_self_referential_projection(p) { debug!(\"evaluate_nested_obligations: encountered a projection predicate equating a type with itself! Skipping\"); } else { self.add_user_pred(computed_preds, predicate); } } // We can only call poly_project_and_unify_type when our predicate's // Ty is an inference variable - otherwise, there won't be anything to // unify if p.ty().skip_binder().is_ty_infer() { debug!(\"Projecting and unifying projection predicate {:?}\", predicate); match poly_project_and_unify_type(select, &obligation.with(p.clone())) { Err(e) => { debug!("} {"_id":"doc-en-rust-56d79684ebad96c68a3b0fc0a74cd87c72d9cbb94b0e6a2c567e0ae45723b1a0","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait Signal { type Item; } pub trait Signal2 { type Item2; } impl Signal2 for B where B: Signal { type Item2 = C; } // @has issue_50159/struct.Switch.html // @has - '//code' 'impl Send for Switch where ::Item: Send' // @has - '//code' 'impl Sync for Switch where ::Item: Sync' // @count - '//*[@id=\"implementations-list\"]/*[@class=\"impl\"]' 0 // @count - '//*[@id=\"synthetic-implementations-list\"]/*[@class=\"impl\"]' 2 pub struct Switch { pub inner: ::Item2, } "} {"_id":"doc-en-rust-db5c627da3af5bbc243e9055f5b52ac4cb8f002f4e7b3b5b07859352c9b1687f","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Some unusual code minimized from // https://github.com/sile/handy_async/tree/7b619b762c06544fc67792c8ff8ebc24a88fdb98 pub trait Pattern { type Value; } pub struct Constrain(A, B, C); impl Pattern for Constrain where A: Pattern, B: Pattern, C: Pattern, { type Value = A::Value; } pub struct Wrapper(T); impl Pattern for Wrapper { type Value = T; } // @has self_referential/struct.WriteAndThen.html // @has - '//*[@id=\"synthetic-implementations-list\"]/*[@class=\"impl\"]//*/code' \"impl Send for // WriteAndThen where ::Value: Send\" pub struct WriteAndThen(pub P1::Value,pub > as Pattern>::Value) where P1: Pattern; "} {"_id":"doc-en-rust-beba344fda0e3a2a03dac3adba8c1c6cb43f11b4f29f2bd627bdb90659947218","title":"","text":"} } /// Replaces the value at a mutable location with a new one, returning the old value, without /// deinitializing either one. /// Moves `src` into the referenced `dest`, returning the previous `dest` value. /// /// Neither value is dropped. /// /// # Examples ///"} {"_id":"doc-en-rust-81ee888ac8b4a26f573e42933260fa196f8500f273efa24e0887b38843ceb13b","title":"","text":"} } /// Replaces the value at `dest` with `src`, returning the old /// value, without dropping either. /// Moves `src` into the pointed `dest`, returning the previous `dest` value. /// /// Neither value is dropped. /// /// # Safety ///"} {"_id":"doc-en-rust-1bbd5515e2721ed3c8e4753f7628172281c6ef3160727c1de51e421c463bb129","title":"","text":"use crate::resolve_imports::{ImportDirective, ImportDirectiveSubclass, ImportResolver}; use crate::{path_names_to_string, KNOWN_TOOLS}; use crate::{CrateLint, LegacyScope, Module, ModuleOrUniformRoot}; use crate::{BindingError, CrateLint, LegacyScope, Module, ModuleOrUniformRoot}; use crate::{PathResult, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Segment}; type Res = def::Res;"} {"_id":"doc-en-rust-60344106e9dd72fd60a43de48a45843b3da1630b38a9eddf447bc03767173bdf","title":"","text":"err } ResolutionError::VariableNotBoundInPattern(binding_error) => { let target_sp = binding_error.target.iter().cloned().collect::>(); let BindingError { name, target, origin, could_be_path } = binding_error; let target_sp = target.iter().copied().collect::>(); let origin_sp = origin.iter().copied().collect::>(); let msp = MultiSpan::from_spans(target_sp.clone()); let msg = format!(\"variable `{}` is not bound in all patterns\", binding_error.name); let msg = format!(\"variable `{}` is not bound in all patterns\", name); let mut err = self.session.struct_span_err_with_code( msp, &msg, DiagnosticId::Error(\"E0408\".into()), ); for sp in target_sp { err.span_label(sp, format!(\"pattern doesn't bind `{}`\", binding_error.name)); err.span_label(sp, format!(\"pattern doesn't bind `{}`\", name)); } let origin_sp = binding_error.origin.iter().cloned(); for sp in origin_sp { err.span_label(sp, \"variable not in all patterns\"); } if *could_be_path { let help_msg = format!( \"if you meant to match on a variant or a `const` item, consider making the path in the pattern qualified: `?::{}`\", name, ); err.span_help(span, &help_msg); } err } ResolutionError::VariableBoundWithDifferentMode(variable_name,"} {"_id":"doc-en-rust-f2b4b6d2549a71fec546e9a7c8cb3c96ef30b4307a7cf93fa71ee4e2c3ac3ef7","title":"","text":"// Checks that all of the arms in an or-pattern have exactly the // same set of bindings, with the same binding modes for each. fn check_consistent_bindings(&mut self, pats: &[P]) { if pats.is_empty() { return; } let mut missing_vars = FxHashMap::default(); let mut inconsistent_vars = FxHashMap::default(); for (i, p) in pats.iter().enumerate() { let map_i = self.binding_mode_map(&p); for (j, q) in pats.iter().enumerate() { if i == j { continue; } let map_j = self.binding_mode_map(&q); for (&key, &binding_i) in &map_i { if map_j.is_empty() { // Account for missing bindings when let binding_error = missing_vars // `map_j` has none. .entry(key.name) .or_insert(BindingError { name: key.name, origin: BTreeSet::new(), target: BTreeSet::new(), }); binding_error.origin.insert(binding_i.span); binding_error.target.insert(q.span); } for (&key_j, &binding_j) in &map_j { match map_i.get(&key_j) { None => { // missing binding let binding_error = missing_vars .entry(key_j.name) .or_insert(BindingError { name: key_j.name, origin: BTreeSet::new(), target: BTreeSet::new(), }); binding_error.origin.insert(binding_j.span); binding_error.target.insert(p.span); } Some(binding_i) => { // check consistent binding if binding_i.binding_mode != binding_j.binding_mode { inconsistent_vars .entry(key.name) .or_insert((binding_j.span, binding_i.span)); } for pat_outer in pats.iter() { let map_outer = self.binding_mode_map(&pat_outer); for pat_inner in pats.iter().filter(|pat| pat.id != pat_outer.id) { let map_inner = self.binding_mode_map(&pat_inner); for (&key_inner, &binding_inner) in map_inner.iter() { match map_outer.get(&key_inner) { None => { // missing binding let binding_error = missing_vars .entry(key_inner.name) .or_insert(BindingError { name: key_inner.name, origin: BTreeSet::new(), target: BTreeSet::new(), could_be_path: key_inner.name.as_str().starts_with(char::is_uppercase) }); binding_error.origin.insert(binding_inner.span); binding_error.target.insert(pat_outer.span); } Some(binding_outer) => { // check consistent binding if binding_outer.binding_mode != binding_inner.binding_mode { inconsistent_vars .entry(key_inner.name) .or_insert((binding_inner.span, binding_outer.span)); } } } } } } let mut missing_vars = missing_vars.iter().collect::>(); let mut missing_vars = missing_vars.iter_mut().collect::>(); missing_vars.sort(); for (_, v) in missing_vars { for (name, mut v) in missing_vars { if inconsistent_vars.contains_key(name) { v.could_be_path = false; } self.r.report_error( *v.origin.iter().next().unwrap(), ResolutionError::VariableNotBoundInPattern(v) ); *v.origin.iter().next().unwrap(), ResolutionError::VariableNotBoundInPattern(v)); } let mut inconsistent_vars = inconsistent_vars.iter().collect::>(); inconsistent_vars.sort(); for (name, v) in inconsistent_vars {"} {"_id":"doc-en-rust-3b916c59521a21ded6b0a8ae11baca67ba31e2d043a64834d8445f10cb25e772","title":"","text":"self.resolve_pattern(pat, source, &mut bindings_list); } // This has to happen *after* we determine which pat_idents are variants self.check_consistent_bindings(pats); if pats.len() > 1 { self.check_consistent_bindings(pats); } } fn resolve_block(&mut self, block: &Block) {"} {"_id":"doc-en-rust-72184421f564501d9915cbe92d9712279cc8787337cf4a8663c973f6ead19ac2","title":"","text":"name: Name, origin: BTreeSet, target: BTreeSet, could_be_path: bool } impl PartialOrd for BindingError {"} {"_id":"doc-en-rust-04890cf5d016864ab6e1de3c3c0dd4c7404a65af88e4eb3129761af571a45d39","title":"","text":" #![allow(non_camel_case_types)] enum E { A, B, c } mod m { const CONST1: usize = 10; const Const2: usize = 20; } fn main() { let y = 1; match y { a | b => {} //~ ERROR variable `a` is not bound in all patterns //~^ ERROR variable `b` is not bound in all patterns //~| ERROR variable `b` is not bound in all patterns } let x = (E::A, E::B); match x { (A, B) | (ref B, c) | (c, A) => () //~^ ERROR variable `A` is not bound in all patterns //~| ERROR variable `B` is not bound in all patterns //~| ERROR variable `B` is bound in inconsistent ways //~| ERROR mismatched types //~| ERROR variable `c` is not bound in all patterns //~| HELP consider making the path in the pattern qualified: `?::A` } let z = (10, 20); match z { (CONST1, _) | (_, Const2) => () //~^ ERROR variable `CONST1` is not bound in all patterns //~| HELP consider making the path in the pattern qualified: `?::CONST1` //~| ERROR variable `Const2` is not bound in all patterns //~| HELP consider making the path in the pattern qualified: `?::Const2` } }"} {"_id":"doc-en-rust-dc645997c4e1ddd96d16eb3a3f77a934a740a5494316e93a126348ea9229e9f1","title":"","text":"error[E0408]: variable `a` is not bound in all patterns --> $DIR/resolve-inconsistent-names.rs:4:12 --> $DIR/resolve-inconsistent-names.rs:13:12 | LL | a | b => {} | - ^ pattern doesn't bind `a`"} {"_id":"doc-en-rust-d7d0c67a5fe28d7c51e6406a65f3961bdaeace1aa99e4994827b27dc7f9725e1","title":"","text":"| variable not in all patterns error[E0408]: variable `b` is not bound in all patterns --> $DIR/resolve-inconsistent-names.rs:4:8 --> $DIR/resolve-inconsistent-names.rs:13:8 | LL | a | b => {} | ^ - variable not in all patterns | | | pattern doesn't bind `b` error: aborting due to 2 previous errors error[E0408]: variable `A` is not bound in all patterns --> $DIR/resolve-inconsistent-names.rs:19:18 | LL | (A, B) | (ref B, c) | (c, A) => () | - ^^^^^^^^^^ - variable not in all patterns | | | | | pattern doesn't bind `A` | variable not in all patterns | help: if you meant to match on a variant or a `const` item, consider making the path in the pattern qualified: `?::A` --> $DIR/resolve-inconsistent-names.rs:19:10 | LL | (A, B) | (ref B, c) | (c, A) => () | ^ error[E0408]: variable `B` is not bound in all patterns --> $DIR/resolve-inconsistent-names.rs:19:31 | LL | (A, B) | (ref B, c) | (c, A) => () | - - ^^^^^^ pattern doesn't bind `B` | | | | | variable not in all patterns | variable not in all patterns error[E0408]: variable `c` is not bound in all patterns --> $DIR/resolve-inconsistent-names.rs:19:9 | LL | (A, B) | (ref B, c) | (c, A) => () | ^^^^^^ - - variable not in all patterns | | | | | variable not in all patterns | pattern doesn't bind `c` error[E0409]: variable `B` is bound in inconsistent ways within the same match arm --> $DIR/resolve-inconsistent-names.rs:19:23 | LL | (A, B) | (ref B, c) | (c, A) => () | - ^ bound in different ways | | | first binding error[E0408]: variable `CONST1` is not bound in all patterns --> $DIR/resolve-inconsistent-names.rs:30:23 | LL | (CONST1, _) | (_, Const2) => () | ------ ^^^^^^^^^^^ pattern doesn't bind `CONST1` | | | variable not in all patterns | help: if you meant to match on a variant or a `const` item, consider making the path in the pattern qualified: `?::CONST1` --> $DIR/resolve-inconsistent-names.rs:30:10 | LL | (CONST1, _) | (_, Const2) => () | ^^^^^^ error[E0408]: variable `Const2` is not bound in all patterns --> $DIR/resolve-inconsistent-names.rs:30:9 | LL | (CONST1, _) | (_, Const2) => () | ^^^^^^^^^^^ ------ variable not in all patterns | | | pattern doesn't bind `Const2` | help: if you meant to match on a variant or a `const` item, consider making the path in the pattern qualified: `?::Const2` --> $DIR/resolve-inconsistent-names.rs:30:27 | LL | (CONST1, _) | (_, Const2) => () | ^^^^^^ error[E0308]: mismatched types --> $DIR/resolve-inconsistent-names.rs:19:19 | LL | (A, B) | (ref B, c) | (c, A) => () | ^^^^^ expected enum `E`, found &E | = note: expected type `E` found type `&E` error: aborting due to 9 previous errors For more information about this error, try `rustc --explain E0408`. Some errors have detailed explanations: E0308, E0408, E0409. For more information about an error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-d6e4a85f8a038192fa4302bbf40ed1f44e39710396cb7d0aa69c251402092d50","title":"","text":"config::CrateTypeDylib | config::CrateTypeProcMacro => MetadataKind::Compressed, } }).max().unwrap(); }).max().unwrap_or(MetadataKind::None); if kind == MetadataKind::None { return (metadata_llcx,"} {"_id":"doc-en-rust-a2960dab250e3ef2212404e04252202cdb682311bf9624dd8cdc6434794681b2","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: --crate-type dylib --target thumbv7em-none-eabihf // compile-pass // error-pattern: dropping unsupported crate type `dylib` for target `thumbv7em-none-eabihf` #![feature(no_core)] #![no_std] #![no_core] "} {"_id":"doc-en-rust-9460dfda4f478d2d0cfefdab8670c34666b9d0caacbbe89b90a1373e0e934983","title":"","text":" warning: dropping unsupported crate type `dylib` for target `thumbv7em-none-eabihf` "} {"_id":"doc-en-rust-f5231b8a9335563d55fcb100a9ea19eb224a9ed40c5fbc8a340643cb82f14472","title":"","text":" // ignore-emscripten no asm! support #![feature(asm)] fn main() { unsafe { asm! {\"mov $0,$1\"::\"0\"(\"bx\"),\"1\"(0x00)} //~^ ERROR: invalid value for constraint in inline assembly } } "} {"_id":"doc-en-rust-d485b68aecc027e13818c1f565d410ed64979746064d00f684bd3cc59e06b104","title":"","text":" error[E0669]: invalid value for constraint in inline assembly --> $DIR/issue-51431.rs:7:32 | LL | asm! {\"mov $0,$1\"::\"0\"(\"bx\"),\"1\"(0x00)} | ^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-10072589dc44876c2810ecad0e934f281f7867c3665844febb0ce84c810a9e0b","title":"","text":" trait A { const C: usize; fn f() -> ([u8; A::C], [u8; A::C]); //~^ ERROR: type annotations needed: cannot resolve //~| ERROR: type annotations needed: cannot resolve } fn main() {} "} {"_id":"doc-en-rust-2e704ed255e8ea3a352b473bd48aab2c1c087509f9540ccfa1013a1e3b63c46f","title":"","text":" error[E0283]: type annotations needed: cannot resolve `_: A` --> $DIR/issue-63496.rs:4:21 | LL | const C: usize; | --------------- required by `A::C` LL | LL | fn f() -> ([u8; A::C], [u8; A::C]); | ^^^^ error[E0283]: type annotations needed: cannot resolve `_: A` --> $DIR/issue-63496.rs:4:33 | LL | const C: usize; | --------------- required by `A::C` LL | LL | fn f() -> ([u8; A::C], [u8; A::C]); | ^^^^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0283`. "} {"_id":"doc-en-rust-bedbb3c212c440f528f318e68fd64ac16d9a7fad10797b8f1c8152ebf67a6fff","title":"","text":" trait T<'x> { type V; } impl<'g> T<'g> for u32 { type V = u16; } fn main() { (&|_|()) as &dyn for<'x> Fn(>::V); //~^ ERROR: type mismatch in closure arguments //~| ERROR: type mismatch resolving } "} {"_id":"doc-en-rust-49495d13f8bb647acc528f871f1a4b34412ba5a9a5a4eee571e23ac77077764e","title":"","text":" error[E0631]: type mismatch in closure arguments --> $DIR/issue-41366.rs:10:5 | LL | (&|_|()) as &dyn for<'x> Fn(>::V); | ^^-----^ | | | | | found signature of `fn(_) -> _` | expected signature of `for<'x> fn(>::V) -> _` | = note: required for the cast to the object type `dyn for<'x> std::ops::Fn(>::V)` error[E0271]: type mismatch resolving `for<'x> <[closure@$DIR/issue-41366.rs:10:7: 10:12] as std::ops::FnOnce<(>::V,)>>::Output == ()` --> $DIR/issue-41366.rs:10:5 | LL | (&|_|()) as &dyn for<'x> Fn(>::V); | ^^^^^^^^ expected bound lifetime parameter 'x, found concrete lifetime | = note: required for the cast to the object type `dyn for<'x> std::ops::Fn(>::V)` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0271`. "} {"_id":"doc-en-rust-8f6aa14951294b9b5e61325734e4242bb1be9a1352ea2ebb6ce9bc0f92d5946f","title":"","text":" fn main() { [(); &(&'static: loop { |x| {}; }) as *const _ as usize] //~^ ERROR: invalid label name `'static` //~| ERROR: type annotations needed } "} {"_id":"doc-en-rust-5c1c20ed8c81b498f7f76af1453e94c766fa9b5ec3be2f0e8f0256fbd662e7ec","title":"","text":" error: invalid label name `'static` --> $DIR/issue-52437.rs:2:13 | LL | [(); &(&'static: loop { |x| {}; }) as *const _ as usize] | ^^^^^^^ error[E0282]: type annotations needed --> $DIR/issue-52437.rs:2:30 | LL | [(); &(&'static: loop { |x| {}; }) as *const _ as usize] | ^ consider giving this closure parameter a type error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0282`. "} {"_id":"doc-en-rust-5e932b9a1b0198ca985a9a5bee9beefd6e0777347053c309acef7dadd8191b04","title":"","text":"Token::Interpolated(ref nt) => may_be_ident(&nt.0), _ => false, }, \"lifetime\" => match *token { Token::Lifetime(_) => true, Token::Interpolated(ref nt) => match nt.0 { token::NtLifetime(_) | token::NtTT(_) => true, _ => false, }, _ => false, }, _ => match *token { token::CloseDelim(_) => false, _ => true,"} {"_id":"doc-en-rust-2208cd1484c76342c69116dd802666c72e82505675edd2017d36d92f4684c957","title":"","text":"fn main() { m!(a); //~^ ERROR expected a lifetime, found `a` //~^ ERROR no rules expected the token `a` }"} {"_id":"doc-en-rust-85d510b757d245a8b1fdb7da7b3eb45579460c99749e27504d058f456b4113e4","title":"","text":"//}}} //{{{ issue 50903 ============================================================== macro_rules! foo_50903 { ($($lif:lifetime ,)* #) => {}; } foo_50903!('a, 'b, #); foo_50903!('a, #); foo_50903!(#); //}}} //{{{ issue 51477 ============================================================== macro_rules! foo_51477 { ($lifetime:lifetime) => { \"last token is lifetime\" }; ($other:tt) => { \"last token is other\" }; ($first:tt $($rest:tt)*) => { foo_51477!($($rest)*) }; } fn test_51477() { assert_eq!(\"last token is lifetime\", foo_51477!('a)); assert_eq!(\"last token is other\", foo_51477!(@)); assert_eq!(\"last token is lifetime\", foo_51477!(@ {} 'a)); } //}}} //{{{ some more tests ========================================================== macro_rules! test_block {"} {"_id":"doc-en-rust-6c2d0fc6cae7f66946caf4a9ef74ef0d9a1987820eef4339842d1526c67b2845","title":"","text":"test_meta_block!(windows {}); macro_rules! test_lifetime { (1. $($l:lifetime)* $($b:block)*) => {}; (2. $($b:block)* $($l:lifetime)*) => {}; } test_lifetime!(1. 'a 'b {} {}); test_lifetime!(2. {} {} 'a 'b); //}}} fn main() {"} {"_id":"doc-en-rust-e2e995eb82dd075ca3629490238ea0a99c8a1173d7c0fe6a18a51caba81cbcb0","title":"","text":"test_40569(); test_35650(); test_24189(); test_51477(); }"} {"_id":"doc-en-rust-d0cc170cfd3bf30d907ba83cf8ff2dd94affe4e83e47570dd5253b24306570d4","title":"","text":"// highlighted text will always be `&` and // thus can transform to `&mut` by slicing off // first ASCII character and prepending \"&mut \". let borrowed_expr = src[1..].to_string(); return (assignment_rhs_span, format!(\"&mut {}\", borrowed_expr)); if src.starts_with('&') { let borrowed_expr = src[1..].to_string(); return (assignment_rhs_span, format!(\"&mut {}\", borrowed_expr)); } } }"} {"_id":"doc-en-rust-1b22ef3a47795ade4957a2f858457eab959e80682fdb5896ed9b44666fbd8ff0","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(nll)] fn main() { let foo = &16; //~^ HELP consider changing this to be a mutable reference //~| SUGGESTION &mut 16 *foo = 32; //~^ ERROR cannot assign to `*foo` which is behind a `&` reference let bar = foo; //~^ HELP consider changing this to be a mutable reference //~| SUGGESTION &mut i32 *bar = 64; //~^ ERROR cannot assign to `*bar` which is behind a `&` reference } "} {"_id":"doc-en-rust-01b442ed645a89986e9a6a8e6db711505701346f192c00a865c0904d3daf4ccd","title":"","text":" error[E0594]: cannot assign to `*foo` which is behind a `&` reference --> $DIR/issue-51515.rs:17:5 | LL | let foo = &16; | --- help: consider changing this to be a mutable reference: `&mut 16` ... LL | *foo = 32; | ^^^^^^^^^ `foo` is a `&` reference, so the data it refers to cannot be written error[E0594]: cannot assign to `*bar` which is behind a `&` reference --> $DIR/issue-51515.rs:22:5 | LL | let bar = foo; | --- help: consider changing this to be a mutable reference: `&mut i32` ... LL | *bar = 64; | ^^^^^^^^^ `bar` is a `&` reference, so the data it refers to cannot be written error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0594`. "} {"_id":"doc-en-rust-4aa94c0b0762ebd2a1c88198d3c2de59763c4d7c8b9b6ba33d3b26b1b9db8bde","title":"","text":"} let t = cx.tables.expr_ty(&expr); // FIXME(varkor): replace with `t.is_unit() || t.conservative_is_uninhabited()`. let type_permits_no_use = match t.sty { ty::Tuple(ref tys) if tys.is_empty() => true, ty::Never => true, ty::Adt(def, _) => { if def.variants.is_empty() { true } else { check_must_use(cx, def.did, s.span, \"\") let type_permits_lack_of_use = if t.is_unit() || cx.tcx.is_ty_uninhabited_from(cx.tcx.hir.get_module_parent(expr.id), t) { true } else { match t.sty { ty::Adt(def, _) => check_must_use(cx, def.did, s.span, \"\", \"\"), ty::Opaque(def, _) => { let mut must_use = false; for (predicate, _) in &cx.tcx.predicates_of(def).predicates { if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate { let trait_ref = poly_trait_predicate.skip_binder().trait_ref; if check_must_use(cx, trait_ref.def_id, s.span, \"implementer of \", \"\") { must_use = true; break; } } } must_use } ty::Dynamic(binder, _) => { let mut must_use = false; for predicate in binder.skip_binder().iter() { if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate { if check_must_use(cx, trait_ref.def_id, s.span, \"\", \" trait object\") { must_use = true; break; } } } must_use } _ => false, } _ => false, }; let mut fn_warned = false;"} {"_id":"doc-en-rust-efd5b50f712d99ec664e953c2467a5ea133b9e1a6a628f86988302b8c0a8b39f","title":"","text":"}; if let Some(def) = maybe_def { let def_id = def.def_id(); fn_warned = check_must_use(cx, def_id, s.span, \"return value of \"); } else if type_permits_no_use { fn_warned = check_must_use(cx, def_id, s.span, \"return value of \", \"\"); } else if type_permits_lack_of_use { // We don't warn about unused unit or uninhabited types. // (See https://github.com/rust-lang/rust/issues/43806 for details.) return;"} {"_id":"doc-en-rust-9f071304879564d3a89e506a93ba95f2f5ad2a6bbbe47bb75bcb30e011156ad3","title":"","text":"op_warned = true; } if !(type_permits_no_use || fn_warned || op_warned) { if !(type_permits_lack_of_use || fn_warned || op_warned) { cx.span_lint(UNUSED_RESULTS, s.span, \"unused result\"); } fn check_must_use(cx: &LateContext, def_id: DefId, sp: Span, describe_path: &str) -> bool { fn check_must_use( cx: &LateContext, def_id: DefId, sp: Span, descr_pre_path: &str, descr_post_path: &str, ) -> bool { for attr in cx.tcx.get_attrs(def_id).iter() { if attr.check_name(\"must_use\") { let msg = format!(\"unused {}`{}` that must be used\", describe_path, cx.tcx.item_path_str(def_id)); let msg = format!(\"unused {}`{}`{} that must be used\", descr_pre_path, cx.tcx.item_path_str(def_id), descr_post_path); let mut err = cx.struct_span_lint(UNUSED_MUST_USE, sp, &msg); // check for #[must_use = \"...\"] if let Some(note) = attr.value_str() {"} {"_id":"doc-en-rust-078fa241d8dadb3c74afdf4ca26e0b6c1edddff36749c2db695383c629302072","title":"","text":" #![deny(unused_must_use)] #[must_use] trait Critical {} trait NotSoCritical {} trait DecidedlyUnimportant {} struct Anon; impl Critical for Anon {} impl NotSoCritical for Anon {} impl DecidedlyUnimportant for Anon {} fn get_critical() -> impl NotSoCritical + Critical + DecidedlyUnimportant { Anon {} } fn main() { get_critical(); //~ ERROR unused implementer of `Critical` that must be used } "} {"_id":"doc-en-rust-e60f9f8bfbe08a2ba4317b8001294dd11c04f328a928e5f3363a9dc921cd0347","title":"","text":" error: unused implementer of `Critical` that must be used --> $DIR/must_use-trait.rs:21:5 | LL | get_critical(); //~ ERROR unused implementer of `Critical` that must be used | ^^^^^^^^^^^^^^^ | note: lint level defined here --> $DIR/must_use-trait.rs:1:9 | LL | #![deny(unused_must_use)] | ^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-2185c11d719580ae6a96bf23adb79035c9d3125dbd763d73071a729c1a03be63","title":"","text":"let crate_types = if options.proc_macro_crate { vec![config::CrateType::ProcMacro] } else { vec![config::CrateType::Dylib] vec![config::CrateType::Rlib] }; let sessopts = config::Options {"} {"_id":"doc-en-rust-730d8af471a097ca87de7e62ba799a568736de53310b9d3a004bfae9da5412d0","title":"","text":"intravisit::walk_crate(this, krate); }); }); compiler.session().abort_if_errors(); let ret: Result<_, ErrorReported> = Ok(collector.tests); ret }) }) .expect(\"compiler aborted in rustdoc!\"); }); let tests = match tests { Ok(tests) => tests, Err(ErrorReported) => return 1, }; test_args.insert(0, \"rustdoctest\".to_string());"} {"_id":"doc-en-rust-4bd020103b9b30d63ef8d769e2f702ddd6246afe24ff491873a5cc734f4597a8","title":"","text":" // compile-flags:--test /// ``` /// assert!(true) /// ``` pub fn f() {} pub fn f() {} "} {"_id":"doc-en-rust-bd8314732989e38719c888c03ebe6b03e87ad1ef2f90c26583ed3be69bc29d23","title":"","text":" error[E0428]: the name `f` is defined multiple times --> $DIR/test-compile-fail1.rs:8:1 | 6 | pub fn f() {} | ---------- previous definition of the value `f` here 7 | 8 | pub fn f() {} | ^^^^^^^^^^ `f` redefined here | = note: `f` must be defined only once in the value namespace of this module error: aborting due to previous error For more information about this error, try `rustc --explain E0428`. "} {"_id":"doc-en-rust-a0351748c9cbf73d77aeccbb984243628302e70247d814c6850fe281764deec1","title":"","text":" error: expected one of `!` or `::`, found `` --> $DIR/test-compile-fail2.rs:3:1 | 3 | fail | ^^^^ expected one of `!` or `::` error: aborting due to previous error "} {"_id":"doc-en-rust-c6dadb5ef56592fc4032b296f90f31832569128a65787342d91d4c06f060a997","title":"","text":" error: unterminated double quote string --> $DIR/test-compile-fail3.rs:3:1 | 3 | \"fail | ^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-58f1a427da5d5eca90f5c857c2cc049cf337d3d53e01e4b769953b5e75829ab3","title":"","text":" // compile-flags:--test // normalize-stdout-test: \"src/test/rustdoc-ui\" -> \"$$DIR\" // build-pass #![no_std] extern crate alloc; /// ``` /// assert!(true) /// ``` pub fn f() {} "} {"_id":"doc-en-rust-9e3779ba40badfef10340e5a4878404bd118f489f87b3f18b3c8188c14387641","title":"","text":" running 1 test test $DIR/test-no_std.rs - f (line 9) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out "} {"_id":"doc-en-rust-80e55fd209c223fb00aed2ff7ea3ec1d0a53c463c93b8182cb57d55f2841cf74","title":"","text":"let mut cargo = Command::new(&self.initial_cargo); let out_dir = self.stage_out(compiler, mode); // command specific path, we call clear_if_dirty with this let mut my_out = match cmd { \"build\" => self.cargo_out(compiler, mode, target), // This is the intended out directory for crate documentation. \"doc\" | \"rustdoc\" => self.crate_doc_out(target), _ => self.stage_out(compiler, mode), }; // This is for the original compiler, but if we're forced to use stage 1, then // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since // we copy the libs forward. let cmp = self.compiler_for(compiler.stage, compiler.host, target); let libstd_stamp = match cmd { \"check\" | \"clippy\" | \"fix\" => check::libstd_stamp(self, cmp, target), _ => compile::libstd_stamp(self, cmp, target), }; let libtest_stamp = match cmd { \"check\" | \"clippy\" | \"fix\" => check::libtest_stamp(self, cmp, target), _ => compile::libtest_stamp(self, cmp, target), }; let librustc_stamp = match cmd { \"check\" | \"clippy\" | \"fix\" => check::librustc_stamp(self, cmp, target), _ => compile::librustc_stamp(self, cmp, target), }; // Codegen backends are not yet tracked by -Zbinary-dep-depinfo, // so we need to explicitly clear out if they've been updated. for backend in self.codegen_backends(compiler) { self.clear_if_dirty(&out_dir, &backend); } if cmd == \"doc\" || cmd == \"rustdoc\" { if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen { let my_out = match mode { // This is the intended out directory for compiler documentation. my_out = self.compiler_doc_out(target); } Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target), _ => self.crate_doc_out(target), }; let rustdoc = self.rustdoc(compiler); self.clear_if_dirty(&my_out, &rustdoc); } else if cmd != \"test\" { match mode { Mode::Std => { self.clear_if_dirty(&my_out, &self.rustc(compiler)); for backend in self.codegen_backends(compiler) { self.clear_if_dirty(&my_out, &backend); } }, Mode::Test => { self.clear_if_dirty(&my_out, &libstd_stamp); }, Mode::Rustc => { self.clear_if_dirty(&my_out, &self.rustc(compiler)); self.clear_if_dirty(&my_out, &libstd_stamp); self.clear_if_dirty(&my_out, &libtest_stamp); }, Mode::Codegen => { self.clear_if_dirty(&my_out, &librustc_stamp); }, Mode::ToolBootstrap => { }, Mode::ToolStd => { self.clear_if_dirty(&my_out, &libstd_stamp); }, Mode::ToolTest => { self.clear_if_dirty(&my_out, &libstd_stamp); self.clear_if_dirty(&my_out, &libtest_stamp); }, Mode::ToolRustc => { self.clear_if_dirty(&my_out, &libstd_stamp); self.clear_if_dirty(&my_out, &libtest_stamp); self.clear_if_dirty(&my_out, &librustc_stamp); }, } } cargo"} {"_id":"doc-en-rust-9d639d84c2f0fe53329d4b551bedabea3c30bcb4f1a8908092c0c607b18583a7","title":"","text":"}, } // This tells Cargo (and in turn, rustc) to output more complete // dependency information. Most importantly for rustbuild, this // includes sysroot artifacts, like libstd, which means that we don't // need to track those in rustbuild (an error prone process!). This // feature is currently unstable as there may be some bugs and such, but // it represents a big improvement in rustbuild's reliability on // rebuilds, so we're using it here. // // For some additional context, see #63470 (the PR originally adding // this), as well as #63012 which is the tracking issue for this // feature on the rustc side. cargo.arg(\"-Zbinary-dep-depinfo\"); cargo.arg(\"-j\").arg(self.jobs().to_string()); // Remove make-related flags to ensure Cargo can correctly set things up cargo.env_remove(\"MAKEFLAGS\");"} {"_id":"doc-en-rust-f515d4963da911b191f7faae357370e1be6dc99e30fd6ccb2209db0947d434f6","title":"","text":"let libdir = builder.sysroot_libdir(compiler, target); let hostdir = builder.sysroot_libdir(compiler, compiler.host); add_to_sysroot(&builder, &libdir, &hostdir, &rustdoc_stamp(builder, compiler, target)); builder.cargo(compiler, Mode::ToolRustc, target, \"clean\"); } }"} {"_id":"doc-en-rust-432d9631a7ef91d129d2cfaff55f38dadb459167bf99bc7744fd5bc512bfc321","title":"","text":"use std::process::{Command, Stdio, exit}; use std::str; use build_helper::{output, mtime, t, up_to_date}; use build_helper::{output, t, up_to_date}; use filetime::FileTime; use serde::Deserialize; use serde_json;"} {"_id":"doc-en-rust-093ad82386bc6f2c9804225303004b7374d3bd3f54cc107e31b82a46c2e29d8e","title":"","text":"// for reason why the sanitizers are not built in stage0. copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), \"osx\", &libdir); } builder.cargo(target_compiler, Mode::ToolStd, target, \"clean\"); } }"} {"_id":"doc-en-rust-4f02897f85d8e9bfdaeae6766e030d8555e33e4613fcd3fb04fedf0d0990a802","title":"","text":"&builder.sysroot_libdir(target_compiler, compiler.host), &libtest_stamp(builder, compiler, target) ); builder.cargo(target_compiler, Mode::ToolTest, target, \"clean\"); } }"} {"_id":"doc-en-rust-d2343b61ee6096e2e13dd91893e26549fb3a997a5898079b8bbabeb6dce96bb6","title":"","text":"&builder.sysroot_libdir(target_compiler, compiler.host), &librustc_stamp(builder, compiler, target) ); builder.cargo(target_compiler, Mode::ToolRustc, target, \"clean\"); } }"} {"_id":"doc-en-rust-d645c75ba90a4081207db3103439b1bcb0c9033b5d6299a205f1ce0b23845741","title":"","text":"deps.push((path_to_add.into(), false)); } // Now we want to update the contents of the stamp file, if necessary. First // we read off the previous contents along with its mtime. If our new // contents (the list of files to copy) is different or if any dep's mtime // is newer then we rewrite the stamp file. deps.sort(); let stamp_contents = fs::read(stamp); let stamp_mtime = mtime(&stamp); let mut new_contents = Vec::new(); let mut max = None; let mut max_path = None; for (dep, proc_macro) in deps.iter() { let mtime = mtime(dep); if Some(mtime) > max { max = Some(mtime); max_path = Some(dep.clone()); } new_contents.extend(if *proc_macro { b\"h\" } else { b\"t\" }); new_contents.extend(dep.to_str().unwrap().as_bytes()); new_contents.extend(b\"0\"); } let max = max.unwrap(); let max_path = max_path.unwrap(); let contents_equal = stamp_contents .map(|contents| contents == new_contents) .unwrap_or_default(); if contents_equal && max <= stamp_mtime { builder.verbose(&format!(\"not updating {:?}; contents equal and {:?} <= {:?}\", stamp, max, stamp_mtime)); return deps.into_iter().map(|(d, _)| d).collect() } if max > stamp_mtime { builder.verbose(&format!(\"updating {:?} as {:?} changed\", stamp, max_path)); } else { builder.verbose(&format!(\"updating {:?} as deps changed\", stamp)); } t!(fs::write(&stamp, &new_contents)); deps.into_iter().map(|(d, _)| d).collect() }"} {"_id":"doc-en-rust-bfff6c562df6eeb6434f1b2fcc5e3ca49ccc18c496c26d56c5273b4ce075710c","title":"","text":" #![feature(existential_type)] existential type Foo: Fn() -> Foo; //~^ ERROR: cycle detected when processing `Foo` fn crash(x: Foo) -> Foo { x } fn main() { } "} {"_id":"doc-en-rust-309c9615514abe45ed4590ac8a2404c29d85f2d8947390ba8c2dfc2ab12efb28","title":"","text":" error[E0391]: cycle detected when processing `Foo` --> $DIR/existential-types-with-cycle-error.rs:3:1 | LL | existential type Foo: Fn() -> Foo; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: ...which requires processing `crash`... --> $DIR/existential-types-with-cycle-error.rs:6:25 | LL | fn crash(x: Foo) -> Foo { | _________________________^ LL | | x LL | | } | |_^ = note: ...which again requires processing `Foo`, completing the cycle note: cycle used when collecting item types in top-level module --> $DIR/existential-types-with-cycle-error.rs:1:1 | LL | / #![feature(existential_type)] LL | | LL | | existential type Foo: Fn() -> Foo; LL | | ... | LL | | LL | | } | |_^ error: aborting due to previous error For more information about this error, try `rustc --explain E0391`. "} {"_id":"doc-en-rust-893119c51d43a9996f15814c0c423cfcba20a64ce0443c2375d3c7799a11b2b9","title":"","text":" #![feature(existential_type)] pub trait Bar { type Item; } existential type Foo: Bar; //~^ ERROR: cycle detected when processing `Foo` fn crash(x: Foo) -> Foo { x } fn main() { } "} {"_id":"doc-en-rust-c4e9fd96991bcdc431b55b2b46602e9c82136f1db32382d87ac204fedb48a616","title":"","text":" error[E0391]: cycle detected when processing `Foo` --> $DIR/existential-types-with-cycle-error2.rs:7:1 | LL | existential type Foo: Bar; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: ...which requires processing `crash`... --> $DIR/existential-types-with-cycle-error2.rs:10:25 | LL | fn crash(x: Foo) -> Foo { | _________________________^ LL | | x LL | | } | |_^ = note: ...which again requires processing `Foo`, completing the cycle note: cycle used when collecting item types in top-level module --> $DIR/existential-types-with-cycle-error2.rs:1:1 | LL | / #![feature(existential_type)] LL | | LL | | pub trait Bar { LL | | type Item; ... | LL | | LL | | } | |_^ error: aborting due to previous error For more information about this error, try `rustc --explain E0391`. "} {"_id":"doc-en-rust-7abb2fef10aa85f2f4f89b3b442b1d096cd25b4b525d395f9815f73913839c24","title":"","text":"pub use vec::{ImmutableEqVector, ImmutableCopyableVector}; pub use vec::{OwnedVector, OwnedCopyableVector}; /* Reexported runtime types */ pub use comm::{stream, Port, Chan, GenericChan, GenericSmartChan, GenericPort, Peekable}; pub use task::spawn; /* Reexported modules */ pub use at_vec;"} {"_id":"doc-en-rust-d0a8eafb49a65744ff4220a167579c233d5095e8d86f35abca7f8b2c60cda137","title":"","text":"// versions of them accidentally sneak into our dependency graph to // ensure we keep our CI times under control // \"cargo\", // FIXME(#53005) // \"rustc-ap-syntax\", // FIXME(#53006) \"rustc-ap-syntax\", ]; let mut name_to_id = HashMap::new(); for node in resolve.nodes.iter() {"} {"_id":"doc-en-rust-2c2a59dbf64a1412f224450ae9df6f3e46305774e5d0fedad748a34d28b229ce","title":"","text":" // compile-pass // edition:2018 #![feature(arbitrary_self_types, async_await, await_macro)] use std::task::{self, Poll}; use std::future::Future; use std::marker::Unpin; use std::pin::Pin; // This is a regression test for a ICE/unbounded recursion issue relating to async-await. #[derive(Debug)] #[must_use = \"futures do nothing unless polled\"] pub struct Lazy { f: Option } impl Unpin for Lazy {} pub fn lazy(f: F) -> Lazy where F: FnOnce(&mut task::Context) -> R, { Lazy { f: Some(f) } } impl Future for Lazy where F: FnOnce(&mut task::Context) -> R, { type Output = R; fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context) -> Poll { Poll::Ready((self.f.take().unwrap())(cx)) } } async fn __receive(want: WantFn) -> () where Fut: Future, WantFn: Fn(&Box) -> Fut, { await!(lazy(|_| ())); } pub fn basic_spawn_receive() { async { await!(__receive(|_| async { () })) }; } fn main() {} "} {"_id":"doc-en-rust-821638dbb94fa27234684f735494b3f36f062fea14d0615f05c9949c21fcfab9","title":"","text":"use std::fmt; use rustc_target::spec::abi; use syntax::ast; use errors::DiagnosticBuilder; use errors::{Applicability, DiagnosticBuilder}; use syntax_pos::Span; use hir;"} {"_id":"doc-en-rust-2ff11411f28cf5373cdcb3397a9631e235accd20837b458164346db94089419d","title":"","text":"db.note(\"no two closures, even if identical, have the same type\"); db.help(\"consider boxing your closure and/or using it as a trait object\"); } match (&values.found.sty, &values.expected.sty) { // Issue #53280 (ty::TyInfer(ty::IntVar(_)), ty::TyFloat(_)) => { if let Ok(snippet) = self.sess.codemap().span_to_snippet(sp) { if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') { db.span_suggestion_with_applicability( sp, \"use a float literal\", format!(\"{}.0\", snippet), Applicability::MachineApplicable ); } } }, _ => {} } }, OldStyleLUB(err) => { db.note(\"this was previously accepted by the compiler but has been phased out\");"} {"_id":"doc-en-rust-bfeb57377dab3f0c492bbc40ca0672bf3e2abcc647618a0728a0599320560755","title":"","text":"--> $DIR/catch-block-type-error.rs:18:9 | LL | 42 | ^^ expected f32, found integral variable | ^^ | | | expected f32, found integral variable | help: use a float literal: `42.0` | = note: expected type `f32` found type `{integer}`"} {"_id":"doc-en-rust-981800a85e59b3f872c59949783b88c469a3fa72570f85c3d23519178cb4a3a8","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let sixteen: f32 = 16; //~^ ERROR mismatched types //~| HELP use a float literal let a_million_and_seventy: f64 = 1_000_070; //~^ ERROR mismatched types //~| HELP use a float literal let negative_nine: f32 = -9; //~^ ERROR mismatched types //~| HELP use a float literal // only base-10 literals get the suggestion let sixteen_again: f64 = 0x10; //~^ ERROR mismatched types let and_once_more: f32 = 0o20; //~^ ERROR mismatched types } "} {"_id":"doc-en-rust-4cd453487e5fa3a45012b5762e11ce463fa8d802ae6dc0268a235b1c22c78695","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-53280-expected-float-found-integer-literal.rs:12:24 | LL | let sixteen: f32 = 16; | ^^ | | | expected f32, found integral variable | help: use a float literal: `16.0` | = note: expected type `f32` found type `{integer}` error[E0308]: mismatched types --> $DIR/issue-53280-expected-float-found-integer-literal.rs:15:38 | LL | let a_million_and_seventy: f64 = 1_000_070; | ^^^^^^^^^ | | | expected f64, found integral variable | help: use a float literal: `1_000_070.0` | = note: expected type `f64` found type `{integer}` error[E0308]: mismatched types --> $DIR/issue-53280-expected-float-found-integer-literal.rs:18:30 | LL | let negative_nine: f32 = -9; | ^^ | | | expected f32, found integral variable | help: use a float literal: `-9.0` | = note: expected type `f32` found type `{integer}` error[E0308]: mismatched types --> $DIR/issue-53280-expected-float-found-integer-literal.rs:25:30 | LL | let sixteen_again: f64 = 0x10; | ^^^^ expected f64, found integral variable | = note: expected type `f64` found type `{integer}` error[E0308]: mismatched types --> $DIR/issue-53280-expected-float-found-integer-literal.rs:27:30 | LL | let and_once_more: f32 = 0o20; | ^^^^ expected f32, found integral variable | = note: expected type `f32` found type `{integer}` error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-19c3dfa8bc32bc9a9584f2e3bafd8a4a997be1399d8b29b2018a77b098620cf3","title":"","text":"let mut cmd = Command::new(rustc); cmd.args(&args) .arg(\"--cfg\") .arg(format!(\"stage{}\", stage)) .env(bootstrap::util::dylib_path_var(), env::join_paths(&dylib_path).unwrap()); let mut maybe_crate = None; // Non-zero stages must all be treated uniformly to avoid problems when attempting to uplift // compiler libraries and such from stage 1 to 2. if stage == \"0\" { cmd.arg(\"--cfg\").arg(\"bootstrap\"); } // Print backtrace in case of ICE if env::var(\"RUSTC_BACKTRACE_ON_ICE\").is_ok() && env::var(\"RUST_BACKTRACE\").is_err() { cmd.env(\"RUST_BACKTRACE\", \"1\");"} {"_id":"doc-en-rust-1dbeda62b6c0057fe1bf796294382bf907a2c954f68a1c0b7d65a2b983beb7ff","title":"","text":"if !up_to_date(src_file, dst_file) { let mut cmd = Command::new(&builder.initial_rustc); builder.run(cmd.env(\"RUSTC_BOOTSTRAP\", \"1\") .arg(\"--cfg\").arg(\"stage0\") .arg(\"--cfg\").arg(\"bootstrap\") .arg(\"--target\").arg(target) .arg(\"--emit=obj\") .arg(\"-o\").arg(dst_file)"} {"_id":"doc-en-rust-2e59dab19486ef3b0a58bde31e33fe9a2c5887e33a1694173a7719ca60ec4a48","title":"","text":"/// Returns the result of an unchecked addition, resulting in /// undefined behavior when `x + y > T::max_value()` or `x + y < T::min_value()`. #[cfg(not(stage0))] #[cfg(not(bootstrap))] pub fn unchecked_add(x: T, y: T) -> T; /// Returns the result of an unchecked substraction, resulting in /// undefined behavior when `x - y > T::max_value()` or `x - y < T::min_value()`. #[cfg(not(stage0))] #[cfg(not(bootstrap))] pub fn unchecked_sub(x: T, y: T) -> T; /// Returns the result of an unchecked multiplication, resulting in /// undefined behavior when `x * y > T::max_value()` or `x * y < T::min_value()`. #[cfg(not(stage0))] #[cfg(not(bootstrap))] pub fn unchecked_mul(x: T, y: T) -> T; /// Performs rotate left."} {"_id":"doc-en-rust-cc011ff0668bd2072e9de041c221f8ca0fe1d41c19577ea919454185c88153b7","title":"","text":"#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] #[repr(transparent)] #[rustc_layout_scalar_valid_range_start(1)] #[cfg_attr(not(stage0), rustc_nonnull_optimization_guaranteed)] #[cfg_attr(not(bootstrap), rustc_nonnull_optimization_guaranteed)] pub struct $Ty($Int); }"} {"_id":"doc-en-rust-f6d2dd2b46d27d24a9fdbb1535240e3889309298fdc1d6a6a64a0ee873ac2b23","title":"","text":"#[stable(feature = \"nonnull\", since = \"1.25.0\")] #[repr(transparent)] #[rustc_layout_scalar_valid_range_start(1)] #[cfg_attr(not(stage0), rustc_nonnull_optimization_guaranteed)] #[cfg_attr(not(bootstrap), rustc_nonnull_optimization_guaranteed)] pub struct NonNull { pointer: *const T, }"} {"_id":"doc-en-rust-8ae11538bc4c12fa714430adecf84234046102af1e7ab41715005d23d939e9bb","title":"","text":"if receiver.ends_with(&method_call) { None // do not suggest code that is already there (#53348) } else { Some(format!(\"{}{}\", receiver, method_call)) /* methods defined in `method_call_list` will overwrite `.clone()` in copy of `receiver` */ let method_call_list = [\".to_vec()\", \".to_string()\"]; if receiver.ends_with(\".clone()\") && method_call_list.contains(&method_call.as_str()){ // created copy of `receiver` because we don't want other // suggestion to get affected let mut new_receiver = receiver.clone(); let max_len = new_receiver.rfind(\".\").unwrap(); new_receiver.truncate(max_len); Some(format!(\"{}{}\", new_receiver, method_call)) } else { Some(format!(\"{}{}\", receiver, method_call)) } } }) .collect::>(); if !suggestions.is_empty() {"} {"_id":"doc-en-rust-30d510eaee38def757036da73a32135e0f9bc82b8e01c2314cfd0a981cbbac3e","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let items = vec![1, 2, 3]; let ref_items: &[i32] = &items; let items_clone: Vec = ref_items.clone(); // in that case no suggestion will be triggered let items_clone_2:Vec = items.clone(); let s = \"hi\"; let string: String = s.clone(); // in that case no suggestion will be triggered let s2 = \"hi\"; let string_2: String = s2.to_string(); } "} {"_id":"doc-en-rust-f17d79c8ff3435d5acbe2c9bdff658e15ecf333a3bffc532e0c2e9b8622b5cb7","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-53692.rs:13:37 | LL | let items_clone: Vec = ref_items.clone(); | ^^^^^^^^^^^^^^^^^ | | | expected struct `std::vec::Vec`, found &[i32] | help: try using a conversion method: `ref_items.to_vec()` | = note: expected type `std::vec::Vec` found type `&[i32]` error[E0308]: mismatched types --> $DIR/issue-53692.rs:19:30 | LL | let string: String = s.clone(); | ^^^^^^^^^ | | | expected struct `std::string::String`, found &str | help: try using a conversion method: `s.to_string()` | = note: expected type `std::string::String` found type `&str` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-965352e527425cb2e2428513ec0566e8d991617c8402e6b553c9518ec06ed767","title":"","text":"// for ':' and '-' '-' | ':' => self.path.temp_buf.push('.'), // Avoid segmentation fault on some platforms, see #60925. 'm' if self.path.temp_buf.ends_with(\".llv\") => self.path.temp_buf.push_str(\"$6d$\"), // These are legal symbols 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => self.path.temp_buf.push(c),"} {"_id":"doc-en-rust-77f5d451307b19de0cd129129217f9d2bbe14fcca4d0b330af5b1f965f0d3ae4","title":"","text":" // compile-pass // This test is the same code as in ui/symbol-names/issue-60925.rs but this checks that the // reproduction compiles successfully and doesn't segfault, whereas that test just checks that the // symbol mangling fix produces the correct result. fn dummy() {} mod llvm { pub(crate) struct Foo; } mod foo { pub(crate) struct Foo(T); impl Foo<::llvm::Foo> { pub(crate) fn foo() { for _ in 0..0 { for _ in &[::dummy()] { ::dummy(); ::dummy(); ::dummy(); } } } } pub(crate) fn foo() { Foo::foo(); Foo::foo(); } } pub fn foo() { foo::foo(); } fn main() {} "} {"_id":"doc-en-rust-39e443e712ffb8bcdbd2441c3cc3be7781dbf146dc4d371976481a7cba3543ad","title":"","text":" #![feature(rustc_attrs)] // This test is the same code as in ui/issue-53912.rs but this test checks that the symbol mangling // fix produces the correct result, whereas that test just checks that the reproduction compiles // successfully and doesn't segfault fn dummy() {} mod llvm { pub(crate) struct Foo; } mod foo { pub(crate) struct Foo(T); impl Foo<::llvm::Foo> { #[rustc_symbol_name] //~^ ERROR _ZN11issue_609253foo36Foo$LT$issue_60925..llv$6d$..Foo$GT$3foo17h059a991a004536adE pub(crate) fn foo() { for _ in 0..0 { for _ in &[::dummy()] { ::dummy(); ::dummy(); ::dummy(); } } } } pub(crate) fn foo() { Foo::foo(); Foo::foo(); } } pub fn foo() { foo::foo(); } fn main() {} "} {"_id":"doc-en-rust-46624c17f2abdd3cd74cc525304007f027a75abc1012a191f5ba70026e7a42eb","title":"","text":" error: symbol-name(_ZN11issue_609253foo36Foo$LT$issue_60925..llv$6d$..Foo$GT$3foo17h059a991a004536adE) --> $DIR/issue-60925.rs:16:9 | LL | #[rustc_symbol_name] | ^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-b111cee88113aab44e0e7a620b5688b5e609d8d74eabb1430ecdb1a13081dc57","title":"","text":" // check-pass // ignore-emscripten no llvm_asm! support #![feature(llvm_asm)] pub fn boot(addr: Option) { unsafe { llvm_asm!(\"mov sp, $0\"::\"r\" (addr)); } } fn main() {} "} {"_id":"doc-en-rust-9bbda2951bd1d422a0299f321743b1ffc80223d3d2b4feb84ae91e1615131b62","title":"","text":" // edition:2018 use std::sync::{Arc, Mutex}; pub async fn f(_: ()) {} pub async fn run() { let x: Arc> = unimplemented!(); f(*x.lock().unwrap()).await; } "} {"_id":"doc-en-rust-0171650462e4b54ca96211827890dfed43585caa9d06c87d9b38aa84282859f0","title":"","text":" // aux-build: issue_67893.rs // edition:2018 // dont-check-compiler-stderr // FIXME(#71222): Add above flag because of the difference of stderrs on some env. extern crate issue_67893; fn g(_: impl Send) {} fn main() { g(issue_67893::run()) //~^ ERROR: `std::sync::MutexGuard<'_, ()>` cannot be sent between threads safely } "} {"_id":"doc-en-rust-2ddf6c58ddf4b601141935c77f885ff7fc81a67e0a3f28728e31de8e60e347d2","title":"","text":" #![feature(intrinsics)] extern \"C\" { pub static FOO: extern \"rust-intrinsic\" fn(); } fn main() { FOO() //~ ERROR: use of extern static is unsafe } "} {"_id":"doc-en-rust-347db88b9583cffb99f514a6abdc7080778fc486bcce9801ef67e394bb032380","title":"","text":" error[E0133]: use of extern static is unsafe and requires unsafe function or block --> $DIR/issue-28575.rs:8:5 | LL | FOO() | ^^^ use of extern static | = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior error: aborting due to previous error For more information about this error, try `rustc --explain E0133`. "} {"_id":"doc-en-rust-39cfaec0d2fbd441504c7b401a9cf6dbd1948d7e157379fc88934e375e7cfb63","title":"","text":" pub static TEST_STR: &'static str = \"Hello world\"; "} {"_id":"doc-en-rust-5c74c3295b7cbb090e71d42c4c3e57b5d4abae463790a7a89870ca49933cbeae","title":"","text":" // aux-build: issue_24843.rs // check-pass extern crate issue_24843; static _TEST_STR_2: &'static str = &issue_24843::TEST_STR; fn main() {} "} {"_id":"doc-en-rust-350e274ef6e82a00ba99357a3982b6ed9d0b64494cf2da840510109239afbd59","title":"","text":"/// `&mut T` references can be freely coerced into `&T` references with the same referent type, and /// references with longer lifetimes can be freely coerced into references with shorter ones. /// /// Reference equality by address, instead of comparing the values pointed to, is accomplished via /// implicit reference-pointer coercion and raw pointer equality via [`ptr::eq`], while /// [`PartialEq`] compares values. /// /// [`ptr::eq`]: ptr/fn.eq.html /// [`PartialEq`]: cmp/trait.PartialEq.html /// /// ``` /// use std::ptr; /// /// let five = 5; /// let other_five = 5; /// let five_ref = &five; /// let same_five_ref = &five; /// let other_five_ref = &other_five; /// /// assert!(five_ref == same_five_ref); /// assert!(five_ref == other_five_ref); /// /// assert!(ptr::eq(five_ref, same_five_ref)); /// assert!(!ptr::eq(five_ref, other_five_ref)); /// ``` /// /// For more information on how to use references, see [the book's section on \"References and /// Borrowing\"][book-refs]. /// /// [book-refs]: ../book/second-edition/ch04-02-references-and-borrowing.html /// /// # Trait implementations /// /// The following traits are implemented for all `&T`, regardless of the type of its referent: /// /// * [`Copy`]"} {"_id":"doc-en-rust-5bdedc812132e683bb84fce1ed07393ea44f05998df134b2dc1b437b1eafea15","title":"","text":"}; if self.can_coerce(ref_ty, expected) { if let Ok(src) = cm.span_to_snippet(sp) { let sugg_expr = match expr.node { // parenthesize if needed (Issue #46756) let needs_parens = match expr.node { // parenthesize if needed (Issue #46756) hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => format!(\"({})\", src), _ => src, hir::ExprKind::Binary(_, _, _) => true, // parenthesize borrows of range literals (Issue #54505) _ if self.is_range_literal(expr) => true, _ => false, }; let sugg_expr = if needs_parens { format!(\"({})\", src) } else { src }; if let Some(sugg) = self.can_use_as_ref(expr) { return Some(sugg); }"} {"_id":"doc-en-rust-010a7dda86dbc7d94aff92302d4fd01089656e021988847660ef6a4996612f9f","title":"","text":"None } /// This function checks if the specified expression is a built-in range literal. /// (See: `LoweringContext::lower_expr()` in `src/librustc/hir/lowering.rs`). fn is_range_literal(&self, expr: &hir::Expr) -> bool { use hir::{Path, QPath, ExprKind, TyKind}; // We support `::std::ops::Range` and `::core::ops::Range` prefixes let is_range_path = |path: &Path| { let mut segs = path.segments.iter() .map(|seg| seg.ident.as_str()); if let (Some(root), Some(std_core), Some(ops), Some(range), None) = (segs.next(), segs.next(), segs.next(), segs.next(), segs.next()) { // \"{{root}}\" is the equivalent of `::` prefix in Path root == \"{{root}}\" && (std_core == \"std\" || std_core == \"core\") && ops == \"ops\" && range.starts_with(\"Range\") } else { false } }; let span_is_range_literal = |span: &Span| { // Check whether a span corresponding to a range expression // is a range literal, rather than an explicit struct or `new()` call. let source_map = self.tcx.sess.source_map(); let end_point = source_map.end_point(*span); if let Ok(end_string) = source_map.span_to_snippet(end_point) { !(end_string.ends_with(\"}\") || end_string.ends_with(\")\")) } else { false } }; match expr.node { // All built-in range literals but `..=` and `..` desugar to Structs ExprKind::Struct(QPath::Resolved(None, ref path), _, _) | // `..` desugars to its struct path ExprKind::Path(QPath::Resolved(None, ref path)) => { return is_range_path(&path) && span_is_range_literal(&expr.span); } // `..=` desugars into `::std::ops::RangeInclusive::new(...)` ExprKind::Call(ref func, _) => { if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node { if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node { let call_to_new = segment.ident.as_str() == \"new\"; return is_range_path(&path) && span_is_range_literal(&expr.span) && call_to_new; } } } _ => {} } false } pub fn check_for_cast(&self, err: &mut DiagnosticBuilder<'tcx>, expr: &hir::Expr,"} {"_id":"doc-en-rust-a5261fce819135d2e62386b006710dc10c88fb761e13852cd7a21c4da565b082","title":"","text":" // run-rustfix // Regression test for changes introduced while fixing #54505 // This test uses non-literals for Ranges // (expecting no parens with borrow suggestion) use std::ops::RangeBounds; // take a reference to any built-in range fn take_range(_r: &impl RangeBounds) {} fn main() { take_range(&std::ops::Range { start: 0, end: 1 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::Range { start: 0, end: 1 } take_range(&::std::ops::Range { start: 0, end: 1 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::Range { start: 0, end: 1 } take_range(&std::ops::RangeFrom { start: 1 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeFrom { start: 1 } take_range(&::std::ops::RangeFrom { start: 1 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeFrom { start: 1 } take_range(&std::ops::RangeFull {}); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeFull {} take_range(&::std::ops::RangeFull {}); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeFull {} take_range(&std::ops::RangeInclusive::new(0, 1)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeInclusive::new(0, 1) take_range(&::std::ops::RangeInclusive::new(0, 1)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeInclusive::new(0, 1) take_range(&std::ops::RangeTo { end: 5 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeTo { end: 5 } take_range(&::std::ops::RangeTo { end: 5 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeTo { end: 5 } take_range(&std::ops::RangeToInclusive { end: 5 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeToInclusive { end: 5 } take_range(&::std::ops::RangeToInclusive { end: 5 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeToInclusive { end: 5 } } "} {"_id":"doc-en-rust-fabdcc7d6d506a1ff52e772db76cc5afd2d4f6ddac47dc034c9d34aa36bae083","title":"","text":" // run-rustfix // Regression test for changes introduced while fixing #54505 // This test uses non-literals for Ranges // (expecting no parens with borrow suggestion) use std::ops::RangeBounds; // take a reference to any built-in range fn take_range(_r: &impl RangeBounds) {} fn main() { take_range(std::ops::Range { start: 0, end: 1 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::Range { start: 0, end: 1 } take_range(::std::ops::Range { start: 0, end: 1 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::Range { start: 0, end: 1 } take_range(std::ops::RangeFrom { start: 1 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeFrom { start: 1 } take_range(::std::ops::RangeFrom { start: 1 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeFrom { start: 1 } take_range(std::ops::RangeFull {}); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeFull {} take_range(::std::ops::RangeFull {}); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeFull {} take_range(std::ops::RangeInclusive::new(0, 1)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeInclusive::new(0, 1) take_range(::std::ops::RangeInclusive::new(0, 1)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeInclusive::new(0, 1) take_range(std::ops::RangeTo { end: 5 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeTo { end: 5 } take_range(::std::ops::RangeTo { end: 5 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeTo { end: 5 } take_range(std::ops::RangeToInclusive { end: 5 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &std::ops::RangeToInclusive { end: 5 } take_range(::std::ops::RangeToInclusive { end: 5 }); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &::std::ops::RangeToInclusive { end: 5 } } "} {"_id":"doc-en-rust-91aa829566a5df7a09c8791c153248e9d3fbd45e1b398560fdad1754e8b5f6f6","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:16:16 | LL | take_range(std::ops::Range { start: 0, end: 1 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::Range` | help: consider borrowing here: `&std::ops::Range { start: 0, end: 1 }` | = note: expected type `&_` found type `std::ops::Range<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:21:16 | LL | take_range(::std::ops::Range { start: 0, end: 1 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::Range` | help: consider borrowing here: `&::std::ops::Range { start: 0, end: 1 }` | = note: expected type `&_` found type `std::ops::Range<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:26:16 | LL | take_range(std::ops::RangeFrom { start: 1 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeFrom` | help: consider borrowing here: `&std::ops::RangeFrom { start: 1 }` | = note: expected type `&_` found type `std::ops::RangeFrom<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:31:16 | LL | take_range(::std::ops::RangeFrom { start: 1 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeFrom` | help: consider borrowing here: `&::std::ops::RangeFrom { start: 1 }` | = note: expected type `&_` found type `std::ops::RangeFrom<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:36:16 | LL | take_range(std::ops::RangeFull {}); | ^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeFull` | help: consider borrowing here: `&std::ops::RangeFull {}` | = note: expected type `&_` found type `std::ops::RangeFull` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:41:16 | LL | take_range(::std::ops::RangeFull {}); | ^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeFull` | help: consider borrowing here: `&::std::ops::RangeFull {}` | = note: expected type `&_` found type `std::ops::RangeFull` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:46:16 | LL | take_range(std::ops::RangeInclusive::new(0, 1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeInclusive` | help: consider borrowing here: `&std::ops::RangeInclusive::new(0, 1)` | = note: expected type `&_` found type `std::ops::RangeInclusive<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:51:16 | LL | take_range(::std::ops::RangeInclusive::new(0, 1)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeInclusive` | help: consider borrowing here: `&::std::ops::RangeInclusive::new(0, 1)` | = note: expected type `&_` found type `std::ops::RangeInclusive<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:56:16 | LL | take_range(std::ops::RangeTo { end: 5 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeTo` | help: consider borrowing here: `&std::ops::RangeTo { end: 5 }` | = note: expected type `&_` found type `std::ops::RangeTo<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:61:16 | LL | take_range(::std::ops::RangeTo { end: 5 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeTo` | help: consider borrowing here: `&::std::ops::RangeTo { end: 5 }` | = note: expected type `&_` found type `std::ops::RangeTo<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:66:16 | LL | take_range(std::ops::RangeToInclusive { end: 5 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeToInclusive` | help: consider borrowing here: `&std::ops::RangeToInclusive { end: 5 }` | = note: expected type `&_` found type `std::ops::RangeToInclusive<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-literals.rs:71:16 | LL | take_range(::std::ops::RangeToInclusive { end: 5 }); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | expected reference, found struct `std::ops::RangeToInclusive` | help: consider borrowing here: `&::std::ops::RangeToInclusive { end: 5 }` | = note: expected type `&_` found type `std::ops::RangeToInclusive<{integer}>` error: aborting due to 12 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-cd4d8604ae155a76c3a701af59bd5abb29f82a20a0ace52c2091a5ddc27bdc8f","title":"","text":" // error-pattern: `#[panic_handler]` function required, but not found // Regression test for #54505 - range borrowing suggestion had // incorrect syntax (missing parentheses). // This test doesn't use std // (so all Ranges resolve to core::ops::Range...) #![no_std] #![feature(lang_items)] use core::ops::RangeBounds; #[cfg(not(target_arch = \"wasm32\"))] #[lang = \"eh_personality\"] extern fn eh_personality() {} #[cfg(target_os = \"windows\")] #[lang = \"eh_unwind_resume\"] extern fn eh_unwind_resume() {} // take a reference to any built-in range fn take_range(_r: &impl RangeBounds) {} fn main() { take_range(0..1); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(0..1) take_range(1..); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(1..) take_range(..); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(..) take_range(0..=1); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(0..=1) take_range(..5); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(..5) take_range(..=42); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(..=42) } "} {"_id":"doc-en-rust-09a06697fbc4231a846de2c13d7cd29f61f5b8aad2cfd53cf82133cd865a5f3e","title":"","text":" error: `#[panic_handler]` function required, but not found error[E0308]: mismatched types --> $DIR/issue-54505-no-std.rs:28:16 | LL | take_range(0..1); | ^^^^ | | | expected reference, found struct `core::ops::Range` | help: consider borrowing here: `&(0..1)` | = note: expected type `&_` found type `core::ops::Range<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-std.rs:33:16 | LL | take_range(1..); | ^^^ | | | expected reference, found struct `core::ops::RangeFrom` | help: consider borrowing here: `&(1..)` | = note: expected type `&_` found type `core::ops::RangeFrom<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-std.rs:38:16 | LL | take_range(..); | ^^ | | | expected reference, found struct `core::ops::RangeFull` | help: consider borrowing here: `&(..)` | = note: expected type `&_` found type `core::ops::RangeFull` error[E0308]: mismatched types --> $DIR/issue-54505-no-std.rs:43:16 | LL | take_range(0..=1); | ^^^^^ | | | expected reference, found struct `core::ops::RangeInclusive` | help: consider borrowing here: `&(0..=1)` | = note: expected type `&_` found type `core::ops::RangeInclusive<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-std.rs:48:16 | LL | take_range(..5); | ^^^ | | | expected reference, found struct `core::ops::RangeTo` | help: consider borrowing here: `&(..5)` | = note: expected type `&_` found type `core::ops::RangeTo<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505-no-std.rs:53:16 | LL | take_range(..=42); | ^^^^^ | | | expected reference, found struct `core::ops::RangeToInclusive` | help: consider borrowing here: `&(..=42)` | = note: expected type `&_` found type `core::ops::RangeToInclusive<{integer}>` error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-d83ff6bebabce62b6f19ddf7d7d80425f810fcee1d4f1c009680bef6f8e641e7","title":"","text":" // run-rustfix // Regression test for #54505 - range borrowing suggestion had // incorrect syntax (missing parentheses). use std::ops::RangeBounds; // take a reference to any built-in range fn take_range(_r: &impl RangeBounds) {} fn main() { take_range(&(0..1)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(0..1) take_range(&(1..)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(1..) take_range(&(..)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(..) take_range(&(0..=1)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(0..=1) take_range(&(..5)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(..5) take_range(&(..=42)); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(..=42) } "} {"_id":"doc-en-rust-3e1d92c8ffc40aa82d752a257b29ea2abfe0bcdf3bad19633b08b741135b7677","title":"","text":" // run-rustfix // Regression test for #54505 - range borrowing suggestion had // incorrect syntax (missing parentheses). use std::ops::RangeBounds; // take a reference to any built-in range fn take_range(_r: &impl RangeBounds) {} fn main() { take_range(0..1); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(0..1) take_range(1..); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(1..) take_range(..); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(..) take_range(0..=1); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(0..=1) take_range(..5); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(..5) take_range(..=42); //~^ ERROR mismatched types [E0308] //~| HELP consider borrowing here //~| SUGGESTION &(..=42) } "} {"_id":"doc-en-rust-deefe676370d584647586c621f1a526d83a84e2c7c25a2c6360858c1953fe721","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-54505.rs:14:16 | LL | take_range(0..1); | ^^^^ | | | expected reference, found struct `std::ops::Range` | help: consider borrowing here: `&(0..1)` | = note: expected type `&_` found type `std::ops::Range<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505.rs:19:16 | LL | take_range(1..); | ^^^ | | | expected reference, found struct `std::ops::RangeFrom` | help: consider borrowing here: `&(1..)` | = note: expected type `&_` found type `std::ops::RangeFrom<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505.rs:24:16 | LL | take_range(..); | ^^ | | | expected reference, found struct `std::ops::RangeFull` | help: consider borrowing here: `&(..)` | = note: expected type `&_` found type `std::ops::RangeFull` error[E0308]: mismatched types --> $DIR/issue-54505.rs:29:16 | LL | take_range(0..=1); | ^^^^^ | | | expected reference, found struct `std::ops::RangeInclusive` | help: consider borrowing here: `&(0..=1)` | = note: expected type `&_` found type `std::ops::RangeInclusive<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505.rs:34:16 | LL | take_range(..5); | ^^^ | | | expected reference, found struct `std::ops::RangeTo` | help: consider borrowing here: `&(..5)` | = note: expected type `&_` found type `std::ops::RangeTo<{integer}>` error[E0308]: mismatched types --> $DIR/issue-54505.rs:39:16 | LL | take_range(..=42); | ^^^^^ | | | expected reference, found struct `std::ops::RangeToInclusive` | help: consider borrowing here: `&(..=42)` | = note: expected type `&_` found type `std::ops::RangeToInclusive<{integer}>` error: aborting due to 6 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-b1e8bfb7983ffc24a235c4315cc4f0052233aeb451593610c91d42a1700d3b02","title":"","text":"match attr.parse_list(cx.parse_sess, |parser| parser.parse_path_allowing_meta(PathStyle::Mod)) { Ok(ref traits) if traits.is_empty() => { cx.span_warn(attr.span, \"empty trait list in `derive`\"); false } Ok(traits) => { result.extend(traits); true"} {"_id":"doc-en-rust-ff4c4961f90f9ede2604b1e03a1a640b056b00519a7c57d87a4e59071c5e1bb1","title":"","text":" // compile-pass #![deny(unused)] #[derive()] //~ WARNING empty trait list in `derive` struct Bar; #[derive()] //~ ERROR unused attribute struct _Bar; pub fn main() {}"} {"_id":"doc-en-rust-8483b7ca7bfacacadfe5611c6b8f0b5ec642263cdf8381fbadd80c47dc249fa5","title":"","text":" warning: empty trait list in `derive` error: unused attribute --> $DIR/deriving-meta-empty-trait-list.rs:3:1 | LL | #[derive()] | ^^^^^^^^^^^ | note: lint level defined here --> $DIR/deriving-meta-empty-trait-list.rs:1:9 | LL | #![deny(unused)] | ^^^^^^ = note: #[deny(unused_attributes)] implied by #[deny(unused)] error: aborting due to previous error "} {"_id":"doc-en-rust-1848e1e7afe437f78b18aff5165f39a3a77e6a781c23e7abdcdb9d55605dc510","title":"","text":"#[derive(Copy=\"bad\")] //~ ERROR expected one of `)`, `,`, or `::`, found `=` struct Test2; #[derive()] //~ WARNING empty trait list struct Test3; #[derive] //~ ERROR malformed `derive` attribute input struct Test4;"} {"_id":"doc-en-rust-5b2a5b41e6f8e84913ace0fafeb8d838d49e837f1b1294ba0f4d507c7b97995d","title":"","text":"LL | #[derive(Copy=\"bad\")] | ^ expected one of `)`, `,`, or `::` here warning: empty trait list in `derive` --> $DIR/malformed-derive-entry.rs:7:1 | LL | #[derive()] | ^^^^^^^^^^^ error: malformed `derive` attribute input --> $DIR/malformed-derive-entry.rs:10:1 --> $DIR/malformed-derive-entry.rs:7:1 | LL | #[derive] | ^^^^^^^^^ help: missing traits to be derived: `#[derive(Trait1, Trait2, ...)]`"} {"_id":"doc-en-rust-6be86a4b17407b66591be990ebb5061a521c69a6a117335881d19c20e8b0685b","title":"","text":"/// An atomic fence. /// /// Depending on the specified order, a fence prevents the compiler and CPU from /// reordering certain types of memory operations around it. /// That creates synchronizes-with relationships between it and atomic operations /// or fences in other threads. /// Fences create synchronization between themselves and atomic operations or fences in other /// threads. To achieve this, a fence prevents the compiler and CPU from reordering certain types of /// memory operations around it. /// /// A fence 'A' which has (at least) [`Release`] ordering semantics, synchronizes /// with a fence 'B' with (at least) [`Acquire`] semantics, if and only if there"} {"_id":"doc-en-rust-97274b5e8277dd4b054060cc97f794d1bdd8dc967f7658c80bfe4ddba57790e0","title":"","text":"/// } /// ``` /// /// Note that in the example above, it is crucial that the accesses to `x` are atomic. Fences cannot /// be used to establish synchronization among non-atomic accesses in different threads. However, /// thanks to the happens-before relationship between A and B, any non-atomic accesses that /// happen-before A are now also properly synchronized with any non-atomic accesses that /// happen-after B. /// /// Atomic operations with [`Release`] or [`Acquire`] semantics can also synchronize /// with a fence. ///"} {"_id":"doc-en-rust-f2ded8438f775bc738785c63a82c3fb960f5d59312583f0db4c45e6e078cd021","title":"","text":"} } /// A compiler memory fence. /// A \"compiler-only\" atomic fence. /// /// `compiler_fence` does not emit any machine code, but restricts the kinds /// of memory re-ordering the compiler is allowed to do. Specifically, depending on /// the given [`Ordering`] semantics, the compiler may be disallowed from moving reads /// or writes from before or after the call to the other side of the call to /// `compiler_fence`. Note that it does **not** prevent the *hardware* /// from doing such re-ordering. This is not a problem in a single-threaded, /// execution context, but when other threads may modify memory at the same /// time, stronger synchronization primitives such as [`fence`] are required. /// Like [`fence`], this function establishes synchronization with other atomic operations and /// fences. However, unlike [`fence`], `compiler_fence` only establishes synchronization with /// operations *in the same thread*. This may at first sound rather useless, since code within a /// thread is typically already totally ordered and does not need any further synchronization. /// However, there are cases where code can run on the same thread without being ordered: /// - The most common case is that of a *signal handler*: a signal handler runs in the same thread /// as the code it interrupted, but it is not ordered with respect to that code. `compiler_fence` /// can be used to establish synchronization between a thread and its signal handler, the same way /// that `fence` can be used to establish synchronization across threads. /// - Similar situations can arise in embedded programming with interrupt handlers, or in custom /// implementations of preemptive green threads. In general, `compiler_fence` can establish /// synchronization with code that is guaranteed to run on the same hardware CPU. /// /// The re-ordering prevented by the different ordering semantics are: /// See [`fence`] for how a fence can be used to achieve synchronization. Note that just like /// [`fence`], synchronization still requires atomic operations to be used in both threads -- it is /// not possible to perform synchronization entirely with fences and non-atomic operations. /// /// - with [`SeqCst`], no re-ordering of reads and writes across this point is allowed. /// - with [`Release`], preceding reads and writes cannot be moved past subsequent writes. /// - with [`Acquire`], subsequent reads and writes cannot be moved ahead of preceding reads. /// - with [`AcqRel`], both of the above rules are enforced. /// `compiler_fence` does not emit any machine code, but restricts the kinds of memory re-ordering /// the compiler is allowed to do. `compiler_fence` corresponds to [`atomic_signal_fence`] in C and /// C++. /// /// `compiler_fence` is generally only useful for preventing a thread from /// racing *with itself*. That is, if a given thread is executing one piece /// of code, and is then interrupted, and starts executing code elsewhere /// (while still in the same thread, and conceptually still on the same /// core). In traditional programs, this can only occur when a signal /// handler is registered. In more low-level code, such situations can also /// arise when handling interrupts, when implementing green threads with /// pre-emption, etc. Curious readers are encouraged to read the Linux kernel's /// discussion of [memory barriers]. /// [`atomic_signal_fence`]: https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence /// /// # Panics ///"} {"_id":"doc-en-rust-e27299259d8c0d9b110a533e632ead76661da767298bdb6195e85e307d9cad45","title":"","text":"/// } /// } /// ``` /// /// [memory barriers]: https://www.kernel.org/doc/Documentation/memory-barriers.txt #[inline] #[stable(feature = \"compiler_fences\", since = \"1.21.0\")] #[rustc_diagnostic_item = \"compiler_fence\"]"} {"_id":"doc-en-rust-12e059053b5009502918c280af5a9d9acc15cc8163b1d6ad059652d6523c87e9","title":"","text":"#![feature(const_transmute)] #![feature(reverse_bits)] #![feature(non_exhaustive)] #![feature(structural_match)] #[prelude_import] #[allow(unused)]"} {"_id":"doc-en-rust-ab132f350e2f8a1fa17eaefe802f367ba0b0d8dba0f1fc038588174fbbad910d","title":"","text":"/// /// [drop check]: ../../nomicon/dropck.html #[lang = \"phantom_data\"] #[structural_match] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub struct PhantomData;"} {"_id":"doc-en-rust-3fcf1c61841cd6438265c773e8ed21a8e2942c8546ef2d559ccb6e0775ee978a","title":"","text":" // run-pass // This file checks that `PhantomData` is considered structurally matchable. use std::marker::PhantomData; fn main() { let mut count = 0; // A type which is not structurally matchable: struct NotSM; // And one that is: #[derive(PartialEq, Eq)] struct SM; // Check that SM is #[structural_match]: const CSM: SM = SM; match SM { CSM => count += 1, }; // Check that PhantomData is #[structural_match] even if T is not. const CPD1: PhantomData = PhantomData; match PhantomData { CPD1 => count += 1, }; // Check that PhantomData is #[structural_match] when T is. const CPD2: PhantomData = PhantomData; match PhantomData { CPD2 => count += 1, }; // Check that a type which has a PhantomData is `#[structural_match]`. #[derive(PartialEq, Eq, Default)] struct Foo { alpha: PhantomData, beta: PhantomData, } const CFOO: Foo = Foo { alpha: PhantomData, beta: PhantomData, }; match Foo::default() { CFOO => count += 1, }; // Final count must be 4 now if all assert_eq!(count, 4); } "} {"_id":"doc-en-rust-a4ac48e9ae704c33e4aad05f47c61ab97cea2d56aef5d94da5fc389456104691","title":"","text":"return false; } function usableLocalStorage() { // Check if the browser supports localStorage at all: if (typeof(Storage) === \"undefined\") { return false; } // Check if we can access it; this access will fail if the browser // preferences deny access to localStorage, e.g., to prevent storage of // \"cookies\" (or cookie-likes, as is the case here). try { window.localStorage; } catch(err) { // Storage is supported, but browser preferences deny access to it. return false; } return true; } function updateLocalStorage(name, value) { if (typeof(Storage) !== \"undefined\") { if (usableLocalStorage()) { localStorage[name] = value; } else { // No Web Storage support so we do nothing"} {"_id":"doc-en-rust-b16cad38b400ffbc9ab4fae63c3573b922ea6efea0aa18c0a58489cede765b84","title":"","text":"} function getCurrentValue(name) { if (typeof(Storage) !== \"undefined\" && localStorage[name] !== undefined) { if (usableLocalStorage() && localStorage[name] !== undefined) { return localStorage[name]; } return null;"} {"_id":"doc-en-rust-57cab936b516ca5b41ac32c9ed7195e3df266e7c99af343b379f8ca24312ec76","title":"","text":"if self.alloc_map.contains_key(&alloc) { // Not yet interned, so proceed recursively self.intern_static(alloc, mutability)?; } else if self.dead_alloc_map.contains_key(&alloc) { // dangling pointer return err!(ValidationFailure( \"encountered dangling pointer in final constant\".into(), )) } } Ok(())"} {"_id":"doc-en-rust-936292c88968680d8a96ec04b02cdda61ecf866d36e3f94acff2deb95639c52c","title":"","text":" // https://github.com/rust-lang/rust/issues/55223 #![feature(const_let)] union Foo<'a> { y: &'a (), long_live_the_unit: &'static (), } const FOO: &() = { //~ ERROR any use of this value will cause an error let y = (); unsafe { Foo { y: &y }.long_live_the_unit } }; fn main() {} "} {"_id":"doc-en-rust-b26aa9eed4a12c5a1de38eb4ad1e87d0dc5310eb98bb1a922e30b0788a3b8207","title":"","text":" error: any use of this value will cause an error --> $DIR/dangling-alloc-id-ice.rs:10:1 | LL | / const FOO: &() = { //~ ERROR any use of this value will cause an error LL | | let y = (); LL | | unsafe { Foo { y: &y }.long_live_the_unit } LL | | }; | |__^ type validation failed: encountered dangling pointer in final constant | = note: #[deny(const_err)] on by default error: aborting due to previous error "} {"_id":"doc-en-rust-9346453625005d0aa1cfd1569ec9e738d3b291025fbf01f3acb1aa941f8988f1","title":"","text":" #![feature(const_let)] const FOO: *const u32 = { //~ ERROR any use of this value will cause an error let x = 42; &x }; fn main() { let x = FOO; } "} {"_id":"doc-en-rust-100ae8fdd2b0311d50a0be5587916efa2d3bb089d4720e828144e08c862e9ca1","title":"","text":" error: any use of this value will cause an error --> $DIR/dangling_raw_ptr.rs:3:1 | LL | / const FOO: *const u32 = { //~ ERROR any use of this value will cause an error LL | | let x = 42; LL | | &x LL | | }; | |__^ type validation failed: encountered dangling pointer in final constant | = note: #[deny(const_err)] on by default error: aborting due to previous error "} {"_id":"doc-en-rust-afeac0229c024d09c60d43228f5ca428e5c330076b402c9a5d1719471f2f9425","title":"","text":"intrinsics::unreachable() } /// Save power or switch hyperthreads in a busy-wait spin-loop. /// Signals the processor that it is entering a busy-wait spin-loop. /// /// This function is deliberately more primitive than /// [`std::thread::yield_now`](../../std/thread/fn.yield_now.html) and /// does not directly yield to the system's scheduler. /// In some cases it might be useful to use a combination of both functions. /// Careful benchmarking is advised. /// Upon receiving spin-loop signal the processor can optimize its behavior by, for example, saving /// power or switching hyper-threads. /// /// On some platforms this function may not do anything at all. /// This function is different than [`std::thread::yield_now`] which directly yields to the /// system's scheduler, whereas `spin_loop` only signals the processor that it is entering a /// busy-wait spin-loop without yielding control to the system's scheduler. /// /// Using a busy-wait spin-loop with `spin_loop` is ideally used in situations where a /// contended lock is held by another thread executed on a different CPU and where the waiting /// times are relatively small. Because entering busy-wait spin-loop does not trigger the system's /// scheduler, no overhead for switching threads occurs. However, if the thread holding the /// contended lock is running on the same CPU, the spin-loop is likely to occupy an entire CPU slice /// before switching to the thread that holds the lock. If the contending lock is held by a thread /// on the same CPU or if the waiting times for acquiring the lock are longer, it is often better to /// use [`std::thread::yield_now`]. /// /// **Note**: On platforms that do not support receiving spin-loop hints this function does not /// do anything at all. /// /// [`std::thread::yield_now`]: ../../std/thread/fn.yield_now.html #[inline] #[unstable(feature = \"renamed_spin_loop\", issue = \"55002\")] pub fn spin_loop() {"} {"_id":"doc-en-rust-7d14533da2cddab2a30caa44a6cd65e182da9604c504d79e32def88ad4be3e3f","title":"","text":"use hint::spin_loop; /// Save power or switch hyperthreads in a busy-wait spin-loop. /// Signals the processor that it is entering a busy-wait spin-loop. /// /// This function is deliberately more primitive than /// [`std::thread::yield_now`](../../../std/thread/fn.yield_now.html) and /// does not directly yield to the system's scheduler. /// In some cases it might be useful to use a combination of both functions. /// Careful benchmarking is advised. /// Upon receiving spin-loop signal the processor can optimize its behavior by, for example, saving /// power or switching hyper-threads. /// /// On some platforms this function may not do anything at all. /// This function is different than [`std::thread::yield_now`] which directly yields to the /// system's scheduler, whereas `spin_loop_hint` only signals the processor that it is entering a /// busy-wait spin-loop without yielding control to the system's scheduler. /// /// Using a busy-wait spin-loop with `spin_loop_hint` is ideally used in situations where a /// contended lock is held by another thread executed on a different CPU and where the waiting /// times are relatively small. Because entering busy-wait spin-loop does not trigger the system's /// scheduler, no overhead for switching threads occurs. However, if the thread holding the /// contended lock is running on the same CPU, the spin-loop is likely to occupy an entire CPU slice /// before switching to the thread that holds the lock. If the contending lock is held by a thread /// on the same CPU or if the waiting times for acquiring the lock are longer, it is often better to /// use [`std::thread::yield_now`]. /// /// **Note**: On platforms that do not support receiving spin-loop hints this function does not /// do anything at all. /// /// [`std::thread::yield_now`]: ../../../std/thread/fn.yield_now.html #[inline] #[stable(feature = \"spin_loop_hint\", since = \"1.24.0\")] pub fn spin_loop_hint() {"} {"_id":"doc-en-rust-1cff204ee024d86311e185e27fef27fe28c8e1a83f0bcad40ba64e49c61c2bdc","title":"","text":"self.unclosed_delims.extend(snapshot.unclosed_delims.clone()); } pub fn unclosed_delims(&self) -> &[UnmatchedBrace] { &self.unclosed_delims } /// Create a snapshot of the `Parser`. pub(super) fn create_snapshot_for_diagnostic(&self) -> SnapshotParser<'a> { let mut snapshot = self.clone();"} {"_id":"doc-en-rust-bab0575fdcd2f6ee5b54ddf7e8c7a464951c3c3400dcb61651b68f6e898d4d9d","title":"","text":"use rustc_middle::hir::map::Map; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_parse::maybe_new_parser_from_source_str; use rustc_parse::parser::attr::InnerAttrPolicy; use rustc_session::config::{self, CrateType, ErrorOutputType}; use rustc_session::parse::ParseSess; use rustc_session::{lint, DiagnosticOutput, Session}; use rustc_span::edition::Edition; use rustc_span::source_map::SourceMap;"} {"_id":"doc-en-rust-7a63ff71512b5b6bcb2a09db07a90c8fd066913e5977f8f05661160360d8b01b","title":"","text":"edition: Edition, test_id: Option<&str>, ) -> (String, usize, bool) { let (crate_attrs, everything_else, crates) = partition_source(s); let (crate_attrs, everything_else, crates) = partition_source(s, edition); let everything_else = everything_else.trim(); let mut line_offset = 0; let mut prog = String::new();"} {"_id":"doc-en-rust-1fadbbb7f740fe6904a6c06be595309aa753d4674888bc38278d8edcb13354db","title":"","text":"rustc_span::create_session_if_not_set_then(edition, |_| { use rustc_errors::emitter::{Emitter, EmitterWriter}; use rustc_errors::Handler; use rustc_parse::maybe_new_parser_from_source_str; use rustc_parse::parser::ForceCollect; use rustc_session::parse::ParseSess; use rustc_span::source_map::FilePathMapping; let filename = FileName::anon_source_code(s);"} {"_id":"doc-en-rust-b608f387d3a29e9464fad8d4b426a3281abee8ba7efa04da6e0250542a6d0713","title":"","text":"(prog, line_offset, supports_color) } // FIXME(aburka): use a real parser to deal with multiline attributes fn partition_source(s: &str) -> (String, String, String) { fn check_if_attr_is_complete(source: &str, edition: Edition) -> bool { if source.is_empty() { // Empty content so nothing to check in here... return true; } rustc_span::create_session_if_not_set_then(edition, |_| { let filename = FileName::anon_source_code(source); let sess = ParseSess::with_silent_emitter(None); let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source.to_owned()) { Ok(p) => p, Err(_) => { debug!(\"Cannot build a parser to check mod attr so skipping...\"); return true; } }; // If a parsing error happened, it's very likely that the attribute is incomplete. if !parser.parse_attribute(InnerAttrPolicy::Permitted).is_ok() { return false; } // We now check if there is an unclosed delimiter for the attribute. To do so, we look at // the `unclosed_delims` and see if the opening square bracket was closed. parser .unclosed_delims() .get(0) .map(|unclosed| { unclosed.unclosed_span.map(|s| s.lo()).unwrap_or(BytePos(0)) != BytePos(2) }) .unwrap_or(true) }) } fn partition_source(s: &str, edition: Edition) -> (String, String, String) { #[derive(Copy, Clone, PartialEq)] enum PartitionState { Attrs,"} {"_id":"doc-en-rust-89ce9b77d1c626a8bdee7e85c92d3d185d26e4173dd8009a175240d12718c84f","title":"","text":"let mut crates = String::new(); let mut after = String::new(); let mut mod_attr_pending = String::new(); for line in s.lines() { let trimline = line.trim();"} {"_id":"doc-en-rust-e8b10fba0bf3ce71442463ee4e1ea706bfc2486713b7aee2fb1055159893e3ec","title":"","text":"// shunted into \"everything else\" match state { PartitionState::Attrs => { state = if trimline.starts_with(\"#![\") || trimline.chars().all(|c| c.is_whitespace()) state = if trimline.starts_with(\"#![\") { if !check_if_attr_is_complete(line, edition) { mod_attr_pending = line.to_owned(); } else { mod_attr_pending.clear(); } PartitionState::Attrs } else if trimline.chars().all(|c| c.is_whitespace()) || (trimline.starts_with(\"//\") && !trimline.starts_with(\"///\")) { PartitionState::Attrs"} {"_id":"doc-en-rust-84b1d62e4e2906a4846aa571951139728bc41eec8ee9e2f97e2dff747710b06b","title":"","text":"{ PartitionState::Crates } else { PartitionState::Other // First we check if the previous attribute was \"complete\"... if !mod_attr_pending.is_empty() { // If not, then we append the new line into the pending attribute to check // if this time it's complete... mod_attr_pending.push_str(line); if !trimline.is_empty() && check_if_attr_is_complete(line, edition) { // If it's complete, then we can clear the pending content. mod_attr_pending.clear(); } // In any case, this is considered as `PartitionState::Attrs` so it's // prepended before rustdoc's inserts. PartitionState::Attrs } else { PartitionState::Other } }; } PartitionState::Crates => {"} {"_id":"doc-en-rust-d0544d36ebafca414b763b7a31d293c2ba326ca6df4db81fb9c840b47e33ac04","title":"","text":" // compile-flags:--test // normalize-stdout-test: \"src/test/rustdoc-ui\" -> \"$$DIR\" // normalize-stdout-test \"finished in d+.d+s\" -> \"finished in $$TIME\" // check-pass /// ``` /// # #![cfg_attr(not(dox), deny(missing_abi, /// # non_ascii_idents))] /// /// pub struct Bar; /// ``` pub struct Bar; "} {"_id":"doc-en-rust-140e61bf4b286a1444dd2ee17651cb20bf05ee799147805ee5099ed325034323","title":"","text":" running 1 test test $DIR/doc-comment-multi-line-cfg-attr.rs - Bar (line 6) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME "} {"_id":"doc-en-rust-44a90984de736df9a4c14cd90592e41e21577c4dec40c2cc66ea6dc3eb4fab39","title":"","text":" Subproject commit 5d967343acae16fd7b53a61e6cd4e93a1ac6f199 Subproject commit 569507ef2beefcce4b666af41e09276f06445e96 "} {"_id":"doc-en-rust-5163ea1321219f56eab1bec8a61eef05960487c410618220785dfa1c9c9ec723","title":"","text":"/// kept separate because of issue #42760. #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum DocFragment { // FIXME #44229 (misdreavus): sugared and raw doc comments can be brought back together once // hoedown is completely removed from rustdoc. /// A doc fragment created from a `///` or `//!` doc comment. SugaredDoc(usize, syntax_pos::Span, String), /// A doc fragment created from a \"raw\" `#[doc=\"\"]` attribute."} {"_id":"doc-en-rust-2f1bbe5b7e2ed3e9e1a845498decf01cddf7f6b9a2bfb43b156e4fa6ed129319","title":"","text":"start.to(end) } /// Reports a resolution failure diagnostic. /// /// Ideally we can report the diagnostic with the actual span in the source where the link failure /// occurred. However, there's a mismatch between the span in the source code and the span in the /// markdown, so we have to do a bit of work to figure out the correspondence. /// /// It's not too hard to find the span for sugared doc comments (`///` and `/**`), because the /// source will match the markdown exactly, excluding the comment markers. However, it's much more /// difficult to calculate the spans for unsugared docs, because we have to deal with escaping and /// other source features. So, we attempt to find the exact source span of the resolution failure /// in sugared docs, but use the span of the documentation attributes themselves for unsugared /// docs. Because this span might be overly large, we display the markdown line containing the /// failure as a note. fn resolution_failure( cx: &DocContext, attrs: &Attributes,"} {"_id":"doc-en-rust-c01781df398f704eae83e7aa64917894a174256b9b207453ddfd127e2f26ecd0","title":"","text":"let sp = span_of_attrs(attrs); let msg = format!(\"`[{}]` cannot be resolved, ignoring it...\", path_str); let code_dox = sp.to_src(cx); let doc_comment_padding = 3; let mut diag = if let Some(link_range) = link_range { // blah blah blahnblahnblah [blah] blah blahnblah blah // ^ ~~~~~~ // | link_range // last_new_line_offset let mut diag; if dox.lines().count() == code_dox.lines().count() { let line_offset = dox[..link_range.start].lines().count(); // The span starts in the `///`, so we don't have to account for the leading whitespace. let code_dox_len = if line_offset <= 1 { doc_comment_padding } else { // The first `///`. doc_comment_padding + // Each subsequent leading whitespace and `///`. code_dox.lines().skip(1).take(line_offset - 1).fold(0, |sum, line| { sum + doc_comment_padding + line.len() - line.trim_start().len() }) }; let src = cx.sess().source_map().span_to_snippet(sp); let is_all_sugared_doc = attrs.doc_strings.iter().all(|frag| match frag { DocFragment::SugaredDoc(..) => true, _ => false, }); if let (Ok(src), true) = (src, is_all_sugared_doc) { // The number of markdown lines up to and including the resolution failure. let num_lines = dox[..link_range.start].lines().count(); // We use `split_terminator('n')` instead of `lines()` when counting bytes to ensure // that DOS-style line endings do not cause the spans to be calculated incorrectly. let mut src_lines = src.split_terminator('n'); let mut md_lines = dox.split_terminator('n').take(num_lines).peekable(); // The number of bytes from the start of the source span to the resolution failure that // are *not* part of the markdown, like comment markers. let mut extra_src_bytes = 0; while let Some(md_line) = md_lines.next() { loop { let source_line = src_lines .next() .expect(\"could not find markdown line in source\"); match source_line.find(md_line) { Some(offset) => { extra_src_bytes += if md_lines.peek().is_some() { source_line.len() - md_line.len() } else { offset }; break; } None => { // Since this is a source line that doesn't include a markdown line, // we have to count the newline that we split from earlier. extra_src_bytes += source_line.len() + 1; } } } } // Extract the specific span. let sp = sp.from_inner_byte_pos( link_range.start + code_dox_len, link_range.end + code_dox_len, link_range.start + extra_src_bytes, link_range.end + extra_src_bytes, ); diag = cx.tcx.struct_span_lint_node(lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE, NodeId::from_u32(0), sp, &msg); let mut diag = cx.tcx.struct_span_lint_node( lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE, NodeId::from_u32(0), sp, &msg, ); diag.span_label(sp, \"cannot be resolved, ignoring\"); diag } else { diag = cx.tcx.struct_span_lint_node(lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE, NodeId::from_u32(0), sp, &msg); let mut diag = cx.tcx.struct_span_lint_node( lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE, NodeId::from_u32(0), sp, &msg, ); // blah blah blahnblahnblah [blah] blah blahnblah blah // ^ ~~~~ // | link_range // last_new_line_offset let last_new_line_offset = dox[..link_range.start].rfind('n').map_or(0, |n| n + 1); let line = dox[last_new_line_offset..].lines().next().unwrap_or(\"\");"} {"_id":"doc-en-rust-5ba1a8e4926ec55d579d926094d671c9fabe4edd3a4393a6911dc411e9545ade","title":"","text":"before=link_range.start - last_new_line_offset, found=link_range.len(), )); diag } diag } else { cx.tcx.struct_span_lint_node(lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE, NodeId::from_u32(0),"} {"_id":"doc-en-rust-c76b77689b2777473f4dfe86e5014afb8c297b5ad21ef5cee971ab162d27b7f3","title":"","text":" intra-links-warning-crlf.rs eol=crlf "} {"_id":"doc-en-rust-7530d342f35e83ba5a192c93d49e19170458f5715257a01eedd1bac23044efaf","title":"","text":" // ignore-tidy-cr // compile-pass // This file checks the spans of intra-link warnings in a file with CRLF line endings. The // .gitattributes file in this directory should enforce it. /// [error] pub struct A; /// /// docs [error1] /// docs [error2] /// pub struct B; /** * This is a multi-line comment. * * It also has an [error]. */ pub struct C; "} {"_id":"doc-en-rust-a9520eb8dfcb0320cbcfc9dcb9b80eb899916be2c2b0d8c8e20cccaa1c2b3a7b","title":"","text":" warning: `[error]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning-crlf.rs:8:6 | LL | /// [error] | ^^^^^ cannot be resolved, ignoring | = note: #[warn(intra_doc_link_resolution_failure)] on by default = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error1]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning-crlf.rs:12:11 | LL | /// docs [error1] | ^^^^^^ cannot be resolved, ignoring | = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error2]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning-crlf.rs:14:11 | LL | /// docs [error2] | ^^^^^^ cannot be resolved, ignoring | = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning-crlf.rs:21:20 | LL | * It also has an [error]. | ^^^^^ cannot be resolved, ignoring | = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` "} {"_id":"doc-en-rust-5e2b6bad927a12ab4dbf470639d1e70eb5e517f9325eb9f3e18b619c51f43a49","title":"","text":"} } f!(\"Foonbar [BarF] barnbaz\"); /** # for example, * * time to introduce a link [error]*/ pub struct A; /** * # for example, * * time to introduce a link [error] */ pub struct B; #[doc = \"single line [error]\"] pub struct C; #[doc = \"single line with \"escaping\" [error]\"] pub struct D; /// Item docs. #[doc=\"Hello there!\"] /// [error] pub struct E; /// /// docs [error1] /// docs [error2] /// pub struct F; "} {"_id":"doc-en-rust-c7ea45eaf0e5d3b5d1fbd52959cb353dd4f3ee6944c711697aa6da44a4b759f6","title":"","text":"| = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:61:30 | LL | * time to introduce a link [error]*/ | ^^^^^ cannot be resolved, ignoring | = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:67:30 | LL | * time to introduce a link [error] | ^^^^^ cannot be resolved, ignoring | = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:71:1 | LL | #[doc = \"single line [error]\"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the link appears in this line: single line [error] ^^^^^ = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:74:1 | LL | #[doc = \"single line with /\"escaping/\" [error]\"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the link appears in this line: single line with \"escaping\" [error] ^^^^^ = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:77:1 | LL | / /// Item docs. LL | | #[doc=\"Hello there!\"] LL | | /// [error] | |___________^ | = note: the link appears in this line: [error] ^^^^^ = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error1]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:83:11 | LL | /// docs [error1] | ^^^^^^ cannot be resolved, ignoring | = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[error2]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:85:11 | LL | /// docs [error2] | ^^^^^^ cannot be resolved, ignoring | = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[BarA]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:24:10 |"} {"_id":"doc-en-rust-f20ef48b16ccc4ec1fbb14b6f4f6ff2fe760eefdb32bc6dff23eeb36c9dd74cc","title":"","text":"= help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[BarB]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:28:1 --> $DIR/intra-links-warning.rs:30:9 | LL | / /** LL | | * Foo LL | | * bar [BarB] bar LL | | * baz LL | | */ | |___^ LL | * bar [BarB] bar | ^^^^ cannot be resolved, ignoring | = note: the link appears in this line: bar [BarB] bar ^^^^ = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[BarC]` cannot be resolved, ignoring it... --> $DIR/intra-links-warning.rs:35:1 --> $DIR/intra-links-warning.rs:37:6 | LL | / /** Foo LL | | LL | | bar [BarC] bar LL | | baz ... | LL | | LL | | */ | |__^ LL | bar [BarC] bar | ^^^^ cannot be resolved, ignoring | = note: the link appears in this line: bar [BarC] bar ^^^^ = help: to escape `[` and `]` characters, just add '/' before them like `/[` or `/]` warning: `[BarD]` cannot be resolved, ignoring it..."} {"_id":"doc-en-rust-417c296d822bd2c6871de073c16e2a23bc9664f7535d7b87773239b3d574a3e8","title":"","text":"); // See https://github.com/rust-lang/rust/issues/32354 if old_binding.is_import() || new_binding.is_import() { let binding = if new_binding.is_import() && !new_binding.span.is_dummy() { new_binding let directive = match (&new_binding.kind, &old_binding.kind) { (NameBindingKind::Import { directive, .. }, _) if !new_binding.span.is_dummy() => Some((directive, new_binding.span)), (_, NameBindingKind::Import { directive, .. }) if !old_binding.span.is_dummy() => Some((directive, old_binding.span)), _ => None, }; if let Some((directive, binding_span)) = directive { let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() { format!(\"Other{}\", name) } else { old_binding format!(\"other_{}\", name) }; let cm = self.session.source_map(); let rename_msg = \"you can use `as` to change the binding name of the import\"; if let ( Ok(snippet), NameBindingKind::Import { directive, ..}, _dummy @ false, ) = ( cm.span_to_snippet(binding.span), binding.kind.clone(), binding.span.is_dummy(), ) { let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() { format!(\"Other{}\", name) } else { format!(\"other_{}\", name) }; let mut suggestion = None; match directive.subclass { ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } => suggestion = Some(format!(\"self as {}\", suggested_name)), ImportDirectiveSubclass::SingleImport { source, .. } => { if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0) .map(|pos| pos as usize) { if let Ok(snippet) = self.session.source_map() .span_to_snippet(binding_span) { if pos <= snippet.len() { suggestion = Some(format!( \"{} as {}{}\", &snippet[..pos], suggested_name, if snippet.ends_with(\";\") { \";\" } else { \"\" } )) } } } } ImportDirectiveSubclass::ExternCrate { source, target, .. } => suggestion = Some(format!( \"extern crate {} as {};\", source.unwrap_or(target.name), suggested_name, )), _ => unreachable!(), } let rename_msg = \"you can use `as` to change the binding name of the import\"; if let Some(suggestion) = suggestion { err.span_suggestion_with_applicability( binding.span, &rename_msg, match directive.subclass { ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } => format!(\"self as {}\", suggested_name), ImportDirectiveSubclass::SingleImport { source, .. } => format!( \"{} as {}{}\", &snippet[..((source.span.hi().0 - binding.span.lo().0) as usize)], suggested_name, if snippet.ends_with(\";\") { \";\" } else { \"\" } ), ImportDirectiveSubclass::ExternCrate { source, target, .. } => format!( \"extern crate {} as {};\", source.unwrap_or(target.name), suggested_name, ), _ => unreachable!(), }, binding_span, rename_msg, suggestion, Applicability::MaybeIncorrect, ); } else { err.span_label(binding.span, rename_msg); err.span_label(binding_span, rename_msg); } }"} {"_id":"doc-en-rust-45ac3499486ef2d242869fb5e78948853d44070866d33c3865bdeb88356d4433","title":"","text":" macro_rules! import { ( $($name:ident),* ) => { $( mod $name; pub use self::$name; //~^ ERROR the name `issue_56411_aux` is defined multiple times //~| ERROR `issue_56411_aux` is private, and cannot be re-exported )* } } import!(issue_56411_aux); fn main() { println!(\"Hello, world!\"); } "} {"_id":"doc-en-rust-a300f928e46834fcc9121fd73d702311f56ca366382d8b716208a1689f9d8da9","title":"","text":" error[E0255]: the name `issue_56411_aux` is defined multiple times --> $DIR/issue-56411.rs:5:21 | LL | mod $name; | ---------- previous definition of the module `issue_56411_aux` here LL | pub use self::$name; | ^^^^^^^^^^^ | | | `issue_56411_aux` reimported here | you can use `as` to change the binding name of the import ... LL | import!(issue_56411_aux); | ------------------------- in this macro invocation | = note: `issue_56411_aux` must be defined only once in the type namespace of this module error[E0365]: `issue_56411_aux` is private, and cannot be re-exported --> $DIR/issue-56411.rs:5:21 | LL | pub use self::$name; | ^^^^^^^^^^^ re-export of private `issue_56411_aux` ... LL | import!(issue_56411_aux); | ------------------------- in this macro invocation | = note: consider declaring type or module `issue_56411_aux` with `pub` error: aborting due to 2 previous errors Some errors occurred: E0255, E0365. For more information about an error, try `rustc --explain E0255`. "} {"_id":"doc-en-rust-8402525181334ba8a9b4780c456a829706ad66ec1bf7966f3e9203a2875fd156","title":"","text":" // compile-pass struct T {} fn main() {} "} {"_id":"doc-en-rust-6bbe88ee1c98cc4803c649758b2d0fd84ed96d36ebe00b0234971df44ad9466f","title":"","text":"#![feature(cfg_target_vendor)] #![feature(char_error_internals)] #![feature(compiler_builtins_lib)] #![feature(concat_idents)] #![feature(const_int_ops)] #![feature(const_ip)] #![feature(const_raw_ptr_deref)]"} {"_id":"doc-en-rust-f5d6fb4c7bebee0d86741f8ad29b06f5ae95406cf9aeea57a7c3c681d1eaedfb","title":"","text":"// Linux. This was added in 2.6.28, however, and because we support // 2.6.18 we must detect this support dynamically. if cfg!(target_os = \"linux\") { weak! { fn accept4(c_int, *mut sockaddr, *mut socklen_t, c_int) -> c_int syscall! { fn accept4( fd: c_int, addr: *mut sockaddr, addr_len: *mut socklen_t, flags: c_int ) -> c_int } if let Some(accept) = accept4.get() { let res = cvt_r(|| unsafe { accept(self.0.raw(), storage, len, SOCK_CLOEXEC) }); match res { Ok(fd) => return Ok(Socket(FileDesc::new(fd))), Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {} Err(e) => return Err(e), } let res = cvt_r(|| unsafe { accept4(self.0.raw(), storage, len, SOCK_CLOEXEC) }); match res { Ok(fd) => return Ok(Socket(FileDesc::new(fd))), Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {} Err(e) => return Err(e), } }"} {"_id":"doc-en-rust-0447182588c4b59524203b3f99b40e15903d0a71d9674d22ca847668f2a6f61b","title":"","text":"} /// Sets the platform-specific value of errno #[cfg(any(target_os = \"solaris\", target_os = \"fuchsia\"))] // only needed for readdir so far #[cfg(all(not(target_os = \"linux\"), not(target_os = \"dragonfly\")))] // needed for readdir and syscall! pub fn set_errno(e: i32) { unsafe { *errno_location() = e as c_int"} {"_id":"doc-en-rust-11df368193c81abda00c8f5c61c8f8c07f33fe4bdca68e276313731c92903730","title":"","text":"unsafe { errno as i32 } } #[cfg(target_os = \"dragonfly\")] pub fn set_errno(e: i32) { extern { #[thread_local] static mut errno: c_int; } unsafe { errno = e; } } /// Gets a detailed string description for the given error number. pub fn error_string(errno: i32) -> String { extern {"} {"_id":"doc-en-rust-ebabb78388484b16e503484022b780cb77654c4c3451c71e053072a486ddf9d2","title":"","text":"pub struct AnonPipe(FileDesc); pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { weak! { fn pipe2(*mut c_int, c_int) -> c_int } syscall! { fn pipe2(fds: *mut c_int, flags: c_int) -> c_int } static INVALID: AtomicBool = ATOMIC_BOOL_INIT; let mut fds = [0; 2];"} {"_id":"doc-en-rust-420fcd87e791df77b05dc8ca52ec4f0bf60ecbad1e465c2403f2c320d4ffc314","title":"","text":"!INVALID.load(Ordering::SeqCst) { if let Some(pipe) = pipe2.get() { // Note that despite calling a glibc function here we may still // get ENOSYS. Glibc has `pipe2` since 2.9 and doesn't try to // emulate on older kernels, so if you happen to be running on // an older kernel you may see `pipe2` as a symbol but still not // see the syscall. match cvt(unsafe { pipe(fds.as_mut_ptr(), libc::O_CLOEXEC) }) { Ok(_) => { return Ok((AnonPipe(FileDesc::new(fds[0])), AnonPipe(FileDesc::new(fds[1])))); } Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => { INVALID.store(true, Ordering::SeqCst); } Err(e) => return Err(e), // Note that despite calling a glibc function here we may still // get ENOSYS. Glibc has `pipe2` since 2.9 and doesn't try to // emulate on older kernels, so if you happen to be running on // an older kernel you may see `pipe2` as a symbol but still not // see the syscall. match cvt(unsafe { pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }) { Ok(_) => { return Ok((AnonPipe(FileDesc::new(fds[0])), AnonPipe(FileDesc::new(fds[1])))); } Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => { INVALID.store(true, Ordering::SeqCst); } Err(e) => return Err(e), } } cvt(unsafe { libc::pipe(fds.as_mut_ptr()) })?;"} {"_id":"doc-en-rust-2ffab8b9dffc66f3ae40594c85a9aea7c6e48e05a58c05d276368f11b0be98f4","title":"","text":"}; libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize } #[cfg(not(target_os = \"linux\"))] macro_rules! syscall { (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => ( unsafe fn $name($($arg_name: $t),*) -> $ret { use libc; use super::os; weak! { fn $name($($t),*) -> $ret } if let Some(fun) = $name.get() { fun($($arg_name),*) } else { os::set_errno(libc::ENOSYS); -1 } } ) } #[cfg(target_os = \"linux\")] macro_rules! syscall { (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => ( unsafe fn $name($($arg_name:$t),*) -> $ret { // This looks like a hack, but concat_idents only accepts idents // (not paths). use libc::*; syscall( concat_idents!(SYS_, $name), $($arg_name as c_long),* ) as $ret } ) } "} {"_id":"doc-en-rust-2a20975e18c1629f9d846aa91be29b2c64b6b4fbde26ea73fc60f10843929028","title":"","text":"// Only allow statics (not consts) to refer to other statics. if self.mode == Mode::Static || self.mode == Mode::StaticMut { if context.is_mutating_use() { if self.mode == Mode::Static && context.is_mutating_use() { // this is not strictly necessary as miri will also bail out // For interior mutability we can't really catch this statically as that // goes through raw pointers and intermediate temporaries, so miri has"} {"_id":"doc-en-rust-0db8ec4095176ef2ac320a60ad549c320c77fcdce2f60d44d9bdb3cd95132a62","title":"","text":" // compile-pass static mut STDERR_BUFFER_SPACE: [u8; 42] = [0u8; 42]; pub static mut STDERR_BUFFER: *mut [u8] = unsafe { &mut STDERR_BUFFER_SPACE }; fn main() {} "} {"_id":"doc-en-rust-1ae03cc3fb5754602502b45c6c1f986e22cb9f5502ed0ca183e34eb62ef1cb20","title":"","text":" #![feature(const_let)] static mut STDERR_BUFFER_SPACE: u8 = 0; pub static mut STDERR_BUFFER: () = unsafe { *(&mut STDERR_BUFFER_SPACE) = 42; }; //~^ ERROR references in statics may only refer to immutable values //~| ERROR static contains unimplemented expression type fn main() {} "} {"_id":"doc-en-rust-f88d1f5b6f35869765ff5724c624b4ca0506327e1c3aa77185a89e9fbc64fb28","title":"","text":" error[E0017]: references in statics may only refer to immutable values --> $DIR/static_mut_containing_mut_ref2.rs:5:46 | LL | pub static mut STDERR_BUFFER: () = unsafe { *(&mut STDERR_BUFFER_SPACE) = 42; }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ statics require immutable values error[E0019]: static contains unimplemented expression type --> $DIR/static_mut_containing_mut_ref2.rs:5:45 | LL | pub static mut STDERR_BUFFER: () = unsafe { *(&mut STDERR_BUFFER_SPACE) = 42; }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors Some errors occurred: E0017, E0019. For more information about an error, try `rustc --explain E0017`. "} {"_id":"doc-en-rust-81228d4d10dc43151de6499104cdafae1401c63963af3049ce5ceb72a246e744","title":"","text":" #![feature(const_let)] static mut FOO: (u8, u8) = (42, 43); static mut BAR: () = unsafe { FOO.0 = 99; }; //~^ ERROR could not evaluate static initializer fn main() {} "} {"_id":"doc-en-rust-e4d157d45227ce9505d9866b365cd4bb0cce04e1b53647fb0f059768904892a3","title":"","text":" error[E0080]: could not evaluate static initializer --> $DIR/static_mut_containing_mut_ref3.rs:5:31 | LL | static mut BAR: () = unsafe { FOO.0 = 99; }; | ^^^^^^^^^^ tried to modify a static's initial value from another static's initializer error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-7e08e31e6d8313a5d3cb5201c8b6f18201a40a9431ed558aec8ac77ddfe7d852","title":"","text":"pub static mut A: u32 = 0; pub static mut B: () = unsafe { A = 1; }; //~^ ERROR cannot mutate statics in the initializer of another static //~^ ERROR could not evaluate static initializer pub static mut C: u32 = unsafe { C = 1; 0 }; //~^ ERROR cannot mutate statics in the initializer of another static //~^ ERROR cycle detected pub static D: u32 = D;"} {"_id":"doc-en-rust-02ed54b08ee6371f5eee530fe1b008776521e19500604db0bd23974d7c339053","title":"","text":" error: cannot mutate statics in the initializer of another static error[E0080]: could not evaluate static initializer --> $DIR/write-to-static-mut-in-static.rs:14:33 | LL | pub static mut B: () = unsafe { A = 1; }; | ^^^^^ | ^^^^^ tried to modify a static's initial value from another static's initializer error: cannot mutate statics in the initializer of another static error[E0391]: cycle detected when const-evaluating `C` --> $DIR/write-to-static-mut-in-static.rs:17:34 | LL | pub static mut C: u32 = unsafe { C = 1; 0 }; | ^^^^^ | note: ...which requires const-evaluating `C`... --> $DIR/write-to-static-mut-in-static.rs:17:1 | LL | pub static mut C: u32 = unsafe { C = 1; 0 }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: ...which again requires const-evaluating `C`, completing the cycle note: cycle used when const-evaluating + checking `C` --> $DIR/write-to-static-mut-in-static.rs:17:1 | LL | pub static mut C: u32 = unsafe { C = 1; 0 }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors Some errors occurred: E0080, E0391. For more information about an error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-bcf0ea8dad6df89b275f99c850a81fd54c6c9d67ffab70c9a6b77acba5213fdf","title":"","text":"}, } impl<'tcx> PatternKind<'tcx> { /// If this is a `PatternKind::AscribeUserType` then return the subpattern kind, otherwise /// return this pattern kind. fn with_user_type_ascription_subpattern(self) -> Self { match self { PatternKind::AscribeUserType { subpattern: Pattern { box kind, .. }, .. } => kind, kind => kind, } } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct PatternRange<'tcx> { pub lo: ty::Const<'tcx>,"} {"_id":"doc-en-rust-3b71ebe1ab83f1f0505004a0b8972157560c5f2592c5f8b2f9b3d7a0eb741d78","title":"","text":"PatKind::Lit(ref value) => self.lower_lit(value), PatKind::Range(ref lo_expr, ref hi_expr, end) => { match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) { (PatternKind::Constant { value: lo }, PatternKind::Constant { value: hi }) => { match ( // Look for `PatternKind::Constant` patterns inside of any // `PatternKind::AscribeUserType` patterns. Type ascriptions can be safely // ignored for the purposes of lowering a range correctly - these are checked // elsewhere for well-formedness. self.lower_lit(lo_expr).with_user_type_ascription_subpattern(), self.lower_lit(hi_expr).with_user_type_ascription_subpattern(), ) { (PatternKind::Constant { value: lo }, PatternKind::Constant { value: hi }) => { use std::cmp::Ordering; let cmp = compare_const_vals( self.tcx,"} {"_id":"doc-en-rust-9395e0472cdba15d0938d81ab53f63af728bc354774256d64159a189854ae663","title":"","text":"} } } _ => PatternKind::Wild ref pats => { self.tcx.sess.delay_span_bug( pat.span, &format!(\"found bad range pattern `{:?}` outside of error recovery\", pats), ); PatternKind::Wild } } }"} {"_id":"doc-en-rust-3c0be0e4374b3b6d0b3ab39b50f36d4c9f61625d1a3827586e3bd36aae3f10a8","title":"","text":" // run-pass #![allow(dead_code)] trait Range { const FIRST: u8; const LAST: u8; } struct OneDigit; impl Range for OneDigit { const FIRST: u8 = 0; const LAST: u8 = 9; } struct TwoDigits; impl Range for TwoDigits { const FIRST: u8 = 10; const LAST: u8 = 99; } struct ThreeDigits; impl Range for ThreeDigits { const FIRST: u8 = 100; const LAST: u8 = 255; } fn digits(x: u8) -> u32 { match x { OneDigit::FIRST...OneDigit::LAST => 1, TwoDigits::FIRST...TwoDigits::LAST => 2, ThreeDigits::FIRST...ThreeDigits::LAST => 3, _ => unreachable!(), } } fn main() { assert_eq!(digits(100), 3); } "} {"_id":"doc-en-rust-a9ddc051244b04e1de2e10f3c27615f00e7dbef410b4c157fdc2a60e7003641f","title":"","text":"/// // The heap should now be empty. /// assert!(heap.is_empty()) /// ``` /// /// ## Min-heap /// /// Either `std::cmp::Reverse` or a custom `Ord` implementation can be used to /// make `BinaryHeap` a min-heap. This makes `heap.pop()` return the smallest /// value instead of the greatest one. /// /// ``` /// use std::collections::BinaryHeap; /// use std::cmp::Reverse; /// /// let mut heap = BinaryHeap::new(); /// /// // Wrap values in `Reverse` /// heap.push(Reverse(1)); /// heap.push(Reverse(5)); /// heap.push(Reverse(2)); /// /// // If we pop these scores now, they should come back in the reverse order. /// assert_eq!(heap.pop(), Some(Reverse(1))); /// assert_eq!(heap.pop(), Some(Reverse(2))); /// assert_eq!(heap.pop(), Some(Reverse(5))); /// assert_eq!(heap.pop(), None); /// ``` #[stable(feature = \"rust1\", since = \"1.0.0\")] pub struct BinaryHeap { data: Vec,"} {"_id":"doc-en-rust-46719821122b85a78f7448084df56ecd160704f5bf89f1539a55a2a5722c50f9","title":"","text":"// Once we're done with llvm 14 and earlier, this test can be deleted. #![crate_type=\"lib\"] #![crate_type = \"lib\"] use std::mem::MaybeUninit;"} {"_id":"doc-en-rust-34c1a30035a567b06342242ed6305a19e6f7ad8fe766c3e33e3f24db64428f03","title":"","text":"Box::new(MaybeUninit::uninit()) } // FIXME: add a test for a bigger box. Currently broken, see // https://github.com/rust-lang/rust/issues/58201. // https://github.com/rust-lang/rust/issues/58201 #[no_mangle] pub fn box_uninitialized2() -> Box> { // CHECK-LABEL: @box_uninitialized2 // CHECK-NOT: store // CHECK-NOT: alloca // CHECK-NOT: memcpy // CHECK-NOT: memset Box::new(MaybeUninit::uninit()) } // Hide the LLVM 15+ `allocalign` attribute in the declaration of __rust_alloc // from the CHECK-NOT above. We don't check the attributes here because we can't rely"} {"_id":"doc-en-rust-a95916736b6952835bc751d521231c339e1fa221b89acc9e5a687e459b5e4370","title":"","text":"// compile-flags: -O // min-llvm-version: 15.0 #![crate_type=\"lib\"] #![crate_type = \"lib\"] use std::mem::MaybeUninit;"} {"_id":"doc-en-rust-17c781cacd66802b6112c5021f0409d0d7ff700eee6d076b1be18bfe870f8f80","title":"","text":"Box::new(MaybeUninit::uninit()) } // FIXME: add a test for a bigger box. Currently broken, see // https://github.com/rust-lang/rust/issues/58201. // https://github.com/rust-lang/rust/issues/58201 #[no_mangle] pub fn box_uninitialized2() -> Box> { // CHECK-LABEL: @box_uninitialized2 // CHECK-NOT: store // CHECK-NOT: alloca // CHECK-NOT: memcpy // CHECK-NOT: memset Box::new(MaybeUninit::uninit()) } // Hide the `allocalign` attribute in the declaration of __rust_alloc // from the CHECK-NOT above, and also verify the attributes got set reasonably."} {"_id":"doc-en-rust-eb8537199e86fd15db83b606788a4463a97f88a891cb211ce1a263f081d6b93b","title":"","text":" // build-fail // ignore-emscripten no asm! support // Regression test for #69092 #![feature(asm)] fn main() { unsafe { asm!(\".ascii \"Xen0\"\"); } //~^ ERROR: :1:9: error: expected string in '.ascii' directive } "} {"_id":"doc-en-rust-b312fb5fbcabc116341c0eb451cb666a21a1213067b094113c5a1e358a9566c3","title":"","text":" error: :1:9: error: expected string in '.ascii' directive .ascii \"Xen ^ --> $DIR/issue-69092.rs:8:14 | LL | unsafe { asm!(\".ascii \"Xen0\"\"); } | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-f6e1cc6cd076cf5f657aed4234435dcec8ad572b8d2a3e77152a05c321a2337a","title":"","text":" // Regression test for #62504 #![feature(const_generics)] #![allow(incomplete_features)] trait HasSize { const SIZE: usize; } impl HasSize for ArrayHolder<{ X }> { const SIZE: usize = X; } struct ArrayHolder([u32; X]); impl ArrayHolder<{ X }> { pub const fn new() -> Self { ArrayHolder([0; Self::SIZE]) //~^ ERROR: array lengths can't depend on generic parameters } } fn main() { let mut array = ArrayHolder::new(); } "} {"_id":"doc-en-rust-251cb73962cf89e954c46f5871748e0bec44587bf7afef3bd80271a7f653b3f2","title":"","text":" error: array lengths can't depend on generic parameters --> $DIR/issue-62504.rs:18:25 | LL | ArrayHolder([0; Self::SIZE]) | ^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-63e9f18f2c19a511ba3defe55cbd8d0c62aa06a7e8ce3f0c5adff426793a0b12","title":"","text":" // Regression test for #67739 #![allow(incomplete_features)] #![feature(const_generics)] use std::mem; pub trait Trait { type Associated: Sized; fn associated_size(&self) -> usize { [0u8; mem::size_of::()]; //~^ ERROR: array lengths can't depend on generic parameters 0 } } fn main() {} "} {"_id":"doc-en-rust-a0203dc112bbcf8431e383d73afd67575380a0fc96d0f5d4f28c7246e728a703","title":"","text":" error: array lengths can't depend on generic parameters --> $DIR/issue-67739.rs:12:15 | LL | [0u8; mem::size_of::()]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-11f1a57cd3b7553296f04e4c13d546c2dbec5dd01188754484858f68641ab32a","title":"","text":" // Regression test for #58490 macro_rules! a { ( @1 $i:item ) => { a! { @2 $i } }; ( @2 $i:item ) => { $i }; } mod b { a! { @1 #[macro_export] macro_rules! b { () => () } } #[macro_export] macro_rules! b { () => () } //~^ ERROR: the name `b` is defined multiple times } mod c { #[allow(unused_imports)] use crate::b; } fn main() {} "} {"_id":"doc-en-rust-b61634794cdad9d38e65ba500b4ae8322b9f59627f58b23d5e85624c06c292f3","title":"","text":" error[E0428]: the name `b` is defined multiple times --> $DIR/issue-58490.rs:18:5 | LL | macro_rules! b { () => () } | -------------- previous definition of the macro `b` here ... LL | macro_rules! b { () => () } | ^^^^^^^^^^^^^^ `b` redefined here | = note: `b` must be defined only once in the macro namespace of this module error: aborting due to previous error For more information about this error, try `rustc --explain E0428`. "} {"_id":"doc-en-rust-47536fb397b2be39b1ab5e6a6b4835ea03329627809d1437a84e8bf7c1eaf494","title":"","text":" // check-pass // compile-flags: --emit=mir,link // Regression test for #60390, this ICE requires `--emit=mir` flag. fn main() { enum Inner { Member(u32) }; Inner::Member(0); } "} {"_id":"doc-en-rust-8c726af1e02bbb67c38ed293b1eebccfdc4026a0c040c0445fab9bea3cec5668","title":"","text":"// Maybe remove `&`? hir::ExprKind::AddrOf(_, ref expr) => { if !cm.span_to_filename(expr.span).is_real() { if let Ok(code) = cm.span_to_snippet(sp) { if code.chars().next() == Some('&') { return Some(( sp, \"consider removing the borrow\", code[1..].to_string()), ); } } return None; } if let Ok(code) = cm.span_to_snippet(expr.span) {"} {"_id":"doc-en-rust-ff6c2935687c89c0140c5c895bacf5f1a729428a2e31fe4eaa37098e1c7cad40","title":"","text":"LL | fn main() { | - expected `()` because of default return type LL | &panic!() | ^^^^^^^^^ expected (), found reference | ^^^^^^^^^ | | | expected (), found reference | help: consider removing the borrow: `panic!()` | = note: expected type `()` found type `&_`"} {"_id":"doc-en-rust-ab59a6f61a573f5ceb1d135e684aa488ad95e525a07dde3681dc1902f015ec13","title":"","text":"error[E0308]: mismatched types --> $DIR/diverging-tuple-parts-39485.rs:8:5 | LL | fn g() { | - help: try adding a return type: `-> &_` LL | &panic!() //~ ERROR mismatched types | ^^^^^^^^^ expected (), found reference | = note: expected type `()` found type `&_` help: try adding a return type | LL | fn g() -> &_ { | ^^^^^ help: consider removing the borrow | LL | panic!() //~ ERROR mismatched types | ^^^^^^^^ error[E0308]: mismatched types --> $DIR/diverging-tuple-parts-39485.rs:12:5"} {"_id":"doc-en-rust-6907558301daf0d8ecc56088b86edb51ce254d00431ea357e3128fabf4a19317","title":"","text":" fn main() { let a: String = &String::from(\"a\"); //~^ ERROR mismatched types let b: String = &format!(\"b\"); //~^ ERROR mismatched types } "} {"_id":"doc-en-rust-2166d2d0880fbdf2344c492f5d52ed537189bef5b2d1dbe236a9ee483bc16cdf","title":"","text":" error[E0308]: mismatched types --> $DIR/format-borrow.rs:2:21 | LL | let a: String = &String::from(\"a\"); | ^^^^^^^^^^^^^^^^^^ | | | expected struct `std::string::String`, found reference | help: consider removing the borrow: `String::from(\"a\")` | = note: expected type `std::string::String` found type `&std::string::String` error[E0308]: mismatched types --> $DIR/format-borrow.rs:4:21 | LL | let b: String = &format!(\"b\"); | ^^^^^^^^^^^^^ | | | expected struct `std::string::String`, found reference | help: consider removing the borrow: `format!(\"b\")` | = note: expected type `std::string::String` found type `&std::string::String` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-887236feb75ed6b62334585c2ea57481bc7d6950bb23fe01a63bbe08cdfb14f0","title":"","text":" // Regression test for #59311. The test is taken from // rust-lang/rust/issues/71546#issuecomment-620638437 // as they seem to have the same cause. // FIXME: It's not clear that this code ought to report // an error, but the regression test is here to ensure // that it does not ICE. See discussion on #74889 for details. pub trait T { fn t(&self, _: F) {} } pub fn crash(v: &V) where for<'a> &'a V: T + 'static, { v.t(|| {}); //~ ERROR: higher-ranked subtype error } fn main() {} "} {"_id":"doc-en-rust-e89dfe2a5cfb60b386e8c448e5b91539d904257e120794532df9efa98cb1f56d","title":"","text":" error: higher-ranked subtype error --> $DIR/issue-59311.rs:17:9 | LL | v.t(|| {}); | ^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-8d8fb5164be0531ba0a1712aa47bb9a779aa39c5103d56d9b26809f68ac55afc","title":"","text":"\"Specify the name of the crate being built\", \"NAME\", ), opt::opt_s( \"\", \"edition\", \"Specify which edition of the compiler to use when compiling code.\", EDITION_NAME_LIST, ), opt::multi_s( \"\", \"emit\","} {"_id":"doc-en-rust-e7fc2b3db9edff87a8135437d208c4584ddea5e57a80e6dcc0bc09cf968318ac","title":"","text":"`expanded,identified` (fully parenthesized, AST nodes with IDs).\", \"TYPE\", ), opt::opt_s( \"\", \"edition\", \"Specify which edition of the compiler to use when compiling code.\", EDITION_NAME_LIST, ), opt::multi_s( \"\", \"remap-path-prefix\","} {"_id":"doc-en-rust-007a15f0ba81ecaf5024f2a1d60c681cf07a6c71c8be67f649f4afb349c0951c","title":"","text":"let ident = *ident; let mut path = path.clone(); for seg in &mut path.segments { seg.id = self.next_node_id(); // Give the cloned segment the same resolution information // as the old one (this is needed for stability checking). let new_id = self.next_node_id(); self.resolver.clone_res(seg.id, new_id); seg.id = new_id; } let span = path.span;"} {"_id":"doc-en-rust-f09d084ac9a833f0ed98ab5e601760bb7e058db48746080b8d409ebcfe33c5e5","title":"","text":"// Give the segments new node-ids since they are being cloned. for seg in &mut prefix.segments { seg.id = self.next_node_id(); // Give the cloned segment the same resolution information // as the old one (this is needed for stability checking). let new_id = self.next_node_id(); self.resolver.clone_res(seg.id, new_id); seg.id = new_id; } // Each `use` import is an item and thus are owners of the"} {"_id":"doc-en-rust-9c42d35bb114611a1562019d0a25eb9fca25873211c9ea25491932f48627213f","title":"","text":"fn legacy_const_generic_args(&self, expr: &Expr) -> Option>; fn get_partial_res(&self, id: NodeId) -> Option; fn get_import_res(&self, id: NodeId) -> PerNS>>; // Clones the resolution (if any) on 'source' and applies it // to 'target'. Used when desugaring a `UseTreeKind::Nested` to // multiple `UseTreeKind::Simple`s fn clone_res(&mut self, source: NodeId, target: NodeId); fn get_label_res(&self, id: NodeId) -> Option; fn get_lifetime_res(&self, id: NodeId) -> Option; fn take_extra_lifetime_params(&mut self, id: NodeId) -> Vec<(Ident, NodeId, LifetimeRes)>;"} {"_id":"doc-en-rust-100e1410865bcfc0956b6362d8ab472bee62bfee318a4cd22cfebca8815fea4f","title":"","text":"None } fn clone_res(&mut self, source: NodeId, target: NodeId) { if let Some(res) = self.partial_res_map.get(&source) { self.partial_res_map.insert(target, *res); } } /// Obtains resolution for a `NodeId` with a single resolution. fn get_partial_res(&self, id: NodeId) -> Option { self.partial_res_map.get(&id).copied()"} {"_id":"doc-en-rust-3363cebeb6eeb6ed67759e2cf01a334369c8abc341721b04e851379c573fd698","title":"","text":"extern crate lint_output_format; //~ ERROR use of unstable library feature use lint_output_format::{foo, bar}; //~ ERROR use of unstable library feature //~| ERROR use of unstable library feature fn main() { let _x = foo();"} {"_id":"doc-en-rust-71c433e59b2b6fe8a8f65e68383c5f5e30cf4a1fbdebc84de4647db6489761c9","title":"","text":"= help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable error[E0658]: use of unstable library feature 'unstable_test_feature' --> $DIR/lint-output-format.rs:7:26 | LL | use lint_output_format::{foo, bar}; | ^^^ | = help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable error[E0658]: use of unstable library feature 'unstable_test_feature' --> $DIR/lint-output-format.rs:7:31 | LL | use lint_output_format::{foo, bar};"} {"_id":"doc-en-rust-6dd638489d825b1447a4a61a464682c63d5b08a4cfa66562e3f8d2afdc05f3a4","title":"","text":"= help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable error[E0658]: use of unstable library feature 'unstable_test_feature' --> $DIR/lint-output-format.rs:11:14 --> $DIR/lint-output-format.rs:12:14 | LL | let _y = bar(); | ^^^ | = help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable error: aborting due to 3 previous errors error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0658`."} {"_id":"doc-en-rust-635c0e933daa32e1f230a314b6de2319e09ff698777f9dffff5ea6681bb2920c","title":"","text":"impl stable_in_unstable_std::old_stable_module::OldTrait for LocalType {} } mod isolated6 { use stable_in_unstable_core::new_unstable_module::{OldTrait}; //~ ERROR use of unstable library feature 'unstable_test_feature' } mod isolated7 { use stable_in_unstable_core::new_unstable_module::*; //~ ERROR use of unstable library feature 'unstable_test_feature' } "} {"_id":"doc-en-rust-518e3e6912c84e005c81ef5c72bc4ab9791235ed568e20da7993c6646e727a9d","title":"","text":"= note: see issue #1 for more information = help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable error: aborting due to 4 previous errors error[E0658]: use of unstable library feature 'unstable_test_feature' --> $DIR/stable-in-unstable.rs:49:56 | LL | use stable_in_unstable_core::new_unstable_module::{OldTrait}; | ^^^^^^^^ | = note: see issue #1 for more information = help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable error[E0658]: use of unstable library feature 'unstable_test_feature' --> $DIR/stable-in-unstable.rs:53:9 | LL | use stable_in_unstable_core::new_unstable_module::*; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #1 for more information = help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable error: aborting due to 6 previous errors For more information about this error, try `rustc --explain E0658`."} {"_id":"doc-en-rust-6ffae7c83517f045e49036fbc5ca3cd965015a3559f6a95d42a02076a5af6eae","title":"","text":"/// Returns the creation time listed in this metadata. /// /// The returned value corresponds to the `birthtime` field of `stat` on /// Unix platforms and the `ftCreationTime` field on Windows platforms. /// The returned value corresponds to the `btime` field of `statx` on /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other /// Unix platforms, and the `ftCreationTime` field on Windows platforms. /// /// # Errors /// /// This field may not be available on all platforms, and will return an /// `Err` on platforms where it is not available. /// `Err` on platforms or filesystems where it is not available. /// /// # Examples ///"} {"_id":"doc-en-rust-12124b097f5c505143c56e1f73fee64db830a315049b13efefbe571629671fdd","title":"","text":"/// if let Ok(time) = metadata.created() { /// println!(\"{:?}\", time); /// } else { /// println!(\"Not supported on this platform\"); /// println!(\"Not supported on this platform or filesystem\"); /// } /// Ok(()) /// }"} {"_id":"doc-en-rust-f4bdf732529175d41d6eb2af2a77b9dd0ada122af984b90b030e96511364fe02","title":"","text":"check!(a.created()); check!(b.created()); } if cfg!(target_os = \"linux\") { // Not always available match (a.created(), b.created()) { (Ok(t1), Ok(t2)) => assert!(t1 <= t2), (Err(e1), Err(e2)) if e1.kind() == ErrorKind::Other && e2.kind() == ErrorKind::Other => {} (a, b) => panic!( \"creation time must be always supported or not supported: {:?} {:?}\", a, b, ), } } } }"} {"_id":"doc-en-rust-1c46b4722a9d8bb0ab20ef95403cc4c386a2b4df4882dbe5fe3d6c00e3e037e0","title":"","text":"pub struct File(FileDesc); #[derive(Clone)] pub struct FileAttr { stat: stat64, // FIXME: This should be available on Linux with all `target_arch` and `target_env`. // https://github.com/rust-lang/libc/issues/1545 macro_rules! cfg_has_statx { ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => { cfg_if::cfg_if! { if #[cfg(all(target_os = \"linux\", target_env = \"gnu\", any( target_arch = \"x86\", target_arch = \"arm\", // target_arch = \"mips\", target_arch = \"powerpc\", target_arch = \"x86_64\", // target_arch = \"aarch64\", target_arch = \"powerpc64\", // target_arch = \"mips64\", // target_arch = \"s390x\", target_arch = \"sparc64\", )))] { $($then_tt)* } else { $($else_tt)* } } }; ($($block_inner:tt)*) => { #[cfg(all(target_os = \"linux\", target_env = \"gnu\", any( target_arch = \"x86\", target_arch = \"arm\", // target_arch = \"mips\", target_arch = \"powerpc\", target_arch = \"x86_64\", // target_arch = \"aarch64\", target_arch = \"powerpc64\", // target_arch = \"mips64\", // target_arch = \"s390x\", target_arch = \"sparc64\", )))] { $($block_inner)* } }; } cfg_has_statx! {{ #[derive(Clone)] pub struct FileAttr { stat: stat64, statx_extra_fields: Option, } #[derive(Clone)] struct StatxExtraFields { // This is needed to check if btime is supported by the filesystem. stx_mask: u32, stx_btime: libc::statx_timestamp, } // We prefer `statx` on Linux if available, which contains file creation time. // Default `stat64` contains no creation time. unsafe fn try_statx( fd: c_int, path: *const libc::c_char, flags: i32, mask: u32, ) -> Option> { use crate::sync::atomic::{AtomicBool, Ordering}; // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx` // We store the availability in a global to avoid unnecessary syscalls static HAS_STATX: AtomicBool = AtomicBool::new(true); syscall! { fn statx( fd: c_int, pathname: *const libc::c_char, flags: c_int, mask: libc::c_uint, statxbuf: *mut libc::statx ) -> c_int } if !HAS_STATX.load(Ordering::Relaxed) { return None; } let mut buf: libc::statx = mem::zeroed(); let ret = cvt(statx(fd, path, flags, mask, &mut buf)); match ret { Err(err) => match err.raw_os_error() { Some(libc::ENOSYS) => { HAS_STATX.store(false, Ordering::Relaxed); return None; } _ => return Some(Err(err)), } Ok(_) => { // We cannot fill `stat64` exhaustively because of private padding fields. let mut stat: stat64 = mem::zeroed(); // `c_ulong` on gnu-mips, `dev_t` otherwise stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _; stat.st_ino = buf.stx_ino as libc::ino64_t; stat.st_nlink = buf.stx_nlink as libc::nlink_t; stat.st_mode = buf.stx_mode as libc::mode_t; stat.st_uid = buf.stx_uid as libc::uid_t; stat.st_gid = buf.stx_gid as libc::gid_t; stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _; stat.st_size = buf.stx_size as off64_t; stat.st_blksize = buf.stx_blksize as libc::blksize_t; stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t; stat.st_atime = buf.stx_atime.tv_sec as libc::time_t; // `i64` on gnu-x86_64-x32, `c_ulong` otherwise. stat.st_atime_nsec = buf.stx_atime.tv_nsec as _; stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t; stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _; stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t; stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _; let extra = StatxExtraFields { stx_mask: buf.stx_mask, stx_btime: buf.stx_btime, }; Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) })) } } } } else { #[derive(Clone)] pub struct FileAttr { stat: stat64, } }} // all DirEntry's will have a reference to this struct struct InnerReadDir { dirp: Dir,"} {"_id":"doc-en-rust-cb57f7431dc4658a2c19bf5f5423222e66a36b149c1c2b72a6a2685989bafdbc","title":"","text":"#[derive(Debug)] pub struct DirBuilder { mode: mode_t } cfg_has_statx! {{ impl FileAttr { fn from_stat64(stat: stat64) -> Self { Self { stat, statx_extra_fields: None } } } } else { impl FileAttr { fn from_stat64(stat: stat64) -> Self { Self { stat } } } }} impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions {"} {"_id":"doc-en-rust-3ef2ffe789937e979fcd372eec247768c415c9095954208fe13de45aa772f90d","title":"","text":"target_os = \"macos\", target_os = \"ios\")))] pub fn created(&self) -> io::Result { cfg_has_statx! { if let Some(ext) = &self.statx_extra_fields { return if (ext.stx_mask & libc::STATX_BTIME) != 0 { Ok(SystemTime::from(libc::timespec { tv_sec: ext.stx_btime.tv_sec as libc::time_t, tv_nsec: ext.stx_btime.tv_nsec as _, })) } else { Err(io::Error::new( io::ErrorKind::Other, \"creation time is not available for the filesystem\", )) }; } } Err(io::Error::new(io::ErrorKind::Other, \"creation time is not available on this platform currently\"))"} {"_id":"doc-en-rust-6348bcd0b8cadda9af321e63de3cd99dfa72a52a128ee7514add33b0b1f34164","title":"","text":"#[cfg(any(target_os = \"linux\", target_os = \"emscripten\", target_os = \"android\"))] pub fn metadata(&self) -> io::Result { let fd = cvt(unsafe {dirfd(self.dir.inner.dirp.0)})?; let fd = cvt(unsafe { dirfd(self.dir.inner.dirp.0) })?; let name = self.entry.d_name.as_ptr(); cfg_has_statx! { if let Some(ret) = unsafe { try_statx( fd, name, libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT, libc::STATX_ALL, ) } { return ret; } } let mut stat: stat64 = unsafe { mem::zeroed() }; cvt(unsafe { fstatat64(fd, self.entry.d_name.as_ptr(), &mut stat, libc::AT_SYMLINK_NOFOLLOW) fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?; Ok(FileAttr { stat }) Ok(FileAttr::from_stat64(stat)) } #[cfg(not(any(target_os = \"linux\", target_os = \"emscripten\", target_os = \"android\")))]"} {"_id":"doc-en-rust-bac7c779720349c09a7bd72971db3a55fbfb78c7f98ece1ff858861eb8946409","title":"","text":"} pub fn file_attr(&self) -> io::Result { let fd = self.0.raw(); cfg_has_statx! { if let Some(ret) = unsafe { try_statx( fd, b\"0\" as *const _ as *const libc::c_char, libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT, libc::STATX_ALL, ) } { return ret; } } let mut stat: stat64 = unsafe { mem::zeroed() }; cvt(unsafe { fstat64(self.0.raw(), &mut stat) fstat64(fd, &mut stat) })?; Ok(FileAttr { stat }) Ok(FileAttr::from_stat64(stat)) } pub fn fsync(&self) -> io::Result<()> {"} {"_id":"doc-en-rust-154b7b1046a764533f4a5211db4adde771ffd61fff442165f5985a08f42fb61d","title":"","text":"pub fn stat(p: &Path) -> io::Result { let p = cstr(p)?; cfg_has_statx! { if let Some(ret) = unsafe { try_statx( libc::AT_FDCWD, p.as_ptr(), libc::AT_STATX_SYNC_AS_STAT, libc::STATX_ALL, ) } { return ret; } } let mut stat: stat64 = unsafe { mem::zeroed() }; cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?; Ok(FileAttr { stat }) Ok(FileAttr::from_stat64(stat)) } pub fn lstat(p: &Path) -> io::Result { let p = cstr(p)?; cfg_has_statx! { if let Some(ret) = unsafe { try_statx( libc::AT_FDCWD, p.as_ptr(), libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT, libc::STATX_ALL, ) } { return ret; } } let mut stat: stat64 = unsafe { mem::zeroed() }; cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?; Ok(FileAttr { stat }) Ok(FileAttr::from_stat64(stat)) } pub fn canonicalize(p: &Path) -> io::Result {"} {"_id":"doc-en-rust-cc5921b9746eb81487141b41e2f283f2f3f7363633331cd1906c41a8109ffc13","title":"","text":" Subproject commit cafbe7f2d9bdf9e94946e3f6f62b781b05b7d556 Subproject commit d420589e1a8208c85368d07c1644c6725367650b "} {"_id":"doc-en-rust-6f23e8e26bd5044e9823f3da937f6e494345b07dffb9148a3270ff00856ec607","title":"","text":"borrow_region: RegionVid, outlived_region: RegionVid, ) -> (ConstraintCategory, bool, Span, Option) { let (category, from_closure, span) = self.best_blame_constraint(mir, borrow_region, |r| r == outlived_region); let (category, from_closure, span) = self.best_blame_constraint( mir, borrow_region, |r| self.provides_universal_region(r, borrow_region, outlived_region) ); let outlived_fr_name = self.give_region_a_name(infcx, mir, upvars, mir_def_id, outlived_region, &mut 1); (category, from_closure, span, outlived_fr_name)"} {"_id":"doc-en-rust-40143f6090083fbc2571b5e12b01cb41fce6caa4376fa9604298a0ff32ea5bd9","title":"","text":" // Test that we handle the case when a local variable is borrowed for `'static` // due to an outlives constraint involving a region in an incompatible universe pub trait Outlives<'this> {} impl<'this, T> Outlives<'this> for T where T: 'this {} trait Reference { type AssociatedType; } impl<'a, T: 'a> Reference for &'a T { type AssociatedType = &'a (); } fn assert_static_via_hrtb(_: G) where for<'a> G: Outlives<'a> {} fn assert_static_via_hrtb_with_assoc_type(_: &'_ T) where for<'a> &'a T: Reference, {} fn main() { let local = 0; assert_static_via_hrtb(&local); //~ ERROR `local` does not live long enough assert_static_via_hrtb_with_assoc_type(&&local); //~ ERROR `local` does not live long enough } "} {"_id":"doc-en-rust-17c836cf91fa21bec237a8ee5331644213a031d9837d811310fe4b230d2eca1b","title":"","text":" error[E0597]: `local` does not live long enough --> $DIR/local-outlives-static-via-hrtb.rs:24:28 | LL | assert_static_via_hrtb(&local); | -----------------------^^^^^^- | | | | | borrowed value does not live long enough | argument requires that `local` is borrowed for `'static` LL | assert_static_via_hrtb_with_assoc_type(&&local); LL | } | - `local` dropped here while still borrowed error[E0597]: `local` does not live long enough --> $DIR/local-outlives-static-via-hrtb.rs:25:45 | LL | assert_static_via_hrtb_with_assoc_type(&&local); | ----------------------------------------^^^^^^- | | | | | borrowed value does not live long enough | argument requires that `local` is borrowed for `'static` LL | } | - `local` dropped here while still borrowed error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0597`. "} {"_id":"doc-en-rust-8bb0db7126ef0e08f8f9422711ffb6c931e39ee1f7dc33cb6e3c6a5e8c6c5d74","title":"","text":"dox[code_block.code].to_owned(), ); let has_errors = { let mut has_errors = false; let validation_status = { let mut has_syntax_errors = false; let mut only_whitespace = true; // even if there is a syntax error, we need to run the lexer over the whole file let mut lexer = Lexer::new(&sess, source_file, None); loop { match lexer.next_token().kind { token::Eof => break, token::Unknown(..) => has_errors = true, _ => (), token::Whitespace => (), token::Unknown(..) => has_syntax_errors = true, _ => only_whitespace = false, } } has_errors if has_syntax_errors { Some(CodeBlockInvalid::SyntaxError) } else if only_whitespace { Some(CodeBlockInvalid::Empty) } else { None } }; if has_errors { if let Some(code_block_invalid) = validation_status { let mut diag = if let Some(sp) = super::source_span_for_markdown_range(self.cx, &dox, &code_block.range, &item.attrs) { let mut diag = self .cx .sess() .struct_span_warn(sp, \"could not parse code block as Rust code\"); let warning_message = match code_block_invalid { CodeBlockInvalid::SyntaxError => \"could not parse code block as Rust code\", CodeBlockInvalid::Empty => \"Rust code block is empty\", }; let mut diag = self.cx.sess().struct_span_warn(sp, warning_message); if code_block.syntax.is_none() && code_block.is_fenced { let sp = sp.from_inner(InnerSpan::new(0, 3));"} {"_id":"doc-en-rust-1ec52126c5f08f0c8c5aa3b146c9cdf4d5677cc3ebaadc301b2f51a1b0c8beb0","title":"","text":"self.fold_item_recur(item) } } enum CodeBlockInvalid { SyntaxError, Empty, } "} {"_id":"doc-en-rust-5387ef1d4966bc457611630c4b854a693acbd4b37e038de802930065c10fbafb","title":"","text":"/// _ #[doc = \"```\"] pub fn crazy_attrs() {} /// ```rust /// ``` pub fn empty_rust() {} /// ``` /// /// /// ``` pub fn empty_rust_with_whitespace() {} "} {"_id":"doc-en-rust-6341d506424b6b06204d954663ebeb6c8cec4e36eaaf825c7fe416025423f159","title":"","text":"| = help: mark blocks that do not contain Rust code as text: ```text warning: Rust code block is empty --> $DIR/invalid-syntax.rs:68:5 | LL | /// ```rust | _____^ LL | | /// ``` | |_______^ warning: Rust code block is empty --> $DIR/invalid-syntax.rs:72:5 | LL | /// ``` | _____^ LL | | /// LL | | /// LL | | /// ``` | |_______^ help: mark blocks that do not contain Rust code as text | LL | /// ```text | ^^^^^^^ error: unknown start of token: --> :1:1 |"} {"_id":"doc-en-rust-eee0b6d5c8ff8c1132fdea1d691fc2e3708ca1aa52004613940595a6aa620f8a","title":"","text":"return } // For the wasm32 target statics with #[link_section] are placed into custom // For the wasm32 target statics with `#[link_section]` are placed into custom // sections of the final output file, but this isn't link custom sections of // other executable formats. Namely we can only embed a list of bytes, // nothing with pointers to anything else or relocations. If any relocation // show up, reject them here. // `#[link_section]` may contain arbitrary, or even undefined bytes, but it is // the consumer's responsibility to ensure all bytes that have been read // have defined values. let instance = ty::Instance::mono(tcx, id); let cid = GlobalId { instance,"} {"_id":"doc-en-rust-049376daccb11c750e5de20ec021a38bcd922157ec8b4cc3f605221c679bbd82","title":"","text":"/// When using a future, you generally won't call `poll` directly, but instead /// `await!` the value. #[doc(spotlight)] #[must_use = \"futures do nothing unless polled\"] #[must_use = \"futures do nothing unless you `.await` or poll them\"] #[stable(feature = \"futures_api\", since = \"1.36.0\")] pub trait Future { /// The type of value produced on completion."} {"_id":"doc-en-rust-4a48e3ff3bf275786c7b5237504abd78ac807cd0a93a47e5d84b4f98bb6770aa","title":"","text":" // compile-flags: --edition=2018 pub use u32; "} {"_id":"doc-en-rust-4f2a9cdd06a724e08fff48879839234ac464219ed22fa312c1ba4379697fccde","title":"","text":" // Regression test for #60976: ICE (with <=1.36.0) when another file had `use ;`. // check-pass // aux-build:extern-use-primitive-type-lib.rs extern crate extern_use_primitive_type_lib; fn main() {} "} {"_id":"doc-en-rust-49272112d327ce33d506d08f51f717cce0536de8e9606a0673252b31c7f0d67b","title":"","text":"use rustc::hir::def::{Res, DefKind}; use rustc::hir::def_id::DefId; use rustc::lint; use rustc::ty; use rustc::ty::{self, Ty}; use rustc::ty::adjustment; use rustc_data_structures::fx::FxHashMap; use lint::{LateContext, EarlyContext, LintContext, LintArray};"} {"_id":"doc-en-rust-419f0df15adbf6ef8ca10d30b9bdd0c91c4c1f2beacbfa09abb9ebb92b42e686","title":"","text":"return; } let t = cx.tables.expr_ty(&expr); let type_permits_lack_of_use = if t.is_unit() || cx.tcx.is_ty_uninhabited_from( cx.tcx.hir().get_module_parent_by_hir_id(expr.hir_id), t) { true } else { match t.sty { ty::Adt(def, _) => check_must_use(cx, def.did, s.span, \"\", \"\"), ty::Opaque(def, _) => { let mut must_use = false; for (predicate, _) in &cx.tcx.predicates_of(def).predicates { if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate { let trait_ref = poly_trait_predicate.skip_binder().trait_ref; if check_must_use(cx, trait_ref.def_id, s.span, \"implementer of \", \"\") { must_use = true; break; } } } must_use } ty::Dynamic(binder, _) => { let mut must_use = false; for predicate in binder.skip_binder().iter() { if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate { if check_must_use(cx, trait_ref.def_id, s.span, \"\", \" trait object\") { must_use = true; break; } } } must_use } _ => false, } }; let ty = cx.tables.expr_ty(&expr); let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, \"\"); let mut fn_warned = false; let mut op_warned = false;"} {"_id":"doc-en-rust-acf38c55fa4e9e0e95e2be1ed3926401e5a2144da248c677682d5eeb35545cba","title":"","text":"_ => None }; if let Some(def_id) = maybe_def_id { fn_warned = check_must_use(cx, def_id, s.span, \"return value of \", \"\"); fn_warned = check_must_use_def(cx, def_id, s.span, \"return value of \", \"\"); } else if type_permits_lack_of_use { // We don't warn about unused unit or uninhabited types. // (See https://github.com/rust-lang/rust/issues/43806 for details.)"} {"_id":"doc-en-rust-336756ea458370dfc860f898b01ad5760d576aaec7849d3f7231ad91b956dce6","title":"","text":"cx.span_lint(UNUSED_RESULTS, s.span, \"unused result\"); } fn check_must_use( // Returns whether an error has been emitted (and thus another does not need to be later). fn check_must_use_ty<'tcx>( cx: &LateContext<'_, 'tcx>, ty: Ty<'tcx>, expr: &hir::Expr, span: Span, descr_post_path: &str, ) -> bool { if ty.is_unit() || cx.tcx.is_ty_uninhabited_from( cx.tcx.hir().get_module_parent_by_hir_id(expr.hir_id), ty) { return true; } match ty.sty { ty::Adt(def, _) => check_must_use_def(cx, def.did, span, \"\", descr_post_path), ty::Opaque(def, _) => { let mut has_emitted = false; for (predicate, _) in &cx.tcx.predicates_of(def).predicates { if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate { let trait_ref = poly_trait_predicate.skip_binder().trait_ref; let def_id = trait_ref.def_id; if check_must_use_def(cx, def_id, span, \"implementer of \", \"\") { has_emitted = true; break; } } } has_emitted } ty::Dynamic(binder, _) => { let mut has_emitted = false; for predicate in binder.skip_binder().iter() { if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate { let def_id = trait_ref.def_id; if check_must_use_def(cx, def_id, span, \"\", \" trait object\") { has_emitted = true; break; } } } has_emitted } ty::Tuple(ref tys) => { let mut has_emitted = false; let spans = if let hir::ExprKind::Tup(comps) = &expr.node { debug_assert_eq!(comps.len(), tys.len()); comps.iter().map(|e| e.span).collect() } else { vec![] }; for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() { let descr_post_path = &format!(\" in tuple element {}\", i); let span = *spans.get(i).unwrap_or(&span); if check_must_use_ty(cx, ty, expr, span, descr_post_path) { has_emitted = true; } } has_emitted } _ => false, } } // Returns whether an error has been emitted (and thus another does not need to be later). fn check_must_use_def( cx: &LateContext<'_, '_>, def_id: DefId, sp: Span, span: Span, descr_pre_path: &str, descr_post_path: &str, ) -> bool {"} {"_id":"doc-en-rust-cde6ace8411e87cafd73e46b72248d819bec28d21a18d33c9eb4bce769808961","title":"","text":"if attr.check_name(sym::must_use) { let msg = format!(\"unused {}`{}`{} that must be used\", descr_pre_path, cx.tcx.def_path_str(def_id), descr_post_path); let mut err = cx.struct_span_lint(UNUSED_MUST_USE, sp, &msg); let mut err = cx.struct_span_lint(UNUSED_MUST_USE, span, &msg); // check for #[must_use = \"...\"] if let Some(note) = attr.value_str() { err.note(¬e.as_str());"} {"_id":"doc-en-rust-6527bc0c8fd566846861729e941e5dcdb30204b99c626bc2357437429f46c284","title":"","text":" #![deny(unused_must_use)] fn foo() -> (Result<(), ()>, ()) { (Ok::<(), ()>(()), ()) } fn main() { (Ok::<(), ()>(()),); //~ ERROR unused `std::result::Result` (Ok::<(), ()>(()), 0, Ok::<(), ()>(()), 5); //~^ ERROR unused `std::result::Result` //~^^ ERROR unused `std::result::Result` foo(); //~ ERROR unused `std::result::Result` ((Err::<(), ()>(()), ()), ()); //~ ERROR unused `std::result::Result` } "} {"_id":"doc-en-rust-126549f1cbd060511e697bd54ddc6bf6c5befadd4750918cfad87c30d953a0a2","title":"","text":" error: unused `std::result::Result` in tuple element 0 that must be used --> $DIR/must_use-tuple.rs:8:6 | LL | (Ok::<(), ()>(()),); | ^^^^^^^^^^^^^^^^ | note: lint level defined here --> $DIR/must_use-tuple.rs:1:9 | LL | #![deny(unused_must_use)] | ^^^^^^^^^^^^^^^ = note: this `Result` may be an `Err` variant, which should be handled error: unused `std::result::Result` in tuple element 0 that must be used --> $DIR/must_use-tuple.rs:10:6 | LL | (Ok::<(), ()>(()), 0, Ok::<(), ()>(()), 5); | ^^^^^^^^^^^^^^^^ | = note: this `Result` may be an `Err` variant, which should be handled error: unused `std::result::Result` in tuple element 2 that must be used --> $DIR/must_use-tuple.rs:10:27 | LL | (Ok::<(), ()>(()), 0, Ok::<(), ()>(()), 5); | ^^^^^^^^^^^^^^^^ | = note: this `Result` may be an `Err` variant, which should be handled error: unused `std::result::Result` in tuple element 0 that must be used --> $DIR/must_use-tuple.rs:14:5 | LL | foo(); | ^^^^^^ | = note: this `Result` may be an `Err` variant, which should be handled error: unused `std::result::Result` in tuple element 0 that must be used --> $DIR/must_use-tuple.rs:16:6 | LL | ((Err::<(), ()>(()), ()), ()); | ^^^^^^^^^^^^^^^^^^^^^^^ | = note: this `Result` may be an `Err` variant, which should be handled error: aborting due to 5 previous errors "} {"_id":"doc-en-rust-599cb4fa2d2d9e9e135f1508626c8ef6528ae166a2cd749105e7f815292cbcd8","title":"","text":"self.tcx().mk_const( ty::Const { val: ConstValue::Infer(InferConst::Canonical(self.binder_index, var.into())), ty: const_var.ty, ty: self.fold_ty(const_var.ty), } ) }"} {"_id":"doc-en-rust-645fed82f7d7ee2824cf0ed704ddbf7e8d3a1d37cdc725f5dcc2aece03c7239f","title":"","text":" // revisions:rpass1 #![feature(const_generics)] struct Struct(T); impl Struct<[T; N]> { fn f() {} fn g() { Self::f(); } } fn main() { Struct::<[u32; 3]>::g(); } "} {"_id":"doc-en-rust-a65965e8c9699485e3f2a237cc11aa631e9853972de974b7178e6eb09fd4e0c4","title":"","text":" // revisions:rpass1 #![feature(const_generics)] struct FakeArray(T); impl FakeArray { fn len(&self) -> usize { N } } fn main() { let fa = FakeArray::(1); assert_eq!(fa.len(), 32); } "} {"_id":"doc-en-rust-4690080eee9b154292f871490000aeeee106f5decd6c41703460f5e1dac28215","title":"","text":" // revisions:cfail1 #![feature(const_generics)] //[cfail1]~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash struct S([T; N]); fn f(x: T) -> S { panic!() } fn main() { f(0u8); //[cfail1]~^ ERROR type annotations needed } "} {"_id":"doc-en-rust-9ccbdfec69736410b0efef1e8edb5e4e2fe5e6f1569f3a2cac58894ec3530891","title":"","text":" // revisions:cfail1 #![feature(const_generics)] //[cfail1]~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash fn combinator() -> [T; S] {} //[cfail1]~^ ERROR mismatched types fn main() { combinator().into_iter(); //[cfail1]~^ ERROR type annotations needed } "} {"_id":"doc-en-rust-f7b8611a02b3212a29dbf707d4cddcbdf5aca4bc10aa54aab501a564844094bd","title":"","text":" // revisions:rpass1 #![feature(const_generics)] pub struct Foo([T; 0]); impl Foo { pub fn new() -> Self { Foo([]) } } fn main() { let _: Foo = Foo::new(); } "} {"_id":"doc-en-rust-6295dcfdc82ddc99d926cae88b77e78bc8959a42c0c38b79aa59adbda0faea76","title":"","text":"use libc; use option::None; use os; use path::Path; use run::{readclose, writeclose}; use run;"} {"_id":"doc-en-rust-2b82f231b36c3b656c11eecd0f995c0e0ae5be8460dbf263afce2895511d8f59","title":"","text":"p.destroy(); // ...and nor should this (and nor should the destructor) } #[cfg(unix)] // there is no way to sleep on windows from inside libcore... fn test_destroy_actually_kills(force: bool) { let path = Path(fmt!(\"test/core-run-test-destroy-actually-kills-%?.tmp\", force)); os::remove_file(&path); #[cfg(unix)] static BLOCK_COMMAND: &'static str = \"cat\"; let cmd = fmt!(\"sleep 5 && echo MurderDeathKill > %s\", path.to_str()); let mut p = run::start_program(\"sh\", [~\"-c\", cmd]); #[cfg(windows)] static BLOCK_COMMAND: &'static str = \"cmd\"; p.destroy(); // destroy the program before it has a chance to echo its message #[cfg(unix)] fn process_exists(pid: libc::pid_t) -> bool { run::program_output(\"ps\", [~\"-p\", pid.to_str()]).out.contains(pid.to_str()) } unsafe { // wait to ensure the program is really destroyed and not just waiting itself libc::sleep(10); #[cfg(windows)] fn process_exists(pid: libc::pid_t) -> bool { use libc::types::os::arch::extra::DWORD; use libc::funcs::extra::kernel32::{CloseHandle, GetExitCodeProcess, OpenProcess}; use libc::consts::os::extra::{FALSE, PROCESS_QUERY_INFORMATION, STILL_ACTIVE }; unsafe { let proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid as DWORD); if proc.is_null() { return false; } // proc will be non-null if the process is alive, or if it died recently let mut status = 0; GetExitCodeProcess(proc, &mut status); CloseHandle(proc); return status == STILL_ACTIVE; } } // the program should not have had chance to echo its message assert!(!path.exists()); // this program will stay alive indefinitely trying to read from stdin let mut p = run::start_program(BLOCK_COMMAND, []); assert!(process_exists(p.get_id())); if force { p.force_destroy(); } else { p.destroy(); } assert!(!process_exists(p.get_id())); } #[test] #[cfg(unix)] fn test_unforced_destroy_actually_kills() { test_destroy_actually_kills(false); } #[test] #[cfg(unix)] fn test_forced_destroy_actually_kills() { test_destroy_actually_kills(true); }"} {"_id":"doc-en-rust-6c7b654fddbb940f1ad50f3b48c94987eb4839023b94891586988aa68258dc2c","title":"","text":" // This previously triggered an ICE. pub(in crate::r#mod) fn main() {} //~^ ERROR expected module, found unresolved item "} {"_id":"doc-en-rust-8c08105e60c6bfc245cdab16004558f2e9cf0cebd1522b1fa1b2c0178a149a48","title":"","text":" error[E0577]: expected module, found unresolved item `crate::r#mod` --> $DIR/issue-61732.rs:3:8 | LL | pub(in crate::r#mod) fn main() {} | ^^^^^^^^^^^^ not a module error: Compilation failed, aborting rustdoc error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0577`. "} {"_id":"doc-en-rust-fdc48aae76f0bfec0470518d52fe4712c2957155702ca7e152de0095da2724db","title":"","text":"let mut indirect_outputs = vec![]; for (i, (out, &place)) in ia.outputs.iter().zip(&outputs).enumerate() { if out.is_rw { inputs.push(self.load_operand(place).immediate()); let operand = self.load_operand(place); if let OperandValue::Immediate(_) = operand.val { inputs.push(operand.immediate()); } ext_constraints.push(i.to_string()); } if out.is_indirect { indirect_outputs.push(self.load_operand(place).immediate()); let operand = self.load_operand(place); if let OperandValue::Immediate(_) = operand.val { indirect_outputs.push(operand.immediate()); } } else { output_types.push(place.layout.llvm_type(self.cx())); }"} {"_id":"doc-en-rust-e39857587a356864d497bb46a886ad50204b32d85d4d2b04b70456c6073e0826","title":"","text":" // build-fail // ignore-emscripten no asm! support #![feature(asm)] fn main() { unsafe { asm!(\"nop\" : \"+r\"(\"r15\")); //~^ malformed inline assembly } } "} {"_id":"doc-en-rust-f5a29efa4da0cfd210a12f483def8dcc3e3f9a2e20830b24a7d2cd887f062964","title":"","text":" error[E0668]: malformed inline assembly --> $DIR/issue-62046.rs:8:9 | LL | asm!(\"nop\" : \"+r\"(\"r15\")); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to previous error For more information about this error, try `rustc --explain E0668`. "} {"_id":"doc-en-rust-13e4a92f6d2c0dd1625c678ce538da02f7fdc7024f2225f9b28680fdda3ffc9a","title":"","text":"id: AllocId, liveness: AllocCheck, ) -> InterpResult<'static, (Size, Align)> { // Regular allocations. if let Ok(alloc) = self.get(id) { return Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align)); } // Function pointers. if let Ok(_) = self.get_fn_alloc(id) { return if let AllocCheck::Dereferencable = liveness { // The caller requested no function pointers. err!(DerefFunctionPointer) } else { Ok((Size::ZERO, Align::from_bytes(1).unwrap())) }; } // Foreign statics. // Can't do this in the match argument, we may get cycle errors since the lock would // be held throughout the match. let alloc = self.tcx.alloc_map.lock().get(id); match alloc { Some(GlobalAlloc::Static(did)) => { assert!(self.tcx.is_foreign_item(did)); // Use size and align of the type let ty = self.tcx.type_of(did); let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap(); return Ok((layout.size, layout.align.abi)); // Don't use `self.get` here as that will // a) cause cycles in case `id` refers to a static // b) duplicate a static's allocation in miri match self.alloc_map.get_or(id, || Err(())) { Ok((_, alloc)) => Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align)), Err(()) => { // Not a local allocation, check the global `tcx.alloc_map`. // Can't do this in the match argument, we may get cycle errors since the lock would // be held throughout the match. let alloc = self.tcx.alloc_map.lock().get(id); match alloc { Some(GlobalAlloc::Static(did)) => { // Use size and align of the type. let ty = self.tcx.type_of(did); let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap(); Ok((layout.size, layout.align.abi)) }, Some(GlobalAlloc::Memory(alloc)) => // Need to duplicate the logic here, because the global allocations have // different associated types than the interpreter-local ones. Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align)), Some(GlobalAlloc::Function(_)) => { if let AllocCheck::Dereferencable = liveness { // The caller requested no function pointers. err!(DerefFunctionPointer) } else { Ok((Size::ZERO, Align::from_bytes(1).unwrap())) } }, // The rest must be dead. None => if let AllocCheck::MaybeDead = liveness { // Deallocated pointers are allowed, we should be able to find // them in the map. Ok(*self.dead_alloc_map.get(&id) .expect(\"deallocated pointers should all be recorded in `dead_alloc_map`\")) } else { err!(DanglingPointerDeref) }, } } _ => {} } // The rest must be dead. if let AllocCheck::MaybeDead = liveness { // Deallocated pointers are allowed, we should be able to find // them in the map. Ok(*self.dead_alloc_map.get(&id) .expect(\"deallocated pointers should all be recorded in `dead_alloc_map`\")) } else { err!(DanglingPointerDeref) } }"} {"_id":"doc-en-rust-e4df6ce2c9d9b510448f5a5f246584b2c25f3f93d5b7f9be2e9ed9fdcfba9a2a","title":"","text":" // check-pass struct Foo { foo: Option<&'static Foo> } static FOO: Foo = Foo { foo: Some(&FOO), }; fn main() {} "} {"_id":"doc-en-rust-a0ecff2ace7fb53d7c8b7a880052dbd45a199b9eb9eaddc4a3f1bb011cd95baf","title":"","text":"debug!(\"late_bound_in_ty = {:?}\", late_bound_in_ty); for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) { let br_name = match *br { ty::BrNamed(_, name) => name, _ => { span_bug!( binding.span, \"anonymous bound region {:?} in binding but not trait ref\", br ); } ty::BrNamed(_, name) => format!(\"lifetime `{}`\", name), _ => \"an anonymous lifetime\".to_string(), }; // FIXME: point at the type params that don't have appropriate lifetimes: // struct S1 Fn(&i32, &i32) -> &'a i32>(F); // ---- ---- ^^^^^^^ struct_span_err!( let mut err = struct_span_err!( tcx.sess, binding.span, E0582, \"binding for associated type `{}` references lifetime `{}`, \"binding for associated type `{}` references {}, which does not appear in the trait input types\", binding.item_name, br_name ) .emit(); ); if let ty::BrAnon(_) = *br { // The only way for an anonymous lifetime to wind up // in the return type but **also** be unconstrained is // if it only appears in \"associated types\" in the // input. See #62200 for an example. In this case, // though we can easily give a hint that ought to be // relevant. err.note(\"lifetimes appearing in an associated type are not considered constrained\"); } err.emit(); } } }"} {"_id":"doc-en-rust-03c3ec6f5da16abcab6efcee604d2f44266109265ce6110499aee2455f43f1e3","title":"","text":" struct S {} trait T<'a> { type A; } impl T<'_> for S { type A = u32; } fn foo(x: impl Fn(>::A) -> >::A) {} //~^ ERROR binding for associated type `Output` references an anonymous lifetime //~^^ NOTE lifetimes appearing in an associated type are not considered constrained fn main() {} "} {"_id":"doc-en-rust-1ecafb07102cc5049d0451bf326ef6cf0ea13e8d92f95f15069460578d4ee849","title":"","text":" error[E0582]: binding for associated type `Output` references an anonymous lifetime, which does not appear in the trait input types --> $DIR/issue-62200.rs:11:39 | LL | fn foo(x: impl Fn(>::A) -> >::A) {} | ^^^^^^^^^^^^^^^ | = note: lifetimes appearing in an associated type are not considered constrained error: aborting due to previous error For more information about this error, try `rustc --explain E0582`. "} {"_id":"doc-en-rust-b77e02727a36ec8916685eae6b567a03bcfce91355c74505255f1a8bfa16cfb0","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(const_generics)] pub struct Vector([T; N]); pub type TruncatedVector = Vector; impl Vector { /// Drop the last component and return the vector with one fewer dimension. pub fn trunc(self) -> (TruncatedVector, T) { unimplemented!() } } fn vec4(a: T, b: T, c: T, d: T) -> Vector { Vector([a, b, c, d]) } fn main() { let (_xyz, _w): (TruncatedVector, u32) = vec4(0u32, 1, 2, 3).trunc(); } "} {"_id":"doc-en-rust-75e65313436d9a157ead3692521981aa4bc25ebfdf16a4c0246522a8c31e6793","title":"","text":" enum A { Value(()) } fn main() { let a = A::Value(()); a == A::Value; //~^ ERROR binary operation `==` cannot be applied to type `A` } "} {"_id":"doc-en-rust-1f29ce2952321735ef0c1b5e28d18981de2ba1815ba028f5fc0eaab13872645b","title":"","text":" error[E0369]: binary operation `==` cannot be applied to type `A` --> $DIR/issue-62375.rs:7:7 | LL | a == A::Value; | - ^^ -------- fn(()) -> A {A::Value} | | | A | = note: an implementation of `std::cmp::PartialEq` might be missing for `A` error: aborting due to previous error For more information about this error, try `rustc --explain E0369`. "} {"_id":"doc-en-rust-4815d91c68f42febd8273ce162a2e6b03a3246e2497997a3f28dcebe907d7f12","title":"","text":" Subproject commit 311d56cd91609c1c1c0370cbd2ece8e3048653a5 Subproject commit d6822f9c433bd70f786b157f17beaf64ee28d83a "} {"_id":"doc-en-rust-047bab63598e1a851e7274a40da7ed6ee4212b1a54c13166e4fb753301e33969","title":"","text":"let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align }; let mut sized = true; let mut offsets = vec![Size::ZERO; fields.len()]; let mut inverse_memory_index: Vec = (0..fields.len() as u32).collect(); let mut optimize = !repr.inhibit_struct_field_reordering_opt();"} {"_id":"doc-en-rust-7ad1ff4c5cfbf1b4dc87af02ca641def972cfc46136039b4e4e67efe4c2708bc","title":"","text":"// At the bottom of this function, we invert `inverse_memory_index` to // produce `memory_index` (see `invert_mapping`). let mut sized = true; let mut offsets = vec![Size::ZERO; fields.len()]; let mut offset = Size::ZERO; let mut largest_niche = None; let mut largest_niche_available = 0;"} {"_id":"doc-en-rust-d587733263545989e51d863eb5479d9a7c8e3397c166694cefb0914229932104","title":"","text":"let count = (niche_variants.end().as_u32() - niche_variants.start().as_u32() + 1) as u128; // FIXME(#62691) use the largest niche across all fields, // not just the first one. for (field_index, &field) in variants[i].iter().enumerate() { let niche = match &field.largest_niche { Some(niche) => niche, _ => continue, }; let (niche_start, niche_scalar) = match niche.reserve(self, count) { Some(pair) => pair, None => continue, }; // Find the field with the largest niche let niche_candidate = variants[i] .iter() .enumerate() .filter_map(|(j, &field)| Some((j, field.largest_niche.as_ref()?))) .max_by_key(|(_, niche)| niche.available(dl)); if let Some((field_index, niche, (niche_start, niche_scalar))) = niche_candidate.and_then(|(field_index, niche)| { Some((field_index, niche, niche.reserve(self, count)?)) }) { let mut align = dl.aggregate_align; let st = variants .iter_enumerated()"} {"_id":"doc-en-rust-dd057ff1e31d559e794188f46e4e5b864f11086d22321f06dac248da2bb29153","title":"","text":"C, } enum Option2 { Some(A, B), None } pub fn main() { assert_eq!(size_of::(), 1 as usize); assert_eq!(size_of::(), 4 as usize);"} {"_id":"doc-en-rust-66d3d63c8e713c21c7ff841f52a00d10f872b3e1f0cda9141a64f005fc3100bb","title":"","text":"assert_eq!(size_of::>>(), size_of::<(bool, &())>()); assert_eq!(size_of::>>(), size_of::<(bool, &())>()); assert_eq!(size_of::>>(), size_of::<(bool, &())>()); assert_eq!(size_of::>>(), size_of::<(bool, &())>()); }"} {"_id":"doc-en-rust-a746f3601cd7919599f74468f6a4153e331e1448867c627d377e4b53357e00e5","title":"","text":"pr: - master variables: - group: public-credentials jobs: - job: Linux timeoutInMinutes: 600"} {"_id":"doc-en-rust-63ef60010bd109220be3472f077545f10a41c2782cb3a4ab722b85003dfc5705","title":"","text":"linker_flavor: LinkerFlavor::Gcc, options: TargetOptions { features: \"+strict-align,+v6,+vfp2\".to_string(), features: \"+strict-align,+v6,+vfp2,-d32\".to_string(), abi_blacklist: super::arm_base::abi_blacklist(), target_mcount: \"u{1}__gnu_mcount_nc\".to_string(), .. base"} {"_id":"doc-en-rust-fb26a89096bd11f572b876af8ce27edbae169914a2dbad959fd533a7f05dd575","title":"","text":"// Most of these settings are copied from the arm_unknown_linux_gnueabihf // target. base.features = \"+strict-align,+v6,+vfp2\".to_string(); base.features = \"+strict-align,+v6,+vfp2,-d32\".to_string(); base.max_atomic_width = Some(64); Ok(Target { // It's important we use \"gnueabihf\" and not \"musleabihf\" here. LLVM"} {"_id":"doc-en-rust-00a85677f481bd34d74fa315a2c798a608f596fdb71d47939b0b922163ac9f6b","title":"","text":"linker_flavor: LinkerFlavor::Gcc, options: TargetOptions { features: \"+v6,+vfp2\".to_string(), features: \"+v6,+vfp2,-d32\".to_string(), max_atomic_width: Some(64), abi_blacklist: super::arm_base::abi_blacklist(), target_mcount: \"u{1}__gnu_mcount_nc\".to_string(),"} {"_id":"doc-en-rust-5b10de015957b1716250b83b10ea4ba02c1979d9bdffcc9bbaf340efcbcf62e5","title":"","text":"linker_flavor: LinkerFlavor::Gcc, options: TargetOptions { features: \"+v6,+vfp2\".to_string(), features: \"+v6,+vfp2,-d32\".to_string(), abi_blacklist: super::arm_base::abi_blacklist(), target_mcount: \"__mcount\".to_string(), .. base"} {"_id":"doc-en-rust-790f95c651a7942bafeed387cbd38cc9c2db07afafa66a9aedb726505df031d3","title":"","text":"ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait, ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl, ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant, ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType] { ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType, ItemType::Keyword] { if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) { let (short, name) = item_ty_to_strs(&myty); sidebar.push_str(&format!(\"\","} {"_id":"doc-en-rust-a78aa7bab43b6b8d570924004940e3132fbd6164e5b733f98d70f31fe9ff6192","title":"","text":"// @has foo/index.html '//h2[@id=\"keywords\"]' 'Keywords' // @has foo/index.html '//a[@href=\"keyword.match.html\"]' 'match' // @has foo/index.html '//div[@class=\"block items\"]//a/@href' '#keywords' // @has foo/keyword.match.html '//a[@class=\"keyword\"]' 'match' // @has foo/keyword.match.html '//span[@class=\"in-band\"]' 'Keyword match' // @has foo/keyword.match.html '//section[@id=\"main\"]//div[@class=\"docblock\"]//p' 'this is a test!'"} {"_id":"doc-en-rust-65ceae59f9dc843f91f807c933fedd5551e2889d715a8190ee6efd9e0a11f882","title":"","text":"_ => false, } } /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`. /// /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information. /// /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool { match param.kind { hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided } => true, _ => false, } } let impl_trait_params = self .params .iter()"} {"_id":"doc-en-rust-ae935f4bfad937e885cc7f024e703811d3cac21dec4bf3dac0cde1656c9f6446","title":"","text":".collect::>(); let mut params = Vec::with_capacity(self.params.len()); for p in self.params.iter().filter(|p| !is_impl_trait(p)) { for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) { let p = p.clean(cx); params.push(p); }"} {"_id":"doc-en-rust-a91df35607bd570b88fc7e4f25a990d0f5cf7c5e838dbca5d45da6ea2e4c8358","title":"","text":"TyKind::Never => Never, TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)), TyKind::Rptr(ref l, ref m) => { let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) }; // There are two times a `Fresh` lifetime can be created: // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`. // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`. // See #59286 for more information. // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it. // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though; // there's no case where it could cause the function to fail to compile. let elided = l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_))); let lifetime = if elided { None } else { Some(l.clean(cx)) }; BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) } } TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),"} {"_id":"doc-en-rust-4a91ec87f05a051392f37e4e4dbafa70dfffb23fac0db9b85aaf3b68a42f81de","title":"","text":" // ignore-tidy-linelength // edition:2018 #![feature(min_const_generics)]"} {"_id":"doc-en-rust-a268d5fab9546cb27d39d3975db33e3b4f963301bd04b9a460b723841e36a74a","title":"","text":"pub async fn mut_self(mut self, mut first: usize) {} } pub trait Pattern<'a> {} pub trait Trait {} // @has async_fn/fn.const_generics.html // @has - '//pre[@class=\"rust fn\"]' 'pub async fn const_generics(_: impl Trait)' pub async fn const_generics(_: impl Trait) {} // test that elided lifetimes are properly elided and not displayed as `'_` // regression test for #63037 // @has async_fn/fn.elided.html // @has - '//pre[@class=\"rust fn\"]' 'pub async fn elided(foo: &str) -> &str' pub async fn elided(foo: &str) -> &str {} // This should really be shown as written, but for implementation reasons it's difficult. // See `impl Clean for TyKind::Rptr`. // @has async_fn/fn.user_elided.html // @has - '//pre[@class=\"rust fn\"]' 'pub async fn user_elided(foo: &str) -> &str' pub async fn user_elided(foo: &'_ str) -> &str {} // @has async_fn/fn.static_trait.html // @has - '//pre[@class=\"rust fn\"]' 'pub async fn static_trait(foo: &str) -> Box' pub async fn static_trait(foo: &str) -> Box {} // @has async_fn/fn.lifetime_for_trait.html // @has - '//pre[@class=\"rust fn\"]' \"pub async fn lifetime_for_trait(foo: &str) -> Box\" pub async fn lifetime_for_trait(foo: &str) -> Box {} // @has async_fn/fn.elided_in_input_trait.html // @has - '//pre[@class=\"rust fn\"]' \"pub async fn elided_in_input_trait(t: impl Pattern<'_>)\" pub async fn elided_in_input_trait(t: impl Pattern<'_>) {} struct AsyncFdReadyGuard<'a, T> { x: &'a T } impl Foo { // @has async_fn/struct.Foo.html // @has - '//h4[@class=\"method\"]' 'pub async fn complicated_lifetimes( &self, context: &impl Bar) -> impl Iterator' pub async fn complicated_lifetimes(&self, context: &impl Bar) -> impl Iterator {} // taken from `tokio` as an example of a method that was particularly bad before // @has - '//h4[@class=\"method\"]' \"pub async fn readable(&self) -> Result, ()>\" pub async fn readable(&self) -> Result, ()> {} // @has - '//h4[@class=\"method\"]' \"pub async fn mut_self(&mut self)\" pub async fn mut_self(&mut self) {} } // test named lifetimes, just in case // @has async_fn/fn.named.html // @has - '//pre[@class=\"rust fn\"]' \"pub async fn named<'a, 'b>(foo: &'a str) -> &'b str\" pub async fn named<'a, 'b>(foo: &'a str) -> &'b str {} // @has async_fn/fn.named_trait.html // @has - '//pre[@class=\"rust fn\"]' \"pub async fn named_trait<'a, 'b>(foo: impl Pattern<'a>) -> impl Pattern<'b>\" pub async fn named_trait<'a, 'b>(foo: impl Pattern<'a>) -> impl Pattern<'b> {} "} {"_id":"doc-en-rust-40af51888d414ce47e94ddd943dd9e0d6766cc996fd0e84d600a8b25e806f5e6","title":"","text":"pub(super) fn recover_parens_around_for_head( &mut self, pat: P, expr: &Expr, begin_paren: Option, ) -> P { match (&self.token.kind, begin_paren) { (token::CloseDelim(token::Paren), Some(begin_par_sp)) => { self.bump(); let pat_str = self // Remove the `(` from the span of the pattern: .span_to_snippet(pat.span.trim_start(begin_par_sp).unwrap()) .unwrap_or_else(|_| pprust::pat_to_string(&pat)); self.struct_span_err(self.prev_token.span, \"unexpected closing `)`\") .span_label(begin_par_sp, \"opening `(`\") .span_suggestion( begin_par_sp.to(self.prev_token.span), \"remove parenthesis in `for` loop\", format!(\"{} in {}\", pat_str, pprust::expr_to_string(&expr)), // With e.g. `for (x) in y)` this would replace `(x) in y)` // with `x) in y)` which is syntactically invalid. // However, this is prevented before we get here. Applicability::MachineApplicable, ) .emit(); self.struct_span_err( MultiSpan::from_spans(vec![begin_par_sp, self.prev_token.span]), \"unexpected parenthesis surrounding `for` loop head\", ) .multipart_suggestion( \"remove parenthesis in `for` loop\", vec![(begin_par_sp, String::new()), (self.prev_token.span, String::new())], // With e.g. `for (x) in y)` this would replace `(x) in y)` // with `x) in y)` which is syntactically invalid. // However, this is prevented before we get here. Applicability::MachineApplicable, ) .emit(); // Unwrap `(pat)` into `pat` to avoid the `unused_parens` lint. pat.and_then(|pat| match pat.kind {"} {"_id":"doc-en-rust-aa24bc30bfec98a4998b9dba1240b81f4e406a25006ff061509c1067ef185af1","title":"","text":"self.check_for_for_in_in_typo(self.prev_token.span); let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; let pat = self.recover_parens_around_for_head(pat, &expr, begin_paren); let pat = self.recover_parens_around_for_head(pat, begin_paren); let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?; attrs.extend(iattrs);"} {"_id":"doc-en-rust-47eec409ff345db50af08de1df440f594fa49bb1cd1f4e549d86f1182abf3ccb","title":"","text":"for ( elem in vec ) { //~^ ERROR expected one of `)`, `,`, `@`, or `|`, found keyword `in` //~| ERROR unexpected closing `)` //~| ERROR unexpected parenthesis surrounding `for` loop head const RECOVERY_WITNESS: () = 0; //~ ERROR mismatched types } }"} {"_id":"doc-en-rust-cccdc52ce667d555aa1a3e3fac018f7153a489241a7e9f14432a59a1dae25613","title":"","text":"LL | for ( elem in vec ) { | ^^ expected one of `)`, `,`, `@`, or `|` error: unexpected closing `)` --> $DIR/recover-for-loop-parens-around-head.rs:10:23 error: unexpected parenthesis surrounding `for` loop head --> $DIR/recover-for-loop-parens-around-head.rs:10:9 | LL | for ( elem in vec ) { | --------------^ | | | opening `(` | help: remove parenthesis in `for` loop: `elem in vec` | ^ ^ | help: remove parenthesis in `for` loop | LL - for ( elem in vec ) { LL + for elem in vec { | error[E0308]: mismatched types --> $DIR/recover-for-loop-parens-around-head.rs:13:38"} {"_id":"doc-en-rust-d8da4f65c7bbba7ffdd3dac15d212458de7316067840ab80e7eb28684eacda6d","title":"","text":"kind_name = \"variant\"; } None => { let resolved_expected = fcx.infcx().ty_to_str(fcx.infcx().resolve_type_vars_if_possible(expected)); fcx.infcx().type_error_message_str(pat.span, |actual| { fcx.infcx().type_error_message_str_with_expected(pat.span, |expected, actual| { expected.map_default(~\"\", |&e| { fmt!(\"mismatched types: expected `%s` but found %s\", resolved_expected, actual)}, ~\"a structure pattern\", e, actual)})}, Some(expected), ~\"a structure pattern\", None); fcx.write_error(pat.id); kind_name = \"[error]\";"} {"_id":"doc-en-rust-ff21f95d3ef7c0d8c5ef6ef4724baa38ffc0cbf0f536b843de57faf06ddc9dc2","title":"","text":"kind_name = \"structure\"; } _ => { let resolved_expected = fcx.infcx().ty_to_str(fcx.infcx().resolve_type_vars_if_possible(expected)); fcx.infcx().type_error_message_str(pat.span, |actual| { fcx.infcx().type_error_message_str_with_expected(pat.span, |expected, actual| { expected.map_default(~\"\", |&e| { fmt!(\"mismatched types: expected `%s` but found %s\", resolved_expected, actual)}, ~\"an enum or structure pattern\", e, actual)})}, Some(expected), ~\"an enum or structure pattern\", None); fcx.write_error(pat.id); kind_name = \"[error]\";"} {"_id":"doc-en-rust-1a1293fab993832e7c8929416738d719d0c062b11c63ad55c4da9f27a105eca4","title":"","text":"for elts.each |elt| { check_pat(pcx, *elt, ty::mk_err()); } let actual = ty::mk_tup(tcx, elts.map(|pat_var| { fcx.node_ty(pat_var.id) })); // use terr_tuple_size if both types are tuples let type_error = match s { ty::ty_tup(ref ex_elts) =>"} {"_id":"doc-en-rust-7ceaa4c9d1d927f67158957c0cd4880e1e7a6449696e8ceaf1ddda7f1388cdfc","title":"","text":"found: e_count}), _ => ty::terr_mismatch }; fcx.infcx().report_mismatched_types(pat.span, expected, actual, &type_error); fcx.infcx().type_error_message_str_with_expected(pat.span, |expected, actual| { expected.map_default(~\"\", |&e| { fmt!(\"mismatched types: expected `%s` but found %s\", e, actual)})}, Some(expected), ~\"tuple\", Some(&type_error)); fcx.write_error(pat.id); } }"} {"_id":"doc-en-rust-d458e9d3932a09d841f262306c811c6034e36c677be9d951e60f287100b681bc","title":"","text":"for after.each |&elt| { check_pat(pcx, elt, ty::mk_err()); } let resolved_expected = fcx.infcx().ty_to_str(fcx.infcx().resolve_type_vars_if_possible(expected)); fcx.infcx().type_error_message_str(pat.span, |actual| { fmt!(\"mismatched types: expected `%s` but found %s\", resolved_expected, actual)}, ~\"a vector pattern\", None); fcx.infcx().type_error_message_str_with_expected( pat.span, |expected, actual| { expected.map_default(~\"\", |&e| { fmt!(\"mismatched types: expected `%s` but found %s\", e, actual)})}, Some(expected), ~\"a vector pattern\", None); fcx.write_error(pat.id); return; }"} {"_id":"doc-en-rust-33c3639ca082a0af4812ed5b6ec6c5314d139f36637f71115525fab5bcd9765f","title":"","text":"} _ => { check_pat(pcx, inner, ty::mk_err()); let resolved_expected = fcx.infcx().ty_to_str(fcx.infcx().resolve_type_vars_if_possible(expected)); fcx.infcx().type_error_message_str(span, |actual| { fmt!(\"mismatched types: expected `%s` but found %s\", resolved_expected, actual)}, fmt!(\"%s pattern\", match pointer_kind { Managed => \"an @-box\", Owned => \"a ~-box\", Borrowed => \"an &-pointer\" }), None); fcx.infcx().type_error_message_str_with_expected( span, |expected, actual| { expected.map_default(~\"\", |&e| { fmt!(\"mismatched types: expected `%s` but found %s\", e, actual)})}, Some(expected), fmt!(\"%s pattern\", match pointer_kind { Managed => \"an @-box\", Owned => \"a ~-box\", Borrowed => \"an &-pointer\" }), None); fcx.write_error(pat_id); } }"} {"_id":"doc-en-rust-5cc1fbade565b49e293edb42f6807ab0fe69ee765dcb2f5543b047c22d0617fe","title":"","text":"} } fn type_error_message_str(@mut self, sp: span, mk_msg: &fn(Option<~str>, ~str) -> ~str, actual_ty: ~str, err: Option<&ty::type_err>) { self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err) } fn type_error_message_str_with_expected(@mut self, sp: span, mk_msg: &fn(Option<~str>, ~str) -> ~str, expected_ty: Option, actual_ty: ~str, err: Option<&ty::type_err>) { debug!(\"hi! expected_ty = %?, actual_ty = %s\", expected_ty, actual_ty); fn type_error_message_str(@mut self, sp: span, mk_msg: &fn(~str) -> ~str, actual_ty: ~str, err: Option<&ty::type_err>) { let error_str = err.map_default(~\"\", |t_err| fmt!(\" (%s)\", ty::type_err_to_str(self.tcx, *t_err))); self.tcx.sess.span_err(sp, fmt!(\"%s%s\", mk_msg(actual_ty), error_str)); for err.each |err| { ty::note_and_explain_type_err(self.tcx, *err) let resolved_expected = expected_ty.map(|&e_ty| { self.resolve_type_vars_if_possible(e_ty) }); if !resolved_expected.map_default(false, |&e| { ty::type_is_error(e) }) { match resolved_expected { None => self.tcx.sess.span_err(sp, fmt!(\"%s%s\", mk_msg(None, actual_ty), error_str)), Some(e) => { self.tcx.sess.span_err(sp, fmt!(\"%s%s\", mk_msg(Some(self.ty_to_str(e)), actual_ty), error_str)); } } for err.each |err| { ty::note_and_explain_type_err(self.tcx, *err) } } } fn type_error_message(@mut self, sp: span, mk_msg: &fn(~str) -> ~str, actual_ty: ty::t, err: Option<&ty::type_err>) { fn type_error_message(@mut self, sp: span, mk_msg: &fn(~str) -> ~str, actual_ty: ty::t, err: Option<&ty::type_err>) { let actual_ty = self.resolve_type_vars_if_possible(actual_ty); // Don't report an error if actual type is ty_err."} {"_id":"doc-en-rust-a57c35b51771b5d1f7d29441997379cb36553c59e981c736a671f51c763005f3","title":"","text":"return; } self.type_error_message_str(sp, mk_msg, self.ty_to_str(actual_ty), err); self.type_error_message_str(sp, |_e, a| { mk_msg(a) }, self.ty_to_str(actual_ty), err); } fn report_mismatched_types(@mut self, sp: span, e: ty::t, a: ty::t,"} {"_id":"doc-en-rust-f750b244616500e8912d78a005e98d33727ad01dee93ad3053b6f463a60b69e1","title":"","text":"} match (true, false) { (true, false, false) => () //~ ERROR mismatched types: expected `(bool,bool)` but found `(bool,bool,bool)` (expected a tuple with 2 elements but found one with 3 elements) (true, false, false) => () //~ ERROR mismatched types: expected `(bool,bool)` but found tuple (expected a tuple with 2 elements but found one with 3 elements) } match (true, false) {"} {"_id":"doc-en-rust-23864763ab6335ffd2352fabba9e7e46292ba90459b872311d47e806c96bc657","title":"","text":" // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let (x, y) = (); //~ ERROR expected `()` but found tuple (types differ) return x; } No newline at end of file"} {"_id":"doc-en-rust-f821ac04436c3c4663eb14e4104a5cdba874afa78cfa8238b838a6dffb4fba96","title":"","text":") -> Bx::Value { let is_float = input_ty.is_floating_point(); let is_signed = input_ty.is_signed(); let is_unit = input_ty.is_unit(); match op { mir::BinOp::Add => if is_float { bx.fadd(lhs, rhs)"} {"_id":"doc-en-rust-ba24a8f07005549a93e131cdc83df50546afaca3bf7f7cc849e4add1a7e17265","title":"","text":"mir::BinOp::Shl => common::build_unchecked_lshift(bx, lhs, rhs), mir::BinOp::Shr => common::build_unchecked_rshift(bx, input_ty, lhs, rhs), mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt | mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_unit { bx.cx().const_bool(match op { mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false, mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true, _ => unreachable!() }) } else if is_float { mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_float { bx.fcmp( base::bin_op_to_fcmp_predicate(op.to_hir_binop()), lhs, rhs"} {"_id":"doc-en-rust-3c3606417ffd533741f3ac44d303b4826e50fcd576710f342e8a814343f73db4","title":"","text":" Subproject commit 4f6f264c305ea30f1de90ad0c2f341e84d972b2e Subproject commit d77fe6c63ca4c50b207a1161def90c9e57368d5b "} {"_id":"doc-en-rust-246333728763704a36a28652dbc36387bcd5481c7accdb152095c8c402ff7c0d","title":"","text":"self.is_keyword_ahead(1, &[ kw::Impl, kw::Const, kw::Async, kw::Fn, kw::Unsafe, kw::Extern,"} {"_id":"doc-en-rust-45281c920829a23b51bb8889948b51c42919bc6eb4a6127a2cd5d634557533b5","title":"","text":" // Ensure that `default async fn` will parse. // See issue #63716 for details. // check-pass // edition:2018 #![feature(specialization)] fn main() {} #[cfg(FALSE)] impl Foo for Bar { default async fn baz() {} } "} {"_id":"doc-en-rust-168d6681f1c3a084505faa883126c4da3b86305565512c8e5e39bde6b51704c0","title":"","text":"/// [`len`]: #method.len /// /// Note: This example shows the internals of `&str`. `unsafe` should not be /// used to get a string slice under normal circumstances. Use `as_slice` /// used to get a string slice under normal circumstances. Use `as_str` /// instead. #[stable(feature = \"rust1\", since = \"1.0.0\")] mod prim_str { }"} {"_id":"doc-en-rust-2f96c1f311b96c456cecf0756f7741029500b0dc52c18116163b3812f932c116","title":"","text":" use rustc_data_structures::fx::FxHashMap; use syntax_pos::Span; use crate::print::pprust::token_to_string;"} {"_id":"doc-en-rust-37c4073582fc1ab8eb98a2609fed7f0461b7e3adf25e6c48aba770b334eb9200","title":"","text":"unmatched_braces: Vec::new(), matching_delim_spans: Vec::new(), last_unclosed_found_span: None, last_delim_empty_block_spans: FxHashMap::default() }; let res = tt_reader.parse_all_token_trees(); (res, tt_reader.unmatched_braces)"} {"_id":"doc-en-rust-4245ef0f1f901dfef27bbef2f27cc664a606d2c5798dcf36db28a1097f70abd3","title":"","text":"/// Used only for error recovery when arriving to EOF with mismatched braces. matching_delim_spans: Vec<(token::DelimToken, Span, Span)>, last_unclosed_found_span: Option, last_delim_empty_block_spans: FxHashMap } impl<'a> TokenTreesReader<'a> {"} {"_id":"doc-en-rust-1a35995d728ed5c55be65d41d2b0d294bbb03101c3b73c8b053fbafd893a4137","title":"","text":"// Correct delimiter. token::CloseDelim(d) if d == delim => { let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); let close_brace_span = self.token.span; if tts.is_empty() { let empty_block_span = open_brace_span.to(close_brace_span); self.last_delim_empty_block_spans.insert(delim, empty_block_span); } if self.open_braces.len() == 0 { // Clear up these spans to avoid suggesting them as we've found // properly matched delimiters so far for an entire block. self.matching_delim_spans.clear(); } else { self.matching_delim_spans.push( (open_brace, open_brace_span, self.token.span), (open_brace, open_brace_span, close_brace_span), ); } // Parse the close delimiter."} {"_id":"doc-en-rust-4e982f59730532b6f4ae1b31339486d60005d762c2b07e82d7bf04a5fead4b88","title":"","text":"tts.into() ).into()) }, token::CloseDelim(_) => { token::CloseDelim(delim) => { // An unexpected closing delimiter (i.e., there is no // matching opening delimiter). let token_str = token_to_string(&self.token); let msg = format!(\"unexpected close delimiter: `{}`\", token_str); let mut err = self.string_reader.sess.span_diagnostic .struct_span_err(self.token.span, &msg); if let Some(span) = self.last_delim_empty_block_spans.remove(&delim) { err.span_label( span, \"this block is empty, you might have not meant to close it\" ); } err.span_label(self.token.span, \"unexpected close delimiter\"); Err(err) },"} {"_id":"doc-en-rust-e0482b0a92b5a2b929ac65d02b58331b6138d107c81be47c0a64e8b9218e8059","title":"","text":"} /// A delimiter token. #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)] pub enum DelimToken { /// A round parenthesis (i.e., `(` or `)`). Paren,"} {"_id":"doc-en-rust-e6eba6d6ea88bbc24d24aba7234fdc04fb5152084551c322021d3622dea1a75e","title":"","text":" fn main() { } let _ = (); } //~ ERROR unexpected close delimiter "} {"_id":"doc-en-rust-73005b98d996fdb074f4686c660dc9fa916168d4856b29cacc4c2af1d022dbad","title":"","text":" error: unexpected close delimiter: `}` --> $DIR/mismatched-delim-brace-empty-block.rs:5:1 | LL | fn main() { | ___________- LL | | LL | | } | |_- this block is empty, you might have not meant to close it LL | let _ = (); LL | } | ^ unexpected close delimiter error: aborting due to previous error "} {"_id":"doc-en-rust-5b5d9d9f627d0ad7151c2159b58ce7954b4d7912704d14f31ac2af1e9deaf5bb","title":"","text":" // This test ensures that `--` (double-hyphen) is correctly converted into `–` (dash). #![crate_name = \"foo\"] // @has 'foo/index.html' '//*[@class=\"desc docblock-short\"]' '–' // @has 'foo/struct.Bar.html' '//*[@class=\"docblock\"]' '–' /// -- pub struct Bar; "} {"_id":"doc-en-rust-29fdd2a29c0ad48e1d611d3b11a3e5840b4e853b57a399b7e3c513c8f934e34a","title":"","text":"use crate::hir::def_id::DefId; use crate::hir; use crate::ty::TyCtxt; use syntax_pos::symbol::{sym, Symbol}; use syntax_pos::symbol::Symbol; use crate::hir::map::blocks::FnLikeNode; use syntax::attr;"} {"_id":"doc-en-rust-fd0ec0ab269fa739370b4594d1c6b1f5d43073b0e124d711f6a307f2bed314f4","title":"","text":"self.is_const_fn_raw(def_id) && match self.is_unstable_const_fn(def_id) { Some(feature_name) => { // has a `rustc_const_unstable` attribute, check whether the user enabled the // corresponding feature gate, const_constructor is not a lib feature, so has // to be checked separately. // corresponding feature gate. self.features() .declared_lib_features .iter() .any(|&(sym, _)| sym == feature_name) || (feature_name == sym::const_constructor && self.features().const_constructor) }, // functions without const stability are either stable user written // const fn or the user is using feature gates and we thus don't"} {"_id":"doc-en-rust-2656cc6b0172a9991ac736f35737855c5f22f478f343fb0201dcae568b53c764","title":"","text":"/// Whether the `def_id` is an unstable const fn and what feature gate is necessary to enable it pub fn is_unstable_const_fn(self, def_id: DefId) -> Option { if self.is_constructor(def_id) { Some(sym::const_constructor) } else if self.is_const_fn_raw(def_id) { if self.is_const_fn_raw(def_id) { self.lookup_stability(def_id)?.const_stability } else { None"} {"_id":"doc-en-rust-b4f395b6b3fb22f6aca7b6104177b94537af477301666425f5f8ca9484c118cf","title":"","text":"(accepted, macros_in_extern, \"1.40.0\", Some(49476), None), /// Allows future-proofing enums/structs with the `#[non_exhaustive]` attribute (RFC 2008). (accepted, non_exhaustive, \"1.40.0\", Some(44109), None), /// Allows calling constructor functions in `const fn`. (accepted, const_constructor, \"1.40.0\", Some(61456), None), // ------------------------------------------------------------------------- // feature-group-end: accepted features"} {"_id":"doc-en-rust-f274508619a7be8465dd90e0e5d46d78fca673c78f059fa23e92203c5704a5cc","title":"","text":"/// Allows the user of associated type bounds. (active, associated_type_bounds, \"1.34.0\", Some(52662), None), /// Allows calling constructor functions in `const fn`. (active, const_constructor, \"1.37.0\", Some(61456), None), /// Allows `if/while p && let q = r && ...` chains. (active, let_chains, \"1.37.0\", Some(53667), None),"} {"_id":"doc-en-rust-7fe136a4757517c91e8107e0a7ddde2d68a0e34c10703515a80143a5768a6f93","title":"","text":"#![cfg_attr(const_fn, feature(const_fn))] #![feature(const_constructor)] // Ctor(..) is transformed to Ctor { 0: ... } in HAIR lowering, so directly // calling constructors doesn't require them to be const."} {"_id":"doc-en-rust-38aa805b8c99f9e778f7ceb095ea47edb7ac333c864d58bc4ea0e4739c759902","title":"","text":" // revisions: min_const_fn const_fn // run-pass #![cfg_attr(const_fn, feature(const_fn))] trait ConstDefault { const DEFAULT: Self; } #[derive(PartialEq)] enum E { V(i32), W(usize), } impl ConstDefault for E { const DEFAULT: Self = Self::V(23); } impl ConstDefault for Option { const DEFAULT: Self = Self::Some(23); } impl E { const NON_DEFAULT: Self = Self::W(12); const fn local_fn() -> Self { Self::V(23) } } const fn explicit_qpath() -> E { let _x = >::Some(23); ::W(12) } fn main() { assert!(E::DEFAULT == E::local_fn()); assert!(Option::DEFAULT == Some(23)); assert!(E::NON_DEFAULT == explicit_qpath()); } "} {"_id":"doc-en-rust-115bf578b0dd752af34ce5ebb7a7e3e2fe3a4207a17937cc772d68c25794a7b5","title":"","text":" error: `std::prelude::v1::Some` is not yet stable as a const fn --> $DIR/feature-gate-const_constructor.rs:9:37 | LL | const EXTERNAL_CONST: Option = {Some}(1); | ^^^^^^^^^ | = help: add `#![feature(const_constructor)]` to the crate attributes to enable error: `E::V` is not yet stable as a const fn --> $DIR/feature-gate-const_constructor.rs:12:24 | LL | const LOCAL_CONST: E = {E::V}(1); | ^^^^^^^^^ | = help: add `#![feature(const_constructor)]` to the crate attributes to enable error: `std::prelude::v1::Some` is not yet stable as a const fn --> $DIR/feature-gate-const_constructor.rs:17:13 | LL | let _ = {Some}(1); | ^^^^^^^^^ | = help: add `#![feature(const_constructor)]` to the crate attributes to enable error: `E::V` is not yet stable as a const fn --> $DIR/feature-gate-const_constructor.rs:23:13 | LL | let _ = {E::V}(1); | ^^^^^^^^^ | = help: add `#![feature(const_constructor)]` to the crate attributes to enable error: aborting due to 4 previous errors "} {"_id":"doc-en-rust-d936a584a4889ab2ea48d1d9b608322fb57dbe4f1499a6897f24286665501db1","title":"","text":" // revisions: min_const_fn const_fn #![cfg_attr(const_fn, feature(const_fn))] enum E { V(i32), } const EXTERNAL_CONST: Option = {Some}(1); //[min_const_fn]~^ ERROR is not yet stable as a const fn //[const_fn]~^^ ERROR is not yet stable as a const fn const LOCAL_CONST: E = {E::V}(1); //[min_const_fn]~^ ERROR is not yet stable as a const fn //[const_fn]~^^ ERROR is not yet stable as a const fn const fn external_fn() { let _ = {Some}(1); //[min_const_fn]~^ ERROR is not yet stable as a const fn //[const_fn]~^^ ERROR is not yet stable as a const fn } const fn local_fn() { let _ = {E::V}(1); //[min_const_fn]~^ ERROR is not yet stable as a const fn //[const_fn]~^^ ERROR is not yet stable as a const fn } fn main() {} "} {"_id":"doc-en-rust-d920f768e49f913738e0ea16ac1ad0e148aaaa50e99212d891bef329503032a3","title":"","text":"/// Free-form case. Only for errors that are never caught! Unsupported(String), /// FIXME(#64506) Error used to work around accessing projections of /// uninhabited types. UninhabitedValue, // -- Everything below is not categorized yet -- FunctionAbiMismatch(Abi, Abi), FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>),"} {"_id":"doc-en-rust-f6f65001745e41b88672a537ce1c60ce7e8d535ecb657c8dc293e5ae0936f3e1","title":"","text":"not a power of two\"), Unsupported(ref msg) => write!(f, \"{}\", msg), UninhabitedValue => write!(f, \"tried to use an uninhabited value\"), } } }"} {"_id":"doc-en-rust-08b0c6f9bfca2179377aef2639f61c266eee6dc33711fd74c5362798c0136265","title":"","text":"}); (present_variants.next(), present_variants.next()) }; if present_first.is_none() { let present_first = match present_first { present_first @ Some(_) => present_first, // Uninhabited because it has no variants, or only absent ones. return tcx.layout_raw(param_env.and(tcx.types.never)); } None if def.is_enum() => return tcx.layout_raw(param_env.and(tcx.types.never)), // if it's a struct, still compute a layout so that we can still compute the // field offsets None => Some(VariantIdx::new(0)), }; let is_struct = !def.is_enum() || // Only one variant is present."} {"_id":"doc-en-rust-fba12061c3799f8675c3d25d072cf871d7eac4548c0c01dbcb489a59a650f05b","title":"","text":"use rustc::mir::interpret::truncate; use rustc::ty::{self, Ty}; use rustc::ty::layout::{ self, Size, Abi, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx, PrimitiveExt self, Size, Align, LayoutOf, TyLayout, HasDataLayout, VariantIdx, PrimitiveExt }; use rustc::ty::TypeFoldable;"} {"_id":"doc-en-rust-0540898e4780b044241423ebef9cbd6ef84cce6045a68d6b67483c52c74a2900","title":"","text":"layout::FieldPlacement::Array { stride, .. } => { let len = base.len(self)?; if field >= len { // This can be violated because this runs during promotion on code where the // type system has not yet ensured that such things don't happen. // This can be violated because the index (field) can be a runtime value // provided by the user. debug!(\"tried to access element {} of array/slice with length {}\", field, len); throw_panic!(BoundsCheck { len, index: field }); } stride * field } layout::FieldPlacement::Union(count) => { // FIXME(#64506) `UninhabitedValue` can be removed when this issue is resolved if base.layout.abi == Abi::Uninhabited { throw_unsup!(UninhabitedValue); } assert!(field < count as u64, \"Tried to access field {} of union with {} fields\", field, count); \"Tried to access field {} of union {:#?} with {} fields\", field, base.layout, count); // Offset is always 0 Size::from_bytes(0) }"} {"_id":"doc-en-rust-2b9a3acfd66f154d17c0584b8c480ee2a79febde8f85b72602d6477e11df1803","title":"","text":"pub fn offset(&self, i: usize) -> Size { match *self { FieldPlacement::Union(_) => Size::ZERO, FieldPlacement::Union(count) => { assert!(i < count, \"Tried to access field {} of union with {} fields\", i, count); Size::ZERO }, FieldPlacement::Array { stride, count } => { let i = i as u64; assert!(i < count);"} {"_id":"doc-en-rust-3fdbc96c74303232efc439253fd4e7ac751317187c64f6daf2d211c8d64e3a13","title":"","text":" // check-pass #[derive(Copy, Clone)] pub struct ChildStdin { inner: AnonPipe, } #[derive(Copy, Clone)] enum AnonPipe {} const FOO: () = { union Foo { a: ChildStdin, b: (), } let x = unsafe { Foo { b: () }.a }; let x = &x.inner; }; fn main() {} "} {"_id":"doc-en-rust-532bf128fe4a56589570e56a2f6784b1397b90d91303efd80a076b57f1584926","title":"","text":"if let hir::ExprKind::Index(ref base, ref index) = e.kind { let mut tables = self.fcx.tables.borrow_mut(); // All valid indexing looks like this; might encounter non-valid indexes at this point if let ty::Ref(_, base_ty, _) = tables.expr_ty_adjusted(&base).kind { let index_ty = tables.expr_ty_adjusted(&index); // All valid indexing looks like this; might encounter non-valid indexes at this point. let base_ty = tables.expr_ty_adjusted_opt(&base).map(|t| &t.kind); if base_ty.is_none() { // When encountering `return [0][0]` outside of a `fn` body we can encounter a base // that isn't in the type table. We assume more relevant errors have already been // emitted, so we delay an ICE if none have. (#64638) self.tcx().sess.delay_span_bug(e.span, &format!(\"bad base: `{:?}`\", base)); } if let Some(ty::Ref(_, base_ty, _)) = base_ty { let index_ty = tables.expr_ty_adjusted_opt(&index).unwrap_or_else(|| { // When encountering `return [0][0]` outside of a `fn` body we would attempt // to access an unexistend index. We assume that more relevant errors will // already have been emitted, so we only gate on this with an ICE if no // error has been emitted. (#64638) self.tcx().sess.delay_span_bug( e.span, &format!(\"bad index {:?} for base: `{:?}`\", index, base), ); self.fcx.tcx.types.err }); let index_ty = self.fcx.resolve_vars_if_possible(&index_ty); if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize {"} {"_id":"doc-en-rust-858f7e3d8c3dcf01e50a75b6f675a72c1ce22468a44ee7a2c51204c453134f1e","title":"","text":" enum Bug { V1 = return [0][0] //~ERROR return statement outside of function body } fn main() {} "} {"_id":"doc-en-rust-61d376eca67fdcbe4e2de57759e91b76578bc417f82eea824d84302de4c2e6e0","title":"","text":" error[E0572]: return statement outside of function body --> $DIR/issue-64620.rs:2:10 | LL | V1 = return [0][0] | ^^^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0572`. "} {"_id":"doc-en-rust-d51a1e608437a95bb1e11700dcd4efb444ba2f3fc2d232940a2e2d1668db58db","title":"","text":"// ignore it. We can't put it on the struct header anyway. RegionKind::ReLateBound(..) => false, // This can appear in `where Self: ` bounds (#64855): // // struct Bar(::Type) where Self: ; // struct Baz<'a>(&'a Self) where Self: ; RegionKind::ReEmpty => false, // These regions don't appear in types from type declarations: RegionKind::ReEmpty | RegionKind::ReErased RegionKind::ReErased | RegionKind::ReClosureBound(..) | RegionKind::ReScope(..) | RegionKind::ReVar(..)"} {"_id":"doc-en-rust-61b75c04e08bb651c35abcf86c09d38cc503729fb9c030159498d3a0c545d5df","title":"","text":" // check-pass pub struct Bar<'a>(&'a Self) where Self: ; fn main() {} "} {"_id":"doc-en-rust-47a5d0023559d51a4e1f5ac66236ffa54bab7506fd14821fa53daa58a7e2d71e","title":"","text":" pub trait Foo { type Type; } pub struct Bar(::Type) where Self: ; //~^ ERROR the trait bound `Bar: Foo` is not satisfied fn main() {} "} {"_id":"doc-en-rust-2678476562124cd1c9742b18ce499ad1c251bb16a880f03ccac01105139d18c3","title":"","text":" error[E0277]: the trait bound `Bar: Foo` is not satisfied --> $DIR/issue-64855.rs:5:19 | LL | pub struct Bar(::Type) where Self: ; | ^^^^^^^^^^^^^^^^^^^ the trait `Foo` is not implemented for `Bar` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-63e0a0d2f711969d4acedf1dc4162d0c959ae9efae2e7f155eb1cc5952248cf2","title":"","text":"use syntax::feature_gate::{GateIssue, emit_feature_err}; use syntax::source_map::{DUMMY_SP, original_sp}; use syntax::symbol::{kw, sym}; use syntax::util::parser::ExprPrecedence; use std::cell::{Cell, RefCell, Ref, RefMut}; use std::collections::hash_map::Entry;"} {"_id":"doc-en-rust-c20b1ea591ff2049fad5b947da81d61eeeeaf79d431711e54dcf5d8c8f76da94","title":"","text":"let max_len = receiver.rfind(\".\").unwrap(); format!(\"{}{}\", &receiver[..max_len], method_call) } else { format!(\"{}{}\", receiver, method_call) if expr.precedence().order() < ExprPrecedence::MethodCall.order() { format!(\"({}){}\", receiver, method_call) } else { format!(\"{}{}\", receiver, method_call) } }; Some(if is_struct_pat_shorthand_field { format!(\"{}: {}\", receiver, sugg)"} {"_id":"doc-en-rust-2d4a7f28d276ca119d489a6e4641bad53b8e1287c9c6946a7da91f91efde72b5","title":"","text":"| ^^^^^^^^^^ | | | expected struct `std::vec::Vec`, found reference | help: try using a conversion method: `&[1, 2, 3].to_vec()` | help: try using a conversion method: `(&[1, 2, 3]).to_vec()` | = note: expected type `std::vec::Vec` found type `&[{integer}; 3]`"} {"_id":"doc-en-rust-1f3dd43498bbebd7cd4af403cb8eb1e2b0b6632d14d79f737e41f180fb936515","title":"","text":"| ^^^^^ | | | cyclic type of infinite size | help: try using a conversion method: `box x.to_string()` | help: try using a conversion method: `(box x).to_string()` error[E0055]: reached the recursion limit while auto-dereferencing `Foo` --> $DIR/infinite-autoderef.rs:25:5"} {"_id":"doc-en-rust-7a64cdbb02cb729969aafd3e76d316e15c312fe7dd0699b7ff0877fa936f19e4","title":"","text":"x //~ ERROR mismatched types } fn f() -> String { 1+2 //~ ERROR mismatched types } fn g() -> String { -2 //~ ERROR mismatched types } fn main() {}"} {"_id":"doc-en-rust-4189669a9b704d521d6a2585a58e1ce307432411d8ebfa119e1b352b3bd5c06d","title":"","text":"= note: expected type `X, _>` found type `X, _>` error: aborting due to 6 previous errors error[E0308]: mismatched types --> $DIR/abridged.rs:54:5 | LL | fn f() -> String { | ------ expected `std::string::String` because of return type LL | 1+2 | ^^^ | | | expected struct `std::string::String`, found integer | help: try using a conversion method: `(1+2).to_string()` | = note: expected type `std::string::String` found type `{integer}` error[E0308]: mismatched types --> $DIR/abridged.rs:59:5 | LL | fn g() -> String { | ------ expected `std::string::String` because of return type LL | -2 | ^^ | | | expected struct `std::string::String`, found integer | help: try using a conversion method: `(-2).to_string()` | = note: expected type `std::string::String` found type `{integer}` error: aborting due to 8 previous errors For more information about this error, try `rustc --explain E0308`."} {"_id":"doc-en-rust-dfd4b6ed12a512b0ad5d405ee5e40de1c552ee424d616d34f5b0bc6c0d5eca00","title":"","text":"| ^^^^^ | | | cyclic type of infinite size | help: try using a conversion method: `box g.to_string()` | help: try using a conversion method: `(box g).to_string()` error: aborting due to previous error"} {"_id":"doc-en-rust-338c8bce4c1f264bb1297d7e376d92ac27c50ac93de5f77356d99ef7476f61bc","title":"","text":"| ^^^^^ | | | cyclic type of infinite size | help: try using a conversion method: `box f.to_string()` | help: try using a conversion method: `(box f).to_string()` error: aborting due to previous error"} {"_id":"doc-en-rust-9fd209d83970c26e4d05778f0f8ce53625921116be170fcdba123dfb236d1849","title":"","text":"| ^^^^^ | | | cyclic type of infinite size | help: try using a conversion method: `box f.to_string()` | help: try using a conversion method: `(box f).to_string()` error[E0308]: mismatched types --> $DIR/coerce-suggestions.rs:21:9"} {"_id":"doc-en-rust-220193a55b141ceaa46a7ce02b7bc391bd2af45b4b632737c4f0ba2e07a7e878","title":"","text":"param_env: ty::ParamEnv<'tcx>, } impl<'tcx> TransferFunction<'_, '_, 'tcx> { /// Returns `true` if this borrow would allow mutation of the `borrowed_place`. fn borrow_allows_mutation( &self, kind: mir::BorrowKind, borrowed_place: &mir::Place<'tcx>, ) -> bool { let borrowed_ty = borrowed_place.ty(self.body, self.tcx).ty; // Zero-sized types cannot be mutated, since there is nothing inside to mutate. // // FIXME: For now, we only exempt arrays of length zero. We need to carefully // consider the effects before extending this to all ZSTs. if let ty::Array(_, len) = borrowed_ty.kind { if len.try_eval_usize(self.tcx, self.param_env) == Some(0) { return false; } } match kind { mir::BorrowKind::Mut { .. } => true, | mir::BorrowKind::Shared | mir::BorrowKind::Shallow | mir::BorrowKind::Unique => !borrowed_ty.is_freeze(self.tcx, self.param_env, DUMMY_SP), } } } impl<'tcx> Visitor<'tcx> for TransferFunction<'_, '_, 'tcx> { fn visit_rvalue( &mut self,"} {"_id":"doc-en-rust-dca4cb240dcb0610b0f1941d941a3f1d330efcacd1d3f388d48903bc44ac287b","title":"","text":"location: Location, ) { if let mir::Rvalue::Ref(_, kind, ref borrowed_place) = *rvalue { let is_mut = match kind { mir::BorrowKind::Mut { .. } => true, | mir::BorrowKind::Shared | mir::BorrowKind::Shallow | mir::BorrowKind::Unique => { !borrowed_place .ty(self.body, self.tcx) .ty .is_freeze(self.tcx, self.param_env, DUMMY_SP) } }; if is_mut { if self.borrow_allows_mutation(kind, borrowed_place) { match borrowed_place.base { mir::PlaceBase::Local(borrowed_local) if !borrowed_place.is_indirect() => self.trans.gen(borrowed_local),"} {"_id":"doc-en-rust-5ddc3d505374432ce8029d0bacab9e15108bee83e77774faded319c0a34aaf6c","title":"","text":"item.tcx, item.body, item.def_id, &[], &item.tcx.get_attrs(item.def_id), &dead_unwinds, old_dataflow::IndirectlyMutableLocals::new(item.tcx, item.body, item.param_env), |_, local| old_dataflow::DebugFormatted::new(&local),"} {"_id":"doc-en-rust-d69094cb29d3bd698422dbe6d3809796d0da6d314b5bff965131d47f53d27e5c","title":"","text":" // Several variants of #64945. // This struct is not important, we just use it to put `T` and `'a` in scope for our associated // consts. struct Generic<'a, T>(std::marker::PhantomData<&'a T>); impl<'a, T: 'static> Generic<'a, T> { const EMPTY_SLICE: &'a [T] = { let x: &'a [T] = &[]; x }; const EMPTY_SLICE_REF: &'a &'static [T] = { let x: &'static [T] = &[]; &x //~^ ERROR `x` does not live long enough }; } static mut INTERIOR_MUT_AND_DROP: &'static [std::cell::RefCell>] = { let x: &[_] = &[]; x }; static mut INTERIOR_MUT_AND_DROP_REF: &'static &'static [std::cell::RefCell>] = { let x: &[_] = &[]; &x //~^ ERROR `x` does not live long enough }; fn main() {} "} {"_id":"doc-en-rust-cf16438859a84b68c6ea8afd4843e6f662cb4e8f5b6be4404cc1c7eae98ff1ed","title":"","text":" error[E0597]: `x` does not live long enough --> $DIR/generic-slice.rs:15:9 | LL | impl<'a, T: 'static> Generic<'a, T> { | -- lifetime `'a` defined here ... LL | &x | ^^ | | | borrowed value does not live long enough | using this value as a constant requires that `x` is borrowed for `'a` LL | LL | }; | - `x` dropped here while still borrowed error[E0597]: `x` does not live long enough --> $DIR/generic-slice.rs:27:5 | LL | &x | ^^ | | | borrowed value does not live long enough | using this value as a static requires that `x` is borrowed for `'static` LL | LL | }; | - `x` dropped here while still borrowed error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0597`. "} {"_id":"doc-en-rust-8ab70ad34cc6d8eac63333e0bb2a2c2a60261fd135b378d849f7fdc58551a14d","title":"","text":"}); if (e.which === 38) { // up if (!actives[currentTab].length || !actives[currentTab][0].previousElementSibling) { return; if (e.ctrlKey) { // Going through result tabs. printTab(currentTab > 0 ? currentTab - 1 : 2); } else { if (!actives[currentTab].length || !actives[currentTab][0].previousElementSibling) { return; } addClass(actives[currentTab][0].previousElementSibling, \"highlighted\"); removeClass(actives[currentTab][0], \"highlighted\"); } addClass(actives[currentTab][0].previousElementSibling, \"highlighted\"); removeClass(actives[currentTab][0], \"highlighted\"); e.preventDefault(); } else if (e.which === 40) { // down if (!actives[currentTab].length) { if (e.ctrlKey) { // Going through result tabs. printTab(currentTab > 1 ? 0 : currentTab + 1); } else if (!actives[currentTab].length) { var results = document.getElementById(\"results\").childNodes; if (results.length > 0) { var res = results[currentTab].getElementsByClassName(\"result\");"} {"_id":"doc-en-rust-178cc3beda4c5c3a777af8de071de7f2aecb00da899eca2808f291ef1f261327","title":"","text":"document.location.href = actives[currentTab][0].getElementsByTagName(\"a\")[0].href; } } else if (e.which === 9) { // tab if (e.shiftKey) { printTab(currentTab > 0 ? currentTab - 1 : 2); } else { printTab(currentTab > 1 ? 0 : currentTab + 1); } e.preventDefault(); } else if (e.which === 16) { // shift // Does nothing, it's just to avoid losing \"focus\" on the highlighted element. } else if (actives[currentTab].length > 0) {"} {"_id":"doc-en-rust-bf9ffc3e1b9e11c5c67bc4f92133d28a604a0910661035be535f7b97ec6271ff","title":"","text":"[\"T\", \"Focus the theme picker menu\"], [\"↑\", \"Move up in search results\"], [\"↓\", \"Move down in search results\"], [\"↹\", \"Switch tab\"], [\"ctrl + ↑ / ↓\", \"Switch result tab\"], [\"⏎\", \"Go to active search result\"], [\"+\", \"Expand all sections\"], [\"-\", \"Collapse all sections\"], ].map(x => \"
\" + x[0] + \"
\" + x[1] + \"
\").join(\"\");
].map(x => \"
\" + x[0].split(\" \") .map((y, index) => (index & 1) === 0 ? \"\" + y + \"\" : y) .join(\"\") + \"
\" + x[1] + \"
\").join(\"\");
var div_shortcuts = document.createElement(\"div\"); addClass(div_shortcuts, \"shortcuts\"); div_shortcuts.innerHTML = \"

Keyboard Shortcuts

\" + shortcuts + \"
\";"} {"_id":"doc-en-rust-3dd1326193118104cc6b62b70c4c1acbc68b527d7ab49780c3836f6c96b31068","title":"","text":"cc @{}, do you think you would have time to do the follow-up work? If so, that would be great! cc @{}, the PR reviewer, and @rust-lang/compiler -- nominating for prioritization. cc @{}, the PR reviewer, and nominating for compiler team prioritization. ''').format( relevant_pr_number, tool, status_description,"} {"_id":"doc-en-rust-4b7bc8db7856bed78f9929f52e1e0c5b667ce24c0848ed3544f404deb7485d2c","title":"","text":"declare_lint! { pub CONST_ERR, Deny, \"constant evaluation detected erroneous expression\" \"constant evaluation detected erroneous expression\", report_in_external_macro: true } declare_lint! {"} {"_id":"doc-en-rust-c9cded4a032def2084746330614b38e7d109d0284b08cee80cf0df223b97a22c","title":"","text":" #![feature(allow_internal_unstable)] // Macro to help ensure CONST_ERR lint errors // are not silenced in external macros. // https://github.com/rust-lang/rust/issues/65300 #[macro_export] #[allow_internal_unstable(type_ascription)] macro_rules! static_assert { ($test:expr) => { #[allow(dead_code)] const _: () = [()][!($test: bool) as usize]; } } "} {"_id":"doc-en-rust-4b39e5b7cd0f2d3517519bd53dfbe735ba7409d0bf1ebfc72cb1aaca57a7fc3f","title":"","text":" // edition:2018 // aux-build:external_macro.rs // Ensure that CONST_ERR lint errors // are not silenced in external macros. // https://github.com/rust-lang/rust/issues/65300 extern crate external_macro; use external_macro::static_assert; fn main() { static_assert!(2 + 2 == 5); //~ ERROR } "} {"_id":"doc-en-rust-ec44a9f04acb06c57a7bea8a5486972794ba2ff1c2e317822b5122cd6ca2cb48","title":"","text":" error: any use of this value will cause an error --> $DIR/const-external-macro-const-err.rs:12:5 | LL | static_assert!(2 + 2 == 5); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ index out of bounds: the len is 1 but the index is 1 | = note: `#[deny(const_err)]` on by default = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info) error: aborting due to previous error "} {"_id":"doc-en-rust-0159e86c1e4cc0ddafde0bc02a69ae5897df9a6cbfe268f4ee37c7058f8f08ad","title":"","text":" Subproject commit 5cb983338e924ec85898880d60e65f2a1291b7be Subproject commit 52cebb1f8f8789b97d243c07bf4c961ca0017f7b "} {"_id":"doc-en-rust-9e597d288eb14fbc0185e3cab9554952acdf160c23579bcb59f08cd7e6036992","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] impl fmt::Debug for RangeFull { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(\"..\", fmt) write!(fmt, \"..\") } }"} {"_id":"doc-en-rust-1d1e5a17691a0410b33ff7bd6b7ff8c9ee8c8b0a9af9a51b7c312d4fcf3c04d8","title":"","text":" Subproject commit 941968db2fd9c85788a4f971c8e425d46b4cb734 Subproject commit 75a5f9236c689a547fe207a10854f0775bce7937 "} {"_id":"doc-en-rust-9181f8c06acf7f5b737614e904b782ca720a8281bf0d868e06aab2378d904c03","title":"","text":"\"regex-syntax\", \"semver\", \"serde\", \"smallvec 0.6.10\", \"smallvec 1.0.0\", \"toml\", \"unicode-normalization\", \"url 2.1.0\","} {"_id":"doc-en-rust-1c3c86032b6d4b0b3010040adbddb11e9a6342a38fabd6635a02d317a36a9b44","title":"","text":"let host_libs = builder .stage_out(compiler, Mode::ToolRustc) .join(builder.cargo_dir()); let target_libs = builder .stage_out(compiler, Mode::ToolRustc) .join(&self.host) .join(builder.cargo_dir()); cargo.env(\"HOST_LIBS\", host_libs); cargo.env(\"TARGET_LIBS\", target_libs); // clippy tests need to find the driver cargo.env(\"CLIPPY_DRIVER_PATH\", clippy);"} {"_id":"doc-en-rust-7f211250bedb527f98283dbabcc8512b7d425ee03cd74f737d62be3cab55ba37","title":"","text":" Subproject commit c8e3cfbdd997839c771ca32c7ac860fe95149a04 Subproject commit 3abdd2f1ced4cf3a44c7de88c5e39b3bb5037c4d "} {"_id":"doc-en-rust-2c6b723cb2a432797a4e330183b4fe5e06c0861b84759c866ac1178bbb334145","title":"","text":"let result = match (&desc.should_panic, task_result) { (&ShouldPanic::No, Ok(())) | (&ShouldPanic::Yes, Err(_)) => TestResult::TrOk, (&ShouldPanic::YesWithMessage(msg), Err(ref err)) => { if err let maybe_panic_str = err .downcast_ref::() .map(|e| &**e) .or_else(|| err.downcast_ref::<&'static str>().map(|e| *e)) .map(|e| e.contains(msg)) .unwrap_or(false) { .or_else(|| err.downcast_ref::<&'static str>().map(|e| *e)); if maybe_panic_str.map(|e| e.contains(msg)).unwrap_or(false) { TestResult::TrOk } else if desc.allow_fail { TestResult::TrAllowedFail } else if let Some(panic_str) = maybe_panic_str { TestResult::TrFailedMsg(format!( r#\"panic did not contain expected string panic message: `{:?}`, expected substring: `{:?}`\"#, panic_str, msg )) } else { if desc.allow_fail { TestResult::TrAllowedFail } else { TestResult::TrFailedMsg( format!(\"panic did not include expected string '{}'\", msg) ) } TestResult::TrFailedMsg(format!( r#\"expected panic with string value, found non-string value: `{:?}` expected substring: `{:?}`\"#, (**err).type_id(), msg )) } } (&ShouldPanic::Yes, Ok(())) => {"} {"_id":"doc-en-rust-092b0822adda1588757d807ce9ec9939646a9c59daa2960691c65065f2ac06be","title":"","text":"// TestType, TrFailedMsg, TrIgnored, TrOk, }, }; use std::any::TypeId; use std::sync::mpsc::channel; use std::time::Duration;"} {"_id":"doc-en-rust-858c9ea174b3df0e2fb1b323f9f912feca18e641fb77e0e64dd239d2623c7f7a","title":"","text":"let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; assert!(result != TrOk); assert_ne!(result, TrOk); } #[test]"} {"_id":"doc-en-rust-a518eb7746e9ffd7c103b487651e817d101df3d1d7ab968e5cfb27e34f31d599","title":"","text":"let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; assert!(result == TrIgnored); assert_eq!(result, TrIgnored); } // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)"} {"_id":"doc-en-rust-1c41cd5c3852b0a38dab0392c71aa262382ce9ae54b6e5a0430dd46818fc3c94","title":"","text":"let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; assert!(result == TrOk); assert_eq!(result, TrOk); } // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)"} {"_id":"doc-en-rust-82500e53a6a0cfb292231cf2208fc7d1b99a34a78fd7739703d6de4eb604738a","title":"","text":"panic!(\"an error message\"); } let expected = \"foobar\"; let failed_msg = \"panic did not include expected string\"; let failed_msg = r#\"panic did not contain expected string panic message: `\"an error message\"`, expected substring: `\"foobar\"`\"#; let desc = TestDescAndFn { desc: TestDesc { name: StaticTestName(\"whatever\"),"} {"_id":"doc-en-rust-a3f1e623feac6b2d928a123fb4b190b540af755cb870c52deaa207516ddbc572","title":"","text":"let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; assert!(result == TrFailedMsg(format!(\"{} '{}'\", failed_msg, expected))); assert_eq!(result, TrFailedMsg(failed_msg.to_string())); } // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251) #[test] #[cfg(not(target_os = \"emscripten\"))] fn test_should_panic_non_string_message_type() { use crate::tests::TrFailedMsg; fn f() { panic!(1i32); } let expected = \"foobar\"; let failed_msg = format!(r#\"expected panic with string value, found non-string value: `{:?}` expected substring: `\"foobar\"`\"#, TypeId::of::()); let desc = TestDescAndFn { desc: TestDesc { name: StaticTestName(\"whatever\"), ignore: false, should_panic: ShouldPanic::YesWithMessage(expected), allow_fail: false, test_type: TestType::Unknown, }, testfn: DynTestFn(Box::new(f)), }; let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; assert_eq!(result, TrFailedMsg(failed_msg)); } // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)"} {"_id":"doc-en-rust-a3b01cb5073dd7dc56ddef0e107fb8988ad074d916d2da7f78bedcb720129fab","title":"","text":"let (tx, rx) = channel(); run_test(&TestOpts::new(), false, desc, RunStrategy::InProcess, tx, Concurrent::No); let result = rx.recv().unwrap().result; assert!(result == TrFailedMsg(\"test did not panic as expected\".to_string())); assert_eq!(result, TrFailedMsg(\"test did not panic as expected\".to_string())); } fn report_time_test_template(report_time: bool) -> Option {"} {"_id":"doc-en-rust-a3f321f5543e70182f4848c95c8e23543ea18e5bc0ab5e130a5706a91fc1800f","title":"","text":"]; for (a, b) in expected.iter().zip(filtered) { assert!(*a == b.desc.name.to_string()); assert_eq!(*a, b.desc.name.to_string()); } }"} {"_id":"doc-en-rust-6c26a243fc96c3542985251279505d0f32a3859181744929ee7d7d7df5d75378","title":"","text":" // edition:2018 trait Test { fn is_some(self: T); //~ ERROR invalid `self` parameter type } async fn f() { let x = Some(2); if x.is_some() { println!(\"Some\"); } } fn main() {} "} {"_id":"doc-en-rust-d9acfbf24dd3214e3926a7a43c9946f9c9da2d3437d6dd2e05015edc98377ba8","title":"","text":" error[E0307]: invalid `self` parameter type: T --> $DIR/issue-66312.rs:4:22 | LL | fn is_some(self: T); | ^ | = note: type of `self` must be `Self` or a type that dereferences to it = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) error: aborting due to previous error For more information about this error, try `rustc --explain E0307`. "} {"_id":"doc-en-rust-d296c234168087a8bd6bc856cf19738c9e82f077ad3ebc19e1d7f6d87e4bb982","title":"","text":"\"clippy_lints\", \"compiletest_rs\", \"derive-new\", \"git2\", \"lazy_static 1.3.0\", \"regex\", \"rustc-workspace-hack\", \"rustc_tools_util 0.2.0\", \"semver\", \"serde\", \"tempfile\", \"tester\", ]"} {"_id":"doc-en-rust-6aefabe3e3dde5bec8464314eaa7335530a9827d25a697fae5b317dac045e89a","title":"","text":" Subproject commit 7b8e8293d08d298579470f9d6c74731043c6601a Subproject commit 7a943a9dfcdca98e5988da6d0b7d2f83a364b5ba "} {"_id":"doc-en-rust-3f371092a5563ab1f1ce31b708d09768f114e2d7c87282a56fedfad0a86fdf50","title":"","text":"impl<'tcx> MirPass<'tcx> for SimplifyArmIdentity { fn run_pass(&self, _: TyCtxt<'tcx>, _: MirSource<'tcx>, body: &mut Body<'tcx>) { for bb in body.basic_blocks_mut() { let (basic_blocks, local_decls) = body.basic_blocks_and_local_decls_mut(); for bb in basic_blocks { // Need 3 statements: let (s0, s1, s2) = match &mut *bb.statements { [s0, s1, s2] => (s0, s1, s2),"} {"_id":"doc-en-rust-3d651afbd895ffa4b4c367de0760227a7166689f3d23a312d9ddd7006df90de9","title":"","text":"Some(x) => x, }; if local_tmp_s0 != local_tmp_s1 // The field-and-variant information match up. || vf_s0 != vf_s1 // Source and target locals have the same type. // FIXME(Centril | oli-obk): possibly relax to same layout? || local_decls[local_0].ty != local_decls[local_1].ty // We're setting the discriminant of `local_0` to this variant. || Some((local_0, vf_s0.var_idx)) != match_set_discr(s2) { continue;"} {"_id":"doc-en-rust-ecbe55277f11e69a08228cb0697459a93aabe31d254022c163fd144219078333","title":"","text":" // Checks that `SimplifyArmIdentity` is not applied if enums have incompatible layouts. // Regression test for issue #66856. // // compile-flags: -Zmir-opt-level=2 enum Src { Foo(u8), Bar, } enum Dst { Foo(u8), } fn main() { let e: Src = Src::Foo(0); let _: Dst = match e { Src::Foo(x) => Dst::Foo(x), Src::Bar => Dst::Foo(0), }; } // END RUST SOURCE // START rustc.main.SimplifyArmIdentity.before.mir // fn main() -> () { // ... // bb0: { // StorageLive(_1); // ((_1 as Foo).0: u8) = const 0u8; // discriminant(_1) = 0; // StorageLive(_2); // _3 = discriminant(_1); // switchInt(move _3) -> [0isize: bb3, 1isize: bb1, otherwise: bb2]; // } // bb1: { // ((_2 as Foo).0: u8) = const 0u8; // discriminant(_2) = 0; // goto -> bb4; // } // ... // bb3: { // _4 = ((_1 as Foo).0: u8); // ((_2 as Foo).0: u8) = move _4; // discriminant(_2) = 0; // goto -> bb4; // } // ... // } // END rustc.main.SimplifyArmIdentity.before.mir // START rustc.main.SimplifyArmIdentity.after.mir // fn main() -> () { // ... // bb0: { // StorageLive(_1); // ((_1 as Foo).0: u8) = const 0u8; // discriminant(_1) = 0; // StorageLive(_2); // _3 = discriminant(_1); // switchInt(move _3) -> [0isize: bb3, 1isize: bb1, otherwise: bb2]; // } // bb1: { // ((_2 as Foo).0: u8) = const 0u8; // discriminant(_2) = 0; // goto -> bb4; // } // ... // bb3: { // _4 = ((_1 as Foo).0: u8); // ((_2 as Foo).0: u8) = move _4; // discriminant(_2) = 0; // goto -> bb4; // } // ... // } // END rustc.main.SimplifyArmIdentity.after.mir "} {"_id":"doc-en-rust-fca9a17431e4aaf6765ed77adaafcebcae3784dd30aa7bd28ce8e7cda159dcd9","title":"","text":" // This used to mis-compile because the mir-opt `SimplifyArmIdentity` // did not check that the types matched up in the `Ok(r)` branch. // // run-pass // compile-flags: -Zmir-opt-level=2 #[derive(Debug, PartialEq, Eq)] enum SpecialsRes { Res(u64) } fn e103() -> SpecialsRes { if let Ok(r) = \"1\".parse() { SpecialsRes::Res(r) } else { SpecialsRes::Res(42) } } fn main() { assert_eq!(e103(), SpecialsRes::Res(1)); } "} {"_id":"doc-en-rust-e9993b8c3cf00f6a602a9b834fdd2d1ade2b669f44f30eb45bd93153a5db920c","title":"","text":"let tcx = self.infcx.tcx; let generics = tcx.generics_of(self.mir_def_id); let param = generics.type_param(¶m_ty, tcx); let generics = tcx.hir().get_generics(self.mir_def_id).unwrap(); suggest_constraining_type_param( generics, &mut err, ¶m.name.as_str(), \"Copy\", tcx.sess.source_map(), span, ); if let Some(generics) = tcx.hir().get_generics(self.mir_def_id) { suggest_constraining_type_param( generics, &mut err, ¶m.name.as_str(), \"Copy\", tcx.sess.source_map(), span, ); } } let span = if let Some(local) = place.as_local() { let decl = &self.body.local_decls[local];"} {"_id":"doc-en-rust-009a59df3b237742c69acc68affa8d657168f14c3700b7a03b9012a69747744c","title":"","text":" // edition:2018 struct Ia(S); impl Ia { fn partial(_: S) {} fn full(self) {} async fn crash(self) { Self::partial(self.0); Self::full(self); //~ ERROR use of moved value: `self` } } fn main() {} "} {"_id":"doc-en-rust-28b1b1feb33038b87da2187f79397a28c71ec3dc01b0f228488ea7b676a6ab98","title":"","text":" error[E0382]: use of moved value: `self` --> $DIR/issue-66958-non-copy-infered-type-arg.rs:11:20 | LL | Self::partial(self.0); | ------ value moved here LL | Self::full(self); | ^^^^ value used here after partial move | = note: move occurs because `self.0` has type `S`, which does not implement the `Copy` trait error: aborting due to previous error For more information about this error, try `rustc --explain E0382`. "} {"_id":"doc-en-rust-8d078763b07a98b63648b63a595870780a02cab2089540811fb5b08bb1148685","title":"","text":"# - thumbv7em-none-eabihf (Bare Cortex-M4F, M7F, FPU, hardfloat) # - thumbv7m-none-eabi (Bare Cortex-M3) # only-thumbv6m-none-eabi # only-thumbv7em-none-eabi # only-thumbv7em-none-eabihf # only-thumbv7m-none-eabi # only-thumb # For cargo setting RUSTC := $(RUSTC_ORIGINAL)"} {"_id":"doc-en-rust-cb7ccecccc5184687888e7a20ee10e3f93a810eb35b58ff8dddeae7811ca26d3","title":"","text":"CRATE_URL := https://github.com/rust-embedded/cortex-m CRATE_SHA1 := a448e9156e2cb1e556e5441fd65426952ef4b927 # 0.5.0 export RUSTFLAGS := --cap-lints=allow # Don't make lints fatal, but they need to at least warn or they break Cargo's target info parsing. export RUSTFLAGS := --cap-lints=warn all: env"} {"_id":"doc-en-rust-80a88800e861bcb2502eb687dc7c7e8a41efbf563499cc296390b46da5614659","title":"","text":"-include ../../run-make-fulldeps/tools.mk # only-thumbv7m-none-eabi # only-thumbv6m-none-eabi # only-thumb # How to run this # $ ./x.py clean"} {"_id":"doc-en-rust-c5ced770a01c256ff419a941afc15dad9dc22732184bcaaf160fee854a6d1044","title":"","text":" [target.thumbv7m-none-eabi] # uncomment this to make `cargo run` execute programs on QEMU [target.thumbv6m-none-eabi] # FIXME: Should be Cortex-M0, but Qemu used by CI is too old runner = \"qemu-system-arm -cpu cortex-m3 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel\" [target.thumbv6m-none-eabi] # uncomment this to make `cargo run` execute programs on QEMU # For now, we use cortex-m3 instead of cortex-m0 which are not supported by QEMU [target.thumbv7m-none-eabi] runner = \"qemu-system-arm -cpu cortex-m3 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel\" [target.thumbv7em-none-eabi] runner = \"qemu-system-arm -cpu cortex-m4 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel\" [target.thumbv7em-none-eabihf] runner = \"qemu-system-arm -cpu cortex-m4 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel\" [target.thumbv8m.base-none-eabi] # FIXME: Should be the Cortex-M23, bt Qemu does not currently support it runner = \"qemu-system-arm -cpu cortex-m33 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel\" [target.thumbv8m.main-none-eabi] runner = \"qemu-system-arm -cpu cortex-m33 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel\" [target.thumbv8m.main-none-eabihf] runner = \"qemu-system-arm -cpu cortex-m33 -machine lm3s6965evb -nographic -semihosting-config enable=on,target=native -kernel\" [target.'cfg(all(target_arch = \"arm\", target_os = \"none\"))'] # uncomment ONE of these three option to make `cargo run` start a GDB session # which option to pick depends on your system"} {"_id":"doc-en-rust-09f9e4a42e7db7cf575819b9d58ba1d6c0c0184fe2c0c437956111630a63ff7f","title":"","text":"# \"-C\", \"linker=arm-none-eabi-gcc\", # \"-C\", \"link-arg=-Wl,-Tlink.x\", # \"-C\", \"link-arg=-nostartfiles\", ] No newline at end of file ] "} {"_id":"doc-en-rust-c26e37aafb4f975e77014afaa1b142a8f84324800ad4d4e2a597c20620ce077f","title":"","text":" # This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = \"aligned\" version = \"0.3.2\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"as-slice 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"as-slice\" version = \"0.1.2\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)\", \"generic-array 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)\", \"stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"bare-metal\" version = \"0.2.5\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"cortex-m\" version = \"0.6.2\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"aligned 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)\", \"bare-metal 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)\", \"volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"cortex-m-rt\" version = \"0.6.11\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"cortex-m-rt-macros 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)\", \"r0 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"cortex-m-rt-macros\" version = \"0.1.7\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)\", \"quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)\", \"syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"cortex-m-semihosting\" version = \"0.3.5\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"cortex-m 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"example\" version = \"0.1.0\" dependencies = [ \"cortex-m 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)\", \"cortex-m-rt 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)\", \"cortex-m-semihosting 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)\", \"panic-halt 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"generic-array\" version = \"0.12.3\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"typenum 1.11.2 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"generic-array\" version = \"0.13.2\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"typenum 1.11.2 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"panic-halt\" version = \"0.2.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" [[package]] name = \"proc-macro2\" version = \"1.0.8\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"quote\" version = \"1.0.2\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"r0\" version = \"0.2.2\" source = \"registry+https://github.com/rust-lang/crates.io-index\" [[package]] name = \"rustc_version\" version = \"0.2.3\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"semver\" version = \"0.9.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"semver-parser\" version = \"0.7.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" [[package]] name = \"stable_deref_trait\" version = \"1.1.1\" source = \"registry+https://github.com/rust-lang/crates.io-index\" [[package]] name = \"syn\" version = \"1.0.14\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)\", \"quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)\", \"unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"typenum\" version = \"1.11.2\" source = \"registry+https://github.com/rust-lang/crates.io-index\" [[package]] name = \"unicode-xid\" version = \"0.2.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" [[package]] name = \"vcell\" version = \"0.1.2\" source = \"registry+https://github.com/rust-lang/crates.io-index\" [[package]] name = \"volatile-register\" version = \"0.2.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"vcell 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\", ] [metadata] \"checksum aligned 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"eb1ce8b3382016136ab1d31a1b5ce807144f8b7eb2d5f16b2108f0f07edceb94\" \"checksum as-slice 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"be6b7e95ac49d753f19cab5a825dea99a1149a04e4e3230b33ae16e120954c04\" \"checksum bare-metal 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)\" = \"5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3\" \"checksum cortex-m 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"2954942fbbdd49996704e6f048ce57567c3e1a4e2dc59b41ae9fde06a01fc763\" \"checksum cortex-m-rt 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)\" = \"33a716cd7d8627fae3892c2eede9249e50d2d79aedfb43ca28dad9a2b23876d9\" \"checksum cortex-m-rt-macros 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)\" = \"72b1073338d1e691b3b7aaf6bd61993e589ececce9242a02dfa5453e1b98918d\" \"checksum cortex-m-semihosting 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)\" = \"113ef0ecffee2b62b58f9380f4469099b30e9f9cbee2804771b4203ba1762cfa\" \"checksum generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec\" \"checksum generic-array 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"0ed1e761351b56f54eb9dcd0cfaca9fd0daecf93918e1cfc01c8a3d26ee7adcd\" \"checksum panic-halt 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"de96540e0ebde571dc55c73d60ef407c653844e6f9a1e2fdbd40c07b9252d812\" \"checksum proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)\" = \"3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548\" \"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe\" \"checksum r0 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"e2a38df5b15c8d5c7e8654189744d8e396bddc18ad48041a500ce52d6948941f\" \"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a\" \"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403\" \"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3\" \"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8\" \"checksum syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)\" = \"af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5\" \"checksum typenum 1.11.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"6d2783fe2d6b8c1101136184eb41be8b1ad379e4657050b8aaff0c79ee7575f9\" \"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c\" \"checksum vcell 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"876e32dcadfe563a4289e994f7cb391197f362b6315dc45e8ba4aa6f564a4b3c\" \"checksum volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"0d67cb4616d99b940db1d6bd28844ff97108b498a6ca850e5b6191a532063286\" "} {"_id":"doc-en-rust-11819c7cd9b13f4e0939f95065b9a38dc1ab7174308a60d81bb9679feadd8486","title":"","text":"edition = \"2018\" [dependencies] cortex-m = \"0.5.4\" cortex-m-rt = \"=0.5.4\" cortex-m = \"0.6.2\" cortex-m-rt = \"0.6.11\" panic-halt = \"0.2.0\" cortex-m-semihosting = \"0.3.1\""} {"_id":"doc-en-rust-82021d1cd5a885c75ff2e3668e6369c291af00d8d654e4af213e29aa2b9a9a24","title":"","text":" // #![feature(stdsimd)] #![no_main] #![no_std] use core::fmt::Write;"} {"_id":"doc-en-rust-86f54a8065a1558a8593fbcd17280ce3c103132425539b16d4a318a2e8888ade","title":"","text":"use cortex_m_rt::entry; use cortex_m_semihosting as semihosting; //FIXME: This imports the provided #[panic_handler]. #[allow(rust_2018_idioms)] extern crate panic_halt; entry!(main); use panic_halt as _; #[entry] fn main() -> ! { let x = 42;"} {"_id":"doc-en-rust-41073ca40f1d61a42f2f3f424f4dabd162625dda20abfe2e74059f41d76ae37c","title":"","text":"// Check timestamps. let mut inputs = inputs.clone(); inputs.add_path(&testpaths.file); // Use `add_dir` to account for run-make tests, which use their individual directory inputs.add_dir(&testpaths.file); for aux in &props.aux { let path = testpaths.file.parent().unwrap().join(\"auxiliary\").join(aux);"} {"_id":"doc-en-rust-383a0fbd45e9718ac34422ed304dbb0f80df0b6475f46d447114b073ec5c9e26","title":"","text":"} // Error possibly reported in `check_assign` so avoid emitting error again. err.emit_unless(expression.filter(|e| fcx.is_assign_to_bool(e, expected)) .is_some()); let assign_to_bool = expression // #67273: Use initial expected type as opposed to `expected`. // Otherwise we end up using prior coercions in e.g. a `match` expression: // ``` // match i { // 0 => true, // Because of this... // 1 => i = 1, // ...`expected == bool` now, but not when checking `i = 1`. // _ => (), // }; // ``` .filter(|e| fcx.is_assign_to_bool(e, self.expected_ty())) .is_some(); err.emit_unless(assign_to_bool); self.final_ty = Some(fcx.tcx.types.err); }"} {"_id":"doc-en-rust-6b27cf802676d58bccd75acc75bdccce00d4f7751bbcd9b051e4838bed482beb","title":"","text":" fn main() { let mut i: i64; // Expected type is an inference variable `?T` // because the `match` is used as a statement. // This is the \"initial\" type of the `coercion`. match i { // Add `bool` to the overall `coercion`. 0 => true, // Necessary to cause the ICE: 1 => true, // Suppose that we had `let _: bool = match i { ... }`. // In that case, as the expected type would be `bool`, // we would suggest `i == 1` as a fix. // // However, no type error happens when checking `i = 1` because `expected == ?T`, // which will unify with `typeof(i = 1) == ()`. // // However, in #67273, we would delay the unification of this arm with the above // because we used the hitherto accumulated coercion as opposed to the \"initial\" type. 2 => i = 1, //~^ ERROR match arms have incompatible types _ => (), } } "} {"_id":"doc-en-rust-40e8f04f60f046dfc3411301479904f9ebe7e877da3b7fec5cdcdb15deb650d6","title":"","text":" error[E0308]: match arms have incompatible types --> $DIR/issue-67273-assignment-match-prior-arm-bool-expected-unit.rs:22:14 | LL | / match i { LL | | // Add `bool` to the overall `coercion`. LL | | 0 => true, | | ---- this is found to be of type `bool` LL | | LL | | // Necessary to cause the ICE: LL | | 1 => true, | | ---- this is found to be of type `bool` ... | LL | | 2 => i = 1, | | ^^^^^ expected `bool`, found `()` ... | LL | | _ => (), LL | | } | |_____- `match` arms have incompatible types error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-4faa366d0b50cb7193bb9926ef3b41b3758a299be3c7eac826d743fa68847bc5","title":"","text":"Ok(mplace) => { // Since evaluation had no errors, valiate the resulting constant: let validation = try { // FIXME do not validate promoteds until a decision on // https://github.com/rust-lang/rust/issues/67465 and // https://github.com/rust-lang/rust/issues/67534 is made. // Promoteds can contain unexpected `UnsafeCell` and reference `static`s, but their // otherwise restricted form ensures that this is still sound. We just lose the // extra safety net of some of the dynamic checks. They can also contain invalid // values, but since we do not usually check intermediate results of a computation // for validity, it might be surprising to do that here. if cid.promoted.is_none() { let mut ref_tracking = RefTracking::new(mplace); let mut inner = false; while let Some((mplace, path)) = ref_tracking.todo.pop() { let mode = match tcx.static_mutability(cid.instance.def_id()) { Some(_) => CtfeValidationMode::Regular, // a `static` None => CtfeValidationMode::Const { inner }, }; ecx.const_validate_operand(mplace.into(), path, &mut ref_tracking, mode)?; inner = true; } let mut ref_tracking = RefTracking::new(mplace); let mut inner = false; while let Some((mplace, path)) = ref_tracking.todo.pop() { let mode = match tcx.static_mutability(cid.instance.def_id()) { Some(_) if cid.promoted.is_some() => { // Promoteds in statics are allowed to point to statics. CtfeValidationMode::Const { inner, allow_static_ptrs: true } } Some(_) => CtfeValidationMode::Regular, // a `static` None => CtfeValidationMode::Const { inner, allow_static_ptrs: false }, }; ecx.const_validate_operand(mplace.into(), path, &mut ref_tracking, mode)?; inner = true; } }; if let Err(error) = validation {"} {"_id":"doc-en-rust-2bcea076a5d6771c127e99b0936a28cc27c354818a5a32ee1aafd3d0244e4783","title":"","text":"pub enum CtfeValidationMode { /// Regular validation, nothing special happening. Regular, /// Validation of a `const`. `inner` says if this is an inner, indirect allocation (as opposed /// to the top-level const allocation). /// Being an inner allocation makes a difference because the top-level allocation of a `const` /// is copied for each use, but the inner allocations are implicitly shared. Const { inner: bool }, /// Validation of a `const`. /// `inner` says if this is an inner, indirect allocation (as opposed to the top-level const /// allocation). Being an inner allocation makes a difference because the top-level allocation /// of a `const` is copied for each use, but the inner allocations are implicitly shared. /// `allow_static_ptrs` says if pointers to statics are permitted (which is the case for promoteds in statics). Const { inner: bool, allow_static_ptrs: bool }, } /// State for tracking recursive validation of references"} {"_id":"doc-en-rust-a96a7108ed4b35bcbc66fcb188a49870a6dc8e964b821299837363794b4e8818","title":"","text":"if let Some(GlobalAlloc::Static(did)) = alloc_kind { assert!(!self.ecx.tcx.is_thread_local_static(did)); assert!(self.ecx.tcx.is_static(did)); if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. })) { if matches!( self.ctfe_mode, Some(CtfeValidationMode::Const { allow_static_ptrs: false, .. }) ) { // See const_eval::machine::MemoryExtra::can_access_statics for why // this check is so important. // This check is reachable when the const just referenced the static,"} {"_id":"doc-en-rust-7cd3173138479f2763f4b61f772b3c67a6668c424fab7718dc61dbf919b60489","title":"","text":"// Sanity check: `builtin_deref` does not know any pointers that are not primitive. assert!(op.layout.ty.builtin_deref(true).is_none()); // Special check preventing `UnsafeCell` in constants // Special check preventing `UnsafeCell` in the inner part of constants if let Some(def) = op.layout.ty.ty_adt_def() { if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true })) if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. })) && Some(def.did) == self.ecx.tcx.lang_items().unsafe_cell_type() { throw_validation_failure!(self.path, { \"`UnsafeCell` in a `const`\" });"} {"_id":"doc-en-rust-83e198c40961a99bca8bb10228d71a505f366f93cd8a1b6ab04bd1b56c5385aa","title":"","text":"if let (local, []) = (&place.local, proj_base) { let decl = &self.body.local_decls[*local]; if decl.internal { // Internal locals are used in the `move_val_init` desugaring. // We want to check unsafety against the source info of the // desugaring, rather than the source info of the RHS. self.source_info = self.body.local_decls[*local].source_info; } else if let LocalInfo::StaticRef { def_id, .. } = decl.local_info { if self.tcx.is_mutable_static(def_id) { self.require_unsafe( \"use of mutable static\", \"mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior\", UnsafetyViolationKind::General, ); return; } else if self.tcx.is_foreign_item(def_id) { self.require_unsafe( \"use of extern static\", \"extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior\", UnsafetyViolationKind::General, ); return; if let LocalInfo::StaticRef { def_id, .. } = decl.local_info { if self.tcx.is_mutable_static(def_id) { self.require_unsafe( \"use of mutable static\", \"mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior\", UnsafetyViolationKind::General, ); return; } else if self.tcx.is_foreign_item(def_id) { self.require_unsafe( \"use of extern static\", \"extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior\", UnsafetyViolationKind::General, ); return; } } else { // Internal locals are used in the `move_val_init` desugaring. // We want to check unsafety against the source info of the // desugaring, rather than the source info of the RHS. self.source_info = self.body.local_decls[*local].source_info; } } }"} {"_id":"doc-en-rust-714d852727aaa9c0601d4c6dd79a683706a219f36e47d85fe3c794936d3a39c3","title":"","text":"} if let ExprKind::StaticRef { def_id, .. } = expr.kind { let is_thread_local = this.hir.tcx().has_attr(def_id, sym::thread_local); local_decl.internal = true; local_decl.local_info = LocalInfo::StaticRef { def_id, is_thread_local }; } this.local_decls.push(local_decl)"} {"_id":"doc-en-rust-b1c12d9e41093b5f9f9336fec76a8d29472a99bb871f53dcda7cfe07edaed50d","title":"","text":"} fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) { let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); match &expr.kind { ExprKind::Call(callee, args) => match &callee.kind { ExprKind::Path(qpath) => {"} {"_id":"doc-en-rust-1de5c7160bb3a5a4bcded27b4379a46216817de153a0787e5ac2d57fcf7caebe","title":"","text":"} _ => intravisit::walk_expr(self, expr), }, ExprKind::Path(qpath) => { let res = self.fcx.tables.borrow().qpath_res(qpath, expr.hir_id); if let Res::Def(DefKind::Static, def_id) = res { // Statics are lowered to temporary references or // pointers in MIR, so record that type. let ptr_ty = self.fcx.tcx.static_ptr_ty(def_id); self.record(ptr_ty, scope, Some(expr), expr.span); } } _ => intravisit::walk_expr(self, expr), } self.expr_count += 1; let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); // If there are adjustments, then record the final type -- // this is the actual value that is being produced. if let Some(adjusted_ty) = self.fcx.tables.borrow().expr_ty_adjusted_opt(expr) {"} {"_id":"doc-en-rust-878a87363493d46c912a1fea3281c4cebad2e960460c63ac04477a469569271c","title":"","text":" // build-pass // edition:2018 static mut A: [i32; 5] = [1, 2, 3, 4, 5]; fn is_send_sync(_: T) {} async fn fun() { let u = unsafe { A[async { 1 }.await] }; unsafe { match A { i if async { true }.await => (), _ => (), } } } fn main() { let index_block = async { let u = unsafe { A[async { 1 }.await] }; }; let match_block = async { unsafe { match A { i if async { true }.await => (), _ => (), } } }; is_send_sync(index_block); is_send_sync(match_block); is_send_sync(fun()); } "} {"_id":"doc-en-rust-02fc4b31bc1ca4fdfdec6ded7339418f5c51ee4963060da067cf0f12d3d794aa","title":"","text":" // build-pass #![feature(generators)] static mut A: [i32; 5] = [1, 2, 3, 4, 5]; fn is_send_sync(_: T) {} fn main() { unsafe { let gen_index = static || { let u = A[{ yield; 1 }]; }; let gen_match = static || match A { i if { yield; true } => { () } _ => (), }; is_send_sync(gen_index); is_send_sync(gen_match); } } "} {"_id":"doc-en-rust-84c034eb5093b25c02e627ed49972b93ae552054c70d655ec60c0efdc50ef7c6","title":"","text":" Subproject commit c807fbc8ba41432388b6f590668ba81314c07c32 Subproject commit d9e38f57c125c5ac50397ec8a006fe49f17cd96c "} {"_id":"doc-en-rust-4fd7e81962b4fb72aeaee2d93130f2ebaf11c2cca212bbfe9a91f6974513043d","title":"","text":" Subproject commit 4da2b2149ca1c6a3331260dfcbb2175c51f2842d Subproject commit 4e44aa010c4c7d616182a3078cafb39da6f6c0a2 "} {"_id":"doc-en-rust-992845074d0beae932829b45f7db24905c43281783866b85e6bc1c64f671f30c","title":"","text":" Subproject commit 732825dcff6d1f115225305ce5e0c9c9d876a0ff Subproject commit e8642c7a2900bed28003a98d4db8b62290ac802f "} {"_id":"doc-en-rust-7e967034694583e13b2d195e8164c5a347b7ae14cfad3c7883b8bb555465c54b","title":"","text":"// listing. let main_ret_ty = cx.tcx().erase_regions(&main_ret_ty.no_bound_vars().unwrap()); if cx.get_defined_value(\"main\").is_some() { if cx.get_declared_value(\"main\").is_some() { // FIXME: We should be smart and show a better diagnostic here. cx.sess() .struct_span_err(sp, \"entry symbol `main` defined multiple times\") .struct_span_err(sp, \"entry symbol `main` declared multiple times\") .help(\"did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead\") .emit(); cx.sess().abort_if_errors();"} {"_id":"doc-en-rust-a8880acbd925c9d4afa398726f499837446288876d08ef36d3d18a37ae8435b6","title":"","text":"// build-fail // // error-pattern: entry symbol `main` defined multiple times // error-pattern: entry symbol `main` declared multiple times // FIXME https://github.com/rust-lang/rust/issues/59774 // normalize-stderr-test \"thread.*panicked.*Metadata module not compiled.*n\" -> \"\""} {"_id":"doc-en-rust-09c34257be9c7dd25ace56538a8efb8ae18450e89835e02175c991c76b8f91ea","title":"","text":" error: entry symbol `main` defined multiple times error: entry symbol `main` declared multiple times --> $DIR/dupe-symbols-7.rs:12:1 | LL | fn main(){}"} {"_id":"doc-en-rust-188d5701930c38fa7f4bb16a83514296ca818f7f5a325534467c878640f29240","title":"","text":" // build-fail // error-pattern: entry symbol `main` declared multiple times // // See #67946. #![allow(warnings)] fn main() { extern \"Rust\" { fn main(); } unsafe { main(); } } "} {"_id":"doc-en-rust-7745cda6c7bb4f8157def5605750c6b8a7275b4db3db2998bcef7d0bacdd8501","title":"","text":" error: entry symbol `main` declared multiple times --> $DIR/dupe-symbols-8.rs:7:1 | LL | / fn main() { LL | | extern \"Rust\" { LL | | fn main(); LL | | } LL | | unsafe { main(); } LL | | } | |_^ | = help: did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead error: aborting due to previous error "} {"_id":"doc-en-rust-8b45c140fd9924d711bc7a49005d30cb275b1afae06eaca8740617b88720f795","title":"","text":"Some(\"std::ops::Add\"), ), hir::BinOpKind::Sub => ( format!(\"cannot substract `{}` from `{}`\", rhs_ty, lhs_ty), format!(\"cannot subtract `{}` from `{}`\", rhs_ty, lhs_ty), Some(\"std::ops::Sub\"), ), hir::BinOpKind::Mul => ("} {"_id":"doc-en-rust-97102eec0701afe10e5afadf1ae867e8add4ce06a68e9fecd0cf6227b34120fa","title":"","text":"a + a; //~ ERROR cannot add `A` to `A` a - a; //~ ERROR cannot substract `A` from `A` a - a; //~ ERROR cannot subtract `A` from `A` a * a; //~ ERROR cannot multiply `A` to `A`"} {"_id":"doc-en-rust-f7e78061e1d52f4ed989ecdaa1a957a4142c4dd931ff482501e035d404f185a9","title":"","text":"| = note: an implementation of `std::ops::Add` might be missing for `A` error[E0369]: cannot substract `A` from `A` error[E0369]: cannot subtract `A` from `A` --> $DIR/issue-28837.rs:8:7 | LL | a - a;"} {"_id":"doc-en-rust-5fcb4cfa2d3d8045b37e42cc041b6c0c224f17842259cc32a7db2216272186fa","title":"","text":"if let Some(item) = module .res .and_then(|res| res.mod_def_id()) // If the module is `self`, i.e. the current crate, // there will be no corresponding item. .filter(|def_id| def_id.index != CRATE_DEF_INDEX || def_id.krate != LOCAL_CRATE) .and_then(|def_id| self.tcx.hir().as_local_hir_id(def_id)) .map(|module_hir_id| self.tcx.hir().expect_item(module_hir_id)) {"} {"_id":"doc-en-rust-f925a93d1b02a0e35a795ed2c6c61aafc7f945a08d45fafb1374533357a90326","title":"","text":" // check-pass pub extern crate self as name; pub use name::name as bug; fn main() {} "} {"_id":"doc-en-rust-d087819ea2ecf4bfe0cac251dc05c48d2d0321d90f0c572ce32bc35c7a519720","title":"","text":"dylibs: FxHashMap, ) -> Option<(Svh, Library)> { let mut slot = None; // Order here matters, rmeta should come first. See comment in // `extract_one` below. let source = CrateSource { rlib: self.extract_one(rlibs, CrateFlavor::Rlib, &mut slot), rmeta: self.extract_one(rmetas, CrateFlavor::Rmeta, &mut slot), rlib: self.extract_one(rlibs, CrateFlavor::Rlib, &mut slot), dylib: self.extract_one(dylibs, CrateFlavor::Dylib, &mut slot), }; slot.map(|(svh, metadata)| (svh, Library { source, metadata })) } fn needs_crate_flavor(&self, flavor: CrateFlavor) -> bool { if flavor == CrateFlavor::Dylib && self.is_proc_macro == Some(true) { return true; } // The all loop is because `--crate-type=rlib --crate-type=rlib` is // legal and produces both inside this type. let is_rlib = self.sess.crate_types.borrow().iter().all(|c| *c == config::CrateType::Rlib); let needs_object_code = self.sess.opts.output_types.should_codegen(); // If we're producing an rlib, then we don't need object code. // Or, if we're not producing object code, then we don't need it either // (e.g., if we're a cdylib but emitting just metadata). if is_rlib || !needs_object_code { flavor == CrateFlavor::Rmeta } else { // we need all flavors (perhaps not true, but what we do for now) true } } // Attempts to extract *one* library from the set `m`. If the set has no // elements, `None` is returned. If the set has more than one element, then // the errors and notes are emitted about the set of libraries."} {"_id":"doc-en-rust-5380432ef965e948f2f11aac3ff494da535dae83c9a127269dc4fa43b7abc4e7","title":"","text":"let mut ret: Option<(PathBuf, PathKind)> = None; let mut error = 0; // If we are producing an rlib, and we've already loaded metadata, then // we should not attempt to discover further crate sources (unless we're // locating a proc macro; exact logic is in needs_crate_flavor). This means // that under -Zbinary-dep-depinfo we will not emit a dependency edge on // the *unused* rlib, and by returning `None` here immediately we // guarantee that we do indeed not use it. // // See also #68149 which provides more detail on why emitting the // dependency on the rlib is a bad thing. // // We currenty do not verify that these other sources are even in sync, // and this is arguably a bug (see #10786), but because reading metadata // is quite slow (especially from dylibs) we currently do not read it // from the other crate sources. if slot.is_some() { // FIXME(#10786): for an optimization, we only read one of the // libraries' metadata sections. In theory we should // read both, but reading dylib metadata is quite // slow. if m.is_empty() { if m.is_empty() || !self.needs_crate_flavor(flavor) { return None; } else if m.len() == 1 { return Some(m.into_iter().next().unwrap());"} {"_id":"doc-en-rust-08ec04a2e25099d5ac945eccb4acf9f7a0cd0b2c6fde45b4be2f2d522b2fa13f","title":"","text":"// run-pass // Test that using rlibs and rmeta dep crates work together. Specifically, that // there can be both an rmeta and an rlib file and rustc will prefer the rlib. // there can be both an rmeta and an rlib file and rustc will prefer the rmeta // file. // // This behavior is simply making sure this doesn't accidentally change; in this // case we want to make sure that the rlib isn't being used as that would cause // bugs in -Zbinary-dep-depinfo (see #68298). // aux-build:rmeta-rmeta.rs // aux-build:rmeta-rlib-rpass.rs"} {"_id":"doc-en-rust-3b8ee1f97a87041ba1b3d28d00289ecf9e87fb92d2a7a68e7078417afa164aae","title":"","text":"use rmeta_aux::Foo; pub fn main() { let _ = Foo { field: 42 }; let _ = Foo { field2: 42 }; }"} {"_id":"doc-en-rust-5e85e1100be4bdfd789dd8e7e8cf8faf8b84574f27a06267fa28e8d48b94236c","title":"","text":" Subproject commit fd0428f622feee209e6014b802f5717d48d9e978 Subproject commit 3e74853d1f9893cf2a47f28b658711d8f9f97b6b "} {"_id":"doc-en-rust-111e70d47893d055c456ed64988844c5d66f0bed499442114d1cc17a4432abfb","title":"","text":"/// `failure` describes the required ordering for the load operation that takes place when /// the comparison fails. Using [`Acquire`] as success ordering makes the store part /// of this operation [`Relaxed`], and using [`Release`] makes the successful load /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`] /// and must be equivalent to or weaker than the success ordering. /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. /// /// **Note:** This method is only available on platforms that support atomic /// operations on `u8`."} {"_id":"doc-en-rust-c0f8f9ec1099901819473654ade517a07ad83825341eb19d2325cc83216f3d4e","title":"","text":"/// Using [`Acquire`] as success ordering makes the store part of this /// operation [`Relaxed`], and using [`Release`] makes the final successful /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], /// [`Acquire`] or [`Relaxed`] and must be equivalent to or weaker than the /// success ordering. /// [`Acquire`] or [`Relaxed`]. /// /// **Note:** This method is only available on platforms that support atomic /// operations on `u8`."} {"_id":"doc-en-rust-3d1463365c1578aa17f6b9f28e39c91d2ec5154ae94d2dc4f994ca12599217d7","title":"","text":"/// `failure` describes the required ordering for the load operation that takes place when /// the comparison fails. Using [`Acquire`] as success ordering makes the store part /// of this operation [`Relaxed`], and using [`Release`] makes the successful load /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`] /// and must be equivalent to or weaker than the success ordering. /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. /// /// **Note:** This method is only available on platforms that support atomic /// operations on pointers."} {"_id":"doc-en-rust-89d278b34215f1e319d9fbdb1c7434decd7c636e893650ace311bb945c337152","title":"","text":"/// Using [`Acquire`] as success ordering makes the store part of this /// operation [`Relaxed`], and using [`Release`] makes the final successful /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], /// [`Acquire`] or [`Relaxed`] and must be equivalent to or weaker than the /// success ordering. /// [`Acquire`] or [`Relaxed`]. /// /// **Note:** This method is only available on platforms that support atomic /// operations on pointers."} {"_id":"doc-en-rust-095e9cdfd56d79efa65d57d54ff7286f446503e20daa834ca26c8df8d958b0c2","title":"","text":"/// `failure` describes the required ordering for the load operation that takes place when /// the comparison fails. Using [`Acquire`] as success ordering makes the store part /// of this operation [`Relaxed`], and using [`Release`] makes the successful load /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`] /// and must be equivalent to or weaker than the success ordering. /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. /// /// **Note**: This method is only available on platforms that support atomic operations on #[doc = concat!(\"[`\", $s_int_type, \"`].\")]"} {"_id":"doc-en-rust-065b84f674706ac0b2133a05245cc49c4378b0565a8eca42ce3e0898a114458d","title":"","text":"/// /// Using [`Acquire`] as success ordering makes the store part /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`] /// and must be equivalent to or weaker than the success ordering. /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]. /// /// **Note**: This method is only available on platforms that support atomic operations on #[doc = concat!(\"[`\", $s_int_type, \"`].\")]"} {"_id":"doc-en-rust-130336fd19e6a627cc42064dc8eff4d776fde713ddff8b2dd2d13f639da13845","title":"","text":"let (val, ok) = unsafe { match (success, failure) { (Relaxed, Relaxed) => intrinsics::atomic_cxchg_relaxed_relaxed(dst, old, new), //(Relaxed, Acquire) => intrinsics::atomic_cxchg_relaxed_acquire(dst, old, new), //(Relaxed, SeqCst) => intrinsics::atomic_cxchg_relaxed_seqcst(dst, old, new), #[cfg(not(bootstrap))] (Relaxed, Acquire) => intrinsics::atomic_cxchg_relaxed_acquire(dst, old, new), #[cfg(not(bootstrap))] (Relaxed, SeqCst) => intrinsics::atomic_cxchg_relaxed_seqcst(dst, old, new), (Acquire, Relaxed) => intrinsics::atomic_cxchg_acquire_relaxed(dst, old, new), (Acquire, Acquire) => intrinsics::atomic_cxchg_acquire_acquire(dst, old, new), //(Acquire, SeqCst) => intrinsics::atomic_cxchg_acquire_seqcst(dst, old, new), #[cfg(not(bootstrap))] (Acquire, SeqCst) => intrinsics::atomic_cxchg_acquire_seqcst(dst, old, new), (Release, Relaxed) => intrinsics::atomic_cxchg_release_relaxed(dst, old, new), //(Release, Acquire) => intrinsics::atomic_cxchg_release_acquire(dst, old, new), //(Release, SeqCst) => intrinsics::atomic_cxchg_release_seqcst(dst, old, new), #[cfg(not(bootstrap))] (Release, Acquire) => intrinsics::atomic_cxchg_release_acquire(dst, old, new), #[cfg(not(bootstrap))] (Release, SeqCst) => intrinsics::atomic_cxchg_release_seqcst(dst, old, new), (AcqRel, Relaxed) => intrinsics::atomic_cxchg_acqrel_relaxed(dst, old, new), (AcqRel, Acquire) => intrinsics::atomic_cxchg_acqrel_acquire(dst, old, new), //(AcqRel, SeqCst) => intrinsics::atomic_cxchg_acqrel_seqcst(dst, old, new), #[cfg(not(bootstrap))] (AcqRel, SeqCst) => intrinsics::atomic_cxchg_acqrel_seqcst(dst, old, new), (SeqCst, Relaxed) => intrinsics::atomic_cxchg_seqcst_relaxed(dst, old, new), (SeqCst, Acquire) => intrinsics::atomic_cxchg_seqcst_acquire(dst, old, new), (SeqCst, SeqCst) => intrinsics::atomic_cxchg_seqcst_seqcst(dst, old, new), (_, AcqRel) => panic!(\"there is no such thing as an acquire-release failure ordering\"), (_, Release) => panic!(\"there is no such thing as a release failure ordering\"), #[cfg(bootstrap)] _ => panic!(\"a failure ordering can't be stronger than a success ordering\"), } };"} {"_id":"doc-en-rust-48ea1a2b62b336e79c0a99e1d1af8bba2b82264505d3966e39f0241c948ee76f","title":"","text":"let (val, ok) = unsafe { match (success, failure) { (Relaxed, Relaxed) => intrinsics::atomic_cxchgweak_relaxed_relaxed(dst, old, new), //(Relaxed, Acquire) => intrinsics::atomic_cxchgweak_relaxed_acquire(dst, old, new), //(Relaxed, SeqCst) => intrinsics::atomic_cxchgweak_relaxed_seqcst(dst, old, new), #[cfg(not(bootstrap))] (Relaxed, Acquire) => intrinsics::atomic_cxchgweak_relaxed_acquire(dst, old, new), #[cfg(not(bootstrap))] (Relaxed, SeqCst) => intrinsics::atomic_cxchgweak_relaxed_seqcst(dst, old, new), (Acquire, Relaxed) => intrinsics::atomic_cxchgweak_acquire_relaxed(dst, old, new), (Acquire, Acquire) => intrinsics::atomic_cxchgweak_acquire_acquire(dst, old, new), //(Acquire, SeqCst) => intrinsics::atomic_cxchgweak_acquire_seqcst(dst, old, new), #[cfg(not(bootstrap))] (Acquire, SeqCst) => intrinsics::atomic_cxchgweak_acquire_seqcst(dst, old, new), (Release, Relaxed) => intrinsics::atomic_cxchgweak_release_relaxed(dst, old, new), //(Release, Acquire) => intrinsics::atomic_cxchgweak_release_acquire(dst, old, new), //(Release, SeqCst) => intrinsics::atomic_cxchgweak_release_seqcst(dst, old, new), #[cfg(not(bootstrap))] (Release, Acquire) => intrinsics::atomic_cxchgweak_release_acquire(dst, old, new), #[cfg(not(bootstrap))] (Release, SeqCst) => intrinsics::atomic_cxchgweak_release_seqcst(dst, old, new), (AcqRel, Relaxed) => intrinsics::atomic_cxchgweak_acqrel_relaxed(dst, old, new), (AcqRel, Acquire) => intrinsics::atomic_cxchgweak_acqrel_acquire(dst, old, new), //(AcqRel, SeqCst) => intrinsics::atomic_cxchgweak_acqrel_seqcst(dst, old, new), #[cfg(not(bootstrap))] (AcqRel, SeqCst) => intrinsics::atomic_cxchgweak_acqrel_seqcst(dst, old, new), (SeqCst, Relaxed) => intrinsics::atomic_cxchgweak_seqcst_relaxed(dst, old, new), (SeqCst, Acquire) => intrinsics::atomic_cxchgweak_seqcst_acquire(dst, old, new), (SeqCst, SeqCst) => intrinsics::atomic_cxchgweak_seqcst_seqcst(dst, old, new), (_, AcqRel) => panic!(\"there is no such thing as an acquire-release failure ordering\"), (_, Release) => panic!(\"there is no such thing as a release failure ordering\"), #[cfg(bootstrap)] _ => panic!(\"a failure ordering can't be stronger than a success ordering\"), } };"} {"_id":"doc-en-rust-233fdd21be0ca9765f9a5ecd766d83c1e91a18e11a9f9fa9a5eabfdd623552e1","title":"","text":" // build-pass // Verify that the compiler doesn't ICE during const prop while evaluating the index operation. #![allow(unconditional_panic)] fn main() { let cols = [0u32; 0]; cols[0]; } "} {"_id":"doc-en-rust-ff1320863fcfd037afb68f3a0fd8206dfa60f875eea09147f9f456ae2947cfb4","title":"","text":"ty_span: Span, ) { if variant.recovered { self.set_tainted_by_errors(); return; } let mut err = self.type_error_struct_with_diag("} {"_id":"doc-en-rust-2bbc9ec8ea5644cf6548da109e4956f327d3326d46d36cae9fb10cfb6899cc4b","title":"","text":" // Regression test for #69378: no type for node after struct parse recovery struct Foo { 0: u8 } //~ ERROR expected identifier fn test(f: Foo) { Foo{foo: 4, ..f}; } fn main() {} "} {"_id":"doc-en-rust-de1dd1835aa70e1cad668b3147418d7c2f68e2405f25dc7a3a39f1017ecddfdd","title":"","text":" error: expected identifier, found `0` --> $DIR/issue-69378-ice-on-invalid-type-node-after-recovery.rs:3:14 | LL | struct Foo { 0: u8 } | ^ expected identifier error: aborting due to previous error "} {"_id":"doc-en-rust-834fbc70360b487080d39e350229ac8c2877a5d610106d1bca5f73fa33f2fcbd","title":"","text":"[[package]] name = \"git2\" version = \"0.11.0\" version = \"0.12.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"77519ef7c5beee314d0804d4534f01e0f9e8d9acdee2b7a48627e590b27e0ec4\" checksum = \"26e07ef27260a78f7e8d218ebac2c72f2c4db50493741b190b6e8eade1da7c68\" dependencies = [ \"bitflags\", \"libc\","} {"_id":"doc-en-rust-74c092ec9c80ab9f5817946a3c20506a69e5f121f9e598980b4aa4576decdf03","title":"","text":"[[package]] name = \"git2-curl\" version = \"0.12.0\" version = \"0.13.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"d2559abb1d87d27668d31bd868a000f0e2e0065d10e78961b62da95d7a7f1cc7\" checksum = \"af1754ec4170e7dcaf9bb43743bb16eddb8d827b2e0291deb6f220a6e16fe46a\" dependencies = [ \"curl\", \"git2\","} {"_id":"doc-en-rust-bb54216b5861832751f025067fc601d6231936dabd9196fe83c48689f80419ce","title":"","text":"[[package]] name = \"libgit2-sys\" version = \"0.10.0\" version = \"0.11.0+0.99.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"d9ec6bca50549d34a392611dde775123086acbd994e3fff64954777ce2dc2e51\" checksum = \"4d5d1459353d397a029fb18862166338de938e6be976606bd056cf8f1a912ecf\" dependencies = [ \"cc\", \"libc\","} {"_id":"doc-en-rust-ec16316ab2500d2b3a76fdfde1edc0408cd6362c8c6a94e20e7913191be9bc1c","title":"","text":" Subproject commit e57bd02999c9f40d52116e0beca7d1dccb0643de Subproject commit bda50510d1daf6e9c53ad6ccf603da6e0fa8103f "} {"_id":"doc-en-rust-734f46667d022b9328075cb40fd760c62f31eeba60cc847150e6631e0c32aac9","title":"","text":" Subproject commit fc5d0cc583cb1cd35d58fdb7f3e0cfa12dccd6c0 Subproject commit 8b7f7e667268921c278af94ae30a61e87a22b22b "} {"_id":"doc-en-rust-d651a3c989b6419a932195c900dacd8fc700388797439716c5b18fb387fa5ff7","title":"","text":"source_file: Lrc, override_span: Option, ) -> Self { if source_file.src.is_none() { // Make sure external source is loaded first, before accessing it. // While this can't show up during normal parsing, `retokenize` may // be called with a source file from an external crate. sess.source_map().ensure_source_file_source_present(source_file.clone()); // FIXME(eddyb) use `Lrc` or similar to avoid cloning the `String`. let src = if let Some(src) = &source_file.src { src.clone() } else if let Some(src) = source_file.external_src.borrow().get_source() { src.clone() } else { sess.span_diagnostic .bug(&format!(\"cannot lex `source_file` without source: {}\", source_file.name)); } let src = (*source_file.src.as_ref().unwrap()).clone(); }; StringReader { sess,"} {"_id":"doc-en-rust-8de21d889fd77491cc9b3433a0eac39602454909e72b53966fb7cb0f47ab33b5","title":"","text":"#[derive(PartialEq, Eq, Clone, Debug)] pub enum ExternalSourceKind { /// The external source has been loaded already. Present(String), Present(Lrc), /// No attempt has been made to load the external source. AbsentOk, /// A failed attempt has been made to load the external source."} {"_id":"doc-en-rust-90d91f64c4b848ebaa2b5fee8798dc8cff3c24a8b3e5afd501d91b0ecf2c2be4","title":"","text":"} } pub fn get_source(&self) -> Option<&str> { pub fn get_source(&self) -> Option<&Lrc> { match self { ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), _ => None,"} {"_id":"doc-en-rust-c6776ab3e54e100631527ad462024fc8a3aae7bc42b9b8dec1ced33f3d29d514","title":"","text":"hasher.write(src.as_bytes()); if hasher.finish::() == self.src_hash { *src_kind = ExternalSourceKind::Present(src); *src_kind = ExternalSourceKind::Present(Lrc::new(src)); return true; } } else {"} {"_id":"doc-en-rust-2d2556a456d61dc8e8d3e8609382363b0d4fa8201ac34acca5f7902767775fa9","title":"","text":"} } /// Checks that generic parameters are in the correct order, /// which is lifetimes, then types and then consts. (`<'a, T, const N: usize>`) fn validate_generic_param_order<'a>( sess: &Session, handler: &rustc_errors::Handler,"} {"_id":"doc-en-rust-2bee2a3652cada4caaa5c88be9b1ee966f988164c22b16227a065f5e8003b693","title":"","text":"// Now create the real type and const parameters. let type_start = own_start - has_self as u32 + params.len() as u32; let mut i = 0; params.extend(ast_generics.params.iter().filter_map(|param| { let kind = match param.kind { GenericParamKind::Type { ref default, synthetic, .. } => { if !allow_defaults && default.is_some() { if !tcx.features().default_type_parameter_fallback { tcx.struct_span_lint_hir( lint::builtin::INVALID_TYPE_PARAM_DEFAULT, param.hir_id, param.span, |lint| { lint.build( \"defaults for type parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions.\", ) .emit(); }, ); } } ty::GenericParamDefKind::Type { has_default: default.is_some(), object_lifetime_default: object_lifetime_defaults .as_ref() .map_or(rl::Set1::Empty, |o| o[i]), synthetic, // FIXME(const_generics): a few places in the compiler expect generic params // to be in the order lifetimes, then type params, then const params. // // To prevent internal errors in case const parameters are supplied before // type parameters we first add all type params, then all const params. params.extend(ast_generics.params.iter().filter_map(|param| { if let GenericParamKind::Type { ref default, synthetic, .. } = param.kind { if !allow_defaults && default.is_some() { if !tcx.features().default_type_parameter_fallback { tcx.struct_span_lint_hir( lint::builtin::INVALID_TYPE_PARAM_DEFAULT, param.hir_id, param.span, |lint| { lint.build( \"defaults for type parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions.\", ) .emit(); }, ); } } GenericParamKind::Const { .. } => ty::GenericParamDefKind::Const, _ => return None, }; let param_def = ty::GenericParamDef { index: type_start + i as u32, name: param.name.ident().name, def_id: tcx.hir().local_def_id(param.hir_id), pure_wrt_drop: param.pure_wrt_drop, kind, }; i += 1; Some(param_def) let kind = ty::GenericParamDefKind::Type { has_default: default.is_some(), object_lifetime_default: object_lifetime_defaults .as_ref() .map_or(rl::Set1::Empty, |o| o[i]), synthetic, }; let param_def = ty::GenericParamDef { index: type_start + i as u32, name: param.name.ident().name, def_id: tcx.hir().local_def_id(param.hir_id), pure_wrt_drop: param.pure_wrt_drop, kind, }; i += 1; Some(param_def) } else { None } })); params.extend(ast_generics.params.iter().filter_map(|param| { if let GenericParamKind::Const { .. } = param.kind { let param_def = ty::GenericParamDef { index: type_start + i as u32, name: param.name.ident().name, def_id: tcx.hir().local_def_id(param.hir_id), pure_wrt_drop: param.pure_wrt_drop, kind: ty::GenericParamDefKind::Const, }; i += 1; Some(param_def) } else { None } })); // provide junk type parameter defs - the only place that"} {"_id":"doc-en-rust-7cb150422a26e94a810185d4e157b9a2cfaf6f570785b692621108cdd6f561c2","title":"","text":" #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash struct Bad { //~ ERROR type parameters must be declared prior arr: [u8; { N }], another: T, } fn main() { } "} {"_id":"doc-en-rust-775136cabe03b0aa83b5fb7004365aaabcddc3a926b2ac83e408961264ed5c02","title":"","text":" error: type parameters must be declared prior to const parameters --> $DIR/argument_order.rs:4:28 | LL | struct Bad { | -----------------^- help: reorder the parameters: lifetimes, then types, then consts: `` warning: the feature `const_generics` is incomplete and may cause the compiler to crash --> $DIR/argument_order.rs:1:12 | LL | #![feature(const_generics)] | ^^^^^^^^^^^^^^ | = note: `#[warn(incomplete_features)]` on by default error: aborting due to previous error "} {"_id":"doc-en-rust-716ad289f723c5ea4b77a65361a4515d98fa430d764150978ef7698e1c29a374","title":"","text":"// The collapse-docs pass won't combine sugared/raw doc attributes, or included files with // anything else, this will combine them for us. if let Some(doc) = attrs.collapsed_doc_value() { self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP)); // Use the outermost invocation, so that doctest names come from where the docs were written. let span = attrs .span .map(|span| span.ctxt().outer_expn().expansion_cause().unwrap_or(span)) .unwrap_or(DUMMY_SP); self.collector.set_position(span); markdown::find_testable_code( &doc, self.collector,"} {"_id":"doc-en-rust-82853b974186cf2cb98b147716ab73ddec65ecda2581dea1081051a49073e550","title":"","text":" #[macro_export] macro_rules! attrs_on_struct { ( $( #[$attr:meta] )* ) => { $( #[$attr] )* pub struct ExpandedStruct; } } "} {"_id":"doc-en-rust-4eab258304ffa1bfabe92b1f45318169543d339cdcc5043ab02cde57747efbd0","title":"","text":" // edition:2018 // aux-build:extern_macros.rs // compile-flags:--test --test-args=--test-threads=1 // normalize-stdout-test: \"src/test/rustdoc-ui\" -> \"$$DIR\" // check-pass"} {"_id":"doc-en-rust-cdd644821676cced6544f8c7972737b9bdda1db74678fd8c7cebb75922a0c596","title":"","text":"//! assert_eq!(1 + 1, 2); //! ``` extern crate extern_macros as macros; use macros::attrs_on_struct; pub mod foo { /// ```"} {"_id":"doc-en-rust-5ac59c875515b0d1f7ad4461276c261d9d2cffdc7fc6a5a9bea4709103013cab","title":"","text":"/// ``` pub fn bar() {} } attrs_on_struct! { /// ``` /// assert!(true); /// ``` } "} {"_id":"doc-en-rust-ce5ff8beabecb39987a7985db5357bee601d5dadcf5abf9461b442738d23b8ba","title":"","text":" running 2 tests test $DIR/doctest-output.rs - (line 5) ... ok test $DIR/doctest-output.rs - foo::bar (line 11) ... ok running 3 tests test $DIR/doctest-output.rs - (line 7) ... ok test $DIR/doctest-output.rs - ExpandedStruct (line 23) ... ok test $DIR/doctest-output.rs - foo::bar (line 17) ... ok test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out "} {"_id":"doc-en-rust-cbb4e347ec9c80c1c08f0e869d417279689d421403d5c4ddc12a669237017507","title":"","text":"} /// Configuration for compiletest #[derive(Clone)] #[derive(Debug, Clone)] pub struct Config { /// `true` to to overwrite stderr/stdout files instead of complaining about changes in output. pub bless: bool,"} {"_id":"doc-en-rust-e9145bcb4c67d13142ea892fd338149e6a46ce8dd85e881ea798313fe8d6200a","title":"","text":"emit_metadata: EmitMetadata, allow_unused: AllowUnused, ) -> Command { let is_rustdoc = self.is_rustdoc(); let is_aux = input_file.components().map(|c| c.as_os_str()).any(|c| c == \"auxiliary\"); let is_rustdoc = self.is_rustdoc() && !is_aux; let mut rustc = if !is_rustdoc { Command::new(&self.config.rustc_path) } else {"} {"_id":"doc-en-rust-1e4468efeb434f9908acb0169542df865eae6f208369d9872998d38f20513b12","title":"","text":"} } #[derive(Debug)] enum TargetLocation { ThisFile(PathBuf), ThisDirectory(PathBuf),"} {"_id":"doc-en-rust-3d5549a9bde51ab60270a07f72761863f06f0b2dc47355aba29e18225a0187e5","title":"","text":" // Regression test for https://github.com/rust-lang/rust/issues/56445#issuecomment-629426939 // check-pass #![crate_type = \"lib\"] use std::marker::PhantomData; pub struct S<'a> { pub m1: PhantomData<&'a u8>, pub m2: [u8; S::size()], } impl<'a> S<'a> { pub const fn size() -> usize { 1 } pub fn new() -> Self { Self { m1: PhantomData, m2: [0; Self::size()], } } } "} {"_id":"doc-en-rust-1daabd479d76c534f33a414e8d4ea539f263a64824c95725b8e338f15ba0e803","title":"","text":" // check-pass pub struct A<'a>(&'a ()); impl<'a> A<'a> { const N: usize = 68; pub fn foo(&self) { let _b = [0; Self::N]; } } fn main() {} "} {"_id":"doc-en-rust-a5965cf8520c4f67805af62d9e59f03e69180d4beb7d701295af5faf75b1afb0","title":"","text":" #![feature(impl_trait_in_bindings)] #![allow(incomplete_features)] fn main() { const C: impl Copy = 0; match C { C | _ => {} //~ ERROR: opaque types cannot be used in patterns } } "} {"_id":"doc-en-rust-ae80c05d4db2accf448f76e4d2a9671420a5f21d8be95fd3df2a599671f1bd4e","title":"","text":" error: opaque types cannot be used in patterns --> $DIR/issue-71042-opaquely-typed-constant-used-in-pattern.rs:7:9 | LL | C | _ => {} | ^ error: aborting due to previous error "} {"_id":"doc-en-rust-9bbe8ded20e3e8a76355f3d73fe7a45f99431ce4a811f5a3f0ef2b18126d0ea9","title":"","text":" // check-pass #![feature(type_alias_impl_trait)] pub type Successors<'a> = impl Iterator; pub fn f<'a>() -> Successors<'a> { None.into_iter() } pub trait Tr { type Item; } impl<'a> Tr for &'a () { type Item = Successors<'a>; } pub fn kazusa<'a>() -> <&'a () as Tr>::Item { None.into_iter() } fn main() {} "} {"_id":"doc-en-rust-ab4c89325c70f5bdc4e6b3dfefc7653eb2898fa58da87eaef10bb42d477fe663","title":"","text":"// figure out which generic parameter it corresponds to and return // the relevant type. let generics = match path.res { Res::Def(DefKind::Ctor(..), def_id) => { Res::Def(DefKind::Ctor(..), def_id) | Res::Def(DefKind::AssocTy, def_id) => { tcx.generics_of(tcx.parent(def_id).unwrap()) } Res::Def(_, def_id) => tcx.generics_of(def_id), Res::Err => return tcx.types.err, res => { tcx.sess.delay_span_bug( DUMMY_SP, &format!(\"unexpected const parent path def {:?}\", res,), &format!( \"unexpected const parent path def, parent: {:?}, def: {:?}\", parent_node, res ), ); return tcx.types.err; }"} {"_id":"doc-en-rust-6954909598c39886c3f29b40c26fb89eca23b86df8b67630479ff04a0f7469a5","title":"","text":".map(|param| tcx.type_of(param.def_id)) // This is no generic parameter associated with the arg. This is // probably from an extra arg where one is not needed. .unwrap_or(tcx.types.err) .unwrap_or_else(|| { tcx.sess.delay_span_bug( DUMMY_SP, &format!( \"missing generic parameter for `AnonConst`, parent {:?}\", parent_node ), ); tcx.types.err }) } else { tcx.sess.delay_span_bug( DUMMY_SP,"} {"_id":"doc-en-rust-71bb8e7fd468615db71f5adc2601e32c4998573f30e902194ec884ddd74e3ea8","title":"","text":" // check-pass #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash pub struct Tuple; pub trait Trait { type Input: From<>::Input>; } fn main() {} "} {"_id":"doc-en-rust-e1cfceb64e951166d4d8df672f919ad42d44b45600caceab56df73e1ff39b8dd","title":"","text":" warning: the feature `const_generics` is incomplete and may cause the compiler to crash --> $DIR/issue-66906.rs:3:12 | LL | #![feature(const_generics)] | ^^^^^^^^^^^^^^ | = note: `#[warn(incomplete_features)]` on by default "} {"_id":"doc-en-rust-d31a95ef718f0ca6d18b9fbcd5b52abc62cbff075f2d8fa040900bf23322e60a","title":"","text":" // check-pass #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash pub trait Trait: From<>::Item> { type Item; } fn main() {} "} {"_id":"doc-en-rust-35904b51ceb37e2a4ab4a74a313c006563b63c8cee572b46e00b1f9d7cdf77bb","title":"","text":" warning: the feature `const_generics` is incomplete and may cause the compiler to crash --> $DIR/issue-70167.rs:3:12 | LL | #![feature(const_generics)] | ^^^^^^^^^^^^^^ | = note: `#[warn(incomplete_features)]` on by default "} {"_id":"doc-en-rust-c22ca7d3367dd3aa0402327451ba9ece41a098f41cafcc8cf7299909c0168633","title":"","text":"span: Span, // span of the field pattern, e.g., `x: 0` def: &'tcx ty::AdtDef, // definition of the struct or enum field: &'tcx ty::FieldDef, in_update_syntax: bool, ) { // definition of the field let ident = Ident::new(kw::Invalid, use_ctxt); let current_hir = self.current_item; let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did, current_hir).1; if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) { let label = if in_update_syntax { format!(\"field `{}` is private\", field.ident) } else { \"private field\".to_string() }; struct_span_err!( self.tcx.sess, span,"} {"_id":"doc-en-rust-56f94aff869655488dbb2438254ea3806f0abc0be99c627f0cb43f714a674eb1","title":"","text":"def.variant_descr(), self.tcx.def_path_str(def.did) ) .span_label(span, \"private field\") .span_label(span, label) .emit(); } }"} {"_id":"doc-en-rust-663106109792107651ef4364aebb2cc000e0bac25d021c08d6ff725e5d55ee48","title":"","text":"Some(field) => (field.ident.span, field.span), None => (base.span, base.span), }; self.check_field(use_ctxt, span, adt, variant_field); self.check_field(use_ctxt, span, adt, variant_field, true); } } else { for field in fields { let use_ctxt = field.ident.span; let index = self.tcx.field_index(field.hir_id, self.tables); self.check_field(use_ctxt, field.span, adt, &variant.fields[index]); self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); } } }"} {"_id":"doc-en-rust-3f5621ec2297f66fea1e4a9d3990b52762a6e1ada1aa8a31827e804ecc843600","title":"","text":"for field in fields { let use_ctxt = field.ident.span; let index = self.tcx.field_index(field.hir_id, self.tables); self.check_field(use_ctxt, field.span, adt, &variant.fields[index]); self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); } } _ => {}"} {"_id":"doc-en-rust-84f123042c9915c8b88783ae19012ccc3931da277da2437c6ea6a3a3453c02c5","title":"","text":"--> $DIR/functional-struct-update-respects-privacy.rs:28:49 | LL | let s_2 = foo::S { b: format!(\"ess two\"), ..s_1 }; // FRU ... | ^^^ private field | ^^^ field `secret_uid` is private error: aborting due to previous error"} {"_id":"doc-en-rust-697468f90505c8350d2c4c4c473364c4f01c16a28d3e6e3d1b699de3198e6b23","title":"","text":" Subproject commit aaa16a5f4b8caabf8e044e6dd1c48330dfb7900d Subproject commit 0d0a457c8b1750e82f19527b18b313f3514633f0 "} {"_id":"doc-en-rust-a241aea3c5b3fb8f1f92c5f390303161e25c7e55c89f65b05590162dd314a9c8","title":"","text":"_memory_extra: &(), _alloc_id: AllocId, allocation: &Allocation, static_def_id: Option, _static_def_id: Option, is_write: bool, ) -> InterpResult<'tcx> { if is_write { throw_machine_stop_str!(\"can't write to global\"); } // If the static allocation is mutable or if it has relocations (it may be legal to mutate // the memory behind that in the future), then we can't const prop it. // If the static allocation is mutable, then we can't const prop it as its content // might be different at runtime. if allocation.mutability == Mutability::Mut { throw_machine_stop_str!(\"can't eval mutable globals in ConstProp\"); } if static_def_id.is_some() && allocation.relocations().len() > 0 { throw_machine_stop_str!(\"can't eval statics with pointers in ConstProp\"); throw_machine_stop_str!(\"can't access mutable globals in ConstProp\"); } Ok(())"} {"_id":"doc-en-rust-0e3e796015e47d7a3646d1b16e034d642a814074b0056375dc4432724315b77b","title":"","text":"fn visit_generics(&mut self, generics: &'a Generics) { let mut prev_ty_default = None; for param in &generics.params { if let GenericParamKind::Type { ref default, .. } = param.kind { if default.is_some() { match param.kind { GenericParamKind::Lifetime => (), GenericParamKind::Type { default: Some(_), .. } => { prev_ty_default = Some(param.ident.span); } else if let Some(span) = prev_ty_default { self.err_handler() .span_err(span, \"type parameters with a default must be trailing\"); break; } GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { if let Some(span) = prev_ty_default { let mut err = self.err_handler().struct_span_err( span, \"type parameters with a default must be trailing\", ); if matches!(param.kind, GenericParamKind::Const { .. }) { err.note( \"using type defaults and const parameters in the same parameter list is currently not permitted\", ); } err.emit(); break; } } } }"} {"_id":"doc-en-rust-813f9581e624bac764542003fb917f299974aa97555ec66cab57f3378c6e156b","title":"","text":" #![feature(const_generics)] //~ WARN the feature `const_generics` is incomplete struct A { //~^ ERROR type parameters with a default must be trailing arg: T, } fn main() {} "} {"_id":"doc-en-rust-092d345eb23c316c1b422a12da68b66f35232bf1c10018b5da180d56879490b1","title":"","text":" error: type parameters with a default must be trailing --> $DIR/wrong-order.rs:3:10 | LL | struct A { | ^ | = note: using type defaults and const parameters in the same parameter list is currently not permitted warning: the feature `const_generics` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/wrong-order.rs:1:12 | LL | #![feature(const_generics)] | ^^^^^^^^^^^^^^ | = note: `#[warn(incomplete_features)]` on by default = note: see issue #44580 for more information error: aborting due to previous error; 1 warning emitted "} {"_id":"doc-en-rust-f65a88bed118dca04b7d3bacb37d95dc570c3bab5c44801bdf5f6e5fb52f9701","title":"","text":"// We can still be zero-sized in this branch, in which case we have to // return `None`. if size.bytes() == 0 { None } else { Some(ptr) } if size.bytes() == 0 { // We may be reading from a static. // In order to ensure that `static FOO: Type = FOO;` causes a cycle error // instead of magically pulling *any* ZST value from the ether, we need to // actually access the referenced allocation. The caller is likely // to short-circuit on `None`, so we trigger the access here to // make sure it happens. self.get_raw(ptr.alloc_id)?; None } else { Some(ptr) } } }) }"} {"_id":"doc-en-rust-da8bb1afc58073c0c49603947f4896a69c55b95c8ff40aec285f0ca3426b5f95","title":"","text":"} }; let alloc = self.memory.get_raw(ptr.alloc_id)?; match mplace.layout.abi { Abi::Scalar(..) => { let scalar = self.memory.get_raw(ptr.alloc_id)?.read_scalar( self, ptr, mplace.layout.size, )?; let scalar = alloc.read_scalar(self, ptr, mplace.layout.size)?; Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout })) } Abi::ScalarPair(ref a, ref b) => {"} {"_id":"doc-en-rust-5d57cf7b06f2967818f9559d2fb42f2fb1321dc46c8de91caa6f66b5f3e24818","title":"","text":"let b_offset = a_size.align_to(b.align(self).abi); assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields let b_ptr = ptr.offset(b_offset, self)?; let a_val = self.memory.get_raw(ptr.alloc_id)?.read_scalar(self, a_ptr, a_size)?; let b_val = self.memory.get_raw(ptr.alloc_id)?.read_scalar(self, b_ptr, b_size)?; let a_val = alloc.read_scalar(self, a_ptr, a_size)?; let b_val = alloc.read_scalar(self, b_ptr, b_size)?; Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout })) } _ => Ok(None),"} {"_id":"doc-en-rust-773aed344788f5adfea119d1bbe0bc7a148235d40502de8571c4dbb0a05ded4d","title":"","text":" // build-pass // This test ensures that we do not allow ZST statics to initialize themselves without ever // actually creating a value of that type. This is important, as the ZST may have private fields // that users can reasonably expect to only get initialized by their own code. Thus unsafe code // can depend on this fact and will thus do unsound things when it is violated. // See https://github.com/rust-lang/rust/issues/71078 for more details. static FOO: () = FOO; static FOO: () = FOO; //~ cycle detected when const-evaluating `FOO` fn main() { FOO"} {"_id":"doc-en-rust-cc4b47399d255d7ac6de9443e4df263706ee96aa42c17fcccc7f708ec1ca7712","title":"","text":" error[E0391]: cycle detected when const-evaluating `FOO` --> $DIR/recursive-zst-static.rs:7:18 | LL | static FOO: () = FOO; | ^^^ | note: ...which requires const-evaluating `FOO`... --> $DIR/recursive-zst-static.rs:7:1 | LL | static FOO: () = FOO; | ^^^^^^^^^^^^^^^^^^^^^ = note: ...which again requires const-evaluating `FOO`, completing the cycle note: cycle used when const-evaluating + checking `FOO` --> $DIR/recursive-zst-static.rs:7:1 | LL | static FOO: () = FOO; | ^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0391`. "} {"_id":"doc-en-rust-8daba7d73da4bed4ab2740a6d6641f4b3dca3dacedf9f95a0db5e2add0a50657","title":"","text":"} impl rustc_serialize::Encodable for AttrId { fn encode(&self, _: &mut S) -> Result<(), S::Error> { Ok(()) fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_unit() } } impl rustc_serialize::Decodable for AttrId { fn decode(_: &mut D) -> Result { Ok(crate::attr::mk_attr_id()) fn decode(d: &mut D) -> Result { d.read_nil().map(|_| crate::attr::mk_attr_id()) } }"} {"_id":"doc-en-rust-aa8d2386201294180fabad6d7ceb42ff513cb27bdbabb492316f5f9931d27ab9","title":"","text":" // Check that AST json printing works. #![crate_type = \"lib\"] // check-pass // compile-flags: -Zast-json-noexpand // normalize-stdout-test \":d+\" -> \":0\" // Only include a single item to reduce how often the test output needs // updating. extern crate core; "} {"_id":"doc-en-rust-571020b8adb551a3de492f0726ad24cda7f2e71aa617301e15ea427a4a30f92f","title":"","text":" {\"module\":{\"inner\":{\"lo\":0,\"hi\":0},\"items\":[{\"attrs\":[],\"id\":0,\"span\":{\"lo\":0,\"hi\":0},\"vis\":{\"node\":\"Inherited\",\"span\":{\"lo\":0,\"hi\":0}},\"ident\":{\"name\":\"core\",\"span\":{\"lo\":0,\"hi\":0}},\"kind\":{\"variant\":\"ExternCrate\",\"fields\":[null]},\"tokens\":{\"_field0\":[[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Ident\",\"fields\":[\"extern\",false]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"],[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Ident\",\"fields\":[\"crate\",false]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"],[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Ident\",\"fields\":[\"core\",false]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"],[{\"variant\":\"Token\",\"fields\":[{\"kind\":\"Semi\",\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"]]}}],\"inline\":true},\"attrs\":[{\"kind\":{\"variant\":\"Normal\",\"fields\":[{\"path\":{\"span\":{\"lo\":0,\"hi\":0},\"segments\":[{\"ident\":{\"name\":\"crate_type\",\"span\":{\"lo\":0,\"hi\":0}},\"id\":0,\"args\":null}]},\"args\":{\"variant\":\"Eq\",\"fields\":[{\"lo\":0,\"hi\":0},{\"_field0\":[[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Literal\",\"fields\":[{\"kind\":\"Str\",\"symbol\":\"lib\",\"suffix\":null}]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"]]}]}}]},\"id\":null,\"style\":\"Inner\",\"span\":{\"lo\":0,\"hi\":0}}],\"span\":{\"lo\":0,\"hi\":0},\"proc_macros\":[]} "} {"_id":"doc-en-rust-eb98fec39eb10322bddf7aee904ab007650edb395959022ae7f14fc6af8411c4","title":"","text":"// Check that AST json printing works. #![crate_type = \"lib\"] // check-pass // compile-flags: -Zast-json-noexpand // compile-flags: -Zast-json // normalize-stdout-test \":d+\" -> \":0\" // Only include a single item to reduce how often the test output needs"} {"_id":"doc-en-rust-bbbfb01f5ae258de8d3b77b674d7630ff13a73398839a3351ca1ce232f2a04b2","title":"","text":" {\"module\":{\"inner\":{\"lo\":0,\"hi\":0},\"items\":[{\"attrs\":[],\"id\":0,\"span\":{\"lo\":0,\"hi\":0},\"vis\":{\"node\":\"Inherited\",\"span\":{\"lo\":0,\"hi\":0}},\"ident\":{\"name\":\"core\",\"span\":{\"lo\":0,\"hi\":0}},\"kind\":{\"variant\":\"ExternCrate\",\"fields\":[null]},\"tokens\":{\"_field0\":[[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Ident\",\"fields\":[\"extern\",false]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"],[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Ident\",\"fields\":[\"crate\",false]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"],[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Ident\",\"fields\":[\"core\",false]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"],[{\"variant\":\"Token\",\"fields\":[{\"kind\":\"Semi\",\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"]]}}],\"inline\":true},\"attrs\":[],\"span\":{\"lo\":0,\"hi\":0},\"proc_macros\":[]} {\"module\":{\"inner\":{\"lo\":0,\"hi\":0},\"items\":[{\"attrs\":[{\"kind\":{\"variant\":\"Normal\",\"fields\":[{\"path\":{\"span\":{\"lo\":0,\"hi\":0},\"segments\":[{\"ident\":{\"name\":\"prelude_import\",\"span\":{\"lo\":0,\"hi\":0}},\"id\":0,\"args\":null}]},\"args\":\"Empty\"}]},\"id\":null,\"style\":\"Outer\",\"span\":{\"lo\":0,\"hi\":0}}],\"id\":0,\"span\":{\"lo\":0,\"hi\":0},\"vis\":{\"node\":\"Inherited\",\"span\":{\"lo\":0,\"hi\":0}},\"ident\":{\"name\":\"\",\"span\":{\"lo\":0,\"hi\":0}},\"kind\":{\"variant\":\"Use\",\"fields\":[{\"prefix\":{\"span\":{\"lo\":0,\"hi\":0},\"segments\":[{\"ident\":{\"name\":\"{{root}}\",\"span\":{\"lo\":0,\"hi\":0}},\"id\":0,\"args\":null},{\"ident\":{\"name\":\"std\",\"span\":{\"lo\":0,\"hi\":0}},\"id\":0,\"args\":null},{\"ident\":{\"name\":\"prelude\",\"span\":{\"lo\":0,\"hi\":0}},\"id\":0,\"args\":null},{\"ident\":{\"name\":\"v1\",\"span\":{\"lo\":0,\"hi\":0}},\"id\":0,\"args\":null}]},\"kind\":\"Glob\",\"span\":{\"lo\":0,\"hi\":0}}]},\"tokens\":null},{\"attrs\":[{\"kind\":{\"variant\":\"Normal\",\"fields\":[{\"path\":{\"span\":{\"lo\":0,\"hi\":0},\"segments\":[{\"ident\":{\"name\":\"macro_use\",\"span\":{\"lo\":0,\"hi\":0}},\"id\":0,\"args\":null}]},\"args\":\"Empty\"}]},\"id\":null,\"style\":\"Outer\",\"span\":{\"lo\":0,\"hi\":0}}],\"id\":0,\"span\":{\"lo\":0,\"hi\":0},\"vis\":{\"node\":\"Inherited\",\"span\":{\"lo\":0,\"hi\":0}},\"ident\":{\"name\":\"std\",\"span\":{\"lo\":0,\"hi\":0}},\"kind\":{\"variant\":\"ExternCrate\",\"fields\":[null]},\"tokens\":null},{\"attrs\":[],\"id\":0,\"span\":{\"lo\":0,\"hi\":0},\"vis\":{\"node\":\"Inherited\",\"span\":{\"lo\":0,\"hi\":0}},\"ident\":{\"name\":\"core\",\"span\":{\"lo\":0,\"hi\":0}},\"kind\":{\"variant\":\"ExternCrate\",\"fields\":[null]},\"tokens\":{\"_field0\":[[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Ident\",\"fields\":[\"extern\",false]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"],[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Ident\",\"fields\":[\"crate\",false]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"],[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Ident\",\"fields\":[\"core\",false]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"],[{\"variant\":\"Token\",\"fields\":[{\"kind\":\"Semi\",\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"]]}}],\"inline\":true},\"attrs\":[{\"kind\":{\"variant\":\"Normal\",\"fields\":[{\"path\":{\"span\":{\"lo\":0,\"hi\":0},\"segments\":[{\"ident\":{\"name\":\"crate_type\",\"span\":{\"lo\":0,\"hi\":0}},\"id\":0,\"args\":null}]},\"args\":{\"variant\":\"Eq\",\"fields\":[{\"lo\":0,\"hi\":0},{\"_field0\":[[{\"variant\":\"Token\",\"fields\":[{\"kind\":{\"variant\":\"Literal\",\"fields\":[{\"kind\":\"Str\",\"symbol\":\"lib\",\"suffix\":null}]},\"span\":{\"lo\":0,\"hi\":0}}]},\"NonJoint\"]]}]}}]},\"id\":null,\"style\":\"Inner\",\"span\":{\"lo\":0,\"hi\":0}}],\"span\":{\"lo\":0,\"hi\":0},\"proc_macros\":[]} "} {"_id":"doc-en-rust-db2c6dc77ccd2a90718a0bdf4ca8c9c32bc76491f36508e5441b9f678272f141","title":"","text":"if let Node::Expr(expr) = tcx.hir_node(arg_hir_id) && let Some(typeck_results) = &self.typeck_results { if let hir::Expr { kind: hir::ExprKind::MethodCall(_, rcvr, _, _), .. } = expr && let Some(ty) = typeck_results.node_type_opt(rcvr.hir_id) && let Some(failed_pred) = failed_pred.to_opt_poly_trait_pred() && let pred = failed_pred.map_bound(|pred| pred.with_self_ty(tcx, ty)) && self.predicate_must_hold_modulo_regions(&Obligation::misc( tcx, expr.span, body_id, param_env, pred, )) { err.span_suggestion_verbose( expr.span.with_lo(rcvr.span.hi()), format!( \"consider removing this method call, as the receiver has type `{ty}` and `{pred}` trivially holds\", ), \"\", Applicability::MaybeIncorrect, ); } if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr { let inner_expr = expr.peel_blocks(); let ty = typeck_results"} {"_id":"doc-en-rust-af88f5e74d791e335432e592304f9f71d39702392cb2f62621083e04261bd41e","title":"","text":"} } if let Node::Expr(expr) = tcx.hir_node(call_hir_id) { if let Node::Expr(expr) = call_node { if let hir::ExprKind::Call(hir::Expr { span, .. }, _) | hir::ExprKind::MethodCall( hir::PathSegment { ident: Ident { span, .. }, .. },"} {"_id":"doc-en-rust-3d512ad7c94afcbc9a0e1d8b7baedfacf2a154a5341937b8d69adc0f56be5f57","title":"","text":"| note: required by a bound in `File::open` --> $SRC_DIR/std/src/fs.rs:LL:COL help: consider removing this method call, as the receiver has type `&Path` and `&Path: AsRef` trivially holds | LL - let mut f = File::open(path.to_str())?; LL + let mut f = File::open(path)?; | error: aborting due to 1 previous error"} {"_id":"doc-en-rust-eb1dcddc88b997e3558479b223026437a5b2e536283b89a09cf4c70e358860fc","title":"","text":"| LL | fn check_bound(_: T) {} | ^^^^ required by this bound in `check_bound` help: consider removing this method call, as the receiver has type `&'static str` and `&'static str: Copy` trivially holds | LL - check_bound(\"nocopy\".to_string()); LL + check_bound(\"nocopy\"); | error: aborting due to 1 previous error"} {"_id":"doc-en-rust-34cfe20934a9cb80cdac182785402c025d9894b5ff8296c00e4388e0d62d6856","title":"","text":"| LL | fn f_copy(t: T) {} | ^^^^ required by this bound in `f_copy` help: consider removing this method call, as the receiver has type `&'static str` and `&'static str: Copy` trivially holds | LL - f_copy(\"\".to_string()); LL + f_copy(\"\"); | error[E0277]: the trait bound `S: Clone` is not satisfied --> $DIR/issue-84973-blacklist.rs:16:13"} {"_id":"doc-en-rust-a57a7e1d6acdbad193a4a882b7c72b80df57598f89a6a4e385aa1055ca4ae6f9","title":"","text":" struct Foo; struct Bar; impl From for Foo { fn from(_: Bar) -> Self { Foo } } fn qux(_: impl From) {} fn main() { qux(Bar.into()); //~ ERROR type annotations needed //~| HELP try using a fully qualified path to specify the expected types //~| HELP consider removing this method call, as the receiver has type `Bar` and `Bar: From` trivially holds } "} {"_id":"doc-en-rust-d0b26d159f5b06b2f633925920939da318c61f410b83a2e3fbed21477ea3fecb","title":"","text":" error[E0283]: type annotations needed --> $DIR/argument-with-unnecessary-method-call.rs:8:13 | LL | qux(Bar.into()); | --- ^^^^ | | | required by a bound introduced by this call | = note: cannot satisfy `_: From` note: required by a bound in `qux` --> $DIR/argument-with-unnecessary-method-call.rs:6:16 | LL | fn qux(_: impl From) {} | ^^^^^^^^^ required by this bound in `qux` help: try using a fully qualified path to specify the expected types | LL | qux(>::into(Bar)); | +++++++++++++++++++++++ ~ help: consider removing this method call, as the receiver has type `Bar` and `Bar: From` trivially holds | LL - qux(Bar.into()); LL + qux(Bar); | error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0283`. "} {"_id":"doc-en-rust-4e014f79f94ea3969553964cfb1d2cf87fdb353ab14accd2c071dd6223a5ca8b","title":"","text":"indirect_dest: PlaceRef<'tcx, V>, ) { debug!(\"OperandRef::store_unsized: operand={:?}, indirect_dest={:?}\", self, indirect_dest); let flags = MemFlags::empty(); // `indirect_dest` must have `*mut T` type. We extract `T` out of it. let unsized_ty = indirect_dest .layout"} {"_id":"doc-en-rust-79ffa03f4749ad197dca6649c6d032907c1568d374b85baef6e1c3b2b6933e17","title":"","text":"bug!(\"store_unsized called with a sized value\") }; // FIXME: choose an appropriate alignment, or use dynamic align somehow let max_align = Align::from_bits(128).unwrap(); let min_align = Align::from_bits(8).unwrap(); // Allocate an appropriate region on the stack, and copy the value into it let (llsize, _) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra)); let lldst = bx.byte_array_alloca(llsize, max_align); bx.memcpy(lldst, max_align, llptr, min_align, llsize, flags); // Allocate an appropriate region on the stack, and copy the value into it. Since alloca // doesn't support dynamic alignment, we allocate an extra align - 1 bytes, and align the // pointer manually. let (size, align) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra)); let one = bx.const_usize(1); let align_minus_1 = bx.sub(align, one); let size_extra = bx.add(size, align_minus_1); let min_align = Align::ONE; let alloca = bx.byte_array_alloca(size_extra, min_align); let address = bx.ptrtoint(alloca, bx.type_isize()); let neg_address = bx.neg(address); let offset = bx.and(neg_address, align_minus_1); let dst = bx.inbounds_gep(bx.type_i8(), alloca, &[offset]); bx.memcpy(dst, min_align, llptr, min_align, size, MemFlags::empty()); // Store the allocated region and the extra to the indirect place. let indirect_operand = OperandValue::Pair(lldst, llextra); let indirect_operand = OperandValue::Pair(dst, llextra); indirect_operand.store(bx, indirect_dest); } }"} {"_id":"doc-en-rust-a0c76235bd2b80b1b0fcce7daba72bb02e1807d1419a585546ce2d7aa558fb76","title":"","text":" // Test that unsized locals uphold alignment requirements. // Regression test for #71416. // run-pass #![feature(unsized_locals)] #![allow(incomplete_features)] use std::any::Any; #[repr(align(256))] #[allow(dead_code)] struct A { v: u8 } impl A { fn f(&self) -> *const A { assert_eq!(self as *const A as usize % 256, 0); self } } fn mk() -> Box { Box::new(A { v: 4 }) } fn main() { let x = *mk(); let dwncst = x.downcast_ref::().unwrap(); let addr = dwncst.f(); assert_eq!(addr as usize % 256, 0); } "} {"_id":"doc-en-rust-f3bf7cebf0bb9cacf71d263cb9b2ee16ec94123474bf62b30ad4528c4bb6d267","title":"","text":" #[derive(PartialEq, Eq)] enum X { A, B, C, } fn main() { let x = X::A; let y = Some(X::A); match (x, y) { //~^ ERROR non-exhaustive patterns: `(A, Some(A))`, `(A, Some(B))`, `(B, Some(B))` and 2 //~| more not covered (_, None) => false, (v, Some(w)) if v == w => true, (X::B, Some(X::C)) => false, (X::B, Some(X::A)) => false, (X::A, Some(X::C)) | (X::C, Some(X::A)) => false, }; } "} {"_id":"doc-en-rust-43dc284e9e3f89d0e139760138b629f3acb9515e78999abb6aec56ae8150cff7","title":"","text":" error[E0004]: non-exhaustive patterns: `(A, Some(A))`, `(A, Some(B))`, `(B, Some(B))` and 2 more not covered --> $DIR/issue-72377.rs:8:11 | LL | match (x, y) { | ^^^^^^ patterns `(A, Some(A))`, `(A, Some(B))`, `(B, Some(B))` and 2 more not covered | = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms = note: the matched value is of type `(X, Option)` error: aborting due to previous error For more information about this error, try `rustc --explain E0004`. "} {"_id":"doc-en-rust-c74ad61e8604b04cc73f922c05f88ef43a310d794c582b384968f5ae5eab402d","title":"","text":"use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_span::hygiene::DesugaringKind; use rustc_span::Span; #[derive(Clone, Copy, Debug, PartialEq)]"} {"_id":"doc-en-rust-7d7d96e7b8c79eb88d369fbc9de8e94448685095562ac2d9c6f76b05357252b3","title":"","text":"label: &Destination, cf_type: &str, ) -> bool { if self.cx == LabeledBlock { if !span.is_desugaring(DesugaringKind::QuestionMark) && self.cx == LabeledBlock { if label.label.is_none() { struct_span_err!( self.sess,"} {"_id":"doc-en-rust-b9d584ab9543574206577cab49f79478541fb7842408308ec2189cb9a0c7cc62","title":"","text":" // compile-flags: --edition 2018 #![feature(label_break_value, try_blocks)] // run-pass fn main() { let _: Result<(), ()> = try { 'foo: { Err(())?; break 'foo; } }; } "} {"_id":"doc-en-rust-3da09cb6854cd8e5b20ace5cdc150ea6ad9a11f96dc88e9af440fc9021db8b62","title":"","text":" // Check that `unused_lifetimes` lint doesn't duplicate a \"parameter is never used\" error. // Fixed in . // Issue: . #![warn(unused_lifetimes)] struct Foo<'a>; //~^ ERROR parameter `'a` is never used fn main() {} "} {"_id":"doc-en-rust-1728db3272aaccccd6c611092e11a3b8f11899b917c554ef1dc2ebf53680bf55","title":"","text":" error[E0392]: lifetime parameter `'a` is never used --> $DIR/dedup.rs:6:12 | LL | struct Foo<'a>; | ^^ unused lifetime parameter | = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData` error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0392`. "} {"_id":"doc-en-rust-24bef5309ff4893abd597dd15b6d1f941a011815e7ab0fd7ee836726cb11fc3d","title":"","text":"use crate::build::{BlockAnd, BlockAndExtension, Builder}; use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode}; use crate::hair::{self, *}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::{fx::{FxHashMap, FxHashSet}, stack::ensure_sufficient_stack}; use rustc_hir::HirId; use rustc_index::bit_set::BitSet; use rustc_middle::middle::region;"} {"_id":"doc-en-rust-29800fedf683c26d33171651277bef4d925f428e8d59a37d4774e44aa4cbd857","title":"","text":"split_or_candidate |= self.simplify_candidate(candidate); } if split_or_candidate { // At least one of the candidates has been split into subcandidates. // We need to change the candidate list to include those. let mut new_candidates = Vec::new(); ensure_sufficient_stack(|| { if split_or_candidate { // At least one of the candidates has been split into subcandidates. // We need to change the candidate list to include those. let mut new_candidates = Vec::new(); for candidate in candidates { candidate.visit_leaves(|leaf_candidate| new_candidates.push(leaf_candidate)); for candidate in candidates { candidate.visit_leaves(|leaf_candidate| new_candidates.push(leaf_candidate)); } self.match_simplified_candidates( span, start_block, otherwise_block, &mut *new_candidates, fake_borrows, ); } else { self.match_simplified_candidates( span, start_block, otherwise_block, candidates, fake_borrows, ); } self.match_simplified_candidates( span, start_block, otherwise_block, &mut *new_candidates, fake_borrows, ); } else { self.match_simplified_candidates( span, start_block, otherwise_block, candidates, fake_borrows, ); }; }); } fn match_simplified_candidates("} {"_id":"doc-en-rust-723d142671a5fd02eb89331a9e88711d360e5c66ec09b71461ce8cd2a6926898","title":"","text":" // build-pass // ignore-tidy-filelength #![crate_type=\"rlib\"] fn banana(v: &str) -> u32 { match v { \"0\" => 0, \"1\" => 1, \"2\" => 2, \"3\" => 3, \"4\" => 4, \"5\" => 5, \"6\" => 6, \"7\" => 7, \"8\" => 8, \"9\" => 9, \"10\" => 10, \"11\" => 11, \"12\" => 12, \"13\" => 13, \"14\" => 14, \"15\" => 15, \"16\" => 16, \"17\" => 17, \"18\" => 18, \"19\" => 19, \"20\" => 20, \"21\" => 21, \"22\" => 22, \"23\" => 23, \"24\" => 24, \"25\" => 25, \"26\" => 26, \"27\" => 27, \"28\" => 28, \"29\" => 29, \"30\" => 30, \"31\" => 31, \"32\" => 32, \"33\" => 33, \"34\" => 34, \"35\" => 35, \"36\" => 36, \"37\" => 37, \"38\" => 38, \"39\" => 39, \"40\" => 40, \"41\" => 41, \"42\" => 42, \"43\" => 43, \"44\" => 44, \"45\" => 45, \"46\" => 46, \"47\" => 47, \"48\" => 48, \"49\" => 49, \"50\" => 50, \"51\" => 51, \"52\" => 52, \"53\" => 53, \"54\" => 54, \"55\" => 55, \"56\" => 56, \"57\" => 57, \"58\" => 58, \"59\" => 59, \"60\" => 60, \"61\" => 61, \"62\" => 62, \"63\" => 63, \"64\" => 64, \"65\" => 65, \"66\" => 66, \"67\" => 67, \"68\" => 68, \"69\" => 69, \"70\" => 70, \"71\" => 71, \"72\" => 72, \"73\" => 73, \"74\" => 74, \"75\" => 75, \"76\" => 76, \"77\" => 77, \"78\" => 78, \"79\" => 79, \"80\" => 80, \"81\" => 81, \"82\" => 82, \"83\" => 83, \"84\" => 84, \"85\" => 85, \"86\" => 86, \"87\" => 87, \"88\" => 88, \"89\" => 89, \"90\" => 90, \"91\" => 91, \"92\" => 92, \"93\" => 93, \"94\" => 94, \"95\" => 95, \"96\" => 96, \"97\" => 97, \"98\" => 98, \"99\" => 99, \"100\" => 100, \"101\" => 101, \"102\" => 102, \"103\" => 103, \"104\" => 104, \"105\" => 105, \"106\" => 106, \"107\" => 107, \"108\" => 108, \"109\" => 109, \"110\" => 110, \"111\" => 111, \"112\" => 112, \"113\" => 113, \"114\" => 114, \"115\" => 115, \"116\" => 116, \"117\" => 117, \"118\" => 118, \"119\" => 119, \"120\" => 120, \"121\" => 121, \"122\" => 122, \"123\" => 123, \"124\" => 124, \"125\" => 125, \"126\" => 126, \"127\" => 127, \"128\" => 128, \"129\" => 129, \"130\" => 130, \"131\" => 131, \"132\" => 132, \"133\" => 133, \"134\" => 134, \"135\" => 135, \"136\" => 136, \"137\" => 137, \"138\" => 138, \"139\" => 139, \"140\" => 140, \"141\" => 141, \"142\" => 142, \"143\" => 143, \"144\" => 144, \"145\" => 145, \"146\" => 146, \"147\" => 147, \"148\" => 148, \"149\" => 149, \"150\" => 150, \"151\" => 151, \"152\" => 152, \"153\" => 153, \"154\" => 154, \"155\" => 155, \"156\" => 156, \"157\" => 157, \"158\" => 158, \"159\" => 159, \"160\" => 160, \"161\" => 161, \"162\" => 162, \"163\" => 163, \"164\" => 164, \"165\" => 165, \"166\" => 166, \"167\" => 167, \"168\" => 168, \"169\" => 169, \"170\" => 170, \"171\" => 171, \"172\" => 172, \"173\" => 173, \"174\" => 174, \"175\" => 175, \"176\" => 176, \"177\" => 177, \"178\" => 178, \"179\" => 179, \"180\" => 180, \"181\" => 181, \"182\" => 182, \"183\" => 183, \"184\" => 184, \"185\" => 185, \"186\" => 186, \"187\" => 187, \"188\" => 188, \"189\" => 189, \"190\" => 190, \"191\" => 191, \"192\" => 192, \"193\" => 193, \"194\" => 194, \"195\" => 195, \"196\" => 196, \"197\" => 197, \"198\" => 198, \"199\" => 199, \"200\" => 200, \"201\" => 201, \"202\" => 202, \"203\" => 203, \"204\" => 204, \"205\" => 205, \"206\" => 206, \"207\" => 207, \"208\" => 208, \"209\" => 209, \"210\" => 210, \"211\" => 211, \"212\" => 212, \"213\" => 213, \"214\" => 214, \"215\" => 215, \"216\" => 216, \"217\" => 217, \"218\" => 218, \"219\" => 219, \"220\" => 220, \"221\" => 221, \"222\" => 222, \"223\" => 223, \"224\" => 224, \"225\" => 225, \"226\" => 226, \"227\" => 227, \"228\" => 228, \"229\" => 229, \"230\" => 230, \"231\" => 231, \"232\" => 232, \"233\" => 233, \"234\" => 234, \"235\" => 235, \"236\" => 236, \"237\" => 237, \"238\" => 238, \"239\" => 239, \"240\" => 240, \"241\" => 241, \"242\" => 242, \"243\" => 243, \"244\" => 244, \"245\" => 245, \"246\" => 246, \"247\" => 247, \"248\" => 248, \"249\" => 249, \"250\" => 250, \"251\" => 251, \"252\" => 252, \"253\" => 253, \"254\" => 254, \"255\" => 255, \"256\" => 256, \"257\" => 257, \"258\" => 258, \"259\" => 259, \"260\" => 260, \"261\" => 261, \"262\" => 262, \"263\" => 263, \"264\" => 264, \"265\" => 265, \"266\" => 266, \"267\" => 267, \"268\" => 268, \"269\" => 269, \"270\" => 270, \"271\" => 271, \"272\" => 272, \"273\" => 273, \"274\" => 274, \"275\" => 275, \"276\" => 276, \"277\" => 277, \"278\" => 278, \"279\" => 279, \"280\" => 280, \"281\" => 281, \"282\" => 282, \"283\" => 283, \"284\" => 284, \"285\" => 285, \"286\" => 286, \"287\" => 287, \"288\" => 288, \"289\" => 289, \"290\" => 290, \"291\" => 291, \"292\" => 292, \"293\" => 293, \"294\" => 294, \"295\" => 295, \"296\" => 296, \"297\" => 297, \"298\" => 298, \"299\" => 299, \"300\" => 300, \"301\" => 301, \"302\" => 302, \"303\" => 303, \"304\" => 304, \"305\" => 305, \"306\" => 306, \"307\" => 307, \"308\" => 308, \"309\" => 309, \"310\" => 310, \"311\" => 311, \"312\" => 312, \"313\" => 313, \"314\" => 314, \"315\" => 315, \"316\" => 316, \"317\" => 317, \"318\" => 318, \"319\" => 319, \"320\" => 320, \"321\" => 321, \"322\" => 322, \"323\" => 323, \"324\" => 324, \"325\" => 325, \"326\" => 326, \"327\" => 327, \"328\" => 328, \"329\" => 329, \"330\" => 330, \"331\" => 331, \"332\" => 332, \"333\" => 333, \"334\" => 334, \"335\" => 335, \"336\" => 336, \"337\" => 337, \"338\" => 338, \"339\" => 339, \"340\" => 340, \"341\" => 341, \"342\" => 342, \"343\" => 343, \"344\" => 344, \"345\" => 345, \"346\" => 346, \"347\" => 347, \"348\" => 348, \"349\" => 349, \"350\" => 350, \"351\" => 351, \"352\" => 352, \"353\" => 353, \"354\" => 354, \"355\" => 355, \"356\" => 356, \"357\" => 357, \"358\" => 358, \"359\" => 359, \"360\" => 360, \"361\" => 361, \"362\" => 362, \"363\" => 363, \"364\" => 364, \"365\" => 365, \"366\" => 366, \"367\" => 367, \"368\" => 368, \"369\" => 369, \"370\" => 370, \"371\" => 371, \"372\" => 372, \"373\" => 373, \"374\" => 374, \"375\" => 375, \"376\" => 376, \"377\" => 377, \"378\" => 378, \"379\" => 379, \"380\" => 380, \"381\" => 381, \"382\" => 382, \"383\" => 383, \"384\" => 384, \"385\" => 385, \"386\" => 386, \"387\" => 387, \"388\" => 388, \"389\" => 389, \"390\" => 390, \"391\" => 391, \"392\" => 392, \"393\" => 393, \"394\" => 394, \"395\" => 395, \"396\" => 396, \"397\" => 397, \"398\" => 398, \"399\" => 399, \"400\" => 400, \"401\" => 401, \"402\" => 402, \"403\" => 403, \"404\" => 404, \"405\" => 405, \"406\" => 406, \"407\" => 407, \"408\" => 408, \"409\" => 409, \"410\" => 410, \"411\" => 411, \"412\" => 412, \"413\" => 413, \"414\" => 414, \"415\" => 415, \"416\" => 416, \"417\" => 417, \"418\" => 418, \"419\" => 419, \"420\" => 420, \"421\" => 421, \"422\" => 422, \"423\" => 423, \"424\" => 424, \"425\" => 425, \"426\" => 426, \"427\" => 427, \"428\" => 428, \"429\" => 429, \"430\" => 430, \"431\" => 431, \"432\" => 432, \"433\" => 433, \"434\" => 434, \"435\" => 435, \"436\" => 436, \"437\" => 437, \"438\" => 438, \"439\" => 439, \"440\" => 440, \"441\" => 441, \"442\" => 442, \"443\" => 443, \"444\" => 444, \"445\" => 445, \"446\" => 446, \"447\" => 447, \"448\" => 448, \"449\" => 449, \"450\" => 450, \"451\" => 451, \"452\" => 452, \"453\" => 453, \"454\" => 454, \"455\" => 455, \"456\" => 456, \"457\" => 457, \"458\" => 458, \"459\" => 459, \"460\" => 460, \"461\" => 461, \"462\" => 462, \"463\" => 463, \"464\" => 464, \"465\" => 465, \"466\" => 466, \"467\" => 467, \"468\" => 468, \"469\" => 469, \"470\" => 470, \"471\" => 471, \"472\" => 472, \"473\" => 473, \"474\" => 474, \"475\" => 475, \"476\" => 476, \"477\" => 477, \"478\" => 478, \"479\" => 479, \"480\" => 480, \"481\" => 481, \"482\" => 482, \"483\" => 483, \"484\" => 484, \"485\" => 485, \"486\" => 486, \"487\" => 487, \"488\" => 488, \"489\" => 489, \"490\" => 490, \"491\" => 491, \"492\" => 492, \"493\" => 493, \"494\" => 494, \"495\" => 495, \"496\" => 496, \"497\" => 497, \"498\" => 498, \"499\" => 499, \"500\" => 500, \"501\" => 501, \"502\" => 502, \"503\" => 503, \"504\" => 504, \"505\" => 505, \"506\" => 506, \"507\" => 507, \"508\" => 508, \"509\" => 509, \"510\" => 510, \"511\" => 511, \"512\" => 512, \"513\" => 513, \"514\" => 514, \"515\" => 515, \"516\" => 516, \"517\" => 517, \"518\" => 518, \"519\" => 519, \"520\" => 520, \"521\" => 521, \"522\" => 522, \"523\" => 523, \"524\" => 524, \"525\" => 525, \"526\" => 526, \"527\" => 527, \"528\" => 528, \"529\" => 529, \"530\" => 530, \"531\" => 531, \"532\" => 532, \"533\" => 533, \"534\" => 534, \"535\" => 535, \"536\" => 536, \"537\" => 537, \"538\" => 538, \"539\" => 539, \"540\" => 540, \"541\" => 541, \"542\" => 542, \"543\" => 543, \"544\" => 544, \"545\" => 545, \"546\" => 546, \"547\" => 547, \"548\" => 548, \"549\" => 549, \"550\" => 550, \"551\" => 551, \"552\" => 552, \"553\" => 553, \"554\" => 554, \"555\" => 555, \"556\" => 556, \"557\" => 557, \"558\" => 558, \"559\" => 559, \"560\" => 560, \"561\" => 561, \"562\" => 562, \"563\" => 563, \"564\" => 564, \"565\" => 565, \"566\" => 566, \"567\" => 567, \"568\" => 568, \"569\" => 569, \"570\" => 570, \"571\" => 571, \"572\" => 572, \"573\" => 573, \"574\" => 574, \"575\" => 575, \"576\" => 576, \"577\" => 577, \"578\" => 578, \"579\" => 579, \"580\" => 580, \"581\" => 581, \"582\" => 582, \"583\" => 583, \"584\" => 584, \"585\" => 585, \"586\" => 586, \"587\" => 587, \"588\" => 588, \"589\" => 589, \"590\" => 590, \"591\" => 591, \"592\" => 592, \"593\" => 593, \"594\" => 594, \"595\" => 595, \"596\" => 596, \"597\" => 597, \"598\" => 598, \"599\" => 599, \"600\" => 600, \"601\" => 601, \"602\" => 602, \"603\" => 603, \"604\" => 604, \"605\" => 605, \"606\" => 606, \"607\" => 607, \"608\" => 608, \"609\" => 609, \"610\" => 610, \"611\" => 611, \"612\" => 612, \"613\" => 613, \"614\" => 614, \"615\" => 615, \"616\" => 616, \"617\" => 617, \"618\" => 618, \"619\" => 619, \"620\" => 620, \"621\" => 621, \"622\" => 622, \"623\" => 623, \"624\" => 624, \"625\" => 625, \"626\" => 626, \"627\" => 627, \"628\" => 628, \"629\" => 629, \"630\" => 630, \"631\" => 631, \"632\" => 632, \"633\" => 633, \"634\" => 634, \"635\" => 635, \"636\" => 636, \"637\" => 637, \"638\" => 638, \"639\" => 639, \"640\" => 640, \"641\" => 641, \"642\" => 642, \"643\" => 643, \"644\" => 644, \"645\" => 645, \"646\" => 646, \"647\" => 647, \"648\" => 648, \"649\" => 649, \"650\" => 650, \"651\" => 651, \"652\" => 652, \"653\" => 653, \"654\" => 654, \"655\" => 655, \"656\" => 656, \"657\" => 657, \"658\" => 658, \"659\" => 659, \"660\" => 660, \"661\" => 661, \"662\" => 662, \"663\" => 663, \"664\" => 664, \"665\" => 665, \"666\" => 666, \"667\" => 667, \"668\" => 668, \"669\" => 669, \"670\" => 670, \"671\" => 671, \"672\" => 672, \"673\" => 673, \"674\" => 674, \"675\" => 675, \"676\" => 676, \"677\" => 677, \"678\" => 678, \"679\" => 679, \"680\" => 680, \"681\" => 681, \"682\" => 682, \"683\" => 683, \"684\" => 684, \"685\" => 685, \"686\" => 686, \"687\" => 687, \"688\" => 688, \"689\" => 689, \"690\" => 690, \"691\" => 691, \"692\" => 692, \"693\" => 693, \"694\" => 694, \"695\" => 695, \"696\" => 696, \"697\" => 697, \"698\" => 698, \"699\" => 699, \"700\" => 700, \"701\" => 701, \"702\" => 702, \"703\" => 703, \"704\" => 704, \"705\" => 705, \"706\" => 706, \"707\" => 707, \"708\" => 708, \"709\" => 709, \"710\" => 710, \"711\" => 711, \"712\" => 712, \"713\" => 713, \"714\" => 714, \"715\" => 715, \"716\" => 716, \"717\" => 717, \"718\" => 718, \"719\" => 719, \"720\" => 720, \"721\" => 721, \"722\" => 722, \"723\" => 723, \"724\" => 724, \"725\" => 725, \"726\" => 726, \"727\" => 727, \"728\" => 728, \"729\" => 729, \"730\" => 730, \"731\" => 731, \"732\" => 732, \"733\" => 733, \"734\" => 734, \"735\" => 735, \"736\" => 736, \"737\" => 737, \"738\" => 738, \"739\" => 739, \"740\" => 740, \"741\" => 741, \"742\" => 742, \"743\" => 743, \"744\" => 744, \"745\" => 745, \"746\" => 746, \"747\" => 747, \"748\" => 748, \"749\" => 749, \"750\" => 750, \"751\" => 751, \"752\" => 752, \"753\" => 753, \"754\" => 754, \"755\" => 755, \"756\" => 756, \"757\" => 757, \"758\" => 758, \"759\" => 759, \"760\" => 760, \"761\" => 761, \"762\" => 762, \"763\" => 763, \"764\" => 764, \"765\" => 765, \"766\" => 766, \"767\" => 767, \"768\" => 768, \"769\" => 769, \"770\" => 770, \"771\" => 771, \"772\" => 772, \"773\" => 773, \"774\" => 774, \"775\" => 775, \"776\" => 776, \"777\" => 777, \"778\" => 778, \"779\" => 779, \"780\" => 780, \"781\" => 781, \"782\" => 782, \"783\" => 783, \"784\" => 784, \"785\" => 785, \"786\" => 786, \"787\" => 787, \"788\" => 788, \"789\" => 789, \"790\" => 790, \"791\" => 791, \"792\" => 792, \"793\" => 793, \"794\" => 794, \"795\" => 795, \"796\" => 796, \"797\" => 797, \"798\" => 798, \"799\" => 799, \"800\" => 800, \"801\" => 801, \"802\" => 802, \"803\" => 803, \"804\" => 804, \"805\" => 805, \"806\" => 806, \"807\" => 807, \"808\" => 808, \"809\" => 809, \"810\" => 810, \"811\" => 811, \"812\" => 812, \"813\" => 813, \"814\" => 814, \"815\" => 815, \"816\" => 816, \"817\" => 817, \"818\" => 818, \"819\" => 819, \"820\" => 820, \"821\" => 821, \"822\" => 822, \"823\" => 823, \"824\" => 824, \"825\" => 825, \"826\" => 826, \"827\" => 827, \"828\" => 828, \"829\" => 829, \"830\" => 830, \"831\" => 831, \"832\" => 832, \"833\" => 833, \"834\" => 834, \"835\" => 835, \"836\" => 836, \"837\" => 837, \"838\" => 838, \"839\" => 839, \"840\" => 840, \"841\" => 841, \"842\" => 842, \"843\" => 843, \"844\" => 844, \"845\" => 845, \"846\" => 846, \"847\" => 847, \"848\" => 848, \"849\" => 849, \"850\" => 850, \"851\" => 851, \"852\" => 852, \"853\" => 853, \"854\" => 854, \"855\" => 855, \"856\" => 856, \"857\" => 857, \"858\" => 858, \"859\" => 859, \"860\" => 860, \"861\" => 861, \"862\" => 862, \"863\" => 863, \"864\" => 864, \"865\" => 865, \"866\" => 866, \"867\" => 867, \"868\" => 868, \"869\" => 869, \"870\" => 870, \"871\" => 871, \"872\" => 872, \"873\" => 873, \"874\" => 874, \"875\" => 875, \"876\" => 876, \"877\" => 877, \"878\" => 878, \"879\" => 879, \"880\" => 880, \"881\" => 881, \"882\" => 882, \"883\" => 883, \"884\" => 884, \"885\" => 885, \"886\" => 886, \"887\" => 887, \"888\" => 888, \"889\" => 889, \"890\" => 890, \"891\" => 891, \"892\" => 892, \"893\" => 893, \"894\" => 894, \"895\" => 895, \"896\" => 896, \"897\" => 897, \"898\" => 898, \"899\" => 899, \"900\" => 900, \"901\" => 901, \"902\" => 902, \"903\" => 903, \"904\" => 904, \"905\" => 905, \"906\" => 906, \"907\" => 907, \"908\" => 908, \"909\" => 909, \"910\" => 910, \"911\" => 911, \"912\" => 912, \"913\" => 913, \"914\" => 914, \"915\" => 915, \"916\" => 916, \"917\" => 917, \"918\" => 918, \"919\" => 919, \"920\" => 920, \"921\" => 921, \"922\" => 922, \"923\" => 923, \"924\" => 924, \"925\" => 925, \"926\" => 926, \"927\" => 927, \"928\" => 928, \"929\" => 929, \"930\" => 930, \"931\" => 931, \"932\" => 932, \"933\" => 933, \"934\" => 934, \"935\" => 935, \"936\" => 936, \"937\" => 937, \"938\" => 938, \"939\" => 939, \"940\" => 940, \"941\" => 941, \"942\" => 942, \"943\" => 943, \"944\" => 944, \"945\" => 945, \"946\" => 946, \"947\" => 947, \"948\" => 948, \"949\" => 949, \"950\" => 950, \"951\" => 951, \"952\" => 952, \"953\" => 953, \"954\" => 954, \"955\" => 955, \"956\" => 956, \"957\" => 957, \"958\" => 958, \"959\" => 959, \"960\" => 960, \"961\" => 961, \"962\" => 962, \"963\" => 963, \"964\" => 964, \"965\" => 965, \"966\" => 966, \"967\" => 967, \"968\" => 968, \"969\" => 969, \"970\" => 970, \"971\" => 971, \"972\" => 972, \"973\" => 973, \"974\" => 974, \"975\" => 975, \"976\" => 976, \"977\" => 977, \"978\" => 978, \"979\" => 979, \"980\" => 980, \"981\" => 981, \"982\" => 982, \"983\" => 983, \"984\" => 984, \"985\" => 985, \"986\" => 986, \"987\" => 987, \"988\" => 988, \"989\" => 989, \"990\" => 990, \"991\" => 991, \"992\" => 992, \"993\" => 993, \"994\" => 994, \"995\" => 995, \"996\" => 996, \"997\" => 997, \"998\" => 998, \"999\" => 999, \"1000\" => 1000, \"1001\" => 1001, \"1002\" => 1002, \"1003\" => 1003, \"1004\" => 1004, \"1005\" => 1005, \"1006\" => 1006, \"1007\" => 1007, \"1008\" => 1008, \"1009\" => 1009, \"1010\" => 1010, \"1011\" => 1011, \"1012\" => 1012, \"1013\" => 1013, \"1014\" => 1014, \"1015\" => 1015, \"1016\" => 1016, \"1017\" => 1017, \"1018\" => 1018, \"1019\" => 1019, \"1020\" => 1020, \"1021\" => 1021, \"1022\" => 1022, \"1023\" => 1023, \"1024\" => 1024, \"1025\" => 1025, \"1026\" => 1026, \"1027\" => 1027, \"1028\" => 1028, \"1029\" => 1029, \"1030\" => 1030, \"1031\" => 1031, \"1032\" => 1032, \"1033\" => 1033, \"1034\" => 1034, \"1035\" => 1035, \"1036\" => 1036, \"1037\" => 1037, \"1038\" => 1038, \"1039\" => 1039, \"1040\" => 1040, \"1041\" => 1041, \"1042\" => 1042, \"1043\" => 1043, \"1044\" => 1044, \"1045\" => 1045, \"1046\" => 1046, \"1047\" => 1047, \"1048\" => 1048, \"1049\" => 1049, \"1050\" => 1050, \"1051\" => 1051, \"1052\" => 1052, \"1053\" => 1053, \"1054\" => 1054, \"1055\" => 1055, \"1056\" => 1056, \"1057\" => 1057, \"1058\" => 1058, \"1059\" => 1059, \"1060\" => 1060, \"1061\" => 1061, \"1062\" => 1062, \"1063\" => 1063, \"1064\" => 1064, \"1065\" => 1065, \"1066\" => 1066, \"1067\" => 1067, \"1068\" => 1068, \"1069\" => 1069, \"1070\" => 1070, \"1071\" => 1071, \"1072\" => 1072, \"1073\" => 1073, \"1074\" => 1074, \"1075\" => 1075, \"1076\" => 1076, \"1077\" => 1077, \"1078\" => 1078, \"1079\" => 1079, \"1080\" => 1080, \"1081\" => 1081, \"1082\" => 1082, \"1083\" => 1083, \"1084\" => 1084, \"1085\" => 1085, \"1086\" => 1086, \"1087\" => 1087, \"1088\" => 1088, \"1089\" => 1089, \"1090\" => 1090, \"1091\" => 1091, \"1092\" => 1092, \"1093\" => 1093, \"1094\" => 1094, \"1095\" => 1095, \"1096\" => 1096, \"1097\" => 1097, \"1098\" => 1098, \"1099\" => 1099, \"1100\" => 1100, \"1101\" => 1101, \"1102\" => 1102, \"1103\" => 1103, \"1104\" => 1104, \"1105\" => 1105, \"1106\" => 1106, \"1107\" => 1107, \"1108\" => 1108, \"1109\" => 1109, \"1110\" => 1110, \"1111\" => 1111, \"1112\" => 1112, \"1113\" => 1113, \"1114\" => 1114, \"1115\" => 1115, \"1116\" => 1116, \"1117\" => 1117, \"1118\" => 1118, \"1119\" => 1119, \"1120\" => 1120, \"1121\" => 1121, \"1122\" => 1122, \"1123\" => 1123, \"1124\" => 1124, \"1125\" => 1125, \"1126\" => 1126, \"1127\" => 1127, \"1128\" => 1128, \"1129\" => 1129, \"1130\" => 1130, \"1131\" => 1131, \"1132\" => 1132, \"1133\" => 1133, \"1134\" => 1134, \"1135\" => 1135, \"1136\" => 1136, \"1137\" => 1137, \"1138\" => 1138, \"1139\" => 1139, \"1140\" => 1140, \"1141\" => 1141, \"1142\" => 1142, \"1143\" => 1143, \"1144\" => 1144, \"1145\" => 1145, \"1146\" => 1146, \"1147\" => 1147, \"1148\" => 1148, \"1149\" => 1149, \"1150\" => 1150, \"1151\" => 1151, \"1152\" => 1152, \"1153\" => 1153, \"1154\" => 1154, \"1155\" => 1155, \"1156\" => 1156, \"1157\" => 1157, \"1158\" => 1158, \"1159\" => 1159, \"1160\" => 1160, \"1161\" => 1161, \"1162\" => 1162, \"1163\" => 1163, \"1164\" => 1164, \"1165\" => 1165, \"1166\" => 1166, \"1167\" => 1167, \"1168\" => 1168, \"1169\" => 1169, \"1170\" => 1170, \"1171\" => 1171, \"1172\" => 1172, \"1173\" => 1173, \"1174\" => 1174, \"1175\" => 1175, \"1176\" => 1176, \"1177\" => 1177, \"1178\" => 1178, \"1179\" => 1179, \"1180\" => 1180, \"1181\" => 1181, \"1182\" => 1182, \"1183\" => 1183, \"1184\" => 1184, \"1185\" => 1185, \"1186\" => 1186, \"1187\" => 1187, \"1188\" => 1188, \"1189\" => 1189, \"1190\" => 1190, \"1191\" => 1191, \"1192\" => 1192, \"1193\" => 1193, \"1194\" => 1194, \"1195\" => 1195, \"1196\" => 1196, \"1197\" => 1197, \"1198\" => 1198, \"1199\" => 1199, \"1200\" => 1200, \"1201\" => 1201, \"1202\" => 1202, \"1203\" => 1203, \"1204\" => 1204, \"1205\" => 1205, \"1206\" => 1206, \"1207\" => 1207, \"1208\" => 1208, \"1209\" => 1209, \"1210\" => 1210, \"1211\" => 1211, \"1212\" => 1212, \"1213\" => 1213, \"1214\" => 1214, \"1215\" => 1215, \"1216\" => 1216, \"1217\" => 1217, \"1218\" => 1218, \"1219\" => 1219, \"1220\" => 1220, \"1221\" => 1221, \"1222\" => 1222, \"1223\" => 1223, \"1224\" => 1224, \"1225\" => 1225, \"1226\" => 1226, \"1227\" => 1227, \"1228\" => 1228, \"1229\" => 1229, \"1230\" => 1230, \"1231\" => 1231, \"1232\" => 1232, \"1233\" => 1233, \"1234\" => 1234, \"1235\" => 1235, \"1236\" => 1236, \"1237\" => 1237, \"1238\" => 1238, \"1239\" => 1239, \"1240\" => 1240, \"1241\" => 1241, \"1242\" => 1242, \"1243\" => 1243, \"1244\" => 1244, \"1245\" => 1245, \"1246\" => 1246, \"1247\" => 1247, \"1248\" => 1248, \"1249\" => 1249, \"1250\" => 1250, \"1251\" => 1251, \"1252\" => 1252, \"1253\" => 1253, \"1254\" => 1254, \"1255\" => 1255, \"1256\" => 1256, \"1257\" => 1257, \"1258\" => 1258, \"1259\" => 1259, \"1260\" => 1260, \"1261\" => 1261, \"1262\" => 1262, \"1263\" => 1263, \"1264\" => 1264, \"1265\" => 1265, \"1266\" => 1266, \"1267\" => 1267, \"1268\" => 1268, \"1269\" => 1269, \"1270\" => 1270, \"1271\" => 1271, \"1272\" => 1272, \"1273\" => 1273, \"1274\" => 1274, \"1275\" => 1275, \"1276\" => 1276, \"1277\" => 1277, \"1278\" => 1278, \"1279\" => 1279, \"1280\" => 1280, \"1281\" => 1281, \"1282\" => 1282, \"1283\" => 1283, \"1284\" => 1284, \"1285\" => 1285, \"1286\" => 1286, \"1287\" => 1287, \"1288\" => 1288, \"1289\" => 1289, \"1290\" => 1290, \"1291\" => 1291, \"1292\" => 1292, \"1293\" => 1293, \"1294\" => 1294, \"1295\" => 1295, \"1296\" => 1296, \"1297\" => 1297, \"1298\" => 1298, \"1299\" => 1299, \"1300\" => 1300, \"1301\" => 1301, \"1302\" => 1302, \"1303\" => 1303, \"1304\" => 1304, \"1305\" => 1305, \"1306\" => 1306, \"1307\" => 1307, \"1308\" => 1308, \"1309\" => 1309, \"1310\" => 1310, \"1311\" => 1311, \"1312\" => 1312, \"1313\" => 1313, \"1314\" => 1314, \"1315\" => 1315, \"1316\" => 1316, \"1317\" => 1317, \"1318\" => 1318, \"1319\" => 1319, \"1320\" => 1320, \"1321\" => 1321, \"1322\" => 1322, \"1323\" => 1323, \"1324\" => 1324, \"1325\" => 1325, \"1326\" => 1326, \"1327\" => 1327, \"1328\" => 1328, \"1329\" => 1329, \"1330\" => 1330, \"1331\" => 1331, \"1332\" => 1332, \"1333\" => 1333, \"1334\" => 1334, \"1335\" => 1335, \"1336\" => 1336, \"1337\" => 1337, \"1338\" => 1338, \"1339\" => 1339, \"1340\" => 1340, \"1341\" => 1341, \"1342\" => 1342, \"1343\" => 1343, \"1344\" => 1344, \"1345\" => 1345, \"1346\" => 1346, \"1347\" => 1347, \"1348\" => 1348, \"1349\" => 1349, \"1350\" => 1350, \"1351\" => 1351, \"1352\" => 1352, \"1353\" => 1353, \"1354\" => 1354, \"1355\" => 1355, \"1356\" => 1356, \"1357\" => 1357, \"1358\" => 1358, \"1359\" => 1359, \"1360\" => 1360, \"1361\" => 1361, \"1362\" => 1362, \"1363\" => 1363, \"1364\" => 1364, \"1365\" => 1365, \"1366\" => 1366, \"1367\" => 1367, \"1368\" => 1368, \"1369\" => 1369, \"1370\" => 1370, \"1371\" => 1371, \"1372\" => 1372, \"1373\" => 1373, \"1374\" => 1374, \"1375\" => 1375, \"1376\" => 1376, \"1377\" => 1377, \"1378\" => 1378, \"1379\" => 1379, \"1380\" => 1380, \"1381\" => 1381, \"1382\" => 1382, \"1383\" => 1383, \"1384\" => 1384, \"1385\" => 1385, \"1386\" => 1386, \"1387\" => 1387, \"1388\" => 1388, \"1389\" => 1389, \"1390\" => 1390, \"1391\" => 1391, \"1392\" => 1392, \"1393\" => 1393, \"1394\" => 1394, \"1395\" => 1395, \"1396\" => 1396, \"1397\" => 1397, \"1398\" => 1398, \"1399\" => 1399, \"1400\" => 1400, \"1401\" => 1401, \"1402\" => 1402, \"1403\" => 1403, \"1404\" => 1404, \"1405\" => 1405, \"1406\" => 1406, \"1407\" => 1407, \"1408\" => 1408, \"1409\" => 1409, \"1410\" => 1410, \"1411\" => 1411, \"1412\" => 1412, \"1413\" => 1413, \"1414\" => 1414, \"1415\" => 1415, \"1416\" => 1416, \"1417\" => 1417, \"1418\" => 1418, \"1419\" => 1419, \"1420\" => 1420, \"1421\" => 1421, \"1422\" => 1422, \"1423\" => 1423, \"1424\" => 1424, \"1425\" => 1425, \"1426\" => 1426, \"1427\" => 1427, \"1428\" => 1428, \"1429\" => 1429, \"1430\" => 1430, \"1431\" => 1431, \"1432\" => 1432, \"1433\" => 1433, \"1434\" => 1434, \"1435\" => 1435, \"1436\" => 1436, \"1437\" => 1437, \"1438\" => 1438, \"1439\" => 1439, \"1440\" => 1440, \"1441\" => 1441, \"1442\" => 1442, \"1443\" => 1443, \"1444\" => 1444, \"1445\" => 1445, \"1446\" => 1446, \"1447\" => 1447, \"1448\" => 1448, \"1449\" => 1449, \"1450\" => 1450, \"1451\" => 1451, \"1452\" => 1452, \"1453\" => 1453, \"1454\" => 1454, \"1455\" => 1455, \"1456\" => 1456, \"1457\" => 1457, \"1458\" => 1458, \"1459\" => 1459, \"1460\" => 1460, \"1461\" => 1461, \"1462\" => 1462, \"1463\" => 1463, \"1464\" => 1464, \"1465\" => 1465, \"1466\" => 1466, \"1467\" => 1467, \"1468\" => 1468, \"1469\" => 1469, \"1470\" => 1470, \"1471\" => 1471, \"1472\" => 1472, \"1473\" => 1473, \"1474\" => 1474, \"1475\" => 1475, \"1476\" => 1476, \"1477\" => 1477, \"1478\" => 1478, \"1479\" => 1479, \"1480\" => 1480, \"1481\" => 1481, \"1482\" => 1482, \"1483\" => 1483, \"1484\" => 1484, \"1485\" => 1485, \"1486\" => 1486, \"1487\" => 1487, \"1488\" => 1488, \"1489\" => 1489, \"1490\" => 1490, \"1491\" => 1491, \"1492\" => 1492, \"1493\" => 1493, \"1494\" => 1494, \"1495\" => 1495, \"1496\" => 1496, \"1497\" => 1497, \"1498\" => 1498, \"1499\" => 1499, \"1500\" => 1500, \"1501\" => 1501, \"1502\" => 1502, \"1503\" => 1503, \"1504\" => 1504, \"1505\" => 1505, \"1506\" => 1506, \"1507\" => 1507, \"1508\" => 1508, \"1509\" => 1509, \"1510\" => 1510, \"1511\" => 1511, \"1512\" => 1512, \"1513\" => 1513, \"1514\" => 1514, \"1515\" => 1515, \"1516\" => 1516, \"1517\" => 1517, \"1518\" => 1518, \"1519\" => 1519, \"1520\" => 1520, \"1521\" => 1521, \"1522\" => 1522, \"1523\" => 1523, \"1524\" => 1524, \"1525\" => 1525, \"1526\" => 1526, \"1527\" => 1527, \"1528\" => 1528, \"1529\" => 1529, \"1530\" => 1530, \"1531\" => 1531, \"1532\" => 1532, \"1533\" => 1533, \"1534\" => 1534, \"1535\" => 1535, \"1536\" => 1536, \"1537\" => 1537, \"1538\" => 1538, \"1539\" => 1539, \"1540\" => 1540, \"1541\" => 1541, \"1542\" => 1542, \"1543\" => 1543, \"1544\" => 1544, \"1545\" => 1545, \"1546\" => 1546, \"1547\" => 1547, \"1548\" => 1548, \"1549\" => 1549, \"1550\" => 1550, \"1551\" => 1551, \"1552\" => 1552, \"1553\" => 1553, \"1554\" => 1554, \"1555\" => 1555, \"1556\" => 1556, \"1557\" => 1557, \"1558\" => 1558, \"1559\" => 1559, \"1560\" => 1560, \"1561\" => 1561, \"1562\" => 1562, \"1563\" => 1563, \"1564\" => 1564, \"1565\" => 1565, \"1566\" => 1566, \"1567\" => 1567, \"1568\" => 1568, \"1569\" => 1569, \"1570\" => 1570, \"1571\" => 1571, \"1572\" => 1572, \"1573\" => 1573, \"1574\" => 1574, \"1575\" => 1575, \"1576\" => 1576, \"1577\" => 1577, \"1578\" => 1578, \"1579\" => 1579, \"1580\" => 1580, \"1581\" => 1581, \"1582\" => 1582, \"1583\" => 1583, \"1584\" => 1584, \"1585\" => 1585, \"1586\" => 1586, \"1587\" => 1587, \"1588\" => 1588, \"1589\" => 1589, \"1590\" => 1590, \"1591\" => 1591, \"1592\" => 1592, \"1593\" => 1593, \"1594\" => 1594, \"1595\" => 1595, \"1596\" => 1596, \"1597\" => 1597, \"1598\" => 1598, \"1599\" => 1599, \"1600\" => 1600, \"1601\" => 1601, \"1602\" => 1602, \"1603\" => 1603, \"1604\" => 1604, \"1605\" => 1605, \"1606\" => 1606, \"1607\" => 1607, \"1608\" => 1608, \"1609\" => 1609, \"1610\" => 1610, \"1611\" => 1611, \"1612\" => 1612, \"1613\" => 1613, \"1614\" => 1614, \"1615\" => 1615, \"1616\" => 1616, \"1617\" => 1617, \"1618\" => 1618, \"1619\" => 1619, \"1620\" => 1620, \"1621\" => 1621, \"1622\" => 1622, \"1623\" => 1623, \"1624\" => 1624, \"1625\" => 1625, \"1626\" => 1626, \"1627\" => 1627, \"1628\" => 1628, \"1629\" => 1629, \"1630\" => 1630, \"1631\" => 1631, \"1632\" => 1632, \"1633\" => 1633, \"1634\" => 1634, \"1635\" => 1635, \"1636\" => 1636, \"1637\" => 1637, \"1638\" => 1638, \"1639\" => 1639, \"1640\" => 1640, \"1641\" => 1641, \"1642\" => 1642, \"1643\" => 1643, \"1644\" => 1644, \"1645\" => 1645, \"1646\" => 1646, \"1647\" => 1647, \"1648\" => 1648, \"1649\" => 1649, \"1650\" => 1650, \"1651\" => 1651, \"1652\" => 1652, \"1653\" => 1653, \"1654\" => 1654, \"1655\" => 1655, \"1656\" => 1656, \"1657\" => 1657, \"1658\" => 1658, \"1659\" => 1659, \"1660\" => 1660, \"1661\" => 1661, \"1662\" => 1662, \"1663\" => 1663, \"1664\" => 1664, \"1665\" => 1665, \"1666\" => 1666, \"1667\" => 1667, \"1668\" => 1668, \"1669\" => 1669, \"1670\" => 1670, \"1671\" => 1671, \"1672\" => 1672, \"1673\" => 1673, \"1674\" => 1674, \"1675\" => 1675, \"1676\" => 1676, \"1677\" => 1677, \"1678\" => 1678, \"1679\" => 1679, \"1680\" => 1680, \"1681\" => 1681, \"1682\" => 1682, \"1683\" => 1683, \"1684\" => 1684, \"1685\" => 1685, \"1686\" => 1686, \"1687\" => 1687, \"1688\" => 1688, \"1689\" => 1689, \"1690\" => 1690, \"1691\" => 1691, \"1692\" => 1692, \"1693\" => 1693, \"1694\" => 1694, \"1695\" => 1695, \"1696\" => 1696, \"1697\" => 1697, \"1698\" => 1698, \"1699\" => 1699, \"1700\" => 1700, \"1701\" => 1701, \"1702\" => 1702, \"1703\" => 1703, \"1704\" => 1704, \"1705\" => 1705, \"1706\" => 1706, \"1707\" => 1707, \"1708\" => 1708, \"1709\" => 1709, \"1710\" => 1710, \"1711\" => 1711, \"1712\" => 1712, \"1713\" => 1713, \"1714\" => 1714, \"1715\" => 1715, \"1716\" => 1716, \"1717\" => 1717, \"1718\" => 1718, \"1719\" => 1719, \"1720\" => 1720, \"1721\" => 1721, \"1722\" => 1722, \"1723\" => 1723, \"1724\" => 1724, \"1725\" => 1725, \"1726\" => 1726, \"1727\" => 1727, \"1728\" => 1728, \"1729\" => 1729, \"1730\" => 1730, \"1731\" => 1731, \"1732\" => 1732, \"1733\" => 1733, \"1734\" => 1734, \"1735\" => 1735, \"1736\" => 1736, \"1737\" => 1737, \"1738\" => 1738, \"1739\" => 1739, \"1740\" => 1740, \"1741\" => 1741, \"1742\" => 1742, \"1743\" => 1743, \"1744\" => 1744, \"1745\" => 1745, \"1746\" => 1746, \"1747\" => 1747, \"1748\" => 1748, \"1749\" => 1749, \"1750\" => 1750, \"1751\" => 1751, \"1752\" => 1752, \"1753\" => 1753, \"1754\" => 1754, \"1755\" => 1755, \"1756\" => 1756, \"1757\" => 1757, \"1758\" => 1758, \"1759\" => 1759, \"1760\" => 1760, \"1761\" => 1761, \"1762\" => 1762, \"1763\" => 1763, \"1764\" => 1764, \"1765\" => 1765, \"1766\" => 1766, \"1767\" => 1767, \"1768\" => 1768, \"1769\" => 1769, \"1770\" => 1770, \"1771\" => 1771, \"1772\" => 1772, \"1773\" => 1773, \"1774\" => 1774, \"1775\" => 1775, \"1776\" => 1776, \"1777\" => 1777, \"1778\" => 1778, \"1779\" => 1779, \"1780\" => 1780, \"1781\" => 1781, \"1782\" => 1782, \"1783\" => 1783, \"1784\" => 1784, \"1785\" => 1785, \"1786\" => 1786, \"1787\" => 1787, \"1788\" => 1788, \"1789\" => 1789, \"1790\" => 1790, \"1791\" => 1791, \"1792\" => 1792, \"1793\" => 1793, \"1794\" => 1794, \"1795\" => 1795, \"1796\" => 1796, \"1797\" => 1797, \"1798\" => 1798, \"1799\" => 1799, \"1800\" => 1800, \"1801\" => 1801, \"1802\" => 1802, \"1803\" => 1803, \"1804\" => 1804, \"1805\" => 1805, \"1806\" => 1806, \"1807\" => 1807, \"1808\" => 1808, \"1809\" => 1809, \"1810\" => 1810, \"1811\" => 1811, \"1812\" => 1812, \"1813\" => 1813, \"1814\" => 1814, \"1815\" => 1815, \"1816\" => 1816, \"1817\" => 1817, \"1818\" => 1818, \"1819\" => 1819, \"1820\" => 1820, \"1821\" => 1821, \"1822\" => 1822, \"1823\" => 1823, \"1824\" => 1824, \"1825\" => 1825, \"1826\" => 1826, \"1827\" => 1827, \"1828\" => 1828, \"1829\" => 1829, \"1830\" => 1830, \"1831\" => 1831, \"1832\" => 1832, \"1833\" => 1833, \"1834\" => 1834, \"1835\" => 1835, \"1836\" => 1836, \"1837\" => 1837, \"1838\" => 1838, \"1839\" => 1839, \"1840\" => 1840, \"1841\" => 1841, \"1842\" => 1842, \"1843\" => 1843, \"1844\" => 1844, \"1845\" => 1845, \"1846\" => 1846, \"1847\" => 1847, \"1848\" => 1848, \"1849\" => 1849, \"1850\" => 1850, \"1851\" => 1851, \"1852\" => 1852, \"1853\" => 1853, \"1854\" => 1854, \"1855\" => 1855, \"1856\" => 1856, \"1857\" => 1857, \"1858\" => 1858, \"1859\" => 1859, \"1860\" => 1860, \"1861\" => 1861, \"1862\" => 1862, \"1863\" => 1863, \"1864\" => 1864, \"1865\" => 1865, \"1866\" => 1866, \"1867\" => 1867, \"1868\" => 1868, \"1869\" => 1869, \"1870\" => 1870, \"1871\" => 1871, \"1872\" => 1872, \"1873\" => 1873, \"1874\" => 1874, \"1875\" => 1875, \"1876\" => 1876, \"1877\" => 1877, \"1878\" => 1878, \"1879\" => 1879, \"1880\" => 1880, \"1881\" => 1881, \"1882\" => 1882, \"1883\" => 1883, \"1884\" => 1884, \"1885\" => 1885, \"1886\" => 1886, \"1887\" => 1887, \"1888\" => 1888, \"1889\" => 1889, \"1890\" => 1890, \"1891\" => 1891, \"1892\" => 1892, \"1893\" => 1893, \"1894\" => 1894, \"1895\" => 1895, \"1896\" => 1896, \"1897\" => 1897, \"1898\" => 1898, \"1899\" => 1899, \"1900\" => 1900, \"1901\" => 1901, \"1902\" => 1902, \"1903\" => 1903, \"1904\" => 1904, \"1905\" => 1905, \"1906\" => 1906, \"1907\" => 1907, \"1908\" => 1908, \"1909\" => 1909, \"1910\" => 1910, \"1911\" => 1911, \"1912\" => 1912, \"1913\" => 1913, \"1914\" => 1914, \"1915\" => 1915, \"1916\" => 1916, \"1917\" => 1917, \"1918\" => 1918, \"1919\" => 1919, \"1920\" => 1920, \"1921\" => 1921, \"1922\" => 1922, \"1923\" => 1923, \"1924\" => 1924, \"1925\" => 1925, \"1926\" => 1926, \"1927\" => 1927, \"1928\" => 1928, \"1929\" => 1929, \"1930\" => 1930, \"1931\" => 1931, \"1932\" => 1932, \"1933\" => 1933, \"1934\" => 1934, \"1935\" => 1935, \"1936\" => 1936, \"1937\" => 1937, \"1938\" => 1938, \"1939\" => 1939, \"1940\" => 1940, \"1941\" => 1941, \"1942\" => 1942, \"1943\" => 1943, \"1944\" => 1944, \"1945\" => 1945, \"1946\" => 1946, \"1947\" => 1947, \"1948\" => 1948, \"1949\" => 1949, \"1950\" => 1950, \"1951\" => 1951, \"1952\" => 1952, \"1953\" => 1953, \"1954\" => 1954, \"1955\" => 1955, \"1956\" => 1956, \"1957\" => 1957, \"1958\" => 1958, \"1959\" => 1959, \"1960\" => 1960, \"1961\" => 1961, \"1962\" => 1962, \"1963\" => 1963, \"1964\" => 1964, \"1965\" => 1965, \"1966\" => 1966, \"1967\" => 1967, \"1968\" => 1968, \"1969\" => 1969, \"1970\" => 1970, \"1971\" => 1971, \"1972\" => 1972, \"1973\" => 1973, \"1974\" => 1974, \"1975\" => 1975, \"1976\" => 1976, \"1977\" => 1977, \"1978\" => 1978, \"1979\" => 1979, \"1980\" => 1980, \"1981\" => 1981, \"1982\" => 1982, \"1983\" => 1983, \"1984\" => 1984, \"1985\" => 1985, \"1986\" => 1986, \"1987\" => 1987, \"1988\" => 1988, \"1989\" => 1989, \"1990\" => 1990, \"1991\" => 1991, \"1992\" => 1992, \"1993\" => 1993, \"1994\" => 1994, \"1995\" => 1995, \"1996\" => 1996, \"1997\" => 1997, \"1998\" => 1998, \"1999\" => 1999, \"2000\" => 2000, \"2001\" => 2001, \"2002\" => 2002, \"2003\" => 2003, \"2004\" => 2004, \"2005\" => 2005, \"2006\" => 2006, \"2007\" => 2007, \"2008\" => 2008, \"2009\" => 2009, \"2010\" => 2010, \"2011\" => 2011, \"2012\" => 2012, \"2013\" => 2013, \"2014\" => 2014, \"2015\" => 2015, \"2016\" => 2016, \"2017\" => 2017, \"2018\" => 2018, \"2019\" => 2019, \"2020\" => 2020, \"2021\" => 2021, \"2022\" => 2022, \"2023\" => 2023, \"2024\" => 2024, \"2025\" => 2025, \"2026\" => 2026, \"2027\" => 2027, \"2028\" => 2028, \"2029\" => 2029, \"2030\" => 2030, \"2031\" => 2031, \"2032\" => 2032, \"2033\" => 2033, \"2034\" => 2034, \"2035\" => 2035, \"2036\" => 2036, \"2037\" => 2037, \"2038\" => 2038, \"2039\" => 2039, \"2040\" => 2040, \"2041\" => 2041, \"2042\" => 2042, \"2043\" => 2043, \"2044\" => 2044, \"2045\" => 2045, \"2046\" => 2046, \"2047\" => 2047, \"2048\" => 2048, \"2049\" => 2049, \"2050\" => 2050, \"2051\" => 2051, \"2052\" => 2052, \"2053\" => 2053, \"2054\" => 2054, \"2055\" => 2055, \"2056\" => 2056, \"2057\" => 2057, \"2058\" => 2058, \"2059\" => 2059, \"2060\" => 2060, \"2061\" => 2061, \"2062\" => 2062, \"2063\" => 2063, \"2064\" => 2064, \"2065\" => 2065, \"2066\" => 2066, \"2067\" => 2067, \"2068\" => 2068, \"2069\" => 2069, \"2070\" => 2070, \"2071\" => 2071, \"2072\" => 2072, \"2073\" => 2073, \"2074\" => 2074, \"2075\" => 2075, \"2076\" => 2076, \"2077\" => 2077, \"2078\" => 2078, \"2079\" => 2079, \"2080\" => 2080, \"2081\" => 2081, \"2082\" => 2082, \"2083\" => 2083, \"2084\" => 2084, \"2085\" => 2085, \"2086\" => 2086, \"2087\" => 2087, \"2088\" => 2088, \"2089\" => 2089, \"2090\" => 2090, \"2091\" => 2091, \"2092\" => 2092, \"2093\" => 2093, \"2094\" => 2094, \"2095\" => 2095, \"2096\" => 2096, \"2097\" => 2097, \"2098\" => 2098, \"2099\" => 2099, \"2100\" => 2100, \"2101\" => 2101, \"2102\" => 2102, \"2103\" => 2103, \"2104\" => 2104, \"2105\" => 2105, \"2106\" => 2106, \"2107\" => 2107, \"2108\" => 2108, \"2109\" => 2109, \"2110\" => 2110, \"2111\" => 2111, \"2112\" => 2112, \"2113\" => 2113, \"2114\" => 2114, \"2115\" => 2115, \"2116\" => 2116, \"2117\" => 2117, \"2118\" => 2118, \"2119\" => 2119, \"2120\" => 2120, \"2121\" => 2121, \"2122\" => 2122, \"2123\" => 2123, \"2124\" => 2124, \"2125\" => 2125, \"2126\" => 2126, \"2127\" => 2127, \"2128\" => 2128, \"2129\" => 2129, \"2130\" => 2130, \"2131\" => 2131, \"2132\" => 2132, \"2133\" => 2133, \"2134\" => 2134, \"2135\" => 2135, \"2136\" => 2136, \"2137\" => 2137, \"2138\" => 2138, \"2139\" => 2139, \"2140\" => 2140, \"2141\" => 2141, \"2142\" => 2142, \"2143\" => 2143, \"2144\" => 2144, \"2145\" => 2145, \"2146\" => 2146, \"2147\" => 2147, \"2148\" => 2148, \"2149\" => 2149, \"2150\" => 2150, \"2151\" => 2151, \"2152\" => 2152, \"2153\" => 2153, \"2154\" => 2154, \"2155\" => 2155, \"2156\" => 2156, \"2157\" => 2157, \"2158\" => 2158, \"2159\" => 2159, \"2160\" => 2160, \"2161\" => 2161, \"2162\" => 2162, \"2163\" => 2163, \"2164\" => 2164, \"2165\" => 2165, \"2166\" => 2166, \"2167\" => 2167, \"2168\" => 2168, \"2169\" => 2169, \"2170\" => 2170, \"2171\" => 2171, \"2172\" => 2172, \"2173\" => 2173, \"2174\" => 2174, \"2175\" => 2175, \"2176\" => 2176, \"2177\" => 2177, \"2178\" => 2178, \"2179\" => 2179, \"2180\" => 2180, \"2181\" => 2181, \"2182\" => 2182, \"2183\" => 2183, \"2184\" => 2184, \"2185\" => 2185, \"2186\" => 2186, \"2187\" => 2187, \"2188\" => 2188, \"2189\" => 2189, \"2190\" => 2190, \"2191\" => 2191, \"2192\" => 2192, \"2193\" => 2193, \"2194\" => 2194, \"2195\" => 2195, \"2196\" => 2196, \"2197\" => 2197, \"2198\" => 2198, \"2199\" => 2199, \"2200\" => 2200, \"2201\" => 2201, \"2202\" => 2202, \"2203\" => 2203, \"2204\" => 2204, \"2205\" => 2205, \"2206\" => 2206, \"2207\" => 2207, \"2208\" => 2208, \"2209\" => 2209, \"2210\" => 2210, \"2211\" => 2211, \"2212\" => 2212, \"2213\" => 2213, \"2214\" => 2214, \"2215\" => 2215, \"2216\" => 2216, \"2217\" => 2217, \"2218\" => 2218, \"2219\" => 2219, \"2220\" => 2220, \"2221\" => 2221, \"2222\" => 2222, \"2223\" => 2223, \"2224\" => 2224, \"2225\" => 2225, \"2226\" => 2226, \"2227\" => 2227, \"2228\" => 2228, \"2229\" => 2229, \"2230\" => 2230, \"2231\" => 2231, \"2232\" => 2232, \"2233\" => 2233, \"2234\" => 2234, \"2235\" => 2235, \"2236\" => 2236, \"2237\" => 2237, \"2238\" => 2238, \"2239\" => 2239, \"2240\" => 2240, \"2241\" => 2241, \"2242\" => 2242, \"2243\" => 2243, \"2244\" => 2244, \"2245\" => 2245, \"2246\" => 2246, \"2247\" => 2247, \"2248\" => 2248, \"2249\" => 2249, \"2250\" => 2250, \"2251\" => 2251, \"2252\" => 2252, \"2253\" => 2253, \"2254\" => 2254, \"2255\" => 2255, \"2256\" => 2256, \"2257\" => 2257, \"2258\" => 2258, \"2259\" => 2259, \"2260\" => 2260, \"2261\" => 2261, \"2262\" => 2262, \"2263\" => 2263, \"2264\" => 2264, \"2265\" => 2265, \"2266\" => 2266, \"2267\" => 2267, \"2268\" => 2268, \"2269\" => 2269, \"2270\" => 2270, \"2271\" => 2271, \"2272\" => 2272, \"2273\" => 2273, \"2274\" => 2274, \"2275\" => 2275, \"2276\" => 2276, \"2277\" => 2277, \"2278\" => 2278, \"2279\" => 2279, \"2280\" => 2280, \"2281\" => 2281, \"2282\" => 2282, \"2283\" => 2283, \"2284\" => 2284, \"2285\" => 2285, \"2286\" => 2286, \"2287\" => 2287, \"2288\" => 2288, \"2289\" => 2289, \"2290\" => 2290, \"2291\" => 2291, \"2292\" => 2292, \"2293\" => 2293, \"2294\" => 2294, \"2295\" => 2295, \"2296\" => 2296, \"2297\" => 2297, \"2298\" => 2298, \"2299\" => 2299, \"2300\" => 2300, \"2301\" => 2301, \"2302\" => 2302, \"2303\" => 2303, \"2304\" => 2304, \"2305\" => 2305, \"2306\" => 2306, \"2307\" => 2307, \"2308\" => 2308, \"2309\" => 2309, \"2310\" => 2310, \"2311\" => 2311, \"2312\" => 2312, \"2313\" => 2313, \"2314\" => 2314, \"2315\" => 2315, \"2316\" => 2316, \"2317\" => 2317, \"2318\" => 2318, \"2319\" => 2319, \"2320\" => 2320, \"2321\" => 2321, \"2322\" => 2322, \"2323\" => 2323, \"2324\" => 2324, \"2325\" => 2325, \"2326\" => 2326, \"2327\" => 2327, \"2328\" => 2328, \"2329\" => 2329, \"2330\" => 2330, \"2331\" => 2331, \"2332\" => 2332, \"2333\" => 2333, \"2334\" => 2334, \"2335\" => 2335, \"2336\" => 2336, \"2337\" => 2337, \"2338\" => 2338, \"2339\" => 2339, \"2340\" => 2340, \"2341\" => 2341, \"2342\" => 2342, \"2343\" => 2343, \"2344\" => 2344, \"2345\" => 2345, \"2346\" => 2346, \"2347\" => 2347, \"2348\" => 2348, \"2349\" => 2349, \"2350\" => 2350, \"2351\" => 2351, \"2352\" => 2352, \"2353\" => 2353, \"2354\" => 2354, \"2355\" => 2355, \"2356\" => 2356, \"2357\" => 2357, \"2358\" => 2358, \"2359\" => 2359, \"2360\" => 2360, \"2361\" => 2361, \"2362\" => 2362, \"2363\" => 2363, \"2364\" => 2364, \"2365\" => 2365, \"2366\" => 2366, \"2367\" => 2367, \"2368\" => 2368, \"2369\" => 2369, \"2370\" => 2370, \"2371\" => 2371, \"2372\" => 2372, \"2373\" => 2373, \"2374\" => 2374, \"2375\" => 2375, \"2376\" => 2376, \"2377\" => 2377, \"2378\" => 2378, \"2379\" => 2379, \"2380\" => 2380, \"2381\" => 2381, \"2382\" => 2382, \"2383\" => 2383, \"2384\" => 2384, \"2385\" => 2385, \"2386\" => 2386, \"2387\" => 2387, \"2388\" => 2388, \"2389\" => 2389, \"2390\" => 2390, \"2391\" => 2391, \"2392\" => 2392, \"2393\" => 2393, \"2394\" => 2394, \"2395\" => 2395, \"2396\" => 2396, \"2397\" => 2397, \"2398\" => 2398, \"2399\" => 2399, \"2400\" => 2400, \"2401\" => 2401, \"2402\" => 2402, \"2403\" => 2403, \"2404\" => 2404, \"2405\" => 2405, \"2406\" => 2406, \"2407\" => 2407, \"2408\" => 2408, \"2409\" => 2409, \"2410\" => 2410, \"2411\" => 2411, \"2412\" => 2412, \"2413\" => 2413, \"2414\" => 2414, \"2415\" => 2415, \"2416\" => 2416, \"2417\" => 2417, \"2418\" => 2418, \"2419\" => 2419, \"2420\" => 2420, \"2421\" => 2421, \"2422\" => 2422, \"2423\" => 2423, \"2424\" => 2424, \"2425\" => 2425, \"2426\" => 2426, \"2427\" => 2427, \"2428\" => 2428, \"2429\" => 2429, \"2430\" => 2430, \"2431\" => 2431, \"2432\" => 2432, \"2433\" => 2433, \"2434\" => 2434, \"2435\" => 2435, \"2436\" => 2436, \"2437\" => 2437, \"2438\" => 2438, \"2439\" => 2439, \"2440\" => 2440, \"2441\" => 2441, \"2442\" => 2442, \"2443\" => 2443, \"2444\" => 2444, \"2445\" => 2445, \"2446\" => 2446, \"2447\" => 2447, \"2448\" => 2448, \"2449\" => 2449, \"2450\" => 2450, \"2451\" => 2451, \"2452\" => 2452, \"2453\" => 2453, \"2454\" => 2454, \"2455\" => 2455, \"2456\" => 2456, \"2457\" => 2457, \"2458\" => 2458, \"2459\" => 2459, \"2460\" => 2460, \"2461\" => 2461, \"2462\" => 2462, \"2463\" => 2463, \"2464\" => 2464, \"2465\" => 2465, \"2466\" => 2466, \"2467\" => 2467, \"2468\" => 2468, \"2469\" => 2469, \"2470\" => 2470, \"2471\" => 2471, \"2472\" => 2472, \"2473\" => 2473, \"2474\" => 2474, \"2475\" => 2475, \"2476\" => 2476, \"2477\" => 2477, \"2478\" => 2478, \"2479\" => 2479, \"2480\" => 2480, \"2481\" => 2481, \"2482\" => 2482, \"2483\" => 2483, \"2484\" => 2484, \"2485\" => 2485, \"2486\" => 2486, \"2487\" => 2487, \"2488\" => 2488, \"2489\" => 2489, \"2490\" => 2490, \"2491\" => 2491, \"2492\" => 2492, \"2493\" => 2493, \"2494\" => 2494, \"2495\" => 2495, \"2496\" => 2496, \"2497\" => 2497, \"2498\" => 2498, \"2499\" => 2499, \"2500\" => 2500, \"2501\" => 2501, \"2502\" => 2502, \"2503\" => 2503, \"2504\" => 2504, \"2505\" => 2505, \"2506\" => 2506, \"2507\" => 2507, \"2508\" => 2508, \"2509\" => 2509, \"2510\" => 2510, \"2511\" => 2511, \"2512\" => 2512, \"2513\" => 2513, \"2514\" => 2514, \"2515\" => 2515, \"2516\" => 2516, \"2517\" => 2517, \"2518\" => 2518, \"2519\" => 2519, \"2520\" => 2520, \"2521\" => 2521, \"2522\" => 2522, \"2523\" => 2523, \"2524\" => 2524, \"2525\" => 2525, \"2526\" => 2526, \"2527\" => 2527, \"2528\" => 2528, \"2529\" => 2529, \"2530\" => 2530, \"2531\" => 2531, \"2532\" => 2532, \"2533\" => 2533, \"2534\" => 2534, \"2535\" => 2535, \"2536\" => 2536, \"2537\" => 2537, \"2538\" => 2538, \"2539\" => 2539, \"2540\" => 2540, \"2541\" => 2541, \"2542\" => 2542, \"2543\" => 2543, \"2544\" => 2544, \"2545\" => 2545, \"2546\" => 2546, \"2547\" => 2547, \"2548\" => 2548, \"2549\" => 2549, \"2550\" => 2550, \"2551\" => 2551, \"2552\" => 2552, \"2553\" => 2553, \"2554\" => 2554, \"2555\" => 2555, \"2556\" => 2556, \"2557\" => 2557, \"2558\" => 2558, \"2559\" => 2559, \"2560\" => 2560, \"2561\" => 2561, \"2562\" => 2562, \"2563\" => 2563, \"2564\" => 2564, \"2565\" => 2565, \"2566\" => 2566, \"2567\" => 2567, \"2568\" => 2568, \"2569\" => 2569, \"2570\" => 2570, \"2571\" => 2571, \"2572\" => 2572, \"2573\" => 2573, \"2574\" => 2574, \"2575\" => 2575, \"2576\" => 2576, \"2577\" => 2577, \"2578\" => 2578, \"2579\" => 2579, \"2580\" => 2580, \"2581\" => 2581, \"2582\" => 2582, \"2583\" => 2583, \"2584\" => 2584, \"2585\" => 2585, \"2586\" => 2586, \"2587\" => 2587, \"2588\" => 2588, \"2589\" => 2589, \"2590\" => 2590, \"2591\" => 2591, \"2592\" => 2592, \"2593\" => 2593, \"2594\" => 2594, \"2595\" => 2595, \"2596\" => 2596, \"2597\" => 2597, \"2598\" => 2598, \"2599\" => 2599, \"2600\" => 2600, \"2601\" => 2601, \"2602\" => 2602, \"2603\" => 2603, \"2604\" => 2604, \"2605\" => 2605, \"2606\" => 2606, \"2607\" => 2607, \"2608\" => 2608, \"2609\" => 2609, \"2610\" => 2610, \"2611\" => 2611, \"2612\" => 2612, \"2613\" => 2613, \"2614\" => 2614, \"2615\" => 2615, \"2616\" => 2616, \"2617\" => 2617, \"2618\" => 2618, \"2619\" => 2619, \"2620\" => 2620, \"2621\" => 2621, \"2622\" => 2622, \"2623\" => 2623, \"2624\" => 2624, \"2625\" => 2625, \"2626\" => 2626, \"2627\" => 2627, \"2628\" => 2628, \"2629\" => 2629, \"2630\" => 2630, \"2631\" => 2631, \"2632\" => 2632, \"2633\" => 2633, \"2634\" => 2634, \"2635\" => 2635, \"2636\" => 2636, \"2637\" => 2637, \"2638\" => 2638, \"2639\" => 2639, \"2640\" => 2640, \"2641\" => 2641, \"2642\" => 2642, \"2643\" => 2643, \"2644\" => 2644, \"2645\" => 2645, \"2646\" => 2646, \"2647\" => 2647, \"2648\" => 2648, \"2649\" => 2649, \"2650\" => 2650, \"2651\" => 2651, \"2652\" => 2652, \"2653\" => 2653, \"2654\" => 2654, \"2655\" => 2655, \"2656\" => 2656, \"2657\" => 2657, \"2658\" => 2658, \"2659\" => 2659, \"2660\" => 2660, \"2661\" => 2661, \"2662\" => 2662, \"2663\" => 2663, \"2664\" => 2664, \"2665\" => 2665, \"2666\" => 2666, \"2667\" => 2667, \"2668\" => 2668, \"2669\" => 2669, \"2670\" => 2670, \"2671\" => 2671, \"2672\" => 2672, \"2673\" => 2673, \"2674\" => 2674, \"2675\" => 2675, \"2676\" => 2676, \"2677\" => 2677, \"2678\" => 2678, \"2679\" => 2679, \"2680\" => 2680, \"2681\" => 2681, \"2682\" => 2682, \"2683\" => 2683, \"2684\" => 2684, \"2685\" => 2685, \"2686\" => 2686, \"2687\" => 2687, \"2688\" => 2688, \"2689\" => 2689, \"2690\" => 2690, \"2691\" => 2691, \"2692\" => 2692, \"2693\" => 2693, \"2694\" => 2694, \"2695\" => 2695, \"2696\" => 2696, \"2697\" => 2697, \"2698\" => 2698, \"2699\" => 2699, \"2700\" => 2700, \"2701\" => 2701, \"2702\" => 2702, \"2703\" => 2703, \"2704\" => 2704, \"2705\" => 2705, \"2706\" => 2706, \"2707\" => 2707, \"2708\" => 2708, \"2709\" => 2709, \"2710\" => 2710, \"2711\" => 2711, \"2712\" => 2712, \"2713\" => 2713, \"2714\" => 2714, \"2715\" => 2715, \"2716\" => 2716, \"2717\" => 2717, \"2718\" => 2718, \"2719\" => 2719, \"2720\" => 2720, \"2721\" => 2721, \"2722\" => 2722, \"2723\" => 2723, \"2724\" => 2724, \"2725\" => 2725, \"2726\" => 2726, \"2727\" => 2727, \"2728\" => 2728, \"2729\" => 2729, \"2730\" => 2730, \"2731\" => 2731, \"2732\" => 2732, \"2733\" => 2733, \"2734\" => 2734, \"2735\" => 2735, \"2736\" => 2736, \"2737\" => 2737, \"2738\" => 2738, \"2739\" => 2739, \"2740\" => 2740, \"2741\" => 2741, \"2742\" => 2742, \"2743\" => 2743, \"2744\" => 2744, \"2745\" => 2745, \"2746\" => 2746, \"2747\" => 2747, \"2748\" => 2748, \"2749\" => 2749, \"2750\" => 2750, \"2751\" => 2751, \"2752\" => 2752, \"2753\" => 2753, \"2754\" => 2754, \"2755\" => 2755, \"2756\" => 2756, \"2757\" => 2757, \"2758\" => 2758, \"2759\" => 2759, \"2760\" => 2760, \"2761\" => 2761, \"2762\" => 2762, \"2763\" => 2763, \"2764\" => 2764, \"2765\" => 2765, \"2766\" => 2766, \"2767\" => 2767, \"2768\" => 2768, \"2769\" => 2769, \"2770\" => 2770, \"2771\" => 2771, \"2772\" => 2772, \"2773\" => 2773, \"2774\" => 2774, \"2775\" => 2775, \"2776\" => 2776, \"2777\" => 2777, \"2778\" => 2778, \"2779\" => 2779, \"2780\" => 2780, \"2781\" => 2781, \"2782\" => 2782, \"2783\" => 2783, \"2784\" => 2784, \"2785\" => 2785, \"2786\" => 2786, \"2787\" => 2787, \"2788\" => 2788, \"2789\" => 2789, \"2790\" => 2790, \"2791\" => 2791, \"2792\" => 2792, \"2793\" => 2793, \"2794\" => 2794, \"2795\" => 2795, \"2796\" => 2796, \"2797\" => 2797, \"2798\" => 2798, \"2799\" => 2799, \"2800\" => 2800, \"2801\" => 2801, \"2802\" => 2802, \"2803\" => 2803, \"2804\" => 2804, \"2805\" => 2805, \"2806\" => 2806, \"2807\" => 2807, \"2808\" => 2808, \"2809\" => 2809, \"2810\" => 2810, \"2811\" => 2811, \"2812\" => 2812, \"2813\" => 2813, \"2814\" => 2814, \"2815\" => 2815, \"2816\" => 2816, \"2817\" => 2817, \"2818\" => 2818, \"2819\" => 2819, \"2820\" => 2820, \"2821\" => 2821, \"2822\" => 2822, \"2823\" => 2823, \"2824\" => 2824, \"2825\" => 2825, \"2826\" => 2826, \"2827\" => 2827, \"2828\" => 2828, \"2829\" => 2829, \"2830\" => 2830, \"2831\" => 2831, \"2832\" => 2832, \"2833\" => 2833, \"2834\" => 2834, \"2835\" => 2835, \"2836\" => 2836, \"2837\" => 2837, \"2838\" => 2838, \"2839\" => 2839, \"2840\" => 2840, \"2841\" => 2841, \"2842\" => 2842, \"2843\" => 2843, \"2844\" => 2844, \"2845\" => 2845, \"2846\" => 2846, \"2847\" => 2847, \"2848\" => 2848, \"2849\" => 2849, \"2850\" => 2850, \"2851\" => 2851, \"2852\" => 2852, \"2853\" => 2853, \"2854\" => 2854, \"2855\" => 2855, \"2856\" => 2856, \"2857\" => 2857, \"2858\" => 2858, \"2859\" => 2859, \"2860\" => 2860, \"2861\" => 2861, \"2862\" => 2862, \"2863\" => 2863, \"2864\" => 2864, \"2865\" => 2865, \"2866\" => 2866, \"2867\" => 2867, \"2868\" => 2868, \"2869\" => 2869, \"2870\" => 2870, \"2871\" => 2871, \"2872\" => 2872, \"2873\" => 2873, \"2874\" => 2874, \"2875\" => 2875, \"2876\" => 2876, \"2877\" => 2877, \"2878\" => 2878, \"2879\" => 2879, \"2880\" => 2880, \"2881\" => 2881, \"2882\" => 2882, \"2883\" => 2883, \"2884\" => 2884, \"2885\" => 2885, \"2886\" => 2886, \"2887\" => 2887, \"2888\" => 2888, \"2889\" => 2889, \"2890\" => 2890, \"2891\" => 2891, \"2892\" => 2892, \"2893\" => 2893, \"2894\" => 2894, \"2895\" => 2895, \"2896\" => 2896, \"2897\" => 2897, \"2898\" => 2898, \"2899\" => 2899, \"2900\" => 2900, \"2901\" => 2901, \"2902\" => 2902, \"2903\" => 2903, \"2904\" => 2904, \"2905\" => 2905, \"2906\" => 2906, \"2907\" => 2907, \"2908\" => 2908, \"2909\" => 2909, \"2910\" => 2910, \"2911\" => 2911, \"2912\" => 2912, \"2913\" => 2913, \"2914\" => 2914, \"2915\" => 2915, \"2916\" => 2916, \"2917\" => 2917, \"2918\" => 2918, \"2919\" => 2919, \"2920\" => 2920, \"2921\" => 2921, \"2922\" => 2922, \"2923\" => 2923, \"2924\" => 2924, \"2925\" => 2925, \"2926\" => 2926, \"2927\" => 2927, \"2928\" => 2928, \"2929\" => 2929, \"2930\" => 2930, \"2931\" => 2931, \"2932\" => 2932, \"2933\" => 2933, \"2934\" => 2934, \"2935\" => 2935, \"2936\" => 2936, \"2937\" => 2937, \"2938\" => 2938, \"2939\" => 2939, \"2940\" => 2940, \"2941\" => 2941, \"2942\" => 2942, \"2943\" => 2943, \"2944\" => 2944, \"2945\" => 2945, \"2946\" => 2946, \"2947\" => 2947, \"2948\" => 2948, \"2949\" => 2949, \"2950\" => 2950, \"2951\" => 2951, \"2952\" => 2952, \"2953\" => 2953, \"2954\" => 2954, \"2955\" => 2955, \"2956\" => 2956, \"2957\" => 2957, \"2958\" => 2958, \"2959\" => 2959, \"2960\" => 2960, \"2961\" => 2961, \"2962\" => 2962, \"2963\" => 2963, \"2964\" => 2964, \"2965\" => 2965, \"2966\" => 2966, \"2967\" => 2967, \"2968\" => 2968, \"2969\" => 2969, \"2970\" => 2970, \"2971\" => 2971, \"2972\" => 2972, \"2973\" => 2973, \"2974\" => 2974, \"2975\" => 2975, \"2976\" => 2976, \"2977\" => 2977, \"2978\" => 2978, \"2979\" => 2979, \"2980\" => 2980, \"2981\" => 2981, \"2982\" => 2982, \"2983\" => 2983, \"2984\" => 2984, \"2985\" => 2985, \"2986\" => 2986, \"2987\" => 2987, \"2988\" => 2988, \"2989\" => 2989, \"2990\" => 2990, \"2991\" => 2991, \"2992\" => 2992, \"2993\" => 2993, \"2994\" => 2994, \"2995\" => 2995, \"2996\" => 2996, \"2997\" => 2997, \"2998\" => 2998, \"2999\" => 2999, \"3000\" => 3000, \"3001\" => 3001, \"3002\" => 3002, \"3003\" => 3003, \"3004\" => 3004, \"3005\" => 3005, \"3006\" => 3006, \"3007\" => 3007, \"3008\" => 3008, \"3009\" => 3009, \"3010\" => 3010, \"3011\" => 3011, \"3012\" => 3012, \"3013\" => 3013, \"3014\" => 3014, \"3015\" => 3015, \"3016\" => 3016, \"3017\" => 3017, \"3018\" => 3018, \"3019\" => 3019, \"3020\" => 3020, \"3021\" => 3021, \"3022\" => 3022, \"3023\" => 3023, \"3024\" => 3024, \"3025\" => 3025, \"3026\" => 3026, \"3027\" => 3027, \"3028\" => 3028, \"3029\" => 3029, \"3030\" => 3030, \"3031\" => 3031, \"3032\" => 3032, \"3033\" => 3033, \"3034\" => 3034, \"3035\" => 3035, \"3036\" => 3036, \"3037\" => 3037, \"3038\" => 3038, \"3039\" => 3039, \"3040\" => 3040, \"3041\" => 3041, \"3042\" => 3042, \"3043\" => 3043, \"3044\" => 3044, \"3045\" => 3045, \"3046\" => 3046, \"3047\" => 3047, \"3048\" => 3048, \"3049\" => 3049, \"3050\" => 3050, \"3051\" => 3051, \"3052\" => 3052, \"3053\" => 3053, \"3054\" => 3054, \"3055\" => 3055, \"3056\" => 3056, \"3057\" => 3057, \"3058\" => 3058, \"3059\" => 3059, \"3060\" => 3060, \"3061\" => 3061, \"3062\" => 3062, \"3063\" => 3063, \"3064\" => 3064, \"3065\" => 3065, \"3066\" => 3066, \"3067\" => 3067, \"3068\" => 3068, \"3069\" => 3069, \"3070\" => 3070, \"3071\" => 3071, \"3072\" => 3072, \"3073\" => 3073, \"3074\" => 3074, \"3075\" => 3075, \"3076\" => 3076, \"3077\" => 3077, \"3078\" => 3078, \"3079\" => 3079, \"3080\" => 3080, \"3081\" => 3081, \"3082\" => 3082, \"3083\" => 3083, \"3084\" => 3084, \"3085\" => 3085, \"3086\" => 3086, \"3087\" => 3087, \"3088\" => 3088, \"3089\" => 3089, \"3090\" => 3090, \"3091\" => 3091, \"3092\" => 3092, \"3093\" => 3093, \"3094\" => 3094, \"3095\" => 3095, \"3096\" => 3096, \"3097\" => 3097, \"3098\" => 3098, \"3099\" => 3099, \"3100\" => 3100, \"3101\" => 3101, \"3102\" => 3102, \"3103\" => 3103, \"3104\" => 3104, \"3105\" => 3105, \"3106\" => 3106, \"3107\" => 3107, \"3108\" => 3108, \"3109\" => 3109, \"3110\" => 3110, \"3111\" => 3111, \"3112\" => 3112, \"3113\" => 3113, \"3114\" => 3114, \"3115\" => 3115, \"3116\" => 3116, \"3117\" => 3117, \"3118\" => 3118, \"3119\" => 3119, \"3120\" => 3120, \"3121\" => 3121, \"3122\" => 3122, \"3123\" => 3123, \"3124\" => 3124, \"3125\" => 3125, \"3126\" => 3126, \"3127\" => 3127, \"3128\" => 3128, \"3129\" => 3129, \"3130\" => 3130, \"3131\" => 3131, \"3132\" => 3132, \"3133\" => 3133, \"3134\" => 3134, \"3135\" => 3135, \"3136\" => 3136, \"3137\" => 3137, \"3138\" => 3138, \"3139\" => 3139, \"3140\" => 3140, \"3141\" => 3141, \"3142\" => 3142, \"3143\" => 3143, \"3144\" => 3144, \"3145\" => 3145, \"3146\" => 3146, \"3147\" => 3147, \"3148\" => 3148, \"3149\" => 3149, \"3150\" => 3150, \"3151\" => 3151, \"3152\" => 3152, \"3153\" => 3153, \"3154\" => 3154, \"3155\" => 3155, \"3156\" => 3156, \"3157\" => 3157, \"3158\" => 3158, \"3159\" => 3159, \"3160\" => 3160, \"3161\" => 3161, \"3162\" => 3162, \"3163\" => 3163, \"3164\" => 3164, \"3165\" => 3165, \"3166\" => 3166, \"3167\" => 3167, \"3168\" => 3168, \"3169\" => 3169, \"3170\" => 3170, \"3171\" => 3171, \"3172\" => 3172, \"3173\" => 3173, \"3174\" => 3174, \"3175\" => 3175, \"3176\" => 3176, \"3177\" => 3177, \"3178\" => 3178, \"3179\" => 3179, \"3180\" => 3180, \"3181\" => 3181, \"3182\" => 3182, \"3183\" => 3183, \"3184\" => 3184, \"3185\" => 3185, \"3186\" => 3186, \"3187\" => 3187, \"3188\" => 3188, \"3189\" => 3189, \"3190\" => 3190, \"3191\" => 3191, \"3192\" => 3192, \"3193\" => 3193, \"3194\" => 3194, \"3195\" => 3195, \"3196\" => 3196, \"3197\" => 3197, \"3198\" => 3198, \"3199\" => 3199, \"3200\" => 3200, \"3201\" => 3201, \"3202\" => 3202, \"3203\" => 3203, \"3204\" => 3204, \"3205\" => 3205, \"3206\" => 3206, \"3207\" => 3207, \"3208\" => 3208, \"3209\" => 3209, \"3210\" => 3210, \"3211\" => 3211, \"3212\" => 3212, \"3213\" => 3213, \"3214\" => 3214, \"3215\" => 3215, \"3216\" => 3216, \"3217\" => 3217, \"3218\" => 3218, \"3219\" => 3219, \"3220\" => 3220, \"3221\" => 3221, \"3222\" => 3222, \"3223\" => 3223, \"3224\" => 3224, \"3225\" => 3225, \"3226\" => 3226, \"3227\" => 3227, \"3228\" => 3228, \"3229\" => 3229, \"3230\" => 3230, \"3231\" => 3231, \"3232\" => 3232, \"3233\" => 3233, \"3234\" => 3234, \"3235\" => 3235, \"3236\" => 3236, \"3237\" => 3237, \"3238\" => 3238, \"3239\" => 3239, \"3240\" => 3240, \"3241\" => 3241, \"3242\" => 3242, \"3243\" => 3243, \"3244\" => 3244, \"3245\" => 3245, \"3246\" => 3246, \"3247\" => 3247, \"3248\" => 3248, \"3249\" => 3249, \"3250\" => 3250, \"3251\" => 3251, \"3252\" => 3252, \"3253\" => 3253, \"3254\" => 3254, \"3255\" => 3255, \"3256\" => 3256, \"3257\" => 3257, \"3258\" => 3258, \"3259\" => 3259, \"3260\" => 3260, \"3261\" => 3261, \"3262\" => 3262, \"3263\" => 3263, \"3264\" => 3264, \"3265\" => 3265, \"3266\" => 3266, \"3267\" => 3267, \"3268\" => 3268, \"3269\" => 3269, \"3270\" => 3270, \"3271\" => 3271, \"3272\" => 3272, \"3273\" => 3273, \"3274\" => 3274, \"3275\" => 3275, \"3276\" => 3276, \"3277\" => 3277, \"3278\" => 3278, \"3279\" => 3279, \"3280\" => 3280, \"3281\" => 3281, \"3282\" => 3282, \"3283\" => 3283, \"3284\" => 3284, \"3285\" => 3285, \"3286\" => 3286, \"3287\" => 3287, \"3288\" => 3288, \"3289\" => 3289, \"3290\" => 3290, \"3291\" => 3291, \"3292\" => 3292, \"3293\" => 3293, \"3294\" => 3294, \"3295\" => 3295, \"3296\" => 3296, \"3297\" => 3297, \"3298\" => 3298, \"3299\" => 3299, \"3300\" => 3300, \"3301\" => 3301, \"3302\" => 3302, \"3303\" => 3303, \"3304\" => 3304, \"3305\" => 3305, \"3306\" => 3306, \"3307\" => 3307, \"3308\" => 3308, \"3309\" => 3309, \"3310\" => 3310, \"3311\" => 3311, \"3312\" => 3312, \"3313\" => 3313, \"3314\" => 3314, \"3315\" => 3315, \"3316\" => 3316, \"3317\" => 3317, \"3318\" => 3318, \"3319\" => 3319, \"3320\" => 3320, \"3321\" => 3321, \"3322\" => 3322, \"3323\" => 3323, \"3324\" => 3324, \"3325\" => 3325, \"3326\" => 3326, \"3327\" => 3327, \"3328\" => 3328, \"3329\" => 3329, \"3330\" => 3330, \"3331\" => 3331, \"3332\" => 3332, \"3333\" => 3333, \"3334\" => 3334, \"3335\" => 3335, \"3336\" => 3336, \"3337\" => 3337, \"3338\" => 3338, \"3339\" => 3339, \"3340\" => 3340, \"3341\" => 3341, \"3342\" => 3342, \"3343\" => 3343, \"3344\" => 3344, \"3345\" => 3345, \"3346\" => 3346, \"3347\" => 3347, \"3348\" => 3348, \"3349\" => 3349, \"3350\" => 3350, \"3351\" => 3351, \"3352\" => 3352, \"3353\" => 3353, \"3354\" => 3354, \"3355\" => 3355, \"3356\" => 3356, \"3357\" => 3357, \"3358\" => 3358, \"3359\" => 3359, \"3360\" => 3360, \"3361\" => 3361, \"3362\" => 3362, \"3363\" => 3363, \"3364\" => 3364, \"3365\" => 3365, \"3366\" => 3366, \"3367\" => 3367, \"3368\" => 3368, \"3369\" => 3369, \"3370\" => 3370, \"3371\" => 3371, \"3372\" => 3372, \"3373\" => 3373, \"3374\" => 3374, \"3375\" => 3375, \"3376\" => 3376, \"3377\" => 3377, \"3378\" => 3378, \"3379\" => 3379, \"3380\" => 3380, \"3381\" => 3381, \"3382\" => 3382, \"3383\" => 3383, \"3384\" => 3384, \"3385\" => 3385, \"3386\" => 3386, \"3387\" => 3387, \"3388\" => 3388, \"3389\" => 3389, \"3390\" => 3390, \"3391\" => 3391, \"3392\" => 3392, \"3393\" => 3393, \"3394\" => 3394, \"3395\" => 3395, \"3396\" => 3396, \"3397\" => 3397, \"3398\" => 3398, \"3399\" => 3399, \"3400\" => 3400, \"3401\" => 3401, \"3402\" => 3402, \"3403\" => 3403, \"3404\" => 3404, \"3405\" => 3405, \"3406\" => 3406, \"3407\" => 3407, \"3408\" => 3408, \"3409\" => 3409, \"3410\" => 3410, \"3411\" => 3411, \"3412\" => 3412, \"3413\" => 3413, \"3414\" => 3414, \"3415\" => 3415, \"3416\" => 3416, \"3417\" => 3417, \"3418\" => 3418, \"3419\" => 3419, \"3420\" => 3420, \"3421\" => 3421, \"3422\" => 3422, \"3423\" => 3423, \"3424\" => 3424, \"3425\" => 3425, \"3426\" => 3426, \"3427\" => 3427, \"3428\" => 3428, \"3429\" => 3429, \"3430\" => 3430, \"3431\" => 3431, \"3432\" => 3432, \"3433\" => 3433, \"3434\" => 3434, \"3435\" => 3435, \"3436\" => 3436, \"3437\" => 3437, \"3438\" => 3438, \"3439\" => 3439, \"3440\" => 3440, \"3441\" => 3441, \"3442\" => 3442, \"3443\" => 3443, \"3444\" => 3444, \"3445\" => 3445, \"3446\" => 3446, \"3447\" => 3447, \"3448\" => 3448, \"3449\" => 3449, \"3450\" => 3450, \"3451\" => 3451, \"3452\" => 3452, \"3453\" => 3453, \"3454\" => 3454, \"3455\" => 3455, \"3456\" => 3456, \"3457\" => 3457, \"3458\" => 3458, \"3459\" => 3459, \"3460\" => 3460, \"3461\" => 3461, \"3462\" => 3462, \"3463\" => 3463, \"3464\" => 3464, \"3465\" => 3465, \"3466\" => 3466, \"3467\" => 3467, \"3468\" => 3468, \"3469\" => 3469, \"3470\" => 3470, \"3471\" => 3471, \"3472\" => 3472, \"3473\" => 3473, \"3474\" => 3474, \"3475\" => 3475, \"3476\" => 3476, \"3477\" => 3477, \"3478\" => 3478, \"3479\" => 3479, \"3480\" => 3480, \"3481\" => 3481, \"3482\" => 3482, \"3483\" => 3483, \"3484\" => 3484, \"3485\" => 3485, \"3486\" => 3486, \"3487\" => 3487, \"3488\" => 3488, \"3489\" => 3489, \"3490\" => 3490, \"3491\" => 3491, \"3492\" => 3492, \"3493\" => 3493, \"3494\" => 3494, \"3495\" => 3495, \"3496\" => 3496, \"3497\" => 3497, \"3498\" => 3498, \"3499\" => 3499, \"3500\" => 3500, \"3501\" => 3501, \"3502\" => 3502, \"3503\" => 3503, \"3504\" => 3504, \"3505\" => 3505, \"3506\" => 3506, \"3507\" => 3507, \"3508\" => 3508, \"3509\" => 3509, \"3510\" => 3510, \"3511\" => 3511, \"3512\" => 3512, \"3513\" => 3513, \"3514\" => 3514, \"3515\" => 3515, \"3516\" => 3516, \"3517\" => 3517, \"3518\" => 3518, \"3519\" => 3519, \"3520\" => 3520, \"3521\" => 3521, \"3522\" => 3522, \"3523\" => 3523, \"3524\" => 3524, \"3525\" => 3525, \"3526\" => 3526, \"3527\" => 3527, \"3528\" => 3528, \"3529\" => 3529, \"3530\" => 3530, \"3531\" => 3531, \"3532\" => 3532, \"3533\" => 3533, \"3534\" => 3534, \"3535\" => 3535, \"3536\" => 3536, \"3537\" => 3537, \"3538\" => 3538, \"3539\" => 3539, \"3540\" => 3540, \"3541\" => 3541, \"3542\" => 3542, \"3543\" => 3543, \"3544\" => 3544, \"3545\" => 3545, \"3546\" => 3546, \"3547\" => 3547, \"3548\" => 3548, \"3549\" => 3549, \"3550\" => 3550, \"3551\" => 3551, \"3552\" => 3552, \"3553\" => 3553, \"3554\" => 3554, \"3555\" => 3555, \"3556\" => 3556, \"3557\" => 3557, \"3558\" => 3558, \"3559\" => 3559, \"3560\" => 3560, \"3561\" => 3561, \"3562\" => 3562, \"3563\" => 3563, \"3564\" => 3564, \"3565\" => 3565, \"3566\" => 3566, \"3567\" => 3567, \"3568\" => 3568, \"3569\" => 3569, \"3570\" => 3570, \"3571\" => 3571, \"3572\" => 3572, \"3573\" => 3573, \"3574\" => 3574, \"3575\" => 3575, \"3576\" => 3576, \"3577\" => 3577, \"3578\" => 3578, \"3579\" => 3579, \"3580\" => 3580, \"3581\" => 3581, \"3582\" => 3582, \"3583\" => 3583, \"3584\" => 3584, \"3585\" => 3585, \"3586\" => 3586, \"3587\" => 3587, \"3588\" => 3588, \"3589\" => 3589, \"3590\" => 3590, \"3591\" => 3591, \"3592\" => 3592, \"3593\" => 3593, \"3594\" => 3594, \"3595\" => 3595, \"3596\" => 3596, \"3597\" => 3597, \"3598\" => 3598, \"3599\" => 3599, \"3600\" => 3600, \"3601\" => 3601, \"3602\" => 3602, \"3603\" => 3603, \"3604\" => 3604, \"3605\" => 3605, \"3606\" => 3606, \"3607\" => 3607, \"3608\" => 3608, \"3609\" => 3609, \"3610\" => 3610, \"3611\" => 3611, \"3612\" => 3612, \"3613\" => 3613, \"3614\" => 3614, \"3615\" => 3615, \"3616\" => 3616, \"3617\" => 3617, \"3618\" => 3618, \"3619\" => 3619, \"3620\" => 3620, \"3621\" => 3621, \"3622\" => 3622, \"3623\" => 3623, \"3624\" => 3624, \"3625\" => 3625, \"3626\" => 3626, \"3627\" => 3627, \"3628\" => 3628, \"3629\" => 3629, \"3630\" => 3630, \"3631\" => 3631, \"3632\" => 3632, \"3633\" => 3633, \"3634\" => 3634, \"3635\" => 3635, \"3636\" => 3636, \"3637\" => 3637, \"3638\" => 3638, \"3639\" => 3639, \"3640\" => 3640, \"3641\" => 3641, \"3642\" => 3642, \"3643\" => 3643, \"3644\" => 3644, \"3645\" => 3645, \"3646\" => 3646, \"3647\" => 3647, \"3648\" => 3648, \"3649\" => 3649, \"3650\" => 3650, \"3651\" => 3651, \"3652\" => 3652, \"3653\" => 3653, \"3654\" => 3654, \"3655\" => 3655, \"3656\" => 3656, \"3657\" => 3657, \"3658\" => 3658, \"3659\" => 3659, \"3660\" => 3660, \"3661\" => 3661, \"3662\" => 3662, \"3663\" => 3663, \"3664\" => 3664, \"3665\" => 3665, \"3666\" => 3666, \"3667\" => 3667, \"3668\" => 3668, \"3669\" => 3669, \"3670\" => 3670, \"3671\" => 3671, \"3672\" => 3672, \"3673\" => 3673, \"3674\" => 3674, \"3675\" => 3675, \"3676\" => 3676, \"3677\" => 3677, \"3678\" => 3678, \"3679\" => 3679, \"3680\" => 3680, \"3681\" => 3681, \"3682\" => 3682, \"3683\" => 3683, \"3684\" => 3684, \"3685\" => 3685, \"3686\" => 3686, \"3687\" => 3687, \"3688\" => 3688, \"3689\" => 3689, \"3690\" => 3690, \"3691\" => 3691, \"3692\" => 3692, \"3693\" => 3693, \"3694\" => 3694, \"3695\" => 3695, \"3696\" => 3696, \"3697\" => 3697, \"3698\" => 3698, \"3699\" => 3699, \"3700\" => 3700, \"3701\" => 3701, \"3702\" => 3702, \"3703\" => 3703, \"3704\" => 3704, \"3705\" => 3705, \"3706\" => 3706, \"3707\" => 3707, \"3708\" => 3708, \"3709\" => 3709, \"3710\" => 3710, \"3711\" => 3711, \"3712\" => 3712, \"3713\" => 3713, \"3714\" => 3714, \"3715\" => 3715, \"3716\" => 3716, \"3717\" => 3717, \"3718\" => 3718, \"3719\" => 3719, \"3720\" => 3720, \"3721\" => 3721, \"3722\" => 3722, \"3723\" => 3723, \"3724\" => 3724, \"3725\" => 3725, \"3726\" => 3726, \"3727\" => 3727, \"3728\" => 3728, \"3729\" => 3729, \"3730\" => 3730, \"3731\" => 3731, \"3732\" => 3732, \"3733\" => 3733, \"3734\" => 3734, \"3735\" => 3735, \"3736\" => 3736, \"3737\" => 3737, \"3738\" => 3738, \"3739\" => 3739, \"3740\" => 3740, \"3741\" => 3741, \"3742\" => 3742, \"3743\" => 3743, \"3744\" => 3744, \"3745\" => 3745, \"3746\" => 3746, \"3747\" => 3747, \"3748\" => 3748, \"3749\" => 3749, \"3750\" => 3750, \"3751\" => 3751, \"3752\" => 3752, \"3753\" => 3753, \"3754\" => 3754, \"3755\" => 3755, \"3756\" => 3756, \"3757\" => 3757, \"3758\" => 3758, \"3759\" => 3759, \"3760\" => 3760, \"3761\" => 3761, \"3762\" => 3762, \"3763\" => 3763, \"3764\" => 3764, \"3765\" => 3765, \"3766\" => 3766, \"3767\" => 3767, \"3768\" => 3768, \"3769\" => 3769, \"3770\" => 3770, \"3771\" => 3771, \"3772\" => 3772, \"3773\" => 3773, \"3774\" => 3774, \"3775\" => 3775, \"3776\" => 3776, \"3777\" => 3777, \"3778\" => 3778, \"3779\" => 3779, \"3780\" => 3780, \"3781\" => 3781, \"3782\" => 3782, \"3783\" => 3783, \"3784\" => 3784, \"3785\" => 3785, \"3786\" => 3786, \"3787\" => 3787, \"3788\" => 3788, \"3789\" => 3789, \"3790\" => 3790, \"3791\" => 3791, \"3792\" => 3792, \"3793\" => 3793, \"3794\" => 3794, \"3795\" => 3795, \"3796\" => 3796, \"3797\" => 3797, \"3798\" => 3798, \"3799\" => 3799, \"3800\" => 3800, \"3801\" => 3801, \"3802\" => 3802, \"3803\" => 3803, \"3804\" => 3804, \"3805\" => 3805, \"3806\" => 3806, \"3807\" => 3807, \"3808\" => 3808, \"3809\" => 3809, \"3810\" => 3810, \"3811\" => 3811, \"3812\" => 3812, \"3813\" => 3813, \"3814\" => 3814, \"3815\" => 3815, \"3816\" => 3816, \"3817\" => 3817, \"3818\" => 3818, \"3819\" => 3819, \"3820\" => 3820, \"3821\" => 3821, \"3822\" => 3822, \"3823\" => 3823, \"3824\" => 3824, \"3825\" => 3825, \"3826\" => 3826, \"3827\" => 3827, \"3828\" => 3828, \"3829\" => 3829, \"3830\" => 3830, \"3831\" => 3831, \"3832\" => 3832, \"3833\" => 3833, \"3834\" => 3834, \"3835\" => 3835, \"3836\" => 3836, \"3837\" => 3837, \"3838\" => 3838, \"3839\" => 3839, \"3840\" => 3840, \"3841\" => 3841, \"3842\" => 3842, \"3843\" => 3843, \"3844\" => 3844, \"3845\" => 3845, \"3846\" => 3846, \"3847\" => 3847, \"3848\" => 3848, \"3849\" => 3849, \"3850\" => 3850, \"3851\" => 3851, \"3852\" => 3852, \"3853\" => 3853, \"3854\" => 3854, \"3855\" => 3855, \"3856\" => 3856, \"3857\" => 3857, \"3858\" => 3858, \"3859\" => 3859, \"3860\" => 3860, \"3861\" => 3861, \"3862\" => 3862, \"3863\" => 3863, \"3864\" => 3864, \"3865\" => 3865, \"3866\" => 3866, \"3867\" => 3867, \"3868\" => 3868, \"3869\" => 3869, \"3870\" => 3870, \"3871\" => 3871, \"3872\" => 3872, \"3873\" => 3873, \"3874\" => 3874, \"3875\" => 3875, \"3876\" => 3876, \"3877\" => 3877, \"3878\" => 3878, \"3879\" => 3879, \"3880\" => 3880, \"3881\" => 3881, \"3882\" => 3882, \"3883\" => 3883, \"3884\" => 3884, \"3885\" => 3885, \"3886\" => 3886, \"3887\" => 3887, \"3888\" => 3888, \"3889\" => 3889, \"3890\" => 3890, \"3891\" => 3891, \"3892\" => 3892, \"3893\" => 3893, \"3894\" => 3894, \"3895\" => 3895, \"3896\" => 3896, \"3897\" => 3897, \"3898\" => 3898, \"3899\" => 3899, \"3900\" => 3900, \"3901\" => 3901, \"3902\" => 3902, \"3903\" => 3903, \"3904\" => 3904, \"3905\" => 3905, \"3906\" => 3906, \"3907\" => 3907, \"3908\" => 3908, \"3909\" => 3909, \"3910\" => 3910, \"3911\" => 3911, \"3912\" => 3912, \"3913\" => 3913, \"3914\" => 3914, \"3915\" => 3915, \"3916\" => 3916, \"3917\" => 3917, \"3918\" => 3918, \"3919\" => 3919, \"3920\" => 3920, \"3921\" => 3921, \"3922\" => 3922, \"3923\" => 3923, \"3924\" => 3924, \"3925\" => 3925, \"3926\" => 3926, \"3927\" => 3927, \"3928\" => 3928, \"3929\" => 3929, \"3930\" => 3930, \"3931\" => 3931, \"3932\" => 3932, \"3933\" => 3933, \"3934\" => 3934, \"3935\" => 3935, \"3936\" => 3936, \"3937\" => 3937, \"3938\" => 3938, \"3939\" => 3939, \"3940\" => 3940, \"3941\" => 3941, \"3942\" => 3942, \"3943\" => 3943, \"3944\" => 3944, \"3945\" => 3945, \"3946\" => 3946, \"3947\" => 3947, \"3948\" => 3948, \"3949\" => 3949, \"3950\" => 3950, \"3951\" => 3951, \"3952\" => 3952, \"3953\" => 3953, \"3954\" => 3954, \"3955\" => 3955, \"3956\" => 3956, \"3957\" => 3957, \"3958\" => 3958, \"3959\" => 3959, \"3960\" => 3960, \"3961\" => 3961, \"3962\" => 3962, \"3963\" => 3963, \"3964\" => 3964, \"3965\" => 3965, \"3966\" => 3966, \"3967\" => 3967, \"3968\" => 3968, \"3969\" => 3969, \"3970\" => 3970, \"3971\" => 3971, \"3972\" => 3972, \"3973\" => 3973, \"3974\" => 3974, \"3975\" => 3975, \"3976\" => 3976, \"3977\" => 3977, \"3978\" => 3978, \"3979\" => 3979, \"3980\" => 3980, \"3981\" => 3981, \"3982\" => 3982, \"3983\" => 3983, \"3984\" => 3984, \"3985\" => 3985, \"3986\" => 3986, \"3987\" => 3987, \"3988\" => 3988, \"3989\" => 3989, \"3990\" => 3990, \"3991\" => 3991, \"3992\" => 3992, \"3993\" => 3993, \"3994\" => 3994, \"3995\" => 3995, \"3996\" => 3996, \"3997\" => 3997, \"3998\" => 3998, \"3999\" => 3999, \"4000\" => 4000, \"4001\" => 4001, \"4002\" => 4002, \"4003\" => 4003, \"4004\" => 4004, \"4005\" => 4005, \"4006\" => 4006, \"4007\" => 4007, \"4008\" => 4008, \"4009\" => 4009, \"4010\" => 4010, \"4011\" => 4011, \"4012\" => 4012, \"4013\" => 4013, \"4014\" => 4014, \"4015\" => 4015, \"4016\" => 4016, \"4017\" => 4017, \"4018\" => 4018, \"4019\" => 4019, \"4020\" => 4020, \"4021\" => 4021, \"4022\" => 4022, \"4023\" => 4023, \"4024\" => 4024, \"4025\" => 4025, \"4026\" => 4026, \"4027\" => 4027, \"4028\" => 4028, \"4029\" => 4029, \"4030\" => 4030, \"4031\" => 4031, \"4032\" => 4032, \"4033\" => 4033, \"4034\" => 4034, \"4035\" => 4035, \"4036\" => 4036, \"4037\" => 4037, \"4038\" => 4038, \"4039\" => 4039, \"4040\" => 4040, \"4041\" => 4041, \"4042\" => 4042, \"4043\" => 4043, \"4044\" => 4044, \"4045\" => 4045, \"4046\" => 4046, \"4047\" => 4047, \"4048\" => 4048, \"4049\" => 4049, \"4050\" => 4050, \"4051\" => 4051, \"4052\" => 4052, \"4053\" => 4053, \"4054\" => 4054, \"4055\" => 4055, \"4056\" => 4056, \"4057\" => 4057, \"4058\" => 4058, \"4059\" => 4059, \"4060\" => 4060, \"4061\" => 4061, \"4062\" => 4062, \"4063\" => 4063, \"4064\" => 4064, \"4065\" => 4065, \"4066\" => 4066, \"4067\" => 4067, \"4068\" => 4068, \"4069\" => 4069, \"4070\" => 4070, \"4071\" => 4071, \"4072\" => 4072, \"4073\" => 4073, \"4074\" => 4074, \"4075\" => 4075, \"4076\" => 4076, \"4077\" => 4077, \"4078\" => 4078, \"4079\" => 4079, \"4080\" => 4080, \"4081\" => 4081, \"4082\" => 4082, \"4083\" => 4083, \"4084\" => 4084, \"4085\" => 4085, \"4086\" => 4086, \"4087\" => 4087, \"4088\" => 4088, \"4089\" => 4089, \"4090\" => 4090, \"4091\" => 4091, \"4092\" => 4092, \"4093\" => 4093, \"4094\" => 4094, \"4095\" => 4095, \"4096\" => 4096, \"4097\" => 4097, \"4098\" => 4098, \"4099\" => 4099, \"4100\" => 4100, \"4101\" => 4101, \"4102\" => 4102, \"4103\" => 4103, \"4104\" => 4104, \"4105\" => 4105, \"4106\" => 4106, \"4107\" => 4107, \"4108\" => 4108, \"4109\" => 4109, \"4110\" => 4110, \"4111\" => 4111, \"4112\" => 4112, \"4113\" => 4113, \"4114\" => 4114, \"4115\" => 4115, \"4116\" => 4116, \"4117\" => 4117, \"4118\" => 4118, \"4119\" => 4119, \"4120\" => 4120, \"4121\" => 4121, \"4122\" => 4122, \"4123\" => 4123, \"4124\" => 4124, \"4125\" => 4125, \"4126\" => 4126, \"4127\" => 4127, \"4128\" => 4128, \"4129\" => 4129, \"4130\" => 4130, \"4131\" => 4131, \"4132\" => 4132, \"4133\" => 4133, \"4134\" => 4134, \"4135\" => 4135, \"4136\" => 4136, \"4137\" => 4137, \"4138\" => 4138, \"4139\" => 4139, \"4140\" => 4140, \"4141\" => 4141, \"4142\" => 4142, \"4143\" => 4143, \"4144\" => 4144, \"4145\" => 4145, \"4146\" => 4146, \"4147\" => 4147, \"4148\" => 4148, \"4149\" => 4149, \"4150\" => 4150, \"4151\" => 4151, \"4152\" => 4152, \"4153\" => 4153, \"4154\" => 4154, \"4155\" => 4155, \"4156\" => 4156, \"4157\" => 4157, \"4158\" => 4158, \"4159\" => 4159, \"4160\" => 4160, \"4161\" => 4161, \"4162\" => 4162, \"4163\" => 4163, \"4164\" => 4164, \"4165\" => 4165, \"4166\" => 4166, \"4167\" => 4167, \"4168\" => 4168, \"4169\" => 4169, \"4170\" => 4170, \"4171\" => 4171, \"4172\" => 4172, \"4173\" => 4173, \"4174\" => 4174, \"4175\" => 4175, \"4176\" => 4176, \"4177\" => 4177, \"4178\" => 4178, \"4179\" => 4179, \"4180\" => 4180, \"4181\" => 4181, \"4182\" => 4182, \"4183\" => 4183, \"4184\" => 4184, \"4185\" => 4185, \"4186\" => 4186, \"4187\" => 4187, \"4188\" => 4188, \"4189\" => 4189, \"4190\" => 4190, \"4191\" => 4191, \"4192\" => 4192, \"4193\" => 4193, \"4194\" => 4194, \"4195\" => 4195, \"4196\" => 4196, \"4197\" => 4197, \"4198\" => 4198, \"4199\" => 4199, \"4200\" => 4200, \"4201\" => 4201, \"4202\" => 4202, \"4203\" => 4203, \"4204\" => 4204, \"4205\" => 4205, \"4206\" => 4206, \"4207\" => 4207, \"4208\" => 4208, \"4209\" => 4209, \"4210\" => 4210, \"4211\" => 4211, \"4212\" => 4212, \"4213\" => 4213, \"4214\" => 4214, \"4215\" => 4215, \"4216\" => 4216, \"4217\" => 4217, \"4218\" => 4218, \"4219\" => 4219, \"4220\" => 4220, \"4221\" => 4221, \"4222\" => 4222, \"4223\" => 4223, \"4224\" => 4224, \"4225\" => 4225, \"4226\" => 4226, \"4227\" => 4227, \"4228\" => 4228, \"4229\" => 4229, \"4230\" => 4230, \"4231\" => 4231, \"4232\" => 4232, \"4233\" => 4233, \"4234\" => 4234, \"4235\" => 4235, \"4236\" => 4236, \"4237\" => 4237, \"4238\" => 4238, \"4239\" => 4239, \"4240\" => 4240, \"4241\" => 4241, \"4242\" => 4242, \"4243\" => 4243, \"4244\" => 4244, \"4245\" => 4245, \"4246\" => 4246, \"4247\" => 4247, \"4248\" => 4248, \"4249\" => 4249, \"4250\" => 4250, \"4251\" => 4251, \"4252\" => 4252, \"4253\" => 4253, \"4254\" => 4254, \"4255\" => 4255, \"4256\" => 4256, \"4257\" => 4257, \"4258\" => 4258, \"4259\" => 4259, \"4260\" => 4260, \"4261\" => 4261, \"4262\" => 4262, \"4263\" => 4263, \"4264\" => 4264, \"4265\" => 4265, \"4266\" => 4266, \"4267\" => 4267, \"4268\" => 4268, \"4269\" => 4269, \"4270\" => 4270, \"4271\" => 4271, \"4272\" => 4272, \"4273\" => 4273, \"4274\" => 4274, \"4275\" => 4275, \"4276\" => 4276, \"4277\" => 4277, \"4278\" => 4278, \"4279\" => 4279, \"4280\" => 4280, \"4281\" => 4281, \"4282\" => 4282, \"4283\" => 4283, \"4284\" => 4284, \"4285\" => 4285, \"4286\" => 4286, \"4287\" => 4287, \"4288\" => 4288, \"4289\" => 4289, \"4290\" => 4290, \"4291\" => 4291, \"4292\" => 4292, \"4293\" => 4293, \"4294\" => 4294, \"4295\" => 4295, \"4296\" => 4296, \"4297\" => 4297, \"4298\" => 4298, \"4299\" => 4299, \"4300\" => 4300, \"4301\" => 4301, \"4302\" => 4302, \"4303\" => 4303, \"4304\" => 4304, \"4305\" => 4305, \"4306\" => 4306, \"4307\" => 4307, \"4308\" => 4308, \"4309\" => 4309, \"4310\" => 4310, \"4311\" => 4311, \"4312\" => 4312, \"4313\" => 4313, \"4314\" => 4314, \"4315\" => 4315, \"4316\" => 4316, \"4317\" => 4317, \"4318\" => 4318, \"4319\" => 4319, \"4320\" => 4320, \"4321\" => 4321, \"4322\" => 4322, \"4323\" => 4323, \"4324\" => 4324, \"4325\" => 4325, \"4326\" => 4326, \"4327\" => 4327, \"4328\" => 4328, \"4329\" => 4329, \"4330\" => 4330, \"4331\" => 4331, \"4332\" => 4332, \"4333\" => 4333, \"4334\" => 4334, \"4335\" => 4335, \"4336\" => 4336, \"4337\" => 4337, \"4338\" => 4338, \"4339\" => 4339, \"4340\" => 4340, \"4341\" => 4341, \"4342\" => 4342, \"4343\" => 4343, \"4344\" => 4344, \"4345\" => 4345, \"4346\" => 4346, \"4347\" => 4347, \"4348\" => 4348, \"4349\" => 4349, \"4350\" => 4350, \"4351\" => 4351, \"4352\" => 4352, \"4353\" => 4353, \"4354\" => 4354, \"4355\" => 4355, \"4356\" => 4356, \"4357\" => 4357, \"4358\" => 4358, \"4359\" => 4359, \"4360\" => 4360, \"4361\" => 4361, \"4362\" => 4362, \"4363\" => 4363, \"4364\" => 4364, \"4365\" => 4365, \"4366\" => 4366, \"4367\" => 4367, \"4368\" => 4368, \"4369\" => 4369, \"4370\" => 4370, \"4371\" => 4371, \"4372\" => 4372, \"4373\" => 4373, \"4374\" => 4374, \"4375\" => 4375, \"4376\" => 4376, \"4377\" => 4377, \"4378\" => 4378, \"4379\" => 4379, \"4380\" => 4380, \"4381\" => 4381, \"4382\" => 4382, \"4383\" => 4383, \"4384\" => 4384, \"4385\" => 4385, \"4386\" => 4386, \"4387\" => 4387, \"4388\" => 4388, \"4389\" => 4389, \"4390\" => 4390, \"4391\" => 4391, \"4392\" => 4392, \"4393\" => 4393, \"4394\" => 4394, \"4395\" => 4395, \"4396\" => 4396, \"4397\" => 4397, \"4398\" => 4398, \"4399\" => 4399, \"4400\" => 4400, \"4401\" => 4401, \"4402\" => 4402, \"4403\" => 4403, \"4404\" => 4404, \"4405\" => 4405, \"4406\" => 4406, \"4407\" => 4407, \"4408\" => 4408, \"4409\" => 4409, \"4410\" => 4410, \"4411\" => 4411, \"4412\" => 4412, \"4413\" => 4413, \"4414\" => 4414, \"4415\" => 4415, \"4416\" => 4416, \"4417\" => 4417, \"4418\" => 4418, \"4419\" => 4419, \"4420\" => 4420, \"4421\" => 4421, \"4422\" => 4422, \"4423\" => 4423, \"4424\" => 4424, \"4425\" => 4425, \"4426\" => 4426, \"4427\" => 4427, \"4428\" => 4428, \"4429\" => 4429, \"4430\" => 4430, \"4431\" => 4431, \"4432\" => 4432, \"4433\" => 4433, \"4434\" => 4434, \"4435\" => 4435, \"4436\" => 4436, \"4437\" => 4437, \"4438\" => 4438, \"4439\" => 4439, \"4440\" => 4440, \"4441\" => 4441, \"4442\" => 4442, \"4443\" => 4443, \"4444\" => 4444, \"4445\" => 4445, \"4446\" => 4446, \"4447\" => 4447, \"4448\" => 4448, \"4449\" => 4449, \"4450\" => 4450, \"4451\" => 4451, \"4452\" => 4452, \"4453\" => 4453, \"4454\" => 4454, \"4455\" => 4455, \"4456\" => 4456, \"4457\" => 4457, \"4458\" => 4458, \"4459\" => 4459, \"4460\" => 4460, \"4461\" => 4461, \"4462\" => 4462, \"4463\" => 4463, \"4464\" => 4464, \"4465\" => 4465, \"4466\" => 4466, \"4467\" => 4467, \"4468\" => 4468, \"4469\" => 4469, \"4470\" => 4470, \"4471\" => 4471, \"4472\" => 4472, \"4473\" => 4473, \"4474\" => 4474, \"4475\" => 4475, \"4476\" => 4476, \"4477\" => 4477, \"4478\" => 4478, \"4479\" => 4479, \"4480\" => 4480, \"4481\" => 4481, \"4482\" => 4482, \"4483\" => 4483, \"4484\" => 4484, \"4485\" => 4485, \"4486\" => 4486, \"4487\" => 4487, \"4488\" => 4488, \"4489\" => 4489, \"4490\" => 4490, \"4491\" => 4491, \"4492\" => 4492, \"4493\" => 4493, \"4494\" => 4494, \"4495\" => 4495, \"4496\" => 4496, \"4497\" => 4497, \"4498\" => 4498, \"4499\" => 4499, \"4500\" => 4500, \"4501\" => 4501, \"4502\" => 4502, \"4503\" => 4503, \"4504\" => 4504, \"4505\" => 4505, \"4506\" => 4506, \"4507\" => 4507, \"4508\" => 4508, \"4509\" => 4509, \"4510\" => 4510, \"4511\" => 4511, \"4512\" => 4512, \"4513\" => 4513, \"4514\" => 4514, \"4515\" => 4515, \"4516\" => 4516, \"4517\" => 4517, \"4518\" => 4518, \"4519\" => 4519, \"4520\" => 4520, \"4521\" => 4521, \"4522\" => 4522, \"4523\" => 4523, \"4524\" => 4524, \"4525\" => 4525, \"4526\" => 4526, \"4527\" => 4527, \"4528\" => 4528, \"4529\" => 4529, \"4530\" => 4530, \"4531\" => 4531, \"4532\" => 4532, \"4533\" => 4533, \"4534\" => 4534, \"4535\" => 4535, \"4536\" => 4536, \"4537\" => 4537, \"4538\" => 4538, \"4539\" => 4539, \"4540\" => 4540, \"4541\" => 4541, \"4542\" => 4542, \"4543\" => 4543, \"4544\" => 4544, \"4545\" => 4545, \"4546\" => 4546, \"4547\" => 4547, \"4548\" => 4548, \"4549\" => 4549, \"4550\" => 4550, \"4551\" => 4551, \"4552\" => 4552, \"4553\" => 4553, \"4554\" => 4554, \"4555\" => 4555, \"4556\" => 4556, \"4557\" => 4557, \"4558\" => 4558, \"4559\" => 4559, \"4560\" => 4560, \"4561\" => 4561, \"4562\" => 4562, \"4563\" => 4563, \"4564\" => 4564, \"4565\" => 4565, \"4566\" => 4566, \"4567\" => 4567, \"4568\" => 4568, \"4569\" => 4569, \"4570\" => 4570, \"4571\" => 4571, \"4572\" => 4572, \"4573\" => 4573, \"4574\" => 4574, \"4575\" => 4575, \"4576\" => 4576, \"4577\" => 4577, \"4578\" => 4578, \"4579\" => 4579, \"4580\" => 4580, \"4581\" => 4581, \"4582\" => 4582, \"4583\" => 4583, \"4584\" => 4584, \"4585\" => 4585, \"4586\" => 4586, \"4587\" => 4587, \"4588\" => 4588, \"4589\" => 4589, \"4590\" => 4590, \"4591\" => 4591, \"4592\" => 4592, \"4593\" => 4593, \"4594\" => 4594, \"4595\" => 4595, \"4596\" => 4596, \"4597\" => 4597, \"4598\" => 4598, \"4599\" => 4599, \"4600\" => 4600, \"4601\" => 4601, \"4602\" => 4602, \"4603\" => 4603, \"4604\" => 4604, \"4605\" => 4605, \"4606\" => 4606, \"4607\" => 4607, \"4608\" => 4608, \"4609\" => 4609, \"4610\" => 4610, \"4611\" => 4611, \"4612\" => 4612, \"4613\" => 4613, \"4614\" => 4614, \"4615\" => 4615, \"4616\" => 4616, \"4617\" => 4617, \"4618\" => 4618, \"4619\" => 4619, \"4620\" => 4620, \"4621\" => 4621, \"4622\" => 4622, \"4623\" => 4623, \"4624\" => 4624, \"4625\" => 4625, \"4626\" => 4626, \"4627\" => 4627, \"4628\" => 4628, \"4629\" => 4629, \"4630\" => 4630, \"4631\" => 4631, \"4632\" => 4632, \"4633\" => 4633, \"4634\" => 4634, \"4635\" => 4635, \"4636\" => 4636, \"4637\" => 4637, \"4638\" => 4638, \"4639\" => 4639, \"4640\" => 4640, \"4641\" => 4641, \"4642\" => 4642, \"4643\" => 4643, \"4644\" => 4644, \"4645\" => 4645, \"4646\" => 4646, \"4647\" => 4647, \"4648\" => 4648, \"4649\" => 4649, \"4650\" => 4650, \"4651\" => 4651, \"4652\" => 4652, \"4653\" => 4653, \"4654\" => 4654, \"4655\" => 4655, \"4656\" => 4656, \"4657\" => 4657, \"4658\" => 4658, \"4659\" => 4659, \"4660\" => 4660, \"4661\" => 4661, \"4662\" => 4662, \"4663\" => 4663, \"4664\" => 4664, \"4665\" => 4665, \"4666\" => 4666, \"4667\" => 4667, \"4668\" => 4668, \"4669\" => 4669, \"4670\" => 4670, \"4671\" => 4671, \"4672\" => 4672, \"4673\" => 4673, \"4674\" => 4674, \"4675\" => 4675, \"4676\" => 4676, \"4677\" => 4677, \"4678\" => 4678, \"4679\" => 4679, \"4680\" => 4680, \"4681\" => 4681, \"4682\" => 4682, \"4683\" => 4683, \"4684\" => 4684, \"4685\" => 4685, \"4686\" => 4686, \"4687\" => 4687, \"4688\" => 4688, \"4689\" => 4689, \"4690\" => 4690, \"4691\" => 4691, \"4692\" => 4692, \"4693\" => 4693, \"4694\" => 4694, \"4695\" => 4695, \"4696\" => 4696, \"4697\" => 4697, \"4698\" => 4698, \"4699\" => 4699, \"4700\" => 4700, \"4701\" => 4701, \"4702\" => 4702, \"4703\" => 4703, \"4704\" => 4704, \"4705\" => 4705, \"4706\" => 4706, \"4707\" => 4707, \"4708\" => 4708, \"4709\" => 4709, \"4710\" => 4710, \"4711\" => 4711, \"4712\" => 4712, \"4713\" => 4713, \"4714\" => 4714, \"4715\" => 4715, \"4716\" => 4716, \"4717\" => 4717, \"4718\" => 4718, \"4719\" => 4719, \"4720\" => 4720, \"4721\" => 4721, \"4722\" => 4722, \"4723\" => 4723, \"4724\" => 4724, \"4725\" => 4725, \"4726\" => 4726, \"4727\" => 4727, \"4728\" => 4728, \"4729\" => 4729, \"4730\" => 4730, \"4731\" => 4731, \"4732\" => 4732, \"4733\" => 4733, \"4734\" => 4734, \"4735\" => 4735, \"4736\" => 4736, \"4737\" => 4737, \"4738\" => 4738, \"4739\" => 4739, \"4740\" => 4740, \"4741\" => 4741, \"4742\" => 4742, \"4743\" => 4743, \"4744\" => 4744, \"4745\" => 4745, \"4746\" => 4746, \"4747\" => 4747, \"4748\" => 4748, \"4749\" => 4749, \"4750\" => 4750, \"4751\" => 4751, \"4752\" => 4752, \"4753\" => 4753, \"4754\" => 4754, \"4755\" => 4755, \"4756\" => 4756, \"4757\" => 4757, \"4758\" => 4758, \"4759\" => 4759, \"4760\" => 4760, \"4761\" => 4761, \"4762\" => 4762, \"4763\" => 4763, \"4764\" => 4764, \"4765\" => 4765, \"4766\" => 4766, \"4767\" => 4767, \"4768\" => 4768, \"4769\" => 4769, \"4770\" => 4770, \"4771\" => 4771, \"4772\" => 4772, \"4773\" => 4773, \"4774\" => 4774, \"4775\" => 4775, \"4776\" => 4776, \"4777\" => 4777, \"4778\" => 4778, \"4779\" => 4779, \"4780\" => 4780, \"4781\" => 4781, \"4782\" => 4782, \"4783\" => 4783, \"4784\" => 4784, \"4785\" => 4785, \"4786\" => 4786, \"4787\" => 4787, \"4788\" => 4788, \"4789\" => 4789, \"4790\" => 4790, \"4791\" => 4791, \"4792\" => 4792, \"4793\" => 4793, \"4794\" => 4794, \"4795\" => 4795, \"4796\" => 4796, \"4797\" => 4797, \"4798\" => 4798, \"4799\" => 4799, \"4800\" => 4800, \"4801\" => 4801, \"4802\" => 4802, \"4803\" => 4803, \"4804\" => 4804, \"4805\" => 4805, \"4806\" => 4806, \"4807\" => 4807, \"4808\" => 4808, \"4809\" => 4809, \"4810\" => 4810, \"4811\" => 4811, \"4812\" => 4812, \"4813\" => 4813, \"4814\" => 4814, \"4815\" => 4815, \"4816\" => 4816, \"4817\" => 4817, \"4818\" => 4818, \"4819\" => 4819, \"4820\" => 4820, \"4821\" => 4821, \"4822\" => 4822, \"4823\" => 4823, \"4824\" => 4824, \"4825\" => 4825, \"4826\" => 4826, \"4827\" => 4827, \"4828\" => 4828, \"4829\" => 4829, \"4830\" => 4830, \"4831\" => 4831, \"4832\" => 4832, \"4833\" => 4833, \"4834\" => 4834, \"4835\" => 4835, \"4836\" => 4836, \"4837\" => 4837, \"4838\" => 4838, \"4839\" => 4839, \"4840\" => 4840, \"4841\" => 4841, \"4842\" => 4842, \"4843\" => 4843, \"4844\" => 4844, \"4845\" => 4845, \"4846\" => 4846, \"4847\" => 4847, \"4848\" => 4848, \"4849\" => 4849, \"4850\" => 4850, \"4851\" => 4851, \"4852\" => 4852, \"4853\" => 4853, \"4854\" => 4854, \"4855\" => 4855, \"4856\" => 4856, \"4857\" => 4857, \"4858\" => 4858, \"4859\" => 4859, \"4860\" => 4860, \"4861\" => 4861, \"4862\" => 4862, \"4863\" => 4863, \"4864\" => 4864, \"4865\" => 4865, \"4866\" => 4866, \"4867\" => 4867, \"4868\" => 4868, \"4869\" => 4869, \"4870\" => 4870, \"4871\" => 4871, \"4872\" => 4872, \"4873\" => 4873, \"4874\" => 4874, \"4875\" => 4875, \"4876\" => 4876, \"4877\" => 4877, \"4878\" => 4878, \"4879\" => 4879, \"4880\" => 4880, \"4881\" => 4881, \"4882\" => 4882, \"4883\" => 4883, \"4884\" => 4884, \"4885\" => 4885, \"4886\" => 4886, \"4887\" => 4887, \"4888\" => 4888, \"4889\" => 4889, \"4890\" => 4890, \"4891\" => 4891, \"4892\" => 4892, \"4893\" => 4893, \"4894\" => 4894, \"4895\" => 4895, \"4896\" => 4896, \"4897\" => 4897, \"4898\" => 4898, \"4899\" => 4899, \"4900\" => 4900, \"4901\" => 4901, \"4902\" => 4902, \"4903\" => 4903, \"4904\" => 4904, \"4905\" => 4905, \"4906\" => 4906, \"4907\" => 4907, \"4908\" => 4908, \"4909\" => 4909, \"4910\" => 4910, \"4911\" => 4911, \"4912\" => 4912, \"4913\" => 4913, \"4914\" => 4914, \"4915\" => 4915, \"4916\" => 4916, \"4917\" => 4917, \"4918\" => 4918, \"4919\" => 4919, \"4920\" => 4920, \"4921\" => 4921, \"4922\" => 4922, \"4923\" => 4923, \"4924\" => 4924, \"4925\" => 4925, \"4926\" => 4926, \"4927\" => 4927, \"4928\" => 4928, \"4929\" => 4929, \"4930\" => 4930, \"4931\" => 4931, \"4932\" => 4932, \"4933\" => 4933, \"4934\" => 4934, \"4935\" => 4935, \"4936\" => 4936, \"4937\" => 4937, \"4938\" => 4938, \"4939\" => 4939, \"4940\" => 4940, \"4941\" => 4941, \"4942\" => 4942, \"4943\" => 4943, \"4944\" => 4944, \"4945\" => 4945, \"4946\" => 4946, \"4947\" => 4947, \"4948\" => 4948, \"4949\" => 4949, \"4950\" => 4950, \"4951\" => 4951, \"4952\" => 4952, \"4953\" => 4953, \"4954\" => 4954, \"4955\" => 4955, \"4956\" => 4956, \"4957\" => 4957, \"4958\" => 4958, \"4959\" => 4959, \"4960\" => 4960, \"4961\" => 4961, \"4962\" => 4962, \"4963\" => 4963, \"4964\" => 4964, \"4965\" => 4965, \"4966\" => 4966, \"4967\" => 4967, \"4968\" => 4968, \"4969\" => 4969, \"4970\" => 4970, \"4971\" => 4971, \"4972\" => 4972, \"4973\" => 4973, \"4974\" => 4974, \"4975\" => 4975, \"4976\" => 4976, \"4977\" => 4977, \"4978\" => 4978, \"4979\" => 4979, \"4980\" => 4980, \"4981\" => 4981, \"4982\" => 4982, \"4983\" => 4983, \"4984\" => 4984, \"4985\" => 4985, \"4986\" => 4986, \"4987\" => 4987, \"4988\" => 4988, \"4989\" => 4989, \"4990\" => 4990, \"4991\" => 4991, \"4992\" => 4992, \"4993\" => 4993, \"4994\" => 4994, \"4995\" => 4995, \"4996\" => 4996, \"4997\" => 4997, \"4998\" => 4998, \"4999\" => 4999, \"5000\" => 5000, \"5001\" => 5001, \"5002\" => 5002, \"5003\" => 5003, \"5004\" => 5004, \"5005\" => 5005, \"5006\" => 5006, \"5007\" => 5007, \"5008\" => 5008, \"5009\" => 5009, \"5010\" => 5010, \"5011\" => 5011, \"5012\" => 5012, \"5013\" => 5013, \"5014\" => 5014, \"5015\" => 5015, \"5016\" => 5016, \"5017\" => 5017, \"5018\" => 5018, \"5019\" => 5019, \"5020\" => 5020, \"5021\" => 5021, \"5022\" => 5022, \"5023\" => 5023, \"5024\" => 5024, \"5025\" => 5025, \"5026\" => 5026, \"5027\" => 5027, \"5028\" => 5028, \"5029\" => 5029, \"5030\" => 5030, \"5031\" => 5031, \"5032\" => 5032, \"5033\" => 5033, \"5034\" => 5034, \"5035\" => 5035, \"5036\" => 5036, \"5037\" => 5037, \"5038\" => 5038, \"5039\" => 5039, \"5040\" => 5040, \"5041\" => 5041, \"5042\" => 5042, \"5043\" => 5043, \"5044\" => 5044, \"5045\" => 5045, \"5046\" => 5046, \"5047\" => 5047, \"5048\" => 5048, \"5049\" => 5049, \"5050\" => 5050, \"5051\" => 5051, \"5052\" => 5052, \"5053\" => 5053, \"5054\" => 5054, \"5055\" => 5055, \"5056\" => 5056, \"5057\" => 5057, \"5058\" => 5058, \"5059\" => 5059, \"5060\" => 5060, \"5061\" => 5061, \"5062\" => 5062, \"5063\" => 5063, \"5064\" => 5064, \"5065\" => 5065, \"5066\" => 5066, \"5067\" => 5067, \"5068\" => 5068, \"5069\" => 5069, \"5070\" => 5070, \"5071\" => 5071, \"5072\" => 5072, \"5073\" => 5073, \"5074\" => 5074, \"5075\" => 5075, \"5076\" => 5076, \"5077\" => 5077, \"5078\" => 5078, \"5079\" => 5079, \"5080\" => 5080, \"5081\" => 5081, \"5082\" => 5082, \"5083\" => 5083, \"5084\" => 5084, \"5085\" => 5085, \"5086\" => 5086, \"5087\" => 5087, \"5088\" => 5088, \"5089\" => 5089, \"5090\" => 5090, \"5091\" => 5091, \"5092\" => 5092, \"5093\" => 5093, \"5094\" => 5094, \"5095\" => 5095, \"5096\" => 5096, \"5097\" => 5097, \"5098\" => 5098, \"5099\" => 5099, \"5100\" => 5100, \"5101\" => 5101, \"5102\" => 5102, \"5103\" => 5103, \"5104\" => 5104, \"5105\" => 5105, \"5106\" => 5106, \"5107\" => 5107, \"5108\" => 5108, \"5109\" => 5109, \"5110\" => 5110, \"5111\" => 5111, \"5112\" => 5112, \"5113\" => 5113, \"5114\" => 5114, \"5115\" => 5115, \"5116\" => 5116, \"5117\" => 5117, \"5118\" => 5118, \"5119\" => 5119, \"5120\" => 5120, \"5121\" => 5121, \"5122\" => 5122, \"5123\" => 5123, \"5124\" => 5124, \"5125\" => 5125, \"5126\" => 5126, \"5127\" => 5127, \"5128\" => 5128, \"5129\" => 5129, \"5130\" => 5130, \"5131\" => 5131, \"5132\" => 5132, \"5133\" => 5133, \"5134\" => 5134, \"5135\" => 5135, \"5136\" => 5136, \"5137\" => 5137, \"5138\" => 5138, \"5139\" => 5139, \"5140\" => 5140, \"5141\" => 5141, \"5142\" => 5142, \"5143\" => 5143, \"5144\" => 5144, \"5145\" => 5145, \"5146\" => 5146, \"5147\" => 5147, \"5148\" => 5148, \"5149\" => 5149, \"5150\" => 5150, \"5151\" => 5151, \"5152\" => 5152, \"5153\" => 5153, \"5154\" => 5154, \"5155\" => 5155, \"5156\" => 5156, \"5157\" => 5157, \"5158\" => 5158, \"5159\" => 5159, \"5160\" => 5160, \"5161\" => 5161, \"5162\" => 5162, \"5163\" => 5163, \"5164\" => 5164, \"5165\" => 5165, \"5166\" => 5166, \"5167\" => 5167, \"5168\" => 5168, \"5169\" => 5169, \"5170\" => 5170, \"5171\" => 5171, \"5172\" => 5172, \"5173\" => 5173, \"5174\" => 5174, \"5175\" => 5175, \"5176\" => 5176, \"5177\" => 5177, \"5178\" => 5178, \"5179\" => 5179, \"5180\" => 5180, \"5181\" => 5181, \"5182\" => 5182, \"5183\" => 5183, \"5184\" => 5184, \"5185\" => 5185, \"5186\" => 5186, \"5187\" => 5187, \"5188\" => 5188, \"5189\" => 5189, \"5190\" => 5190, \"5191\" => 5191, \"5192\" => 5192, \"5193\" => 5193, \"5194\" => 5194, \"5195\" => 5195, \"5196\" => 5196, \"5197\" => 5197, \"5198\" => 5198, _ => 5199, } } "} {"_id":"doc-en-rust-39c3e88b9381d1647bd20f37dd88087dc5f3468226601f793622e329fa8f31b1","title":"","text":"// As write_sub_paths, but does not process the last ident in the path (assuming it // will be processed elsewhere). See note on write_sub_paths about global. fn write_sub_paths_truncated(&mut self, path: &'tcx hir::Path<'tcx>) { for seg in &path.segments[..path.segments.len() - 1] { if let Some(data) = self.save_ctxt.get_path_segment_data(seg) { self.dumper.dump_ref(data); if let [segments @ .., _] = path.segments { for seg in segments { if let Some(data) = self.save_ctxt.get_path_segment_data(seg) { self.dumper.dump_ref(data); } } } }"} {"_id":"doc-en-rust-4dee3d48839879b329150a5e81af8189769bfb5a7c48a22734c750b2f3bb89a6","title":"","text":"} } } hir::ExprKind::Struct(hir::QPath::Resolved(_, path), ..) => { hir::ExprKind::Struct(qpath, ..) => { let segment = match qpath { hir::QPath::Resolved(_, path) => path.segments.last().unwrap(), hir::QPath::TypeRelative(_, segment) => segment, }; match self.tables.expr_ty_adjusted(&hir_node).kind { ty::Adt(def, _) if !def.is_enum() => { let sub_span = path.segments.last().unwrap().ident.span; let sub_span = segment.ident.span; filter!(self.span_utils, sub_span); let span = self.span_from_span(sub_span); Some(Data::RefData(Ref {"} {"_id":"doc-en-rust-714532ff63f605b2708cebb978fc0c9190b3cb8f67b729c443541c2ad7f4c4e0","title":"","text":"} _ => { // FIXME bug!(); bug!(\"invalid expression: {:?}\", expr); } } }"} {"_id":"doc-en-rust-4957270aa6b6034274f84e74d3aede675524138ee6bb57197feee6e9b19433aa","title":"","text":" // compile-flags: -Zsave-analysis use {self}; //~ ERROR E0431 fn main () { } "} {"_id":"doc-en-rust-01dc33c36ddba47fb9c83c80aef7ac769e15bd45789309b78570a290d71e2172","title":"","text":" error[E0431]: `self` import can only appear in an import list with a non-empty prefix --> $DIR/issue-73020.rs:2:6 | LL | use {self}; | ^^^^ can only appear in an import list with a non-empty prefix error: aborting due to previous error For more information about this error, try `rustc --explain E0431`. "} {"_id":"doc-en-rust-872209a0ed43d2d997e72f83489275b62c2036af22da6b7047b066051983a6bd","title":"","text":" // build-pass // compile-flags: -Zsave-analysis enum Enum2 { Variant8 { _field: bool }, } impl Enum2 { fn new_variant8() -> Enum2 { Self::Variant8 { _field: true } } } fn main() {} "} {"_id":"doc-en-rust-0471f35bb9d2dd8da8232c93bca40376f796d40a24291502eb695cfa13dc344c","title":"","text":"debug = false debug-assertions = false [profile.release.package.compiler_builtins] # For compiler-builtins we always use a high number of codegen units. # The goal here is to place every single intrinsic into its own object # file to avoid symbol clashes with the system libgcc if possible. Note # that this number doesn't actually produce this many object files, we # just don't create more than this number of object files. # # It's a bit of a bummer that we have to pass this here, unfortunately. # Ideally this would be specified through an env var to Cargo so Cargo # knows how many CGUs are for this specific crate, but for now # per-crate configuration isn't specifiable in the environment. codegen-units = 10000 # We want the RLS to use the version of Cargo that we've got vendored in this # repository to ensure that the same exact version of Cargo is used by both the # RLS and the Cargo binary itself. The RLS depends on Cargo as a git repository"} {"_id":"doc-en-rust-f8174b9350f42e1da29632a0891ec98a801211f6e929aff2324a34297ab3229f","title":"","text":"fn merge_codegen_units<'tcx>( tcx: TyCtxt<'tcx>, initial_partitioning: &mut PreInliningPartitioning<'tcx>, mut target_cgu_count: usize, target_cgu_count: usize, ) { assert!(target_cgu_count >= 1); let codegen_units = &mut initial_partitioning.codegen_units; if tcx.is_compiler_builtins(LOCAL_CRATE) { // Compiler builtins require some degree of control over how mono items // are partitioned into compilation units. Provide it by keeping the // original partitioning when compiling the compiler builtins crate. target_cgu_count = codegen_units.len(); } // Note that at this point in time the `codegen_units` here may not be in a // deterministic order (but we know they're deterministically the same set). // We want this merging to produce a deterministic ordering of codegen units"} {"_id":"doc-en-rust-d659bc4851df7751bb4dcbedd237c9d7558270447fe937ad56d0bee27aa93f69","title":"","text":" // Verifies that during compiler_builtins compilation the codegen units are kept // unmerged. Even when only a single codegen unit is requested with -Ccodegen-units=1. // // compile-flags: -Zprint-mono-items=eager -Ccodegen-units=1 #![compiler_builtins] #![crate_type=\"lib\"] #![feature(compiler_builtins)] mod atomics { //~ MONO_ITEM fn compiler_builtins::atomics[0]::sync_1[0] @@ compiler_builtins-cgu.0[External] #[no_mangle] pub extern \"C\" fn sync_1() {} //~ MONO_ITEM fn compiler_builtins::atomics[0]::sync_2[0] @@ compiler_builtins-cgu.0[External] #[no_mangle] pub extern \"C\" fn sync_2() {} //~ MONO_ITEM fn compiler_builtins::atomics[0]::sync_3[0] @@ compiler_builtins-cgu.0[External] #[no_mangle] pub extern \"C\" fn sync_3() {} } mod x { //~ MONO_ITEM fn compiler_builtins::x[0]::x[0] @@ compiler_builtins-cgu.1[External] #[no_mangle] pub extern \"C\" fn x() {} } mod y { //~ MONO_ITEM fn compiler_builtins::y[0]::y[0] @@ compiler_builtins-cgu.2[External] #[no_mangle] pub extern \"C\" fn y() {} } mod z { //~ MONO_ITEM fn compiler_builtins::z[0]::z[0] @@ compiler_builtins-cgu.3[External] #[no_mangle] pub extern \"C\" fn z() {} } "} {"_id":"doc-en-rust-4aefbba8b9b5c31341d5d5ecad331d6e246f0aaa1f61a868742eda3f097edd58","title":"","text":"ValueNS } #[deriving(Eq)] pub enum NamespaceError { NoError, ModuleError, TypeError, ValueError } /// A NamespaceResult represents the result of resolving an import in /// a particular namespace. The result is either definitely-resolved, /// definitely- unresolved, or unknown."} {"_id":"doc-en-rust-4185e6432df8f06557d4942e56827b4ddeb37625e028eb1670a1f155beb4ba2a","title":"","text":"} pub fn namespace_to_str(ns: Namespace) -> ~str { pub fn namespace_error_to_str(ns: NamespaceError) -> &'static str { match ns { TypeNS => ~\"type\", ValueNS => ~\"value\", NoError => \"\", ModuleError => \"module\", TypeError => \"type\", ValueError => \"value\", } }"} {"_id":"doc-en-rust-8ceea6a3b7fa1fa03fcd8f6d1136e61e0c310793c43b0d12b4ebd23611e5e8b4","title":"","text":"// * If no duplicate checking was requested at all, do // nothing. let mut is_duplicate = false; let mut duplicate_type = NoError; let ns = match duplicate_checking_mode { ForbidDuplicateModules => { is_duplicate = child.get_module_if_available().is_some(); if (child.get_module_if_available().is_some()) { duplicate_type = ModuleError; } Some(TypeNS) } ForbidDuplicateTypes => { match child.def_for_namespace(TypeNS) { Some(def_mod(_)) | None => {} Some(_) => is_duplicate = true Some(_) => duplicate_type = TypeError } Some(TypeNS) } ForbidDuplicateValues => { is_duplicate = child.defined_in_namespace(ValueNS); if child.defined_in_namespace(ValueNS) { duplicate_type = ValueError; } Some(ValueNS) } ForbidDuplicateTypesAndValues => {"} {"_id":"doc-en-rust-dae0d5db6f0a43982085b9bada88c3d69580f6c0982ca37f9c0c05160be7d165","title":"","text":"Some(def_mod(_)) | None => {} Some(_) => { n = Some(TypeNS); is_duplicate = true; duplicate_type = TypeError; } }; if child.defined_in_namespace(ValueNS) { is_duplicate = true; duplicate_type = ValueError; n = Some(ValueNS); } n } OverwriteDuplicates => None }; if is_duplicate { if (duplicate_type != NoError) { // Return an error here by looking up the namespace that // had the duplicate. let ns = ns.unwrap(); self.session.span_err(sp, fmt!(\"duplicate definition of %s `%s`\", namespace_to_str(ns), namespace_error_to_str(duplicate_type), self.session.str_of(name))); { let r = child.span_for_namespace(ns); for r.iter().advance |sp| { self.session.span_note(*sp, fmt!(\"first definition of %s %s here:\", namespace_to_str(ns), fmt!(\"first definition of %s `%s` here\", namespace_error_to_str(duplicate_type), self.session.str_of(name))); } }"} {"_id":"doc-en-rust-4da015732521097ee10b33e4be69ff3caf8b322fb5008bd0a190f681898a4df1","title":"","text":"pub mod a {} pub mod a {} //~ ERROR duplicate definition of type `a` pub mod a {} //~ ERROR duplicate definition of module `a` fn main() {}"} {"_id":"doc-en-rust-fad54e2b3faa0467a1cec23f5a1c44095928183c1acd532d2352b6162d46fdf5","title":"","text":"impl<'mir, 'tcx, Tag, Extra> Frame<'mir, 'tcx, Tag, Extra> { /// Return the `SourceInfo` of the current instruction. pub fn current_source_info(&self) -> Option { self.loc.map(|loc| { let block = &self.body.basic_blocks()[loc.block]; if loc.statement_index < block.statements.len() { block.statements[loc.statement_index].source_info } else { block.terminator().source_info } }) pub fn current_source_info(&self) -> Option<&mir::SourceInfo> { self.loc.map(|loc| self.body.source_info(loc)) } }"} {"_id":"doc-en-rust-9b3516c9312424688b7032335ed84cc77483d28cd3bddafe70e675fd4b4cc5bd","title":"","text":"}) // Assert that there is always such a frame. .unwrap(); // Assert that the frame we look at is actually executing code currently // (`current_source_info` is None when we are unwinding and the frame does // not require cleanup). let loc = frame.loc.unwrap(); // If this is a `Call` terminator, use the `fn_span` instead. let block = &frame.body.basic_blocks()[loc.block]; assert_eq!(block.statements.len(), loc.statement_index); debug!( \"find_closest_untracked_caller_location:: got terminator {:?} ({:?})\", block.terminator(), block.terminator().kind ); if let TerminatorKind::Call { fn_span, .. } = block.terminator().kind { return fn_span; if loc.statement_index == block.statements.len() { debug!( \"find_closest_untracked_caller_location:: got terminator {:?} ({:?})\", block.terminator(), block.terminator().kind ); if let TerminatorKind::Call { fn_span, .. } = block.terminator().kind { return fn_span; } } unreachable!(); // This is a different terminator (such as `Drop`) or not a terminator at all // (such as `box`). Use the normal span. frame.body.source_info(loc).span } /// Allocate a `const core::panic::Location` with the provided filename and line/column numbers."} {"_id":"doc-en-rust-44817d088270d812582dd36fb35136a94b0e62ec7c395fb9a61ded594403cffb","title":"","text":"impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { fn visit_local(&mut self, local: &Local, context: PlaceContext, location: Location) { if self.body.local_decls.get(*local).is_none() { self.fail( location, format!(\"local {:?} has no corresponding declaration in `body.local_decls`\", local), ); } if self.reachable_blocks.contains(location.block) && context.is_use() { // Uses of locals must occur while the local's storage is allocated. self.storage_liveness.seek_after_primary_effect(location);"} {"_id":"doc-en-rust-8052b3484288fc6bc0987006395c7a62170cc0f28ffc051cd9b75f0d76851ccc","title":"","text":" // Disabling on android for the time being // See https://github.com/rust-lang/rust/issues/73535#event-3477699747 #![cfg(not(target_os = \"android\"))] #![feature(btree_drain_filter)] #![feature(map_first_last)] #![feature(repr_simd)]"} {"_id":"doc-en-rust-f12f96d0d0236a04a67f5ff7bbbfd6c8555f02c64b8188b4c341ea7d37843691","title":"","text":"// std testing crates, okay for now at least \"src/libcore/tests\", \"src/liballoc/tests/lib.rs\", \"src/liballoc/benches/lib.rs\", // The `VaList` implementation must have platform specific code. // The Windows implementation of a `va_list` is always a character // pointer regardless of the target architecture. As a result,"} {"_id":"doc-en-rust-13e277f5cd7ee1d87a5a221eb44fe9d36a0eab90f5b3f61e5e3d88c376a92e07","title":"","text":"/// Inline asm operand type must be `Sized`. InlineAsmSized, /// `[T, ..n]` implies that `T` must be `Copy`. RepeatVec, /// If the function in the array repeat expression is a `const fn`, /// display a help message suggesting to move the function call to a /// new `const` item while saying that `T` doesn't implement `Copy`. RepeatVec(bool), /// Types of fields (other than the last, except for packed structs) in a struct must be sized. FieldSized {"} {"_id":"doc-en-rust-cd52df2f33c831c503e0474a65dad5f81bb0ba2612ed750175312ba36922ec4b","title":"","text":"use crate::dataflow::impls::MaybeInitializedPlaces; use crate::dataflow::move_paths::MoveData; use crate::dataflow::ResultsCursor; use crate::transform::{ check_consts::ConstCx, promote_consts::is_const_fn_in_array_repeat_expression, }; use crate::borrow_check::{ borrow_set::BorrowSet,"} {"_id":"doc-en-rust-51c4aac3c82cb0b86db81f71087fdb10d92e257eb9256aa85f0eb6d4616cde73","title":"","text":"Operand::Copy(..) | Operand::Constant(..) => { // These are always okay: direct use of a const, or a value that can evidently be copied. } Operand::Move(_) => { Operand::Move(place) => { // Make sure that repeated elements implement `Copy`. let span = body.source_info(location).span; let ty = operand.ty(body, tcx); if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) { let ccx = ConstCx::new_with_param_env(tcx, body, self.param_env); let is_const_fn = is_const_fn_in_array_repeat_expression(&ccx, &place, &body); debug!(\"check_rvalue: is_const_fn={:?}\", is_const_fn); let def_id = body.source.def_id().expect_local(); self.infcx.report_selection_error( &traits::Obligation::new( ObligationCause::new( span, self.tcx().hir().local_def_id_to_hir_id(def_id), traits::ObligationCauseCode::RepeatVec, traits::ObligationCauseCode::RepeatVec(is_const_fn), ), self.param_env, ty::Binder::bind(ty::TraitRef::new("} {"_id":"doc-en-rust-d90e7ad9a2c867cc9559bc73cf2767c2217727ebe77bf75e942f0974d551385f","title":"","text":"promotions } /// This function returns `true` if the function being called in the array /// repeat expression is a `const` function. crate fn is_const_fn_in_array_repeat_expression<'tcx>( ccx: &ConstCx<'_, 'tcx>, place: &Place<'tcx>, body: &Body<'tcx>, ) -> bool { match place.as_local() { // rule out cases such as: `let my_var = some_fn(); [my_var; N]` Some(local) if body.local_decls[local].is_user_variable() => return false, None => return false, _ => {} } for block in body.basic_blocks() { if let Some(Terminator { kind: TerminatorKind::Call { func, destination, .. }, .. }) = &block.terminator { if let Operand::Constant(box Constant { literal: ty::Const { ty, .. }, .. }) = func { if let ty::FnDef(def_id, _) = *ty.kind() { if let Some((destination_place, _)) = destination { if destination_place == place { if is_const_fn(ccx.tcx, def_id) { return true; } } } } } } } false } "} {"_id":"doc-en-rust-bd48d9ac7e75d402eeba7f6f6f86f9db0dd29a5651f677c79f5217305a11fff4","title":"","text":"ObligationCauseCode::Coercion { source: _, target } => { err.note(&format!(\"required by cast to type `{}`\", self.ty_to_string(target))); } ObligationCauseCode::RepeatVec => { ObligationCauseCode::RepeatVec(is_const_fn) => { err.note( \"the `Copy` trait is required because the repeated element will be copied\", ); if is_const_fn { err.help( \"consider creating a new `const` item and initializing with the result of the function call to be used in the repeat position, like `const VAL: Type = const_fn();` and `let x = [VAL; 42];`\", ); } if self.tcx.sess.is_nightly_build() && is_const_fn { err.help( \"create an inline `const` block, see PR #2920 for more information\", ); } } ObligationCauseCode::VariableType(hir_id) => { let parent_node = self.tcx.hir().get_parent_node(hir_id);"} {"_id":"doc-en-rust-00c1de3e0b51810ac9a23c137a2bc1bdd719fd4257e90ce3467ab311edccb433","title":"","text":"This directory contains the source code of the rust project, including: - The test suite - The bootstrapping build system - Various submodules for tools, like rustdoc, rls, etc."} {"_id":"doc-en-rust-45ce88ef150a34b889c7f1fa60fc94d70dfdfe6bd0f8b363f5afc129140e708e","title":"","text":"= help: the following implementations were found: as Copy> = note: the `Copy` trait is required because the repeated element will be copied = help: consider creating a new `const` item and initializing with the result of the function call to be used in the repeat position, like `const VAL: Type = const_fn();` and `let x = [VAL; 42];` = help: create an inline `const` block, see PR #2920 for more information error: aborting due to previous error"} {"_id":"doc-en-rust-8e74159336e7fa42b7a630032db50e27baaef504312ceaacb038c39207f04e4d","title":"","text":" fn main() { // should hint to create an inline `const` block // or to create a new `const` item let strings: [String; 5] = [String::new(); 5]; //~^ ERROR the trait bound `String: Copy` is not satisfied println!(\"{:?}\", strings); } "} {"_id":"doc-en-rust-523e7a974584cd35be6758e810e97bd69882d084f2c35ccfa1f5accfcb634b34","title":"","text":" error[E0277]: the trait bound `String: Copy` is not satisfied --> $DIR/const-fn-in-vec.rs:4:32 | LL | let strings: [String; 5] = [String::new(); 5]; | ^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` | = note: the `Copy` trait is required because the repeated element will be copied = help: consider creating a new `const` item and initializing with the result of the function call to be used in the repeat position, like `const VAL: Type = const_fn();` and `let x = [VAL; 42];` = help: create an inline `const` block, see PR #2920 for more information error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-d81b2e5e4868eff48e6aafa0239b3698274a040d4325e440ae404f1475567e03","title":"","text":"use rustc_infer::infer::{self, InferOk, TyCtxtInferExt}; use rustc_middle::ty; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::subst::{InternalSubsts, Subst, SubstsRef}; use rustc_middle::ty::subst::{InternalSubsts, Subst}; use rustc_middle::ty::util::ExplicitSelf; use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt, WithConstness}; use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt}; use rustc_span::Span; use rustc_trait_selection::traits::error_reporting::InferCtxtExt; use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, Reveal}; use super::{potentially_plural_count, FnCtxt, Inherited}; use std::iter; /// Checks that a method from an impl conforms to the signature of /// the same method as declared in the trait."} {"_id":"doc-en-rust-43eb3e20efc4a9cd59bd9bb82d11bb239abd09e9887a5ccdaa411916cafd57e4","title":"","text":"return Ok(()); } let param_env = tcx.param_env(impl_ty.def_id); // Given // // impl Foo for (A, B) {"} {"_id":"doc-en-rust-9c42ca862b818e5726074f8f3be5bd46c6914289555ce5300471c21ca9d1ba08","title":"","text":"impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs); let impl_ty_value = tcx.type_of(impl_ty.def_id); // Map the predicate from the trait to the corresponding one for the impl. // For example: let param_env = tcx.param_env(impl_ty.def_id); // When checking something like // // trait X { type Y<'a>: PartialEq } impl X for T { type Y<'a> = &'a S; } // impl<'x> X<&'x u32> for () { type Y<'c> = &'c u32; } // trait X { type Y: PartialEq<::Y> } // impl X for T { default type Y = S; } // // For the `for<'a> <>::Y<'a>: PartialEq` bound, this // function would translate and partially normalize // `[>::Y<'a>, A]` to `[&'a u32, &'x u32]`. let translate_predicate_substs = move |predicate_substs: SubstsRef<'tcx>| { tcx.mk_substs( iter::once(impl_ty_value.into()) .chain(predicate_substs[1..].iter().map(|s| s.subst(tcx, rebased_substs))), ) // We will have to prove the bound S: PartialEq<::Y>. In this case // we want ::Y to normalize to S. This is valid because we are // checking the default value specifically here. Add this equality to the // ParamEnv for normalization specifically. let normalize_param_env = { let mut predicates = param_env.caller_bounds().iter().collect::>(); predicates.push( ty::Binder::dummy(ty::ProjectionPredicate { projection_ty: ty::ProjectionTy { item_def_id: trait_ty.def_id, substs: rebased_substs, }, ty: impl_ty_value, }) .to_predicate(tcx), ); ty::ParamEnv::new(tcx.intern_predicates(&predicates), Reveal::UserFacing, None) }; tcx.infer_ctxt().enter(move |infcx| {"} {"_id":"doc-en-rust-2e06451544aca8f1387faa5a9e04a6c5dbcce88d3cca1bb44475359992518604","title":"","text":"); let predicates = tcx.projection_predicates(trait_ty.def_id); debug!(\"compare_projection_bounds: projection_predicates={:?}\", predicates); for predicate in predicates { let concrete_ty_predicate = match predicate.kind() { ty::PredicateKind::Trait(poly_tr, c) => poly_tr .map_bound(|tr| { let trait_substs = translate_predicate_substs(tr.trait_ref.substs); ty::TraitRef { def_id: tr.def_id(), substs: trait_substs } }) .with_constness(*c) .to_predicate(tcx), ty::PredicateKind::Projection(poly_projection) => poly_projection .map_bound(|projection| { let projection_substs = translate_predicate_substs(projection.projection_ty.substs); ty::ProjectionPredicate { projection_ty: ty::ProjectionTy { substs: projection_substs, item_def_id: projection.projection_ty.item_def_id, }, ty: projection.ty.subst(tcx, rebased_substs), } }) .to_predicate(tcx), ty::PredicateKind::TypeOutlives(poly_outlives) => poly_outlives .map_bound(|outlives| { ty::OutlivesPredicate(impl_ty_value, outlives.1.subst(tcx, rebased_substs)) }) .to_predicate(tcx), _ => bug!(\"unexepected projection predicate kind: `{:?}`\", predicate), }; let concrete_ty_predicate = predicate.subst(tcx, rebased_substs); debug!(\"compare_projection_bounds: concrete predicate = {:?}\", concrete_ty_predicate); let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize( &mut selcx, param_env, normalize_param_env, normalize_cause.clone(), &concrete_ty_predicate, ); debug!(\"compare_projection_bounds: normalized predicate = {:?}\", normalized_predicate); inh.register_predicates(obligations);"} {"_id":"doc-en-rust-76436d5f2c4b12772466f553af93009476c1d1ca142d83491a61d91c269a79af","title":"","text":" // Test that associated type bounds are correctly normalized when checking // default associated type values. // check-pass #![allow(incomplete_features)] #![feature(specialization)] #[derive(PartialEq)] enum Never {} trait Foo { type Assoc: PartialEq; // PartialEq<::Assoc> } impl Foo for T { default type Assoc = Never; } trait Trait1 { type Selection: PartialEq; } trait Trait2: PartialEq {} impl Trait1 for T { default type Selection = T; } fn main() {} "} {"_id":"doc-en-rust-6051ca0bf09579a4a847419208a88f158809d6694eb693c16f9c5deda0e51ab6","title":"","text":"/// N.B., **No cleanup is scheduled for this temporary.** You should /// call `schedule_drop` once the temporary is initialized. crate fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Place<'tcx> { let temp = self.local_decls.push(LocalDecl::new(ty, span)); // Mark this local as internal to avoid temporaries with types not present in the // user's code resulting in ICEs from the generator transform. let temp = self.local_decls.push(LocalDecl::new(ty, span).internal()); let place = Place::from(temp); debug!(\"temp: created temp {:?} with type {:?}\", place, self.local_decls[temp].ty); place"} {"_id":"doc-en-rust-e3db5107d4a1419c4f36116fa46a22a70596f770bf5459b3bc6856224a7e821f","title":"","text":" // build-pass // compile-flags:-Copt-level=0 // edition:2018 struct S(std::marker::PhantomData); impl std::ops::Deref for S { type Target = T; fn deref(&self) -> &Self::Target { todo!() } } impl std::ops::DerefMut for S { fn deref_mut(&mut self) -> &mut Self::Target { todo!() } } async fn new() -> S { todo!() } async fn crash() { *new().await = 1 + 1; } fn main() { let _ = crash(); } "} {"_id":"doc-en-rust-a371e1677943206d4752644688cfce898f5d0fe77d8488d6884dba70e12cf2b4","title":"","text":"pre.rust .comment, pre.rust .doccomment { color: #788797; font-style: italic; } nav:not(.sidebar) {"} {"_id":"doc-en-rust-02bbe9591f12b846ec538853187b2f9b24ef8e81eb266d91bf7f0e8e554dd144","title":"","text":" #![feature(associated_type_defaults)] #![feature(generic_associated_types)] #![allow(incomplete_features)] trait Trait1 { fn foo(); } trait Trait2 { type Associated: Trait1 = Self; //~^ ERROR: the trait bound `Self: Trait1` is not satisfied //~| the size for values of type `Self` cannot be known } impl Trait2 for () {} fn call_foo() { T::Associated::foo() } fn main() { call_foo::<()>() } "} {"_id":"doc-en-rust-dcffd7ee31b2377355da69862b75ee19879f405b820bb763d827f6d85f08baed","title":"","text":" error[E0277]: the trait bound `Self: Trait1` is not satisfied --> $DIR/issue-74816.rs:10:5 | LL | type Associated: Trait1 = Self; | ^^^^^^^^^^^^^^^^^------^^^^^^^^ | | | | | required by this bound in `Trait2::Associated` | the trait `Trait1` is not implemented for `Self` | help: consider further restricting `Self` | LL | trait Trait2: Trait1 { | ^^^^^^^^ error[E0277]: the size for values of type `Self` cannot be known at compilation time --> $DIR/issue-74816.rs:10:5 | LL | type Associated: Trait1 = Self; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | doesn't have a size known at compile-time | required by this bound in `Trait2::Associated` | help: consider further restricting `Self` | LL | trait Trait2: Sized { | ^^^^^^^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-51db54b405faf053621c2412b77733231a17b3bf920324033178191a0b4724f4","title":"","text":" #![feature(type_alias_impl_trait)] #![feature(impl_trait_in_bindings)] #![allow(incomplete_features)] type FooArg<'a> = &'a dyn ToString; type FooRet = impl std::fmt::Debug; type FooItem = Box FooRet>; type Foo = impl Iterator; //~ ERROR: type mismatch #[repr(C)] struct Bar(u8); impl Iterator for Bar { type Item = FooItem; fn next(&mut self) -> Option { Some(Box::new(quux)) } } fn quux(st: FooArg) -> FooRet { Some(st.to_string()) } fn ham() -> Foo { Bar(1) } fn oof() -> impl std::fmt::Debug { let mut bar = ham(); let func = bar.next().unwrap(); return func(&\"oof\"); } fn main() { let _ = oof(); } "} {"_id":"doc-en-rust-2e4c514e9ddbbdfdd9136d69d4568f8a129894f49b9e88d861b568c521696554","title":"","text":" error[E0271]: type mismatch resolving `::Item == Box<(dyn for<'r> Fn(&'r (dyn ToString + 'r)) -> Option + 'static)>` --> $DIR/issue-70877.rs:9:12 | LL | type FooRet = impl std::fmt::Debug; | -------------------- the expected opaque type ... LL | type Foo = impl Iterator; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected opaque type, found enum `Option` | = note: expected struct `Box<(dyn for<'r> Fn(&'r (dyn ToString + 'r)) -> impl Debug + 'static)>` found struct `Box<(dyn for<'r> Fn(&'r (dyn ToString + 'r)) -> Option + 'static)>` error: aborting due to previous error For more information about this error, try `rustc --explain E0271`. "} {"_id":"doc-en-rust-280845f7d823135acb02729e607b825bbee8a51aa981c44d218c5f718711c2a3","title":"","text":" // check-pass // Regression test of #70944, should compile fine. use std::ops::Index; pub struct KeyA; pub struct KeyB; pub struct KeyC; pub trait Foo: Index + Index + Index {} pub trait FooBuilder { type Inner: Foo; fn inner(&self) -> &Self::Inner; } pub fn do_stuff(foo: &impl FooBuilder) { let inner = foo.inner(); &inner[KeyA]; &inner[KeyB]; &inner[KeyC]; } fn main() {} "} {"_id":"doc-en-rust-527155b488a4b05b4cd41e0b121b11773a5daafc44b0d5ff356680aa23723715","title":"","text":" // check-pass #![feature(trait_alias)] struct Bar; trait Foo {} impl Foo for Bar {} trait Baz = Foo where Bar: Foo; fn new() -> impl Baz { Bar } fn main() { let _ = new(); } "} {"_id":"doc-en-rust-6fe7847153421209e9ec9f2ff478554b4f4ddcf1c97ea1dab03f2ac5de590fd7","title":"","text":" #![feature(unsize)] use std::marker::Unsize; pub trait CastTo: Unsize { fn cast_to(&self) -> &T; } impl> CastTo for U { fn cast_to(&self) -> &T { self } } impl Cast for T {} pub trait Cast { fn cast(&self) -> &T where Self: CastTo, { self } } pub trait Foo: CastTo<[i32]> {} impl Foo for [i32; 0] {} fn main() { let x: &dyn Foo = &[]; let x = x.cast::<[i32]>(); //~^ ERROR: the trait bound `dyn Foo: CastTo<[i32]>` is not satisfied } "} {"_id":"doc-en-rust-fa6f56d63951f4ce170e817741a7e9d7e778ed441255012f2ad3d10f14b6f33e","title":"","text":" error[E0277]: the trait bound `dyn Foo: CastTo<[i32]>` is not satisfied --> $DIR/issue-71659.rs:30:15 | LL | let x = x.cast::<[i32]>(); | ^^^^ the trait `CastTo<[i32]>` is not implemented for `dyn Foo` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-76eb2efceb013335ddd4c40cda877ac4d003783df5910d7ddd8f2bc24db9c22b","title":"","text":" pub trait Callback { fn cb(); } pub trait Processing { type Call: Callback; } fn f() { P::Call::cb(); } fn main() { struct MyCall; f::>(); //~^ ERROR: the trait bound `MyCall: Callback` is not satisfied } "} {"_id":"doc-en-rust-19c4872f2a82525bba34a91a72c61700fd6f2af4f9edcfba7cd2eb9ec8d271a0","title":"","text":" error[E0277]: the trait bound `MyCall: Callback` is not satisfied --> $DIR/issue-75707.rs:15:5 | LL | fn f() { | ---------- required by this bound in `f` ... LL | f::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Callback` is not implemented for `MyCall` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-b5013b2d44e261e6fb467d59f69f82f7a4392d003316021c7794e9b0cca4b790","title":"","text":"use crate::infer::error_reporting::nice_region_error::NiceRegionError; use crate::infer::lexical_region_resolve::RegionResolutionError; use crate::infer::{Subtype, TyCtxtInferExt, ValuePairs}; use crate::infer::{Subtype, ValuePairs}; use crate::traits::ObligationCauseCode::CompareImplMethodObligation; use rustc_errors::ErrorReported; use rustc_hir as hir;"} {"_id":"doc-en-rust-d02651b657102be49e0c37f4ced4ab0639536361f3f4f60664589e5a8cfca7af","title":"","text":"} fn emit_err(&self, sp: Span, expected: Ty<'tcx>, found: Ty<'tcx>, trait_def_id: DefId) { let tcx = self.tcx(); let trait_sp = self.tcx().def_span(trait_def_id); let mut err = self .tcx()"} {"_id":"doc-en-rust-9bbfc9111048b44c091e1d627ffcbac77422ba721b3823b1133e27f79026de5a","title":"","text":"); } if let Some((expected, found)) = tcx .infer_ctxt() .enter(|infcx| infcx.expected_found_str_ty(&ExpectedFound { expected, found })) if let Some((expected, found)) = self.infcx.expected_found_str_ty(&ExpectedFound { expected, found }) { // Highlighted the differences when showing the \"expected/found\" note. err.note_expected_found(&\"\", expected, &\"\", found);"} {"_id":"doc-en-rust-74c1e19aeca7a713830f92a4353441ddc1ab749e842233c6869779336dfad4d4","title":"","text":" // Regression test for issue #74918 // Tests that we don't ICE after emitting an error struct ChunkingIterator> { source: S, } impl> Iterator for ChunkingIterator { type Item = IteratorChunk; //~ ERROR missing lifetime fn next(&mut self) -> Option> { //~ ERROR `impl` todo!() } } struct IteratorChunk<'a, T, S: Iterator> { source: &'a mut S, } impl> Iterator for IteratorChunk<'_, T, S> { type Item = T; fn next(&mut self) -> Option { todo!() } } fn main() {} "} {"_id":"doc-en-rust-be217537e051dcf8ce269957ddeeba5afd9f9fa53a3b76a599c741a8c4daac94","title":"","text":" error[E0106]: missing lifetime specifier --> $DIR/issue-74918-missing-lifetime.rs:9:31 | LL | type Item = IteratorChunk; | ^ expected named lifetime parameter | help: consider introducing a named lifetime parameter | LL | type Item<'a> = IteratorChunk<<'a>T, S>; | ^^^^ ^^^^ error: `impl` item signature doesn't match `trait` item signature --> $DIR/issue-74918-missing-lifetime.rs:11:5 | LL | fn next(&mut self) -> Option> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&mut ChunkingIterator) -> std::option::Option>` | ::: $SRC_DIR/core/src/iter/traits/iterator.rs:LL:COL | LL | fn next(&mut self) -> Option; | ----------------------------------------- expected `fn(&mut ChunkingIterator) -> std::option::Option>` | = note: expected `fn(&mut ChunkingIterator) -> std::option::Option>` found `fn(&mut ChunkingIterator) -> std::option::Option>` = help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait` = help: verify the lifetime relationships in the `trait` and `impl` between the `self` argument, the other inputs and its output error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0106`. "} {"_id":"doc-en-rust-197a6ba76e12e3458dc7e0f10e763287c4505bba6969e6e99cd91e2c2f5b87f7","title":"","text":" // Regresison test for issue #75361 // Tests that we don't ICE on mismatched types with inference variables trait MyTrait { type Item; } pub trait Graph { type EdgeType; fn adjacent_edges(&self) -> Box>; } impl Graph for T { type EdgeType = T; fn adjacent_edges(&self) -> Box + '_> { //~ ERROR `impl` panic!() } } fn main() {} "} {"_id":"doc-en-rust-8e23f61fbaf5b1ecaea92c09fa4eccc9d66bca4396c365eb9cec21d8e22287d7","title":"","text":" error: `impl` item signature doesn't match `trait` item signature --> $DIR/issue-75361-mismatched-impl.rs:18:3 | LL | fn adjacent_edges(&self) -> Box>; | --------------------------------------------------------------------- expected `fn(&T) -> std::boxed::Box<(dyn MyTrait + 'static)>` ... LL | fn adjacent_edges(&self) -> Box + '_> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ found `fn(&T) -> std::boxed::Box>` | = note: expected `fn(&T) -> std::boxed::Box<(dyn MyTrait + 'static)>` found `fn(&T) -> std::boxed::Box>` help: the lifetime requirements from the `impl` do not correspond to the requirements in the `trait` --> $DIR/issue-75361-mismatched-impl.rs:12:55 | LL | fn adjacent_edges(&self) -> Box>; | ^^^^^^^^^^^^^^ consider borrowing this type parameter in the trait error: aborting due to previous error "} {"_id":"doc-en-rust-79da82ad59de32496951245ae20c23c53a4a2daf76444f3baed809232fc465d5","title":"","text":"use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::util; use rustc_session::config::EntryFnType; use rustc_span::{Span, DUMMY_SP}; use rustc_span::{symbol::sym, Span, DUMMY_SP}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _; use rustc_trait_selection::traits::{"} {"_id":"doc-en-rust-2fd1b7b6c1fe49e0ab89f003b2f7fd421187ba5999f530353cdada035fa4b009","title":"","text":".emit(); error = true; } for attr in it.attrs { if attr.check_name(sym::track_caller) { tcx.sess .struct_span_err( attr.span, \"`main` function is not allowed to be `#[track_caller]`\", ) .span_label( main_span, \"`main` function is not allowed to be `#[track_caller]`\", ) .emit(); error = true; } } if error { return; }"} {"_id":"doc-en-rust-1a91ec3c5acaa8173d27ce252b9d151561355518027ee113cf60904fec761d25","title":"","text":"tcx.sess, span, E0752, \"start is not allowed to be `async`\" \"`start` is not allowed to be `async`\" ) .span_label(span, \"start is not allowed to be `async`\") .span_label(span, \"`start` is not allowed to be `async`\") .emit(); error = true; } for attr in it.attrs { if attr.check_name(sym::track_caller) { tcx.sess .struct_span_err( attr.span, \"`start` is not allowed to be `#[track_caller]`\", ) .span_label( start_span, \"`start` is not allowed to be `#[track_caller]`\", ) .emit(); error = true; } } if error { return; }"} {"_id":"doc-en-rust-86798fd3fc291339ceabf4eb246e347a7c032b588c2fa28ebcc32713af5cdee8","title":"","text":"#[start] pub async fn start(_: isize, _: *const *const u8) -> isize { //~^ ERROR start is not allowed to be `async` //~^ ERROR `start` is not allowed to be `async` 0 }"} {"_id":"doc-en-rust-e500aa2011cbb870c821e7793fa94ed48c832e24e1fa1c507710538d99094366","title":"","text":" error[E0752]: start is not allowed to be `async` error[E0752]: `start` is not allowed to be `async` --> $DIR/issue-68523-start.rs:6:1 | LL | pub async fn start(_: isize, _: *const *const u8) -> isize { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ start is not allowed to be `async` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `start` is not allowed to be `async` error: aborting due to previous error"} {"_id":"doc-en-rust-c661d55d0a6098313241adfcd393a5c10ce079fde7a2a4a0ed12876980652fd3","title":"","text":" #[track_caller] //~ ERROR `main` function is not allowed to be fn main() { panic!(\"{}: oh no\", std::panic::Location::caller()); } "} {"_id":"doc-en-rust-6544fc8f5a347b1aaec314960faf1d52da3fcb5bde8205ebf772471a668b02c1","title":"","text":" error: `main` function is not allowed to be `#[track_caller]` --> $DIR/error-with-main.rs:1:1 | LL | #[track_caller] | ^^^^^^^^^^^^^^^ LL | / fn main() { LL | | panic!(\"{}: oh no\", std::panic::Location::caller()); LL | | } | |_- `main` function is not allowed to be `#[track_caller]` error: aborting due to previous error "} {"_id":"doc-en-rust-55b2eb20e3197d4e1f5a55d23419b56a909769fead1b726229d6e6176f8a36c7","title":"","text":" #![feature(start)] #[start] #[track_caller] //~ ERROR `start` is not allowed to be `#[track_caller]` fn start(_argc: isize, _argv: *const *const u8) -> isize { panic!(\"{}: oh no\", std::panic::Location::caller()); } "} {"_id":"doc-en-rust-6afe90333170db6ee178b6cd303dce82e25eaeb4c2b93709aab068ca6d985f46","title":"","text":" error: `start` is not allowed to be `#[track_caller]` --> $DIR/error-with-start.rs:4:1 | LL | #[track_caller] | ^^^^^^^^^^^^^^^ LL | / fn start(_argc: isize, _argv: *const *const u8) -> isize { LL | | panic!(\"{}: oh no\", std::panic::Location::caller()); LL | | } | |_- `start` is not allowed to be `#[track_caller]` error: aborting due to previous error "} {"_id":"doc-en-rust-67e697a86fada8e6aeeb13d6d3222db0a3357e4d94a54d1bcd731eb4669e4360","title":"","text":"return Ok(expr); } } if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual) && self.token.kind == token::Eq && self.prev_token.span.hi() == self.token.span.lo() { // Look for JS' `===` and `!==` and recover 😇 let sp = op.span.to(self.token.span); let sugg = match op.node { AssocOp::Equal => \"==\", AssocOp::NotEqual => \"!=\", _ => unreachable!(), }; self.struct_span_err(sp, &format!(\"invalid comparison operator `{}=`\", sugg)) .span_suggestion_short( sp, &format!(\"`{s}=` is not a valid comparison operator, use `{s}`\", s = sugg), sugg.to_string(), Applicability::MachineApplicable, ) .emit(); self.bump(); } let op = op.node; // Special cases: if op == AssocOp::As {"} {"_id":"doc-en-rust-a1bd55206ad4440c18554ea72d9e14e19083608331024f3c3b72368a37a24ce5","title":"","text":" fn main() { if 1 == = 1 { //~ ERROR expected expression println!(\"yup!\"); } } "} {"_id":"doc-en-rust-716bdadbf96dccf5918a720895529865bfda8c1209db71682a5a65489d602020","title":"","text":" error: expected expression, found `=` --> $DIR/js-style-comparison-op-separate-eq-token.rs:2:13 | LL | if 1 == = 1 { | ^ expected expression error: aborting due to previous error "} {"_id":"doc-en-rust-ddb1b38231b5c22c1a2df84856105af95052c959bf8a68712c48e8b06cfefeaa","title":"","text":" // run-rustfix fn main() { if 1 == 1 { //~ ERROR invalid comparison operator `===` println!(\"yup!\"); } else if 1 != 1 { //~ ERROR invalid comparison operator `!==` println!(\"nope!\"); } } "} {"_id":"doc-en-rust-f97cb859e7fb3df9ba79b31f8a7024cee8e1bca4e6b26d17006d9ce2958c02e2","title":"","text":" // run-rustfix fn main() { if 1 === 1 { //~ ERROR invalid comparison operator `===` println!(\"yup!\"); } else if 1 !== 1 { //~ ERROR invalid comparison operator `!==` println!(\"nope!\"); } } "} {"_id":"doc-en-rust-ef35af5db04d7d2b741f54b4b1da56b6bebe16682227020ef64d1a616d041ae4","title":"","text":" error: invalid comparison operator `===` --> $DIR/js-style-comparison-op.rs:3:10 | LL | if 1 === 1 { | ^^^ help: `===` is not a valid comparison operator, use `==` error: invalid comparison operator `!==` --> $DIR/js-style-comparison-op.rs:5:17 | LL | } else if 1 !== 1 { | ^^^ help: `!==` is not a valid comparison operator, use `!=` error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-e8dd60ef3aec8f0570452419271f4638eb192c42bd1c1bf46d0c75a85696fd53","title":"","text":"self.variants.iter().flat_map(|v| v.fields.iter()) } /// Whether the ADT lacks fields. Note that this includes uninhabited enums, /// e.g., `enum Void {}` is considered payload free as well. pub fn is_payloadfree(&self) -> bool { !self.variants.is_empty() && self.variants.iter().all(|v| v.fields.is_empty()) self.variants.iter().all(|v| v.fields.is_empty()) } /// Return a `VariantDef` given a variant id."} {"_id":"doc-en-rust-424e850a3c17831271b4c47d935b1cb3c951d8e881873d87cbd1f8b1193e0143","title":"","text":"// # First handle non-scalar source values. // Handle cast from a univariant (ZST) enum. // Handle cast from a ZST enum (0 or 1 variants). match src.layout.variants { Variants::Single { index } => { if src.layout.abi.is_uninhabited() { // This is dead code, because an uninhabited enum is UB to // instantiate. throw_ub!(Unreachable); } if let Some(discr) = src.layout.ty.discriminant_for_variant(*self.tcx, index) { assert!(src.layout.is_zst()); let discr_layout = self.layout_of(discr.ty)?;"} {"_id":"doc-en-rust-5e377564fd322db53863aa1264901e369ad409b700f94833bb1897fa5aec87fa","title":"","text":" // check-pass enum E {} fn f(e: E) { println!(\"{}\", (e as isize).to_string()); //~ ERROR non-primitive cast println!(\"{}\", (e as isize).to_string()); } fn main() {}"} {"_id":"doc-en-rust-fd3bc43fe06696fdcd66ed534a66bcc6a86abfabb307782174df5980293953d7","title":"","text":" error[E0605]: non-primitive cast: `E` as `isize` --> $DIR/uninhabited-enum-cast.rs:4:20 | LL | println!(\"{}\", (e as isize).to_string()); | ^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object error: aborting due to previous error For more information about this error, try `rustc --explain E0605`. "} {"_id":"doc-en-rust-6422cc607467ddcbf22655308430c901b501ff61b5cf78a2f3a1da3f0080403b","title":"","text":"} #theme-choices > button:hover, #theme-choices > button:focus { background-color: rgba(70, 70, 70, 0.33); background-color: rgba(110, 110, 110, 0.33); } @media (max-width: 700px) {"} {"_id":"doc-en-rust-e66e34947c690f1816e1759f00781f7e942be395cdd892aa34a246417af4cd5f","title":"","text":"use tracing::debug; macro_rules! gate_feature_fn { ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $help: expr) => {{ let (visitor, has_feature, span, name, explain, help) = (&*$visitor, $has_feature, $span, $name, $explain, $help); let has_feature: bool = has_feature(visitor.features); debug!(\"gate_feature(feature = {:?}, span = {:?}); has? {}\", name, span, has_feature); if !has_feature && !span.allows_unstable($name) { feature_err_issue(&visitor.sess.parse_sess, name, span, GateIssue::Language, explain) .help(help) .emit(); } }}; ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{ let (visitor, has_feature, span, name, explain) = (&*$visitor, $has_feature, $span, $name, $explain);"} {"_id":"doc-en-rust-89c72c962c101f6cdaf155469efd34d340aae9ccc21986fde334f0622aa99d23","title":"","text":"} macro_rules! gate_feature_post { ($visitor: expr, $feature: ident, $span: expr, $explain: expr, $help: expr) => { gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain, $help) }; ($visitor: expr, $feature: ident, $span: expr, $explain: expr) => { gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain) };"} {"_id":"doc-en-rust-a86e7b576f25cc684d64a1b854d673dc4c6e4904e685a1a4553520b64b10e50d","title":"","text":"let spans = sess.parse_sess.gated_spans.spans.borrow(); macro_rules! gate_all { ($gate:ident, $msg:literal, $help:literal) => { if let Some(spans) = spans.get(&sym::$gate) { for span in spans { gate_feature_post!(&visitor, $gate, *span, $msg, $help); } } }; ($gate:ident, $msg:literal) => { if let Some(spans) = spans.get(&sym::$gate) { for span in spans {"} {"_id":"doc-en-rust-bc7a7eff5993cedc191eb1909fe20e90a5e9e0c1df020e70aac9e3610f92454a","title":"","text":"} gate_all!(if_let_guard, \"`if let` guard is not implemented\"); gate_all!(let_chains, \"`let` expressions in this position are experimental\"); gate_all!(async_closure, \"async closures are unstable\"); gate_all!( async_closure, \"async closures are unstable\", \"to use an async block, remove the `||`: `async {`\" ); gate_all!(generators, \"yield syntax is experimental\"); gate_all!(or_patterns, \"or-patterns syntax is experimental\"); gate_all!(raw_ref_op, \"raw address of syntax is experimental\");"} {"_id":"doc-en-rust-5c91bb8df753f9f0be1dca7f94dcaa6af157f484c1b87237502d063c1ca21d5d","title":"","text":"} else { Async::No }; if let Async::Yes { span, .. } = asyncness { // Feature-gate `async ||` closures. self.sess.gated_spans.gate(sym::async_closure, span); } let capture_clause = self.parse_capture_clause(); let decl = self.parse_fn_block_decl()?;"} {"_id":"doc-en-rust-bd16a5170ebad0afd9e9ece87797a6456507a5774d265df35f1777129c79a351","title":"","text":"} }; if let Async::Yes { span, .. } = asyncness { // Feature-gate `async ||` closures. self.sess.gated_spans.gate(sym::async_closure, span); } Ok(self.mk_expr( lo.to(body.span), ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),"} {"_id":"doc-en-rust-74711e0fccde38f0e75185605b55c6a248614c5129d71fb24b7867527b4e1115","title":"","text":"| = note: see issue #62290 for more information = help: add `#![feature(async_closure)]` to the crate attributes to enable = help: to use an async block, remove the `||`: `async {` error: aborting due to previous error"} {"_id":"doc-en-rust-8cb151b70ff591762db749ac674feee8ba25f8e57999d8ccfc16d39b5f3f35bd","title":"","text":"} fn f5() { async //~ ERROR async closures are unstable async let x = 0; //~ ERROR expected one of `move`, `|`, or `||`, found keyword `let` }"} {"_id":"doc-en-rust-040ce946f5a5a98f22f9cba65c2e240dc7bfc98e99e22b2650a05b0cc6260137","title":"","text":"LL | let x = 0; | ^^^ unexpected token error[E0658]: async closures are unstable --> $DIR/block-no-opening-brace.rs:29:5 | LL | async | ^^^^^ | = note: see issue #62290 for more information = help: add `#![feature(async_closure)]` to the crate attributes to enable error: aborting due to 6 previous errors error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0658`. "} {"_id":"doc-en-rust-8cae7ec397a9897f612a7bb5585312ee8e42dc3f675677338c3d82a23fe84f3c","title":"","text":"trace!(\"encoding {} further alloc ids\", new_n - n); for idx in n..new_n { let id = self.interpret_allocs[idx]; let pos = self.position() as u32; let pos = self.position() as u64; interpret_alloc_index.push(pos); interpret::specialized_encode_alloc_id(self, tcx, id); }"} {"_id":"doc-en-rust-7053d79ee0dfa9daaf8cb90263c3406a92ca9d43572d078c67ad7c9521429d53","title":"","text":"traits: LazyArray, impls: LazyArray, incoherent_impls: LazyArray, interpret_alloc_index: LazyArray, interpret_alloc_index: LazyArray, proc_macro_data: Option, tables: LazyTables,"} {"_id":"doc-en-rust-5e2610d44e35956a10a415e72aadb5950aba8294b0979a5c8fbccec1fbe05b1d","title":"","text":"// For each `AllocId`, we keep track of which decoding state it's currently in. decoding_state: Vec>, // The offsets of each allocation in the data stream. data_offsets: Vec, data_offsets: Vec, } impl AllocDecodingState {"} {"_id":"doc-en-rust-d871e3c762aae4b00cc9351cb57c6d508dc0fffab6eb0779ec736b361571a83f","title":"","text":"AllocDecodingSession { state: self, session_id } } pub fn new(data_offsets: Vec) -> Self { pub fn new(data_offsets: Vec) -> Self { let decoding_state = std::iter::repeat_with(|| Lock::new(State::Empty)).take(data_offsets.len()).collect();"} {"_id":"doc-en-rust-59ba2b80e03daf3cb54c2fddf7ccf3d6e4a56629b492fda655723d9f2fd04ca8","title":"","text":"query_result_index: EncodedDepNodeIndex, side_effects_index: EncodedDepNodeIndex, // The location of all allocations. interpret_alloc_index: Vec, // Most uses only need values up to u32::MAX, but benchmarking indicates that we can use a u64 // without measurable overhead. This permits larger const allocations without ICEing. interpret_alloc_index: Vec, // See `OnDiskCache.syntax_contexts` syntax_contexts: FxHashMap, // See `OnDiskCache.expn_data`"} {"_id":"doc-en-rust-25a541c82b2a49b0aa3a5ff9a3a7b038acca39f391819b0c01a3f74ae8cc834e","title":"","text":"interpret_alloc_index.reserve(new_n - n); for idx in n..new_n { let id = encoder.interpret_allocs[idx]; let pos: u32 = encoder.position().try_into().unwrap(); let pos: u64 = encoder.position().try_into().unwrap(); interpret_alloc_index.push(pos); interpret::specialized_encode_alloc_id(&mut encoder, tcx, id); }"} {"_id":"doc-en-rust-d845156a48e82cb531ffdd3aa843918ea5d37aaf039d17474327992219e29d2b","title":"","text":"usize, (), u32, u64, bool, std::string::String, crate::metadata::ModChild,"} {"_id":"doc-en-rust-d9484079c9878a95a709cc37d54b816004ab4f8a6bf134bdbd60f72fef070699","title":"","text":"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. "} {"_id":"doc-en-rust-6d4bc88ec270741134d55855eb97986a14ed44dcf33b46893bf8b112937ec55f","title":"","text":"{\"message\":\"mismatched types\",\"code\":{\"code\":\"E0308\",\"explanation\":\"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. \"},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":621,\"byte_end\":622,\"line_start\":17,\"line_end\":17,\"column_start\":22,\"column_end\":23,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = 1; // Error in the middle of line.\",\"highlight_start\":22,\"highlight_end\":23}],\"label\":\"expected struct `String`, found integer\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null},{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":612,\"byte_end\":618,\"line_start\":17,\"line_end\":17,\"column_start\":13,\"column_end\":19,\"is_primary\":false,\"text\":[{\"text\":\" let s : String = 1; // Error in the middle of line.\",\"highlight_start\":13,\"highlight_end\":19}],\"label\":\"expected due to this\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[{\"message\":\"try using a conversion method\",\"code\":null,\"level\":\"help\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":621,\"byte_end\":622,\"line_start\":17,\"line_end\":17,\"column_start\":22,\"column_end\":23,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = 1; // Error in the middle of line.\",\"highlight_start\":22,\"highlight_end\":23}],\"label\":null,\"suggested_replacement\":\"1.to_string()\",\"suggestion_applicability\":\"MaybeIncorrect\",\"expansion\":null}],\"children\":[],\"rendered\":null}],\"rendered\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs:17:22: error[E0308]: mismatched types \"} {\"message\":\"mismatched types\",\"code\":{\"code\":\"E0308\",\"explanation\":\"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. \"},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":681,\"byte_end\":682,\"line_start\":19,\"line_end\":19,\"column_start\":22,\"column_end\":23,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = 1\",\"highlight_start\":22,\"highlight_end\":23}],\"label\":\"expected struct `String`, found integer\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null},{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":672,\"byte_end\":678,\"line_start\":19,\"line_end\":19,\"column_start\":13,\"column_end\":19,\"is_primary\":false,\"text\":[{\"text\":\" let s : String = 1\",\"highlight_start\":13,\"highlight_end\":19}],\"label\":\"expected due to this\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[{\"message\":\"try using a conversion method\",\"code\":null,\"level\":\"help\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":681,\"byte_end\":682,\"line_start\":19,\"line_end\":19,\"column_start\":22,\"column_end\":23,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = 1\",\"highlight_start\":22,\"highlight_end\":23}],\"label\":null,\"suggested_replacement\":\"1.to_string()\",\"suggestion_applicability\":\"MaybeIncorrect\",\"expansion\":null}],\"children\":[],\"rendered\":null}],\"rendered\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs:19:22: error[E0308]: mismatched types \"} {\"message\":\"mismatched types\",\"code\":{\"code\":\"E0308\",\"explanation\":\"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. \"},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":745,\"byte_end\":746,\"line_start\":23,\"line_end\":23,\"column_start\":1,\"column_end\":2,\"is_primary\":true,\"text\":[{\"text\":\"1; // Error after the newline.\",\"highlight_start\":1,\"highlight_end\":2}],\"label\":\"expected struct `String`, found integer\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null},{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":735,\"byte_end\":741,\"line_start\":22,\"line_end\":22,\"column_start\":13,\"column_end\":19,\"is_primary\":false,\"text\":[{\"text\":\" let s : String =\",\"highlight_start\":13,\"highlight_end\":19}],\"label\":\"expected due to this\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[{\"message\":\"try using a conversion method\",\"code\":null,\"level\":\"help\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":745,\"byte_end\":746,\"line_start\":23,\"line_end\":23,\"column_start\":1,\"column_end\":2,\"is_primary\":true,\"text\":[{\"text\":\"1; // Error after the newline.\",\"highlight_start\":1,\"highlight_end\":2}],\"label\":null,\"suggested_replacement\":\"1.to_string()\",\"suggestion_applicability\":\"MaybeIncorrect\",\"expansion\":null}],\"children\":[],\"rendered\":null}],\"rendered\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs:23:1: error[E0308]: mismatched types \"} {\"message\":\"mismatched types\",\"code\":{\"code\":\"E0308\",\"explanation\":\"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. \"},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":801,\"byte_end\":809,\"line_start\":25,\"line_end\":26,\"column_start\":22,\"column_end\":6,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = (\",\"highlight_start\":22,\"highlight_end\":23},{\"text\":\" ); // Error spanning the newline.\",\"highlight_start\":1,\"highlight_end\":6}],\"label\":\"expected struct `String`, found `()`\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null},{\"file_name\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs\",\"byte_start\":792,\"byte_end\":798,\"line_start\":25,\"line_end\":25,\"column_start\":13,\"column_end\":19,\"is_primary\":false,\"text\":[{\"text\":\" let s : String = (\",\"highlight_start\":13,\"highlight_end\":19}],\"label\":\"expected due to this\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[],\"rendered\":\"$DIR/json-bom-plus-crlf-multifile-aux.rs:25:22: error[E0308]: mismatched types \"} {\"message\":\"aborting due to 4 previous errors\",\"code\":null,\"level\":\"error\",\"spans\":[],\"children\":[],\"rendered\":\"error: aborting due to 4 previous errors"} {"_id":"doc-en-rust-dd9b22862b5ca9a9c810f21d7052016725a01902dad61d65ece584e1106310b2","title":"","text":"{\"message\":\"mismatched types\",\"code\":{\"code\":\"E0308\",\"explanation\":\"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. \"},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":606,\"byte_end\":607,\"line_start\":16,\"line_end\":16,\"column_start\":22,\"column_end\":23,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = 1; // Error in the middle of line.\",\"highlight_start\":22,\"highlight_end\":23}],\"label\":\"expected struct `String`, found integer\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null},{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":597,\"byte_end\":603,\"line_start\":16,\"line_end\":16,\"column_start\":13,\"column_end\":19,\"is_primary\":false,\"text\":[{\"text\":\" let s : String = 1; // Error in the middle of line.\",\"highlight_start\":13,\"highlight_end\":19}],\"label\":\"expected due to this\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[{\"message\":\"try using a conversion method\",\"code\":null,\"level\":\"help\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":606,\"byte_end\":607,\"line_start\":16,\"line_end\":16,\"column_start\":22,\"column_end\":23,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = 1; // Error in the middle of line.\",\"highlight_start\":22,\"highlight_end\":23}],\"label\":null,\"suggested_replacement\":\"1.to_string()\",\"suggestion_applicability\":\"MaybeIncorrect\",\"expansion\":null}],\"children\":[],\"rendered\":null}],\"rendered\":\"$DIR/json-bom-plus-crlf.rs:16:22: error[E0308]: mismatched types \"} {\"message\":\"mismatched types\",\"code\":{\"code\":\"E0308\",\"explanation\":\"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. \"},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":666,\"byte_end\":667,\"line_start\":18,\"line_end\":18,\"column_start\":22,\"column_end\":23,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = 1\",\"highlight_start\":22,\"highlight_end\":23}],\"label\":\"expected struct `String`, found integer\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null},{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":657,\"byte_end\":663,\"line_start\":18,\"line_end\":18,\"column_start\":13,\"column_end\":19,\"is_primary\":false,\"text\":[{\"text\":\" let s : String = 1\",\"highlight_start\":13,\"highlight_end\":19}],\"label\":\"expected due to this\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[{\"message\":\"try using a conversion method\",\"code\":null,\"level\":\"help\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":666,\"byte_end\":667,\"line_start\":18,\"line_end\":18,\"column_start\":22,\"column_end\":23,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = 1\",\"highlight_start\":22,\"highlight_end\":23}],\"label\":null,\"suggested_replacement\":\"1.to_string()\",\"suggestion_applicability\":\"MaybeIncorrect\",\"expansion\":null}],\"children\":[],\"rendered\":null}],\"rendered\":\"$DIR/json-bom-plus-crlf.rs:18:22: error[E0308]: mismatched types \"} {\"message\":\"mismatched types\",\"code\":{\"code\":\"E0308\",\"explanation\":\"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. \"},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":730,\"byte_end\":731,\"line_start\":22,\"line_end\":22,\"column_start\":1,\"column_end\":2,\"is_primary\":true,\"text\":[{\"text\":\"1; // Error after the newline.\",\"highlight_start\":1,\"highlight_end\":2}],\"label\":\"expected struct `String`, found integer\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null},{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":720,\"byte_end\":726,\"line_start\":21,\"line_end\":21,\"column_start\":13,\"column_end\":19,\"is_primary\":false,\"text\":[{\"text\":\" let s : String =\",\"highlight_start\":13,\"highlight_end\":19}],\"label\":\"expected due to this\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[{\"message\":\"try using a conversion method\",\"code\":null,\"level\":\"help\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":730,\"byte_end\":731,\"line_start\":22,\"line_end\":22,\"column_start\":1,\"column_end\":2,\"is_primary\":true,\"text\":[{\"text\":\"1; // Error after the newline.\",\"highlight_start\":1,\"highlight_end\":2}],\"label\":null,\"suggested_replacement\":\"1.to_string()\",\"suggestion_applicability\":\"MaybeIncorrect\",\"expansion\":null}],\"children\":[],\"rendered\":null}],\"rendered\":\"$DIR/json-bom-plus-crlf.rs:22:1: error[E0308]: mismatched types \"} {\"message\":\"mismatched types\",\"code\":{\"code\":\"E0308\",\"explanation\":\"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. \"},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":786,\"byte_end\":794,\"line_start\":24,\"line_end\":25,\"column_start\":22,\"column_end\":6,\"is_primary\":true,\"text\":[{\"text\":\" let s : String = (\",\"highlight_start\":22,\"highlight_end\":23},{\"text\":\" ); // Error spanning the newline.\",\"highlight_start\":1,\"highlight_end\":6}],\"label\":\"expected struct `String`, found `()`\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null},{\"file_name\":\"$DIR/json-bom-plus-crlf.rs\",\"byte_start\":777,\"byte_end\":783,\"line_start\":24,\"line_end\":24,\"column_start\":13,\"column_end\":19,\"is_primary\":false,\"text\":[{\"text\":\" let s : String = (\",\"highlight_start\":13,\"highlight_end\":19}],\"label\":\"expected due to this\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[],\"rendered\":\"$DIR/json-bom-plus-crlf.rs:24:22: error[E0308]: mismatched types \"} {\"message\":\"aborting due to 4 previous errors\",\"code\":null,\"level\":\"error\",\"spans\":[],\"children\":[],\"rendered\":\"error: aborting due to 4 previous errors"} {"_id":"doc-en-rust-f5c060d0f7493eda6162851673ed9af24fadf2d0c582cc7933bad99bc70a14f8","title":"","text":"{\"message\":\"mismatched types\",\"code\":{\"code\":\"E0308\",\"explanation\":\"Expected type did not match the received type. Erroneous code example: Erroneous code examples: ```compile_fail,E0308 let x: i32 = \"I am not a number!\"; // ~~~ ~~~~~~~~~~~~~~~~~~~~ // | | // | initializing expression; // | compiler infers type `&str` // | // type `i32` assigned to variable `x` fn plus_one(x: i32) -> i32 { x + 1 } plus_one(\"Not a number\"); // ^^^^^^^^^^^^^^ expected `i32`, found `&str` if \"Not a bool\" { // ^^^^^^^^^^^^ expected `bool`, found `&str` } let x: f32 = \"Not a float\"; // --- ^^^^^^^^^^^^^ expected `f32`, found `&str` // | // expected due to this ``` This error occurs when the compiler is unable to infer the concrete type of a variable. It can occur in several cases, the most common being a mismatch between two types: the type the author explicitly assigned, and the type the compiler inferred. This error occurs when an expression was used in a place where the compiler expected an expression of a different type. It can occur in several cases, the most common being when calling a function and passing an argument which has a different type than the matching type in the function declaration. \"},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/flag-json.rs\",\"byte_start\":244,\"byte_end\":246,\"line_start\":7,\"line_end\":7,\"column_start\":17,\"column_end\":19,\"is_primary\":true,\"text\":[{\"text\":\" let _: () = 42;\",\"highlight_start\":17,\"highlight_end\":19}],\"label\":\"expected `()`, found integer\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null},{\"file_name\":\"$DIR/flag-json.rs\",\"byte_start\":239,\"byte_end\":241,\"line_start\":7,\"line_end\":7,\"column_start\":12,\"column_end\":14,\"is_primary\":false,\"text\":[{\"text\":\" let _: () = 42;\",\"highlight_start\":12,\"highlight_end\":14}],\"label\":\"expected due to this\",\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[],\"rendered\":\"error[E0308]: mismatched types --> $DIR/flag-json.rs:7:17 |"} {"_id":"doc-en-rust-8e7fefe7ee3f0f415f456dfd0ed8f53750d8e6569a01ce205bc20a593ea8b6ae","title":"","text":"self.to_bits().to_ne_bytes() } /// Return the memory representation of this floating point number as a byte array in /// native byte order. /// /// [`to_ne_bytes`] should be preferred over this whenever possible. /// /// [`to_ne_bytes`]: f32::to_ne_bytes /// /// # Examples /// /// ``` /// #![feature(num_as_ne_bytes)] /// let num = 12.5f32; /// let bytes = num.as_ne_bytes(); /// assert_eq!( /// bytes, /// if cfg!(target_endian = \"big\") { /// &[0x41, 0x48, 0x00, 0x00] /// } else { /// &[0x00, 0x00, 0x48, 0x41] /// } /// ); /// ``` #[unstable(feature = \"num_as_ne_bytes\", issue = \"76976\")] #[inline] pub fn as_ne_bytes(&self) -> &[u8; 4] { // SAFETY: `f32` is a plain old datatype so we can always transmute to it unsafe { &*(self as *const Self as *const _) } } /// Create a floating point value from its representation as a byte array in big endian. /// /// # Examples"} {"_id":"doc-en-rust-b585c56a4ee803854188dd4d9063f40e985217254f0b6ef45f2c756b4ef36e34","title":"","text":"self.to_bits().to_ne_bytes() } /// Return the memory representation of this floating point number as a byte array in /// native byte order. /// /// [`to_ne_bytes`] should be preferred over this whenever possible. /// /// [`to_ne_bytes`]: f64::to_ne_bytes /// /// # Examples /// /// ``` /// #![feature(num_as_ne_bytes)] /// let num = 12.5f64; /// let bytes = num.as_ne_bytes(); /// assert_eq!( /// bytes, /// if cfg!(target_endian = \"big\") { /// &[0x40, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] /// } else { /// &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x40] /// } /// ); /// ``` #[unstable(feature = \"num_as_ne_bytes\", issue = \"76976\")] #[inline] pub fn as_ne_bytes(&self) -> &[u8; 8] { // SAFETY: `f64` is a plain old datatype so we can always transmute to it unsafe { &*(self as *const Self as *const _) } } /// Create a floating point value from its representation as a byte array in big endian. /// /// # Examples"} {"_id":"doc-en-rust-4212bb242e88ef215962916c97e2aa641d69f399cdd97c59a05b7604a20d0b33","title":"","text":"unsafe { mem::transmute(self) } } /// Return the memory representation of this integer as a byte array in /// native byte order. /// /// [`to_ne_bytes`] should be preferred over this whenever possible. /// /// [`to_ne_bytes`]: Self::to_ne_bytes /// /// # Examples /// /// ``` /// #![feature(num_as_ne_bytes)] #[doc = concat!(\"let num = \", $swap_op, stringify!($SelfT), \";\")] /// let bytes = num.as_ne_bytes(); /// assert_eq!( /// bytes, /// if cfg!(target_endian = \"big\") { #[doc = concat!(\" &\", $be_bytes)] /// } else { #[doc = concat!(\" &\", $le_bytes)] /// } /// ); /// ``` #[unstable(feature = \"num_as_ne_bytes\", issue = \"76976\")] #[inline] pub fn as_ne_bytes(&self) -> &[u8; mem::size_of::()] { // SAFETY: integers are plain old datatypes so we can always transmute them to // arrays of bytes unsafe { &*(self as *const Self as *const _) } } /// Create an integer value from its representation as a byte array in /// big endian. ///"} {"_id":"doc-en-rust-c4dc6bfaad5ae434f0f8a72656df9fabb45770b19ceb339d231817f2169d5bd7","title":"","text":"unsafe { mem::transmute(self) } } /// Return the memory representation of this integer as a byte array in /// native byte order. /// /// [`to_ne_bytes`] should be preferred over this whenever possible. /// /// [`to_ne_bytes`]: Self::to_ne_bytes /// /// # Examples /// /// ``` /// #![feature(num_as_ne_bytes)] #[doc = concat!(\"let num = \", $swap_op, stringify!($SelfT), \";\")] /// let bytes = num.as_ne_bytes(); /// assert_eq!( /// bytes, /// if cfg!(target_endian = \"big\") { #[doc = concat!(\" &\", $be_bytes)] /// } else { #[doc = concat!(\" &\", $le_bytes)] /// } /// ); /// ``` #[unstable(feature = \"num_as_ne_bytes\", issue = \"76976\")] #[inline] pub fn as_ne_bytes(&self) -> &[u8; mem::size_of::()] { // SAFETY: integers are plain old datatypes so we can always transmute them to // arrays of bytes unsafe { &*(self as *const Self as *const _) } } /// Create a native endian integer value from its representation /// as a byte array in big endian. ///"} {"_id":"doc-en-rust-146b5979c82b406d3a9e7a9292029fde21f7d9b34e3e0ca4e257aa0920977b7a","title":"","text":" Subproject commit 3c5d47c81d78e9316e971c9870e8bc7c2c449d24 Subproject commit 77a0125981b293260c9aec6355dff46ec707ab59 "} {"_id":"doc-en-rust-3dd9220d8e1a7a6dcc2189edaa5cc73fb4b4453bc189a06e63bc577f25a0e4dc","title":"","text":")); } } if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() { if cx.tcx.is_ty_uninhabited_from(cx.module, sub_ty, cx.param_env) { err.note(\"references are always considered inhabited\"); } } err.emit(); }"} {"_id":"doc-en-rust-b341efc936bf499974495e71c3d28c55f3c0298619145756cac76699312b4a3f","title":"","text":"| = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms = note: the matched value is of type `&!` = note: references are always considered inhabited error[E0004]: non-exhaustive patterns: type `Foo` is non-empty --> $DIR/always-inhabited-union-ref.rs:27:11"} {"_id":"doc-en-rust-f3f823ee2e77ff8ffff6285c20b5bb3b6f5ec2be2ad0acab44cd3e54306f2bce","title":"","text":" enum A {} //~^ NOTE `A` defined here fn f(a: &A) { match a {} //~^ ERROR non-exhaustive patterns: type `&A` is non-empty //~| NOTE the matched value is of type `&A` //~| NOTE references are always considered inhabited } fn main() {} "} {"_id":"doc-en-rust-bc21a69b791d35d2b65d415448580ba03186b927664b95aa933128254b7bf061","title":"","text":" error[E0004]: non-exhaustive patterns: type `&A` is non-empty --> $DIR/issue-78123-non-exhaustive-reference.rs:5:11 | LL | enum A {} | --------- `A` defined here ... LL | match a {} | ^ | = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms = note: the matched value is of type `&A` = note: references are always considered inhabited error: aborting due to previous error For more information about this error, try `rustc --explain E0004`. "} {"_id":"doc-en-rust-eb166ce5b5e9ddaaee536df3b25f8154683d9981d5ed47adab0450f616ec58f3","title":"","text":"| = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms = note: the matched value is of type `&Void` = note: references are always considered inhabited error[E0004]: non-exhaustive patterns: type `(Void,)` is non-empty --> $DIR/uninhabited-matches-feature-gated.rs:18:19"} {"_id":"doc-en-rust-dd39614408c162f51100ce0da7aef0e36768e82dc66ddc1ef117eae5a580e12a","title":"","text":"// The type table might not have information for this expression // if it is in a malformed scope. (#66387) if let Some(ty) = self.fcx.typeck_results.borrow().expr_ty_opt(expr) { if guard_borrowing_from_pattern { // Match guards create references to all the bindings in the pattern that are used // in the guard, e.g. `y if is_even(y) => ...` becomes `is_even(*r_y)` where `r_y` // is a reference to `y`, so we must record a reference to the type of the binding. let tcx = self.fcx.tcx; let ref_ty = tcx.mk_ref( // Use `ReErased` as `resolve_interior` is going to replace all the regions anyway. tcx.mk_region(ty::RegionKind::ReErased), ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }, ); self.record(ref_ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern); } self.record(ty, scope, Some(expr), expr.span, guard_borrowing_from_pattern); } else { self.fcx.tcx.sess.delay_span_bug(expr.span, \"no type for node\");"} {"_id":"doc-en-rust-1ebcdf765f4f7facefcb2d229b792a11f003e137ed9c953588733f3e310109d5","title":"","text":" // check-pass // build-pass // edition:2018 // This test is derived from"} {"_id":"doc-en-rust-d9e1e10ae6ee43a74aa9d690ddc512e84a9827572a818395139831da9c9c94d7","title":"","text":"// of the underlying generator. async fn f() -> u8 { 1 } async fn foo() -> [bool; 10] { [false; 10] } pub async fn g(x: u8) { match x {"} {"_id":"doc-en-rust-b789a8cd9684b9c387798821596b2a238f9f15fdb8b5b675b891f86663cf4a2c","title":"","text":"} } // #78366: check the reference to the binding is recorded even if the binding is not autorefed async fn h(x: usize) { match x { y if foo().await[y] => (), _ => (), } } async fn i(x: u8) { match x { y if f().await == y + 1 => (), _ => (), } } fn main() { let _ = g(10); let _ = h(9); let _ = i(8); }"} {"_id":"doc-en-rust-5eb1e4dbae50f319fa79dbcd343149e00fb36e98e772d835effb56769a18e9f2","title":"","text":".with_indent_lines(true) .with_ansi(true) .with_targets(true) .with_thread_ids(true) .with_thread_names(true) .with_wraparound(10) .with_verbose_exit(true) .with_verbose_entry(true) .with_indent_amount(2); #[cfg(parallel_compiler)] let layer = layer.with_thread_ids(true).with_thread_names(true); use tracing_subscriber::layer::SubscriberExt; let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);"} {"_id":"doc-en-rust-a425f54f5a85b4da8305ed47c87c9edb6b40f468225fea620b13fc021b6a2e1c","title":"","text":"Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, \"no_mangle\"); } // FIXME: #[no_mangle] was previously allowed on non-functions/statics, this should be an error // The error should specify that the item that is wrong is specifically a *foreign* fn/static // otherwise the error seems odd Target::ForeignFn | Target::ForeignStatic => { let foreign_item_kind = match target { Target::ForeignFn => \"function\", Target::ForeignStatic => \"static\", _ => unreachable!(), }; self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { lint.build(&format!( \"`#[no_mangle]` has no effect on a foreign {}\", foreign_item_kind )) .warn( \"this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!\", ) .span_label(*span, format!(\"foreign {}\", foreign_item_kind)) .note(\"symbol names in extern blocks are not mangled\") .span_suggestion( attr.span, \"remove this attribute\", String::new(), Applicability::MachineApplicable, ) .emit(); }); } _ => { // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some // crates used this, so only emit a warning."} {"_id":"doc-en-rust-2726cd00a0d8ca5a9e4298e1daef7f502300414efb0acbc2d4c36887f8a91c62","title":"","text":" #![warn(unused_attributes)] // Tests that placing the #[no_mangle] attribute on a foreign fn or static emits // a specialized warning. // The previous warning only talks about a \"function or static\" but foreign fns/statics // are also not allowed to have #[no_mangle] // build-pass extern \"C\" { #[no_mangle] //~^ WARNING `#[no_mangle]` has no effect on a foreign static //~^^ WARNING this was previously accepted by the compiler pub static FOO: u8; #[no_mangle] //~^ WARNING `#[no_mangle]` has no effect on a foreign function //~^^ WARNING this was previously accepted by the compiler pub fn bar(); } fn no_new_warn() { // Should emit the generic \"not a function or static\" warning #[no_mangle] //~^ WARNING attribute should be applied to a free function, impl method or static //~^^ WARNING this was previously accepted by the compiler let x = 0_u8; } fn main() {} "} {"_id":"doc-en-rust-ac626b785497e7c8757c1faaca668fb8aa25a7e39a035ee37b4e14338c139b03","title":"","text":" warning: attribute should be applied to a free function, impl method or static --> $DIR/extern-no-mangle.rs:24:5 | LL | #[no_mangle] | ^^^^^^^^^^^^ ... LL | let x = 0_u8; | ------------- not a free function, impl method or static | note: the lint level is defined here --> $DIR/extern-no-mangle.rs:1:9 | LL | #![warn(unused_attributes)] | ^^^^^^^^^^^^^^^^^ = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: `#[no_mangle]` has no effect on a foreign static --> $DIR/extern-no-mangle.rs:11:5 | LL | #[no_mangle] | ^^^^^^^^^^^^ help: remove this attribute ... LL | pub static FOO: u8; | ------------------- foreign static | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: symbol names in extern blocks are not mangled warning: `#[no_mangle]` has no effect on a foreign function --> $DIR/extern-no-mangle.rs:16:5 | LL | #[no_mangle] | ^^^^^^^^^^^^ help: remove this attribute ... LL | pub fn bar(); | ------------- foreign function | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: symbol names in extern blocks are not mangled warning: 3 warnings emitted "} {"_id":"doc-en-rust-bcfb95d6568908394c8230259098f22ff9774927ebaadb384f699912b05196c5","title":"","text":"// ignore-debug: the debug assertions get in the way // compile-flags: -O -Z merge-functions=disabled // min-llvm-version: 16 #![crate_type = \"lib\"] // Ensure that trivial casts of vec elements are O(1) pub struct Wrapper(T); // previously repr(C) caused the optimization to fail #[repr(C)] pub struct Foo { a: u64,"} {"_id":"doc-en-rust-57064b064deab31704491676db4a29a813016da1a795f8660afb8d6909dde1fa","title":"","text":"d: u64, } // Going from an aggregate struct to another type currently requires Copy to // enable the TrustedRandomAccess specialization. Without it optimizations do not yet // reliably recognize the loops as noop for repr(C) or non-Copy structs. // implementing Copy exercises the TrustedRandomAccess specialization inside the in-place // specialization #[derive(Copy, Clone)] pub struct Bar { a: u64,"} {"_id":"doc-en-rust-54782ee28ec04658b941dea93711c8591f527ee5432d07634d070cf8a2c14274","title":"","text":"d: u64, } // this exercises the try-fold codepath pub struct Baz { a: u64, b: u64, c: u64, d: u64, } // CHECK-LABEL: @vec_iterator_cast_primitive #[no_mangle] pub fn vec_iterator_cast_primitive(vec: Vec) -> Vec {"} {"_id":"doc-en-rust-362bfa966505a9b51bad9279218ec9a3e4b9ea1d3c95a3322edecff8767a76ea","title":"","text":"// CHECK-LABEL: @vec_iterator_cast_aggregate #[no_mangle] pub fn vec_iterator_cast_aggregate(vec: Vec<[u64; 4]>) -> Vec { // FIXME These checks should be the same as other functions. // CHECK-NOT: @__rust_alloc // CHECK-NOT: @__rust_alloc // CHECK-NOT: loop // CHECK-NOT: call vec.into_iter().map(|e| unsafe { std::mem::transmute(e) }).collect() } // CHECK-LABEL: @vec_iterator_cast_deaggregate // CHECK-LABEL: @vec_iterator_cast_deaggregate_tra #[no_mangle] pub fn vec_iterator_cast_deaggregate(vec: Vec) -> Vec<[u64; 4]> { // FIXME These checks should be the same as other functions. // CHECK-NOT: @__rust_alloc // CHECK-NOT: @__rust_alloc pub fn vec_iterator_cast_deaggregate_tra(vec: Vec) -> Vec<[u64; 4]> { // CHECK-NOT: loop // CHECK-NOT: call // Safety: For the purpose of this test we assume that Bar layout matches [u64; 4]. // This currently is not guaranteed for repr(Rust) types, but it happens to work here and // the UCG may add additional guarantees for homogenous types in the future that would make this // correct. vec.into_iter().map(|e| unsafe { std::mem::transmute(e) }).collect() } // CHECK-LABEL: @vec_iterator_cast_deaggregate_fold #[no_mangle] pub fn vec_iterator_cast_deaggregate_fold(vec: Vec) -> Vec<[u64; 4]> { // CHECK-NOT: loop // CHECK-NOT: call // Safety: For the purpose of this test we assume that Bar layout matches [u64; 4]. // This currently is not guaranteed for repr(Rust) types, but it happens to work here and"} {"_id":"doc-en-rust-8d017c23e2c3e4170064d3854f4f71546c6beae937548fbdd2b9d349a4c484eb","title":"","text":"ty::Adt(def, _) => format!(\"{} `{}`\", def.descr(), tcx.def_path_str(def.did)).into(), ty::Foreign(def_id) => format!(\"extern type `{}`\", tcx.def_path_str(def_id)).into(), ty::Array(t, n) => { if t.is_simple_ty() { return format!(\"array `{}`\", self).into(); } let n = tcx.lift(n).unwrap(); match n.try_eval_usize(tcx, ty::ParamEnv::empty()) { _ if t.is_simple_ty() => format!(\"array `{}`\", self).into(), Some(n) => format!(\"array of {} element{}\", n, pluralize!(n)).into(), None => \"array\".into(), if let ty::ConstKind::Value(v) = n.val { if let Some(n) = v.try_to_machine_usize(tcx) { return format!(\"array of {} element{}\", n, pluralize!(n)).into(); } } \"array\".into() } ty::Slice(ty) if ty.is_simple_ty() => format!(\"slice `{}`\", self).into(), ty::Slice(_) => \"slice\".into(),"} {"_id":"doc-en-rust-d3bd9358126878b0c7275ec63d759fdc69c61bfa51e03507e64b70d05c769d8f","title":"","text":"tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> { // see comment in const_eval_raw_provider for what we're doing here // see comment in eval_to_allocation_raw_provider for what we're doing here if key.param_env.reveal() == Reveal::All { let mut key = key; key.param_env = key.param_env.with_user_facing();"} {"_id":"doc-en-rust-5dc0a3d0f771cae118c451ec8f5ba3438e2343e585139a69337271daf3301fec","title":"","text":" #![feature(const_generics, const_evaluatable_checked)] #![allow(incomplete_features)] // This test is a minimized reproduction for #79518 where // during error handling for the type mismatch we would try // to evaluate std::mem::size_of:: causing an ICE trait Foo { type Assoc: PartialEq; const AssocInstance: Self::Assoc; fn foo() where [(); std::mem::size_of::()]: , { Self::AssocInstance == [(); std::mem::size_of::()]; //~^ Error: mismatched types } } fn main() {} "} {"_id":"doc-en-rust-20712aecf21abaf18717016317166914bd6e9f7692fbbbf2e8becca18c16b7ab","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-79518-default_trait_method_normalization.rs:16:32 | LL | Self::AssocInstance == [(); std::mem::size_of::()]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected associated type, found array `[(); _]` | = note: expected associated type `::Assoc` found array `[(); _]` = help: consider constraining the associated type `::Assoc` to `[(); _]` or calling a method that returns `::Assoc` = note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-013d51f7c3825ea0a995931be27397d18a487ef6a093e6a0b5d0d74f64a44a06","title":"","text":"*self = snapshot; Err(err) } /// Get the diagnostics for the cases where `move async` is found. /// /// `move_async_span` starts at the 'm' of the move keyword and ends with the 'c' of the async keyword pub(super) fn incorrect_move_async_order_found( &self, move_async_span: Span, ) -> DiagnosticBuilder<'a> { let mut err = self.struct_span_err(move_async_span, \"the order of `move` and `async` is incorrect\"); err.span_suggestion_verbose( move_async_span, \"try switching the order\", \"async move\".to_owned(), Applicability::MaybeIncorrect, ); err } }"} {"_id":"doc-en-rust-9b92b965c344ced830d7ca3e5212c8ae17ab46cefdd553c476bcae99dee8f9b7","title":"","text":"self.sess.gated_spans.gate(sym::async_closure, span); } let capture_clause = self.parse_capture_clause(); let capture_clause = self.parse_capture_clause()?; let decl = self.parse_fn_block_decl()?; let decl_hi = self.prev_token.span; let body = match decl.output {"} {"_id":"doc-en-rust-4c94c4945f03f671ecd167bacb20e9574b2af0f8433ac1aec38c298f104f3e76","title":"","text":"} /// Parses an optional `move` prefix to a closure-like construct. fn parse_capture_clause(&mut self) -> CaptureBy { if self.eat_keyword(kw::Move) { CaptureBy::Value } else { CaptureBy::Ref } fn parse_capture_clause(&mut self) -> PResult<'a, CaptureBy> { if self.eat_keyword(kw::Move) { // Check for `move async` and recover if self.check_keyword(kw::Async) { let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo); Err(self.incorrect_move_async_order_found(move_async_span)) } else { Ok(CaptureBy::Value) } } else { Ok(CaptureBy::Ref) } } /// Parses the `|arg, arg|` header of a closure."} {"_id":"doc-en-rust-46f273f88659b71dbec629c7b79877b90f34b877e9221a88a333ff828de5c04c","title":"","text":"fn parse_async_block(&mut self, mut attrs: AttrVec) -> PResult<'a, P> { let lo = self.token.span; self.expect_keyword(kw::Async)?; let capture_clause = self.parse_capture_clause(); let capture_clause = self.parse_capture_clause()?; let (iattrs, body) = self.parse_inner_attrs_and_block()?; attrs.extend(iattrs); let kind = ExprKind::Async(capture_clause, DUMMY_NODE_ID, body);"} {"_id":"doc-en-rust-df098d7e3c0ea706a28d8fb0b6dec33e1787a73192d6b8915d4a969a130b34d5","title":"","text":" // run-rustfix // edition:2018 // Regression test for issue 79694 fn main() { let _ = async move { }; //~ ERROR 7:13: 7:23: the order of `move` and `async` is incorrect } "} {"_id":"doc-en-rust-02862d5ce81b793a75feea5124449426660c42a2c1303a6ed595ebeb645d1f7d","title":"","text":" // run-rustfix // edition:2018 // Regression test for issue 79694 fn main() { let _ = move async { }; //~ ERROR 7:13: 7:23: the order of `move` and `async` is incorrect } "} {"_id":"doc-en-rust-f9fd67a63d733b2a201cc1dd6cd0da4b5730a3b84efc2a74380f5ecfe5c1a2bb","title":"","text":" error: the order of `move` and `async` is incorrect --> $DIR/incorrect-move-async-order-issue-79694.rs:7:13 | LL | let _ = move async { }; | ^^^^^^^^^^ | help: try switching the order | LL | let _ = async move { }; | ^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-466b97a41f2206e07f0fd45157e2fefa8dcc84ed9f990c3194ed6c4cb11a869c","title":"","text":"let pred = trait_ref.without_const().to_predicate(tcx).to_string(); let pred = pred.replace(&impl_trait_str, &type_param_name); let mut sugg = vec![ // Find the last of the generic parameters contained within the span of // the generics match generics .params .iter() .filter(|p| match p.kind { hir::GenericParamKind::Type { synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), .. } => false, _ => true, }) .last() .map(|p| p.bounds_span().unwrap_or(p.span)) .filter(|&span| generics.span.contains(span) && span.desugaring_kind().is_none()) .max_by_key(|span| span.hi()) { // `fn foo(t: impl Trait)` // ^ suggest `` here None => (generics.span, format!(\"<{}>\", type_param)), // `fn foo(t: impl Trait)` // ^^^ suggest `` here Some(param) => ( param.bounds_span().unwrap_or(param.span).shrink_to_hi(), format!(\", {}\", type_param), ), Some(span) => (span.shrink_to_hi(), format!(\", {}\", type_param)), }, // `fn foo(t: impl Trait)` // ^ suggest `where ::A: Bound`"} {"_id":"doc-en-rust-05a596f469eda23c8aba1eed9d5ae081757a7bdb2e42144a9501616cc502ef2c","title":"","text":"} } #[rustfmt::skip] fn baw<>(constraints: impl Iterator) { for constraint in constraints { qux(constraint); //~^ ERROR `::Item` doesn't implement `Debug` } } fn qux(_: impl std::fmt::Debug) {} fn main() {}"} {"_id":"doc-en-rust-b11b9ed495ee1755bbac9cb3c7121c0e9f76ab7563e320a12ef3e6b53a43ad6c","title":"","text":"LL | fn bak(constraints: I) where ::Item: Debug { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 5 previous errors error[E0277]: `::Item` doesn't implement `Debug` --> $DIR/impl-trait-with-missing-bounds.rs:45:13 | LL | qux(constraint); | ^^^^^^^^^^ `::Item` cannot be formatted using `{:?}` because it doesn't implement `Debug` ... LL | fn qux(_: impl std::fmt::Debug) {} | --------------- required by this bound in `qux` | = help: the trait `Debug` is not implemented for `::Item` help: introduce a type parameter with a trait bound instead of using `impl Trait` | LL | fn baw(constraints: I) where ::Item: Debug { | ^^^^^^^^^^^^^ ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 6 previous errors For more information about this error, try `rustc --explain E0277`."} {"_id":"doc-en-rust-368c87b7e7fec3e10f7bbf439ade70d98cd1b1fedd577bf58839e10701c4edf9","title":"","text":" // Regression test: if we suggest replacing an `impl Trait` argument to an async // fn with a named type parameter in order to add bounds, the suggested function // signature should be well-formed. // // edition:2018 trait Foo { type Bar; fn bar(&self) -> Self::Bar; } async fn run(_: &(), foo: impl Foo) -> std::io::Result<()> { let bar = foo.bar(); assert_is_send(&bar); //~^ ERROR: `::Bar` cannot be sent between threads safely Ok(()) } // Test our handling of cases where there is a generic parameter list in the // source, but only synthetic generic parameters async fn run2< >(_: &(), foo: impl Foo) -> std::io::Result<()> { let bar = foo.bar(); assert_is_send(&bar); //~^ ERROR: `::Bar` cannot be sent between threads safely Ok(()) } fn assert_is_send(_: &T) {} fn main() {} "} {"_id":"doc-en-rust-9d6c9deb72ed9a54f2d2f3323752a03f60e14a127cd6de990173d14cba539b43","title":"","text":" error[E0277]: `::Bar` cannot be sent between threads safely --> $DIR/issue-79843-impl-trait-with-missing-bounds-on-async-fn.rs:14:20 | LL | assert_is_send(&bar); | ^^^^ `::Bar` cannot be sent between threads safely ... LL | fn assert_is_send(_: &T) {} | ---- required by this bound in `assert_is_send` | = help: the trait `Send` is not implemented for `::Bar` help: introduce a type parameter with a trait bound instead of using `impl Trait` | LL | async fn run(_: &(), foo: F) -> std::io::Result<()> where ::Bar: Send { | ^^^^^^^^ ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: `::Bar` cannot be sent between threads safely --> $DIR/issue-79843-impl-trait-with-missing-bounds-on-async-fn.rs:24:20 | LL | assert_is_send(&bar); | ^^^^ `::Bar` cannot be sent between threads safely ... LL | fn assert_is_send(_: &T) {} | ---- required by this bound in `assert_is_send` | = help: the trait `Send` is not implemented for `::Bar` help: introduce a type parameter with a trait bound instead of using `impl Trait` | LL | async fn run2(_: &(), foo: F) -> std::io::Result<()> where ::Bar: Send { | ^^^^^^^^ ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-3c86809eb8c4580889053403b74114397a96bceb6a0eab5fd09d04503e1dc0f0","title":"","text":"token.can_begin_expr() // This exception is here for backwards compatibility. && !token.is_keyword(kw::Let) // This exception is here for backwards compatibility. && !token.is_keyword(kw::Const) } NonterminalKind::Ty => token.can_begin_type(), NonterminalKind::Ident => get_macro_ident(token).is_some(),"} {"_id":"doc-en-rust-aaea424c908569607cdcd899bc219da7ebf709f7611c0b80159182a30339b52b","title":"","text":" // check-pass macro_rules! exp { (const $n:expr) => { $n }; } macro_rules! stmt { (exp $e:expr) => { $e }; (exp $($t:tt)+) => { exp!($($t)+) }; } fn main() { stmt!(exp const 1); } "} {"_id":"doc-en-rust-ceb73441a5447ce119c0d8ed8077ae31f404620e755dc984d8a1617e18f80fee","title":"","text":"} #titles > button:hover, #titles > button.selected { background-color: #ffffff; border-top-color: #0089ff; background-color: #353535; } #titles > button > div.count {"} {"_id":"doc-en-rust-f1b3ef6e8a97a1677ecef9c5086aad23fd2b34f2759447edfe92431aaab2bf51","title":"","text":"] [[package]] name = \"cargo-credential\" version = \"0.1.0\" [[package]] name = \"cargo-credential-1password\" version = \"0.1.0\" dependencies = [ \"cargo-credential\", \"serde\", \"serde_json\", ] [[package]] name = \"cargo-credential-macos-keychain\" version = \"0.1.0\" dependencies = [ \"cargo-credential\", \"security-framework\", ] [[package]] name = \"cargo-credential-wincred\" version = \"0.1.0\" dependencies = [ \"cargo-credential\", \"winapi 0.3.9\", ] [[package]] name = \"cargo-miri\" version = \"0.1.0\" dependencies = ["} {"_id":"doc-en-rust-77f3fb0ee24e84238818926508d52d03b9156590019d65de8f265338e8f6ce67","title":"","text":"checksum = \"d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd\" [[package]] name = \"security-framework\" version = \"2.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"c1759c2e3c8580017a484a7ac56d3abc5a6c1feadf88db2f3633f12ae4268c69\" dependencies = [ \"bitflags\", \"core-foundation\", \"core-foundation-sys\", \"libc\", \"security-framework-sys\", ] [[package]] name = \"security-framework-sys\" version = \"2.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"f99b9d5e26d2a71633cc4f2ebae7cc9f874044e0c351a27e17892d76dce5678b\" dependencies = [ \"core-foundation-sys\", \"libc\", ] [[package]] name = \"semver\" version = \"0.9.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"doc-en-rust-d3899b57f6613ffc2f218d47a2c49106da2cc66d9e7d7ed83c46aa816fa31c0f","title":"","text":"[[package]] name = \"serde\" version = \"1.0.115\" version = \"1.0.118\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"e54c9a88f2da7238af84b5101443f0c0d0a3bbdc455e34a5c9497b1903ed55d5\" checksum = \"06c64263859d87aa2eb554587e2d23183398d617427327cf2b3d0ed8c69e4800\" dependencies = [ \"serde_derive\", ] [[package]] name = \"serde_derive\" version = \"1.0.115\" version = \"1.0.118\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"609feed1d0a73cc36a0182a840a9b37b4a82f0b1150369f0536a9e3f2a31dc48\" checksum = \"c84d3526699cd55261af4b941e4e725444df67aa4f9e6a3564f18030d12672df\" dependencies = [ \"proc-macro2\", \"quote\","} {"_id":"doc-en-rust-bc681656fced8b03a629006dcc6a35c9ac7f19da0d991f14571ee5b4ad3ac078","title":"","text":"\"src/tools/rust-installer\", \"src/tools/rust-demangler\", \"src/tools/cargo\", \"src/tools/cargo/crates/credential/cargo-credential-1password\", \"src/tools/cargo/crates/credential/cargo-credential-macos-keychain\", \"src/tools/cargo/crates/credential/cargo-credential-wincred\", \"src/tools/rustdoc\", \"src/tools/rls\", \"src/tools/rustfmt\","} {"_id":"doc-en-rust-1941695baeee8836ca2713350259a801a8f3aab50d438aa5c256f403747092a3","title":"","text":"builder.create_dir(&image.join(\"etc/bash_completion.d\")); let cargo = builder.ensure(tool::Cargo { compiler, target }); builder.install(&cargo, &image.join(\"bin\"), 0o755); for dirent in fs::read_dir(cargo.parent().unwrap()).expect(\"read_dir\") { let dirent = dirent.expect(\"read dir entry\"); if dirent.file_name().to_str().expect(\"utf8\").starts_with(\"cargo-credential-\") { builder.install(&dirent.path(), &image.join(\"libexec\"), 0o755); } } for man in t!(etc.join(\"man\").read_dir()) { let man = t!(man); builder.install(&man.path(), &image.join(\"share/man/man1\"), 0o644);"} {"_id":"doc-en-rust-2b359d023d2647f181d4063bde4b7d5e1fcefe94b6715efa46b0270635ff36cb","title":"","text":"} fn run(self, builder: &Builder<'_>) -> PathBuf { builder let cargo_bin_path = builder .ensure(ToolBuild { compiler: self.compiler, target: self.target,"} {"_id":"doc-en-rust-cbc304c5e1edac8d40b299b2ae3c57cf986d6635f2975a1d9e7d30f8f9b3b695","title":"","text":"source_type: SourceType::Submodule, extra_features: Vec::new(), }) .expect(\"expected to build -- essential tool\") .expect(\"expected to build -- essential tool\"); let build_cred = |name, path| { // These credential helpers are currently experimental. // Any build failures will be ignored. let _ = builder.ensure(ToolBuild { compiler: self.compiler, target: self.target, tool: name, mode: Mode::ToolRustc, path, is_optional_tool: true, source_type: SourceType::Submodule, extra_features: Vec::new(), }); }; if self.target.contains(\"windows\") { build_cred( \"cargo-credential-wincred\", \"src/tools/cargo/crates/credential/cargo-credential-wincred\", ); } if self.target.contains(\"apple-darwin\") { build_cred( \"cargo-credential-macos-keychain\", \"src/tools/cargo/crates/credential/cargo-credential-macos-keychain\", ); } build_cred( \"cargo-credential-1password\", \"src/tools/cargo/crates/credential/cargo-credential-1password\", ); cargo_bin_path } }"} {"_id":"doc-en-rust-57775a6167f61c1514c463409e5f33898c4e22760d3016fe20135b1c8090bf27","title":"","text":" Subproject commit d274fcf862b89264fa2c6b917b15230705257317 Subproject commit a3c2627fbc2f5391c65ba45ab53b81bf71fa323c "} {"_id":"doc-en-rust-d6e19a2f33e58fa976a52464cfae8a9b7f4b9eb05e88f9ebafbd6f77d0ff5128","title":"","text":" // check-pass #![allow(unreachable_code, unused)] use std::marker::PhantomData; struct FsmBuilder { _fsm: PhantomData, } impl FsmBuilder { fn state(&mut self) -> FsmStateBuilder { todo!() } } struct FsmStateBuilder { _state: PhantomData, } impl FsmStateBuilder { fn on_entry)>(&self, _action: TAction) {} } trait Fsm { type Context; } struct StateContext<'a, TFsm: Fsm> { context: &'a mut TFsm::Context, } fn main() { let mut builder: FsmBuilder = todo!(); builder.state().on_entry(|_| {}); } "} {"_id":"doc-en-rust-635b6872ca01fc1b2cd20bb3f5e4ad933af4d9f2f63be4442b1b5cb55ece36b9","title":"","text":"s.print_type_bounds(\":\", ¶m.bounds); if let Some(ref _default) = default { // FIXME(const_generics_defaults): print the `default` value here todo!(); } } }"} {"_id":"doc-en-rust-b621cc9c22fed70998418c7a51030a3d9781ead27e5e015cde908effb9cf09e3","title":"","text":"self.print_type(ty); if let Some(ref _default) = default { // FIXME(const_generics_defaults): print the `default` value here todo!(); } } }"} {"_id":"doc-en-rust-3c33f3a9fac80f473cc8d69fd80c66da4984c114c1ed7eea7b176dd8f44fcbef","title":"","text":"param_text.push_str(&ty_to_string(&ty)); if let Some(ref _default) = default { // FIXME(const_generics_defaults): push the `default` value here todo!(); } } if !param.bounds.is_empty() {"} {"_id":"doc-en-rust-20cb283f4e1da5458472b1c3c7f367e139c2214d8fa65286e4c37cfc9a77a307","title":"","text":" //! Test case for [#80737]. //! //! A SomeTrait that is implemented for `&mut T where T: SomeTrait` //! should not be marked as \"notable\" for return values that do not //! have bounds on the trait itself. //! //! [#80737]: https://github.com/rust-lang/rust/issues/80737 #![feature(rustdoc_internals)] #![no_std] #[doc(primitive = \"reference\")] /// Some useless docs, wouhou! /// /// We need to put this in here, because notable traits /// that are implemented on foreign types don't show up. mod reference {} // @has doc_notable_trait_mut_t_is_not_an_iterator/fn.fn_no_matches.html // @!has - '//code[@class=\"content\"]' 'Iterator' pub fn fn_no_matches<'a, T: 'a>() -> &'a mut T { panic!() } "} {"_id":"doc-en-rust-e0acd014c1dd771211052adcda6d8acd5ae8f86c65c1966cecd255e8a4e25029","title":"","text":" #![allow(unreachable_code)] use std::marker::PhantomData; use std::ops::Deref; use std::sync::Arc; pub struct Guard { _phantom: PhantomData, } impl Deref for Guard { type Target = T; fn deref(&self) -> &T { unimplemented!() } } pub struct DirectDeref(T); impl Deref for DirectDeref> { type Target = T; fn deref(&self) -> &T { unimplemented!() } } pub trait Access { type Guard: Deref; fn load(&self) -> Self::Guard { unimplemented!() } } impl, P: Deref> Access for P { //~^ NOTE: required for `Arc>>` to implement `Access<_>` type Guard = A::Guard; } impl Access for ArcSwapAny { //~^ NOTE: multiple `impl`s satisfying `ArcSwapAny>: Access<_>` found type Guard = Guard; } impl Access for ArcSwapAny> { type Guard = DirectDeref>; } pub struct ArcSwapAny { _phantom_arc: PhantomData, } pub fn foo() { let s: Arc>> = unimplemented!(); let guard: Guard> = s.load(); //~^ ERROR: type annotations needed //~| HELP: try using a fully qualified path to specify the expected types } fn main() {} "} {"_id":"doc-en-rust-925721e825d393e07fbe463a5599987283f1092f430a6e55920ca16853bdf1a8","title":"","text":" error[E0283]: type annotations needed --> $DIR/issue-80816.rs:49:38 | LL | let guard: Guard> = s.load(); | ^^^^ | note: multiple `impl`s satisfying `ArcSwapAny>: Access<_>` found --> $DIR/issue-80816.rs:35:1 | LL | impl Access for ArcSwapAny { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ... LL | impl Access for ArcSwapAny> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: required for `Arc>>` to implement `Access<_>` --> $DIR/issue-80816.rs:31:45 | LL | impl, P: Deref> Access for P { | ^^^^^^^^^ ^ help: try using a fully qualified path to specify the expected types | LL | let guard: Guard> = >> as Access>::load(&s); | ++++++++++++++++++++++++++++++++++++++++++++++++++ ~ error: aborting due to previous error For more information about this error, try `rustc --explain E0283`. "} {"_id":"doc-en-rust-769e3495b7a8b006f9dd4482bbfccff4b99ae9f58dff489128e1f80e9c165c0a","title":"","text":"fn source_info(&self, cx: &CodegenCx<'ll, 'tcx>) -> Option> { match self { VariantInfo::Generator { def_id, variant_index, .. } => { let span = cx.tcx.generator_layout(*def_id).variant_source_info[*variant_index].span; let span = cx.tcx.generator_layout(*def_id).unwrap().variant_source_info [*variant_index] .span; if !span.is_dummy() { let loc = cx.lookup_debug_loc(span.lo()); return Some(SourceInfo {"} {"_id":"doc-en-rust-382c343cd3f06eedcd839f5deca2b034ad0b0eaf22010c772a416313cd5fd026","title":"","text":") -> Result<&'tcx Layout, LayoutError<'tcx>> { use SavedLocalEligibility::*; let tcx = self.tcx; let subst_field = |ty: Ty<'tcx>| ty.subst(tcx, substs); let info = tcx.generator_layout(def_id); let info = match tcx.generator_layout(def_id) { None => return Err(LayoutError::Unknown(ty)), Some(info) => info, }; let (ineligible_locals, assignments) = self.generator_saved_local_eligibility(&info); // Build a prefix layout, including \"promoting\" all ineligible"} {"_id":"doc-en-rust-b58bdba1deb767ead97ee4baa6ee9e920948b79e61488ffd8f2b0221788bc76e","title":"","text":"self.trait_def(trait_def_id).has_auto_impl } pub fn generator_layout(self, def_id: DefId) -> &'tcx GeneratorLayout<'tcx> { self.optimized_mir(def_id).generator_layout.as_ref().unwrap() /// Returns layout of a generator. Layout might be unavailable if the /// generator is tainted by errors. pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx GeneratorLayout<'tcx>> { self.optimized_mir(def_id).generator_layout.as_ref() } /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements."} {"_id":"doc-en-rust-bdd4f3cb51fa42acd436bc6ed935aa5aa1aa1afc505b1b7ac67eba8d073fcba8","title":"","text":"#[inline] pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range { // FIXME requires optimized MIR let num_variants = tcx.generator_layout(def_id).variant_fields.len(); let num_variants = tcx.generator_layout(def_id).unwrap().variant_fields.len(); VariantIdx::new(0)..VariantIdx::new(num_variants) }"} {"_id":"doc-en-rust-921a997f6b6cc4c3fb04665b5277d39cb70e824908a497571733dd34587c2ae6","title":"","text":"def_id: DefId, tcx: TyCtxt<'tcx>, ) -> impl Iterator> + Captures<'tcx>> { let layout = tcx.generator_layout(def_id); let layout = tcx.generator_layout(def_id).unwrap(); layout.variant_fields.iter().map(move |variant| { variant.iter().map(move |field| layout.field_tys[*field].subst(tcx, self.substs)) })"} {"_id":"doc-en-rust-931f5ebeee7edf5eaace85d06b4333d89dd63aa63ec37ad1e7a3acab52bfecd2","title":"","text":" // Verifies that computing a layout of a generator tainted by type errors // doesn't ICE. Regression test for #80998. // // edition:2018 #![feature(type_alias_impl_trait)] use std::future::Future; pub struct Task(F); impl Task { fn new() -> Self { todo!() } fn spawn(&self, _: impl FnOnce() -> F) { todo!() } } fn main() { async fn cb() { let a = Foo; //~ ERROR cannot find value `Foo` in this scope } type F = impl Future; // Check that statics are inhabited computes they layout. static POOL: Task = Task::new(); Task::spawn(&POOL, || cb()); } "} {"_id":"doc-en-rust-db3579e7e937c60b1ba3dc524bde57d48ed4b1d50c1441f1b6241f67c92e6f97","title":"","text":" error[E0425]: cannot find value `Foo` in this scope --> $DIR/layout-error.rs:21:17 | LL | let a = Foo; | ^^^ not found in this scope error: aborting due to previous error For more information about this error, try `rustc --explain E0425`. "} {"_id":"doc-en-rust-b065ee8a628031daaf33b7ae2267d8baa730da8ba3f2818e96a3f11eed6c18f6","title":"","text":"debug!(\"exp_found {:?} terr {:?}\", exp_found, terr); if let Some(exp_found) = exp_found { self.suggest_as_ref_where_appropriate(span, &exp_found, diag); self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag); self.suggest_await_on_expect_found(cause, span, &exp_found, diag); }"} {"_id":"doc-en-rust-de6f65d12148d4d79cbb326a710017b2bb55100601cd489f34299b07fddb1c7d","title":"","text":"} } fn suggest_accessing_field_where_appropriate( &self, cause: &ObligationCause<'tcx>, exp_found: &ty::error::ExpectedFound>, diag: &mut DiagnosticBuilder<'tcx>, ) { debug!( \"suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})\", cause, exp_found ); if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() { if expected_def.is_enum() { return; } if let Some((name, ty)) = expected_def .non_enum_variant() .fields .iter() .filter(|field| field.vis.is_accessible_from(field.did, self.tcx)) .map(|field| (field.ident.name, field.ty(self.tcx, expected_substs))) .find(|(_, ty)| ty::TyS::same_type(ty, exp_found.found)) { if let ObligationCauseCode::Pattern { span: Some(span), .. } = cause.code { if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { let suggestion = if expected_def.is_struct() { format!(\"{}.{}\", snippet, name) } else if expected_def.is_union() { format!(\"unsafe {{ {}.{} }}\", snippet, name) } else { return; }; diag.span_suggestion( span, &format!( \"you might have meant to use field `{}` of type `{}`\", name, ty ), suggestion, Applicability::MaybeIncorrect, ); } } } } } /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate, /// suggests it. fn suggest_as_ref_where_appropriate("} {"_id":"doc-en-rust-c251053fce62a3b2437f5e9e278be620e89d4ea8a6b60e92dd9acc9416ab9c03","title":"","text":" // run-rustfix #![allow(dead_code)] struct A { b: B, } enum B { Fst, Snd, } union Foo { bar: u32, qux: f32, } fn main() { let a = A { b: B::Fst }; if let B::Fst = a.b {}; //~ ERROR mismatched types [E0308] //~^ HELP you might have meant to use field `b` of type `B` match a.b { //~^ HELP you might have meant to use field `b` of type `B` //~| HELP you might have meant to use field `b` of type `B` B::Fst => (), //~ ERROR mismatched types [E0308] B::Snd => (), //~ ERROR mismatched types [E0308] } let foo = Foo { bar: 42 }; match unsafe { foo.bar } { //~^ HELP you might have meant to use field `bar` of type `u32` 1u32 => (), //~ ERROR mismatched types [E0308] _ => (), } } "} {"_id":"doc-en-rust-986fc1b0c2f14ddd9dc7ab08654a009423e67f69d097a0d33eef92eaf8c0b8fe","title":"","text":" // run-rustfix #![allow(dead_code)] struct A { b: B, } enum B { Fst, Snd, } union Foo { bar: u32, qux: f32, } fn main() { let a = A { b: B::Fst }; if let B::Fst = a {}; //~ ERROR mismatched types [E0308] //~^ HELP you might have meant to use field `b` of type `B` match a { //~^ HELP you might have meant to use field `b` of type `B` //~| HELP you might have meant to use field `b` of type `B` B::Fst => (), //~ ERROR mismatched types [E0308] B::Snd => (), //~ ERROR mismatched types [E0308] } let foo = Foo { bar: 42 }; match foo { //~^ HELP you might have meant to use field `bar` of type `u32` 1u32 => (), //~ ERROR mismatched types [E0308] _ => (), } } "} {"_id":"doc-en-rust-6940b93714cc27e0a4ec83c3f075b3ec4c6c881e055e96a42c15910eff1cb54d","title":"","text":" error[E0308]: mismatched types --> $DIR/field-access.rs:20:12 | LL | Fst, | --- unit variant defined here ... LL | if let B::Fst = a {}; | ^^^^^^ - this expression has type `A` | | | expected struct `A`, found enum `B` | help: you might have meant to use field `b` of type `B` | LL | if let B::Fst = a.b {}; | ^^^ error[E0308]: mismatched types --> $DIR/field-access.rs:25:9 | LL | Fst, | --- unit variant defined here ... LL | match a { | - this expression has type `A` ... LL | B::Fst => (), | ^^^^^^ expected struct `A`, found enum `B` | help: you might have meant to use field `b` of type `B` | LL | match a.b { | ^^^ error[E0308]: mismatched types --> $DIR/field-access.rs:26:9 | LL | Snd, | --- unit variant defined here ... LL | match a { | - this expression has type `A` ... LL | B::Snd => (), | ^^^^^^ expected struct `A`, found enum `B` | help: you might have meant to use field `b` of type `B` | LL | match a.b { | ^^^ error[E0308]: mismatched types --> $DIR/field-access.rs:32:9 | LL | match foo { | --- this expression has type `Foo` LL | LL | 1u32 => (), | ^^^^ expected union `Foo`, found `u32` | help: you might have meant to use field `bar` of type `u32` | LL | match unsafe { foo.bar } { | ^^^^^^^^^^^^^^^^^^ error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-f35d6b784d42813ac3f84e8b88e8c72bee62ba5ac80a239a1d0251606c2623e5","title":"","text":"FakeReadCause, Local, LocalDecl, LocalInfo, LocalKind, Location, Operand, Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind, VarBindingForm, }; use rustc_middle::ty::{self, suggest_constraining_type_param, Instance, Ty}; use rustc_span::{source_map::DesugaringKind, symbol::sym, Span}; use rustc_middle::ty::{self, suggest_constraining_type_param, Ty, TypeFoldable}; use rustc_span::source_map::DesugaringKind; use rustc_span::symbol::sym; use rustc_span::Span; use crate::dataflow::drop_flag_effects; use crate::dataflow::indexes::{MoveOutIndex, MovePathIndex}; use crate::util::borrowck_errors; use crate::borrow_check::{ borrow_set::BorrowData, prefixes::IsPrefixOf, InitializationRequiringAction, MirBorrowckCtxt, PrefixSet, WriteKind, borrow_set::BorrowData, diagnostics::Instance, prefixes::IsPrefixOf, InitializationRequiringAction, MirBorrowckCtxt, PrefixSet, WriteKind, }; use super::{"} {"_id":"doc-en-rust-820d70c2f2f6977328c93e61e6610d700b7921447a11c71b5d7c9031126b4ead","title":"","text":"if return_span != borrow_span { err.span_label(borrow_span, note); let tcx = self.infcx.tcx; let ty_params = ty::List::empty(); let return_ty = self.regioncx.universal_regions().unnormalized_output_ty; let return_ty = tcx.erase_regions(return_ty); // to avoid panics if !return_ty.has_infer_types() { if let Some(iter_trait) = tcx.get_diagnostic_item(sym::Iterator) { if tcx.type_implements_trait((iter_trait, return_ty, ty_params, self.param_env)) { if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(return_span) { err.span_suggestion_hidden( return_span, \"use `.collect()` to allocate the iterator\", format!(\"{}{}\", snippet, \".collect::>()\"), Applicability::MaybeIncorrect, ); } } } } } Some(err)"} {"_id":"doc-en-rust-dcdbd2ae4d737b083d7ce215320efefebec42f524068e90d6315cd2742952c15","title":"","text":"message = \"`{Self}` is not an iterator\" )] #[doc(spotlight)] #[rustc_diagnostic_item = \"Iterator\"] #[must_use = \"iterators are lazy and do nothing unless consumed\"] pub trait Iterator { /// The type of the elements being iterated over."} {"_id":"doc-en-rust-6a1fbfb9380fef5f9ebc837b3429d3f81eec782b4eb680ff4bacbc73471c63e4","title":"","text":" // run-rustfix fn main() { let _ = vec![vec![0, 1], vec![2]] .into_iter() .map(|y| y.iter().map(|x| x + 1).collect::>()) //~^ ERROR cannot return value referencing function parameter `y` .collect::>(); } "} {"_id":"doc-en-rust-d4aae6401fbe4cb2e4d7a6992f33d3be951c3b782cddf772150294d3d8115a3f","title":"","text":" // run-rustfix fn main() { let _ = vec![vec![0, 1], vec![2]] .into_iter() .map(|y| y.iter().map(|x| x + 1)) //~^ ERROR cannot return value referencing function parameter `y` .collect::>(); } "} {"_id":"doc-en-rust-ce80105f401d1c731fd09d63de1947c4ec75c2febbf485814466d4a0de0779f2","title":"","text":" error[E0515]: cannot return value referencing function parameter `y` --> $DIR/issue-81584.rs:5:22 | LL | .map(|y| y.iter().map(|x| x + 1)) | -^^^^^^^^^^^^^^^^^^^^^^ | | | returns a value referencing data owned by the current function | `y` is borrowed here | = help: use `.collect()` to allocate the iterator error: aborting due to previous error For more information about this error, try `rustc --explain E0515`. "} {"_id":"doc-en-rust-f5660944fd8c94206e095af290b1517984a7ffa4e2775dbe970041793415df31","title":"","text":"| | ------------------------------ temporary value created here LL | | } | |_____^ returns a value referencing data owned by the current function | = help: use `.collect()` to allocate the iterator error: aborting due to 4 previous errors"} {"_id":"doc-en-rust-33538e8388398b2d380be3249ad2e9cc0282c4d67ade4c448c1a8ce5a9498515","title":"","text":"ctrl = table.GetChildMemberWithName(\"ctrl\").GetChildAtIndex(0) self.size = table.GetChildMemberWithName(\"items\").GetValueAsUnsigned() self.pair_type = table.type.template_args[0].GetTypedefedType() self.pair_type = table.type.template_args[0] if self.pair_type.IsTypedefType(): self.pair_type = self.pair_type.GetTypedefedType() self.pair_type_size = self.pair_type.GetByteSize() self.new_layout = not table.GetChildMemberWithName(\"data\").IsValid()"} {"_id":"doc-en-rust-6157badaf9d6023fb87617fa97ad49094b37ebc7d8c18e46c29fcdae8f482927","title":"","text":"} let mut completed_test = res.unwrap(); let running_test = running_tests.remove(&completed_test.desc).unwrap(); if let Some(join_handle) = running_test.join_handle { if let Err(_) = join_handle.join() { if let TrOk = completed_test.result { completed_test.result = TrFailedMsg(\"panicked after reporting success\".to_string()); if let Some(running_test) = running_tests.remove(&completed_test.desc) { if let Some(join_handle) = running_test.join_handle { if let Err(_) = join_handle.join() { if let TrOk = completed_test.result { completed_test.result = TrFailedMsg(\"panicked after reporting success\".to_string()); } } } }"} {"_id":"doc-en-rust-e0e7409fb9549309a5a7e9a57089921a95a3cef4cea041edbf2a348b7a86633a","title":"","text":"| GenericArgKind::Const(_), _, ) => { // I *think* that HIR lowering should ensure this // doesn't happen, even in erroneous // programs. Else we should use delay-span-bug. span_bug!( // HIR lowering sometimes doesn't catch this in erroneous // programs, so we need to use delay_span_bug here. See #82126. self.infcx.tcx.sess.delay_span_bug( hir_arg.span(), \"unmatched subst and hir arg: found {:?} vs {:?}\", kind, hir_arg, &format!(\"unmatched subst and hir arg: found {:?} vs {:?}\", kind, hir_arg), ); } }"} {"_id":"doc-en-rust-bae8b97c9f31b403d82fa0a3e52ba46aabc45137dcba082c3b0522c89d833be5","title":"","text":" // Regression test for #82126. Checks that mismatched lifetimes and types are // properly handled. // edition:2018 use std::sync::Mutex; struct MarketMultiplier {} impl MarketMultiplier { fn buy(&mut self) -> &mut usize { todo!() } } async fn buy_lock(generator: &Mutex) -> LockedMarket<'_> { //~^ ERROR this struct takes 0 lifetime arguments but 1 lifetime argument was supplied //~^^ ERROR this struct takes 1 type argument but 0 type arguments were supplied LockedMarket(generator.lock().unwrap().buy()) //~^ ERROR cannot return value referencing temporary value } struct LockedMarket(T); fn main() {} "} {"_id":"doc-en-rust-baf40f20f04692842eb476ee3cf4364e260aa3ab7bafddff9d7b1ce768608e27","title":"","text":" error[E0107]: this struct takes 0 lifetime arguments but 1 lifetime argument was supplied --> $DIR/issue-82126-mismatched-subst-and-hir.rs:16:59 | LL | async fn buy_lock(generator: &Mutex) -> LockedMarket<'_> { | ^^^^^^^^^^^^---- help: remove these generics | | | expected 0 lifetime arguments | note: struct defined here, with 0 lifetime parameters --> $DIR/issue-82126-mismatched-subst-and-hir.rs:23:8 | LL | struct LockedMarket(T); | ^^^^^^^^^^^^ error[E0107]: this struct takes 1 type argument but 0 type arguments were supplied --> $DIR/issue-82126-mismatched-subst-and-hir.rs:16:59 | LL | async fn buy_lock(generator: &Mutex) -> LockedMarket<'_> { | ^^^^^^^^^^^^ expected 1 type argument | note: struct defined here, with 1 type parameter: `T` --> $DIR/issue-82126-mismatched-subst-and-hir.rs:23:8 | LL | struct LockedMarket(T); | ^^^^^^^^^^^^ - help: add missing type argument | LL | async fn buy_lock(generator: &Mutex) -> LockedMarket<'_, T> { | ^^^ error[E0515]: cannot return value referencing temporary value --> $DIR/issue-82126-mismatched-subst-and-hir.rs:19:5 | LL | LockedMarket(generator.lock().unwrap().buy()) | ^^^^^^^^^^^^^-------------------------^^^^^^^ | | | | | temporary value created here | returns a value referencing data owned by the current function error: aborting due to 3 previous errors Some errors have detailed explanations: E0107, E0515. For more information about an error, try `rustc --explain E0107`. "} {"_id":"doc-en-rust-62b4c287b42c73938b099160e6b95792009281966e54c3f5d92faf33c11aebf3","title":"","text":"fn run(self, builder: &Builder<'_>) -> Option { let compiler = self.compiler; let target = self.target; let tool = self.tool; let mut tool = self.tool; let path = self.path; let is_optional_tool = self.is_optional_tool;"} {"_id":"doc-en-rust-3a52c7e43a8905c45c34e738659961bed3be3486206db3798328f4676397a9d4","title":"","text":"None } } else { // HACK(#82501): on Windows, the tools directory gets added to PATH when running tests, and // compiletest confuses HTML tidy with the in-tree tidy. Name the in-tree tidy something // different so the problem doesn't come up. if tool == \"tidy\" { tool = \"rust-tidy\"; } let cargo_out = builder.cargo_out(compiler, self.mode, target).join(exe(tool, compiler.host)); let bin = builder.tools_dir(compiler).join(exe(tool, compiler.host));"} {"_id":"doc-en-rust-ef4b2776646b90d7ddf88ff1ff9bf6ceaf9b3bde3227129b1582dc7285dd4add","title":"","text":"version = \"0.1.0\" authors = [\"Alex Crichton \"] edition = \"2018\" autobins = false [dependencies] cargo_metadata = \"0.11\" regex = \"1\" lazy_static = \"1\" walkdir = \"2\" [[bin]] name = \"rust-tidy\" path = \"src/main.rs\" "} {"_id":"doc-en-rust-5b1c7c017d3a2fb8024f1e8f9dd97167b1fbc92df792bd038126e673c8e92d8c","title":"","text":"/* ignore-tidy-linelength */ /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none} /*! normalize.css v3.0.0 | MIT License | git.io/normalize */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:bold}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type=\"button\"],input[type=\"reset\"],input[type=\"submit\"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type=\"checkbox\"],input[type=\"radio\"]{box-sizing:border-box;padding:0}input[type=\"number\"]::-webkit-inner-spin-button,input[type=\"number\"]::-webkit-outer-spin-button{height:auto}input[type=\"search\"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type=\"search\"]::-webkit-search-cancel-button,input[type=\"search\"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:bold}table{border-collapse:collapse;border-spacing:0}td,th{padding:0} "} {"_id":"doc-en-rust-fb999e009e34bb515496539d952b86e8615f7dd80ceabe1461df1c44d0a35a1e","title":"","text":"use rustc_hir::{ExprKind, ItemKind, Node}; use rustc_infer::infer; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::{self, Ty}; use rustc_middle::ty::{self, Binder, Ty}; use rustc_span::symbol::kw; use std::iter;"} {"_id":"doc-en-rust-0cf47c6cfbbfd41655b9a7316eb798f63098e341c1d19bb68ec43a8a8b9577e3","title":"","text":"let found = self.resolve_vars_with_obligations(found); if let hir::FnRetTy::Return(ty) = fn_decl.output { let ty = AstConv::ast_ty_to_ty(self, ty); let ty = self.tcx.erase_late_bound_regions(Binder::bind(ty)); let ty = self.normalize_associated_types_in(expr.span, ty); if self.can_coerce(found, ty) { err.multipart_suggestion("} {"_id":"doc-en-rust-6f2b2108267a9c6dc5708868210095c1af8900efd39148cf5f2848a7466678b2","title":"","text":" // Regression test for #82612. use std::marker::PhantomData; pub trait SparseSetIndex { fn sparse_set_index(&self) -> usize; } pub struct SparseArray { values: Vec>, marker: PhantomData, } impl SparseArray { pub fn get_or_insert_with(&mut self, index: I, func: impl FnOnce() -> V) -> &mut V { let index = index.sparse_set_index(); if index < self.values.len() { let value = unsafe { self.values.get_unchecked_mut(index) }; value.get_or_insert_with(func) //~ ERROR mismatched types } unsafe { self.values.get_unchecked_mut(index).as_mut().unwrap() } } } fn main() {} "} {"_id":"doc-en-rust-16b3f616a67ac750f7bcf565cfe7492e01f75d731bda85ff0c5b84dfcfe6401b","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-82612-return-mutable-reference.rs:18:13 | LL | / if index < self.values.len() { LL | | let value = unsafe { self.values.get_unchecked_mut(index) }; LL | | value.get_or_insert_with(func) | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found `&mut V` LL | | } | |_________- expected this to be `()` | = note: expected unit type `()` found mutable reference `&mut V` help: consider using a semicolon here | LL | value.get_or_insert_with(func); | ^ help: consider using a semicolon here | LL | }; | ^ help: you might have meant to return this value | LL | return value.get_or_insert_with(func); | ^^^^^^ ^ error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-ba77f25049381d2b3da916ecc4abd7e097ead8cf13db9d79d57d2adf51f5e003","title":"","text":"- [Documentation tests](documentation-tests.md) - [Linking to items by name](linking-to-items-by-name.md) - [Lints](lints.md) - [Passes](passes.md) - [Advanced features](advanced-features.md) - [Unstable features](unstable-features.md) - [Passes](passes.md) - [References](references.md)"} {"_id":"doc-en-rust-ba9f5f0b33cb5f9d8a3b4ff47661af64b0ad54482fbc215262e202c3c4150f3c","title":"","text":"LLVM version: 3.9 ``` ## `-r`/`--input-format`: input format This flag is currently ignored; the idea is that `rustdoc` would support various input formats, and you could specify them via this flag. Rustdoc only supports Rust source code and Markdown input formats. If the file ends in `.md` or `.markdown`, `rustdoc` treats it as a Markdown file. Otherwise, it assumes that the input file is Rust. ## `-w`/`--output-format`: output format This flag is currently ignored; the idea is that `rustdoc` would support various output formats, and you could specify them via this flag. Rustdoc only supports HTML output, and so this flag is redundant today. ## `-o`/`--output`: output path Using this flag looks like this:"} {"_id":"doc-en-rust-7b4f77f9225194c65d9fc1418920b8a78f22fd4e53e1abef7a9a19ec0711d044","title":"","text":"as the `.rs` file. `--crate-name` lets you override this assumption with whatever name you choose. ## `--document-private-items`: Show items that are not public Using this flag looks like this: ```bash $ rustdoc src/lib.rs --document-private-items ``` By default, `rustdoc` only documents items that are publicly reachable. ```rust pub fn public() {} // this item is public and will documented mod private { // this item is private and will not be documented pub fn unreachable() {} // this item is public, but unreachable, so it will not be documented } ``` `--document-private-items` documents all items, even if they're not public. ## `-L`/`--library-path`: where to look for dependencies Using this flag looks like this:"} {"_id":"doc-en-rust-3598473487262cda462b01c68bfcadd75a67300ca3b239a1d38a2222cd4cf76c","title":"","text":"The arguments to this flag are the same as those for the `-C` flag on rustc. Run `rustc -C help` to get the full list. ## `--passes`: add more rustdoc passes Using this flag looks like this: ```bash $ rustdoc --passes list $ rustdoc src/lib.rs --passes strip-priv-imports ``` An argument of \"list\" will print a list of possible \"rustdoc passes\", and other arguments will be the name of which passes to run in addition to the defaults. For more details on passes, see [the chapter on them](passes.md). See also `--no-defaults`. ## `--no-defaults`: don't run default passes Using this flag looks like this: ```bash $ rustdoc src/lib.rs --no-defaults ``` By default, `rustdoc` will run several passes over your code. This removes those defaults, allowing you to use `--passes` to specify exactly which passes you want. For more details on passes, see [the chapter on them](passes.md). See also `--passes`. ## `--test`: run code examples as tests Using this flag looks like this:"} {"_id":"doc-en-rust-b500e8fcca0a640ce59f9b49dc2ee85177e3f13ff37d2e1c70e2f680208d44e7","title":"","text":"command line options from it. These options are one per line; a blank line indicates an empty option. The file can use Unix or Windows style line endings, and must be encoded as UTF-8. ## `--passes`: add more rustdoc passes This flag is **deprecated**. For more details on passes, see [the chapter on them](passes.md). ## `--no-defaults`: don't run default passes This flag is **deprecated**. For more details on passes, see [the chapter on them](passes.md). ## `-r`/`--input-format`: input format This flag is **deprecated** and **has no effect**. Rustdoc only supports Rust source code and Markdown input formats. If the file ends in `.md` or `.markdown`, `rustdoc` treats it as a Markdown file. Otherwise, it assumes that the input file is Rust. "} {"_id":"doc-en-rust-2f234221f8496a04929c6a7548c443673d985a017fdd39a22c153505bc9e4623","title":"","text":"Rustdoc has a concept called \"passes\". These are transformations that `rustdoc` runs on your documentation before producing its final output. In addition to the passes below, check out the docs for these flags: Customizing passes is **deprecated**. The available passes are not considered stable and may change in any release. * [`--passes`](command-line-arguments.md#--passes-add-more-rustdoc-passes) * [`--no-defaults`](command-line-arguments.md#--no-defaults-dont-run-default-passes) ## Default passes By default, rustdoc will run some passes, namely: * `strip-hidden` * `strip-private` * `collapse-docs` * `unindent-comments` However, `strip-private` implies `strip-priv-imports`, and so effectively, all passes are run by default. ## `strip-hidden` This pass implements the `#[doc(hidden)]` attribute. When this pass runs, it checks each item, and if it is annotated with this attribute, it removes it from `rustdoc`'s output. Without this pass, these items will remain in the output. ## `unindent-comments` When you write a doc comment like this: ```rust,no_run /// This is a documentation comment. # fn f() {} ``` There's a space between the `///` and that `T`. That spacing isn't intended to be a part of the output; it's there for humans, to help separate the doc comment syntax from the text of the comment. This pass is what removes that space. The exact rules are left under-specified so that we can fix issues that we find. Without this pass, the exact number of spaces is preserved. ## `collapse-docs` With this pass, multiple `#[doc]` attributes are converted into one single documentation string. For example: ```rust,no_run #[doc = \"This is the first line.\"] #[doc = \"This is the second line.\"] # fn f() {} ``` Gets collapsed into a single doc string of ```text This is the first line. This is the second line. ``` ## `strip-private` This removes documentation for any non-public items, so for example: ```rust,no_run /// These are private docs. struct Private; /// These are public docs. pub struct Public; ``` This pass removes the docs for `Private`, since they're not public. This pass implies `strip-priv-imports`. ## `strip-priv-imports` This is the same as `strip-private`, but for `extern crate` and `use` statements instead of items. In the past the most common use case for customizing passes was to omit the `strip-private` pass. You can do this more easily, and without risk of the pass being changed, by passing [`--document-private-items`](./unstable-features.md#--document-private-items). "} {"_id":"doc-en-rust-7746ce03fc849f96ef031973a7ea03857c6074522c070a980c6822b383ba222e","title":"","text":"Public items that are not documented can be seen with the built-in `missing_docs` lint. Private items that are not documented can be seen with Clippy's `missing_docs_in_private_items` lint. ## `-w`/`--output-format`: output format When using [`--show-coverage`](https://doc.rust-lang.org/nightly/rustdoc/unstable-features.html#--show-coverage-get-statistics-about-code-documentation-coverage), passing `--output-format json` will display the coverage information in JSON format. For example, here is the JSON for a file with one documented item and one undocumented item: ```rust /// This item has documentation pub fn foo() {} pub fn no_documentation() {} ``` ```json {\"no_std.rs\":{\"total\":3,\"with_docs\":1,\"total_examples\":3,\"with_examples\":0}} ``` Note that the third item is the crate root, which in this case is undocumented. When not using `--show-coverage`, `--output-format json` emits documentation in the experimental [JSON format](https://github.com/rust-lang/rfcs/pull/2963). `--output-format html` has no effect, and is also accepted on stable toolchains. ### `--enable-per-target-ignores`: allow `ignore-foo` style filters for doctests Using this flag looks like this:"} {"_id":"doc-en-rust-adff4a978196666cc4e8dfdc46f9eec1c6f577f5a5920158a6f88d7f7c435c3e","title":"","text":"} impl Attribute { #[inline] pub fn has_name(&self, name: Symbol) -> bool { match self.kind { AttrKind::Normal(ref item, _) => item.path == name,"} {"_id":"doc-en-rust-5e81c75718f40a733f3cde27c32c51a7588108a36c9e79ddd8b4d94d83e365d3","title":"","text":"use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_ast::{Attribute, LitKind, NestedMetaItem}; use rustc_ast::{Attribute, Lit, LitKind, NestedMetaItem}; use rustc_errors::{pluralize, struct_span_err}; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId;"} {"_id":"doc-en-rust-2c9b7e731b7fd070882cc9cee8f6a4f8ca96a89f479edcdb5a4e7f1ffe6229b6","title":"","text":"self.check_export_name(hir_id, &attr, span, target) } else if self.tcx.sess.check_name(attr, sym::rustc_args_required_const) { self.check_rustc_args_required_const(&attr, span, target, item) } else if self.tcx.sess.check_name(attr, sym::rustc_layout_scalar_valid_range_start) { self.check_rustc_layout_scalar_valid_range(&attr, span, target) } else if self.tcx.sess.check_name(attr, sym::rustc_layout_scalar_valid_range_end) { self.check_rustc_layout_scalar_valid_range(&attr, span, target) } else if self.tcx.sess.check_name(attr, sym::allow_internal_unstable) { self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs) } else if self.tcx.sess.check_name(attr, sym::rustc_allow_const_fn_unstable) {"} {"_id":"doc-en-rust-7d269aec264b68c4821978f5192430f464692b54eeb297e5545d8913ddb07c38","title":"","text":"} } fn check_rustc_layout_scalar_valid_range( &self, attr: &Attribute, span: &Span, target: Target, ) -> bool { if target != Target::Struct { self.tcx .sess .struct_span_err(attr.span, \"attribute should be applied to a struct\") .span_label(*span, \"not a struct\") .emit(); return false; } let list = match attr.meta_item_list() { None => return false, Some(it) => it, }; if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) { true } else { self.tcx .sess .struct_span_err(attr.span, \"expected exactly one integer literal argument\") .emit(); false } } /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument. fn check_rustc_legacy_const_generics( &self,"} {"_id":"doc-en-rust-4d3a9b065ab2c1e56c71e060826c8a544b66708350201e41bc62fdbb7aec16e6","title":"","text":" #![feature(rustc_attrs)] #[rustc_layout_scalar_valid_range_start(u32::MAX)] //~ ERROR pub struct A(u32); #[rustc_layout_scalar_valid_range_end(1, 2)] //~ ERROR pub struct B(u8); #[rustc_layout_scalar_valid_range_end(a = \"a\")] //~ ERROR pub struct C(i32); #[rustc_layout_scalar_valid_range_end(1)] //~ ERROR enum E { X = 1, Y = 14, } fn main() { let _ = A(0); let _ = B(0); let _ = C(0); let _ = E::X; } "} {"_id":"doc-en-rust-49d2057271117b8937cac199ef2a497c0532ec8c4ffcc5613805330fa1db1e00","title":"","text":" error: expected exactly one integer literal argument --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:3:1 | LL | #[rustc_layout_scalar_valid_range_start(u32::MAX)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: expected exactly one integer literal argument --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:6:1 | LL | #[rustc_layout_scalar_valid_range_end(1, 2)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: expected exactly one integer literal argument --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:9:1 | LL | #[rustc_layout_scalar_valid_range_end(a = \"a\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: attribute should be applied to a struct --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:12:1 | LL | #[rustc_layout_scalar_valid_range_end(1)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | / enum E { LL | | X = 1, LL | | Y = 14, LL | | } | |_- not a struct error: aborting due to 4 previous errors "} {"_id":"doc-en-rust-31c622facdc72b8fcd4e850ae1de7a1984f801da60ca944a7470b984e759ab8c","title":"","text":"cx.generated_synthetics.insert((ty, trait_def_id)); let hir_imp = impl_def_id.as_local() .map(|local| cx.tcx.hir().expect_item(local)) .and_then(|item| if let hir::ItemKind::Impl(i) = &item.kind { Some(i) } else { None }); let items = match hir_imp { Some(imp) => imp .items .iter() .map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)) .collect::>(), None => cx.tcx .associated_items(impl_def_id) .in_definition_order() .map(|x| x.clean(cx)) .collect::>(), }; impls.push(Item { name: None, attrs: Default::default(),"} {"_id":"doc-en-rust-5c497fcdc8ed4419bfdba7d08965a0a93b521ccf18f5bed3c152ff98e45b3fbb","title":"","text":"// the post-inference `trait_ref`, as it's more accurate. trait_: Some(trait_ref.clean(cx)), for_: ty.clean(cx), items: cx .tcx .associated_items(impl_def_id) .in_definition_order() .map(|x| x.clean(cx)) .collect::>(), items, polarity: ty::ImplPolarity::Positive, kind: ImplKind::Blanket(box trait_ref.self_ty().clean(cx)), }),"} {"_id":"doc-en-rust-1a1161b7ce6350c3983e6d83cf960c55f8d1e54eb1af8ee22e6cecbf3c1bade3","title":"","text":"/// the hashmap because certain items (traits and types) need to have their mappings for trait /// implementations filled out before they're inserted. fn item(&mut self, item: clean::Item) -> Result<(), Error> { let local_blanket_impl = match item.def_id { clean::ItemId::Blanket { impl_id, .. } => impl_id.is_local(), clean::ItemId::Auto { .. } | clean::ItemId::DefId(_) | clean::ItemId::Primitive(_, _) => false, }; // Flatten items that recursively store other items // FIXME(CraftSpider): We skip children of local blanket implementations, as we'll have // already seen the actual generic impl, and the generated ones don't need documenting. // This is necessary due to the visibility, return type, and self arg of the generated // impls not quite matching, and will no longer be necessary when the mismatch is fixed. if !local_blanket_impl { item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap()); } item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap()); let id = item.def_id; if let Some(mut new_item) = self.convert_item(item) {"} {"_id":"doc-en-rust-4911a8bf87fd99b511f8624a3b3387ab21fb441f28cd25ff92d20b1d431f4ed6","title":"","text":"// @has blanket_with_local.json \"$.index[*][?(@.name=='Load')]\" pub trait Load { // @has - \"$.index[*][?(@.name=='load')]\" fn load() {} // @has - \"$.index[*][?(@.name=='write')]\" fn write(self) {} } impl

Load for P { fn load() {} fn write(self) {} } // @has - \"$.index[*][?(@.name=='Wrapper')]\""} {"_id":"doc-en-rust-34f39b92ade460ebf59e93ba3b7ab647f1c152de64991f80126c952936fd111a","title":"","text":"use option::{Option,Some,None}; use libc::c_void; use ops::Drop; use util::NonCopyable; /** * A simple atomic flag, that can be set and cleared. The most basic atomic type. */ pub struct AtomicFlag { priv v: int priv v: int, priv nocopy: NonCopyable } /** * An atomic boolean type. */ pub struct AtomicBool { priv v: uint priv v: uint, priv nocopy: NonCopyable } /** * A signed atomic integer type, supporting basic atomic arithmetic operations */ pub struct AtomicInt { priv v: int priv v: int, priv nocopy: NonCopyable } /** * An unsigned atomic integer type, supporting basic atomic arithmetic operations */ pub struct AtomicUint { priv v: uint priv v: uint, priv nocopy: NonCopyable } /** * An unsafe atomic pointer. Only supports basic atomic operations */ pub struct AtomicPtr { priv p: *mut T priv p: *mut T, priv nocopy: NonCopyable } /**"} {"_id":"doc-en-rust-4812e8d640f01084ec73f82a644fe26d8d82aad7355a7335235732ed3dd0fe96","title":"","text":"SeqCst } pub static INIT_ATOMIC_FLAG : AtomicFlag = AtomicFlag { v: 0 }; pub static INIT_ATOMIC_BOOL : AtomicBool = AtomicBool { v: 0 }; pub static INIT_ATOMIC_INT : AtomicInt = AtomicInt { v: 0 }; pub static INIT_ATOMIC_UINT : AtomicUint = AtomicUint { v: 0 }; pub static INIT_ATOMIC_FLAG : AtomicFlag = AtomicFlag { v: 0, nocopy: NonCopyable }; pub static INIT_ATOMIC_BOOL : AtomicBool = AtomicBool { v: 0, nocopy: NonCopyable }; pub static INIT_ATOMIC_INT : AtomicInt = AtomicInt { v: 0, nocopy: NonCopyable }; pub static INIT_ATOMIC_UINT : AtomicUint = AtomicUint { v: 0, nocopy: NonCopyable }; impl AtomicFlag { pub fn new() -> AtomicFlag { AtomicFlag { v: 0 } AtomicFlag { v: 0, nocopy: NonCopyable } } /**"} {"_id":"doc-en-rust-5dd67b7960b9163fa2327edd1c3cd64d0f7843e3a53d1b90143b4b9bf77e3384","title":"","text":"impl AtomicBool { pub fn new(v: bool) -> AtomicBool { AtomicBool { v: if v { 1 } else { 0 } } AtomicBool { v: if v { 1 } else { 0 }, nocopy: NonCopyable } } #[inline]"} {"_id":"doc-en-rust-419b4f209ff9c898c3ac1d341e0bb44190fd2779004f25c1a2ab51bdd62fce99","title":"","text":"impl AtomicInt { pub fn new(v: int) -> AtomicInt { AtomicInt { v:v } AtomicInt { v:v, nocopy: NonCopyable } } #[inline]"} {"_id":"doc-en-rust-daa7581ccedd4230aafee0fe52f0f8c82750f167069624af37efeca5a2e14f77","title":"","text":"impl AtomicUint { pub fn new(v: uint) -> AtomicUint { AtomicUint { v:v } AtomicUint { v:v, nocopy: NonCopyable } } #[inline]"} {"_id":"doc-en-rust-4e3f2e2480ac496c0a8663bb594c68378c17f3099d1f5bd009071418b4f852ed","title":"","text":"impl AtomicPtr { pub fn new(p: *mut T) -> AtomicPtr { AtomicPtr { p:p } AtomicPtr { p:p, nocopy: NonCopyable } } #[inline]"} {"_id":"doc-en-rust-6dde38dac5ca653d96950d7fbe5c1be7593fae641a19415a7ac9ba73aa5a972d","title":"","text":" // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Issue #8380 #[feature(globs)]; use std::unstable::atomics::*; use std::ptr; fn main() { let x = INIT_ATOMIC_FLAG; let x = *&x; //~ ERROR: cannot move out of dereference let x = INIT_ATOMIC_BOOL; let x = *&x; //~ ERROR: cannot move out of dereference let x = INIT_ATOMIC_INT; let x = *&x; //~ ERROR: cannot move out of dereference let x = INIT_ATOMIC_UINT; let x = *&x; //~ ERROR: cannot move out of dereference let x: AtomicPtr = AtomicPtr::new(ptr::mut_null()); let x = *&x; //~ ERROR: cannot move out of dereference let x: AtomicOption = AtomicOption::empty(); let x = *&x; //~ ERROR: cannot move out of dereference } "} {"_id":"doc-en-rust-d9a2349486f2ac83809e118eb65e5628c07d9ef0290f05b8fc83a2cad08dce5d","title":"","text":"debug!(\"QueryNormalizer: result = {:#?}\", result); debug!(\"QueryNormalizer: obligations = {:#?}\", obligations); self.obligations.extend(obligations); Ok(result.normalized_ty) let res = result.normalized_ty; // `tcx.normalize_projection_ty` may normalize to a type that still has // unevaluated consts, so keep normalizing here if that's the case. if res != ty && res.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) { Ok(res.try_super_fold_with(self)?) } else { Ok(res) } } ty::Projection(data) => {"} {"_id":"doc-en-rust-4c10c20c68f52310151407fb648a283b0193d57cbb627454ddf2c7b38265bac5","title":"","text":"debug!(\"QueryNormalizer: result = {:#?}\", result); debug!(\"QueryNormalizer: obligations = {:#?}\", obligations); self.obligations.extend(obligations); Ok(crate::traits::project::PlaceholderReplacer::replace_placeholders( let res = crate::traits::project::PlaceholderReplacer::replace_placeholders( infcx, mapped_regions, mapped_types, mapped_consts, &self.universes, result.normalized_ty, )) ); // `tcx.normalize_projection_ty` may normalize to a type that still has // unevaluated consts, so keep normalizing here if that's the case. if res != ty && res.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) { Ok(res.try_super_fold_with(self)?) } else { Ok(res) } } _ => ty.try_super_fold_with(self), })()?; self.cache.insert(ty, res); Ok(res) }"} {"_id":"doc-en-rust-9e0d2963a7063282ea1c541378620b0b8f5ffe1cd3cf1273acc25503d9508e5d","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] trait TraitOne { const MY_NUM: usize; type MyErr: std::fmt::Debug; fn do_one_stuff(arr: [u8; Self::MY_NUM]) -> Result<(), Self::MyErr>; } trait TraitTwo { fn do_two_stuff(); } impl TraitTwo for O where [(); Self::MY_NUM]:, { fn do_two_stuff() { O::do_one_stuff([5; Self::MY_NUM]).unwrap() } } struct Blargotron; #[derive(Debug)] struct ErrTy([(); N]); impl TraitOne for Blargotron { const MY_NUM: usize = 3; type MyErr = ErrTy<{ Self::MY_NUM }>; fn do_one_stuff(_arr: [u8; Self::MY_NUM]) -> Result<(), Self::MyErr> { Ok(()) } } fn main() { Blargotron::do_two_stuff(); } "} {"_id":"doc-en-rust-4ef1badb8b4e66a0481061d956ea2f925348b4208a4892dc4ac9306eca0f0830","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] use std::convert::AsMut; use std::default::Default; trait Foo: Sized { type Baz: Default + AsMut<[u8]>; fn bar() { Self::Baz::default().as_mut(); } } impl Foo for () { type Baz = [u8; 1 * 1]; //type Baz = [u8; 1]; } fn main() { <() as Foo>::bar(); } "} {"_id":"doc-en-rust-60d8c8ca4707ea67dfc47eb24b5a64bf3b33eda5b8e60fc1d1e31bdd9a29cff4","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] trait Collate { type Pass; type Fail; fn collate(self) -> (Self::Pass, Self::Fail); } impl Collate for () { type Pass = (); type Fail = (); fn collate(self) -> ((), ()) { ((), ()) } } trait CollateStep { type Pass; type Fail; fn collate_step(x: X, prev: Prev) -> (Self::Pass, Self::Fail); } impl CollateStep for () { type Pass = (X, P); type Fail = F; fn collate_step(x: X, (p, f): (P, F)) -> ((X, P), F) { ((x, p), f) } } struct CollateOpImpl; trait CollateOpStep { type NextOp; type Apply; } impl CollateOpStep for CollateOpImpl where CollateOpImpl<{ MASK >> 1 }>: Sized, { type NextOp = CollateOpImpl<{ MASK >> 1 }>; type Apply = (); } impl Collate for (H, T) where T: Collate, Op::Apply: CollateStep, { type Pass = >::Pass; type Fail = >::Fail; fn collate(self) -> (Self::Pass, Self::Fail) { >::collate_step(self.0, self.1.collate()) } } fn collate(x: X) -> (X::Pass, X::Fail) where X: Collate>, { x.collate() } fn main() { dbg!(collate::<_, 5>((\"Hello\", (42, ('!', ()))))); } "} {"_id":"doc-en-rust-dbbb603c5fcc6d5c259f92dbcb0a72c4326cd35c656ab9df4213724672071c38","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] pub trait Foo { fn foo(&self); } pub struct FooImpl; impl Foo for FooImpl { fn foo(&self) {} } pub trait Bar: 'static { type Foo: Foo; fn get() -> &'static Self::Foo; } struct BarImpl; impl Bar for BarImpl { type Foo = FooImpl< { { 4 } }, >; fn get() -> &'static Self::Foo { &FooImpl } } pub fn boom() { B::get().foo(); } fn main() { boom::(); } "} {"_id":"doc-en-rust-384001e7b0aaedf7cb8681fc4e0450067900e9fcf6c15abef529b28445d22f31","title":"","text":" // build-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] trait Foo { type Output; fn foo() -> Self::Output; } impl Foo for [u8; 3] { type Output = [u8; 1 + 2]; fn foo() -> [u8; 3] { [1u8; 3] } } fn bug() where [u8; N]: Foo, <[u8; N] as Foo>::Output: AsRef<[u8]>, { <[u8; N]>::foo().as_ref(); } fn main() { bug::<3>(); } "} {"_id":"doc-en-rust-d6238cb6db88702eea712aa5a0b07b35fcd2b219ef44271d00151cb8860d3698","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] use std::marker::PhantomData; fn main() { let x = FooImpl::> { phantom: PhantomData }; let _ = x.foo::>(); } trait Foo where T: Bar, { fn foo(&self) where T: Operation, >::Output: Bar; } struct FooImpl where T: Bar, { phantom: PhantomData, } impl Foo for FooImpl where T: Bar, { fn foo(&self) where T: Operation, >::Output: Bar, { <>::Output as Bar>::error_occurs_here(); } } trait Bar { fn error_occurs_here(); } struct BarImpl; impl Bar for BarImpl { fn error_occurs_here() {} } trait Operation { type Output; } //// Part-A: This causes error. impl Operation> for BarImpl where BarImpl<{ N + M }>: Sized, { type Output = BarImpl<{ N + M }>; } //// Part-B: This doesn't cause error. // impl Operation> for BarImpl { // type Output = BarImpl; // } //// Part-C: This also doesn't cause error. // impl Operation> for BarImpl { // type Output = BarImpl<{ M }>; // } "} {"_id":"doc-en-rust-51560eba3372fdaf78e28a389100654225c3c637ee0aa11222e49de2e8feb0df","title":"","text":"Res::Def(DefKind::Ctor(..), def_id) => { tcx.generics_of(tcx.parent(def_id).unwrap()) } Res::Def(_, def_id) => tcx.generics_of(def_id), // Other `DefKind`s don't have generics and would ICE when calling // `generics_of`. Res::Def( DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Variant | DefKind::Trait | DefKind::OpaqueTy | DefKind::TyAlias | DefKind::ForeignTy | DefKind::TraitAlias | DefKind::AssocTy | DefKind::Fn | DefKind::AssocFn | DefKind::AssocConst | DefKind::Impl, def_id, ) => tcx.generics_of(def_id), Res::Err => { tcx.sess.delay_span_bug(tcx.def_span(def_id), \"anon const with Res::Err\"); return None;"} {"_id":"doc-en-rust-a57caad4b1755d364f1164806fe5c5eb3904774d5502a52d899c30d05a63a20e","title":"","text":" fn f() { std::<0>; //~ ERROR expected value } fn j() { std::<_ as _>; //~ ERROR expected value //~^ ERROR expected one of `,` or `>`, found keyword `as` } fn main () {} "} {"_id":"doc-en-rust-50bb1eaf1243b6f88f1737573bcbfbe7586f57ed413e13943fc99408b8fd99c1","title":"","text":" error: expected one of `,` or `>`, found keyword `as` --> $DIR/issue-84831.rs:5:13 | LL | std::<_ as _>; | ^^ expected one of `,` or `>` | help: expressions must be enclosed in braces to be used as const generic arguments | LL | std::<{ _ as _ }>; | ^ ^ error[E0423]: expected value, found crate `std` --> $DIR/issue-84831.rs:2:5 | LL | std::<0>; | ^^^^^^^^ not a value error[E0423]: expected value, found crate `std` --> $DIR/issue-84831.rs:5:5 | LL | std::<_ as _>; | ^^^^^^^^^^^^^ not a value error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0423`. "} {"_id":"doc-en-rust-0017db5581aa46c8b0c0fe879064730dd5bb916643b06adec2109a7c8186c92b","title":"","text":"E0782: include_str!(\"./error_codes/E0782.md\"), E0783: include_str!(\"./error_codes/E0783.md\"), E0784: include_str!(\"./error_codes/E0784.md\"), E0785: include_str!(\"./error_codes/E0785.md\"), ; // E0006, // merged with E0005 // E0008, // cannot bind by-move into a pattern guard"} {"_id":"doc-en-rust-3c2e6e20ac2c33f651dedcc82cbb0a4b261ea8422447ecda6ad11b0427d48f32","title":"","text":" An inherent `impl` was written on a dyn auto trait. Erroneous code example: ```compile_fail,E0785 #![feature(auto_traits)] auto trait AutoTrait {} impl dyn AutoTrait {} ``` Dyn objects allow any number of auto traits, plus at most one non-auto trait. The non-auto trait becomes the \"principal trait\". When checking if an impl on a dyn trait is coherent, the principal trait is normally the only one considered. Since the erroneous code has no principal trait, it cannot be implemented at all. Working example: ``` #![feature(auto_traits)] trait PrincipalTrait {} auto trait AutoTrait {} impl dyn PrincipalTrait + AutoTrait + Send {} ``` "} {"_id":"doc-en-rust-a34b1dfbe4301ed4092cc4baaf5dcaff2e179fc99332d7e1cbb45b31e3745f98","title":"","text":"ty::Dynamic(ref data, ..) if data.principal_def_id().is_some() => { self.check_def_id(item, data.principal_def_id().unwrap()); } ty::Dynamic(..) => { struct_span_err!( self.tcx.sess, ty.span, E0785, \"cannot define inherent `impl` for a dyn auto trait\" ) .span_label(ty.span, \"impl requires at least one non-auto trait\") .note(\"define and implement a new trait or type instead\") .emit(); } ty::Bool => { self.check_primitive_impl( item.def_id,"} {"_id":"doc-en-rust-c7402a8d2c6e45fc7f595422a72bb379b7f98daa44f6bc9257da075f3e44fcb6","title":"","text":" #![feature(auto_traits)] auto trait AutoTrait {} // You cannot impl your own `dyn AutoTrait`. impl dyn AutoTrait {} //~ERROR E0785 // You cannot impl someone else's `dyn AutoTrait` impl dyn Unpin {} //~ERROR E0785 fn main() {} "} {"_id":"doc-en-rust-d683066e98f28414eb67e7c58963ff11a2ed0e6bdf89820b2a8eb13a4d470994","title":"","text":" error[E0785]: cannot define inherent `impl` for a dyn auto trait --> $DIR/issue-85026.rs:5:6 | LL | impl dyn AutoTrait {} | ^^^^^^^^^^^^^ impl requires at least one non-auto trait | = note: define and implement a new trait or type instead error[E0785]: cannot define inherent `impl` for a dyn auto trait --> $DIR/issue-85026.rs:8:6 | LL | impl dyn Unpin {} | ^^^^^^^^^ impl requires at least one non-auto trait | = note: define and implement a new trait or type instead error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0785`. "} {"_id":"doc-en-rust-69268c69dcb19a27797991b1f4c570463dd11dd4155165debf7408d176ecfa83","title":"","text":"from rust_types import * rust_enabled = 'set language rust' in gdb.execute('complete set language ru', to_string=True) _gdb_version_matched = re.search('([0-9]+).([0-9]+)', gdb.VERSION) gdb_version = [int(num) for num in _gdb_version_matched.groups()] if _gdb_version_matched else []"} {"_id":"doc-en-rust-6eb393869e19e2a16dec31c6998eaf7effd3fffd86303c674f6b5c847c82cc40","title":"","text":"return StdStringProvider(valobj) if rust_type == RustType.STD_OS_STRING: return StdOsStringProvider(valobj) if rust_type == RustType.STD_STR and not rust_enabled: if rust_type == RustType.STD_STR: return StdStrProvider(valobj) if rust_type == RustType.STD_SLICE: return StdSliceProvider(valobj) if rust_type == RustType.STD_VEC: return StdVecProvider(valobj) if rust_type == RustType.STD_VEC_DEQUE:"} {"_id":"doc-en-rust-b49c22e8eb441cfafad6c8bab04e8970f08302baecf7b4231cd5d45a1780eac5","title":"","text":"def display_hint(): return \"string\" def _enumerate_array_elements(element_ptrs): for (i, element_ptr) in enumerate(element_ptrs): key = \"[{}]\".format(i) element = element_ptr.dereference() try: # rust-lang/rust#64343: passing deref expr to `str` allows # catching exception on garbage pointer str(element) except RuntimeError: yield key, \"inaccessible\" break yield key, element class StdSliceProvider: def __init__(self, valobj): self.valobj = valobj self.length = int(valobj[\"length\"]) self.data_ptr = valobj[\"data_ptr\"] def to_string(self): return \"{}(size={})\".format(self.valobj.type, self.length) def children(self): return _enumerate_array_elements( self.data_ptr + index for index in xrange(self.length) ) @staticmethod def display_hint(): return \"array\" class StdVecProvider: def __init__(self, valobj):"} {"_id":"doc-en-rust-0944d690bdf67f8414320d97df644ec7553108bc853345b340c653fdaeee56f2","title":"","text":"return \"Vec(size={})\".format(self.length) def children(self): saw_inaccessible = False for index in xrange(self.length): element_ptr = self.data_ptr + index if saw_inaccessible: return try: # rust-lang/rust#64343: passing deref expr to `str` allows # catching exception on garbage pointer str(element_ptr.dereference()) yield \"[{}]\".format(index), element_ptr.dereference() except RuntimeError: saw_inaccessible = True yield str(index), \"inaccessible\" return _enumerate_array_elements( self.data_ptr + index for index in xrange(self.length) ) @staticmethod def display_hint():"} {"_id":"doc-en-rust-916a6f7d7487df6c130bb4d95b289ef511da24af7ef2e8d6c6c1f5dc19972169","title":"","text":"return \"VecDeque(size={})\".format(self.size) def children(self): for index in xrange(0, self.size): value = (self.data_ptr + ((self.tail + index) % self.cap)).dereference() yield \"[{}]\".format(index), value return _enumerate_array_elements( (self.data_ptr + ((self.tail + index) % self.cap)) for index in xrange(self.size) ) @staticmethod def display_hint():"} {"_id":"doc-en-rust-9f09e31da0b69e213d3ddda94fe8f9005fd5b2459bf4c1551062d6937839c8b7","title":"","text":"type synthetic add -l lldb_lookup.synthetic_lookup -x \".*\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^(alloc::([a-z_]+::)+)String$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^&str$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^&[.+]$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^&(mut )?str$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^&(mut )?[.+]$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^(std::ffi::([a-z_]+::)+)OsString$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^(alloc::([a-z_]+::)+)Vec<.+>$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^(alloc::([a-z_]+::)+)VecDeque<.+>$\" --category Rust"} {"_id":"doc-en-rust-cf1fb542c2e6482320af55d7369db201d1983ed4161fb941fdfb2d1d509a8227","title":"","text":"STD_STRING_REGEX = re.compile(r\"^(alloc::(w+::)+)String$\") STD_STR_REGEX = re.compile(r\"^&str$\") STD_SLICE_REGEX = re.compile(r\"^&[.+]$\") STD_STR_REGEX = re.compile(r\"^&(mut )?str$\") STD_SLICE_REGEX = re.compile(r\"^&(mut )?[.+]$\") STD_OS_STRING_REGEX = re.compile(r\"^(std::ffi::(w+::)+)OsString$\") STD_VEC_REGEX = re.compile(r\"^(alloc::(w+::)+)Vec<.+>$\") STD_VEC_DEQUE_REGEX = re.compile(r\"^(alloc::(w+::)+)VecDeque<.+>$\")"} {"_id":"doc-en-rust-7d2ca41e3f9bb1854bf0777a9a49f87d1d9b18cac1701f50b995b7d77ad4c1cd","title":"","text":"// gdb-check:$1 = Vec(size=1000000000) = {[...]...} // gdb-command: print slice // gdb-check:$2 = &[u8] {data_ptr: [...], length: 1000000000} // gdb-check:$2 = &[u8](size=1000000000) = {[...]...} #![allow(unused_variables)]"} {"_id":"doc-en-rust-264e1d67b5d583f3ea6cd3f1a1e0f1c7682fd990c9cc905b53ade79fce73a3da","title":"","text":" // ignore-android: FIXME(#10381) // ignore-windows // compile-flags:-g // gdb-command: run // gdb-command: print slice // gdbg-check: $1 = struct &[i32](size=3) = {0, 1, 2} // gdbr-check: $1 = &[i32](size=3) = {0, 1, 2} // gdb-command: print mut_slice // gdbg-check: $2 = struct &mut [i32](size=4) = {2, 3, 5, 7} // gdbr-check: $2 = &mut [i32](size=4) = {2, 3, 5, 7} // gdb-command: print str_slice // gdb-check: $3 = \"string slice\" // gdb-command: print mut_str_slice // gdb-check: $4 = \"mutable string slice\" // lldb-command: run // lldb-command: print slice // lldb-check: (&[i32]) $0 = size=3 { [0] = 0 [1] = 1 [2] = 2 } // lldb-command: print mut_slice // lldb-check: (&mut [i32]) $1 = size=4 { [0] = 2 [1] = 3 [2] = 5 [3] = 7 } // lldb-command: print str_slice // lldb-check: (&str) $2 = \"string slice\" { data_ptr = [...] length = 12 } // lldb-command: print mut_str_slice // lldb-check: (&mut str) $3 = \"mutable string slice\" { data_ptr = [...] length = 20 } fn b() {} fn main() { let slice: &[i32] = &[0, 1, 2]; let mut_slice: &mut [i32] = &mut [2, 3, 5, 7]; let str_slice: &str = \"string slice\"; let mut mut_str_slice_buffer = String::from(\"mutable string slice\"); let mut_str_slice: &mut str = mut_str_slice_buffer.as_mut_str(); b(); // #break } "} {"_id":"doc-en-rust-a72bcf840c235280dc1c9fb6804ff3558def0e137298f0bcb8d6e68c515d3579","title":"","text":"let rust_type_regexes = vec![ \"^(alloc::([a-z_]+::)+)String$\", \"^&str$\", \"^&[.+]$\", \"^&(mut )?str$\", \"^&(mut )?[.+]$\", \"^(std::ffi::([a-z_]+::)+)OsString$\", \"^(alloc::([a-z_]+::)+)Vec<.+>$\", \"^(alloc::([a-z_]+::)+)VecDeque<.+>$\","} {"_id":"doc-en-rust-e0157fad0203f30e5f08898b7219d22d3dc3eb656861a1f055ad0bcad625549e","title":"","text":" Version 1.54.0 (2021-07-29) ============================ Language ----------------------- - [You can now use macros for values in built-in attribute macros.][83366] While a seemingly minor addition on its own, this enables a lot of powerful functionality when combined correctly. Most notably you can now include external documentation in your crate by writing the following. ```rust #![doc = include_str!(\"README.md\")] ``` You can also use this to include auto-generated modules: ```rust #[path = concat!(env!(\"OUT_DIR\"), \"/generated.rs\")] mod generated; ``` - [You can now cast between unsized slice types (and types which contain unsized slices) in `const fn`.][85078] - [You can now use multiple generic lifetimes with `impl Trait` where the lifetimes don't explicitly outlive another.][84701] In code this means that you can now have `impl Trait<'a, 'b>` where as before you could only have `impl Trait<'a, 'b> where 'b: 'a`. Compiler ----------------------- - [Rustc will now search for custom JSON targets in `/lib/rustlib//target.json` where `/` is the \"sysroot\" directory.][83800] You can find your sysroot directory by running `rustc --print sysroot`. - [Added `wasm` as a `target_family` for WebAssembly platforms.][84072] - [You can now use `#[target_feature]` on safe functions when targeting WebAssembly platforms.][84988] - [Improved debugger output for enums on Windows MSVC platforms.][85292] - [Added tier 3* support for `bpfel-unknown-none` and `bpfeb-unknown-none`.][79608] * Refer to Rust's [platform support page][platform-support-doc] for more information on Rust's tiered platform support. Libraries ----------------------- - [`panic::panic_any` will now `#[track_caller]`.][85745] - [Added `OutOfMemory` as a variant of `io::ErrorKind`.][84744] - [ `proc_macro::Literal` now implements `FromStr`.][84717] - [The implementations of vendor intrinsics in core::arch have been significantly refactored.][83278] The main user-visible changes are a 50% reduction in the size of libcore.rlib and stricter validation of constant operands passed to intrinsics. The latter is technically a breaking change, but allows Rust to more closely match the C vendor intrinsics API. Stabilized APIs --------------- - [`BTreeMap::into_keys`] - [`BTreeMap::into_values`] - [`HashMap::into_keys`] - [`HashMap::into_values`] - [`arch::wasm32`] - [`VecDeque::binary_search`] - [`VecDeque::binary_search_by`] - [`VecDeque::binary_search_by_key`] - [`VecDeque::partition_point`] Cargo ----------------------- - [Added the `--prune ` option to `cargo-tree` to remove a package from the dependency graph.][cargo/9520] - [Added the `--depth` option to `cargo-tree` to print only to a certain depth in the tree ][cargo/9499] - [Added the `no-proc-macro` value to `cargo-tree --edges` to hide procedural macro dependencies.][cargo/9488] - [A new environment variable named `CARGO_TARGET_TMPDIR` is available.][cargo/9375] This variable points to a directory that integration tests and benches can use as a \"scratchpad\" for testing filesystem operations. [79608]: https://github.com/rust-lang/rust/pull/79608 [84988]: https://github.com/rust-lang/rust/pull/84988 [84701]: https://github.com/rust-lang/rust/pull/84701 [84072]: https://github.com/rust-lang/rust/pull/84072 [85745]: https://github.com/rust-lang/rust/pull/85745 [84744]: https://github.com/rust-lang/rust/pull/84744 [85078]: https://github.com/rust-lang/rust/pull/85078 [84717]: https://github.com/rust-lang/rust/pull/84717 [83800]: https://github.com/rust-lang/rust/pull/83800 [83366]: https://github.com/rust-lang/rust/pull/83366 [83278]: https://github.com/rust-lang/rust/pull/83278 [85292]: https://github.com/rust-lang/rust/pull/85292 [cargo/9520]: https://github.com/rust-lang/cargo/pull/9520 [cargo/9499]: https://github.com/rust-lang/cargo/pull/9499 [cargo/9488]: https://github.com/rust-lang/cargo/pull/9488 [cargo/9375]: https://github.com/rust-lang/cargo/pull/9375 [`BTreeMap::into_keys`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.into_keys [`BTreeMap::into_values`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.into_values [`HashMap::into_keys`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.into_keys [`HashMap::into_values`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.into_values [`arch::wasm32`]: https://doc.rust-lang.org/core/arch/wasm32/index.html [`VecDeque::binary_search`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search [`VecDeque::binary_search_by`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search_by [`VecDeque::binary_search_by_key`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.binary_search_by_key [`VecDeque::partition_point`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html#method.partition_point Version 1.53.0 (2021-06-17) ============================"} {"_id":"doc-en-rust-4f4e475060d01aad503266148346122aefa7138eae067dab14bf903d7f9f42c8","title":"","text":"- [You can now use `#[repr(transparent)]` on univariant `enum`s.][68122] Meaning that you can create an enum that has the exact layout and ABI of the type it contains. - [You can now use outer attribute procedural macros on inline modules.][64273] - [You can now use outer attribute procedural macros on inline modules.][64273] - [There are some *syntax-only* changes:][67131] - `default` is syntactically allowed before items in `trait` definitions. - Items in `impl`s (i.e. `const`s, `type`s, and `fn`s) may syntactically"} {"_id":"doc-en-rust-8d6b95de5126572e9eea7131ca8fcbb9fa49216045fc47cf6511b17384c76f31","title":"","text":"ty = it.type_(), path = relpath ); if parentlen == 0 { // There is no sidebar-items.js beyond the crate root path // FIXME maybe dynamic crate loading can be merged here write!( buffer, \"\", relpath, cx.shared.resource_suffix ); } else { write!(buffer, \"\", path = relpath); write!(buffer, \"\", relpath); } // Closes sidebar-elems div. buffer.write_str(\"\"); }"} {"_id":"doc-en-rust-7064e3e450a17d58370b49def05b89f69a839f27cc541ab97619f4ef42ff924e","title":"","text":")?; write_minify(\"search.js\", static_files::SEARCH_JS)?; write_minify(\"settings.js\", static_files::SETTINGS_JS)?; write_minify(\"sidebar-items.js\", static_files::sidebar::ITEMS)?; if cx.shared.include_sources { write_minify(\"source-script.js\", static_files::sidebar::SOURCE_SCRIPT)?; }"} {"_id":"doc-en-rust-09c53182b7266b440ece70652e9fe24ced85919fe8fa43270aed3180ef6bb6b7","title":"","text":"crate mod sidebar { /// File script to handle sidebar. crate static SOURCE_SCRIPT: &str = include_str!(\"static/source-script.js\"); /// Top Level sidebar items script which will load a sidebar without items. crate static ITEMS: &str = include_str!(\"static/sidebar-items.js\"); }"} {"_id":"doc-en-rust-cc69551c7f76c29280a4f16a3097e7882126c95eccdfefbb17e0543732a84fcb","title":"","text":".define(\"LLVM_TARGET_ARCH\", target_native.split('-').next().unwrap()) .define(\"LLVM_DEFAULT_TARGET_TRIPLE\", target_native); if target != \"aarch64-apple-darwin\" { if target != \"aarch64-apple-darwin\" && !target.contains(\"windows\") { cfg.define(\"LLVM_ENABLE_ZLIB\", \"ON\"); } else { cfg.define(\"LLVM_ENABLE_ZLIB\", \"OFF\");"} {"_id":"doc-en-rust-b5b2f0beba69eecef97b31e0979e0117bcd7f8bd487a7329069bc23a00381f29","title":"","text":"use crate::cell::UnsafeCell; use crate::mem::MaybeUninit; use crate::mem::{forget, MaybeUninit}; use crate::sys::cvt_nz; use crate::sys_common::lazy_box::{LazyBox, LazyInit};"} {"_id":"doc-en-rust-0cbe1e33f80cae3abdefe703022b8a0df64d1c5b08e26f88ce04bae5e1fa77df","title":"","text":"unsafe { mutex.init() }; mutex } fn destroy(mutex: Box) { // We're not allowed to pthread_mutex_destroy a locked mutex, // so check first if it's unlocked. if unsafe { mutex.try_lock() } { unsafe { mutex.unlock() }; drop(mutex); } else { // The mutex is locked. This happens if a MutexGuard is leaked. // In this case, we just leak the Mutex too. forget(mutex); } } fn cancel_init(_: Box) { // In this case, we can just drop it without any checks, // since it cannot have been locked yet. } } impl Mutex {"} {"_id":"doc-en-rust-de221c3794d75ed2fb3cfb31858407fd2abb85229be8386c00dc4d8dedb0db3d","title":"","text":"use crate::cell::UnsafeCell; use crate::mem::forget; use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sys_common::lazy_box::{LazyBox, LazyInit};"} {"_id":"doc-en-rust-1fee89d2ade45b2d203fdc8f3e3746284a3418c21751d390ca90a11bb2a793ad","title":"","text":"fn init() -> Box { Box::new(Self::new()) } fn destroy(mut rwlock: Box) { // We're not allowed to pthread_rwlock_destroy a locked rwlock, // so check first if it's unlocked. if *rwlock.write_locked.get_mut() || *rwlock.num_readers.get_mut() != 0 { // The rwlock is locked. This happens if a RwLock{Read,Write}Guard is leaked. // In this case, we just leak the RwLock too. forget(rwlock); } } fn cancel_init(_: Box) { // In this case, we can just drop it without any checks, // since it cannot have been locked yet. } } impl RwLock {"} {"_id":"doc-en-rust-9a7bc207c135b88088b5cf7d74b915017df73a64484cd9201f874bb1332117a0","title":"","text":"/// /// It might be called more than once per LazyBox, as multiple threads /// might race to initialize it concurrently, each constructing and initializing /// their own box. (All but one of them will be destroyed right after.) /// their own box. All but one of them will be passed to `cancel_init` right after. fn init() -> Box; /// Any surplus boxes from `init()` that lost the initialization race /// are passed to this function for disposal. /// /// The default implementation calls destroy(). fn cancel_init(x: Box) { Self::destroy(x); } /// This is called to destroy a used box. /// /// The default implementation just drops it. fn destroy(_: Box) {} } impl LazyBox {"} {"_id":"doc-en-rust-93276c40ce243ba0191a81cc18cb9e960e00fa1068eb80d2f370a3694e854365","title":"","text":"Err(ptr) => { // Lost the race to another thread. // Drop the box we created, and use the one from the other thread instead. drop(unsafe { Box::from_raw(new_ptr) }); T::cancel_init(unsafe { Box::from_raw(new_ptr) }); ptr } }"} {"_id":"doc-en-rust-34089494c5b04950c37a532f9e77a706f3ac47f920ad5a19bb90997dab8249d2","title":"","text":"fn drop(&mut self) { let ptr = *self.ptr.get_mut(); if !ptr.is_null() { drop(unsafe { Box::from_raw(ptr) }); T::destroy(unsafe { Box::from_raw(ptr) }); } } }"} {"_id":"doc-en-rust-a83f3854e28e219bf3a21fc54cad501f766e8beedc24622e42c0617f1bc1b8e9","title":"","text":"let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); if same_bucket(&mut *read_ptr, &mut *prev_ptr) { // Increase `gap.read` now since the drop may panic. gap.read += 1; /* We have found duplicate, drop it in-place */ ptr::drop_in_place(read_ptr); } else {"} {"_id":"doc-en-rust-b209d7db0f69ed03ef034161da108fbfd86436598c06a7a6f55d423466020af4","title":"","text":"/* We have filled that place, so go further */ gap.write += 1; gap.read += 1; } gap.read += 1; } /* Technically we could let `gap` clean up with its Drop, but"} {"_id":"doc-en-rust-537368ae514dff54ab0798166e5e0b735196a5028ac8596f449b3fb2ff1a8f9b","title":"","text":"#[test] fn test_vec_dedup_panicking() { #[derive(Debug)] struct Panic { drop_counter: &'static AtomicU32, struct Panic<'a> { drop_counter: &'a Cell, value: bool, index: usize, } impl PartialEq for Panic { impl<'a> PartialEq for Panic<'a> { fn eq(&self, other: &Self) -> bool { self.value == other.value } } impl Drop for Panic { impl<'a> Drop for Panic<'a> { fn drop(&mut self) { let x = self.drop_counter.fetch_add(1, Ordering::SeqCst); assert!(x != 4); self.drop_counter.set(self.drop_counter.get() + 1); if !std::thread::panicking() { assert!(self.index != 4); } } } static DROP_COUNTER: AtomicU32 = AtomicU32::new(0); let drop_counter = &Cell::new(0); let expected = [ Panic { drop_counter: &DROP_COUNTER, value: false, index: 0 }, Panic { drop_counter: &DROP_COUNTER, value: false, index: 5 }, Panic { drop_counter: &DROP_COUNTER, value: true, index: 6 }, Panic { drop_counter: &DROP_COUNTER, value: true, index: 7 }, Panic { drop_counter, value: false, index: 0 }, Panic { drop_counter, value: false, index: 5 }, Panic { drop_counter, value: true, index: 6 }, Panic { drop_counter, value: true, index: 7 }, ]; let mut vec = vec![ Panic { drop_counter: &DROP_COUNTER, value: false, index: 0 }, Panic { drop_counter, value: false, index: 0 }, // these elements get deduplicated Panic { drop_counter: &DROP_COUNTER, value: false, index: 1 }, Panic { drop_counter: &DROP_COUNTER, value: false, index: 2 }, Panic { drop_counter: &DROP_COUNTER, value: false, index: 3 }, Panic { drop_counter: &DROP_COUNTER, value: false, index: 4 }, // here it panics Panic { drop_counter: &DROP_COUNTER, value: false, index: 5 }, Panic { drop_counter: &DROP_COUNTER, value: true, index: 6 }, Panic { drop_counter: &DROP_COUNTER, value: true, index: 7 }, Panic { drop_counter, value: false, index: 1 }, Panic { drop_counter, value: false, index: 2 }, Panic { drop_counter, value: false, index: 3 }, Panic { drop_counter, value: false, index: 4 }, // here it panics while dropping the item with index==4 Panic { drop_counter, value: false, index: 5 }, Panic { drop_counter, value: true, index: 6 }, Panic { drop_counter, value: true, index: 7 }, ]; let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { vec.dedup(); })); let _ = catch_unwind(AssertUnwindSafe(|| vec.dedup())).unwrap_err(); assert_eq!(drop_counter.get(), 4); let ok = vec.iter().zip(expected.iter()).all(|(x, y)| x.index == y.index);"} {"_id":"doc-en-rust-e848d61a8d52ad54a97b0faa3db68b596f1de84a3cb4bdf05848c8794e4bbc77","title":"","text":" Subproject commit 62046bf8b4eadd4fb398d59f1eebcc140506bf85 Subproject commit 4fa9363ebba236f7c29ae11180db6051d7d2ce3b "} {"_id":"doc-en-rust-59ad6672ed38489f6a53985b691c439c75b2c00285f1fd9146a934acd0f6115c","title":"","text":"} } // This is required by the compiler to exist (e.g., it's a lang item), but it's // never actually called by the compiler. Emscripten EH doesn't use a // personality function at all, it instead uses __cxa_find_matching_catch. // Wasm error handling would use __gxx_personality_wasm0. #[lang = \"eh_personality\"] unsafe extern \"C\" fn rust_eh_personality( version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, _version: c_int, _actions: uw::_Unwind_Action, _exception_class: uw::_Unwind_Exception_Class, _exception_object: *mut uw::_Unwind_Exception, _context: *mut uw::_Unwind_Context, ) -> uw::_Unwind_Reason_Code { __gxx_personality_v0(version, actions, exception_class, exception_object, context) core::intrinsics::abort() } extern \"C\" {"} {"_id":"doc-en-rust-b60a83dd72393c8ce7821df6d7201b70738b0aac6736b8a20ffdb1e467f89214","title":"","text":"tinfo: *const TypeInfo, dest: extern \"C\" fn(*mut libc::c_void) -> *mut libc::c_void, ) -> !; fn __gxx_personality_v0( version: c_int, actions: uw::_Unwind_Action, exception_class: uw::_Unwind_Exception_Class, exception_object: *mut uw::_Unwind_Exception, context: *mut uw::_Unwind_Context, ) -> uw::_Unwind_Reason_Code; }"} {"_id":"doc-en-rust-f329711e7ec6d7e0437be7d35e4a5a50a366bccea0778dacee41f15394bc0f3a","title":"","text":" Subproject commit 453affaaa1762a065d2857970b8333017211208c Subproject commit 5dde0fe6de2941c9ef16bc1e9d91ecf20ac5ee8b "} {"_id":"doc-en-rust-b64c5d7880d2c237c81fdc7227300406c2dec8256e815de32f5da9a108e5548c","title":"","text":"use crate::cmp; use crate::iter::{ adapters::zip::try_get_unchecked, adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen, TrustedRandomAccess, }; use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedLen}; use crate::ops::{ControlFlow, Try}; /// An iterator that only iterates over the first `n` iterations of `iter`."} {"_id":"doc-en-rust-c7be3a386404d68edf5a7db8cf564e4396e6dd18a48f8a0d29f2367890705d33","title":"","text":"self.try_fold(init, ok(fold)).unwrap() } unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> ::Item where Self: TrustedRandomAccess, { // SAFETY: the caller must uphold the contract for // `Iterator::__iterator_get_unchecked`. unsafe { try_get_unchecked(&mut self.iter, idx) } } } #[unstable(issue = \"none\", feature = \"inplace_iteration\")]"} {"_id":"doc-en-rust-48d6bf56e34f14449bcf470b89c0806996e9d962a218aff52b79713342bb66b7","title":"","text":"#[unstable(feature = \"trusted_len\", issue = \"37572\")] unsafe impl TrustedLen for Take {} #[doc(hidden)] #[unstable(feature = \"trusted_random_access\", issue = \"none\")] unsafe impl TrustedRandomAccess for Take where I: TrustedRandomAccess, { const MAY_HAVE_SIDE_EFFECT: bool = I::MAY_HAVE_SIDE_EFFECT; } "} {"_id":"doc-en-rust-86c5a5f065157b14215d93c8fea1372e9ed6577c7df962e76ff69fc657fc8ae1","title":"","text":"#[test] fn smoke() { #[derive(Clone)] struct TypeWithDrop; impl Drop for TypeWithDrop { fn drop(&mut self) {"} {"_id":"doc-en-rust-98b826c965c246581bba29a3360b628fbd80045f00877837b6a5d306c7b17909","title":"","text":"let x: Box> = Box::new(ManuallyDrop::new([TypeWithDrop, TypeWithDrop])); drop(x); // test clone and clone_from implementations let mut x = ManuallyDrop::new(TypeWithDrop); let y = x.clone(); x.clone_from(&y); drop(x); drop(y); }"} {"_id":"doc-en-rust-e1f73685e946e4df1912ec7b27cbac21105e72ef356dc5a0a595eb76d46d9cd7","title":"","text":"if let LinkerFlavor::Gcc = flavor { match ld_impl { LdImpl::Lld => { let tools_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(false); let lld_path = tools_path .into_iter() .map(|p| p.join(\"gcc-ld\")) .find(|p| { p.join(if sess.host.is_like_windows { \"ld.exe\" } else { \"ld\" }).exists() }) .unwrap_or_else(|| sess.fatal(\"rust-lld (as ld) not found\")); cmd.cmd().arg({ let mut arg = OsString::from(\"-B\"); arg.push(lld_path); arg }); if sess.target.lld_flavor == LldFlavor::Ld64 { let tools_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(false); let ld64_exe = tools_path .into_iter() .map(|p| p.join(\"gcc-ld\")) .map(|p| { p.join(if sess.host.is_like_windows { \"ld64.exe\" } else { \"ld64\" }) }) .find(|p| p.exists()) .unwrap_or_else(|| sess.fatal(\"rust-lld (as ld64) not found\")); cmd.cmd().arg({ let mut arg = OsString::from(\"-fuse-ld=\"); arg.push(ld64_exe); arg }); } else { let tools_path = sess.host_filesearch(PathKind::All).get_tools_search_paths(false); let lld_path = tools_path .into_iter() .map(|p| p.join(\"gcc-ld\")) .find(|p| { p.join(if sess.host.is_like_windows { \"ld.exe\" } else { \"ld\" }) .exists() }) .unwrap_or_else(|| sess.fatal(\"rust-lld (as ld) not found\")); cmd.cmd().arg({ let mut arg = OsString::from(\"-B\"); arg.push(lld_path); arg }); } } } } else {"} {"_id":"doc-en-rust-a16cb81dc109ddedf52ae89bbad7c3c1ea00d1d4126b30fec297f75bcde3b4ac","title":"","text":"use std::env; use crate::spec::{FramePointer, SplitDebuginfo, TargetOptions}; use crate::spec::{FramePointer, LldFlavor, SplitDebuginfo, TargetOptions}; pub fn opts(os: &str) -> TargetOptions { // ELF TLS is only available in macOS 10.7+. If you try to compile for 10.6"} {"_id":"doc-en-rust-0621ceb3fdfda38bf7559143834d56ef6dca343c08a80dc4248da949946f7f06","title":"","text":"abi_return_struct_as_int: true, emit_debug_gdb_scripts: false, eh_frame_header: false, lld_flavor: LldFlavor::Ld64, // The historical default for macOS targets is to run `dsymutil` which // generates a packed version of debuginfo split from the main file."} {"_id":"doc-en-rust-d222350fb05c290f9ed917f9e31354b26de4b0de713bcbb6428ea75f35a57197","title":"","text":"&lld_install.join(\"bin\").join(&src_exe), &gcc_ld_dir.join(exe(\"ld\", target_compiler.host)), ); builder.copy( &lld_install.join(\"bin\").join(&src_exe), &gcc_ld_dir.join(exe(\"ld64\", target_compiler.host)), ); } // Similarly, copy `llvm-dwp` into libdir for Split DWARF. Only copy it when the LLVM"} {"_id":"doc-en-rust-bb303d64b78dc9b59bc4744ef708e976f0be37db643e3d82c93ef08f6866c624","title":"","text":"let gcc_lld_dir = dst_dir.join(\"gcc-ld\"); t!(fs::create_dir(&gcc_lld_dir)); builder.copy(&src_dir.join(&rust_lld), &gcc_lld_dir.join(exe(\"ld\", compiler.host))); builder .copy(&src_dir.join(&rust_lld), &gcc_lld_dir.join(exe(\"ld64\", compiler.host))); } // Copy over llvm-dwp if it's there"} {"_id":"doc-en-rust-8270455f9b8e980aed609f3785ccb64b782d5072562831ad927c3b9e1afc201d","title":"","text":"padding: 0 20px 20px 17px;; } .item-info .stab { display: table; } .stab { border-width: 1px; border-style: solid;"} {"_id":"doc-en-rust-bd4749abd3a03fb50bfcf0665c5b03a8b83c227d50224afe4efe7956d1da8773","title":"","text":" // This test ensures that the item information don't take 100% of the width if unnecessary. goto: file://|DOC_PATH|/lib2/struct.Foo.html // We set a fixed size so there is no chance of \"random\" resize. size: (1100, 800) // We check that \".item-info\" is bigger than its content. assert-css: (\".item-info\", {\"width\": \"807px\"}) assert-css: (\".item-info .stab\", {\"width\": \"343px\"}) "} {"_id":"doc-en-rust-e9b30b875de9e4cdbf75618bca711fd9ad4380771c6288e46d04b6a018bd7867","title":"","text":"// ignore-tidy-linelength #![feature(doc_cfg)] pub mod module { pub mod sub_module { pub mod sub_sub_module {"} {"_id":"doc-en-rust-f99341d9daf2357850ad9b8cc48ffb17d1997b2bc1309559498eb001956a4971","title":"","text":"pub type Alias = u32; #[doc(cfg(feature = \"foo-method\"))] pub struct Foo { pub x: Alias, }"} {"_id":"doc-en-rust-f11a3270fc21b8550bdd9cdf26bc985cebbaf5a8a49d0ba509f1dd8ba5869cb9","title":"","text":"} } } PatKind::Lit(_) => { // If the PatKind is a Lit then we want PatKind::Lit(_) | PatKind::Range(..) => { // If the PatKind is a Lit or a Range then we want // to borrow discr. needs_to_be_read = true; } _ => {} PatKind::Or(_) | PatKind::Box(_) | PatKind::Slice(..) | PatKind::Ref(..) | PatKind::Wild => { // If the PatKind is Or, Box, Slice or Ref, the decision is made later // as these patterns contains subpatterns // If the PatKind is Wild, the decision is made based on the other patterns being // examined } } })); }"} {"_id":"doc-en-rust-f62145d59d125a9169f5cf63e18412c709d68b7b5d2079e1914813f768907533","title":"","text":" // run-pass // edition:2021 pub fn foo() { let ref_x_ck = 123; let _y = || match ref_x_ck { 2_000_000..=3_999_999 => { println!(\"A\")} _ => { println!(\"B\")} }; } fn main() { foo(); } "} {"_id":"doc-en-rust-2dea0e1fb85c5001578157e2e1479892587cf8945ec4c1ebcb0b771d12319020","title":"","text":"let mut err = match *error { SelectionError::Unimplemented => { // If this obligation was generated as a result of well-formed checking, see if we // can get a better error message by performing HIR-based well formed checking. // If this obligation was generated as a result of well-formedness checking, see if we // can get a better error message by performing HIR-based well-formedness checking. if let ObligationCauseCode::WellFormed(Some(wf_loc)) = root_obligation.cause.code.peel_derives() {"} {"_id":"doc-en-rust-241575eec8537947fb85166194832667f668321b841ad5e4efcf5a88fba82ff5","title":"","text":"// given the type `Option>`, we will check // `Option>`, `MyStruct`, and `u8`. // For each type, we perform a well-formed check, and see if we get // an erorr that matches our expected predicate. We keep save // an error that matches our expected predicate. We save // the `ObligationCause` corresponding to the *innermost* type, // which is the most specific type that we can point to. // In general, the different components of an `hir::Ty` may have // completely differentr spans due to macro invocations. Pointing // completely different spans due to macro invocations. Pointing // to the most accurate part of the type can be the difference // between a useless span (e.g. the macro invocation site) // and a useful span (e.g. a user-provided type passed in to the macro). // and a useful span (e.g. a user-provided type passed into the macro). // // This approach is quite inefficient - we redo a lot of work done // by the normal WF checker. However, this code is run at most once // per reported error - it will have no impact when compilation succeeds, // and should only have an impact if a very large number of errors are // displaydd to the user. // and should only have an impact if a very large number of errors is // displayed to the user. struct HirWfCheck<'tcx> { tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>,"} {"_id":"doc-en-rust-e815682edf4a630eaf2e1b56cb4a6c34dfb08c8976c5d8c891d734fcdf108e9e","title":"","text":"WellFormedLoc::Ty(_) => match hir.get(hir_id) { hir::Node::ImplItem(item) => match item.kind { hir::ImplItemKind::TyAlias(ty) => Some(ty), hir::ImplItemKind::Const(ty, _) => Some(ty), ref item => bug!(\"Unexpected ImplItem {:?}\", item), }, hir::Node::TraitItem(item) => match item.kind { hir::TraitItemKind::Type(_, ty) => ty, hir::TraitItemKind::Const(ty, _) => Some(ty), ref item => bug!(\"Unexpected TraitItem {:?}\", item), }, hir::Node::Item(item) => match item.kind {"} {"_id":"doc-en-rust-1f1986b28bab8effcf5b1087921827b4603e8be082cc828689dd99cf55bcc8d4","title":"","text":" // Regression test for the ICE described in #87495. trait T { const CONST: (bool, dyn T); //~^ ERROR: the trait `T` cannot be made into an object [E0038] } fn main() {} "} {"_id":"doc-en-rust-46194ee1ab242f27e7ba32442a33777dbd317acc393478877a408343b3a39d8f","title":"","text":" error[E0038]: the trait `T` cannot be made into an object --> $DIR/issue-87495.rs:4:25 | LL | const CONST: (bool, dyn T); | ^^^^^ `T` cannot be made into an object | = help: consider moving `CONST` to another trait note: for a trait to be \"object safe\" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit --> $DIR/issue-87495.rs:4:11 | LL | trait T { | - this trait cannot be made into an object... LL | const CONST: (bool, dyn T); | ^^^^^ ...because it contains this associated `const` error: aborting due to previous error For more information about this error, try `rustc --explain E0038`. "} {"_id":"doc-en-rust-536f9c9e032b4e8d0cb69cc62778de50c2b4416ff7b6cecbfad9b39207ca4e20","title":"","text":"if let ObligationCauseCode::WellFormed(Some(wf_loc)) = root_obligation.cause.code.peel_derives() { if let Some(cause) = self.tcx.diagnostic_hir_wf_check((obligation.predicate, wf_loc.clone())) { if let Some(cause) = self.tcx.diagnostic_hir_wf_check(( tcx.erase_regions(obligation.predicate), wf_loc.clone(), )) { obligation.cause = cause; span = obligation.cause.span; }"} {"_id":"doc-en-rust-0bdf0ed8c7cb6ad3dc5ad19d7f240099207e1ce4c52729135eb745f4932f6b17","title":"","text":" // Regression test for #87549. // compile-flags: -C incremental=tmp/wf/hir-wf-check-erase-regions pub struct Table([Option; N]); impl<'a, T, const N: usize> IntoIterator for &'a Table { type IntoIter = std::iter::Flatten>; //~ ERROR `&T` is not an iterator type Item = &'a T; fn into_iter(self) -> Self::IntoIter { //~ ERROR `&T` is not an iterator unimplemented!() } } fn main() {} "} {"_id":"doc-en-rust-e8149c4e3617a08e589839a9db59222a0c0718f0272ff84b8134ac7c854d81db","title":"","text":" error[E0277]: `&T` is not an iterator --> $DIR/hir-wf-check-erase-regions.rs:7:5 | LL | type IntoIter = std::iter::Flatten>; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&T` is not an iterator | ::: $SRC_DIR/core/src/iter/adapters/flatten.rs:LL:COL | LL | pub struct Flatten> { | ------------ required by this bound in `Flatten` | = help: the trait `Iterator` is not implemented for `&T` = note: required because of the requirements on the impl of `IntoIterator` for `&T` error[E0277]: `&T` is not an iterator --> $DIR/hir-wf-check-erase-regions.rs:10:27 | LL | fn into_iter(self) -> Self::IntoIter { | ^^^^^^^^^^^^^^ `&T` is not an iterator | ::: $SRC_DIR/core/src/iter/adapters/flatten.rs:LL:COL | LL | pub struct Flatten> { | ------------ required by this bound in `Flatten` | = help: the trait `Iterator` is not implemented for `&T` = note: required because of the requirements on the impl of `IntoIterator` for `&T` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-96bae6d7669d1b6d33cf2bcf358b760ec02fc1b4c636d0e137446d2ad3ff5e9b","title":"","text":"if def.variants.len() > 1 { needs_to_be_read = true; } } else { // If it is not ty::Adt, then it should be read needs_to_be_read = true; } } PatKind::Lit(_) | PatKind::Range(..) => {"} {"_id":"doc-en-rust-e33726ad2a6bafba96a777662e4c35c4b9b91a06a7a803db95f7bb5af8d54624","title":"","text":" // run-pass // edition:2021 const LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED: i32 = 0x01; const LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT: i32 = 0x02; pub fn hotplug_callback(event: i32) { let _ = || { match event { LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED => (), LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT => (), _ => (), }; }; } fn main() { hotplug_callback(1); } "} {"_id":"doc-en-rust-b6a060ac0c43a8cc66b73df9109215c76bcae0a17ba919d305551526df1a5b46","title":"","text":" // run-pass // edition:2021 const PATTERN_REF: &str = \"Hello World\"; const NUMBER: i32 = 30; const NUMBER_POINTER: *const i32 = &NUMBER; pub fn edge_case_ref(event: &str) { let _ = || { match event { PATTERN_REF => (), _ => (), }; }; } pub fn edge_case_str(event: String) { let _ = || { match event.as_str() { \"hello\" => (), _ => (), }; }; } pub fn edge_case_raw_ptr(event: *const i32) { let _ = || { match event { NUMBER_POINTER => (), _ => (), }; }; } pub fn edge_case_char(event: char) { let _ = || { match event { 'a' => (), _ => (), }; }; } fn main() {} "} {"_id":"doc-en-rust-5f6dfca2c10be8ff30225bc77a93325b2f5b38a1a5ce1c1b6227048b85dd91e9","title":"","text":"impl AddCallGuards { pub fn add_call_guards(&self, body: &mut Body<'_>) { let pred_count: IndexVec<_, _> = body.predecessors().iter().map(|ps| ps.len()).collect(); let mut pred_count: IndexVec<_, _> = body.predecessors().iter().map(|ps| ps.len()).collect(); pred_count[START_BLOCK] += 1; // We need a place to store the new blocks generated let mut new_blocks = Vec::new();"} {"_id":"doc-en-rust-402f9c86f573c8185b907dac30d1b36511b6afaae3dbd4eea41f32fba007cc70","title":"","text":"// CHECK-LABEL: @main fn main() { take_until(|| true); f(None); } fn f(_a: Option) -> Option { loop { g(); () } } fn g() -> Option { None } "} {"_id":"doc-en-rust-1e0640284b41cc1155596bacfd36954112e1a3e7cb115099966d6b1e6d3c250a","title":"","text":"if let Some(hir::Guard::If(ref e)) = arm.guard { self.consume_expr(e) } else if let Some(hir::Guard::IfLet(_, ref e)) = arm.guard { self.consume_expr(e) } self.consume_expr(&arm.body);"} {"_id":"doc-en-rust-fce9dc2f60aba47e76ec3e52c00b2327c505a2b9bfcde418ce864fe3fd899079","title":"","text":" // edition:2021 // run-pass #![feature(if_let_guard)] #[allow(unused_must_use)] #[allow(dead_code)] fn print_error_count(registry: &Registry) { |x: &Registry| { match &x { Registry if let _ = registry.try_find_description() => { } //~^ WARNING: irrefutable `if let` guard pattern _ => {} } }; } struct Registry; impl Registry { pub fn try_find_description(&self) { unimplemented!() } } fn main() {} "} {"_id":"doc-en-rust-f56fb4d481c0b4e7ee2592fb645dab3d28d3b40dc9a34d5e0de041037fedff40","title":"","text":" warning: irrefutable `if let` guard pattern --> $DIR/issue-88118-2.rs:10:29 | LL | Registry if let _ = registry.try_find_description() => { } | ^ | = note: `#[warn(irrefutable_let_patterns)]` on by default = note: this pattern will always match, so the guard is useless = help: consider removing the guard and adding a `let` inside the match arm warning: 1 warning emitted "} {"_id":"doc-en-rust-c2d352233b888075ba50cad996ef282270f42661fd6aea2b39a56d061b938f98","title":"","text":"} fn check_fn_decl(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) { self.check_decl_num_args(fn_decl); self.check_decl_cvaradic_pos(fn_decl); self.check_decl_attrs(fn_decl); self.check_decl_self_param(fn_decl, self_semantic); } /// Emits fatal error if function declaration has more than `u16::MAX` arguments /// Error is fatal to prevent errors during typechecking fn check_decl_num_args(&self, fn_decl: &FnDecl) { let max_num_args: usize = u16::MAX.into(); if fn_decl.inputs.len() > max_num_args { let Param { span, .. } = fn_decl.inputs[0]; self.err_handler().span_fatal( span, &format!(\"function can not have more than {} arguments\", max_num_args), ); } } fn check_decl_cvaradic_pos(&self, fn_decl: &FnDecl) { match &*fn_decl.inputs { [Param { ty, span, .. }] => {"} {"_id":"doc-en-rust-99e8fdd487264f4961f91d4b1db0f3021a382901510efc39a03ff14b12418de7","title":"","text":" macro_rules! many_args { ([$($t:tt)*]#$($h:tt)*) => { many_args!{[$($t)*$($t)*]$($h)*} }; ([$($t:tt)*]) => { fn _f($($t: ()),*) {} //~ ERROR function can not have more than 65535 arguments } } many_args!{[_]########## ######} fn main() {} "} {"_id":"doc-en-rust-68052938402af349618cb8dc8d44abf5e172a80ace56d0851ed2f6fe37e0a355","title":"","text":" error: function can not have more than 65535 arguments --> $DIR/issue-88577-check-fn-with-more-than-65535-arguments.rs:6:24 | LL | fn _f($($t: ()),*) {} | ________________________^ LL | | } LL | | } LL | | LL | | many_args!{[_]########## ######} | |____________^ error: aborting due to previous error "} {"_id":"doc-en-rust-359bd182d7fe54efa985e86c61d1e97b25f79301877752dc15abe4bbb9074066","title":"","text":"struct_span_err!(sess, sp, E0004, \"{}\", &error_message) } #[derive(PartialEq)] enum RefutableFlag { Irrefutable, Refutable, } use RefutableFlag::*; struct MatchVisitor<'a, 'p, 'tcx> { tcx: TyCtxt<'tcx>, typeck_results: &'a ty::TypeckResults<'tcx>,"} {"_id":"doc-en-rust-73fc0071039aa92c59d33e961f2f993d445b00f8d103cba028c7a2bf95315b14","title":"","text":"hir::LocalSource::AssignDesugar(_) => (\"destructuring assignment binding\", None), }; self.check_irrefutable(&loc.pat, msg, sp); self.check_patterns(&loc.pat); self.check_patterns(&loc.pat, Irrefutable); } fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { intravisit::walk_param(self, param); self.check_irrefutable(¶m.pat, \"function argument\", None); self.check_patterns(¶m.pat); self.check_patterns(¶m.pat, Irrefutable); } }"} {"_id":"doc-en-rust-61acf8d17edc4a323c8d368c9458c4126e5d9e0d431ca4d959dffddfb4cd7018","title":"","text":"} impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> { fn check_patterns(&self, pat: &Pat<'_>) { fn check_patterns(&self, pat: &Pat<'_>, rf: RefutableFlag) { pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat)); check_for_bindings_named_same_as_variants(self, pat); check_for_bindings_named_same_as_variants(self, pat, rf); } fn lower_pattern("} {"_id":"doc-en-rust-062cb961abf3e2b8b6ba2e5f3a3c5fb797cec3c98831d3c52ba5d686936a679f","title":"","text":"} fn check_let(&mut self, pat: &'tcx hir::Pat<'tcx>, expr: &hir::Expr<'_>, span: Span) { self.check_patterns(pat); self.check_patterns(pat, Refutable); let mut cx = self.new_cx(expr.hir_id); let tpat = self.lower_pattern(&mut cx, pat, &mut false); check_let_reachability(&mut cx, pat.hir_id, tpat, span);"} {"_id":"doc-en-rust-c4bd9454642ddab08512cb5c910ee073518fc4ea43dc0ebccabe2e33351a6952","title":"","text":"for arm in arms { // Check the arm for some things unrelated to exhaustiveness. self.check_patterns(&arm.pat); self.check_patterns(&arm.pat, Refutable); if let Some(hir::Guard::IfLet(ref pat, _)) = arm.guard { self.check_patterns(pat); self.check_patterns(pat, Refutable); let tpat = self.lower_pattern(&mut cx, pat, &mut false); check_let_reachability(&mut cx, pat.hir_id, tpat, tpat.span()); }"} {"_id":"doc-en-rust-7da09f122cf5f80dbc903c0fe31f24b3ebc04e9cd443b87a5e7f095f43b0d734","title":"","text":"} } fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>) { fn check_for_bindings_named_same_as_variants( cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>, rf: RefutableFlag, ) { pat.walk_always(|p| { if let hir::PatKind::Binding(_, _, ident, None) = p.kind { if let Some(ty::BindByValue(hir::Mutability::Not)) ="} {"_id":"doc-en-rust-5d4ba3b51c7efca8685de939f59a8ec983020cd38779835f6242684245f923fa","title":"","text":"variant.ident == ident && variant.ctor_kind == CtorKind::Const }) { let variant_count = edef.variants.len(); cx.tcx.struct_span_lint_hir( BINDINGS_WITH_VARIANT_NAME, p.hir_id, p.span, |lint| { let ty_path = cx.tcx.def_path_str(edef.did); lint.build(&format!( let mut err = lint.build(&format!( \"pattern binding `{}` is named the same as one of the variants of the type `{}`\", of the variants of the type `{}`\", ident, ty_path )) .code(error_code!(E0170)) .span_suggestion( p.span, \"to match on the variant, qualify the path\", format!(\"{}::{}\", ty_path, ident), Applicability::MachineApplicable, ) .emit(); )); err.code(error_code!(E0170)); // If this is an irrefutable pattern, and there's > 1 variant, // then we can't actually match on this. Applying the below // suggestion would produce code that breaks on `check_irrefutable`. if rf == Refutable || variant_count == 1 { err.span_suggestion( p.span, \"to match on the variant, qualify the path\", format!(\"{}::{}\", ty_path, ident), Applicability::MachineApplicable, ); } err.emit(); }, ) }"} {"_id":"doc-en-rust-970d6ad470ebea9f0b9f04112a573c93183d7953ed3f9f845b0ff8944f7cbb3a","title":"","text":" #![allow(unused, nonstandard_style)] #![deny(bindings_with_variant_name)] // If an enum has two different variants, // then it cannot be matched upon in a function argument. // It still gets a warning, but no suggestions. enum Foo { C, D, } fn foo(C: Foo) {} //~ERROR fn main() { let C = Foo::D; //~ERROR } "} {"_id":"doc-en-rust-d3195d68c9a7302a8cfe21ba376bbda18dc922729697ac3397c84c9c96f41e84","title":"","text":" error[E0170]: pattern binding `C` is named the same as one of the variants of the type `Foo` --> $DIR/issue-88730.rs:12:8 | LL | fn foo(C: Foo) {} | ^ | note: the lint level is defined here --> $DIR/issue-88730.rs:2:9 | LL | #![deny(bindings_with_variant_name)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0170]: pattern binding `C` is named the same as one of the variants of the type `Foo` --> $DIR/issue-88730.rs:15:9 | LL | let C = Foo::D; | ^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0170`. "} {"_id":"doc-en-rust-251bf28d25cd40f969458277db881e01c654ee46611d9bb055d5f0f88eba2002","title":"","text":"if self.not_enough_args_provided() { self.suggest_adding_args(err); } else if self.too_many_args_provided() { self.suggest_moving_args_from_assoc_fn_to_trait(err); self.suggest_removing_args_or_generics(err); } else { unreachable!();"} {"_id":"doc-en-rust-c96b645d4d726ab8d85820b1e507b3643672c7ebf3f2101bf8547b6722ec6717","title":"","text":"} } /// Suggests moving redundant argument(s) of an associate function to the /// trait it belongs to. /// /// ```compile_fail /// Into::into::>(42) // suggests considering `Into::>::into(42)` /// ``` fn suggest_moving_args_from_assoc_fn_to_trait(&self, err: &mut Diagnostic) { let trait_ = match self.tcx.trait_of_item(self.def_id) { Some(def_id) => def_id, None => return, }; // Skip suggestion when the associated function is itself generic, it is unclear // how to split the provided parameters between those to suggest to the trait and // those to remain on the associated type. let num_assoc_fn_expected_args = self.num_expected_type_or_const_args() + self.num_expected_lifetime_args(); if num_assoc_fn_expected_args > 0 { return; } let num_assoc_fn_excess_args = self.num_excess_type_or_const_args() + self.num_excess_lifetime_args(); let trait_generics = self.tcx.generics_of(trait_); let num_trait_generics_except_self = trait_generics.count() - if trait_generics.has_self { 1 } else { 0 }; let msg = format!( \"consider moving {these} generic argument{s} to the `{name}` trait, which takes up to {num} argument{s}\", these = pluralize!(\"this\", num_assoc_fn_excess_args), s = pluralize!(num_assoc_fn_excess_args), name = self.tcx.item_name(trait_), num = num_trait_generics_except_self, ); if let Some(hir_id) = self.path_segment.hir_id && let Some(parent_node) = self.tcx.hir().find_parent_node(hir_id) && let Some(parent_node) = self.tcx.hir().find(parent_node) && let hir::Node::Expr(expr) = parent_node { match expr.kind { hir::ExprKind::Path(ref qpath) => { self.suggest_moving_args_from_assoc_fn_to_trait_for_qualified_path( err, qpath, msg, num_assoc_fn_excess_args, num_trait_generics_except_self ) }, hir::ExprKind::MethodCall(..) => { self.suggest_moving_args_from_assoc_fn_to_trait_for_method_call( err, trait_, expr, msg, num_assoc_fn_excess_args, num_trait_generics_except_self ) }, _ => return, } } } fn suggest_moving_args_from_assoc_fn_to_trait_for_qualified_path( &self, err: &mut Diagnostic, qpath: &'tcx hir::QPath<'tcx>, msg: String, num_assoc_fn_excess_args: usize, num_trait_generics_except_self: usize, ) { if let hir::QPath::Resolved(_, path) = qpath && let Some(trait_path_segment) = path.segments.get(0) { let num_generic_args_supplied_to_trait = trait_path_segment.args().num_generic_params(); if num_assoc_fn_excess_args == num_trait_generics_except_self - num_generic_args_supplied_to_trait { if let Some(span) = self.gen_args.span_ext() && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { let sugg = vec![ (self.path_segment.ident.span, format!(\"{}::{}\", snippet, self.path_segment.ident)), (span.with_lo(self.path_segment.ident.span.hi()), \"\".to_owned()) ]; err.multipart_suggestion( msg, sugg, Applicability::MaybeIncorrect ); } } } } fn suggest_moving_args_from_assoc_fn_to_trait_for_method_call( &self, err: &mut Diagnostic, trait_: DefId, expr: &'tcx hir::Expr<'tcx>, msg: String, num_assoc_fn_excess_args: usize, num_trait_generics_except_self: usize, ) { if let hir::ExprKind::MethodCall(_, args, _) = expr.kind { assert_eq!(args.len(), 1); if num_assoc_fn_excess_args == num_trait_generics_except_self { if let Some(gen_args) = self.gen_args.span_ext() && let Ok(gen_args) = self.tcx.sess.source_map().span_to_snippet(gen_args) && let Ok(args) = self.tcx.sess.source_map().span_to_snippet(args[0].span) { let sugg = format!(\"{}::{}::{}({})\", self.tcx.item_name(trait_), gen_args, self.tcx.item_name(self.def_id), args); err.span_suggestion(expr.span, msg, sugg, Applicability::MaybeIncorrect); } } } } /// Suggests to remove redundant argument(s): /// /// ```text"} {"_id":"doc-en-rust-471d72cabbc6a30b8c06134dbca332c66b07929f9829bbc1754f8ca8cf1cf971","title":"","text":"--> $DIR/invalid-const-arg-for-type-param.rs:6:23 | LL | let _: u32 = 5i32.try_into::<32>().unwrap(); | ^^^^^^^^------ help: remove these generics | | | expected 0 generic arguments | ^^^^^^^^ expected 0 generic arguments | note: associated function defined here, with 0 generic parameters --> $SRC_DIR/core/src/convert/mod.rs:LL:COL | LL | fn try_into(self) -> Result; | ^^^^^^^^ help: consider moving this generic argument to the `TryInto` trait, which takes up to 1 argument | LL | let _: u32 = TryInto::<32>::try_into(5i32).unwrap(); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ help: remove these generics | LL - let _: u32 = 5i32.try_into::<32>().unwrap(); LL + let _: u32 = 5i32.try_into().unwrap(); | error[E0599]: no method named `f` found for struct `S` in the current scope --> $DIR/invalid-const-arg-for-type-param.rs:9:7"} {"_id":"doc-en-rust-8b415a7b02e7b4e355b480cee6542d8eb7c8e711546645e778b49b387f75ece2","title":"","text":" use std::convert::TryInto; trait A { fn foo() {} } trait B { fn bar() {} } struct S; impl A for S {} impl B for S {} fn main() { let _ = A::foo::(); //~^ ERROR //~| HELP remove these generics //~| HELP consider moving this generic argument let _ = B::bar::(); //~^ ERROR //~| HELP remove these generics //~| HELP consider moving these generic arguments let _ = A::::foo::(); //~^ ERROR //~| HELP remove these generics let _ = 42.into::>(); //~^ ERROR //~| HELP remove these generics //~| HELP consider moving this generic argument } "} {"_id":"doc-en-rust-efef4a20b03ad908b92c508fc8fc992f7e169c28030195b05c45fc9477111faa","title":"","text":" error[E0107]: this associated function takes 0 generic arguments but 1 generic argument was supplied --> $DIR/issue-89064.rs:17:16 | LL | let _ = A::foo::(); | ^^^ expected 0 generic arguments | note: associated function defined here, with 0 generic parameters --> $DIR/issue-89064.rs:4:8 | LL | fn foo() {} | ^^^ help: consider moving this generic argument to the `A` trait, which takes up to 1 argument | LL - let _ = A::foo::(); LL + let _ = A::::foo(); | help: remove these generics | LL - let _ = A::foo::(); LL + let _ = A::foo(); | error[E0107]: this associated function takes 0 generic arguments but 2 generic arguments were supplied --> $DIR/issue-89064.rs:22:16 | LL | let _ = B::bar::(); | ^^^ expected 0 generic arguments | note: associated function defined here, with 0 generic parameters --> $DIR/issue-89064.rs:8:8 | LL | fn bar() {} | ^^^ help: consider moving these generic arguments to the `B` trait, which takes up to 2 arguments | LL - let _ = B::bar::(); LL + let _ = B::::bar(); | help: remove these generics | LL - let _ = B::bar::(); LL + let _ = B::bar(); | error[E0107]: this associated function takes 0 generic arguments but 1 generic argument was supplied --> $DIR/issue-89064.rs:27:21 | LL | let _ = A::::foo::(); | ^^^----- help: remove these generics | | | expected 0 generic arguments | note: associated function defined here, with 0 generic parameters --> $DIR/issue-89064.rs:4:8 | LL | fn foo() {} | ^^^ error[E0107]: this associated function takes 0 generic arguments but 1 generic argument was supplied --> $DIR/issue-89064.rs:31:16 | LL | let _ = 42.into::>(); | ^^^^ expected 0 generic arguments | note: associated function defined here, with 0 generic parameters --> $SRC_DIR/core/src/convert/mod.rs:LL:COL | LL | fn into(self) -> T; | ^^^^ help: consider moving this generic argument to the `Into` trait, which takes up to 1 argument | LL | let _ = Into::>::into(42); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ help: remove these generics | LL - let _ = 42.into::>(); LL + let _ = 42.into(); | error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0107`. "} {"_id":"doc-en-rust-7e7bf7e618ec5184baa17e199136b3bc03572baf52f1c66a87c0778bfc23349e","title":"","text":"} impl<'tcx> FieldDef { /// Returns the type of this field. The `subst` is typically obtained /// via the second field of `TyKind::AdtDef`. /// Returns the type of this field. The resulting type is not normalized. The `subst` is /// typically obtained via the second field of `TyKind::AdtDef`. pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> { tcx.type_of(self.did).subst(tcx, subst) }"} {"_id":"doc-en-rust-d85c48ab06b0f9bdd5162e29caee792dbf2677f52215941172881668cd08f6c2","title":"","text":"variant.fields.iter().enumerate().filter_map(move |(i, field)| { let ty = field.ty(cx.tcx, substs); // `field.ty()` doesn't normalize after substituting. let ty = cx.tcx.normalize_erasing_regions(cx.param_env, ty); let is_visible = adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx); let is_uninhabited = cx.is_uninhabited(ty);"} {"_id":"doc-en-rust-8168728707c586eb2c5ef861ee7fecac0a840618afb6fcbdb075699f71ebdbd6","title":"","text":"write!(f, \"{}\", hi) } IntRange(range) => write!(f, \"{:?}\", range), // Best-effort, will render e.g. `false` as `0..=0` Wildcard | Missing { .. } | NonExhaustive => write!(f, \"_\"), Wildcard | Missing { .. } | NonExhaustive => write!(f, \"_ : {:?}\", self.ty), Or => { for pat in self.iter_fields() { write!(f, \"{}{:?}\", start_or_continue(\" | \"), pat)?;"} {"_id":"doc-en-rust-9ad0a62ef8f0f7114d878d46325cc234fbd256e521cf49a73bfe19e0595ccba2","title":"","text":"assert!(rows.iter().all(|r| r.len() == v.len())); // FIXME(Nadrieril): Hack to work around type normalization issues (see #72476). let ty = matrix.heads().next().map_or(v.head().ty(), |r| r.ty()); let ty = v.head().ty(); let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty); let pcx = PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive };"} {"_id":"doc-en-rust-c40793f3858eaa62a093c1a244027cc1ebe04a593d5b7f04427896827b48121d","title":"","text":" // check-pass // From https://github.com/rust-lang/rust/issues/72476 // and https://github.com/rust-lang/rust/issues/89393 trait Trait { type Projection; } struct A; impl Trait for A { type Projection = bool; } struct B; impl Trait for B { type Projection = (u32, u32); } struct Next(T::Projection); fn foo1(item: Next) { match item { Next(true) => {} Next(false) => {} } } fn foo2(x: ::Projection) { match x { true => {} false => {} } } fn foo3(x: Next) { let Next((_, _)) = x; match x { Next((_, _)) => {} } } fn foo4(x: ::Projection) { let (_, _) = x; match x { (_, _) => {} } } fn foo5(x: ::Projection) { match x { _ => {} } } fn main() {} "} {"_id":"doc-en-rust-c66aacc154c55a8ac830332d48376445baf921f85988d3318ed45e95fbec97f7","title":"","text":" // check-pass // From https://github.com/rust-lang/rust/issues/72476 trait A { type Projection; } impl A for () { type Projection = bool; } struct Next(T::Projection); fn f(item: Next<()>) { match item { Next(true) => {} Next(false) => {} } } fn main() {} "} {"_id":"doc-en-rust-3b1a99f114dfc89c2260e798b0791ea9f47d32a99e6ab653122b50cec448f9cb","title":"","text":" Subproject commit 18667a856596713fc4479f99b96afc7f03aa995c Subproject commit fa91a89193d26e6a86e2eee1cbaa38cb28ccebe1 "} {"_id":"doc-en-rust-1bb8d6671656d3f9769043ad45673360ab4372013a226ccf59857c989ac23e62","title":"","text":"fn universe_for(&mut self, debruijn: ty::DebruijnIndex) -> ty::UniverseIndex { let infcx = self.infcx; let index = self.universe_indices.len() - debruijn.as_usize() + self.current_index.as_usize() - 1; self.universe_indices.len() + self.current_index.as_usize() - debruijn.as_usize() - 1; let universe = self.universe_indices[index].unwrap_or_else(|| { for i in self.universe_indices.iter_mut().take(index + 1) { *i = i.or_else(|| Some(infcx.create_next_universe()))"} {"_id":"doc-en-rust-6457f918df1740af35422ca33bab60f777f202098ca643be514e2a98ec1b32e9","title":"","text":"!ptr.is_null() && ptr as usize % mem::align_of::() == 0 } /// Checks whether the regions of memory starting at `src` and `dst` of size /// `count * size_of::()` do *not* overlap. #[cfg(debug_assertions)] pub(crate) fn is_nonoverlapping(src: *const T, dst: *const T, count: usize) -> bool { let src_usize = src as usize; let dst_usize = dst as usize; let size = mem::size_of::().checked_mul(count).unwrap(); let diff = if src_usize > dst_usize { src_usize - dst_usize } else { dst_usize - src_usize }; // If the absolute distance between the ptrs is at least as big as the size of the buffer, // they do not overlap. diff >= size } /// Copies `count * size_of::()` bytes from `src` to `dst`. The source /// and destination must *not* overlap. ///"} {"_id":"doc-en-rust-7211a8f36d5b0c03cd76e356b24fcd6e9b4c0009fa4eaa7a87299f0e6a0a8be0","title":"","text":"pub fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); } // FIXME: Perform these checks only at run time /*if cfg!(debug_assertions) && !(is_aligned_and_not_null(src) && is_aligned_and_not_null(dst) && is_nonoverlapping(src, dst, count)) { // Not panicking to keep codegen impact smaller. abort(); }*/ #[cfg(debug_assertions)] fn runtime_check(src: *const T, dst: *mut T, count: usize) { if !is_aligned_and_not_null(src) || !is_aligned_and_not_null(dst) || !is_nonoverlapping(src, dst, count) { // Not panicking to keep codegen impact smaller. abort(); } } #[cfg(debug_assertions)] const fn compiletime_check(_src: *const T, _dst: *mut T, _count: usize) {} #[cfg(debug_assertions)] // SAFETY: runtime debug-assertions are a best-effort basis; it's fine to // not do them during compile time unsafe { const_eval_select((src, dst, count), compiletime_check, runtime_check); } // SAFETY: the safety contract for `copy_nonoverlapping` must be // upheld by the caller."} {"_id":"doc-en-rust-e9207f6222c83f4e8993f6ed6f99a646b679da1008114af760128db85b836fd8","title":"","text":"fn copy(src: *const T, dst: *mut T, count: usize); } // FIXME: Perform these checks only at run time /*if cfg!(debug_assertions) && !(is_aligned_and_not_null(src) && is_aligned_and_not_null(dst)) { // Not panicking to keep codegen impact smaller. abort(); }*/ #[cfg(debug_assertions)] fn runtime_check(src: *const T, dst: *mut T) { if !is_aligned_and_not_null(src) || !is_aligned_and_not_null(dst) { // Not panicking to keep codegen impact smaller. abort(); } } #[cfg(debug_assertions)] const fn compiletime_check(_src: *const T, _dst: *mut T) {} #[cfg(debug_assertions)] // SAFETY: runtime debug-assertions are a best-effort basis; it's fine to // not do them during compile time unsafe { const_eval_select((src, dst), compiletime_check, runtime_check); } // SAFETY: the safety contract for `copy` must be upheld by the caller. unsafe { copy(src, dst, count) }"} {"_id":"doc-en-rust-bbcff4fc6064c299228c9c117cdfb7d9d9dc2376cf144f44412b56a1d84bafc2","title":"","text":"#![feature(const_caller_location)] #![feature(const_cell_into_inner)] #![feature(const_discriminant)] #![cfg_attr(not(bootstrap), feature(const_eval_select))] #![feature(const_eval_select)] #![feature(const_float_bits_conv)] #![feature(const_float_classify)] #![feature(const_fmt_arguments_new)]"} {"_id":"doc-en-rust-aaadb029425c175c6ea81e9df9a90199a213fe58fd3af326ebab769c95448ca1","title":"","text":"// Save the index of all fields regardless of their visibility in case // of error recovery. self.write_field_index(expr.hir_id, index); let adjustments = self.adjust_steps(&autoderef); if field.vis.is_accessible_from(def_scope, self.tcx) { let adjustments = self.adjust_steps(&autoderef); self.apply_adjustments(base, adjustments); self.register_predicates(autoderef.into_obligations()); self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None); return field_ty; } private_candidate = Some((base_def.did, field_ty)); private_candidate = Some((adjustments, base_def.did, field_ty)); } } ty::Tuple(tys) => {"} {"_id":"doc-en-rust-ff7785d42965667dc7627fc07ade41b86d0aa1423912def1658cbc5e0f15463c","title":"","text":"} self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false)); if let Some((did, field_ty)) = private_candidate { if let Some((adjustments, did, field_ty)) = private_candidate { // (#90483) apply adjustments to avoid ExprUseVisitor from // creating erroneous projection. self.apply_adjustments(base, adjustments); self.ban_private_field_access(expr, expr_t, field, did); return field_ty; }"} {"_id":"doc-en-rust-1210c04e59cf226a229d918f3db8dc5298369c7a070de3bf7decde3e5ad23dad","title":"","text":" // edition:2021 mod m { pub struct S { foo: i32 } impl S { pub fn foo(&self) -> i32 { 42 } } } fn bar(s: &m::S) { || s.foo() + s.foo; //~ ERROR E0616 } fn main() {} "} {"_id":"doc-en-rust-c03a550c16142494a7d480a6d503ff05be8e28641d6ecaefd6e4b287aece8a6e","title":"","text":" error[E0616]: field `foo` of struct `S` is private --> $DIR/issue-90483-inaccessible-field-adjustment.rs:11:18 | LL | || s.foo() + s.foo; | ^^^ private field | help: a method `foo` also exists, call it with parentheses | LL | || s.foo() + s.foo(); | ++ error: aborting due to previous error For more information about this error, try `rustc --explain E0616`. "} {"_id":"doc-en-rust-391bf7ffdd79953c8689f97e2982e1cf22e40c1b25d926e40535f8d1eb1d19f8","title":"","text":" Subproject commit 01c8b654f9a01371414d1fd69cba38b289510a9e Subproject commit 2b9078f4afae82f60c5ac0fdb4af42d269e2f2f3 "} {"_id":"doc-en-rust-9e16002b66588d33605cc0bdafbf260aa3213e8b919378869f65e98d70dfd9bb","title":"","text":"//! `RETURN_PLACE` the MIR arguments) are always fully normalized (and //! contain revealed `impl Trait` values). use crate::type_check::constraint_conversion::ConstraintConversion; use rustc_index::vec::Idx; use rustc_infer::infer::LateBoundRegionConversionTime; use rustc_middle::mir::*; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::{self, Ty}; use rustc_middle::ty::Ty; use rustc_span::Span; use rustc_trait_selection::traits::query::normalize::AtExt; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits::query::type_op::{self, TypeOp}; use rustc_trait_selection::traits::query::Fallible; use type_op::TypeOpOutput; use crate::universal_regions::UniversalRegions;"} {"_id":"doc-en-rust-5384e1b2e61fbdcc467337df033b4b276b27d3e5fa07252359ba9ad48cf36bbb","title":"","text":"let (&normalized_output_ty, normalized_input_tys) = normalized_inputs_and_output.split_last().unwrap(); debug!(?normalized_output_ty); debug!(?normalized_input_tys); let mir_def_id = body.source.def_id().expect_local(); // If the user explicitly annotated the input types, extract"} {"_id":"doc-en-rust-d7ccf0878c5c0358440b07fca487d90283587688e2ae3bc6e7809612c4ae9cf3","title":"","text":".delay_span_bug(body.span, \"found more normalized_input_ty than local_decls\"); break; } // In MIR, argument N is stored in local N+1. let local = Local::new(argument_index + 1); let mir_input_ty = body.local_decls[local].ty; let mir_input_span = body.local_decls[local].source_info.span; self.equate_normalized_input_or_output( normalized_input_ty,"} {"_id":"doc-en-rust-9f7c19cfb0185383cada68ec13d8ae68232d7ff16cd46da78997b6cf18b9ff74","title":"","text":"// If the user explicitly annotated the input types, enforce those. let user_provided_input_ty = self.normalize(user_provided_input_ty, Locations::All(mir_input_span)); self.equate_normalized_input_or_output( user_provided_input_ty, mir_input_ty,"} {"_id":"doc-en-rust-e4156b23ab33d44173cf3cebf8c25845f695d9dfca908e751b6531d27f40e220","title":"","text":"// `rustc_traits::normalize_after_erasing_regions`. Ideally, we'd // like to normalize *before* inserting into `local_decls`, but // doing so ends up causing some other trouble. let b = match self .infcx .at(&ObligationCause::dummy(), ty::ParamEnv::empty()) .normalize(b) { Ok(n) => { debug!(\"equate_inputs_and_outputs: {:?}\", n); if n.obligations.iter().all(|o| { matches!( o.predicate.kind().skip_binder(), ty::PredicateKind::RegionOutlives(_) | ty::PredicateKind::TypeOutlives(_) ) }) { n.value } else { b } } let b = match self.normalize_and_add_constraints(b) { Ok(n) => n, Err(_) => { debug!(\"equate_inputs_and_outputs: NoSolution\"); b } }; // Note: if we have to introduce new placeholders during normalization above, then we won't have // added those universes to the universe info, which we would want in `relate_tys`. if let Err(terr) ="} {"_id":"doc-en-rust-e1776be1359873d13e3f96a1d9b46d807ca5a55b09bbb9ac8fe04d733217a5f8","title":"","text":"} } } pub(crate) fn normalize_and_add_constraints(&mut self, t: Ty<'tcx>) -> Fallible> { let TypeOpOutput { output: norm_ty, constraints, .. } = self.param_env.and(type_op::normalize::Normalize::new(t)).fully_perform(self.infcx)?; debug!(\"{:?} normalized to {:?}\", t, norm_ty); for data in constraints.into_iter().collect::>() { ConstraintConversion::new( self.infcx, &self.borrowck_context.universal_regions, &self.region_bound_pairs, Some(self.implicit_region_bound), self.param_env, Locations::All(DUMMY_SP), ConstraintCategory::Internal, &mut self.borrowck_context.constraints, ) .convert_all(&*data); } Ok(norm_ty) } }"} {"_id":"doc-en-rust-e94ad80024a1e3790d49973c66ba4c0b0ff42eb0c7b6092a5e3dc2dfd06a146c","title":"","text":"} struct BorrowCheckContext<'a, 'tcx> { universal_regions: &'a UniversalRegions<'tcx>, pub(crate) universal_regions: &'a UniversalRegions<'tcx>, location_table: &'a LocationTable, all_facts: &'a mut Option, borrow_set: &'a BorrowSet<'tcx>, constraints: &'a mut MirTypeckRegionConstraints<'tcx>, pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>, upvars: &'a [Upvar<'tcx>], }"} {"_id":"doc-en-rust-13fdc09f7f7e608d528899033b4423ee77e506d48bc851fe61c3616127254ace","title":"","text":"self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category) } #[instrument(skip(self, category), level = \"debug\")] fn eq_types( &mut self, expected: Ty<'tcx>,"} {"_id":"doc-en-rust-8d4838df6e221e350c9eb64a944f16c21e63503423c0981a5a762a39d80b9a67","title":"","text":" // check-pass #![feature(generic_associated_types)] use std::marker::PhantomData; trait Family: Sized { type Item<'a>; fn apply_all(&self, f: F) where F: FamilyItemFn { } } struct Array(PhantomData); impl Family for Array { type Item<'a> = &'a T; } trait FamilyItemFn { fn apply(&self, item: T::Item<'_>); } impl FamilyItemFn for F where T: Family, for<'a> F: Fn(T::Item<'a>) { fn apply(&self, item: T::Item<'_>) { (*self)(item); } } fn process(array: Array) { // Works array.apply_all(|x: &T| { }); // ICE: NoSolution array.apply_all(|x: as Family>::Item<'_>| { }); } fn main() {} "} {"_id":"doc-en-rust-7907cb87f1d1bccde50bbac08831230226e843d1a5762619966f2971e67a1014","title":"","text":" //check-pass #![feature(generic_associated_types)] trait Yokeable<'a>: 'static { type Output: 'a; } trait IsCovariant<'a> {} struct Yoke Yokeable<'a>> { data: Y, } impl Yokeable<'a>> Yoke { fn project Yokeable<'a>>(&self, _f: for<'a> fn(>::Output, &'a ()) -> >::Output) -> Yoke { unimplemented!() } } fn _upcast(x: Yoke) -> Yoke + 'static>> where Y: for<'a> Yokeable<'a>, for<'a> >::Output: IsCovariant<'a> { x.project(|data, _| { Box::new(data) }) } impl<'a> Yokeable<'a> for Box + 'static> { type Output = Box + 'a>; } fn main() {} "} {"_id":"doc-en-rust-79fd43d97b3fa4f266d84b2a10764514f4a0219d5aae1e362e771958df6cf033","title":"","text":"let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline); let pub_underscore = visibility.is_public() && name == kw::Underscore; let current_mod = cx.tcx.parent_module_from_def_id(import.def_id); // The parent of the module in which this import resides. This // is the same as `current_mod` if that's already the top // level module. let parent_mod = cx.tcx.parent_module_from_def_id(current_mod); // This checks if the import can be seen from a higher level module. // In other words, it checks if the visibility is the equivalent of // `pub(super)` or higher. If the current module is the top level // module, there isn't really a parent module, which makes the results // meaningless. In this case, we make sure the answer is `false`. let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx) && !current_mod.is_top_level_module(); if pub_underscore { if let Some(ref inline) = inline_attr { rustc_errors::struct_span_err!("} {"_id":"doc-en-rust-d283edc964c1f73474a0759b2086e74ae6986e391404c48166fec4cf72c7f9c3","title":"","text":"// #[doc(no_inline)] attribute is present. // Don't inline doc(hidden) imports so they can be stripped at a later stage. let mut denied = !(visibility.is_public() || (cx.render_options.document_private && visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx))) || (cx.render_options.document_private && is_visible_from_parent_mod)) || pub_underscore || attrs.iter().any(|a| { a.has_name(sym::doc)"} {"_id":"doc-en-rust-0b6596683aa237f95ac07405d1314ea14a60d446a6eb86d0524d5e1d91a8ebce","title":"","text":"&raw const $place } pub macro addr_of_crate($place:expr) { &raw const $place } pub macro addr_of_super($place:expr) { &raw const $place } pub macro addr_of_self($place:expr) { &raw const $place } pub macro addr_of_crate($place:expr) { pub macro addr_of_local($place:expr) { &raw const $place } pub struct Foo; pub struct FooSelf; pub struct FooCrate; pub struct FooSuper; pub struct FooSelf; pub struct FooLocal; pub enum Bar { Foo, } pub enum BarSelf { Foo, } pub enum BarCrate { Foo, } pub enum BarSuper { Foo, } pub enum BarSelf { Foo, } pub enum BarLocal { Foo, } pub fn foo() {} pub fn foo_self() {} pub fn foo_crate() {} pub fn foo_super() {} pub fn foo_self() {} pub fn foo_local() {} pub type Type = i32; pub type TypeSelf = i32; pub type TypeCrate = i32; pub type TypeSuper = i32; pub type TypeSelf = i32; pub type TypeLocal = i32; pub union Union { a: i8, b: i8, } pub union UnionCrate { a: i8, b: i8, } pub union UnionSuper { a: i8, b: i8, } pub union UnionSelf { a: i8, b: i8, } pub union UnionCrate { pub union UnionLocal { a: i8, b: i8, }"} {"_id":"doc-en-rust-b056f9cabace3bbf477f99141b6a174501734bf3c8336a89ba304993dab8ceca","title":"","text":"// @has 'foo/macro.addr_of.html' '//*[@class=\"docblock item-decl\"]' 'pub macro addr_of($place : expr) {' pub use reexports::addr_of; // @has 'foo/macro.addr_of_crate.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) macro addr_of_crate($place : expr) {' // @!has 'foo/macro.addr_of_crate.html' pub(crate) use reexports::addr_of_crate; // @has 'foo/macro.addr_of_self.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) macro addr_of_self($place : expr) {' // @!has 'foo/macro.addr_of_self.html' pub(self) use reexports::addr_of_self; // @!has 'foo/macro.addr_of_local.html' use reexports::addr_of_local; // @has 'foo/struct.Foo.html' '//*[@class=\"docblock item-decl\"]' 'pub struct Foo;' pub use reexports::Foo; // @has 'foo/struct.FooCrate.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) struct FooCrate;' // @!has 'foo/struct.FooCrate.html' pub(crate) use reexports::FooCrate; // @has 'foo/struct.FooSelf.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) struct FooSelf;' // @!has 'foo/struct.FooSelf.html' pub(self) use reexports::FooSelf; // @!has 'foo/struct.FooLocal.html' use reexports::FooLocal; // @has 'foo/enum.Bar.html' '//*[@class=\"docblock item-decl\"]' 'pub enum Bar {' pub use reexports::Bar; // @has 'foo/enum.BarCrate.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) enum BarCrate {' // @!has 'foo/enum.BarCrate.html' pub(crate) use reexports::BarCrate; // @has 'foo/enum.BarSelf.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) enum BarSelf {' // @!has 'foo/enum.BarSelf.html' pub(self) use reexports::BarSelf; // @!has 'foo/enum.BarLocal.html' use reexports::BarLocal; // @has 'foo/fn.foo.html' '//*[@class=\"rust fn\"]' 'pub fn foo()' pub use reexports::foo; // @has 'foo/fn.foo_crate.html' '//*[@class=\"rust fn\"]' 'pub(crate) fn foo_crate()' // @!has 'foo/fn.foo_crate.html' pub(crate) use reexports::foo_crate; // @has 'foo/fn.foo_self.html' '//*[@class=\"rust fn\"]' 'pub(crate) fn foo_self()' // @!has 'foo/fn.foo_self.html' pub(self) use reexports::foo_self; // @!has 'foo/fn.foo_local.html' use reexports::foo_local; // @has 'foo/type.Type.html' '//*[@class=\"rust typedef\"]' 'pub type Type =' pub use reexports::Type; // @has 'foo/type.TypeCrate.html' '//*[@class=\"rust typedef\"]' 'pub(crate) type TypeCrate =' // @!has 'foo/type.TypeCrate.html' pub(crate) use reexports::TypeCrate; // @has 'foo/type.TypeSelf.html' '//*[@class=\"rust typedef\"]' 'pub(crate) type TypeSelf =' // @!has 'foo/type.TypeSelf.html' pub(self) use reexports::TypeSelf; // @!has 'foo/type.TypeLocal.html' use reexports::TypeLocal; // @has 'foo/union.Union.html' '//*[@class=\"docblock item-decl\"]' 'pub union Union {' pub use reexports::Union; // @has 'foo/union.UnionCrate.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) union UnionCrate {' // @!has 'foo/union.UnionCrate.html' pub(crate) use reexports::UnionCrate; // @has 'foo/union.UnionSelf.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) union UnionSelf {' // @!has 'foo/union.UnionSelf.html' pub(self) use reexports::UnionSelf; // @!has 'foo/union.UnionLocal.html' use reexports::UnionLocal; pub mod foo { // @!has 'foo/foo/union.Union.html' use crate::reexports::Union; pub mod outer { pub mod inner { // @has 'foo/outer/inner/macro.addr_of.html' '//*[@class=\"docblock item-decl\"]' 'pub macro addr_of($place : expr) {' pub use reexports::addr_of; // @has 'foo/outer/inner/macro.addr_of_crate.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) macro addr_of_crate($place : expr) {' pub(crate) use reexports::addr_of_crate; // @has 'foo/outer/inner/macro.addr_of_super.html' '//*[@class=\"docblock item-decl\"]' 'pub(in outer) macro addr_of_super($place : expr) {' pub(super) use reexports::addr_of_super; // @!has 'foo/outer/inner/macro.addr_of_self.html' pub(self) use reexports::addr_of_self; // @!has 'foo/outer/inner/macro.addr_of_local.html' use reexports::addr_of_local; // @has 'foo/outer/inner/struct.Foo.html' '//*[@class=\"docblock item-decl\"]' 'pub struct Foo;' pub use reexports::Foo; // @has 'foo/outer/inner/struct.FooCrate.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) struct FooCrate;' pub(crate) use reexports::FooCrate; // @has 'foo/outer/inner/struct.FooSuper.html' '//*[@class=\"docblock item-decl\"]' 'pub(in outer) struct FooSuper;' pub(super) use reexports::FooSuper; // @!has 'foo/outer/inner/struct.FooSelf.html' pub(self) use reexports::FooSelf; // @!has 'foo/outer/inner/struct.FooLocal.html' use reexports::FooLocal; // @has 'foo/outer/inner/enum.Bar.html' '//*[@class=\"docblock item-decl\"]' 'pub enum Bar {' pub use reexports::Bar; // @has 'foo/outer/inner/enum.BarCrate.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) enum BarCrate {' pub(crate) use reexports::BarCrate; // @has 'foo/outer/inner/enum.BarSuper.html' '//*[@class=\"docblock item-decl\"]' 'pub(in outer) enum BarSuper {' pub(super) use reexports::BarSuper; // @!has 'foo/outer/inner/enum.BarSelf.html' pub(self) use reexports::BarSelf; // @!has 'foo/outer/inner/enum.BarLocal.html' use reexports::BarLocal; // @has 'foo/outer/inner/fn.foo.html' '//*[@class=\"rust fn\"]' 'pub fn foo()' pub use reexports::foo; // @has 'foo/outer/inner/fn.foo_crate.html' '//*[@class=\"rust fn\"]' 'pub(crate) fn foo_crate()' pub(crate) use reexports::foo_crate; // @has 'foo/outer/inner/fn.foo_super.html' '//*[@class=\"rust fn\"]' 'pub(in outer) fn foo_super()' pub(super) use::reexports::foo_super; // @!has 'foo/outer/inner/fn.foo_self.html' pub(self) use reexports::foo_self; // @!has 'foo/outer/inner/fn.foo_local.html' use reexports::foo_local; // @has 'foo/outer/inner/type.Type.html' '//*[@class=\"rust typedef\"]' 'pub type Type =' pub use reexports::Type; // @has 'foo/outer/inner/type.TypeCrate.html' '//*[@class=\"rust typedef\"]' 'pub(crate) type TypeCrate =' pub(crate) use reexports::TypeCrate; // @has 'foo/outer/inner/type.TypeSuper.html' '//*[@class=\"rust typedef\"]' 'pub(in outer) type TypeSuper =' pub(super) use reexports::TypeSuper; // @!has 'foo/outer/inner/type.TypeSelf.html' pub(self) use reexports::TypeSelf; // @!has 'foo/outer/inner/type.TypeLocal.html' use reexports::TypeLocal; // @has 'foo/outer/inner/union.Union.html' '//*[@class=\"docblock item-decl\"]' 'pub union Union {' pub use reexports::Union; // @has 'foo/outer/inner/union.UnionCrate.html' '//*[@class=\"docblock item-decl\"]' 'pub(crate) union UnionCrate {' pub(crate) use reexports::UnionCrate; // @has 'foo/outer/inner/union.UnionSuper.html' '//*[@class=\"docblock item-decl\"]' 'pub(in outer) union UnionSuper {' pub(super) use reexports::UnionSuper; // @!has 'foo/outer/inner/union.UnionSelf.html' pub(self) use reexports::UnionSelf; // @!has 'foo/outer/inner/union.UnionLocal.html' use reexports::UnionLocal; } } mod re_re_exports { // @!has 'foo/re_re_exports/union.Union.html' use crate::reexports::Union; }"} {"_id":"doc-en-rust-c9b1e6e32c1f07c5aad2497770cc259d360f3dde9e9ff56636891c769943a82b","title":"","text":"pub(crate) use reexports::addr_of_crate; // @!has 'foo/macro.addr_of_self.html' pub(self) use reexports::addr_of_self; // @!has 'foo/macro.addr_of_local.html' use reexports::addr_of_local; // @has 'foo/struct.Foo.html' '//*[@class=\"docblock item-decl\"]' 'pub struct Foo;' pub use reexports::Foo;"} {"_id":"doc-en-rust-0b84bb52a825d36498ffea7fbefb09d69515ed53657294531b93e8ea8dc42b92","title":"","text":"pub(crate) use reexports::FooCrate; // @!has 'foo/struct.FooSelf.html' pub(self) use reexports::FooSelf; // @!has 'foo/struct.FooLocal.html' use reexports::FooLocal; // @has 'foo/enum.Bar.html' '//*[@class=\"docblock item-decl\"]' 'pub enum Bar {' pub use reexports::Bar;"} {"_id":"doc-en-rust-7865fc8455905c6414c62c2859f05812e5d52d164ea6012272760be35869e0a9","title":"","text":"pub(crate) use reexports::BarCrate; // @!has 'foo/enum.BarSelf.html' pub(self) use reexports::BarSelf; // @!has 'foo/enum.BarLocal.html' use reexports::BarLocal; // @has 'foo/fn.foo.html' '//*[@class=\"rust fn\"]' 'pub fn foo()' pub use reexports::foo;"} {"_id":"doc-en-rust-66523ca3ee32811847efa05eb1c2f6873168cca22bfce0fd01e4089bec95fc99","title":"","text":"pub(crate) use reexports::foo_crate; // @!has 'foo/fn.foo_self.html' pub(self) use reexports::foo_self; // @!has 'foo/fn.foo_local.html' use reexports::foo_local; // @has 'foo/type.Type.html' '//*[@class=\"rust typedef\"]' 'pub type Type =' pub use reexports::Type;"} {"_id":"doc-en-rust-7201490c9ba0bdac91e30debc2a5db7579802b94b3ee7e3919266ffe8a6eb591","title":"","text":"pub(crate) use reexports::TypeCrate; // @!has 'foo/type.TypeSelf.html' pub(self) use reexports::TypeSelf; // @!has 'foo/type.TypeLocal.html' use reexports::TypeLocal; // @has 'foo/union.Union.html' '//*[@class=\"docblock item-decl\"]' 'pub union Union {' pub use reexports::Union;"} {"_id":"doc-en-rust-c4962a870ab2a19ad278ed1f7745de91c658f59b68692daa04c34d5c9a3a335f","title":"","text":"pub(crate) use reexports::UnionCrate; // @!has 'foo/union.UnionSelf.html' pub(self) use reexports::UnionSelf; // @!has 'foo/union.UnionLocal.html' use reexports::UnionLocal; pub mod outer { pub mod inner { // @has 'foo/outer/inner/macro.addr_of.html' '//*[@class=\"docblock item-decl\"]' 'pub macro addr_of($place : expr) {' pub use reexports::addr_of; // @!has 'foo/outer/inner/macro.addr_of_crate.html' pub(crate) use reexports::addr_of_crate; // @!has 'foo/outer/inner/macro.addr_of_super.html' pub(super) use reexports::addr_of_super; // @!has 'foo/outer/inner/macro.addr_of_self.html' pub(self) use reexports::addr_of_self; // @!has 'foo/outer/inner/macro.addr_of_local.html' use reexports::addr_of_local; // @has 'foo/outer/inner/struct.Foo.html' '//*[@class=\"docblock item-decl\"]' 'pub struct Foo;' pub use reexports::Foo; // @!has 'foo/outer/inner/struct.FooCrate.html' pub(crate) use reexports::FooCrate; // @!has 'foo/outer/inner/struct.FooSuper.html' pub(super) use reexports::FooSuper; // @!has 'foo/outer/inner/struct.FooSelf.html' pub(self) use reexports::FooSelf; // @!has 'foo/outer/inner/struct.FooLocal.html' use reexports::FooLocal; // @has 'foo/outer/inner/enum.Bar.html' '//*[@class=\"docblock item-decl\"]' 'pub enum Bar {' pub use reexports::Bar; // @!has 'foo/outer/inner/enum.BarCrate.html' pub(crate) use reexports::BarCrate; // @!has 'foo/outer/inner/enum.BarSuper.html' pub(super) use reexports::BarSuper; // @!has 'foo/outer/inner/enum.BarSelf.html' pub(self) use reexports::BarSelf; // @!has 'foo/outer/inner/enum.BarLocal.html' use reexports::BarLocal; // @has 'foo/outer/inner/fn.foo.html' '//*[@class=\"rust fn\"]' 'pub fn foo()' pub use reexports::foo; // @!has 'foo/outer/inner/fn.foo_crate.html' pub(crate) use reexports::foo_crate; // @!has 'foo/outer/inner/fn.foo_super.html' pub(super) use::reexports::foo_super; // @!has 'foo/outer/inner/fn.foo_self.html' pub(self) use reexports::foo_self; // @!has 'foo/outer/inner/fn.foo_local.html' use reexports::foo_local; // @has 'foo/outer/inner/type.Type.html' '//*[@class=\"rust typedef\"]' 'pub type Type =' pub use reexports::Type; // @!has 'foo/outer/inner/type.TypeCrate.html' pub(crate) use reexports::TypeCrate; // @!has 'foo/outer/inner/type.TypeSuper.html' pub(super) use reexports::TypeSuper; // @!has 'foo/outer/inner/type.TypeSelf.html' pub(self) use reexports::TypeSelf; // @!has 'foo/outer/inner/type.TypeLocal.html' use reexports::TypeLocal; // @has 'foo/outer/inner/union.Union.html' '//*[@class=\"docblock item-decl\"]' 'pub union Union {' pub use reexports::Union; // @!has 'foo/outer/inner/union.UnionCrate.html' pub(crate) use reexports::UnionCrate; // @!has 'foo/outer/inner/union.UnionSuper.html' pub(super) use reexports::UnionSuper; // @!has 'foo/outer/inner/union.UnionSelf.html' pub(self) use reexports::UnionSelf; // @!has 'foo/outer/inner/union.UnionLocal.html' use reexports::UnionLocal; } } "} {"_id":"doc-en-rust-6d007ea5409aa67d449d57e45a58cb67bc6ac903c0c70932520431936e442db2","title":"","text":" // check-pass pub trait Associate { type Associated; } pub struct Wrap<'a> { pub field: &'a i32, } pub trait Create { fn create() -> Self; } pub fn oh_no<'a, T>() where Wrap<'a>: Associate, as Associate>::Associated: Create, { as Associate>::Associated::create(); } pub fn main() {} "} {"_id":"doc-en-rust-4b6acae815e178899e33c5fb9cd99877b84d3b340566963e1991fb78369a3665","title":"","text":" // check-pass #![feature(generic_associated_types)] trait Foo { type Type<'a> where T: 'a; } impl Foo for () { type Type<'a> where T: 'a, = (); } fn foo() { let _: for<'a> fn(<() as Foo>::Type<'a>, &'a T) = |_, _| (); } pub fn main() {} "} {"_id":"doc-en-rust-8e6ca9082e1cec4114da9836db922a8e739fd161231783f385ae14a1c3a9e0d0","title":"","text":"(active, c_unwind, \"1.52.0\", Some(74990), None), /// Allows using C-variadics. (active, c_variadic, \"1.34.0\", Some(44930), None), /// Allows the use of `#[cfg(overflow_checks)` to check if integer overflow behaviour. (active, cfg_overflow_checks, \"CURRENT_RUSTC_VERSION\", Some(111466), None), /// Allows the use of `#[cfg(sanitize = \"option\")]`; set when -Zsanitizer is used. (active, cfg_sanitize, \"1.41.0\", Some(39699), None), /// Allows `cfg(target_abi = \"...\")`."} {"_id":"doc-en-rust-1ee5e599dd26a538e8879c1e31ea258d62c363566733d4753dc24ea8e2e4d8da","title":"","text":"/// `cfg(...)`'s that are feature gated. const GATED_CFGS: &[GatedCfg] = &[ // (name in cfg, feature, function to check if the feature is enabled) (sym::overflow_checks, sym::cfg_overflow_checks, cfg_fn!(cfg_overflow_checks)), (sym::target_abi, sym::cfg_target_abi, cfg_fn!(cfg_target_abi)), (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)), ("} {"_id":"doc-en-rust-5e93bebc8106546f35241514e88607c7efe149615d23fedb8e5d17f514edc548","title":"","text":"if sess.opts.debug_assertions { ret.insert((sym::debug_assertions, None)); } if sess.overflow_checks() { ret.insert((sym::overflow_checks, None)); } // JUSTIFICATION: before wrapper fn is available #[allow(rustc::bad_opt_access)] if sess.opts.crate_types.contains(&CrateType::ProcMacro) {"} {"_id":"doc-en-rust-a801a9a6affdd7c2b26d28829affca8967098efdfa7fdb4bcf262b1f1736642d","title":"","text":"sym::windows, sym::proc_macro, sym::debug_assertions, sym::overflow_checks, sym::target_thread_local, ] { self.expecteds.entry(name).or_insert_with(no_values);"} {"_id":"doc-en-rust-f91741b7d8694a3e7fdf67a679d8f0ffc704c6e4ca896683c83f154eef32d6d7","title":"","text":"cfg_doctest, cfg_eval, cfg_hide, cfg_overflow_checks, cfg_panic, cfg_sanitize, cfg_target_abi,"} {"_id":"doc-en-rust-54d9193b9f6af94dc696ead2a01996fe27be95afe283bf1c4b3349dbbc0e6119","title":"","text":"or_patterns, other, out, overflow_checks, overlapping_marker_traits, owned_box, packed,"} {"_id":"doc-en-rust-cd16e4e5317d3c175056e8795b83546a38f6be0c5e4a0c649243888d6849f49d","title":"","text":" #![crate_type = \"lib\"] #[cfg(overflow_checks)] //~ ERROR `cfg(overflow_checks)` is experimental pub fn cast(v: i64)->u32{ todo!() } "} {"_id":"doc-en-rust-7bdd63f6a3e68fe4e722864dfccbceb98ef1a40084af9d0e32f58e202fd88317","title":"","text":" error[E0658]: `cfg(overflow_checks)` is experimental and subject to change --> $DIR/feature-gate-cfg_overflow_checks.rs:3:7 | LL | #[cfg(overflow_checks)] | ^^^^^^^^^^^^^^^ | = note: see issue #111466 for more information = help: add `#![feature(cfg_overflow_checks)]` to the crate attributes to enable error: aborting due to previous error For more information about this error, try `rustc --explain E0658`. "} {"_id":"doc-en-rust-2ad1c62208d5ff64702dbb305f12ac7cbcf455b7f85ee50d45a9d9dcf6c98fb0","title":"","text":" // run-pass // compile-flags: -C overflow_checks=true #![feature(cfg_overflow_checks)] fn main() { assert!(cfg!(overflow_checks)); assert!(compiles_differently()); } #[cfg(overflow_checks)] fn compiles_differently()->bool { true } #[cfg(not(overflow_checks))] fn compiles_differently()->bool { false } "} {"_id":"doc-en-rust-7b6f27a364a75778de4dd09f94baaa665c4339e6925cf42f49d803d7e37a336f","title":"","text":" // run-pass // compile-flags: -C overflow_checks=false #![feature(cfg_overflow_checks)] fn main() { assert!(!cfg!(overflow_checks)); assert!(!compiles_differently()); } #[cfg(overflow_checks)] fn compiles_differently()->bool { true } #[cfg(not(overflow_checks))] fn compiles_differently()->bool { false } "} {"_id":"doc-en-rust-956cdc78628fd71146477c9177a3fb194330e4ef607ab0967f05a2a51f53639d","title":"","text":"// substitutions. use crate::check::FnCtxt; use hir::def_id::LocalDefId; use rustc_data_structures::fx::FxHashMap; use rustc_errors::ErrorGuaranteed;"} {"_id":"doc-en-rust-8e548a738e4622d447f01cce8ccf2de1cdaacc03add857c1dcbe7990f77a5d1b","title":"","text":"use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCast}; use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable}; use rustc_middle::ty::TypeckResults; use rustc_middle::ty::{self, ClosureSizeProfileData, Ty, TyCtxt}; use rustc_span::symbol::sym; use rustc_span::Span;"} {"_id":"doc-en-rust-b1aec8f23be77166f572d9533b28c673d81e67bfa09db2881d6613ccdbcd736d","title":"","text":"} } // (ouz-a 1005988): Normally `[T] : std::ops::Index` should be normalized // into [T] but currently `Where` clause stops the normalization process for it, // here we compare types of expr and base in a code without `Where` clause they would be equal // if they are not we don't modify the expr, hence we bypass the ICE fn is_builtin_index( &mut self, typeck_results: &TypeckResults<'tcx>, e: &hir::Expr<'_>, base_ty: Ty<'tcx>, index_ty: Ty<'tcx>, ) -> bool { if let Some(elem_ty) = base_ty.builtin_index() { let Some(exp_ty) = typeck_results.expr_ty_opt(e) else {return false;}; let resolved_exp_ty = self.resolve(exp_ty, &e.span); elem_ty == resolved_exp_ty && index_ty == self.fcx.tcx.types.usize } else { false } } // Similar to operators, indexing is always assumed to be overloaded // Here, correct cases where an indexing expression can be simplified // to use builtin indexing because the index type is known to be"} {"_id":"doc-en-rust-6b157768922fcd29ac1d018ae7a909972ccae2a689995541d8f5949ad4c013b9","title":"","text":") }); let index_ty = self.fcx.resolve_vars_if_possible(index_ty); let resolved_base_ty = self.resolve(*base_ty, &base.span); if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize { if self.is_builtin_index(&typeck_results, e, resolved_base_ty, index_ty) { // Remove the method call record typeck_results.type_dependent_defs_mut().remove(e.hir_id); typeck_results.node_substs_mut().remove(e.hir_id);"} {"_id":"doc-en-rust-dbb3bccb385db3d19a835725ac69403db49a5497652658b8e154bb4e0784bfd7","title":"","text":" // compile-flags: -Z mir-opt-level=0 // EMIT_MIR issue_91633.hey.mir_map.0.mir fn hey (it: &[T]) where [T] : std::ops::Index, { let _ = &it[0]; } // EMIT_MIR issue_91633.bar.mir_map.0.mir fn bar (it: Box<[T]>) where [T] : std::ops::Index, { let _ = it[0]; } // EMIT_MIR issue_91633.fun.mir_map.0.mir fn fun (it: &[T]) -> &T { let f = &it[0]; f } // EMIT_MIR issue_91633.foo.mir_map.0.mir fn foo (it: Box<[T]>) -> T { let f = it[0].clone(); f } fn main(){} "} {"_id":"doc-en-rust-f1ba15cf40a74d3f904b0e238c216070968c79ecee9321bd6a5827261c997bd5","title":"","text":" // MIR for `bar` 0 mir_map fn bar(_1: Box<[T]>) -> () { debug it => _1; // in scope 0 at $DIR/issue-91633.rs:+0:12: +0:14 let mut _0: (); // return place in scope 0 at $DIR/issue-91633.rs:+1:2: +1:2 let mut _2: &<[T] as std::ops::Index>::Output; // in scope 0 at $DIR/issue-91633.rs:+4:14: +4:19 let mut _3: &[T]; // in scope 0 at $DIR/issue-91633.rs:+4:14: +4:16 scope 1 { } bb0: { StorageLive(_2); // scope 0 at $DIR/issue-91633.rs:+4:14: +4:19 StorageLive(_3); // scope 0 at $DIR/issue-91633.rs:+4:14: +4:16 _3 = &(*_1); // scope 0 at $DIR/issue-91633.rs:+4:14: +4:16 _2 = <[T] as Index>::index(move _3, const 0_usize) -> [return: bb1, unwind: bb3]; // scope 0 at $DIR/issue-91633.rs:+4:14: +4:19 // mir::Constant // + span: $DIR/issue-91633.rs:15:14: 15:19 // + literal: Const { ty: for<'r> fn(&'r [T], usize) -> &'r <[T] as Index>::Output {<[T] as Index>::index}, val: Value() } } bb1: { StorageDead(_3); // scope 0 at $DIR/issue-91633.rs:+4:18: +4:19 StorageDead(_2); // scope 0 at $DIR/issue-91633.rs:+4:19: +4:20 _0 = const (); // scope 0 at $DIR/issue-91633.rs:+3:2: +5:3 drop(_1) -> [return: bb2, unwind: bb4]; // scope 0 at $DIR/issue-91633.rs:+5:2: +5:3 } bb2: { return; // scope 0 at $DIR/issue-91633.rs:+5:3: +5:3 } bb3 (cleanup): { drop(_1) -> bb4; // scope 0 at $DIR/issue-91633.rs:+5:2: +5:3 } bb4 (cleanup): { resume; // scope 0 at $DIR/issue-91633.rs:+0:1: +5:3 } } "} {"_id":"doc-en-rust-ece496af52f69c795f7381998260cbf836b6450b6f2c9a122af8c6ef004e25d0","title":"","text":" // MIR for `foo` 0 mir_map fn foo(_1: Box<[T]>) -> T { debug it => _1; // in scope 0 at $DIR/issue-91633.rs:+0:19: +0:21 let mut _0: T; // return place in scope 0 at $DIR/issue-91633.rs:+0:36: +0:37 let _2: T; // in scope 0 at $DIR/issue-91633.rs:+2:10: +2:11 let mut _3: &T; // in scope 0 at $DIR/issue-91633.rs:+2:14: +2:27 let _4: usize; // in scope 0 at $DIR/issue-91633.rs:+2:17: +2:18 let mut _5: usize; // in scope 0 at $DIR/issue-91633.rs:+2:14: +2:19 let mut _6: bool; // in scope 0 at $DIR/issue-91633.rs:+2:14: +2:19 scope 1 { debug f => _2; // in scope 1 at $DIR/issue-91633.rs:+2:10: +2:11 } bb0: { StorageLive(_2); // scope 0 at $DIR/issue-91633.rs:+2:10: +2:11 StorageLive(_3); // scope 0 at $DIR/issue-91633.rs:+2:14: +2:27 StorageLive(_4); // scope 0 at $DIR/issue-91633.rs:+2:17: +2:18 _4 = const 0_usize; // scope 0 at $DIR/issue-91633.rs:+2:17: +2:18 _5 = Len((*_1)); // scope 0 at $DIR/issue-91633.rs:+2:14: +2:19 _6 = Lt(_4, _5); // scope 0 at $DIR/issue-91633.rs:+2:14: +2:19 assert(move _6, \"index out of bounds: the length is {} but the index is {}\", move _5, _4) -> [success: bb1, unwind: bb5]; // scope 0 at $DIR/issue-91633.rs:+2:14: +2:19 } bb1: { _3 = &(*_1)[_4]; // scope 0 at $DIR/issue-91633.rs:+2:14: +2:27 _2 = ::clone(move _3) -> [return: bb2, unwind: bb5]; // scope 0 at $DIR/issue-91633.rs:+2:14: +2:27 // mir::Constant // + span: $DIR/issue-91633.rs:28:20: 28:25 // + literal: Const { ty: for<'r> fn(&'r T) -> T {::clone}, val: Value() } } bb2: { StorageDead(_3); // scope 0 at $DIR/issue-91633.rs:+2:26: +2:27 FakeRead(ForLet(None), _2); // scope 0 at $DIR/issue-91633.rs:+2:10: +2:11 StorageDead(_4); // scope 0 at $DIR/issue-91633.rs:+2:27: +2:28 _0 = move _2; // scope 1 at $DIR/issue-91633.rs:+3:6: +3:7 drop(_2) -> [return: bb3, unwind: bb5]; // scope 0 at $DIR/issue-91633.rs:+4:2: +4:3 } bb3: { StorageDead(_2); // scope 0 at $DIR/issue-91633.rs:+4:2: +4:3 drop(_1) -> [return: bb4, unwind: bb6]; // scope 0 at $DIR/issue-91633.rs:+4:2: +4:3 } bb4: { return; // scope 0 at $DIR/issue-91633.rs:+4:3: +4:3 } bb5 (cleanup): { drop(_1) -> bb6; // scope 0 at $DIR/issue-91633.rs:+4:2: +4:3 } bb6 (cleanup): { resume; // scope 0 at $DIR/issue-91633.rs:+0:1: +4:3 } } "} {"_id":"doc-en-rust-f3740c25fc38754a68d70824f25ea4b5382a15e49a8a2027e8120a5fd9da2120","title":"","text":" // MIR for `fun` 0 mir_map fn fun(_1: &[T]) -> &T { debug it => _1; // in scope 0 at $DIR/issue-91633.rs:+0:12: +0:14 let mut _0: &T; // return place in scope 0 at $DIR/issue-91633.rs:+0:25: +0:27 let _2: &T; // in scope 0 at $DIR/issue-91633.rs:+2:10: +2:11 let _3: usize; // in scope 0 at $DIR/issue-91633.rs:+2:18: +2:19 let mut _4: usize; // in scope 0 at $DIR/issue-91633.rs:+2:15: +2:20 let mut _5: bool; // in scope 0 at $DIR/issue-91633.rs:+2:15: +2:20 scope 1 { debug f => _2; // in scope 1 at $DIR/issue-91633.rs:+2:10: +2:11 } bb0: { StorageLive(_2); // scope 0 at $DIR/issue-91633.rs:+2:10: +2:11 StorageLive(_3); // scope 0 at $DIR/issue-91633.rs:+2:18: +2:19 _3 = const 0_usize; // scope 0 at $DIR/issue-91633.rs:+2:18: +2:19 _4 = Len((*_1)); // scope 0 at $DIR/issue-91633.rs:+2:15: +2:20 _5 = Lt(_3, _4); // scope 0 at $DIR/issue-91633.rs:+2:15: +2:20 assert(move _5, \"index out of bounds: the length is {} but the index is {}\", move _4, _3) -> [success: bb1, unwind: bb2]; // scope 0 at $DIR/issue-91633.rs:+2:15: +2:20 } bb1: { _2 = &(*_1)[_3]; // scope 0 at $DIR/issue-91633.rs:+2:14: +2:20 FakeRead(ForLet(None), _2); // scope 0 at $DIR/issue-91633.rs:+2:10: +2:11 _0 = &(*_2); // scope 1 at $DIR/issue-91633.rs:+3:6: +3:7 StorageDead(_3); // scope 0 at $DIR/issue-91633.rs:+4:2: +4:3 StorageDead(_2); // scope 0 at $DIR/issue-91633.rs:+4:2: +4:3 return; // scope 0 at $DIR/issue-91633.rs:+4:3: +4:3 } bb2 (cleanup): { resume; // scope 0 at $DIR/issue-91633.rs:+0:1: +4:3 } } "} {"_id":"doc-en-rust-ff818a3731fa1364bd3682541bb9ced95e8022e1e281c53bd6edf236ed61329d","title":"","text":" // MIR for `hey` 0 mir_map fn hey(_1: &[T]) -> () { debug it => _1; // in scope 0 at $DIR/issue-91633.rs:+0:12: +0:14 let mut _0: (); // return place in scope 0 at $DIR/issue-91633.rs:+1:2: +1:2 let mut _2: &<[T] as std::ops::Index>::Output; // in scope 0 at $DIR/issue-91633.rs:+4:14: +4:20 let _3: &<[T] as std::ops::Index>::Output; // in scope 0 at $DIR/issue-91633.rs:+4:15: +4:20 let mut _4: &[T]; // in scope 0 at $DIR/issue-91633.rs:+4:15: +4:17 scope 1 { } bb0: { StorageLive(_2); // scope 0 at $DIR/issue-91633.rs:+4:14: +4:20 StorageLive(_3); // scope 0 at $DIR/issue-91633.rs:+4:15: +4:20 StorageLive(_4); // scope 0 at $DIR/issue-91633.rs:+4:15: +4:17 _4 = &(*_1); // scope 0 at $DIR/issue-91633.rs:+4:15: +4:17 _3 = <[T] as Index>::index(move _4, const 0_usize) -> [return: bb1, unwind: bb2]; // scope 0 at $DIR/issue-91633.rs:+4:15: +4:20 // mir::Constant // + span: $DIR/issue-91633.rs:7:15: 7:20 // + literal: Const { ty: for<'r> fn(&'r [T], usize) -> &'r <[T] as Index>::Output {<[T] as Index>::index}, val: Value() } } bb1: { StorageDead(_4); // scope 0 at $DIR/issue-91633.rs:+4:19: +4:20 _2 = &(*_3); // scope 0 at $DIR/issue-91633.rs:+4:14: +4:20 StorageDead(_2); // scope 0 at $DIR/issue-91633.rs:+4:20: +4:21 _0 = const (); // scope 0 at $DIR/issue-91633.rs:+3:2: +5:3 StorageDead(_3); // scope 0 at $DIR/issue-91633.rs:+5:2: +5:3 return; // scope 0 at $DIR/issue-91633.rs:+5:3: +5:3 } bb2 (cleanup): { resume; // scope 0 at $DIR/issue-91633.rs:+0:1: +5:3 } } "} {"_id":"doc-en-rust-b9b7160ff1452791dd49e223b5555f11243fdd9f68bba37bf22bd7a145303c9c","title":"","text":" // check-pass fn f (it: &[T]) where [T] : std::ops::Index, { let _ = &it[0]; } fn main(){} "} {"_id":"doc-en-rust-52da2e737317144111bd5d02581fcdd35e64cf5fcfde0d3d673079aba237b452","title":"","text":"db.span_note(glob_reexport_span, format!(\"the name `{}` in the {} namespace is supposed to be publicly re-exported here\", name, namespace)); db.span_note(private_item_span, \"but the private item here shadows it\".to_owned()); } BuiltinLintDiagnostics::UnusedQualifications { path_span, unqualified_path } => { db.span_suggestion_verbose( path_span, \"replace it with the unqualified path\", unqualified_path, Applicability::MachineApplicable ); } } // Rewrap `db`, and pass control to the user. decorate(db)"} {"_id":"doc-en-rust-594909b042850d77f285fc7e925ac2051320d3439267c346a97c70856eeff449","title":"","text":"/// The local binding that shadows the glob reexport. private_item_span: Span, }, UnusedQualifications { /// The span of the unnecessarily-qualified path. path_span: Span, /// The replacement unqualified path. unqualified_path: Ident, }, } /// Lints that are buffered up early on in the `Session` before the"} {"_id":"doc-en-rust-0639b400fc9dd5fc57c62c3ec7efc954ea3b9ed59716532626a6ff5f71a54780","title":"","text":"}; if res == unqualified_result { let lint = lint::builtin::UNUSED_QUALIFICATIONS; self.r.lint_buffer.buffer_lint( self.r.lint_buffer.buffer_lint_with_diagnostic( lint, finalize.node_id, finalize.path_span, \"unnecessary qualification\", lint::BuiltinLintDiagnostics::UnusedQualifications { path_span: finalize.path_span, unqualified_path: path.last().unwrap().ident } ) } }"} {"_id":"doc-en-rust-c346d222b71273239719bf43c01a94b99f984967c8e6957f6a02f283054b2fa4","title":"","text":"| LL | #![deny(unused_qualifications)] | ^^^^^^^^^^^^^^^^^^^^^ help: replace it with the unqualified path | LL | bar(); | ~~~ error: aborting due to previous error"} {"_id":"doc-en-rust-660b4c6d3feb42f092bdcc3b8935ce21264ff2d45f1f3cd1969676008870dfe9","title":"","text":" // run-rustfix #![deny(unused_qualifications)] mod foo { pub fn bar() {} } mod baz { pub mod qux { pub fn quux() {} } } fn main() { use foo::bar; bar(); //~^ ERROR unnecessary qualification use baz::qux::quux; quux(); //~^ ERROR unnecessary qualification } "} {"_id":"doc-en-rust-8127cba2b2c35218c19b09278bbed7f809b66e9b07ebefdb30b18c8c6e642753","title":"","text":" // run-rustfix #![deny(unused_qualifications)] mod foo { pub fn bar() {} } mod baz { pub mod qux { pub fn quux() {} } } fn main() { use foo::bar; foo::bar(); //~^ ERROR unnecessary qualification use baz::qux::quux; baz::qux::quux(); //~^ ERROR unnecessary qualification } "} {"_id":"doc-en-rust-4b98863be1f91f1ba79e2d36117e87cea4f16a3a7b7786ec88256a86b1b01c66","title":"","text":" error: unnecessary qualification --> $DIR/unused-qualifications-suggestion.rs:17:5 | LL | foo::bar(); | ^^^^^^^^ | note: the lint level is defined here --> $DIR/unused-qualifications-suggestion.rs:3:9 | LL | #![deny(unused_qualifications)] | ^^^^^^^^^^^^^^^^^^^^^ help: replace it with the unqualified path | LL | bar(); | ~~~ error: unnecessary qualification --> $DIR/unused-qualifications-suggestion.rs:21:5 | LL | baz::qux::quux(); | ^^^^^^^^^^^^^^ | help: replace it with the unqualified path | LL | quux(); | ~~~~ error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-8e3e9347189dd647658f65d91d1398af731f686537bef2c942bb4ff05ed0f6ab","title":"","text":" // edition:2021 use std::iter; fn f(data: &[T]) -> impl Iterator { //~^ ERROR: missing generics for struct `Vec` [E0107] iter::empty() //~ ERROR: type annotations needed [E0282] } fn g(data: &[T], target: T) -> impl Iterator> { //~^ ERROR: type annotations needed [E0282] f(data).filter(|x| x == target) } fn main() {} "} {"_id":"doc-en-rust-b8aa65178091608db1b49f5f228648a355c1f522bf122e22d0bc98a3ba22145b","title":"","text":" error[E0107]: missing generics for struct `Vec` --> $DIR/issue-92305.rs:5:45 | LL | fn f(data: &[T]) -> impl Iterator { | ^^^ expected at least 1 generic argument | note: struct defined here, with at least 1 generic parameter: `T` --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL | LL | pub struct Vec { | ^^^ - help: add missing generic argument | LL | fn f(data: &[T]) -> impl Iterator> { | ~~~~~~ error[E0282]: type annotations needed --> $DIR/issue-92305.rs:7:5 | LL | iter::empty() | ^^^^^^^^^^^ cannot infer type for type parameter `T` declared on the function `empty` error[E0282]: type annotations needed --> $DIR/issue-92305.rs:10:35 | LL | fn g(data: &[T], target: T) -> impl Iterator> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type error: aborting due to 3 previous errors Some errors have detailed explanations: E0107, E0282. For more information about an error, try `rustc --explain E0107`. "} {"_id":"doc-en-rust-ded3e5f49fa1efcf8a4833103679902ab236a2343fcd90b91fe38e584717420c","title":"","text":"saved_locals: &GeneratorSavedLocals, ) { let did = body.source.def_id(); let allowed_upvars = tcx.erase_regions(upvars); let param_env = tcx.param_env(did); let allowed_upvars = tcx.normalize_erasing_regions(param_env, upvars); let allowed = match witness.kind() { &ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(s), &ty::GeneratorWitness(interior_tys) => { tcx.normalize_erasing_late_bound_regions(param_env, interior_tys) } _ => { tcx.sess.delay_span_bug( body.span,"} {"_id":"doc-en-rust-3da43d9631eae95b86116bab5c1ecd31aaa35c913ddbd859731914234d0acace","title":"","text":"} }; let param_env = tcx.param_env(did); for (local, decl) in body.local_decls.iter_enumerated() { // Ignore locals which are internal or not saved between yields. if !saved_locals.contains(local) || decl.internal {"} {"_id":"doc-en-rust-36963cd0718877af6a0756131e360367661a8a734d68a17d3bc26b3256d714c5","title":"","text":" // edition:2018 // run-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] #![allow(unused)] fn main() { let x = test(); } fn concat(a: [f32; A], b: [f32; B]) -> [f32; A + B] { todo!() } async fn reverse(x: [f32; A]) -> [f32; A] { todo!() } async fn test() { let a = [0.0]; let b = [1.0, 2.0]; let ab = concat(a,b); let ba = reverse(ab).await; println!(\"{:?}\", ba); } "} {"_id":"doc-en-rust-51107099db1aa879f70ce2a774cdbac625c29ccd76ffb62eb0ec55eae6e6b2df","title":"","text":"Extern functions may be called directly from Rust code as Rust uses large, contiguous stack segments like C. ### Type definitions ### Type aliases A _type definition_ defines a new name for an existing [type](#types). Type definitions are declared with the keyword `type`. Every value has a single, A _type alias_ defines a new name for an existing [type](#types). Type aliases are declared with the keyword `type`. Every value has a single, specific type; the type-specified aspects of a value include: * Whether the value is composed of sub-values or is indivisible."} {"_id":"doc-en-rust-36cfae5e0319918b1e6db01313bdf66d782e5b1716e78c7e21abd7f8749bacbe","title":"","text":" // Regression test for . #![allow(incomplete_features)] #![feature(generic_const_exprs)] #![crate_name = \"foo\"] // @has 'foo/trait.Foo.html' pub trait Foo: Sized { const WIDTH: usize; fn arrayify(self) -> [Self; Self::WIDTH]; } impl Foo for T { const WIDTH: usize = 1; // @has - '//*[@id=\"tymethod.arrayify\"]/*[@class=\"code-header\"]' // 'fn arrayify(self) -> [Self; Self::WIDTH]' fn arrayify(self) -> [Self; Self::WIDTH] { [self] } } "} {"_id":"doc-en-rust-a354b86ac35d07785647385755bff602e7b55523eadabd643f7b41febc0a3808","title":"","text":"\"clippy_utils\", \"if_chain\", \"itertools 0.10.1\", \"pulldown-cmark 0.9.0\", \"pulldown-cmark\", \"quine-mc_cluskey\", \"regex-syntax\", \"rustc-semver\","} {"_id":"doc-en-rust-baf4ef50582c7c8c19dbffa2f1d36f6e0a86eb8a19d7d7adfc627d2f5df24dd1","title":"","text":"[[package]] name = \"mdbook\" version = \"0.4.14\" version = \"0.4.15\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"f6e77253c46a90eb7e96b2807201dab941a4db5ea05eca5aaaf7027395f352b3\" checksum = \"241f10687eb3b4e0634b3b4e423f97c5f1efbd69dc9522e24a8b94583eeec3c6\" dependencies = [ \"ammonia\", \"anyhow\","} {"_id":"doc-en-rust-b714c10a5e3ded9ab9790015fc28d44b3b7b8b2959ebcfd805ac203eb6298b99","title":"","text":"\"log\", \"memchr\", \"opener\", \"pulldown-cmark 0.8.0\", \"pulldown-cmark\", \"regex\", \"serde\", \"serde_derive\","} {"_id":"doc-en-rust-b8d72ff2d97df6fa0db84ff7ce29f893b7638a9e22c7658ef9bd5ece03506932","title":"","text":"[[package]] name = \"pulldown-cmark\" version = \"0.8.0\" version = \"0.9.1\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"ffade02495f22453cd593159ea2f59827aae7f53fa8323f756799b670881dcf8\" checksum = \"34f197a544b0c9ab3ae46c359a7ec9cbbb5c7bf97054266fecb7ead794a181d6\" dependencies = [ \"bitflags\", \"getopts\","} {"_id":"doc-en-rust-35b4ab7ba205a9f0a913cc2db827eb61646ac041b7cd8c5bb073267c6f6116bb","title":"","text":"] [[package]] name = \"pulldown-cmark\" version = \"0.9.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"acd16514d1af5f7a71f909a44ef253cdb712a376d7ebc8ae4a471a9be9743548\" dependencies = [ \"bitflags\", \"memchr\", \"unicase\", ] [[package]] name = \"punycode\" version = \"0.4.1\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"doc-en-rust-d91bd6789a5ad41a13821e8c2bb45a3224a753386ba1e267f4349667a637edee","title":"","text":"\"expect-test\", \"itertools 0.9.0\", \"minifier\", \"pulldown-cmark 0.9.0\", \"pulldown-cmark\", \"rayon\", \"regex\", \"rustdoc-json-types\","} {"_id":"doc-en-rust-caa0a2ce3f1c7531a1f9f69f7a36fef8c8b5224773178f56d7f099247ee59070","title":"","text":"debug!(?result, \"CACHE MISS\"); self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result); stack.cache().on_completion(stack.dfn, |fresh_trait_pred, provisional_result| { self.insert_evaluation_cache( param_env, fresh_trait_pred, dep_node, provisional_result.max(result), ); }); stack.cache().on_completion( stack.dfn, |fresh_trait_pred, provisional_result, provisional_dep_node| { // Create a new `DepNode` that has dependencies on: // * The `DepNode` for the original evaluation that resulted in a provisional cache // entry being crated // * The `DepNode` for the *current* evaluation, which resulted in us completing // provisional caches entries and inserting them into the evaluation cache // // This ensures that when a query reads this entry from the evaluation cache, // it will end up (transitively) dependening on all of the incr-comp dependencies // created during the evaluation of this trait. For example, evaluating a trait // will usually require us to invoke `type_of(field_def_id)` to determine the // constituent types, and we want any queries reading from this evaluation // cache entry to end up with a transitive `type_of(field_def_id`)` dependency. // // By using `in_task`, we're also creating an edge from the *current* query // to the newly-created `combined_dep_node`. This is probably redundant, // but it's better to add too many dep graph edges than to add too few // dep graph edges. let ((), combined_dep_node) = self.in_task(|this| { this.tcx().dep_graph.read_index(provisional_dep_node); this.tcx().dep_graph.read_index(dep_node); }); self.insert_evaluation_cache( param_env, fresh_trait_pred, combined_dep_node, provisional_result.max(result), ); }, ); } else { debug!(?result, \"PROVISIONAL\"); debug!("} {"_id":"doc-en-rust-0e97e051448bc09d27d9790e6e908ab182a50c25be24e858e1ae37c0c7c5a3e8","title":"","text":"fresh_trait_pred, stack.depth, reached_depth, ); stack.cache().insert_provisional(stack.dfn, reached_depth, fresh_trait_pred, result); stack.cache().insert_provisional( stack.dfn, reached_depth, fresh_trait_pred, result, dep_node, ); } Ok(result)"} {"_id":"doc-en-rust-89cb591bae681668ffd393af45e63e6087891dd0672b3070d1a2361a51cbe7d3","title":"","text":"from_dfn: usize, reached_depth: usize, result: EvaluationResult, /// The `DepNodeIndex` created for the `evaluate_stack` call for this provisional /// evaluation. When we create an entry in the evaluation cache using this provisional /// cache entry (see `on_completion`), we use this `dep_node` to ensure that future reads from /// the cache will have all of the necessary incr comp dependencies tracked. dep_node: DepNodeIndex, } impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {"} {"_id":"doc-en-rust-d043ab034c3bf69edb789a0425f9f6009d55c7f038e608b6ba6072ffbce3b825","title":"","text":"reached_depth: usize, fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, result: EvaluationResult, dep_node: DepNodeIndex, ) { debug!(?from_dfn, ?fresh_trait_pred, ?result, \"insert_provisional\");"} {"_id":"doc-en-rust-ce2d0251bcdb93843377b53dbd61de42f717e4b6149467831ad7fb4f8b405a7b","title":"","text":"} } map.insert(fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result }); map.insert( fresh_trait_pred, ProvisionalEvaluation { from_dfn, reached_depth, result, dep_node }, ); } /// Invoked when the node with dfn `dfn` does not get a successful"} {"_id":"doc-en-rust-70e042a3d4cbc2fe40f45c50597ab1d576711f5c8ab3402ecdd78925fce6e914","title":"","text":"fn on_completion( &self, dfn: usize, mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult), mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult, DepNodeIndex), ) { debug!(?dfn, \"on_completion\");"} {"_id":"doc-en-rust-e0c7fb2fbf152516753d8d9739f71f7630379da02c3f89e8a2614998e6232294","title":"","text":"{ debug!(?fresh_trait_pred, ?eval, \"on_completion\"); op(fresh_trait_pred, eval.result); op(fresh_trait_pred, eval.result, eval.dep_node); } } }"} {"_id":"doc-en-rust-fe177f0b7a02eb44ee8fe53500367368de4012e20691663654a462b9e5c42bdc","title":"","text":" // revisions: rpass1 rpass2 // Regression test for issue #92987 // Tests that we properly manage `DepNode`s during trait evaluation // involing an auto-trait cycle. #[cfg(rpass1)] struct CycleOne(Box); #[cfg(rpass2)] enum CycleOne { Variant(Box) } struct CycleTwo(CycleOne); fn assert_send() {} fn bar() { assert_send::(); assert_send::(); } fn main() {} "} {"_id":"doc-en-rust-32c264943ed9295a9074cc050c53a5b3a7163fc5a190d5b93a4af333d2b22481","title":"","text":" // build-pass // ignore-tidy-linelength // Regression for #93775, needs build-pass to test it. #![recursion_limit = \"1000\"] use std::marker::PhantomData; struct Z; struct S(PhantomData); type Nested = S>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>; trait AsNum { const NUM: u32; } impl AsNum for Z { const NUM: u32 = 0; } impl AsNum for S { const NUM: u32 = T::NUM + 1; } fn main() { let _ = Nested::NUM; } "} {"_id":"doc-en-rust-b5df001ecc8ab8e327b2e40812e63326685cea3dcac535c5b98ed4a70b91d4c1","title":"","text":" {#- -#}
{#- -#}

{#- -#} {#- This empty span is a hacky fix for Safari - See #93184 -#} // Regression test for #93205 #![crate_name = \"foo\"] mod generated { pub struct MyNewType; impl MyNewType { pub const FOO: Self = Self; } } pub use generated::MyNewType; mod prelude { impl super::MyNewType { /// An alias for [`Self::FOO`]. // @has 'foo/struct.MyNewType.html' '//a[@href=\"struct.MyNewType.html#associatedconstant.FOO\"]' 'Self::FOO' pub const FOO2: Self = Self::FOO; } } "} {"_id":"doc-en-rust-5ff1cd84c327fa47d5ede46fd99ac70cb403833b35b526c3b96bae3cca90b322","title":"","text":"self } /// Clear any existing suggestions. pub fn clear_suggestions(&mut self) -> &mut Self { if let Ok(suggestions) = &mut self.suggestions { suggestions.clear(); } self } /// Helper for pushing to `self.suggestions`, if available (not disable). fn push_suggestion(&mut self, suggestion: CodeSuggestion) { if let Ok(suggestions) = &mut self.suggestions {"} {"_id":"doc-en-rust-52a4642702be7b5bb6fca915321412bda96978efc22da14af9d35d83d25afe5c","title":"","text":"forward!(pub fn set_is_lint(&mut self,) -> &mut Self); forward!(pub fn disable_suggestions(&mut self,) -> &mut Self); forward!(pub fn clear_suggestions(&mut self,) -> &mut Self); forward!(pub fn multipart_suggestion( &mut self,"} {"_id":"doc-en-rust-d076f28ad3e64d06628ff1f2c8c2bb28cffb8656e725d519c19446bf16a953b1","title":"","text":"// | // = note: cannot satisfy `_: Tt` // Clear any more general suggestions in favor of our specific one err.clear_suggestions(); err.span_suggestion_verbose( span.shrink_to_hi(), &format!("} {"_id":"doc-en-rust-8e33ce597ab694245fa33cfc6c0e74c2b0b0b803c292bd9397638fe346dd7b0f","title":"","text":"| = help: normalized in stderr note: required by a bound in `DiagnosticBuilder::<'a, G>::set_arg` --> $COMPILER_DIR/rustc_errors/src/diagnostic_builder.rs:538:19 --> $COMPILER_DIR/rustc_errors/src/diagnostic_builder.rs:539:19 | LL | arg: impl IntoDiagnosticArg, | ^^^^^^^^^^^^^^^^^ required by this bound in `DiagnosticBuilder::<'a, G>::set_arg`"} {"_id":"doc-en-rust-d08a4d5546ec2cfedc347bcbe16e0ad4c715df9ceb9901826b98cb6e26b695c7","title":"","text":"| LL | fn foo(t: T, k: K) -> Foo { | ^^^^^^^ required by this bound in `foo` help: consider giving `foo` an explicit type, where the type for type parameter `W` is specified | LL | let foo: Foo = foo(1, \"\"); | ++++++++++++++++++++++ help: consider specifying the type arguments in the function call | LL | let foo = foo::(1, \"\");"} {"_id":"doc-en-rust-fdeb9a63608a3551fb6fd344e7055337b15f7495a1315dcb76bfb2e6fd9b1889","title":"","text":"| LL | fn bar(t: T, k: K) -> Bar { | ^^^^^^^ required by this bound in `bar` help: consider giving `bar` an explicit type, where the type for type parameter `Z` is specified | LL | let bar: Bar = bar(1, \"\"); | +++++++++++++++++++ help: consider specifying the type arguments in the function call | LL | let bar = bar::(1, \"\");"} {"_id":"doc-en-rust-182058511bb3ad3cbc3324f30dc1498cf43140595395a04ec1d07aecf0df12d5","title":"","text":"| LL | K: Borrow, | ^^^^^^^^^ required by this bound in `HashMap::::get` help: consider specifying the generic argument | LL | .get::(&\"key\".into()) | +++++ help: consider specifying the type argument in the function call | LL | .get::(&\"key\".into())"} {"_id":"doc-en-rust-a093f7e9627641270afd4098ab96696ce684dfc2cdda79b1ef3f4e99a52a35d9","title":"","text":"| LL | K: Borrow, | ^^^^^^^^^ required by this bound in `HashMap::::get` help: consider specifying the generic argument | LL | opts.get::(opt.as_ref()); | +++++ help: consider specifying the type argument in the function call | LL | opts.get::(opt.as_ref());"} {"_id":"doc-en-rust-27108cad8813dfc02905327ae837e948bce1e507d3190ec867c92faa73012bd8","title":"","text":"| ---- required by a bound in this LL | where T : Convert | ^^^^^^^^^^ required by this bound in `test` help: consider specifying the generic arguments | LL | test::(22, std::default::Default::default()); | ++++++++++ help: consider specifying the type arguments in the function call | LL | test::(22, std::default::Default::default());"} {"_id":"doc-en-rust-9dd92e47350a1fb261ba925954d69ab9d80f7e5b04787cb995bdb767cc6cd10a","title":"","text":"| LL | fn foo>(x: i32) {} | ^^^^^^^^^^^^ required by this bound in `foo` help: consider specifying the generic argument | LL | foo::(42); | +++++ help: consider specifying the type argument in the function call | LL | foo::(42);"} {"_id":"doc-en-rust-ecaede2bb059a3b55a8be49df022de1fcae7b4ac16b0c7e70ddbf69019b683a5","title":"","text":"if self.has_root() { return false; } let mut iter = self.path[self.prefix_len()..].iter(); let mut iter = self.path[self.prefix_remaining()..].iter(); match (iter.next(), iter.next()) { (Some(&b'.'), None) => true, (Some(&b'.'), Some(&b)) => self.is_sep_byte(b),"} {"_id":"doc-en-rust-f7a21804c49e2eebc98a7b6b9acd1bcda3346a2d50485153b0ba4056e39bc683","title":"","text":"assert_eq!(prefix, parse_prefix(r\"/?C:windowssystem32notepad.exe\")); assert_eq!(prefix, parse_prefix(r\"?/C:windowssystem32notepad.exe\")); } // See #93586 for more infomation. #[test] fn test_windows_prefix_components() { use crate::path::Path; let path = Path::new(\"C:\"); let mut components = path.components(); let drive = components.next().expect(\"drive is expected here\"); assert_eq!(drive.as_os_str(), OsStr::new(\"C:\")); assert_eq!(components.as_path(), Path::new(\"\")); } "} {"_id":"doc-en-rust-df844c1ea3fbe0e52ce01764e5818be01ebd93e9b64fb89e6eba8cf28cadaeed","title":"","text":"this.visit_ty(&ty); } } GenericParamKind::Const { ref ty, .. } => { GenericParamKind::Const { ref ty, default } => { let was_in_const_generic = this.is_in_const_generic; this.is_in_const_generic = true; walk_list!(this, visit_param_bound, param.bounds); this.visit_ty(&ty); if let Some(default) = default { this.visit_body(this.tcx.hir().body(default.body)); } this.is_in_const_generic = was_in_const_generic; } }"} {"_id":"doc-en-rust-cddbcf8e472471148da5baaaa83fd15183b37ed20bf51db3da3eef6a078f3dc3","title":"","text":" struct X; fn main() {} "} {"_id":"doc-en-rust-de02523b56a174042c02b6080934c90169214dd724423558e388b8a5eeafeb77","title":"","text":" error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants --> $DIR/issue-93647.rs:2:5 | LL | (||1usize)() | ^^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0015`. "} {"_id":"doc-en-rust-86adae31a4825fae446de79ed47b4ea41f63dc82a2c2358a47e62601c9b80be9","title":"","text":" struct Foo< 'a, const N: usize = { let x: &'a (); //~^ ERROR use of non-static lifetime `'a` in const generic 3 }, >(&'a ()); fn main() {} "} {"_id":"doc-en-rust-4c70e2e71682fac13d10d6de0960475c5c25979f5d68b1f981530eb1edfb61d5","title":"","text":" error[E0771]: use of non-static lifetime `'a` in const generic --> $DIR/outer-lifetime-in-const-generic-default.rs:4:17 | LL | let x: &'a (); | ^^ | = note: for more information, see issue #74052 error: aborting due to previous error For more information about this error, try `rustc --explain E0771`. "} {"_id":"doc-en-rust-07a112299e22a4fb8d33cdc9a715ec5b644ee14686fa19bc6dcfb7cafe56224b","title":"","text":"// The new pass manager is enabled by default for LLVM >= 13. // This matches Clang, which also enables it since Clang 13. // FIXME: There are some perf issues with the new pass manager // when targeting s390x, so it is temporarily disabled for that // arch, see https://github.com/rust-lang/rust/issues/89609 user_opt.unwrap_or_else(|| target_arch != \"s390x\" && llvm_util::get_version() >= (13, 0, 0)) // There are some perf issues with the new pass manager when targeting // s390x with LLVM 13, so enable the new pass manager only with LLVM 14. // See https://github.com/rust-lang/rust/issues/89609. let min_version = if target_arch == \"s390x\" { 14 } else { 13 }; user_opt.unwrap_or_else(|| llvm_util::get_version() >= (min_version, 0, 0)) }"} {"_id":"doc-en-rust-411fea592fa585dc1277147b6a58b97c8f944f0c0772f3a45a8a162ae7b787ab","title":"","text":" Subproject commit e29ac13bc97e26f886c3bfe72f9135e994c3cd0a Subproject commit c8eccf626fb5bb851b2ade93af8851ca1523807f "} {"_id":"doc-en-rust-ce2daf20afb1adb2bd7d6fffcc8f19025790c31be265364ebe270b6f32eec69f","title":"","text":"// run-pass // ignore-wasm32-bare FIXME(#93923) llvm miscompilation use std::collections::HashMap; use std::path::Path;"} {"_id":"doc-en-rust-61e6b91cbdbb593499eb33806bd3806967e8f47b73d7e38009f3d9f0d1c142c5","title":"","text":" // Issue #94176: wrong span for the error message of a mismatched type error, // if the function uses a `let else` construct. #![feature(let_else)] pub fn test(a: Option) -> Option { //~ ERROR mismatched types let Some(_) = a else { return None; }; println!(\"Foo\"); } fn main() {} "} {"_id":"doc-en-rust-73704e829cd43db6a336466fb902e232c0ee4993bc720bbb28b24fb3e9c4ea9b","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-94176.rs:5:32 | LL | pub fn test(a: Option) -> Option { | ---- ^^^^^^^^^^^ expected enum `Option`, found `()` | | | implicitly returns `()` as its body has no tail or `return` expression | = note: expected enum `Option` found unit type `()` help: consider returning the local binding `a` | LL ~ println!(\"Foo\"); LL + a | error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-1dd993665146ca2ce65c635fc8f8b1e73cb8b04234b4f14f4263f01e28338624","title":"","text":" // // popped up in in #94012, where an alternative desugaring was // causing unreachable code errors #![feature(let_else)] #![deny(unused_variables)] #![deny(unreachable_code)] fn let_else_diverge() -> bool { let Some(_) = Some(\"test\") else { let x = 5; //~ ERROR unused variable: `x` return false; }; return true; } fn main() { let_else_diverge(); } "} {"_id":"doc-en-rust-cdcdf50d973fb4023e89f68aa3e52025d1a82e061ab54e7197970253916ec60d","title":"","text":" error: unused variable: `x` --> $DIR/let-else-then-diverge.rs:11:13 | LL | let x = 5; | ^ help: if this is intentional, prefix it with an underscore: `_x` | note: the lint level is defined here --> $DIR/let-else-then-diverge.rs:6:9 | LL | #![deny(unused_variables)] | ^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-1a46e94f9c4ff3f04f364fda0aac8f0ac3e9863306b35e231f7be5f0ca769b0d","title":"","text":" // check-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] #![deny(const_evaluatable_unchecked)] pub struct If; pub trait True {} impl True for If {} pub struct FixedI8 { pub bits: i8, } impl PartialEq> for FixedI8 where If<{ FRAC_RHS <= 8 }>: True, { fn eq(&self, _rhs: &FixedI8) -> bool { unimplemented!() } } impl PartialEq for FixedI8 { fn eq(&self, rhs: &i8) -> bool { let rhs_as_fixed = FixedI8::<0> { bits: *rhs }; PartialEq::eq(self, &rhs_as_fixed) } } fn main() {} "} {"_id":"doc-en-rust-6573f0389ff8be51ca58d3a8a7d8d0c9eff3681ca370d8cd8b2654ff68aad299","title":"","text":"target: Target, item: Option>, ) -> bool { let is_function = matches!(target, Target::Fn | Target::Method(..)); let is_function = matches!(target, Target::Fn); if !is_function { self.tcx .sess"} {"_id":"doc-en-rust-5a801c9817405557bb83a6194b1f39bcf4600e42a19cde6886508c275b530207","title":"","text":"#[rustc_legacy_const_generics(0)] //~ ERROR #[rustc_legacy_const_generics] functions must only have fn foo8() {} impl S { #[rustc_legacy_const_generics(0)] //~ ERROR attribute should be applied to a function fn foo9() {} } #[rustc_legacy_const_generics] //~ ERROR malformed `rustc_legacy_const_generics` attribute fn bar1() {}"} {"_id":"doc-en-rust-50d58bbef05adfb29d8890eefb44f3dec61ab09a2ad83074c6ff0a7f8800cb75","title":"","text":"= help: instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), use an unsuffixed version (`1`, `1.0`, etc.) error: malformed `rustc_legacy_const_generics` attribute input --> $DIR/invalid-rustc_legacy_const_generics-arguments.rs:32:1 --> $DIR/invalid-rustc_legacy_const_generics-arguments.rs:37:1 | LL | #[rustc_legacy_const_generics] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[rustc_legacy_const_generics(N)]` error: malformed `rustc_legacy_const_generics` attribute input --> $DIR/invalid-rustc_legacy_const_generics-arguments.rs:35:1 --> $DIR/invalid-rustc_legacy_const_generics-arguments.rs:40:1 | LL | #[rustc_legacy_const_generics = 1] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[rustc_legacy_const_generics(N)]`"} {"_id":"doc-en-rust-318a9417d0ecb735086c51b396a733c6636aeccfb16f182bf4ac55534b33854b","title":"","text":"| - non-const generic parameter error: attribute should be applied to a function --> $DIR/invalid-rustc_legacy_const_generics-arguments.rs:33:5 | LL | #[rustc_legacy_const_generics(0)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | fn foo9() {} | ---------------------------- not a function error: attribute should be applied to a function --> $DIR/invalid-rustc_legacy_const_generics-arguments.rs:25:5 | LL | #[rustc_legacy_const_generics(1)]"} {"_id":"doc-en-rust-fc83e17f817c235d9db626c8f19d0257ac8d804773dd227b852cedb6a707eb3f","title":"","text":"| = help: replace the const parameters with concrete consts error: aborting due to 12 previous errors error: aborting due to 13 previous errors For more information about this error, try `rustc --explain E0044`."} {"_id":"doc-en-rust-8d5173a4f62b5917dcda362d89e520cb1afc6ec683f68bff760628d32267a0d3","title":"","text":"// FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias` #[cfg(stage0, not(test))] use core::raw; #[cfg(stage0, not(test))] use util; /// Returns a pointer to `size` bytes of memory. /// /// Behavior is undefined if the requested size is 0 or the alignment is not a"} {"_id":"doc-en-rust-3adcb69fce7c220fdae61ae4dcb66f29f0d9746adf9b416a26654eb76b4cc761","title":"","text":"deallocate(ptr, size, align); } #[cfg(stage0, not(test))] #[lang=\"closure_exchange_malloc\"] #[inline] #[allow(deprecated)] unsafe fn closure_exchange_malloc(drop_glue: fn(*mut u8), size: uint, align: uint) -> *mut u8 { let total_size = util::get_box_size(size, align); let p = allocate(total_size, 8); let alloc = p as *mut raw::Box<()>; (*alloc).drop_glue = drop_glue; alloc as *mut u8 } // The minimum alignment guaranteed by the architecture. This value is used to // add fast paths for low alignment values. In practice, the alignment is a // constant at the call site and the branch will be optimized out."} {"_id":"doc-en-rust-caae00db1507796217323c37abfbb3c98473e7b70233f580d62bbfa0ff9951b7","title":"","text":"flags: c_int) -> *mut c_void; fn je_xallocx(ptr: *mut c_void, size: size_t, extra: size_t, flags: c_int) -> size_t; #[cfg(stage0)] fn je_dallocx(ptr: *mut c_void, flags: c_int); #[cfg(not(stage0))] fn je_sdallocx(ptr: *mut c_void, size: size_t, flags: c_int); fn je_nallocx(size: size_t, flags: c_int) -> size_t; fn je_malloc_stats_print(write_cb: Option #[cfg(stage0)] pub unsafe fn deallocate(ptr: *mut u8, _size: uint, align: uint) { let flags = align_to_flags(align); je_dallocx(ptr as *mut c_void, flags) } #[inline] #[cfg(not(stage0))] pub unsafe fn deallocate(ptr: *mut u8, size: uint, align: uint) { let flags = align_to_flags(align); je_sdallocx(ptr as *mut c_void, size as size_t, flags)"} {"_id":"doc-en-rust-b33c2f292d2cbcef1af34e8fb7e32be838e709116110d6890a3c24e9252df6fb","title":"","text":"//! These definitions are similar to their `ct` equivalents, but differ in that //! these can be statically allocated and are slightly optimized for the runtime #[cfg(stage0)] #[doc(hidden)] pub enum Piece<'a> { String(&'a str), Argument(Argument<'a>), } #[doc(hidden)] pub struct Argument<'a> { pub position: Position,"} {"_id":"doc-en-rust-8480caf258d7bd322c84bd7def519d824a5f14b5639b9e5638b16feec52fa79e","title":"","text":" S 2014-09-16 828e075 winnt-x86_64 ce1e9d7f6967bfa368853e7c968e1626cc319951 winnt-i386 a8bd994666dfe683a5d7922c7998500255780724 linux-x86_64 88ff474db96c6ffc5c1dc7a43442cbe1cd88c8a2 linux-i386 7a731891f726c8a0590b142a4e8924c5e8b22e8d freebsd-x86_64 e67a56f76484f775cd4836dedb2d1069ab5d7921 macos-i386 f48023648a77e89086f4a2b39d76b09e4fff032d macos-x86_64 2ad6457b2b3036f87eae7581d64ee5341a07fb06 S 2014-09-10 6faa4f3 winnt-x86_64 939eb546469cb936441cff3b6f2478f562f77c46 winnt-i386 cfe4f8b519bb9d62588f9310a8f94bc919d5423b"} {"_id":"doc-en-rust-4be9eaad390bb200185e8371a6b466b39077c416d7af2d9c0fe4eb2cd22795d7","title":"","text":"use crate::collections::TryReserveError; use crate::fmt; use crate::hash::{Hash, Hasher}; use crate::iter::FromIterator; use crate::iter::{FromIterator, FusedIterator}; use crate::mem; use crate::ops; use crate::rc::Rc;"} {"_id":"doc-en-rust-9852e4035097709caace6fec97ce523a6628a8338ae4265cae11a7a61053df70","title":"","text":"} } #[stable(feature = \"encode_wide_fused_iterator\", since = \"1.62.0\")] impl FusedIterator for EncodeWide<'_> {} impl Hash for CodePoint { #[inline] fn hash(&self, state: &mut H) {"} {"_id":"doc-en-rust-45aa69f2585bb32a909eb913bbd2d29f392eff4fca9ad24167f1b36468d6bc2c","title":"","text":"| PathSource::Struct | PathSource::TupleStruct(..) => false, }; let mut error = false; let mut res = LifetimeRes::Error; for rib in self.lifetime_ribs.iter().rev() { match rib.kind { // In create-parameter mode we error here because we don't want to support"} {"_id":"doc-en-rust-743c7f5fe2b93c7a861cfbe6b96c149137ea65f2ca0ecd55e2c07dc5fee34c90","title":"","text":"// impl Foo for std::cell::Ref // note lack of '_ // async fn foo(_: std::cell::Ref) { ... } LifetimeRibKind::AnonymousCreateParameter(_) => { error = true; break; } // `PassThrough` is the normal case."} {"_id":"doc-en-rust-08cfb9301b47b496b7f24003f30822fb10a6991109b387f9aa7ad49fdd79342e","title":"","text":"// `PathSegment`, for which there is no associated `'_` or `&T` with no explicit // lifetime. Instead, we simply create an implicit lifetime, which will be checked // later, at which point a suitable error will be emitted. LifetimeRibKind::AnonymousPassThrough(..) | LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => break, LifetimeRibKind::AnonymousPassThrough(binder) => { res = LifetimeRes::Anonymous { binder, elided: true }; break; } LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => { // FIXME(cjgillot) This resolution is wrong, but this does not matter // since these cases are erroneous anyway. Lifetime resolution should // emit a \"missing lifetime specifier\" diagnostic. res = LifetimeRes::Anonymous { binder: DUMMY_NODE_ID, elided: true }; break; } _ => {} } } let res = if error { LifetimeRes::Error } else { LifetimeRes::Anonymous { binder: segment_id, elided: true } }; let node_ids = self.r.next_node_ids(expected_lifetimes); self.record_lifetime_res( segment_id,"} {"_id":"doc-en-rust-7261a86a90ef2e7688462d6ebdc8d7db737499016aa28be4cac42149ee7a8b38","title":"","text":"// originating from macros, since the segment's span might be from a macro arg. segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span) }; if error { if let LifetimeRes::Error = res { let sess = self.r.session; let mut err = rustc_errors::struct_span_err!( sess,"} {"_id":"doc-en-rust-7c54a1ece8102b919428ade9d758a3168530eff3b2d17e2c1cd5190890ae6c56","title":"","text":" // check-pass struct Foo<'a>(&'a ()); fn with_fn() -> fn(Foo) { |_| () } fn with_impl_fn() -> impl Fn(Foo) { |_| () } fn with_where_fn() where T: Fn(Foo), { } fn main() {} "} {"_id":"doc-en-rust-4f743a9466d73f1ccd8222edcb687b5bd97511d02a71bf04b68415dae8334335","title":"","text":"); err.span_label(self.span, \"invalid cast\"); if self.expr_ty.is_numeric() { err.span_help( self.span, if self.expr_ty == fcx.tcx.types.i8 { \"try casting from `u8` instead\" } else if self.expr_ty == fcx.tcx.types.u32 { \"try `char::from_u32` instead\" } else { \"try `char::from_u32` instead (via a `u32`)\" }, ); if self.expr_ty == fcx.tcx.types.u32 { match fcx.tcx.sess.source_map().span_to_snippet(self.expr.span) { Ok(snippet) => err.span_suggestion( self.span, \"try `char::from_u32` instead\", format!(\"char::from_u32({snippet})\"), Applicability::MachineApplicable, ), Err(_) => err.span_help(self.span, \"try `char::from_u32` instead\"), }; } else if self.expr_ty == fcx.tcx.types.i8 { err.span_help(self.span, \"try casting from `u8` instead\"); } else { err.span_help(self.span, \"try `char::from_u32` instead (via a `u32`)\"); }; } err.emit(); }"} {"_id":"doc-en-rust-413e68b42cfabf3612401797214053b3970ae745ba901985bb929114cebac9cb","title":"","text":"--> $DIR/E0604.rs:2:5 | LL | 1u32 as char; | ^^^^^^^^^^^^ invalid cast | help: try `char::from_u32` instead --> $DIR/E0604.rs:2:5 | LL | 1u32 as char; | ^^^^^^^^^^^^ | | | invalid cast | help: try `char::from_u32` instead: `char::from_u32(1u32)` error: aborting due to previous error"} {"_id":"doc-en-rust-f4f43084346c8f5df39e051ab4d6991d2181617eb5c2ba5521d830caa44aa9ee","title":"","text":"--> $DIR/error-festival.rs:25:5 | LL | 0u32 as char; | ^^^^^^^^^^^^ invalid cast | help: try `char::from_u32` instead --> $DIR/error-festival.rs:25:5 | LL | 0u32 as char; | ^^^^^^^^^^^^ | | | invalid cast | help: try `char::from_u32` instead: `char::from_u32(0u32)` error[E0605]: non-primitive cast: `u8` as `Vec` --> $DIR/error-festival.rs:29:5"} {"_id":"doc-en-rust-4f7fb1eafc53ef62899cd8572987f327fa1322aaf1be920971b74a391d093199","title":"","text":"--> $DIR/cast-rfc0401.rs:41:13 | LL | let _ = 0x61u32 as char; | ^^^^^^^^^^^^^^^ invalid cast | help: try `char::from_u32` instead --> $DIR/cast-rfc0401.rs:41:13 | LL | let _ = 0x61u32 as char; | ^^^^^^^^^^^^^^^ | | | invalid cast | help: try `char::from_u32` instead: `char::from_u32(0x61u32)` error[E0606]: casting `bool` as `f32` is invalid --> $DIR/cast-rfc0401.rs:43:13"} {"_id":"doc-en-rust-7c53494db0a7ad65cab62b09fc1a5ae3b92ffc1b72929c060a9665eb093a0030","title":"","text":"let second_input_ty = self.resolve_vars_if_possible(expected_input_tys[second_idx]); let third_input_ty = self.resolve_vars_if_possible(expected_input_tys[second_idx]); self.resolve_vars_if_possible(expected_input_tys[third_idx]); let span = if third_idx < provided_arg_count { let first_arg_span = provided_args[first_idx].span; let third_arg_span = provided_args[third_idx].span;"} {"_id":"doc-en-rust-cc7de1451c08b42307f7548be2a37135a975fff151a663f6b9459ef022fd68a5","title":"","text":"} missing_idxs => { let first_idx = *missing_idxs.first().unwrap(); let second_idx = *missing_idxs.last().unwrap(); let last_idx = *missing_idxs.last().unwrap(); // NOTE: Because we might be re-arranging arguments, might have extra arguments, etc. // It's hard to *really* know where we should provide this error label, so this is a // decent heuristic let span = if first_idx < provided_arg_count { let span = if last_idx < provided_arg_count { let first_arg_span = provided_args[first_idx].span; let second_arg_span = provided_args[second_idx].span; let last_arg_span = provided_args[last_idx].span; Span::new( first_arg_span.lo(), second_arg_span.hi(), last_arg_span.hi(), first_arg_span.ctxt(), None, )"} {"_id":"doc-en-rust-528182fc3d4a252c582bd06d7d4450db6bffb11f986fcc7b69b37cb30f880eca","title":"","text":" fn main() { g((), ()); //~^ ERROR this function takes 6 arguments but 2 arguments were supplied } pub fn g(a1: (), a2: bool, a3: bool, a4: bool, a5: bool, a6: ()) -> () {} "} {"_id":"doc-en-rust-14408a1de1c1115ad60f3892777b903222b29cb4c359ceae29acf84b6f5145ee","title":"","text":" error[E0061]: this function takes 6 arguments but 2 arguments were supplied --> $DIR/issue-97197.rs:2:5 | LL | g((), ()); | ^-------- multiple arguments are missing | note: function defined here --> $DIR/issue-97197.rs:6:8 | LL | pub fn g(a1: (), a2: bool, a3: bool, a4: bool, a5: bool, a6: ()) -> () {} | ^ ------ -------- -------- -------- -------- ------ help: provide the arguments | LL | g((), {bool}, {bool}, {bool}, {bool}, ()); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to previous error For more information about this error, try `rustc --explain E0061`. "} {"_id":"doc-en-rust-2ffc5218a8084fc385ae24bddf0eff015c37c7a29178f21ac3ddc0ca1eec2368","title":"","text":"--> $DIR/missing_arguments.rs:39:3 | LL | complex( 1, \"\" ); | ^^^^^^^--------------------------------- three arguments of type `f32`, `i32`, and `i32` are missing | ^^^^^^^--------------------------------- three arguments of type `f32`, `i32`, and `f32` are missing | note: function defined here --> $DIR/missing_arguments.rs:7:4"} {"_id":"doc-en-rust-a6c4c27f99df5b6f545286339855e56a8b1ff1f09967f66e2ff2e6061721dffb","title":"","text":" Subproject commit 47848665966fc7393cb6f898077994f6dec2b591 Subproject commit c9e2e89ed3aa5a3be77143aa0c86906b4138374a "} {"_id":"doc-en-rust-c2add5fa5a899e721764b95bbb51f01f490afdbd43ec514842371f967d828145","title":"","text":"\"libc\", \"once_cell\", \"opener\", \"pretty_assertions\", \"pretty_assertions 0.7.2\", \"serde\", \"serde_json\", \"tar\","} {"_id":"doc-en-rust-602d43c19a722f28c5b8d9354c2e1f3d528f7237c3e1b1af5bb2d1d072d440fc","title":"","text":"] [[package]] name = \"crossbeam\" version = \"0.8.1\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"4ae5588f6b3c3cb05239e90bd110f257254aecd01e4635400391aeae07497845\" dependencies = [ \"cfg-if 1.0.0\", \"crossbeam-channel\", \"crossbeam-deque\", \"crossbeam-epoch\", \"crossbeam-queue\", \"crossbeam-utils\", ] [[package]] name = \"crossbeam-channel\" version = \"0.5.4\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"doc-en-rust-9f3c353ee0f7a684cede654ddb050fd6f8e56700e5d52aa89cec8660538fa664","title":"","text":"] [[package]] name = \"crossbeam-queue\" version = \"0.3.5\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"1f25d8400f4a7a5778f0e4e52384a48cbd9b5c495d110786187fc750075277a2\" dependencies = [ \"cfg-if 1.0.0\", \"crossbeam-utils\", ] [[package]] name = \"crossbeam-utils\" version = \"0.8.8\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"doc-en-rust-c4759e9399eb88e741da5b27fe08ba9fdd3fe204dc8dfac634c0bb3ed2ed0712","title":"","text":"version = \"0.1.0\" dependencies = [ \"colored\", \"compiletest_rs\", \"env_logger 0.9.0\", \"getrandom 0.2.0\", \"lazy_static\", \"libc\", \"log\", \"measureme 9.1.2\", \"rand 0.8.5\", \"regex\", \"rustc-workspace-hack\", \"rustc_version\", \"shell-escape\", \"smallvec\", \"ui_test\", ] [[package]]"} {"_id":"doc-en-rust-1eeff89e54a417e828a5e6e55e263f0363b6f6ea30771f6f1f7005b91d9494fb","title":"","text":"] [[package]] name = \"pretty_assertions\" version = \"1.2.1\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"c89f989ac94207d048d92db058e4f6ec7342b0971fc58d1271ca148b799b3563\" dependencies = [ \"ansi_term\", \"ctor\", \"diff\", \"output_vt100\", ] [[package]] name = \"pretty_env_logger\" version = \"0.4.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"doc-en-rust-3bf64dc269890880a0142186c38d81fab33469dfbadd9412602a63aaebb91d46","title":"","text":"checksum = \"56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c\" [[package]] name = \"ui_test\" version = \"0.1.0\" dependencies = [ \"colored\", \"crossbeam\", \"lazy_static\", \"pretty_assertions 1.2.1\", \"regex\", \"rustc_version\", ] [[package]] name = \"unic-char-property\" version = \"0.9.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"doc-en-rust-dea18a0b712ae1565c5bca581dbb3e9f1e8134ece7f150d73b0bd57ecefb77fb","title":"","text":"return; } // # Run `cargo test` with `-Zmir-opt-level=4`. cargo.env(\"MIRIFLAGS\", \"-O -Zmir-opt-level=4\"); if !try_run(builder, &mut cargo) { return; } // # Done! builder.save_toolstate(\"miri\", ToolState::TestPass); } else {"} {"_id":"doc-en-rust-bb1d4f82c32ee56419e84b5fa171d926c2ad11a92930516a0dfa0e5caee15272","title":"","text":" Subproject commit 22c97b33e470d0b7c085e98417bef8b362d43d4e Subproject commit 065ff89e33b67b3527fcdd56cf8b432e593e32d4 "} {"_id":"doc-en-rust-46e7a7ddfdc627950edf7c3d5aeed4e4786f730012e45d96762e156bc81bc200","title":"","text":" // check-pass #[allow(unused)] fn test(f: F) -> Box U + 'static> where F: 'static + Fn(T) -> U, for<'a> U: 'a, // < This is the problematic line, see #97607 { Box::new(move |t| f(t)) } fn main() {} "} {"_id":"doc-en-rust-a348e4fa70188a97010a99d556e3480491407d8d8bfd452d4b6016985c20080a","title":"","text":"let llvm_selfprofiler = llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut()); let extra_passes = config.passes.join(\",\"); let extra_passes = if !is_lto { config.passes.join(\",\") } else { \"\".to_string() }; let llvm_plugins = config.llvm_plugins.join(\",\");"} {"_id":"doc-en-rust-fb18b50958a73148452152a3fc17c1c95c6adc349acdeb6d4bd6ef16e062948a","title":"","text":"} fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] { // Skip items with no generics - there's nothing to infer in them. if tcx.generics_of(item_def_id).count() == 0 { return &[]; } match tcx.def_kind(item_def_id) { DefKind::Fn | DefKind::AssocFn"} {"_id":"doc-en-rust-03f2cda83073495825c432bc73ed1ea665c467b5c30a7e8acd4b4bda3b773cad","title":"","text":" fn main() {} trait A { fn a(aa: B) -> Result<_, B> { //~^ ERROR: the placeholder `_` is not allowed within types on item signatures for return types [E0121] Ok(()) } } enum B {} "} {"_id":"doc-en-rust-42a56be6cbee35b8eff33441c24b835da552d236d7c5601b6ddf0ab58f03cff3","title":"","text":" error[E0121]: the placeholder `_` is not allowed within types on item signatures for return types --> $DIR/issue-98260.rs:3:27 | LL | fn a(aa: B) -> Result<_, B> { | -------^---- | | | | | not allowed in type signatures | help: replace with the correct return type: `Result<(), B>` error: aborting due to previous error For more information about this error, try `rustc --explain E0121`. "} {"_id":"doc-en-rust-45e337dd34a67cfdf2655a72b14cd78cb55a270ee474e25b2f6902941ba88c5a","title":"","text":"Self::with_capacity_in(capacity, Global) } /// Creates a `Vec` directly from the raw components of another vector. /// Creates a `Vec` directly from a pointer, a capacity, and a length. /// /// # Safety /// /// This is highly unsafe, due to the number of invariants that aren't /// checked: /// /// * `ptr` needs to have been previously allocated via [`String`]/`Vec` /// (at least, it's highly likely to be incorrect if it wasn't). /// * `T` needs to have the same alignment as what `ptr` was allocated with. /// (`T` having a less strict alignment is not sufficient, the alignment really /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be"} {"_id":"doc-en-rust-d8080c33444a3f4541d60c23851872cf762bd64bf6ec987567f4ca8880a17f75","title":"","text":"/// to be the same size as the pointer was allocated with. (Because similar to /// alignment, [`dealloc`] must be called with the same layout `size`.) /// * `length` needs to be less than or equal to `capacity`. /// * The first `length` values must be properly initialized values of type `T`. /// * `capacity` needs to be the capacity that the pointer was allocated with. /// * The allocated size in bytes must be no larger than `isize::MAX`. /// See the safety documentation of [`pointer::offset`]. /// /// These requirements are always upheld by any `ptr` that has been allocated /// via `Vec`. Other allocation sources are allowed if the invariants are /// upheld. /// /// Violating these may cause problems like corrupting the allocator's /// internal data structures. For example it is normally **not** safe"} {"_id":"doc-en-rust-f1c4eec3fd95cb611ac2894ff7afc4e6766237ec10a0d1f25cb68c5ae10664ce","title":"","text":"/// assert_eq!(rebuilt, [4, 5, 6]); /// } /// ``` /// /// Using memory that was allocated elsewhere: /// /// ```rust /// #![feature(allocator_api)] /// /// use std::alloc::{AllocError, Allocator, Global, Layout}; /// /// fn main() { /// let layout = Layout::array::(16).expect(\"overflow cannot happen\"); /// /// let vec = unsafe { /// let mem = match Global.allocate(layout) { /// Ok(mem) => mem.cast::().as_ptr(), /// Err(AllocError) => return, /// }; /// /// mem.write(1_000_000); /// /// Vec::from_raw_parts_in(mem, 1, 16, Global) /// }; /// /// assert_eq!(vec, &[1_000_000]); /// assert_eq!(vec.capacity(), 16); /// } /// ``` #[inline] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {"} {"_id":"doc-en-rust-ec8dd75de0a2b31092e44789ace711d4c160ed5641f82f85edafa6ed7b02966d","title":"","text":"Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } } /// Creates a `Vec` directly from the raw components of another vector. /// Creates a `Vec` directly from a pointer, a capacity, a length, /// and an allocator. /// /// # Safety /// /// This is highly unsafe, due to the number of invariants that aren't /// checked: /// /// * `ptr` needs to have been previously allocated via [`String`]/`Vec` /// (at least, it's highly likely to be incorrect if it wasn't). /// * `T` needs to have the same size and alignment as what `ptr` was allocated with. /// * `T` needs to have the same alignment as what `ptr` was allocated with. /// (`T` having a less strict alignment is not sufficient, the alignment really /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be /// allocated and deallocated with the same layout.) /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs /// to be the same size as the pointer was allocated with. (Because similar to /// alignment, [`dealloc`] must be called with the same layout `size`.) /// * `length` needs to be less than or equal to `capacity`. /// * `capacity` needs to be the capacity that the pointer was allocated with. /// * The first `length` values must be properly initialized values of type `T`. /// * `capacity` needs to [*fit*] the layout size that the pointer was allocated with. /// * The allocated size in bytes must be no larger than `isize::MAX`. /// See the safety documentation of [`pointer::offset`]. /// /// These requirements are always upheld by any `ptr` that has been allocated /// via `Vec`. Other allocation sources are allowed if the invariants are /// upheld. /// /// Violating these may cause problems like corrupting the allocator's /// internal data structures. For example it is **not** safe"} {"_id":"doc-en-rust-bce6d35ac4d74e46f0f1a35430f6d7d7eeb52a1de287f79ffe026f6a10301b57","title":"","text":"/// /// [`String`]: crate::string::String /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc /// [*fit*]: crate::alloc::Allocator#memory-fitting /// /// # Examples ///"} {"_id":"doc-en-rust-4ca4e113feb631d75c26af70e27553ec782de39bac6af2b80998e46caf1cce49","title":"","text":"/// assert_eq!(rebuilt, [4, 5, 6]); /// } /// ``` /// /// Using memory that was allocated elsewhere: /// /// ```rust /// use std::alloc::{alloc, Layout}; /// /// fn main() { /// let layout = Layout::array::(16).expect(\"overflow cannot happen\"); /// let vec = unsafe { /// let mem = alloc(layout).cast::(); /// if mem.is_null() { /// return; /// } /// /// mem.write(1_000_000); /// /// Vec::from_raw_parts(mem, 1, 16) /// }; /// /// assert_eq!(vec, &[1_000_000]); /// assert_eq!(vec.capacity(), 16); /// } /// ``` #[inline] #[unstable(feature = \"allocator_api\", issue = \"32838\")] pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {"} {"_id":"doc-en-rust-5122ad4b2d8385157e80306754af259fa49955af4789bdb5276fb5e2ffe0a852","title":"","text":"} #[instrument(skip(self, expr), level = \"debug\")] pub(super) fn check_expr_kind( fn check_expr_kind( &self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>,"} {"_id":"doc-en-rust-bb619718f162d765564e5c98bf2f0d8b15e8bccc11e00d8aa7a17314521c3447","title":"","text":"self.set_tainted_by_errors(); let tcx = self.tcx; // Precompute the provided types and spans, since that's all we typically need for below let provided_arg_tys: IndexVec, Span)> = provided_args .iter() .map(|expr| { let ty = self .typeck_results .borrow() .expr_ty_adjusted_opt(*expr) .unwrap_or_else(|| tcx.ty_error()); (self.resolve_vars_if_possible(ty), expr.span) }) .collect(); // A \"softer\" version of the `demand_compatible`, which checks types without persisting them, // and treats error types differently // This will allow us to \"probe\" for other argument orders that would likely have been correct"} {"_id":"doc-en-rust-d89580d2f72e5431ad7bb62a7d03b8837526af08ca0dfc4fee7797d2c18cd8d3","title":"","text":"return Compatibility::Incompatible(None); } let provided_arg: &hir::Expr<'tcx> = &provided_args[provided_idx]; let expectation = Expectation::rvalue_hint(self, expected_input_ty); // FIXME: check that this is safe; I don't believe this commits any of the obligations, but I can't be sure. // // I had another method of \"soft\" type checking before, // but it was failing to find the type of some expressions (like \"\") // so I prodded this method and made it pub(super) so I could call it, and it seems to work well. let checked_ty = self.check_expr_kind(provided_arg, expectation); let (arg_ty, arg_span) = provided_arg_tys[provided_idx]; let expectation = Expectation::rvalue_hint(self, expected_input_ty); let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty); let can_coerce = self.can_coerce(checked_ty, coerced_ty); let can_coerce = self.can_coerce(arg_ty, coerced_ty); if !can_coerce { return Compatibility::Incompatible(None); } // Using probe here, since we don't want this subtyping to affect inference. let subtyping_error = self.probe(|_| { self.at(&self.misc(provided_arg.span), self.param_env) .sup(formal_input_ty, coerced_ty) .err() self.at(&self.misc(arg_span), self.param_env).sup(formal_input_ty, coerced_ty).err() }); // Same as above: if either the coerce type or the checked type is an error type, // consider them *not* compatible. let references_error = (coerced_ty, checked_ty).references_error(); let references_error = (coerced_ty, arg_ty).references_error(); match (references_error, subtyping_error) { (false, None) => Compatibility::Compatible, (_, subtyping_error) => Compatibility::Incompatible(subtyping_error),"} {"_id":"doc-en-rust-09fd9b3da64eb440401e2ae5f4cae3b8b37892698ad638cef08eae7c214c2277","title":"","text":"ArgMatrix::new(provided_args.len(), formal_and_expected_inputs.len(), check_compatible) .find_errors(); // Precompute the provided types and spans, since that's all we typically need for below let provided_arg_tys: IndexVec, Span)> = provided_args .iter() .map(|expr| { let ty = self .typeck_results .borrow() .expr_ty_adjusted_opt(*expr) .unwrap_or_else(|| tcx.ty_error()); (self.resolve_vars_if_possible(ty), expr.span) }) .collect(); // First, check if we just need to wrap some arguments in a tuple. if let Some((mismatch_idx, terr)) = compatibility_diagonal.iter().enumerate().find_map(|(i, c)| {"} {"_id":"doc-en-rust-55babfcad883c33d5322f9c1200e8b276624b837cfba0d50c8050be4e7dbf423","title":"","text":"fn main() { let needlesArr: Vec = vec!['a', 'f']; needlesArr.iter().fold(|x, y| { //~^ ERROR this function takes 2 arguments but 1 argument was supplied }); //~^^ ERROR mismatched types //~| ERROR this function takes 2 arguments but 1 argument was supplied }"} {"_id":"doc-en-rust-c96828ed652a2ae4f689f4f00b24b4fb939d8be2526ce44df75e8a9469d1aca1","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-3044.rs:3:35 | LL | needlesArr.iter().fold(|x, y| { | ____________________________------_^ | | | | | the expected closure LL | | }); | |_____^ expected closure, found `()` | = note: expected closure `[closure@$DIR/issue-3044.rs:3:28: 3:34]` found unit type `()` error[E0061]: this function takes 2 arguments but 1 argument was supplied --> $DIR/issue-3044.rs:3:23 | LL | needlesArr.iter().fold(|x, y| { | _______________________^^^^- LL | | LL | | }); | |______- an argument is missing |"} {"_id":"doc-en-rust-7b89db557b8e241b0d6357c7317a8993974498efdb9e4bbfc942546d134af313","title":"","text":"help: provide the argument | LL ~ needlesArr.iter().fold(|x, y| { LL + LL ~ }, /* value */); | error: aborting due to 2 previous errors error: aborting due to previous error Some errors have detailed explanations: E0061, E0308. For more information about an error, try `rustc --explain E0061`. For more information about this error, try `rustc --explain E0061`. "} {"_id":"doc-en-rust-a758c6d1bb59a019ee016da7aff36e56858bca10cfc24cfb80b1474d37aa940c","title":"","text":"use rustc_lint_defs::builtin::NAMED_ARGUMENTS_USED_POSITIONALLY; use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, LintId}; use rustc_parse_format::{Count, FormatSpec}; use rustc_parse_format::Count; use std::borrow::Cow; use std::collections::hash_map::Entry;"} {"_id":"doc-en-rust-70f29fc7002466a80a51b5063c9e171150d9b8763e10685304c6390342f534af","title":"","text":"} _ => {} }; match a.format { FormatSpec { width: Count::CountIsName(s, _), .. } | FormatSpec { precision: Count::CountIsName(s, _), .. } => { used_argument_names.insert(s); } _ => {} }; if let Count::CountIsName(s, _) = a.format.width { used_argument_names.insert(s); } if let Count::CountIsName(s, _) = a.format.precision { used_argument_names.insert(s); } } } for (symbol, (index, span)) in names { if !used_argument_names.contains(symbol.as_str()) { let msg = format!(\"named argument `{}` is not used by name\", symbol.as_str()); let arg_span = cx.arg_spans[index]; let arg_span = cx.arg_spans.get(index).copied(); cx.ecx.buffered_early_lint.push(BufferedEarlyLint { span: MultiSpan::from_span(span), msg: msg.clone(),"} {"_id":"doc-en-rust-5f355e051db3844de28625ac5cf9afaece905e7c473d3c88eadf0bc2ab33ac94","title":"","text":"}, BuiltinLintDiagnostics::NamedArgumentUsedPositionally(positional_arg, named_arg, name) => { db.span_label(named_arg, \"this named argument is only referred to by position in formatting string\"); let msg = format!(\"this formatting argument uses named argument `{}` by position\", name); db.span_label(positional_arg, msg); db.span_suggestion_verbose( positional_arg, \"use the named argument by name to avoid ambiguity\", format!(\"{{{}}}\", name), Applicability::MaybeIncorrect, ); if let Some(positional_arg) = positional_arg { let msg = format!(\"this formatting argument uses named argument `{}` by position\", name); db.span_label(positional_arg, msg); db.span_suggestion_verbose( positional_arg, \"use the named argument by name to avoid ambiguity\", format!(\"{{{}}}\", name), Applicability::MaybeIncorrect, ); } } } // Rewrap `db`, and pass control to the user."} {"_id":"doc-en-rust-3246e0fb5b92e7852864d983027424c78ce1f8347b1e6999fbbae91ec1f40019","title":"","text":"/// If true, the lifetime will be fully elided. use_span: Option<(Span, bool)>, }, NamedArgumentUsedPositionally(Span, Span, String), NamedArgumentUsedPositionally(Option, Span, String), } /// Lints that are buffered up early on in the `Session` before the"} {"_id":"doc-en-rust-64ffccf136db7a9b00dfe9033cc9bf15225a46bb27bf7e219e9fd3dc4e5cd6a5","title":"","text":" // check-pass #![deny(named_arguments_used_positionally)] fn main() { let value: f64 = 314.15926; let digits_before_decimal = 1; let digits_after_decimal = 2; let width = digits_before_decimal + 1 + digits_after_decimal; println!( \"{value:0>width$.digits_after_decimal$}\", value = value, width = width, digits_after_decimal = digits_after_decimal, ); } "} {"_id":"doc-en-rust-874b241870e7c8fba419bec55cae1a19470bffa09e52ae3672cf45a4e23345d3","title":"","text":"/// Parses an enum declaration. fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> { if self.token.is_keyword(kw::Struct) { let mut err = self.struct_span_err( self.prev_token.span.to(self.token.span), \"`enum` and `struct` are mutually exclusive\", ); err.span_suggestion( self.prev_token.span.to(self.token.span), \"replace `enum struct` with\", \"enum\", Applicability::MachineApplicable, ); if self.look_ahead(1, |t| t.is_ident()) { self.bump(); err.emit(); } else { return Err(err); } } let id = self.parse_ident()?; let mut generics = self.parse_generics()?; generics.where_clause = self.parse_where_clause()?;"} {"_id":"doc-en-rust-db69808fa862c0daa62b37e7fab23ee4ce1cca1fc90a40ec0f3e3369d5b403ba","title":"","text":" // run-rustfix pub enum Range { //~^ ERROR `enum` and `struct` are mutually exclusive Valid { begin: u32, len: u32, }, Out, } fn main() { } "} {"_id":"doc-en-rust-9d4d9387ff864fe8cb730a2278b496141e29ce8c5776435a0c79168ff86a952f","title":"","text":" // run-rustfix pub enum struct Range { //~^ ERROR `enum` and `struct` are mutually exclusive Valid { begin: u32, len: u32, }, Out, } fn main() { } "} {"_id":"doc-en-rust-836b680022205ef5353aa021dbe767010833b2fc430c292363de59cdb4d9629d","title":"","text":" error: `enum` and `struct` are mutually exclusive --> $DIR/issue-99625-enum-struct-mutually-exclusive.rs:3:5 | LL | pub enum struct Range { | ^^^^^^^^^^^ help: replace `enum struct` with: `enum` error: aborting due to previous error "} {"_id":"doc-en-rust-9266d10b0b9097e5ed5f79b3342ae945405fecd8395b46d6ed297206db5c4b9a","title":"","text":"} else { if matches!(def_kind, DefKind::AnonConst) && tcx.lazy_normalization() { let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); let parent_def_id = tcx.hir().get_parent_item(hir_id); if tcx.hir().opt_const_param_default_param_hir_id(hir_id).is_some() { // In `generics_of` we set the generics' parent to be our parent's parent which means that // we lose out on the predicates of our actual parent if we dont return those predicates here."} {"_id":"doc-en-rust-d50299d80b025813c5e8b3307ff75bbf5bb8d012bd82ed0602077781e3467f16","title":"","text":"// parent of generics returned by `generics_of` // // In the above code we want the anon const to have predicates in its param env for `T: Trait` let item_def_id = tcx.hir().get_parent_item(hir_id); // In the above code example we would be calling `explicit_predicates_of(Foo)` here // and we would be calling `explicit_predicates_of(Foo)` here return tcx.explicit_predicates_of(parent_def_id); } let parent_def_kind = tcx.def_kind(parent_def_id); if matches!(parent_def_kind, DefKind::OpaqueTy) { // In `instantiate_identity` we inherit the predicates of our parent. // However, opaque types do not have a parent (see `gather_explicit_predicates_of`), which means // that we lose out on the predicates of our actual parent if we dont return those predicates here. // // // fn foo() -> impl Iterator::ASSOC }> > { todo!() } // ^^^^^^^^^^^^^^^^^^^ the def id we are calling // explicit_predicates_of on // // In the above code we want the anon const to have predicates in its param env for `T: Trait`. // However, the anon const cannot inherit predicates from its parent since it's opaque. // // To fix this, we call `explicit_predicates_of` directly on `foo`, the parent's parent. // In the above example this is `foo::{opaque#0}` or `impl Iterator` let parent_hir_id = tcx.hir().local_def_id_to_hir_id(parent_def_id.def_id); // In the above example this is the function `foo` let item_def_id = tcx.hir().get_parent_item(parent_hir_id); // In the above code example we would be calling `explicit_predicates_of(foo)` here return tcx.explicit_predicates_of(item_def_id); } }"} {"_id":"doc-en-rust-2174879d926dffa8257647c4180272cd20199e6fc1314094601d651e59ecb532","title":"","text":" // check-pass #![crate_type = \"lib\"] #![feature(generic_const_exprs)] #![allow(incomplete_features)] pub trait MyIterator { type Output; } pub trait Foo { const ABC: usize; } pub struct IteratorStruct{ } pub struct Bar { pub data: [usize; N] } impl MyIterator for IteratorStruct { type Output = Bar; } pub fn test1() -> impl MyIterator> where [(); T::ABC]: Sized { IteratorStruct::<{T::ABC}>{} } pub trait Baz{} impl Baz for Bar {} pub fn test2() -> impl MyIterator> where [(); T::ABC]: Sized { IteratorStruct::<{T::ABC}>{} } "} {"_id":"doc-en-rust-c5d0a6b07643abd0bdf502d4d15a1369ac5b4128c53aab5e9512efda9f037c2b","title":"","text":"builder.update_submodule(&Path::new(\"library\").join(\"stdarch\")); // Profiler information requires LLVM's compiler-rt if builder.config.profiler { builder.update_submodule(&Path::new(\"src/llvm-project\")); } let mut target_deps = builder.ensure(StartupObjects { compiler, target }); let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target);"}
  • {name}