{"_id":"q-en-rust-00197aac97777e71a073a0bfbab0bf915653c70f8d24646b77205c19adf26a31","text":"} } fn compute_components_recursive<'tcx>( /// Collect [Component]s for *all* the substs of `parent`. /// /// This should not be used to get the components of `parent` itself. /// Use [push_outlives_components] instead. pub(super) fn compute_components_recursive<'tcx>( tcx: TyCtxt<'tcx>, parent: GenericArg<'tcx>, out: &mut SmallVec<[Component<'tcx>; 4]>,"} {"_id":"q-en-rust-003ccfcc39191bd6342c2eced06fdcee27d97dcef8e9999d72873a8e06f54e6b","text":" // check-pass // aux-build:issue-112831-aux.rs mod zeroable { pub trait Zeroable {} } use zeroable::*; mod pod { use super::*; pub trait Pod: Zeroable {} } use pod::*; extern crate issue_112831_aux; use issue_112831_aux::Zeroable; fn main() {} "} {"_id":"q-en-rust-0040e044ed267a4df108483b07ce573d53cb06e43adf913c4ba1f943a8511204","text":"// Change value between simple literals --------------------------------------- #[cfg(cfail1)] static STATIC_CHANGE_VALUE_1: i16 = 1; #[cfg(not(cfail1))] #[rustc_clean(cfg=\"cfail2\", except=\"HirBody\")] #[rustc_clean(cfg=\"cfail3\")] #[rustc_metadata_clean(cfg=\"cfail2\")] #[rustc_metadata_clean(cfg=\"cfail3\")] static STATIC_CHANGE_VALUE_1: i16 = 2; static STATIC_CHANGE_VALUE_1: i16 = { #[cfg(cfail1)] { 1 } #[cfg(not(cfail1))] { 2 } }; // Change value between expressions ------------------------------------------- #[cfg(cfail1)] static STATIC_CHANGE_VALUE_2: i16 = 1 + 1; #[cfg(not(cfail1))] // Change value between expressions ------------------------------------------- #[rustc_clean(cfg=\"cfail2\", except=\"HirBody\")] #[rustc_clean(cfg=\"cfail3\")] #[rustc_metadata_clean(cfg=\"cfail2\")] #[rustc_metadata_clean(cfg=\"cfail3\")] static STATIC_CHANGE_VALUE_2: i16 = 1 + 2; static STATIC_CHANGE_VALUE_2: i16 = { #[cfg(cfail1)] { 1 + 1 } #[cfg(cfail1)] static STATIC_CHANGE_VALUE_3: i16 = 2 + 3; #[cfg(not(cfail1))] { 1 + 2 } }; #[cfg(not(cfail1))] #[rustc_clean(cfg=\"cfail2\", except=\"HirBody\")] #[rustc_clean(cfg=\"cfail3\")] #[rustc_metadata_clean(cfg=\"cfail2\")] #[rustc_metadata_clean(cfg=\"cfail3\")] static STATIC_CHANGE_VALUE_3: i16 = 2 * 3; static STATIC_CHANGE_VALUE_3: i16 = { #[cfg(cfail1)] { 2 + 3 } #[cfg(cfail1)] static STATIC_CHANGE_VALUE_4: i16 = 1 + 2 * 3; #[cfg(not(cfail1))] { 2 * 3 } }; #[cfg(not(cfail1))] #[rustc_clean(cfg=\"cfail2\", except=\"HirBody\")] #[rustc_clean(cfg=\"cfail3\")] #[rustc_metadata_clean(cfg=\"cfail2\")] #[rustc_metadata_clean(cfg=\"cfail3\")] static STATIC_CHANGE_VALUE_4: i16 = 1 + 2 * 4; static STATIC_CHANGE_VALUE_4: i16 = { #[cfg(cfail1)] { 1 + 2 * 3 } #[cfg(not(cfail1))] { 1 + 2 * 4 } }; // Change type indirectly -----------------------------------------------------"} {"_id":"q-en-rust-0044f606aef33ca4599a834d45ec9854b2c5bda263807ad54c23087e54c01aeb","text":" error[E0308]: mismatched types --> $DIR/issue-107775.rs:35:16 | LL | map.insert(1, Struct::do_something); | - -------------------- this is of type `fn(u8) -> Pin + Send>> {::do_something::<'_>}`, which causes `map` to be inferred as `HashMap<{integer}, fn(u8) -> Pin + Send>> {::do_something::<'_>}>` | | | this is of type `{integer}`, which causes `map` to be inferred as `HashMap<{integer}, fn(u8) -> Pin + Send>> {::do_something::<'_>}>` LL | Self { map } | ^^^ expected `HashMap Pin<...>>`, found `HashMap<{integer}, ...>` | = note: expected struct `HashMap Pin + Send + 'static)>>>` found struct `HashMap<{integer}, fn(_) -> Pin + Send>> {::do_something::<'_>}>` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-004b0f27c043622f4cf292a91cb7d1d01dc2407189414de16781512a28d9c3d7","text":"spflags, maybe_definition_llfn, template_parameters, None, ); } decl, ) }; fn get_function_signature<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>,"} {"_id":"q-en-rust-009a59df3b237742c69acc68affa8d657168f14c3700b7a03b9012a69747744c","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":"q-en-rust-00a85677f481bd34d74fa315a2c798a608f596fdb71d47939b0b922163ac9f6b","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":"q-en-rust-01072bd7205f514d35fb21c12e396db2d07991534780a8b6bb329427780b2cad","text":"* `unboxed_closures` - Rust's new closure design, which is currently a work in progress feature with many known bugs. * `unmarked_api` - Allows use of items within a `#![staged_api]` crate which have not been marked with a stability marker. Such items should not be allowed by the compiler to exist, so if you need this there probably is a compiler bug. * `allow_internal_unstable` - Allows `macro_rules!` macros to be tagged with the `#[allow_internal_unstable]` attribute, designed to allow `std` macros to call"} {"_id":"q-en-rust-011f47db789b793c707a4eddbc5eba4fb441f7eeb35bc797243a005eb057e352","text":"use std::sync::Arc; use crate::clean::cfg::Cfg; use crate::clean::inline::{load_attrs, merge_attrs}; use crate::clean::{Crate, Item}; use crate::core::DocContext; use crate::fold::DocFolder; use crate::passes::Pass; use rustc_hir::def_id::LocalDefId; pub(crate) const PROPAGATE_DOC_CFG: Pass = Pass { name: \"propagate-doc-cfg\", run: propagate_doc_cfg, description: \"propagates `#[doc(cfg(...))]` to child items\", }; pub(crate) fn propagate_doc_cfg(cr: Crate, _: &mut DocContext<'_>) -> Crate { CfgPropagator { parent_cfg: None }.fold_crate(cr) pub(crate) fn propagate_doc_cfg(cr: Crate, cx: &mut DocContext<'_>) -> Crate { CfgPropagator { parent_cfg: None, parent: None, cx }.fold_crate(cr) } struct CfgPropagator { struct CfgPropagator<'a, 'tcx> { parent_cfg: Option>, parent: Option, cx: &'a mut DocContext<'tcx>, } impl DocFolder for CfgPropagator { impl<'a, 'tcx> DocFolder for CfgPropagator<'a, 'tcx> { fn fold_item(&mut self, mut item: Item) -> Option { let old_parent_cfg = self.parent_cfg.clone(); if item.kind.is_non_assoc() && let Some(def_id) = item.item_id.as_def_id().and_then(|def_id| def_id.as_local()) { let hir = self.cx.tcx.hir(); let hir_id = hir.local_def_id_to_hir_id(def_id); let expected_parent = hir.get_parent_item(hir_id); // If parents are different, it means that `item` is a reexport and we need to compute // the actual `cfg` by iterating through its \"real\" parents. if self.parent != Some(expected_parent) { let mut attrs = Vec::new(); for (parent_hir_id, _) in hir.parent_iter(hir_id) { let def_id = hir.local_def_id(parent_hir_id).to_def_id(); attrs.extend_from_slice(load_attrs(self.cx, def_id)); } let (_, cfg) = merge_attrs(self.cx, None, item.attrs.other_attrs.as_slice(), Some(&attrs)); item.cfg = cfg; } } let new_cfg = match (self.parent_cfg.take(), item.cfg.take()) { (None, None) => None, (Some(rc), None) | (None, Some(rc)) => Some(rc),"} {"_id":"q-en-rust-0137539a8c321a6e4d180d0eb9103a84166a2fd3afebac54d06aec1d1cc20b07","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":"q-en-rust-0140303a41e627423b4adf0c21f76e7cdb748626d53b3aee0845501f3d712d89","text":"/// Used to detect possible new binding written without `let` and to provide structured suggestion. in_assignment: Option<&'ast Expr>, is_assign_rhs: bool, /// If we are currently in a trait object definition. Used to point at the bounds when /// encountering a struct or enum."} {"_id":"q-en-rust-0159e86c1e4cc0ddafde0bc02a69ae5897df9a6cbfe268f4ee37c7058f8f08ad","text":" Subproject commit 5cb983338e924ec85898880d60e65f2a1291b7be Subproject commit 52cebb1f8f8789b97d243c07bf4c961ca0017f7b "} {"_id":"q-en-rust-015ddaf38ebcd5a42537a637de94c07c8c1ed2636c5d4feb1b002a49a08e9f5a","text":"if (splitAt !== -1) { const implId = savedHash.slice(0, splitAt); const assocId = savedHash.slice(splitAt + 1); const implElem = document.getElementById(implId); if (implElem && implElem.parentElement.tagName === \"SUMMARY\" && implElem.parentElement.parentElement.tagName === \"DETAILS\") { onEachLazy(implElem.parentElement.parentElement.querySelectorAll( const implElems = document.querySelectorAll( `details > summary > section[id^=\"${implId}\"]`, ); onEachLazy(implElems, implElem => { const numbered = /^(.+?)-([0-9]+)$/.exec(implElem.id); if (implElem.id !== implId && (!numbered || numbered[1] !== implId)) { return false; } return onEachLazy(implElem.parentElement.parentElement.querySelectorAll( `[id^=\"${assocId}\"]`), item => { const numbered = /([^-]+)-([0-9]+)/.exec(item.id); const numbered = /^(.+?)-([0-9]+)$/.exec(item.id); if (item.id === assocId || (numbered && numbered[1] === assocId)) { openParentDetails(item); item.scrollIntoView();"} {"_id":"q-en-rust-01f52084181b8e1c5e74588d18a52477a2ec0d01af2cdce112daf0311f6b11d0","text":" // Regression test for an ICE: https://github.com/rust-lang/rust/issues/120884 // Test that we don't ICE for coercions with type errors. // We still need to properly go through coercions between types with errors instead of // shortcutting and returning success, because we need the adjustments for building the MIR. pub fn has_error() -> TypeError {} //~^ ERROR cannot find type `TypeError` in this scope // https://github.com/rust-lang/rust/issues/120884 // Casting a function item to a data pointer in valid in HIR, but invalid in MIR. // We need an adjustment (ReifyFnPointer) to insert a cast from the function item // to a function pointer as a separate MIR statement. pub fn cast() -> *const u8 { // Casting a function item to a data pointer in valid in HIR, but invalid in MIR. // We need an adjustment (ReifyFnPointer) to insert a cast from the function item // to a function pointer as a separate MIR statement. has_error as *const u8 } // https://github.com/rust-lang/rust/issues/120945 // This one ICEd, because we skipped the builtin deref from `&TypeError` to `TypeError`. pub fn autoderef_source(e: &TypeError) { //~^ ERROR cannot find type `TypeError` in this scope autoderef_target(e) } pub fn autoderef_target(_: &TypeError) {} //~^ ERROR cannot find type `TypeError` in this scope fn main() {}"} {"_id":"q-en-rust-02262c424b4eadfef6170fcf1be0e4d427206e8f0338aebd642f99461568a296","text":"use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::util; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::util::ExplicitSelf; use rustc_middle::ty::{ self, GenericArgs, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt,"} {"_id":"q-en-rust-0242ea71aa59c89735af105e1a5f6cc82804bac198d845573b5d731a86a17015","text":"let lifetime_params: Vec<(Span, ParamName)> = this.in_scope_lifetimes .iter().cloned() .map(|ident| (ident.span, ParamName::Plain(ident))) .map(|name| (name.ident().span, name)) .chain(this.lifetimes_to_define.iter().cloned()) .collect(); debug!(\"lower_async_fn_ret_ty: in_scope_lifetimes={:#?}\", this.in_scope_lifetimes); debug!(\"lower_async_fn_ret_ty: lifetimes_to_define={:#?}\", this.lifetimes_to_define); debug!(\"lower_async_fn_ret_ty: lifetime_params={:#?}\", lifetime_params); let generic_params = lifetime_params .iter().cloned()"} {"_id":"q-en-rust-02590f15a97a97f0c28325f27370deed2134a7f714c540ef999013007763b0f3","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":"q-en-rust-0271977ebf9a9ee7b7930981f07037c35915917ce35700e42d52f53638d11e26","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":"q-en-rust-0292e6e00e541911069720cf079d791c2fd2472ec8ddedb01edd2c4d566bbd7f","text":"return; } let is_error = match self.level { self.handler.emit_db(&self); self.cancel(); } pub fn is_error(&self) -> bool { match self.level { Level::Bug | Level::Fatal | Level::PhaseFatal |"} {"_id":"q-en-rust-0295310439546ad0a47771723f5ffda24f1043e3b830cbc287f92dd3d05664f7","text":" error[E0451]: field `0` of struct `Box` is private --> $DIR/issue-82772.rs:5:15 | LL | let Box { 0: _, .. }: Box<()>; | ^^^^ private field error[E0451]: field `1` of struct `Box` is private --> $DIR/issue-82772.rs:6:15 | LL | let Box { 1: _, .. }: Box<()>; | ^^^^ private field error[E0451]: field `1` of struct `ModPrivateStruct` is private --> $DIR/issue-82772.rs:7:28 | LL | let ModPrivateStruct { 1: _, .. } = ModPrivateStruct::default(); | ^^^^ private field error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0451`. "} {"_id":"q-en-rust-02a4971fcb1fd805eeef3d6539b6a9200f341e3f06a4c614b1021284ddb650ba","text":"| LL | semitransparent!; | + help: a unit struct with a similar name exists | LL | SemiTransparent; | ~~~~~~~~~~~~~~~ error[E0423]: expected value, found macro `opaque` --> $DIR/rustc-macro-transparency.rs:30:5 | LL | struct Opaque; | -------------- similarly named unit struct `Opaque` defined here ... LL | opaque; | ^^^^^^ not a value |"} {"_id":"q-en-rust-02e3a766dff3bf66db915472ba62a57c8e018d242df50cb51cd72e1b481a2a34","text":"sig.decl.has_self(), sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)), &sig.decl.output, ) ); this.record_lifetime_params_for_async( fn_id, sig.header.asyncness.opt_return_id(), ); }, ); return;"} {"_id":"q-en-rust-02fc4b31bc1ca4fdfdec6ded7339418f5c51ee4963060da067cf0f12d3d794aa","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":"q-en-rust-032d6e8a20d23aac5c52b2147fabf2bbf6230a9da363314d6d401b1f36735de6","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! invalid { _ => (); //~^ ERROR Invalid macro matcher } fn main() { } "} {"_id":"q-en-rust-032da46e331577358cb86803aef8873e1a9de02ddd21f5a1ee2d34acc930e1e5","text":" // build-pass #![feature(dyn_star)] //~^ WARN the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes fn main() { let x: dyn* Send = &(); let x = Box::new(x) as Box; } "} {"_id":"q-en-rust-03704bbf2f682f0a4fbcb6335d6aa1e284ca6d1487ca81a289948d40340397f7","text":" // build-pass // compile-flags: --crate-type lib // Regression test for ICE which occurred when const propagating an enum with three variants // one of which is uninhabited. pub enum ApiError {} #[allow(dead_code)] pub struct TokioError { b: bool, } pub enum Error { Api { source: ApiError, }, Ethereum, Tokio { source: TokioError, }, } struct Api; impl IntoError for Api { type Source = ApiError; fn into_error(self, error: Self::Source) -> Error { Error::Api { source: (|v| v)(error), } } } pub trait IntoError { /// The underlying error type Source; /// Combine the information to produce the error fn into_error(self, source: Self::Source) -> E; } "} {"_id":"q-en-rust-037e3023fcecdc9f4aa8ff176874769d49debd898aba475bd63357314d7e60e6","text":"use core::intrinsics::abort; use core::iter; use core::marker::{PhantomData, Unpin, Unsize}; use core::mem::{self, align_of_val, size_of_val}; use core::mem::{self, align_of_val_raw, size_of_val}; use core::ops::{CoerceUnsized, Deref, DispatchFromDyn, Receiver}; use core::pin::Pin; use core::ptr::{self, NonNull};"} {"_id":"q-en-rust-0390e9e01ecc03045ad64893b7d9985900a55753284bfc11c4536dd8edd8b9b2","text":"} } } declare_lint! { pub UNNECESSARY_EXTERN_CRATE, Allow, \"suggest removing `extern crate` for the 2018 edition\" } pub struct ExternCrate(/* depth */ u32); impl ExternCrate { pub fn new() -> Self { ExternCrate(0) } } impl LintPass for ExternCrate { fn get_lints(&self) -> LintArray { lint_array!(UNNECESSARY_EXTERN_CRATE) } } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExternCrate { fn check_item(&mut self, cx: &LateContext, it: &hir::Item) { if let hir::ItemExternCrate(ref orig) = it.node { if it.attrs.iter().any(|a| a.check_name(\"macro_use\")) { return } let mut err = cx.struct_span_lint(UNNECESSARY_EXTERN_CRATE, it.span, \"`extern crate` is unnecessary in the new edition\"); if it.vis == hir::Visibility::Public || self.0 > 1 || orig.is_some() { let pub_ = if it.vis == hir::Visibility::Public { \"pub \" } else { \"\" }; let help = format!(\"use `{}use`\", pub_); if let Some(orig) = orig { err.span_suggestion(it.span, &help, format!(\"{}use {} as {}\", pub_, orig, it.name)); } else { err.span_suggestion(it.span, &help, format!(\"{}use {}\", pub_, it.name)); } } else { err.span_suggestion(it.span, \"remove it\", \"\".into()); } err.emit(); } } fn check_mod(&mut self, _: &LateContext, _: &hir::Mod, _: Span, _: ast::NodeId) { self.0 += 1; } fn check_mod_post(&mut self, _: &LateContext, _: &hir::Mod, _: Span, _: ast::NodeId) { self.0 += 1; } } "} {"_id":"q-en-rust-0391b77f7eb41c0cb95d67226ca6a1e126beef4bbce26134dc8c7a9215c73e44","text":"fn hash_stable(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher) { let hash_spans = match self.node { let (is_const, hash_spans) = match self.node { hir::ItemStatic(..) | hir::ItemConst(..) | hir::ItemFn(..) => { hcx.hash_spans() hir::ItemConst(..) => { (true, hcx.hash_spans()) } hir::ItemFn(_, _, constness, ..) => { (constness == hir::Constness::Const, hcx.hash_spans()) } hir::ItemUse(..) | hir::ItemExternCrate(..) |"} {"_id":"q-en-rust-03bcf558741ebc17b3497042d80a14c818fb45a8ae9608b4e7d223e3802bc3e3","text":"} impl, U: ?Sized> CoerceUnsized> for Box {} #[stable(feature = \"box_slice_clone\", since = \"1.3.0\")] impl Clone for Box<[T]> { fn clone(&self) -> Self { let mut new = BoxBuilder { data: RawVec::with_capacity(self.len()), len: 0 }; let mut target = new.data.ptr(); for item in self.iter() { unsafe { ptr::write(target, item.clone()); target = target.offset(1); }; new.len += 1; } return unsafe { new.into_box() }; // Helper type for responding to panics correctly. struct BoxBuilder { data: RawVec, len: usize, } impl BoxBuilder { unsafe fn into_box(self) -> Box<[T]> { let raw = ptr::read(&self.data); mem::forget(self); raw.into_box() } } impl Drop for BoxBuilder { fn drop(&mut self) { let mut data = self.data.ptr(); let max = unsafe { data.offset(self.len as isize) }; while data != max { unsafe { ptr::read(data); data = data.offset(1); } } } } } } "} {"_id":"q-en-rust-03d627bb75f4bb2c172cfd6f54f6356f8206d8e980dc5f1e9871606482f7371e","text":"css_file_extension: css_file_extension.clone(), markdown_warnings: RefCell::new(vec![]), created_dirs: RefCell::new(FxHashSet()), sort_modules_alphabetically, }; // If user passed in `--playground-url` arg, we fill in crate name here"} {"_id":"q-en-rust-03e42111983a0ef7fb6a0983b411934ca02fa6cb63b656c57786eb500600d372","text":"/// of each element in the array. /// /// On arithmetic overflow, returns `None`. #[inline] pub fn repeat(&self, n: usize) -> Option<(Self, usize)> { let padded_size = match self.size.checked_add(self.padding_needed_for(self.align)) { None => return None,"} {"_id":"q-en-rust-042abd1ed5cb9e7873ea0d56f916bd6c29708e73ce8aab39fd64747cbe89e7fe","text":"false } }; if !eligible { return Ok(None); } // HACK: We may have overlapping `dyn Trait` built-in impls and // user-provided blanket impls. Detect that case here, and return // ambiguity. // // This should not affect totally monomorphized contexts, only // resolve calls that happen polymorphically, such as the mir-inliner // and const-prop (and also some lints). let self_ty = rcvr_args.type_at(0); if !self_ty.is_known_rigid() { let predicates = tcx .predicates_of(impl_data.impl_def_id) .instantiate(tcx, impl_data.args) .predicates; let sized_def_id = tcx.lang_items().sized_trait(); // If we find a `Self: Sized` bound on the item, then we know // that `dyn Trait` can certainly never apply here. if !predicates.into_iter().filter_map(ty::Clause::as_trait_clause).any(|clause| { Some(clause.def_id()) == sized_def_id && clause.skip_binder().self_ty() == self_ty }) { return Ok(None); } } // Any final impl is required to define all associated items. if !leaf_def.item.defaultness(tcx).has_value() { let guard = tcx.sess.delay_span_bug("} {"_id":"q-en-rust-0436c132463f84d0e05da28bee198e5919a1e0404c04e627f9bfcc25ddf2f52c","text":"// For LTO purposes, the bytecode of this library is also inserted // into the archive. let bc = obj_filename.with_extension(\"bc\"); let bc_deflated = obj_filename.with_extension(\"bc.deflate\"); match fs::File::open(&bc).read_to_end().and_then(|data| { fs::File::create(&bc).write(flate::deflate_bytes(data).as_slice()) fs::File::create(&bc_deflated).write(flate::deflate_bytes(data).as_slice()) }) { Ok(()) => {} Err(e) => {"} {"_id":"q-en-rust-046aa599a1fe854c4eca013d6a195cb17d1eccd1634cbec8b74dfc6474def9a3","text":"/// # Examples /// /// ```no_run /// #![feature(rw_exact_all_at)] /// use std::io; /// use std::fs::File; /// use std::os::unix::prelude::FileExt;"} {"_id":"q-en-rust-0482bc8cdd75f2a2af955fec1f9d2e7eb891f2bc011570c24438f7578014c6eb","text":" error: expected one of `.`, `?`, `]`, or an operator, found `:` --> $DIR/range-index-instead-of-colon.rs:4:17 | LL | &[1, 2, 3][1:2]; | ^ expected one of `.`, `?`, `]`, or an operator | help: you might have meant a range expression | LL | &[1, 2, 3][1..2]; | ~~ error: aborting due to 1 previous error "} {"_id":"q-en-rust-04ab155a862c79ef4c1d45a1eef33c2300bea6cb504ac58364130d4564131daa","text":"self.insert_def_id(def.non_enum_variant().fields[index].did); } ty::Tuple(..) => {} _ => span_bug!(lhs.span, \"named field access on non-ADT\"), ty::Error(_) => {} kind => span_bug!(lhs.span, \"named field access on non-ADT: {kind:?}\"), } }"} {"_id":"q-en-rust-04ad3eb841a10c0144ee3d2fb9467ee4fc2cf6145014fd05e00a91c6fe6279df","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(associated_consts)] pub use self::sub::{Bar, Baz}; pub trait Trait { fn foo(&self); type Assoc; const CONST: u32; } struct Foo; impl Foo { pub fn new() {} pub const C: u32 = 0; } mod sub {"} {"_id":"q-en-rust-04b039140e9d55e2882bf916372c154de5846db9f452826e34f921a8d9a56423","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":"q-en-rust-054012863feed619bb0fee6ee44e9da98f182f51d6ada3d677a535788e56b7b4","text":"| ^^^^^^^ value used here after move | = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider borrowing instead of transferring ownership | LL | let _ = dbg!(&a); | + error: aborting due to 1 previous error"} {"_id":"q-en-rust-0553a8ec1b92f978fe923d6ffeef4dd12ad99e46ca5fa511e780a7c28f3776f4","text":"match module.inner { ModuleItem(ref module) => { for it in &module.items { if it.is_extern_crate() && it.attrs.has_doc_flag(\"masked\") { // `compiler_builtins` should be masked too, but we can't apply // `#[doc(masked)]` to the injected `extern crate` because it's unstable. if it.is_extern_crate() && (it.attrs.has_doc_flag(\"masked\") || self.cx.tcx.is_compiler_builtins(it.def_id.krate)) { masked_crates.insert(it.def_id.krate); } }"} {"_id":"q-en-rust-0568356bde8f909eb76a75e83907a79e870f13bd66c2341e2c1e5823bb5945a8","text":"} // We probe again, taking all traits into account (not only those in scope). let mut candidates = let candidates = match self.lookup_probe(segment.ident, self_ty, call_expr, ProbeScope::AllTraits) { // If we find a different result the caller probably forgot to import a trait. Ok(ref new_pick) if pick.differs_from(new_pick) => {"} {"_id":"q-en-rust-05a596f469eda23c8aba1eed9d5ae081757a7bdb2e42144a9501616cc502ef2c","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":"q-en-rust-05b661ab003fe80ef09f4800870d8c46fe31ccbf23aca42f81f729ca86905e82","text":"} let (ours, theirs) = self.setup_io(default, needs_stdin)?; if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? { return Ok((ret, ours)) } let (input, output) = sys::pipe::anon_pipe()?; let pid = unsafe {"} {"_id":"q-en-rust-06063728883504ad86c84442dd06b89a2b7b80c5e8a2d96c736689a39d0830d2","text":"impl FileAttr { pub fn size(&self) -> u64 { self.stat.st_size as u64 } pub fn perm(&self) -> FilePermissions { FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 } FilePermissions { mode: (self.stat.st_mode as mode_t) } } pub fn file_type(&self) -> FileType {"} {"_id":"q-en-rust-0641117d07c4bb60cdbe5feb13df1b7c066bcb0de43ef0668e2652e6817c32e3","text":"{ // The dereferenced place must have type `&_`. let ty = Place::ty_from(local, proj_base, self.body, self.tcx).ty; if let ty::Ref(_, _, mtbl) = ty.kind { self.optimizations.and_stars.insert(location, mtbl); if let ty::Ref(_, _, Mutability::Not) = ty.kind { self.optimizations.and_stars.insert(location); } } }"} {"_id":"q-en-rust-067bacad6c23d213fa817c54bc0625c51b4386cfb9c1c9b886514570655cbb98","text":" // no-prefer-dynamic // pretty-expanded FIXME #23616 #![feature(rustc_private)]"} {"_id":"q-en-rust-06d1585d1929ea255ebf844614840eda009680f63a53174fc284b2fced656ad6","text":" { \"message\": \"unnecessary parentheses around `if` condition\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 521, \"byte_end\": 525, \"line_start\": 18, \"line_end\": 18, \"column_start\": 8, \"column_end\": 12, \"is_primary\": true, \"text\": [ { \"text\": \" if (_b) {\", \"highlight_start\": 8, \"highlight_end\": 12 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"lint level defined here\", \"code\": null, \"level\": \"note\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 435, \"byte_end\": 448, \"line_start\": 11, \"line_end\": 11, \"column_start\": 9, \"column_end\": 22, \"is_primary\": true, \"text\": [ { \"text\": \"#![warn(unused_parens)]\", \"highlight_start\": 9, \"highlight_end\": 22 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [], \"rendered\": null }, { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 521, \"byte_end\": 525, \"line_start\": 18, \"line_end\": 18, \"column_start\": 8, \"column_end\": 12, \"is_primary\": true, \"text\": [ { \"text\": \" if (_b) {\", \"highlight_start\": 8, \"highlight_end\": 12 } ], \"label\": null, \"suggested_replacement\": \"_b\", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around `if` condition --> $DIR/unused_parens_remove_json_suggestion.rs:18:8 {\"message\":\"unnecessary parentheses around `if` condition\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":500,\"byte_end\":504,\"line_start\":17,\"line_end\":17,\"column_start\":8,\"column_end\":12,\"is_primary\":true,\"text\":[{\"text\":\" if (_b) { --> $DIR/unused_parens_remove_json_suggestion.rs:17:8 | LL | if (_b) { | ^^^^ help: remove these parentheses | note: lint level defined here --> $DIR/unused_parens_remove_json_suggestion.rs:11:9 --> $DIR/unused_parens_remove_json_suggestion.rs:10:9 | LL | #![warn(unused_parens)] LL | #![deny(unused_parens)] | ^^^^^^^^^^^^^ \" } { \"message\": \"unnecessary parentheses around `if` condition\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 618, \"byte_end\": 621, \"line_start\": 29, \"line_end\": 29, \"column_start\": 7, \"column_end\": 10, \"is_primary\": true, \"text\": [ { \"text\": \" if(c) {\", \"highlight_start\": 7, \"highlight_end\": 10 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 618, \"byte_end\": 621, \"line_start\": 29, \"line_end\": 29, \"column_start\": 7, \"column_end\": 10, \"is_primary\": true, \"text\": [ { \"text\": \" if(c) {\", \"highlight_start\": 7, \"highlight_end\": 10 } ], \"label\": null, \"suggested_replacement\": \" c\", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around `if` condition --> $DIR/unused_parens_remove_json_suggestion.rs:29:7 \"} {\"message\":\"unnecessary parentheses around `if` condition\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":631,\"byte_end\":634,\"line_start\":28,\"line_end\":28,\"column_start\":7,\"column_end\":10,\"is_primary\":true,\"text\":[{\"text\":\" if(c) { --> $DIR/unused_parens_remove_json_suggestion.rs:28:7 | LL | if(c) { | ^^^ help: remove these parentheses \" } { \"message\": \"unnecessary parentheses around `if` condition\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 664, \"byte_end\": 667, \"line_start\": 33, \"line_end\": 33, \"column_start\": 8, \"column_end\": 11, \"is_primary\": true, \"text\": [ { \"text\": \" if (c){\", \"highlight_start\": 8, \"highlight_end\": 11 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 664, \"byte_end\": 667, \"line_start\": 33, \"line_end\": 33, \"column_start\": 8, \"column_end\": 11, \"is_primary\": true, \"text\": [ { \"text\": \" if (c){\", \"highlight_start\": 8, \"highlight_end\": 11 } ], \"label\": null, \"suggested_replacement\": \"c \", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around `if` condition --> $DIR/unused_parens_remove_json_suggestion.rs:33:8 \"} {\"message\":\"unnecessary parentheses around `if` condition\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":711,\"byte_end\":714,\"line_start\":32,\"line_end\":32,\"column_start\":8,\"column_end\":11,\"is_primary\":true,\"text\":[{\"text\":\" if (c){ --> $DIR/unused_parens_remove_json_suggestion.rs:32:8 | LL | if (c){ | ^^^ help: remove these parentheses \" } { \"message\": \"unnecessary parentheses around `while` condition\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 712, \"byte_end\": 727, \"line_start\": 37, \"line_end\": 37, \"column_start\": 11, \"column_end\": 26, \"is_primary\": true, \"text\": [ { \"text\": \" while (false && true){\", \"highlight_start\": 11, \"highlight_end\": 26 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 712, \"byte_end\": 727, \"line_start\": 37, \"line_end\": 37, \"column_start\": 11, \"column_end\": 26, \"is_primary\": true, \"text\": [ { \"text\": \" while (false && true){\", \"highlight_start\": 11, \"highlight_end\": 26 } ], \"label\": null, \"suggested_replacement\": \"false && true \", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around `while` condition --> $DIR/unused_parens_remove_json_suggestion.rs:37:11 \"} {\"message\":\"unnecessary parentheses around `while` condition\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":793,\"byte_end\":808,\"line_start\":36,\"line_end\":36,\"column_start\":11,\"column_end\":26,\"is_primary\":true,\"text\":[{\"text\":\" while (false && true){\",\"highlight_start\":11,\"highlight_end\":26}],\"label\":null,\"suggested_replacement\":null,\"suggestion_applicability\":null,\"expansion\":null}],\"children\":[{\"message\":\"remove these parentheses\",\"code\":null,\"level\":\"help\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":793,\"byte_end\":808,\"line_start\":36,\"line_end\":36,\"column_start\":11,\"column_end\":26,\"is_primary\":true,\"text\":[{\"text\":\" while (false && true){\",\"highlight_start\":11,\"highlight_end\":26}],\"label\":null,\"suggested_replacement\":\"false && true \",\"suggestion_applicability\":\"MachineApplicable\",\"expansion\":null}],\"children\":[],\"rendered\":null}],\"rendered\":\"error: unnecessary parentheses around `while` condition --> $DIR/unused_parens_remove_json_suggestion.rs:36:11 | LL | while (false && true){ | ^^^^^^^^^^^^^^^ help: remove these parentheses \" } { \"message\": \"unnecessary parentheses around `if` condition\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 740, \"byte_end\": 743, \"line_start\": 38, \"line_end\": 38, \"column_start\": 12, \"column_end\": 15, \"is_primary\": true, \"text\": [ { \"text\": \" if (c) {\", \"highlight_start\": 12, \"highlight_end\": 15 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 740, \"byte_end\": 743, \"line_start\": 38, \"line_end\": 38, \"column_start\": 12, \"column_end\": 15, \"is_primary\": true, \"text\": [ { \"text\": \" if (c) {\", \"highlight_start\": 12, \"highlight_end\": 15 } ], \"label\": null, \"suggested_replacement\": \"c\", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around `if` condition --> $DIR/unused_parens_remove_json_suggestion.rs:38:12 \"} {\"message\":\"unnecessary parentheses around `if` condition\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":821,\"byte_end\":824,\"line_start\":37,\"line_end\":37,\"column_start\":12,\"column_end\":15,\"is_primary\":true,\"text\":[{\"text\":\" if (c) { --> $DIR/unused_parens_remove_json_suggestion.rs:37:12 | LL | if (c) { | ^^^ help: remove these parentheses \" } { \"message\": \"unnecessary parentheses around `while` condition\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 803, \"byte_end\": 818, \"line_start\": 44, \"line_end\": 44, \"column_start\": 10, \"column_end\": 25, \"is_primary\": true, \"text\": [ { \"text\": \" while(true && false) {\", \"highlight_start\": 10, \"highlight_end\": 25 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 803, \"byte_end\": 818, \"line_start\": 44, \"line_end\": 44, \"column_start\": 10, \"column_end\": 25, \"is_primary\": true, \"text\": [ { \"text\": \" while(true && false) {\", \"highlight_start\": 10, \"highlight_end\": 25 } ], \"label\": null, \"suggested_replacement\": \" true && false\", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around `while` condition --> $DIR/unused_parens_remove_json_suggestion.rs:44:10 \"} {\"message\":\"unnecessary parentheses around `while` condition\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":918,\"byte_end\":933,\"line_start\":43,\"line_end\":43,\"column_start\":10,\"column_end\":25,\"is_primary\":true,\"text\":[{\"text\":\" while(true && false) { --> $DIR/unused_parens_remove_json_suggestion.rs:43:10 | LL | while(true && false) { | ^^^^^^^^^^^^^^^ help: remove these parentheses \" } { \"message\": \"unnecessary parentheses around `for` head expression\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 838, \"byte_end\": 846, \"line_start\": 45, \"line_end\": 45, \"column_start\": 18, \"column_end\": 26, \"is_primary\": true, \"text\": [ { \"text\": \" for _ in (0 .. 3){\", \"highlight_start\": 18, \"highlight_end\": 26 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 838, \"byte_end\": 846, \"line_start\": 45, \"line_end\": 45, \"column_start\": 18, \"column_end\": 26, \"is_primary\": true, \"text\": [ { \"text\": \" for _ in (0 .. 3){\", \"highlight_start\": 18, \"highlight_end\": 26 } ], \"label\": null, \"suggested_replacement\": \"0 .. 3 \", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around `for` head expression --> $DIR/unused_parens_remove_json_suggestion.rs:45:18 \"} {\"message\":\"unnecessary parentheses around `for` head expression\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":987,\"byte_end\":995,\"line_start\":44,\"line_end\":44,\"column_start\":18,\"column_end\":26,\"is_primary\":true,\"text\":[{\"text\":\" for _ in (0 .. 3){ --> $DIR/unused_parens_remove_json_suggestion.rs:44:18 | LL | for _ in (0 .. 3){ | ^^^^^^^^ help: remove these parentheses \" } { \"message\": \"unnecessary parentheses around `for` head expression\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 905, \"byte_end\": 913, \"line_start\": 50, \"line_end\": 50, \"column_start\": 14, \"column_end\": 22, \"is_primary\": true, \"text\": [ { \"text\": \" for _ in (0 .. 3) {\", \"highlight_start\": 14, \"highlight_end\": 22 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 905, \"byte_end\": 913, \"line_start\": 50, \"line_end\": 50, \"column_start\": 14, \"column_end\": 22, \"is_primary\": true, \"text\": [ { \"text\": \" for _ in (0 .. 3) {\", \"highlight_start\": 14, \"highlight_end\": 22 } ], \"label\": null, \"suggested_replacement\": \"0 .. 3\", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around `for` head expression --> $DIR/unused_parens_remove_json_suggestion.rs:50:14 \"} {\"message\":\"unnecessary parentheses around `for` head expression\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":1088,\"byte_end\":1096,\"line_start\":49,\"line_end\":49,\"column_start\":14,\"column_end\":22,\"is_primary\":true,\"text\":[{\"text\":\" for _ in (0 .. 3) { --> $DIR/unused_parens_remove_json_suggestion.rs:49:14 | LL | for _ in (0 .. 3) { | ^^^^^^^^ help: remove these parentheses \" } { \"message\": \"unnecessary parentheses around `while` condition\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 930, \"byte_end\": 945, \"line_start\": 51, \"line_end\": 51, \"column_start\": 15, \"column_end\": 30, \"is_primary\": true, \"text\": [ { \"text\": \" while (true && false) {\", \"highlight_start\": 15, \"highlight_end\": 30 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_remove_json_suggestion.rs\", \"byte_start\": 930, \"byte_end\": 945, \"line_start\": 51, \"line_end\": 51, \"column_start\": 15, \"column_end\": 30, \"is_primary\": true, \"text\": [ { \"text\": \" while (true && false) {\", \"highlight_start\": 15, \"highlight_end\": 30 } ], \"label\": null, \"suggested_replacement\": \"true && false\", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around `while` condition --> $DIR/unused_parens_remove_json_suggestion.rs:51:15 \"} {\"message\":\"unnecessary parentheses around `while` condition\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_remove_json_suggestion.rs\",\"byte_start\":1147,\"byte_end\":1162,\"line_start\":50,\"line_end\":50,\"column_start\":15,\"column_end\":30,\"is_primary\":true,\"text\":[{\"text\":\" while (true && false) { --> $DIR/unused_parens_remove_json_suggestion.rs:50:15 | LL | while (true && false) { | ^^^^^^^^^^^^^^^ help: remove these parentheses \" } \"} {\"message\":\"aborting due to 9 previous errors\",\"code\":null,\"level\":\"error\",\"spans\":[],\"children\":[],\"rendered\":\"error: aborting due to 9 previous errors \"} "} {"_id":"q-en-rust-06d2986a9df270a92f67f9dbaf80438542a18202a4393dc1e87ffa25b5e6e531","text":" // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // 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. // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // - Neither the name of \"The Computer Language Benchmarks Game\" nor // the name of \"The Computer Language Shootout Benchmarks\" nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // ignore-pretty very bad with line comments // ignore-android doesn't terminate?"} {"_id":"q-en-rust-06f0f3644e046d5a2f324212de26df31f9f2af838f180e7111e678ab20c01e1a","text":"} } fn rustc_sysroot() -> str { alt os::get_exe_path() { some(_path) { let path = [_path, \"..\", \"bin\", \"rustc\"]; check vec::is_not_empty(path); let rustc = fs::normalize(fs::connect_many(path)); #debug(\" rustc: %s\", rustc); rustc } none { \"rustc\" } } } fn install_source(c: cargo, path: str) { #debug(\"source: %s\", path); fs::change_dir(path);"} {"_id":"q-en-rust-07332d9e064a29a1c0d3d1f0c7c16a7b5c4939387ec3075edcbbbc162b3a1ad0","text":"} struct SelectionCandidateSet<'tcx> { // A list of candidates that definitely apply to the current // obligation (meaning: types unify). /// A list of candidates that definitely apply to the current /// obligation (meaning: types unify). vec: Vec>, // If `true`, then there were candidates that might or might // not have applied, but we couldn't tell. This occurs when some // of the input types are type variables, in which case there are // various \"builtin\" rules that might or might not trigger. /// If `true`, then there were candidates that might or might /// not have applied, but we couldn't tell. This occurs when some /// of the input types are type variables, in which case there are /// various \"builtin\" rules that might or might not trigger. ambiguous: bool, }"} {"_id":"q-en-rust-076355d47459ad6502fe5249338f189b9625da034962fd16a9d4a85203ad8bb9","text":"# FIXME: we should probe the default azure image and see if we can use the MSYS2 # toolchain there. (if there's even one there). For now though this gets the job # done. - script: | set MSYS_PATH=%CD%citoolsmsys64 choco install msys2 --params=\"/InstallDir:%MSYS_PATH% /NoPath\" -y set PATH=%MSYS_PATH%usrbin;%PATH% pacman -S --noconfirm --needed base-devel ca-certificates make diffutils tar IF \"%MINGW_URL%\"==\"\" ( IF \"%MSYS_BITS%\"==\"32\" pacman -S --noconfirm --needed mingw-w64-i686-toolchain mingw-w64-i686-cmake mingw-w64-i686-gcc mingw-w64-i686-python2 IF \"%MSYS_BITS%\"==\"64\" pacman -S --noconfirm --needed mingw-w64-x86_64-toolchain mingw-w64-x86_64-cmake mingw-w64-x86_64-gcc mingw-w64-x86_64-python2 ) where rev rev --help where make echo ##vso[task.setvariable variable=MSYS_PATH]%MSYS_PATH% echo ##vso[task.prependpath]%MSYS_PATH%usrbin - bash: | set -e choco install msys2 --params=\"/InstallDir:$(System.Workfolder)/msys2 /NoPath\" -y --no-progress echo \"##vso[task.prependpath]$(System.Workfolder)/msys2/usr/bin\" mkdir -p \"$(System.Workfolder)/msys2/home/$USERNAME\" displayName: Install msys2 condition: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT')) - bash: pacman -S --noconfirm --needed base-devel ca-certificates make diffutils tar displayName: Install msys2 base deps condition: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT')) # If we need to download a custom MinGW, do so here and set the path # appropriately. #"} {"_id":"q-en-rust-07654e43974e10e1b2f232586ba368d9f762d687a89bb861fd259f30760c6411","text":"--> $DIR/rustc-macro-transparency.rs:26:5 | LL | Opaque; | ^^^^^^ help: a local variable with a similar name exists (notice the capitalization): `opaque` | ^^^^^^ not found in this scope error[E0423]: expected value, found macro `semitransparent` --> $DIR/rustc-macro-transparency.rs:29:5 | LL | struct SemiTransparent; | ----------------------- similarly named unit struct `SemiTransparent` defined here ... LL | semitransparent; | ^^^^^^^^^^^^^^^ not a value |"} {"_id":"q-en-rust-077aa89114342042339d91e7b32db32bb53d9c6a3d330b6149ad8bdc4eb502c3","text":"} } let sp = span_of_attrs(attrs).from_inner(InnerSpan::new( Some(span_of_attrs(attrs)?.from_inner(InnerSpan::new( md_range.start + start_bytes, md_range.end + start_bytes + end_bytes, )); Some(sp) ))) }"} {"_id":"q-en-rust-077b0797a955bd8741c7f84bcc61f044b4c6c2a2e13b9b9eebb07a3a24284ac8","text":" // Regression test for #80468. #![crate_type = \"lib\"] pub trait Trait {} #[repr(transparent)] pub struct Wrapper(T); #[repr(transparent)] pub struct Ref<'a>(&'a u8); impl Trait for Ref {} //~ ERROR: implicit elided lifetime not allowed here extern \"C\" { pub fn repro(_: Wrapper); //~ ERROR: mismatched types } "} {"_id":"q-en-rust-07c9be00b47297410d45c47ab99b62ab4d0628b03f69897727d68e6c57b95fc3","text":"#[expect(invalid_nan_comparisons)] //~^ WARNING this lint expectation is unfulfilled [unfulfilled_lint_expectations] //~| WARNING this lint expectation is unfulfilled [unfulfilled_lint_expectations] //~| NOTE duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` let _b = x == 5; } }"} {"_id":"q-en-rust-08060cd9fe5bece4b98eedeba5fb9f0297089842c2aa58ceeb8077187a0c2c58","text":" # `macro_literal_matcher` The tracking issue for this feature is: [#35625] The RFC is: [rfc#1576]. With this feature gate enabled, the [list of designators] gains one more entry: * `literal`: a literal. Examples: 2, \"string\", 'c' A `literal` may be followed by anything, similarly to the `ident` specifier. [rfc#1576]: http://rust-lang.github.io/rfcs/1576-macros-literal-matcher.html [#35625]: https://github.com/rust-lang/rust/issues/35625 [list of designators]: ../reference/macros-by-example.html ------------------------ "} {"_id":"q-en-rust-08347a5c175b4c04a9e8be4f426ee0b485c3e0f70a6b8b54ed72aaff8b7d5d45","text":"/// A specific scope in which a name can be looked up. /// This enum is currently used only for early resolution (imports and macros), /// but not for late resolution yet. #[derive(Clone, Copy)] #[derive(Clone, Copy, Debug)] enum Scope<'a> { DeriveHelpers(LocalExpnId), DeriveHelpersCompat,"} {"_id":"q-en-rust-0837155d8f79f9dfd4bb68d20af6b3560522c2c54847124cf689217c7c5d317f","text":"pub use crate::sys_common::fs::remove_dir_all; } // Dynamically choose implementation Macos x86-64: modern for 10.10+, fallback for older versions #[cfg(all(target_os = \"macos\", target_arch = \"x86_64\"))] // Modern implementation using openat(), unlinkat() and fdopendir() #[cfg(not(any(target_os = \"redox\", target_os = \"espidf\")))] mod remove_dir_impl { use super::{cstr, lstat, Dir, InnerReadDir, ReadDir}; use super::{cstr, lstat, Dir, DirEntry, InnerReadDir, ReadDir}; use crate::ffi::CStr; use crate::io; use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd}; use crate::os::unix::prelude::{OwnedFd, RawFd}; use crate::path::{Path, PathBuf}; use crate::sync::Arc; use crate::sys::weak::weak; use crate::sys::{cvt, cvt_r}; use libc::{c_char, c_int, DIR}; pub fn openat_nofollow_dironly(parent_fd: Option, p: &CStr) -> io::Result { weak!(fn openat(c_int, *const c_char, c_int) -> c_int); let fd = cvt_r(|| unsafe { openat.get().unwrap()( parent_fd.unwrap_or(libc::AT_FDCWD), p.as_ptr(), libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY, ) })?; Ok(unsafe { OwnedFd::from_raw_fd(fd) }) } fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> { weak!(fn fdopendir(c_int) -> *mut DIR, \"fdopendir$INODE64\"); let ptr = unsafe { fdopendir.get().unwrap()(dir_fd.as_raw_fd()) }; if ptr.is_null() { return Err(io::Error::last_os_error()); } let dirp = Dir(ptr); // file descriptor is automatically closed by libc::closedir() now, so give up ownership let new_parent_fd = dir_fd.into_raw_fd(); // a valid root is not needed because we do not call any functions involving the full path // of the DirEntrys. let dummy_root = PathBuf::new(); Ok(( ReadDir { inner: Arc::new(InnerReadDir { dirp, root: dummy_root }), end_of_stream: false, }, new_parent_fd, )) } fn remove_dir_all_recursive(parent_fd: Option, p: &Path) -> io::Result<()> { weak!(fn unlinkat(c_int, *const c_char, c_int) -> c_int); #[cfg(not(all(target_os = \"macos\", target_arch = \"x86_64\"),))] use libc::{fdopendir, openat, unlinkat}; #[cfg(all(target_os = \"macos\", target_arch = \"x86_64\"))] use macos_weak::{fdopendir, openat, unlinkat}; let pcstr = cstr(p)?; #[cfg(all(target_os = \"macos\", target_arch = \"x86_64\"))] mod macos_weak { use crate::sys::weak::weak; use libc::{c_char, c_int, DIR}; // entry is expected to be a directory, open as such let fd = openat_nofollow_dironly(parent_fd, &pcstr)?; fn get_openat_fn() -> Option c_int> { weak!(fn openat(c_int, *const c_char, c_int) -> c_int); openat.get() } // open the directory passing ownership of the fd let (dir, fd) = fdreaddir(fd)?; for child in dir { let child = child?; match child.entry.d_type { libc::DT_DIR => { remove_dir_all_recursive(Some(fd), Path::new(&child.file_name()))?; } libc::DT_UNKNOWN => { match cvt(unsafe { unlinkat.get().unwrap()(fd, child.name_cstr().as_ptr(), 0) }) { // type unknown - try to unlink Err(err) if err.raw_os_error() == Some(libc::EPERM) => { // if the file is a directory unlink fails with EPERM remove_dir_all_recursive(Some(fd), Path::new(&child.file_name()))?; } result => { result?; } } } _ => { // not a directory -> unlink cvt(unsafe { unlinkat.get().unwrap()(fd, child.name_cstr().as_ptr(), 0) })?; } } pub fn has_openat() -> bool { get_openat_fn().is_some() } // unlink the directory after removing its contents cvt(unsafe { unlinkat.get().unwrap()( parent_fd.unwrap_or(libc::AT_FDCWD), pcstr.as_ptr(), libc::AT_REMOVEDIR, ) })?; Ok(()) } pub unsafe fn openat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int { get_openat_fn().map(|openat| openat(dirfd, pathname, flags)).unwrap_or_else(|| { crate::sys::unix::os::set_errno(libc::ENOSYS); -1 }) } fn remove_dir_all_modern(p: &Path) -> io::Result<()> { // We cannot just call remove_dir_all_recursive() here because that would not delete a passed // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse // into symlinks. let attr = lstat(p)?; if attr.file_type().is_symlink() { crate::fs::remove_file(p) } else { remove_dir_all_recursive(None, p) pub unsafe fn fdopendir(fd: c_int) -> *mut DIR { weak!(fn fdopendir(c_int) -> *mut DIR, \"fdopendir$INODE64\"); fdopendir.get().map(|fdopendir| fdopendir(fd)).unwrap_or_else(|| { crate::sys::unix::os::set_errno(libc::ENOSYS); crate::ptr::null_mut() }) } } pub fn remove_dir_all(p: &Path) -> io::Result<()> { weak!(fn openat(c_int, *const c_char, c_int) -> c_int); if openat.get().is_some() { // openat() is available with macOS 10.10+, just like unlinkat() and fdopendir() remove_dir_all_modern(p) } else { // fall back to classic implementation crate::sys_common::fs::remove_dir_all(p) pub unsafe fn unlinkat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int { weak!(fn unlinkat(c_int, *const c_char, c_int) -> c_int); unlinkat.get().map(|unlinkat| unlinkat(dirfd, pathname, flags)).unwrap_or_else(|| { crate::sys::unix::os::set_errno(libc::ENOSYS); -1 }) } } } // Modern implementation using openat(), unlinkat() and fdopendir() #[cfg(not(any( all(target_os = \"macos\", target_arch = \"x86_64\"), target_os = \"redox\", target_os = \"espidf\" )))] mod remove_dir_impl { use super::{cstr, lstat, Dir, DirEntry, InnerReadDir, ReadDir}; use crate::ffi::CStr; use crate::io; use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd}; use crate::os::unix::prelude::{OwnedFd, RawFd}; use crate::path::{Path, PathBuf}; use crate::sync::Arc; use crate::sys::{cvt, cvt_r}; use libc::{fdopendir, openat, unlinkat}; pub fn openat_nofollow_dironly(parent_fd: Option, p: &CStr) -> io::Result { let fd = cvt_r(|| unsafe {"} {"_id":"q-en-rust-0850700fe0e913ce30f1faf526cd0d8d73735b1a278f2029e64daf08d02ec924","text":"BufWriter { inner: Some(inner), buf: Vec::with_capacity(cap), panicked: false, } }"} {"_id":"q-en-rust-08692c17e88e60d7e728d429aa3332e0bfd3cdaa28f60f9eacddd3b68a0007dc","text":" error[E0658]: trait upcasting coercion is experimental error[E0658]: cannot cast `dyn Fn()` to `dyn FnMut()`, trait upcasting coercion is experimental --> $DIR/issue-11515.rs:9:33 | LL | let test = box Test { func: closure };"} {"_id":"q-en-rust-08816bf85ae41e8f9a03e81fa3552a7e2fcff77e3818361cbb66f727356eea1f","text":" error[E0433]: failed to resolve: there are too many leading `super` keywords --> $DIR/issue-117920.rs:3:5 | LL | use super::A; | ^^^^^ there are too many leading `super` keywords error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0433`. "} {"_id":"q-en-rust-088d125e37e007ea8983dfe8259ec554ce5299fa6d7805f55617f2be154779bb","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. // ignore-pretty #27582 // Check that when a `let`-binding occurs in a loop, its associated // drop-flag is reinitialized (to indicate \"needs-drop\" at the end of // the owning variable's scope). struct A<'a>(&'a mut i32); impl<'a> Drop for A<'a> { fn drop(&mut self) { *self.0 += 1; } } fn main() { let mut cnt = 0; for i in 0..2 { let a = A(&mut cnt); if i == 1 { // Note that break; // both this break } // and also drop(a); // this move of `a` // are necessary to expose the bug } assert_eq!(cnt, 2); } "} {"_id":"q-en-rust-08bd8698c1bf275b67c9fc99a3e3a62dd4299692048bdf36f80fc87b9b44f9b6","text":"// except according to those terms. // run-pass #![feature(macro_literal_matcher)] macro_rules! mtester { ($l:literal) => {"} {"_id":"q-en-rust-08c0967057c6b67760883abf3d876fbbbc42a1812cce0c29846d8250230f3330","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":"q-en-rust-08cfb9301b47b496b7f24003f30822fb10a6991109b387f9aa7ad49fdd79342e","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":"q-en-rust-08d45275b33e40d64087215db14eaf9f27b76c9b44b13db18073ade98267545d","text":"assert_eq!(ys, [1, 2, 3]); } #[test] fn test_box_slice_clone() { let data = vec![vec![0, 1], vec![0], vec![1]]; let data2 = data.clone().into_boxed_slice().clone().to_vec(); assert_eq!(data, data2); } #[test] fn test_box_slice_clone_panics() { use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread::spawn; struct Canary { count: Arc, panics: bool } impl Drop for Canary { fn drop(&mut self) { self.count.fetch_add(1, Ordering::SeqCst); } } impl Clone for Canary { fn clone(&self) -> Self { if self.panics { panic!() } Canary { count: self.count.clone(), panics: self.panics } } } let drop_count = Arc::new(AtomicUsize::new(0)); let canary = Canary { count: drop_count.clone(), panics: false }; let panic = Canary { count: drop_count.clone(), panics: true }; spawn(move || { // When xs is dropped, +5. let xs = vec![canary.clone(), canary.clone(), canary.clone(), panic, canary].into_boxed_slice(); // When panic is cloned, +3. xs.clone(); }).join().unwrap_err(); // Total = 8 assert_eq!(drop_count.load(Ordering::SeqCst), 8); } mod bench { use std::iter::repeat; use std::{mem, ptr};"} {"_id":"q-en-rust-09136fdc43033d74b82f8a7fef3ea6028bfcab9f716d79fbc4f0ddd3693be4a3","text":"= 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 #71800 error: aborting due to 47 previous errors error: any use of this value will cause an error --> $DIR/const-int-unchecked.rs:191:25 | LL | const _: u32 = unsafe { std::intrinsics::ctlz_nonzero(0) }; | ------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- | | | `ctlz_nonzero` called on 0 | = 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 #71800 error: any use of this value will cause an error --> $DIR/const-int-unchecked.rs:194:25 | LL | const _: u32 = unsafe { std::intrinsics::cttz_nonzero(0) }; | ------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- | | | `cttz_nonzero` called on 0 | = 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 #71800 error: aborting due to 49 previous errors "} {"_id":"q-en-rust-092e4cb5fdaa34b9d0e9d374311f0cc4b40bfcd9aafe8749a3704875db8510bb","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":"q-en-rust-09663c436c0fd4cc41c9ca1b07f9df18e7246923c52f4ded105f8d23379c302b","text":"use rustc_hir::def::{self, DefKind, NonMacroAttrKind}; use rustc_hir::def_id; use rustc_middle::middle::stability; use rustc_middle::{span_bug, ty}; use rustc_middle::ty; use rustc_session::lint::builtin::UNUSED_MACROS; use rustc_session::Session; use rustc_span::edition::Edition;"} {"_id":"q-en-rust-098d01c8f0796a82e3cf8d1b54cb0b9a4068449cba2338b535a80fae2fffd3d1","text":" error: requires `generator` lang_item error: aborting due to previous error "} {"_id":"q-en-rust-0995b2437505d6d6ca01f4baa226c80feb0d79e5a131db01db807f9ebf627bc8","text":" // In rustc_typeck::check::expr::no_such_field_err we recursively // look in subfields for the field. This recursive search is limited // in depth for compile-time reasons and to avoid infinite recursion // in case of cycles. This file tests that the limit in the recursion // depth is enforced. struct Foo { first: Bar, second: u32, third: u32, } struct Bar { bar: C, } struct C { c: D, } struct D { test: E, } struct E { e: F, } struct F { f: u32, } fn main() { let f = F { f: 6 }; let e = E { e: f }; let d = D { test: e }; let c = C { c: d }; let bar = Bar { bar: c }; let fooer = Foo { first: bar, second: 4, third: 5 }; let test = fooer.f; //~^ ERROR no field } "} {"_id":"q-en-rust-09c1ab9c6ddef57f859143b85e7eb84f7385e129ae9675b2e7906f44fcdb64ad","text":" // run-rustfix fn main() { let a: usize = 123; let b: &usize = &a; if true { a } else { b //~ ERROR `if` and `else` have incompatible types [E0308] }; if true { 1 } else { &1 //~ ERROR `if` and `else` have incompatible types [E0308] }; if true { 1 } else { &mut 1 //~ ERROR `if` and `else` have incompatible types [E0308] }; } "} {"_id":"q-en-rust-09d6df2ee613a1874fc408a296ea83737c768b998f5f5136ca999a02da192fd6","text":" // rust-lang/rust#60654: Do not ICE on an attempt to use GATs that is // missing the feature gate. struct Foo; impl Iterator for Foo { type Item<'b> = &'b Foo; //~ ERROR generic associated types are unstable [E0658] fn next(&mut self) -> Option { None } } fn main() { } "} {"_id":"q-en-rust-09dc5160318ee6f1401c3562dcf6d4b7cae5fe5abe51a58d1ba82c3e565c428b","text":"// SAFETY: left and right must be valid and part of v same for out. unsafe { let to_copy = if is_less(&*right, &**left) { get_and_increment(&mut right) } else { get_and_increment(left) }; ptr::copy_nonoverlapping(to_copy, get_and_increment(out), 1); let is_l = is_less(&*right, &**left); let to_copy = if is_l { right } else { *left }; ptr::copy_nonoverlapping(to_copy, *out, 1); *out = out.add(1); right = right.add(is_l as usize); *left = left.add(!is_l as usize); } } } else {"} {"_id":"q-en-rust-09e6548e490a5ed27835cb29be850c7df1b2a22a686105974f39310a26e35b28","text":")]; let mut has_unsized_tuple_coercion = false; let mut has_trait_upcasting_coercion = false; let mut has_trait_upcasting_coercion = None; // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where"} {"_id":"q-en-rust-09ea12acf5548be4649b9f5a26e607727cbe4063083b13a88002d35f2bd85153","text":"// More information on the environment variable is available here: // https://www.gnu.org/prep/standards/html_node/DESTDIR.html if let Some(destdir) = env::var_os(\"DESTDIR\").map(PathBuf::from) { // Sanity check for the user write access on DESTDIR assert!(is_dir_writable_for_user(&destdir), \"User doesn't have write access on DESTDIR.\"); let without_destdir = path.clone(); path = destdir; // Custom .join() which ignores disk roots."} {"_id":"q-en-rust-09f9e4a42e7db7cf575819b9d58ba1d6c0c0184fe2c0c437956111630a63ff7f","text":"# \"-C\", \"linker=arm-none-eabi-gcc\", # \"-C\", \"link-arg=-Wl,-Tlink.x\", # \"-C\", \"link-arg=-nostartfiles\", ] No newline at end of file ] "} {"_id":"q-en-rust-0a0339ede579f438e494a3cdc3bdcdbf7b31b042738fa735f00456c2b67efd76","text":"if x == 0.0 { 0 } else { 1 } } pub fn bitwise_not() -> i32 { // CHECK-LABEL: fn bitwise_not( // CHECK: switchInt( // Test for #131195, which was optimizing `!a == b` into `a != b`. let mut a: i32 = 0; a = 1; if !a == 0 { 1 } else { 0 } } fn main() { // CHECK-LABEL: fn main( too_complex(Ok(0));"} {"_id":"q-en-rust-0a04a6d8847f98798798cac94cbcce5cf0133f0d4da0ff6d001e9dda2500321b","text":"None, ); if let Some(infer::RelateParamBound(_, t, _)) = origin { let return_impl_trait = self.tcx.return_type_impl_trait(generic_param_scope).is_some(); let t = self.resolve_vars_if_possible(t); match t.kind() { // We've got: // fn get_later(g: G, dest: &mut T) -> impl FnOnce() + '_ // suggest: // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a ty::Closure(..) | ty::Alias(ty::Opaque, ..) if return_impl_trait => { ty::Closure(..) | ty::Alias(ty::Opaque, ..) => { new_binding_suggestion(&mut err, type_param_span); } _ => {"} {"_id":"q-en-rust-0a1aad8bf59545719f4ad4b2d5a01a6f00bb8b7dd44bc0d6f6d2be29d8b340d2","text":" error[E0046]: not all trait items implemented, missing: `Error`, `try_from` --> $DIR/issue-74047.rs:14:1 | LL | impl TryFrom for MyStream {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `Error`, `try_from` in implementation | = help: implement the missing item: `type Error = Type;` = help: implement the missing item: `fn try_from(_: T) -> std::result::Result>::Error> { todo!() }` error: aborting due to previous error For more information about this error, try `rustc --explain E0046`. "} {"_id":"q-en-rust-0a305f49e6198873d7b4b5a37ec09c135def487effb2d32d6a883141077065f4","text":"// Since this is a return parameter type it is safe to unwrap. let ret_param_ty = projection.skip_binder().term.expect_type(); let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty); debug!(?ret_param_ty); let sig = projection.rebind(self.tcx.mk_fn_sig("} {"_id":"q-en-rust-0a39915611ce0eaa25c14cdcaf04bd28d86a85817a73a9f82980349ac8562fea","text":"gate_feature_post!(&self, generic_associated_types, ti.span, \"generic associated types are unstable\"); } if !ti.generics.where_clause.predicates.is_empty() { gate_feature_post!(&self, generic_associated_types, ti.span, \"where clauses on associated types are unstable\"); } } _ => {} }"} {"_id":"q-en-rust-0a42fbfcf273088b5b3bca040ab6abf6103d0ad787f48fbb06bdf103bf4511e5","text":"let path = match bounds.remove(0) { GenericBound::Trait(pt, ..) => pt.trait_ref.path, GenericBound::Outlives(..) => { self.span_bug(ty.span, \"unexpected lifetime bound\") return Err(self.struct_span_err( ty.span, \"expected trait bound, not lifetime bound\", )); } }; self.parse_remaining_bounds(Vec::new(), path, lo, true)"} {"_id":"q-en-rust-0a87375726d56308c07230dfa22ae60bc23227ec460cae0e89cac0b97f0115b0","text":"// memory, which makes for some *confusing* logs. That's why these are here // instead of in std. #![reexport_test_harness_main = \"test_main\"] #![feature(libc, std_misc, duration)] extern crate libc;"} {"_id":"q-en-rust-0a959bca1845d7e05a5ea534b93afe2c211c148015d1666622c93d14191f12fb","text":" trait PrivateTrait { const FOO: usize; } "} {"_id":"q-en-rust-0a99a285e7ac3914b3d61861da40db981efced525063cd82de948ceb5c475ce7","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":"q-en-rust-0ad2ca958ea02cb8324f39b400b1bf539789714897505cef01d2b5b934038f6f","text":"trait_def_id, ty, params, param_env ); // Do not check on infer_types to avoid panic in evaluate_obligation. if ty.has_infer_types() { return false; } let ty = tcx.erase_regions(&ty); let trait_ref = ty::TraitRef { def_id: trait_def_id, substs: tcx.mk_substs_trait(ty, params) }; let obligation = Obligation {"} {"_id":"q-en-rust-0ad76837279b910364da2d274a98749053b53d028324051bca14bde6594b56a7","text":" //@ check-pass #![feature(adt_const_params)] // Regression test for #116308 pub trait Identity { type Identity; } impl Identity for T { type Identity = Self; } pub fn foo::Identity>() {} fn main() { foo::<12>(); } "} {"_id":"q-en-rust-0adbcbe5570ba41d3d20ae874fc1d1bc9e5aada7d3a9f37cce297a58860eaf51","text":"name: FieldName) { let fields = ty::lookup_struct_fields(self.tcx, id); let field = match name { NamedField(ident) => { debug!(\"privacy - check named field {} in struct {:?}\", ident.name, id); fields.iter().find(|f| f.name == ident.name).unwrap() NamedField(f_name) => { debug!(\"privacy - check named field {} in struct {:?}\", f_name, id); fields.iter().find(|f| f.name == f_name).unwrap() } UnnamedField(idx) => &fields[idx] };"} {"_id":"q-en-rust-0adcbda36b11b23dcc5509c9d18c22619dbfd81de0312dce779c2b29c176fbde","text":"// the specialized routine `ty::replace_late_regions()`. match *r { ty::ReEarlyBound(data) => { let r = self.substs.get(data.index as usize).map(|k| k.unpack()); match r { let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); match rk { Some(UnpackedKind::Lifetime(lt)) => { self.shift_region_through_binders(lt) } _ => { let span = self.span.unwrap_or(DUMMY_SP); span_bug!( span, let msg = format!( \"Region parameter out of range when substituting in region {} (root type={:?}) (index={})\", data.name, self.root_ty, data.index); self.tcx.sess.delay_span_bug(span, &msg); r } } }"} {"_id":"q-en-rust-0ae59ce3e95797bd0994d101280cbd5ad9486f25f25a8b6cf4a006f3cc397b4d","text":"def gh_url(): # type: () -> str return os.environ['TOOLSTATE_ISSUES_API_URL'] def maybe_delink(message): # type: (str) -> str if os.environ.get('TOOLSTATE_SKIP_MENTIONS') is not None: return message.replace(\"@\", \"\") return message"} {"_id":"q-en-rust-0b18eff1abf7aad5da2f79f157d5a7f2c4b0958b7f64e1f1ea8e21fb66d3e3ce","text":"//~ TRANS_ITEM fn instantiation_through_vtable::{{impl}}[0]::bar[0] let _ = &s1 as &Trait; } //~ TRANS_ITEM drop-glue i8 "} {"_id":"q-en-rust-0b30049fcb8c3fd3f9886c90599cb62c0416bcfd6019b3178ecfc308d0da5868","text":".and_then(|ur_vid| self.definitions[*ur_vid].external_name) .unwrap_or(infcx.tcx.lifetimes.re_root_empty), ty::ReLateBound(..) => region, ty::ReStatic => region, _ => { infcx.tcx.sess.delay_span_bug( span,"} {"_id":"q-en-rust-0b37dc7a4dfe7d31a761b6afa0d2b220975f98318032609c82554285d0397d24","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":"q-en-rust-0b4526199c7a5ad2011c8b43433ea14b50d92e0e461fb8e55846c0d298716f6f","text":" error: arbitrary expressions aren't allowed in patterns --> $DIR/expr_before_ident_pat.rs:12:12 | LL | funny!(a, a); | ^ error[E0425]: cannot find value `a` in this scope --> $DIR/expr_before_ident_pat.rs:12:12 | LL | funny!(a, a); | ^ not found in this scope error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-0b5de7963f6f9795dcdacb065060c6ddf345e190c8e963dd20430700cb5d9c51","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":"q-en-rust-0b7035830b79c7ee16344ff28e032255ef63545396c3c79f59d8268dfbf41210","text":"where L: HasLocalDecls<'tcx>, { for (place_base, elem) in place.iter_projections().rev() { match elem { // encountered a Deref, which is ABI-aligned ProjectionElem::Deref => break, ProjectionElem::Field(..) => { let ty = place_base.ty(local_decls, tcx).ty; match ty.kind() { ty::Adt(def, _) => return def.repr().pack, _ => {} } } _ => {} } } None place .iter_projections() .rev() // Stop at `Deref`; standard ABI alignment applies there. .take_while(|(_base, elem)| !matches!(elem, ProjectionElem::Deref)) // Consider the packed alignments at play here... .filter_map(|(base, _elem)| { base.ty(local_decls, tcx).ty.ty_adt_def().and_then(|adt| adt.repr().pack) }) // ... and compute their minimum. // The overall smallest alignment is what matters. .min() }"} {"_id":"q-en-rust-0b9f32b924d86e44c3c535cd7de6a972c4ad5f11f5d77d8a273356f2eda9298d","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":"q-en-rust-0b9fed5f5bdff3a77caf196c401db25574a1e2dd1da23a6075d07b379f33f0a7","text":"// See the discussion in the stream implementation for why we we // might decrement steals. Some(data) => { self.steals += 1; if self.steals > MAX_STEALS { match self.cnt.swap(0, atomics::SeqCst) { DISCONNECTED => {"} {"_id":"q-en-rust-0baea70f537e736d9a159d441d69d2c019f997d1387bb513dbcf3ea344772d80","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. // Tests that the trait matching code takes lifetime parameters into account. // (Issue #15517.) struct Foo<'a,'b> { x: &'a int, y: &'b int, } trait Tr { fn foo(x: Self) {} } impl<'a,'b> Tr for Foo<'a,'b> { fn foo(x: Foo<'b,'a>) { //~^ ERROR method not compatible with trait //~^^ ERROR method not compatible with trait } } fn main(){} "} {"_id":"q-en-rust-0bb90625a38a31024c99368d3a71fbeb3b4c6fdbb8294e9be1bf95436ec54578","text":"use super::{check_fn, Expectation, FnCtxt, GeneratorTypes}; use crate::astconv::AstConv; use crate::middle::region; use crate::middle::{lang_items, region}; use rustc::hir::def_id::DefId; use rustc::infer::{InferOk, InferResult}; use rustc::infer::LateBoundRegionConversionTime;"} {"_id":"q-en-rust-0bd8ce42440598d120be07a10d03f7cf4c6ff6d04d81adf92678902fc71e6f4a","text":" error: the `wait` method cannot be invoked on a trait object --> $DIR/issue-35976.rs:14:9 | LL | fn wait(&self) where Self: Sized; | ----- this has a `Sized` requirement ... LL | arg.wait(); | ^^^^ error: aborting due to previous error "} {"_id":"q-en-rust-0be7240ef85bc21347d918bc5d890d696866e23a0db884eb854b166a26b2507e","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":"q-en-rust-0bfd7b1c2c7f0d337ecb37a4a51ea93ff9e4fb51be1eb9fd49df6d14846bd79f","text":" // Verify that move before the call of the function with noalias, nocapture, readonly. // #107436 // compile-flags: -O // min-llvm-version: 17 #![crate_type = \"lib\"] #[repr(C)] pub struct ThreeSlices<'a>(&'a [u32], &'a [u32], &'a [u32]); #[no_mangle] pub fn sum_slices(val: ThreeSlices) -> u32 { // CHECK-NOT: memcpy let val = val; sum(&val) } #[no_mangle] #[inline(never)] pub fn sum(val: &ThreeSlices) -> u32 { val.0.iter().sum::() + val.1.iter().sum::() + val.2.iter().sum::() } "} {"_id":"q-en-rust-0c0bbd4802e90778deb3f7a2ae0748b03cabf7c3f79c03a2059471c9e7df1316","text":"/// # Examples /// /// ``` /// #![feature(osstring_ascii)] /// use std::ffi::OsString; /// let s = OsString::from(\"Grüße, Jürgen ❤\"); /// /// assert_eq!(\"GRüßE, JüRGEN ❤\", s.to_ascii_uppercase()); /// ``` #[unstable(feature = \"osstring_ascii\", issue = \"70516\")] #[stable(feature = \"osstring_ascii\", since = \"1.53.0\")] pub fn to_ascii_uppercase(&self) -> OsString { OsString::from_inner(self.inner.to_ascii_uppercase()) }"} {"_id":"q-en-rust-0c7f100b8f51c71a7933c1fb2d84479396640e6ad478b062ca60aa97bde2ba21","text":"} hir::ImplItemKind::Type(_) => false, }, Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => true, _ => false, } }"} {"_id":"q-en-rust-0c9efa495375a0ce509c0f384c312b40f942e33abc741c1ad5872e4ad146b6ee","text":" // edition:2018 // compile-flags: -Cincremental=tmp/issue-72766 pub struct SadGirl; impl SadGirl { pub async fn call(&self) -> Result<(), ()> { Ok(()) } } async fn async_main() -> Result<(), ()> { // should be `.call().await?` SadGirl {}.call()?; //~ ERROR: the `?` operator can only be applied to values Ok(()) } fn main() { let _ = async_main(); } "} {"_id":"q-en-rust-0d108f447e41b8fa1263e6a0088949ff571e1d678861b66b16a30a4bda02fbb8","text":" error[E0603]: tuple struct constructor `A` is private --> $DIR/issue-111220-2-tuple-struct-fields-projection.rs:27:13 | LL | let Self(a) = self; | ^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0603`. "} {"_id":"q-en-rust-0d16cedddbfede40fe5bd738e16658839441e79139cd48967347cbd0d866d385","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":"q-en-rust-0d2558f6a742582c622a646607fbb198ef44d9a075f9f76b9ac44bbd9ac2621c","text":" #![feature(never_type)] #![deny(dead_code)] pub struct T1(!); pub struct T2(()); pub struct T3(std::marker::PhantomData); pub struct T4 { _x: !, } pub struct T5 { _x: !, _y: X, } pub struct T6 { _x: (), } pub struct T7 { _x: (), _y: X, } pub struct T8 { _x: std::marker::PhantomData, } pub struct T9 { //~ ERROR struct `T9` is never constructed _x: std::marker::PhantomData, _y: i32, } fn main() {} "} {"_id":"q-en-rust-0d38ea9d59ed0ef5ea3295ee0a41398b42700f38a395b1c1cde9c4850623b1de","text":"return krate; } krate.module.items.push(mk_decls(&mut cx, &derives, &attr_macros, &bang_macros)); krate.module.items.push(mk_decls(&mut cx, ¯os)); krate }"} {"_id":"q-en-rust-0d4c61627f6bfde14c54b621cfc3df58254fcc851c8841092b0b6f381c99da76","text":"attrs: Vec, } enum ProcMacroDefType { Attr, Bang } struct ProcMacroDef { function_name: Ident, span: Span, def_type: ProcMacroDefType } enum ProcMacro { Derive(ProcMacroDerive), Def(ProcMacroDef) } struct CollectProcMacros<'a> { derives: Vec, attr_macros: Vec, bang_macros: Vec, macros: Vec, in_root: bool, handler: &'a errors::Handler, is_proc_macro_crate: bool,"} {"_id":"q-en-rust-0d5295478d66627652e27ad2bd54971e8200ab298d3add750ec64a2fc9a99c7f","text":"let ecfg = ExpansionConfig::default(\"proc_macro\".to_string()); let mut cx = ExtCtxt::new(sess, ecfg, resolver); let (derives, attr_macros, bang_macros) = { let mut collect = CollectProcMacros { derives: Vec::new(), attr_macros: Vec::new(), bang_macros: Vec::new(), in_root: true, handler, is_proc_macro_crate, is_test_crate, }; if has_proc_macro_decls || is_proc_macro_crate { visit::walk_crate(&mut collect, &krate); } (collect.derives, collect.attr_macros, collect.bang_macros) let mut collect = CollectProcMacros { macros: Vec::new(), in_root: true, handler, is_proc_macro_crate, is_test_crate, }; if has_proc_macro_decls || is_proc_macro_crate { visit::walk_crate(&mut collect, &krate); } // NOTE: If you change the order of macros in this vec // for any reason, you must also update 'raw_proc_macro' // in src/librustc_metadata/decoder.rs let macros = collect.macros; if !is_proc_macro_crate { return krate }"} {"_id":"q-en-rust-0d8693e8e038eeb70004646f58a2e08536fbe6f0cd24e101eb997b805e0f91d9","text":" // edition:2021 // run-rustfix #![allow(dead_code)] async fn a() {} async fn foo() -> Result<(), i32> { a().await //~ ERROR mismatched types } fn main() {} "} {"_id":"q-en-rust-0dae700fcba7a930df31007262ec5053b7590b74f0fa5036a08367e00e6739a6","text":"use prelude::v1::*; use io::prelude::*; use io::{self, BufReader, BufWriter, LineWriter, SeekFrom}; use sync::atomic::{AtomicUsize, Ordering}; use thread; use test; /// A dummy reader intended at testing short-reads propagation."} {"_id":"q-en-rust-0dc0b9aeb789411fd5e3c9b1639be146832bdb1b189efc1cd3c1ae4b94aa89fd","text":"// this function uses `unwrap` copiously, because an already validated constant must have valid // fields and can thus never fail outside of compiler bugs pub fn const_variant_index<'tcx>( pub(crate) fn const_variant_index<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, val: &'tcx ty::Const<'tcx>,"} {"_id":"q-en-rust-0dd6e3473b68eb5057457641d67e6b64a56592ace837ffcbaa3e9d11e6c68dc7","text":"/// [`NonNull::dangling()`]: ptr::NonNull::dangling #[inline] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] { debug_assert!(is_aligned_and_not_null(data), \"attempt to create unaligned or null slice\"); debug_assert!( mem::size_of::().saturating_mul(len) <= isize::MAX as usize, \"attempt to create slice covering at least half the address space\" ); #[rustc_const_unstable(feature = \"const_slice_from_raw_parts\", issue = \"67456\")] pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] { debug_check_data_len(data, len); // SAFETY: the caller must uphold the safety contract for `from_raw_parts`. unsafe { &*ptr::slice_from_raw_parts(data, len) } }"} {"_id":"q-en-rust-0dece596615980c9c0148572c0ef45e7f11274ead224a6983bcf078547afd7ff","text":".span_to_snippet(self.prev_span) .map(|s| s.ends_with(\")\") || s.ends_with(\"]\")) .unwrap_or(false); let right_brace_span = if has_close_delim { // it's safe to peel off one character only when it has the close delim self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)) } else { self.prev_span.shrink_to_hi() }; self.struct_span_err( let mut err = self.struct_span_err( self.prev_span, \"macros that expand to items must be delimited with braces or followed by a semicolon\", ) .multipart_suggestion( \"change the delimiters to curly braces\", vec![ (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), \"{\".to_string()), (right_brace_span, '}'.to_string()), ], Applicability::MaybeIncorrect, ) .span_suggestion( ); // To avoid ICE, we shouldn't emit actual suggestions when it hasn't closing delims if has_close_delim { err.multipart_suggestion( \"change the delimiters to curly braces\", vec![ (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), '{'.to_string()), (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()), ], Applicability::MaybeIncorrect, ); } else { err.span_suggestion( self.prev_span, \"change the delimiters to curly braces\", \" { /* items */ }\".to_string(), Applicability::HasPlaceholders, ); } err.span_suggestion( self.prev_span.shrink_to_hi(), \"add a semicolon\", ';'.to_string(),"} {"_id":"q-en-rust-0e133ec912fd41620cc6adaf8104b1cc7ea9a392f56b078710cbf8929b9f5cc3","text":"/// /// assert_eq!(n.leading_zeros(), 0); /// ``` #[doc = concat!(\"[`ilog2`]: \", stringify!($SelfT), \"::ilog2\")] #[stable(feature = \"rust1\", since = \"1.0.0\")] #[rustc_const_stable(feature = \"const_int_methods\", since = \"1.32.0\")] #[must_use = \"this returns the result of the operation, "} {"_id":"q-en-rust-0e2a6aad007d2be2ac3af74eb24eb99d7fdecaf052bb53a37d47831ef465cd5c","text":"// MIR-level lints. &check_packed_ref::CheckPackedRef, &check_const_item_mutation::CheckConstItemMutation, &function_item_references::FunctionItemReferences, // What we need to do constant evaluation. &simplify::SimplifyCfg::new(\"initial\"), &rustc_peek::SanityCheck,"} {"_id":"q-en-rust-0e5187b435a93a81d78a1b2e383fc74748a37bbc89414eb65ac2a54fc467dc53","text":"/// /// This should not be used to get the components of `parent` itself. /// Use [push_outlives_components] instead. pub(super) fn compute_components_recursive<'tcx>( pub(super) fn compute_alias_components_recursive<'tcx>( tcx: TyCtxt<'tcx>, alias_ty: Ty<'tcx>, out: &mut SmallVec<[Component<'tcx>; 4]>, visited: &mut SsoHashSet>, ) { let ty::Alias(kind, alias_ty) = alias_ty.kind() else { bug!() }; let opt_variances = if *kind == ty::Opaque { tcx.variances_of(alias_ty.def_id) } else { &[] }; for (index, child) in alias_ty.substs.iter().enumerate() { if opt_variances.get(index) == Some(&ty::Bivariant) { continue; } if !visited.insert(child) { continue; } match child.unpack() { GenericArgKind::Type(ty) => { compute_components(tcx, ty, out, visited); } GenericArgKind::Lifetime(lt) => { // Ignore late-bound regions. if !lt.is_late_bound() { out.push(Component::Region(lt)); } } GenericArgKind::Const(_) => { compute_components_recursive(tcx, child, out, visited); } } } } /// Collect [Component]s for *all* the substs of `parent`. /// /// This should not be used to get the components of `parent` itself. /// Use [push_outlives_components] instead. fn compute_components_recursive<'tcx>( tcx: TyCtxt<'tcx>, parent: GenericArg<'tcx>, out: &mut SmallVec<[Component<'tcx>; 4]>,"} {"_id":"q-en-rust-0e600443e70a42beee73cf0a11e477f65d2ab750306ffafc5c39885cb65ae30b","text":"use std::fmt::{Debug, Display}; #[marker] trait MyMarker {} #[marker] trait MyMarker {} impl MyMarker for T {} impl MyMarker for T {}"} {"_id":"q-en-rust-0ed1bfed21275c690a1f2eac35d87181609f604747160a1d4e5c0eaebb843c3d","text":" error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:28:20 | LL | if let [ref first, ref second, ..] = *s { | ---------- immutable borrow occurs here LL | if let [_, ref mut second2, ref mut third, ..] = *s { //~ERROR | ^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[first, second, second2, third]); | ------ borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:44:21 | LL | if let [.., ref fourth, ref third, _, ref first] = *s { | --------- immutable borrow occurs here LL | if let [.., ref mut third2, _, _] = *s { //~ERROR | ^^^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[first, third, third2, fourth]); | ----- borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:55:20 | LL | if let [.., _, ref from_end4, ref from_end3, _, ref from_end1] = *s { | ------------- immutable borrow occurs here ... LL | if let [_, ref mut from_begin1, ..] = *s { //~ERROR | ^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[from_begin1, from_end1, from_end3, from_end4]); | --------- borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:58:23 | LL | if let [.., _, ref from_end4, ref from_end3, _, ref from_end1] = *s { | ------------- immutable borrow occurs here ... LL | if let [_, _, ref mut from_begin2, ..] = *s { //~ERROR | ^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[from_begin2, from_end1, from_end3, from_end4]); | --------- borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:61:26 | LL | if let [.., _, ref from_end4, ref from_end3, _, ref from_end1] = *s { | ------------- immutable borrow occurs here ... LL | if let [_, _, _, ref mut from_begin3, ..] = *s { //~ERROR | ^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[from_begin3, from_end1, from_end3, from_end4]); | --------- borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:69:21 | LL | if let [ref from_begin0, ref from_begin1, _, ref from_begin3, _, ..] = *s { | --------------- immutable borrow occurs here ... LL | if let [.., ref mut from_end2, _] = *s { //~ERROR | ^^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[from_begin0, from_begin1, from_begin3, from_end2]); | ----------- borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:72:21 | LL | if let [ref from_begin0, ref from_begin1, _, ref from_begin3, _, ..] = *s { | --------------- immutable borrow occurs here ... LL | if let [.., ref mut from_end3, _, _] = *s { //~ERROR | ^^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[from_begin0, from_begin1, from_begin3, from_end3]); | ----------- borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:75:21 | LL | if let [ref from_begin0, ref from_begin1, _, ref from_begin3, _, ..] = *s { | --------------- immutable borrow occurs here ... LL | if let [.., ref mut from_end4, _, _, _] = *s { //~ERROR | ^^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[from_begin0, from_begin1, from_begin3, from_end4]); | ----------- borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:92:20 | LL | if let [ref first, ref second, ..] = *s { | ---------- immutable borrow occurs here LL | if let [_, ref mut tail..] = *s { //~ERROR | ^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[first, second]); | ------ borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:110:17 | LL | if let [.., ref second, ref first] = *s { | ---------- immutable borrow occurs here LL | if let [ref mut tail.., _] = *s { //~ERROR | ^^^^^^^^^^^^ mutable borrow occurs here LL | nop(&[first, second]); | ------ borrow later used here error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable --> $DIR/borrowck-slice-pattern-element-loan.rs:119:17 | LL | if let [_, _, _, ref s1..] = *s { | ------ immutable borrow occurs here LL | if let [ref mut s2.., _, _, _] = *s { //~ERROR | ^^^^^^^^^^ mutable borrow occurs here LL | nop_subslice(s1); | -- borrow later used here error: aborting due to 11 previous errors For more information about this error, try `rustc --explain E0502`. "} {"_id":"q-en-rust-0efd805496fc64855e98309807bd513bc80c8a990865136186c27195873badd7","text":"rm $(TMPDIR)/foo $(RUSTC) foo.rs --crate-type=bin -o $(TMPDIR)/foo rm $(TMPDIR)/foo mv $(TMPDIR)/bar.bc $(TMPDIR)/foo.bc $(RUSTC) foo.rs --emit=bc,link --crate-type=rlib cmp $(TMPDIR)/foo.bc $(TMPDIR)/bar.bc rm $(TMPDIR)/bar.bc rm $(TMPDIR)/foo.bc rm $(TMPDIR)/$(call RLIB_GLOB,bar)"} {"_id":"q-en-rust-0f0f819b852595a28e7121953324f88c1ddfa430fc10d4e7e656f605108789ce","text":"expr } pub fn peel_blocks(&self) -> &Self { let mut expr = self; while let ExprKind::Block(Block { expr: Some(inner), .. }, _) = &expr.kind { expr = inner; } expr } pub fn can_have_side_effects(&self) -> bool { match self.peel_drop_temps().kind { ExprKind::Path(_) | ExprKind::Lit(_) => false,"} {"_id":"q-en-rust-0f4071f78609c55ae53ef395d27dee827f7e64f1a22f4b6c29d39ddd910e54e6","text":" //! This test makes sure that with never show the inner fields in the //! aliased type view of type alias. //@ compile-flags: -Z unstable-options --document-private-items #![crate_name = \"foo\"] use std::collections::BTreeMap; // @has 'foo/type.FooBar.html' '//*[@class=\"rust item-decl\"]/code' 'struct FooBar { /* private fields */ }' pub type FooBar = BTreeMap; "} {"_id":"q-en-rust-0f4a231805cf0db7812dffd38e2ce889f1dec88f069e62df4785be427fa880f9","text":" pub fn tadam() {} pub struct MultiImplBlockStruct; impl MultiImplBlockStruct { pub fn first_fn() {} } impl MultiImplBlockStruct { pub fn second_fn(self) -> bool { true } } pub trait MultiImplBlockTrait { fn first_fn(); fn second_fn(self) -> u32; } impl MultiImplBlockTrait for MultiImplBlockStruct { fn first_fn() {} fn second_fn(self) -> u32 { 1 } } "} {"_id":"q-en-rust-0fa86f4e124645d8f0bad67f78ab56b97023f39735d8c895b6d054f6c3c14da9","text":"} }; let attrs = &item.attrs; let sp = span_of_attrs(attrs); let sp = span_of_attrs(attrs).unwrap_or(item.source.span()); let mut msg = format!(\"`{}` is \", path_str);"} {"_id":"q-en-rust-0fee38d8fec5076272f30e33d4ae7101c75f4cfa74fa7e44bbf3c8c70305e497","text":"/// The directories that have already been created in this doc run. Used to reduce the number /// of spurious `create_dir_all` calls. pub created_dirs: RefCell>, /// This flag indicates whether listings of modules (in the side bar and documentation itself) /// should be ordered alphabetically or in order of appearance (in the source code). pub sort_modules_alphabetically: bool, } impl SharedContext {"} {"_id":"q-en-rust-10072589dc44876c2810ecad0e934f281f7867c3665844febb0ce84c810a9e0b","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":"q-en-rust-101587f8d1335c70f89291f8e184b93aef046a0e2574f8aa09756febb0314987","text":"//! recording the output. use rustc_ast as ast; use rustc_ast::{token, walk_list}; use rustc_ast::walk_list; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::def::{DefKind as HirDefKind, Res};"} {"_id":"q-en-rust-1051437e744dd32fce340d2fd43f8e6877dc3045b13246785fe695674322df4c","text":"fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) { for (i, tt) in tts.into_trees().enumerate() { if i != 0 { if i != 0 && tt_prepend_space(&tt) { self.space(); } self.print_tt(tt, convert_dollar_crate);"} {"_id":"q-en-rust-1095c86314a09036287669a20080bc8a574823c01c9e364c4848fc94b1c106c7","text":"} #[derive(Diagnostic)] #[diag(ast_passes_const_and_async)] pub(crate) struct ConstAndAsync { #[diag(ast_passes_const_and_coroutine)] pub(crate) struct ConstAndCoroutine { #[primary_span] pub spans: Vec, #[label(ast_passes_const)] pub cspan: Span, #[label(ast_passes_async)] pub aspan: Span, pub const_span: Span, #[label(ast_passes_coroutine)] pub coroutine_span: Span, #[label] pub span: Span, pub coroutine_kind: &'static str, } #[derive(Diagnostic)]"} {"_id":"q-en-rust-109cd63e49baab94e8b2c9fe981ae9ba7ed52b4929161ca817bfd75b11ef70b5","text":"* `MIRI_LOCAL_CRATES` is set by `cargo-miri` to tell the Miri driver which crates should be given special treatment in diagnostics, in addition to the crate currently being compiled. * `MIRI_ORIG_RUSTDOC` is set and read by different phases of `cargo-miri` to remember the value of `RUSTDOC` from before it was overwritten. * `MIRI_VERBOSE` when set to any value tells the various `cargo-miri` phases to perform verbose logging. * `MIRI_HOST_SYSROOT` is set by bootstrap to tell `cargo-miri` which sysroot to use for *host*"} {"_id":"q-en-rust-10cb2834c62ba15fa1ffe3766402ebe566aad84fa249051c2dd33c5210bdb2ef","text":" error[E0659]: `bar` is ambiguous --> $DIR/issue-109153.rs:11:5 | LL | use bar::bar; | ^^^ ambiguous name | = note: ambiguous because of multiple glob imports of a name in the same module note: `bar` could refer to the module imported here --> $DIR/issue-109153.rs:1:5 | LL | use foo::*; | ^^^^^^ = help: consider adding an explicit import of `bar` to disambiguate note: `bar` could also refer to the module imported here --> $DIR/issue-109153.rs:12:5 | LL | use bar::*; | ^^^^^^ = help: consider adding an explicit import of `bar` to disambiguate error: aborting due to previous error For more information about this error, try `rustc --explain E0659`. "} {"_id":"q-en-rust-10cd505bbd34e15b46176070fb7822e9160507ad16d634e2aac3507bd304e93c","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":"q-en-rust-10d7e0837240bda3d20807c33814df3cccc3df8a227043b7264795a9c3037e44","text":"/// move in the future, and this method does not enable the pointee to move. \"Malicious\" /// implementations of `Ptr::DerefMut` are likewise ruled out by the contract of /// `Pin::new_unchecked`. #[unstable(feature = \"pin_deref_mut\", issue = \"86918\")] #[stable(feature = \"pin_deref_mut\", since = \"CURRENT_RUSTC_VERSION\")] #[must_use = \"`self` will be dropped if the result is not used\"] #[inline(always)] pub fn as_deref_mut(self: Pin<&mut Pin>) -> Pin<&mut Ptr::Target> {"} {"_id":"q-en-rust-10ddb0b15f96ab77603df73466f44e9257cae4726c9f3f8ce621f5c23cd4ab7f","text":"| LL | E::Empty3 => () | ^^^^^^^^^ not a unit struct, unit variant or constant | help: use the struct variant pattern syntax | LL | E::Empty3 {} => () | ++ error[E0533]: expected unit struct, unit variant or constant, found struct variant `XE::XEmpty3` --> $DIR/empty-struct-braces-pat-1.rs:31:9 | LL | XE::XEmpty3 => () | ^^^^^^^^^^^ not a unit struct, unit variant or constant | help: use the struct variant pattern syntax | LL | XE::XEmpty3 {} => () | ++ error: aborting due to 2 previous errors"} {"_id":"q-en-rust-1132f7b39cf331e374540d727135b21acd45e699e225e4413bff757f92f29bb9","text":"// Inline format with parent. let len_or_tag = len_or_tag | PARENT_MASK; let parent2 = parent.local_def_index.as_u32(); if ctxt2 == SyntaxContext::root().as_u32() && parent2 <= MAX_CTXT { if ctxt2 == SyntaxContext::root().as_u32() && parent2 <= MAX_CTXT && len_or_tag < LEN_TAG { debug_assert_ne!(len_or_tag, LEN_TAG); return Span { base_or_index: base, len_or_tag, ctxt_or_tag: parent2 as u16 }; } } else { // Inline format with ctxt. debug_assert_ne!(len_or_tag, LEN_TAG); return Span { base_or_index: base, len_or_tag: len as u16,"} {"_id":"q-en-rust-115bf578b0dd752af34ce5ebb7a7e3e2fe3a4207a17937cc772d68c25794a7b5","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":"q-en-rust-11819c7cd9b13f4e0939f95065b9a38dc1ab7174308a60d81bb9679feadd8486","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":"q-en-rust-1191f827ae511bac499e5198001b136ec4c3a24343e060c7ecccbc1bbb0daa1f","text":"| = note: see issue #65991 for more information = help: add `#![feature(trait_upcasting)]` to the crate attributes to enable = note: required when coercing `&dyn Bar` into `&dyn Foo` error: aborting due to previous error"} {"_id":"q-en-rust-11d16cb5b26c73a7cb68bb90c236eb9c67d2418b82af0de7f288aded42531209","text":") } /// Returns `true` if the token is the integer literal. pub fn is_integer_lit(&self) -> bool { matches!(self.kind, Literal(Lit { kind: LitKind::Integer, .. })) } /// Returns `true` if the token is a non-raw identifier for which `pred` holds. pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { match self.ident() {"} {"_id":"q-en-rust-11dc327423f27924868fed5398e3fce78c85f01a6fe8ad95819d35fa57fc40f8","text":"(`Foo`) of the impl. In this case, we can fix the error by moving the type parameter from the `impl` to the method `get`: ``` struct Foo;"} {"_id":"q-en-rust-11e229f11de0b29b05c341fe76c70a2e6ba9ae8d6301f3d40c6a6141f7d6b1a8","text":" #![feature(generic_const_exprs)] //~^ WARN the feature `generic_const_exprs` is incomplete struct DataWrapper<'static> { //~^ ERROR invalid lifetime parameter name: `'static` data: &'a [u8; Self::SIZE], //~^ ERROR use of undeclared lifetime name `'a` //~^^ ERROR lifetime may not live long enough } impl DataWrapper<'a> { //~^ ERROR undeclared lifetime const SIZE: usize = 14; } fn main(){} "} {"_id":"q-en-rust-1202aee5a65270368af1ddb5284fd7e53fce05bb22026db380aed0cff11f6624","text":"UserTypeProjections { contents: projs.collect() } } pub fn projections_and_spans(&self) -> impl Iterator { pub fn projections_and_spans(&self) -> impl Iterator + ExactSizeIterator { self.contents.iter() } pub fn projections(&self) -> impl Iterator { pub fn projections(&self) -> impl Iterator + ExactSizeIterator { self.contents.iter().map(|&(ref user_type, _span)| user_type) }"} {"_id":"q-en-rust-1214122dfbf0135bb51d66c7be70fd4c19f7c5798b4a2ad446e386619064d55c","text":"COPY host-x86_64/dist-x86_64-linux/build-gcc.sh /tmp/ RUN ./build-gcc.sh && apt-get remove -y gcc g++ # Debian 6 has Python 2.6 by default, but LLVM >= 12 needs Python 3 # Debian 6 has Python 2.6 by default, but LLVM needs 2.7+ COPY host-x86_64/dist-x86_64-linux/build-python.sh /tmp/ RUN ./build-python.sh # LLVM needs cmake 3.13.4 or higher # LLVM needs cmake 3.4.3 or higher, and is planning to raise to 3.13.4. COPY host-x86_64/dist-x86_64-linux/build-cmake.sh /tmp/ RUN ./build-cmake.sh"} {"_id":"q-en-rust-122f083b49e3062cdb3b44256dda1cbab2533d08c4133ebf144d388c7e382ecb","text":"hir::Path { segments: [segment], .. }, )) | hir::ExprKind::Path(QPath::TypeRelative(ty, segment)) => { let self_ty = self.astconv().ast_ty_to_ty(ty); if let Ok(pick) = self.probe_for_name( Mode::Path, Ident::new(capitalized_name, segment.ident.span), Some(expected_ty), IsSuggestion(true), self_ty, expr.hir_id, ProbeScope::TraitsInScope, ) { if let Some(self_ty) = self.typeck_results.borrow().node_type_opt(ty.hir_id) && let Ok(pick) = self.probe_for_name( Mode::Path, Ident::new(capitalized_name, segment.ident.span), Some(expected_ty), IsSuggestion(true), self_ty, expr.hir_id, ProbeScope::TraitsInScope, ) { (pick.item, segment) } else { return false;"} {"_id":"q-en-rust-12325e251e5b9427dcedb04cbb9ee757294485c326e7b62c5249224ae52dcf73","text":"prog = time(sess.time_passes(), \"running linker\", || { exec_linker(sess, &mut cmd, tmpdir) }); if !retry_on_segfault || i > 3 { break } let output = match prog { Ok(ref output) => output, Err(_) => break,"} {"_id":"q-en-rust-126549f1cbd060511e697bd54ddc6bf6c5befadd4750918cfad87c30d953a0a2","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":"q-en-rust-126a8538e7ce6582ae7507734f68ccaff72bee71ac8701fd04111f2a70ef26c4","text":"remove_dir_all_recursive(None, p) } } #[cfg(not(all(target_os = \"macos\", target_arch = \"x86_64\")))] pub fn remove_dir_all(p: &Path) -> io::Result<()> { remove_dir_all_modern(p) } #[cfg(all(target_os = \"macos\", target_arch = \"x86_64\"))] pub fn remove_dir_all(p: &Path) -> io::Result<()> { if macos_weak::has_openat() { // openat() is available with macOS 10.10+, just like unlinkat() and fdopendir() remove_dir_all_modern(p) } else { // fall back to classic implementation crate::sys_common::fs::remove_dir_all(p) } } }"} {"_id":"q-en-rust-1270aafa272eb93aceab26cbd0ba0cc14f1cbf6980560701cf1c359c824a93ae","text":"// see the extensive comment in projection_must_outlive let recursive_bound = { let mut components = smallvec![]; compute_components_recursive(self.tcx, alias_ty_as_ty.into(), &mut components, visited); compute_alias_components_recursive( self.tcx, alias_ty_as_ty.into(), &mut components, visited, ); self.bound_from_components(&components, visited) };"} {"_id":"q-en-rust-129f354fa1b915349c52db0ea7ca7b2ad8de93861926d673deba27cf3c52f1a4","text":" warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:40:18 | LL | Pointer::fmt(&zst_ref, f) | ^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` | note: the lint level is defined here --> $DIR/function-item-references.rs:3:9 | LL | #![warn(function_item_references)] | ^^^^^^^^^^^^^^^^^^^^^^^^ warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:77:22 | LL | println!(\"{:p}\", &foo); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:79:20 | LL | print!(\"{:p}\", &foo); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:81:21 | LL | format!(\"{:p}\", &foo); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:84:22 | LL | println!(\"{:p}\", &foo as *const _); | ^^^^^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:86:22 | LL | println!(\"{:p}\", zst_ref); | ^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:88:22 | LL | println!(\"{:p}\", cast_zst_ptr); | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:90:22 | LL | println!(\"{:p}\", coerced_zst_ptr); | ^^^^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:93:22 | LL | println!(\"{:p}\", &fn_item); | ^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:95:22 | LL | println!(\"{:p}\", indirect_ref); | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:98:22 | LL | println!(\"{:p}\", &nop); | ^^^^ help: cast `nop` to obtain a function pointer: `nop as fn()` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:100:22 | LL | println!(\"{:p}\", &bar); | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:102:22 | LL | println!(\"{:p}\", &baz); | ^^^^ help: cast `baz` to obtain a function pointer: `baz as fn(_, _) -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:104:22 | LL | println!(\"{:p}\", &unsafe_fn); | ^^^^^^^^^^ help: cast `unsafe_fn` to obtain a function pointer: `unsafe_fn as unsafe fn()` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:106:22 | LL | println!(\"{:p}\", &c_fn); | ^^^^^ help: cast `c_fn` to obtain a function pointer: `c_fn as extern \"C\" fn()` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:108:22 | LL | println!(\"{:p}\", &unsafe_c_fn); | ^^^^^^^^^^^^ help: cast `unsafe_c_fn` to obtain a function pointer: `unsafe_c_fn as unsafe extern \"C\" fn()` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:110:22 | LL | println!(\"{:p}\", &variadic); | ^^^^^^^^^ help: cast `variadic` to obtain a function pointer: `variadic as unsafe extern \"C\" fn(_, ...)` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:112:22 | LL | println!(\"{:p}\", &std::env::var::); | ^^^^^^^^^^^^^^^^^^^^^^^^ help: cast `var` to obtain a function pointer: `var as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:115:32 | LL | println!(\"{:p} {:p} {:p}\", &nop, &foo, &bar); | ^^^^ help: cast `nop` to obtain a function pointer: `nop as fn()` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:115:38 | LL | println!(\"{:p} {:p} {:p}\", &nop, &foo, &bar); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:115:44 | LL | println!(\"{:p} {:p} {:p}\", &nop, &foo, &bar); | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:130:41 | LL | std::mem::transmute::<_, usize>(&foo); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:132:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:132:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:142:15 | LL | print_ptr(&bar); | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:144:24 | LL | bound_by_ptr_trait(&bar); | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:146:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer --> $DIR/function-item-references.rs:146:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: 28 warnings emitted "} {"_id":"q-en-rust-130881512be78fbfdb35904344db199d1c898c3177f659f9216994f54244e14a","text":"if let Some(old_binding) = resolution.shadowed_glob { assert!(old_binding.is_glob_import()); if glob_binding.res() != old_binding.res() { resolution.shadowed_glob = Some(self.ambiguity( resolution.shadowed_glob = Some(this.ambiguity( AmbiguityKind::GlobVsGlob, old_binding, glob_binding, )); } else if !old_binding.vis.is_at_least(binding.vis, self.tcx) { } else if !old_binding.vis.is_at_least(binding.vis, this.tcx) { resolution.shadowed_glob = Some(glob_binding); } } else {"} {"_id":"q-en-rust-13089c8fde55403dfa71decd853b58bbf544dc3ed9d6b16d0337002f78b47c30","text":" // Checks that there is a suggestion for simple tuple index access expression (used where an // identifier is expected in a format arg) to use positional arg instead. // Issue: . //@ run-rustfix fn main() { let x = (1,); println!(\"{x.0}\"); //~^ ERROR invalid format string } "} {"_id":"q-en-rust-130aba35e9f43e7cf9d8243867f25d587fd5a97c482af0f44a09c082c9370f29","text":"| ^^^^^^^^ error[E0603]: enum `Bar` is private --> $DIR/struct-variant-privacy.rs:9:14 --> $DIR/struct-variant-privacy.rs:10:14 | LL | foo::Bar::Baz { a: _a } => {} | ^^^ private enum"} {"_id":"q-en-rust-13120390b0125ac8b08320af5e420e1ba98a9c9873b025efd24c6d95b3095f58","text":" // build-pass #![allow(incomplete_features)] #![feature(const_generics)] struct Bug; fn main() { let b: Bug::<{ unsafe { // FIXME(const_generics): Decide on how to deal with invalid values as const params. std::mem::transmute::<&[u8], &str>(&[0xC0, 0xC1, 0xF5]) } }>; } "} {"_id":"q-en-rust-13259a77584230a531ccb662521a45c890d0f09ac74a763e1c6a330cc920ed61","text":" error[E0658]: trait upcasting coercion is experimental error[E0658]: cannot cast `dyn Bar` to `dyn Foo`, trait upcasting coercion is experimental --> $DIR/feature-gate-trait_upcasting.rs:11:25 | LL | let foo: &dyn Foo = bar;"} {"_id":"q-en-rust-1337f0d630634208e5f78b375c3f1adb1b62941d84dd8c33d142fd71673de45d","text":"driver_rlink_rustc_version_mismatch = .rlink file was produced by rustc version `{$rustc_version}`, but the current version is `{$current_version}` driver_rlink_no_a_file = rlink must be a file driver_unpretty_dump_fail = pretty-print failed to write `{$path}` due to error `{$err}` "} {"_id":"q-en-rust-1342b69ca75cf0afb5359cebe4991d1f81343bf033ff677dbc4079e9f26b6974","text":"#![feature(const_slice_split_at_mut)] #![feature(const_str_from_utf8_unchecked_mut)] #![feature(const_swap)] #![feature(const_transmute_copy)] #![feature(const_try)] #![feature(const_type_id)] #![feature(const_type_name)]"} {"_id":"q-en-rust-13727101ec52d5b4dc61c2ebfc7f3275438210aa7c60261fece05ff68a24a1b4","text":"false } fn let_binding_suggestion(&self, err: &mut Diagnostic, ident_span: Span) -> bool { // try to give a suggestion for this pattern: `name = 1`, which is common in other languages let mut added_suggestion = false; if let Some(Expr { kind: ExprKind::Assign(lhs, _rhs, _), .. }) = self.diagnostic_metadata.in_assignment && // try to give a suggestion for this pattern: `name = blah`, which is common in other languages // suggest `let name = blah` to introduce a new binding fn let_binding_suggestion(&mut self, err: &mut Diagnostic, ident_span: Span) -> bool { if let Some(Expr { kind: ExprKind::Assign(lhs, .. ), .. }) = self.diagnostic_metadata.in_assignment && let ast::ExprKind::Path(None, _) = lhs.kind { let sm = self.r.session.source_map(); let line_span = sm.span_extend_to_line(ident_span); let ident_name = sm.span_to_snippet(ident_span).unwrap(); // HACK(chenyukang): make sure ident_name is at the starting of the line to protect against macros if sm .span_to_snippet(line_span) .map_or(false, |s| s.trim().starts_with(&ident_name)) { if !ident_span.from_expansion() { err.span_suggestion_verbose( ident_span.shrink_to_lo(), \"you might have meant to introduce a new binding\", \"let \".to_string(), Applicability::MaybeIncorrect, ); added_suggestion = true; return true; } } added_suggestion false } fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> {"} {"_id":"q-en-rust-13a90331805ac48f0c84fe40d0b6298b7c7be696139e9aaad08c990bed73e26b","text":"pub fn cargo_clippy_cmd(&self, run_compiler: Compiler) -> BootstrapCommand { if run_compiler.stage == 0 { // `ensure(Clippy { stage: 0 })` *builds* clippy with stage0, it doesn't use the beta clippy. let cargo_clippy = self.build.config.download_clippy(); let cargo_clippy = self .config .initial_cargo_clippy .clone() .unwrap_or_else(|| self.build.config.download_clippy()); let mut cmd = command(cargo_clippy); cmd.env(\"CARGO\", &self.initial_cargo); return cmd;"} {"_id":"q-en-rust-13e033fa31948b11eaed85c34463fd714296cd85c1d2ea246664548c38645db5","text":" error: `_x @` is not allowed in a tuple struct --> $DIR/issue-72574-2.rs:6:20 | LL | Binder(_a, _x @ ..) => {} | ^^^^^^^ this is only allowed in slice patterns | = help: remove this and bind each tuple field independently help: if you don't need to use the contents of _x, discard the tuple's remaining fields | LL | Binder(_a, ..) => {} | ^^ error: aborting due to previous error "} {"_id":"q-en-rust-13f8b7a538626f64186f360f7ed5027ef4e6729e422fab718d224d00c82997b2","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:panic evaluated #[allow(unused_variables)] fn main() { let x = [panic!(\"panic evaluated\"); 0]; } "} {"_id":"q-en-rust-13fd00c99995f99bf295a50fa7739388c0ccb0553c5865d882d24039e3ce53ae","text":"#[proc_macro_attribute] pub fn expect_print_expr(attr: TokenStream, item: TokenStream) -> TokenStream { assert!(attr.to_string().is_empty()); assert_eq!(item.to_string(), \"println!(\"{}\" , string)\"); assert_eq!(item.to_string(), \"println!(\"{}\", string)\"); item }"} {"_id":"q-en-rust-145fc9dae61fc0ea27c2555c6e5a88444324c5e445745a9a2caf6cf7cae6bd95","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":"q-en-rust-148bc2f2882caf37f729399b924df4f53999bd8b648f277d9f11fd9fbaf9106d","text":"} #[stable(feature = \"rust1\", since = \"1.0.0\")] impl Clone for CString { fn clone(&self) -> Self { CString { inner: self.inner.to_owned().into_boxed_slice() } } } #[stable(feature = \"rust1\", since = \"1.0.0\")] impl Deref for CString { type Target = CStr;"} {"_id":"q-en-rust-14926bee1461a8d9cad0cca749413ded89d806aaed757cb42e406640352691c4","text":" error[E0277]: the size for values of type `[u8]` cannot be known at compilation time --> $DIR/suggest-borrow.rs:2:9 | LL | let x: [u8] = vec!(1, 2, 3)[..]; | ^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `[u8]` = note: all local variables must have a statically known size = help: unsized locals are gated as an unstable feature help: consider borrowing here | LL | let x: &[u8] = vec!(1, 2, 3)[..]; | + error[E0308]: mismatched types --> $DIR/suggest-borrow.rs:3:20 | LL | let x: &[u8] = vec!(1, 2, 3)[..]; | ----- ^^^^^^^^^^^^^^^^^ | | | | | expected `&[u8]`, found slice `[{integer}]` | | help: consider borrowing here: `&vec!(1, 2, 3)[..]` | expected due to this error[E0308]: mismatched types --> $DIR/suggest-borrow.rs:4:19 | LL | let x: [u8] = &vec!(1, 2, 3)[..]; | ---- ^^^^^^^^^^^^^^^^^^ expected slice `[u8]`, found `&[{integer}]` | | | expected due to this | help: consider removing the borrow | LL - let x: [u8] = &vec!(1, 2, 3)[..]; LL + let x: [u8] = vec!(1, 2, 3)[..]; | help: alternatively, consider changing the type annotation | LL | let x: &[u8] = &vec!(1, 2, 3)[..]; | + error[E0277]: the size for values of type `[u8]` cannot be known at compilation time --> $DIR/suggest-borrow.rs:4:9 | LL | let x: [u8] = &vec!(1, 2, 3)[..]; | ^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `[u8]` = note: all local variables must have a statically known size = help: unsized locals are gated as an unstable feature help: consider borrowing here | LL | let x: &[u8] = &vec!(1, 2, 3)[..]; | + 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":"q-en-rust-14b39f9a843e2b57cdaba99d219efeecf096ccb84597797e012f55f4b45d1084","text":"#![crate_name = \"compiletest\"] #![feature(test)] #![feature(vec_remove_item)] #![deny(warnings)] extern crate test;"} {"_id":"q-en-rust-14bf4e6bd3759b03214da3442840104fb6f8336f0fb47a52cc4674f4b2af90dd","text":" fn main() { x = x = x; //~^ ERROR cannot find value `x` in this scope //~| ERROR cannot find value `x` in this scope //~| ERROR cannot find value `x` in this scope x = y = y = y; //~^ ERROR cannot find value `y` in this scope //~| ERROR cannot find value `y` in this scope //~| ERROR cannot find value `y` in this scope //~| ERROR cannot find value `x` in this scope x = y = y; //~^ ERROR cannot find value `x` in this scope //~| ERROR cannot find value `y` in this scope //~| ERROR cannot find value `y` in this scope x = x = y; //~^ ERROR cannot find value `x` in this scope //~| ERROR cannot find value `x` in this scope //~| ERROR cannot find value `y` in this scope x = x; // will suggest add `let` //~^ ERROR cannot find value `x` in this scope //~| ERROR cannot find value `x` in this scope x = y // will suggest add `let` //~^ ERROR cannot find value `x` in this scope //~| ERROR cannot find value `y` in this scope } "} {"_id":"q-en-rust-14e9abb7630588108ff9a06349627f082d7d64b1ef724189684b9972b9a7c716","text":" // Checks that we do not ICE when comparing `Self` to `Pin` // edition:2021 struct S; impl S { fn foo(_: Box>) {} fn bar() { Self::foo(None) //~ ERROR mismatched types } } fn main() {} "} {"_id":"q-en-rust-1523df9b490d94ce239170de766577d2ea3f370d75bd74bc322aec4a976bc55a","text":"match x { box 1 => (), //~^ box pattern syntax is experimental //~| add #![feature(box_patterns)] to the crate attributes to enable _ => () }; }"} {"_id":"q-en-rust-1529446971f67746d8613e7872940e69cbcc4eb7e4009731c513e5acc528fa42","text":"(src, src_name) } fn write_or_print(out: &str, ofile: Option<&Path>) { fn write_or_print(out: &str, ofile: Option<&Path>, sess: &Session) { match ofile { None => print!(\"{}\", out), Some(p) => { if let Err(e) = std::fs::write(p, out) { panic!(\"print-print failed to write {} due to {}\", p.display(), e); sess.emit_fatal(UnprettyDumpFail { path: p.display().to_string(), err: e.to_string(), }); } } }"} {"_id":"q-en-rust-15374e0ce221a97a0889b6a8a1ef25ec16880aced7081aeb826876c71efdbf23","text":"//! Free functions to create `&[T]` and `&mut [T]`. use crate::array; use crate::intrinsics::is_aligned_and_not_null; use crate::mem; use crate::ptr; /// Forms a slice from a pointer and a length."} {"_id":"q-en-rust-15a8f47c5de7c2d1490d3348958261f2bb14bf0f159872105fa41de2492dfb82","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. // This used to generate invalid IR in that even if we took the // `false` branch we'd still try to free the Box from the other // arm. This was due to treating `*Box::new(9)` as an rvalue datum // instead of as an lvalue. fn test(foo: bool) -> u8 { match foo { true => *Box::new(9), false => 0 } } fn main() { assert_eq!(9, test(true)); } "} {"_id":"q-en-rust-160f5b1a364da68615ff4a162ff0bd1120281485c54f2a96fd9a12dcebe6cd4f","text":"ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called }, ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType, ast::AssocItemKind::Delegation(..) if self.r.delegation_fn_sigs[&self.r.local_def_id(assoc_item.id)] .has_self => if self .r .delegation_fn_sigs .get(&self.r.local_def_id(assoc_item.id)) .map_or(false, |sig| sig.has_self) => { AssocSuggestion::MethodWithSelf { called } }"} {"_id":"q-en-rust-1678d3b7f120953fd4135246d2c4cc0b6ba980e6ceca37e8948c576dda0ce7cd","text":"} } crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { use rustc_hir::*; debug!(\"trying to get a name from pattern: {:?}\", p); Symbol::intern(&match p.kind { PatKind::Wild => return kw::Underscore, PatKind::Binding(_, _, ident, _) => return ident.name, PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p), PatKind::Struct(ref name, ref fields, etc) => format!( \"{} {{ {}{} }}\", qpath_to_string(name), fields .iter() .map(|fp| format!(\"{}: {}\", fp.ident, name_from_pat(&fp.pat))) .collect::>() .join(\", \"), if etc { \", ..\" } else { \"\" } ), PatKind::Or(ref pats) => pats .iter() .map(|p| name_from_pat(&**p).to_string()) .collect::>() .join(\" | \"), PatKind::Tuple(ref elts, _) => format!( \"({})\", elts.iter() .map(|p| name_from_pat(&**p).to_string()) .collect::>() .join(\", \") ), PatKind::Box(ref p) => return name_from_pat(&**p), PatKind::Ref(ref p, _) => return name_from_pat(&**p), PatKind::Lit(..) => { warn!( \"tried to get argument name from PatKind::Lit, which is silly in function arguments\" ); return Symbol::intern(\"()\"); } PatKind::Range(..) => return kw::Underscore, PatKind::Slice(ref begin, ref mid, ref end) => { let begin = begin.iter().map(|p| name_from_pat(&**p).to_string()); let mid = mid.as_ref().map(|p| format!(\"..{}\", name_from_pat(&**p))).into_iter(); let end = end.iter().map(|p| name_from_pat(&**p).to_string()); format!(\"[{}]\", begin.chain(mid).chain(end).collect::>().join(\", \")) } }) } crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String { match n.val { ty::ConstKind::Unevaluated(def, _, promoted) => {"} {"_id":"q-en-rust-16895289024cf200a6bd329e7278f7caebb7311fbf1b3eac9851c36fd1e38962","text":"} fn check_version(config: &Config) -> Option { const VERSION: usize = 2; let mut msg = String::new(); let suggestion = if let Some(seen) = config.changelog_seen {"} {"_id":"q-en-rust-169b12c6346f6355d0f653598d0b6e1cc3dab5e081c2972176ca44273d7cb2c5","text":"fn read(&mut self, buf: &mut [u8]) -> io::Result { (**self).read(buf) } fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> { (**self).read_buf(cursor) } } impl AsInner for FileDesc {"} {"_id":"q-en-rust-16a8387fc17dd9645b04922671475393e2dcdb218bf0a1effc9d973405ef6765","text":"use rustc_ast::ast::*; use rustc_ast::ptr::P; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_span::symbol::Ident;"} {"_id":"q-en-rust-16b2fd02788800567abf08d4bdc7e7701673b2474718da6de482e2967fbd5a1e","text":"use rustc::hir::def::Namespace::*; use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId}; use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap}; use rustc::ty; use rustc::ty::{self, DefIdTree}; use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap}; use rustc::{bug, span_bug};"} {"_id":"q-en-rust-171d98dbe51daec91807434732d1b5b140d74136e8d6c1d493e0ae5b6924726f","text":" // crate foo #![feature(type_alias_impl_trait)] type Tait = impl Sized; fn _constrain() -> Tait {} struct WrapperWithDrop(T); impl Drop for WrapperWithDrop { fn drop(&mut self) {} } pub struct Foo(WrapperWithDrop); trait Id { type Id: ?Sized; } impl Id for T { type Id = T; } pub struct Bar(WrapperWithDrop<::Id>); "} {"_id":"q-en-rust-171f1bafcd5632b45f992c8400344934181b61f0ceb93760bdc338bff4425ac4","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":"q-en-rust-1737695cb355f837d57c8a9ee73c5ab0e172419c0c8b7f9c658b28a17febd2ab","text":"/// the two vectors, `regions` and `types` (depending on their kind). For each /// parameter `Pi` also track the index `i`. struct GATSubstCollector<'tcx> { tcx: TyCtxt<'tcx>, gat: DefId, // Which region appears and which parameter index its subsituted for regions: FxHashSet<(ty::Region<'tcx>, usize)>,"} {"_id":"q-en-rust-175ab9667669e521c781778f53ec490502742ec7ec0690f028fd0253a7b01f21","text":"impl PartialOrd for bool { #[inline] fn partial_cmp(&self, other: &bool) -> Option { (*self as u8).partial_cmp(&(*other as u8)) Some(self.cmp(other)) } }"} {"_id":"q-en-rust-176784669dcc015189e9d59dcf0f326282c7c2294fe3db1e8838afb9871c7cb4","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. struct S; impl Iterator for S { type Item = i32; fn next(&mut self) -> Result { Ok(7) } //~^ ERROR method `next` has an incompatible type for trait //~| expected enum `core::option::Option` //~| found enum `core::result::Result` [E0053] } fn main() {} "} {"_id":"q-en-rust-177711e14a36cccd23c339318848e6f10106200030824b1d8d4f46487ad1c022","text":"margin-bottom: .625em; } p { p, .docblock > .warning { /* Paragraph spacing at least 1.5 times line spacing per Web Content Accessibility Guidelines. Line-height is 1.5rem, so line spacing is .5rem; .75em is 1.5 times that. https://www.w3.org/WAI/WCAG21/Understanding/visual-presentation.html */"} {"_id":"q-en-rust-178cdf3d0a39dea86e4f854ec7f50f7f25825954ef27c91d927d93cade7a9a38","text":"if bcx.expr_is_lval(a) { let datum = unpack_datum!(bcx, trans_to_datum(bcx, a)); return match dest { Ignore => datum.drop_val(bcx), Ignore => drop_and_cancel_clean(datum, bcx), SaveIn(addr) => datum.move_to(bcx, INIT, addr) }; } else {"} {"_id":"q-en-rust-17b68b97071755daf493bd70ee247ff7b05629d9f8d29f77430dfbb7bdc1ea39","text":" //! To determine all the types that need to be private when looking at `Struct`, we //! used to invoke `predicates_of` to also look at types in `where` bounds. //! Unfortunately this also computes the inferred outlives bounds, which means for //! every field we check that if it is of type `&'a T` then `T: 'a` and if it is of //! struct type, we check that the struct satisfies its lifetime parameters by looking //! at its inferred outlives bounds. This means we end up with a `::Assoc: 'a` //! in the outlives bounds of `Struct`. While this is trivially provable, privacy //! only sees `Foo` and `Trait` and determines that `Foo` is private and then errors. //! So now we invoke `explicit_predicates_of` to make sure we only care about user-written //! predicates. //@ check-pass mod baz { struct Foo; pub trait Trait { type Assoc; } impl Trait for Foo { type Assoc = (); } pub struct Bar<'a, T: Trait> { source: &'a T::Assoc, } pub struct Baz<'a> { mode: Bar<'a, Foo>, } } pub struct Struct<'a> { lexer: baz::Baz<'a>, } fn main() {} "} {"_id":"q-en-rust-1807955f33e289ce51071900b664294b03805e2eb4bddd9d13beca5f7d5f6f69","text":"Path { global: path.global, res: path.res, segments } } crate fn qpath_to_string(p: &hir::QPath<'_>) -> String { let segments = match *p { hir::QPath::Resolved(_, ref path) => &path.segments, hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(), hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(), }; let mut s = String::new(); for (i, seg) in segments.iter().enumerate() { if i > 0 { s.push_str(\"::\"); } if seg.ident.name != kw::PathRoot { s.push_str(&seg.ident.as_str()); } } s } crate fn build_deref_target_impls(cx: &DocContext<'_>, items: &[Item], ret: &mut Vec) { let tcx = cx.tcx;"} {"_id":"q-en-rust-18448998884e66dd634c9295e4f057c3e9ff4d641a64eaacad9cd7660689abe4","text":" // run-pass #![feature(unsized_locals)] #![allow(dead_code)] #[repr(align(256))] struct A { v: u8, } impl A { fn f(&self) -> *const A { self } } fn f2(v: u8) -> Box *const A> { let a = A { v }; Box::new(move || a.f()) } fn main() { let addr = f2(0)(); assert_eq!(addr as usize % 256, 0, \"addr: {:?}\", addr); } "} {"_id":"q-en-rust-184c743ca443eb50ae630eb5e339412a51d02c3272429f87ea95039ba04885a8","text":"/// ``` /// /// ``` /// #![feature(maybe_uninit_write_slice, vec_spare_capacity)] /// #![feature(maybe_uninit_write_slice)] /// use std::mem::MaybeUninit; /// /// let mut vec = Vec::with_capacity(32);"} {"_id":"q-en-rust-185d63b124b5bd284a8f3b5d67352ed202210ca6d4aee8f3564ce261d36665f0","text":".find(|p| link.starts_with(**p)) { kind = Some(ValueNS); disambiguator = Some(&prefix[..prefix.len() - 1]); link.trim_start_matches(prefix) } else if link.ends_with(\"()\") { kind = Some(ValueNS); disambiguator = Some(\"fn\"); link.trim_end_matches(\"()\") } else if link.starts_with(\"macro@\") { kind = Some(MacroNS); disambiguator = Some(\"macro\"); link.trim_start_matches(\"macro@\") } else if link.starts_with(\"derive@\") { kind = Some(MacroNS); disambiguator = Some(\"derive\"); link.trim_start_matches(\"derive@\") } else if link.ends_with('!') { kind = Some(MacroNS); disambiguator = Some(\"macro\"); link.trim_end_matches('!') } else { &link[..]"} {"_id":"q-en-rust-188e62922a625c6258679a3e0f95157e8123b55fc1fe0fd3340fe2d85fd6917b","text":"use crate::any::Any; use crate::fmt; use crate::marker::PhantomData; use crate::panic::AssertUnwindSafe; use crate::ptr; /// A `RawWaker` allows the implementor of a task executor to create a [`Waker`]"} {"_id":"q-en-rust-18a10e2690ea20c984a5c040390546128a941c0cd555bfc3af381ebcf3c085b0","text":"a: ty::Region<'tcx>, b: ty::Region<'tcx>, ) { if let ty::ReEmpty = a { return; } let b = self.to_region_vid(b); let a = self.to_region_vid(a); self.add_outlives(b, a);"} {"_id":"q-en-rust-18bffb2f0090c00ea668abb5e28170caabf132878f0b4d7b4e2f6a2d96544578","text":"(cfg, _) => cfg.as_deref().cloned(), }; debug!(\"Portability {:?} - {:?} = {:?}\", item.cfg, parent.and_then(|p| p.cfg.as_ref()), cfg); debug!( \"Portability {:?} {:?} (parent: {:?}) - {:?} = {:?}\", item.name, item.cfg, parent, parent.and_then(|p| p.cfg.as_ref()), cfg ); Some(format!(\"
{}
\", cfg?.render_long_html())) }"} {"_id":"q-en-rust-18e7cacd79603a111e43caea030fd54025b4c7d0c5a243cc9bf11ca8fd7ad7df","text":"msg: &str) -> DiagnosticBuilder<'a> { let (level, src) = self.sets.get_lint_level(lint, self.cur); let (level, src) = self.sets.get_lint_level(lint, self.cur, None); lint::struct_lint_level(self.sess, lint, level, src, span, msg) }"} {"_id":"q-en-rust-193306c9ed199ddab6c1f815741381290512a420dbe014ea1b5140bdc9eb786c","text":" // assembly-output: emit-asm // # zen3 previously exhibited odd vectorization // compile-flags: --crate-type=lib -Ctarget-cpu=znver3 -O // only-x86_64 // ignore-sgx use std::iter; // previously this produced a long chain of // 56: vpextrb $6, %xmm0, %ecx // 57: orb %cl, 22(%rsi) // 58: vpextrb $7, %xmm0, %ecx // 59: orb %cl, 23(%rsi) // [...] // CHECK-LABEL: zip_arrays: #[no_mangle] pub fn zip_arrays(mut a: [u8; 32], b: [u8; 32]) -> [u8; 32] { // CHECK-NOT: vpextrb // CHECK-NOT: orb %cl // CHECK: vorps iter::zip(&mut a, b).for_each(|(a, b)| *a |= b); // CHECK: retq a } "} {"_id":"q-en-rust-195b524e255a3c29b6a82717d9486970a337b7923608bed24ec2cb0f2ee3b6e6","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":"q-en-rust-195e07695956847e9288be9727f35c1294be13d58692b218b091bbc1642c9ad7","text":" error: lifetime may not live long enough --> $DIR/issue-16922.rs:4:5 | LL | fn foo(value: &T) -> Box { | - let's call the lifetime of this reference `'1` LL | Box::new(value) as Box | ^^^^^^^^^^^^^^^ cast requires that `'1` must outlive `'static` | help: to declare that the trait object captures data from argument `value`, you can add an explicit `'_` lifetime bound | LL | fn foo(value: &T) -> Box { | ++++ error: aborting due to previous error "} {"_id":"q-en-rust-19b4cd0b2284614ff5f908e4db0ee827ca02d9256c02a9ca68f4fbd0dcbe1edd","text":"run_pass_manager(cgcx, tm, llmod, config, true); cgcx.save_temp_bitcode(&mtrans, \"thin-lto-after-pm\"); timeline.record(\"thin-done\"); // FIXME: this is a hack around a bug in LLVM right now. Discovered in // #46910 it was found out that on 32-bit MSVC LLVM will hit a codegen // error if there's an available_externally function in the LLVM module. // Typically we don't actually use these functions but ThinLTO makes // heavy use of them when inlining across modules. // // Tracked upstream at https://bugs.llvm.org/show_bug.cgi?id=35736 this // function call (and its definition on the C++ side of things) // shouldn't be necessary eventually and we can safetly delete these few // lines. llvm::LLVMRustThinLTORemoveAvailableExternally(llmod); cgcx.save_temp_bitcode(&mtrans, \"thin-lto-after-rm-ae\"); timeline.record(\"no-ae\"); Ok(mtrans) } }"} {"_id":"q-en-rust-19d4d015787af8da602baf74610b2095c2d5679df95804cfbc2ec50b2e9218ae","text":"self_ty: Ty<'tcx>, sig: ty::PolyGenSig<'tcx>, ) -> ty::Binder<'tcx, (ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)> { debug_assert!(!self_ty.has_escaping_bound_vars()); assert!(!self_ty.has_escaping_bound_vars()); let trait_ref = tcx.mk_trait_ref(fn_trait_def_id, [self_ty, sig.skip_binder().resume_ty]); sig.map_bound(|sig| (trait_ref, sig.yield_ty, sig.return_ty)) }"} {"_id":"q-en-rust-1a3e673a30b48a4775545f7bfc534bccb025127168857a7f905445540b83eb98","text":"linker_flavor: LinkerFlavor::Ld, linker: Some(\"arm-none-eabi-ld\".into()), asm_args: cvs![\"-mthumb-interwork\", \"-march=armv4t\", \"-mlittle-endian\",], features: \"+soft-float,+strict-align\".into(), // Force-enable 32-bit atomics, which allows the use of atomic load/store only. // The resulting atomics are ABI incompatible with atomics backed by libatomic. features: \"+soft-float,+strict-align,+atomics-32\".into(), main_needs_argc_argv: false, atomic_cas: false, has_thumb_interworking: true,"} {"_id":"q-en-rust-1a46e94f9c4ff3f04f364fda0aac8f0ac3e9863306b35e231f7be5f0ca769b0d","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":"q-en-rust-1a67dcab853caf5c65bacc8cf92ce2665f07662c17c5064137f11b3474ed4f83","text":"#[stable(feature = \"array_value_iter_impls\", since = \"1.40.0\")] unsafe impl TrustedLen for IntoIter {} #[doc(hidden)] #[unstable(issue = \"none\", feature = \"std_internals\")] #[rustc_unsafe_specialization_marker] pub trait NonDrop {} // T: Copy as approximation for !Drop since get_unchecked does not advance self.alive // and thus we can't implement drop-handling #[unstable(issue = \"none\", feature = \"std_internals\")] impl NonDrop for T {} #[doc(hidden)] #[unstable(issue = \"none\", feature = \"std_internals\")] unsafe impl TrustedRandomAccessNoCoerce for IntoIter where T: NonDrop, { const MAY_HAVE_SIDE_EFFECT: bool = false; } #[stable(feature = \"array_value_iter_impls\", since = \"1.40.0\")] impl Clone for IntoIter { fn clone(&self) -> Self {"} {"_id":"q-en-rust-1ab0968be59768982f9c36cc68161380f1fcece849982cae2a54b3aedd9bff91","text":"let r = match datum.ty.sty { ty::ty_uniq(content_ty) => { // Make sure we have an lvalue datum here to get the // proper cleanups scheduled let datum = unpack_datum!( bcx, datum.to_lvalue_datum(bcx, \"deref\", expr.id)); if type_is_sized(bcx.tcx(), content_ty) { deref_owned_pointer(bcx, expr, datum, content_ty) let ptr = load_ty(bcx, datum.val, datum.ty); DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr)) } else { // A fat pointer and a DST lvalue have the same representation // just different types. Since there is no temporary for `*e` // here (because it is unsized), we cannot emulate the sized // object code path for running drop glue and free. Instead, // we schedule cleanup for `e`, turning it into an lvalue. let datum = unpack_datum!( bcx, datum.to_lvalue_datum(bcx, \"deref\", expr.id)); let datum = Datum::new(datum.val, content_ty, LvalueExpr); DatumBlock::new(bcx, datum)"} {"_id":"q-en-rust-1add763287fc3c2e2925776ecd1b12026ffaccd1da6f7c9e48cc474b0d15ab23","text":"/// # Examples /// /// ``` /// format!(\"test\"); /// format!(\"hello {}\", \"world!\"); /// format!(\"x = {}, y = {y}\", 10, y = 30); /// format!(\"test\"); // => \"test\" /// format!(\"hello {}\", \"world!\"); // => \"hello world!\" /// format!(\"x = {}, y = {val}\", 10, val = 30); // => \"x = 10, y = 30\" /// let (x, y) = (1, 2); /// format!(\"{x} + {y} = 3\"); /// format!(\"{x} + {y} = 3\"); // => \"1 + 2 = 3\" /// ``` #[macro_export] #[stable(feature = \"rust1\", since = \"1.0.0\")]"} {"_id":"q-en-rust-1aeae1edc37a56795165174e0fd94cd9c39a4fcec2143985a12dbe4b8d95d88c","text":"_ => unreachable!(), }; write_or_print(&out, ofile); write_or_print(&out, ofile, sess); } pub fn print_after_hir_lowering<'tcx>("} {"_id":"q-en-rust-1b1438bc74b0d97638b461d1710e6b4f8f51a4fd0fe8cf24d79f141df6c68c40","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. // RFC 736 (and Issue 21407): functional struct update should respect privacy. // The `foo` module attempts to maintains an invariant that each `S` // has a unique `u64` id. use self::foo::S; mod foo { use std::cell::{UnsafeCell}; static mut count : UnsafeCell = UnsafeCell { value: 1 }; pub struct S { pub a: u8, pub b: String, secret_uid: u64 } pub fn make_secrets(a: u8, b: String) -> S { let val = unsafe { let p = count.get(); let val = *p; *p = val + 1; val }; println!(\"creating {}, uid {}\", b, val); S { a: a, b: b, secret_uid: val } } impl Drop for S { fn drop(&mut self) { println!(\"dropping {}, uid {}\", self.b, self.secret_uid); } } } fn main() { let s_1 = foo::make_secrets(3, format!(\"ess one\")); let s_2 = foo::S { b: format!(\"ess two\"), ..s_1 }; // FRU ... //~^ ERROR field `secret_uid` of struct `foo::S` is private println!(\"main forged an S named: {}\", s_2.b); // at end of scope, ... both s_1 *and* s_2 get dropped. Boom! } "} {"_id":"q-en-rust-1b1d8a694e0b6db7ac5aab7c68d8b5910494583fe26de953931673ab52cdaeb8","text":"/// # Examples /// /// ```no_run /// #![feature(buffered_io_capacity)] /// use std::io::BufWriter; /// use std::net::TcpStream; ///"} {"_id":"q-en-rust-1bc7945903df0de654fa86cfa35372f4508ea72a010fbbb2a113c23f3cf4fefe","text":" error: unused pinned `MustUsePtr` that must be used --> $DIR/must_use-pin.rs:42:5 | LL | pin_must_use_ptr(); | ^^^^^^^^^^^^^^^^^^ | note: the lint level is defined here --> $DIR/must_use-pin.rs:1:9 | LL | #![deny(unused_must_use)] | ^^^^^^^^^^^^^^^ error: unused pinned boxed `MustUse` that must be used --> $DIR/must_use-pin.rs:44:5 | LL | pin_box_must_use(); | ^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors "} {"_id":"q-en-rust-1bef6b95d229c3337941746e48e6097cf70a8d078c7b02cc536542d4a798238c","text":"without modifying the original\"] #[inline] #[track_caller] #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] pub const fn ilog10(self) -> u32 { match self.checked_ilog10() { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } self.checked_ilog10().expect(\"argument of integer logarithm must be positive\") } /// Returns the logarithm of the number with respect to an arbitrary base,"} {"_id":"q-en-rust-1c40375779a3814db74807d5781862fa796b59dabb881c59976d57fcd5cacf08","text":" // https://github.com/rust-lang/rust/issues/69228 // Used to give bogus suggestion about T not being Sized. use std::mem::size_of; fn foo() { let _arr: [u8; size_of::()]; //~^ ERROR generic parameters may not be used in const operations //~| NOTE cannot perform const operation //~| NOTE type parameters may not be used in const expressions } fn main() {} "} {"_id":"q-en-rust-1c53f5b541c125ac8d8ad8998386184908bf61ec05757c93def76d991ab0cb0a","text":" // run-pass #![feature(const_mut_refs)] static mut TEST: i32 = { // We must not promote this, as CTFE needs to be able to mutate it later. let x = &mut [1,2,3]; x[0] += 1; x[0] }; // This still works -- it's not done via promotion. #[allow(unused)] static mut TEST2: &'static mut [i32] = &mut [0,1,2]; fn main() { assert_eq!(unsafe { TEST }, 2); } "} {"_id":"q-en-rust-1c6e25773fadb8348bd45d4f26e0dda9f894c672d9f73ab633f0180bd09f6921","text":"pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str = \"attributes of the form `#[derive_*]` are reserved for the compiler\"; pub const EXPLAIN_LITERAL_MATCHER: &'static str = \":literal fragment specifier is experimental and subject to change\"; pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str = \"unsized tuple coercion is not stable enough for use and is subject to change\";"} {"_id":"q-en-rust-1c7c8d034747add611cd3f38fc9ab26ac979126aabff85727b4f8574b4a1b427","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":"q-en-rust-1c8a11c9aeb40a567ebb81f2305d5665b8bcb1488eaa0226857f47f8e55f700e","text":" // This tests the parser recovery in `recover_intersection_pat` // and serves as a regression test for the diagnostics issue #65400. // // The general idea is that for `$pat_lhs @ $pat_rhs` where // `$pat_lhs` is not generated by `ref? mut? $ident` we want // to suggest either switching the order or note that intersection // patterns are not allowed. fn main() { let s: Option = None; match s { Some(x) @ y => {} //~^ ERROR pattern on wrong side of `@` //~| pattern on the left, should be on the right //~| binding on the right, should be on the left //~| HELP switch the order //~| SUGGESTION y @ Some(x) _ => {} } match s { Some(x) @ Some(y) => {} //~^ ERROR left-hand side of `@` must be a binding //~| interpreted as a pattern, not a binding //~| also a pattern //~| NOTE bindings are `x`, `mut x`, `ref x`, and `ref mut x` _ => {} } match 2 { 1 ..= 5 @ e => {} //~^ ERROR pattern on wrong side of `@` //~| pattern on the left, should be on the right //~| binding on the right, should be on the left //~| HELP switch the order //~| SUGGESTION e @ 1 ..=5 _ => {} } } "} {"_id":"q-en-rust-1cabb507006fce0adb97c170f21dff5c9e4803adeaf432a212e56192204b162b","text":"/// [`NonNull::dangling()`]: ptr::NonNull::dangling #[inline] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] { debug_assert!(is_aligned_and_not_null(data), \"attempt to create unaligned or null slice\"); debug_assert!( mem::size_of::().saturating_mul(len) <= isize::MAX as usize, \"attempt to create slice covering at least half the address space\" ); #[rustc_const_unstable(feature = \"const_slice_from_raw_parts\", issue = \"67456\")] pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] { debug_check_data_len(data as _, len); // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`. unsafe { &mut *ptr::slice_from_raw_parts_mut(data, len) } } // In debug builds checks that `data` pointer is aligned and non-null and that slice with given `len` would cover less than half the address space #[cfg(all(not(bootstrap), debug_assertions))] #[unstable(feature = \"const_slice_from_raw_parts\", issue = \"67456\")] #[rustc_const_unstable(feature = \"const_slice_from_raw_parts\", issue = \"67456\")] const fn debug_check_data_len(data: *const T, len: usize) { fn rt_check(data: *const T) { use crate::intrinsics::is_aligned_and_not_null; assert!(is_aligned_and_not_null(data), \"attempt to create unaligned or null slice\"); } const fn noop(_: *const T) {} // SAFETY: // // `rt_check` is just a debug assert to hint users that they are causing UB, // it is not required for safety (the safety must be guatanteed by // the `from_raw_parts[_mut]` caller). // // Since the checks are not required, we ignore them in CTFE as they can't // be done there (alignment does not make much sense there). unsafe { crate::intrinsics::const_eval_select((data,), noop, rt_check); } assert!( crate::mem::size_of::().saturating_mul(len) <= isize::MAX as usize, \"attempt to create slice covering at least half the address space\" ); } #[cfg(not(all(not(bootstrap), debug_assertions)))] const fn debug_check_data_len(_data: *const T, _len: usize) {} /// Converts a reference to T into a slice of length 1 (without copying). #[stable(feature = \"from_ref\", since = \"1.28.0\")] #[rustc_const_unstable(feature = \"const_slice_from_ref\", issue = \"90206\")]"} {"_id":"q-en-rust-1cbee4788b76390791b7768c3b48d9f8f96c483402c3e7cfd5db3444cdd2b114","text":"/// N.B., while `f` is running, the thread-local state /// is `BridgeState::InUse`. fn with(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R { BRIDGE_STATE.with(|state| { state.replace(BridgeState::InUse, |mut state| { // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone f(&mut *state) }) }) BRIDGE_STATE.with(|state| state.replace(BridgeState::InUse, f)) } }"} {"_id":"q-en-rust-1cc6c8cca2787c3bdab5ccfef5c887d0c1bce4d3a60d9dfb31db338509fe51b8","text":"let tcx = self.tcx(); let mut pred = cache_fresh_trait_pred.skip_binder(); param_env = param_env.with_constness(pred.constness.and(param_env.constness())); pred.remap_constness(tcx, &mut param_env); if !self.can_cache_candidate(&candidate) { debug!(?pred, ?candidate, \"insert_candidate_cache - candidate is not cacheable\");"} {"_id":"q-en-rust-1cd0d10357d12c35ffbc6ef499263477475a970a2d3b6b7f15e0515d90114d54","text":"// one: if self.emitted_diagnostics.borrow_mut().insert(diagnostic_hash) { self.emitter.borrow_mut().emit(db); if db.is_error() { self.bump_err_count(); } } } }"} {"_id":"q-en-rust-1d63d5d762c7a9bdb55d563bcae97ae3d1f4825e5786e9487099199db48efad9","text":" //@ known-bug: #121574 #![feature(generic_const_exprs)] impl X { pub fn y<'a, U: 'a>(&'a self) -> impl Iterator + '_> {} } "} {"_id":"q-en-rust-1d6fca66c634775e2b2fa3c913f95044dcf72809ad9028b5d6e1567b187f3202","text":" #[derive(Clone)] pub struct Struct; pub mod dep_mod1 { pub struct Fields { /// [crate::Struct::clone] pub field: u8, } } pub mod dep_mod2 { pub enum Fields { V { /// [crate::Struct::clone] field: u8, }, } } "} {"_id":"q-en-rust-1d8ce8def654e663acf8fa07326f89599c96a898f21a8d86a0b9d8a635ad055d","text":"have happily compiled. If we forget in the `match`, it will not. Rust helps us make sure to cover all of our bases. `match` expressions also allow us to get the values contained in an `enum` (also known as destructuring) as follows: ```{rust} enum OptionalInt { Value(int), Missing, } fn main() { let x = Value(5); let y = Missing; match x { Value(n) => println!(\"x is {}\", n), Missing => println!(\"x is missing!\"), } match y { Value(n) => println!(\"y is {}\", n), Missing => println!(\"y is missing!\"), } } ``` That is how you can get and use the values contained in `enum`s. It can also allow us to treat errors or unexpected computations, for example, a function that is not guaranteed to be able to compute a result (an `int` here), could return an `OptionalInt`, and we would handle that value with a `match`. As you can see, `enum` and `match` used together are quite useful! `match` is also an expression, which means we can use it on the right hand side of a `let` binding or directly where an expression is used. We could also implement the previous line like this:"} {"_id":"q-en-rust-1dbb75c1a7a05e588bd321a5a3aa81d5201d64f51e69e9fdee68c24fcead2f51","text":"// Functions cannot both be `const async` or `const gen` if let Some(&FnHeader { constness: Const::Yes(cspan), constness: Const::Yes(const_span), coroutine_kind: Some(coroutine_kind), .. }) = fk.header() { let aspan = match coroutine_kind { CoroutineKind::Async { span: aspan, .. } | CoroutineKind::Gen { span: aspan, .. } | CoroutineKind::AsyncGen { span: aspan, .. } => aspan, }; // FIXME(gen_blocks): Report a different error for `const gen` self.dcx().emit_err(errors::ConstAndAsync { spans: vec![cspan, aspan], cspan, aspan, self.dcx().emit_err(errors::ConstAndCoroutine { spans: vec![coroutine_kind.span(), const_span], const_span, coroutine_span: coroutine_kind.span(), coroutine_kind: coroutine_kind.as_str(), span, }); }"} {"_id":"q-en-rust-1dc1180ba7fe0d2325d1f6ac0477ff7c36cccca8303ee4f26e6a7de2b95d465d","text":" // test for https://github.com/rust-lang/rust/issues/86940 // run-rustfix // edition:2018 // check-pass #![warn(rust_2021_prelude_collisions)] #![allow(dead_code)] #![allow(unused_imports)] struct Generic(T, U); trait MyFromIter { fn from_iter(_: i32) -> Self; } impl MyFromIter for Generic { fn from_iter(x: i32) -> Self { Self(x, x) } } impl std::iter::FromIterator for Generic { fn from_iter>(_: T) -> Self { todo!() } } fn main() { Generic::from_iter(1); //~^ WARNING trait-associated function `from_iter` will become ambiguous in Rust 2021 //~| this is accepted in the current edition (Rust 2018) Generic::::from_iter(1); //~^ WARNING trait-associated function `from_iter` will become ambiguous in Rust 2021 //~| this is accepted in the current edition (Rust 2018) Generic::<_, _>::from_iter(1); //~^ WARNING trait-associated function `from_iter` will become ambiguous in Rust 2021 //~| this is accepted in the current edition (Rust 2018) } "} {"_id":"q-en-rust-1dcbf8c67be9156d0970a76306fb061aad0bbe69444f65bdccb3517d9b442da3","text":"use rustc_infer::infer; use rustc_infer::traits::{self, StatementAsExpression}; use rustc_middle::lint::in_external_macro; use rustc_middle::ty::{self, Binder, DefIdTree, IsSuggestable, Ty}; use rustc_middle::ty::{ self, suggest_constraining_type_params, Binder, DefIdTree, IsSuggestable, ToPredicate, Ty, }; use rustc_session::errors::ExprParenthesesNeeded; use rustc_span::symbol::sym; use rustc_span::Span;"} {"_id":"q-en-rust-1de5c7160bb3a5a4bcded27b4379a46216817de153a0787e5ac2d57fcf7caebe","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":"q-en-rust-1e1b29ce45bfa4b36e68f19253d01f20796f6d2b52c3314253d4659794ab48af","text":" error[E0310]: the parameter type `T` may not live long enough --> $DIR/issue_74400.rs:12:5 | LL | f(data, identity) | ^^^^^^^^^^^^^^^^^ | = help: consider adding an explicit lifetime bound `T: 'static`... error[E0308]: mismatched types --> $DIR/issue_74400.rs:12:5 | LL | f(data, identity) | ^^^^^^^^^^^^^^^^^ one type is more general than the other | = note: expected type `for<'r> Fn<(&'r T,)>` found type `Fn<(&T,)>` error: implementation of `FnOnce` is not general enough --> $DIR/issue_74400.rs:12:5 | LL | f(data, identity) | ^^^^^^^^^^^^^^^^^ implementation of `FnOnce` is not general enough | = note: `fn(&'2 T) -> &'2 T {identity::<&'2 T>}` must implement `FnOnce<(&'1 T,)>`, for any lifetime `'1`... = note: ...but it actually implements `FnOnce<(&'2 T,)>`, for some specific lifetime `'2` error: aborting due to 3 previous errors Some errors have detailed explanations: E0308, E0310. For more information about an error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-1e332ff1f6a4bf23d7e2977fa03cac0dbfe253a282e1b2ef780741961a27d9a3","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":"q-en-rust-1e38e3c3c7d4ebe26b1a56fd8bbf14e6d156ec24287c4eca6f5993a1d1ab2315","text":"# Only commits merged by bors will have CI artifacts. merge_base = [ \"git\", \"rev-list\", \"--author=bors@rust-lang.org\", \"-n1\", \"--merges\", \"--first-parent\", \"HEAD\" \"--first-parent\", \"HEAD\" ] commit = subprocess.check_output(merge_base, universal_newlines=True).strip() if not commit: print(\"error: could not find commit hash for downloading rustc\") print(\"help: maybe your repository history is too shallow?\") print(\"help: consider disabling `download-rustc`\") print(\"help: or fetch enough history to include one upstream commit\") exit(1) # Warn if there were changes to the compiler or standard library since the ancestor commit. status = subprocess.call([\"git\", \"diff-index\", \"--quiet\", commit, \"--\", compiler, library])"} {"_id":"q-en-rust-1e8d206a7f2fce7000ace8ba040ec7d20714f1279702df832408ae8c980f2a44","text":" error[E0609]: no field `f` on type `Foo` --> $DIR/non-existent-field-present-in-subfield-recursion-limit.rs:41:22 | LL | let test = fooer.f; | ^ unknown field | = note: available fields are: `first`, `second`, `third` error: aborting due to previous error For more information about this error, try `rustc --explain E0609`. "} {"_id":"q-en-rust-1eb099e061f422776f9a3f6d4aae18a2aef84597b60b51121d32a07c35cb7ae2","text":" // build-fail fn main() { let xs: [i32; 5] = [1, 2, 3, 4, 5]; let _ = &xs; let _ = xs[7]; //~ ERROR: this operation will panic at runtime [unconditional_panic] } "} {"_id":"q-en-rust-1eb697f5be687ad181a955db6665cd6a5f17917b54c6695d5174e182c85e646e","text":"impl Mumbo for usize { // Cannot have a larger effect than the trait: unsafe fn jumbo(&self, x: &usize) { *self + *x; } //~^ ERROR expected normal fn, found unsafe fn //~^ ERROR method `jumbo` has an incompatible type for trait //~| expected normal fn, //~| found unsafe fn } fn main() {}"} {"_id":"q-en-rust-1ec3ce660e019cb07c90d91c5f57bf816f9624da641b9cd893f60e0f87a6378a","text":"/// This function does not perform any I/O, it simply informs this object /// that some amount of its buffer, returned from `fill_buf`, has been /// consumed and should no longer be returned. /// /// This function is used to tell the buffer how many bytes you've consumed /// from the return value of `fill_buf`, and so may do odd things if /// `fill_buf` isn't called before calling this. /// /// The `amt` must be `<=` the number of bytes in the buffer returned by `fill_buf`. #[stable(feature = \"rust1\", since = \"1.0.0\")] fn consume(&mut self, amt: usize);"} {"_id":"q-en-rust-1ed66a53d9fff4d1dd0901506db14355e768b42f4f739a160d1a4f2277f66fbb","text":"// } fn mk_decls( cx: &mut ExtCtxt<'_>, custom_derives: &[ProcMacroDerive], custom_attrs: &[ProcMacroDef], custom_macros: &[ProcMacroDef], macros: &[ProcMacro], ) -> P { let expn_id = cx.resolver.expansion_for_ast_pass( DUMMY_SP,"} {"_id":"q-en-rust-1f14ae7f36911946f67cc5fc9d92f2dff1b7ca7bda39845ab681fbb03ae7b217","text":"generic_ty: Ty<'tcx>, min: ty::Region<'tcx>, ) -> bool { if let ty::ReError(_) = *min { return true; } match bound { VerifyBound::IfEq(verify_if_eq_b) => { let verify_if_eq_b = var_values.normalize(self.region_rels.tcx, *verify_if_eq_b);"} {"_id":"q-en-rust-1f384871c3dc0d6b34cf16d17bd3d6fd5bd1d09ce0c958f2b34c16d3a6872918","text":" error: lifetime may not live long enough --> $DIR/suggest-using-tick-underscore-lifetime-in-return-trait-object.rs:5:5 | LL | fn foo(value: &T) -> Box { | - let's call the lifetime of this reference `'1` LL | Box::new(value) as Box | ^^^^^^^^^^^^^^^ cast requires that `'1` must outlive `'static` | help: to declare that the trait object captures data from argument `value`, you can add an explicit `'_` lifetime bound | LL | fn foo(value: &T) -> Box { | ++++ error: aborting due to previous error "} {"_id":"q-en-rust-1f61d149bfe4d2efec8cc0f4e1fe36f5334007160327ff5c140962ce94bd4657","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":"q-en-rust-1f84bde837b2b1b93879f1b9fc26cc279fcb6833d76f4c08ba15276882312ec6","text":"lazy_state: LazyState::NoNode, type_shorthands: Default::default(), predicate_shorthands: Default::default(), } .encode_crate_root(); }; // Encode the rustc version string in a predictable location. rustc_version().encode(&mut ecx).unwrap(); // Encode all the entries and extra information in the crate, // culminating in the `CrateRoot` which points to all of it. ecx.encode_crate_root() }; let mut result = cursor.into_inner(); // Encode the root position."} {"_id":"q-en-rust-1f851207f9f049bf5ff08eb6d96fc4d3d45f101ef5fac86f18d614a3c3777b7a","text":"/// /// assert_eq!(\"GRüßE, JüRGEN ❤\", s); /// ``` #[unstable(feature = \"osstring_ascii\", issue = \"70516\")] #[stable(feature = \"osstring_ascii\", since = \"1.53.0\")] #[inline] pub fn make_ascii_uppercase(&mut self) { self.inner.make_ascii_uppercase()"} {"_id":"q-en-rust-1f9e47b025f2d2032fc9b1822395a7a6f0fdd51bceba8315e8f24a2f72c79a80","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":"q-en-rust-1f9e5275535dcd3d0d7cfd5f16da5826b649bf514018d50673603e87bde562bc","text":"ascription: thir::Ascription { variance, user_ty, user_ty_span }, } => { // Apply the type ascription to the value at `match_pair.place`, which is the candidate.ascriptions.push(Ascription { span: user_ty_span, user_ty, source: match_pair.place.clone().into_place(self.tcx, self.typeck_results), variance, }); if let Ok(place_resolved) = match_pair.place.clone().try_upvars_resolved(self.tcx, self.typeck_results) { candidate.ascriptions.push(Ascription { span: user_ty_span, user_ty, source: place_resolved.into_place(self.tcx, self.typeck_results), variance, }); } candidate.match_pairs.push(MatchPair::new(match_pair.place, subpattern));"} {"_id":"q-en-rust-1fad8867339b723139d144b6b2c8db5770c84c55e394cdbda69a6f695072d5a6","text":"/// assert_eq!(*guard, 1); /// ``` #[inline] #[unstable(feature = \"mutex_unpoison\", issue = \"96469\")] #[stable(feature = \"mutex_unpoison\", since = \"CURRENT_RUSTC_VERSION\")] pub fn clear_poison(&self) { self.poison.clear(); }"} {"_id":"q-en-rust-1fc4d647b787c4f227871a7ac12d691b478e34b65a70c55e7cb3e21b13f172d3","text":"}; append_arg(&mut cmd, arg, quote)?; } if is_batch_file { cmd.push(b'\"' as u16); } return Ok(cmd); fn append_arg(cmd: &mut Vec, arg: &OsStr, quote: Quote) -> io::Result<()> {"} {"_id":"q-en-rust-20045b56be8fa825b2f4bf3b3b01511039df9bacba38c31b1ecad251c6046eb9","text":" // check-pass #![feature(type_alias_impl_trait)] pub trait Trait { type A; fn f() -> Self::A; } pub trait Tr2<'a, 'b> {} pub struct A(T); pub trait Tr { type B; } impl<'a, 'b, T: Tr>> Trait for A { type A = impl core::fmt::Debug; fn f() -> Self::A {} } fn main() {} "} {"_id":"q-en-rust-201470e3992ea4e6ed925ab0cdaf11c3c24140c994902c33449d87fbb6b56504","text":"name: Symbol, ) -> Result { // FIXME: use direct symbol comparison for register names name.with(|name| { Ok(match arch { InlineAsmArch::X86 | InlineAsmArch::X86_64 => { Self::X86(X86InlineAsmReg::parse(arch, has_feature, name)?) } InlineAsmArch::Arm => Self::Arm(ArmInlineAsmReg::parse(arch, has_feature, name)?), InlineAsmArch::AArch64 => { Self::AArch64(AArch64InlineAsmReg::parse(arch, has_feature, name)?) } InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => { Self::RiscV(RiscVInlineAsmReg::parse(arch, has_feature, name)?) } }) // Use `Symbol::as_str` instead of `Symbol::with` here because `has_feature` may access `Symbol`. let name = name.as_str(); Ok(match arch { InlineAsmArch::X86 | InlineAsmArch::X86_64 => { Self::X86(X86InlineAsmReg::parse(arch, has_feature, &name)?) } InlineAsmArch::Arm => Self::Arm(ArmInlineAsmReg::parse(arch, has_feature, &name)?), InlineAsmArch::AArch64 => { Self::AArch64(AArch64InlineAsmReg::parse(arch, has_feature, &name)?) } InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => { Self::RiscV(RiscVInlineAsmReg::parse(arch, has_feature, &name)?) } }) }"} {"_id":"q-en-rust-2028ffa1ea5b19e9120af2bf78fa220ce31d77b79c6abfe144fbce8b130b3f7b","text":"} } // FIXME: This has the same issue as #108544, but since this isn't breaking // existing code, I'm not particularly inclined to do the same hack as above // where we process wf obligations manually. This can be fixed in a forward- // compatible way later. let collected_types = collector.types; for (_, &(ty, _)) in &collected_types { ocx.register_obligation(traits::Obligation::new( tcx, misc_cause.clone(), param_env, ty::ClauseKind::WellFormed(ty.into()), )); } // Check that all obligations are satisfied by the implementation's // RPITs. let errors = ocx.select_all_or_error();"} {"_id":"q-en-rust-202cb349464e09a2933ea80dd476d2911beb1701192ceff05cb0077e599d390a","text":"self.suggest_derive(err, &preds); } fn suggest_derive( pub fn suggest_derive( &self, err: &mut Diagnostic, unsatisfied_predicates: &[("} {"_id":"q-en-rust-20687e623ca42568bbbf06f155b94f47944f23ed7b9e59bb4484db5ee2d31660","text":"/// let src = [1, 2, 3, 4]; /// let mut dst = [0, 0]; /// /// // Because the slices have to be the same length, /// // we slice the source slice from four elements /// // to two. It will panic if we don't do this. /// dst.copy_from_slice(&src[2..]); /// /// assert_eq!(src, [1, 2, 3, 4]);"} {"_id":"q-en-rust-206e93601513e0a50c05618ef1f0f39a66b49ad1da96b7d152b02e48caafb2a3","text":"fn main() { let x = match { 5 } { 1 => 5, 2 => 6, _ => 7, }; assert_eq!(x , 7); assert_eq!(x, 7); }"} {"_id":"q-en-rust-20d8efc39123a96f46204db8fc3415d341e4423c6fdc10bf111cda61959afcd2","text":"} self.print_ident(ident); if let Some(ref p) = *sub { self.s.word(\"@\"); self.s.space(); self.s.word_space(\"@\"); self.print_pat(p); } }"} {"_id":"q-en-rust-20e579c49df7bb207a17fc80f4d13ebb6fe187547f803d39e93f21e055fb90c4","text":"| LL | FarmAnimal::Chicken(_) => \"cluck, cluck!\".to_string(), | ^^^^^^^^^^^^^^^^^^^^^^ not a tuple struct or tuple variant | help: the struct variant's field is being ignored | LL | FarmAnimal::Chicken { num_eggs: _ } => \"cluck, cluck!\".to_string(), | ~~~~~~~~~~~~~~~ error: aborting due to 2 previous errors"} {"_id":"q-en-rust-20f69730a4f033a8e836fab65ffb9f0ddce245a115ef1614251cddef3aed954a","text":"/// /// assert_eq!(\"grÜße, jÜrgen ❤\", s); /// ``` #[unstable(feature = \"osstring_ascii\", issue = \"70516\")] #[stable(feature = \"osstring_ascii\", since = \"1.53.0\")] #[inline] pub fn make_ascii_lowercase(&mut self) { self.inner.make_ascii_lowercase()"} {"_id":"q-en-rust-21042bba8124db1f43b36d8bc447dafa576de846de5d9c995628d76fe4d3634b","text":" //@ compile-flags: -Zthreads=16 // original issue: https://github.com/rust-lang/rust/issues/129112 // Previously, the \"next\" solver asserted that each successful solution is only obtained once. // This test exhibits a repro that, with next-solver + -Zthreads, triggered that old assert. // In the presence of multithreaded solving, it's possible to concurrently evaluate things twice, // which leads to replacing already-solved solutions in the global solution cache! // We assume this is fine if we check to make sure they are solved the same way each time. // This test only nondeterministically fails but that's okay, as it will be rerun by CI many times, // so it should almost always fail before anything is merged. As other thread tests already exist, // we already face this difficulty, probably. If we need to fix this by reducing the error margin, // we should improve compiletest. #[derive(Clone, Eq)] //~ ERROR [E0277] pub struct Struct(T); impl PartialEq for Struct where U: Into> + Clone { fn eq(&self, _other: &U) -> bool { todo!() } } fn main() {} "} {"_id":"q-en-rust-2128e9fd06f41f49832d4e566037b422794f3aa8ff576207120a9095511b4968","text":"} } // for dbg!(x) which may take ownership, suggest dbg!(&x) instead // but here we actually do not check whether the macro name is `dbg!` // so that we may extend the scope a bit larger to cover more cases fn suggest_ref_for_dbg_args( &self, body: &hir::Expr<'_>, place: &Place<'tcx>, move_span: Span, err: &mut Diag<'infcx>, ) { let var_info = self.body.var_debug_info.iter().find(|info| match info.value { VarDebugInfoContents::Place(ref p) => p == place, _ => false, }); let arg_name = if let Some(var_info) = var_info { var_info.name } else { return; }; struct MatchArgFinder { expr_span: Span, match_arg_span: Option, arg_name: Symbol, } impl Visitor<'_> for MatchArgFinder { fn visit_expr(&mut self, e: &hir::Expr<'_>) { // dbg! is expanded into a match pattern, we need to find the right argument span if let hir::ExprKind::Match(expr, ..) = &e.kind && let hir::ExprKind::Path(hir::QPath::Resolved( _, path @ Path { segments: [seg], .. }, )) = &expr.kind && seg.ident.name == self.arg_name && self.expr_span.source_callsite().contains(expr.span) { self.match_arg_span = Some(path.span); } hir::intravisit::walk_expr(self, e); } } let mut finder = MatchArgFinder { expr_span: move_span, match_arg_span: None, arg_name }; finder.visit_expr(body); if let Some(macro_arg_span) = finder.match_arg_span { err.span_suggestion_verbose( macro_arg_span.shrink_to_lo(), \"consider borrowing instead of transferring ownership\", \"&\", Applicability::MachineApplicable, ); } } fn report_use_of_uninitialized( &self, mpi: MovePathIndex,"} {"_id":"q-en-rust-21321f87d8d49ff426e09840b44191c6431467a98a41a436be911221a71bd9cd","text":"/// /// assert_eq!(&v, &[0, 1, 2]); /// ``` #[unstable(feature = \"vec_spare_capacity\", issue = \"75017\")] #[stable(feature = \"vec_spare_capacity\", since = \"1.60.0\")] #[inline] pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { // Note:"} {"_id":"q-en-rust-216389043891c4ac8ce218cfdba629e44982157ea68bad4479077bbe88784d37","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":"q-en-rust-218a07c24fda7ebed438f4a2eefba2d83ad44a3707338cf7cea2afb2208c6495","text":"use test::{Bencher, black_box}; use super::BTreeMap; use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n}; #[bench] pub fn insert_rand_100(b: &mut Bencher) { let mut m = BTreeMap::new(); insert_rand_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); } #[bench] pub fn insert_rand_10_000(b: &mut Bencher) { let mut m = BTreeMap::new(); insert_rand_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); } // Insert seq #[bench] pub fn insert_seq_100(b: &mut Bencher) { let mut m = BTreeMap::new(); insert_seq_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); } #[bench] pub fn insert_seq_10_000(b: &mut Bencher) { let mut m = BTreeMap::new(); insert_seq_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); } map_insert_rand_bench!{insert_rand_100, 100, BTreeMap} map_insert_rand_bench!{insert_rand_10_000, 10_000, BTreeMap} // Find rand #[bench] pub fn find_rand_100(b: &mut Bencher) { let mut m = BTreeMap::new(); find_rand_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.get(&i); }); } #[bench] pub fn find_rand_10_000(b: &mut Bencher) { let mut m = BTreeMap::new(); find_rand_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.get(&i); }); } map_insert_seq_bench!{insert_seq_100, 100, BTreeMap} map_insert_seq_bench!{insert_seq_10_000, 10_000, BTreeMap} // Find seq #[bench] pub fn find_seq_100(b: &mut Bencher) { let mut m = BTreeMap::new(); find_seq_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.get(&i); }); } map_find_rand_bench!{find_rand_100, 100, BTreeMap} map_find_rand_bench!{find_rand_10_000, 10_000, BTreeMap} #[bench] pub fn find_seq_10_000(b: &mut Bencher) { let mut m = BTreeMap::new(); find_seq_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.get(&i); }); } map_find_seq_bench!{find_seq_100, 100, BTreeMap} map_find_seq_bench!{find_seq_10_000, 10_000, BTreeMap} fn bench_iter(b: &mut Bencher, size: i32) { let mut map = BTreeMap::::new();"} {"_id":"q-en-rust-219d4e9c40e54c77c0032da535f859d9ad84b23f217ec071ac681a717bfdd2a3","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. // Ensure assigning an owned or managed variable to itself works. In particular, // that we do not glue_drop before we glue_take (#3290). use std::rc::Rc; pub fn main() { let mut x = ~3; x = x; assert!(*x == 3); let mut x = Rc::new(3); x = x; assert!(*x.borrow() == 3); } "} {"_id":"q-en-rust-21ab9c24eb129e9834786d6d7a9a032db0a77fc39b57fcc2c5e99ae639a9b442","text":"/// } /// ``` #[stable(feature = \"rust1\", since = \"1.0.0\")] #[rustc_deprecated(since = \"1.41.0\", reason = \"use the Display impl or to_string()\")] #[rustc_deprecated(since = \"1.42.0\", reason = \"use the Display impl or to_string()\")] fn description(&self) -> &str { \"description() is deprecated; use Display\" }"} {"_id":"q-en-rust-21b779214bf5bdfabd999da0fe91e9f4fae4548af0d7144cfb915a14bfea196f","text":"} } #[derive(Clone, PartialEq, Encodable, Decodable)] #[derive(Copy, Clone, PartialEq, Encodable, Decodable)] pub enum InlineAttr { None, Hint,"} {"_id":"q-en-rust-21d3c094d0d07d68d72501e778077fe16daf68e508c5f1e7deb6d4c9f65363db","text":"fn vtable_impl( &mut self, impl_def_id: DefId, mut substs: Normalized<'tcx, SubstsRef<'tcx>>, substs: Normalized<'tcx, SubstsRef<'tcx>>, cause: ObligationCause<'tcx>, recursion_depth: usize, param_env: ty::ParamEnv<'tcx>,"} {"_id":"q-en-rust-2211fc5494eedeb188428881068a3bd2582dfaaec580f21219107a30bb3d3d11","text":"// `allow(warnings)` in scope then we want to respect that instead. if level == Level::Warn { let (warnings_level, warnings_src) = self.get_lint_id_level(LintId::of(lint::builtin::WARNINGS), idx); self.get_lint_id_level(LintId::of(lint::builtin::WARNINGS), idx, aux); if let Some(configured_warning_level) = warnings_level { if configured_warning_level != Level::Warn { level = configured_warning_level;"} {"_id":"q-en-rust-22340d0c1e88a6131de081f293b2e3ec72cd45857c47c05972782d1e1a3caf5d","text":"println!(\"running {}\", test_file_name); let nodejs = build.config.nodejs.as_ref().expect(\"nodejs not configured\"); let mut cmd = Command::new(nodejs); cmd.arg(&test_file_name) .stderr(::std::process::Stdio::inherit()); cmd.arg(&test_file_name); if build.config.quiet_tests { cmd.arg(\"--quiet\"); }"} {"_id":"q-en-rust-225f4e4d880f748bcad78c68fff31d7de596f529b5f6597bd7fec7d5db7e9be4","text":"/// /// Note that the argument is not passed through a shell, but given /// literally to the program. This means that shell syntax like quotes, /// escaped characters, word splitting, glob patterns, substitution, etc. /// escaped characters, word splitting, glob patterns, variable substitution, etc. /// have no effect. /// /// # Examples"} {"_id":"q-en-rust-228375c5029ef7d2771ee96106df160a57174afb3d7a950344d0dd0dc054b2b4","text":"/// # Examples /// /// ``` /// #![feature(arc_unwrap_or_clone)] /// # use std::{ptr, sync::Arc}; /// let inner = String::from(\"test\"); /// let ptr = inner.as_ptr();"} {"_id":"q-en-rust-22a8cd0b24f0ca8bfc6e07834402a154ad7a30706c21a5b10c925cd4b6c950b3","text":"--codeblock-error-color: rgba(255, 0, 0, .5); --codeblock-ignore-hover-color: rgb(255, 142, 0); --codeblock-ignore-color: rgba(255, 142, 0, .6); --warning-border-color: rgb(255, 142, 0); --type-link-color: #ffa0a5; --trait-link-color: #39afd7; --assoc-item-link-color: #39afd7;"} {"_id":"q-en-rust-22b97205445797a273b2036928bf8023da0c295b08c5fd26709785df2e63f4e8","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(box_syntax)] struct Node(T); fn main() { let x: Box> = box Node([]); } "} {"_id":"q-en-rust-22d2c8ae796aa9b157e5ebf9747f51353248dc58e4ff79854004cdf03f8aacf1","text":"/// Whether the original and suggested code are visually similar enough to warrant extra wording. pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool { // FIXME: this should probably be extended to also account for `FO0` → `FOO` and unicode. let found = sm.span_to_snippet(sp).unwrap(); let found = match sm.span_to_snippet(sp) { Ok(snippet) => snippet, Err(e) => { warn!(\"Invalid span {:?}. Err={:?}\", sp, e); return false; } }; let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z']; // All the chars that differ in capitalization are confusable (above): let confusable = found"} {"_id":"q-en-rust-22e1eb7ad4b683fcd220b11f753aa05a3f163c8e484a7b01d046c0321e417c36","text":" error[E0262]: invalid lifetime parameter name: `'static` --> $DIR/generic_const_early_param.rs:4:20 | LL | struct DataWrapper<'static> { | ^^^^^^^ 'static is a reserved lifetime name error[E0261]: use of undeclared lifetime name `'a` --> $DIR/generic_const_early_param.rs:6:12 | LL | struct DataWrapper<'static> { | - help: consider introducing lifetime `'a` here: `'a,` LL | LL | data: &'a [u8; Self::SIZE], | ^^ undeclared lifetime error[E0261]: use of undeclared lifetime name `'a` --> $DIR/generic_const_early_param.rs:11:18 | LL | impl DataWrapper<'a> { | - ^^ undeclared lifetime | | | help: consider introducing lifetime `'a` here: `<'a>` warning: the feature `generic_const_exprs` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/generic_const_early_param.rs:1:12 | LL | #![feature(generic_const_exprs)] | ^^^^^^^^^^^^^^^^^^^ | = note: see issue #76560 for more information = note: `#[warn(incomplete_features)]` on by default error: lifetime may not live long enough --> $DIR/generic_const_early_param.rs:6:20 | LL | data: &'a [u8; Self::SIZE], | ^^^^^^^^^^ requires that `'_` must outlive `'static` error: aborting due to 4 previous errors; 1 warning emitted Some errors have detailed explanations: E0261, E0262. For more information about an error, try `rustc --explain E0261`. "} {"_id":"q-en-rust-2304cd1710eff8ac083672cf1856e3312aa0334fbb8c7de1f47b41f1dcda6224","text":" error: expected item, found `;` --> $DIR/fn-no-semicolon-issue-124935-semi-after-item.rs:5:1 | LL | ; | ^ help: remove this semicolon error: aborting due to 1 previous error "} {"_id":"q-en-rust-233a5e5c9ffb5ebce33c264b685cd8fd83cd4d4da867aa47b49fa8fc055094d2","text":"return Some(p); } if let Some(e) = self.expr { if let ast::ExprKind::Lit(_) = e.kind { if matches!(e.kind, ast::ExprKind::Lit(_) | ast::ExprKind::IncludedBytes(_)) { return Some(P(ast::Pat { id: ast::DUMMY_NODE_ID, span: e.span,"} {"_id":"q-en-rust-238898a81af0a37e967a4f51c683700e990139c60885063d123bcc0382fead25","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":"q-en-rust-23e7e8cfc748b2060ca2fff45c2a187f51341c003435391c3ea1020dca783923","text":"rm -rf /tmp/rustc-pgo python3 ../x.py build --target=$PGO_HOST --host=$PGO_HOST python2.7 ../x.py build --target=$PGO_HOST --host=$PGO_HOST --stage 2 library/std --rust-profile-generate=/tmp/rustc-pgo ./build/$PGO_HOST/stage2/bin/rustc --edition=2018 "} {"_id":"q-en-rust-23fc129f866b97d9086a90f4d82792817d67c869b6b629cf64461993fd5d45ca","text":"{ unreachable!(\"Always specialized\"); } #[inline] default fn fold(self, init: Acc, f: F) -> Acc where F: FnMut(Acc, Self::Item) -> Acc, { SpecFold::spec_fold(self, init, f) } } #[doc(hidden)]"} {"_id":"q-en-rust-24179473c9879499068dc90ef144f99334371f77cf56a725a52221453e1c6831","text":"let main = P(ast::Item { ident: main_id, attrs: thin_vec![main_attr], attrs: thin_vec![main_attr, no_coverage_attr], id: ast::DUMMY_NODE_ID, kind: main, vis: ast::Visibility { span: sp, kind: ast::VisibilityKind::Public, tokens: None },"} {"_id":"q-en-rust-245b1a324e8e7b2706193f537822b856a279e72f79e474e58291758f58cb2187","text":"base.cpu = \"x86-64\".to_string(); base.max_atomic_width = Some(64); base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push(\"-mx32\".to_string()); // BUG: temporarily workaround #59674 base.stack_probes = false; base.stack_probes = true; base.has_elf_tls = false; // BUG(GabrielMajeri): disabling the PLT on x86_64 Linux with x32 ABI // breaks code gen. See LLVM bug 36743"} {"_id":"q-en-rust-246e96d15452c07a5827d38a00dac906cfef8f7acb9ef4c2908c3330d4f9d714","text":"is_unwindsafe(async { //~^ ERROR the type `&mut Context<'_>` may not be safely transferred across an unwind boundary //~| ERROR the type `&mut (dyn Any + 'static)` may not be safely transferred across an unwind boundary use std::ptr::null; use std::task::{Context, RawWaker, RawWakerVTable, Waker}; let waker = unsafe {"} {"_id":"q-en-rust-2472ce7a5d72bc0caed71c1024ec77c02b1eace36b9b825c8627c10c28a3d29f","text":"} SaveIn(lldest) => { match ty::eval_repeat_count(bcx.tcx(), &**count_expr) { 0 => bcx, 0 => expr::trans_into(bcx, &**element, Ignore), 1 => expr::trans_into(bcx, &**element, SaveIn(lldest)), count => { let elem = unpack_datum!(bcx, expr::trans(bcx, &**element));"} {"_id":"q-en-rust-247fe22a42305e17c8dcc79311bc3a3ecf3806e1e5875c374e746f83cbba2c5f","text":"/// When `is_collectin_in_band_lifetimes` is true, each lifetime is checked /// against this list to see if it is already in-scope, or if a definition /// needs to be created for it. in_scope_lifetimes: Vec, /// /// We always store a `modern()` version of the param-name in this /// vector. in_scope_lifetimes: Vec, current_module: NodeId,"} {"_id":"q-en-rust-24852f2f82e14b7fb44ffa9dc4521a37ea054b3db78d3984f0cbf43225865692","text":"// However, since this is a variadic function, C integer promotion rules mean that on // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms). let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?; let fd = FileDesc::new(fd); // Currently the standard library supports Linux 2.6.18 which did not // have the O_CLOEXEC flag (passed above). If we're running on an older // Linux kernel then the flag is just ignored by the OS. After we open // the first file, we check whether it has CLOEXEC set. If it doesn't, // we will explicitly ask for a CLOEXEC fd for every further file we // open, if it does, we will skip that step. // // The CLOEXEC flag, however, is supported on versions of macOS/BSD/etc // that we support, so we only do this on Linux currently. #[cfg(target_os = \"linux\")] fn ensure_cloexec(fd: &FileDesc) -> io::Result<()> { use crate::sync::atomic::{AtomicUsize, Ordering}; const OPEN_CLOEXEC_UNKNOWN: usize = 0; const OPEN_CLOEXEC_SUPPORTED: usize = 1; const OPEN_CLOEXEC_NOTSUPPORTED: usize = 2; static OPEN_CLOEXEC: AtomicUsize = AtomicUsize::new(OPEN_CLOEXEC_UNKNOWN); let need_to_set; match OPEN_CLOEXEC.load(Ordering::Relaxed) { OPEN_CLOEXEC_UNKNOWN => { need_to_set = !fd.get_cloexec()?; OPEN_CLOEXEC.store( if need_to_set { OPEN_CLOEXEC_NOTSUPPORTED } else { OPEN_CLOEXEC_SUPPORTED }, Ordering::Relaxed, ); } OPEN_CLOEXEC_SUPPORTED => need_to_set = false, OPEN_CLOEXEC_NOTSUPPORTED => need_to_set = true, _ => unreachable!(), } if need_to_set { fd.set_cloexec()?; } Ok(()) } #[cfg(not(target_os = \"linux\"))] fn ensure_cloexec(_: &FileDesc) -> io::Result<()> { Ok(()) } ensure_cloexec(&fd)?; Ok(File(fd)) Ok(File(FileDesc::new(fd))) } pub fn file_attr(&self) -> io::Result {"} {"_id":"q-en-rust-249aca76c6eea0abf89141ed23959dca1da0da0411f144a83ab9053a0c46036b","text":" error: constant evaluation is taking a long time --> $DIR/do-not-ice-on-field-access-of-err-type.rs:5:24 | LL | let array = [(); { loop {} }]; | ^^^^^^^ | = note: this lint makes sure the compiler doesn't get stuck due to infinite loops in const eval. If your compilation actually takes a long time, you can safely allow the lint. help: the constant being evaluated --> $DIR/do-not-ice-on-field-access-of-err-type.rs:5:22 | LL | let array = [(); { loop {} }]; | ^^^^^^^^^^^ = note: `#[deny(long_running_const_eval)]` on by default error: aborting due to 1 previous error "} {"_id":"q-en-rust-251bf28d25cd40f969458277db881e01c654ee46611d9bb055d5f0f88eba2002","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":"q-en-rust-25270aca1f3681ea1605bf0c99c3598420823e4f3f32a1de83ae767833d24b21","text":"Some(Node::Item(it)) => item_scope_tag(&it), Some(Node::TraitItem(it)) => trait_item_scope_tag(&it), Some(Node::ImplItem(it)) => impl_item_scope_tag(&it), Some(Node::ForeignItem(it)) => foreign_item_scope_tag(&it), _ => unreachable!(), }; let (prefix, span) = match *region {"} {"_id":"q-en-rust-257d66adff5efa935fdf84d05c983f7147c78da3af28c76577e39fbf689dea78","text":"] [[package]] name = \"compiletest_rs\" version = \"0.5.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"9f737835bfbbe29ed1ff82d5137520338d7ed5bf1a1d4b9c1c7c58bb45b8fa29\" dependencies = [ \"diff\", \"filetime\", \"getopts\", \"libc\", \"log\", \"miow 0.3.3\", \"regex\", \"rustfix 0.5.0\", \"serde\", \"serde_derive\", \"serde_json\", \"tempfile\", \"tester\", \"winapi 0.3.8\", ] [[package]] name = \"constant_time_eq\" version = \"0.1.3\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"q-en-rust-258ac8555ee9126bfaa3a19504c8c8c246164e1eecfa2ac4faf564abb3361c4b","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":"q-en-rust-25ba302cafaeaa15c94e16263f4b4c86a5a491d2e19a46d83280e2e423842549","text":"// to them. We run some optimizations before that, because they may be harder to do on the state // machine than on MIR with async primitives. let optimizations_with_generators: &[&dyn MirPass<'tcx>] = &[ &reveal_all::RevealAll, // has to be done before inlining, since inlined code is in RevealAll mode. &lower_slice_len::LowerSliceLenCalls, // has to be done before inlining, otherwise actual call will be almost always inlined. Also simple, so can just do first &normalize_array_len::NormalizeArrayLen, // has to run after `slice::len` lowering &unreachable_prop::UnreachablePropagation,"} {"_id":"q-en-rust-25c9aea11ca4ac1b68e14353a1dd04dc778cba4ef606289543ed7e91c213529d","text":" #[derive(Clone)] pub struct Struct(A); impl Struct { pub fn new() -> Self { todo!() } } "} {"_id":"q-en-rust-25dc70cb821475ed14b7a9b73c783a317b4cff853d4e26fb0f5e05438b90d1c8","text":"arg.cast_to(Reg { kind: RegKind::Integer, size }); } }; fixup(&mut self.ret); fixup(&mut self.ret, true); for arg in &mut self.args { fixup(arg); fixup(arg, false); } if let PassMode::Indirect(ref mut attrs, _) = self.ret.mode { attrs.set(ArgAttribute::StructRet);"} {"_id":"q-en-rust-25df4c975ef0baa6f3ce7142078a611a8574d823cd815941c1b76726a0413de0","text":" error[E0283]: type annotations needed: cannot satisfy `&(): Marker` --> $DIR/overlap-marker-trait-with-underscore-lifetime.rs:6:6 | LL | impl Marker for &'_ () {} | ^^^^^^ | note: multiple `impl`s satisfying `&(): Marker` found --> $DIR/overlap-marker-trait-with-underscore-lifetime.rs:6:1 | LL | impl Marker for &'_ () {} | ^^^^^^^^^^^^^^^^^^^^^^ LL | impl Marker for &'_ () {} | ^^^^^^^^^^^^^^^^^^^^^^ error[E0283]: type annotations needed: cannot satisfy `&(): Marker` --> $DIR/overlap-marker-trait-with-underscore-lifetime.rs:7:6 | LL | impl Marker for &'_ () {} | ^^^^^^ | note: multiple `impl`s satisfying `&(): Marker` found --> $DIR/overlap-marker-trait-with-underscore-lifetime.rs:6:1 | LL | impl Marker for &'_ () {} | ^^^^^^^^^^^^^^^^^^^^^^ LL | impl Marker for &'_ () {} | ^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0283`. "} {"_id":"q-en-rust-261f1662f9dee88b99f7a1535713614f35c13feabf7ca5f08ecef6038fa2e283","text":" error[E0596]: cannot borrow field of immutable binding as mutable --> $DIR/issue-52240.rs:9:27 | LL | if let (Some(Foo::Bar(ref mut val)), _) = (&arr.get(0), 0) { | ^^^^^^^^^^^ cannot mutably borrow field of immutable binding error: aborting due to previous error For more information about this error, try `rustc --explain E0596`. "} {"_id":"q-en-rust-2656cc6b0172a9991ac736f35737855c5f22f478f343fb0201dcae568b53c764","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":"q-en-rust-2663072dc5b75ce734eb345eb1f0c0a795bc80cbd959edcf491948a6953cde5a","text":" Subproject commit 56444a4545bd71430d64b86b8a71714cfdbe9f5d Subproject commit 8bed48a751562c1c396b361bb6940c677268e997 "} {"_id":"q-en-rust-26711a4be1b30e61729ade6f9c3747487e0bc67e71e9d77952633ac70ac946bb","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":"q-en-rust-2678476562124cd1c9742b18ce499ad1c251bb16a880f03ccac01105139d18c3","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":"q-en-rust-2683d51390a781f634aa37785691fdd525ed5abbd7b39c6175fa52c4cdf6f5f3","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":"q-en-rust-273c7e6bbc3125a4901e982b47f083a82e0bb3bf34ad31bbe719cd431d914e8b","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":"q-en-rust-274bdb2f88d4b68b53f6a75a91aafbe490f45cbaa53dd3e522dfe5cec63142ea","text":" - // MIR for `bar` before Inline + // MIR for `bar` after Inline fn bar(_1: P) -> () { debug _baz => _1; // in scope 0 at $DIR/issue-78442.rs:9:5: 9:9 let mut _0: (); // return place in scope 0 at $DIR/issue-78442.rs:10:3: 10:3 let _2: (); // in scope 0 at $DIR/issue-78442.rs:11:5: 11:17 let mut _3: &fn() {foo}; // in scope 0 at $DIR/issue-78442.rs:11:5: 11:15 let _4: fn() {foo}; // in scope 0 at $DIR/issue-78442.rs:11:5: 11:15 let mut _5: (); // in scope 0 at $DIR/issue-78442.rs:11:5: 11:17 + scope 1 (inlined >::call - shim(fn() {foo})) { // at $DIR/issue-78442.rs:11:5: 11:17 + } bb0: { StorageLive(_2); // scope 0 at $DIR/issue-78442.rs:11:5: 11:17 StorageLive(_3); // scope 0 at $DIR/issue-78442.rs:11:5: 11:15 StorageLive(_4); // scope 0 at $DIR/issue-78442.rs:11:5: 11:15 - _4 = hide_foo() -> [return: bb1, unwind: bb4]; // scope 0 at $DIR/issue-78442.rs:11:5: 11:15 + _4 = hide_foo() -> [return: bb1, unwind: bb3]; // scope 0 at $DIR/issue-78442.rs:11:5: 11:15 // mir::Constant // + span: $DIR/issue-78442.rs:11:5: 11:13 // + literal: Const { ty: fn() -> impl std::ops::Fn<()> {hide_foo}, val: Value(Scalar()) } } bb1: { _3 = &_4; // scope 0 at $DIR/issue-78442.rs:11:5: 11:15 StorageLive(_5); // scope 0 at $DIR/issue-78442.rs:11:5: 11:17 - _2 = as Fn<()>>::call(move _3, move _5) -> [return: bb2, unwind: bb4]; // scope 0 at $DIR/issue-78442.rs:11:5: 11:17 - // mir::Constant - // + span: $DIR/issue-78442.rs:11:5: 11:15 - // + literal: Const { ty: for<'r> extern \"rust-call\" fn(&'r impl std::ops::Fn<()>, ()) -> as std::ops::FnOnce<()>>::Output { as std::ops::Fn<()>>::call}, val: Value(Scalar()) } + _2 = move (*_3)() -> [return: bb5, unwind: bb3]; // scope 1 at $DIR/issue-78442.rs:11:5: 11:17 } bb2: { - StorageDead(_5); // scope 0 at $DIR/issue-78442.rs:11:16: 11:17 - StorageDead(_3); // scope 0 at $DIR/issue-78442.rs:11:16: 11:17 - StorageDead(_4); // scope 0 at $DIR/issue-78442.rs:11:17: 11:18 - StorageDead(_2); // scope 0 at $DIR/issue-78442.rs:11:17: 11:18 - _0 = const (); // scope 0 at $DIR/issue-78442.rs:10:3: 12:2 - drop(_1) -> [return: bb3, unwind: bb5]; // scope 0 at $DIR/issue-78442.rs:12:1: 12:2 + return; // scope 0 at $DIR/issue-78442.rs:12:2: 12:2 } - bb3: { - return; // scope 0 at $DIR/issue-78442.rs:12:2: 12:2 + bb3 (cleanup): { + drop(_1) -> bb4; // scope 0 at $DIR/issue-78442.rs:12:1: 12:2 } bb4 (cleanup): { - drop(_1) -> bb5; // scope 0 at $DIR/issue-78442.rs:12:1: 12:2 + resume; // scope 0 at $DIR/issue-78442.rs:7:1: 12:2 } - bb5 (cleanup): { - resume; // scope 0 at $DIR/issue-78442.rs:7:1: 12:2 + bb5: { + StorageDead(_5); // scope 0 at $DIR/issue-78442.rs:11:16: 11:17 + StorageDead(_3); // scope 0 at $DIR/issue-78442.rs:11:16: 11:17 + StorageDead(_4); // scope 0 at $DIR/issue-78442.rs:11:17: 11:18 + StorageDead(_2); // scope 0 at $DIR/issue-78442.rs:11:17: 11:18 + _0 = const (); // scope 0 at $DIR/issue-78442.rs:10:3: 12:2 + drop(_1) -> [return: bb2, unwind: bb4]; // scope 0 at $DIR/issue-78442.rs:12:1: 12:2 } } "} {"_id":"q-en-rust-2750d36bd60e4329843607a4cca2ad612d1284f95f0bd9a18228861e659fd13d","text":"method_name.name )); let self_ty = self let self_ty_name = self .sess() .source_map() .span_to_snippet(self_ty_span) .unwrap_or_else(|_| self_ty.to_string()); let self_ty_generics_count = match self_ty.kind() { // Get the number of generics the self type has (if an Adt) unless we can determine that // the user has written the self type with generics already which we (naively) do by looking // for a \"<\" in `self_ty_name`. Adt(def, _) if !self_ty_name.contains(\"<\") => self.tcx.generics_of(def.did).count(), _ => 0, }; let self_ty_generics = if self_ty_generics_count > 0 { format!(\"<{}>\", vec![\"_\"; self_ty_generics_count].join(\", \")) } else { String::new() }; lint.span_suggestion( span, \"disambiguate the associated function\", format!(\"<{} as {}>::{}\", self_ty, trait_name, method_name.name,), format!( \"<{}{} as {}>::{}\", self_ty_name, self_ty_generics, trait_name, method_name.name, ), Applicability::MachineApplicable, );"} {"_id":"q-en-rust-276dfe5dc1a0856ef4e3e11b86716b866cae66f759a5a409215316d0d1b1b826","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. // Regression test for issue #25436: permit token-trees to be followed // by sequences, enabling more general parsing. use self::Join::*; #[derive(Debug)] enum Join { Keep(A,B), Skip(A,B), } macro_rules! parse_list { ( < $a:expr; > $($b:tt)* ) => { Keep(parse_item!($a),parse_list!($($b)*)) }; ( $a:tt $($b:tt)* ) => { Skip(parse_item!($a), parse_list!($($b)*)) }; ( ) => { () }; } macro_rules! parse_item { ( $x:expr ) => { $x } } fn main() { let list = parse_list!(<1;> 2 <3;> 4); assert_eq!(\"Keep(1, Skip(2, Keep(3, Skip(4, ()))))\", format!(\"{:?}\", list)); } "} {"_id":"q-en-rust-277376c392f2f64e76207b5620a2f63dfa2ff922de490951e363fc31cf0439a6","text":"let self_ty = self.resolve_vars_if_possible(&trait_ref.self_ty()); // Do not check on infer_types to avoid panic in evaluate_obligation. if self_ty.has_infer_types() { return; } let self_ty = self.tcx.erase_regions(&self_ty); let impls_future = self.tcx.type_implements_trait(( future_trait, self_ty,"} {"_id":"q-en-rust-28660d7ad35e16a99443f5677c5263c373702a2c6833178d55ac136d4b546c51","text":"use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; use rustc_hir::{ Constness, HirId, ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet, Node, TraitCandidate, Constness, ExprKind, HirId, ImplItemKind, ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet, Node, TraitCandidate, TraitItemKind, }; use rustc_index::vec::{Idx, IndexVec}; use rustc_macros::HashStable;"} {"_id":"q-en-rust-288a431e8cfcfd19a121277eaf3c85e0ef8e185d949c50d196e7984a82b053c8","text":"CFG_RUSTC_FLAGS += -g else ifdef CFG_ENABLE_DEBUGINFO_LINES $(info cfg: enabling line number debuginfo (CFG_ENABLE_DEBUGINFO_LINES)) CFG_RUSTC_FLAGS += -C debuginfo=1 CFG_RUSTC_FLAGS += -Cdebuginfo=1 endif ifdef SAVE_TEMPS"} {"_id":"q-en-rust-28951f59bd8177b6af7037aadc2ff1c2f038c29cddac2fc9c6985bbbcb09375d","text":"passes: FxHashSet, css_file_extension: Option, renderinfo: RenderInfo, render_type: RenderType) -> Result<(), Error> { render_type: RenderType, sort_modules_alphabetically: bool) -> Result<(), Error> { let src_root = match krate.src { FileName::Real(ref p) => match p.parent() { Some(p) => p.to_path_buf(),"} {"_id":"q-en-rust-28b1b1feb33038b87da2187f79397a28c71ec3dc01b0f228488ea7b676a6ab98","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":"q-en-rust-28d7680677b4913d5a5b5cc77cca63b7cd7e8e410f7309d03e9186168f25f188","text":"{ let old_len = self.in_scope_lifetimes.len(); let lt_def_names = params.iter().filter_map(|param| match param.kind { GenericParamKind::Lifetime { .. } => Some(param.ident.modern()), GenericParamKind::Lifetime { .. } => Some(ParamName::Plain(param.ident.modern())), _ => None, }); self.in_scope_lifetimes.extend(lt_def_names);"} {"_id":"q-en-rust-28eeabc9014baed96333528c3b1b337441fbbc2953f7df968968f3e5255cd1ea","text":" // compile-flags: -Cdebuginfo=2 // build-pass // Regression test for #87142 // This test needs the above flags and the \"lib\" crate type. #![feature(type_alias_impl_trait, generator_trait, generators)] #![crate_type = \"lib\"] use std::ops::Generator; pub trait GeneratorProviderAlt: Sized { type Gen: Generator<(), Return = (), Yield = ()>; fn start(ctx: Context) -> Self::Gen; } pub struct Context { pub link: Box, } impl GeneratorProviderAlt for () { type Gen = impl Generator<(), Return = (), Yield = ()>; fn start(ctx: Context) -> Self::Gen { move || { match ctx { _ => (), } yield (); } } } "} {"_id":"q-en-rust-28f585a73fbc0d9cdfdeb58feeaf3834b6e789632f72309ef928a5f8e7a01b7c","text":"/// } /// # } /// ``` #[derive(PartialEq, PartialOrd, Eq, Ord, Hash)] #[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub struct CString { inner: Box<[u8]>,"} {"_id":"q-en-rust-29032dce6a71fee52f414cf6ef385bf1038294e2d27192de637d1a5ec0babb7d","text":"print(\"Creating issue:n{}\".format(request)) response = urllib2.urlopen(urllib2.Request( gh_url(), request, request.encode(), { 'Authorization': 'token ' + github_token, 'Content-Type': 'application/json',"} {"_id":"q-en-rust-2915d32c996f53fb3499ec3d763a4c86e2e156f3553fe4981f171083ccb6ebe8","text":"\"lazy_static\", \"log\", \"rls-span\", \"rustc-ap-rustc_ast\", \"rustc-ap-rustc_ast_pretty\", \"rustc-ap-rustc_data_structures\", \"rustc-ap-rustc_errors\", \"rustc-ap-rustc_parse\", \"rustc-ap-rustc_session\", \"rustc-ap-rustc_span\", ] [[package]]"} {"_id":"q-en-rust-2925b4de5ced2974afac7d2de6e17b9f2c67b2a37fccd9696c94a5d346534de8","text":"enum FieldName { UnnamedField(uint), // index // FIXME #6993: change type (and name) from Ident to Name NamedField(ast::Ident), // (Name, not Ident, because struct fields are not macro-hygienic) NamedField(ast::Name), } impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {"} {"_id":"q-en-rust-2944d93694f828ae0cbec4d8d18936b1107edbbbe3a272c9ccc586f8f9db0159","text":"// Try to lookup name in more relaxed fashion for better error reporting. let ident = path.last().unwrap().ident; let candidates = self.lookup_import_candidates(ident, ns, is_expected); let candidates = self.lookup_import_candidates(ident, ns, is_expected) .drain(..) .filter(|ImportSuggestion { did, .. }| { match (did, def.and_then(|def| def.opt_def_id())) { (Some(suggestion_did), Some(actual_did)) => *suggestion_did != actual_did, _ => true, } }) .collect::>(); if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) { let enum_candidates = self.lookup_import_candidates(ident, ns, is_enum_variant);"} {"_id":"q-en-rust-294abfc9d2d760570d603d51b3184b45561070d229fff72686875292fbc4626f","text":"pub struct AnonPipe(FileDesc); pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { syscall! { fn pipe2(fds: *mut c_int, flags: c_int) -> c_int } static INVALID: AtomicBool = AtomicBool::new(false); let mut fds = [0; 2]; // Unfortunately the only known way right now to create atomically set the // CLOEXEC flag is to use the `pipe2` syscall on Linux. This was added in // 2.6.27, however, and because we support 2.6.18 we must detect this // support dynamically. if cfg!(any( target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"linux\", target_os = \"netbsd\", target_os = \"openbsd\", target_os = \"redox\" )) && !INVALID.load(Ordering::SeqCst) { // 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), // The only known way right now to create atomically set the CLOEXEC flag is // to use the `pipe2` syscall. This was added to Linux in 2.6.27, glibc 2.9 // and musl 0.9.3, and some other targets also have it. cfg_if::cfg_if! { if #[cfg(any( target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"linux\", target_os = \"netbsd\", target_os = \"openbsd\", target_os = \"redox\" ))] { cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) })?; Ok((AnonPipe(FileDesc::new(fds[0])), AnonPipe(FileDesc::new(fds[1])))) } else { cvt(unsafe { libc::pipe(fds.as_mut_ptr()) })?; let fd0 = FileDesc::new(fds[0]); let fd1 = FileDesc::new(fds[1]); fd0.set_cloexec()?; fd1.set_cloexec()?; Ok((AnonPipe(fd0), AnonPipe(fd1))) } } cvt(unsafe { libc::pipe(fds.as_mut_ptr()) })?; let fd0 = FileDesc::new(fds[0]); let fd1 = FileDesc::new(fds[1]); fd0.set_cloexec()?; fd1.set_cloexec()?; Ok((AnonPipe(fd0), AnonPipe(fd1))) } impl AnonPipe {"} {"_id":"q-en-rust-294ff737ec17d919ceaa62c9b9d625e7762402b77db3ade4f5160f7e1422766a","text":" error[E0308]: `if` and `else` have incompatible types --> $DIR/issue-82361.rs:10:9 | LL | / if true { LL | | a | | - expected because of this LL | | } else { LL | | b | | ^ | | | | | expected `usize`, found `&usize` | | help: consider dereferencing the borrow: `*b` LL | | }; | |_____- `if` and `else` have incompatible types error[E0308]: `if` and `else` have incompatible types --> $DIR/issue-82361.rs:16:9 | LL | / if true { LL | | 1 | | - expected because of this LL | | } else { LL | | &1 | | -^ | | | | | expected integer, found `&{integer}` | | help: consider removing the `&` LL | | }; | |_____- `if` and `else` have incompatible types error[E0308]: `if` and `else` have incompatible types --> $DIR/issue-82361.rs:22:9 | LL | / if true { LL | | 1 | | - expected because of this LL | | } else { LL | | &mut 1 | | -----^ | | | | | expected integer, found `&mut {integer}` | | help: consider removing the `&mut` LL | | }; | |_____- `if` and `else` have incompatible types error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-2970a76febced250a9869edd7adf728946d0f3d1fd3a1be246fe012e16f6476d","text":"// `match ::std::future::IntoFuture::into_future() { ... }` let into_future_span = self.mark_span_with_reason( DesugaringKind::Await, await_span, dot_await_span, self.allow_into_future.clone(), ); let into_future_expr = self.expr_call_lang_item_fn("} {"_id":"q-en-rust-299ee6c4110d3df1bae50367ffc2520b6b17fbcedeb05bb77abb503cd94e5c9f","text":"# # Note that we don't literally overwrite the gdb.exe binary because it appears # to just use gdborig.exe, so that's the binary we deal with instead. - script: | powershell -Command \"$ProgressPreference = 'SilentlyContinue'; iwr -outf %MINGW_ARCHIVE% %MINGW_URL%/%MINGW_ARCHIVE%\" 7z x -y %MINGW_ARCHIVE% > nul powershell -Command \"$ProgressPreference = 'SilentlyContinue'; iwr -outf 2017-04-20-%MSYS_BITS%bit-gdborig.exe %MINGW_URL%/2017-04-20-%MSYS_BITS%bit-gdborig.exe\" mv 2017-04-20-%MSYS_BITS%bit-gdborig.exe %MINGW_DIR%bingdborig.exe echo ##vso[task.prependpath]%CD%%MINGW_DIR%bin - bash: | set -e curl -o mingw.7z $MINGW_URL/$MINGW_ARCHIVE 7z x -y mingw.7z > /dev/null curl -o $MINGW_DIR/bin/gdborig.exe $MINGW_URL/2017-04-20-${MSYS_BITS}bit-gdborig.exe echo \"##vso[task.prependpath]`pwd`/$MINGW_DIR/bin\" condition: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT'), ne(variables['MINGW_URL'],'')) displayName: Download custom MinGW # Otherwise pull in the MinGW installed on appveyor - script: | echo ##vso[task.prependpath]%MSYS_PATH%mingw%MSYS_BITS%bin # Otherwise install MinGW through `pacman` - bash: | set -e arch=i686 if [ \"$MSYS_BITS\" = \"64\" ]; then arch=x86_64 fi pacman -S --noconfirm --needed mingw-w64-$arch-toolchain mingw-w64-$arch-cmake mingw-w64-$arch-gcc mingw-w64-$arch-python2 echo \"##vso[task.prependpath]$(System.Workfolder)/msys2/mingw$MSYS_BITS/bin\" condition: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT'), eq(variables['MINGW_URL'],'')) displayName: Add MinGW to path displayName: Download standard MinGW # Make sure we use the native python interpreter instead of some msys equivalent # one way or another. The msys interpreters seem to have weird path conversions # baked in which break LLVM's build system one way or another, so let's use the # native version which keeps everything as native as possible. - script: | copy C:Python27amd64python.exe C:Python27amd64python2.7.exe echo ##vso[task.prependpath]C:Python27amd64 - bash: | set -e cp C:/Python27amd64/python.exe C:/Python27amd64/python2.7.exe echo \"##vso[task.prependpath]C:/Python27amd64\" displayName: Prefer the \"native\" Python as LLVM has trouble building with MSYS sometimes condition: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT')) # Note that this is originally from the github releases patch of Ninja - script: | md ninja powershell -Command \"$ProgressPreference = 'SilentlyContinue'; iwr -outf 2017-03-15-ninja-win.zip https://rust-lang-ci-mirrors.s3-us-west-1.amazonaws.com/rustc/2017-03-15-ninja-win.zip\" 7z x -oninja 2017-03-15-ninja-win.zip del 2017-03-15-ninja-win.zip set RUST_CONFIGURE_ARGS=%RUST_CONFIGURE_ARGS% --enable-ninja echo ##vso[task.setvariable variable=RUST_CONFIGURE_ARGS]%RUST_CONFIGURE_ARGS% echo ##vso[task.prependpath]%CD%ninja - bash: | set -e mkdir ninja curl -o ninja.zip https://rust-lang-ci-mirrors.s3-us-west-1.amazonaws.com/rustc/2017-03-15-ninja-win.zip 7z x -oninja ninja.zip rm ninja.zip echo \"##vso[task.setvariable variable=RUST_CONFIGURE_ARGS]$RUST_CONFIGURE_ARGS --enable-ninja\" echo \"##vso[task.prependpath]`pwd`/ninja\" displayName: Download and install ninja condition: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT'))"} {"_id":"q-en-rust-29d269409d8c23e8767e8fdefbcf4bce93aee609a79b4a6b106a001567318817","text":"fn get_str() -> &str; // ILLEGAL, no inputs fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is unclear fn get_mut(&mut self) -> &mut T; // elided fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded"} {"_id":"q-en-rust-29ed7b10cb76cfbe3145e27f01ab487f073d367d997c9a5c854fc076275ec772","text":"-> Option<(Level, LintSource)> { self.id_to_set.get(&id).map(|idx| { self.sets.get_lint_level(lint, *idx) self.sets.get_lint_level(lint, *idx, None) }) } }"} {"_id":"q-en-rust-29fdd2a29c0ad48e1d611d3b11a3e5840b4e853b57a399b7e3c513c8f934e34a","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":"q-en-rust-2a16ca48f1e51fc2cf85744377c1d4074b98de7afebe622c183ca19c1ff3dcb0","text":"fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) { if self.in_root && item.vis.node.is_pub() { self.bang_macros.push(ProcMacroDef { self.macros.push(ProcMacro::Def(ProcMacroDef { span: item.span, function_name: item.ident, }); def_type: ProcMacroDefType::Bang })); } else { let msg = if !self.in_root { \"functions tagged with `#[proc_macro]` must "} {"_id":"q-en-rust-2a1df10ebc8ee2a1f793cbd7e08af8b3ac4c5c5526ea0ada53907a3f279cd917","text":" // check-pass #![feature(allocator_api)] fn main() { Box::new_in((), &std::alloc::Global); } "} {"_id":"q-en-rust-2a30a9df23bf00d2c5b4bf6266795795e52d35676525360045737c0bbd04d66e","text":"= help: add #![feature(generic_associated_types)] to the crate attributes to enable error[E0658]: generic associated types are unstable (see issue #44265) --> $DIR/feature-gate-generic_associated_types.rs:24:5 --> $DIR/feature-gate-generic_associated_types.rs:25:5 | LL | type Pointer2 = Box; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: add #![feature(generic_associated_types)] to the crate attributes to enable error: aborting due to 4 previous errors error[E0658]: where clauses on associated types are unstable (see issue #44265) --> $DIR/feature-gate-generic_associated_types.rs:30:5 | LL | type Assoc where Self: Sized; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: add #![feature(generic_associated_types)] to the crate attributes to enable error: aborting due to 6 previous errors For more information about this error, try `rustc --explain E0658`."} {"_id":"q-en-rust-2a622572d79bdf05f401ff62913dcc951040af27371cfec9381fc6c42b233721","text":"(cfg, _) => cfg.as_deref().cloned(), }; debug!(\"Portability {:?} - {:?} = {:?}\", item.cfg, parent.cfg, cfg); debug!(\"Portability name={:?} {:?} - {:?} = {:?}\", item.name, item.cfg, parent.cfg, cfg); if let Some(ref cfg) = cfg { tags += &tag_html(\"portability\", &cfg.render_long_plain(), &cfg.render_short_html()); }"} {"_id":"q-en-rust-2a63094784530007cefba111037ca9149f0702042068e8aac7cbe158b808dd0e","text":"14 | } | - immutable borrow ends here error: aborting due to 2 previous errors error: aborting due to previous error "} {"_id":"q-en-rust-2a9e6fd569d74dd5789a03965772ddb6893d19799f801a0e117d3aac55393bc4","text":"--> $DIR/privacy-struct-ctor.rs:20:9 | LL | Z; | ^ constructor is not visible here due to private fields help: a tuple struct with a similar name exists | LL | S; | ^ help: possible better candidate is found in another module, you can import it into scope | LL | use m::n::Z; | | | | constructor is not visible here due to private fields | help: a tuple struct with a similar name exists: `S` error[E0423]: expected value, found struct `S` --> $DIR/privacy-struct-ctor.rs:33:5 | LL | S; | ^ constructor is not visible here due to private fields help: possible better candidate is found in another module, you can import it into scope | LL | use m::S; | error[E0423]: expected value, found struct `S2` --> $DIR/privacy-struct-ctor.rs:38:5"} {"_id":"q-en-rust-2abb820698ea4907c22db32c025f3f67631b7a2300c0c0f28a2933978cdd0572","text":" fn main() { // There shall be no suggestions here. In particular not `Ok`. let _ = 读文; //~ ERROR cannot find value `读文` in this scope } "} {"_id":"q-en-rust-2abf58efc91734a969bba1da105ba52739074cadcfef0773077387d7162bd16e","text":"/// You can also use `dbg!()` without a value to just print the /// file and line whenever it's reached. /// /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as /// a tuple (and return it, too): /// /// ``` /// assert_eq!(dbg!(1usize, 2u32), (1, 2)); /// ``` /// /// However, a single argument with a trailing comma will still not be treated /// as a tuple, following the convention of ignoring trailing commas in macro /// invocations. You can use a 1-tuple directly if you need one: /// /// ``` /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple /// ``` /// /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr) /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html /// [`log`]: https://crates.io/crates/log"} {"_id":"q-en-rust-2ae604c63c18fde744b8574f8af047341e8f65c5b567d47c1250bca7b29985f9","text":"--set target.i686-unknown-linux-gnu.linker=clang --build=i686-unknown-linux-gnu --set llvm.ninja=false --set llvm.use-linker=lld --set rust.use-lld=true --set rust.jemalloc ENV SCRIPT python3 ../x.py dist --build $HOSTS --host $HOSTS --target $HOSTS ENV SCRIPT python2.7 ../x.py dist --build $HOSTS --host $HOSTS --target $HOSTS ENV CARGO_TARGET_I686_UNKNOWN_LINUX_GNU_LINKER=clang # This was added when we switched from gcc to clang. It's not clear why this is"} {"_id":"q-en-rust-2af71561abbcdae03cf7611aa462393a8545d11e58198e74baa70ab900b44df7","text":" // edition: 2021 // https://github.com/rust-lang/rust/pull/111761#issuecomment-1557777314 macro_rules! m { () => { extern crate core as std; //~^ ERROR macro-expanded `extern crate` items cannot shadow names passed with `--extern` } } m!(); use std::mem; fn main() {} "} {"_id":"q-en-rust-2af93f7309f417cbf6332e4053cbc641f2f872da791db3d18cea9f8ddaaf1c0f","text":"} #[derive(Diagnostic)] #[diag(passes_lang_item_fn_with_target_feature)] pub struct LangItemWithTargetFeature { #[primary_span] pub attr_span: Span, pub name: Symbol, #[label] pub sig_span: Span, } #[derive(Diagnostic)] #[diag(passes_lang_item_on_incorrect_target, code = \"E0718\")] pub struct LangItemOnIncorrectTarget { #[primary_span]"} {"_id":"q-en-rust-2b07c7aad423d3b0fcbc56624b50e97fcb9bab4c71d54f30c1f6219b6e7eabb5","text":"#![feature(exhaustive_patterns)] #![feature(extend_one)] #![feature(external_doc)] #![feature(fmt_as_str)] #![feature(fn_traits)] #![feature(format_args_nl)] #![feature(gen_future)]"} {"_id":"q-en-rust-2b22f49769970ba6e7a3b3aadab7196ce8ffae48d2a461c2933f910db62bdf80","text":"mod foo { enum Bar { Baz { a: isize } Baz { a: isize }, } } fn f(b: foo::Bar) { //~ ERROR enum `Bar` is private fn f(b: foo::Bar) { //~^ ERROR enum `Bar` is private match b { foo::Bar::Baz { a: _a } => {} //~ ERROR enum `Bar` is private }"} {"_id":"q-en-rust-2b3e279033eac22616805f5e0d3010a45bd2385e158ac11581f0723d81ec2166","text":"pub(crate) const PASSES: &[Pass] = &[ CHECK_CUSTOM_CODE_CLASSES, CHECK_DOC_TEST_VISIBILITY, STRIP_ALIASED_NON_LOCAL, STRIP_HIDDEN, STRIP_PRIVATE, STRIP_PRIV_IMPORTS,"} {"_id":"q-en-rust-2b59ef0484e1934e65811906f31e7a627cf2f93311a4e1d8d301470679300f0d","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":"q-en-rust-2bbdbd53df19e448c08382241d4691096cf4e8eaad65f33a0d5900965b6fd0b9","text":"pub fn emit_feature_warn(diag: &SpanHandler, feature: &str, span: Span, explain: &str) { diag.span_warn(span, explain); // #23973: do not suggest `#![feature(...)]` if we are in beta/stable if option_env!(\"CFG_DISABLE_UNSTABLE_FEATURES\").is_some() { return; } if diag.handler.can_emit_warnings { diag.fileline_help(span, &format!(\"add #![feature({})] to the crate attributes to silence this warning\","} {"_id":"q-en-rust-2bd8880d286e016fca8a735006b9479ee033be45c42029b11737bbdcc4e628c2","text":"#[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":"q-en-rust-2bfa1c344cecde34aaaa115b9dcd2ea690029b6b769142dd18bc04c37d86f332","text":"#[derive(SessionDiagnostic)] #[diag(driver::rlink_no_a_file)] pub(crate) struct RlinkNotAFile; #[derive(SessionDiagnostic)] #[diag(driver::unpretty_dump_fail)] pub(crate) struct UnprettyDumpFail { pub path: String, pub err: String, } "} {"_id":"q-en-rust-2c2a59dbf64a1412f224450ae9df6f3e46305774e5d0fedad748a34d28b229ce","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":"q-en-rust-2c2f11b6104419a4d8792394a71d35b500d66826a69c897371f09b834b98a511","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":"q-en-rust-2c32c5ef490e54c829c4ca6ec47be51322f3f75b19a467b6c6520dfcb8b6498f","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. #![crate_name = \"foo\"] //! Dox // @has src/foo/foo.rs.html // @has foo/index.html '//a/@href' '../src/foo/foo.rs.html' pub mod qux; // @has foo/bar/index.html '//a/@href' '../../src/foo/foo.rs.html' pub mod bar { /// Dox // @has foo/bar/baz/index.html '//a/@href' '../../../src/foo/foo.rs.html' pub mod baz { /// Dox // @has foo/bar/baz/fn.baz.html '//a/@href' '../../../src/foo/foo.rs.html' pub fn baz() { } } /// Dox // @has foo/bar/trait.Foobar.html '//a/@href' '../../src/foo/foo.rs.html' pub trait Foobar { fn dummy(&self) { } } // @has foo/bar/struct.Foo.html '//a/@href' '../../src/foo/foo.rs.html' pub struct Foo { x: i32, y: u32 } // @has foo/bar/fn.prawns.html '//a/@href' '../../src/foo/foo.rs.html' pub fn prawns((a, b): (i32, u32), Foo { x, y }: Foo) { } } /// Dox // @has foo/fn.modfn.html '//a/@href' '../src/foo/foo.rs.html' pub fn modfn() { } "} {"_id":"q-en-rust-2c5d80a37735cf3602143d3a4e00d9cb37f5e1d90edceab981f6b985088a6c3a","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":"q-en-rust-2c8142b03da5f25f7cdae5dc1859df071153f87675d998b18b03ef0357480269","text":" use std::error::Error; use std::fmt; use super::InterpCx; use crate::interpret::{ConstEvalErr, InterpErrorInfo, Machine}; #[derive(Clone, Debug)] pub enum ConstEvalError { NeedsRfc(String), ConstAccessesStatic, } impl<'tcx> Into> for ConstEvalError { fn into(self) -> InterpErrorInfo<'tcx> { err_unsup!(Unsupported(self.to_string())).into() } } impl fmt::Display for ConstEvalError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::ConstEvalError::*; match *self { NeedsRfc(ref msg) => { write!(f, \"\"{}\" needs an rfc before being allowed inside constants\", msg) } ConstAccessesStatic => write!(f, \"constant accesses static\"), } } } impl Error for ConstEvalError {} /// Turn an interpreter error into something to report to the user. /// As a side-effect, if RUSTC_CTFE_BACKTRACE is set, this prints the backtrace. /// Should be called only if the error is actually going to to be reported! pub fn error_to_const_error<'mir, 'tcx, M: Machine<'mir, 'tcx>>( ecx: &InterpCx<'mir, 'tcx, M>, mut error: InterpErrorInfo<'tcx>, ) -> ConstEvalErr<'tcx> { error.print_backtrace(); let stacktrace = ecx.generate_stacktrace(None); ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span } } "} {"_id":"q-en-rust-2cb1333964a98c31b7dc173032127bef36071f31d30cfd9f2aaf298f222b1db8","text":"// Recreate the edges in the graph that are still clean. let mut clean_work_products = FxHashSet(); let mut dirty_work_products = FxHashSet(); // incomplete; just used to suppress debug output let mut extra_edges = vec![]; for (source, targets) in &edge_map { for target in targets { // If the target is dirty, skip the edge. If this is an edge // that targets a work-product, we can print the blame // information now. if let Some(blame) = dirty_raw_nodes.get(target) { if let DepNode::WorkProduct(ref wp) = *target { if tcx.sess.opts.debugging_opts.incremental_info { if dirty_work_products.insert(wp.clone()) { // It'd be nice to pretty-print these paths better than just // using the `Debug` impls, but wev. println!(\"incremental: module {:?} is dirty because {:?} changed or was removed\", wp, blame.map_def(|&index| { Some(directory.def_path_string(tcx, index)) }).unwrap()); } } } continue; } // If the source is dirty, the target will be dirty. assert!(!dirty_raw_nodes.contains_key(source)); // Retrace the source -> target edges to def-ids and then // create an edge in the graph. Retracing may yield none if // some of the data happens to have been removed; this ought // to be impossible unless it is dirty, so we can unwrap. let source_node = retraced.map(source).unwrap(); let target_node = retraced.map(target).unwrap(); let _task = tcx.dep_graph.in_task(target_node); tcx.dep_graph.read(source_node); if let DepNode::WorkProduct(ref wp) = *target { clean_work_products.insert(wp.clone()); } process_edges(tcx, source, target, &edge_map, &directory, &retraced, &dirty_raw_nodes, &mut clean_work_products, &mut dirty_work_products, &mut extra_edges); } } // Subtle. Sometimes we have intermediate nodes that we can't recreate in the new graph. // This is pretty unusual but it arises in a scenario like this: // // Hir(X) -> Foo(Y) -> Bar // // Note that the `Hir(Y)` is not an input to `Foo(Y)` -- this // almost never happens, but can happen in some obscure // scenarios. In that case, if `Y` is removed, then we can't // recreate `Foo(Y)` (the def-id `Y` no longer exists); what we do // then is to push the edge `Hir(X) -> Bar` onto `extra_edges` // (along with any other targets of `Foo(Y)`). We will then add // the edge from `Hir(X)` to `Bar` (or, if `Bar` itself cannot be // recreated, to the targets of `Bar`). while let Some((source, target)) = extra_edges.pop() { process_edges(tcx, source, target, &edge_map, &directory, &retraced, &dirty_raw_nodes, &mut clean_work_products, &mut dirty_work_products, &mut extra_edges); } // Add in work-products that are still clean, and delete those that are // dirty. reconcile_work_products(tcx, work_products, &clean_work_products);"} {"_id":"q-en-rust-2cb1e25fd71e3b75e6ab7485d4e10aa83719946ee63dc1d24dc12812b7372cde","text":"/// # Examples /// /// ``` /// #![feature(inner_deref)] /// let x: Result = Ok(\"hello\".to_string()); /// let y: Result<&str, &u32> = Ok(\"hello\"); /// assert_eq!(x.as_deref(), y);"} {"_id":"q-en-rust-2cf2699a521c8106afe9b955c86e9dc9c6cedead94ad826fa327b0e73b264b15","text":"last = match *token { TtToken(sp, MatchNt(ref name, ref frag_spec, _, _)) => { // ii. If T is a simple NT, look ahead to the next token T' in // M. let next_token = match tokens.peek() { // If T' closes a complex NT, replace T' with F Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtSequence(sp, _)) => { cx.span_err(sp, &format!(\"`${0}:{1}` is followed by a sequence repetition, which is not allowed for `{1}` fragments\", name.as_str(), frag_spec.as_str()) // M. If T' is in the set FOLLOW(NT), continue. Else; reject. if can_be_followed_by_any(frag_spec.as_str()) { continue } else { let next_token = match tokens.peek() { // If T' closes a complex NT, replace T' with F Some(&&TtToken(_, CloseDelim(_))) => follow.clone(), Some(&&TtToken(_, ref tok)) => tok.clone(), Some(&&TtSequence(sp, _)) => { // Be conservative around sequences: to be // more specific, we would need to // consider FIRST sets, but also the // possibility that the sequence occurred // zero times (in which case we need to // look at the token that follows the // sequence, which may itself a sequence, // and so on). cx.span_err(sp, &format!(\"`${0}:{1}` is followed by a sequence repetition, which is not allowed for `{1}` fragments\", name.as_str(), frag_spec.as_str()) ); Eof }, // die next iteration Some(&&TtDelimited(_, ref delim)) => delim.close_token(), // else, we're at the end of the macro or sequence None => follow.clone() }; let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. match (&next_token, is_in_follow(cx, &next_token, frag_spec.as_str())) { (_, Err(msg)) => { cx.span_err(sp, &msg); continue Eof }, // die next iteration Some(&&TtDelimited(_, ref delim)) => delim.close_token(), // else, we're at the end of the macro or sequence None => follow.clone() }; let tok = if let TtToken(_, ref tok) = *token { tok } else { unreachable!() }; // If T' is in the set FOLLOW(NT), continue. Else, reject. match (&next_token, is_in_follow(cx, &next_token, frag_spec.as_str())) { (_, Err(msg)) => { cx.span_err(sp, &msg); continue } (&Eof, _) => return Some((sp, tok.clone())), (_, Ok(true)) => continue, (next, Ok(false)) => { cx.span_err(sp, &format!(\"`${0}:{1}` is followed by `{2}`, which is not allowed for `{1}` fragments\", name.as_str(), frag_spec.as_str(), token_to_string(next))); continue }, } (&Eof, _) => return Some((sp, tok.clone())), (_, Ok(true)) => continue, (next, Ok(false)) => { cx.span_err(sp, &format!(\"`${0}:{1}` is followed by `{2}`, which is not allowed for `{1}` fragments\", name.as_str(), frag_spec.as_str(), token_to_string(next))); continue }, } }, TtSequence(sp, ref seq) => {"} {"_id":"q-en-rust-2cf932a87dc73fad9ca6e1346081000ef2f1420c85f14b48e3285de5f09fc34f","text":"// In theory, any zero-sized value could be borrowed // mutably without consequences. However, only &mut [] // is allowed right now, and only in functions. if self.const_kind == Some(hir::ConstContext::Static(hir::Mutability::Mut)) { // Inside a `static mut`, &mut [...] is also allowed. match ty.kind() { ty::Array(..) | ty::Slice(_) => {} _ => return Err(Unpromotable), } } else if let ty::Array(_, len) = ty.kind() { if let ty::Array(_, len) = ty.kind() { // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a // const context which seems unnecessary given that this is merely a ZST. match len.try_eval_usize(self.tcx, self.param_env) {"} {"_id":"q-en-rust-2d16c3983ad9a2827c23e0b6d3e033700156f0ed90fd99ad1592defa7883b4c0","text":"unsafe { Self::from_inner(Box::leak(x).into()) } } /// Constructs a new `Arc` using a closure `data_fn` that has access to /// a weak reference to the constructing `Arc`. /// Constructs a new `Arc` while giving you a `Weak` to the allocation, /// to allow you to construct a `T` which holds a weak pointer to itself. /// /// Generally, a structure circularly referencing itself, either directly or /// indirectly, should not hold a strong reference to prevent a memory leak. /// In `data_fn`, initialization of `T` can make use of the weak reference /// by cloning and storing it inside `T` for use at a later time. /// indirectly, should not hold a strong reference to itself to prevent a memory leak. /// Using this function, you get access to the weak pointer during the /// initialization of `T`, before the `Arc` is created, such that you can /// clone and store it inside the `T`. /// /// Since the new `Arc` is not fully-constructed until /// `Arc::new_cyclic` returns, calling [`upgrade`] on the weak /// reference inside `data_fn` will fail and result in a `None` value. /// `new_cyclic` first allocates the managed allocation for the `Arc`, /// then calls your closure, giving it a `Weak` to this allocation, /// and only afterwards completes the construction of the `Arc` by placing /// the `T` returned from your closure into the allocation. /// /// Since the new `Arc` is not fully-constructed until `Arc::new_cyclic` /// returns, calling [`upgrade`] on the weak reference inside your closure will /// fail and result in a `None` value. /// /// # Panics /// /// If `data_fn` panics, the panic is propagated to the caller, and the /// temporary [`Weak`] is dropped normally. /// /// # Example /// /// ``` /// #![allow(dead_code)] /// use std::sync::{Arc, Weak};"} {"_id":"q-en-rust-2d39ebeedb3e91fc3ea1537d80743d6072ecce5986725dee9d3b805573c22700","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:derive-two-attrs.rs #![feature(use_extern_macros)] extern crate derive_two_attrs as foo; use foo::A; #[derive(A)] #[b] #[b] struct B; fn main() {} "} {"_id":"q-en-rust-2d7566fabead5ffb7c74c74c5b5241e750698fd6a4bdf170901fad8038939819","text":" error[E0308]: mismatched types --> $DIR/issue-90213-expected-boxfuture-self-ice.rs:9:19 | LL | Self::foo(None) | ^^^^ expected struct `Box`, found enum `Option` | = note: expected struct `Box>` found enum `Option<_>` = note: for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html help: store this in the heap by calling `Box::new` | LL | Self::foo(Box::new(None)) | +++++++++ + error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-2dafc6ef187b224231001d720e8c96d5b3cd884d4b683c6d0532b7b16926d180","text":"intravisit::walk_foreign_item(self, it); } fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) { // We will call `add_id` when we walk // the `StmtKind`. The outer statement itself doesn't // define the lint levels. intravisit::walk_stmt(self, e); fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) { self.add_id(s.hir_id); intravisit::walk_stmt(self, s); } fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {"} {"_id":"q-en-rust-2dd11a72e7f202b6ea42b04aaa4247ec56d78a37c1c2ef391d78f8c11a239dba","text":"}; let msg = match name { NamedField(name) => format!(\"field `{}` of {} is private\", token::get_ident(name), struct_desc), token::get_name(name), struct_desc), UnnamedField(idx) => format!(\"field #{} of {} is private\", idx + 1, struct_desc), };"} {"_id":"q-en-rust-2e0014a4def1d07a5768533842e892892c8fcd9ad282d235ca4585acef81eaf9","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":"q-en-rust-2e06451544aca8f1387faa5a9e04a6c5dbcce88d3cca1bb44475359992518604","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":"q-en-rust-2e252861f8299b49feaccb8c8d7e74b3113bc2becf9dafbc21204e16894d0eaa","text":"G(); H(); I(); K()(); }"} {"_id":"q-en-rust-2e2b0921605d5b61056cfbc48cc884d7ecfd228ec5afae0b786362ca7ead0db9","text":"ENV HOSTS=armv7-unknown-linux-gnueabihf ENV RUST_CONFIGURE_ARGS --enable-full-tools --disable-docs ENV RUST_CONFIGURE_ARGS --enable-full-tools --enable-profiler --disable-docs ENV SCRIPT python3 ../x.py dist --host $HOSTS --target $HOSTS"} {"_id":"q-en-rust-2e35518915bc37089ef6395747a441ee0a0c2a0ffcd18b58cf53e8ca07ea3300","text":" // check-pass #![feature(associated_type_defaults)] use std::io::Read; trait View { type Deserializers: Deserializer; type RequestParams = DefaultRequestParams; } struct DefaultRequestParams; trait Deserializer { type Item; fn deserialize(r: impl Read) -> Self::Item; } fn main() {} "} {"_id":"q-en-rust-2e520138dd78ab5303fa1b34415ed2b73529a2799503efe5895a350554bb86da","text":"ty::Ref(..) | ty::RawPtr(_) => { return self.field(cx, index).llvm_type(cx); } ty::Adt(def, _) if def.is_box() => { // only wide pointer boxes are handled as pointers // thin pointer boxes with scalar allocators are handled by the general logic below ty::Adt(def, substs) if def.is_box() && cx.layout_of(substs.type_at(1)).is_zst() => { let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty()); return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate); }"} {"_id":"q-en-rust-2e5a9a72cc06b45287694555911af37fa432f6045c3e096350cbaca0f5a0fad4","text":"fn main() { static foo: Fn() -> u32 = || -> u32 { //~^ ERROR: mismatched types //~| ERROR: `std::ops::Fn() -> u32 + 'static: std::marker::Sized` is not satisfied 0 }; }"} {"_id":"q-en-rust-2e6f87101c10fc22d5e66d8a2334b7c5c471456b8d5bb70fa1ed8c3bd52ac1f2","text":"= note: the only supported types are integers, `bool` and `char` = help: more complex types are supported with `#![feature(adt_const_params)]` error: aborting due to 7 previous errors error: `&dyn for<'a> Foo<'a>` is forbidden as the type of a const generic parameter --> $DIR/unusual-rib-combinations.rs:29:21 | LL | struct Bar Foo<'a>)>; | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the only supported types are integers, `bool` and `char` = help: more complex types are supported with `#![feature(adt_const_params)]` error: aborting due to 9 previous errors Some errors have detailed explanations: E0106, E0214, E0308. Some errors have detailed explanations: E0106, E0214, E0308, E0771. For more information about an error, try `rustc --explain E0106`."} {"_id":"q-en-rust-2e704ed255e8ea3a352b473bd48aab2c1c087509f9540ccfa1013a1e3b63c46f","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":"q-en-rust-2eb2c20e570184defa723b669abc6c4e2c36c70261e2d453a5d17814d52add94","text":"where A: DoubleEndedIterator + ExactSizeIterator, B: DoubleEndedIterator + ExactSizeIterator; fn fold(self, init: Acc, f: F) -> Acc where F: FnMut(Acc, Self::Item) -> Acc; // This has the same safety requirements as `Iterator::__iterator_get_unchecked` unsafe fn get_unchecked(&mut self, idx: usize) -> ::Item where"} {"_id":"q-en-rust-2ed0ef1b999959f22ca146b36e3f5cdc79fc2c4a5b7dc05a97cdfe955981b669","text":"fn visit_impl_item(&mut self, ii: &'a ImplItem) { let def_data = match ii.node { ImplItemKind::Method(MethodSig { header: FnHeader { asyncness: IsAsync::Async { closure_id, return_impl_trait_id, }, .. }, .. }, ..) => { header: ref header @ FnHeader { asyncness: IsAsync::Async { .. }, .. }, ref decl, }, ref body) => { return self.visit_async_fn( ii.id, closure_id, return_impl_trait_id, ii.ident.name, ii.span, |this| visit::walk_impl_item(this, ii) header, &ii.generics, decl, body, ) } ImplItemKind::Method(..) | ImplItemKind::Const(..) =>"} {"_id":"q-en-rust-2ed13aaefab1e3fd23282e461d8caa408225ce890a0e60077640db5ea2a142f5","text":"let path = cfg_file.unwrap_or_else(|| src_path.join(\"config.toml\")); let settings = format!( \"# Includes one of the default files in src/bootstrap/defaultsn profile = \"{}\"n\", profile profile = \"{}\"n changelog-seen = {}n\", profile, VERSION ); t!(fs::write(path, settings));"} {"_id":"q-en-rust-2ef5b5e2eb60692e1eab8ad0a38d69421c14112e6faef323a92f5fed30ddeff0","text":"use std::path::PathBuf; pub static BINARY_PATH: OnceLock = OnceLock::new(); pub const RUN_OPTION: &str = \"*doctest-inner-test\"; pub const BIN_OPTION: &str = \"*doctest-bin-path\"; pub const RUN_OPTION: &str = \"RUSTDOC_DOCTEST_RUN_NB_TEST\"; #[allow(unused)] pub fn doctest_path() -> Option<&'static PathBuf> {{"} {"_id":"q-en-rust-2f230e27f0db34a5ef61a1df4b00ace56396e84f47d9b206485b20a47dd3a763","text":" fn hello() -> Vec { Vec::::mew() //~^ ERROR no function or associated item named `mew` found for struct `Vec` in the current scope } fn main() {} "} {"_id":"q-en-rust-2f247b44ee56243494d0b9a4c3bb6482c0a9ed4200a41ca1e59ade94bfcda56a","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. //compile-flags: -Z borrowck=mir #![feature(slice_patterns)] fn mut_head_tail<'a, A>(v: &'a mut [A]) -> Option<(&'a mut A, &'a mut [A])> { match *v { [ref mut head, ref mut tail..] => { Some((head, tail)) } [] => None } } fn main() { let mut v = [1,2,3,4]; match mut_head_tail(&mut v) { None => {}, Some((h,t)) => { *h = 1000; t.reverse(); } } } "} {"_id":"q-en-rust-2f5bc0c189246f20c47a42d98bf8c96ad23df9f1512c62e19e48a684ee31e93c","text":" error[E0425]: cannot find value `bogus` in this scope --> $DIR/issue-59134-1.rs:8:37 | LL | const CONST: Self::MyType = bogus.field; | ^^^^^ not found in this scope error: aborting due to previous error For more information about this error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-2f8986280a5719021b58695ab0120d53d203db96f907ebeb1dec3350131a32ae","text":"} declare_lint! { /// The `function_item_references` lint detects function references that are /// formatted with [`fmt::Pointer`] or transmuted. /// /// [`fmt::Pointer`]: https://doc.rust-lang.org/std/fmt/trait.Pointer.html /// /// ### Example /// /// ```rust /// fn foo() { } /// /// fn main() { /// println!(\"{:p}\", &foo); /// } /// ``` /// /// {{produces}} /// /// ### Explanation /// /// Taking a reference to a function may be mistaken as a way to obtain a /// pointer to that function. This can give unexpected results when /// formatting the reference as a pointer or transmuting it. This lint is /// issued when function references are formatted as pointers, passed as /// arguments bound by [`fmt::Pointer`] or transmuted. pub FUNCTION_ITEM_REFERENCES, Warn, \"suggest casting to a function pointer when attempting to take references to function items\", } declare_lint! { /// The `uninhabited_static` lint detects uninhabited statics. /// /// ### Example"} {"_id":"q-en-rust-2f900f0f14e5ccfd5d40fc499353f02925d3491f9a7a8dd6364c06081835b392","text":"/// If a file already exists in the source_map with the same id, that file is returned /// unmodified pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc { self.try_new_source_file(filename, src) .unwrap_or_else(|OffsetOverflowError| { eprintln!(\"fatal error: rustc does not support files larger than 4GB\"); errors::FatalError.raise() }) } fn try_new_source_file( &self, filename: FileName, src: String ) -> Result, OffsetOverflowError> { let start_pos = self.next_start_pos(); // The path is used to determine the directory for loading submodules and"} {"_id":"q-en-rust-2f970cf50a39bd9535d54ce7a139f40493f65445dc2c7e85715fdbbc2e7b05f8","text":"CONST_EVALUATABLE_UNCHECKED, INEFFECTIVE_UNSTABLE_TRAIT_IMPL, UNINHABITED_STATIC, FUNCTION_ITEM_REFERENCES, ] }"} {"_id":"q-en-rust-2fb54a6d38e3f4f9f3d2ad97e2e9f93c545fdd89cc28c9128823c742bbb17c10","text":"/// f.read_to_string(&mut buf).unwrap(); /// assert_eq!(&buf, hello); /// ``` #[unstable(feature = \"seek_rewind\", issue = \"85149\")] #[stable(feature = \"seek_rewind\", since = \"1.55.0\")] fn rewind(&mut self) -> Result<()> { self.seek(SeekFrom::Start(0))?; Ok(())"} {"_id":"q-en-rust-2fc8634aa8d5592d3b0a0eebc4a531fdb462d51323ce3210f9c820e1a5009efd","text":"def update_submodules(self): \"\"\"Update submodules\"\"\" if (not os.path.exists(os.path.join(self.rust_root, \".git\"))) or self.get_toml('submodules') == \"false\": has_git = os.path.exists(os.path.join(self.rust_root, \".git\")) # This just arbitrarily checks for cargo, but any workspace member in # a submodule would work. has_submodules = os.path.exists(os.path.join(self.rust_root, \"src/tools/cargo/Cargo.toml\")) if not has_git and not has_submodules: print(\"This is not a git repository, and the requisite git submodules were not found.\") print(\"If you downloaded the source from https://github.com/rust-lang/rust/releases,\") print(\"those sources will not work. Instead, consider downloading from the source\") print(\"releases linked at\") print(\"https://forge.rust-lang.org/infra/other-installation-methods.html#source-code\") print(\"or clone the repository at https://github.com/rust-lang/rust/.\") raise SystemExit(1) if not has_git or self.get_toml('submodules') == \"false\": return default_encoding = sys.getdefaultencoding()"} {"_id":"q-en-rust-303cb0d8e7366ff92f687b14352362d47fe0638634779ad5fd2701e9df36a3d9","text":"hasher.finish() }; let end_pos = start_pos.to_usize() + src.len(); if end_pos > u32::max_value() as usize { return Err(OffsetOverflowError); } let (lines, multibyte_chars, non_narrow_chars) = analyze_source_file::analyze_source_file(&src[..], start_pos); SourceFile { Ok(SourceFile { name, name_was_remapped, unmapped_path: Some(unmapped_path),"} {"_id":"q-en-rust-306ee3fc85f0757d1327e5d3235f055fd7c71181d507a0b5b9a0017b7e518664","text":"fn main() { let x = Foo; x.zero(0) //~ ERROR this function takes 0 parameters but 1 parameter was supplied //~^ NOTE expected 0 parameters .one() //~ ERROR this function takes 1 parameter but 0 parameters were supplied //~^ NOTE the following parameter type was expected //~| NOTE expected 1 parameter .two(0); //~ ERROR this function takes 2 parameters but 1 parameter was supplied //~^ NOTE the following parameter types were expected //~| NOTE expected 2 parameters let y = Foo; y.zero()"} {"_id":"q-en-rust-31295d6ea3693e0e380b22f6f34d39279d239c878be30624c20160da2a300f52","text":" error: expected `;`, found `#` --> $DIR/multiple-tail-expr-behind-cfg.rs:5:64 | LL | #[cfg(feature = \"validation\")] | ------------------------------ only `;` terminated statements or tail expressions are allowed after this attribute LL | [1, 2, 3].iter().map(|c| c.to_string()).collect::() | ^ expected `;` here LL | #[cfg(not(feature = \"validation\"))] | - unexpected token | help: add `;` here | LL | [1, 2, 3].iter().map(|c| c.to_string()).collect::(); | + help: alternatively, consider surrounding the expression with a block | LL | { [1, 2, 3].iter().map(|c| c.to_string()).collect::() } | + + help: it seems like you are trying to provide different expressions depending on `cfg`, consider using `if cfg!(..)` | LL ~ if cfg!(feature = \"validation\") { LL ~ [1, 2, 3].iter().map(|c| c.to_string()).collect::() LL ~ } else if cfg!(not(feature = \"validation\")) { LL ~ String::new() LL + } | error: expected `;`, found `#` --> $DIR/multiple-tail-expr-behind-cfg.rs:12:64 | LL | #[attr] | ------- only `;` terminated statements or tail expressions are allowed after this attribute LL | [1, 2, 3].iter().map(|c| c.to_string()).collect::() | ^ expected `;` here LL | #[attr] | - unexpected token | help: add `;` here | LL | [1, 2, 3].iter().map(|c| c.to_string()).collect::(); | + help: alternatively, consider surrounding the expression with a block | LL | { [1, 2, 3].iter().map(|c| c.to_string()).collect::() } | + + error: cannot find attribute `attr` in this scope --> $DIR/multiple-tail-expr-behind-cfg.rs:13:7 | LL | #[attr] | ^^^^ error: aborting due to 3 previous errors "} {"_id":"q-en-rust-3164e4b0dd778a958f190c7cf428137f4ea7d3ded37a691a4bf0f5c8e1535045","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. #![deny(unused_variable)] fn main() { for _ in range(1i, 101) { let x = (); //~ ERROR: unused variable: `x` match () { a => {} //~ ERROR: unused variable: `a` } } } "} {"_id":"q-en-rust-31743379056549de78800982bc85b35314576bbdff33beb7ec2dbc180b1a5fee","text":"signature. Each type parameter must be explicitly declared, in an angle-bracket-enclosed, comma-separated list following the function name. ```{.ignore} fn iter(seq: &[T], f: F) where T: Copy, F: Fn(T) { for elt in seq { f(*elt); } } fn map(seq: &[T], f: F) -> Vec where T: Copy, U: Copy, F: Fn(T) -> U { let mut acc = vec![]; for elt in seq { acc.push(f(*elt)); } acc } ```rust,ignore // foo is generic over A and B fn foo(x: A, y: B) { ``` Inside the function signature and body, the name of the type parameter can be used as a type name. [Trait](#traits) bounds can be specified for type parameters to allow methods with that trait to be called on values of that type. This is specified using the `where` syntax, as in the above example. specified using the `where` syntax: ```rust,ignore fn foo(x: T) where T: Debug { ``` When a generic function is referenced, its type is instantiated based on the context of the reference. For example, calling the `iter` function defined"} {"_id":"q-en-rust-31a482838953ba040461eda0330f59950e6444eae9fa911cf4460fe468998f78","text":"#![allow(unused_variables)]; //~ ERROR expected item, found `;` //~^ ERROR `main` function fn foo() {} //~^ ERROR `main` function "} {"_id":"q-en-rust-31bc286ea1296f1e512dc52a082113853e6658e2a43f7eec549d388d003c583c","text":"See [LICENSE-APACHE](LICENSE-APACHE), [LICENSE-MIT](LICENSE-MIT), and [COPYRIGHT](COPYRIGHT) for details. ## Trademark [trademark]: #trademark The Rust programming language is an open source, community project governed by a core team. It is also sponsored by the Mozilla Foundation (“Mozilla”), which owns and protects the Rust and Cargo trademarks and logos (the “Rust Trademarks”). If you want to use these names or brands, please read the [media guide][media-guide]. Third-party logos may be subject to third-party copyrights and trademarks. See [Licenses][policies-licenses] for details. [media-guide]: https://www.rust-lang.org/policies/media-guide [policies-licenses]: https://www.rust-lang.org/policies/licenses "} {"_id":"q-en-rust-31c82bd52e296b302272daf5a525f53e50fe81d431af17ce327d15fc6d71bc8f","text":"#[rustc_const_unstable(feature = \"const_waker\", issue = \"102012\")] pub const fn build(self) -> Context<'a> { let ContextBuilder { waker, local_waker, ext, _marker, _marker2 } = self; Context { waker, local_waker, ext, _marker, _marker2 } Context { waker, local_waker, ext: AssertUnwindSafe(ext), _marker, _marker2 } } }"} {"_id":"q-en-rust-320449cadd2030f3a3085dff2b2b10ab709068e1e1f2cb21dd82b153e84dfb40","text":"/// } /// } /// ``` fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> { let dot_await_span = expr.span.shrink_to_hi().to(await_span); fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> { let full_span = expr.span.to(dot_await_span); match self.generator_kind { Some(hir::GeneratorKind::Async(_)) => {} Some(hir::GeneratorKind::Gen) | None => { let mut err = struct_span_err!( self.sess, await_span, dot_await_span, E0728, \"`await` is only allowed inside `async` functions and blocks\" ); err.span_label(await_span, \"only allowed inside `async` functions and blocks\"); err.span_label(dot_await_span, \"only allowed inside `async` functions and blocks\"); if let Some(item_sp) = self.current_item { err.span_label(item_sp, \"this is not `async`\"); }"} {"_id":"q-en-rust-32237fca4266af04f5381591aad1922d7eb5f3cc3748b87150b7c15e1ffc7ccc","text":" // compile-flags:--test // run-pass // ignore-emscripten no subprocess support use std::fmt; use std::fmt::{Display, Formatter}; pub struct A(Vec); impl Display for A { fn fmt(&self, _f: &mut Formatter<'_>) -> fmt::Result { self.0[0]; Ok(()) } } #[test] fn main() { let result = std::panic::catch_unwind(|| { let a = A(vec![]); eprintln!(\"{}\", a); }); assert!(result.is_err()); } "} {"_id":"q-en-rust-32454ea1b084e69d2c6c0a8d5b583f44b201514a1db113569f75992f5e863865","text":" error: using function pointers as const generic parameters is forbidden --> $DIR/default-ty-closure.rs:3:20 | LL | struct X; | ^^^^ | = note: the only supported types are integers, `bool` and `char` error: aborting due to 1 previous error "} {"_id":"q-en-rust-32584430a49eeb818905c7efb476b1de52a9c828d7ce167f0bb5aecbed41c347","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-prefer-dynamic #[crate_id = \"collections#0.10-pre\"]; #[crate_type = \"dylib\"]; "} {"_id":"q-en-rust-329c8e0b133c893614989f2c2af3b4a19d8b1a0b35710238739991cce098b844","text":"let err = LifetimeOutliveErr { span: *span }; let mut diag = self.infcx.tcx.sess.create_err(err); let fr_name = self.give_region_a_name(*fr).unwrap(); // In certain scenarios, such as the one described in issue #118021, // we might encounter a lifetime that cannot be named. // These situations are bound to result in errors. // To prevent an immediate ICE, we opt to create a dummy name instead. let fr_name = self.give_region_a_name(*fr).unwrap_or(RegionName { name: kw::UnderscoreLifetime, source: RegionNameSource::Static, }); fr_name.highlight_region_name(&mut diag); let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap(); outlived_fr_name.highlight_region_name(&mut diag);"} {"_id":"q-en-rust-32d63d7c04ad7d9a01ced489295c1a5d1e7393be4004641a91c49c9f367a86ed","text":"participle: &'tcx str, name_list: DiagSymbolList, #[subdiagnostic] change_fields_suggestion: ChangeFieldsToBeOfUnitType, change_fields_suggestion: ChangeFields, #[subdiagnostic] parent_info: Option>, #[subdiagnostic]"} {"_id":"q-en-rust-333d4eb455abb098df259f3c75939d763ec7b6601d8073f52e7dc99fa77dd4cc","text":"[78429]: https://github.com/rust-lang/rust/pull/78429 [82733]: https://github.com/rust-lang/rust/pull/82733 [82594]: https://github.com/rust-lang/rust/pull/82594 [79078]: https://github.com/rust-lang/rust/pull/79078 [cargo/9181]: https://github.com/rust-lang/cargo/pull/9181 [`char::MAX`]: https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.MAX [`char::REPLACEMENT_CHARACTER`]: https://doc.rust-lang.org/std/primitive.char.html#associatedconstant.REPLACEMENT_CHARACTER"} {"_id":"q-en-rust-336756ea458370dfc860f898b01ad5760d576aaec7849d3f7231ad91b956dce6","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":"q-en-rust-33a0afde46b5f7b5e98917d029ef55350493e828453263c30816846806702787","text":"// We only want to handle exclusive (`..`) ranges, // which are represented as `ExprKind::Struct`. if let ExprKind::Struct(_, eps, _) = &parent_expr.node { debug_assert_eq!(eps.len(), 2); if eps.len() != 2 { return false; } // We can suggest using an inclusive range // (`..=`) instead only if it is the `end` that is // overflowing and only by 1."} {"_id":"q-en-rust-33cd26d774530f179d839c5119d120ce461d3e74bb4b365d061ef7ce0b616300","text":"fn resolve( &self, path_str: &str, disambiguator: Option<&str>, ns: Namespace, current_item: &Option, parent_id: Option,"} {"_id":"q-en-rust-33e19b7d0de75e2cf1c51a5119b9f9cf7131dcccf5cabfd30ce5685b6c2dee1f","text":" // issue: rust-lang/rust#127868 fn main() { let a = [[[[[[[[[[[[[[[[[[[[1, {, (, [,; } //~ ERROR mismatched closing delimiter: `}` //~ ERROR this file contains an unclosed delimiter "} {"_id":"q-en-rust-33ef0a07b71a93a4d7008c47774aca46da78fc10435cf4e00d95de401a226a40","text":"#![feature(thread_local)] #![feature(trace_macros)] #![feature(trusted_len)] #![feature(vec_remove_item)] #![feature(stmt_expr_attributes)] #![feature(integer_atomics)] #![feature(test)]"} {"_id":"q-en-rust-3416808dca9fca9d5ab60e3c0ba59bca4a5ac3fb7c710108112909072fc078c2","text":"item_name ) }).unwrap(); let impl_span = fcx.tcx().map.def_id_span(impl_did, span); let item_span = fcx.tcx().map.def_id_span(item.def_id(), impl_span); let note_span = fcx.tcx().map.span_if_local(item.def_id()).or_else(|| { fcx.tcx().map.span_if_local(impl_did) }); let impl_ty = check::impl_self_ty(fcx, span, impl_did).ty;"} {"_id":"q-en-rust-344123f2d85bcf5c477fdcc4011c0d7dfe080811cc7119aafa2ead686cc2a96e","text":"return (level, src) } fn get_lint_id_level(&self, id: LintId, mut idx: u32) fn get_lint_id_level(&self, id: LintId, mut idx: u32, aux: Option<&FxHashMap>) -> (Option, LintSource) { if let Some(specs) = aux { if let Some(&(level, src)) = specs.get(&id) { return (Some(level), src) } } loop { match self.list[idx as usize] { LintSet::CommandLine { ref specs } => {"} {"_id":"q-en-rust-34544fe856af0863c39e405420d22c9a2ac00bb8380ecfc7a1e8794067f9cb6e","text":"libc::execvp(self.get_argv()[0], self.get_argv().as_ptr()); io::Error::last_os_error() } #[cfg(not(any(target_os = \"macos\", target_os = \"freebsd\")))] fn posix_spawn(&mut self, _stdio: &ChildPipes, _envp: Option<&CStringArray>) -> io::Result> { Ok(None) } #[cfg(any(target_os = \"macos\", target_os = \"freebsd\"))] fn posix_spawn(&mut self, stdio: &ChildPipes, envp: Option<&CStringArray>) -> io::Result> { use mem; use sys; if self.get_cwd().is_some() || self.get_gid().is_some() || self.get_uid().is_some() || self.get_closures().len() != 0 { return Ok(None) } let mut p = Process { pid: 0, status: None }; struct PosixSpawnFileActions(libc::posix_spawn_file_actions_t); impl Drop for PosixSpawnFileActions { fn drop(&mut self) { unsafe { libc::posix_spawn_file_actions_destroy(&mut self.0); } } } struct PosixSpawnattr(libc::posix_spawnattr_t); impl Drop for PosixSpawnattr { fn drop(&mut self) { unsafe { libc::posix_spawnattr_destroy(&mut self.0); } } } unsafe { let mut file_actions = PosixSpawnFileActions(mem::uninitialized()); let mut attrs = PosixSpawnattr(mem::uninitialized()); libc::posix_spawnattr_init(&mut attrs.0); libc::posix_spawn_file_actions_init(&mut file_actions.0); if let Some(fd) = stdio.stdin.fd() { cvt(libc::posix_spawn_file_actions_adddup2(&mut file_actions.0, fd, libc::STDIN_FILENO))?; } if let Some(fd) = stdio.stdout.fd() { cvt(libc::posix_spawn_file_actions_adddup2(&mut file_actions.0, fd, libc::STDOUT_FILENO))?; } if let Some(fd) = stdio.stderr.fd() { cvt(libc::posix_spawn_file_actions_adddup2(&mut file_actions.0, fd, libc::STDERR_FILENO))?; } let mut set: libc::sigset_t = mem::uninitialized(); cvt(libc::sigemptyset(&mut set))?; cvt(libc::posix_spawnattr_setsigmask(&mut attrs.0, &set))?; cvt(libc::sigaddset(&mut set, libc::SIGPIPE))?; cvt(libc::posix_spawnattr_setsigdefault(&mut attrs.0, &set))?; let flags = libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK; cvt(libc::posix_spawnattr_setflags(&mut attrs.0, flags as _))?; let envp = envp.map(|c| c.as_ptr()) .unwrap_or(*sys::os::environ() as *const _); let ret = libc::posix_spawnp( &mut p.pid, self.get_argv()[0], &file_actions.0, &attrs.0, self.get_argv().as_ptr() as *const _, envp as *const _, ); if ret == 0 { Ok(Some(p)) } else { Err(io::Error::from_raw_os_error(ret)) } } } } ////////////////////////////////////////////////////////////////////////////////"} {"_id":"q-en-rust-350432eb53fbe3d036479319cd624b40746241a85ce8e61992962b9bf242673f","text":"span: name_binding.span, segments: path_segments, }; result = Some((module, ImportSuggestion { path })); let did = module.def().and_then(|def| def.opt_def_id()); result = Some((module, ImportSuggestion { did, path })); } else { // add the module to the lookup if seen_modules.insert(module.def_id().unwrap()) {"} {"_id":"q-en-rust-3524f5cd0fe7fa65562039bdc2c151b90b260b9f63e9c7112aae3a3594a56778","text":"expr.id, method_call, r.datum.to_string(ccx)); return r; /// We microoptimize derefs of owned pointers a bit here. Basically, the idea is to make the /// deref of an rvalue result in an rvalue. This helps to avoid intermediate stack slots in the /// resulting LLVM. The idea here is that, if the `Box` pointer is an rvalue, then we can /// schedule a *shallow* free of the `Box` pointer, and then return a ByRef rvalue into the /// pointer. Because the free is shallow, it is legit to return an rvalue, because we know that /// the contents are not yet scheduled to be freed. The language rules ensure that the contents /// will be used (or moved) before the free occurs. fn deref_owned_pointer<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr, datum: Datum<'tcx, Expr>, content_ty: Ty<'tcx>) -> DatumBlock<'blk, 'tcx, Expr> { match datum.kind { RvalueExpr(Rvalue { mode: ByRef }) => { let scope = cleanup::temporary_scope(bcx.tcx(), expr.id); let ptr = Load(bcx, datum.val); if !type_is_zero_size(bcx.ccx(), content_ty) { bcx.fcx.schedule_free_value(scope, ptr, cleanup::HeapExchange, content_ty); } } RvalueExpr(Rvalue { mode: ByValue }) => { let scope = cleanup::temporary_scope(bcx.tcx(), expr.id); if !type_is_zero_size(bcx.ccx(), content_ty) { bcx.fcx.schedule_free_value(scope, datum.val, cleanup::HeapExchange, content_ty); } } LvalueExpr => { } } // If we had an rvalue in, we produce an rvalue out. let (llptr, kind) = match datum.kind { LvalueExpr => { (Load(bcx, datum.val), LvalueExpr) } RvalueExpr(Rvalue { mode: ByRef }) => { (Load(bcx, datum.val), RvalueExpr(Rvalue::new(ByRef))) } RvalueExpr(Rvalue { mode: ByValue }) => { (datum.val, RvalueExpr(Rvalue::new(ByRef))) } }; let datum = Datum { ty: content_ty, val: llptr, kind: kind }; DatumBlock { bcx: bcx, datum: datum } } } #[derive(Debug)]"} {"_id":"q-en-rust-355a93491c2661032f692a77a3f9b10a172e2e27487c2c3212a7230a1344b5db","text":"HashSet, Hasher, Implied, IndexOutput, Input, Into, IntoDiagnostic,"} {"_id":"q-en-rust-3568d113912d4342d1527bb27ff39d1aa1ac4a12bba91923bb1ffe715daab5e4","text":"let expn_id = ext_cx.resolver.expansion_for_ast_pass( DUMMY_SP, AstPass::TestHarness, &[sym::test, sym::rustc_attrs], &[sym::test, sym::rustc_attrs, sym::no_coverage], None, ); let def_site = DUMMY_SP.with_def_site_ctxt(expn_id.to_expn_id());"} {"_id":"q-en-rust-358feaa9f4b187c43e729789139d76c674d95d4dd5267600e4e085e4df0d62e3","text":"/// Ok(()) /// } /// ``` #[unstable(feature = \"buffered_io_capacity\", issue = \"68833\")] #[stable(feature = \"buffered_io_capacity\", since = \"1.46.0\")] pub fn capacity(&self) -> usize { self.buf.len() }"} {"_id":"q-en-rust-35904b51ceb37e2a4ab4a74a313c006563b63c8cee572b46e00b1f9d7cdf77bb","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":"q-en-rust-35a5c0249ea42732e8d74ef0a7471e5d9f5e2e32dbc1ada67b3a2dfd2a739cc4","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":"q-en-rust-35b8991e85d68fb14a7e9ea2ec7c2abac93b07dbaddc46fed65248aaebe7ad68","text":" // compile-flags:-C panic=abort // only-x86_64 #![feature(target_feature_11)] #![no_std] #![no_main] use core::panic::PanicInfo; #[panic_handler] #[target_feature(enable = \"avx2\")] //~^ ERROR `panic_impl` language item function is not allowed to have `#[target_feature]` fn panic(info: &PanicInfo) -> ! { unimplemented!(); } "} {"_id":"q-en-rust-35cc4024baea1d199069f414c406e3f9815fd4c4a88fc319921003d6f5a2fd56","text":"last } /// True if a fragment of type `frag` can be followed by any sort of /// token. We use this (among other things) as a useful approximation /// for when `frag` can be followed by a repetition like `$(...)*` or /// `$(...)+`. In general, these can be a bit tricky to reason about, /// so we adopt a conservative position that says that any fragment /// specifier which consumes at most one token tree can be followed by /// a fragment specifier (indeed, these fragments can be followed by /// ANYTHING without fear of future compatibility hazards). fn can_be_followed_by_any(frag: &str) -> bool { match frag { \"item\" | // always terminated by `}` or `;` \"block\" | // exactly one token tree \"ident\" | // exactly one token tree \"meta\" | // exactly one token tree \"tt\" => // exactly one token tree true, _ => false, } } /// True if `frag` can legally be followed by the token `tok`. For /// fragments that can consume an unbounded numbe of tokens, `tok` /// must be within a well-defined follow set. This is intended to /// guarantee future compatibility: for example, without this rule, if /// we expanded `expr` to include a new binary operator, we might /// break macros that were relying on that binary operator as a /// separator. fn is_in_follow(_: &ExtCtxt, tok: &Token, frag: &str) -> Result { if let &CloseDelim(_) = tok { // closing a token tree can never be matched by any fragment; // iow, we always require that `(` and `)` match, etc. Ok(true) } else { match frag {"} {"_id":"q-en-rust-35dc7edd88e1532da98aa09d902283275e3464e81b53ceb29c98011084e28ee9","text":"\"before\", \":51] { foo += 1; eprintln!(\"before\"); 7331 } = 7331\", \":59] (\"Yeah\",) = (\", \" \"Yeah\",\", \")\", \":62] 1 = 1\", \":62] 2 = 2\", \":66] 1u8 = 1\", \":66] 2u32 = 2\", \":66] \"Yeah\" = \"Yeah\"\", ]); }"} {"_id":"q-en-rust-35ec9892ae1cd5318babea610c1e5b9029b90c543b7414af173558c75dd241a6","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 tup = (0, 1, 2); // the case where we show a suggestion let _ = tup[0]; //~^ ERROR cannot index a value of type //~| HELP to access tuple elements, use tuple indexing syntax as shown //~| SUGGESTION let _ = tup.0 // the case where we show just a general hint let i = 0_usize; let _ = tup[i]; //~^ ERROR cannot index a value of type //~| HELP to access tuple elements, use tuple indexing syntax (e.g. `tuple.0`) } "} {"_id":"q-en-rust-35ffa820210957130ad243508f5be729041ce1e367274c70ea1d8e005d525462","text":"let trait_ref = projection.to_poly_trait_ref(tcx); let is_fn = tcx.lang_items().fn_trait_kind(trait_ref.def_id()).is_some(); let gen_trait = tcx.lang_items().gen_trait().unwrap(); let gen_trait = tcx.require_lang_item(lang_items::GeneratorTraitLangItem); let is_gen = gen_trait == trait_ref.def_id(); if !is_fn && !is_gen { debug!(\"deduce_sig_from_projection: not fn or generator\");"} {"_id":"q-en-rust-36024c19c57e7d874954ce34c6dce60a0bea0a3a2ad4c88b32cf8dfbe6bacf97","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":"q-en-rust-36149482e1d0e47ed159d96bac92f448852da90737ea17a1f820c854f90c715d","text":"_ => &[], }; let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind { hir::GenericParamKind::Lifetime { .. } => Some(param.name.ident().modern()), hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()), _ => None, }); self.in_scope_lifetimes.extend(lt_def_names);"} {"_id":"q-en-rust-363a7dd07607c998d570b09000ea50f292317daf08d67bcc16768a393087e2dd","text":" // run-pass #![feature(bench_black_box)] use std::hint; struct U16(u16); impl Drop for U16 { fn drop(&mut self) { // Prevent LLVM from optimizing away our alignment check. assert!(hint::black_box(self as *mut U16 as usize) % 2 == 0); } } struct HasDrop; impl Drop for HasDrop { fn drop(&mut self) {} } struct Wrapper { _a: U16, b: HasDrop, } #[repr(packed)] struct Misalign(u8, Wrapper); fn main() { let m = Misalign( 0, Wrapper { _a: U16(10), b: HasDrop, }, ); // Put it somewhere definitely even (so the `a` field is definitely at an odd address). let m: ([u16; 0], Misalign) = ([], m); // Move out one field, so we run custom per-field drop logic below. let _x = m.1.1.b; } "} {"_id":"q-en-rust-364ea11b770e8305c0c53250604cdc00dcbd3caefe0f00551b50048ae9a3beff","text":" error: argument to `panic!()` in a const context must have type `&str` --> $DIR/issue-66693.rs:13:5 | LL | panic!(&1); | ^^^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: argument to `panic!()` in a const context must have type `&str` --> $DIR/issue-66693.rs:6:15 | LL | const _: () = panic!(1); | ^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: argument to `panic!()` in a const context must have type `&str` --> $DIR/issue-66693.rs:9:19 | LL | static _FOO: () = panic!(true); | ^^^^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors "} {"_id":"q-en-rust-366aec0b367c74bc1466d97196e8ad65fb71bfe07fecb94b8fa0d700979176fc","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":"q-en-rust-368c87b7e7fec3e10f7bbf439ade70d98cd1b1fedd577bf58839e10701c4edf9","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":"q-en-rust-36a37e6edf3f6e3bb91b8e47bf3a63cd1ecdb7caf5bf4cf16ef58594ea3b0b8f","text":"} fn check_overalign_requests(mut allocator: T) { let size = 8; let align = 16; // greater than size let iterations = 100; unsafe { let pointers: Vec<_> = (0..iterations).map(|_| { allocator.alloc(Layout::from_size_align(size, align).unwrap()).unwrap() }).collect(); for &ptr in &pointers { assert_eq!((ptr.as_ptr() as usize) % align, 0, \"Got a pointer less aligned than requested\") } for &align in &[4, 8, 16, 32] { // less than and bigger than `MIN_ALIGN` for &size in &[align/2, align-1] { // size less than alignment let iterations = 128; unsafe { let pointers: Vec<_> = (0..iterations).map(|_| { allocator.alloc(Layout::from_size_align(size, align).unwrap()).unwrap() }).collect(); for &ptr in &pointers { assert_eq!((ptr.as_ptr() as usize) % align, 0, \"Got a pointer less aligned than requested\") } // Clean up for &ptr in &pointers { allocator.dealloc(ptr, Layout::from_size_align(size, align).unwrap()) // Clean up for &ptr in &pointers { allocator.dealloc(ptr, Layout::from_size_align(size, align).unwrap()) } } } } }"} {"_id":"q-en-rust-36b5c1eca31deac9837bad351ef50069e950e85098e344c82edc9a50e577296a","text":"}, x => { bug!(\"unexpected sort of node in type_of_def_id(): {:?}\", x); bug!(\"unexpected sort of node in type_of(): {:?}\", x); } } }"} {"_id":"q-en-rust-372b4ff3f8f5028ceedb734fbdbe9a6190fee0ba49c53d185f143b6981bd5c5e","text":"RUST_CONFIGURE_ARGS=--build=x86_64-apple-darwin SRC=. os: osx before_script: &osx_before_script > ulimit -c unlimited install: &osx_install_sccache > curl -L https://api.pub.build.mozilla.org/tooltool/sha512/d0025b286468cc5ada83b23d3fafbc936b9f190eaa7d4a981715b18e8e3bf720a7bcee7bfe758cfdeb8268857f6098fd52dcdd8818232692a30ce91039936596 | tar xJf - -C /usr/local/bin --strip-components=1 after_failure: &osx_after_failure > echo 'bt all' > cmds; for file in $(ls /cores); do echo core file $file; lldb -c $file `which ld` -b -s cmds; done - env: > RUST_CHECK_TARGET=check RUST_CONFIGURE_ARGS=--build=i686-apple-darwin SRC=. os: osx before_script: *osx_before_script install: *osx_install_sccache after_failure: *osx_after_failure - env: > RUST_CHECK_TARGET=check RUST_CONFIGURE_ARGS=--build=x86_64-apple-darwin --disable-rustbuild SRC=. os: osx before_script: *osx_before_script install: *osx_install_sccache after_failure: *osx_after_failure - env: > RUST_CHECK_TARGET= RUST_CONFIGURE_ARGS=--target=aarch64-apple-ios,armv7-apple-ios,armv7s-apple-ios,i386-apple-ios,x86_64-apple-ios SRC=. os: osx before_script: *osx_before_script install: *osx_install_sccache after_failure: *osx_after_failure env: global:"} {"_id":"q-en-rust-372b7f6db1a6f73312d570a9caf7c25c411d85adc781913fbd4c1fc9ad6fcd7c","text":"NonZeroUsize::new(remaining).map_or(Ok(()), Err) } #[inline] unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item { // SAFETY: The caller must provide an idx that is in bound of the remainder. unsafe { self.data.as_ptr().add(self.alive.start()).add(idx).cast::().read() } } } #[stable(feature = \"array_value_iter_impls\", since = \"1.40.0\")]"} {"_id":"q-en-rust-375b4ba9dc3902c5216e604065827d093c2be6906501e88883540116e4f2984d","text":" error: named argument `world` is not used by name --> $DIR/sugg_with_positional_args_and_debug_fmt.rs:6:28 | LL | println!(\"hello {:?}\", world = \"world\"); | ---- ^^^^^ this named argument is referred to by position in formatting string | | | this formatting argument uses named argument `world` by position | note: the lint level is defined here --> $DIR/sugg_with_positional_args_and_debug_fmt.rs:3:9 | LL | #![deny(warnings)] | ^^^^^^^^ = note: `#[deny(named_arguments_used_positionally)]` implied by `#[deny(warnings)]` help: use the named argument by name to avoid ambiguity | LL | println!(\"hello {world:?}\", world = \"world\"); | +++++ error: aborting due to previous error "} {"_id":"q-en-rust-37680bb17ce26bb7fba40af4244b4f770c4a037414da950a051dbaa21f7d5846","text":"n => { let m = cmp::min(n, self.steals); self.steals -= m; self.cnt.fetch_add(n - m, atomics::SeqCst); self.bump(n - m); } } assert!(self.steals >= 0); } self.steals += 1; Ok(data) }"} {"_id":"q-en-rust-3777765427445574cde3e3445fea017edb4675595fa2a91477c7e4080d830a77","text":" // no-prefer-dynamic static mut DROP_RAN: bool = false; struct Foo;"} {"_id":"q-en-rust-377f9c9205ff301cf356565694356be4cb796e55fbf220af623f976efa049c6a","text":" // no-prefer-dynamic // ignore-cloudabi // ignore-emscripten // ignore-sgx no processes"} {"_id":"q-en-rust-37803f41c877da45c819ac39518649b45c072ea71750cfa4038f8e0f55bd18aa","text":" // run-rustfix fn wat(t: &T) -> T { t.clone() //~ ERROR E0308 } #[derive(Clone)] struct Foo; fn wut(t: &Foo) -> Foo { t.clone() //~ ERROR E0308 } fn main() { wat(&42); wut(&Foo); } "} {"_id":"q-en-rust-379ffdb683666e657ee367eb965380ab8bdcf393840d56bc7ede30e1ab3c5ef7","text":"let it = xs.iter_mut().map(|x| *x = 1).enumerate().zip(&ys); it.count(); } assert_eq!(&xs, &[1, 1, 1, 1, 1, 0]); let length_aware = &xs == &[1, 1, 1, 1, 0, 0]; let probe_first = &xs == &[1, 1, 1, 1, 1, 0]; // either implementation is valid according to zip documentation assert!(length_aware || probe_first); } #[test]"} {"_id":"q-en-rust-37ca763d724d953fe7df1b4128d3de41c9da97ff862b1cd187fcc98b1ee1602d","text":" error: unmatched angle bracket error: expected one of `!`, `+`, `::`, `;`, `where`, or `{`, found `>` --> $DIR/issue-24780.rs:5:23 | LL | fn foo() -> Vec> { | ^^ help: remove extra angle bracket | ^ expected one of `!`, `+`, `::`, `;`, `where`, or `{` error: aborting due to previous error"} {"_id":"q-en-rust-37cae60f51de95d157dcf437ff2a876b39f7f6c7094e75099a0c017e5116f3bc","text":"let buildpath = fs::connect(_path, \"/test\"); need_dir(buildpath); #debug(\"Testing: %s -> %s\", cf, buildpath); let p = run::program_output(\"rustc\", [\"--out-dir\", buildpath, \"--test\", cf]); let p = run::program_output(rustc_sysroot(), [\"--out-dir\", buildpath, \"--test\", cf]); if p.status != 0 { error(#fmt[\"rustc failed: %dn%sn%s\", p.status, p.err, p.out]); ret;"} {"_id":"q-en-rust-37eb485f94a24a8ce4db4d25e6fae32bea017fab0f996340337aa38fbc0680d3","text":"args.push(~\"-dynamiclib\"); args.push(~\"-Wl,-dylib\"); // FIXME (#9639): This needs to handle non-utf8 paths args.push(~\"-Wl,-install_name,@rpath/\" + out_filename.filename_str().unwrap()); if !sess.opts.no_rpath { args.push(~\"-Wl,-install_name,@rpath/\" + out_filename.filename_str().unwrap()); } } else { args.push(~\"-shared\") }"} {"_id":"q-en-rust-37f5cc81e02c80adbacbc0e41b4bbe46a961f46a02a453bb7b5be56c1a5c1ac3","text":" // issue: rust-lang/rust#125081 fn main() { let _: &str = 'β; //~^ ERROR expected `while`, `for`, `loop` or `{` after a label //~| ERROR mismatched types } "} {"_id":"q-en-rust-38281f5cf7089c339a4197f24157ddf3686d7ae6af9c43756acf261309fd9f0b","text":"hir::ItemEnum(..) | hir::ItemStruct(..) | hir::ItemUnion(..) => { false (false, false) } };"} {"_id":"q-en-rust-382ad4be3c8dbcb07dc93e9320cbe11665aaa1a2392b615a8c0c0dc8b1b6db32","text":" // edition:2018 fn main() { use a::ModPrivateStruct; let Box { 0: _, .. }: Box<()>; //~ ERROR field `0` of let Box { 1: _, .. }: Box<()>; //~ ERROR field `1` of let ModPrivateStruct { 1: _, .. } = ModPrivateStruct::default(); //~ ERROR field `1` of } mod a { #[derive(Default)] pub struct ModPrivateStruct(u8, u8); } "} {"_id":"q-en-rust-3832c1dda031dac89de40e50c7c43769c33998421d496b0b2e5f0bd53e2bae8d","text":" extern crate alloc; #[cfg(test)] mod tests { #[test] fn something_alloc() { assert_eq!(Vec::::new(), Vec::::new()); } } "} {"_id":"q-en-rust-383533e1ffc9f9a7de0e73c3da075c5b1e57f57297d1fe819bf1b82e65982a45","text":"self.delegate.push_verify(origin, GenericKind::Alias(alias_ty), region, verify_bound); } #[instrument(level = \"debug\", skip(self))] fn substs_must_outlive( &mut self, substs: SubstsRef<'tcx>, origin: infer::SubregionOrigin<'tcx>, region: ty::Region<'tcx>, opt_variances: Option<&[ty::Variance]>, ) { let constraint = origin.to_constraint_category(); for k in substs { for (index, k) in substs.iter().enumerate() { match k.unpack() { GenericArgKind::Lifetime(lt) => { self.delegate.push_sub_region_constraint( origin.clone(), region, lt, constraint, ); let variance = if let Some(variances) = opt_variances { variances[index] } else { ty::Invariant }; if variance == ty::Invariant { self.delegate.push_sub_region_constraint( origin.clone(), region, lt, constraint, ); } } GenericArgKind::Type(ty) => { self.type_must_outlive(origin.clone(), ty, region, constraint);"} {"_id":"q-en-rust-3836b761969c9e3e67b64d7c7bfbb953573b3e785b1094fa214b490b2d4ae282","text":"source shared.sh LLVM=llvmorg-11.0.1 LLVM=llvmorg-10.0.0 mkdir llvm-project cd llvm-project"} {"_id":"q-en-rust-384badb77388f07c80a248cbc31c2848a490ae9abfc54f52f51ca75822c04e86","text":"\"Force drop flag checks on or off\"), trace_macros: bool = (false, parse_bool, \"For every macro invocation, print its name and arguments\"), disable_nonzeroing_move_hints: bool = (false, parse_bool, \"Force nonzeroing move optimization off\"), enable_nonzeroing_move_hints: bool = (false, parse_bool, \"Force nonzeroing move optimization on\"), } pub fn default_lib_output() -> CrateType {"} {"_id":"q-en-rust-387429d0b3a33ef9214e60e015d6c72b2f30d70ff3c175b11c5e398573b9edaf","text":"} } fn no_such_field_err( fn no_such_field_err( &self, span: Span, field: T, expr_t: &ty::TyS<'_>, field: Ident, expr_t: &'tcx ty::TyS<'tcx>, ) -> DiagnosticBuilder<'_> { type_error_struct!( let span = field.span; debug!(\"no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})\", span, field, expr_t); let mut err = type_error_struct!( self.tcx().sess, span, field.span, expr_t, E0609, \"no field `{}` on type `{}`\", field, expr_t ) ); // try to add a suggestion in case the field is a nested field of a field of the Adt if let Some((fields, substs)) = self.get_field_candidates(span, &expr_t) { for candidate_field in fields.iter() { if let Some(field_path) = self.check_for_nested_field(span, field, candidate_field, substs, vec![]) { let field_path_str = field_path .iter() .map(|id| id.name.to_ident_string()) .collect::>() .join(\".\"); debug!(\"field_path_str: {:?}\", field_path_str); err.span_suggestion_verbose( field.span.shrink_to_lo(), \"one of the expressions' fields has a field of the same name\", format!(\"{}.\", field_path_str), Applicability::MaybeIncorrect, ); } } } err } fn get_field_candidates( &self, span: Span, base_t: Ty<'tcx>, ) -> Option<(&Vec, SubstsRef<'tcx>)> { debug!(\"get_field_candidates(span: {:?}, base_t: {:?}\", span, base_t); let mut autoderef = self.autoderef(span, base_t); while let Some((base_t, _)) = autoderef.next() { match base_t.kind() { ty::Adt(base_def, substs) if !base_def.is_enum() => { let fields = &base_def.non_enum_variant().fields; // For compile-time reasons put a limit on number of fields we search if fields.len() > 100 { return None; } return Some((fields, substs)); } _ => {} } } None } /// This method is called after we have encountered a missing field error to recursively /// search for the field fn check_for_nested_field( &self, span: Span, target_field: Ident, candidate_field: &ty::FieldDef, subst: SubstsRef<'tcx>, mut field_path: Vec, ) -> Option> { debug!( \"check_for_nested_field(span: {:?}, candidate_field: {:?}, field_path: {:?}\", span, candidate_field, field_path ); if candidate_field.ident == target_field { Some(field_path) } else if field_path.len() > 3 { // For compile-time reasons and to avoid infinite recursion we only check for fields // up to a depth of three None } else { // recursively search fields of `candidate_field` if it's a ty::Adt field_path.push(candidate_field.ident.normalize_to_macros_2_0()); let field_ty = candidate_field.ty(self.tcx, subst); if let Some((nested_fields, _)) = self.get_field_candidates(span, &field_ty) { for field in nested_fields.iter() { let ident = field.ident.normalize_to_macros_2_0(); if ident == target_field { return Some(field_path); } else { let field_path = field_path.clone(); if let Some(path) = self.check_for_nested_field( span, target_field, field, subst, field_path, ) { return Some(path); } } } } None } } fn check_expr_index("} {"_id":"q-en-rust-38759c88c08e92189ad48f24e6a0c885897d7ca331aee31a458469aba2bedb90","text":"}, base_t, None); // Try to give some advice about indexing tuples. if let ty::TyTuple(_) = base_t.sty { let mut needs_note = true; // If the index is an integer, we can show the actual // fixed expression: if let hir::ExprLit(ref lit) = idx.node { if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node { let snip = fcx.tcx().sess.codemap().span_to_snippet(base.span); if let Ok(snip) = snip { err.span_suggestion(expr.span, \"to access tuple elements, use tuple indexing syntax as shown\", format!(\"{}.{}\", snip, i)); needs_note = false; } } } if needs_note { err.help(\"to access tuple elements, use tuple indexing syntax (e.g. `tuple.0`)\"); } } err.emit(); fcx.write_ty(id, fcx.tcx().types.err); } }"} {"_id":"q-en-rust-388ade6c3d9f1a836394f2d63f6b777a9201ac1cb01d022be6da51c7baf63a88","text":"error[E0277]: the trait bound `NotDebugOrDisplay: Marker` is not satisfied --> $DIR/overlap-marker-trait.rs:27:17 --> $DIR/overlap-marker-trait.rs:28:17 | LL | is_marker::(); | ^^^^^^^^^^^^^^^^^ the trait `Marker` is not implemented for `NotDebugOrDisplay` | note: required by a bound in `is_marker` --> $DIR/overlap-marker-trait.rs:15:17 --> $DIR/overlap-marker-trait.rs:16:17 | LL | fn is_marker() { } | ^^^^^^ required by this bound in `is_marker`"} {"_id":"q-en-rust-389224534f7325c557f1d83e367ca538f27d316ff6b1e62f973caf1fc982e554","text":" fn foo() { let x = Tr; //~^ ERROR expected one of `!`, `.`, `::`, `;`, `?`, `else`, `{`, or an operator, found `,` } fn main() {} "} {"_id":"q-en-rust-38aa805b8c99f9e778f7ceb095ea47edb7ac333c864d58bc4ea0e4739c759902","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":"q-en-rust-38b521c8dc312ba3d2e69d7bc174aa7ed040e319602bc00f4c9c8a4f9ecf04e4","text":"probe CFG_FLEX flex probe CFG_BISON bison probe CFG_PANDOC pandoc probe CFG_PDFLATEX pdflatex probe CFG_XELATEX xelatex probe CFG_LUALATEX lualatex probe CFG_GDB gdb probe CFG_LLDB lldb"} {"_id":"q-en-rust-38bf42335233800f879f3274aa31cd9a8737384d8af7759f58f240b6d6cb9c52","text":"pub struct FrozenTupleStruct(pub int); #[locked] pub struct LockedTupleStruct(pub int); #[macro_export] macro_rules! macro_test( () => (deprecated()); ) "} {"_id":"q-en-rust-38c37f4bdddf002074aa0d42bc64af64d7a44c50e0d476fc8449135d17c0a59d","text":"def read_current_status(current_commit, path): # type: (str, str) -> typing.Mapping[str, typing.Any] '''Reads build status of `current_commit` from content of `history/*.tsv` ''' with open(path, 'rU') as f: with open(path, 'r') as f: for line in f: (commit, status) = line.split('t', 1) if commit == current_commit:"} {"_id":"q-en-rust-394789741473aa90b42903454ba480d06b09fb053ebe287933733cfa39a07873","text":"cargo.env(\"RUSTC_TLS_MODEL_INITIAL_EXEC\", \"1\"); } if self.config.incremental { // Ignore incremental modes except for stage0, since we're // not guaranteeing correctness across builds if the compiler // is changing under your feet. if self.config.incremental && compiler.stage == 0 { cargo.env(\"CARGO_INCREMENTAL\", \"1\"); } else { // Don't rely on any default setting for incr. comp. in Cargo"} {"_id":"q-en-rust-394c3deff87301bac8a231b6cb5556a2c8b700d8ac3c94eb869bed87673b5909","text":"StorageLive(_3); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:3:5: 3:15 StorageLive(_4); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:3:5: 3:6 _4 = &mut (*_1); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:3:5: 3:6 _3 = move _4; // scope 1 at $SRC_DIR/libcore/convert/mod.rs:LL:COL StorageLive(_5); // scope 1 at $SRC_DIR/libcore/convert/mod.rs:LL:COL _5 = &mut (*_4); // scope 1 at $SRC_DIR/libcore/convert/mod.rs:LL:COL _3 = &mut (*_5); // scope 1 at $SRC_DIR/libcore/convert/mod.rs:LL:COL StorageDead(_5); // scope 1 at $SRC_DIR/libcore/convert/mod.rs:LL:COL _2 = &mut (*_3); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:3:5: 3:15 StorageDead(_4); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:3:14: 3:15 _0 = &mut (*_2); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:3:5: 3:15"} {"_id":"q-en-rust-3979fafe5557e5980690d4cd89f60e1eea516a326e84b1af3f5d04b2c249da16","text":"/// Cancel the diagnostic (a structured diagnostic must either be emitted or /// canceled or it will panic when dropped). /// BEWARE: if this DiagnosticBuilder is an error, then creating it will /// bump the error count on the Handler and canceling it won't undo that. /// If you want to decrement the error count you should use `Handler::cancel`. pub fn cancel(&mut self) { self.level = Level::Cancelled; }"} {"_id":"q-en-rust-398146ab5164be20473e0e7afb1cb395754b0c39aa162434800cfe242907b15c","text":"//~^ ERROR generic associated types are unstable } trait Bar { type Assoc where Self: Sized; //~^ ERROR where clauses on associated types are unstable } fn main() {}"} {"_id":"q-en-rust-399016b6a04b7613eab1c6fc704d04bfbefbc11c54caec1fdc3119688bb61bfc","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":"q-en-rust-3999bcb759c1eee754e7bb8c797a7820a348f16347bfd1c9e2c165ad196365b1","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. #![crate_type=\"lib\"] pub trait Trait { // the issue is sensitive to interning order - so use names // unlikely to appear in libstd. type Issue25467FooT; type Issue25467BarT; } pub type Object = Option>>; "} {"_id":"q-en-rust-39ac5425fdaff5b01c309e2c7344bce4f7ea4eb7930af31eb6bd0677697c38a1","text":"for autoderefs in range(0, fcx.tcx().sess.recursion_limit.get()) { let resolved_t = structurally_resolved_type(fcx, sp, t); if ty::type_is_bot(resolved_t) { return (resolved_t, autoderefs, None); } match should_stop(resolved_t, autoderefs) { Some(x) => return (resolved_t, autoderefs, Some(x)), None => {}"} {"_id":"q-en-rust-39ae740f1f34530075a7219090eb58b4972c6214282f897c42f75e91de1c06c5","text":" // Check that `async fn` inside of an impl with `'_` // in the header compiles correctly. // // Regression test for #63500. // // check-pass // edition:2018 #![feature(async_await)] struct Foo<'a>(&'a u8); impl Foo<'_> { async fn bar() {} } fn main() { } "} {"_id":"q-en-rust-39b42e9f5a7dfe4ca572b20ec367e3cc565aa81a4636a79d5305682c181a5d15","text":"#[inline] #[must_use] #[stable(feature = \"rust1\", since = \"1.0.0\")] #[rustc_const_unstable(feature = \"const_transmute_copy\", issue = \"83165\")] #[rustc_const_stable(feature = \"const_transmute_copy\", since = \"CURRENT_RUSTC_VERSION\")] pub const unsafe fn transmute_copy(src: &Src) -> Dst { assert!( size_of::() >= size_of::(),"} {"_id":"q-en-rust-39c669f00f1eb7bfd94787096e650d5514807c256afe7049bb6b3a74fcebcf31","text":"/// assert!(ascii.is_ascii()); /// assert!(!non_ascii.is_ascii()); /// ``` #[unstable(feature = \"osstring_ascii\", issue = \"70516\")] #[stable(feature = \"osstring_ascii\", since = \"1.53.0\")] #[inline] pub fn is_ascii(&self) -> bool { self.inner.is_ascii()"} {"_id":"q-en-rust-39cb234eb72877cbf29fd2527348f16381401cab1b83e1274f7bb821e7a0b014","text":"let p = Command::new(\"cmd\").args(&[\"/C\", \"exit 0\"]).env_clear().spawn(); assert!(p.is_ok()); } // See issue #91991 #[test] #[cfg(windows)] fn run_bat_script() { let tempdir = crate::sys_common::io::test::tmpdir(); let script_path = tempdir.join(\"hello.cmd\"); crate::fs::write(&script_path, \"@echo Hello, %~1!\").unwrap(); let output = Command::new(&script_path) .arg(\"fellow Rustaceans\") .stdout(crate::process::Stdio::piped()) .spawn() .unwrap() .wait_with_output() .unwrap(); assert!(output.status.success()); assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), \"Hello, fellow Rustaceans!\"); } "} {"_id":"q-en-rust-39daa33e2df46b8572d840f3120b3838648c8962fad2205d3dd369565e536c68","text":"if ast_util::is_local(self.item.def_id) { let mut path = Vec::new(); clean_srcpath(&cx.src_root, Path::new(&self.item.source.filename), |component| { true, |component| { path.push(component.to_string()); }); let href = if self.item.source.loline == self.item.source.hiline {"} {"_id":"q-en-rust-3a29390d1c9035170f416e53d9549a7d9d365dbe68ffd06d81096faf55c3c48f","text":"# tarball for a stable release you'll likely see `1.x.0-$date` where `1.x.0` was # released on `$date` rustc: beta-2017-03-21 rustc: beta-2017-04-05 "} {"_id":"q-en-rust-3a39cbcf552f02ecb6dae2660dc82939786de83cbebed62dcc338b7ec89e6b83","text":" Subproject commit bf88026f11f2cc7bb9fefdfe1dbcab642f110afa Subproject commit f37425e33c864c697af06df66e7473444605c149 "} {"_id":"q-en-rust-3a452cc7ea5c0bc0338517e30a7828adab13e6dd3b14e59340638120d10d9c67","text":"without modifying the original\"] #[inline] #[track_caller] #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] pub const fn ilog(self, base: Self) -> u32 { match self.checked_ilog(base) { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } assert!(base >= 2, \"base of integer logarithm must be at least 2\"); self.checked_ilog(base).expect(\"argument of integer logarithm must be positive\") } /// Returns the base 2 logarithm of the number, rounded down. /// /// # Panics /// /// When the number is zero it panics in debug mode and /// the return value is 0 in release mode. /// This function will panic if `self` is zero. /// /// # Examples ///"} {"_id":"q-en-rust-3a5267d9d598fc257eabbccdc30ce4f664ccff77b4361ad567b0533c362cd554","text":"numbers [no longer return platform-specific types][1.8r], but instead return widened integers. [RFC 1415]. * [Modules sourced from the filesystem cannot appear within arbitrary blocks, but only within other modules][1.8m]. blocks, but only within other modules][1.8mf]. * [`--cfg` compiler flags are parsed strictly as identifiers][1.8c]. * On Unix, [stack overflow triggers a runtime abort instead of a SIGSEGV][1.8so]."} {"_id":"q-en-rust-3a5456e39887f8e298ea31124373da8e402e4cf39133e871b3b3dab6c1e7564d","text":"} return Ok((res, Some(path_str.to_owned()))); } other => { debug!( \"failed to resolve {} in namespace {:?} (got {:?})\", path_str, ns, other ); Res::Def(DefKind::Mod, _) => { // This resolved to a module, but if we were passed `type@`, // we want primitive types to take precedence instead. if disambiguator == Some(\"type\") { if let Some(prim) = is_primitive(path_str, ns) { if extra_fragment.is_some() { return Err(ErrorKind::AnchorFailure( \"primitive types cannot be followed by anchors\", )); } return Ok((prim, Some(path_str.to_owned()))); } } return Ok((res, extra_fragment.clone())); } _ => { return Ok((res, extra_fragment.clone())); } };"} {"_id":"q-en-rust-3a949dac23df745088494dcd313d0e967d0e3a4839661dc6d1f801052f2dbe55","text":" struct Foo { field1: u8, field2: u8, } fn main() { let foo = Foo { field1: 1, field2: 2 }; let Foo { var @ field1, .. } = foo; //~ ERROR Unexpected `@` in struct pattern dbg!(var); //~ ERROR cannot find value `var` in this scope let Foo { field1: _, bar @ .. } = foo; //~ ERROR `@ ..` is not supported in struct patterns let Foo { bar @ .. } = foo; //~ ERROR `@ ..` is not supported in struct patterns let Foo { @ } = foo; //~ ERROR expected identifier, found `@` let Foo { @ .. } = foo; //~ ERROR expected identifier, found `@` } "} {"_id":"q-en-rust-3ab5396e9788275cf7d302ffe6b172abd04bfe53f3cf6d45e18c552969b18e5b","text":"t } fn ambiguity( &self, kind: AmbiguityKind, primary_binding: &'a NameBinding<'a>, secondary_binding: &'a NameBinding<'a>, ) -> &'a NameBinding<'a> { self.arenas.alloc_name_binding(NameBinding { ambiguity: Some((secondary_binding, kind)), ..primary_binding.clone() }) } // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed // or indeterminate resolution, also mark such failed imports as used to avoid duplicate diagnostics. fn import_dummy_binding(&mut self, import: &'a Import<'a>, is_indeterminate: bool) {"} {"_id":"q-en-rust-3b42e2d73f1d75534bf57c6048c0ac6685ad34671fac3b0456591435dd10107d","text":"use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_middle::ty; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::Ty; use rustc_middle::ty::TypeFoldable; use rustc_middle::ty::{AdtKind, Visibility};"} {"_id":"q-en-rust-3b53bcc9e02a53fade0a0b079c172530088050a63137fb3513ab7a880af49bf3","text":"} log_rpaths(\"relative\", rel_rpaths); log_rpaths(\"absolute\", abs_rpaths); log_rpaths(\"fallback\", fallback_rpaths); let mut rpaths = rel_rpaths; rpaths.push_all(abs_rpaths); rpaths.push_all(fallback_rpaths); // Remove duplicates"} {"_id":"q-en-rust-3c3a5dc1f3eaabefbb0a98c7d952f7db919ba5a263953278138cb95be0625bbd","text":"#[test] fn uninit_write_slice_cloned_no_drop() { let rc = Rc::new(()); #[derive(Clone)] struct Bomb; impl Drop for Bomb { fn drop(&mut self) { panic!(\"dropped a bomb! kaboom\") } } let mut dst = [MaybeUninit::uninit()]; let src = [rc.clone()]; let src = [Bomb]; MaybeUninit::write_slice_cloned(&mut dst, &src); drop(src); assert_eq!(Rc::strong_count(&rc), 2); forget(src); }"} {"_id":"q-en-rust-3c4167a008006e27bbb2144ac56593930b70362439784e9d75bce1f48e554d61","text":"check-custom-code-classes collect-trait-impls check_doc_test_visibility strip-aliased-non-local strip-hidden (when not --document-hidden-items) strip-private (when not --document-private-items) strip-priv-imports (when --document-private-items)"} {"_id":"q-en-rust-3c4f14bbea90d8ce8a96bb5e7d8d6d581aeffbbef35c2fd9357c48e1b073a00d","text":"fn check_item_safety(&self, span: Span, safety: Safety) { match self.extern_mod_safety { Some(extern_safety) => { if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_)) && (extern_safety == Safety::Default || !self.features.unsafe_extern_blocks) { self.dcx().emit_err(errors::InvalidSafetyOnExtern { item_span: span, block: self.current_extern_span().shrink_to_lo(), }); if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_)) { if extern_safety == Safety::Default { self.dcx().emit_err(errors::InvalidSafetyOnExtern { item_span: span, block: Some(self.current_extern_span().shrink_to_lo()), }); } else if !self.features.unsafe_extern_blocks { self.dcx().emit_err(errors::InvalidSafetyOnExtern { item_span: span, block: None, }); } } } None => {"} {"_id":"q-en-rust-3c60941ba181e276780d7fd57532f6a8532b93d9d80c9d49852d474d55c53eb9","text":"pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t) -> io::Result { // Unfortunately the only known way right now to accept a socket and // atomically set the CLOEXEC flag is to use the `accept4` syscall on // Linux. This was added in 2.6.28, however, and because we support // 2.6.18 we must detect this support dynamically. #[cfg(target_os = \"linux\")] { syscall! { fn accept4( fd: c_int, addr: *mut sockaddr, addr_len: *mut socklen_t, flags: c_int ) -> c_int } let res = cvt_r(|| unsafe { accept4(self.0.raw(), storage, len, libc::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), // Linux. This was added in 2.6.28, glibc 2.10 and musl 0.9.5. cfg_if::cfg_if! { if #[cfg(target_os = \"linux\")] { let fd = cvt_r(|| unsafe { libc::accept4(self.0.raw(), storage, len, libc::SOCK_CLOEXEC) })?; Ok(Socket(FileDesc::new(fd))) } else { let fd = cvt_r(|| unsafe { libc::accept(self.0.raw(), storage, len) })?; let fd = FileDesc::new(fd); fd.set_cloexec()?; Ok(Socket(fd)) } } let fd = cvt_r(|| unsafe { libc::accept(self.0.raw(), storage, len) })?; let fd = FileDesc::new(fd); fd.set_cloexec()?; Ok(Socket(fd)) } pub fn duplicate(&self) -> io::Result {"} {"_id":"q-en-rust-3c6d5af8798572d39eb29fb6bb7d0f0f26c878ae203f507996537dfb63843969","text":" - // MIR for `size_of` before ConstProp + // MIR for `size_of` after ConstProp fn size_of() -> usize { let mut _0: usize; let mut _1: usize; scope 1 { debug a => _1; } bb0: { StorageLive(_1); _1 = const 0_usize; _1 = const _; _0 = _1; StorageDead(_1); return; } } "} {"_id":"q-en-rust-3c91899df1cd0846e01fe9a78752be617779db5a17ca211bf04056fb4b6112ec","text":"let mut where_clause = WhereClause { id: ast::DUMMY_NODE_ID, predicates: Vec::new(), span: DUMMY_SP, span: self.prev_span.to(self.prev_span), }; if !self.eat_keyword(kw::Where) {"} {"_id":"q-en-rust-3cca6c67052f4e3025558af047f67eb2bfb51e4e5e8747d8c8f014ccc27d3667","text":"op_to_const(&ecx, field) } pub fn const_caller_location<'tcx>( pub(crate) fn const_caller_location<'tcx>( tcx: TyCtxt<'tcx>, (file, line, col): (Symbol, u32, u32), ) -> &'tcx ty::Const<'tcx> {"} {"_id":"q-en-rust-3cdb716568947800dc660665d46637966e4ec7ae4633aad377ba78cbad116ae9","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":"q-en-rust-3ce57ab86841a560619900eecfb26297a97ed7fe87ce2fd10fee219b9c79aa8f","text":"#[plugin_registrar] pub fn registrar() {} //~^ ERROR compiler plugins are experimental //~| HELP add #![feature(plugin_registrar)] to the crate attributes to enable fn main() {}"} {"_id":"q-en-rust-3ce6b10678432af7d083a78f73b0eb71d8402ab5aef0da749d7c519c45bf280c","text":"If you do, Rust has been installed successfully! Congrats! If you don't and you're on Windows, check that Rust is in your %PATH% system variable: `$ echo %PATH%`. If it isn't, run the installer again, select \"Change\" on the \"Change, repair, or remove installation\" page and ensure \"Add to PATH\" is installed on the local hard drive. If you need to configure your path manually, you can find the Rust executables in a directory like `\"C:Program FilesRust stable GNU 1.xbin\"`. If you don't, that probably means that the `PATH` environment variable doesn't include Cargo's binary directory, `~/.cargo/bin` on Unix, or `%USERPROFILE%.cargobin` on Windows. This is the directory where Rust development tools live, and most Rust developers keep it in their `PATH` environment variable, which makes it possible to run `rustc` on the command line. Due to differences in operating systems, command shells, and bugs in installation, you may need to restart your shell, log out of the system, or configure `PATH` manually as appropriate for your operating environment. 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. For"} {"_id":"q-en-rust-3d43b3ea17dd8c1db412a19353c0774a71876785262b60c4e3cd2b8a8b3fcfab","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. #![deny(unnecessary_extern_crate)] #![feature(alloc, test, libc)] extern crate alloc; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP remove extern crate alloc as x; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP use `use` #[macro_use] extern crate test; pub extern crate test as y; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP use `pub use` pub extern crate libc; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP use `pub use` mod foo { extern crate alloc; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP use `use` extern crate alloc as x; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP use `use` pub extern crate test; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP use `pub use` pub extern crate test as y; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP use `pub use` mod bar { extern crate alloc; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP use `use` extern crate alloc as x; //~^ ERROR `extern crate` is unnecessary in the new edition //~| HELP use `use` } } fn main() {} "} {"_id":"q-en-rust-3d45253a97c0ad17b8e2645d4ddacdf77e35bbde1534e3d4454b08e229519574","text":" // run-pass #![feature(inline_const)] // Makes sure we don't propagate generic instances of `Self: ?Sized` blanket impls. // This is relevant when we have an overlapping impl and builtin dyn instance. // See for more context. trait Trait { fn foo(&self) -> &'static str; } impl Trait for T { fn foo(&self) -> &'static str { std::any::type_name::() } } fn bar() -> fn(&T) -> &'static str { const { Trait::foo as fn(&T) -> &'static str } // If const prop were to propagate the instance } fn main() { assert_eq!(\"i32\", bar::()(&1i32)); } "} {"_id":"q-en-rust-3d865ec8ac6d7117b574a371e2b82064ed77e3a23ed6b1a8da0d809fadc701bd","text":"_ => unreachable!(), }; write_or_print(&out, ofile); write_or_print(&out, ofile, tcx.sess); Ok(()) }"} {"_id":"q-en-rust-3da34d5c1259de633307d5029413d5165afe9b4464c554e8f4777f299ba2d5fa","text":" fn main() { while let 1 = 1 { vec![].last_mut().unwrap() = 3_u8; //~^ ERROR invalid left-hand side of assignment } } "} {"_id":"q-en-rust-3da4346c9aa35c7a9496ca681a316886ecd61237d8647384bb79cfe412f67a75","text":"use std::cell::Cell; use std::mem; use std::ops::{Deref, DerefMut}; /// Type lambda application, with a lifetime. #[allow(unused_lifetimes)]"} {"_id":"q-en-rust-3dc7b2914eef5b234f7ac8e5ca2499f6586104fd048468e24237788ca06cc85d","text":"#![feature(plugin, custom_attribute)] #![plugin(lint_for_crate)] #![crate_okay] #![crate_blue] #![crate_red] #![crate_grey] #![crate_green] pub fn main() { }"} {"_id":"q-en-rust-3df599cc31470603d1a2ec3df8fde21cb1e5c23917a624c3e41bf912284d9f78","text":"_ => false, } } pub fn is_known_rigid(self) -> bool { match self.kind() { Bool | Char | Int(_) | Uint(_) | Float(_) | Adt(_, _) | Foreign(_) | Str | Array(_, _) | Slice(_) | RawPtr(_) | Ref(_, _, _) | FnDef(_, _) | FnPtr(_) | Dynamic(_, _, _) | Closure(_, _) | Generator(_, _, _) | GeneratorWitness(_) | GeneratorWitnessMIR(_, _) | Never | Tuple(_) => true, Error(_) | Infer(_) | Alias(_, _) | Param(_) | Bound(_, _) | Placeholder(_) => false, } } } /// Extra information about why we ended up with a particular variance."} {"_id":"q-en-rust-3df7083aa64a9b0a9ffa82aad0b163b14a7c10f65c7649fabd23993b843bfad9","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. //! Dox // @has src/foo/qux/mod.rs.html // @has foo/qux/index.html '//a/@href' '../../src/foo/qux/mod.rs.html' // @has foo/qux/bar/index.html '//a/@href' '../../../src/foo/qux/mod.rs.html' pub mod bar { /// Dox // @has foo/qux/bar/baz/index.html '//a/@href' '../../../../src/foo/qux/mod.rs.html' pub mod baz { /// Dox // @has foo/qux/bar/baz/fn.baz.html '//a/@href' '../../../../src/foo/qux/mod.rs.html' pub fn baz() { } } /// Dox // @has foo/qux/bar/trait.Foobar.html '//a/@href' '../../../src/foo/qux/mod.rs.html' pub trait Foobar { fn dummy(&self) { } } // @has foo/qux/bar/struct.Foo.html '//a/@href' '../../../src/foo/qux/mod.rs.html' pub struct Foo { x: i32, y: u32 } // @has foo/qux/bar/fn.prawns.html '//a/@href' '../../../src/foo/qux/mod.rs.html' pub fn prawns((a, b): (i32, u32), Foo { x, y }: Foo) { } } /// Dox // @has foo/qux/fn.modfn.html '//a/@href' '../../src/foo/qux/mod.rs.html' pub fn modfn() { } "} {"_id":"q-en-rust-3e7625c96968e014926438559ef2269194b0cbd8e2d31e937c07c60eb1b6a1bc","text":".enumerate() .skip(1) // Remove `Self` for `ExistentialPredicate`. .map(|(index, arg)| { if let ty::GenericArgKind::Type(ty) = arg.unpack() { debug!(?ty); if ty == dummy_self { let param = &generics.params[index]; missing_type_params.push(param.name); tcx.ty_error().into() } else if ty.walk().any(|arg| arg == dummy_self.into()) { references_self = true; tcx.ty_error().into() } else { arg } } else { arg if arg == dummy_self.into() { let param = &generics.params[index]; missing_type_params.push(param.name); return tcx.ty_error().into(); } else if arg.walk().any(|arg| arg == dummy_self.into()) { references_self = true; return tcx.ty_error().into(); } arg }) .collect(); let substs = tcx.intern_substs(&substs[..]);"} {"_id":"q-en-rust-3e8de5b10fe227ad7cbd1cbf92594ba5cbd692bfba9a4436a8296437fdc37510","text":"// of the function signature. In our example, the GAT in the return // type is `::Item<'a>`, so 'a and Self are arguments. let (regions, types) = GATSubstCollector::visit(trait_item.def_id.to_def_id(), sig.output()); GATSubstCollector::visit(tcx, trait_item.def_id.to_def_id(), sig.output()); // If both regions and types are empty, then this GAT isn't in the // return type, and we shouldn't try to do clause analysis"} {"_id":"q-en-rust-3e9edb9d3e2b507ddc077f8a8f45b28e578e5b8b1707593bfd20c8aaffbf4c51","text":"/// Parses the fields of a struct-like pattern. fn parse_pat_fields(&mut self) -> PResult<'a, (ThinVec, PatFieldsRest)> { let mut fields = ThinVec::new(); let mut fields: ThinVec = ThinVec::new(); let mut etc = PatFieldsRest::None; let mut ate_comma = true; let mut delayed_err: Option> = None;"} {"_id":"q-en-rust-3ee5fbaaec92ccdf8fbdeec8b4fbc842f5d784c746b41435822826f3042587d0","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":"q-en-rust-3f19086fcb897b6ddd8d2eee6042b8f84be1308e98e761f63c92af372a153a71","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":"q-en-rust-3f27980dc77d193d414f62de2e83ae4d7b8d5da73864aa08f5276dada1aac22b","text":"Ident::new(keywords::SelfLower.name(), new_span) ), kind: ast::UseTreeKind::Simple( Some(Ident::new(keywords::Underscore.name().gensymed(), new_span)), Some(Ident::new(Name::gensym(\"__dummy\"), new_span)), ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID, ),"} {"_id":"q-en-rust-3f2f395aa2a5035dc78a459491e75f5af833a5c6fe615f540fd767cb9489c89d","text":"fn visit(&mut self, span: Span, value: impl TypeVisitable>) -> Self::Result; } #[instrument(level = \"trace\", skip(tcx, visitor))] pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( tcx: TyCtxt<'tcx>, item: LocalDefId,"} {"_id":"q-en-rust-3f5621ec2297f66fea1e4a9d3990b52762a6e1ada1aa8a31827e804ecc843600","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":"q-en-rust-3f6fc77158ec1f38d77b1b9de09eb4f692f8f4e2ecf7c1e7bde88c2ee45077f2","text":"let link_meta = self.link_meta; let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro); let root = self.lazy(&CrateRoot { rustc_version: rustc_version(), name: link_meta.crate_name, triple: tcx.sess.opts.target_triple.clone(), hash: link_meta.crate_hash,"} {"_id":"q-en-rust-3f9f0805fa0df31fe1c63fa293eeb4ec5b7e32339ba025b0b5c19fff77ee52a6","text":" // check-pass #![feature(type_alias_impl_trait)] fn opaque<'a: 'a>() -> impl Sized {} fn assert_static(_: T) {} fn test_closure() { let closure = |_| { assert_static(opaque()); }; closure(&opaque()); } type Opaque<'a> = impl Sized; fn define<'a>() -> Opaque<'a> {} fn test_tait(_: &Opaque<'_>) { None::<&'static Opaque<'_>>; } fn main() {} "} {"_id":"q-en-rust-3fb0c9f1061962cad777f2f78411e1043327a77915b10d3442eef6af61eca2d7","text":"unstable(\"linker\", |o| { o.optopt(\"\", \"linker\", \"linker used for building executable test code\", \"PATH\") }), unstable(\"sort-modules-by-appearance\", |o| { o.optflag(\"\", \"sort-modules-by-appearance\", \"sort modules by where they appear in the program, rather than alphabetically\") }), ] }"} {"_id":"q-en-rust-3fb27a961c1e25e8858ea3226117b0265673343c450f7323ade9d4887512aa3e","text":"/// For most cases with placeholders, this function will return `None`. /// /// See [`fmt::Arguments::as_str`] for details. #[unstable(feature = \"panic_info_message\", issue = \"66745\")] #[stable(feature = \"panic_info_message\", since = \"CURRENT_RUSTC_VERSION\")] #[rustc_const_unstable(feature = \"const_arguments_as_str\", issue = \"103900\")] #[must_use] #[inline]"} {"_id":"q-en-rust-3ff8af9a12a070977a537a4e2eddb211b3756fcd520d2ce6853fb8ca43dd5730","text":" //@ known-bug: #124342 trait Trait2 : Trait { reuse <() as Trait>::async { (async || {}).await; }; } "} {"_id":"q-en-rust-402d497f49da8707f6d3594496b673d3f284feda688b8ce0b0998c86fa0512cb","text":".filter(|item| matches!(item.kind, ty::AssocKind::Fn) && !item.fn_has_self_parameter) .filter_map(|item| { // Only assoc fns that return `Self`, `Option` or `Result`. let ret_ty = self.tcx.fn_sig(item.def_id).skip_binder().output(); let ret_ty = self .tcx .fn_sig(item.def_id) .instantiate(self.tcx, self.fresh_args_for_item(DUMMY_SP, item.def_id)) .output(); let ret_ty = self.tcx.instantiate_bound_regions_with_erased(ret_ty); let ty::Adt(def, args) = ret_ty.kind() else { return None;"} {"_id":"q-en-rust-4042c629dfd8f6d2e5f941d52e66cb441f9a5c0ffb8d7e68fe5774efa8791a7f","text":"// For additional insurance via fuzzing and crater, we verify that the constraint's min // choice indeed escapes the function. In the future, we could e.g. turn this check into // a debug assert and early return as an optimization. let scc = sccs.scc(successor); for constraint in self.regioncx.applied_member_constraints(scc) { if universal_regions.is_universal_region(constraint.min_choice) { return;"} {"_id":"q-en-rust-4043b98b105bd8e0e4662e7a08ee258ed48f18039fa37e8ac2a223456247b67f","text":"T: Iterator, { let max_dist = dist.map_or_else(|| cmp::max(lookup.len(), 3) / 3, |d| d); let name_vec: Vec<&Symbol> = iter_names.collect(); let (case_insensitive_match, levenstein_match) = iter_names let (case_insensitive_match, levenshtein_match) = name_vec .iter() .filter_map(|&name| { let dist = lev_distance(lookup, &name.as_str()); if dist <= max_dist { Some((name, dist)) } else { None } }) // Here we are collecting the next structure: // (case_insensitive_match, (levenstein_match, levenstein_distance)) // (case_insensitive_match, (levenshtein_match, levenshtein_distance)) .fold((None, None), |result, (candidate, dist)| { ( if candidate.as_str().to_uppercase() == lookup.to_uppercase() {"} {"_id":"q-en-rust-40456a439eb148fbe6307782f36e271545ef5e509e249aedf90567082becc483","text":" // no-prefer-dynamic #![allow(dead_code)] // check dtor calling order when casting enums."} {"_id":"q-en-rust-4073e6f2e7c0469af4b8f9a58d937574fad2aeb6cadf9b6e52ff8263f6be5af1","text":"// Will be filed with the root position after encoding everything. cursor.write_all(&[0, 0, 0, 0]).unwrap(); let root = EncodeContext { let root = { let mut ecx = EncodeContext { opaque: opaque::Encoder::new(&mut cursor), tcx: tcx, reexports: reexports,"} {"_id":"q-en-rust-40776aa709422d31637eee4ba52d28852f7bb932c84b019aa3cb97a4608dc555","text":"#![feature(maybe_uninit_uninit_array)] #![feature(maybe_uninit_write_slice)] #![feature(panic_can_unwind)] #![feature(panic_info_message)] #![feature(panic_internals)] #![feature(pointer_is_aligned_to)] #![feature(portable_simd)]"} {"_id":"q-en-rust-40bafc2520cc2e8bef82f98c4b177b4eb4580d004e1e34550cb09e5c25515344","text":"fn visit_assign(&mut self, place: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) { self.super_assign(place, rvalue, location); let Some(()) = self.check_rvalue(rvalue) else { return }; let Some(()) = self.check_rvalue(rvalue) else { trace!(\"rvalue check failed, removing const\"); Self::remove_const(&mut self.ecx, place.local); return; }; match self.ecx.machine.can_const_prop[place.local] { // Do nothing if the place is indirect."} {"_id":"q-en-rust-40df3106270a89f4dafa079df0accec62a7882a203084ad29f5117b2bdbd4155","text":"/// # Examples /// /// ```no_run /// #![feature(rw_exact_all_at)] /// use std::fs::File; /// use std::io; /// use std::os::unix::prelude::FileExt;"} {"_id":"q-en-rust-4101ec2b02c3d83eeba62bc895fddbe7c1b267c0c7fcc283de0bae488e26f53c","text":"pure fn ne(other: &Dest) -> bool { !self.eq(other) } } fn drop_and_cancel_clean(dat: Datum, bcx: block) -> block { let bcx = dat.drop_val(bcx); dat.cancel_clean(bcx); return bcx; } fn trans_to_datum(bcx: block, expr: @ast::expr) -> DatumBlock { debug!(\"trans_to_datum(expr=%s)\", bcx.expr_to_str(expr));"} {"_id":"q-en-rust-41073ca40f1d61a42f2f3f424f4dabd162625dda20abfe2e74059f41d76ae37c","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":"q-en-rust-4118165c523d71b4bf3ced26103975d720aa034de2429de35d0305f24dac69c8","text":"} fn run(self, builder: &Builder<'_>) -> Option { // This prevents miri from being built for \"dist\" or \"install\" // on the stable/beta channels. It is a nightly-only tool and should // not be included. if !builder.build.unstable_features() { return None; } let compiler = self.compiler; let target = self.target; assert!(builder.config.extended);"} {"_id":"q-en-rust-419f0df15adbf6ef8ca10d30b9bdd0c91c4c1f2beacbfa09abb9ebb92b42e686","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":"q-en-rust-41d7cf6444a9c0ce9f67d065b95d668678d2cf9cee9efa1d69f1df55818ba346","text":"LifetimeReturnCategoryErr, RequireStaticErr, VarHereDenote, }; use super::{OutlivesSuggestionBuilder, RegionName}; use super::{OutlivesSuggestionBuilder, RegionName, RegionNameSource}; use crate::region_infer::{BlameConstraint, ExtraConstraintInfo}; use crate::{ nll::ConstraintDescription,"} {"_id":"q-en-rust-41ea0fa0170d270d266ee5b9916f07f4bbf6bb96db16f6abae33ce8ec68e4e35","text":"let used_link_args = &trans.crate_info.link_args; if crate_type == config::CrateTypeExecutable && t.options.position_independent_executables { let empty_vec = Vec::new(); let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec); let more_args = &sess.opts.cg.link_arg; let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter()); if get_reloc_model(sess) == llvm::RelocMode::PIC && !sess.crt_static() && !args.any(|x| *x == \"-static\") { if crate_type == config::CrateTypeExecutable { let mut position_independent_executable = false; if t.options.position_independent_executables { let empty_vec = Vec::new(); let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec); let more_args = &sess.opts.cg.link_arg; let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter()); if get_reloc_model(sess) == llvm::RelocMode::PIC && !sess.crt_static() && !args.any(|x| *x == \"-static\") { position_independent_executable = true; } } if position_independent_executable { cmd.position_independent_executable(); } else { // recent versions of gcc can be configured to generate position // independent executables by default. We have to pass -no-pie to // explicitly turn that off. if sess.target.target.options.linker_is_gnu { cmd.no_position_independent_executable(); } } }"} {"_id":"q-en-rust-41f6bf5b80da86880eb6ece7a50799882d3cb19c8da0e701bf346aee6db2fab1","text":"Some(ExpectedSig { cause_span, sig }) } /// When an async closure is passed to a function that has a \"two-part\" `Fn` /// and `Future` trait bound, like: /// /// ```rust /// use std::future::Future; /// /// fn not_exactly_an_async_closure(_f: F) /// where /// F: FnOnce(String, u32) -> Fut, /// Fut: Future, /// {} /// ``` /// /// The we want to be able to extract the signature to guide inference in the async /// closure. We will have two projection predicates registered in this case. First, /// we identify the `FnOnce` bound, and if the output type is /// an inference variable `?Fut`, we check if that is bounded by a `Future` /// projection. fn extract_sig_from_projection_and_future_bound( &self, cause_span: Option, projection: ty::PolyProjectionPredicate<'tcx>, ) -> Option> { let projection = self.resolve_vars_if_possible(projection); let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1); debug!(?arg_param_ty); let ty::Tuple(input_tys) = *arg_param_ty.kind() else { return None; }; // If the return type is a type variable, look for bounds on it. // We could theoretically support other kinds of return types here, // but none of them would be useful, since async closures return // concrete anonymous future types, and their futures are not coerced // into any other type within the body of the async closure. let ty::Infer(ty::TyVar(return_vid)) = *projection.skip_binder().term.expect_type().kind() else { return None; }; // FIXME: We may want to elaborate here, though I assume this will be exceedingly rare. for bound in self.obligations_for_self_ty(return_vid) { if let Some(ret_projection) = bound.predicate.as_projection_clause() && let Some(ret_projection) = ret_projection.no_bound_vars() && self.tcx.is_lang_item(ret_projection.def_id(), LangItem::FutureOutput) { let sig = projection.rebind(self.tcx.mk_fn_sig( input_tys, ret_projection.term.expect_type(), false, hir::Safety::Safe, Abi::Rust, )); return Some(ExpectedSig { cause_span, sig }); } } None } fn sig_of_closure( &self, expr_def_id: LocalDefId,"} {"_id":"q-en-rust-423911300284cb2d5c84dc23af76c012fd857444f83b9daba7204312ed1c5415","text":"} else { LifetimeUseSet::Many }), LifetimeRibKind::Generics { .. } => None, LifetimeRibKind::ConstGeneric | LifetimeRibKind::AnonConst => { LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstGeneric => None, LifetimeRibKind::AnonConst => { span_bug!(ident.span, \"unexpected rib kind: {:?}\", rib.kind) } })"} {"_id":"q-en-rust-424c87b4f575b89e02877c0c942cfe95a32de8d2f3f5097da55fb8620129b455","text":"Level::Cancelled => { false } }; self.handler.emit_db(&self); self.cancel(); if is_error { self.handler.bump_err_count(); } // if self.is_fatal() { // panic!(FatalError); // } } /// Convenience function for internal use, clients should use one of the"} {"_id":"q-en-rust-4268d815a878dc31eb8c4eaa00393b8a25e226865d6e46a6805f53e75f9ca64c","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. #[allow(dead_code)] fn check(a: &str) { let x = a as *const str; x == x; } fn main() {} "} {"_id":"q-en-rust-429abe5e2206decacaf10dc3fbce07a09447d0f9893e3c2b08b23a101c0dd4d8","text":"without modifying the original\"] #[inline] #[track_caller] #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] pub const fn ilog2(self) -> u32 { match self.checked_ilog2() { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } self.checked_ilog2().expect(\"argument of integer logarithm must be positive\") } /// Returns the base 10 logarithm of the number, rounded down. /// /// # Panics /// /// When the number is zero it panics in debug mode and the /// return value is 0 in release mode. /// This function will panic if `self` is zero. /// /// # Example ///"} {"_id":"q-en-rust-42d76c3e09b5dc25c145c0f94b91dafbb5e7ea0345b8389fb8443c0a4d42d7b1","text":"| ^^^^^^^^^^^^^^^^^^^^^^^ error: this lint expectation is unfulfilled --> tests/ui/expect_tool_lint_rfc_2383.rs:36:18 | LL | #[expect(invalid_nan_comparisons)] | ^^^^^^^^^^^^^^^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: this lint expectation is unfulfilled --> tests/ui/expect_tool_lint_rfc_2383.rs:107:14 | LL | #[expect(clippy::almost_swapped)]"} {"_id":"q-en-rust-42fdaf7f0ece255b53eea55539c80cf903e22531950554ae0795e62bc9bacc2f","text":"fn clone(&self) -> Self { *self } } fn main() { let one = (Some(Packed((&(), 0))), true); fn sanity_check_size(one: T) { let two = [one, one]; let stride = (&two[1] as *const _ as usize) - (&two[0] as *const _ as usize); assert_eq!(stride, std::mem::size_of_val(&one)); } fn main() { // This can fail if rustc and LLVM disagree on the size of a type. // In this case, `Option>` was erronously not // marked as packed despite needing alignment `1` and containing // its `&()` discriminant, which has alignment larger than `1`. assert_eq!(stride, std::mem::size_of_val(&one)); sanity_check_size((Some(Packed((&(), 0))), true)); // In #46769, `Option<(Packed<&()>, bool)>` was found to have // pointer alignment, without actually being aligned in size. // E.g. on 64-bit platforms, it had alignment `8` but size `9`. sanity_check_size(Some((Packed(&()), true))); }"} {"_id":"q-en-rust-4317147c52161e7c8bcc4a951a24f5c6a83a1907bb9107761c037847a1b988eb","text":" // compile-flags: --test --persist-doctests /../../ -Z unstable-options // failure-status: 101 // only-linux #![crate_name = \"foo\"] //! ```rust //! use foo::dummy; //! dummy(); //! ``` "} {"_id":"q-en-rust-434589c74bebc1034d4a2cca8ca4d2d278017e67f24b727b6edc4ff051da8fb9","text":"#![feature(const_int_unchecked_arith)] #![feature(const_mut_refs)] #![feature(const_refs_to_cell)] #![feature(const_cttz)] #![feature(const_panic)] #![feature(const_pin)] #![feature(const_fn)]"} {"_id":"q-en-rust-434eb19ef9c7fa0aafd32c5d0e695220e79d05e0fa8554a278b1fd40e7b6541c","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. // ignore-windows // ignore-tidy-linelength // compile-flags: -g -C metadata=foo -C no-prepopulate-passes // aux-build:xcrate-generic.rs #![crate_type = \"lib\"] extern crate xcrate_generic; pub fn foo() { xcrate_generic::foo::(); } // Here we check that local debuginfo is mapped correctly. // CHECK: !DIFile(filename: \"/the/aux-src/xcrate-generic.rs\", directory: \"\") "} {"_id":"q-en-rust-436aae6aaf026f203711e7f11e2d82f7a9caf2ef2318645a080d1fdb79471d7c","text":"tmp } } } }; // Trailing comma with single argument is ignored ($val:expr,) => { dbg!($val) }; ($($val:expr),+ $(,)?) => { ($(dbg!($val)),+,) }; } /// Awaits the completion of an async call."} {"_id":"q-en-rust-437a88cc7bdddfd8ba8add1844d77dbc4e3feaa9f3cbec1f03691f8d80863c44","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":"q-en-rust-4384e3095a167550012728ef4312915a1d80cc68ffcaedb51af676adf16b8bf6","text":"// If a string was expected and the found expression is a character literal, // perhaps the user meant to write `\"s\"` to specify a string literal. (ty::Ref(_, r, _), ty::Char) if r.is_str() => { suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral { start: span.with_hi(span.lo() + BytePos(1)), end: span.with_lo(span.hi() - BytePos(1)), }) if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) && code.starts_with(\"'\") && code.ends_with(\"'\") { suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral { start: span.with_hi(span.lo() + BytePos(1)), end: span.with_lo(span.hi() - BytePos(1)), }); } } // For code `if Some(..) = expr `, the type mismatch may be expected `bool` but found `()`, // we try to suggest to add the missing `let` for `if let Some(..) = expr`"} {"_id":"q-en-rust-43dfcf358157d3aea9b597b0480d9d21111bcb7def5cc0a258cd40113fec2089","text":" // compile-flags: -Zsave-analysis // Check that this doesn't ICE when processing associated const (type). fn func() { trait Trait { type MyType; const CONST: Self::MyType = bogus.field; //~ ERROR cannot find value `bogus` } } fn main() {} "} {"_id":"q-en-rust-43eb3e20efc4a9cd59bd9bb82d11bb239abd09e9887a5ccdaa411916cafd57e4","text":"return Ok(()); } let param_env = tcx.param_env(impl_ty.def_id); // Given // // impl Foo for (A, B) {"} {"_id":"q-en-rust-43fd9a5f0fda2e87a35419055c91eb80c625022d4758aa52edb208bac4e2c287","text":" //@ known-bug: #116308 #![feature(adt_const_params)] pub trait Identity { type Identity; } impl Identity for T { type Identity = Self; } pub fn foo::Identity>() {} fn main() { foo::<12>(); } "} {"_id":"q-en-rust-44066dc9c2737fb49f9abb236761b25682de91546e70fe94132ac4af45a941ef","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:panic evaluated #[allow(unused_variables)] fn main() { // This used to trigger an LLVM assertion during compilation let x = [panic!(\"panic evaluated\"); 2]; } "} {"_id":"q-en-rust-442703d00e0cde9bece0db79e7ad7ad1f963f4c209821aed968b2eef86e17c41","text":"if tcx.fn_sig(did).skip_binder().abi() == RustIntrinsic && tcx.item_name(did) == sym::transmute { let from = fn_sig.inputs().skip_binder()[0]; let Some(from) = fn_sig.inputs().skip_binder().get(0) else { let e = self.dcx().span_delayed_bug( tcx.def_span(did), \"intrinsic fn `transmute` defined with no parameters\", ); self.set_tainted_by_errors(e); return Ty::new_error(tcx, e); }; let to = fn_sig.output().skip_binder(); // We defer the transmute to the end of typeck, once all inference vars have // been resolved or we errored. This is important as we can only check transmute // on concrete types, but the output type may not be known yet (it would only // be known if explicitly specified via turbofish). self.deferred_transmute_checks.borrow_mut().push((from, to, expr.hir_id)); self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id)); } if !tcx.features().unsized_fn_params { // We want to remove some Sized bounds from std functions,"} {"_id":"q-en-rust-4441e8c48370f0b0ee8199e8fd8adfbde25df7c4f15cf5b7c4b015abb38b3eb6","text":"cargo, rustc, rustfmt, cargo_clippy, docs, compiler_docs, library_docs_private_items,"} {"_id":"q-en-rust-447ceb55c280ffe8dd699cfcfb2cb6dbd1f282f0e2987d758006a3f12583aa57","text":"[[package]] name = \"racer\" version = \"2.1.48\" version = \"2.2.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"7fec2e85e7a30f8fd31b7cf288ad363b5e51fd2cb6f53b416b0cfaabd84e1ccb\" checksum = \"b0b4b5faaf07040474e8af74a9e19ff167d5d204df5db5c5c765edecfb900358\" dependencies = [ \"bitflags\", \"clap 2.34.0\","} {"_id":"q-en-rust-44817d088270d812582dd36fb35136a94b0e62ec7c395fb9a61ded594403cffb","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":"q-en-rust-44a90984de736df9a4c14cd90592e41e21577c4dec40c2cc66ea6dc3eb4fab39","text":" Subproject commit 5d967343acae16fd7b53a61e6cd4e93a1ac6f199 Subproject commit 569507ef2beefcce4b666af41e09276f06445e96 "} {"_id":"q-en-rust-4536062f2f3fc3305c89989cee2288b082f39477adbba07b39a29d5a80fc0b42","text":"use super::*; use rustc_span::source_map::DUMMY_SP; fn create_doc_fragment(s: &str) -> Vec { vec![DocFragment { line: 0, span: DUMMY_SP, parent_module: None, doc: s.to_string(), kind: DocFragmentKind::SugaredDoc, }] } #[track_caller] fn run_test(input: &str, expected: &str) { let mut s = create_doc_fragment(input); unindent_fragments(&mut s); assert_eq!(s[0].doc, expected); } #[test] fn should_unindent() { let s = \" line1n line2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1nline2\"); run_test(\" line1n line2\", \"line1nline2\"); } #[test] fn should_unindent_multiple_paragraphs() { let s = \" line1nn line2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1nnline2\"); run_test(\" line1nn line2\", \"line1nnline2\"); } #[test] fn should_leave_multiple_indent_levels() { // Line 2 is indented another level beyond the // base indentation and should be preserved let s = \" line1nn line2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1nn line2\"); run_test(\" line1nn line2\", \"line1nn line2\"); } #[test] fn should_ignore_first_line_indent() { // The first line of the first paragraph may not be indented as // far due to the way the doc string was written: // // #[doc = \"Start way over here // and continue here\"] let s = \"line1n line2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1nline2\"); run_test(\"line1n line2\", \"line1n line2\"); } #[test] fn should_not_ignore_first_line_indent_in_a_single_line_para() { let s = \"line1nn line2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1nn line2\"); run_test(\"line1nn line2\", \"line1nn line2\"); } #[test] fn should_unindent_tabs() { let s = \"tline1ntline2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1nline2\"); run_test(\"tline1ntline2\", \"line1nline2\"); } #[test] fn should_trim_mixed_indentation() { let s = \"t line1nt line2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1nline2\"); let s = \" tline1n tline2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1nline2\"); run_test(\"t line1nt line2\", \"line1nline2\"); run_test(\" tline1n tline2\", \"line1nline2\"); } #[test] fn should_not_trim() { let s = \"t line1 nt line2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1 nline2\"); let s = \" tline1 n tline2\".to_string(); let r = unindent(&s); assert_eq!(r, \"line1 nline2\"); run_test(\"t line1 nt line2\", \"line1 nline2\"); run_test(\" tline1 n tline2\", \"line1 nline2\"); }"} {"_id":"q-en-rust-45802a704aa65ac197dd5759e30938d8a28cfab0be1080a3615ef084c4d52dbd","text":" error[E0261]: use of undeclared lifetime name `'missing` --> $DIR/missing-lt-outlives-in-rpitit-114274.rs:8:55 | LL | fn iter(&self) -> impl Iterator>; | ^^^^^^^^ undeclared lifetime | = note: for more information on higher-ranked polymorphism, visit https://doc.rust-lang.org/nomicon/hrtb.html help: consider making the bound lifetime-generic with a new `'missing` lifetime | LL | fn iter(&self) -> impl for<'missing> Iterator>; | +++++++++++++ help: consider introducing lifetime `'missing` here | LL | fn iter<'missing>(&self) -> impl Iterator>; | ++++++++++ help: consider introducing lifetime `'missing` here | LL | trait Iterable<'missing> { | ++++++++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0261`. "} {"_id":"q-en-rust-45aa69f2585bb32a909eb913bbd2d29f392eff4fca9ad24167f1b36468d6bc2c","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":"q-en-rust-45cd888b062fc7437c4f780a7b2e4848feabab7bff8f6f9ce3a01d55d61be2fb","text":"let lo = self.token.span; if !self.eat(&token::OpenDelim(token::Brace)) { let sp = self.token.span; let tok = self.this_token_descr(); let mut e = self.span_fatal(sp, &format!(\"expected `{{`, found {}\", tok)); let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon; if self.token.is_ident_named(sym::and) { e.span_suggestion_short( self.token.span, \"use `&&` instead of `and` for the boolean operator\", \"&&\".to_string(), Applicability::MaybeIncorrect, ); } if self.token.is_ident_named(sym::or) { e.span_suggestion_short( self.token.span, \"use `||` instead of `or` for the boolean operator\", \"||\".to_string(), Applicability::MaybeIncorrect, ); } return self.error_block_no_opening_brace(); } // Check to see if the user has written something like // // if (cond) // bar; // // which is valid in other languages, but not Rust. match self.parse_stmt_without_recovery(false) { Ok(Some(stmt)) => { if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) || do_not_suggest_help { // If the next token is an open brace (e.g., `if a b {`), the place- // inside-a-block suggestion would be more likely wrong than right. e.span_label(sp, \"expected `{`\"); return Err(e); } let mut stmt_span = stmt.span; // Expand the span to include the semicolon, if it exists. if self.eat(&token::Semi) { stmt_span = stmt_span.with_hi(self.prev_span.hi()); } if let Ok(snippet) = self.span_to_snippet(stmt_span) { e.span_suggestion( stmt_span, \"try placing this code inside a block\", format!(\"{{ {} }}\", snippet), // Speculative; has been misleading in the past (#46836). Applicability::MaybeIncorrect, ); } self.parse_block_tail(lo, BlockCheckMode::Default) } fn error_block_no_opening_brace(&mut self) -> PResult<'a, T> { let sp = self.token.span; let tok = self.this_token_descr(); let mut e = self.span_fatal(sp, &format!(\"expected `{{`, found {}\", tok)); let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon; if self.token.is_ident_named(sym::and) { e.span_suggestion_short( self.token.span, \"use `&&` instead of `and` for the boolean operator\", \"&&\".to_string(), Applicability::MaybeIncorrect, ); } if self.token.is_ident_named(sym::or) { e.span_suggestion_short( self.token.span, \"use `||` instead of `or` for the boolean operator\", \"||\".to_string(), Applicability::MaybeIncorrect, ); } // Check to see if the user has written something like // // if (cond) // bar; // // which is valid in other languages, but not Rust. match self.parse_stmt_without_recovery(false) { Ok(Some(stmt)) => { if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) || do_not_suggest_help { // If the next token is an open brace (e.g., `if a b {`), the place- // inside-a-block suggestion would be more likely wrong than right. e.span_label(sp, \"expected `{`\"); return Err(e); } Err(mut e) => { self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore); e.cancel(); let stmt_span = if self.eat(&token::Semi) { // Expand the span to include the semicolon. stmt.span.with_hi(self.prev_span.hi()) } else { stmt.span }; if let Ok(snippet) = self.span_to_snippet(stmt_span) { e.span_suggestion( stmt_span, \"try placing this code inside a block\", format!(\"{{ {} }}\", snippet), // Speculative; has been misleading in the past (#46836). Applicability::MaybeIncorrect, ); } _ => () } e.span_label(sp, \"expected `{`\"); return Err(e); Err(mut e) => { self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore); e.cancel(); } _ => {} } self.parse_block_tail(lo, BlockCheckMode::Default) e.span_label(sp, \"expected `{`\"); return Err(e); } /// Parses a block. Inner attributes are allowed."} {"_id":"q-en-rust-45da9ecba03172c1f74b4644d3d1a3750bb5f3a8076e938b67014f97734fabd3","text":" // revisions: imported unimported //[imported] check-pass mod private { pub trait Future { //[unimported]~^^ HELP perhaps add a `use` for it fn wait(&self) where Self: Sized; }"} {"_id":"q-en-rust-45dc36be35dabefb22f7828a2139f36384c7836d7e4c72ecb4a2069dbdc1ecf0","text":"{ // When the suggested binding change would be from `x` to `_x`, suggest changing the // original binding definition instead. (#60164) (span, snippet, \", consider changing it\") let post = format!(\", consider renaming `{}` into `{snippet}`\", suggestion.candidate); (span, snippet, post) } else { (span, suggestion.candidate.to_string(), \"\") (span, suggestion.candidate.to_string(), String::new()) }; let msg = match suggestion.target { SuggestionTarget::SimilarlyNamed => format!("} {"_id":"q-en-rust-460f099db414e912c39dd4812dfb5b8d4de21847b7c4fc291e6d9b3d81fde33c","text":" error: this operation will panic at runtime --> $DIR/unconditional_panic_98444.rs:6:13 | LL | let _ = xs[7]; | ^^^^^ index out of bounds: the length is 5 but the index is 7 | = note: `#[deny(unconditional_panic)]` on by default error: aborting due to previous error "} {"_id":"q-en-rust-461c14343232b91967614f4638a6c61abdb2592ff1dd27e2c5fd8c24aa379a1f","text":" // run-pass // Makes sure we don't propagate generic instances of `Self: ?Sized` blanket impls. // This is relevant when we have an overlapping impl and builtin dyn instance. // See for more context. trait Trait { fn foo(&self) -> &'static str; } impl Trait for T { fn foo(&self) -> &'static str { std::any::type_name::() } } const fn bar() -> fn(&T) -> &'static str { Trait::foo // If const prop were to propagate the instance } fn main() { assert_eq!(\"i32\", bar::()(&1i32)); } "} {"_id":"q-en-rust-462d6d8d27096c9fd79a519cb4ad6e869d84652c7440d27941b754ab3152340b","text":"let snippet = cx .sess() .source_map() .span_to_snippet(span_of_attrs(attrs)) .span_to_snippet(span_of_attrs(attrs)?) .ok()?; let starting_line = markdown[..md_range.start].matches('n').count();"} {"_id":"q-en-rust-466b97a41f2206e07f0fd45157e2fefa8dcc84ed9f990c3194ed6c4cb11a869c","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":"q-en-rust-4674c9031e3960050d4a579b06cd98526dad637bf995fe45ef136a8c3edadb90","text":" //! Regression test for #74400: Type mismatch in function arguments E0631, E0271 are falsely //! recognized as E0308 mismatched types. use std::convert::identity; fn main() {} fn f(data: &[T], key: impl Fn(&T) -> S) { } fn g(data: &[T]) { f(data, identity) //~ ERROR implementation of `FnOnce` is not general } "} {"_id":"q-en-rust-4695e13753693c029e0f9a672583f04f396f1ee5d9f9cde7cda69b8304ccdb1f","text":"LL - fn f2(x: &X) { LL + fn f2(x: &X) { | help: consider borrowing here | LL | let y: &X; | + error[E0277]: the size for values of type `Y` cannot be known at compilation time --> $DIR/unsized6.rs:17:12"} {"_id":"q-en-rust-46cc7ceeb9fe35208ab598bf94fb614c55d518d87bbf0d6b3ae98fa31b92a213","text":"// The lifetime was defined on node that doesn't own a body, // which in practice can only mean a trait or an impl, that // is the parent of a method, and that is enforced below. assert_eq!(Some(param_owner_id), self.root_parent, \"free_scope: {:?} not recognized by the region scope tree for {:?} / {:?}\", param_owner, self.root_parent.map(|id| tcx.hir().local_def_id_from_hir_id(id)), self.root_body.map(|hir_id| DefId::local(hir_id.owner))); if Some(param_owner_id) != self.root_parent { tcx.sess.delay_span_bug( DUMMY_SP, &format!(\"free_scope: {:?} not recognized by the region scope tree for {:?} / {:?}\", param_owner, self.root_parent.map(|id| tcx.hir().local_def_id_from_hir_id(id)), self.root_body.map(|hir_id| DefId::local(hir_id.owner)))); } // The trait/impl lifetime is in scope for the method's body. self.root_body.unwrap().local_id"} {"_id":"q-en-rust-46fe4a73a4ec17281f7b78e178c7786650e0e1aa70cf092d023b05f403f16b9e","text":"Value(int), Missing, } fn main() { let x = Value(5); let y = Missing; match x { Value(n) => println!(\"x is {}\", n), Missing => println!(\"x is missing!\"), } match y { Value(n) => println!(\"y is {}\", n), Missing => println!(\"y is missing!\"), } } ``` This enum represents an `int` that we may or may not have. In the `Missing`"} {"_id":"q-en-rust-4700e226a1862ee1002bd629256e1f41cdbc63f514f094e1d05094d83cd47009","text":"span } = *self; hcx.hash_hir_item_like(attrs, |hcx| { let is_const = match *node { hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => true, hir::TraitItemKind::Method(hir::MethodSig { constness, .. }, _) => { constness == hir::Constness::Const } }; hcx.hash_hir_item_like(attrs, is_const, |hcx| { name.hash_stable(hcx, hasher); attrs.hash_stable(hcx, hasher); generics.hash_stable(hcx, hasher);"} {"_id":"q-en-rust-470ea1065baa5d3bd3457efbf9d4f6b77a17eb046f847b528cd6fd1e2f47f919","text":" error[E0277]: the `?` operator can only be applied to values that implement `std::ops::Try` --> $DIR/issue-72766.rs:14:5 | LL | SadGirl {}.call()?; | ^^^^^^^^^^^^^^^^^^ | | | the `?` operator cannot be applied to type `impl std::future::Future` | help: consider using `.await` here: `SadGirl {}.call().await?` | = help: the trait `std::ops::Try` is not implemented for `impl std::future::Future` = note: required by `std::ops::Try::into_result` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"q-en-rust-471d72cabbc6a30b8c06134dbca332c66b07929f9829bbc1754f8ca8cf1cf971","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":"q-en-rust-473a6ec5e0bc9239e3f3e49ec9c514d3a2c57e56fdf6b0a0323af769d19747c0","text":" error[E0310]: the associated type `::Item` may not live long enough --> $DIR/closure-in-projection-issue-97405.rs:24:5 | LL | assert_static(opaque(async move { t; }).next()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider adding an explicit lifetime bound `::Item: 'static`... = note: ...so that the type `::Item` will meet its required lifetime bounds error[E0310]: the associated type `::Item` may not live long enough --> $DIR/closure-in-projection-issue-97405.rs:26:5 | LL | assert_static(opaque(move || { t; }).next()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider adding an explicit lifetime bound `::Item: 'static`... = note: ...so that the type `::Item` will meet its required lifetime bounds error[E0310]: the associated type `::Item` may not live long enough --> $DIR/closure-in-projection-issue-97405.rs:28:5 | LL | assert_static(opaque(opaque(async move { t; }).next()).next()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider adding an explicit lifetime bound `::Item: 'static`... = note: ...so that the type `::Item` will meet its required lifetime bounds error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0310`. "} {"_id":"q-en-rust-47515ba0243cd00ba1a6950c3c6141d8362599858c0bd92025328f1cd1819579","text":"use core::mem; use core::ops::{CoerceUnsized, Deref, DerefMut}; use core::ops::{Placer, Boxed, Place, InPlace, BoxPlace}; use core::ptr::Unique; use core::ptr::{self, Unique}; use core::raw::{TraitObject}; /// A value that represents the heap. This is the default place that the `box`"} {"_id":"q-en-rust-476f2cb7910e8555d5f63239af4bbf2abb2fbe9894ae4a441e051b001e4cd1e7","text":"// Create the intermediate directories let mut cur = self.dst.clone(); let mut root_path = String::from_str(\"../../\"); clean_srcpath(&self.cx.src_root, &p, |component| { clean_srcpath(&self.cx.src_root, &p, false, |component| { cur.push(component); mkdir(&cur).unwrap(); root_path.push_str(\"../\");"} {"_id":"q-en-rust-47a5d0023559d51a4e1f5ac66236ffa54bab7506fd14821fa53daa58a7e2d71e","text":" pub trait Foo { type Type; } pub struct Bar(::Type) where Self: ; //~^ ERROR the trait bound `Bar: Foo` is not satisfied fn main() {} "} {"_id":"q-en-rust-47b6b03d2d242da8aaeaf583de279c821088706165cda1a0dfae1ca09b4836ba","text":"HTML_DEPS := endif # Check for the various external utilities for the EPUB/PDF docs: ifeq ($(CFG_LUALATEX),) $(info cfg: no lualatex found, deferring to xelatex) ifeq ($(CFG_XELATEX),) $(info cfg: no xelatex found, deferring to pdflatex) ifeq ($(CFG_PDFLATEX),) $(info cfg: no pdflatex found, disabling LaTeX docs) NO_PDF_DOCS = 1 else CFG_LATEX := $(CFG_PDFLATEX) endif else # Check for xelatex ifeq ($(CFG_XELATEX),) CFG_LATEX := $(CFG_XELATEX) XELATEX = 1 endif else CFG_LATEX := $(CFG_LUALATEX) else $(info cfg: no xelatex found, disabling LaTeX docs) NO_PDF_DOCS = 1 endif ifeq ($(CFG_PANDOC),) $(info cfg: no pandoc found, omitting PDF and EPUB docs) ONLY_HTML_DOCS = 1"} {"_id":"q-en-rust-47ce49013a93497fb1d1addd13c4207f2d4ee56e1709ff1c069e392d16080c2a","text":"Some(ns @ TypeNS) => { match self.resolve( path_str, disambiguator, ns, ¤t_item, base_node,"} {"_id":"q-en-rust-47d4a9e03781fcadb76c934c9812b39aa7b34ca62881ac4aca676afbddca6ece","text":"| KeywordItem => [].iter(), } } /// Returns `true` if this item does not appear inside an impl block. pub(crate) fn is_non_assoc(&self) -> bool { matches!( self, StructItem(_) | UnionItem(_) | EnumItem(_) | TraitItem(_) | ModuleItem(_) | ExternCrateItem { .. } | FunctionItem(_) | TypedefItem(_) | OpaqueTyItem(_) | StaticItem(_) | ConstantItem(_) | TraitAliasItem(_) | ForeignFunctionItem(_) | ForeignStaticItem(_) | ForeignTypeItem | MacroItem(_) | ProcMacroItem(_) | PrimitiveItem(_) ) } } #[derive(Clone, Debug)]"} {"_id":"q-en-rust-4806a176fae7c1d663a2e1e675694ac66a718cb0cf09826246aa1ffe0c9ea827","text":"# Find out where the pretty printer Python module is RUSTC_SYSROOT=\"$(\"$RUSTC\" --print=sysroot)\" GDB_PYTHON_MODULE_DIRECTORY=\"$RUSTC_SYSROOT/lib/rustlib/etc\" # Get the commit hash for path remapping RUSTC_COMMIT_HASH=\"$(\"$RUSTC\" -vV | sed -n 's/commit-hash: (w*)/1/p')\" # Set the environment variable `RUST_GDB` to overwrite the call to a # different/specific command (defaults to `gdb`)."} {"_id":"q-en-rust-4808cfa1ea1d35f2c202a5e5b332bfd824b55d48fd7e75380e6d66ddfe579575","text":"padding: 5px 10px; } h5, h6 { color: black; text-decoration: underline; }"} {"_id":"q-en-rust-4850bfc3d625a6ccf502bfb17b2149a0a1c5c2a8af53cd685e8708d28e9b2c0b","text":"fn output_filename(&mut self, path: &Path) { self.cmd.arg(\"-o\").arg(path); } fn add_object(&mut self, path: &Path) { self.cmd.arg(path); } fn position_independent_executable(&mut self) { self.cmd.arg(\"-pie\"); } fn no_position_independent_executable(&mut self) { self.cmd.arg(\"-no-pie\"); } fn partial_relro(&mut self) { self.linker_arg(\"-z,relro\"); } fn full_relro(&mut self) { self.linker_arg(\"-z,relro,-z,now\"); } fn build_static_executable(&mut self) { self.cmd.arg(\"-static\"); }"} {"_id":"q-en-rust-4854db40fa34116a1909a4f52fdfecc5c62f1cbf4c979e490bbd25a9c9ead9e1","text":"// We errored. Signal that in the pattern, so that follow up errors can be silenced. let kind = PatKind::Error(e); return Box::new(Pat { span: self.span, ty: cv.ty(), kind }); } else if let ty::Adt(..) = cv.ty().kind() && matches!(cv, mir::Const::Val(..)) { // This branch is only entered when the current `cv` is `mir::Const::Val`. // This is because `mir::Const::ty` has already been handled by `Self::recur` // and the invalid types may be ignored. let err = TypeNotStructural { span: self.span, non_sm_ty }; let e = self.tcx().sess.emit_err(err); let kind = PatKind::Error(e); return Box::new(Pat { span: self.span, ty: cv.ty(), kind }); } else if !self.saw_const_match_lint.get() { if let Some(mir_structural_match_violation) = mir_structural_match_violation { match non_sm_ty.kind() {"} {"_id":"q-en-rust-48b1db8313abc1680f2bba8cad30de90d791ff4da467e7b479a33a184c341cbc","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. #![allow(dead_code)] struct Foo; impl Foo { fn new() -> Self { Foo } fn bar() { Self::new(); } } fn main() {} "} {"_id":"q-en-rust-48d88aee3881dad74551642ede7d7e65bd8c1df0fdc4c40558bda05bde6bd05b","text":" use crate::infer::outlives::components::{compute_components_recursive, Component}; use crate::infer::outlives::env::RegionBoundPairs; use crate::infer::region_constraints::VerifyIfEq; use crate::infer::{GenericKind, VerifyBound}; use rustc_data_structures::captures::Captures; use rustc_data_structures::sso::SsoHashSet; use rustc_hir::def_id::DefId; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst}; use rustc_middle::ty::subst::{GenericArg, Subst}; use rustc_middle::ty::{self, EarlyBinder, Ty, TyCtxt}; use smallvec::smallvec; /// The `TypeOutlives` struct has the job of \"lowering\" a `T: 'a` /// obligation into a series of `'a: 'b` constraints and \"verifys\", as /// described on the module comment. The final constraints are emitted"} {"_id":"q-en-rust-48daf681578cdc0eca57c1dc64dccd418c96d38c7bfa9e8f7e50b3633dd1be5a","text":"fn outer(self) { fn inner(_: Self) { //~^ ERROR can't use type parameters from outer function //~^^ ERROR use of undeclared type name `Self` //~^^ ERROR use of `Self` outside of an impl or trait } } }"} {"_id":"q-en-rust-48ea2203b29ccffb73a113227be8f043556b9e40d5ee429b06ed0383c1da6e8f","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 Foo: Sized { fn foo(self) {} } trait Bar: Sized { fn bar(self) {} } struct S; impl<'l> Foo for &'l S {} impl Bar for T {} fn main() { let s = S; s.foo(); (&s).bar(); s.bar(); } "} {"_id":"q-en-rust-49272112d327ce33d506d08f51f717cce0536de8e9606a0673252b31c7f0d67b","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":"q-en-rust-4947259a1ffb5032696f75863dcdce395f4cd9b1a061fcbdef1166b3f1e734b5","text":"#[primary_span] pub item_span: Span, #[suggestion(code = \"unsafe \", applicability = \"machine-applicable\", style = \"verbose\")] pub block: Span, pub block: Option, } #[derive(Diagnostic)]"} {"_id":"q-en-rust-49472db796da5bbf030fc4d563dcf7893fcf450e4291a852017b715be8d71d45","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":"q-en-rust-49495d13f8bb647acc528f871f1a4b34412ba5a9a5a4eee571e23ac77077764e","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":"q-en-rust-4963f283766df6f8e6de54af7438508ee56d45be0b8b861405d0c6017bc4f86a","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. // @has issue_31899/index.html // @has - 'Make this line a bit longer.' // @!has - 'rust rust-example-rendered' // @!has - 'use ndarray::arr2' // @!has - 'prohibited' /// A tuple or fixed size array that can be used to index an array. /// Make this line a bit longer. /// /// ``` /// use ndarray::arr2; /// /// let mut a = arr2(&[[0, 1], [0, 0]]); /// a[[1, 1]] = 1; /// assert_eq!(a[[0, 1]], 1); /// assert_eq!(a[[1, 1]], 1); /// ``` /// /// **Note** the blanket implementation that's not visible in rustdoc: /// `impl NdIndex for D where D: Dimension { ... }` pub fn bar() {} /// Some line /// /// # prohibited pub fn foo() {} /// Some line /// /// 1. prohibited /// 2. bar pub fn baz() {} /// Some line /// /// - prohibited /// - bar pub fn qux() {} /// Some line /// /// * prohibited /// * bar pub fn quz() {} /// Some line /// /// > prohibited /// > bar pub fn qur() {} /// Some line /// /// prohibited /// ===== /// /// Second /// ------ pub fn qut() {} "} {"_id":"q-en-rust-496d056cfae95062ed5ba639706d3252d31abc888706828a3c2254344cc4d447","text":" error[E0277]: the trait bound `T: Clone` is not satisfied --> $DIR/global-cache-and-parallel-frontend.rs:15:17 | LL | #[derive(Clone, Eq)] | ^^ the trait `Clone` is not implemented for `T`, which is required by `Struct: PartialEq` | note: required for `Struct` to implement `PartialEq` --> $DIR/global-cache-and-parallel-frontend.rs:18:19 | LL | impl PartialEq for Struct | ----- ^^^^^^^^^^^^ ^^^^^^^^^ | | | unsatisfied trait bound introduced here note: required by a bound in `Eq` --> $SRC_DIR/core/src/cmp.rs:LL:COL = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `T` | LL | pub struct Struct(T); | +++++++++++++++++++ error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"q-en-rust-497e17c2cc8895bbd252087420562758e075dadf26208d283034f699c059322d","text":"(\"thread_local\", Whitelisted, Gated(Stability::Unstable, \"thread_local\", \"`#[thread_local]` is an experimental feature, and does not currently handle destructors. There is no corresponding `#[task_local]` mapping to the task model\", not currently handle destructors.\", cfg_fn!(thread_local))), (\"rustc_on_unimplemented\", Normal, Gated(Stability::Unstable,"} {"_id":"q-en-rust-499f87e22e4c82bb4c26c1e60d63547bc36b63ff62ec3453415212e1fe18bcc6","text":" trait Foo {} impl Foo for T {} fn main() { let array = [(); { loop {} }]; //~ ERROR constant evaluation is taking a long time let tup = (7,); let x: &dyn Foo = &tup.0; } "} {"_id":"q-en-rust-49a877d2bee47a2ef974b2acce5154c2053dfc280d0572875028f833acf7297e","text":"// want to keep their span info to improve diagnostics in these cases in a later stage. (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3` (true, Some(AssocOp::Subtract)) | // `{ 42 } -5` (true, Some(AssocOp::Add)) => { // `{ 42 } + 42 (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475) (true, Some(AssocOp::Add)) // `{ 42 } + 42 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect: // `if x { a } else { b } && if y { c } else { d }` if !self.look_ahead(1, |t| t.is_reserved_ident()) => { // These cases are ambiguous and can't be identified in the parser alone let sp = self.sess.source_map().start_point(self.span); self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);"} {"_id":"q-en-rust-49c1f1be0406ee7a14bfd98bd35524b7b097a5cf90f829b956e7f0a437ab878b","text":" mod b { #[derive(Default)] pub struct A(u32); } impl b::A { fn inherent_bypass(&self) { let Self(x) = self; //~^ ERROR: tuple struct constructor `A` is private println!(\"{x}\"); } } pub trait B { fn f(&self); } impl B for b::A { fn f(&self) { let Self(a) = self; //~^ ERROR: tuple struct constructor `A` is private println!(\"{}\", a); } } pub trait Projector { type P; } impl Projector for () { type P = b::A; } pub trait Bypass2 { fn f2(&self); } impl Bypass2 for <() as Projector>::P { fn f2(&self) { let Self(a) = self; //~^ ERROR: tuple struct constructor `A` is private println!(\"{}\", a); } } fn main() {} "} {"_id":"q-en-rust-49c678e9b9484118c00452796e204d0fd82e73c9a1ebf5b40efd6a1be9570115","text":"| -------------- variant or associated item `PIE` not found here ... LL | ApplePie = Delicious::Apple as isize | Delicious::PIE as isize, | ^^^ variant or associated item not found in `Delicious` | ^^^ | | | variant or associated item not found in `Delicious` | help: there is a variant with a similar name: `Pie` error: aborting due to previous error"} {"_id":"q-en-rust-49c93666071eb687ad19c950ef5cdaab9dcdf5106d91351896b06ea6adc731a9","text":" // check-pass // compile-flags: --emit=mir,link // Regression test for #66930, this ICE requires `--emit=mir` flag. static UTF8_CHAR_WIDTH: [u8; 0] = []; pub fn utf8_char_width(b: u8) -> usize { UTF8_CHAR_WIDTH[b as usize] as usize } fn main() {} "} {"_id":"q-en-rust-49cdb0c70f95ca8fcd9e7cc939952d42dc30f6d614ab01e5c27e8473b96a93f1","text":"[[package]] name = \"racer\" version = \"2.1.46\" version = \"2.1.47\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"e7cbda48a9124ed2e83766d2c15e3725710d344abca35fad8cf52341a55883b1\" checksum = \"513c70e67444a0d62fdc581dffa521c6820942a5f08300d0864863f8d0e750e3\" dependencies = [ \"bitflags\", \"clap\","} {"_id":"q-en-rust-49f47fee2413f1854bfc67f70e3ff144bab0cfe15f58aeb3fee72858aab9b319","text":"} } #[derive(Debug)] pub struct OffsetOverflowError; /// A single source in the `SourceMap`. #[derive(Clone)] pub struct SourceFile {"} {"_id":"q-en-rust-4a4d83f5733b084fb06e4e9411753b9efb3223e3cc019085058a5983143d3462","text":"let buildpath = fs::connect(_path, \"/build\"); need_dir(buildpath); #debug(\"Installing: %s -> %s\", cf, buildpath); let p = run::program_output(\"rustc\", [\"--out-dir\", buildpath, cf]); let p = run::program_output(rustc_sysroot(), [\"--out-dir\", buildpath, cf]); if p.status != 0 { error(#fmt[\"rustc failed: %dn%sn%s\", p.status, p.err, p.out]); ret;"} {"_id":"q-en-rust-4a6e04e62ce0bf5f70c06f2a8be94f3b1cc5fa0b69ea4ba8b6b19d48c34d8641","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. // Regression test for issue #25436: check that things which can be // followed by any token also permit X* to come afterwards. macro_rules! foo { ( $a:tt $($b:tt)* ) => { }; ( $a:ident $($b:tt)* ) => { }; ( $a:item $($b:tt)* ) => { }; ( $a:block $($b:tt)* ) => { }; ( $a:meta $($b:tt)* ) => { } } fn main() { } "} {"_id":"q-en-rust-4a72eb49cf6237d23fe7971b4a0f96fd8569ed93a731b1390d9a1fd7c0eec54c","text":"So, no need to manually enter those Unicode characters! ### Adding a warning block If you want to make a warning or similar note stand out in the documentation, you can wrap it like this: ```md /// documentation /// ///
A big warning!
/// /// more documentation ```
[`backtrace`]: https://docs.rs/backtrace/0.3.50/backtrace/ [commonmark markdown specification]: https://commonmark.org/ [commonmark quick reference]: https://commonmark.org/help/"} {"_id":"q-en-rust-4a7b048a54f6995f9dfc91bd475870f46b5416567d1866948593732c8907864b","text":"error[E0382]: borrow of moved value: `x` --> $DIR/borrow-after-move.rs:39:24 | LL | let x = \"hello\".to_owned().into_boxed_str(); | - move occurs because `x` has type `std::boxed::Box`, which does not implement the `Copy` trait LL | x.foo(); | - value moved here LL | println!(\"{}\", &x); | ^^ value borrowed here after partial move | = note: move occurs because `*x` has type `str`, which does not implement the `Copy` trait | ^^ value borrowed here after move error: aborting due to 5 previous errors"} {"_id":"q-en-rust-4ac199984a45b234d092426330dd856a1325eff0ed58c50b3bc406ab084562f3","text":" #![feature(fn_delegation)] #![allow(incomplete_features)] mod to_reuse {} trait Trait { reuse to_reuse::foo { foo } //~^ ERROR cannot find function `foo` in module `to_reuse` //~| ERROR cannot find value `foo` in this scope } fn main() {} "} {"_id":"q-en-rust-4acf4f7c3604c5858d2bb272c66a01393c586b53926d545e7add457068d72cdf","text":"tt @ &TtSequence(..) => { check_matcher(cx, Some(tt).into_iter(), &Eof); }, _ => cx.span_bug(sp, \"wrong-structured lhs for follow check (didn't find a TtDelimited or TtSequence)\") _ => cx.span_err(sp, \"Invalid macro matcher; matchers must be contained in balanced delimiters or a repetition indicator\") }, _ => cx.span_bug(sp, \"wrong-structured lhs for follow check (didn't find a MatchedNonterminal)\")"} {"_id":"q-en-rust-4b39950257f7db7a0eb48e746e0744bf3db0c3035d9ca20d3731d151222f2964","text":" // Regression test for #92111. // // The issue was that we normalize trait bounds before caching // results of selection. Checking that `impl NoDrop for S` requires // checking `S: !Drop` because it cannot overlap with the blanket // impl. Then we save the (unsatisfied) result from checking `S: Drop`. // Then the call to `a` checks whether `S: ~const Drop` but we normalize // it to `S: Drop` which the cache claims to be unsatisfied. // // check-pass #![feature(const_trait_impl)] #![feature(const_fn_trait_bound)] pub trait Tr {} #[allow(drop_bounds)] impl Tr for T {} #[derive(Debug)] pub struct S(i32); impl Tr for S {} const fn a(t: T) {} fn main() { a(S(0)); } "} {"_id":"q-en-rust-4b5e11890484a5a1148e3fe260e08a9b3c379d2d7bf04219d56e3ab3bad338b9","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":"q-en-rust-4b672b65222ce3fa4cc0468af1e3a7da347c5d39733955780c1d33f0fb5f93e6","text":" struct Foo(i32); fn main() { let Foo(...) = Foo(0); //~ ERROR unexpected `...` let [_, ..., _] = [0, 1]; //~ ERROR unexpected `...` let _recovery_witness: () = 0; //~ ERROR mismatched types } "} {"_id":"q-en-rust-4b828379070abd612874b5c57c133f0f2cf49fabe5cea0224a450d65a013e076","text":" mod list { pub use self::List::Cons; pub enum List { Cons(T, Box>), } } mod alias { use crate::list::List; pub type Foo = List; } fn foo(l: crate::alias::Foo) { match l { Cons(..) => {} //~ ERROR: cannot find tuple struct or tuple variant `Cons` in this scope } } fn main() {} "} {"_id":"q-en-rust-4bc42a7790426e9957a7e58169fc48e7beb852b3483a5ca97ddc40ea21a546be","text":" Couldn't create directory for doctest executables: Permission denied (os error 13) "} {"_id":"q-en-rust-4bca0d9b3cb4ac83466b1fbd6976e8d7d1fd65c93c870374cd54cc82a3c57c81","text":"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":"q-en-rust-4bcfd40122de3e0dc590bc4b911fe5765de430bf56a412a846e748e2a0b9806b","text":" // compile-flags: -Ztrait-solver=next-coherence // Makes sure we don't ICE on associated const projection when the feature gate // is not enabled, since we should avoid encountering ICEs on stable if possible. trait Bar { const ASSOC: usize; } impl Bar for () { const ASSOC: usize = 1; } trait Foo {} impl Foo for () {} impl Foo for T where T: Bar {} //~^ ERROR associated const equality is incomplete //~| ERROR conflicting implementations of trait `Foo` for type `()` fn main() {} "} {"_id":"q-en-rust-4c1fbb82142c5c882828419bfabc1f2497171f6a03b74d4d39f5815f94665cd6","text":"let scope = if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark }; let attr_id_before = invoc.attr_id(); let ext = match self.cx.resolver.resolve_invoc(&mut invoc, scope, force) { Ok(ext) => Some(ext), Err(Determinacy::Determined) => None, Err(Determinacy::Undetermined) => { // Sometimes attributes which we thought were invocations // end up being custom attributes for custom derives. If // that's the case our `invoc` will have changed out from // under us. If this is the case we're making progress so we // want to flag it as such, and we test this by looking if // the `attr_id()` method has been changing over time. if invoc.attr_id() != attr_id_before { progress = true; } undetermined_invocations.push(invoc); continue }"} {"_id":"q-en-rust-4c4804e1e9af7983a311e5602a147b30b23e8485d424fb776190e7cb671afe61","text":"| LL | extern \"C\" unsafe { | ^^^^^^ | = note: see issue #123743 for more information = help: add `#![feature(unsafe_extern_blocks)]` 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: items in unadorned `extern` blocks cannot have safety qualifiers --> $DIR/unsafe-foreign-mod-2.rs:4:5 | LL | unsafe fn foo(); | ^^^^^^^^^^^^^^^^ | help: add unsafe to this `extern` block | LL | unsafe extern \"C\" unsafe { | ++++++ error: aborting due to 3 previous errors"} {"_id":"q-en-rust-4c5c2cbf3d1e12b2ec0579e07144c5d2ff900522f24a888491f9bb1ecfdd1543","text":" // Don't suggest double quotes when encountering an expr of type `char` where a `&str` // is expected if the expr is not a char literal. // issue: rust-lang/rust#125595 fn main() { let _: &str = ('a'); //~ ERROR mismatched types let token = || 'a'; let _: &str = token(); //~ ERROR mismatched types } "} {"_id":"q-en-rust-4c70e2e71682fac13d10d6de0960475c5c25979f5d68b1f981530eb1edfb61d5","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":"q-en-rust-4c82e06350c3732594ebfca98df7cefc26bb3841efe36fe21d0aca03c62077ce","text":"/// ``` ``` As of version 1.34.0, one can also omit the `fn main()`, but you will have to disambiguate the error type: ```ignore /// ``` /// use std::io; /// let mut input = String::new(); /// io::stdin().read_line(&mut input)?; /// # Ok::<(), io:Error>(()) /// ``` ``` This is an unfortunate consequence of the `?` operator adding an implicit conversion, so type inference fails because the type is not unique. Please note that you must write the `(())` in one sequence without intermediate whitespace so that rustdoc understands you want an implicit `Result`-returning function. ## Documenting macros Here’s an example of documenting a macro:"} {"_id":"q-en-rust-4ca06783b01c0e83098606730a471bc711a3df4388da5972e3c0dc419b6a44b4","text":" error: macro-expanded `extern crate` items cannot shadow names passed with `--extern` --> $DIR/issue-78325-inconsistent-resolution.rs:3:9 | LL | extern crate std as core; | ^^^^^^^^^^^^^^^^^^^^^^^^^ ... LL | define_other_core!(); | --------------------- in this macro invocation | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to previous error "} {"_id":"q-en-rust-4cd154078b2836110b453dce381af572506a7283c7cd7f9388fdb3cfd957dc14","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] pub trait PhantomFn { } /// `PhantomData` is a way to tell the compiler about fake fields. /// Phantom data is required whenever type parameters are not used. /// The idea is that if the compiler encounters a `PhantomData` /// instance, it will behave *as if* an instance of the type `T` were /// present for the purpose of various automatic analyses. /// `PhantomData` allows you to describe that a type acts as if it stores a value of type `T`, /// even though it does not. This allows you to inform the compiler about certain safety properties /// of your code. /// /// Though they both have scary names, `PhantomData` and \"phantom types\" are unrelated. 👻👻👻 /// /// # Examples /// /// When handling external resources over a foreign function interface, `PhantomData` can /// prevent mismatches by enforcing types in the method implementations, although the struct /// doesn't actually contain values of the resource type. /// prevent mismatches by enforcing types in the method implementations: /// /// ``` /// # trait ResType { fn foo(&self); };"} {"_id":"q-en-rust-4ce307524a1846786ce8ed1ece008738dcac3cb231e7f1afccd990cd70a55420","text":"use std::fmt::{Debug, Display}; #[marker] trait Marker {} #[marker] trait Marker {} impl Marker for T {} impl Marker for T {}"} {"_id":"q-en-rust-4cf1495772a86d2aca7ed579420ca3e3d41f402a56324dae2ef7bd7c214e5b16","text":"pub fn new_raw(fam: c_int, ty: c_int) -> io::Result { unsafe { // On linux we first attempt to pass the SOCK_CLOEXEC flag to // atomically create the socket and set it as CLOEXEC. Support for // this option, however, was added in 2.6.27, and we still support // 2.6.18 as a kernel, so if the returned error is EINVAL we // fallthrough to the fallback. #[cfg(target_os = \"linux\")] { match cvt(libc::socket(fam, ty | libc::SOCK_CLOEXEC, 0)) { Ok(fd) => return Ok(Socket(FileDesc::new(fd))), Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} Err(e) => return Err(e), } } let fd = cvt(libc::socket(fam, ty, 0))?; let fd = FileDesc::new(fd); fd.set_cloexec()?; let socket = Socket(fd); cfg_if::cfg_if! { if #[cfg(target_os = \"linux\")] { // On Linux we pass the SOCK_CLOEXEC flag to atomically create // the socket and set it as CLOEXEC, added in 2.6.27. let fd = cvt(libc::socket(fam, ty | libc::SOCK_CLOEXEC, 0))?; Ok(Socket(FileDesc::new(fd))) } else { let fd = cvt(libc::socket(fam, ty, 0))?; let fd = FileDesc::new(fd); fd.set_cloexec()?; let socket = Socket(fd); // macOS and iOS use `SO_NOSIGPIPE` as a `setsockopt` // flag to disable `SIGPIPE` emission on socket. #[cfg(target_vendor = \"apple\")] setsockopt(&socket, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1)?; // macOS and iOS use `SO_NOSIGPIPE` as a `setsockopt` // flag to disable `SIGPIPE` emission on socket. #[cfg(target_vendor = \"apple\")] setsockopt(&socket, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1)?; Ok(socket) Ok(socket) } } } }"} {"_id":"q-en-rust-4d52ece44292dd648235d224e8329c7d1f8a5e16e7f0912cd4e2e0567d16ac3e","text":" Subproject commit 4cf36f285084f8f841f3cff7b29d44b1d95ee1dd Subproject commit 54bbbd13ac532deed80416295a224ce12547a40c "} {"_id":"q-en-rust-4d5d48e93ff3e884088496ac6f3b25d2ad4916834c42eb38cc0ffaea2ffa3bb8","text":"pub mod map; pub mod set; #[doc(hidden)] trait Recover { type Key;"} {"_id":"q-en-rust-4d89eee0ceb10bc71dbfd49260c600b28e91f2d4a547ea90965587dea4cdf1c6","text":"assert_eq!(c.stream_position()?, 8); assert_eq!(c.stream_position()?, 8); c.rewind()?; assert_eq!(c.stream_position()?, 0); assert_eq!(c.stream_position()?, 0); Ok(()) }"} {"_id":"q-en-rust-4d8c499bd2c1079579d3b4eb61a487b3069872a74e92087cd567f7c0a48878a0","text":" // edition: 2021 use std::collections::HashMap; use std::future::Future; use std::pin::Pin; pub trait Trait { fn do_something<'async_trait>(byte: u8) -> Pin + Send + 'async_trait>>; } pub struct Struct; impl Trait for Struct { fn do_something<'async_trait>(byte: u8) -> Pin + Send + 'async_trait>> { Box::pin( async move { let byte = byte; let _: () = {}; }) } } pub struct Map { map: HashMap Pin + Send>>>, } impl Map { pub fn new() -> Self { let mut map = HashMap::new(); map.insert(1, Struct::do_something); Self { map } //~^ ERROR mismatched types } } fn main() {} "} {"_id":"q-en-rust-4d8ea99a47eca7e811670e7c48a948ee3c8c9c42cc680fbccf6fc7fe3f33c707","text":" // build-pass // compile-flags: -O // min-llvm-version: 14.0.5 // needs-asm-support // only-x86_64 // only-linux // regression test for #96797 #![feature(asm_sym)] use std::arch::global_asm; #[no_mangle] fn my_func() {} global_asm!(\"call_foobar: jmp {}\", sym foobar); fn foobar() {} fn main() { extern \"Rust\" { fn call_foobar(); } unsafe { call_foobar() }; } "} {"_id":"q-en-rust-4dbb1beb7c6f5d0412b09a19e4ea3e1a18933fb2cf8090a070d27d25512ea08a","text":"// These are either the stage0 downloaded binaries or the locally installed ones. pub initial_cargo: PathBuf, pub initial_rustc: PathBuf, pub initial_cargo_clippy: Option, #[cfg(not(test))] initial_rustfmt: RefCell,"} {"_id":"q-en-rust-4dc335c452ebaf4c7e073f3bdfc7f46fcf34f7f5b770b0004ebe0586e75bd8ce","text":" error: expected item, found `;` --> $DIR/missing-main-issue-124935-semi-after-item.rs:5:1 | LL | ; | ^ help: remove this semicolon | = help: function declarations are not followed by a semicolon error: aborting due to 1 previous error "} {"_id":"q-en-rust-4de814b51b14849259548ef7a19f7039033f777e434f40cf52211c787ab72c31","text":"fn visit_async_fn( &mut self, id: NodeId, async_node_id: NodeId, return_impl_trait_id: NodeId, name: Name, span: Span, visit_fn: impl FnOnce(&mut DefCollector<'a>) header: &FnHeader, generics: &'a Generics, decl: &'a FnDecl, body: &'a Block, ) { let (closure_id, return_impl_trait_id) = match header.asyncness { IsAsync::Async { closure_id, return_impl_trait_id, } => (closure_id, return_impl_trait_id), _ => unreachable!(), }; // For async functions, we need to create their inner defs inside of a // closure to match their desugared representation. let fn_def_data = DefPathData::ValueNs(name.as_interned_str()); let fn_def = self.create_def(id, fn_def_data, ITEM_LIKE_SPACE, span); return self.with_parent(fn_def, |this| { this.create_def(return_impl_trait_id, DefPathData::ImplTrait, REGULAR_SPACE, span); let closure_def = this.create_def(async_node_id, visit::walk_generics(this, generics); visit::walk_fn_decl(this, decl); let closure_def = this.create_def(closure_id, DefPathData::ClosureExpr, REGULAR_SPACE, span); this.with_parent(closure_def, visit_fn) this.with_parent(closure_def, |this| { visit::walk_block(this, body); }) }) }"} {"_id":"q-en-rust-4dfd27ea5764a27b6a5574bdadd8dda97d5d7f8fe961e3b6d0578a76a25276b1","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":"q-en-rust-4e283e7b1b9c4e8ecd32e1a30e0908954def9d5b1a0e6af0e604be057d99b433","text":"}; let diag = match report_on { ReportOn::TupleField => MultipleDeadCodes::UnusedTupleStructFields { multiple, num, descr, participle, name_list, change_fields_suggestion: ChangeFieldsToBeOfUnitType { num, spans: spans.clone() }, parent_info, ignored_derived_impls, }, ReportOn::TupleField => { let tuple_fields = if let Some(parent_id) = parent_item && let node = tcx.hir_node_by_def_id(parent_id) && let hir::Node::Item(hir::Item { kind: hir::ItemKind::Struct(hir::VariantData::Tuple(fields, _, _), _), .. }) = node { *fields } else { &[] }; let trailing_tuple_fields = if tuple_fields.len() >= dead_codes.len() { LocalDefIdSet::from_iter( tuple_fields .iter() .skip(tuple_fields.len() - dead_codes.len()) .map(|f| f.def_id), ) } else { LocalDefIdSet::default() }; let fields_suggestion = // Suggest removal if all tuple fields are at the end. // Otherwise suggest removal or changing to unit type if dead_codes.iter().all(|dc| trailing_tuple_fields.contains(&dc.def_id)) { ChangeFields::Remove { num } } else { ChangeFields::ChangeToUnitTypeOrRemove { num, spans: spans.clone() } }; MultipleDeadCodes::UnusedTupleStructFields { multiple, num, descr, participle, name_list, change_fields_suggestion: fields_suggestion, parent_info, ignored_derived_impls, } } ReportOn::NamedField => MultipleDeadCodes::DeadCodes { multiple, num,"} {"_id":"q-en-rust-4e42b8c20a0a5bfdaca8e376ce0a5dd1375f6ff6f677e9bfb8224894052d9bb3","text":"parse_only: bool, no_trans: bool, no_analysis: bool, no_rpath: bool, debugging_opts: u64, android_cross_path: Option<~str>, /// Whether to write dependency files. It's (enabled, optional filename)."} {"_id":"q-en-rust-4e568ccd750da64a4a7fde82760a206eaf3bce687128e530067da17ad39f2c46","text":"let new_loan_indices = self.loans_generated_by(node); debug!(\"new_loan_indices = {:?}\", new_loan_indices); self.each_issued_loan(node, |issued_loan| { for &new_loan_index in &new_loan_indices { for &new_loan_index in &new_loan_indices { self.each_issued_loan(node, |issued_loan| { let new_loan = &self.all_loans[new_loan_index]; self.report_error_if_loans_conflict(issued_loan, new_loan); } true }); // Only report an error for the first issued loan that conflicts // to avoid O(n^2) errors. self.report_error_if_loans_conflict(issued_loan, new_loan) }); } for (i, &x) in new_loan_indices.iter().enumerate() { let old_loan = &self.all_loans[x];"} {"_id":"q-en-rust-4e586350732163a73244b983d05459f4b24c5a8fb8b86f6c64b6b5b3539d5a53","text":" // check-pass #![feature(or_patterns)] enum MyEnum { FirstCase(u8), OtherCase(u16), } fn my_fn(x @ (MyEnum::FirstCase(_) | MyEnum::OtherCase(_)): MyEnum) {} fn main() { my_fn(MyEnum::FirstCase(0)); } "} {"_id":"q-en-rust-4e798409ee88a683a03ac44a13ba2f1ef7ca17c7bce892d97b883535a49d187a","text":"] [[package]] name = \"rustc-ap-rustc_arena\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"550ca1a0925d31a0af089b18c89f5adf3b286e319e3e1f1a5204c21bd2f17371\" dependencies = [ \"rustc-ap-rustc_data_structures\", \"smallvec\", ] [[package]] name = \"rustc-ap-rustc_ast\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"4aa53b68080df17994a54747f7c37b0686288a670efb9ba3b382ce62e744aed2\" dependencies = [ \"bitflags\", \"rustc-ap-rustc_data_structures\", \"rustc-ap-rustc_index\", \"rustc-ap-rustc_lexer\", \"rustc-ap-rustc_macros\", \"rustc-ap-rustc_serialize\", \"rustc-ap-rustc_span\", \"smallvec\", \"tracing\", ] [[package]] name = \"rustc-ap-rustc_ast_pretty\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"0ae71e68fada466a4b2c39c79ca6aee3226587abe6787170d2f6c92237569565\" dependencies = [ \"rustc-ap-rustc_ast\", \"rustc-ap-rustc_span\", \"tracing\", ] [[package]] name = \"rustc-ap-rustc_data_structures\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"faa484d6e0ca32d1d82303647275c696f745599b3d97e686f396ceef5b99d7ae\" dependencies = [ \"arrayvec\", \"bitflags\", \"cfg-if 0.1.10\", \"crossbeam-utils\", \"ena\", \"indexmap\", \"jobserver\", \"libc\", \"measureme 9.1.2\", \"memmap2\", \"parking_lot\", \"rustc-ap-rustc_graphviz\", \"rustc-ap-rustc_index\", \"rustc-ap-rustc_macros\", \"rustc-ap-rustc_serialize\", \"rustc-hash\", \"rustc-rayon\", \"rustc-rayon-core\", \"smallvec\", \"stable_deref_trait\", \"stacker\", \"tempfile\", \"tracing\", \"winapi\", ] [[package]] name = \"rustc-ap-rustc_errors\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"5f85ba19cca320ad797e3a29c35cab9bddfff0e7adbde336a436249e54cee7b1\" dependencies = [ \"annotate-snippets\", \"atty\", \"rustc-ap-rustc_data_structures\", \"rustc-ap-rustc_lint_defs\", \"rustc-ap-rustc_macros\", \"rustc-ap-rustc_serialize\", \"rustc-ap-rustc_span\", \"termcolor\", \"termize\", \"tracing\", \"unicode-width\", \"winapi\", ] [[package]] name = \"rustc-ap-rustc_feature\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"97d538adab96b8b2b1ca9fcd4c8c47d4e23e862a23d1a38b6c15cd8fd52b34b1\" dependencies = [ \"rustc-ap-rustc_data_structures\", \"rustc-ap-rustc_span\", ] [[package]] name = \"rustc-ap-rustc_fs_util\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"8ad6f13d240944fa8f360d2f3b849a7cadaec75e477829e7dde61e838deda83d\" [[package]] name = \"rustc-ap-rustc_graphviz\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"08b3451153cc5828c02cc4f1a0df146d25ac4b3382a112e25fd9d3f5bff15cdc\" [[package]] name = \"rustc-ap-rustc_index\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"cd39a9f01b442c629bdff5778cb3dd29b7c2ea4afe62d5ab61d216bd1b556692\" dependencies = [ \"arrayvec\", \"rustc-ap-rustc_macros\", \"rustc-ap-rustc_serialize\", ] [[package]] name = \"rustc-ap-rustc_lexer\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"a5de290c44a90e671d2cd730062b9ef73d11155da7e44e7741d633e1e51e616e\" dependencies = [ \"unicode-xid\", ] [[package]] name = \"rustc-ap-rustc_lint_defs\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"69570b4beb61088926b131579865bbe70d124d30778c46307a62ec8b310ae462\" dependencies = [ \"rustc-ap-rustc_ast\", \"rustc-ap-rustc_data_structures\", \"rustc-ap-rustc_macros\", \"rustc-ap-rustc_serialize\", \"rustc-ap-rustc_span\", \"rustc-ap-rustc_target\", \"tracing\", ] [[package]] name = \"rustc-ap-rustc_macros\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"86bd877df37f15c5a44d9679d1b5207ebc95f3943fbc336eeac670195ac58610\" dependencies = [ \"proc-macro2\", \"quote\", \"syn\", \"synstructure\", ] [[package]] name = \"rustc-ap-rustc_parse\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"02502d8522ba31d0bcad28a78822b68c1b6ba947a2b4aa6a2341b30594379b80\" dependencies = [ \"bitflags\", \"rustc-ap-rustc_ast\", \"rustc-ap-rustc_ast_pretty\", \"rustc-ap-rustc_data_structures\", \"rustc-ap-rustc_errors\", \"rustc-ap-rustc_feature\", \"rustc-ap-rustc_lexer\", \"rustc-ap-rustc_session\", \"rustc-ap-rustc_span\", \"smallvec\", \"tracing\", \"unicode-normalization\", ] [[package]] name = \"rustc-ap-rustc_serialize\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"5f741f8e9aee6323fbe127329490608a5a250cc0072ac91e684ef62518cdb1ff\" dependencies = [ \"indexmap\", \"smallvec\", ] [[package]] name = \"rustc-ap-rustc_session\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"dba61eca749f4fced4427ad1cc7f23342cfc6527c3bcc624e3aa56abc1f81298\" dependencies = [ \"bitflags\", \"getopts\", \"num_cpus\", \"rustc-ap-rustc_ast\", \"rustc-ap-rustc_data_structures\", \"rustc-ap-rustc_errors\", \"rustc-ap-rustc_feature\", \"rustc-ap-rustc_fs_util\", \"rustc-ap-rustc_lint_defs\", \"rustc-ap-rustc_macros\", \"rustc-ap-rustc_serialize\", \"rustc-ap-rustc_span\", \"rustc-ap-rustc_target\", \"tracing\", ] [[package]] name = \"rustc-ap-rustc_span\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"a642e8d6fc883f34e0778e079f8242ac40c6614a6b7a0ef61681333e847f5e62\" dependencies = [ \"cfg-if 0.1.10\", \"md-5\", \"rustc-ap-rustc_arena\", \"rustc-ap-rustc_data_structures\", \"rustc-ap-rustc_index\", \"rustc-ap-rustc_macros\", \"rustc-ap-rustc_serialize\", \"scoped-tls\", \"sha-1 0.9.1\", \"sha2\", \"tracing\", \"unicode-width\", ] [[package]] name = \"rustc-ap-rustc_target\" version = \"722.0.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"80feebd8c323b80dd73a395fa7fabba9e2098b6277670ff89c473f618ffa07de\" dependencies = [ \"bitflags\", \"rustc-ap-rustc_data_structures\", \"rustc-ap-rustc_index\", \"rustc-ap-rustc_macros\", \"rustc-ap-rustc_serialize\", \"rustc-ap-rustc_span\", \"tracing\", ] [[package]] name = \"rustc-demangle\" version = \"0.1.21\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"q-en-rust-4e8557afbf0f9ff04262339fc3608d700d2812899a7ad2c29d27b12c4de0589d","text":"use crate::infer::{InferCtxt, InferOk, TypeFreshener}; use crate::traits::error_reporting::TypeErrCtxtExt; use crate::traits::project::try_normalize_with_depth_to; use crate::traits::project::ProjectAndUnifyResult; use crate::traits::project::ProjectionCacheKeyExt; use crate::traits::ProjectionCacheKey;"} {"_id":"q-en-rust-4e8f316ef48671535b797caecef9dca4f9964f383067bca8b9067100a3c86f70","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":"q-en-rust-4e9cb7210da8ddec596ca11963be232964d155e01e045994ceca9adb523a8a11","text":"without modifying the original\"] #[inline] #[track_caller] #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] pub const fn ilog(self, base: Self) -> u32 { match self.checked_ilog(base) { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } assert!(base >= 2, \"base of integer logarithm must be at least 2\"); self.checked_ilog(base).expect(\"argument of integer logarithm must be positive\") } /// Returns the base 2 logarithm of the number, rounded down. /// /// # Panics /// /// When the number is negative or zero it panics in debug mode and the return value /// is 0 in release mode. /// This function will panic if `self` is less than or equal to zero. /// /// # Examples ///"} {"_id":"q-en-rust-4e9dd52c82ca3a4f85db0111c6fdfab4ca95f57f88447c89e1cdb72f8655847b","text":"\"this was erroneously allowed and will become a hard error in a future release\" }).emit(); } fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt { Stmt { id: DUMMY_NODE_ID, kind, span } } }"} {"_id":"q-en-rust-4e9edbd3face3ca98bc5edcce9309a8065fb22a5d8537ee066d309e13b187f48","text":"// noop } fn no_position_independent_executable(&mut self) { // noop } fn partial_relro(&mut self) { // noop }"} {"_id":"q-en-rust-4eb160549a8b0bc6ffa20bbdc16cfa938ba08b339c8a65298f8b85ae2ae81929","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":"q-en-rust-4ed9f192a3d9125ed311b5bb67f04b0394b07381d66b379c633956cf0deab7ae","text":"use super::{ForceCollect, Parser, PathStyle, Restrictions, Trailing, UsePreAttrPos}; use crate::errors::{ self, AmbiguousRangePattern, DotDotDotForRemainingFields, DotDotDotRangeToPatternNotAllowed, DotDotDotRestPattern, EnumPatternInsteadOfIdentifier, ExpectedBindingLeftOfAt, ExpectedCommaAfterPatternField, GenericArgsInPatRequireTurbofishSyntax, InclusiveRangeExtraEquals, InclusiveRangeMatchArrow, InclusiveRangeNoEnd, InvalidMutInPattern, ParenRangeSuggestion, PatternOnWrongSideOfAt, RemoveLet, RepeatedMutInPattern, SwitchRefBoxOrder, TopLevelOrPatternNotAllowed, TopLevelOrPatternNotAllowedSugg, TrailingVertNotAllowed, UnexpectedExpressionInPattern, UnexpectedExpressionInPatternSugg, UnexpectedLifetimeInPattern, UnexpectedParenInRangePat, UnexpectedParenInRangePatSugg, UnexpectedVertVertBeforeFunctionParam, UnexpectedVertVertInPattern, WrapInParens, self, AmbiguousRangePattern, AtDotDotInStructPattern, AtInStructPattern, DotDotDotForRemainingFields, DotDotDotRangeToPatternNotAllowed, DotDotDotRestPattern, EnumPatternInsteadOfIdentifier, ExpectedBindingLeftOfAt, ExpectedCommaAfterPatternField, GenericArgsInPatRequireTurbofishSyntax, InclusiveRangeExtraEquals, InclusiveRangeMatchArrow, InclusiveRangeNoEnd, InvalidMutInPattern, ParenRangeSuggestion, PatternOnWrongSideOfAt, RemoveLet, RepeatedMutInPattern, SwitchRefBoxOrder, TopLevelOrPatternNotAllowed, TopLevelOrPatternNotAllowedSugg, TrailingVertNotAllowed, UnexpectedExpressionInPattern, UnexpectedExpressionInPatternSugg, UnexpectedLifetimeInPattern, UnexpectedParenInRangePat, UnexpectedParenInRangePatSugg, UnexpectedVertVertBeforeFunctionParam, UnexpectedVertVertInPattern, WrapInParens, }; use crate::parser::expr::{could_be_unclosed_char_literal, DestructuredFloat}; use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};"} {"_id":"q-en-rust-4ef42f40af9de12e5adfa43e1fbf6808a901d862b09614586b91fb4d774cc2e6","text":" // build-pass fn main() { let mut log_service = LogService { inner: Inner }; log_service.call(()); } pub trait Service { type Response; fn call(&mut self, req: Request) -> Self::Response; } pub struct LogService { inner: S, } impl Service for LogService where S: Service, U: Extension + 'static, for<'a> U::Item<'a>: std::fmt::Debug, { type Response = S::Response; fn call(&mut self, req: T) -> Self::Response { self.inner.call(req) } } pub struct Inner; impl Service<()> for Inner { type Response = Resp; fn call(&mut self, req: ()) -> Self::Response { Resp::A(req) } } pub trait Extension { type Item<'a>; fn touch(self, f: F) -> Self where for<'a> F: Fn(Self::Item<'a>); } pub enum Resp { A(()), } impl Extension for Resp { type Item<'a> = RespItem<'a>; fn touch(self, _f: F) -> Self where for<'a> F: Fn(Self::Item<'a>), { match self { Self::A(a) => Self::A(a), } } } pub enum RespItem<'a> { A(&'a ()), } impl<'a> std::fmt::Debug for RespItem<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::A(arg0) => f.debug_tuple(\"A\").field(arg0).finish(), } } } "} {"_id":"q-en-rust-4ef62bf331d9f98fc6f056e5ce5169aa4b2fcad90cb9486a8dce85d0ce176450","text":"#[derive(RustcEncodable, RustcDecodable)] pub struct CrateRoot { pub rustc_version: String, pub name: Symbol, pub triple: String, pub hash: hir::svh::Svh,"} {"_id":"q-en-rust-4f04670d5bf66f58d0b6ad0f1cd3d0720b9158978c20aab7875293b778b7f0d7","text":"// linking executables as pie. Different versions of gcc seem to use // different quotes in the error message so don't check for them. if sess.target.target.options.linker_is_gnu && sess.linker_flavor() != LinkerFlavor::Ld && (out.contains(\"unrecognized command line option\") || out.contains(\"unknown argument\")) && out.contains(\"-no-pie\") &&"} {"_id":"q-en-rust-4f4e475060d01aad503266148346122aefa7138eae067dab14bf903d7f9f42c8","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":"q-en-rust-4fae9e5845d6e6f9da9e30b912aed52e06c23f99a4e50ec801b1b310b5230115","text":"}, ) }); // Priority of matches: // 1. Exact case insensitive match // 2. Levenshtein distance match // 3. Sorted word match if let Some(candidate) = case_insensitive_match { Some(candidate) // exact case insensitive match has a higher priority Some(*candidate) } else if levenshtein_match.is_some() { levenshtein_match.map(|(candidate, _)| *candidate) } else { levenstein_match.map(|(candidate, _)| candidate) find_match_by_sorted_words(name_vec, lookup) } } fn find_match_by_sorted_words<'a>(iter_names: Vec<&'a Symbol>, lookup: &str) -> Option { iter_names.iter().fold(None, |result, candidate| { if sort_by_words(&candidate.as_str()) == sort_by_words(lookup) { Some(**candidate) } else { result } }) } fn sort_by_words(name: &str) -> String { let mut split_words: Vec<&str> = name.split('_').collect(); split_words.sort(); split_words.join(\"_\") } "} {"_id":"q-en-rust-4fd6d3ac46fa24cf6cbb9593d699fa9ab50ec18237a2ea319fe6536aaaf84f62","text":"#![feature(unboxed_closures)] #![feature(unwrap_infallible)] #![feature(vec_into_raw_parts)] #![feature(vec_spare_capacity)] // NB: the above list is sorted to minimize merge conflicts. #![default_lib_allocator]"} {"_id":"q-en-rust-501273af67428a03efdc6a5d5beb1252b68b13c60112c506253704e98d3587b4","text":" error: expected `{`, found `;` --> $DIR/semi-in-let-chain.rs:7:23 | LL | && let () = (); | ^ expected `{` | note: you likely meant to continue parsing the let-chain starting here --> $DIR/semi-in-let-chain.rs:8:9 | LL | && let () = () | ^^^^^^ help: consider removing this semicolon to parse the `let` as part of the same chain | LL - && let () = (); LL + && let () = () | error: expected `{`, found `;` --> $DIR/semi-in-let-chain.rs:15:20 | LL | && () == (); | ^ expected `{` | note: the `if` expression is missing a block after this condition --> $DIR/semi-in-let-chain.rs:14:8 | LL | if let () = () | ________^ LL | | && () == (); | |___________________^ error: expected `{`, found `;` --> $DIR/semi-in-let-chain.rs:23:20 | LL | && () == (); | ^ expected `{` | note: you likely meant to continue parsing the let-chain starting here --> $DIR/semi-in-let-chain.rs:24:9 | LL | && let () = () | ^^^^^^ help: consider removing this semicolon to parse the `let` as part of the same chain | LL - && () == (); LL + && () == () | error: aborting due to 3 previous errors "} {"_id":"q-en-rust-5026628232884d4d056b4046a6f46301da4afa00a8ce41c645e18e7c20d39c2e","text":"try!(self.flush_buf()); } if buf.len() >= self.buf.capacity() { self.inner.as_mut().unwrap().write(buf) self.panicked = true; let r = self.inner.as_mut().unwrap().write(buf); self.panicked = false; r } else { let amt = cmp::min(buf.len(), self.buf.capacity()); Write::write(&mut self.buf, &buf[..amt])"} {"_id":"q-en-rust-502f1fc09410e14efee59e807615c7d401421889af7849be5cdfccc386ea5a25","text":"use rustc::hir; use syntax::attr; declare_lint!(CRATE_NOT_OKAY, Warn, \"crate not marked with #![crate_okay]\"); macro_rules! fake_lint_pass { ($struct:ident, $lints:expr, $($attr:expr),*) => { struct $struct; impl LintPass for $struct { fn get_lints(&self) -> LintArray { $lints } } struct Pass; impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $struct { fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) { $( if !attr::contains_name(&krate.attrs, $attr) { cx.span_lint(CRATE_NOT_OKAY, krate.span, &format!(\"crate is not marked with #![{}]\", $attr)); } )* } } impl LintPass for Pass { fn get_lints(&self) -> LintArray { lint_array!(CRATE_NOT_OKAY) } } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass { fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) { if !attr::contains_name(&krate.attrs, \"crate_okay\") { cx.span_lint(CRATE_NOT_OKAY, krate.span, \"crate is not marked with #![crate_okay]\"); } } declare_lint!(CRATE_NOT_OKAY, Warn, \"crate not marked with #![crate_okay]\"); declare_lint!(CRATE_NOT_RED, Warn, \"crate not marked with #![crate_red]\"); declare_lint!(CRATE_NOT_BLUE, Warn, \"crate not marked with #![crate_blue]\"); declare_lint!(CRATE_NOT_GREY, Warn, \"crate not marked with #![crate_grey]\"); declare_lint!(CRATE_NOT_GREEN, Warn, \"crate not marked with #![crate_green]\"); fake_lint_pass! { PassOkay, lint_array!(CRATE_NOT_OKAY), // Single lint \"crate_okay\" } fake_lint_pass! { PassRedBlue, lint_array!(CRATE_NOT_RED, CRATE_NOT_BLUE), // Multiple lints \"crate_red\", \"crate_blue\" } fake_lint_pass! { PassGreyGreen, lint_array!(CRATE_NOT_GREY, CRATE_NOT_GREEN, ), // Trailing comma \"crate_grey\", \"crate_green\" } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_late_lint_pass(box Pass); reg.register_late_lint_pass(box PassOkay); reg.register_late_lint_pass(box PassRedBlue); reg.register_late_lint_pass(box PassGreyGreen); }"} {"_id":"q-en-rust-505d050da985bd66ee4158271f64ac7c98fc819265ee9fa355078232a1333a64","text":" error[E0382]: use of moved value: `a` --> $DIR/dbg-issue-120327.rs:4:12 | LL | let a = String::new(); | - move occurs because `a` has type `String`, which does not implement the `Copy` trait LL | dbg!(a); | ------- value moved here LL | return a; | ^ value used here after move | help: consider borrowing instead of transferring ownership | LL | dbg!(&a); | + error[E0382]: use of moved value: `a` --> $DIR/dbg-issue-120327.rs:10:12 | LL | let a = String::new(); | - move occurs because `a` has type `String`, which does not implement the `Copy` trait LL | dbg!(1, 2, a, 1, 2); | ------------------- value moved here LL | return a; | ^ value used here after move | help: consider borrowing instead of transferring ownership | LL | dbg!(1, 2, &a, 1, 2); | + error[E0382]: use of moved value: `b` --> $DIR/dbg-issue-120327.rs:16:12 | LL | let b: String = \"\".to_string(); | - move occurs because `b` has type `String`, which does not implement the `Copy` trait LL | dbg!(a, b); | ---------- value moved here LL | return b; | ^ value used here after move | help: consider borrowing instead of transferring ownership | LL | dbg!(a, &b); | + error[E0382]: use of moved value: `a` --> $DIR/dbg-issue-120327.rs:22:12 | LL | fn x(a: String) -> String { | - move occurs because `a` has type `String`, which does not implement the `Copy` trait LL | let b: String = \"\".to_string(); LL | dbg!(a, b); | ---------- value moved here LL | return a; | ^ value used here after move | help: consider borrowing instead of transferring ownership | LL | dbg!(&a, b); | + error[E0382]: use of moved value: `b` --> $DIR/dbg-issue-120327.rs:46:12 | LL | tmp => { | --- value moved here ... LL | let b: String = \"\".to_string(); | - move occurs because `b` has type `String`, which does not implement the `Copy` trait LL | my_dbg!(b, 1); LL | return b; | ^ value used here after move | help: consider borrowing instead of transferring ownership | LL | my_dbg!(&b, 1); | + help: borrow this binding in the pattern to avoid moving the value | LL | ref tmp => { | +++ error[E0382]: use of moved value: `a` --> $DIR/dbg-issue-120327.rs:57:12 | LL | let a = String::new(); | - move occurs because `a` has type `String`, which does not implement the `Copy` trait LL | let _b = match a { LL | tmp => { | --- value moved here ... LL | return a; | ^ value used here after move | help: borrow this binding in the pattern to avoid moving the value | LL | ref tmp => { | +++ error[E0382]: borrow of moved value: `a` --> $DIR/dbg-issue-120327.rs:65:14 | LL | let a: String = \"\".to_string(); | - move occurs because `a` has type `String`, which does not implement the `Copy` trait LL | let _res = get_expr(dbg!(a)); | ------- value moved here LL | let _l = a.len(); | ^ value borrowed here after move | help: consider borrowing instead of transferring ownership | LL | let _res = get_expr(dbg!(&a)); | + error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0382`. "} {"_id":"q-en-rust-508160d5a776e6461ef20e59034ea6a641b313cb19f7fa554fa726884f0dc8df","text":" // Verify that the entry point injected by the test harness doesn't cause // weird artifacts in the coverage report (e.g. issue #10749). // compile-flags: --test #[allow(dead_code)] fn unused() {} #[test] fn my_test() {} "} {"_id":"q-en-rust-50e2afe7a7d6a964998cd385ef3132d68cba4f8cc07f4a00b95f382812ba43df","text":"} fn run(self, builder: &Builder<'_>) -> Option { // This prevents rust-analyzer from being built for \"dist\" or \"install\" // on the stable/beta channels. It is a nightly-only tool and should // not be included. if !builder.build.unstable_features() { return None; } let compiler = self.compiler; let target = self.target; assert!(builder.config.extended);"} {"_id":"q-en-rust-50fc0f6c82aafd045b4ec72511dc0e58dc79a591d3fa5ab3206bb2c4f17c1d73","text":" // Test to check that the \"warning blocks\" are displayed as expected. go-to: \"file://\" + |DOC_PATH| + \"/test_docs/struct.Foo.html\" show-text: true define-function: ( \"check-warning\", (theme, color, border_color, background_color), block { set-local-storage: {\"rustdoc-theme\": |theme|, \"rustdoc-use-system-theme\": \"false\"} reload: // The IDs are added directly into the DOM to make writing this test easier. assert-css: (\"#doc-warning-1\", { \"margin-bottom\": \"12px\", \"color\": |color|, \"border-left\": \"2px solid \" + |border_color|, \"background-color\": |background_color|, }) assert-css: (\"#doc-warning-2\", { \"margin-bottom\": \"0px\", \"color\": |color|, \"border-left\": \"2px solid \" + |border_color|, \"background-color\": |background_color|, }) }, ) call-function: (\"check-warning\", { \"theme\": \"ayu\", \"color\": \"rgb(197, 197, 197)\", \"border_color\": \"rgb(255, 142, 0)\", \"background_color\": \"rgba(0, 0, 0, 0)\", }) call-function: (\"check-warning\", { \"theme\": \"dark\", \"color\": \"rgb(221, 221, 221)\", \"border_color\": \"rgb(255, 142, 0)\", \"background_color\": \"rgba(0, 0, 0, 0)\", }) call-function: (\"check-warning\", { \"theme\": \"light\", \"color\": \"rgb(0, 0, 0)\", \"border_color\": \"rgb(255, 142, 0)\", \"background_color\": \"rgba(0, 0, 0, 0)\", }) "} {"_id":"q-en-rust-5112dbb659220f1ff1c7f4edeb443009cc2f66d672afce2a8a77b35806818de8","text":".label = invalid stability version .item = the stability attribute annotates this item passes_lang_item_fn_with_target_feature = `{$name}` language item function is not allowed to have `#[target_feature]` .label = `{$name}` language item function is not allowed to have `#[target_feature]` passes_lang_item_on_incorrect_target = `{$name}` language item must be applied to a {$expected_target} .label = attribute should be applied to a {$expected_target}, not a {$actual_target}"} {"_id":"q-en-rust-514b7bd853aeacb35a3cb39f9f88144c84d8b49d655c22406d23bddffba9b274","text":"if builder.config.llvm_thin_lto { cfg.define(\"LLVM_ENABLE_LTO\", \"Thin\"); if !target.contains(\"apple\") { cfg.define(\"LLVM_USE_LINKER\", \"lld\"); cfg.define(\"LLVM_ENABLE_LLD\", \"ON\"); } }"} {"_id":"q-en-rust-5175c854044606cfa0fda881cb65908c399bcd3fb34d51c9ceef74ca8c507ddd","text":"} ``` ### Error example 3 Suppose we have a struct `Foo` and we would like to define some methods for it. The following code example has a definition which leads to a compiler error: ```compile_fail,E0207 struct Foo; impl Foo { // error: the const parameter `T` is not constrained by the impl trait, self // type, or predicates [E0207] fn get(&self) -> i32 { i32::default() } } ``` The problem is that the const parameter `T` does not appear in the implementing type (`Foo`) of the impl. In this case, we can fix the error by moving the type parameter from the `impl` to the method `get`: ``` struct Foo; // Move the const parameter from the impl to the method impl Foo { fn get(&self) -> i32 { i32::default() } } ``` ### Error example 4 Suppose we have a struct `Foo` and a struct `Bar` that uses lifetime `'a`. We would like to implement trait `Contains` for `Foo`. The trait `Contains` have the associated type `B`. The following code example has a definition which leads to a compiler error: ```compile_fail,E0207 struct Foo; struct Bar<'a>; trait Contains { type B; fn get(&self) -> i32; } impl<'a> Contains for Foo { type B = Bar<'a>; // error: the lifetime parameter `'a` is not constrained by the impl trait, // self type, or predicates [E0207] fn get(&self) -> i32 { i32::default() } } ``` Please note that unconstrained lifetime parameters are not supported if they are being used by an associated type. ### Additional information For more information, please see [RFC 447]."} {"_id":"q-en-rust-5181ddc60c2a6701eae012d19c33d5f7fd79c13c3c4f9e94a9e8571c69ada1cd","text":" error[E0204]: the trait `ConstParamTy` cannot be implemented for this type --> $DIR/nested_bad_const_param_ty.rs:6:10 | LL | #[derive(ConstParamTy)] | ^^^^^^^^^^^^ LL | LL | struct Foo([*const u8; 1]); | -------------- this field does not implement `ConstParamTy` | note: the `ConstParamTy` impl for `[*const u8; 1]` requires that `*const u8: ConstParamTy` --> $DIR/nested_bad_const_param_ty.rs:8:12 | LL | struct Foo([*const u8; 1]); | ^^^^^^^^^^^^^^ = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy` cannot be implemented for this type --> $DIR/nested_bad_const_param_ty.rs:10:10 | LL | #[derive(ConstParamTy)] | ^^^^^^^^^^^^ LL | LL | struct Foo2([*mut u8; 1]); | ------------ this field does not implement `ConstParamTy` | note: the `ConstParamTy` impl for `[*mut u8; 1]` requires that `*mut u8: ConstParamTy` --> $DIR/nested_bad_const_param_ty.rs:12:13 | LL | struct Foo2([*mut u8; 1]); | ^^^^^^^^^^^^ = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy` cannot be implemented for this type --> $DIR/nested_bad_const_param_ty.rs:14:10 | LL | #[derive(ConstParamTy)] | ^^^^^^^^^^^^ LL | LL | struct Foo3([fn(); 1]); | --------- this field does not implement `ConstParamTy` | note: the `ConstParamTy` impl for `[fn(); 1]` requires that `fn(): ConstParamTy` --> $DIR/nested_bad_const_param_ty.rs:16:13 | LL | struct Foo3([fn(); 1]); | ^^^^^^^^^ = note: this error originates in the derive macro `ConstParamTy` (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 E0204`. "} {"_id":"q-en-rust-518a8298f9b628d2c01fe1fd21712e42186fc91a5378002a77e9d843cf6ed2c6","text":"use rustc_hir::definitions::Definitions; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; use rustc_hir::{ Constness, ExprKind, HirId, ImplItemKind, ItemKind, Node, TraitCandidate, TraitItemKind, }; use rustc_hir::{Constness, HirId, Node, TraitCandidate}; use rustc_index::IndexVec; use rustc_macros::HashStable; use rustc_query_system::dep_graph::DepNodeIndex;"} {"_id":"q-en-rust-519428d40dcacfa6375da9c2558811c8e9e7da73fdfc11ef03b764d7d96f971c","text":"Ok(lhs) } fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool { match (self.expr_is_complete(lhs), self.check_assoc_op()) { // Semi-statement forms are odd: // See https://github.com/rust-lang/rust/issues/29071 (true, None) => false, (false, _) => true, // Continue parsing the expression. // An exhaustive check is done in the following block, but these are checked first // because they *are* ambiguous but also reasonable looking incorrect syntax, so we // want to keep their span info to improve diagnostics in these cases in a later stage. (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3` (true, Some(AssocOp::Subtract)) | // `{ 42 } -5` (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475) (true, Some(AssocOp::Add)) // `{ 42 } + 42 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect: // `if x { a } else { b } && if y { c } else { d }` if !self.look_ahead(1, |t| t.is_reserved_ident()) => { // These cases are ambiguous and can't be identified in the parser alone. let sp = self.sess.source_map().start_point(self.token.span); self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span); false } (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => false, (true, Some(_)) => { self.error_found_expr_would_be_stmt(lhs); true } } } /// We've found an expression that would be parsed as a statement, /// but the next token implies this should be parsed as an expression. /// For example: `if let Some(x) = x { x } else { 0 } / 2`. fn error_found_expr_would_be_stmt(&self, lhs: &Expr) { let mut err = self.struct_span_err(self.token.span, &format!( \"expected expression, found `{}`\", pprust::token_to_string(&self.token), )); err.span_label(self.token.span, \"expected expression\"); self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs))); err.emit(); } /// Possibly translate the current token to an associative operator. /// The method does not advance the current token. /// /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively. fn check_assoc_op(&self) -> Option { AssocOp::from_token(&self.token) } /// Checks if this expression is a successfully parsed statement. fn expr_is_complete(&self, e: &Expr) -> bool { self.restrictions.contains(Restrictions::STMT_EXPR) &&"} {"_id":"q-en-rust-51a14b0fe4e788cce99d711f6ee4279bb5d9700c75d23d0bf30ee8ce06efaa36","text":"use util::fs::fix_windows_verbatim_for_gcc; use rustc_back::tempdir::TempDir; use std::ascii; use std::char; use std::env; use std::ffi::OsString; use std::fs::{self, PathExt};"} {"_id":"q-en-rust-51ab7edd1eb40a7806fc40939e458f81e6d86a8c6a90e16b6fcdcaf2deef86b9","text":"Also, please make sure that fixup commits are squashed into other related commits with meaningful commit messages. GitHub allows [closing issues using keywords][closing-keywords]. This feature should be used to keep the issue tracker tidy. However, it is generally preferred to put the \"closes #123\" text in the PR description rather than the issue commit; particularly during rebasing, citing the issue number in the commit can \"spam\" the issue in question. [closing-keywords]: https://help.github.com/en/articles/closing-issues-using-keywords Please make sure your pull request is in compliance with Rust's style guidelines by running"} {"_id":"q-en-rust-51b896b2ab86eac95d6d416f37a01b4792dd22a082ca58b06ad4ec6f09451e52","text":"#[derive(Default)] struct OptimizationList<'tcx> { and_stars: FxHashMap, and_stars: FxHashSet, arrays_lengths: FxHashMap>, }"} {"_id":"q-en-rust-51b9dcb4266975dcdc228cb93e60153c53ecb1ce47e2f91d9bce9bb250a7a38f","text":" // Test that the `'a` from the impl doesn't // prevent us from creating a `'a` parameter // on the `blah` function. // // check-pass #![feature(in_band_lifetimes)] struct Foo<'a> { x: &'a u32 } impl Foo<'a> { fn method(&self) { fn blah(f: Foo<'a>) { } } } fn main() { } "} {"_id":"q-en-rust-51d36013277a2150cff5ecb7e97ebfcdc9d42abf388f276efffc13781a598ca5","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":"q-en-rust-51daf00b2fd4965413dec13dd06509891a78db94797447b9bc135dc39d3b64ef","text":"rustflags.arg(sysroot_str); } // https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/.E2.9C.94.20link.20new.20library.20into.20stage1.2Frustc if self.config.llvm_enzyme { rustflags.arg(\"-l\"); rustflags.arg(\"Enzyme-19\"); } let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling { Some(setting) => { // If an explicit setting is given, use that"} {"_id":"q-en-rust-5206f5a0098b9f67695383b69ffa401cef805f5596a9b4f20a99dc2cea9aa973","text":"} } pub fn retokenise_span(&self, span: Span) -> StringReader<'a> { lexer::StringReader::retokenize(&self.sess.parse_sess, span) } pub fn sub_span_of_token(&self, span: Span, tok: TokenKind) -> Option { let mut toks = self.retokenise_span(span); loop { let next = toks.next_token(); if next == token::Eof { return None; } if next == tok { return Some(next.span); } /// Finds the span of `*` token withing the larger `span`. pub fn sub_span_of_star(&self, mut span: Span) -> Option { let begin = self.sess.source_map().lookup_byte_offset(span.lo()); let end = self.sess.source_map().lookup_byte_offset(span.hi()); // Make the range zero-length if the span is invalid. if begin.sf.start_pos != end.sf.start_pos { span = span.shrink_to_lo(); } } // // Return the name for a macro definition (identifier after first `!`) // pub fn span_for_macro_def_name(&self, span: Span) -> Option { // let mut toks = self.retokenise_span(span); // loop { // let ts = toks.real_token(); // if ts == token::Eof { // return None; // } // if ts == token::Not { // let ts = toks.real_token(); // if ts.kind.is_ident() { // return Some(ts.sp); // } else { // return None; // } // } // } // } let sf = Lrc::clone(&begin.sf); // // Return the name for a macro use (identifier before first `!`). // pub fn span_for_macro_use_name(&self, span:Span) -> Option { // let mut toks = self.retokenise_span(span); // let mut prev = toks.real_token(); // loop { // if prev == token::Eof { // return None; // } // let ts = toks.real_token(); // if ts == token::Not { // if prev.kind.is_ident() { // return Some(prev.sp); // } else { // return None; // } // } // prev = ts; // } // } self.sess.source_map().ensure_source_file_source_present(Lrc::clone(&sf)); let src = sf.src.clone().or_else(|| sf.external_src.borrow().get_source().map(Lrc::clone))?; let to_index = |pos: BytePos| -> usize { (pos - sf.start_pos).0 as usize }; let text = &src[to_index(span.lo())..to_index(span.hi())]; let start_pos = { let mut pos = 0; tokenize(text) .map(|token| { let start = pos; pos += token.len; (start, token) }) .find(|(_pos, token)| token.kind == TokenKind::Star)? .0 }; let lo = span.lo() + BytePos(start_pos as u32); let hi = lo + BytePos(1); Some(span.with_lo(lo).with_hi(hi)) } /// Return true if the span is generated code, and /// it is not a subspan of the root callsite."} {"_id":"q-en-rust-52494d20dc491cea6474134aaef4eb6c07f0a452083b8ed0b26c49253039e86c","text":"for possible_ancestor in min_cap_list.iter_mut() { match determine_place_ancestry_relation(&place, &possible_ancestor.place) { // current place is descendant of possible_ancestor PlaceAncestryRelation::Descendant => { PlaceAncestryRelation::Descendant | PlaceAncestryRelation::SamePlace => { ancestor_found = true; let backup_path_expr_id = possible_ancestor.info.path_expr_id;"} {"_id":"q-en-rust-526793ee434580301314c7981f76f7a518a0398415a6236f1fa008bd70c313d8","text":"# If this file is modified, then llvm will be forcibly cleaned and then rebuilt. # The actual contents of this file do not matter, but to trigger a change on the # build bots then the contents should be changed so git updates the mtime. 2017-03-02 2017-03-04 "} {"_id":"q-en-rust-527e5c495b76279610722d92337d7d657943b5c33e41d1cfe571cfc433aee5a9","text":"Ok(()) } } /// Returns the maximum size of return values to be passed by value in the Rust ABI. /// /// Return values beyond this size will use an implicit out-pointer instead. pub fn max_ret_by_val(spec: &C) -> Size { match spec.target_spec().arch.as_str() { // System-V will pass return values up to 128 bits in RAX/RDX. \"x86_64\" => Size::from_bits(128), _ => spec.data_layout().pointer_size, } } "} {"_id":"q-en-rust-5291abfd826290e7423bd1462e4feb0c86319a565f499ef69702b6de6ba6ea91","text":"}); output.extend(items); // Also add the destructor let dg_type = glue::get_drop_glue_type(scx.tcx(), trait_ref.self_ty()); output.push(TransItem::DropGlue(DropGlueKind::Ty(dg_type))); } _ => { /* */ } } } // Also add the destructor let dg_type = glue::get_drop_glue_type(scx.tcx(), impl_ty); if glue::type_needs_drop(scx.tcx(), dg_type) { output.push(TransItem::DropGlue(DropGlueKind::Ty(dg_type))); } } }"} {"_id":"q-en-rust-52d5f89d0737690806b973a9151c99fccbf30491a4e9a191b701ace3ba24d83d","text":"MergeFunctions::Disabled | MergeFunctions::Trampolines => {} MergeFunctions::Aliases => { add(\"-mergefunc-use-aliases\"); add(\"-mergefunc-use-aliases\", false); } } } if sess.target.target.target_os == \"emscripten\" && sess.panic_strategy() == PanicStrategy::Unwind { add(\"-enable-emscripten-cxx-exceptions\"); add(\"-enable-emscripten-cxx-exceptions\", false); } // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes // during inlining. Unfortunately these may block other optimizations. add(\"-preserve-alignment-assumptions-during-inlining=false\"); add(\"-preserve-alignment-assumptions-during-inlining=false\", false); for arg in &sess.opts.cg.llvm_args { add(&(*arg)); add(&(*arg), true); } }"} {"_id":"q-en-rust-532d40b1569c8921eb60c407e10359c3ee8e80c91022e14aa465c18e1abc78ca","text":" use rustc_middle::ty::TyCtxt; use rustc_middle::ty::Visibility; use crate::clean; use crate::clean::Item; use crate::core::DocContext; use crate::fold::{strip_item, DocFolder}; use crate::passes::Pass; pub(crate) const STRIP_ALIASED_NON_LOCAL: Pass = Pass { name: \"strip-aliased-non-local\", run: strip_aliased_non_local, description: \"strips all non-local private aliased items from the output\", }; fn strip_aliased_non_local(krate: clean::Crate, cx: &mut DocContext<'_>) -> clean::Crate { let mut stripper = AliasedNonLocalStripper { tcx: cx.tcx }; stripper.fold_crate(krate) } struct AliasedNonLocalStripper<'tcx> { tcx: TyCtxt<'tcx>, } impl<'tcx> DocFolder for AliasedNonLocalStripper<'tcx> { fn fold_item(&mut self, i: Item) -> Option { Some(match *i.kind { clean::TypeAliasItem(..) => { let mut stripper = NonLocalStripper { tcx: self.tcx }; // don't call `fold_item` as that could strip the type-alias it-self // which we don't want to strip out stripper.fold_item_recur(i) } _ => self.fold_item_recur(i), }) } } struct NonLocalStripper<'tcx> { tcx: TyCtxt<'tcx>, } impl<'tcx> DocFolder for NonLocalStripper<'tcx> { fn fold_item(&mut self, i: Item) -> Option { // If not local, we want to respect the original visibility of // the field and not the one given by the user for the currrent crate. // // FIXME(#125009): Not-local should probably consider same Cargo workspace if !i.def_id().map_or(true, |did| did.is_local()) { if i.visibility(self.tcx) != Some(Visibility::Public) || i.is_doc_hidden() { return Some(strip_item(i)); } } Some(self.fold_item_recur(i)) } } "} {"_id":"q-en-rust-5358e74b84d096562ac437709df4b096f2a6cf9989aeb3ab76b779f1779438a4","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":"q-en-rust-53e132a1218920666bdb0f6ea6bc215d5ff80256ba19ed81e4729986ee090877","text":"use std::c_str::ToCStr; use std::cast; use std::hashmap::{HashMap, HashSet}; use std::cmp; use std::io; use std::os::consts::{macos, freebsd, linux, android, win32};"} {"_id":"q-en-rust-53e8ab9bcbe5fd3017686d2f038fdd391c5e23886b96a202fe0a309fb2ef5419","text":" error: macro-expanded `extern crate` items cannot shadow names passed with `--extern` --> $DIR/issue-109148.rs:6:9 | LL | extern crate core as std; | ^^^^^^^^^^^^^^^^^^^^^^^^^ ... LL | m!(); | ---- in this macro invocation | = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to previous error "} {"_id":"q-en-rust-542bade0d4af2b7af6e97a9c3ba77e1b663527f31a948e1398407c854b4d3aa7","text":"use syntax::source_map::Span; use super::{ FnVal, GlobalId, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, StackPopCleanup, FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, StackPopCleanup, }; impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {"} {"_id":"q-en-rust-544367c34933427651221fce21ceacadb209e99c957a8034b35ea1dcb48c3006","text":"self_ty: Ty<'tcx>, sig: ty::PolyGenSig<'tcx>, ) -> ty::Binder<'tcx, (ty::TraitRef<'tcx>, Ty<'tcx>)> { debug_assert!(!self_ty.has_escaping_bound_vars()); assert!(!self_ty.has_escaping_bound_vars()); let trait_ref = tcx.mk_trait_ref(fn_trait_def_id, [self_ty]); sig.map_bound(|sig| (trait_ref, sig.return_ty)) }"} {"_id":"q-en-rust-547cd3113824f259a4d2cca3dc76bd54ef2b1db686b3880a7b71650634053fe3","text":"} #[cfg(test)] mod bench; #[cfg(test)] #[macro_use] mod bench; // FIXME(#14344) this shouldn't be necessary #[doc(hidden)]"} {"_id":"q-en-rust-54fc3dd964382d24ef6b2bd6a388679548ab108856d1dfa7c2cd27d6ab3107df","text":" // Regression test for https://github.com/rust-lang/rust/issues/43134 // check-pass // compile-flags: --cap-lints allow type Foo = Option; fn main() {} "} {"_id":"q-en-rust-556a70d91ec77637dae96320aedbe4b059e5b409351b8fcd4a3580d67e7ccbe2","text":"fn parse_crate_mod(&mut self) -> Result { let mut parser = AssertUnwindSafe(&mut self.parser); match catch_unwind(move || parser.parse_crate_mod()) { Ok(Ok(k)) => Ok(k), Ok(Err(db)) => { // rustfmt doesn't use `run_compiler` like other tools, so it must emit // any stashed diagnostics itself, otherwise the `DiagCtxt` will assert // when dropped. The final result here combines the parsing result and // the `emit_stashed_diagnostics` result. let parse_res = catch_unwind(move || parser.parse_crate_mod()); let stashed_res = self.parser.dcx().emit_stashed_diagnostics(); let err = Err(ParserError::ParsePanicError); match (parse_res, stashed_res) { (Ok(Ok(k)), None) => Ok(k), (Ok(Ok(_)), Some(_guar)) => err, (Ok(Err(db)), _) => { db.emit(); Err(ParserError::ParseError) err } Err(_) => Err(ParserError::ParsePanicError), (Err(_), _) => err, } } }"} {"_id":"q-en-rust-55a37e08d63fd3f6d5d71d99c02dd06fe03e36225686d970b29093dd26e1e63f","text":"use use_from_trait_xc::Trait::foo; //~^ ERROR `foo` is not directly importable use use_from_trait_xc::Trait::Assoc; //~^ ERROR `Assoc` is not directly importable use use_from_trait_xc::Trait::CONST; //~^ ERROR `CONST` is not directly importable use use_from_trait_xc::Foo::new; //~^ ERROR `new` is not directly importable use use_from_trait_xc::Foo::C; //~^ ERROR unresolved import `use_from_trait_xc::Foo::C` use use_from_trait_xc::Bar::new as bnew; //~^ ERROR `bnew` is not directly importable"} {"_id":"q-en-rust-5653a5a4535e2eedad3a123a0cdaca78958203bbab0aac6e31bdf98f54ac7e7f","text":"pub fn run_silent(cmd: &mut Command) { let status = match cmd.status() { Ok(status) => status, Err(e) => fail(&format!(\"failed to execute command: {}\", e)), Err(e) => fail(&format!(\"failed to execute command: {:?}nerror: {}\", cmd, e)), }; if !status.success() { fail(&format!(\"command did not execute successfully: {:?}n"} {"_id":"q-en-rust-565860e6f8336d34442cb162de6280e8124d7750a0c9a575ee2f62cf39a7dd70","text":"/// /// # Examples /// ``` /// #![feature(div_duration)] /// use std::time::Duration; /// /// let dur1 = Duration::new(2, 700_000_000); /// let dur2 = Duration::new(5, 400_000_000); /// assert_eq!(dur1.div_duration_f64(dur2), 0.5); /// ``` #[unstable(feature = \"div_duration\", issue = \"63139\")] #[stable(feature = \"div_duration\", since = \"CURRENT_RUSTC_VERSION\")] #[must_use = \"this returns the result of the operation, without modifying the original\"] #[inline] #[rustc_const_unstable(feature = \"duration_consts_float\", issue = \"72440\")] pub const fn div_duration_f64(self, rhs: Duration) -> f64 { self.as_secs_f64() / rhs.as_secs_f64() let self_nanos = (self.secs as f64) * (NANOS_PER_SEC as f64) + (self.nanos.0 as f64); let rhs_nanos = (rhs.secs as f64) * (NANOS_PER_SEC as f64) + (rhs.nanos.0 as f64); self_nanos / rhs_nanos } /// Divide `Duration` by `Duration` and return `f32`. /// /// # Examples /// ``` /// #![feature(div_duration)] /// use std::time::Duration; /// /// let dur1 = Duration::new(2, 700_000_000); /// let dur2 = Duration::new(5, 400_000_000); /// assert_eq!(dur1.div_duration_f32(dur2), 0.5); /// ``` #[unstable(feature = \"div_duration\", issue = \"63139\")] #[stable(feature = \"div_duration\", since = \"CURRENT_RUSTC_VERSION\")] #[must_use = \"this returns the result of the operation, without modifying the original\"] #[inline] #[rustc_const_unstable(feature = \"duration_consts_float\", issue = \"72440\")] pub const fn div_duration_f32(self, rhs: Duration) -> f32 { self.as_secs_f32() / rhs.as_secs_f32() let self_nanos = (self.secs as f32) * (NANOS_PER_SEC as f32) + (self.nanos.0 as f32); let rhs_nanos = (rhs.secs as f32) * (NANOS_PER_SEC as f32) + (rhs.nanos.0 as f32); self_nanos / rhs_nanos } }"} {"_id":"q-en-rust-569d85e493bff380b6d71535f9e48d2656d6f88309a8ba1be7b243a9638d9d7b","text":" // https://github.com/rust-lang/rust/issues/116796 struct X; //~^ ERROR using function pointers as const generic parameters is forbidden fn main() {} "} {"_id":"q-en-rust-56da3253d8bda107fa8229b29afa15a4231e88be37f976c2d0a2eca764a303ad","text":"use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::def_id::DefIdSet; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Symbol; use rustc_span::{edit_distance, ExpnKind, FileName, MacroKind, Span}; use rustc_span::{Symbol, DUMMY_SP}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::error_reporting::on_unimplemented::OnUnimplementedNote; use rustc_trait_selection::traits::error_reporting::on_unimplemented::TypeErrCtxtExt as _;"} {"_id":"q-en-rust-56f94aff869655488dbb2438254ea3806f0abc0be99c627f0cb43f714a674eb1","text":"def.variant_descr(), self.tcx.def_path_str(def.did) ) .span_label(span, \"private field\") .span_label(span, label) .emit(); } }"} {"_id":"q-en-rust-5704eb02bd8b51d8b913ca0614ed051a65a4c9307fe32714c9df3cfb0d2af72d","text":"let rty = ccx.tcx.node_id_to_type(id); let fcx = FnCtxt::new(&inh, ty::FnConverging(rty), e.id); let declty = fcx.tcx.lookup_item_type(ccx.tcx.map.local_def_id(id)).ty; fcx.require_type_is_sized(declty, e.span, traits::ConstSized); fcx.check_const_with_ty(sp, e, declty); }); }"} {"_id":"q-en-rust-5755739e34f53597f01dab6e8b2fb0ccd2b76d453671aed498237ea13d396e59","text":" // no-prefer-dynamic #![feature(unsized_tuple_coercion)] static mut DROP_RAN: bool = false;"} {"_id":"q-en-rust-577347ff97a897de52aeafa2b5ea174a38d8065492229dedd255a8acc7029c42","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":"q-en-rust-57c748aa6ca21b9aeebbef9328ee9ce749544f1889339cff1a16b49e1d5becee","text":"name_was_remapped: bool, unmapped_path: FileName, mut src: String, start_pos: BytePos) -> SourceFile { start_pos: BytePos) -> Result { remove_bom(&mut src); let src_hash = {"} {"_id":"q-en-rust-581e6f09f679ae44f5b498ef9e445dc3c5c89af959f7b1173268bb9c62be1568","text":" error[E0658]: associated const equality is incomplete --> $DIR/dont-ice-on-assoc-projection.rs:15:32 | LL | impl Foo for T where T: Bar {} | ^^^^^^^^^ | = note: see issue #92827 for more information = help: add `#![feature(associated_const_equality)]` to the crate attributes to enable error[E0119]: conflicting implementations of trait `Foo` for type `()` --> $DIR/dont-ice-on-assoc-projection.rs:15:1 | LL | impl Foo for () {} | --------------- first implementation here LL | impl Foo for T where T: Bar {} | ^^^^^^^^^^^^^^^^^ conflicting implementation for `()` error: aborting due to 2 previous errors Some errors have detailed explanations: E0119, E0658. For more information about an error, try `rustc --explain E0119`. "} {"_id":"q-en-rust-58305f8119de56228536916cc7f17e60bbc5ab6e8a59af48904070ca68af00b7","text":" // ignore-tidy-linelength #![deny(intra_doc_resolution_failure)] pub mod char {} /// See also [type@char] // @has intra_link_prim_precedence/struct.MyString.html '//a/@href' 'https://doc.rust-lang.org/nightly/std/primitive.char.html' pub struct MyString; /// See also [char] // @has intra_link_prim_precedence/struct.MyString2.html '//a/@href' 'intra_link_prim_precedence/char/index.html' pub struct MyString2; "} {"_id":"q-en-rust-58376f50ca9f184f78766388a906065e764a0f8b1ada0d869f3ef08fff6f3d9f","text":"(accepted, impl_header_lifetime_elision, \"1.31.0\", Some(15872), None), // `extern crate foo as bar;` puts `bar` into extern prelude. (accepted, extern_crate_item_prelude, \"1.31.0\", Some(55599), None), // Allows use of the :literal macro fragment specifier (RFC 1576) (accepted, macro_literal_matcher, \"1.31.0\", Some(35625), None), ); // If you change this, please modify src/doc/unstable-book as well. You must"} {"_id":"q-en-rust-583e4481c9d0e9b2f8ad8ac72d78de0208514aa0ebfe39ac4d6f464c4e02f5fd","text":" // normalize-stderr-test \"error `.*`\" -> \"$$ERROR_MESSAGE\" // compile-flags: -o/tmp/ -Zunpretty=ast-tree fn main() {} "} {"_id":"q-en-rust-589bd3a8c5d4dc4d0f25875ebdcaa154787d6c552f3184bd6c8503412d75fbf3","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:issue-25467.rs pub type Issue25467BarT = (); pub type Issue25467FooT = (); extern crate issue_25467 as aux; fn main() { let o: aux::Object = None; } "} {"_id":"q-en-rust-58a938ed27375ea1ee29c752721b4dfa60e1ba7f498eea337a11bd3fe4a88d65","text":"document(w, cx, it) } fn implementor2item<'a>(cache: &'a Cache, imp : &Implementor) -> Option<&'a clean::Item> { if let Some(t_did) = imp.impl_.for_.def_id() { if let Some(impl_item) = cache.impls.get(&t_did).and_then(|i| i.iter() .find(|i| i.impl_item.def_id == imp.def_id)) { let i = &impl_item.impl_item; return Some(i); } } None } fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, t: &clean::Trait) -> fmt::Result { let mut bounds = String::new();"} {"_id":"q-en-rust-58b46e6bc2aa545d820e73afd12ef91d2f74e446d0f8f26771476fa7f8b994a8","text":"//! paths/files is based on Microsoft's logic in their vcvars bat files, but //! comments can also be found below leading through the various code paths. use std::process::Command; use session::Session; #[cfg(windows)] mod registry; #[cfg(windows)] pub fn link_exe_cmd(sess: &Session) -> Command { mod platform { use std::env; use std::ffi::OsString; use std::fs; use std::path::{Path, PathBuf}; use self::registry::{LOCAL_MACHINE}; let arch = &sess.target.target.arch; let (binsub, libsub, vclibsub) = match (bin_subdir(arch), lib_subdir(arch), vc_lib_subdir(arch)) { (Some(x), Some(y), Some(z)) => (x, y, z), _ => return Command::new(\"link.exe\"), }; use std::process::Command; use session::Session; use super::registry::{LOCAL_MACHINE}; // First we need to figure out whether the environment is already correctly // configured by vcvars. We do this by looking at the environment variable // `VCINSTALLDIR` which is always set by vcvars, and unlikely to be set // otherwise. If it is defined, then we derive the path to `link.exe` from // that and trust that everything else is configured correctly. // // If `VCINSTALLDIR` wasn't defined (or we couldn't find the linker where it // claimed it should be), then we resort to finding everything ourselves. // First we find where the latest version of MSVC is installed and what // version it is. Then based on the version we find the appropriate SDKs. // // For MSVC 14 (VS 2015) we look for the Win10 SDK and failing that we look // for the Win8.1 SDK. We also look for the Universal CRT. // // For MSVC 12 (VS 2013) we look for the Win8.1 SDK. // // For MSVC 11 (VS 2012) we look for the Win8 SDK. // // For all other versions the user has to execute the appropriate vcvars bat // file themselves to configure the environment. // // If despite our best efforts we are still unable to find MSVC then we just // blindly call `link.exe` and hope for the best. return env::var_os(\"VCINSTALLDIR\").and_then(|dir| { debug!(\"Environment already configured by user. Assuming it works.\"); let mut p = PathBuf::from(dir); p.push(\"bin\"); p.push(binsub); p.push(\"link.exe\"); if !p.is_file() { return None } Some(Command::new(p)) }).or_else(|| { get_vc_dir().and_then(|(ver, vcdir)| { debug!(\"Found VC installation directory {:?}\", vcdir); let mut linker = vcdir.clone(); linker.push(\"bin\"); linker.push(binsub); linker.push(\"link.exe\"); if !linker.is_file() { return None } let mut cmd = Command::new(linker); add_lib(&mut cmd, &vcdir.join(\"lib\").join(vclibsub)); if ver == \"14.0\" { if let Some(dir) = get_ucrt_dir() { debug!(\"Found Universal CRT {:?}\", dir); add_lib(&mut cmd, &dir.join(\"ucrt\").join(libsub)); } if let Some(dir) = get_sdk10_dir() { debug!(\"Found Win10 SDK {:?}\", dir); add_lib(&mut cmd, &dir.join(\"um\").join(libsub)); } else if let Some(dir) = get_sdk81_dir() { debug!(\"Found Win8.1 SDK {:?}\", dir); add_lib(&mut cmd, &dir.join(\"um\").join(libsub)); } } else if ver == \"12.0\" { if let Some(dir) = get_sdk81_dir() { debug!(\"Found Win8.1 SDK {:?}\", dir); add_lib(&mut cmd, &dir.join(\"um\").join(libsub)); } } else { // ver == \"11.0\" if let Some(dir) = get_sdk8_dir() { debug!(\"Found Win8 SDK {:?}\", dir); add_lib(&mut cmd, &dir.join(\"um\").join(libsub)); } } Some(cmd) // Cross toolchains depend on dlls from the host toolchain // We can't just add it to the Command's PATH in `link_exe_cmd` because it // is later overridden so we publicly expose it here instead pub fn host_dll_path() -> Option { get_vc_dir().and_then(|(_, vcdir)| { host_dll_subdir().map(|sub| { vcdir.join(\"bin\").join(sub) }) }) }).unwrap_or_else(|| { debug!(\"Failed to locate linker.\"); Command::new(\"link.exe\") }); } pub fn link_exe_cmd(sess: &Session) -> Command { let arch = &sess.target.target.arch; let (binsub, libsub, vclibsub) = match (bin_subdir(arch), lib_subdir(arch), vc_lib_subdir(arch)) { (Some(x), Some(y), Some(z)) => (x, y, z), _ => return Command::new(\"link.exe\"), }; // First we need to figure out whether the environment is already correctly // configured by vcvars. We do this by looking at the environment variable // `VCINSTALLDIR` which is always set by vcvars, and unlikely to be set // otherwise. If it is defined, then we derive the path to `link.exe` from // that and trust that everything else is configured correctly. // // If `VCINSTALLDIR` wasn't defined (or we couldn't find the linker where it // claimed it should be), then we resort to finding everything ourselves. // First we find where the latest version of MSVC is installed and what // version it is. Then based on the version we find the appropriate SDKs. // // For MSVC 14 (VS 2015) we look for the Win10 SDK and failing that we look // for the Win8.1 SDK. We also look for the Universal CRT. // // For MSVC 12 (VS 2013) we look for the Win8.1 SDK. // // For MSVC 11 (VS 2012) we look for the Win8 SDK. // // For all other versions the user has to execute the appropriate vcvars bat // file themselves to configure the environment. // // If despite our best efforts we are still unable to find MSVC then we just // blindly call `link.exe` and hope for the best. return env::var_os(\"VCINSTALLDIR\").and_then(|dir| { debug!(\"Environment already configured by user. Assuming it works.\"); let mut p = PathBuf::from(dir); p.push(\"bin\"); p.push(binsub); p.push(\"link.exe\"); if !p.is_file() { return None } Some(Command::new(p)) }).or_else(|| { get_vc_dir().and_then(|(ver, vcdir)| { debug!(\"Found VC installation directory {:?}\", vcdir); let linker = vcdir.clone().join(\"bin\").join(binsub).join(\"link.exe\"); if !linker.is_file() { return None } let mut cmd = Command::new(linker); add_lib(&mut cmd, &vcdir.join(\"lib\").join(vclibsub)); if ver == \"14.0\" { if let Some(dir) = get_ucrt_dir() { debug!(\"Found Universal CRT {:?}\", dir); add_lib(&mut cmd, &dir.join(\"ucrt\").join(libsub)); } if let Some(dir) = get_sdk10_dir() { debug!(\"Found Win10 SDK {:?}\", dir); add_lib(&mut cmd, &dir.join(\"um\").join(libsub)); } else if let Some(dir) = get_sdk81_dir() { debug!(\"Found Win8.1 SDK {:?}\", dir); add_lib(&mut cmd, &dir.join(\"um\").join(libsub)); } } else if ver == \"12.0\" { if let Some(dir) = get_sdk81_dir() { debug!(\"Found Win8.1 SDK {:?}\", dir); add_lib(&mut cmd, &dir.join(\"um\").join(libsub)); } } else { // ver == \"11.0\" if let Some(dir) = get_sdk8_dir() { debug!(\"Found Win8 SDK {:?}\", dir); add_lib(&mut cmd, &dir.join(\"um\").join(libsub)); } } Some(cmd) }) }).unwrap_or_else(|| { debug!(\"Failed to locate linker.\"); Command::new(\"link.exe\") }); } // A convenience function to make the above code simpler fn add_lib(cmd: &mut Command, lib: &Path) { let mut arg: OsString = \"/LIBPATH:\".into();"} {"_id":"q-en-rust-58dd1b7da09d10c07512506c5ba87a5213e486e8ca27f32ad2c9c65d59e7940e","text":"/// /// A common use for `format!` is concatenation and interpolation of strings. /// The same convention is used with [`print!`] and [`write!`] macros, /// depending on the intended destination of the string. /// depending on the intended destination of the string; all these macros internally use [`format_args!`]. /// /// To convert a single value to a string, use the [`to_string`] method. This /// will use the [`Display`] formatting trait. /// /// To concatenate literals into a `&'static str`, use the [`concat!`] macro. /// /// [`print!`]: ../std/macro.print.html /// [`write!`]: core::write /// [`format_args!`]: core::format_args /// [`to_string`]: crate::string::ToString /// [`Display`]: core::fmt::Display /// [`concat!`]: core::concat /// /// # Panics ///"} {"_id":"q-en-rust-58e5e2ede0f01c25b29f3c53787e4a4f93cf0751bf5e3c4f602e3a9427c8c869","text":"/// Returns an operand suitable for use until the end of the current /// scope expression. /// /// The operand returned from this function will *not be valid* after /// an ExprKind::Scope is passed, so please do *not* return it from /// functions to avoid bad miscompiles. /// The operand returned from this function will *not be valid* /// after the current enclosing `ExprKind::Scope` has ended, so /// please do *not* return it from functions to avoid bad /// miscompiles. crate fn as_local_operand(&mut self, block: BasicBlock, expr: M) -> BlockAnd> where M: Mirror<'tcx, Output = Expr<'tcx>>,"} {"_id":"q-en-rust-58e6b91ca14e0cbde7ef454bc9178655419593182718c9f3a31760d723ce0503","text":"// killed, rather than having an error bubble up and cause a panic. cargo.rustflag(\"-Zon-broken-pipe=kill\"); if builder.config.llvm_enzyme { cargo.rustflag(\"-l\").rustflag(\"Enzyme-19\"); } // We currently don't support cross-crate LTO in stage0. This also isn't hugely necessary // and may just be a time sink. if compiler.stage != 0 {"} {"_id":"q-en-rust-58ee6c5cf1e3d6e9aea9739c89201dc64d06dc700030babcdc73c153869480ea","text":"); err } infer::ReborrowUpvar(span, ref upvar_id) => { let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id); let mut err = struct_span_err!( self.tcx.sess, span, E0313, \"lifetime of borrowed pointer outlives lifetime of captured variable `{}`...\", var_name ); note_and_explain_region( self.tcx, &mut err, \"...the borrowed pointer is valid for \", sub, \"...\", None, ); note_and_explain_region( self.tcx, &mut err, &format!(\"...but `{}` is only valid for \", var_name), sup, \"\", None, ); err } infer::RelateObjectBound(span) => { let mut err = struct_span_err!( self.tcx.sess,"} {"_id":"q-en-rust-593177600d2ba67a9e05dfa75406f4bdadd50042d20e8e8eea0a1f8544466e16","text":"self.sess.gated_spans.gate(sym::const_extern_fn, lo.to(self.token.span)); } let ext = self.parse_extern()?; self.bump(); // `fn` self.expect_keyword(kw::Fn)?; let header = FnHeader { unsafety,"} {"_id":"q-en-rust-596716146d122960089ec623eaaf12f1de486f8a3d4c9622cc86a2edb19f6b5b","text":"fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) { if self.in_root && item.vis.node.is_pub() { self.attr_macros.push(ProcMacroDef { self.macros.push(ProcMacro::Def(ProcMacroDef { span: item.span, function_name: item.ident, }); def_type: ProcMacroDefType::Attr })); } else { let msg = if !self.in_root { \"functions tagged with `#[proc_macro_attribute]` must "} {"_id":"q-en-rust-5974b62b4b002026e131f2b95f61a1054370c92621d9a0ecd6ddf276e92d0bf1","text":" error: generic parameters may not be used in const operations --> $DIR/size-of-t.rs:7:30 | LL | let _arr: [u8; size_of::()]; | ^ cannot perform const operation using `T` | = note: type parameters may not be used in const expressions = help: use `#![feature(generic_const_exprs)]` to allow generic const expressions error: aborting due to previous error "} {"_id":"q-en-rust-597b7c7c7959e7a9d7b5dab423f80e795ef24a66eaa6f6ef187aa0c62e18c714","text":"RelateParamBound(a, ..) => a, RelateRegionParamBound(a) => a, Reborrow(a) => a, ReborrowUpvar(a, _) => a, DataBorrowed(_, a) => a, ReferenceOutlivesReferent(_, a) => a, CompareImplItemObligation { span, .. } => span,"} {"_id":"q-en-rust-59ad6672ed38489f6a53985b691c439c75b2c00285f1fd9146a934acd0f6115c","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":"q-en-rust-59bf31980a0cc8f2949038426644ed4f166cf41b6352e2bfa92c61aac037a37b","text":"scope 1 { debug self => _4; // in scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL let mut _5: &mut T; // in scope 1 at $DIR/issue-58867-inline-as-ref-as-mut.rs:8:5: 8:15 let mut _6: &mut T; // in scope 1 at $DIR/issue-58867-inline-as-ref-as-mut.rs:8:5: 8:15 } bb0: {"} {"_id":"q-en-rust-59c74c4a5246062343bed89d570b8f9488d746c887ac7504f774029eaee7ecb3","text":" error[E0425]: cannot find value `a` in this scope --> $DIR/issue-92100.rs:5:10 | LL | [a.., a] => {} | ^ not found in this scope error: aborting due to previous error For more information about this error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-59dbe352bd427181b839796a3e76397df42a477d58a4421ab706736e36bbb300","text":"let mut param_env = obligation.param_env; fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| { param_env = param_env.with_constness(pred.constness.and(param_env.constness())); pred.remap_constness(self.tcx(), &mut param_env); pred });"} {"_id":"q-en-rust-59e7e038d552b409be40828f42a627e0e6f162068cd0e93f127264ecb516f296","text":"// the `type_of` of the trait's associated item. If we're using the old lowering // strategy, then just reinterpret the associated type like an opaque :^) let default_ty = if self.tcx.lower_impl_trait_in_trait_to_assoc_ty() { self .tcx .type_of(alias_ty.def_id) .subst(self.tcx, alias_ty.substs) self.tcx.type_of(shifted_alias_ty.def_id).subst(self.tcx, shifted_alias_ty.substs) } else { self.tcx.mk_alias(ty::Opaque, alias_ty) self.tcx.mk_alias(ty::Opaque, shifted_alias_ty) }; self.predicates.push( ty::Binder::bind_with_vars( ty::ProjectionPredicate { projection_ty: alias_ty, term: default_ty.into(), }, ty::ProjectionPredicate { projection_ty: shifted_alias_ty, term: default_ty.into() }, self.bound_vars, ) .to_predicate(self.tcx), ); for bound in self.tcx.item_bounds(alias_ty.def_id).subst_iter(self.tcx, alias_ty.substs) // We walk the *un-shifted* alias ty, because we're tracking the de bruijn // binder depth, and if we were to walk `shifted_alias_ty` instead, we'd // have to reset `self.depth` back to `ty::INNERMOST` or something. It's // easier to just do this. for bound in self .tcx .item_bounds(unshifted_alias_ty.def_id) .subst_iter(self.tcx, unshifted_alias_ty.substs) { bound.visit_with(self); }"} {"_id":"q-en-rust-5a0283a9cd915e77db7eeaf517e43f1191f5472c6943c723e0dc5b6c515a22ec","text":"pub struct Context<'a> { waker: &'a Waker, local_waker: &'a LocalWaker, ext: ExtData<'a>, ext: AssertUnwindSafe>, // Ensure we future-proof against variance changes by forcing // the lifetime to be invariant (argument-position lifetimes // are contravariant while return-position lifetimes are"} {"_id":"q-en-rust-5a845a8b1c7da77caab6513ecfd1fc4f207e3d58e90c4a07aa70f7c5ae69181c","text":" // Test that async fn works when nested inside of // impls with lifetime parameters. // // check-pass // edition:2018 #![feature(async_await)] struct Foo<'a>(&'a ()); impl<'a> Foo<'a> { fn test() { async fn test() {} } } fn main() { } "} {"_id":"q-en-rust-5a8ff22c7a4cea3423f940f2f5e08d53b119768c2d2d19ee5276374292a3d765","text":" #![feature(const_raw_ptr_to_usize_cast)] const BAR: *mut () = ((|| 3) as fn() -> i32) as *mut (); pub const FOO: usize = unsafe { BAR as usize }; //~^ ERROR it is undefined behavior to use this value fn main() {} "} {"_id":"q-en-rust-5aa99e95beac26ee53ed6c3b2231f07d2e169220cb93d308eb8bfe1ce305d859","text":"MD->addOperand(Unit); } extern \"C\" void LLVMRustThinLTORemoveAvailableExternally(LLVMModuleRef Mod) { Module *M = unwrap(Mod); for (Function &F : M->functions()) { if (F.hasAvailableExternallyLinkage()) F.deleteBody(); } } #else extern \"C\" bool"} {"_id":"q-en-rust-5ac23efc9ec40c99a177d2906f075c4274ff159884660a55fa6fd317258a4222","text":"// Otherwise it's a span with wrong macro expansion info, which // we don't want to track anyway, since it's probably macro-internal `use` if let Some(sub_span) = self.span.sub_span_of_token(item.span, token::BinOp(token::Star)) { if let Some(sub_span) = self.span.sub_span_of_star(item.span) { if !self.span.filter_generated(item.span) { let access = access_from!(self.save_ctxt, item, item.hir_id); let span = self.span_from_span(sub_span);"} {"_id":"q-en-rust-5b10de015957b1716250b83b10ea4ba02c1979d9bdffcc9bbaf340efcbcf62e5","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":"q-en-rust-5b1d073da4ac68aeed71af3b5fa4652bd40aa4db9e251f2354758b6d5cb24ba1","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":"q-en-rust-5b35fbeafbb773889a596c4eddd2a047852f5e83930959e8d481708fd0708611","text":"\")?; for implementor in foreign { // need to get from a clean::Impl to a clean::Item so i can use render_impl if let Some(t_did) = implementor.impl_.for_.def_id() { if let Some(impl_item) = cache.impls.get(&t_did).and_then(|i| i.iter() .find(|i| i.impl_item.def_id == implementor.def_id)) { let i = &impl_item.impl_item; let impl_ = Impl { impl_item: i.clone() }; let assoc_link = AssocItemLink::GotoSource( i.def_id, &implementor.impl_.provided_trait_methods ); render_impl(w, cx, &impl_, assoc_link, RenderMode::Normal, i.stable_since(), false)?; } if let Some(i) = implementor2item(&cache, implementor) { let impl_ = Impl { impl_item: i.clone() }; let assoc_link = AssocItemLink::GotoSource( i.def_id, &implementor.impl_.provided_trait_methods ); render_impl(w, cx, &impl_, assoc_link, RenderMode::Normal, i.stable_since(), false)?; } } }"} {"_id":"q-en-rust-5b4a51ec68eccc4daaa06176f260aeb31773269095a18c1ad8f9f063d7733abc","text":" error[E0070]: invalid left-hand side of assignment --> $DIR/issue-93486.rs:3:36 | LL | vec![].last_mut().unwrap() = 3_u8; | -------------------------- ^ | | | cannot assign to this expression error: aborting due to previous error For more information about this error, try `rustc --explain E0070`. "} {"_id":"q-en-rust-5b5bd393c9584aea250df7b8f1fcf9a7ee6b5f975196c68d1aea729c0694d3f4","text":" //@ edition:2024 //@ compile-flags: -Zunstable-options #![feature(gen_blocks)] const gen fn a() {} //~^ ERROR functions cannot be both `const` and `gen` const async gen fn b() {} //~^ ERROR functions cannot be both `const` and `async gen` fn main() {} "} {"_id":"q-en-rust-5ba12c899b3b173945af6235912ea97c17a281a88cec1e0251a47963c6916ff5","text":" error[E0567]: auto traits cannot have generic parameters --> $DIR/issue-117789.rs:3:17 | LL | auto trait Trait

{} | -----^^^ help: remove the parameters | | | auto trait cannot have generic parameters error[E0658]: auto traits are experimental and possibly buggy --> $DIR/issue-117789.rs:3:1 | LL | auto trait Trait

( // Error won't happen if \"bar\" is not generic _baz: P, ) { hide_foo()(); } fn hide_foo() -> impl Fn() { // Error won't happen if \"iterate\" hasn't impl Trait or has generics foo } fn foo() { // Error won't happen if \"foo\" isn't used in \"iterate\" or has generics } "} {"_id":"q-en-rust-6c6ca59937530dd51778cd338300195bacc8240879f4976415e46e9f2ed4f689","text":" // compile-flags: -Zdrop-tracking-mir // edition:2021 use std::future::Future; trait Client { type Connecting<'a>: Future + Send where Self: 'a; fn connect(&'_ self) -> Self::Connecting<'a>; //~^ ERROR use of undeclared lifetime name `'a` } fn call_connect(c: &'_ C) -> impl '_ + Future + Send where C: Client + Send + Sync, { async move { c.connect().await } //~^ ERROR `C` does not live long enough } fn main() {} "} {"_id":"q-en-rust-6cb9a0ab903c43677755ed1f87ba326040bb2c4da90674434cbd123fb789a171","text":"font-size: 1.25rem; } /* This class only exists for users who want to draw attention to a particular element in their documentation. */ .content .docblock .warning { border-left: 2px solid var(--warning-border-color); padding: 14px; position: relative; /* The \"!important\" part is required because the rule is otherwise overruled in this CSS selector: \".docblock > :not(.more-examples-toggle):not(.example-wrap)\" */ overflow-x: visible !important; } .content .docblock .warning::before { color: var(--warning-border-color); content: \"ⓘ\"; position: absolute; left: -25px; top: 5px; font-weight: bold; font-size: 1.25rem; } a.test-arrow { visibility: hidden; position: absolute;"} {"_id":"q-en-rust-6d073c4d4d5b9812c940037dc9bba61b25156e8477a027bdcb321d2a4d992446","text":"use ext::tt::macro_parser::{parse, parse_failure_msg}; use ext::tt::quoted; use ext::tt::transcribe::transcribe; use feature_gate::{self, emit_feature_err, Features, GateIssue}; use feature_gate::Features; use parse::{Directory, ParseSess}; use parse::parser::Parser; use parse::token::{self, NtTT};"} {"_id":"q-en-rust-6d88be0f9aaec544e2ae8fd0b8a24a32e858ac340b4fa567c9298e48289c675f","text":" #![feature(staged_api)] #![stable(feature = \"libfoo\", since = \"1.0.0\")] #[unstable(feature = \"foo\", reason = \"...\", issue = \"none\")] pub fn foo() {} #[stable(feature = \"libfoo\", since = \"1.0.0\")] pub struct Foo; impl Foo { #[unstable(feature = \"foo\", reason = \"...\", issue = \"none\")] pub fn foo(&self) {} } "} {"_id":"q-en-rust-6d8d8e4624fd26ca4fbfec74ce2030667346fd22fe50f18673b52d1a527e9119","text":"span } = *self; hcx.hash_hir_item_like(attrs, |hcx| { hcx.hash_hir_item_like(attrs, is_const, |hcx| { hcx.while_hashing_spans(hash_spans, |hcx| { name.hash_stable(hcx, hasher); attrs.hash_stable(hcx, hasher);"} {"_id":"q-en-rust-6d935e7eec649de1e4a2989abae6f9f1bf7ed771e1c942382035bb1e9e7efe11","text":"was_remapped, Some(&unmapped_path)); return match self.source_file_by_stable_id(file_id) { let lrc_sf = match self.source_file_by_stable_id(file_id) { Some(lrc_sf) => lrc_sf, None => { let source_file = Lrc::new(SourceFile::new("} {"_id":"q-en-rust-6dc590bb238dc6688f3c77454540f1b487fac49935bd30c3ea52b743978011a1","text":"source_file: Lrc, override_span: Option, ) -> Self { // 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(Lrc::clone(&source_file)); let src = if let Some(src) = &source_file.src { Lrc::clone(&src) } else if let Some(src) = source_file.external_src.borrow().get_source() { Lrc::clone(&src) } else { let src = source_file.src.clone().unwrap_or_else(|| { sess.span_diagnostic .bug(&format!(\"cannot lex `source_file` without source: {}\", source_file.name)); }; }); StringReader { sess,"} {"_id":"q-en-rust-6dd5ca973f3aaa9fa3c0cc4f59386cd990f3525a0e029376e9223ef5ddd3923f","text":") => { eq_closure_binder(lb, rb) && lc == rc && la.map_or(false, CoroutineKind::is_async) == ra.map_or(false, CoroutineKind::is_async) && eq_coroutine_kind(*la, *ra) && lm == rm && eq_fn_decl(lf, rf) && eq_expr(le, re)"} {"_id":"q-en-rust-6dd7e68474ebb8199ed4c92b47421b980d052825ef3c51c694dcec6bc0a886bb","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":"q-en-rust-6e0fcc2b9429407ba9e0250c62d2f519181e425a0d0835ac6834dab4a31dfe40","text":"with_interner(|interner| interner.gensymed(self)) } pub fn is_gensymed(self) -> bool { with_interner(|interner| interner.is_gensymed(self)) } pub fn as_str(self) -> LocalInternedString { with_interner(|interner| unsafe { LocalInternedString {"} {"_id":"q-en-rust-6e3319b2e3d21deb65a1722e72a03b92b27e546720646000a9ae1d4d3ee601c7","text":"if let Res::Def(DefKind::Mod, ..) = child.res { self.resolve_doc_links_extern_inner(def_id); // Inner attribute scope } // Traits are processed in `add_extern_traits_in_scope`. // `DefKind::Trait`s are processed in `process_extern_impls`. if let Res::Def(DefKind::Mod | DefKind::Enum, ..) = child.res { self.process_module_children_or_reexports(def_id); } if let Res::Def(DefKind::Struct | DefKind::Union | DefKind::Variant, _) = child.res { let field_def_ids = Vec::from_iter( self.resolver .cstore() .associated_item_def_ids_untracked(def_id, self.sess), ); for field_def_id in field_def_ids { self.resolve_doc_links_extern_outer(field_def_id, scope_id); } } } } }"} {"_id":"q-en-rust-6e4e0d6cb3843189ae31b6aa54a601669a2dcdd05eb9e2fbff12272e2ebdca8a","text":"self.report_error_if_loan_conflicts_with_restriction( old_loan, new_loan, old_loan, new_loan) && self.report_error_if_loan_conflicts_with_restriction( new_loan, old_loan, old_loan, new_loan); new_loan, old_loan, old_loan, new_loan) } pub fn report_error_if_loan_conflicts_with_restriction(&self,"} {"_id":"q-en-rust-6e8ba981830c454aea9a40fe59a679edfbfe1d5a9091fd7d06886aa7c3cbbbd9","text":"fn eof_err(&mut self) -> PErr<'psess> { let msg = \"this file contains an unclosed delimiter\"; let mut err = self.string_reader.dcx().struct_span_err(self.token.span, msg); for &(_, sp) in &self.diag_info.open_braces { err.span_label(sp, \"unclosed delimiter\"); let unclosed_delimiter_show_limit = 5; let len = usize::min(unclosed_delimiter_show_limit, self.diag_info.open_braces.len()); for &(_, span) in &self.diag_info.open_braces[..len] { err.span_label(span, \"unclosed delimiter\"); self.diag_info.unmatched_delims.push(UnmatchedDelim { found_delim: None, found_span: self.token.span, unclosed_span: Some(sp), unclosed_span: Some(span), candidate_span: None, }); } if let Some((_, span)) = self.diag_info.open_braces.get(unclosed_delimiter_show_limit) && self.diag_info.open_braces.len() >= unclosed_delimiter_show_limit + 2 { err.span_label( *span, format!( \"another {} unclosed delimiters begin from here\", self.diag_info.open_braces.len() - unclosed_delimiter_show_limit ), ); } if let Some((delim, _)) = self.diag_info.open_braces.last() { report_suspicious_mismatch_block( &mut err,"} {"_id":"q-en-rust-6eb7e9eafc845383b76d3c984ad4e4f9e9ce4a64cb67841098f690cbc77ce821","text":" 1| |// Verify that the entry point injected by the test harness doesn't cause 2| |// weird artifacts in the coverage report (e.g. issue #10749). 3| | 4| |// compile-flags: --test 5| | 6| |#[allow(dead_code)] 7| 0|fn unused() {} 8| | 9| 1|#[test] 10| 1|fn my_test() {} "} {"_id":"q-en-rust-6f2c9484aed977ba41f034e6792d4927ae7d59f23d9cc2001b201caf71fdef79","text":"sym::coverage => self.check_coverage(hir_id, attr, span, target), sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target), sym::marker => self.check_marker(hir_id, attr, span, target), sym::target_feature => self.check_target_feature(hir_id, attr, span, target), sym::target_feature => self.check_target_feature(hir_id, attr, span, target, attrs), sym::thread_local => self.check_thread_local(attr, span, target), sym::track_caller => { self.check_track_caller(hir_id, attr.span, attrs, span, target)"} {"_id":"q-en-rust-6f3db25d9be5015200474184629990b0c4eadb4bb0ef60039cbe55d70f29fd18","text":"}; } ast::UnNot => { oprnd_t = structurally_resolved_type(fcx, oprnd.span, oprnd_t); if !(ty::type_is_integral(oprnd_t) || ty::get(oprnd_t).sty == ty::ty_bool) { oprnd_t = check_user_unop(fcx, \"!\", \"not\", tcx.lang_items.not_trait(), expr, &**oprnd, oprnd_t); if !ty::type_is_bot(oprnd_t) { oprnd_t = structurally_resolved_type(fcx, oprnd.span, oprnd_t); if !(ty::type_is_integral(oprnd_t) || ty::get(oprnd_t).sty == ty::ty_bool) { oprnd_t = check_user_unop(fcx, \"!\", \"not\", tcx.lang_items.not_trait(), expr, &**oprnd, oprnd_t); } } } ast::UnNeg => { oprnd_t = structurally_resolved_type(fcx, oprnd.span, oprnd_t); if !(ty::type_is_integral(oprnd_t) || ty::type_is_fp(oprnd_t)) { oprnd_t = check_user_unop(fcx, \"-\", \"neg\", tcx.lang_items.neg_trait(), expr, &**oprnd, oprnd_t); if !ty::type_is_bot(oprnd_t) { oprnd_t = structurally_resolved_type(fcx, oprnd.span, oprnd_t); if !(ty::type_is_integral(oprnd_t) || ty::type_is_fp(oprnd_t)) { oprnd_t = check_user_unop(fcx, \"-\", \"neg\", tcx.lang_items.neg_trait(), expr, &**oprnd, oprnd_t); } } } }"} {"_id":"q-en-rust-6f4fdaf5eec3cd9713694684f32408722362859e7474c37cbedb3cb72faa1be3","text":"#[unsafe_destructor] //~^ ERROR `#[unsafe_destructor]` does nothing anymore //~| HELP: add #![feature(unsafe_destructor)] to the crate attributes to enable // (but of couse there is no point in doing so) impl<'a> Drop for D<'a> { fn drop(&mut self) { } }"} {"_id":"q-en-rust-6f53c658c930a04bf093061882d6d2c6fb9c21148412f2691d63db637c7e5f7c","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(reflect_marker)] use std::any::TypeId; use std::marker::Reflect; use std::rc::Rc; type Fp = Rc; struct Engine; trait Component: 'static + Reflect {} impl Component for Engine {} trait Env { fn get_component_type_id(&self, type_id: TypeId) -> Option>; } impl<'a> Env+'a { fn get_component(&self) -> Option> { let x = self.get_component_type_id(TypeId::of::()); None } } trait Figment { fn init(&mut self, env: &Env); } struct MyFigment; impl Figment for MyFigment { fn init(&mut self, env: &Env) { let engine = env.get_component::(); } } fn main() {} "} {"_id":"q-en-rust-6fbb605c00850df5ba331771252b2426f8722348213f63af65ac86e0ccc7816a","text":" // issue-52240: Can turn immutable into mut with `ref mut` enum Foo { Bar(i32), } fn main() { let arr = vec!(Foo::Bar(0)); if let (Some(Foo::Bar(ref mut val)), _) = (&arr.get(0), 0) { //~^ ERROR cannot borrow field of immutable binding as mutable *val = 9001; } match arr[0] { Foo::Bar(ref s) => println!(\"{}\", s) } } "} {"_id":"q-en-rust-7007c7d47e3ca9461cee5fe758fe910bcb484e20d900b45f7e1be42988a7f192","text":"#![feature(nll)] #![feature(set_stdio)] #![feature(test)] #![feature(vec_remove_item)] #![feature(ptr_offset_from)] #![feature(crate_visibility_modifier)] #![feature(const_fn)]"} {"_id":"q-en-rust-70341beb003a719791b5d45aee5803e6745cd3a49f742b2d0576f54a57c127e1","text":"} } #[unstable(feature = \"panic_info_message\", issue = \"66745\")] #[stable(feature = \"panic_info_message\", since = \"CURRENT_RUSTC_VERSION\")] impl Display for PanicMessage<'_> { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {"} {"_id":"q-en-rust-70560c5b5103eec656439c2d9eb2cc90b404995e5d6468dab9f710f9f10e3e33","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() { (return)[0u]; //~ ERROR cannot index a value of type `!` } "} {"_id":"q-en-rust-706182f2a269a07e3cea36787d4910611901dac7436f66dddb4af67bffe9d272","text":" // Regression test for https://github.com/rust-lang/rust/issues/70673. // run-pass #![feature(thread_local)] #[thread_local] static A: &u8 = &42; fn main() { dbg!(*A); } "} {"_id":"q-en-rust-70650facd78c1e6390bab57b8c75f2bc365c8c58abfdbf638bb4b8df02a564e3","text":"} } fn eq_coroutine_kind(a: Option, b: Option) -> bool { match (a, b) { (Some(CoroutineKind::Async { .. }), Some(CoroutineKind::Async { .. })) | (Some(CoroutineKind::Gen { .. }), Some(CoroutineKind::Gen { .. })) | (Some(CoroutineKind::AsyncGen { .. }), Some(CoroutineKind::AsyncGen { .. })) | (None, None) => true, _ => false, } } pub fn eq_field(l: &ExprField, r: &ExprField) -> bool { l.is_placeholder == r.is_placeholder && eq_id(l.ident, r.ident)"} {"_id":"q-en-rust-708a02c13f45bab1b8a94ca5feff2000cd0d08624a88dbcff8d60c8d2b8b11e4","text":"} None => { debug!(?param.ident, ?param.ident.span); let deletion_span = deletion_span(); self.r.lint_buffer.buffer_lint_with_diagnostic( lint::builtin::UNUSED_LIFETIMES, param.id, param.ident.span, &format!(\"lifetime parameter `{}` never used\", param.ident), lint::BuiltinLintDiagnostics::SingleUseLifetime { param_span: param.ident.span, use_span: None, deletion_span, }, ); // the give lifetime originates from expanded code so we won't be able to remove it #104432 let lifetime_only_in_expanded_code = deletion_span.map(|sp| sp.in_derive_expansion()).unwrap_or(true); if !lifetime_only_in_expanded_code { self.r.lint_buffer.buffer_lint_with_diagnostic( lint::builtin::UNUSED_LIFETIMES, param.id, param.ident.span, &format!(\"lifetime parameter `{}` never used\", param.ident), lint::BuiltinLintDiagnostics::SingleUseLifetime { param_span: param.ident.span, use_span: None, deletion_span, }, ); } } } }"} {"_id":"q-en-rust-70cf71fbae9157d6e4fc94002419101b1d40d4e8c8b8bc5497bfd9de8a056bc4","text":"multibyte_chars, non_narrow_chars, name_hash, } }) } /// Returns the `BytePos` of the beginning of the current line."} {"_id":"q-en-rust-70dcd1f1c89e53851da25305899244afd5b1d8493a86313938c973ab90426cf9","text":"fn ilog10_u128() { ilog10_loop! { u128, 38 } } #[test] #[should_panic(expected = \"argument of integer logarithm must be positive\")] fn ilog2_of_0_panic() { let _ = 0u32.ilog2(); } #[test] #[should_panic(expected = \"argument of integer logarithm must be positive\")] fn ilog10_of_0_panic() { let _ = 0u32.ilog10(); } #[test] #[should_panic(expected = \"argument of integer logarithm must be positive\")] fn ilog3_of_0_panic() { let _ = 0u32.ilog(3); } #[test] #[should_panic(expected = \"base of integer logarithm must be at least 2\")] fn ilog0_of_1_panic() { let _ = 1u32.ilog(0); } #[test] #[should_panic(expected = \"base of integer logarithm must be at least 2\")] fn ilog1_of_1_panic() { let _ = 1u32.ilog(1); } "} {"_id":"q-en-rust-70f6cc167f71cca7f8186a7163f7697c6b5a3928a02efa6ddce61938d2e4b6ef","text":"| LL | MyEnum::Struct => \"\", | ^^^^^^^^^^^^^^ not a unit struct, unit variant or constant | help: the struct variant's field is being ignored | LL | MyEnum::Struct { s: _ } => \"\", | ++++++++ error: aborting due to 2 previous errors"} {"_id":"q-en-rust-70fa4043d1bf7c29773cfade4cd063b2d63c3536fe130ed58289b87fbc4d100d","text":" error[E0308]: mismatched types --> $DIR/mut-mut-wont-coerce.rs:36:14 | LL | make_foo(&mut &mut *result); | -------- ^^^^^^^^^^^^^^^^^ expected `*mut *mut Foo`, found `&mut &mut Foo` | | | arguments to this function are incorrect | = note: expected raw pointer `*mut *mut Foo` found mutable reference `&mut &mut Foo` note: function defined here --> $DIR/mut-mut-wont-coerce.rs:30:4 | LL | fn make_foo(_: *mut *mut Foo) { | ^^^^^^^^ ---------------- error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-70ff2e2c73913345bbd87ce0af8864966a21900fae39ebca4025dbb82440a9e1","text":" warning: unused variable: `props_2` --> $DIR/issue-87987.rs:11:9 | LL | let props_2 = Props { | ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_props_2` | = note: `#[warn(unused_variables)]` on by default warning: field is never read: `field_1` --> $DIR/issue-87987.rs:5:5 | LL | field_1: u32, | ^^^^^^^^^^^^ | = note: `#[warn(dead_code)]` on by default warning: field is never read: `field_2` --> $DIR/issue-87987.rs:6:5 | LL | field_2: u32, | ^^^^^^^^^^^^ warning: 3 warnings emitted "} {"_id":"q-en-rust-71150c2af545813fe8cfeb3ea319a3a30f6e850d59ef6dc39a672c134bb0cb11","text":"// of llvm-config, not the target that we're attempting to link. let mut cmd = Command::new(&llvm_config); cmd.arg(\"--libs\"); // Force static linking with \"--link-static\" if available. let mut version_cmd = Command::new(&llvm_config); version_cmd.arg(\"--version\"); let version_output = output(&mut version_cmd); let mut parts = version_output.split('.'); if let (Some(major), Some(minor)) = (parts.next().and_then(|s| s.parse::().ok()), parts.next().and_then(|s| s.parse::().ok())) { if major > 3 || (major == 3 && minor >= 8) { cmd.arg(\"--link-static\"); } } if !is_crossed { cmd.arg(\"--system-libs\"); }"} {"_id":"q-en-rust-7117f77926ccf00bcaa9cf291e1f9b510431d111ad32d92d6e61af29b863d8e2","text":" error: field `1` is never read --> $DIR/tuple-struct-field.rs:8:26 error: fields `1`, `2`, `3`, and `4` are never read --> $DIR/tuple-struct-field.rs:8:28 | LL | struct SingleUnused(i32, [u8; LEN], String); | ------------ ^^^^^^^^^ LL | struct UnusedAtTheEnd(i32, f32, [u8; LEN], String, u8); | -------------- ^^^ ^^^^^^^^^ ^^^^^^ ^^ | | | field in this struct | fields in this struct | = help: consider removing these fields note: the lint level is defined here --> $DIR/tuple-struct-field.rs:1:9 | LL | #![deny(dead_code)] | ^^^^^^^^^ help: consider changing the field to be of unit type to suppress this warning while preserving the field numbering, or remove the field error: field `0` is never read --> $DIR/tuple-struct-field.rs:13:27 | LL | struct UnusedJustOneField(i32); | ------------------ ^^^ | | | field in this struct | LL | struct SingleUnused(i32, (), String); | ~~ = help: consider removing this field error: fields `0`, `1`, `2`, and `3` are never read --> $DIR/tuple-struct-field.rs:13:23 error: fields `1`, `2`, and `4` are never read --> $DIR/tuple-struct-field.rs:18:31 | LL | struct MultipleUnused(i32, f32, String, u8); | -------------- ^^^ ^^^ ^^^^^^ ^^ LL | struct UnusedInTheMiddle(i32, f32, String, u8, u32); | ----------------- ^^^ ^^^^^^ ^^^ | | | fields in this struct | help: consider changing the fields to be of unit type to suppress this warning while preserving the field numbering, or remove the fields | LL | struct MultipleUnused((), (), (), ()); | ~~ ~~ ~~ ~~ LL | struct UnusedInTheMiddle(i32, (), (), u8, ()); | ~~ ~~ ~~ error: aborting due to 2 previous errors error: aborting due to 3 previous errors "} {"_id":"q-en-rust-711a9943aef01c2732f695a6f265393c0a5557a8dbf2fbeecad157c6aa9c7d5b","text":"} } return ty::ExistentialBounds { region_bound: region_bound, builtin_bounds: builtin_bounds, projection_bounds: projection_bounds }; ty::ExistentialBounds::new( region_bound, builtin_bounds, projection_bounds) } fn parse_builtin_bounds(&mut self) -> ty::BuiltinBounds {"} {"_id":"q-en-rust-714082cda1feb67bd7cc15fe67457072269fd794fe19546b50a3bca277a176db","text":"use crate::io::{self, IoSlice, IoSliceMut}; use crate::mem; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sys::fd::FileDesc; use crate::sys::{cvt, cvt_r}; use libc::c_int; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes ////////////////////////////////////////////////////////////////////////////////"} {"_id":"q-en-rust-7142e286eac356ee7dd1423ffe1c41ea1194309cdb42419bd1819856d88c8404","text":"/// Basic usage: /// /// ``` /// #![feature(nonzero_leading_trailing_zeros)] #[doc = concat!(\"let n = std::num::\", stringify!($Ty), \"::new(\", stringify!($LeadingTestExpr), \").unwrap();\")] /// /// assert_eq!(n.leading_zeros(), 0); /// ``` #[unstable(feature = \"nonzero_leading_trailing_zeros\", issue = \"79143\")] #[rustc_const_unstable(feature = \"nonzero_leading_trailing_zeros\", issue = \"79143\")] #[stable(feature = \"nonzero_leading_trailing_zeros\", since = \"1.53.0\")] #[rustc_const_stable(feature = \"nonzero_leading_trailing_zeros\", since = \"1.53.0\")] #[inline] pub const fn leading_zeros(self) -> u32 { // SAFETY: since `self` can not be zero it is safe to call ctlz_nonzero"} {"_id":"q-en-rust-714d852727aaa9c0601d4c6dd79a683706a219f36e47d85fe3c794936d3a39c3","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":"q-en-rust-7174154ca9b0d924f7b2372f7c562aea5e5eb130cb7b05740837ce69534fabed","text":"// `dyn T:` is lowered to `dyn T: ReEmpty` - check that we don't ICE in NLL for // the unexpected region. // build-pass (FIXME(62277): could be check-pass?) // check-pass trait T {} fn f() where dyn T: {} fn main() {} fn main() { f(); } "} {"_id":"q-en-rust-7179a616dbc6da760891ba98b8dc0d92945cc0fee14bfbc12e7f08f628331e7b","text":"const ENTRY_LIMIT: usize = 900; // FIXME: The following limits should be reduced eventually. const ISSUES_ENTRY_LIMIT: usize = 1854; const ISSUES_ENTRY_LIMIT: usize = 1852; const ROOT_ENTRY_LIMIT: usize = 867; const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &["} {"_id":"q-en-rust-71a7e003ac94192610c7dcd1ef1485d46c458eaa38c268ec3d51649016c8ee6b","text":" -include ../tools.mk all: $(HOST_RPATH_ENV) $(RUSTDOC) -w html -o $(TMPDIR)/doc foo.rs $(HTMLDOCCK) $(TMPDIR)/doc foo.rs $(HTMLDOCCK) $(TMPDIR)/doc qux/mod.rs "} {"_id":"q-en-rust-71bb8e7fd468615db71f5adc2601e32c4998573f30e902194ec884ddd74e3ea8","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":"q-en-rust-71d5e9f18a13a0bdeca500c930d858531f82b11bbd821ae51db4a846cb3477a4","text":"use astconv::AstConv; use check::{self, FnCtxt}; use middle::ty::{self, Ty}; use middle::ty::{self, Ty, ToPolyTraitRef, AsPredicate}; use middle::def; use middle::lang_items::FnOnceTraitLangItem; use middle::subst::Substs; use middle::traits::{Obligation, SelectionContext}; use metadata::{csearch, cstore, decoder}; use syntax::{ast, ast_util};"} {"_id":"q-en-rust-72402dba4b0653eec1c2616c710fcb7340de0db8b93eacfb50de9e0514e2d07d","text":") .lines() .map(|s| s.trim().to_owned()) .filter(|f| Path::new(f).extension().map_or(false, |ext| ext == \"rs\")) .collect(), ) }"} {"_id":"q-en-rust-7257c8c01b2a07aa1397abf233348234ee0dd86b128a14b5211d5a92ac252811","text":" // check-pass // edition:2021 // compile-flags: -Zunstable-options fn main() { let _: u16 = 123i32.try_into().unwrap(); } "} {"_id":"q-en-rust-7261a86a90ef2e7688462d6ebdc8d7db737499016aa28be4cac42149ee7a8b38","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":"q-en-rust-729bb6c7e0617b1543eeba1c2162f269d1802990300aa2f73f1d6fc5ad1c2534","text":"use std::alloc::{Global, Alloc, Layout, System}; /// Issue #45955. /// Issue #45955 and #62251. #[test] fn alloc_system_overaligned_request() { check_overalign_requests(System)"} {"_id":"q-en-rust-72e60209aeb8c12608cd98adfeb26a27dab5fa303fda88fc621f36621fde0452","text":"discr_index, .. } => { if !dest.layout.ty.variant_range(*self.tcx).unwrap().contains(&variant_index) { throw_ub!(InvalidDiscriminant(variant_scalar)); } // No need to validate that the discriminant here because the // `TyLayout::for_variant()` call earlier already checks the variant is valid. let discr_val = dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val;"} {"_id":"q-en-rust-730d47c795d3de7f929ef5aa77976e144545126877f0a9178ed588fd39ed9129","text":"if create_issue_for_status is not None: try: issue( tool, create_issue_for_status, MAINTAINERS.get(tool, ''), relevant_pr_number, relevant_pr_user, LABELS.get(tool, ''), tool, create_issue_for_status, MAINTAINERS.get(tool, ()), relevant_pr_number, relevant_pr_user, LABELS.get(tool, []), github_token, ) except urllib2.HTTPError as e: except HTTPError as e: # network errors will simply end up not creating an issue, but that's better # than failing the entire build job print(\"HTTPError when creating issue for status regression: {0}n{1}\" print(\"HTTPError when creating issue for status regression: {0}n{1!r}\" .format(e, e.read())) except IOError as e: print(\"I/O error when creating issue for status regression: {0}\".format(e))"} {"_id":"q-en-rust-733397247349fdae9ae1903d8f51362f67d4038c066cabd3f017a5cf4f549137","text":"// stripping away any starting or ending parenthesis characters—hence this // test of the JSON error format. #![warn(unused_parens)] #![deny(unused_parens)] #![allow(unreachable_code)] fn main() { let _b = false; if (_b) { if (_b) { //~ ERROR unnecessary parentheses println!(\"hello\"); }"} {"_id":"q-en-rust-7339a1458a85e363317f0717ff7b234d8ec8d8af67ec029733189eb7a33b20a7","text":"]).decode(sys.getdefaultencoding()).strip() llvm_sha = subprocess.check_output([ \"git\", \"rev-list\", \"--author=bors@rust-lang.org\", \"-n1\", \"--merges\", \"--first-parent\", \"HEAD\", \"--first-parent\", \"HEAD\", \"--\", \"{}/src/llvm-project\".format(top_level), \"{}/src/bootstrap/download-ci-llvm-stamp\".format(top_level),"} {"_id":"q-en-rust-7345ae7247e21ee084b7814f9cd08cfa3a837b4ae7bc9a84c1a27b62d0bd4608","text":"ItemKind::Mod(..) if i.ident == keywords::Invalid.ident() => { return visit::walk_item(self, i); } ItemKind::Fn(_, FnHeader { asyncness: IsAsync::Async { closure_id, return_impl_trait_id, }, .. }, ..) => { ItemKind::Fn( ref decl, ref header @ FnHeader { asyncness: IsAsync::Async { .. }, .. }, ref generics, ref body, ) => { return self.visit_async_fn( i.id, closure_id, return_impl_trait_id, i.ident.name, i.span, |this| visit::walk_item(this, i) header, generics, decl, body, ) } ItemKind::Mod(..) => DefPathData::Module(i.ident.as_interned_str()),"} {"_id":"q-en-rust-737222cc7f70d361323c635fade2aca9e525d2f730868402ffccd3f7af1c7cf3","text":"), .. }) => { // We have a situation like `while Some(0) = value.get(0) {`, where `while let` // was more likely intended. err.span_suggestion_verbose( expr.span.shrink_to_lo(), \"you might have meant to use pattern destructuring\", \"let \".to_string(), Applicability::MachineApplicable, ); // Check if our lhs is a child of the condition of a while loop let expr_is_ancestor = std::iter::successors(Some(lhs.hir_id), |id| { self.tcx.hir().find_parent_node(*id) }) .take_while(|id| *id != parent) .any(|id| id == expr.hir_id); // if it is, then we have a situation like `while Some(0) = value.get(0) {`, // where `while let` was more likely intended. if expr_is_ancestor { err.span_suggestion_verbose( expr.span.shrink_to_lo(), \"you might have meant to use pattern destructuring\", \"let \".to_string(), Applicability::MachineApplicable, ); } break; } hir::Node::Item(_)"} {"_id":"q-en-rust-73733b776582457c8328379790e9c82ab87db42c399f7013456a8b90853edb62","text":" // Checks that there is a suggestion for simple tuple index access expression (used where an // identifier is expected in a format arg) to use positional arg instead. // Issue: . //@ run-rustfix fn main() { let x = (1,); println!(\"{0}\", x.0); //~^ ERROR invalid format string } "} {"_id":"q-en-rust-7412e64d55a581b84516974fc8c91468fd6488f1b0e350b0074bac31bf1f39c8","text":"impl HashStable for InferTy { fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { use InferTy::*; discriminant(self).hash_stable(ctx, hasher); match self { TyVar(v) => v.as_u32().hash_stable(ctx, hasher), IntVar(v) => v.index.hash_stable(ctx, hasher),"} {"_id":"q-en-rust-742962301088ed6657b323b3a57077a1040d263d7712c64670c5fd845881072d","text":"{ let result = local_s .try_with(|s| { if let Ok(mut borrowed) = s.try_borrow_mut() { if let Some(w) = borrowed.as_mut() { return w.write_fmt(args); } // Note that we completely remove a local sink to write to in case // our printing recursively panics/prints, so the recursive // panic/print goes to the global sink instead of our local sink. let prev = s.borrow_mut().take(); if let Some(mut w) = prev { let result = w.write_fmt(args); *s.borrow_mut() = Some(w); return result; } global_s().write_fmt(args) })"} {"_id":"q-en-rust-7436cc769b575f4abfe94d054e1a0ae228cf05af6637b50a3c3fef9d6fd7d328","text":"_ => tcx.def_span(item), }; try_visit!(visitor.visit(span, tcx.type_of(item).instantiate_identity())); for (pred, span) in tcx.predicates_of(item).instantiate_identity(tcx) { for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { try_visit!(visitor.visit(span, pred)); } } DefKind::TraitAlias | DefKind::Trait => { for (pred, span) in tcx.predicates_of(item).instantiate_identity(tcx) { for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { try_visit!(visitor.visit(span, pred)); } }"} {"_id":"q-en-rust-743c7f5fe2b93c7a861cfbe6b96c149137ea65f2ca0ecd55e2c07dc5fee34c90","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":"q-en-rust-747049d5720908cb0edf0c431a0faa67377326335192b601dcce3468ba3528d0","text":"pub fn to_u16s>(s: S) -> crate::io::Result> { fn inner(s: &OsStr) -> crate::io::Result> { let mut maybe_result: Vec = s.encode_wide().collect(); // Most paths are ASCII, so reserve capacity for as much as there are bytes // in the OsStr plus one for the null-terminating character. We are not // wasting bytes here as paths created by this function are primarily used // in an ephemeral fashion. let mut maybe_result = Vec::with_capacity(s.len() + 1); maybe_result.extend(s.encode_wide()); if unrolled_find_u16s(0, &maybe_result).is_some() { return Err(crate::io::const_io_error!( ErrorKind::InvalidInput,"} {"_id":"q-en-rust-74cc19bbed6c2abc3a40c67ff4f6ecf223fd60249812040b058ac6b895bc7bfe","text":"return self.parse_if_expr(); } if try!(self.eat_keyword(keywords::For) ){ return self.parse_for_expr(None); let lo = self.last_span.lo; return self.parse_for_expr(None, lo); } if try!(self.eat_keyword(keywords::While) ){ return self.parse_while_expr(None); let lo = self.last_span.lo; return self.parse_while_expr(None, lo); } if self.token.is_lifetime() { let lifetime = self.get_lifetime(); let lo = self.span.lo; try!(self.bump()); try!(self.expect(&token::Colon)); if try!(self.eat_keyword(keywords::While) ){ return self.parse_while_expr(Some(lifetime)) return self.parse_while_expr(Some(lifetime), lo) } if try!(self.eat_keyword(keywords::For) ){ return self.parse_for_expr(Some(lifetime)) return self.parse_for_expr(Some(lifetime), lo) } if try!(self.eat_keyword(keywords::Loop) ){ return self.parse_loop_expr(Some(lifetime)) return self.parse_loop_expr(Some(lifetime), lo) } return Err(self.fatal(\"expected `while`, `for`, or `loop` after a label\")) } if try!(self.eat_keyword(keywords::Loop) ){ return self.parse_loop_expr(None); let lo = self.last_span.lo; return self.parse_loop_expr(None, lo); } if try!(self.eat_keyword(keywords::Continue) ){ let lo = self.span.lo;"} {"_id":"q-en-rust-7505da0de157bff225ae655882ccc805ac7ebe461dca5e2b292838b302114841","text":"Abi::Aggregate { sized: true } }; align = align.max(niche_align); size = size.abi_align(align); return Ok(tcx.intern_layout(LayoutDetails { variants: Variants::NicheFilling {"} {"_id":"q-en-rust-7563e493063f73ea2ecff2f5477c886cb4176691b695822f98b0026b6682eed3","text":"| ^ help: remove this semicolon error[E0601]: `main` function not found in crate `issue_49040` --> $DIR/issue-49040.rs:1:29 --> $DIR/issue-49040.rs:2:12 | LL | #![allow(unused_variables)]; | ^ consider adding a `main` function to `$DIR/issue-49040.rs` LL | fn foo() {} | ^ consider adding a `main` function to `$DIR/issue-49040.rs` error: aborting due to 2 previous errors"} {"_id":"q-en-rust-75f6bb4b20d820d91908fd09d063499c7b72fee8033ae29c820fa87335d96ebb","text":"/// # Examples /// /// ``` /// #![feature(mutex_unpoison)] /// /// use std::sync::{Arc, Mutex}; /// use std::thread; ///"} {"_id":"q-en-rust-75fb882892193dba0d552e95c5fc4bfba955b2d86a24014db11584e7e32f32bd","text":" //! This test checks that types of up to 128 bits are returned by-value instead of via out-pointer. // compile-flags: -C no-prepopulate-passes -O // only-x86_64 #![crate_type = \"lib\"] pub struct S { a: u64, b: u32, c: u32, } // CHECK: define i128 @modify(%S* noalias nocapture dereferenceable(16) %s) #[no_mangle] pub fn modify(s: S) -> S { S { a: s.a + s.a, b: s.b + s.b, c: s.c + s.c } } #[repr(packed)] pub struct TooBig { a: u64, b: u32, c: u32, d: u8, } // CHECK: define void @m_big(%TooBig* [[ATTRS:.*sret.*]], %TooBig* [[ATTRS2:.*]] %s) #[no_mangle] pub fn m_big(s: TooBig) -> TooBig { TooBig { a: s.a + s.a, b: s.b + s.b, c: s.c + s.c, d: s.d + s.d } } "} {"_id":"q-en-rust-7635a3c65c62082b4201cb568f186307e0bf19ff92e10bafebc26035b129cc96","text":"} } } self.sess.abort_if_errors(); None } } } fn add_existing_rlib(&self, libs: &mut [Library], path: &Path, file: &str) -> bool { let (prefix, suffix) = self.dylibname(); let file = file.slice_from(3); // chop off 'lib' let file = file.slice_to(file.len() - 5); // chop off '.rlib' let file = format!(\"{}{}{}\", prefix, file, suffix); for lib in libs.mut_iter() { match lib.dylib { Some(ref p) if p.filename_str() == Some(file.as_slice()) => { assert!(lib.rlib.is_none()); // FIXME: legit compiler error lib.rlib = Some(path.clone()); return true; } Some(..) | None => {} } // Attempts to match the requested version of a library against the file // specified. The prefix/suffix are specified (disambiguates between // rlib/dylib). // // The return value is `None` if `file` doesn't look like a rust-generated // library, or if a specific version was requested and it doens't match the // apparent file's version. // // If everything checks out, then `Some(hash)` is returned where `hash` is // the listed hash in the filename itself. fn try_match(&self, file: &str, prefix: &str, suffix: &str) -> Option<~str>{ let middle = file.slice(prefix.len(), file.len() - suffix.len()); debug!(\"matching -- {}, middle: {}\", file, middle); let mut parts = middle.splitn('-', 1); let hash = match parts.next() { Some(h) => h, None => return None }; debug!(\"matching -- {}, hash: {}\", file, hash); let vers = match parts.next() { Some(v) => v, None => return None }; debug!(\"matching -- {}, vers: {}\", file, vers); if !self.version.is_empty() && self.version.as_slice() != vers { return None } debug!(\"matching -- {}, vers ok (requested {})\", file, self.version); // hashes in filenames are prefixes of the \"true hash\" if self.hash.is_empty() || self.hash.starts_with(hash) { debug!(\"matching -- {}, hash ok (requested {})\", file, self.hash); Some(hash.to_owned()) } else { None } return false; } fn add_existing_dylib(&self, libs: &mut [Library], path: &Path, file: &str) -> bool { let (prefix, suffix) = self.dylibname(); let file = file.slice_from(prefix.len()); let file = file.slice_to(file.len() - suffix.len()); let file = format!(\"lib{}.rlib\", file); // 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. // // With only one library in the set, this function will extract it, and then // read the metadata from it if `*slot` is `None`. If the metadata couldn't // be read, it is assumed that the file isn't a valid rust library (no // errors are emitted). // // FIXME(#10786): for an optimization, we only read one of the library's // metadata sections. In theory we should read both, but // reading dylib metadata is quite slow. fn extract_one(&self, m: HashSet, flavor: &str, slot: &mut Option) -> Option { if m.len() == 0 { return None } if m.len() > 1 { self.sess.span_err(self.span, format!(\"multiple {} candidates for `{}` found\", flavor, self.name)); for (i, path) in m.iter().enumerate() { self.sess.span_note(self.span, format!(r\"candidate #{}: {}\", i + 1, path.display())); } return None } for lib in libs.mut_iter() { match lib.rlib { Some(ref p) if p.filename_str() == Some(file.as_slice()) => { assert!(lib.dylib.is_none()); // FIXME: legit compiler error lib.dylib = Some(path.clone()); return true; let lib = m.move_iter().next().unwrap(); if slot.is_none() { info!(\"{} reading meatadata from: {}\", flavor, lib.display()); match get_metadata_section(self.os, &lib) { Some(blob) => { if crate_matches(blob.as_slice(), self.name, self.version, self.hash) { *slot = Some(blob); } else { info!(\"metadata mismatch\"); return None; } } None => { info!(\"no metadata found\"); return None } Some(..) | None => {} } } return false; return Some(lib); } // Returns the corresponding (prefix, suffix) that files need to have for"} {"_id":"q-en-rust-7636dbf25d848660fd79c73fce1bfc28e461837b4038e447569f38c0eaccfbec","text":"} } /// External iterator for a string's characters and their byte offsets. /// Use with the `std::iter` module. /// Iterator for a string's characters and their byte offsets. #[derive(Clone)] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub struct CharIndices<'a> {"} {"_id":"q-en-rust-76436d5f2c4b12772466f553af93009476c1d1ca142d83491a61d91c269a79af","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":"q-en-rust-765b49dcb58ce25b60fe85e86bd27b8268a1d71d65036da7bee10d7d8f287459","text":"// FIXME (#2397): At some point we want to rpath our guesses as to // where extern libraries might live, based on the // addl_lib_search_paths args.push_all(rpath::get_rpath_flags(sess, out_filename)); if !sess.opts.no_rpath { args.push_all(rpath::get_rpath_flags(sess, out_filename)); } // Finally add all the linker arguments provided on the command line along // with any #[link_args] attributes found inside the crate"} {"_id":"q-en-rust-7681bf4fb052e0f275cf7e490dc40ccea88b53451932a9a098c2a69814bf1f80","text":"impl<'tcx> GATSubstCollector<'tcx> { fn visit>( tcx: TyCtxt<'tcx>, gat: DefId, t: T, ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) { let mut visitor = GATSubstCollector { gat, regions: FxHashSet::default(), types: FxHashSet::default() }; let mut visitor = GATSubstCollector { tcx, gat, regions: FxHashSet::default(), types: FxHashSet::default(), }; t.visit_with(&mut visitor); (visitor.regions, visitor.types) }"} {"_id":"q-en-rust-7696d67b22dab9b9e012e7baa6930df4ef882783dacf52b80b4fa4f3569ba258","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":"q-en-rust-7699d0ef8d08eceac88489674326ea40115e9d0df9359d24686c2b7ad302edc0","text":"fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pat<'tcx> { let mut ty = self.typeck_results.node_type(pat.hir_id); if let ty::Error(_) = ty.kind { // Avoid ICEs (e.g., #50577 and #50585). return Pat { span: pat.span, ty, kind: Box::new(PatKind::Wild) }; } let kind = match pat.kind { hir::PatKind::Wild => PatKind::Wild,"} {"_id":"q-en-rust-76a29033d42f6ed3da9efa47a1674c37abd41176438e6ee55bd16989edd5f596","text":"to `int`s, though. We can make it usable by any type, but we haven't quite gotten there yet! You can have any number of values in an enum: You can also have any number of values in an enum: ```{rust} enum OptionalColor {"} {"_id":"q-en-rust-773963bb14fb1a9f01f1def6cecaeefc572075ddff7ff67006eee9ce437d78bb","text":"// Regression test for issue #4935 fn foo(a: usize) {} fn main() { foo(5, 6) } //~ ERROR this function takes 1 parameter but 2 parameters were supplied //~^ NOTE the following parameter type was expected fn main() { foo(5, 6) } //~^ ERROR this function takes 1 parameter but 2 parameters were supplied //~| NOTE the following parameter type was expected //~| NOTE expected 1 parameter "} {"_id":"q-en-rust-77734f58fb8629179652a8a9d0a77c01c314c1309a90a82c4ac9425542a88265","text":" // check-pass // This is currently stable behavior, which was almost accidentally made an // error in #102161 since there is no test exercising it. I am not sure if // this _should_ be the desired behavior, but at least we should know if it // changes. fn main() {} trait Foo { fn fn_with_type_named_same_as_local_in_param(b: i32, b: i32); } "} {"_id":"q-en-rust-77b0dfdbb3c3b2b7a2e77edb0bb2ff9f909abc84280182cd2b745171b4a237bd","text":" error: Unexpected `@` in struct pattern --> $DIR/at-in-struct-patterns.rs:8:15 | LL | let Foo { var @ field1, .. } = foo; | --- ^^^^^ | | | while parsing the fields for this pattern | = note: struct patterns use `field: pattern` syntax to bind to fields = help: consider replacing `new_name @ field_name` with `field_name: new_name` if that is what you intended error: `@ ..` is not supported in struct patterns --> $DIR/at-in-struct-patterns.rs:10:26 | LL | let Foo { field1: _, bar @ .. } = foo; | --- ^^^^^^^^ | | | while parsing the fields for this pattern | help: bind to each field separately or, if you don't need them, just remove `bar @` | LL - let Foo { field1: _, bar @ .. } = foo; LL + let Foo { field1: _, .. } = foo; | error: `@ ..` is not supported in struct patterns --> $DIR/at-in-struct-patterns.rs:11:15 | LL | let Foo { bar @ .. } = foo; | --- ^^^^^^^^ | | | while parsing the fields for this pattern | help: bind to each field separately or, if you don't need them, just remove `bar @` | LL - let Foo { bar @ .. } = foo; LL + let Foo { .. } = foo; | error: expected identifier, found `@` --> $DIR/at-in-struct-patterns.rs:12:15 | LL | let Foo { @ } = foo; | --- ^ expected identifier | | | while parsing the fields for this pattern error: expected identifier, found `@` --> $DIR/at-in-struct-patterns.rs:13:15 | LL | let Foo { @ .. } = foo; | --- ^ expected identifier | | | while parsing the fields for this pattern error[E0425]: cannot find value `var` in this scope --> $DIR/at-in-struct-patterns.rs:9:10 | LL | dbg!(var); | ^^^ not found in this scope | help: consider importing this function | LL + use std::env::var; | error: aborting due to 6 previous errors For more information about this error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-77ef62c2e4941f6fb7381e17978c92e4c773fc42ca45bb7d94a0b22dbdb90799","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: expected item, found `parse_error` include!(\"../auxiliary/issue-21146-inc.rs\"); fn main() {} "} {"_id":"q-en-rust-77fa73c798a34b119dddaeb0c05598a4c49ebe3b59d069f043de43bc9d5f3d2f","text":"this.pat_bindings(&**pat, |this, ln, var, sp, id| { this.warn_about_unused(sp, id, ln, var); }); visit::walk_expr(this, expr); } // no correctness conditions related to liveness"} {"_id":"q-en-rust-78029f67e4ec5ec95cfe1348900f93a91bef04ef20891cd09379af4418e4476e","text":"impl Foo for u32 { fn len(&self) -> u32 { *self } //~^ ERROR incompatible type for trait: expected unsafe fn, found normal fn //~^ ERROR method `len` has an incompatible type for trait //~| expected unsafe fn, //~| found normal fn } fn main() { }"} {"_id":"q-en-rust-7821be39a343fa3c08bdaa608432591acfc7e06cc297e9090b7cca558c70730e","text":"/// impl Gadget { /// /// Construct a reference counted Gadget. /// fn new() -> Rc { /// Rc::new_cyclic(|me| Gadget { me: me.clone() }) /// // `me` is a `Weak` pointing at the new allocation of the /// // `Rc` we're constructing. /// Rc::new_cyclic(|me| { /// // Create the actual struct here. /// Gadget { me: me.clone() } /// }) /// } /// /// /// Return a reference counted pointer to Self."} {"_id":"q-en-rust-7823a58f6882da886a6b47244378918f145f518bf7e16647e2d96de5818b41fc","text":"} } inline(cx, llfn, codegen_fn_attrs.inline.clone(), instance.def.requires_inline(cx.tcx)); let inline_attr = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) { InlineAttr::Never } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) { InlineAttr::Hint } else { codegen_fn_attrs.inline }; inline(cx, llfn, inline_attr); // The `uwtable` attribute according to LLVM is: //"} {"_id":"q-en-rust-7856b0cd31d54ab66476b268c816b379075c2269c282d5c5deaf8c9c8c95808f","text":"expr_is_from_block, ); } MustUsePath::Pinned(path) => { let descr_pre = &format!(\"{descr_pre}pinned \"); emit_must_use_untranslated( cx, path, descr_pre, descr_post, plural_len, true, expr_is_from_block, ); } MustUsePath::Opaque(path) => { let descr_pre = &format!(\"{descr_pre}implementer{plural_suffix} of \"); emit_must_use_untranslated("} {"_id":"q-en-rust-785a5b9a2beb8d0f94158954d847f9d5b143834defc1de5a5cbd72c20e451944","text":"self.output); } } mir::Rvalue::Box(_) => { mir::Rvalue::Box(..) => { let exchange_malloc_fn_def_id = self.scx .tcx()"} {"_id":"q-en-rust-788dc459a6f284e3a1d37e203985104745a54bc1339dab5cf5854cf70fe75cc1","text":"error[E0207]: the type parameter `U` is not constrained by the impl trait, self type, or predicates --> $DIR/impl-unused-tps.rs:13:8 --> $DIR/impl-unused-tps.rs:15:8 | LL | impl Foo for [isize;1] { | ^ unconstrained type parameter error[E0207]: the type parameter `U` is not constrained by the impl trait, self type, or predicates --> $DIR/impl-unused-tps.rs:30:8 --> $DIR/impl-unused-tps.rs:31:8 | LL | impl Bar for T { | ^ unconstrained type parameter error[E0207]: the type parameter `U` is not constrained by the impl trait, self type, or predicates --> $DIR/impl-unused-tps.rs:38:8 --> $DIR/impl-unused-tps.rs:39:8 | LL | impl Bar for T | ^ unconstrained type parameter error[E0207]: the type parameter `U` is not constrained by the impl trait, self type, or predicates --> $DIR/impl-unused-tps.rs:46:8 --> $DIR/impl-unused-tps.rs:47:8 | LL | impl Foo for T | ^ unconstrained type parameter error[E0207]: the type parameter `V` is not constrained by the impl trait, self type, or predicates --> $DIR/impl-unused-tps.rs:46:10 --> $DIR/impl-unused-tps.rs:47:10 | LL | impl Foo for T | ^ unconstrained type parameter error: aborting due to 5 previous errors error[E0119]: conflicting implementations of trait `Foo<_>` for type `[isize; 0]` --> $DIR/impl-unused-tps.rs:27:1 | LL | impl Foo for [isize;0] { | ---------------------------- first implementation here ... LL | impl Foo for U { | ^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `[isize; 0]` error[E0275]: overflow evaluating the requirement `([isize; 0], _): Sized` | = help: consider increasing the recursion limit by adding a `#![recursion_limit = \"256\"]` attribute to your crate (`impl_unused_tps`) note: required for `([isize; 0], _)` to implement `Bar` --> $DIR/impl-unused-tps.rs:31:11 | LL | impl Bar for T { | - ^^^ ^ | | | unsatisfied trait bound introduced here = note: 126 redundant requirements hidden = note: required for `([isize; 0], _)` to implement `Bar` error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0207`. Some errors have detailed explanations: E0119, E0207, E0275. For more information about an error, try `rustc --explain E0119`. "} {"_id":"q-en-rust-7899fc9485030901dc4f6faffe8fe65da1cd4e20dd3654594fbbe028fddcbab1","text":"sig: ty::PolyFnSig<'tcx>, tuple_arguments: TupleArgumentsFlag, ) -> ty::Binder<'tcx, (ty::TraitRef<'tcx>, Ty<'tcx>)> { assert!(!self_ty.has_escaping_bound_vars()); let arguments_tuple = match tuple_arguments { TupleArgumentsFlag::No => sig.skip_binder().inputs()[0], TupleArgumentsFlag::Yes => tcx.intern_tup(sig.skip_binder().inputs()), }; debug_assert!(!self_ty.has_escaping_bound_vars()); let trait_ref = tcx.mk_trait_ref(fn_trait_def_id, [self_ty, arguments_tuple]); sig.map_bound(|sig| (trait_ref, sig.output())) }"} {"_id":"q-en-rust-78ac75d6b195115976117471ca901341df6e1dcb58adfb8e6c18526ded72766b","text":"} } pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self { let begin = sess.source_map().lookup_byte_offset(span.lo()); let end = sess.source_map().lookup_byte_offset(span.hi()); // Make the range zero-length if the span is invalid. if begin.sf.start_pos != end.sf.start_pos { span = span.shrink_to_lo(); } let mut sr = StringReader::new(sess, begin.sf, None); // Seek the lexer to the right byte range. sr.end_src_index = sr.src_index(span.hi()); sr } fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) }"} {"_id":"q-en-rust-791cf9a0a722d1b6f1dde0e6ef5c09fe7748aa165cd29c4c2b53e834a618e40b","text":"/// # Examples /// /// ``` /// #![feature(osstring_ascii)] /// use std::ffi::OsString; /// /// let mut s = OsString::from(\"Grüße, Jürgen ❤\");"} {"_id":"q-en-rust-79a070e0b47f77082606e6c990b707dda9a52bf698a33326ff05b444eca26ba9","text":"self.super_terminator(terminator, location); match &terminator.kind { TerminatorKind::Call { func, .. } => { TerminatorKind::Call { func, args, .. } => { let ConstCx { tcx, body, param_env, .. } = *self.ccx; let caller = self.def_id().to_def_id();"} {"_id":"q-en-rust-79bb893c6b7639168c130dea7cf33ba1545ad20ffbf82ec43ab0c48ce380f7a1","text":"fn find_library_crate(&self) -> Option { let filesearch = self.sess.filesearch; let crate_name = self.name.clone(); let (dyprefix, dysuffix) = self.dylibname(); // want: crate_name.dir_part() + prefix + crate_name.file_part + \"-\" let dylib_prefix = format!(\"{}{}-\", dyprefix, crate_name); let rlib_prefix = format!(\"lib{}-\", crate_name); let dylib_prefix = format!(\"{}{}-\", dyprefix, self.name); let rlib_prefix = format!(\"lib{}-\", self.name); let mut matches = ~[]; filesearch.search(|path| { match path.filename_str() { None => FileDoesntMatch, Some(file) => { let (candidate, existing) = if file.starts_with(rlib_prefix) && file.ends_with(\".rlib\") { debug!(\"{} is an rlib candidate\", path.display()); (true, self.add_existing_rlib(matches, path, file)) } else if file.starts_with(dylib_prefix) && file.ends_with(dysuffix) { debug!(\"{} is a dylib candidate\", path.display()); (true, self.add_existing_dylib(matches, path, file)) } else { (false, false) }; let mut candidates = HashMap::new(); if candidate && existing { // First, find all possible candidate rlibs and dylibs purely based on // the name of the files themselves. We're trying to match against an // exact crate_id and a possibly an exact hash. // // During this step, we can filter all found libraries based on the // name and id found in the crate id (we ignore the path portion for // filename matching), as well as the exact hash (if specified). If we // end up having many candidates, we must look at the metadata to // perform exact matches against hashes/crate ids. Note that opening up // the metadata is where we do an exact match against the full contents // of the crate id (path/name/id). // // The goal of this step is to look at as little metadata as possible. filesearch.search(|path| { let file = match path.filename_str() { None => return FileDoesntMatch, Some(file) => file, }; if file.starts_with(rlib_prefix) && file.ends_with(\".rlib\") { info!(\"rlib candidate: {}\", path.display()); match self.try_match(file, rlib_prefix, \".rlib\") { Some(hash) => { info!(\"rlib accepted, hash: {}\", hash); let slot = candidates.find_or_insert_with(hash, |_| { (HashSet::new(), HashSet::new()) }); let (ref mut rlibs, _) = *slot; rlibs.insert(path.clone()); FileMatches } else if candidate { match get_metadata_section(self.os, path) { Some(cvec) => if crate_matches(cvec.as_slice(), self.name.clone(), self.version.clone(), self.hash.clone()) { debug!(\"found {} with matching crate_id\", path.display()); let (rlib, dylib) = if file.ends_with(\".rlib\") { (Some(path.clone()), None) } else { (None, Some(path.clone())) }; matches.push(Library { rlib: rlib, dylib: dylib, metadata: cvec, }); FileMatches } else { debug!(\"skipping {}, crate_id doesn't match\", path.display()); FileDoesntMatch }, _ => { debug!(\"could not load metadata for {}\", path.display()); FileDoesntMatch } } } else { } None => { info!(\"rlib rejected\"); FileDoesntMatch } } } else if file.starts_with(dylib_prefix) && file.ends_with(dysuffix){ info!(\"dylib candidate: {}\", path.display()); match self.try_match(file, dylib_prefix, dysuffix) { Some(hash) => { info!(\"dylib accepted, hash: {}\", hash); let slot = candidates.find_or_insert_with(hash, |_| { (HashSet::new(), HashSet::new()) }); let (_, ref mut dylibs) = *slot; dylibs.insert(path.clone()); FileMatches } None => { info!(\"dylib rejected\"); FileDoesntMatch } } } else { FileDoesntMatch } }); match matches.len() { // We have now collected all known libraries into a set of candidates // keyed of the filename hash listed. For each filename, we also have a // list of rlibs/dylibs that apply. Here, we map each of these lists // (per hash), to a Library candidate for returning. // // A Library candidate is created if the metadata for the set of // libraries corresponds to the crate id and hash criteria that this // serach is being performed for. let mut libraries = ~[]; for (_hash, (rlibs, dylibs)) in candidates.move_iter() { let mut metadata = None; let rlib = self.extract_one(rlibs, \"rlib\", &mut metadata); let dylib = self.extract_one(dylibs, \"dylib\", &mut metadata); match metadata { Some(metadata) => { libraries.push(Library { dylib: dylib, rlib: rlib, metadata: metadata, }) } None => {} } } // Having now translated all relevant found hashes into libraries, see // what we've got and figure out if we found multiple candidates for // libraries or not. match libraries.len() { 0 => None, 1 => Some(matches[0]), 1 => Some(libraries[0]), _ => { self.sess.span_err(self.span, format!(\"multiple matching crates for `{}`\", crate_name)); format!(\"multiple matching crates for `{}`\", self.name)); self.sess.note(\"candidates:\"); for lib in matches.iter() { for lib in libraries.iter() { match lib.dylib { Some(ref p) => { self.sess.note(format!(\"path: {}\", p.display()));"} {"_id":"q-en-rust-79c143c555e1ec7415a9986cb183ce423f100b13276d37ef92796e391a98ee31","text":"match eh_action { EHAction::None | EHAction::Cleanup(_) => return continue_unwind(exception_object, context), EHAction::Catch(_) => return uw::_URC_HANDLER_FOUND, EHAction::Catch(_) => { // EHABI requires the personality routine to update the // SP value in the barrier cache of the exception object. (*exception_object).private[5] = uw::_Unwind_GetGR(context, uw::UNWIND_SP_REG); return uw::_URC_HANDLER_FOUND; } EHAction::Terminate => return uw::_URC_FAILURE, } } else {"} {"_id":"q-en-rust-79fbc86c03f081a504357185152c7ba087a1ba970588b367217b3adc0a098148","text":"if let Some(path) = env::var_os(\"PATH\") { new_path.extend(env::split_paths(&path)); } if sess.target.target.options.is_like_msvc { new_path.extend(msvc::host_dll_path()); } env::join_paths(new_path).unwrap() }"} {"_id":"q-en-rust-7a520750eaf75ca5165556a71c4e23ce511b3fc239059a7892f94bf8a38ddf17","text":"llvm::LLVMRustInstallFatalErrorHandler(); fn llvm_arg_to_arg_name(full_arg: &str) -> &str { full_arg.trim().split(|c: char| { c == '=' || c.is_whitespace() }).next().unwrap_or(\"\") } let user_specified_args: FxHashSet<_> = sess .opts .cg .llvm_args .iter() .map(|s| llvm_arg_to_arg_name(s)) .filter(|s| s.len() > 0) .collect(); { let mut add = |arg: &str| { let s = CString::new(arg).unwrap(); llvm_args.push(s.as_ptr()); llvm_c_strs.push(s); // This adds the given argument to LLVM. Unless `force` is true // user specified arguments are *not* overridden. let mut add = |arg: &str, force: bool| { if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) { let s = CString::new(arg).unwrap(); llvm_args.push(s.as_ptr()); llvm_c_strs.push(s); } }; add(\"rustc\"); // fake program name if sess.time_llvm_passes() { add(\"-time-passes\"); } if sess.print_llvm_passes() { add(\"-debug-pass=Structure\"); } if sess.opts.debugging_opts.disable_instrumentation_preinliner { add(\"-disable-preinline\"); } add(\"rustc\", true); // fake program name if sess.time_llvm_passes() { add(\"-time-passes\", false); } if sess.print_llvm_passes() { add(\"-debug-pass=Structure\", false); } if sess.opts.debugging_opts.generate_arange_section { add(\"-generate-arange-section\"); add(\"-generate-arange-section\", false); } if get_major_version() >= 8 { match sess.opts.debugging_opts.merge_functions"} {"_id":"q-en-rust-7a7fc1a7c38152ece862a883bf4c95fdd82ff0450d4f603151c5b2768c80d0e2","text":"#![feature(iter_advance_by)] #![feature(slice_group_by)] #![feature(slice_partition_dedup)] #![feature(vec_spare_capacity)] #![feature(string_remove_matches)] #![feature(const_btree_new)] #![feature(const_default_impls)]"} {"_id":"q-en-rust-7a9642303801c22f3cfa5caaffb4c300f2ec5f411be895b3af30e720a7e42d13","text":" // This test ensures that non-glob reexports don't get their attributes merge with // the reexported item whereas glob reexports do. // Regression test for . #![crate_name = \"foo\"] #![feature(doc_cfg)] // @has 'foo/index.html' // There are two items. // @count - '//*[@class=\"item-table\"]//div[@class=\"item-name\"]' 2 // Only one of them should have an attribute. // @count - '//*[@class=\"item-table\"]//div[@class=\"item-name\"]/*[@class=\"stab portability\"]' 1 mod a { #[doc(cfg(not(feature = \"a\")))] #[cfg(not(feature = \"a\"))] pub struct Test1; } mod b { #[doc(cfg(not(feature = \"a\")))] #[cfg(not(feature = \"a\"))] pub struct Test2; } // @has 'foo/struct.Test1.html' // @count - '//*[@id=\"main-content\"]/*[@class=\"item-info\"]' 1 // @has - '//*[@id=\"main-content\"]/*[@class=\"item-info\"]' 'Available on non-crate feature a only.' pub use a::*; // @has 'foo/struct.Test2.html' // @count - '//*[@id=\"main-content\"]/*[@class=\"item-info\"]' 0 pub use b::Test2; "} {"_id":"q-en-rust-7abcce3e072390dbd37764fcda4e63578b467fc7e2d58c2b74ae72d4e1f31f88","text":"pub mod dump_mir; pub mod early_otherwise_branch; pub mod elaborate_drops; pub mod function_item_references; pub mod generator; pub mod inline; pub mod instcombine;"} {"_id":"q-en-rust-7ac8ed50bff7dfa24f9b9619836d50edda325a56c3a1d06fe469f1e5348bb77e","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-pass trait DictLike<'a> { type ItemsIterator: Iterator; fn get(c: Self::ItemsIterator) { c.into_iter(); } } trait DictLike2<'a> { type ItemsIterator: Iterator; fn items(&self) -> Self::ItemsIterator; fn get(&self) { for _ in self.items() {} } } fn main() {} "} {"_id":"q-en-rust-7af8fece514973d500b926f76909c7ce33cdd1e392b85f4914c9af99ceaccc61","text":"let res = binding.res(); self.check_reserved_macro_name(key.ident, res); self.set_binding_parent_module(binding, module); let mut resolution = self.resolution(module, key).borrow_mut(); let old_binding = resolution.binding(); let mut t = Ok(()); if let Some(old_binding) = resolution.binding { if res == Res::Err && old_binding.res() != Res::Err { // Do not override real bindings with `Res::Err`s from error recovery. } else { self.update_resolution(module, key, |this, resolution| { if let Some(old_binding) = resolution.binding { if res == Res::Err && old_binding.res() != Res::Err { // Do not override real bindings with `Res::Err`s from error recovery. return Ok(()); } match (old_binding.is_glob_import(), binding.is_glob_import()) { (true, true) => { if res != old_binding.res() { resolution.binding = Some(self.ambiguity( resolution.binding = Some(this.ambiguity( AmbiguityKind::GlobVsGlob, old_binding, binding, )); } else if !old_binding.vis.is_at_least(binding.vis, self.tcx) { } else if !old_binding.vis.is_at_least(binding.vis, this.tcx) { // We are glob-importing the same item but with greater visibility. resolution.binding = Some(binding); }"} {"_id":"q-en-rust-7afe46694c3b1903fd54d0e3d88360b36d31b67d328e15109129e4c7d2a0c1de","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":"q-en-rust-7b2a1fa9bc7af9b1ee54931eab4f360a2f01dd7f21cf6d0d248f0781e9ceda86","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":"q-en-rust-7b4c6e38befa3c07a4c097605d90a3d19091f65ef554ab3e319b6a19c77cae10","text":"pub fn duplicate(&self) -> io::Result { // We want to atomically duplicate this file descriptor and set the // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This // flag, however, isn't supported on older Linux kernels (earlier than // 2.6.24). // // To detect this and ensure that CLOEXEC is still set, we // follow a strategy similar to musl [1] where if passing // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not // supported (the third parameter, 0, is always valid), so we stop // trying that. // // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to // resolve so we at least compile this. // // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963 #[cfg(any(target_os = \"android\", target_os = \"haiku\"))] use libc::F_DUPFD as F_DUPFD_CLOEXEC; #[cfg(not(any(target_os = \"android\", target_os = \"haiku\")))] use libc::F_DUPFD_CLOEXEC; let make_filedesc = |fd| { let fd = FileDesc::new(fd); fd.set_cloexec()?; Ok(fd) }; static TRY_CLOEXEC: AtomicBool = AtomicBool::new(!cfg!(target_os = \"android\")); let fd = self.raw(); if TRY_CLOEXEC.load(Ordering::Relaxed) { match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) { // We *still* call the `set_cloexec` method as apparently some // linux kernel at some point stopped setting CLOEXEC even // though it reported doing so on F_DUPFD_CLOEXEC. Ok(fd) => { return Ok(if cfg!(target_os = \"linux\") { make_filedesc(fd)? } else { FileDesc::new(fd) }); } Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => { TRY_CLOEXEC.store(false, Ordering::Relaxed); } Err(e) => return Err(e), } } cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc) // is a POSIX flag that was added to Linux in 2.6.24. let fd = cvt(unsafe { libc::fcntl(self.raw(), libc::F_DUPFD_CLOEXEC, 0) })?; Ok(FileDesc::new(fd)) } }"} {"_id":"q-en-rust-7b53bfd62178d5b32391af26f11ebcc62e73a05f46e92e61b2bf7429f5ada0b0","text":"self.expr_as_operand(block, scope, expr) } /// Like `as_local_call_operand`, except that the argument will /// not be valid once `scope` ends. fn as_call_operand( &mut self, block: BasicBlock, scope: Option, expr: M, ) -> BlockAnd> where M: Mirror<'tcx, Output = Expr<'tcx>>, { let expr = self.hir.mirror(expr); self.expr_as_call_operand(block, scope, expr) } fn expr_as_operand( &mut self, mut block: BasicBlock,"} {"_id":"q-en-rust-7b8412e450d6df47715a97fdb38e988ea2398fd9076d3732b293a3d15f1aa721","text":" macro_rules! define_other_core { ( ) => { extern crate std as core; //~^ ERROR macro-expanded `extern crate` items cannot shadow names passed with `--extern` }; } fn main() { core::panic!(); } define_other_core!(); "} {"_id":"q-en-rust-7bb36251f3aefc8c2603c717430e4652770bdeafe1c7a4d2faa467aa4ded7dca","text":" //! This test makes sure that with never show the inner fields in the //! aliased type view of type alias. #![crate_name = \"foo\"] use std::collections::BTreeMap; // @has 'foo/type.FooBar.html' '//*[@class=\"rust item-decl\"]/code' 'struct FooBar { /* private fields */ }' pub type FooBar = BTreeMap; "} {"_id":"q-en-rust-7be48f79e3f378b48c5b34e9a9687c8a384270d4dd3956c861437746a2231758","text":" // check-pass #![feature(marker_trait_attr)] #[marker] trait Marker {} impl Marker for &'static () {} impl Marker for &'static () {} fn main() {} "} {"_id":"q-en-rust-7c37d39505667b3457e3c30615165c38181eeda791f510297d6779a66af6da3a","text":" // compile-flags: -Zsave-analysis // Check that this doesn't ICE when processing associated const (field expr). pub fn f() { trait Trait {} impl Trait { const FLAG: u32 = bogus.field; //~ ERROR cannot find value `bogus` } } fn main() {} "} {"_id":"q-en-rust-7c54a1ece8102b919428ade9d758a3168530eff3b2d17e2c1cd5190890ae6c56","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":"q-en-rust-7c701a138fb6b682be0f469a11625eca2dcf839e6d3f8c714670b090ac593d32","text":" Subproject commit e8b556b6a8836147429abe391d6ed18806867b45 Subproject commit 3adf16e0cb1a0d9d7216883ac47857a6d1ee6581 "} {"_id":"q-en-rust-7c79db9fd3ee1476cadff9b8510e982305de351b4d19e872415fec81b21b110d","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. // Test that multibyte characters don't crash the compiler fn main() { io::println(\"마이너스 사인이 없으면\"); } "} {"_id":"q-en-rust-7ccadec2cdc57acd50d75fa9d48d49477aa928390ac05c030440137503357a48","text":"let mut path_str; let (res, fragment) = { let mut kind = None; let mut disambiguator = None; path_str = if let Some(prefix) = [\"struct@\", \"enum@\", \"type@\", \"trait@\", \"union@\"] .iter() .find(|p| link.starts_with(**p)) { kind = Some(TypeNS); disambiguator = Some(&prefix[..prefix.len() - 1]); link.trim_start_matches(prefix) } else if let Some(prefix) = [ \"const@\","} {"_id":"q-en-rust-7cf3634c775f2621760b899415befcaa8beccb1ee69a65a472f97755f1c155ca","text":") { let sccs = self.regioncx.constraint_sccs(); let universal_regions = self.regioncx.universal_regions(); let issuing_region_scc = sccs.scc(issuing_region); // We first handle the cases where the loan doesn't go out of scope, depending on the issuing // region's successors. for scc in sccs.depth_first_search(issuing_region_scc) { for successor in self.regioncx.region_graph().depth_first_search(issuing_region) { // 1. Via applied member constraints // // The issuing region can flow into the choice regions, and they are either:"} {"_id":"q-en-rust-7d0824eebcaaecc09fce7694c5e543656c144b2aa2d7352d81bc5a7e8e0380c6","text":".iter() .enumerate() .map(|(i, ty)| Argument { name: Symbol::intern(&rustc_hir_pretty::param_to_string(&body.params[i])), name: name_from_pat(&body.params[i].pat), type_: ty.clean(cx), }) .collect(),"} {"_id":"q-en-rust-7d17d3e2464ca4b22297db044749e1391143854f19b29b60f58d15b8c4d74965","text":" // run-rustfix fn wat(t: &T) -> T { t.clone() //~ ERROR E0308 } struct Foo; fn wut(t: &Foo) -> Foo { t.clone() //~ ERROR E0308 } fn main() { wat(&42); wut(&Foo); } "} {"_id":"q-en-rust-7d49cb0c1c28911544ef219b4dd6e3e21f6fcc4ce45880631ff8903bd807697f","text":" error: struct `Whatever` is never constructed --> $DIR/clone-debug-dead-code-in-the-same-struct.rs:4:12 error: fields `field1`, `field2`, `field3`, and `field4` are never read --> $DIR/clone-debug-dead-code-in-the-same-struct.rs:6:5 | LL | pub struct Whatever { | ^^^^^^^^ | -------- fields in this struct LL | pub field0: (), LL | field1: (), | ^^^^^^ LL | field2: (), | ^^^^^^ LL | field3: (), | ^^^^^^ LL | field4: (), | ^^^^^^ | = note: `Whatever` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis note: the lint level is defined here --> $DIR/clone-debug-dead-code-in-the-same-struct.rs:1:11 |"} {"_id":"q-en-rust-7d797b1e8c07943b17232e0478b7e03f236d5a61bdaeae30aa19b40cdc01efa9","text":"/// Parses a statement. This stops just before trailing semicolons on everything but items. /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed. pub fn parse_stmt(&mut self) -> PResult<'a, Option> { Ok(self.parse_stmt_(true)) } fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option { self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| { Ok(self.parse_stmt_without_recovery(true).unwrap_or_else(|mut e| { e.emit(); self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore); None }) })) } fn parse_stmt_without_recovery("} {"_id":"q-en-rust-7d7d96e7b8c79eb88d369fbc9de8e94448685095562ac2d9c6f76b05357252b3","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":"q-en-rust-7dfed09c0eaac0f0fe0187da402954ecad476e544ad6c81bbfa1373c70ee69b5","text":" Subproject commit a7348ae0df3c71581dbe3d355fc0fb6ce6332dd0 Subproject commit e048e97f5280e8a232a43ae134d395aeab67c2e8 "} {"_id":"q-en-rust-7e7bf7e618ec5184baa17e199136b3bc03572baf52f1c66a87c0778bfc23349e","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":"q-en-rust-7e94890988837b48de23e199095dd72455043aa11e73fdc95a71a015dabcd4d5","text":" // only-x86_64 // check-fail #![feature(lang_items, no_core, target_feature_11)] #![no_core] #[lang = \"copy\"] pub trait Copy {} #[lang = \"sized\"] pub trait Sized {} #[lang = \"start\"] #[target_feature(enable = \"avx2\")] //~^ ERROR `start` language item function is not allowed to have `#[target_feature]` fn start(_main: fn() -> T, _argc: isize, _argv: *const *const u8, _sigpipe: u8) -> isize { 0 } fn main() {} "} {"_id":"q-en-rust-7ea5e07931cfaadbc2d23b5f444b42b2dfab8bfe351a91cce15792413dba167f","text":"use rustc_middle::mir::interpret::{sign_extend, truncate}; use rustc_middle::ty::layout::{IntegerExt, SizeSkeleton}; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt, TypeFoldable}; use rustc_middle::ty::{self, AdtKind, Ty, TypeFoldable}; use rustc_span::source_map; use rustc_span::symbol::sym; use rustc_span::{Span, DUMMY_SP};"} {"_id":"q-en-rust-7ea9a8e821512b51598bb77b71c7c1d1c40ee64638b3c090abeb5fedb3175902","text":"/// } /// ``` #[must_use] #[unstable(feature = \"panic_info_message\", issue = \"66745\")] #[stable(feature = \"panic_info_message\", since = \"CURRENT_RUSTC_VERSION\")] pub fn message(&self) -> PanicMessage<'_> { PanicMessage { message: self.message } }"} {"_id":"q-en-rust-7eaf3acf7057c86cb3c04930e6bed0552f8967b3037d79014b329038cd28b562","text":"error[E0508]: cannot move out of type `[u8]`, a non-copy slice --> $DIR/unsized-exprs2.rs:22:19 --> $DIR/unsized-exprs2.rs:22:5 | LL | udrop::<[u8]>(foo()[..]); | ^^^^^^^^^ | | | cannot move out of here | move occurs because value has type `[u8]`, which does not implement the `Copy` trait | ^^^^^^^^^^^^^^^^^^^^^^^^ | | | cannot move out of here | move occurs because value has type `[u8]`, which does not implement the `Copy` trait error: aborting due to previous error"} {"_id":"q-en-rust-7ec4d42010ca12ae3cbfcdd9a803c10b30ed2e66707295f5c68af8ea6162b9f7","text":"rm $(TMPDIR)/bar $(RUSTC) foo.rs --emit=asm,ir,bc,obj,link --crate-type=staticlib rm $(TMPDIR)/bar.ll rm $(TMPDIR)/bar.bc rm $(TMPDIR)/bar.s rm $(TMPDIR)/bar.o rm $(TMPDIR)/$(call STATICLIB_GLOB,bar)"} {"_id":"q-en-rust-7ef9a2da9e0ec31968acd5d78cab2c2cf73794bc31c1f8388d2e885fba7b449b","text":"[1.8h]: https://github.com/rust-lang/rust/pull/31460 [1.8l]: https://github.com/rust-lang/rust/pull/31668 [1.8m]: https://github.com/rust-lang/rust/pull/31020 [1.8m]: https://github.com/rust-lang/rust/pull/31534 [1.8mf]: https://github.com/rust-lang/rust/pull/31534 [1.8mp]: https://github.com/rust-lang/rust/pull/30894 [1.8mr]: https://users.rust-lang.org/t/multirust-0-8-with-cross-std-installation/4901 [1.8ms]: https://github.com/rust-lang/rust/pull/30448"} {"_id":"q-en-rust-7f0c1971d452a503bc23a5c950010ce945b2e0f81ed1dacf1936ae72d5077074","text":"pub fn emit_feature_err(diag: &SpanHandler, feature: &str, span: Span, explain: &str) { diag.span_err(span, explain); // #23973: do not suggest `#![feature(...)]` if we are in beta/stable if option_env!(\"CFG_DISABLE_UNSTABLE_FEATURES\").is_some() { return; } diag.fileline_help(span, &format!(\"add #![feature({})] to the crate attributes to enable\", feature));"} {"_id":"q-en-rust-7f5fc2e420d7d957d56257ae65aecab8528201adfd7c88f03dbea1dbb21fa863","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. // // no-system-llvm // compile-flags: -O #![crate_type=\"lib\"] #[no_mangle] pub fn sum_me() -> i32 { // CHECK-LABEL: @sum_me // CHECK-NEXT: {{^.*:$}} // CHECK-NEXT: ret i32 6 vec![1, 2, 3].iter().sum::() } "} {"_id":"q-en-rust-7f6790480771b6671343513ae337652136e85cf3e8ed9b2bde14853d2749303c","text":"// In theory, any zero-sized value could be borrowed // mutably without consequences. However, only &mut [] // is allowed right now, and only in functions. if self.const_kind == Some(hir::ConstContext::Static(hir::Mutability::Mut)) { // Inside a `static mut`, &mut [...] is also allowed. match ty.kind() { ty::Array(..) | ty::Slice(_) => {} _ => return Err(Unpromotable), } } else if let ty::Array(_, len) = ty.kind() { if let ty::Array(_, len) = ty.kind() { // FIXME(eddyb) the `self.is_non_const_fn` condition // seems unnecessary, given that this is merely a ZST. match len.try_eval_usize(self.tcx, self.param_env) {"} {"_id":"q-en-rust-7f85300e426c4b75ba2ee81ce3fb96d9f13868dd994b638f421b83a58211e89c","text":"// for where the type was defined. On the other // hand, `paths` always has the right // information if present. Some(&( ref fqp, ItemType::Trait | ItemType::Struct | ItemType::Union | ItemType::Enum, )) => Some(&fqp[..fqp.len() - 1]), Some(..) => Some(&*self.cache.stack), Some(&(ref fqp, _)) => Some(&fqp[..fqp.len() - 1]), None => None, }; ((Some(*last), path), true)"} {"_id":"q-en-rust-7fc8299a0747ad1f230a31ecb059e27e6c4b7d551aaba4d0f218d16f61244d25","text":" // Assuming that the hidden type in these tests is `&'_#15r u8`, // we have a member constraint: `'_#15r member ['static, 'a, 'b, 'c]`. // // Make sure we pick up the minimum non-ambiguous region among them. // We will have to exclude `['b, 'c]` because they're incomparable, // and then we should pick `'a` because we know `'static: 'a`. // check-pass trait Cap<'a> {} impl Cap<'_> for T {} fn type_test<'a, T: 'a>() -> &'a u8 { &0 } // Basic test: make sure we don't bail out because 'b and 'c are incomparable. fn basic<'a, 'b, 'c>() -> impl Cap<'a> + Cap<'b> + Cap<'c> where 'a: 'b, 'a: 'c, { &0 } // Make sure we don't pick `'static`. fn test_static<'a, 'b, 'c, T>() -> impl Cap<'a> + Cap<'b> + Cap<'c> where 'a: 'b, 'a: 'c, T: 'a, { type_test::<'_, T>() // This will fail if we pick 'static } fn main() {} "} {"_id":"q-en-rust-7fe136a4757517c91e8107e0a7ddde2d68a0e34c10703515a80143a5768a6f93","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":"q-en-rust-7fe30a3aaa2e633f3e99e63f29c8e0ce8f2e48a75c3773bbed90f68726b1da72","text":" enum e{A((?'a a+?+l))} //~^ ERROR `?` may only modify trait bounds, not lifetime bounds //~| ERROR expected one of `)`, `+`, or `,` //~| ERROR expected trait bound, not lifetime bound "} {"_id":"q-en-rust-802bae6a5b5fb437f3e619dc40032ebf8229999507c0db40aef15ecffe3984a1","text":"/// /// Note that the arguments are not passed through a shell, but given /// literally to the program. This means that shell syntax like quotes, /// escaped characters, word splitting, glob patterns, substitution, etc. /// escaped characters, word splitting, glob patterns, variable substitution, etc. /// have no effect. /// /// # Examples"} {"_id":"q-en-rust-803b91e8949d53937454f110f8c63a2b8eca562049662ed115ec04c80aa7883d","text":"StorageLive(_4); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:8:5: 8:6 _4 = &mut (*_1); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:8:5: 8:6 StorageLive(_5); // scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL _5 = &mut (*(*_4)); // scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL _3 = move _5; // scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL StorageLive(_6); // scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL _6 = &mut (*(*_4)); // scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL _5 = &mut (*_6); // scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL _3 = &mut (*_5); // scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL StorageDead(_6); // scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL StorageDead(_5); // scope 1 at $SRC_DIR/liballoc/boxed.rs:LL:COL _2 = &mut (*_3); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:8:5: 8:15 StorageDead(_4); // scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:8:14: 8:15"} {"_id":"q-en-rust-806f3977153ce0b3e950131039eb8a02e53d038da17d1217ba484857f2ae7f6f","text":"35 | #[stable = \"1300\"] impl S { } | ^^^^^^^^^^^^^^^^^^ error: aborting due to 9 previous errors error: aborting due to 8 previous errors "} {"_id":"q-en-rust-808c2643d085a37e09f91ff9825e8fea956b1a1bb7d1a6f35c44813e7555fa8e","text":"} _ if sp == expr.span && !is_macro => { if let Some(steps) = self.deref_steps(checked_ty, expected) { let expr = expr.peel_blocks(); if steps == 1 { // For a suggestion to make sense, the type would need to be `Copy`. if self.infcx.type_is_copy_modulo_regions(self.param_env, expected, sp) { if let Ok(code) = sm.span_to_snippet(sp) { if let hir::ExprKind::AddrOf(_, mutbl, inner) = expr.kind { // If the expression has `&`, removing it would fix the error let prefix_span = expr.span.with_hi(inner.span.lo()); let message = match mutbl { hir::Mutability::Not => \"consider removing the `&`\", hir::Mutability::Mut => \"consider removing the `&mut`\", }; let suggestion = String::new(); return Some(( prefix_span, message, suggestion, Applicability::MachineApplicable, )); } else if self.infcx.type_is_copy_modulo_regions( self.param_env, expected, sp, ) { // For this suggestion to make sense, the type would need to be `Copy`. if let Ok(code) = sm.span_to_snippet(expr.span) { let message = if checked_ty.is_region_ptr() { \"consider dereferencing the borrow\" } else {"} {"_id":"q-en-rust-80a88800e861bcb2502eb687dc7c7e8a41efbf563499cc296390b46da5614659","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":"q-en-rust-80b96d33100a4ceae4d7b5de0bc0a48e8f7c876425d8ce1f457f98bf9151824a","text":" error[E0261]: use of undeclared lifetime name `'a` --> $DIR/erase-error-in-mir-drop-tracking.rs:11:46 | LL | fn connect(&'_ self) -> Self::Connecting<'a>; | ^^ undeclared lifetime | help: consider introducing lifetime `'a` here | LL | fn connect<'a>(&'_ self) -> Self::Connecting<'a>; | ++++ help: consider introducing lifetime `'a` here | LL | trait Client<'a> { | ++++ error: `C` does not live long enough --> $DIR/erase-error-in-mir-drop-tracking.rs:19:5 | LL | async move { c.connect().await } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0261`. "} {"_id":"q-en-rust-8101f95307ba0bcc1ce308963db18635a86a37e0b5b629dd2b1541a878f6ce9f","text":"// Allows irrefutable patterns in if-let and while-let statements (RFC 2086) (active, irrefutable_let_patterns, \"1.27.0\", Some(44495), None), // Allows use of the :literal macro fragment specifier (RFC 1576) (active, macro_literal_matcher, \"1.27.0\", Some(35625), None), // inconsistent bounds in where clauses (active, trivial_bounds, \"1.28.0\", Some(48214), None),"} {"_id":"q-en-rust-812257b9bdeb685c50874e6f128920f13b777316032b980e574632fdda214a1c","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":"q-en-rust-81355cff4b3baa9e6d82fd2414cbe4fad1697d15b89dbdd6880cf0b79c6d48fc","text":"// declared as public (due to pruning, we don't explore // outside crate private modules => no need to check this) if !in_module_is_extern || name_binding.vis == ty::Visibility::Public { candidates.push(ImportSuggestion { path }); let did = match def { Def::StructCtor(did, _) | Def::VariantCtor(did, _) => self.parent(did), _ => def.opt_def_id(), }; candidates.push(ImportSuggestion { did, path }); } } }"} {"_id":"q-en-rust-8168728707c586eb2c5ef861ee7fecac0a840618afb6fcbdb075699f71ebdbd6","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":"q-en-rust-818503d92e9526542514f6dd744a7bfcc3b26987ef1cfc752ee308ca9155bd0f","text":"relevant_pr_url, relevant_pr_user, pr_reviewer, cur_datetime cur_datetime, github_token, ) if not message: print('')"} {"_id":"q-en-rust-81b6f518461f8685cc2dbc8f10b81233fb577af7260207d1080550251d038eac","text":"} } else { debug!(\"receiver_is_valid: type `{:?}` does not deref to `{:?}`\", receiver_ty, self_ty); // If the receiver already has errors reported due to it, consider it valid to avoid // unnecessary errors (#58712). return receiver_ty.references_error(); return false; } }"} {"_id":"q-en-rust-81becdd5997148649369ef781b03f17a21310d2939f586c1ba637dbf8dac4618","text":" // check-pass // incremental struct Struct(T); impl std::ops::Deref for Struct { type Target = dyn Fn(T); fn deref(&self) -> &Self::Target { unimplemented!() } } fn main() { let f = Struct(Default::default()); f(0); f(0); } "} {"_id":"q-en-rust-81fb057c353b530318402da780dbf61e2e7e4dc6c054d5966d6d4e5a18479b74","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":"q-en-rust-82021d1cd5a885c75ff2e3668e6369c291af00d8d654e4af213e29aa2b9a9a24","text":" // #![feature(stdsimd)] #![no_main] #![no_std] use core::fmt::Write;"} {"_id":"q-en-rust-8280e4738570f3dad31e3f73eed2cca1494d5e419340561fe4fa58e57ef8ab4d","text":"//~^ ERROR missing lifetime specifier //~| ERROR `S<'_>` is forbidden as the type of a const generic parameter trait Foo<'a> {} struct Bar Foo<'a>)>; //~^ ERROR use of non-static lifetime `'a` in const generic //~| ERROR `&dyn for<'a> Foo<'a>` is forbidden as the type of a const generic parameter fn main() {}"} {"_id":"q-en-rust-828b6b8a5faadf24293f69fade5e7c52697469a53d573be8e47bfced7db11a54","text":"20 | m!(MyTrait<>); //~ ERROR generic arguments in macro path | ^^ error: aborting due to 5 previous errors error: aborting due to 4 previous errors "} {"_id":"q-en-rust-828b9c6379aefd1903e2b2ee5e58fe38bf76c77850878eba80d65f5ec47b91eb","text":"unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // jemalloc provides alignment less than MIN_ALIGN for small allocations. // So only rely on MIN_ALIGN if size >= align. // Also see and // . if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { libc::malloc(layout.size()) as *mut u8 } else {"} {"_id":"q-en-rust-829ef606971383bd0beae6327fad90a3896165fda6edcecc2d2448e74bf86f4c","text":" fn s() -> String { let a = String::new(); dbg!(a); return a; //~ ERROR use of moved value: } fn m() -> String { let a = String::new(); dbg!(1, 2, a, 1, 2); return a; //~ ERROR use of moved value: } fn t(a: String) -> String { let b: String = \"\".to_string(); dbg!(a, b); return b; //~ ERROR use of moved value: } fn x(a: String) -> String { let b: String = \"\".to_string(); dbg!(a, b); return a; //~ ERROR use of moved value: } macro_rules! my_dbg { () => { eprintln!(\"[{}:{}:{}]\", file!(), line!(), column!()) }; ($val:expr $(,)?) => { match $val { tmp => { eprintln!(\"[{}:{}:{}] {} = {:#?}\", file!(), line!(), column!(), stringify!($val), &tmp); tmp } } }; ($($val:expr),+ $(,)?) => { ($(my_dbg!($val)),+,) }; } fn test_my_dbg() -> String { let b: String = \"\".to_string(); my_dbg!(b, 1); return b; //~ ERROR use of moved value: } fn test_not_macro() -> String { let a = String::new(); let _b = match a { tmp => { eprintln!(\"dbg: {}\", tmp); tmp } }; return a; //~ ERROR use of moved value: } fn get_expr(_s: String) {} fn test() { let a: String = \"\".to_string(); let _res = get_expr(dbg!(a)); let _l = a.len(); //~ ERROR borrow of moved value } fn main() {} "} {"_id":"q-en-rust-82eef4701e1221397f443e158e169f1ee460520fad2bdd45fdc28c5c8dceb3db","text":"//! Performs various peephole optimizations. use crate::transform::{MirPass, MirSource}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::Mutability; use rustc_index::vec::Idx; use rustc_middle::mir::visit::{MutVisitor, Visitor}; use rustc_middle::mir::{ Body, Constant, Local, Location, Mutability, Operand, Place, PlaceRef, ProjectionElem, Rvalue, Body, Constant, Local, Location, Operand, Place, PlaceRef, ProjectionElem, Rvalue, }; use rustc_middle::ty::{self, TyCtxt}; use std::mem;"} {"_id":"q-en-rust-82f27f423d8a084801c62f76d7e2880a337c2c3a154cda06782b1220575d170f","text":"/// Declare a static `LintArray` and return it as an expression. #[macro_export] macro_rules! lint_array { ($( $lint:expr ),*) => ( { static ARRAY: LintArray = &[ $( &$lint ),* ]; ARRAY } ) } macro_rules! lint_array { ($( $lint:expr ),*,) => { lint_array!( $( $lint ),* ) }; ($( $lint:expr ),*) => {{ static ARRAY: LintArray = &[ $( &$lint ),* ]; ARRAY }} } pub type LintArray = &'static [&'static &'static Lint];"} {"_id":"q-en-rust-8317a1d4eb7e15aa2d44bb2d481f93c5f0cc893eeea347c80466c0d87929b7ed","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. //! Cross-platform file path handling (re-write) use container::Container; use c_str::CString; use clone::Clone; use iter::Iterator; use option::{Option, None, Some}; use str; use str::StrSlice; use vec; use vec::{CopyableVector, OwnedCopyableVector, OwnedVector}; use vec::{ImmutableEqVector, ImmutableVector}; pub mod posix; pub mod windows; /// Typedef for POSIX file paths. /// See `posix::Path` for more info. pub type PosixPath = posix::Path; /// Typedef for Windows file paths. /// See `windows::Path` for more info. pub type WindowsPath = windows::Path; /// Typedef for the platform-native path type #[cfg(unix)] pub type Path = PosixPath; /// Typedef for the platform-native path type #[cfg(windows)] pub type Path = WindowsPath; /// Typedef for the POSIX path component iterator. /// See `posix::ComponentIter` for more info. pub type PosixComponentIter<'self> = posix::ComponentIter<'self>; // /// Typedef for the Windows path component iterator. // /// See `windows::ComponentIter` for more info. // pub type WindowsComponentIter<'self> = windows::ComponentIter<'self>; /// Typedef for the platform-native component iterator #[cfg(unix)] pub type ComponentIter<'self> = PosixComponentIter<'self>; // /// Typedef for the platform-native component iterator //#[cfg(windows)] //pub type ComponentIter<'self> = WindowsComponentIter<'self>; // Condition that is raised when a NUL is found in a byte vector given to a Path function condition! { // this should be a &[u8] but there's a lifetime issue null_byte: ~[u8] -> ~[u8]; } /// A trait that represents the generic operations available on paths pub trait GenericPath: Clone + GenericPathUnsafe { /// Creates a new Path from a byte vector. /// The resulting Path will always be normalized. /// /// # Failure /// /// Raises the `null_byte` condition if the path contains a NUL. /// /// See individual Path impls for additional restrictions. #[inline] fn from_vec(path: &[u8]) -> Self { if contains_nul(path) { let path = self::null_byte::cond.raise(path.to_owned()); assert!(!contains_nul(path)); unsafe { GenericPathUnsafe::from_vec_unchecked(path) } } else { unsafe { GenericPathUnsafe::from_vec_unchecked(path) } } } /// Creates a new Path from a string. /// The resulting Path will always be normalized. /// /// # Failure /// /// Raises the `null_byte` condition if the path contains a NUL. #[inline] fn from_str(path: &str) -> Self { let v = path.as_bytes(); if contains_nul(v) { GenericPath::from_vec(path.as_bytes()) // let from_vec handle the condition } else { unsafe { GenericPathUnsafe::from_str_unchecked(path) } } } /// Creates a new Path from a CString. /// The resulting Path will always be normalized. /// /// See individual Path impls for potential restrictions. #[inline] fn from_c_str(path: CString) -> Self { // CStrings can't contain NULs unsafe { GenericPathUnsafe::from_vec_unchecked(path.as_bytes()) } } /// Returns the path as a string, if possible. /// If the path is not representable in utf-8, this returns None. #[inline] fn as_str<'a>(&'a self) -> Option<&'a str> { str::from_utf8_slice_opt(self.as_vec()) } /// Returns the path as a byte vector fn as_vec<'a>(&'a self) -> &'a [u8]; /// Returns the directory component of `self`, as a byte vector (with no trailing separator). /// If `self` has no directory component, returns ['.']. fn dirname<'a>(&'a self) -> &'a [u8]; /// Returns the directory component of `self`, as a string, if possible. /// See `dirname` for details. #[inline] fn dirname_str<'a>(&'a self) -> Option<&'a str> { str::from_utf8_slice_opt(self.dirname()) } /// Returns the file component of `self`, as a byte vector. /// If `self` represents the root of the file hierarchy, returns the empty vector. /// If `self` is \".\", returns the empty vector. fn filename<'a>(&'a self) -> &'a [u8]; /// Returns the file component of `self`, as a string, if possible. /// See `filename` for details. #[inline] fn filename_str<'a>(&'a self) -> Option<&'a str> { str::from_utf8_slice_opt(self.filename()) } /// Returns the stem of the filename of `self`, as a byte vector. /// The stem is the portion of the filename just before the last '.'. /// If there is no '.', the entire filename is returned. fn filestem<'a>(&'a self) -> &'a [u8] { let name = self.filename(); let dot = '.' as u8; match name.rposition_elem(&dot) { None | Some(0) => name, Some(1) if name == bytes!(\"..\") => name, Some(pos) => name.slice_to(pos) } } /// Returns the stem of the filename of `self`, as a string, if possible. /// See `filestem` for details. #[inline] fn filestem_str<'a>(&'a self) -> Option<&'a str> { str::from_utf8_slice_opt(self.filestem()) } /// Returns the extension of the filename of `self`, as an optional byte vector. /// The extension is the portion of the filename just after the last '.'. /// If there is no extension, None is returned. /// If the filename ends in '.', the empty vector is returned. fn extension<'a>(&'a self) -> Option<&'a [u8]> { let name = self.filename(); let dot = '.' as u8; match name.rposition_elem(&dot) { None | Some(0) => None, Some(1) if name == bytes!(\"..\") => None, Some(pos) => Some(name.slice_from(pos+1)) } } /// Returns the extension of the filename of `self`, as a string, if possible. /// See `extension` for details. #[inline] fn extension_str<'a>(&'a self) -> Option<&'a str> { self.extension().and_then(|v| str::from_utf8_slice_opt(v)) } /// Replaces the directory portion of the path with the given byte vector. /// If `self` represents the root of the filesystem hierarchy, the last path component /// of the given byte vector becomes the filename. /// /// # Failure /// /// Raises the `null_byte` condition if the dirname contains a NUL. #[inline] fn set_dirname(&mut self, dirname: &[u8]) { if contains_nul(dirname) { let dirname = self::null_byte::cond.raise(dirname.to_owned()); assert!(!contains_nul(dirname)); unsafe { self.set_dirname_unchecked(dirname) } } else { unsafe { self.set_dirname_unchecked(dirname) } } } /// Replaces the directory portion of the path with the given string. /// See `set_dirname` for details. #[inline] fn set_dirname_str(&mut self, dirname: &str) { if contains_nul(dirname.as_bytes()) { self.set_dirname(dirname.as_bytes()) // triggers null_byte condition } else { unsafe { self.set_dirname_str_unchecked(dirname) } } } /// Replaces the filename portion of the path with the given byte vector. /// If the replacement name is [], this is equivalent to popping the path. /// /// # Failure /// /// Raises the `null_byte` condition if the filename contains a NUL. #[inline] fn set_filename(&mut self, filename: &[u8]) { if contains_nul(filename) { let filename = self::null_byte::cond.raise(filename.to_owned()); assert!(!contains_nul(filename)); unsafe { self.set_filename_unchecked(filename) } } else { unsafe { self.set_filename_unchecked(filename) } } } /// Replaces the filename portion of the path with the given string. /// See `set_filename` for details. #[inline] fn set_filename_str(&mut self, filename: &str) { if contains_nul(filename.as_bytes()) { self.set_filename(filename.as_bytes()) // triggers null_byte condition } else { unsafe { self.set_filename_str_unchecked(filename) } } } /// Replaces the filestem with the given byte vector. /// If there is no extension in `self` (or `self` has no filename), this is equivalent /// to `set_filename`. Otherwise, if the given byte vector is [], the extension (including /// the preceding '.') becomes the new filename. /// /// # Failure /// /// Raises the `null_byte` condition if the filestem contains a NUL. fn set_filestem(&mut self, filestem: &[u8]) { // borrowck is being a pain here let val = { let name = self.filename(); if !name.is_empty() { let dot = '.' as u8; match name.rposition_elem(&dot) { None | Some(0) => None, Some(idx) => { let mut v; if contains_nul(filestem) { let filestem = self::null_byte::cond.raise(filestem.to_owned()); assert!(!contains_nul(filestem)); v = vec::with_capacity(filestem.len() + name.len() - idx); v.push_all(filestem); } else { v = vec::with_capacity(filestem.len() + name.len() - idx); v.push_all(filestem); } v.push_all(name.slice_from(idx)); Some(v) } } } else { None } }; match val { None => self.set_filename(filestem), Some(v) => unsafe { self.set_filename_unchecked(v) } } } /// Replaces the filestem with the given string. /// See `set_filestem` for details. #[inline] fn set_filestem_str(&mut self, filestem: &str) { self.set_filestem(filestem.as_bytes()) } /// Replaces the extension with the given byte vector. /// If there is no extension in `self`, this adds one. /// If the given byte vector is [], this removes the extension. /// If `self` has no filename, this is a no-op. /// /// # Failure /// /// Raises the `null_byte` condition if the extension contains a NUL. fn set_extension(&mut self, extension: &[u8]) { // borrowck causes problems here too let val = { let name = self.filename(); if !name.is_empty() { let dot = '.' as u8; match name.rposition_elem(&dot) { None | Some(0) => { if extension.is_empty() { None } else { let mut v; if contains_nul(extension) { let extension = self::null_byte::cond.raise(extension.to_owned()); assert!(!contains_nul(extension)); v = vec::with_capacity(name.len() + extension.len() + 1); v.push_all(name); v.push(dot); v.push_all(extension); } else { v = vec::with_capacity(name.len() + extension.len() + 1); v.push_all(name); v.push(dot); v.push_all(extension); } Some(v) } } Some(idx) => { if extension.is_empty() { Some(name.slice_to(idx).to_owned()) } else { let mut v; if contains_nul(extension) { let extension = self::null_byte::cond.raise(extension.to_owned()); assert!(!contains_nul(extension)); v = vec::with_capacity(idx + extension.len() + 1); v.push_all(name.slice_to(idx+1)); v.push_all(extension); } else { v = vec::with_capacity(idx + extension.len() + 1); v.push_all(name.slice_to(idx+1)); v.push_all(extension); } Some(v) } } } } else { None } }; match val { None => (), Some(v) => unsafe { self.set_filename_unchecked(v) } } } /// Replaces the extension with the given string. /// See `set_extension` for details. #[inline] fn set_extension_str(&mut self, extension: &str) { self.set_extension(extension.as_bytes()) } /// Returns a new Path constructed by replacing the dirname with the given byte vector. /// See `set_dirname` for details. /// /// # Failure /// /// Raises the `null_byte` condition if the dirname contains a NUL. #[inline] fn with_dirname(&self, dirname: &[u8]) -> Self { let mut p = self.clone(); p.set_dirname(dirname); p } /// Returns a new Path constructed by replacing the dirname with the given string. /// See `set_dirname` for details. #[inline] fn with_dirname_str(&self, dirname: &str) -> Self { let mut p = self.clone(); p.set_dirname_str(dirname); p } /// Returns a new Path constructed by replacing the filename with the given byte vector. /// See `set_filename` for details. /// /// # Failure /// /// Raises the `null_byte` condition if the filename contains a NUL. #[inline] fn with_filename(&self, filename: &[u8]) -> Self { let mut p = self.clone(); p.set_filename(filename); p } /// Returns a new Path constructed by replacing the filename with the given string. /// See `set_filename` for details. #[inline] fn with_filename_str(&self, filename: &str) -> Self { let mut p = self.clone(); p.set_filename_str(filename); p } /// Returns a new Path constructed by setting the filestem to the given byte vector. /// See `set_filestem` for details. /// /// # Failure /// /// Raises the `null_byte` condition if the filestem contains a NUL. #[inline] fn with_filestem(&self, filestem: &[u8]) -> Self { let mut p = self.clone(); p.set_filestem(filestem); p } /// Returns a new Path constructed by setting the filestem to the given string. /// See `set_filestem` for details. #[inline] fn with_filestem_str(&self, filestem: &str) -> Self { let mut p = self.clone(); p.set_filestem_str(filestem); p } /// Returns a new Path constructed by setting the extension to the given byte vector. /// See `set_extension` for details. /// /// # Failure /// /// Raises the `null_byte` condition if the extension contains a NUL. #[inline] fn with_extension(&self, extension: &[u8]) -> Self { let mut p = self.clone(); p.set_extension(extension); p } /// Returns a new Path constructed by setting the extension to the given string. /// See `set_extension` for details. #[inline] fn with_extension_str(&self, extension: &str) -> Self { let mut p = self.clone(); p.set_extension_str(extension); p } /// Returns the directory component of `self`, as a Path. /// If `self` represents the root of the filesystem hierarchy, returns `self`. fn dir_path(&self) -> Self { // self.dirname() returns a NUL-free vector unsafe { GenericPathUnsafe::from_vec_unchecked(self.dirname()) } } /// Returns the file component of `self`, as a relative Path. /// If `self` represents the root of the filesystem hierarchy, returns None. fn file_path(&self) -> Option { // self.filename() returns a NUL-free vector match self.filename() { [] => None, v => Some(unsafe { GenericPathUnsafe::from_vec_unchecked(v) }) } } /// Pushes a path (as a byte vector) onto `self`. /// If the argument represents an absolute path, it replaces `self`. /// /// # Failure /// /// Raises the `null_byte` condition if the path contains a NUL. #[inline] fn push(&mut self, path: &[u8]) { if contains_nul(path) { let path = self::null_byte::cond.raise(path.to_owned()); assert!(!contains_nul(path)); unsafe { self.push_unchecked(path) } } else { unsafe { self.push_unchecked(path) } } } /// Pushes a path (as a string) onto `self. /// See `push` for details. #[inline] fn push_str(&mut self, path: &str) { if contains_nul(path.as_bytes()) { self.push(path.as_bytes()) // triggers null_byte condition } else { unsafe { self.push_str_unchecked(path) } } } /// Pushes a Path onto `self`. /// If the argument represents an absolute path, it replaces `self`. #[inline] fn push_path(&mut self, path: &Self) { self.push(path.as_vec()) } /// Pops the last path component off of `self` and returns it. /// If `self` represents the root of the file hierarchy, None is returned. fn pop_opt(&mut self) -> Option<~[u8]>; /// Pops the last path component off of `self` and returns it as a string, if possible. /// `self` will still be modified even if None is returned. /// See `pop_opt` for details. #[inline] fn pop_opt_str(&mut self) -> Option<~str> { self.pop_opt().and_then(|v| str::from_utf8_owned_opt(v)) } /// Returns a new Path constructed by joining `self` with the given path (as a byte vector). /// If the given path is absolute, the new Path will represent just that. /// /// # Failure /// /// Raises the `null_byte` condition if the path contains a NUL. #[inline] fn join(&self, path: &[u8]) -> Self { let mut p = self.clone(); p.push(path); p } /// Returns a new Path constructed by joining `self` with the given path (as a string). /// See `join` for details. #[inline] fn join_str(&self, path: &str) -> Self { let mut p = self.clone(); p.push_str(path); p } /// Returns a new Path constructed by joining `self` with the given path. /// If the given path is absolute, the new Path will represent just that. #[inline] fn join_path(&self, path: &Self) -> Self { let mut p = self.clone(); p.push_path(path); p } /// Returns whether `self` represents an absolute path. /// An absolute path is defined as one that, when joined to another path, will /// yield back the same absolute path. fn is_absolute(&self) -> bool; /// Returns whether `self` is equal to, or is an ancestor of, the given path. /// If both paths are relative, they are compared as though they are relative /// to the same parent path. fn is_ancestor_of(&self, other: &Self) -> bool; /// Returns the Path that, were it joined to `base`, would yield `self`. /// If no such path exists, None is returned. /// If `self` is absolute and `base` is relative, or on Windows if both /// paths refer to separate drives, an absolute path is returned. fn path_relative_from(&self, base: &Self) -> Option; } /// A trait that represents the unsafe operations on GenericPaths pub trait GenericPathUnsafe { /// Creates a new Path from a byte vector without checking for null bytes. /// The resulting Path will always be normalized. unsafe fn from_vec_unchecked(path: &[u8]) -> Self; /// Creates a new Path from a str without checking for null bytes. /// The resulting Path will always be normalized. #[inline] unsafe fn from_str_unchecked(path: &str) -> Self { GenericPathUnsafe::from_vec_unchecked(path.as_bytes()) } /// Replaces the directory portion of the path with the given byte vector without /// checking for null bytes. /// See `set_dirname` for details. unsafe fn set_dirname_unchecked(&mut self, dirname: &[u8]); /// Replaces the directory portion of the path with the given str without /// checking for null bytes. /// See `set_dirname_str` for details. #[inline] unsafe fn set_dirname_str_unchecked(&mut self, dirname: &str) { self.set_dirname_unchecked(dirname.as_bytes()) } /// Replaces the filename portion of the path with the given byte vector without /// checking for null bytes. /// See `set_filename` for details. unsafe fn set_filename_unchecked(&mut self, filename: &[u8]); /// Replaces the filename portion of the path with the given str without /// checking for null bytes. /// See `set_filename_str` for details. #[inline] unsafe fn set_filename_str_unchecked(&mut self, filename: &str) { self.set_filename_unchecked(filename.as_bytes()) } /// Pushes a byte vector onto `self` without checking for null bytes. /// See `push` for details. unsafe fn push_unchecked(&mut self, path: &[u8]); /// Pushes a str onto `self` without checking for null bytes. /// See `push_str` for details. #[inline] unsafe fn push_str_unchecked(&mut self, path: &str) { self.push_unchecked(path.as_bytes()) } } #[inline(always)] fn contains_nul(v: &[u8]) -> bool { v.iter().any(|&x| x == 0) } "} {"_id":"q-en-rust-8339eff4c30944db97cf0618e42b67ff15156d6e328c430e682d563b2752e95e","text":"/// Returns an iterator over all function arguments. #[inline] pub fn args_iter(&self) -> impl Iterator { pub fn args_iter(&self) -> impl Iterator + ExactSizeIterator { let arg_count = self.arg_count; (1..=arg_count).map(Local::new) (1..arg_count + 1).map(Local::new) } /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all /// locals that are neither arguments nor the return place). #[inline] pub fn vars_and_temps_iter(&self) -> impl Iterator { pub fn vars_and_temps_iter(&self) -> impl Iterator + ExactSizeIterator { let arg_count = self.arg_count; let local_count = self.local_decls.len(); (arg_count + 1..local_count).map(Local::new)"} {"_id":"q-en-rust-833a4256444833c90e33e5ceb58f4e0094a29f317296743009f4305d6b0dae2b","text":"})); } let (inh_first, inh_second) = { let mut inh_variants = (0..variants.len()).filter(|&v| { variants[v].iter().all(|f| f.abi != Abi::Uninhabited) }); (inh_variants.next(), inh_variants.next()) }; if inh_first.is_none() { // Uninhabited because it has no variants, or only uninhabited ones. return Ok(tcx.intern_layout(LayoutDetails::uninhabited(0))); } let is_struct = !def.is_enum() || // Only one variant is inhabited. (inh_second.is_none() &&"} {"_id":"q-en-rust-835494981ae6928c51af2a47e3ed1f77c362c3c219c8ef1bf32e0b64bb09d781","text":"for i in 0..tupled_arg_tys.len() { let arg = &fx.fn_ty.args[idx]; idx += 1; if arg.pad.is_some() { llarg_idx += 1; } arg.store_fn_arg(bx, &mut llarg_idx, place.project_field(bx, i)); }"} {"_id":"q-en-rust-83622628ec2e74f4fdbde2b579052c3b526edd83af0d3f397557cdd9b41b7827","text":"} fn crate_matches(crate_data: &[u8], name: ~str, version: ~str, hash: ~str) -> bool { name: &str, version: &str, hash: &str) -> bool { let attrs = decoder::get_crate_attributes(crate_data); match attr::find_crateid(attrs) { None => false, Some(crateid) => { if !hash.is_empty() { let chash = decoder::get_crate_hash(crate_data); if chash != hash { return false; } if chash.as_slice() != hash { return false; } } name == crateid.name && (version.is_empty() ||"} {"_id":"q-en-rust-8381154e3fa4dc21918563bf25967fa78a7fab322213776c811a6177c593bad7","text":"let args = vec!(self_arg); // Add all the fields as a value which needs to be cleaned at the end of // this scope. for (i, ty) in st.fields.iter().enumerate() { // this scope. Iterate in reverse order so a Drop impl doesn't reverse // the order in which fields get dropped. for (i, ty) in st.fields.iter().enumerate().rev() { let llfld_a = adt::struct_field_ptr(variant_cx, &*st, value, i, false); variant_cx.fcx.schedule_drop_mem(cleanup::CustomScope(field_scope), llfld_a, *ty);"} {"_id":"q-en-rust-83be8f9ff10c7c3859303f320aa9c119bb183d2bfae162e14e5597b3be785910","text":"/// # Examples /// /// ``` /// #![feature(inner_deref)] /// let mut s = \"HELLO\".to_string(); /// let mut x: Result = Ok(\"hello\".to_string()); /// let y: Result<&mut str, &mut u32> = Ok(\"HELLO\"); /// let y: Result<&mut str, &mut u32> = Ok(&mut s); /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); /// /// let mut i = 42; /// let mut x: Result = Err(42); /// let y: Result<&mut str, &mut u32> = Err(&42); /// let y: Result<&mut str, &mut u32> = Err(&mut i); /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); /// ``` pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> {"} {"_id":"q-en-rust-83e198c40961a99bca8bb10228d71a505f366f93cd8a1b6ab04bd1b56c5385aa","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":"q-en-rust-83f5e90c5fdace849eabe406e3e43c0699741cfef2084392f9334e1a960d9794","text":".arg(\"--manifest-path\") .arg(builder.src.join(\"src/tools/miri/test-cargo-miri/Cargo.toml\")); cargo.arg(\"--target\").arg(target.rustc_target_arg()); cargo.arg(\"--tests\"); // don't run doctests, they are too confused by the staging cargo.arg(\"--\").args(builder.config.test_args()); // `prepare_tool_cargo` sets RUSTDOC to the bootstrap wrapper and RUSTDOC_REAL to a dummy path as this is a \"run\", not a \"test\". // Also, we want the rustdoc from the \"next\" stage for the same reason that we build a std from the next stage. // So let's just set that here, and bypass bootstrap's RUSTDOC (just like cargo-miri already ignores bootstrap's RUSTC_WRAPPER). cargo.env(\"RUSTDOC\", builder.rustdoc(compiler_std)); // Tell `cargo miri` where to find things. cargo.env(\"MIRI_SYSROOT\", &miri_sysroot); cargo.env(\"MIRI_HOST_SYSROOT\", sysroot);"} {"_id":"q-en-rust-840fbc6edba2052295e52ed884fb8b34df24a34a4f9d3faf7fc934e07108dc33","text":"&[], ); miri.add_rustc_lib_path(builder); // Forward arguments. miri.arg(\"--\").arg(\"--target\").arg(target.rustc_target_arg()); miri.args(builder.config.args()); // miri tests need to know about the stage sysroot miri.env(\"MIRI_SYSROOT\", &miri_sysroot); miri.arg(\"--sysroot\").arg(miri_sysroot); // Forward arguments. This may contain further arguments to the program // after another --, so this must be at the end. miri.args(builder.config.args()); let mut miri = Command::from(miri); builder.run(&mut miri);"} {"_id":"q-en-rust-841ae6bcd47972e13a0ab53394e1dd63085c67016e9b593ddb3a93a51fbb06e0","text":" - // MIR for `bar` before RevealAll + // MIR for `bar` after RevealAll fn bar(_1: P) -> () { debug _baz => _1; // in scope 0 at $DIR/issue-78442.rs:9:5: 9:9 let mut _0: (); // return place in scope 0 at $DIR/issue-78442.rs:10:3: 10:3 let _2: (); // in scope 0 at $DIR/issue-78442.rs:11:5: 11:17 - let mut _3: &impl std::ops::Fn<()>; // in scope 0 at $DIR/issue-78442.rs:11:5: 11:15 - let _4: impl std::ops::Fn<()>; // in scope 0 at $DIR/issue-78442.rs:11:5: 11:15 + let mut _3: &fn() {foo}; // in scope 0 at $DIR/issue-78442.rs:11:5: 11:15 + let _4: fn() {foo}; // in scope 0 at $DIR/issue-78442.rs:11:5: 11:15 let mut _5: (); // in scope 0 at $DIR/issue-78442.rs:11:5: 11:17 bb0: { StorageLive(_2); // scope 0 at $DIR/issue-78442.rs:11:5: 11:17 StorageLive(_3); // scope 0 at $DIR/issue-78442.rs:11:5: 11:15 StorageLive(_4); // scope 0 at $DIR/issue-78442.rs:11:5: 11:15 _4 = hide_foo() -> [return: bb1, unwind: bb4]; // scope 0 at $DIR/issue-78442.rs:11:5: 11:15 // mir::Constant // + span: $DIR/issue-78442.rs:11:5: 11:13 // + literal: Const { ty: fn() -> impl std::ops::Fn<()> {hide_foo}, val: Value(Scalar()) } } bb1: { _3 = &_4; // scope 0 at $DIR/issue-78442.rs:11:5: 11:15 StorageLive(_5); // scope 0 at $DIR/issue-78442.rs:11:5: 11:17 nop; // scope 0 at $DIR/issue-78442.rs:11:5: 11:17 _2 = as Fn<()>>::call(move _3, move _5) -> [return: bb2, unwind: bb4]; // scope 0 at $DIR/issue-78442.rs:11:5: 11:17 // mir::Constant // + span: $DIR/issue-78442.rs:11:5: 11:15 // + literal: Const { ty: for<'r> extern \"rust-call\" fn(&'r impl std::ops::Fn<()>, ()) -> as std::ops::FnOnce<()>>::Output { as std::ops::Fn<()>>::call}, val: Value(Scalar()) } } bb2: { StorageDead(_5); // scope 0 at $DIR/issue-78442.rs:11:16: 11:17 StorageDead(_3); // scope 0 at $DIR/issue-78442.rs:11:16: 11:17 StorageDead(_4); // scope 0 at $DIR/issue-78442.rs:11:17: 11:18 StorageDead(_2); // scope 0 at $DIR/issue-78442.rs:11:17: 11:18 _0 = const (); // scope 0 at $DIR/issue-78442.rs:10:3: 12:2 drop(_1) -> [return: bb3, unwind: bb5]; // scope 0 at $DIR/issue-78442.rs:12:1: 12:2 } bb3: { return; // scope 0 at $DIR/issue-78442.rs:12:2: 12:2 } bb4 (cleanup): { drop(_1) -> bb5; // scope 0 at $DIR/issue-78442.rs:12:1: 12:2 } bb5 (cleanup): { resume; // scope 0 at $DIR/issue-78442.rs:7:1: 12:2 } } "} {"_id":"q-en-rust-8434e0c46ee3b420201af32616aa427a4f65cc237b8b84eb4a0a2a7eedcbdffa","text":"} ``` Enums with values are quite useful, but as I mentioned, they're even more useful when they're generic across types. But before we get to generics, let's talk about how to fix these big `if`/`else` statements we've been writing. We'll do that with `match`. And you can also have something like this: ```{rust} enum StringResult { StringOK(String), ErrorReason(String), } ``` Where a `StringResult` is either an `StringOK`, with the result of a computation, or an `ErrorReason` with a `String` explaining what caused the computation to fail. This kind of `enum`s are actually very useful and are even part of the standard library. As you can see `enum`s with values are quite a powerful tool for data representation, and can be even more useful when they're generic across types. But before we get to generics, let's talk about how to use them with pattern matching, a tool that will let us deconstruct this sum type (the type theory term for enums) in a very elegant way and avoid all these messy `if`/`else`s. # Match"} {"_id":"q-en-rust-84371256d5ecd0d3c95bc9982ed2eae15a678d7262bfc95ede78ad3c2097184f","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 that the :lifetime macro fragment cannot be used when macro_lifetime_matcher // feature gate is not used. macro_rules! m { ($lt:literal) => {} } //~^ ERROR :literal fragment specifier is experimental and subject to change fn main() { m!(\"some string literal\"); } "} {"_id":"q-en-rust-845075f6b1e94c0114196dfa76ba8a235113e0a0492fa4bf0ad5fe1f12b2e9fd","text":"| ty::Alias(..) | ty::Param(..) | ty::Bound(..) | ty::Error(_) => {} ty::Infer(_) => { | ty::Error(_) | ty::Infer( ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(_) | ty::InferTy::FreshIntTy(_) | ty::InferTy::FreshFloatTy(_), ) => {} ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)) => { candidates.ambiguous = true; } }"} {"_id":"q-en-rust-8496391b516d37e376ee3cff0f705b0da0eb825241455c41ccf489e2ab06a40a","text":"let loop_hir_id = self.lower_node_id(loop_node_id); let ready_arm = { let x_ident = Ident::with_dummy_span(sym::result); let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident); let x_expr = self.expr_ident(span, x_ident, x_pat_hid); let ready_field = self.single_pat_field(span, x_pat); let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident); let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid); let ready_field = self.single_pat_field(gen_future_span, x_pat); let ready_pat = self.pat_lang_item_variant( span, hir::LangItem::PollReady,"} {"_id":"q-en-rust-849f8e59cbf3a334040aa782a6f0d7ffd4d680783064d2c7970b8df4590f2eef","text":"} debug!(?choice_regions, \"after ub\"); // If we ruled everything out, we're done. if choice_regions.is_empty() { return false; } // Otherwise, we need to find the minimum remaining choice, if // any, and take that. debug!(\"choice_regions remaining are {:#?}\", choice_regions); let Some(&min_choice) = choice_regions.iter().find(|&r1| { // At this point we can pick any member of `choice_regions`, but to avoid potential // non-determinism we will pick the *unique minimum* choice. // // Because universal regions are only partially ordered (i.e, not every two regions are // comparable), we will ignore any region that doesn't compare to all others when picking // the minimum choice. // For example, consider `choice_regions = ['static, 'a, 'b, 'c, 'd, 'e]`, where // `'static: 'a, 'static: 'b, 'a: 'c, 'b: 'c, 'c: 'd, 'c: 'e`. // `['d, 'e]` are ignored because they do not compare - the same goes for `['a, 'b]`. let totally_ordered_subset = choice_regions.iter().copied().filter(|&r1| { choice_regions.iter().all(|&r2| { self.universal_region_relations.outlives(r2, *r1) self.universal_region_relations.outlives(r1, r2) || self.universal_region_relations.outlives(r2, r1) }) }); // Now we're left with `['static, 'c]`. Pick `'c` as the minimum! let Some(min_choice) = totally_ordered_subset.reduce(|r1, r2| { let r1_outlives_r2 = self.universal_region_relations.outlives(r1, r2); let r2_outlives_r1 = self.universal_region_relations.outlives(r2, r1); match (r1_outlives_r2, r2_outlives_r1) { (true, true) => r1.min(r2), (true, false) => r2, (false, true) => r1, (false, false) => bug!(\"incomparable regions in total order\"), } }) else { debug!(\"no choice region outlived by all others\"); debug!(\"no unique minimum choice\"); return false; };"} {"_id":"q-en-rust-84dea630b2f294bcb2a21b3c6f562bf2c9ab3e2c0867bf7fcb71926393e2ff47","text":"} def load_json_from_response(resp): # type: (typing.Any) -> typing.Any content = resp.read() if isinstance(content, bytes): content = content.decode('utf-8') content_str = content.decode('utf-8') else: print(\"Refusing to decode \" + str(type(content)) + \" to str\") return json.loads(content) return json.loads(content_str) def validate_maintainers(repo, github_token): # type: (str, str) -> None '''Ensure all maintainers are assignable on a GitHub repo''' next_link_re = re.compile(r'<([^>]+)>; rel=\"next\"') # Load the list of assignable people in the GitHub repo assignable = [] url = 'https://api.github.com/repos/%s/collaborators?per_page=100' % repo assignable = [] # type: typing.List[str] url = 'https://api.github.com/repos/' + '%s/collaborators?per_page=100' % repo # type: typing.Optional[str] while url is not None: response = urllib2.urlopen(urllib2.Request(url, headers={ 'Authorization': 'token ' + github_token,"} {"_id":"q-en-rust-84e200c3d23bae5e85d795cb4ddd6b463d994acd879f4ce9c320acacf9105d82","text":"// EMIT_MIR jump_threading.assume.JumpThreading.diff // EMIT_MIR jump_threading.aggregate_copy.JumpThreading.diff // EMIT_MIR jump_threading.floats.JumpThreading.diff // EMIT_MIR jump_threading.bitwise_not.JumpThreading.diff "} {"_id":"q-en-rust-84f123042c9915c8b88783ae19012ccc3931da277da2437c6ea6a3a3453c02c5","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":"q-en-rust-850b458174f910356868b315d552c0bdc72dd400f625a59575acdbf4369f14d1","text":"use rustc_hir::def::{DefKind, DocLinkResMap, Namespace, Res}; use rustc_hir::HirId; use rustc_lint_defs::Applicability; use rustc_resolve::rustdoc::source_span_for_markdown_range; use rustc_resolve::rustdoc::{prepare_to_doc_link_resolution, source_span_for_markdown_range}; use rustc_span::def_id::DefId; use rustc_span::Symbol;"} {"_id":"q-en-rust-8511df17d87ab4cc7eeaead35dc3c0e8f924307c92d349aa8059a66b865ee15e","text":"sess.note(&format!(\"{:?}\", &cmd)); let mut output = prog.stderr.clone(); output.push_all(&prog.stdout); sess.note(str::from_utf8(&output[..]).unwrap()); sess.note(&*escape_string(&output[..])); sess.abort_if_errors(); } info!(\"linker stderr:n{}\", String::from_utf8(prog.stderr).unwrap()); info!(\"linker stdout:n{}\", String::from_utf8(prog.stdout).unwrap()); info!(\"linker stderr:n{}\", escape_string(&prog.stderr[..])); info!(\"linker stdout:n{}\", escape_string(&prog.stdout[..])); }, Err(e) => { sess.fatal(&format!(\"could not exec the linker `{}`: {}\", pname, e));"} {"_id":"q-en-rust-8573ef716adb1b4a129e0714a9a2fda77d6e0a138830ea067756d9dbd51c90ab","text":"codegen_fn_attrs.export_name = Some(s); } } else if attr.check_name(sym::target_feature) { if tcx.fn_sig(id).unsafety() == Unsafety::Normal { if tcx.is_closure(id) || tcx.fn_sig(id).unsafety() == Unsafety::Normal { let msg = \"`#[target_feature(..)]` can only be applied to `unsafe` functions\"; tcx.sess .struct_span_err(attr.span, msg)"} {"_id":"q-en-rust-857d2b1e41619099bb494e8aa5880678fb0c1acd832e35fa2679dcbd3894ef86","text":"// except according to those terms. // run-pass #![feature(macro_literal_matcher)] macro_rules! a { ($i:literal) => { \"right\" };"} {"_id":"q-en-rust-8580b18f522540db5d90059dc7b65721a8907837540639939e980229c95eb684","text":"cargo: Option = \"cargo\", rustc: Option = \"rustc\", rustfmt: Option = \"rustfmt\", cargo_clippy: Option = \"cargo-clippy\", docs: Option = \"docs\", compiler_docs: Option = \"compiler-docs\", library_docs_private_items: Option = \"library-docs-private-items\","} {"_id":"q-en-rust-858956bfbeacc4a26c50bcf4452304c01e84baadaa75e070afdc168fcca7090c","text":"run_path_with_cstr(original, &|original| { run_path_with_cstr(link, &|link| { cfg_if::cfg_if! { if #[cfg(any(target_os = \"vxworks\", target_os = \"redox\", target_os = \"android\", target_os = \"espidf\", target_os = \"horizon\", target_os = \"vita\", target_os = \"nto\"))] { if #[cfg(any(target_os = \"vxworks\", target_os = \"redox\", target_os = \"android\", target_os = \"espidf\", target_os = \"horizon\", target_os = \"vita\", target_env = \"nto70\"))] { // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves // it implementation-defined whether `link` follows symlinks, so rely on the // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior."} {"_id":"q-en-rust-85a2d7167cc8a68f4911b721745faab59f7775f9163bb5e153c860f57e8e2f24","text":"} pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx>, Span)> { // HACK: `type_of_def_id()` will fail on these (#55796), so return `None`. // `type_of()` will fail on these (#55796, #86483), so only allow `fn`s or closures. let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id); match self.hir().get(hir_id) { Node::Item(item) => { match item.kind { ItemKind::Fn(..) => { /* `type_of_def_id()` will work */ } _ => { return None; } } } _ => { /* `type_of_def_id()` will work or panic */ } Node::Item(&hir::Item { kind: ItemKind::Fn(..), .. }) => {} Node::TraitItem(&hir::TraitItem { kind: TraitItemKind::Fn(..), .. }) => {} Node::ImplItem(&hir::ImplItem { kind: ImplItemKind::Fn(..), .. }) => {} Node::Expr(&hir::Expr { kind: ExprKind::Closure(..), .. }) => {} _ => return None, } let ret_ty = self.type_of(scope_def_id);"} {"_id":"q-en-rust-85b0efbc11e56d68602436dc263253a15751749ef160b66d8e68017e6453f814","text":"pub fn replace<'a, R>( &self, replacement: >::Out, f: impl for<'b, 'c> FnOnce(RefMutL<'b, 'c, T>) -> R, f: impl for<'b, 'c> FnOnce(&'b mut >::Out) -> R, ) -> R { /// Wrapper that ensures that the cell always gets filled /// (with the original state, optionally changed by `f`),"} {"_id":"q-en-rust-861ee0867355d3d63c387cb34d2774f5d59506a58174ea4a955f61fc67877974","text":" // Regression test for #61320 // This is the same issue as #61311, just a larger test case. // compile-pass pub struct AndThen where A: Future, B: IntoFuture, { state: (A, B::Future, F), } pub struct FutureResult { inner: Option>, } impl Future for FutureResult { type Item = T; type Error = E; fn poll(&mut self) -> Poll { unimplemented!() } } pub type Poll = Result; impl Future for AndThen where A: Future, B: IntoFuture, F: FnOnce(A::Item) -> B, { type Item = B::Item; type Error = B::Error; fn poll(&mut self) -> Poll { unimplemented!() } } pub trait Future { type Item; type Error; fn poll(&mut self) -> Poll; fn and_then(self, f: F) -> AndThen where F: FnOnce(Self::Item) -> B, B: IntoFuture, Self: Sized, { unimplemented!() } } pub trait IntoFuture { /// The future that this type can be converted into. type Future: Future; /// The item that the future may resolve with. type Item; /// The error that the future may resolve with. type Error; /// Consumes this object and produces a future. fn into_future(self) -> Self::Future; } impl IntoFuture for F { type Future = F; type Item = F::Item; type Error = F::Error; fn into_future(self) -> F { self } } impl Future for ::std::boxed::Box { type Item = F::Item; type Error = F::Error; fn poll(&mut self) -> Poll { (**self).poll() } } impl IntoFuture for Result { type Future = FutureResult; type Item = T; type Error = E; fn into_future(self) -> FutureResult { unimplemented!() } } struct Request(T); trait RequestContext {} impl RequestContext for T {} struct NoContext; impl AsRef for NoContext { fn as_ref(&self) -> &Self { &NoContext } } type BoxedError = Box; type DefaultFuture = Box + Send>; trait Guard: Sized { type Result: IntoFuture; fn from_request(request: &Request<()>) -> Self::Result; } trait FromRequest: Sized { type Context; type Future: Future + Send; fn from_request(request: Request<()>) -> Self::Future; } struct MyGuard; impl Guard for MyGuard { type Result = Result; fn from_request(_request: &Request<()>) -> Self::Result { Ok(MyGuard) } } struct Generic { _inner: I, } impl FromRequest for Generic where MyGuard: Guard, ::Result: IntoFuture, <::Result as IntoFuture>::Future: Send, I: FromRequest, { type Future = DefaultFuture; type Context = NoContext; fn from_request(headers: Request<()>) -> DefaultFuture { let _future = ::from_request(&headers) .into_future() .and_then(move |_| { ::from_request(headers) .into_future() .and_then(move |fld_inner| Ok(Generic { _inner: fld_inner }).into_future()) }); panic!(); } } fn main() {} "} {"_id":"q-en-rust-86254b621bc67898454f26b1f7f640f30c86307cc58532d763d58c36233cc5fb","text":"// // We could remove this hack whenever we decide to drop macOS 10.10 support. if self.tcx.sess.target.target.options.is_like_osx { assert_eq!(alloc.relocations().len(), 0); let is_zeroed = { // Treats undefined bytes as if they were defined with the byte value that // happens to be currently assigned in mir. This is valid since reading // undef bytes may yield arbitrary values. // // FIXME: ignore undef bytes even with representation `!= 0`. // // The `inspect` method is okay here because we checked relocations, and // because we are doing this access to inspect the final interpreter state // (not as part of the interpreter execution). alloc // The `inspect` method is okay here because we checked relocations, and // because we are doing this access to inspect the final interpreter state // (not as part of the interpreter execution). // // FIXME: This check requires that the (arbitrary) value of undefined bytes // happens to be zero. Instead, we should only check the value of defined bytes // and set all undefined bytes to zero if this allocation is headed for the // BSS. let all_bytes_are_zero = alloc.relocations().is_empty() && alloc .inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len()) .iter() .all(|b| *b == 0) }; let sect_name = if is_zeroed { .all(|&byte| byte == 0); let sect_name = if all_bytes_are_zero { CStr::from_bytes_with_nul_unchecked(b\"__DATA,__thread_bss0\") } else { CStr::from_bytes_with_nul_unchecked(b\"__DATA,__thread_data0\")"} {"_id":"q-en-rust-866270a3494c7a5a296334cc14df5cbabf766e8643c12734393f3790b867fcd1","text":"pluralize, CodeSuggestion, Diagnostic, DiagnosticId, Level, SubDiagnostic, SuggestionStyle, }; use log::*; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; use rustc_span::hygiene::{ExpnKind, MacroKind};"} {"_id":"q-en-rust-86adae31a4825fae446de79ed47b4ea41f63dc82a2c2358a47e62601c9b80be9","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":"q-en-rust-86c2428ae18340819fa5bcc497878f1b2b9ba35a5d365b80708c6038b222281e","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":"q-en-rust-86c9ada332e896c4b394c1dc84129b46150cb8b4cad0e432f434f65e092a631e","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":"q-en-rust-86f54a8065a1558a8593fbcd17280ce3c103132425539b16d4a318a2e8888ade","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":"q-en-rust-86fc7d8f004bbb9b923095181bafdddc105a19737ae1e09a482aeb39bbf02578","text":"// We couldn't calculate the span of the markdown block that had the error, so our // diagnostics are going to be a bit lacking. let mut diag = self.cx.sess().struct_span_warn( super::span_of_attrs(&item.attrs), super::span_of_attrs(&item.attrs).unwrap_or(item.source.span()), \"doc comment contains an invalid Rust code block\", );"} {"_id":"q-en-rust-872af9d980804f24c534df803d1c9d945fbe39f5bfe69660caaabc7db4ba75ff","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":"q-en-rust-878a87363493d46c912a1fea3281c4cebad2e960460c63ac04477a469569271c","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":"q-en-rust-87c5ec6d5c8f7938bf247f4add5d030856c858032a7f6c09da1b0349e847f5a6","text":"static G: fn() = aux::G; static H: &(dyn Fn() + Sync) = aux::H; static I: fn() = aux::I; static K: fn() -> fn() = aux::K; fn v() -> *const u32 { V"} {"_id":"q-en-rust-87cef540ea9b347b2412a084f7f29a833095b2e2593512fba94b6c14eb7bf9b2","text":") } fn is_glob_import(tcx: TyCtxt<'_>, import_id: LocalDefId) -> bool { if let Some(node) = tcx.opt_hir_node_by_def_id(import_id) && let hir::Node::Item(item) = node && let hir::ItemKind::Use(_, use_kind) = item.kind { use_kind == hir::UseKind::Glob } else { false } } fn generate_item_with_correct_attrs( cx: &mut DocContext<'_>, kind: ItemKind,"} {"_id":"q-en-rust-87d248ff9c221c3d66efff976a2ade33452ef5b267f0a10d0a2e3e729345bf08","text":"f: F) { let prev_owner = self.current_dep_node_owner; let prev_signature_dep_index = self.current_signature_dep_index; let prev_full_dep_index = self.current_signature_dep_index; let prev_full_dep_index = self.current_full_dep_index; let prev_in_body = self.currently_in_body; let def_path_hash = self.definitions.def_path_hash(dep_node_owner);"} {"_id":"q-en-rust-87ed71cc2fddacac631b35bc6cd83f7d23d08767cb26f7f288ee9def3c18d305","text":"#[cfg(unix, test)] mod test { use core::prelude::*; use core::os; // FIXME(#2119): the outer attribute should be #[cfg(unix, test)], then // these redundant #[cfg(test)] blocks can be removed #[cfg(test)] #[cfg(test)] use back::rpath::{get_install_prefix_rpath}; use back::rpath::{get_absolute_rpath, get_install_prefix_rpath}; use back::rpath::{get_relative_to, get_rpath_relative_to_output}; use back::rpath::{minimize_rpaths, rpaths_to_flags}; use driver::session;"} {"_id":"q-en-rust-880a0cb937f0ba0225ea7a524e90143124e7b21028b0f6c9968f6da1a94b209c","text":" // Regression test for #97405. // In `good_generic_fn` the param `T` ends up in the substs of closures/generators, // but we should be able to prove ` as Iterator>::Item: 'static` without // requiring `T: 'static` // edition:2018 // check-fail fn opaque(_: F) -> impl Iterator { b\"\".iter() } fn assert_static(_: T) {} fn good_generic_fn() { // Previously, proving ` as Iterator>::Item: 'static` // used to require `T: 'static`. assert_static(opaque(async {}).next()); assert_static(opaque(|| {}).next()); assert_static(opaque(opaque(async {}).next()).next()); } // This should fail because `T` ends up in the upvars of the closure. fn bad_generic_fn(t: T) { assert_static(opaque(async move { t; }).next()); //~^ ERROR the associated type `::Item` may not live long enough assert_static(opaque(move || { t; }).next()); //~^ ERROR the associated type `::Item` may not live long enough assert_static(opaque(opaque(async move { t; }).next()).next()); //~^ ERROR the associated type `::Item` may not live long enough } fn main() {} "} {"_id":"q-en-rust-883450e770135c33dce9e8411cb042e1188f5ae62366bee807f8898992d35f34","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":"q-en-rust-883d00add2809de358a9955f82c62f518615a99960bc1d700e56a1e957874f3a","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":"q-en-rust-884f6210d960f8a92f443f51e5030895725e9a48d6b0cd75b30d9825f7583eda","text":"passes_proc_macro_bad_sig = {$kind} has incorrect signature passes_remove_fields = consider removing { $num -> [one] this *[other] these } { $num -> [one] field *[other] fields } passes_repr_conflicting = conflicting representation hints"} {"_id":"q-en-rust-8886248245c18dbf03f762388b4f3b4132e99a667133649cf93383e3e4b3b8fa","text":"/// commonly necessary if the structure is using an unsafe pointer /// like `*mut T` whose referent may be dropped when the type is /// dropped, as a `*mut T` is otherwise not treated as owned. /// /// FIXME. Better documentation and examples of common patterns needed /// here! For now, please see [RFC 738][738] for more information. /// /// [738]: https://github.com/rust-lang/rfcs/blob/master/text/0738-variance.md #[lang=\"phantom_data\"] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub struct PhantomData;"} {"_id":"q-en-rust-888a85dd73dcd9565e02de4e30d3adc6e38aef703e515874a30c7a36e81066ad","text":"unpack(tarball, tarball_suffix, self.bin_root(stage0), match=pattern, verbose=self.verbose) def _download_ci_llvm(self, llvm_sha, llvm_assertions): if not llvm_sha: print(\"error: could not find commit hash for downloading LLVM\") print(\"help: maybe your repository history is too shallow?\") print(\"help: consider disabling `download-ci-llvm`\") print(\"help: or fetch enough history to include one upstream commit\") exit(1) cache_prefix = \"llvm-{}-{}\".format(llvm_sha, llvm_assertions) cache_dst = os.path.join(self.build_dir, \"cache\") rustc_cache = os.path.join(cache_dst, cache_prefix)"} {"_id":"q-en-rust-8890ce03d3a11501ccfeea3e96fde257974f237ef77cb49ed24413f0ed509c91","text":"/// # Examples /// /// ``` /// #![feature(osstring_ascii)] /// use std::ffi::OsString; /// /// let ascii = OsString::from(\"hello!n\");"} {"_id":"q-en-rust-88d4f2007ecaedfd36005d78f178aea8fafba000ed6c8a97eafcc9c576234402","text":"let text = lines.collect::>().join(\"n\"); if rendered { return } PLAYGROUND_KRATE.with(|krate| { let mut s = String::new(); // insert newline to clearly separate it from the // previous block so we can shorten the html output let mut s = String::from(\"n\"); krate.borrow().as_ref().map(|krate| { let test = origtext.lines().map(|l| { stripped_filtered_line(l).unwrap_or(l)"} {"_id":"q-en-rust-891696763d03124a090cb3f404f6fbe033e2835b81dc65d9fc3c3fe158308d18","text":"/// # Examples /// /// ``` /// #![feature(osstring_ascii)] /// use std::ffi::OsString; /// /// let mut s = OsString::from(\"GRÜßE, JÜRGEN ❤\");"} {"_id":"q-en-rust-8937475dac22def8c46dd6c61490dda7929ceba29c7068c3e4f0f9e068715a24","text":" #![feature(adt_const_params)] #![allow(incomplete_features)] use std::marker::ConstParamTy; #[derive(ConstParamTy)] //~^ the trait `ConstParamTy` cannot be implemented for this ty struct Foo([*const u8; 1]); #[derive(ConstParamTy)] //~^ the trait `ConstParamTy` cannot be implemented for this ty struct Foo2([*mut u8; 1]); #[derive(ConstParamTy)] //~^ the trait `ConstParamTy` cannot be implemented for this ty struct Foo3([fn(); 1]); fn main() {} "} {"_id":"q-en-rust-8949cf9e87656fc8ae7893b0417a2615513757bc4973f0ed0898c77f5bddc676","text":"return Err(reported); } let collected_types = collector.types; // Finally, resolve all regions. This catches wily misuses of // lifetime parameters. let outlives_env = OutlivesEnvironment::with_bounds("} {"_id":"q-en-rust-8954c4e4b2a02b1c7e79cefb4371beec95697f88d6d76be9c0c580881b98a106","text":"// crates they depend on. let rel_rpaths = get_rpaths_relative_to_output(os, output, libs); // Make backup absolute paths to the libraries. Binaries can // be moved as long as the crates they link against don't move. let abs_rpaths = get_absolute_rpaths(libs); // And a final backup rpath to the global library location. let fallback_rpaths = ~[get_install_prefix_rpath(target_triple)];"} {"_id":"q-en-rust-8983b26bb8d2cfd31d084a9249b0e9f6621a66a3104db1e104d20d2da00f4ada","text":"| - unclosed delimiter ... LL | fn foo() { | - unclosed delimiter ... LL | fn bar() { | - unclosed delimiter | - another 3 unclosed delimiters begin from here ... LL | fn baz() { | - unclosed delimiter LL | if false { LL | { | - this delimiter might not be properly closed... LL | && let () = ()"} {"_id":"q-en-rust-89b1b69887769fdd8753d87298f3de3e3f08567a8f7204cb282ee3cecce97a10","text":"Ok(()) } fn is_legal_fragment_specifier(sess: &ParseSess, features: &Features, attrs: &[ast::Attribute], fn is_legal_fragment_specifier(_sess: &ParseSess, _features: &Features, _attrs: &[ast::Attribute], frag_name: &str, frag_span: Span) -> bool { _frag_span: Span) -> bool { /* * If new fragment specifiers are invented in nightly, `_sess`, * `_features`, `_attrs`, and `_frag_span` will be useful here * for checking against feature gates. See past versions of * this function. */ match frag_name { \"item\" | \"block\" | \"stmt\" | \"expr\" | \"pat\" | \"lifetime\" | \"path\" | \"ty\" | \"ident\" | \"meta\" | \"tt\" | \"vis\" | \"\" => true, \"literal\" => { if !features.macro_literal_matcher && !attr::contains_name(attrs, \"allow_internal_unstable\") { let explain = feature_gate::EXPLAIN_LITERAL_MATCHER; emit_feature_err(sess, \"macro_literal_matcher\", frag_span, GateIssue::Language, explain); } true }, \"path\" | \"ty\" | \"ident\" | \"meta\" | \"tt\" | \"vis\" | \"literal\" | \"\" => true, _ => false, } }"} {"_id":"q-en-rust-89d1274d0b65d5d5d8c0934f9eee7fa299f58a316549fcce2935e7d485da29d7","text":"rustc_data_structures = { path = \"../librustc_data_structures\" } rustc_hir = { path = \"../librustc_hir\" } rustc_hir_pretty = { path = \"../librustc_hir_pretty\" } rustc_parse = { path = \"../librustc_parse\" } rustc_lexer = { path = \"../librustc_lexer\" } serde_json = \"1\" rustc_session = { path = \"../librustc_session\" } rustc_span = { path = \"../librustc_span\" }"} {"_id":"q-en-rust-89e22bae5332f73ea20ef3121dae357c44e7260e05c457ddc5f3319f097fddc9","text":" Subproject commit 2e951c3ae354bcbd2e50b30798e232949a926b75 Subproject commit a884d21cc5f0b23a1693d1e872fd8998a4fdd17f "} {"_id":"q-en-rust-89f447127647d6435352d04b9cc888efd73779d8e2932038ac247859ef0b0577","text":"h3.impl, h3.method, h3.type { margin-top: 15px; } h1, h2, h3, h4, .sidebar, a.source, .search-input, .content table :not(code)>a, .collapse-toggle { h1, h2, h3, h4, .sidebar, a.source, .search-input, .content table :not(code)>a, .collapse-toggle, ul.item-list > li > .out-of-band { font-family: \"Fira Sans\", \"Helvetica Neue\", Helvetica, Arial, sans-serif; }"} {"_id":"q-en-rust-89f684347260d2c471f024c7cbd12faa885ec498b3fe5ef13fc6851af7298b0e","text":"format!(\"{}-apple-macosx{}.{}.0\", arch, major, minor) } pub fn macos_link_env(arch: &str) -> Vec<(String, String)> { // Use the default deployment target for linking just as with the LLVM target if not // specified via MACOSX_DEPLOYMENT_TARGET, otherwise the system linker would use its // default which varies with Xcode version. if env::var(\"MACOSX_DEPLOYMENT_TARGET\").is_err() { let default = macos_default_deployment_target(arch); vec![(\"MACOSX_DEPLOYMENT_TARGET\".to_string(), format!(\"{}.{}\", default.0, default.1))] } else { vec![] } } pub fn macos_link_env_remove() -> Vec { let mut env_remove = Vec::with_capacity(2); // Remove the `SDKROOT` environment variable if it's clearly set for the wrong platform, which"} {"_id":"q-en-rust-8a1f611e556499a71797c7410c3498ef93d52d8232dfa74b65fa45b1b815049d","text":"&& !results.expr_adjustments(callee_expr).iter().any(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(..))) // Check that we're in fact trying to clone into the expected type && self.can_coerce(*pointee_ty, expected_ty) && let trait_ref = ty::Binder::dummy(self.tcx.mk_trait_ref(clone_trait_did, [expected_ty])) // And the expected type doesn't implement `Clone` && !self.predicate_must_hold_considering_regions(&traits::Obligation::new( self.tcx, traits::ObligationCause::dummy(), self.param_env, ty::Binder::dummy(self.tcx.mk_trait_ref( clone_trait_did, [expected_ty], )), trait_ref, )) { diag.span_note("} {"_id":"q-en-rust-8a20abefde8dcfb7764d0f2ced0bd76929b3af4143ea8f042904c885824b7849","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. // This test makes sure that just changing a definition's location in the // source file also changes its incr. comp. hash, if debuginfo is enabled. // revisions:rpass1 rpass2 // compile-flags: -C overflow-checks=on #![feature(rustc_attrs)] #[cfg(rpass1)] pub fn main() { let _ = 0u8 + 1; } #[cfg(rpass2)] #[rustc_clean(label=\"Hir\", cfg=\"rpass2\")] #[rustc_dirty(label=\"HirBody\", cfg=\"rpass2\")] pub fn main() { let _ = 0u8 + 1; } "} {"_id":"q-en-rust-8a2c679c6f706ddc71358242ce372b439f6bad321a3a017b89a694234f36ced4","text":"serialized_hashes.index_map.len()); } fn process_edges<'a, 'tcx, 'edges>( tcx: TyCtxt<'a, 'tcx, 'tcx>, source: &'edges DepNode, target: &'edges DepNode, edges: &'edges FxHashMap, Vec>>, directory: &DefIdDirectory, retraced: &RetracedDefIdDirectory, dirty_raw_nodes: &DirtyNodes, clean_work_products: &mut FxHashSet>, dirty_work_products: &mut FxHashSet>, extra_edges: &mut Vec<(&'edges DepNode, &'edges DepNode)>) { // If the target is dirty, skip the edge. If this is an edge // that targets a work-product, we can print the blame // information now. if let Some(blame) = dirty_raw_nodes.get(target) { if let DepNode::WorkProduct(ref wp) = *target { if tcx.sess.opts.debugging_opts.incremental_info { if dirty_work_products.insert(wp.clone()) { // It'd be nice to pretty-print these paths better than just // using the `Debug` impls, but wev. println!(\"incremental: module {:?} is dirty because {:?} changed or was removed\", wp, blame.map_def(|&index| { Some(directory.def_path_string(tcx, index)) }).unwrap()); } } } return; } // If the source is dirty, the target will be dirty. assert!(!dirty_raw_nodes.contains_key(source)); // Retrace the source -> target edges to def-ids and then create // an edge in the graph. Retracing may yield none if some of the // data happens to have been removed. if let Some(source_node) = retraced.map(source) { if let Some(target_node) = retraced.map(target) { let _task = tcx.dep_graph.in_task(target_node); tcx.dep_graph.read(source_node); if let DepNode::WorkProduct(ref wp) = *target { clean_work_products.insert(wp.clone()); } } else { // As discussed in `decode_dep_graph` above, sometimes the // target cannot be recreated again, in which case we add // edges to go from `source` to the targets of `target`. extra_edges.extend( edges[target].iter().map(|t| (source, t))); } } else { // It's also possible that the source can't be created! But we // can ignore such cases, because (a) if `source` is a HIR // node, it would be considered dirty; and (b) in other cases, // there must be some input to this node that is clean, and so // we'll re-create the edges over in the case where target is // undefined. } } "} {"_id":"q-en-rust-8a2f154a3e25bca36d8061c15367ee5207ffa638be911cc5d758f7daf03175bb","text":" pub type Archived = ::Archived; //~^ ERROR failed to resolve: use of undeclared crate or module `m` //~| ERROR failed to resolve: use of undeclared crate or module `n` fn main() {} "} {"_id":"q-en-rust-8a76e16983d55d652bf26db7f2729c21f1a82548026eea0e702e4235f57845c3","text":"let ty = field.ty(tcx, args); try_visit!(visitor.visit(span, ty)); } for (pred, span) in tcx.predicates_of(item).instantiate_identity(tcx) { for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { try_visit!(visitor.visit(span, pred)); } }"} {"_id":"q-en-rust-8a93ddf2895e48f4844de3049df2a9e08de1195fdf3a1134bd4362c387c8a5f1","text":"// E0300, // unexpanded macro // E0304, // expected signed integer constant // E0305, // expected constant E0313, // lifetime of borrowed pointer outlives lifetime of captured // variable // E0313, // removed: found unreachable // E0314, // closure outlives stack frame // E0315, // cannot invoke closure outside of its lifetime // E0319, // trait impls for defaulted traits allowed just for structs/enums"} {"_id":"q-en-rust-8aa2d46f3b9569d7f60033c12558740c68bedaf2f1e28316bbc9b9b26d5e388a","text":"*x } async fn async_fn_with_borrow_named_lifetime<'a>(x: &'a u8) -> u8 { await!(wake_and_yield_once()); *x } fn async_fn_with_impl_future_named_lifetime<'a>(x: &'a u8) -> impl Future + 'a { async move { await!(wake_and_yield_once()); *x } } async fn async_fn_with_named_lifetime_multiple_args<'a>(x: &'a u8, _y: &'a u8) -> u8 { await!(wake_and_yield_once()); *x } fn async_fn_with_internal_borrow(y: u8) -> impl Future { async move { await!(async_fn_with_borrow(&y))"} {"_id":"q-en-rust-8ab9e0a27c1da409968a249131796085dc211fe1dd96aaa82ab6267f3719955b","text":" #!/usr/bin/env python # ignore-tidy-linelength # This is a small script that we use on CI to collect CPU usage statistics of # our builders. By seeing graphs of CPU usage over time we hope to correlate # that with possible improvements to Rust's own build system, ideally diagnosing # that either builders are always fully using their CPU resources or they're # idle for long stretches of time. # # This script is relatively simple, but it's platform specific. Each platform # (OSX/Windows/Linux) has a different way of calculating the current state of # CPU at a point in time. We then compare two captured states to determine the # percentage of time spent in one state versus another. The state capturing is # all platform-specific but the loop at the bottom is the cross platform part # that executes everywhere. # # # Viewing statistics # # All builders will upload their CPU statistics as CSV files to our S3 buckets. # These URLS look like: # # https://$bucket.s3.amazonaws.com/rustc-builds/$commit/cpu-$builder.csv # # for example # # https://rust-lang-ci2.s3.amazonaws.com/rustc-builds/68baada19cd5340f05f0db15a3e16d6671609bcc/cpu-x86_64-apple.csv # # Each CSV file has two columns. The first is the timestamp of the measurement # and the second column is the % of idle cpu time in that time slice. Ideally # the second column is always zero. # # Once you've downloaded a file there's various ways to plot it and visualize # it. For command line usage you can use a script like so: # # set timefmt '%Y-%m-%dT%H:%M:%S' # set xdata time # set ylabel \"Idle CPU %\" # set xlabel \"Time\" # set datafile sep ',' # set term png # set output \"printme.png\" # set grid # builder = \"i686-apple\" # plot \"cpu-\".builder.\".csv\" using 1:2 with lines title builder # # Executed as `gnuplot < ./foo.plot` it will generate a graph called # `printme.png` which you can then open up. If you know how to improve this # script or the viewing process that would be much appreciated :) (or even if # you know how to automate it!) import datetime import sys import time if sys.platform == 'linux2': class State: def __init__(self): with open('/proc/stat', 'r') as file: data = file.readline().split() if data[0] != 'cpu': raise Exception('did not start with \"cpu\"') self.user = int(data[1]) self.nice = int(data[2]) self.system = int(data[3]) self.idle = int(data[4]) self.iowait = int(data[5]) self.irq = int(data[6]) self.softirq = int(data[7]) self.steal = int(data[8]) self.guest = int(data[9]) self.guest_nice = int(data[10]) def idle_since(self, prev): user = self.user - prev.user nice = self.nice - prev.nice system = self.system - prev.system idle = self.idle - prev.idle iowait = self.iowait - prev.iowait irq = self.irq - prev.irq softirq = self.softirq - prev.softirq steal = self.steal - prev.steal guest = self.guest - prev.guest guest_nice = self.guest_nice - prev.guest_nice total = user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice return float(idle) / float(total) * 100 elif sys.platform == 'win32': from ctypes.wintypes import DWORD from ctypes import Structure, windll, WinError, GetLastError, byref class FILETIME(Structure): _fields_ = [ (\"dwLowDateTime\", DWORD), (\"dwHighDateTime\", DWORD), ] class State: def __init__(self): idle, kernel, user = FILETIME(), FILETIME(), FILETIME() success = windll.kernel32.GetSystemTimes( byref(idle), byref(kernel), byref(user), ) assert success, WinError(GetLastError())[1] self.idle = (idle.dwHighDateTime << 32) | idle.dwLowDateTime self.kernel = (kernel.dwHighDateTime << 32) | kernel.dwLowDateTime self.user = (user.dwHighDateTime << 32) | user.dwLowDateTime def idle_since(self, prev): idle = self.idle - prev.idle user = self.user - prev.user kernel = self.kernel - prev.kernel return float(idle) / float(user + kernel) * 100 elif sys.platform == 'darwin': from ctypes import * libc = cdll.LoadLibrary('/usr/lib/libc.dylib') PROESSOR_CPU_LOAD_INFO = c_int(2) CPU_STATE_USER = 0 CPU_STATE_SYSTEM = 1 CPU_STATE_IDLE = 2 CPU_STATE_NICE = 3 c_int_p = POINTER(c_int) class State: def __init__(self): num_cpus_u = c_uint(0) cpu_info = c_int_p() cpu_info_cnt = c_int(0) err = libc.host_processor_info( libc.mach_host_self(), PROESSOR_CPU_LOAD_INFO, byref(num_cpus_u), byref(cpu_info), byref(cpu_info_cnt), ) assert err == 0 self.user = 0 self.system = 0 self.idle = 0 self.nice = 0 cur = 0 while cur < cpu_info_cnt.value: self.user += cpu_info[cur + CPU_STATE_USER] self.system += cpu_info[cur + CPU_STATE_SYSTEM] self.idle += cpu_info[cur + CPU_STATE_IDLE] self.nice += cpu_info[cur + CPU_STATE_NICE] cur += num_cpus_u.value def idle_since(self, prev): user = self.user - prev.user system = self.system - prev.system idle = self.idle - prev.idle nice = self.nice - prev.nice return float(idle) / float(user + system + idle + nice) * 100.0 else: print('unknown platform', sys.platform) sys.exit(1) cur_state = State(); print(\"Time,Idle\") while True: time.sleep(1); next_state = State(); now = datetime.datetime.utcnow().isoformat() idle = next_state.idle_since(cur_state) print(\"%s,%s\" % (now, idle)) sys.stdout.flush() cur_state = next_state "} {"_id":"q-en-rust-8ac3bf80e88c4093868abede532757023a7d3ec5a207fb43444d2f03f699132f","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(associated_consts)] #![deny(dead_code)] // use different types / traits to test all combinations trait Const { const C: (); } trait StaticFn { fn sfn(); } struct ConstStruct; struct StaticFnStruct; enum ConstEnum {} enum StaticFnEnum {} struct AliasedConstStruct; struct AliasedStaticFnStruct; enum AliasedConstEnum {} enum AliasedStaticFnEnum {} type AliasConstStruct = AliasedConstStruct; type AliasStaticFnStruct = AliasedStaticFnStruct; type AliasConstEnum = AliasedConstEnum; type AliasStaticFnEnum = AliasedStaticFnEnum; macro_rules! impl_Const {($($T:ident),*) => {$( impl Const for $T { const C: () = (); } )*}} macro_rules! impl_StaticFn {($($T:ident),*) => {$( impl StaticFn for $T { fn sfn() {} } )*}} impl_Const!(ConstStruct, ConstEnum, AliasedConstStruct, AliasedConstEnum); impl_StaticFn!(StaticFnStruct, StaticFnEnum, AliasedStaticFnStruct, AliasedStaticFnEnum); fn main() { let _ = ConstStruct::C; let _ = ConstEnum::C; StaticFnStruct::sfn(); StaticFnEnum::sfn(); let _ = AliasConstStruct::C; let _ = AliasConstEnum::C; AliasStaticFnStruct::sfn(); AliasStaticFnEnum::sfn(); } "} {"_id":"q-en-rust-8b03aac4696597a5afa99e04df7a6aa00e9b331a038bee1bb030a419814701a9","text":"\"`{expected_ty}` does not implement `Clone`, so `{found_ty}` was cloned instead\" ), ); let owner = self.tcx.hir().enclosing_body_owner(expr.hir_id); if let ty::Param(param) = expected_ty.kind() && let Some(generics) = self.tcx.hir().get_generics(owner) { suggest_constraining_type_params( self.tcx, generics, diag, vec![(param.name.as_str(), \"Clone\", Some(clone_trait_did))].into_iter(), ); } else { self.suggest_derive(diag, &[(trait_ref.to_predicate(self.tcx), None, None)]); } } }"} {"_id":"q-en-rust-8b0d7fd164539198948d10223d7d875adeb51955aec0dadd69f587caa976e10a","text":"macro_rules! mac { ($ ($ tt : tt) *) => () } mac! { struct S { field1 : u8 , field2 : u16 , } impl Clone for S struct S { field1 : u8, field2 : u16, } impl Clone for S { fn clone () -> S {"} {"_id":"q-en-rust-8b20509d96ccf61db53373e1b42509f6466bf825f93b59c6286f18039dc2cfd0","text":"//! Unicode string slices. //! //! The `&str` type is one of the two main string types, the other being `String`. //! Unlike its `String` counterpart, its contents are borrowed. //! //! # Basic Usage //! //! A basic string declaration of `&str` type: //! //! ``` //! let hello_world = \"Hello, World!\"; //! ``` //! //! Here we have declared a string literal, also known as a string slice. //! String literals have a static lifetime, which means the string `hello_world` //! is guaranteed to be valid for the duration of the entire program. //! We can explicitly specify `hello_world`'s lifetime as well: //! //! ``` //! let hello_world: &'static str = \"Hello, world!\"; //! ``` //! //! *[See also the `str` primitive type](../../std/primitive.str.html).* #![stable(feature = \"rust1\", since = \"1.0.0\")] // Many of the usings in this module are only used in the test configuration."} {"_id":"q-en-rust-8b35b59110368adb05880f53682f667dce5c05bad77fb02e2f4e102240e92e0c","text":"#[allow(unused)] pub fn doctest_runner(bin: &std::path::Path, test_nb: usize) -> Result<(), String> {{ let out = std::process::Command::new(bin) .arg(self::RUN_OPTION) .arg(test_nb.to_string()) .env(self::RUN_OPTION, test_nb.to_string()) .args(std::env::args().skip(1).collect::>()) .output() .expect(\"failed to run command\"); if !out.status.success() {{"} {"_id":"q-en-rust-8b37259a0a2bb1a99c3e3cd11cf7231d44c73fefef5727a8ce6fd3804a3567d8","text":"let attrs = self.parse_outer_attributes()?; let lo = self.token.span; Ok(Some(if self.eat_keyword(kw::Let) { Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Local(self.parse_local(attrs.into())?), span: lo.to(self.prev_span), } } else if let Some(macro_def) = self.eat_macro_def( &attrs, &respan(lo, VisibilityKind::Inherited), lo, )? { Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Item(macro_def), span: lo.to(self.prev_span), } if self.eat_keyword(kw::Let) { let local = self.parse_local(attrs.into())?; return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Local(local)))); } let mac_vis = respan(lo, VisibilityKind::Inherited); if let Some(macro_def) = self.eat_macro_def(&attrs, &mac_vis, lo)? { return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Item(macro_def)))); } // Starts like a simple path, being careful to avoid contextual keywords // such as a union items, item with `crate` visibility or auto trait items. // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts // like a path (1 token), but it fact not a path. // `union::b::c` - path, `union U { ... }` - not a path. // `crate::b::c` - path, `crate struct S;` - not a path. } else if self.token.is_path_start() && !self.token.is_qpath_start() && !self.is_union_item() && !self.is_crate_vis() && !self.is_auto_trait_item() && !self.is_async_fn() { if self.token.is_path_start() && !self.token.is_qpath_start() && !self.is_union_item() // `union::b::c` - path, `union U { ... }` - not a path. && !self.is_crate_vis() // `crate::b::c` - path, `crate struct S;` - not a path. && !self.is_auto_trait_item() && !self.is_async_fn() { let path = self.parse_path(PathStyle::Expr)?; if !self.eat(&token::Not) { let expr = if self.check(&token::OpenDelim(token::Brace)) { self.parse_struct_expr(lo, path, ThinVec::new())? } else { let hi = self.prev_span; self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()) }; let expr = self.with_res(Restrictions::STMT_EXPR, |this| { let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?; this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) })?; return Ok(Some(Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Expr(expr), span: lo.to(self.prev_span), })); if self.eat(&token::Not) { return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings); } let args = self.parse_mac_args()?; let delim = args.delim(); let hi = self.prev_span; let style = if delim == token::Brace { MacStmtStyle::Braces let expr = if self.check(&token::OpenDelim(token::Brace)) { self.parse_struct_expr(lo, path, ThinVec::new())? } else { MacStmtStyle::NoBraces let hi = self.prev_span; self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()) }; let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription, }; let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof { StmtKind::Mac(P((mac, style, attrs.into()))) } // We used to incorrectly stop parsing macro-expanded statements here. // If the next token will be an error anyway but could have parsed with the // earlier behavior, stop parsing here and emit a warning to avoid breakage. else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token.kind { // These can continue an expression, so we can't stop parsing and warn. token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | token::BinOp(token::Minus) | token::BinOp(token::Star) | token::BinOp(token::And) | token::BinOp(token::Or) | token::AndAnd | token::OrOr | token::DotDot | token::DotDotDot | token::DotDotEq => false, _ => true, } { self.warn_missing_semicolon(); StmtKind::Mac(P((mac, style, attrs.into()))) } else { let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), ThinVec::new()); let e = self.maybe_recover_from_bad_qpath(e, true)?; let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?; let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?; StmtKind::Expr(e) }; Stmt { id: DUMMY_NODE_ID, span: lo.to(hi), kind, let expr = self.with_res(Restrictions::STMT_EXPR, |this| { let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?; this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) })?; return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr)))); } // FIXME: Bad copy of attrs let old_directory_ownership = mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock); let item = self.parse_item_(attrs.clone(), false, true)?; self.directory.ownership = old_directory_ownership; if let Some(item) = item { return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item)))); } // Do not attempt to parse an expression if we're done here. if self.token == token::Semi { self.error_outer_attrs(&attrs); self.bump(); let mut last_semi = lo; while self.token == token::Semi { last_semi = self.token.span; self.bump(); } // We are encoding a string of semicolons as an an empty tuple that spans // the excess semicolons to preserve this info until the lint stage. let kind = StmtKind::Semi(self.mk_expr( lo.to(last_semi), ExprKind::Tup(Vec::new()), ThinVec::new() )); return Ok(Some(self.mk_stmt(lo.to(last_semi), kind))); } if self.token == token::CloseDelim(token::Brace) { self.error_outer_attrs(&attrs); return Ok(None); } // Remainder are line-expr stmts. let e = self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs.into()))?; Ok(Some(self.mk_stmt(lo.to(e.span), StmtKind::Expr(e)))) } /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`. /// At this point, the `!` token after the path has already been eaten. fn parse_stmt_mac( &mut self, lo: Span, attrs: ThinVec, path: ast::Path, legacy_warnings: bool, ) -> PResult<'a, Option> { let args = self.parse_mac_args()?; let delim = args.delim(); let hi = self.prev_span; let style = if delim == token::Brace { MacStmtStyle::Braces } else { // FIXME: Bad copy of attrs let old_directory_ownership = mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock); let item = self.parse_item_(attrs.clone(), false, true)?; self.directory.ownership = old_directory_ownership; match item { Some(i) => Stmt { id: DUMMY_NODE_ID, span: lo.to(i.span), kind: StmtKind::Item(i), }, None => { let unused_attrs = |attrs: &[Attribute], s: &mut Self| { if !attrs.is_empty() { if s.prev_token_kind == PrevTokenKind::DocComment { s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit(); } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { s.span_err( s.token.span, \"expected statement after outer attribute\" ); } } }; // Do not attempt to parse an expression if we're done here. if self.token == token::Semi { unused_attrs(&attrs, self); self.bump(); let mut last_semi = lo; while self.token == token::Semi { last_semi = self.token.span; self.bump(); } // We are encoding a string of semicolons as an // an empty tuple that spans the excess semicolons // to preserve this info until the lint stage return Ok(Some(Stmt { id: DUMMY_NODE_ID, span: lo.to(last_semi), kind: StmtKind::Semi(self.mk_expr(lo.to(last_semi), ExprKind::Tup(Vec::new()), ThinVec::new() )), })); } MacStmtStyle::NoBraces }; if self.token == token::CloseDelim(token::Brace) { unused_attrs(&attrs, self); return Ok(None); } let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription, }; // Remainder are line-expr stmts. let e = self.parse_expr_res( Restrictions::STMT_EXPR, Some(attrs.into()))?; Stmt { id: DUMMY_NODE_ID, span: lo.to(e.span), kind: StmtKind::Expr(e), } } let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof { StmtKind::Mac(P((mac, style, attrs.into()))) } // We used to incorrectly stop parsing macro-expanded statements here. // If the next token will be an error anyway but could have parsed with the // earlier behavior, stop parsing here and emit a warning to avoid breakage. else if legacy_warnings && self.token.can_begin_expr() && match self.token.kind { // These can continue an expression, so we can't stop parsing and warn. token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | token::BinOp(token::Minus) | token::BinOp(token::Star) | token::BinOp(token::And) | token::BinOp(token::Or) | token::AndAnd | token::OrOr | token::DotDot | token::DotDotDot | token::DotDotEq => false, _ => true, } })) { self.warn_missing_semicolon(); StmtKind::Mac(P((mac, style, attrs))) } else { // Since none of the above applied, this is an expression statement macro. let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), ThinVec::new()); let e = self.maybe_recover_from_bad_qpath(e, true)?; let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?; let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?; StmtKind::Expr(e) }; Ok(Some(self.mk_stmt(lo.to(hi), kind))) } /// Error on outer attributes in this context. /// Also error if the previous token was a doc comment. fn error_outer_attrs(&self, attrs: &[Attribute]) { if !attrs.is_empty() { if self.prev_token_kind == PrevTokenKind::DocComment { self.span_fatal_err(self.prev_span, Error::UselessDocComment).emit(); } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { self.span_err(self.token.span, \"expected statement after outer attribute\"); } } } /// Parses a local variable declaration."} {"_id":"q-en-rust-8b415a7b02e7b4e355b480cee6542d8eb7c8e711546645e778b49b387f75ece2","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":"q-en-rust-8b58ac22b5f734e6f2924e792cec732a7941d61f084ac380688eda8ad83606fb","text":"} .example-wrap.ignore .tooltip { color: var(--codeblock-ignore-color); color: var(--codeblock-ignore-color); } .example-wrap.compile_fail:hover .tooltip,"} {"_id":"q-en-rust-8b62be820932ed3bd386b9ae4371154586907724331650605671706a73db346b","text":"Ok(pat) } /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`. /// /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs` /// should already have been parsed by now at this point, /// if the next token is `@` then we can try to parse the more general form. /// /// Consult `parse_pat_ident` for the `binding` grammar. /// /// The notion of intersection patterns are found in /// e.g. [F#][and] where they are called AND-patterns. /// /// [and]: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching fn recover_intersection_pat(&mut self, lhs: P) -> PResult<'a, P> { if self.token.kind != token::At { // Next token is not `@` so it's not going to be an intersection pattern. return Ok(lhs); } // At this point we attempt to parse `@ $pat_rhs` and emit an error. self.bump(); // `@` let mut rhs = self.parse_pat(None)?; let sp = lhs.span.to(rhs.span); if let PatKind::Ident(_, _, ref mut sub @ None) = rhs.kind { // The user inverted the order, so help them fix that. let mut applicability = Applicability::MachineApplicable; lhs.walk(&mut |p| match p.kind { // `check_match` is unhappy if the subpattern has a binding anywhere. PatKind::Ident(..) => { applicability = Applicability::MaybeIncorrect; false // Short-circuit. }, _ => true, }); let lhs_span = lhs.span; // Move the LHS into the RHS as a subpattern. // The RHS is now the full pattern. *sub = Some(lhs); self.struct_span_err(sp, \"pattern on wrong side of `@`\") .span_label(lhs_span, \"pattern on the left, should be on the right\") .span_label(rhs.span, \"binding on the right, should be on the left\") .span_suggestion(sp, \"switch the order\", pprust::pat_to_string(&rhs), applicability) .emit(); } else { // The special case above doesn't apply so we may have e.g. `A(x) @ B(y)`. rhs.kind = PatKind::Wild; self.struct_span_err(sp, \"left-hand side of `@` must be a binding\") .span_label(lhs.span, \"interpreted as a pattern, not a binding\") .span_label(rhs.span, \"also a pattern\") .note(\"bindings are `x`, `mut x`, `ref x`, and `ref mut x`\") .emit(); } rhs.span = sp; Ok(rhs) } /// Ban a range pattern if it has an ambiguous interpretation. fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> { match pat.kind {"} {"_id":"q-en-rust-8b66cb400b734924213d7be3b96e63551f315c732fbc4a38c7cb5cafb1cc7f12","text":"(removed, test_removed_feature, \"1.0.0\", None), (removed, visible_private_types, \"1.0.0\", None), (removed, unsafe_no_drop_flag, \"1.0.0\", None), // Allows using items which are missing stability attributes // rustc internal (removed, unmarked_api, \"1.0.0\", None), ); declare_features! ("} {"_id":"q-en-rust-8b73b2758c283a06d813f00704f943acda97411a0884a7bbe7ac00cd9f3f2e25","text":"} fn unindent_fragments(docs: &mut Vec) { for fragment in docs { fragment.doc = unindent(&fragment.doc); } } fn unindent(s: &str) -> String { let lines = s.lines().collect::>(); let mut saw_first_line = false; let mut saw_second_line = false; let min_indent = lines.iter().fold(usize::MAX, |min_indent, line| { // After we see the first non-whitespace line, look at // the line we have. If it is not whitespace, and therefore // part of the first paragraph, then ignore the indentation // level of the first line let ignore_previous_indents = saw_first_line && !saw_second_line && !line.chars().all(|c| c.is_whitespace()); // `add` is used in case the most common sugared doc syntax is used (\"/// \"). The other // fragments kind's lines are never starting with a whitespace unless they are using some // markdown formatting requiring it. Therefore, if the doc block have a mix between the two, // we need to take into account the fact that the minimum indent minus one (to take this // whitespace into account). // // For example: // // /// hello! // #[doc = \"another\"] // // In this case, you want \"hello! another\" and not \"hello! another\". let add = if docs.windows(2).any(|arr| arr[0].kind != arr[1].kind) && docs.iter().any(|d| d.kind == DocFragmentKind::SugaredDoc) { // In case we have a mix of sugared doc comments and \"raw\" ones, we want the sugared one to // \"decide\" how much the minimum indent will be. 1 } else { 0 }; let min_indent = if ignore_previous_indents { usize::MAX } else { min_indent }; // `min_indent` is used to know how much whitespaces from the start of each lines must be // removed. Example: // // /// hello! // #[doc = \"another\"] // // In here, the `min_indent` is 1 (because non-sugared fragment are always counted with minimum // 1 whitespace), meaning that \"hello!\" will be considered a codeblock because it starts with 4 // (5 - 1) whitespaces. let min_indent = match docs .iter() .map(|fragment| { fragment.doc.lines().fold(usize::MAX, |min_indent, line| { if line.chars().all(|c| c.is_whitespace()) { min_indent } else { // Compare against either space or tab, ignoring whether they are // mixed or not. let whitespace = line.chars().take_while(|c| *c == ' ' || *c == 't').count(); cmp::min(min_indent, whitespace) + if fragment.kind == DocFragmentKind::SugaredDoc { 0 } else { add } } }) }) .min() { Some(x) => x, None => return, }; if saw_first_line { saw_second_line = true; for fragment in docs { if fragment.doc.lines().count() == 0 { continue; } if line.chars().all(|c| c.is_whitespace()) { min_indent let min_indent = if fragment.kind != DocFragmentKind::SugaredDoc && min_indent > 0 { min_indent - add } else { saw_first_line = true; let mut whitespace = 0; line.chars().all(|char| { // Compare against either space or tab, ignoring whether they // are mixed or not if char == ' ' || char == 't' { whitespace += 1; true min_indent }; fragment.doc = fragment .doc .lines() .map(|line| { if line.chars().all(|c| c.is_whitespace()) { line.to_string() } else { false assert!(line.len() >= min_indent); line[min_indent..].to_string() } }); cmp::min(min_indent, whitespace) } }); if !lines.is_empty() { let mut unindented = vec![lines[0].trim_start().to_string()]; unindented.extend_from_slice( &lines[1..] .iter() .map(|&line| { if line.chars().all(|c| c.is_whitespace()) { line.to_string() } else { assert!(line.len() >= min_indent); line[min_indent..].to_string() } }) .collect::>(), ); unindented.join(\"n\") } else { s.to_string() }) .collect::>() .join(\"n\"); } }"} {"_id":"q-en-rust-8b9336c0a7aab7d79a1263e5fdd4abaa8ffcff3ef707fe386d529204dc424e6f","text":"} None => { check_expr_has_type(fcx, &idx, fcx.tcx().types.err); fcx.type_error_message( let mut err = fcx.type_error_struct( expr.span, |actual| { format!(\"cannot index a value of type `{}`\","} {"_id":"q-en-rust-8b981f7cc91e5d6d21fe1600ac0becd287770a6f96708644569deaba54a1faea","text":"version = \"0.6.0\" dependencies = [ \"clippy_lints\", \"env_logger 0.7.1\", \"env_logger 0.9.0\", \"futures 0.3.12\", \"log\", \"rand 0.7.3\", \"rand 0.8.4\", \"rls-data\", \"rls-ipc\", \"serde\","} {"_id":"q-en-rust-8bcbda56104edc5078582ff7c2e72c90a938cb9771dc46356b113f653ee82ddc","text":" use crate::infer::outlives::components::{compute_components_recursive, Component}; use crate::infer::outlives::components::{compute_alias_components_recursive, Component}; use crate::infer::outlives::env::RegionBoundPairs; use crate::infer::region_constraints::VerifyIfEq; use crate::infer::VerifyBound;"} {"_id":"q-en-rust-8bea5298227f535c7138e47487800bc28c4a908a50632b650288122e375e4fc4","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-prefer-dynamic #[crate_id = \"collections#0.10-pre\"]; #[crate_type = \"rlib\"]; "} {"_id":"q-en-rust-8c0d892694a97ef4e55cd5e8ecede5de0a1689f41d60e84f574880dd0567d497","text":"} #[inline] fn fold(self, init: Acc, f: F) -> Acc where F: FnMut(Acc, Self::Item) -> Acc, { ZipImpl::fold(self, init, f) } #[inline] unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item where Self: TrustedRandomAccessNoCoerce,"} {"_id":"q-en-rust-8c56028b31a52f73ad55dc9b194d6930eef43b588dfe8dfdef11d46a2548dcc3","text":"/// # Examples /// /// ``` /// #![feature(osstring_ascii)] /// use std::ffi::OsString; /// /// assert!(OsString::from(\"Ferris\").eq_ignore_ascii_case(\"FERRIS\")); /// assert!(OsString::from(\"Ferrös\").eq_ignore_ascii_case(\"FERRöS\")); /// assert!(!OsString::from(\"Ferrös\").eq_ignore_ascii_case(\"FERRÖS\")); /// ``` #[unstable(feature = \"osstring_ascii\", issue = \"70516\")] #[stable(feature = \"osstring_ascii\", since = \"1.53.0\")] pub fn eq_ignore_ascii_case>(&self, other: S) -> bool { self.inner.eq_ignore_ascii_case(&other.as_ref().inner) }"} {"_id":"q-en-rust-8c60afcd91fa6d072b9779b673991e4d4824c343b5058e9d9971f3a25b6e10ac","text":"let outdir = if let Some(mut path) = rustdoc_options.persist_doctests.clone() { path.push(&test_id); std::fs::create_dir_all(&path) .expect(\"Couldn't create directory for doctest executables\"); if let Err(err) = std::fs::create_dir_all(&path) { eprintln!(\"Couldn't create directory for doctest executables: {}\", err); panic::resume_unwind(box ()); } DirState::Perm(path) } else {"} {"_id":"q-en-rust-8c6b89969089f1546aa3e8593a52fa98f5ba2b2308c01af48e186e0280214f7b","text":"for (hir, ty) in hir_sig.inputs.iter().zip(ty_sig.inputs().iter()) { try_visit!(visitor.visit(hir.span, ty.map_bound(|x| *x))); } for (pred, span) in tcx.predicates_of(item).instantiate_identity(tcx) { for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { try_visit!(visitor.visit(span, pred)); } }"} {"_id":"q-en-rust-8c8c5c20cb6134013f5b0d58c3be0100d0caa8493ba543d42cf87de6ce22f5fc","text":"let op = ecx.eval_const_to_op(val, None).unwrap(); ecx.read_discriminant(op).unwrap().1 } /// Turn an interpreter error into something to report to the user. /// As a side-effect, if RUSTC_CTFE_BACKTRACE is set, this prints the backtrace. /// Should be called only if the error is actually going to to be reported! pub fn error_to_const_error<'mir, 'tcx, M: Machine<'mir, 'tcx>>( ecx: &InterpCx<'mir, 'tcx, M>, mut error: InterpErrorInfo<'tcx>, ) -> ConstEvalErr<'tcx> { error.print_backtrace(); let stacktrace = ecx.generate_stacktrace(None); ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span } } pub fn note_on_undefined_behavior_error() -> &'static str { \"The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.\" } fn validate_and_turn_into_const<'tcx>( tcx: TyCtxt<'tcx>, constant: RawConst<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> { let cid = key.value; let def_id = cid.instance.def.def_id(); let is_static = tcx.is_static(def_id); let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static); let val = (|| { let mplace = ecx.raw_const_to_mplace(constant)?; let mut ref_tracking = RefTracking::new(mplace); while let Some((mplace, path)) = ref_tracking.todo.pop() { ecx.validate_operand(mplace.into(), path, Some(&mut ref_tracking))?; } // Now that we validated, turn this into a proper constant. // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides // whether they become immediates. if is_static || cid.promoted.is_some() { let ptr = mplace.ptr.to_ptr()?; Ok(tcx.mk_const(ty::Const { val: ty::ConstKind::Value(ConstValue::ByRef { alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id), offset: ptr.offset, }), ty: mplace.layout.ty, })) } else { Ok(op_to_const(&ecx, mplace.into())) } })(); val.map_err(|error| { let err = error_to_const_error(&ecx, error); match err.struct_error(ecx.tcx, \"it is undefined behavior to use this value\") { Ok(mut diag) => { diag.note(note_on_undefined_behavior_error()); diag.emit(); ErrorHandled::Reported } Err(err) => err, } }) } pub fn const_eval_validated_provider<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> { // see comment in const_eval_raw_provider for what we're doing here if key.param_env.reveal == Reveal::All { let mut key = key.clone(); key.param_env.reveal = Reveal::UserFacing; match tcx.const_eval_validated(key) { // try again with reveal all as requested Err(ErrorHandled::TooGeneric) => { // Promoteds should never be \"too generic\" when getting evaluated. // They either don't get evaluated, or we are in a monomorphic context assert!(key.value.promoted.is_none()); } // dedupliate calls other => return other, } } // We call `const_eval` for zero arg intrinsics, too, in order to cache their value. // Catch such calls and evaluate them instead of trying to load a constant's MIR. if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def { let ty = key.value.instance.ty(tcx); let substs = match ty.kind { ty::FnDef(_, substs) => substs, _ => bug!(\"intrinsic with type {:?}\", ty), }; return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| { let span = tcx.def_span(def_id); let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span }; error.report_as_error(tcx.at(span), \"could not evaluate nullary intrinsic\") }); } tcx.const_eval_raw(key).and_then(|val| validate_and_turn_into_const(tcx, val, key)) } pub fn const_eval_raw_provider<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> { // Because the constant is computed twice (once per value of `Reveal`), we are at risk of // reporting the same error twice here. To resolve this, we check whether we can evaluate the // constant in the more restrictive `Reveal::UserFacing`, which most likely already was // computed. For a large percentage of constants that will already have succeeded. Only // associated constants of generic functions will fail due to not enough monomorphization // information being available. // In case we fail in the `UserFacing` variant, we just do the real computation. if key.param_env.reveal == Reveal::All { let mut key = key.clone(); key.param_env.reveal = Reveal::UserFacing; match tcx.const_eval_raw(key) { // try again with reveal all as requested Err(ErrorHandled::TooGeneric) => {} // dedupliate calls other => return other, } } if cfg!(debug_assertions) { // Make sure we format the instance even if we do not print it. // This serves as a regression test against an ICE on printing. // The next two lines concatenated contain some discussion: // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/ // subject/anon_const_instance_printing/near/135980032 let instance = key.value.instance.to_string(); trace!(\"const eval: {:?} ({})\", key, instance); } let cid = key.value; let def_id = cid.instance.def.def_id(); if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors { return Err(ErrorHandled::Reported); } let is_static = tcx.is_static(def_id); let span = tcx.def_span(cid.instance.def_id()); let mut ecx = InterpCx::new( tcx.at(span), key.param_env, CompileTimeInterpreter::new(), MemoryExtra { can_access_statics: is_static }, ); let res = ecx.load_mir(cid.instance.def, cid.promoted); res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, *body)) .and_then(|place| { Ok(RawConst { alloc_id: place.ptr.assert_ptr().alloc_id, ty: place.layout.ty }) }) .map_err(|error| { let err = error_to_const_error(&ecx, error); // errors in statics are always emitted as fatal errors if is_static { // Ensure that if the above error was either `TooGeneric` or `Reported` // an error must be reported. let v = err.report_as_error(ecx.tcx, \"could not evaluate static initializer\"); tcx.sess.delay_span_bug( err.span, &format!(\"static eval failure did not emit an error: {:#?}\", v), ); v } else if def_id.is_local() { // constant defined in this crate, we can figure out a lint level! match tcx.def_kind(def_id) { // constants never produce a hard error at the definition site. Anything else is // a backwards compatibility hazard (and will break old versions of winapi for sure) // // note that validation may still cause a hard error on this very same constant, // because any code that existed before validation could not have failed validation // thus preventing such a hard error from being a backwards compatibility hazard Some(DefKind::Const) | Some(DefKind::AssocConst) => { let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); err.report_as_lint( tcx.at(tcx.def_span(def_id)), \"any use of this value will cause an error\", hir_id, Some(err.span), ) } // promoting runtime code is only allowed to error if it references broken constants // any other kind of error will be reported to the user as a deny-by-default lint _ => { if let Some(p) = cid.promoted { let span = tcx.promoted_mir(def_id)[p].span; if let err_inval!(ReferencedConstant) = err.error { err.report_as_error( tcx.at(span), \"evaluation of constant expression failed\", ) } else { err.report_as_lint( tcx.at(span), \"reaching this expression at runtime will panic or abort\", tcx.hir().as_local_hir_id(def_id).unwrap(), Some(err.span), ) } // anything else (array lengths, enum initializers, constant patterns) are reported // as hard errors } else { err.report_as_error(ecx.tcx, \"evaluation of constant value failed\") } } } } else { // use of broken constant from other crate err.report_as_error(ecx.tcx, \"could not evaluate constant\") } }) } "} {"_id":"q-en-rust-8cc46e6a97ca7e55a6f01b495ecf087dc00e675c76ca571a002b1b20410202c3","text":"use rustc_errors::Applicability; use rustc_hir as hir; use rustc_middle::ty::subst::InternalSubsts; use rustc_middle::ty::{Ref, Ty}; use rustc_middle::ty::{Adt, Ref, Ty}; use rustc_session::lint::builtin::RUST_2021_PRELUDE_COLLISIONS; use rustc_span::symbol::kw::Underscore; use rustc_span::symbol::{sym, Ident};"} {"_id":"q-en-rust-8ce6b63be8d9c68af8f0112a4aa04cb73ed1a0c8db4836cbf9fa0d9f11837fa2","text":"let out = cargo.output() .expect(\"We already ran `cargo miri setup` before and that worked\"); assert!(out.status.success(), \"`cargo miri setup` returned with non-0 exit code\"); // Output is \"MIRI_SYSROOT=n\". // Output is \"n\". let stdout = String::from_utf8(out.stdout) .expect(\"`cargo miri setup` stdout is not valid UTF-8\"); let stdout = stdout.trim(); builder.verbose(&format!(\"`cargo miri setup --env` returned: {:?}\", stdout)); let sysroot = stdout.splitn(2, '=') .nth(1).expect(\"`cargo miri setup` stdout did not contain '='\"); let sysroot = stdout.trim_end(); builder.verbose(&format!(\"`cargo miri setup --print-sysroot` said: {:?}\", sysroot)); sysroot.to_owned() };"} {"_id":"q-en-rust-8cf298058a790aace42076ee75f34a613f786aabcfa289523f580e479f6f73f4","text":"set -ex source shared.sh curl https://www.python.org/ftp/python/3.9.1/Python-3.9.1.tgz | curl https://www.python.org/ftp/python/2.7.12/Python-2.7.12.tgz | tar xzf - mkdir python-build"} {"_id":"q-en-rust-8d02c01b6a2d1bdbd368087578ed4f1cb334314c0ecad8e94f05946c490782ce","text":"fn main() { let o = Obj { closure: || 42 }; o.closure(); //~ ERROR no method named `closure` found //~^ NOTE use `(s.closure)(...)` if you meant to call the function stored in the `closure` field //~^ NOTE use `(o.closure)(...)` if you meant to call the function stored in the `closure` field }"} {"_id":"q-en-rust-8d078763b07a98b63648b63a595870780a02cab2089540811fb5b08bb1148685","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":"q-en-rust-8d1a8222365b7d06559cb2b2a891dab975457c8df80178a46564de21ffe9bf60","text":" error: invalid format string: tuple index access isn't supported --> $DIR/format-args-non-identifier-diagnostics.rs:8:16 | LL | println!(\"{x.0}\"); | ^^^ not supported in format string | help: consider using a positional formatting argument instead | LL | println!(\"{0}\", x.0); | ~ +++++ error: aborting due to 1 previous error "} {"_id":"q-en-rust-8d2861a8f4d4bb11a3f3c65dbe841c6a05173704c144735d92727866f9094b6b","text":"} ``` Any type parameter of an `impl` must meet at least one of the following criteria: Any type or const parameter of an `impl` must meet at least one of the following criteria: - it appears in the _implementing type_ of the impl, e.g. `impl Foo` - for a trait impl, it appears in the _implemented trait_, e.g."} {"_id":"q-en-rust-8d359bf3491de3bd1700809ebce554f844c4026e6a76c609a7e0cc9a24510fa1","text":"self.constraint_sccs.as_ref() } /// Returns whether the given SCC is live at all points: whether the representative is a /// Access to the region graph, built from the outlives constraints. pub(crate) fn region_graph(&self) -> RegionGraph<'_, 'tcx, graph::Normal> { self.constraint_graph.region_graph(&self.constraints, self.universal_regions.fr_static) } /// Returns whether the given region is considered live at all points: whether it is a /// placeholder or a free region. pub(crate) fn scc_is_live_at_all_points(&self, scc: ConstraintSccIndex) -> bool { pub(crate) fn is_region_live_at_all_points(&self, region: RegionVid) -> bool { // FIXME: there must be a cleaner way to find this information. At least, when // higher-ranked subtyping is abstracted away from the borrowck main path, we'll only // need to check whether this is a universal region. let representative = self.scc_representatives[scc]; let origin = self.var_infos[representative].origin; let origin = self.region_definition(region).origin; let live_at_all_points = matches!( origin, RegionVariableOrigin::Nll( NllRegionVariableOrigin::Placeholder(_) | NllRegionVariableOrigin::FreeRegion ) NllRegionVariableOrigin::Placeholder(_) | NllRegionVariableOrigin::FreeRegion ); live_at_all_points }"} {"_id":"q-en-rust-8d4d32787170c3ac2497444f98dd700835794cbde8f9b87560cd617130d0903e","text":" // aux-build:through-proc-macro-aux.rs // build-aux-docs #![warn(intra_doc_link_resolution_failure)] extern crate some_macros; #[some_macros::second] pub enum Boom { /// [Oooops] Bam, } fn main() {} "} {"_id":"q-en-rust-8d6fafda6f27413c6cd7bdd100981eb8955dd9aad9524c5f8bd03554db557ebd","text":" warning: the feature `dyn_star` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/dyn-star-to-dyn.rs:3:12 | LL | #![feature(dyn_star)] | ^^^^^^^^ | = note: see issue #102425 for more information = note: `#[warn(incomplete_features)]` on by default warning: 1 warning emitted "} {"_id":"q-en-rust-8d741a16dfb96b75c3cfd192a24f5061af05ba5c3e52178b02fed41d93e3d13b","text":"span } = *self; hcx.hash_hir_item_like(attrs, |hcx| { let is_const = match *node { hir::ImplItemKind::Const(..) | hir::ImplItemKind::Type(..) => true, hir::ImplItemKind::Method(hir::MethodSig { constness, .. }, _) => { constness == hir::Constness::Const } }; hcx.hash_hir_item_like(attrs, is_const, |hcx| { name.hash_stable(hcx, hasher); vis.hash_stable(hcx, hasher); defaultness.hash_stable(hcx, hasher);"} {"_id":"q-en-rust-8d80eaed92d4f217b572add154eb183b72141a975d5fd7445481057ee55fee06","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":"q-en-rust-8de0ab24807adf19b56fdbc53099e747a3927de8a370d0b4cf1d3e824ad0a94e","text":"pub type _Unwind_Ptr = uintptr_t; pub type _Unwind_Trace_Fn = extern \"C\" fn(ctx: *mut _Unwind_Context, arg: *mut c_void) -> _Unwind_Reason_Code; #[cfg(target_arch = \"x86\")] pub const unwinder_private_data_size: usize = 5;"} {"_id":"q-en-rust-8df85a01ffad7f164b437af7a462a5f925462f125ddf957b84b6ed657506eb89","text":"trait_ref: ty::TraitRef<'tcx>, impl_def_id: LocalDefId, ) { assert_eq!(trait_ref.args.len(), 1); if trait_ref.args.len() != 1 { tcx.sess.diagnostic().delay_span_bug( tcx.def_span(impl_def_id), \"auto traits cannot have generic parameters\", ); return; } let self_ty = trait_ref.self_ty(); let (self_type_did, args) = match self_ty.kind() { ty::Adt(def, args) => (def.did(), args),"} {"_id":"q-en-rust-8e367eb26aae5f458313750f84aecffcff85e8c3841ddd288b884f61e626b7db","text":" // no-prefer-dynamic // This would previously leak the Box because we wouldn't // schedule cleanups when auto borrowing trait objects. // This program should be valgrind clean."} {"_id":"q-en-rust-8e36afee3a0426ce381e92fe315864c1db3f9c0c3fe12a443c27df154518ed3e","text":"break; case \"+\": ev.preventDefault(); expandAllDocs(); break; case \"-\": ev.preventDefault(); toggleAllDocs(); collapseAllDocs(); break; case \"?\":"} {"_id":"q-en-rust-8e3e9347189dd647658f65d91d1398af731f686537bef2c942bb4ff05ed0f6ab","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":"q-en-rust-8e520fd9d441a2c53c3a1f0d6ba548748b4bc67780b711ed1bfc08d4daa86195","text":"# These arguments get passed through to GDB and make it load the # Rust pretty printers. GDB_ARGS=\"--directory=\"$GDB_PYTHON_MODULE_DIRECTORY\" -iex \"add-auto-load-safe-path $GDB_PYTHON_MODULE_DIRECTORY\"\" GDB_ARGS=\"--directory=\"$GDB_PYTHON_MODULE_DIRECTORY\"\" \"-iex \"add-auto-load-safe-path $GDB_PYTHON_MODULE_DIRECTORY\"\" \"-iex \"set substitute-path /rustc/$RUSTC_COMMIT_HASH $RUSTC_SYSROOT/lib/rustlib/src/rust\"\" # Finally we execute gdbgui. PYTHONPATH=\"$PYTHONPATH:$GDB_PYTHON_MODULE_DIRECTORY\" "} {"_id":"q-en-rust-8e54fb835952cba04d9f26114e53a16a66d587863929647b1860c9b87776522a","text":"pub type PolyTraitPredicate<'tcx> = ty::Binder<'tcx, TraitPredicate<'tcx>>; impl<'tcx> TraitPredicate<'tcx> { pub fn remap_constness(&mut self, tcx: TyCtxt<'tcx>, param_env: &mut ParamEnv<'tcx>) { if unlikely!(Some(self.trait_ref.def_id) == tcx.lang_items().drop_trait()) { // remap without changing constness of this predicate. // this is because `T: ~const Drop` has a different meaning to `T: Drop` param_env.remap_constness_with(self.constness) } else { *param_env = param_env.with_constness(self.constness.and(param_env.constness())) } } pub fn def_id(self) -> DefId { self.trait_ref.def_id }"} {"_id":"q-en-rust-8e7d588baa841a358711e7a0f00bf602dcc0f388db1f95a76a14cb1a6cab8880","text":"until the stack is unwound and the task transitions to the *dead* state. There is no way to \"recover\" from task failure. Once a task has temporarily suspended its unwinding in the *failing* state, failure occurring from within this destructor results in *hard* failure. The unwinding procedure of hard failure frees resources but does not execute destructors. The original (soft) failure is still resumed at the point where it was temporarily suspended. occurring from within this destructor results in *hard* failure. A hard failure currently results in the process aborting. A task in the *dead* state cannot transition to other states; it exists only to have its termination status inspected by other tasks, and/or to await"} {"_id":"q-en-rust-8ee04a00421454b1dd1757e4caf603b7904c6f6d066b5538c9030e3071821ccf","text":"/// all files in a directory and updating the stamp if any are newer. fn update_mtime(path: &Path) { let mut max = None; if let Ok(entries) = path.parent().unwrap().read_dir() { if let Ok(entries) = path.parent().unwrap().join(\"deps\").read_dir() { for entry in entries.map(|e| t!(e)) { if t!(entry.file_type()).is_file() { let meta = t!(entry.metadata());"} {"_id":"q-en-rust-8f0a0a5121c7cf0370b19686ee0fd6cc9984fa17ff9d8f8e242d470cb4653a8f","text":"req_name: ReqName, ret_allow_plus: AllowPlus, ) -> PResult<'a, P> { let inputs = self.parse_fn_params(req_name)?; let output = self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?; if let ast::FnRetTy::Ty(ty) = &output { if let TyKind::Path(_, Path { segments, .. }) = &ty.kind { if let [.., last] = &segments[..] { // Detect and recover `fn foo() -> Vec> {}` self.check_trailing_angle_brackets(last, &[&token::OpenDelim(token::Brace)]); } } } Ok(P(FnDecl { inputs, output })) Ok(P(FnDecl { inputs: self.parse_fn_params(req_name)?, output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes)?, })) } /// Parses the parameter list of a function, including the `(` and `)` delimiters."} {"_id":"q-en-rust-8f680acb33d2428fa3491d2b1a8352e74fd5c2702ca8f239e17c3e1d9e1ccb81","text":"children.iter() .map(|sub| self.get_multispan_max_line_num(&sub.span)) .max() .unwrap_or(primary) .unwrap_or(0) .max(primary) } /// Adds a left margin to every line but the first, given a padding length and the label being"} {"_id":"q-en-rust-8f6aa14951294b9b5e61325734e4242bb1be9a1352ea2ebb6ce9bc0f92d5946f","text":" fn main() { [(); &(&'static: loop { |x| {}; }) as *const _ as usize] //~^ ERROR: invalid label name `'static` //~| ERROR: type annotations needed } "} {"_id":"q-en-rust-8f740c1cf32df34d872b61cef615cc9cf1997b7a3cf1a58a329fb9b288646a38","text":"trait_id: DefId, ty_params: &[GenericArg<'tcx>], ) -> bool { // Do not check on infer_types to avoid panic in evaluate_obligation. if ty.has_infer_types() { return false; } let ty = cx.tcx.erase_regions(&ty); let ty_params = cx.tcx.mk_substs(ty_params.iter()); cx.tcx.type_implements_trait((trait_id, ty, ty_params, cx.param_env)) }"} {"_id":"q-en-rust-8fa9b58a2688bc2e58a2ac23de2b9199e36bc4405ae0d5c5f38e72e2f522b1a3","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":"q-en-rust-8fc9ed15cad4eb1ba962f9420a912a08a479af9b960f795f7761c26d5c357b04","text":"\"llvm-ar\", // used for creating and modifying archive files ]; pub const VERSION: usize = 2; /// A structure representing a Rust compiler. /// /// Each compiler has a `stage` that it is associated with and a `host` that"} {"_id":"q-en-rust-8fe75fbb11c04942f7d65cded5756fd3387a3556d61e0a1e5acb5930fcd41ab9","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":"q-en-rust-8fed197e24919e15f03522e7c5c292f058e2f8b0c29d1c17ce88bb9e00857192","text":" mod a { mod b { mod c { pub struct E; } mod d { #[derive(Debug)] pub struct E; } pub use self::d::*; pub use self::c::*; } pub use self::b::*; } use self::a::E::in_exist; //~^ ERROR: unresolved import `self::a::E` //~| WARNING: `E` is ambiguous //~| WARNING: 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":"q-en-rust-900c21d11b8180646a1d67a033d12dd332510e071d00c103df858b55d60f64c4","text":"use crate::{ fmt, intrinsics::transmute_unchecked, iter::{self, ExactSizeIterator, FusedIterator, TrustedLen}, iter::{self, ExactSizeIterator, FusedIterator, TrustedLen, TrustedRandomAccessNoCoerce}, mem::MaybeUninit, ops::{IndexRange, Range}, ptr,"} {"_id":"q-en-rust-90eeb4d13cc82ed630dd97df238f3121d4175f6de24eb9a59e07c23c498344a9","text":"infer::Reborrow(span) => { RegionOriginNote::Plain { span, msg: fluent::infer_reborrow }.add_to_diagnostic(err) } infer::ReborrowUpvar(span, ref upvar_id) => { let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id); RegionOriginNote::WithName { span, msg: fluent::infer_reborrow, name: &var_name.to_string(), continues: false, } .add_to_diagnostic(err); } infer::RelateObjectBound(span) => { RegionOriginNote::Plain { span, msg: fluent::infer_relate_object_bound } .add_to_diagnostic(err);"} {"_id":"q-en-rust-91095adab7b3564b9c44fe3f054907fa41d6f1bf1eb94ea3885232df0e48df45","text":"/// A hacky variant of `canonicalize_query` that does not /// canonicalize `'static`. Unfortunately, the existing leak /// check treaks `'static` differently in some cases (see also /// check treats `'static` differently in some cases (see also /// #33684), so if we are performing an operation that may need to /// prove \"leak-check\" related things, we leave `'static` /// alone. /// /// `'static` is also special cased when winnowing candidates when /// selecting implementation candidates, so we also have to leave `'static` /// alone for queries that do selection. // // FIXME(#48536): once we have universes, we can remove this and just use // `canonicalize_query`. // FIXME(#48536): once the above issues are resolved, we can remove this // and just use `canonicalize_query`. pub fn canonicalize_hr_query_hack( &self, value: &V,"} {"_id":"q-en-rust-913b924d08ab95180410bc756bf2a66b464f2f170ad8c636d2f29347ad1e47e2","text":"#![feature(associated_type_bounds)] #![feature(binary_heap_into_iter_sorted)] #![feature(binary_heap_drain_sorted)] #![feature(vec_remove_item)] use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher};"} {"_id":"q-en-rust-9149a8334bf96711483d753411c4bbf57175d981daa3ca2cc442c67a4ede7dab","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":"q-en-rust-915991533ca293db58eb2de9c8c5d3e576cae9f3c9108f2cd2bb71351781f174","text":"sess.abort_if_errors(); } // Clean up on Darwin if sess.targ_cfg.os == abi::OsMacos { // On OSX, debuggers needs this utility to get run to do some munging of the // symbols if sess.targ_cfg.os == abi::OsMacos && sess.opts.debuginfo { // FIXME (#9639): This needs to handle non-utf8 paths run::process_status(\"dsymutil\", [output.as_str().unwrap().to_owned()]); }"} {"_id":"q-en-rust-915c9a2973d1864c4d78fecd55efdeb2f3cafc35584cbbe7774339ffb97b5ad6","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":"q-en-rust-9187981ff5e1d38eedf1f31dd4ced54d92cd72d7065c73e326e350a7361f5a4b","text":"/// Ok(()) /// } /// ``` #[unstable(feature = \"rw_exact_all_at\", issue = \"51984\")] #[stable(feature = \"rw_exact_all_at\", since = \"1.33.0\")] fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> { while !buf.is_empty() { match self.write_at(buf, offset) {"} {"_id":"q-en-rust-919d37b11c0dac3bc6be49c434baf386362ef5e4d1b03df366b2d770b469ef9e","text":"#[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":"q-en-rust-91a85ceaf85c65e6590b1d09ad37e379284f866bfeaa567faac5939bb6676d36","text":"base.cpu = \"yonah\".to_string(); base.max_atomic_width = Some(64); base.pre_link_args.insert(LinkerFlavor::Gcc, vec![\"-m32\".to_string()]); base.link_env.extend(super::apple_base::macos_link_env(\"i686\")); base.link_env_remove.extend(super::apple_base::macos_link_env_remove()); // don't use probe-stack=inline-asm until rust#83139 and rust#84667 are resolved base.stack_probes = StackProbeType::Call;"} {"_id":"q-en-rust-91bfaa0e19aa1dce8663b511d0dcbfdb34be1f005f038a9f74fe09782a293123","text":".push((myname, Some(plain_summary_line(item.doc_value())))); } for (_, items) in &mut map { items.sort(); if self.shared.sort_modules_alphabetically { for (_, items) in &mut map { items.sort(); } } map }"} {"_id":"q-en-rust-91c57892952a57b61d28e31d78f1bd582db9f35fa43d4e185714ec53ce640ad7","text":"[tlgba]: http://tomlee.co/2014/04/a-more-detailed-tour-of-the-rust-compiler/ [ro]: http://www.rustaceans.org/ [rctd]: ./src/test/COMPILER_TESTS.md [cheatsheet]: https://buildbot.rust-lang.org/homu/ [cheatsheet]: https://buildbot2.rust-lang.org/homu/ "} {"_id":"q-en-rust-91f49dffdd4e1ff4d8933acb527fce63a4a62364e73efe61f80eb4b4024e3428","text":" Subproject commit 2adc39f27b7fd2d06b3d1d470827928766731a1d Subproject commit fccb2398248802a268fcda544ff3945247ef2119 "} {"_id":"q-en-rust-91f4c17bd13b986427277f5b63cb3255d9082c35cb64c1cc0b81e90f6b56856e","text":"#[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":"q-en-rust-922ea34f9e71c5e08bf2a47a307c03a2d8436c75b3c239348e8ecf173251848c","text":" // Rustdoc shouldn't display `mut` in function arguments, which are // implementation details. Regression test for #81289. #![crate_name = \"foo\"] pub struct Foo; // @count foo/struct.Foo.html '//*[@class=\"impl-items\"]//*[@class=\"method\"]' 2 // @!has - '//*[@class=\"impl-items\"]//*[@class=\"method\"]' 'mut' impl Foo { pub fn foo(mut self) {} pub fn bar(mut bar: ()) {} } // @count foo/fn.baz.html '//*[@class=\"rust fn\"]' 1 // @!has - '//*[@class=\"rust fn\"]' 'mut' pub fn baz(mut foo: Foo) {} "} {"_id":"q-en-rust-92947bd6a9d8e2e13966a8cc87259d68072d2bacde3301923b9fb2b29d7c544f","text":"// As a result 16 was chosen here! Mostly because it was a power of 2 // and most benchmarks agreed it was roughly a local optimum. Not very // scientific. match self.opts.optimize { config::OptLevel::No => 16, _ => 1, // FIXME(#46346) this should be 16 } 16 } /// Returns whether ThinLTO is enabled for this compilation"} {"_id":"q-en-rust-92d00a4e02287557f04b48af9c33de1f4a7ad047708f8b9d77d994c0d88ccb73","text":" #![feature(extern_types)] pub mod aaaaaaa { extern { pub type MyForeignType; } impl MyForeignType { pub fn my_method() {} } } "} {"_id":"q-en-rust-92fa67275f9e6ab1b881332f6c5c65fdd66983f1a3b9d035b886f85d6523d5bc","text":" error: mismatched closing delimiter: `}` --> $DIR/mismatched-delimiter-corner-case-issue-127868.rs:4:42 | LL | fn main() { | - closing delimiter possibly meant for this LL | let a = [[[[[[[[[[[[[[[[[[[[1, {, (, [,; | ^ unclosed delimiter LL | } | ^ mismatched closing delimiter error: this file contains an unclosed delimiter --> $DIR/mismatched-delimiter-corner-case-issue-127868.rs:6:52 | LL | fn main() { | - unclosed delimiter LL | let a = [[[[[[[[[[[[[[[[[[[[1, {, (, [,; | ----- - this delimiter might not be properly closed... | ||||| | ||||another 16 unclosed delimiters begin from here | |||unclosed delimiter | ||unclosed delimiter | |unclosed delimiter | unclosed delimiter LL | } | - ...as it matches this but it has different indentation LL | | ^ error: aborting due to 2 previous errors "} {"_id":"q-en-rust-9328ed706a19015ba19e0cbade6cf72b0d3baf89e3873b119dd99adf1f065e6a","text":" error[E0573]: expected type, found variant `Ok` --> $DIR/issue-106062.rs:15:64 | LL | async fn connection_handler(handler: impl Sized) -> Result { | ^^ not a type | help: try using the variant's enum | LL | async fn connection_handler(handler: impl Sized) -> Result { | ~~~~~~~~~~~~~~~~~~~~ LL | async fn connection_handler(handler: impl Sized) -> Result { | ~~~~~~~~~~~~~~~~~~~ error: aborting due to previous error For more information about this error, try `rustc --explain E0573`. "} {"_id":"q-en-rust-9338e302fcf9a02a3bf3f105ef05c1f66ab60137a4e9e92324338e01202d0158","text":"#![feature(const_caller_location)] #![feature(const_cell_into_inner)] #![feature(const_discriminant)] #![cfg_attr(not(bootstrap), feature(const_eval_select))] #![feature(const_float_bits_conv)] #![feature(const_float_classify)] #![feature(const_fmt_arguments_new)]"} {"_id":"q-en-rust-933be2c68e5a4d12595935cf7327baaf42fed835129a8566f8929f9b11111b4f","text":" // no-prefer-dynamic // ignore-emscripten thread_local!(static FOO: Foo = Foo);"} {"_id":"q-en-rust-937a925cc2ed0945d5b11512a4fdad8ee0083162ab0d67190766b5e994149648","text":"/// that were given to the `panic!()` macro. /// /// See [`PanicInfo::message`]. #[unstable(feature = \"panic_info_message\", issue = \"66745\")] #[stable(feature = \"panic_info_message\", since = \"CURRENT_RUSTC_VERSION\")] pub struct PanicMessage<'a> { message: fmt::Arguments<'a>, }"} {"_id":"q-en-rust-93aba413ad51db43753d1e2e4280d8b3009727bd238950c1597d091724853ad5","text":" // force-host // no-prefer-dynamic #![crate_type = \"proc-macro\"] #![crate_name=\"some_macros\"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_attribute] pub fn first(_attr: TokenStream, item: TokenStream) -> TokenStream { item // This doesn't erase the spans. } #[proc_macro_attribute] pub fn second(_attr: TokenStream, item: TokenStream) -> TokenStream { // Make a new `TokenStream` to erase the spans: let mut out: TokenStream = TokenStream::new(); out.extend(item); out } "} {"_id":"q-en-rust-93c5d7f2a630f97ac407877601acccd389796dd1dff540f8070f22652cbb7a0f","text":"/// # Example /// /// ```rust /// # #![allow(deprecated)] /// use url::Url; /// /// let raw = \"https://username@example.com:8080/foo/bar?baz=qux#quz\";"} {"_id":"q-en-rust-94071e4acf6f5c0915e331f9061a16e09f887c1947a58645b490954b9a6f93cf","text":"sections[None] = [] section_order = [None] targets = {} top_level_keys = [] for line in open(rust_dir + '/config.toml.example').read().split(\"n\"): if cur_section == None: if line.count('=') == 1: top_level_key = line.split('=')[0] top_level_key = top_level_key.strip(' #') top_level_keys.append(top_level_key) if line.startswith('['): cur_section = line[1:-1] if cur_section.startswith('target'):"} {"_id":"q-en-rust-943bba69b9ec9bc28b06249af8048608754b08f98b4a1154cfeedc7c9f493b25","text":"use crate::callee::{self, DeferredCallResolution}; use crate::errors::CtorIsPrivate; use crate::method::{self, MethodCallee, SelfSource}; use crate::rvalue_scopes; use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LocalTy, RawTy};"} {"_id":"q-en-rust-94522475c9185138290cb82a74e0c91f6dc0dfdca9d80eed282580b8d0f7f3d4","text":"to rejecting hexadecimal IP addresses.][83652] The octal format can lead to confusion and potential security vulnerabilities and [is no longer recommended][ietf6943]. - [The added `BITS` constant may conflict with external definitions.][85667] In particular, this was known to be a problem in the `lexical-core` crate, but they have published fixes for semantic versions 0.4 through 0.7. To update this dependency alone, use `cargo update -p lexical-core`. Internal Only -------------"} {"_id":"q-en-rust-945bc8dab7f17613e80c460b4402a145d5a99d534304407d095ad1f40a8acaa1","text":" error[E0658]: intrinsics are subject to change --> $DIR/incorrect-transmute.rs:5:8 | LL | extern \"rust-intrinsic\" fn transmute() {} | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(intrinsics)]` 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[E0094]: intrinsic has wrong number of type parameters: found 0, expected 2 --> $DIR/incorrect-transmute.rs:5:37 | LL | extern \"rust-intrinsic\" fn transmute() {} | ^ expected 2 type parameters error: intrinsic must be in `extern \"rust-intrinsic\" { ... }` block --> $DIR/incorrect-transmute.rs:5:40 | LL | extern \"rust-intrinsic\" fn transmute() {} | ^^ error: aborting due to 3 previous errors Some errors have detailed explanations: E0094, E0658. For more information about an error, try `rustc --explain E0094`. "} {"_id":"q-en-rust-949a7ff49cf372cf55184ae59d490b8361528b76836882c4768cd67825f95210","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-pass fn main() { let mut i = [1, 2, 3]; i[i[0]] = 0; i[i[0] - 1] = 0; } "} {"_id":"q-en-rust-94aed7b7473f5ff214de5c60900a6bf11daadc59cca46df21095cf69a112e226","text":"CU1: *mut *mut c_void, CU2: *mut *mut c_void); pub fn LLVMRustThinLTOPatchDICompileUnit(M: ModuleRef, CU: *mut c_void); pub fn LLVMRustThinLTORemoveAvailableExternally(M: ModuleRef); }"} {"_id":"q-en-rust-94f36402df2960d279c5b26d7f1c631d3232c2081f254727ddf7d6df32e011e9","text":" // run-rustfix struct Foo { first: Bar, _second: u32, _third: u32, } struct Bar { bar: C, } struct C { c: D, } struct D { test: E, } struct E { _e: F, } struct F { _f: u32, } fn main() { let f = F { _f: 6 }; let e = E { _e: f }; let d = D { test: e }; let c = C { c: d }; let bar = Bar { bar: c }; let fooer = Foo { first: bar, _second: 4, _third: 5 }; let _test = &fooer.c; //~^ ERROR no field let _test2 = fooer.test; //~^ ERROR no field } "} {"_id":"q-en-rust-9506de102557af4d60cf30489445a35cd250e1e535cc83be847268522493e879","text":"const _: u32 = recursive_expand!(); //~ ERROR: recursion limit reached while expanding `recursive_expand!` fn main() {} fn main() { // https://github.com/rust-lang/rust/issues/104414 match b\"Included file contentsn\" { include_bytes!(\"auxiliary/included-file.txt\") => (), _ => panic!(\"include_bytes! in pattern\"), } } "} {"_id":"q-en-rust-95074d08e71c9b2e81212bd5334c81e1954dab75d0318d090319e818449a8c74","text":"| ^^^^^^^^ error[E0603]: enum `Bar` is private --> $DIR/struct-variant-privacy-xc.rs:6:33 --> $DIR/struct-variant-privacy-xc.rs:7:33 | LL | struct_variant_privacy::Bar::Baz { a: _a } => {} | ^^^ private enum"} {"_id":"q-en-rust-9513d24cdbbed658bfb3b983271f3481ba7cb0f0101c0651eb1810b777754568","text":"/// # Examples /// /// ``` /// #![feature(arc_unwrap_or_clone)] /// # use std::{ptr, rc::Rc}; /// let inner = String::from(\"test\"); /// let ptr = inner.as_ptr();"} {"_id":"q-en-rust-959351194e96aebd4863d61f28fe9b867a82e4016e8b66a5a377e6b97f36e5ed","text":"error[E0658]: panicking in constants is unstable --> $DIR/issue-76064.rs:1:17 --> $DIR/issue-76064.rs:3:17 | LL | struct Bug([u8; panic!(1)]); | ^^^^^^^^^ LL | struct Bug([u8; panic!(\"panic\")]); | ^^^^^^^^^^^^^^^ | = note: see issue #51999 for more information = help: add `#![feature(const_panic)]` to the crate attributes to enable"} {"_id":"q-en-rust-9598a86019636b1d353301348b44de6a1f3ff49b9f32bf0c11d4c0d48aa6e372","text":"pub fn must_use(&self) -> bool { true } /// hello /// ///

this is a warning
/// /// done pub fn warning1() {} /// Checking there is no bottom margin if \"warning\" is the last element. /// ///
this is a warning
pub fn warning2() {} } impl AsRef for Foo {"} {"_id":"q-en-rust-9607d1e0a7f28fdc7194d38fd476735713570aa6e5c0b36e85d4f4ee33995cab","text":" use foo::*; mod foo { pub mod bar { pub mod bar { pub mod bar {} } } } use bar::bar; //~ ERROR `bar` is ambiguous use bar::*; fn main() { } "} {"_id":"q-en-rust-9618c928f725ea323b0a9709fedadce67f5df75061f0335df1a845d39d23841f","text":" // Regression test for #79902 // Check that evaluation (which is used to determine whether to copy a type in // MIR building) evaluates bounds from normalizing an impl after evaluating // any bounds on the impl. // check-pass trait A { type B; } trait M {} struct G(*const T, *const U); impl Clone for G { fn clone(&self) -> Self { G { ..*self } } } impl Copy for G where T: A, U: A, { } impl A for () { type B = (); } fn is_m(_: T) {} fn main() { let x = G(&(), &()); drop(x); drop(x); } "} {"_id":"q-en-rust-9641c6ca18ad4502dee0be9727c212a3b2c08682e1cb6803cff838346013e45d","text":"// stripping away any starting or ending parenthesis characters—hence this // test of the JSON error format. #![warn(unused_parens)] #![deny(unused_parens)] #![allow(unreachable_code)] fn main() { let _b = false; if _b { if _b { //~ ERROR unnecessary parentheses println!(\"hello\"); }"} {"_id":"q-en-rust-969b5f1853c4e2f339bc6805c3225bf75d1f3c021da0a6f08d2508e2289d9366","text":"// Note that unlike for slice patterns, // where `xs @ ..` is a legal sub-slice pattern, // it is not a legal sub-tuple pattern. if pat.is_rest() { rest = Some((idx, pat.span)); break; match pat.kind { // Found a sub-tuple rest pattern PatKind::Rest => { rest = Some((idx, pat.span)); break; } // Found a sub-tuple pattern `$binding_mode $ident @ ..`. // This is not allowed as a sub-tuple pattern PatKind::Ident(ref _bm, ident, Some(ref sub)) if sub.is_rest() => { rest = Some((idx, pat.span)); let sp = pat.span; self.diagnostic() .struct_span_err( sp, &format!(\"`{} @` is not allowed in a {}\", ident.name, ctx), ) .span_label(sp, \"this is only allowed in slice patterns\") .help(\"remove this and bind each tuple field independently\") .span_suggestion_verbose( sp, &format!(\"if you don't need to use the contents of {}, discard the tuple's remaining fields\", ident), \"..\".to_string(), Applicability::MaybeIncorrect, ) .emit(); break; } _ => {} } // It was not a sub-tuple pattern so lower it normally. elems.push(self.lower_pat(pat)); }"} {"_id":"q-en-rust-96b9a8a8f8bc1871a033c37cc40698387768dc8f884fea7847748b1e8251683f","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":"q-en-rust-96c863cc7550e5ebbc4f52f167b128e2ed0b909675088d34d47af12dca779cb5","text":" // run-rustfix use std::any::Any; fn foo(value: &T) -> Box { Box::new(value) as Box //~^ ERROR lifetime may not live long enough } fn main() { let _ = foo(&5); } "} {"_id":"q-en-rust-973a5da4b825a16a06b05382df2c725d768eb0ec3fab62ce6359c115869cd292","text":" error: expected one of `!`, `.`, `::`, `;`, `?`, `else`, `{`, or an operator, found `,` --> $DIR/turbofish-arg-with-stray-colon.rs:2:17 | LL | let x = Tr; | ^ expected one of 8 possible tokens | = note: type ascription syntax has been removed, see issue #101728 help: maybe write a path separator here | LL | let x = Tr; | ~~ error: aborting due to 1 previous error "} {"_id":"q-en-rust-975ab7db4fa091e5afb1c37f6decd93d48aeef24512da92953b7d1b883012634","text":"} } /// Evaluate a const function where all arguments (if any) are zero-sized types. /// The evaluation is memoized thanks to the query system. // FIXME: Consider moving this to `const_eval.rs`. pub(crate) fn eval_const_fn_call( &mut self, gid: GlobalId<'tcx>, ret: Option<(PlaceTy<'tcx, M::PointerTag>, mir::BasicBlock)>, ) -> InterpResult<'tcx> { trace!(\"eval_const_fn_call: {:?}\", gid); let place = self.const_eval_raw(gid)?; let dest = ret.ok_or_else(|| err_ub!(Unreachable))?.0; self.copy_op(place.into(), dest)?; self.return_to_block(ret.map(|r| r.1))?; self.dump_place(*dest); return Ok(()); } fn drop_in_place( &mut self, place: PlaceTy<'tcx, M::PointerTag>,"} {"_id":"q-en-rust-97646f3cc2aaf0f0ddea1d091ddc89fae6402a3edd8b7efd5402866cefa3437a","text":"| LL | unsafe extern \"C\" { | ^^^^^^ | = note: see issue #123743 for more information = help: add `#![feature(unsafe_extern_blocks)]` 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 1 previous error"} {"_id":"q-en-rust-9764f9e3b31d11297b5310bbca4454373f440ec511a197d05720ba8c8b3b2cac","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. //! POSIX file path handling use container::Container; use c_str::{CString, ToCStr}; use clone::Clone; use cmp::Eq; use from_str::FromStr; use iter::{AdditiveIterator, Extendable, Iterator}; use option::{Option, None, Some}; use str; use str::Str; use util; use vec; use vec::CopyableVector; use vec::{Vector, VectorVector}; use super::{GenericPath, GenericPathUnsafe}; /// Iterator that yields successive components of a Path pub type ComponentIter<'self> = vec::SplitIterator<'self, u8>; /// Represents a POSIX file path #[deriving(Clone, DeepClone)] pub struct Path { priv repr: ~[u8], // assumed to never be empty or contain NULs priv sepidx: Option // index of the final separator in repr } /// The standard path separator character pub static sep: u8 = '/' as u8; /// Returns whether the given byte is a path separator #[inline] pub fn is_sep(u: &u8) -> bool { *u == sep } impl Eq for Path { #[inline] fn eq(&self, other: &Path) -> bool { self.repr == other.repr } } impl FromStr for Path { fn from_str(s: &str) -> Option { let v = s.as_bytes(); if contains_nul(v) { None } else { Some(unsafe { GenericPathUnsafe::from_vec_unchecked(v) }) } } } impl ToCStr for Path { #[inline] fn to_c_str(&self) -> CString { // The Path impl guarantees no internal NUL unsafe { self.as_vec().to_c_str_unchecked() } } #[inline] unsafe fn to_c_str_unchecked(&self) -> CString { self.as_vec().to_c_str_unchecked() } } impl GenericPathUnsafe for Path { unsafe fn from_vec_unchecked(path: &[u8]) -> Path { let path = Path::normalize(path); assert!(!path.is_empty()); let idx = path.rposition_elem(&sep); Path{ repr: path, sepidx: idx } } unsafe fn set_dirname_unchecked(&mut self, dirname: &[u8]) { match self.sepidx { None if bytes!(\".\") == self.repr || bytes!(\"..\") == self.repr => { self.repr = Path::normalize(dirname); } None => { let mut v = vec::with_capacity(dirname.len() + self.repr.len() + 1); v.push_all(dirname); v.push(sep); v.push_all(self.repr); self.repr = Path::normalize(v); } Some(0) if self.repr.len() == 1 && self.repr[0] == sep => { self.repr = Path::normalize(dirname); } Some(idx) if self.repr.slice_from(idx+1) == bytes!(\"..\") => { self.repr = Path::normalize(dirname); } Some(idx) if dirname.is_empty() => { let v = Path::normalize(self.repr.slice_from(idx+1)); self.repr = v; } Some(idx) => { let mut v = vec::with_capacity(dirname.len() + self.repr.len() - idx); v.push_all(dirname); v.push_all(self.repr.slice_from(idx)); self.repr = Path::normalize(v); } } self.sepidx = self.repr.rposition_elem(&sep); } unsafe fn set_filename_unchecked(&mut self, filename: &[u8]) { match self.sepidx { None if bytes!(\"..\") == self.repr => { let mut v = vec::with_capacity(3 + filename.len()); v.push_all(dot_dot_static); v.push(sep); v.push_all(filename); self.repr = Path::normalize(v); } None => { self.repr = Path::normalize(filename); } Some(idx) if self.repr.slice_from(idx+1) == bytes!(\"..\") => { let mut v = vec::with_capacity(self.repr.len() + 1 + filename.len()); v.push_all(self.repr); v.push(sep); v.push_all(filename); self.repr = Path::normalize(v); } Some(idx) => { let mut v = vec::with_capacity(idx + 1 + filename.len()); v.push_all(self.repr.slice_to(idx+1)); v.push_all(filename); self.repr = Path::normalize(v); } } self.sepidx = self.repr.rposition_elem(&sep); } unsafe fn push_unchecked(&mut self, path: &[u8]) { if !path.is_empty() { if path[0] == sep { self.repr = Path::normalize(path); } else { let mut v = vec::with_capacity(self.repr.len() + path.len() + 1); v.push_all(self.repr); v.push(sep); v.push_all(path); self.repr = Path::normalize(v); } self.sepidx = self.repr.rposition_elem(&sep); } } } impl GenericPath for Path { #[inline] fn as_vec<'a>(&'a self) -> &'a [u8] { self.repr.as_slice() } fn dirname<'a>(&'a self) -> &'a [u8] { match self.sepidx { None if bytes!(\"..\") == self.repr => self.repr.as_slice(), None => dot_static, Some(0) => self.repr.slice_to(1), Some(idx) if self.repr.slice_from(idx+1) == bytes!(\"..\") => self.repr.as_slice(), Some(idx) => self.repr.slice_to(idx) } } fn filename<'a>(&'a self) -> &'a [u8] { match self.sepidx { None if bytes!(\".\") == self.repr || bytes!(\"..\") == self.repr => &[], None => self.repr.as_slice(), Some(idx) if self.repr.slice_from(idx+1) == bytes!(\"..\") => &[], Some(idx) => self.repr.slice_from(idx+1) } } fn pop_opt(&mut self) -> Option<~[u8]> { match self.sepidx { None if bytes!(\".\") == self.repr => None, None => { let mut v = ~['.' as u8]; util::swap(&mut v, &mut self.repr); self.sepidx = None; Some(v) } Some(0) if bytes!(\"/\") == self.repr => None, Some(idx) => { let v = self.repr.slice_from(idx+1).to_owned(); if idx == 0 { self.repr.truncate(idx+1); } else { self.repr.truncate(idx); } self.sepidx = self.repr.rposition_elem(&sep); Some(v) } } } #[inline] fn is_absolute(&self) -> bool { self.repr[0] == sep } fn is_ancestor_of(&self, other: &Path) -> bool { if self.is_absolute() != other.is_absolute() { false } else { let mut ita = self.component_iter(); let mut itb = other.component_iter(); if bytes!(\".\") == self.repr { return itb.next() != Some(bytes!(\"..\")); } loop { match (ita.next(), itb.next()) { (None, _) => break, (Some(a), Some(b)) if a == b => { loop }, (Some(a), _) if a == bytes!(\"..\") => { // if ita contains only .. components, it's an ancestor return ita.all(|x| x == bytes!(\"..\")); } _ => return false } } true } } fn path_relative_from(&self, base: &Path) -> Option { if self.is_absolute() != base.is_absolute() { if self.is_absolute() { Some(self.clone()) } else { None } } else { let mut ita = self.component_iter(); let mut itb = base.component_iter(); let mut comps = ~[]; loop { match (ita.next(), itb.next()) { (None, None) => break, (Some(a), None) => { comps.push(a); comps.extend(&mut ita); break; } (None, _) => comps.push(dot_dot_static), (Some(a), Some(b)) if comps.is_empty() && a == b => (), (Some(a), Some(b)) if b == bytes!(\".\") => comps.push(a), (Some(_), Some(b)) if b == bytes!(\"..\") => return None, (Some(a), Some(_)) => { comps.push(dot_dot_static); for _ in itb { comps.push(dot_dot_static); } comps.push(a); comps.extend(&mut ita); break; } } } Some(Path::new(comps.connect_vec(&sep))) } } } impl Path { /// Returns a new Path from a byte vector /// /// # Failure /// /// Raises the `null_byte` condition if the vector contains a NUL. #[inline] pub fn new(v: &[u8]) -> Path { GenericPath::from_vec(v) } /// Returns a new Path from a string /// /// # Failure /// /// Raises the `null_byte` condition if the str contains a NUL. #[inline] pub fn from_str(s: &str) -> Path { GenericPath::from_str(s) } /// Converts the Path into an owned byte vector pub fn into_vec(self) -> ~[u8] { self.repr } /// Converts the Path into an owned string, if possible pub fn into_str(self) -> Option<~str> { str::from_utf8_owned_opt(self.repr) } /// Returns a normalized byte vector representation of a path, by removing all empty /// components, and unnecessary . and .. components. pub fn normalize+CopyableVector>(v: V) -> ~[u8] { // borrowck is being very picky let val = { let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == sep; let v_ = if is_abs { v.as_slice().slice_from(1) } else { v.as_slice() }; let comps = normalize_helper(v_, is_abs); match comps { None => None, Some(comps) => { if is_abs && comps.is_empty() { Some(~[sep]) } else { let n = if is_abs { comps.len() } else { comps.len() - 1} + comps.iter().map(|v| v.len()).sum(); let mut v = vec::with_capacity(n); let mut it = comps.move_iter(); if !is_abs { match it.next() { None => (), Some(comp) => v.push_all(comp) } } for comp in it { v.push(sep); v.push_all(comp); } Some(v) } } } }; match val { None => v.into_owned(), Some(val) => val } } /// Returns an iterator that yields each component of the path in turn. /// Does not distinguish between absolute and relative paths, e.g. /// /a/b/c and a/b/c yield the same set of components. /// A path of \"/\" yields no components. A path of \".\" yields one component. pub fn component_iter<'a>(&'a self) -> ComponentIter<'a> { let v = if self.repr[0] == sep { self.repr.slice_from(1) } else { self.repr.as_slice() }; let mut ret = v.split_iter(is_sep); if v.is_empty() { // consume the empty \"\" component ret.next(); } ret } } // None result means the byte vector didn't need normalizing fn normalize_helper<'a>(v: &'a [u8], is_abs: bool) -> Option<~[&'a [u8]]> { if is_abs && v.as_slice().is_empty() { return None; } let mut comps: ~[&'a [u8]] = ~[]; let mut n_up = 0u; let mut changed = false; for comp in v.split_iter(is_sep) { if comp.is_empty() { changed = true } else if comp == bytes!(\".\") { changed = true } else if comp == bytes!(\"..\") { if is_abs && comps.is_empty() { changed = true } else if comps.len() == n_up { comps.push(dot_dot_static); n_up += 1 } else { comps.pop_opt(); changed = true } } else { comps.push(comp) } } if changed { if comps.is_empty() && !is_abs { if v == bytes!(\".\") { return None; } comps.push(dot_static); } Some(comps) } else { None } } // FIXME (#8169): Pull this into parent module once visibility works #[inline(always)] fn contains_nul(v: &[u8]) -> bool { v.iter().any(|&x| x == 0) } static dot_static: &'static [u8] = &'static ['.' as u8]; static dot_dot_static: &'static [u8] = &'static ['.' as u8, '.' as u8]; #[cfg(test)] mod tests { use super::*; use option::{Some, None}; use iter::Iterator; use str; use vec::Vector; macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = $path; assert_eq!(path.as_str(), Some($exp)); } ); (v: $path:expr, $exp:expr) => ( { let path = $path; assert_eq!(path.as_vec(), $exp); } ) ) macro_rules! b( ($($arg:expr),+) => ( bytes!($($arg),+) ) ) #[test] fn test_paths() { t!(v: Path::new([]), b!(\".\")); t!(v: Path::new(b!(\"/\")), b!(\"/\")); t!(v: Path::new(b!(\"a/b/c\")), b!(\"a/b/c\")); t!(v: Path::new(b!(\"a/b/c\", 0xff)), b!(\"a/b/c\", 0xff)); t!(v: Path::new(b!(0xff, \"/../foo\", 0x80)), b!(\"foo\", 0x80)); let p = Path::new(b!(\"a/b/c\", 0xff)); assert_eq!(p.as_str(), None); t!(s: Path::from_str(\"\"), \".\"); t!(s: Path::from_str(\"/\"), \"/\"); t!(s: Path::from_str(\"hi\"), \"hi\"); t!(s: Path::from_str(\"hi/\"), \"hi\"); t!(s: Path::from_str(\"/lib\"), \"/lib\"); t!(s: Path::from_str(\"/lib/\"), \"/lib\"); t!(s: Path::from_str(\"hi/there\"), \"hi/there\"); t!(s: Path::from_str(\"hi/there.txt\"), \"hi/there.txt\"); t!(s: Path::from_str(\"hi/there/\"), \"hi/there\"); t!(s: Path::from_str(\"hi/../there\"), \"there\"); t!(s: Path::from_str(\"../hi/there\"), \"../hi/there\"); t!(s: Path::from_str(\"/../hi/there\"), \"/hi/there\"); t!(s: Path::from_str(\"foo/..\"), \".\"); t!(s: Path::from_str(\"/foo/..\"), \"/\"); t!(s: Path::from_str(\"/foo/../..\"), \"/\"); t!(s: Path::from_str(\"/foo/../../bar\"), \"/bar\"); t!(s: Path::from_str(\"/./hi/./there/.\"), \"/hi/there\"); t!(s: Path::from_str(\"/./hi/./there/./..\"), \"/hi\"); t!(s: Path::from_str(\"foo/../..\"), \"..\"); t!(s: Path::from_str(\"foo/../../..\"), \"../..\"); t!(s: Path::from_str(\"foo/../../bar\"), \"../bar\"); assert_eq!(Path::new(b!(\"foo/bar\")).into_vec(), b!(\"foo/bar\").to_owned()); assert_eq!(Path::new(b!(\"/foo/../../bar\")).into_vec(), b!(\"/bar\").to_owned()); assert_eq!(Path::from_str(\"foo/bar\").into_str(), Some(~\"foo/bar\")); assert_eq!(Path::from_str(\"/foo/../../bar\").into_str(), Some(~\"/bar\")); let p = Path::new(b!(\"foo/bar\", 0x80)); assert_eq!(p.as_str(), None); assert_eq!(Path::new(b!(\"foo\", 0xff, \"/bar\")).into_str(), None); } #[test] fn test_null_byte() { use path2::null_byte::cond; let mut handled = false; let mut p = do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!(\"foo/bar\", 0)); (b!(\"/bar\").to_owned()) }).inside { Path::new(b!(\"foo/bar\", 0)) }; assert!(handled); assert_eq!(p.as_vec(), b!(\"/bar\")); handled = false; do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!(\"f\", 0, \"o\")); (b!(\"foo\").to_owned()) }).inside { p.set_filename(b!(\"f\", 0, \"o\")) }; assert!(handled); assert_eq!(p.as_vec(), b!(\"/foo\")); handled = false; do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!(\"null/\", 0, \"/byte\")); (b!(\"null/byte\").to_owned()) }).inside { p.set_dirname(b!(\"null/\", 0, \"/byte\")); }; assert!(handled); assert_eq!(p.as_vec(), b!(\"null/byte/foo\")); handled = false; do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!(\"f\", 0, \"o\")); (b!(\"foo\").to_owned()) }).inside { p.push(b!(\"f\", 0, \"o\")); }; assert!(handled); assert_eq!(p.as_vec(), b!(\"null/byte/foo/foo\")); } #[test] fn test_null_byte_fail() { use path2::null_byte::cond; use task; macro_rules! t( ($name:expr => $code:block) => ( { let mut t = task::task(); t.supervised(); t.name($name); let res = do t.try $code; assert!(res.is_err()); } ) ) t!(~\"new() w/nul\" => { do cond.trap(|_| { (b!(\"null\", 0).to_owned()) }).inside { Path::new(b!(\"foo/bar\", 0)) }; }) t!(~\"set_filename w/nul\" => { let mut p = Path::new(b!(\"foo/bar\")); do cond.trap(|_| { (b!(\"null\", 0).to_owned()) }).inside { p.set_filename(b!(\"foo\", 0)) }; }) t!(~\"set_dirname w/nul\" => { let mut p = Path::new(b!(\"foo/bar\")); do cond.trap(|_| { (b!(\"null\", 0).to_owned()) }).inside { p.set_dirname(b!(\"foo\", 0)) }; }) t!(~\"push w/nul\" => { let mut p = Path::new(b!(\"foo/bar\")); do cond.trap(|_| { (b!(\"null\", 0).to_owned()) }).inside { p.push(b!(\"foo\", 0)) }; }) } #[test] fn test_components() { macro_rules! t( (s: $path:expr, $op:ident, $exp:expr) => ( { let path = Path::from_str($path); assert_eq!(path.$op(), ($exp).as_bytes()); } ); (s: $path:expr, $op:ident, $exp:expr, opt) => ( { let path = Path::from_str($path); let left = path.$op().map(|&x| str::from_utf8_slice(x)); assert_eq!(left, $exp); } ); (v: $path:expr, $op:ident, $exp:expr) => ( { let path = Path::new($path); assert_eq!(path.$op(), $exp); } ) ) t!(v: b!(\"a/b/c\"), filename, b!(\"c\")); t!(v: b!(\"a/b/c\", 0xff), filename, b!(\"c\", 0xff)); t!(v: b!(\"a/b\", 0xff, \"/c\"), filename, b!(\"c\")); t!(s: \"a/b/c\", filename, \"c\"); t!(s: \"/a/b/c\", filename, \"c\"); t!(s: \"a\", filename, \"a\"); t!(s: \"/a\", filename, \"a\"); t!(s: \".\", filename, \"\"); t!(s: \"/\", filename, \"\"); t!(s: \"..\", filename, \"\"); t!(s: \"../..\", filename, \"\"); t!(v: b!(\"a/b/c\"), dirname, b!(\"a/b\")); t!(v: b!(\"a/b/c\", 0xff), dirname, b!(\"a/b\")); t!(v: b!(\"a/b\", 0xff, \"/c\"), dirname, b!(\"a/b\", 0xff)); t!(s: \"a/b/c\", dirname, \"a/b\"); t!(s: \"/a/b/c\", dirname, \"/a/b\"); t!(s: \"a\", dirname, \".\"); t!(s: \"/a\", dirname, \"/\"); t!(s: \".\", dirname, \".\"); t!(s: \"/\", dirname, \"/\"); t!(s: \"..\", dirname, \"..\"); t!(s: \"../..\", dirname, \"../..\"); t!(v: b!(\"hi/there.txt\"), filestem, b!(\"there\")); t!(v: b!(\"hi/there\", 0x80, \".txt\"), filestem, b!(\"there\", 0x80)); t!(v: b!(\"hi/there.t\", 0x80, \"xt\"), filestem, b!(\"there\")); t!(s: \"hi/there.txt\", filestem, \"there\"); t!(s: \"hi/there\", filestem, \"there\"); t!(s: \"there.txt\", filestem, \"there\"); t!(s: \"there\", filestem, \"there\"); t!(s: \".\", filestem, \"\"); t!(s: \"/\", filestem, \"\"); t!(s: \"foo/.bar\", filestem, \".bar\"); t!(s: \".bar\", filestem, \".bar\"); t!(s: \"..bar\", filestem, \".\"); t!(s: \"hi/there..txt\", filestem, \"there.\"); t!(s: \"..\", filestem, \"\"); t!(s: \"../..\", filestem, \"\"); t!(v: b!(\"hi/there.txt\"), extension, Some(b!(\"txt\"))); t!(v: b!(\"hi/there\", 0x80, \".txt\"), extension, Some(b!(\"txt\"))); t!(v: b!(\"hi/there.t\", 0x80, \"xt\"), extension, Some(b!(\"t\", 0x80, \"xt\"))); t!(v: b!(\"hi/there\"), extension, None); t!(v: b!(\"hi/there\", 0x80), extension, None); t!(s: \"hi/there.txt\", extension, Some(\"txt\"), opt); t!(s: \"hi/there\", extension, None, opt); t!(s: \"there.txt\", extension, Some(\"txt\"), opt); t!(s: \"there\", extension, None, opt); t!(s: \".\", extension, None, opt); t!(s: \"/\", extension, None, opt); t!(s: \"foo/.bar\", extension, None, opt); t!(s: \".bar\", extension, None, opt); t!(s: \"..bar\", extension, Some(\"bar\"), opt); t!(s: \"hi/there..txt\", extension, Some(\"txt\"), opt); t!(s: \"..\", extension, None, opt); t!(s: \"../..\", extension, None, opt); } #[test] fn test_push() { macro_rules! t( (s: $path:expr, $join:expr) => ( { let path = ($path); let join = ($join); let mut p1 = Path::from_str(path); let p2 = p1.clone(); p1.push_str(join); assert_eq!(p1, p2.join_str(join)); } ) ) t!(s: \"a/b/c\", \"..\"); t!(s: \"/a/b/c\", \"d\"); t!(s: \"a/b\", \"c/d\"); t!(s: \"a/b\", \"/c/d\"); } #[test] fn test_push_path() { macro_rules! t( (s: $path:expr, $push:expr, $exp:expr) => ( { let mut p = Path::from_str($path); let push = Path::from_str($push); p.push_path(&push); assert_eq!(p.as_str(), Some($exp)); } ) ) t!(s: \"a/b/c\", \"d\", \"a/b/c/d\"); t!(s: \"/a/b/c\", \"d\", \"/a/b/c/d\"); t!(s: \"a/b\", \"c/d\", \"a/b/c/d\"); t!(s: \"a/b\", \"/c/d\", \"/c/d\"); t!(s: \"a/b\", \".\", \"a/b\"); t!(s: \"a/b\", \"../c\", \"a/c\"); } #[test] fn test_pop() { macro_rules! t( (s: $path:expr, $left:expr, $right:expr) => ( { let mut p = Path::from_str($path); let file = p.pop_opt_str(); assert_eq!(p.as_str(), Some($left)); assert_eq!(file.map(|s| s.as_slice()), $right); } ); (v: [$($path:expr),+], [$($left:expr),+], Some($($right:expr),+)) => ( { let mut p = Path::new(b!($($path),+)); let file = p.pop_opt(); assert_eq!(p.as_vec(), b!($($left),+)); assert_eq!(file.map(|v| v.as_slice()), Some(b!($($right),+))); } ); (v: [$($path:expr),+], [$($left:expr),+], None) => ( { let mut p = Path::new(b!($($path),+)); let file = p.pop_opt(); assert_eq!(p.as_vec(), b!($($left),+)); assert_eq!(file, None); } ) ) t!(v: [\"a/b/c\"], [\"a/b\"], Some(\"c\")); t!(v: [\"a\"], [\".\"], Some(\"a\")); t!(v: [\".\"], [\".\"], None); t!(v: [\"/a\"], [\"/\"], Some(\"a\")); t!(v: [\"/\"], [\"/\"], None); t!(v: [\"a/b/c\", 0x80], [\"a/b\"], Some(\"c\", 0x80)); t!(v: [\"a/b\", 0x80, \"/c\"], [\"a/b\", 0x80], Some(\"c\")); t!(v: [0xff], [\".\"], Some(0xff)); t!(v: [\"/\", 0xff], [\"/\"], Some(0xff)); t!(s: \"a/b/c\", \"a/b\", Some(\"c\")); t!(s: \"a\", \".\", Some(\"a\")); t!(s: \".\", \".\", None); t!(s: \"/a\", \"/\", Some(\"a\")); t!(s: \"/\", \"/\", None); assert_eq!(Path::new(b!(\"foo/bar\", 0x80)).pop_opt_str(), None); assert_eq!(Path::new(b!(\"foo\", 0x80, \"/bar\")).pop_opt_str(), Some(~\"bar\")); } #[test] fn test_join() { t!(v: Path::new(b!(\"a/b/c\")).join(b!(\"..\")), b!(\"a/b\")); t!(v: Path::new(b!(\"/a/b/c\")).join(b!(\"d\")), b!(\"/a/b/c/d\")); t!(v: Path::new(b!(\"a/\", 0x80, \"/c\")).join(b!(0xff)), b!(\"a/\", 0x80, \"/c/\", 0xff)); t!(s: Path::from_str(\"a/b/c\").join_str(\"..\"), \"a/b\"); t!(s: Path::from_str(\"/a/b/c\").join_str(\"d\"), \"/a/b/c/d\"); t!(s: Path::from_str(\"a/b\").join_str(\"c/d\"), \"a/b/c/d\"); t!(s: Path::from_str(\"a/b\").join_str(\"/c/d\"), \"/c/d\"); t!(s: Path::from_str(\".\").join_str(\"a/b\"), \"a/b\"); t!(s: Path::from_str(\"/\").join_str(\"a/b\"), \"/a/b\"); } #[test] fn test_join_path() { macro_rules! t( (s: $path:expr, $join:expr, $exp:expr) => ( { let path = Path::from_str($path); let join = Path::from_str($join); let res = path.join_path(&join); assert_eq!(res.as_str(), Some($exp)); } ) ) t!(s: \"a/b/c\", \"..\", \"a/b\"); t!(s: \"/a/b/c\", \"d\", \"/a/b/c/d\"); t!(s: \"a/b\", \"c/d\", \"a/b/c/d\"); t!(s: \"a/b\", \"/c/d\", \"/c/d\"); t!(s: \".\", \"a/b\", \"a/b\"); t!(s: \"/\", \"a/b\", \"/a/b\"); } #[test] fn test_with_helpers() { t!(v: Path::new(b!(\"a/b/c\")).with_dirname(b!(\"d\")), b!(\"d/c\")); t!(v: Path::new(b!(\"a/b/c\")).with_dirname(b!(\"d/e\")), b!(\"d/e/c\")); t!(v: Path::new(b!(\"a/\", 0x80, \"b/c\")).with_dirname(b!(0xff)), b!(0xff, \"/c\")); t!(v: Path::new(b!(\"a/b/\", 0x80)).with_dirname(b!(\"/\", 0xcd)), b!(\"/\", 0xcd, \"/\", 0x80)); t!(s: Path::from_str(\"a/b/c\").with_dirname_str(\"d\"), \"d/c\"); t!(s: Path::from_str(\"a/b/c\").with_dirname_str(\"d/e\"), \"d/e/c\"); t!(s: Path::from_str(\"a/b/c\").with_dirname_str(\"\"), \"c\"); t!(s: Path::from_str(\"a/b/c\").with_dirname_str(\"/\"), \"/c\"); t!(s: Path::from_str(\"a/b/c\").with_dirname_str(\".\"), \"c\"); t!(s: Path::from_str(\"a/b/c\").with_dirname_str(\"..\"), \"../c\"); t!(s: Path::from_str(\"/\").with_dirname_str(\"foo\"), \"foo\"); t!(s: Path::from_str(\"/\").with_dirname_str(\"\"), \".\"); t!(s: Path::from_str(\"/foo\").with_dirname_str(\"bar\"), \"bar/foo\"); t!(s: Path::from_str(\"..\").with_dirname_str(\"foo\"), \"foo\"); t!(s: Path::from_str(\"../..\").with_dirname_str(\"foo\"), \"foo\"); t!(s: Path::from_str(\"..\").with_dirname_str(\"\"), \".\"); t!(s: Path::from_str(\"../..\").with_dirname_str(\"\"), \".\"); t!(s: Path::from_str(\"foo\").with_dirname_str(\"..\"), \"../foo\"); t!(s: Path::from_str(\"foo\").with_dirname_str(\"../..\"), \"../../foo\"); t!(v: Path::new(b!(\"a/b/c\")).with_filename(b!(\"d\")), b!(\"a/b/d\")); t!(v: Path::new(b!(\"a/b/c\", 0xff)).with_filename(b!(0x80)), b!(\"a/b/\", 0x80)); t!(v: Path::new(b!(\"/\", 0xff, \"/foo\")).with_filename(b!(0xcd)), b!(\"/\", 0xff, \"/\", 0xcd)); t!(s: Path::from_str(\"a/b/c\").with_filename_str(\"d\"), \"a/b/d\"); t!(s: Path::from_str(\".\").with_filename_str(\"foo\"), \"foo\"); t!(s: Path::from_str(\"/a/b/c\").with_filename_str(\"d\"), \"/a/b/d\"); t!(s: Path::from_str(\"/\").with_filename_str(\"foo\"), \"/foo\"); t!(s: Path::from_str(\"/a\").with_filename_str(\"foo\"), \"/foo\"); t!(s: Path::from_str(\"foo\").with_filename_str(\"bar\"), \"bar\"); t!(s: Path::from_str(\"/\").with_filename_str(\"foo/\"), \"/foo\"); t!(s: Path::from_str(\"/a\").with_filename_str(\"foo/\"), \"/foo\"); t!(s: Path::from_str(\"a/b/c\").with_filename_str(\"\"), \"a/b\"); t!(s: Path::from_str(\"a/b/c\").with_filename_str(\".\"), \"a/b\"); t!(s: Path::from_str(\"a/b/c\").with_filename_str(\"..\"), \"a\"); t!(s: Path::from_str(\"/a\").with_filename_str(\"\"), \"/\"); t!(s: Path::from_str(\"foo\").with_filename_str(\"\"), \".\"); t!(s: Path::from_str(\"a/b/c\").with_filename_str(\"d/e\"), \"a/b/d/e\"); t!(s: Path::from_str(\"a/b/c\").with_filename_str(\"/d\"), \"a/b/d\"); t!(s: Path::from_str(\"..\").with_filename_str(\"foo\"), \"../foo\"); t!(s: Path::from_str(\"../..\").with_filename_str(\"foo\"), \"../../foo\"); t!(s: Path::from_str(\"..\").with_filename_str(\"\"), \"..\"); t!(s: Path::from_str(\"../..\").with_filename_str(\"\"), \"../..\"); t!(v: Path::new(b!(\"hi/there\", 0x80, \".txt\")).with_filestem(b!(0xff)), b!(\"hi/\", 0xff, \".txt\")); t!(v: Path::new(b!(\"hi/there.txt\", 0x80)).with_filestem(b!(0xff)), b!(\"hi/\", 0xff, \".txt\", 0x80)); t!(v: Path::new(b!(\"hi/there\", 0xff)).with_filestem(b!(0x80)), b!(\"hi/\", 0x80)); t!(v: Path::new(b!(\"hi\", 0x80, \"/there\")).with_filestem([]), b!(\"hi\", 0x80)); t!(s: Path::from_str(\"hi/there.txt\").with_filestem_str(\"here\"), \"hi/here.txt\"); t!(s: Path::from_str(\"hi/there.txt\").with_filestem_str(\"\"), \"hi/.txt\"); t!(s: Path::from_str(\"hi/there.txt\").with_filestem_str(\".\"), \"hi/..txt\"); t!(s: Path::from_str(\"hi/there.txt\").with_filestem_str(\"..\"), \"hi/...txt\"); t!(s: Path::from_str(\"hi/there.txt\").with_filestem_str(\"/\"), \"hi/.txt\"); t!(s: Path::from_str(\"hi/there.txt\").with_filestem_str(\"foo/bar\"), \"hi/foo/bar.txt\"); t!(s: Path::from_str(\"hi/there.foo.txt\").with_filestem_str(\"here\"), \"hi/here.txt\"); t!(s: Path::from_str(\"hi/there\").with_filestem_str(\"here\"), \"hi/here\"); t!(s: Path::from_str(\"hi/there\").with_filestem_str(\"\"), \"hi\"); t!(s: Path::from_str(\"hi\").with_filestem_str(\"\"), \".\"); t!(s: Path::from_str(\"/hi\").with_filestem_str(\"\"), \"/\"); t!(s: Path::from_str(\"hi/there\").with_filestem_str(\"..\"), \".\"); t!(s: Path::from_str(\"hi/there\").with_filestem_str(\".\"), \"hi\"); t!(s: Path::from_str(\"hi/there.\").with_filestem_str(\"foo\"), \"hi/foo.\"); t!(s: Path::from_str(\"hi/there.\").with_filestem_str(\"\"), \"hi\"); t!(s: Path::from_str(\"hi/there.\").with_filestem_str(\".\"), \".\"); t!(s: Path::from_str(\"hi/there.\").with_filestem_str(\"..\"), \"hi/...\"); t!(s: Path::from_str(\"/\").with_filestem_str(\"foo\"), \"/foo\"); t!(s: Path::from_str(\".\").with_filestem_str(\"foo\"), \"foo\"); t!(s: Path::from_str(\"hi/there..\").with_filestem_str(\"here\"), \"hi/here.\"); t!(s: Path::from_str(\"hi/there..\").with_filestem_str(\"\"), \"hi\"); t!(v: Path::new(b!(\"hi/there\", 0x80, \".txt\")).with_extension(b!(\"exe\")), b!(\"hi/there\", 0x80, \".exe\")); t!(v: Path::new(b!(\"hi/there.txt\", 0x80)).with_extension(b!(0xff)), b!(\"hi/there.\", 0xff)); t!(v: Path::new(b!(\"hi/there\", 0x80)).with_extension(b!(0xff)), b!(\"hi/there\", 0x80, \".\", 0xff)); t!(v: Path::new(b!(\"hi/there.\", 0xff)).with_extension([]), b!(\"hi/there\")); t!(s: Path::from_str(\"hi/there.txt\").with_extension_str(\"exe\"), \"hi/there.exe\"); t!(s: Path::from_str(\"hi/there.txt\").with_extension_str(\"\"), \"hi/there\"); t!(s: Path::from_str(\"hi/there.txt\").with_extension_str(\".\"), \"hi/there..\"); t!(s: Path::from_str(\"hi/there.txt\").with_extension_str(\"..\"), \"hi/there...\"); t!(s: Path::from_str(\"hi/there\").with_extension_str(\"txt\"), \"hi/there.txt\"); t!(s: Path::from_str(\"hi/there\").with_extension_str(\".\"), \"hi/there..\"); t!(s: Path::from_str(\"hi/there\").with_extension_str(\"..\"), \"hi/there...\"); t!(s: Path::from_str(\"hi/there.\").with_extension_str(\"txt\"), \"hi/there.txt\"); t!(s: Path::from_str(\"hi/.foo\").with_extension_str(\"txt\"), \"hi/.foo.txt\"); t!(s: Path::from_str(\"hi/there.txt\").with_extension_str(\".foo\"), \"hi/there..foo\"); t!(s: Path::from_str(\"/\").with_extension_str(\"txt\"), \"/\"); t!(s: Path::from_str(\"/\").with_extension_str(\".\"), \"/\"); t!(s: Path::from_str(\"/\").with_extension_str(\"..\"), \"/\"); t!(s: Path::from_str(\".\").with_extension_str(\"txt\"), \".\"); } #[test] fn test_setters() { macro_rules! t( (s: $path:expr, $set:ident, $with:ident, $arg:expr) => ( { let path = $path; let arg = $arg; let mut p1 = Path::from_str(path); p1.$set(arg); let p2 = Path::from_str(path); assert_eq!(p1, p2.$with(arg)); } ); (v: $path:expr, $set:ident, $with:ident, $arg:expr) => ( { let path = $path; let arg = $arg; let mut p1 = Path::new(path); p1.$set(arg); let p2 = Path::new(path); assert_eq!(p1, p2.$with(arg)); } ) ) t!(v: b!(\"a/b/c\"), set_dirname, with_dirname, b!(\"d\")); t!(v: b!(\"a/b/c\"), set_dirname, with_dirname, b!(\"d/e\")); t!(v: b!(\"a/\", 0x80, \"/c\"), set_dirname, with_dirname, b!(0xff)); t!(s: \"a/b/c\", set_dirname_str, with_dirname_str, \"d\"); t!(s: \"a/b/c\", set_dirname_str, with_dirname_str, \"d/e\"); t!(s: \"/\", set_dirname_str, with_dirname_str, \"foo\"); t!(s: \"/foo\", set_dirname_str, with_dirname_str, \"bar\"); t!(s: \"a/b/c\", set_dirname_str, with_dirname_str, \"\"); t!(s: \"../..\", set_dirname_str, with_dirname_str, \"x\"); t!(s: \"foo\", set_dirname_str, with_dirname_str, \"../..\"); t!(v: b!(\"a/b/c\"), set_filename, with_filename, b!(\"d\")); t!(v: b!(\"/\"), set_filename, with_filename, b!(\"foo\")); t!(v: b!(0x80), set_filename, with_filename, b!(0xff)); t!(s: \"a/b/c\", set_filename_str, with_filename_str, \"d\"); t!(s: \"/\", set_filename_str, with_filename_str, \"foo\"); t!(s: \".\", set_filename_str, with_filename_str, \"foo\"); t!(s: \"a/b\", set_filename_str, with_filename_str, \"\"); t!(s: \"a\", set_filename_str, with_filename_str, \"\"); t!(v: b!(\"hi/there.txt\"), set_filestem, with_filestem, b!(\"here\")); t!(v: b!(\"hi/there\", 0x80, \".txt\"), set_filestem, with_filestem, b!(\"here\", 0xff)); t!(s: \"hi/there.txt\", set_filestem_str, with_filestem_str, \"here\"); t!(s: \"hi/there.\", set_filestem_str, with_filestem_str, \"here\"); t!(s: \"hi/there\", set_filestem_str, with_filestem_str, \"here\"); t!(s: \"hi/there.txt\", set_filestem_str, with_filestem_str, \"\"); t!(s: \"hi/there\", set_filestem_str, with_filestem_str, \"\"); t!(v: b!(\"hi/there.txt\"), set_extension, with_extension, b!(\"exe\")); t!(v: b!(\"hi/there.t\", 0x80, \"xt\"), set_extension, with_extension, b!(\"exe\", 0xff)); t!(s: \"hi/there.txt\", set_extension_str, with_extension_str, \"exe\"); t!(s: \"hi/there.\", set_extension_str, with_extension_str, \"txt\"); t!(s: \"hi/there\", set_extension_str, with_extension_str, \"txt\"); t!(s: \"hi/there.txt\", set_extension_str, with_extension_str, \"\"); t!(s: \"hi/there\", set_extension_str, with_extension_str, \"\"); t!(s: \".\", set_extension_str, with_extension_str, \"txt\"); } #[test] fn test_getters() { macro_rules! t( (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; assert_eq!(path.filename_str(), $filename); assert_eq!(path.dirname_str(), $dirname); assert_eq!(path.filestem_str(), $filestem); assert_eq!(path.extension_str(), $ext); } ); (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; assert_eq!(path.filename(), $filename); assert_eq!(path.dirname(), $dirname); assert_eq!(path.filestem(), $filestem); assert_eq!(path.extension(), $ext); } ) ) t!(v: Path::new(b!(\"a/b/c\")), b!(\"c\"), b!(\"a/b\"), b!(\"c\"), None); t!(v: Path::new(b!(\"a/b/\", 0xff)), b!(0xff), b!(\"a/b\"), b!(0xff), None); t!(v: Path::new(b!(\"hi/there.\", 0xff)), b!(\"there.\", 0xff), b!(\"hi\"), b!(\"there\"), Some(b!(0xff))); t!(s: Path::from_str(\"a/b/c\"), Some(\"c\"), Some(\"a/b\"), Some(\"c\"), None); t!(s: Path::from_str(\".\"), Some(\"\"), Some(\".\"), Some(\"\"), None); t!(s: Path::from_str(\"/\"), Some(\"\"), Some(\"/\"), Some(\"\"), None); t!(s: Path::from_str(\"..\"), Some(\"\"), Some(\"..\"), Some(\"\"), None); t!(s: Path::from_str(\"../..\"), Some(\"\"), Some(\"../..\"), Some(\"\"), None); t!(s: Path::from_str(\"hi/there.txt\"), Some(\"there.txt\"), Some(\"hi\"), Some(\"there\"), Some(\"txt\")); t!(s: Path::from_str(\"hi/there\"), Some(\"there\"), Some(\"hi\"), Some(\"there\"), None); t!(s: Path::from_str(\"hi/there.\"), Some(\"there.\"), Some(\"hi\"), Some(\"there\"), Some(\"\")); t!(s: Path::from_str(\"hi/.there\"), Some(\".there\"), Some(\"hi\"), Some(\".there\"), None); t!(s: Path::from_str(\"hi/..there\"), Some(\"..there\"), Some(\"hi\"), Some(\".\"), Some(\"there\")); t!(s: Path::new(b!(\"a/b/\", 0xff)), None, Some(\"a/b\"), None, None); t!(s: Path::new(b!(\"a/b/\", 0xff, \".txt\")), None, Some(\"a/b\"), None, Some(\"txt\")); t!(s: Path::new(b!(\"a/b/c.\", 0x80)), None, Some(\"a/b\"), Some(\"c\"), None); t!(s: Path::new(b!(0xff, \"/b\")), Some(\"b\"), None, Some(\"b\"), None); } #[test] fn test_dir_file_path() { t!(v: Path::new(b!(\"hi/there\", 0x80)).dir_path(), b!(\"hi\")); t!(v: Path::new(b!(\"hi\", 0xff, \"/there\")).dir_path(), b!(\"hi\", 0xff)); t!(s: Path::from_str(\"hi/there\").dir_path(), \"hi\"); t!(s: Path::from_str(\"hi\").dir_path(), \".\"); t!(s: Path::from_str(\"/hi\").dir_path(), \"/\"); t!(s: Path::from_str(\"/\").dir_path(), \"/\"); t!(s: Path::from_str(\"..\").dir_path(), \"..\"); t!(s: Path::from_str(\"../..\").dir_path(), \"../..\"); macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = $path; let left = path.and_then_ref(|p| p.as_str()); assert_eq!(left, $exp); } ); (v: $path:expr, $exp:expr) => ( { let path = $path; let left = path.map(|p| p.as_vec()); assert_eq!(left, $exp); } ) ) t!(v: Path::new(b!(\"hi/there\", 0x80)).file_path(), Some(b!(\"there\", 0x80))); t!(v: Path::new(b!(\"hi\", 0xff, \"/there\")).file_path(), Some(b!(\"there\"))); t!(s: Path::from_str(\"hi/there\").file_path(), Some(\"there\")); t!(s: Path::from_str(\"hi\").file_path(), Some(\"hi\")); t!(s: Path::from_str(\".\").file_path(), None); t!(s: Path::from_str(\"/\").file_path(), None); t!(s: Path::from_str(\"..\").file_path(), None); t!(s: Path::from_str(\"../..\").file_path(), None); } #[test] fn test_is_absolute() { assert_eq!(Path::from_str(\"a/b/c\").is_absolute(), false); assert_eq!(Path::from_str(\"/a/b/c\").is_absolute(), true); assert_eq!(Path::from_str(\"a\").is_absolute(), false); assert_eq!(Path::from_str(\"/a\").is_absolute(), true); assert_eq!(Path::from_str(\".\").is_absolute(), false); assert_eq!(Path::from_str(\"/\").is_absolute(), true); assert_eq!(Path::from_str(\"..\").is_absolute(), false); assert_eq!(Path::from_str(\"../..\").is_absolute(), false); } #[test] fn test_is_ancestor_of() { macro_rules! t( (s: $path:expr, $dest:expr, $exp:expr) => ( { let path = Path::from_str($path); let dest = Path::from_str($dest); assert_eq!(path.is_ancestor_of(&dest), $exp); } ) ) t!(s: \"a/b/c\", \"a/b/c/d\", true); t!(s: \"a/b/c\", \"a/b/c\", true); t!(s: \"a/b/c\", \"a/b\", false); t!(s: \"/a/b/c\", \"/a/b/c\", true); t!(s: \"/a/b\", \"/a/b/c\", true); t!(s: \"/a/b/c/d\", \"/a/b/c\", false); t!(s: \"/a/b\", \"a/b/c\", false); t!(s: \"a/b\", \"/a/b/c\", false); t!(s: \"a/b/c\", \"a/b/d\", false); t!(s: \"../a/b/c\", \"a/b/c\", false); t!(s: \"a/b/c\", \"../a/b/c\", false); t!(s: \"a/b/c\", \"a/b/cd\", false); t!(s: \"a/b/cd\", \"a/b/c\", false); t!(s: \"../a/b\", \"../a/b/c\", true); t!(s: \".\", \"a/b\", true); t!(s: \".\", \".\", true); t!(s: \"/\", \"/\", true); t!(s: \"/\", \"/a/b\", true); t!(s: \"..\", \"a/b\", true); t!(s: \"../..\", \"a/b\", true); } #[test] fn test_path_relative_from() { macro_rules! t( (s: $path:expr, $other:expr, $exp:expr) => ( { let path = Path::from_str($path); let other = Path::from_str($other); let res = path.path_relative_from(&other); assert_eq!(res.and_then_ref(|x| x.as_str()), $exp); } ) ) t!(s: \"a/b/c\", \"a/b\", Some(\"c\")); t!(s: \"a/b/c\", \"a/b/d\", Some(\"../c\")); t!(s: \"a/b/c\", \"a/b/c/d\", Some(\"..\")); t!(s: \"a/b/c\", \"a/b/c\", Some(\".\")); t!(s: \"a/b/c\", \"a/b/c/d/e\", Some(\"../..\")); t!(s: \"a/b/c\", \"a/d/e\", Some(\"../../b/c\")); t!(s: \"a/b/c\", \"d/e/f\", Some(\"../../../a/b/c\")); t!(s: \"a/b/c\", \"/a/b/c\", None); t!(s: \"/a/b/c\", \"a/b/c\", Some(\"/a/b/c\")); t!(s: \"/a/b/c\", \"/a/b/c/d\", Some(\"..\")); t!(s: \"/a/b/c\", \"/a/b\", Some(\"c\")); t!(s: \"/a/b/c\", \"/a/b/c/d/e\", Some(\"../..\")); t!(s: \"/a/b/c\", \"/a/d/e\", Some(\"../../b/c\")); t!(s: \"/a/b/c\", \"/d/e/f\", Some(\"../../../a/b/c\")); t!(s: \"hi/there.txt\", \"hi/there\", Some(\"../there.txt\")); t!(s: \".\", \"a\", Some(\"..\")); t!(s: \".\", \"a/b\", Some(\"../..\")); t!(s: \".\", \".\", Some(\".\")); t!(s: \"a\", \".\", Some(\"a\")); t!(s: \"a/b\", \".\", Some(\"a/b\")); t!(s: \"..\", \".\", Some(\"..\")); t!(s: \"a/b/c\", \"a/b/c\", Some(\".\")); t!(s: \"/a/b/c\", \"/a/b/c\", Some(\".\")); t!(s: \"/\", \"/\", Some(\".\")); t!(s: \"/\", \".\", Some(\"/\")); t!(s: \"../../a\", \"b\", Some(\"../../../a\")); t!(s: \"a\", \"../../b\", None); t!(s: \"../../a\", \"../../b\", Some(\"../a\")); t!(s: \"../../a\", \"../../a/b\", Some(\"..\")); t!(s: \"../../a/b\", \"../../a\", Some(\"b\")); } #[test] fn test_component_iter() { macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = Path::from_str($path); let comps = path.component_iter().to_owned_vec(); let exp: &[&str] = $exp; let exps = exp.iter().map(|x| x.as_bytes()).to_owned_vec(); assert_eq!(comps, exps); } ); (v: [$($arg:expr),+], [$([$($exp:expr),*]),*]) => ( { let path = Path::new(b!($($arg),+)); let comps = path.component_iter().to_owned_vec(); let exp: &[&[u8]] = [$(b!($($exp),*)),*]; assert_eq!(comps.as_slice(), exp); } ) ) t!(v: [\"a/b/c\"], [[\"a\"], [\"b\"], [\"c\"]]); t!(v: [\"/\", 0xff, \"/a/\", 0x80], [[0xff], [\"a\"], [0x80]]); t!(v: [\"../../foo\", 0xcd, \"bar\"], [[\"..\"], [\"..\"], [\"foo\", 0xcd, \"bar\"]]); t!(s: \"a/b/c\", [\"a\", \"b\", \"c\"]); t!(s: \"a/b/d\", [\"a\", \"b\", \"d\"]); t!(s: \"a/b/cd\", [\"a\", \"b\", \"cd\"]); t!(s: \"/a/b/c\", [\"a\", \"b\", \"c\"]); t!(s: \"a\", [\"a\"]); t!(s: \"/a\", [\"a\"]); t!(s: \"/\", []); t!(s: \".\", [\".\"]); t!(s: \"..\", [\"..\"]); t!(s: \"../..\", [\"..\", \"..\"]); t!(s: \"../../foo\", [\"..\", \"..\", \"foo\"]); } } "} {"_id":"q-en-rust-977c0c80333f37747f9d20a6309d69c6fe92a76339fb2b6ac592db54c4a49b81","text":"is_ty_must_use(cx, boxed_ty, expr, span) .map(|inner| MustUsePath::Boxed(Box::new(inner))) } ty::Adt(def, args) if cx.tcx.lang_items().pin_type() == Some(def.did()) => { let pinned_ty = args.type_at(0); is_ty_must_use(cx, pinned_ty, expr, span) .map(|inner| MustUsePath::Pinned(Box::new(inner))) } ty::Adt(def, _) => is_def_must_use(cx, def.did(), span), ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => { elaborate("} {"_id":"q-en-rust-978604a7be0674086db779480a7a37797206b6e9d3239790d9a447c581c1c687","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. #![allow(dead_code)] enum FooMode { Check = 0x1001, } enum BarMode { Check = 0x2001, } enum Mode { Foo(FooMode), Bar(BarMode), } #[inline(never)] fn broken(mode: &Mode) -> u32 { for _ in 0..1 { if let Mode::Foo(FooMode::Check) = *mode { return 17 } if let Mode::Bar(BarMode::Check) = *mode { return 19 } } return 42; } fn main() { let mode = Mode::Bar(BarMode::Check); assert_eq!(broken(&mode), 19); } "} {"_id":"q-en-rust-97b796b7df1f4fef113d7203a0dc41ad61965536c488fb909f1739222e4d9375","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. #[derive(Clone, Debug, PartialEq)] enum Expression { Dummy, Add(Box), } use Expression::*; fn simplify(exp: Expression) -> Expression { match exp { Add(n) => *n.clone(), _ => Dummy } } fn main() { assert_eq!(simplify(Add(Box::new(Dummy))), Dummy); } "} {"_id":"q-en-rust-97d14e654560aa8e7ee193be803659048910006b5c4ff78c794db376eb96f469","text":"} } //use private::Future; #[cfg(imported)] use private::Future; fn bar(arg: Box) { // Importing the trait means that we don't autoderef `Box` arg.wait(); //~^ ERROR the `wait` method cannot be invoked on a trait object //[unimported]~^ ERROR the `wait` method cannot be invoked on a trait object } fn main() { } fn main() {} "} {"_id":"q-en-rust-97d3513b4253c34389461477795ff568acd6315f945f5d2d47ed85b01e89243c","text":"InvocationKind::Derive { ref path, .. } => path.span, } } pub fn attr_id(&self) -> Option { match self.kind { InvocationKind::Attr { attr: Some(ref attr), .. } => Some(attr.id), _ => None, } } } pub struct MacroExpander<'a, 'b:'a> {"} {"_id":"q-en-rust-9858f7a72bb4ee3e8bc9371b358f6ab88df93e2ed15a5bdcb996db017489ecb4","text":"} fn crate_matches(&mut self, metadata: &MetadataBlob, libpath: &Path) -> Option { let root = metadata.get_root(); if let Some(is_proc_macro) = self.is_proc_macro { if root.macro_derive_registrar.is_some() != is_proc_macro { return None; } } let rustc_version = rustc_version(); if root.rustc_version != rustc_version { let found_version = metadata.get_rustc_version(); if found_version != rustc_version { info!(\"Rejecting via version: expected {} got {}\", rustc_version, root.rustc_version); found_version); self.rejected_via_version.push(CrateMismatch { path: libpath.to_path_buf(), got: root.rustc_version, got: found_version, }); return None; } let root = metadata.get_root(); if let Some(is_proc_macro) = self.is_proc_macro { if root.macro_derive_registrar.is_some() != is_proc_macro { return None; } } if self.should_match_name { if self.crate_name != root.name { info!(\"Rejecting via crate name\");"} {"_id":"q-en-rust-99149495629f63f4a440bf560e9cda408b47245b293f7cc9a2e0f34fdace6910","text":"fn foo<'a>() -> &'a () { Hash([0; HASH_LEN]); init_hash(&mut [0; HASH_LEN]); let (_array,) = ([0; HASH_LEN],); &() }"} {"_id":"q-en-rust-992845074d0beae932829b45f7db24905c43281783866b85e6bc1c64f671f30c","text":" Subproject commit 732825dcff6d1f115225305ce5e0c9c9d876a0ff Subproject commit e8642c7a2900bed28003a98d4db8b62290ac802f "} {"_id":"q-en-rust-9977312a1fb35a42d3da0d262b08403624b829fb63f762f9bd67d490d4738776","text":" error: implementation of `FnOnce` is not general enough --> $DIR/issue_74400.rs:12:5 | LL | f(data, identity) | ^ implementation of `FnOnce` is not general enough | = note: `fn(&'2 T) -> &'2 T {identity::<&'2 T>}` must implement `FnOnce<(&'1 T,)>`, for any lifetime `'1`... = note: ...but it actually implements `FnOnce<(&'2 T,)>`, for some specific lifetime `'2` error: aborting due to previous error "} {"_id":"q-en-rust-9979c163f2234e1280bbeae5c887349c36e74eb6d44341415a29d57a1e747505","text":"// stripping away any starting or ending parenthesis characters—hence this // test of the JSON error format. #![warn(unused_parens)] #![deny(unused_parens)] #![allow(unreachable_code)] fn main() { // We want to suggest the properly-balanced expression `1 / (2 + 3)`, not // the malformed `1 / (2 + 3` let _a = (1 / (2 + 3)); let _a = (1 / (2 + 3)); //~ERROR unnecessary parentheses f(); }"} {"_id":"q-en-rust-99ac72ee8abc0d2bbcbafbfa9868f8f28ada2d040c9790d16fcbd87d2baeb7ef","text":"/// # Examples /// /// ``` /// #![feature(mutex_unpoison)] /// /// use std::sync::{Arc, RwLock}; /// use std::thread; ///"} {"_id":"q-en-rust-99c54219595165d77c94e7f2f16b6061d4bde85a19fcd73fdbec3abc37069442","text":"// FIXME(valtrees): check whether const qualifs should behave the same // way for type and mir constants. let uneval = match constant.literal { ConstantKind::Ty(ct) if matches!(ct.kind(), ty::ConstKind::Param(_)) => None, ConstantKind::Ty(ct) if matches!(ct.kind(), ty::ConstKind::Param(_) | ty::ConstKind::Error(_)) => { None } ConstantKind::Ty(c) => bug!(\"expected ConstKind::Param here, found {:?}\", c), ConstantKind::Unevaluated(uv, _) => Some(uv), ConstantKind::Val(..) => None,"} {"_id":"q-en-rust-99d728035e523a42526ebc649b1900404acb2eb4b51f683d414144b725fd3cce","text":"} // At this point, we are calling a function, `callee`, whose `DefId` is known... if is_lang_panic_fn(tcx, callee) { self.check_op(ops::Panic); // const-eval of the `begin_panic` fn assumes the argument is `&str` if Some(callee) == tcx.lang_items().begin_panic_fn() { match args[0].ty(&self.ccx.body.local_decls, tcx).kind() { ty::Ref(_, ty, _) if ty.is_str() => (), _ => self.check_op(ops::PanicNonStr), } } return; }"} {"_id":"q-en-rust-99e5bd48b11b65cb22123ad5d38001e68527887d7a68741981643ef35e51cef1","text":"let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![ proc_macro, bridge, client, proc_macro_ty, method, ])); custom_derives.iter().map(|cd| { cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![ cx.expr_str(cd.span, cd.trait_name), cx.expr_vec_slice( span, cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::>() ), local_path(cd.span, cd.function_name), ]) }).chain(custom_attrs.iter().map(|ca| { cx.expr_call(span, proc_macro_ty_method_path(attr), vec![ cx.expr_str(ca.span, ca.function_name.name), local_path(ca.span, ca.function_name), ]) })).chain(custom_macros.iter().map(|cm| { cx.expr_call(span, proc_macro_ty_method_path(bang), vec![ cx.expr_str(cm.span, cm.function_name.name), local_path(cm.span, cm.function_name), ]) })).collect() macros.iter().map(|m| { match m { ProcMacro::Derive(cd) => { cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![ cx.expr_str(cd.span, cd.trait_name), cx.expr_vec_slice( span, cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::>() ), local_path(cd.span, cd.function_name), ]) }, ProcMacro::Def(ca) => { let ident = match ca.def_type { ProcMacroDefType::Attr => attr, ProcMacroDefType::Bang => bang }; cx.expr_call(span, proc_macro_ty_method_path(ident), vec![ cx.expr_str(ca.span, ca.function_name.name), local_path(ca.span, ca.function_name), ]) } } }).collect() }; let decls_static = cx.item_static("} {"_id":"q-en-rust-9a30f9bcdcaac2b5cf1055fe91eb8427ff4ea9f6df0a96bb37d0a09d7cbb1c39","text":"} } fn get_absolute_rpaths(libs: &[Path]) -> ~[Path] { vec::map(libs, |a| get_absolute_rpath(a) ) } pub fn get_absolute_rpath(lib: &Path) -> Path { os::make_absolute(lib).dir_path() } #[cfg(stage0)] pub fn get_install_prefix_rpath(target_triple: &str) -> Path { let install_prefix = env!(\"CFG_PREFIX\");"} {"_id":"q-en-rust-9a39f0731662a0439a07880224b3fecc2c3bfaa932e8adc3d220d0388b151699","text":"let attrs = self.parse_inner_attributes()?; let post_attr_lo = self.token.span; let mut items = ThinVec::new(); while let Some(item) = self.parse_item(ForceCollect::No)? { self.maybe_consume_incorrect_semicolon(Some(&item)); let mut items: ThinVec> = ThinVec::new(); // There shouldn't be any stray semicolons before or after items. // `parse_item` consumes the appropriate semicolons so any leftover is an error. loop { while self.maybe_consume_incorrect_semicolon(items.last().map(|x| &**x)) {} // Eat all bad semicolons let Some(item) = self.parse_item(ForceCollect::No)? else { break; }; items.push(item); }"} {"_id":"q-en-rust-9a3eaa152192d15ef53d683733c5c9c392b68d8e0cc569908c5152c0fe8c67f9","text":"# use this rustfmt binary instead as the stage0 snapshot rustfmt. #rustfmt = \"/path/to/rustfmt\" # Instead of downloading the src/stage0 version of cargo-clippy specified, # use this cargo-clippy binary instead as the stage0 snapshot cargo-clippy. # # Note that this option should be used with the same toolchain as the `rustc` option above. # Otherwise, clippy is likely to fail due to a toolchain conflict. #cargo-clippy = \"/path/to/cargo-clippy\" # Whether to build documentation by default. If false, rustdoc and # friends will still be compiled but they will not be used to generate any # documentation."} {"_id":"q-en-rust-9a4344123574086f3fdb11e15d1fa3cd2a399c373f89e3595aff3fa1a9c5b2ef","text":"LL | y.foo(); | ^ value used here after move error[E0382]: use of moved value: `*x` error[E0382]: use of moved value: `x` --> $DIR/double-move.rs:45:9 | LL | let _y = *x; | -- value moved here LL | x.foo(); | ^ value used here after move | ^ value used here after partial move | = note: move occurs because `*x` has type `str`, which does not implement the `Copy` trait error[E0382]: use of moved value: `*x` --> $DIR/double-move.rs:51:18 | LL | let x = \"hello\".to_owned().into_boxed_str(); | - move occurs because `x` has type `std::boxed::Box`, which does not implement the `Copy` trait LL | x.foo(); | - value moved here LL | let _y = *x; | ^^ value used here after move | = note: move occurs because `*x` has type `str`, which does not implement the `Copy` trait error: aborting due to 6 previous errors"} {"_id":"q-en-rust-9a83fc9f78700d48d487a5f8107e90e83eb27cb8394a6da7973c45a6fe804cfc","text":"# Complete! At this point, you have successfully built the Guessing Game! Congratulations! This project showed you a lot: `let`, `match`, methods, associated functions, using external crates, and more. This first project showed you a lot: `let`, `match`, methods, associated functions, using external crates, and more. Our next project will show off even more. At this point, you have successfully built the Guessing Game! Congratulations! "} {"_id":"q-en-rust-9a864c79d5f7576dcb7e6a5c804ddc2b0d19bb25c0f37360b865fc561b7ffd64","text":"LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod) { report_fatal_error(\"ThinLTO not available\"); } extern \"C\" void LLVMRustThinLTORemoveAvailableExternally(LLVMModuleRef Mod) { report_fatal_error(\"ThinLTO not available\"); } #endif // LLVM_VERSION_GE(4, 0)"} {"_id":"q-en-rust-9a9d26e98addf1868e11f3ae81e4260eb830539ef00563d4a65fd92f5821d879","text":"(&self_ty.kind, parent_pred) { if let ty::Adt(def, _) = p.skip_binder().trait_ref.self_ty().kind { let id = self.tcx.hir().as_local_hir_id(def.did).unwrap(); let node = self.tcx.hir().get(id); let node = self .tcx .hir() .as_local_hir_id(def.did) .map(|id| self.tcx.hir().get(id)); match node { hir::Node::Item(hir::Item { kind, .. }) => { Some(hir::Node::Item(hir::Item { kind, .. })) => { if let Some(g) = kind.generics() { let key = match &g.where_clause.predicates[..] { [.., pred] => {"} {"_id":"q-en-rust-9ab9238216208a639255e55ba7901653a22efe82ba25f045378fc55d20270622","text":"/// Unix-specific extensions to `Permissions` #[stable(feature = \"fs_ext\", since = \"1.1.0\")] pub trait PermissionsExt { /// Returns the underlying raw `mode_t` bits that are the standard Unix /// permissions for this file. /// Returns the underlying raw `st_mode` bits that contain the standard /// Unix permissions for this file. /// /// # Examples ///"} {"_id":"q-en-rust-9abb73820cedad68a8605de79954cab92ba723b0c0f3f8a5a1b9109bcbbc0629","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":"q-en-rust-9ac6eb2e47da44cf516961a833cbbb2d09a56b6197a13ed0104354e09a0890ca","text":"/// Sets the platform-specific value of errno #[cfg(all(not(target_os = \"linux\"), not(target_os = \"dragonfly\")))] // needed for readdir and syscall! #[allow(dead_code)] // but not all target cfgs actually end up using it pub fn set_errno(e: i32) { unsafe { *errno_location() = e as c_int } }"} {"_id":"q-en-rust-9ad0a62ef8f0f7114d878d46325cc234fbd256e521cf49a73bfe19e0595ccba2","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":"q-en-rust-9ad24ad2485a7a467ddc79d61a8e8cd28ebd0952f76441a6ee95a79df7991d0c","text":"let mut out = output.stderr.clone(); out.extend(&output.stdout); let out = String::from_utf8_lossy(&out); // Check to see if the link failed with \"unrecognized command line option: // '-no-pie'\" for gcc or \"unknown argument: '-no-pie'\" for clang. If so, // reperform the link step without the -no-pie option. This is safe because // if the linker doesn't support -no-pie then it should not default to // linking executables as pie. Different versions of gcc seem to use // different quotes in the error message so don't check for them. if sess.target.target.options.linker_is_gnu && (out.contains(\"unrecognized command line option\") || out.contains(\"unknown argument\")) && out.contains(\"-no-pie\") && cmd.get_args().iter().any(|e| e.to_string_lossy() == \"-no-pie\") { info!(\"linker output: {:?}\", out); warn!(\"Linker does not support -no-pie command line option. Retrying without.\"); for arg in cmd.take_args() { if arg.to_string_lossy() != \"-no-pie\" { cmd.arg(arg); } } info!(\"{:?}\", &cmd); continue; } if !retry_on_segfault || i > 3 { break } let msg_segv = \"clang: error: unable to execute command: Segmentation fault: 11\"; let msg_bus = \"clang: error: unable to execute command: Bus error: 10\"; if !(out.contains(msg_segv) || out.contains(msg_bus)) {"} {"_id":"q-en-rust-9b35e43dddbd72320c887f65142b18c2510a5d0580b3e5f383e3f762a27d6ff2","text":"| LL | let Alias::Braced = panic!(); | ^^^^^^^^^^^^^ not a unit struct, unit variant or constant | help: use the struct variant pattern syntax | LL | let Alias::Braced {} = panic!(); | ++ error[E0164]: expected tuple struct or tuple variant, found struct variant `Alias::Braced` --> $DIR/incorrect-variant-form-through-alias-caught.rs:12:9 | LL | let Alias::Braced(..) = panic!(); | ^^^^^^^^^^^^^^^^^ not a tuple struct or tuple variant | help: use the struct variant pattern syntax | LL | let Alias::Braced {} = panic!(); | ~~ error[E0618]: expected function, found enum variant `Alias::Unit` --> $DIR/incorrect-variant-form-through-alias-caught.rs:15:5"} {"_id":"q-en-rust-9b390e088592e4bf764f0920aad02e766aff03b7b6c7341606c6acbd9422b4ed","text":" // run-rustfix struct Foo { first: Bar, _second: u32, _third: u32, } struct Bar { bar: C, } struct C { c: D, } struct D { test: E, } struct E { _e: F, } struct F { _f: u32, } fn main() { let f = F { _f: 6 }; let e = E { _e: f }; let d = D { test: e }; let c = C { c: d }; let bar = Bar { bar: c }; let fooer = Foo { first: bar, _second: 4, _third: 5 }; let _test = &fooer.first.bar.c; //~^ ERROR no field let _test2 = fooer.first.bar.c.test; //~^ ERROR no field } "} {"_id":"q-en-rust-9b71b5fde73fcc1554bd061a4d5624f89293614d24d87cb9fa0dd02db921ffba","text":"// the problem is to add `T: 'r`, which isn't true. So, if there are no // inference variables, we use a verify constraint instead of adding // edges, which winds up enforcing the same condition. let is_opaque = alias_ty.kind(self.tcx) == ty::Opaque; if approx_env_bounds.is_empty() && trait_bounds.is_empty() && (alias_ty.needs_infer() || alias_ty.kind(self.tcx) == ty::Opaque) && (alias_ty.needs_infer() || is_opaque) { debug!(\"no declared bounds\"); self.substs_must_outlive(alias_ty.substs, origin, region); let opt_variances = is_opaque.then(|| self.tcx.variances_of(alias_ty.def_id)); self.substs_must_outlive(alias_ty.substs, origin, region, opt_variances); return; }"} {"_id":"q-en-rust-9bc1c75abc73cb64fd4125a1698f0bc0adbdf9220f812bf268bc690bb0ee6b2b","text":"[stackoverflow]: http://stackoverflow.com/questions/tagged/rust This installer also installs a copy of the documentation locally, so we can read it offline. On UNIX systems, `/usr/local/share/doc/rust` is the location. On Windows, it's in a `share/doc` directory, inside the directory to which Rust was installed. read it offline. It's only a `rustup doc` away! # Hello, world!"} {"_id":"q-en-rust-9bd3bd6e0a998a4d48445f3b365d561104b2dc603c3b8788e1b34f18923f5f18","text":".emit(); } let key = BindingKey::new(target, ns); let mut resolution = this.resolution(parent, key).borrow_mut(); resolution.single_imports.remove(&Interned::new_unchecked(import)); this.update_resolution(parent, key, |_, resolution| { resolution.single_imports.remove(&Interned::new_unchecked(import)); }); } } }"} {"_id":"q-en-rust-9bda1228dddf7471639f15a6069043ba20a998a61d68943c2649536fe0d695bd","text":" - // MIR for `call` before Inline + // MIR for `call` after Inline fn call(_1: &T) -> TypeId { debug s => _1; let mut _0: std::any::TypeId; let mut _2: &T; bb0: { StorageLive(_2); _2 = &(*_1); _0 = ::type_id(move _2) -> [return: bb1, unwind unreachable]; } bb1: { StorageDead(_2); return; } } "} {"_id":"q-en-rust-9beb3742b7e170f95daa6d8ea1ba13fa5db2ca4f76af64a31cb70d37ca135fa6","text":"debug!(?closure_sig); // (1) Feels icky to skip the binder here, but OTOH we know // that the self-type is an unboxed closure type and hence is // NOTE: The self-type is an unboxed closure type and hence is // in fact unparameterized (or at least does not reference any // regions bound in the obligation). Still probably some // refactoring could make this nicer. // regions bound in the obligation). let self_ty = obligation .predicate .self_ty() .no_bound_vars() .expect(\"unboxed closure type should not capture bound vars from the predicate\"); closure_trait_ref_and_return_type( self.tcx(), obligation.predicate.def_id(), obligation.predicate.skip_binder().self_ty(), // (1) self_ty, closure_sig, util::TupleArgumentsFlag::No, )"} {"_id":"q-en-rust-9beea4d0f77dee97eaef9fc1b3bb00b1bbdf19151352a265bb9fa0b58a9feeae","text":" #![feature(doc_cfg)] #![feature(no_core)] #![crate_name = \"foo\"] #![no_core] // @has 'foo/index.html' // @has - '//*[@class=\"item-left module-item\"]/*[@class=\"stab portability\"]' 'foobar' // @has - '//*[@class=\"item-left module-item\"]/*[@class=\"stab portability\"]' 'bar' #[doc(cfg(feature = \"foobar\"))] mod imp_priv { // @has 'foo/struct.BarPriv.html' // @has - '//*[@id=\"main-content\"]/*[@class=\"item-info\"]/*[@class=\"stab portability\"]' // 'Available on crate feature foobar only.' pub struct BarPriv {} impl BarPriv { pub fn test() {} } } #[doc(cfg(feature = \"foobar\"))] pub use crate::imp_priv::*; pub mod bar { // @has 'foo/bar/struct.Bar.html' // @has - '//*[@id=\"main-content\"]/*[@class=\"item-info\"]/*[@class=\"stab portability\"]' // 'Available on crate feature bar only.' #[doc(cfg(feature = \"bar\"))] pub struct Bar; } #[doc(cfg(feature = \"bar\"))] pub use bar::Bar; "} {"_id":"q-en-rust-9c0fa58cbe546c444181fc70346c59cff427dab29c7b8427b1204d63cf7e93b9","text":" #![feature(return_position_impl_trait_in_trait)] trait Extend { fn extend(_: &str) -> (impl Sized + '_, &'static str); } impl Extend for () { fn extend(s: &str) -> (Option<&'static &'_ ()>, &'static str) { //~^ ERROR in type `&'static &()`, reference has a longer lifetime than the data it references (None, s) } } // This indirection is not necessary for reproduction, // but it makes this test future-proof against #114936. fn extend(s: &str) -> &'static str { ::extend(s).1 } fn main() { let use_after_free = extend::<()>(&String::from(\"temporary\")); println!(\"{}\", use_after_free); } "} {"_id":"q-en-rust-9c254ef3db3de1cdce3d3714eec525aecdb60297f8cdd85298f6653966fdc982","text":"setTimeout(() => { window.location.replace(\"#\" + item.id); }, 0); return true; } }, ); } }); } } }"} {"_id":"q-en-rust-9c275cfe9024dcb2b8d97cd06fb8977c9d543ea76a3a8bfea16d44adee200da5","text":" error[E0308]: mismatched types --> $DIR/str-as-char-non-lit.rs:6:19 | LL | let _: &str = ('a'); | ---- ^^^^^ expected `&str`, found `char` | | | expected due to this error[E0308]: mismatched types --> $DIR/str-as-char-non-lit.rs:8:19 | LL | let _: &str = token(); | ---- ^^^^^^^ expected `&str`, found `char` | | | expected due to this error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-9c29561ad936ae3dbf03f4dee8ff5e36e5626004928f502088276921c936553a","text":" //! Normalizes MIR in RevealAll mode. use crate::MirPass; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::{self, Ty, TyCtxt}; pub struct RevealAll; impl<'tcx> MirPass<'tcx> for RevealAll { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // This pass must run before inlining, since we insert callee bodies in RevealAll mode. // Do not apply this transformation to generators. if (tcx.sess.mir_opt_level() >= 3 || !super::inline::is_enabled(tcx)) && body.generator.is_none() { let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); RevealAllVisitor { tcx, param_env }.visit_body(body); } } } struct RevealAllVisitor<'tcx> { tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, } impl<'tcx> MutVisitor<'tcx> for RevealAllVisitor<'tcx> { #[inline] fn tcx(&self) -> TyCtxt<'tcx> { self.tcx } #[inline] fn visit_ty(&mut self, ty: &mut Ty<'tcx>, _: TyContext) { *ty = self.tcx.normalize_erasing_regions(self.param_env, ty); } #[inline] fn process_projection_elem( &mut self, elem: PlaceElem<'tcx>, _: Location, ) -> Option> { match elem { PlaceElem::Field(field, ty) => { let new_ty = self.tcx.normalize_erasing_regions(self.param_env, ty); if ty != new_ty { Some(PlaceElem::Field(field, new_ty)) } else { None } } // None of those contain a Ty. PlaceElem::Index(..) | PlaceElem::Deref | PlaceElem::ConstantIndex { .. } | PlaceElem::Subslice { .. } | PlaceElem::Downcast(..) => None, } } } "} {"_id":"q-en-rust-9c39350bb6041d77048ecc2c8001fedfe2117c776dfc971cb0a6ed287cb72ec0","text":" //@ check-pass #![deny(rustdoc::redundant_explicit_links)] mod bar { /// [`Rc`](std::rc::Rc) pub enum Baz {} } pub use bar::*; use std::rc::Rc; /// [`Rc::allocator`] [foo](std::rc::Rc) pub fn winit_runner() {} "} {"_id":"q-en-rust-9c42ca862b818e5726074f8f3be5bd46c6914289555ce5300471c21ca9d1ba08","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":"q-en-rust-9c866109297c9ae36fc64a0a0dc701fa0f6c1512c95fe2e8495840ad9b8419a5","text":"TypeLimits, MissingDoc, MissingDebugImplementations, ExternCrate, ); add_lint_group!(sess,"} {"_id":"q-en-rust-9c9baff8a0ed971f89042e3c7628b90a770e2d45d11eeff3772dfd0fbd956273","text":"sess.abort_if_errors() } } a.add_file(&bc, false); a.add_file(&bc_deflated, false); remove(sess, &bc_deflated); if !sess.opts.cg.save_temps && !sess.opts.output_types.contains(&OutputTypeBitcode) { remove(sess, &bc);"} {"_id":"q-en-rust-9ca50671be9993351fad2ad92823007d5242a851065a3b778346f21a2bae908c","text":"/// assert_eq!(&l_ptr[..2], \"0x\"); /// ``` #[stable(feature = \"rust1\", since = \"1.0.0\")] #[rustc_diagnostic_item = \"pointer_trait\"] pub trait Pointer { /// Formats the value using the given formatter. #[stable(feature = \"rust1\", since = \"1.0.0\")] #[rustc_diagnostic_item = \"pointer_trait_fmt\"] fn fmt(&self, f: &mut Formatter<'_>) -> Result; }"} {"_id":"q-en-rust-9cd421c8532235a9996184b485063971504d628247031e3e4f4f79fffd97b7f1","text":" // Issue #117720 #![feature(let_chains)] fn main() { if let () = () && let () = (); //~ERROR && let () = () { } } fn foo() { if let () = () && () == (); //~ERROR && 1 < 0 { } } fn bar() { if let () = () && () == (); //~ERROR && let () = () { } } "} {"_id":"q-en-rust-9ce6e7db2fd07599323cb6e87a347e7ec1d0bfac18af85a2738076cdad28c143","text":"} fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) { use middle::ty::TypeVariants::{TyEnum, TyStruct}; // If `bar` is a trait item, make sure to mark Foo as alive in `Foo::bar` self.tcx.tables.borrow().item_substs.get(id) .and_then(|substs| substs.substs.self_ty()) .map(|ty| match ty.sty { TyEnum(tyid, _) | TyStruct(tyid, _) => self.check_def_id(tyid.did), _ => (), }); self.tcx.def_map.borrow().get(id).map(|def| { match def.full_def() { def::DefConst(_) | def::DefAssociatedConst(..) => {"} {"_id":"q-en-rust-9ceafb433cb228a43c5cc164761d71d7214c3429d57d40af511c228b9fb90435","text":"// Finally we construct the actual value of the associated type. let term = match assoc_def.item.kind { ty::AssocKind::Type => tcx.type_of(assoc_def.item.def_id).map_bound(|ty| ty.into()), ty::AssocKind::Const => bug!(\"associated const projection is not supported yet\"), ty::AssocKind::Const => { if tcx.features().associated_const_equality { bug!(\"associated const projection is not supported yet\") } else { ty::EarlyBinder::bind( ty::Const::new_error_with_message( tcx, tcx.type_of(assoc_def.item.def_id).instantiate_identity(), DUMMY_SP, \"associated const projection is not supported yet\", ) .into(), ) } } ty::AssocKind::Fn => unreachable!(\"we should never project to a fn\"), };"} {"_id":"q-en-rust-9cec961e71dcac175156eaa7373fd8d9a9a51578e163d8a4839b9f5dd0f60657","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":"q-en-rust-9d0d990273742042940e8f23b90abf665ab60b6ba1ba128606540d4e1bbc0770","text":"} } fn foreign_item_scope_tag(item: &hir::ForeignItem<'_>) -> &'static str { match item.kind { hir::ForeignItemKind::Fn(..) => \"method body\", hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => \"associated item\", } } fn explain_span(tcx: TyCtxt<'tcx>, heading: &str, span: Span) -> (String, Option) { let lo = tcx.sess.source_map().lookup_char_pos(span.lo()); (format!(\"the {} at {}:{}\", heading, lo.line, lo.col.to_usize() + 1), Some(span))"} {"_id":"q-en-rust-9d2abd8dd95b678aaca2e05c02a4adb2f6c0321bb74ccdf44670f84f85f406b5","text":".map(|r| VerifyBound::OutlivedBy(r)); // see the extensive comment in projection_must_outlive let ty = self.tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs); let recursive_bound = self.recursive_bound(ty.into(), visited); let recursive_bound = { let mut components = smallvec![]; let ty = self.tcx.mk_projection(projection_ty.item_def_id, projection_ty.substs); compute_components_recursive(self.tcx, ty.into(), &mut components, visited); self.bound_from_components(&components, visited) }; VerifyBound::AnyBound(env_bounds.chain(trait_bounds).collect()).or(recursive_bound) } fn recursive_bound( fn bound_from_components( &self, parent: GenericArg<'tcx>, components: &[Component<'tcx>], visited: &mut SsoHashSet>, ) -> VerifyBound<'tcx> { let mut bounds = parent .walk_shallow(visited) .filter_map(|child| match child.unpack() { GenericArgKind::Type(ty) => Some(self.type_bound(ty, visited)), GenericArgKind::Lifetime(lt) => { // Ignore late-bound regions. if !lt.is_late_bound() { Some(VerifyBound::OutlivedBy(lt)) } else { None } } GenericArgKind::Const(_) => Some(self.recursive_bound(child, visited)), }) let mut bounds = components .iter() .map(|component| self.bound_from_single_component(component, visited)) .filter(|bound| { // Remove bounds that must hold, since they are not interesting. !bound.must_hold()"} {"_id":"q-en-rust-9d6c9deb72ed9a54f2d2f3323752a03f60e14a127cd6de990173d14cba539b43","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":"q-en-rust-9d87a2438bdc3bf9aad0b24d67cef63a4337c6431216583c2a236143f84959f2","text":"check_expr(fcx, &**idx); let raw_base_t = fcx.expr_ty(&**base); let idx_t = fcx.expr_ty(&**idx); if ty::type_is_error(raw_base_t) || ty::type_is_bot(raw_base_t) { if ty::type_is_error(raw_base_t) { fcx.write_ty(id, raw_base_t); } else if ty::type_is_error(idx_t) || ty::type_is_bot(idx_t) { } else if ty::type_is_error(idx_t) { fcx.write_ty(id, idx_t); } else { let (_, autoderefs, field_ty) = autoderef(fcx, expr.span, raw_base_t, Some(base.id), lvalue_pref, |base_t, _| ty::index(base_t)); match field_ty { Some(ty) => { Some(ty) if !ty::type_is_bot(ty) => { check_expr_has_type(fcx, &**idx, ty::mk_uint()); fcx.write_ty(id, ty); fcx.write_autoderef_adjustment(base.id, base.span, autoderefs); } None => { _ => { // This is an overloaded method. let base_t = structurally_resolved_type(fcx, expr.span,"} {"_id":"q-en-rust-9d89377b6123bfa9c0405e2a7ef3b5f38333e5386208bd68d01876969848634e","text":"path = self.parse_path(PathStyle::Type)?; path_span = path_lo.to(self.prev_span); } else { path = ast::Path { segments: Vec::new(), span: DUMMY_SP }; path_span = self.span.to(self.span); path = ast::Path { segments: Vec::new(), span: path_span }; } // See doc comment for `unmatched_angle_bracket_count`."} {"_id":"q-en-rust-9d899ed14e0518fe8f0efb4c188c29d5e15f2d627fc4d2a7824867fa1b4af68e","text":"res } // Clears (and restores) the `in_scope_lifetimes` field. Used when // visiting nested items, which never inherit in-scope lifetimes // from their surrounding environment. fn without_in_scope_lifetime_defs( &mut self, f: impl FnOnce(&mut LoweringContext<'_>) -> T, ) -> T { let old_in_scope_lifetimes = std::mem::replace(&mut self.in_scope_lifetimes, vec![]); // this vector is only used when walking over impl headers, // input types, and the like, and should not be non-empty in // between items assert!(self.lifetimes_to_define.is_empty()); let res = f(self); assert!(self.in_scope_lifetimes.is_empty()); self.in_scope_lifetimes = old_in_scope_lifetimes; res } pub(super) fn lower_mod(&mut self, m: &Mod) -> hir::Mod { hir::Mod { inner: m.inner,"} {"_id":"q-en-rust-9d8c6d880c99ebca1c3992108fa45a83bb68838e37f3b017b6833b21efe98157","text":"} pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode self.masked() == mode } fn masked(&self) -> mode_t { self.mode & libc::S_IFMT } }"} {"_id":"q-en-rust-9dd1879698d922ae29c496a045f5eb035650afb30cb9ca859692f7e7a642c35c","text":" error: pattern on wrong side of `@` --> $DIR/intersection-patterns.rs:13:9 | LL | Some(x) @ y => {} | -------^^^- | | | | | binding on the right, should be on the left | pattern on the left, should be on the right | help: switch the order: `y @ Some(x)` error: left-hand side of `@` must be a binding --> $DIR/intersection-patterns.rs:23:9 | LL | Some(x) @ Some(y) => {} | -------^^^------- | | | | | also a pattern | interpreted as a pattern, not a binding | = note: bindings are `x`, `mut x`, `ref x`, and `ref mut x` error: pattern on wrong side of `@` --> $DIR/intersection-patterns.rs:32:9 | LL | 1 ..= 5 @ e => {} | -------^^^- | | | | | binding on the right, should be on the left | pattern on the left, should be on the right | help: switch the order: `e @ 1 ..=5` error: aborting due to 3 previous errors "} {"_id":"q-en-rust-9df45ddc28ab8a49da38cdb8604999f3501f8a23554827f887ab00570d412062","text":"def::DefVariant(_, variant_id, _) => { for field in fields { self.check_field(expr.span, variant_id, NamedField(field.ident.node)); NamedField(field.ident.node.name)); } } _ => self.tcx.sess.span_bug(expr.span,"} {"_id":"q-en-rust-9e326be467fce2de0a4383c7fb5490b8b637ac2665c1d7366ca0bad6f84a8aca","text":"self.opts.debugging_opts.print_enum_sizes } pub fn nonzeroing_move_hints(&self) -> bool { !self.opts.debugging_opts.disable_nonzeroing_move_hints self.opts.debugging_opts.enable_nonzeroing_move_hints } pub fn sysroot<'a>(&'a self) -> &'a Path { match self.opts.maybe_sysroot {"} {"_id":"q-en-rust-9e5a15545918bb86695b44edf3c577c5ace0b547a05a3dd1baac9c1c4004e102","text":"format!(\"*{}\", code) }; return Some(( sp, expr.span, message, suggestion, Applicability::MachineApplicable,"} {"_id":"q-en-rust-9e7d64a96ad236c76675569bac428927e58aa5f646168470530d899b21018246","text":"// Encode the command and arguments in a command line string such // that the spawned process may recover them using CommandLineToArgvW. let mut cmd: Vec = Vec::new(); // CreateFileW has special handling for .bat and .cmd files, which means we // need to add an extra pair of quotes surrounding the whole command line // so they are properly passed on to the script. // See issue #91991. let is_batch_file = Path::new(prog) .extension() .map(|ext| ext.eq_ignore_ascii_case(\"cmd\") || ext.eq_ignore_ascii_case(\"bat\")) .unwrap_or(false); if is_batch_file { cmd.push(b'\"' as u16); } // Always quote the program name so CreateProcess doesn't interpret args as // part of the name if the binary wasn't found first time. append_arg(&mut cmd, prog, Quote::Always)?;"} {"_id":"q-en-rust-9ea2ce22a36061aa0710fea17ad3282d08bf9fc6ff5c2fd43f75d1f6ce1445cf","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":"q-en-rust-9eea7f5f19d6c453b99df4902291d9ab299c1421a6f0c2b8b4ac6b8e56cea50e","text":"// on the GAT itself. for (region_b, region_b_idx) in ®ions { // Again, skip `'static` because it outlives everything. Also, we trivially // know that a region outlives itself. if ty::ReStatic == **region_b || region_a == region_b { // know that a region outlives itself. Also ignore `ReError`, to avoid // knock-down errors. if matches!(**region_b, ty::ReStatic | ty::ReError(_)) || region_a == region_b { continue; } if region_known_to_outlive("} {"_id":"q-en-rust-9efdfa3dfc3d5ad8daa5d909e0ecc1e2ab574a52bdf68c4f7d03c362c0cff854","text":"35 | #[unstable = \"1200\"] impl S { } | ^^^^^^^^^^^^^^^^^^^^ error: aborting due to 9 previous errors error: aborting due to 8 previous errors "} {"_id":"q-en-rust-9f00bcaa467b892ac80054063ae8a954a62a2cd75df34d166c76a7ef2cd9f2a3","text":"\"byteorder\", \"cargo_metadata 0.9.1\", \"colored\", \"compiletest_rs\", \"compiletest_rs 0.4.0\", \"directories\", \"env_logger 0.7.1\", \"getrandom\","} {"_id":"q-en-rust-9f1af126dc65b35b1652e39d497e10292fb80ff13a5027b2b8344d81f7c67ef4","text":"let break_x = self.with_loop_scope(loop_node_id, move |this| { let expr_break = hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr)); this.arena.alloc(this.expr(span, expr_break, ThinVec::new())) this.arena.alloc(this.expr(gen_future_span, expr_break, ThinVec::new())) }); self.arm(ready_pat, break_x) };"} {"_id":"q-en-rust-9f342cd547aaf6d148122ca30a202bd7b24cdff36461511c4d05c72a24e57327","text":"use std::mem; use crate::errors::{ ChangeFieldsToBeOfUnitType, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment, ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment, }; // Any local node that may call something in its body block should be"} {"_id":"q-en-rust-9f639667326bbb920e0ea15e151c3675f6124742fc06835784bd72420ced7737","text":"// A rest pattern `..`. self.bump(); // `..` PatKind::Rest } else if self.check(&token::DotDotDot) && !self.is_pat_range_end_start(1) { self.recover_dotdotdot_rest_pat(lo) } else if let Some(form) = self.parse_range_end() { self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`. } else if self.eat_keyword(kw::Underscore) {"} {"_id":"q-en-rust-9f7e574cd2a32267f3481d536317276b955a807356fad6645a92f2f804e959eb","text":"unsafe { let mut fds = [0, 0]; // Like above, see if we can set cloexec atomically #[cfg(target_os = \"linux\")] { match cvt(libc::socketpair(fam, ty | libc::SOCK_CLOEXEC, 0, fds.as_mut_ptr())) { Ok(_) => { return Ok((Socket(FileDesc::new(fds[0])), Socket(FileDesc::new(fds[1])))); } Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} Err(e) => return Err(e), cfg_if::cfg_if! { if #[cfg(target_os = \"linux\")] { // Like above, set cloexec atomically cvt(libc::socketpair(fam, ty | libc::SOCK_CLOEXEC, 0, fds.as_mut_ptr()))?; Ok((Socket(FileDesc::new(fds[0])), Socket(FileDesc::new(fds[1])))) } else { cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?; let a = FileDesc::new(fds[0]); let b = FileDesc::new(fds[1]); a.set_cloexec()?; b.set_cloexec()?; Ok((Socket(a), Socket(b))) } } cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?; let a = FileDesc::new(fds[0]); let b = FileDesc::new(fds[1]); a.set_cloexec()?; b.set_cloexec()?; Ok((Socket(a), Socket(b))) } }"} {"_id":"q-en-rust-9f95e81bb222ceabed5391f095fbb15d792eacefde27d0b8011f6b9631a2b2f4","text":" error[E0309]: the parameter type `T` may not live long enough --> $DIR/min-choice-reject-ambiguous.rs:17:5 | LL | type_test::<'_, T>() // This should pass if we pick 'b. | ^^^^^^^^^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds | help: consider adding an explicit lifetime bound... | LL | T: 'b + 'a, | ++++ error[E0309]: the parameter type `T` may not live long enough --> $DIR/min-choice-reject-ambiguous.rs:28:5 | LL | type_test::<'_, T>() // This should pass if we pick 'c. | ^^^^^^^^^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds | help: consider adding an explicit lifetime bound... | LL | T: 'c + 'a, | ++++ error[E0700]: hidden type for `impl Cap<'b> + Cap<'c>` captures lifetime that does not appear in bounds --> $DIR/min-choice-reject-ambiguous.rs:39:5 | LL | fn test_ambiguous<'a, 'b, 'c>(s: &'a u8) -> impl Cap<'b> + Cap<'c> | -- hidden type `&'a u8` captures the lifetime `'a` as defined here ... LL | s | ^ | help: to declare that `impl Cap<'b> + Cap<'c>` captures `'a`, you can add an explicit `'a` lifetime bound | LL | fn test_ambiguous<'a, 'b, 'c>(s: &'a u8) -> impl Cap<'b> + Cap<'c> + 'a | ++++ error: aborting due to 3 previous errors Some errors have detailed explanations: E0309, E0700. For more information about an error, try `rustc --explain E0309`. "} {"_id":"q-en-rust-9fa2e55de3214c639f3fd23fc7918e3ebaa357867d879b631c9b2e151d852feb","text":" // This is a non-regression test for issue #117146, where NLL and `-Zpolonius=next` computed // different loan scopes when a region flowed into an SCC whose representative was an existential // region. // revisions: nll polonius // [polonius] compile-flags: -Zpolonius=next fn main() { let a = (); let b = |_| &a; //[nll]~^ ERROR `a` does not live long enough //[polonius]~^^ ERROR `a` does not live long enough bad(&b); //[nll]~^ ERROR implementation of `Fn` //[nll]~| ERROR implementation of `FnOnce` //[polonius]~^^^ ERROR implementation of `Fn` //[polonius]~| ERROR implementation of `FnOnce` } fn bad &()>(_: F) {} "} {"_id":"q-en-rust-9fb0599d05137dd818c9e4b2c1e86f8ff2902c9f05836ff418a3af713785d9ea","text":"Some((ident.name, ns)), ) } /// Construct the list of in-scope lifetime parameters for async lowering. /// We include all lifetime parameters, either named or \"Fresh\". /// The order of those parameters does not matter, as long as it is /// deterministic. fn record_lifetime_params_for_async( &mut self, fn_id: NodeId, async_node_id: Option<(NodeId, Span)>, ) { if let Some((async_node_id, _)) = async_node_id { let mut extra_lifetime_params = self.r.extra_lifetime_params_map.get(&fn_id).cloned().unwrap_or_default(); for rib in self.lifetime_ribs.iter().rev() { extra_lifetime_params.extend( rib.bindings.iter().map(|(&ident, &(node_id, res))| (ident, node_id, res)), ); match rib.kind { LifetimeRibKind::Item => break, LifetimeRibKind::AnonymousCreateParameter { binder, .. } => { if let Some(earlier_fresh) = self.r.extra_lifetime_params_map.get(&binder) { extra_lifetime_params.extend(earlier_fresh); } } _ => {} } } self.r.extra_lifetime_params_map.insert(async_node_id, extra_lifetime_params); } } } struct LifetimeCountVisitor<'a, 'b> {"} {"_id":"q-en-rust-9fb54fb16eed96a9df592fa95d62839726294ae235d9f7fe1e6caed82f2fb9ad","text":"fn make_items(mut self: Box>) -> Option>> { let mut ret = SmallVector::zero(); loop { while self.p.token != token::Eof { match self.p.parse_item_with_outer_attributes() { Some(item) => ret.push(item), None => break None => self.p.span_fatal( self.p.span, &format!(\"expected item, found `{}`\", self.p.this_token_to_string())[] ) } } Some(ret)"} {"_id":"q-en-rust-9fb88338e3f0f8e2f9a7b56581817246229fa83c97718a8056cbbf7b8a3ee0c3","text":"self.tcx().mk_region(ReScope(lub)) } (&ReEarlyBound(_), &ReEarlyBound(_) | &ReFree(_)) | (&ReFree(_), &ReEarlyBound(_) | &ReFree(_)) => { (&ReEarlyBound(_) | &ReFree(_), &ReEarlyBound(_) | &ReFree(_)) => { self.region_rels.lub_free_regions(a, b) }"} {"_id":"q-en-rust-9fbe00d2fc1616d83ac6edab4d11b39650beeeac77935ce2210142cc8777716f","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":"q-en-rust-9fcf30aae380e0b344e6962951ecdbae3316d6ab725ff821f65d1319407ae067","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":"q-en-rust-9feee5106f4c92cea7a9d0db112be2c558374a387b21343da9d9cbeda795550c","text":" // This test is a regression test for #34792 // check-pass pub struct A; pub struct B; pub trait Foo { type T: PartialEq + PartialEq; } pub fn generic(t: F::T, a: A, b: B) -> bool { t == a && t == b } pub fn main() {} "} {"_id":"q-en-rust-a021b8d25e2cd590ab973c8abc6ca9f252b6ba8aae8ca8e0c94301492e3ef518","text":"return; } // #90113: Do not count an inaccessible reexported item as a candidate. if let NameBindingKind::Import { binding, .. } = name_binding.kind { if this.is_accessible_from(binding.vis, parent_scope.module) && !this.is_accessible_from(name_binding.vis, parent_scope.module) { return; } } // collect results based on the filter function // avoid suggesting anything from the same module in which we are resolving if ident.name == lookup_ident.name"} {"_id":"q-en-rust-a053b1b13150643fa62684a602d57de1825acc79e31111722244af204dcebfe5","text":"hir_typeck_convert_to_str = try converting the passed type into a `&str` hir_typeck_ctor_is_private = tuple struct constructor `{$def}` is private hir_typeck_expected_default_return_type = expected `()` because of default return type hir_typeck_expected_return_type = expected `{$expected}` because of return type"} {"_id":"q-en-rust-a064bb9df5c69ca6a2475f71ac6bacb7867febc0650126db0064fb5feae759c2","text":" //@ run-pass // Tests against a regression surfaced by crater in https://github.com/rust-lang/rust/issues/125193 // Unwind Safety is not a very coherent concept, but we'd prefer no regressions until we kibosh it // and this is an unstable feature anyways sooo... use std::panic::UnwindSafe; use std::task::Context; fn unwind_safe() {} fn main() { unwind_safe::>(); // test UnwindSafe unwind_safe::<&Context<'_>>(); // test RefUnwindSafe } "} {"_id":"q-en-rust-a079595a909eff9d8dfdfde1fbb0af2c417c402ff562b6efcc2513fc55421a06","text":" #![feature(half_open_range_patterns)] fn main() { match [1, 2] { [a.., a] => {} //~ ERROR cannot find value `a` in this scope } } "} {"_id":"q-en-rust-a08b6412118c08d6089f0bb94ee4311b337e014a9ac18d746f8f2461e5338ef2","text":"//! The various pretty-printing routines. use crate::session_diagnostics::UnprettyDumpFail; use rustc_ast as ast; use rustc_ast_pretty::pprust; use rustc_errors::ErrorGuaranteed;"} {"_id":"q-en-rust-a0cdaa3c380018988f8e47e1bc2258968b7714d023833ade0396203c899283a3","text":"_ => unreachable!(), }; write_or_print(&out, ofile); write_or_print(&out, ofile, tcx.sess); } // In an ideal world, this would be a public function called by the driver after"} {"_id":"q-en-rust-a0e51632f354481f171b273d481d280d36b0fa31c652250b092e15c7b9b37117","text":" // check-pass #![feature(generic_associated_types)] pub trait Foo { type Assoc<'c>; fn function() -> for<'x> fn(Self::Assoc<'x>); } fn main() {} "} {"_id":"q-en-rust-a0ed3b7b72e0a7ebceef4dffd01e8d6e3bbb9d9f2c69e90c57acb95e3a7e0db7","text":"// Confirm the `type Output: Sized;` bound that is present on `FnOnce` let cause = obligation.derived_cause(BuiltinDerivedObligation); // The binder on the Fn obligation is \"less\" important than the one on // the signature, as evidenced by how we treat it during projection. // The safe thing to do here is to liberate it, though, which should // have no worse effect than skipping the binder here. let liberated_fn_ty = self.infcx.replace_bound_vars_with_placeholders(obligation.predicate.rebind(self_ty)); let output_ty = self .infcx .replace_bound_vars_with_placeholders(liberated_fn_ty.fn_sig(self.tcx()).output()); let output_ty = self.infcx.replace_bound_vars_with_placeholders(sig.output()); let output_ty = normalize_with_depth_to( self, obligation.param_env,"} {"_id":"q-en-rust-a111f00af53879584166ccd6f0f722026c820777e55b2c2acdc8e4a4b7a939a6","text":"use syntax_pos::symbol::Symbol; use rustc::session::Session; use rustc::session::config::PrintRequest; use rustc_data_structures::fx::FxHashSet; use rustc_target::spec::{MergeFunctions, PanicStrategy}; use libc::c_int; use std::ffi::CString;"} {"_id":"q-en-rust-a130d5c261b6eb5b0f1b230d2da65293ea3c8f09a3df7214b1f8da454738beda","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:issue-11908-1.rs // ignore-android this test is incompatible with the android test runner // error-pattern: multiple dylib candidates for `collections` found // This test ensures that if you have the same rlib or dylib at two locations // in the same path that you don't hit an assertion in the compiler. // // Note that this relies on `libcollections` to be in the path somewhere else, // and then our aux-built libraries will collide with libcollections (they have // the same version listed) extern crate collections; fn main() {} "} {"_id":"q-en-rust-a14024f6a71ed0cbff34156e492dbe5189f1afa47d6ef6078fb5a4b0561f80be","text":" error[E0284]: type annotations needed: cannot satisfy `::T == ()` --> $DIR/coherence-constrained.rs:14:5 | LL | async fn foo(&self) {} | ^^^^^^^^^^^^^^^^^^^ cannot satisfy `::T == ()` error[E0284]: type annotations needed: cannot satisfy `::T == ()` --> $DIR/coherence-constrained.rs:22:5 | LL | async fn foo(&self) {} | ^^^^^^^^^^^^^^^^^^^ cannot satisfy `::T == ()` error[E0119]: conflicting implementations of trait `Foo` for type `Bar` --> $DIR/coherence-constrained.rs:18:1 | LL | impl Foo for Bar { | ---------------- first implementation here ... LL | impl Foo for Bar { | ^^^^^^^^^^^^^^^^ conflicting implementation for `Bar` error: aborting due to 3 previous errors Some errors have detailed explanations: E0119, E0284. For more information about an error, try `rustc --explain E0119`. "} {"_id":"q-en-rust-a159fadfa1ea5a635dcb6d369447fc73103d2371a3047cfe0d69262e862cdfff","text":"pub static G: fn() = G0; pub static H: &(dyn Fn() + Sync) = &h; pub static I: fn() = Helper(j).mk(); pub static K: fn() -> fn() = { #[inline(never)] fn k() {} #[inline(always)] || -> fn() { k } }; static X: u32 = 42; static G0: fn() = g;"} {"_id":"q-en-rust-a1dae52acc3c2367bff88d7bdd2e939cd40fcb03345c040997d4d6f68e60e3a0","text":" fn main() {} #[cfg(FALSE)] fn container() { const extern \"Rust\" PUT_ANYTHING_YOU_WANT_HERE bug() -> usize { 1 } //~^ ERROR expected `fn` //~| ERROR `const extern fn` definitions are unstable } "} {"_id":"q-en-rust-a1f6ae7722aba151ed6c38dc4da927a6481a1bda96277ae3230685ddb69c4653","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":"q-en-rust-a244dd86b7e6d0b0c3a59adae5296673a39459d1e861da3795af3d6587384159","text":" #![feature(marker_trait_attr)] #[marker] trait Marker {} impl Marker for &'_ () {} //~ ERROR type annotations needed impl Marker for &'_ () {} //~ ERROR type annotations needed fn main() {} "} {"_id":"q-en-rust-a24e617dfd501808b355378fb963cf13ef712dd1bde60f61b9224e68f0acaba6","text":" // astconv uses `FreshTy(0)` as a dummy `Self` type when instanciating trait objects. // This `FreshTy(0)` can leak into substs, causing ICEs in several places. // Using `save-analysis` triggers type-checking `f` that would be normally skipped // as `type_of` emitted an error. // // compile-flags: -Zsave-analysis #![feature(trait_alias)] pub trait SelfInput = Fn(&mut Self);"} {"_id":"q-en-rust-a2c4329301368210a0220addc4351361a5fd88ffa5eb2915a9a069ceba8a0ada","text":"/// Basic usage: /// /// ``` /// #![feature(nonzero_leading_trailing_zeros)] #[doc = concat!(\"let n = std::num::\", stringify!($Ty), \"::new(0b0101000).unwrap();\")] /// /// assert_eq!(n.trailing_zeros(), 3); /// ``` #[unstable(feature = \"nonzero_leading_trailing_zeros\", issue = \"79143\")] #[rustc_const_unstable(feature = \"nonzero_leading_trailing_zeros\", issue = \"79143\")] #[stable(feature = \"nonzero_leading_trailing_zeros\", since = \"1.53.0\")] #[rustc_const_stable(feature = \"nonzero_leading_trailing_zeros\", since = \"1.53.0\")] #[inline] pub const fn trailing_zeros(self) -> u32 { // SAFETY: since `self` can not be zero it is safe to call cttz_nonzero"} {"_id":"q-en-rust-a2cacad53dbc2d3212e12f35af871f1836dbc6f1b8ce1435f7134fe7ead8e493","text":"pub fn hash_hir_item_like(&mut self, item_attrs: &[ast::Attribute], is_const: bool, f: F) { let prev_overflow_checks = self.overflow_checks_enabled; if attr::contains_name(item_attrs, \"rustc_inherit_overflow_checks\") { if is_const || attr::contains_name(item_attrs, \"rustc_inherit_overflow_checks\") { self.overflow_checks_enabled = true; } let prev_hash_node_ids = self.node_id_hashing_mode;"} {"_id":"q-en-rust-a2f0e1690a13e6ee4fbdd2ab530b34a194300e5f55f118861bf9bb0c59c41995","text":"} /// Parse a 'for' .. 'in' expression ('for' token already eaten) pub fn parse_for_expr(&mut self, opt_ident: Option) -> PResult> { pub fn parse_for_expr(&mut self, opt_ident: Option, span_lo: BytePos) -> PResult> { // Parse: `for in ` let lo = self.last_span.lo; let pat = try!(self.parse_pat_nopanic()); try!(self.expect_keyword(keywords::In)); let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)); let loop_block = try!(self.parse_block()); let hi = self.last_span.hi; Ok(self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))) Ok(self.mk_expr(span_lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))) } /// Parse a 'while' or 'while let' expression ('while' token already eaten) pub fn parse_while_expr(&mut self, opt_ident: Option) -> PResult> { pub fn parse_while_expr(&mut self, opt_ident: Option, span_lo: BytePos) -> PResult> { if self.token.is_keyword(keywords::Let) { return self.parse_while_let_expr(opt_ident); return self.parse_while_let_expr(opt_ident, span_lo); } let lo = self.last_span.lo; let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)); let body = try!(self.parse_block()); let hi = body.span.hi; return Ok(self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident))); return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident))); } /// Parse a 'while let' expression ('while' token already eaten) pub fn parse_while_let_expr(&mut self, opt_ident: Option) -> PResult> { let lo = self.last_span.lo; pub fn parse_while_let_expr(&mut self, opt_ident: Option, span_lo: BytePos) -> PResult> { try!(self.expect_keyword(keywords::Let)); let pat = try!(self.parse_pat_nopanic()); try!(self.expect(&token::Eq)); let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)); let body = try!(self.parse_block()); let hi = body.span.hi; return Ok(self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident))); return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident))); } pub fn parse_loop_expr(&mut self, opt_ident: Option) -> PResult> { let lo = self.last_span.lo; pub fn parse_loop_expr(&mut self, opt_ident: Option, span_lo: BytePos) -> PResult> { let body = try!(self.parse_block()); let hi = body.span.hi; Ok(self.mk_expr(lo, hi, ExprLoop(body, opt_ident))) Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident))) } fn parse_match_expr(&mut self) -> PResult> {"} {"_id":"q-en-rust-a2fbe868941d18a55fe862f9bb89052a71f744795115324cd03deaf21f3698c1","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. // include file for issue-21146.rs parse_error "} {"_id":"q-en-rust-a3405046ffc92d3d49f09914f20cfcd7ac9fa6fde2d939d41237c93ebefd5522","text":"\"list\" will list all of the available passes\", \"NAMES\"), optopt(\"\", \"llvm-args\", \"A list of arguments to pass to llvm, comma separated\", \"ARGS\"), optflag(\"\", \"no-rpath\", \"Disables setting the rpath in libs/exes\"), optopt( \"\", \"out-dir\", \"Write output to compiler-chosen filename in \", \"DIR\"),"} {"_id":"q-en-rust-a347b85563984bc16d37f6044d1364e139f98e506ce928afc2af483b2c2871e4","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 attempts to implicitly coerce a value into an // object respect the lifetime bound on the object type. fn a(v: &[u8]) -> Box { let x: Box = box v; //~ ERROR does not outlive x } fn b(v: &[u8]) -> Box { box v //~ ERROR does not outlive } fn c(v: &[u8]) -> Box { box v // OK thanks to lifetime elision } fn d<'a,'b>(v: &'a [u8]) -> Box { box v //~ ERROR does not outlive } fn e<'a:'b,'b>(v: &'a [u8]) -> Box { box v // OK, thanks to 'a:'b } fn main() { } "} {"_id":"q-en-rust-a349c8f1e2e54d141134363fc729e548d1eb23573b03e3c23275a78bc3ae7374","text":"// down as much as possible (without going negative), and then // adding back in whatever we couldn't factor into steals. Some(data) => { self.steals += 1; if self.steals > MAX_STEALS { match self.cnt.swap(0, atomics::SeqCst) { DISCONNECTED => {"} {"_id":"q-en-rust-a34d2c0d6a763fb3fc97c408518257707d5152e95c9c53a3fd3d95e161890260","text":"/// # Example /// /// ```rust /// # #![allow(deprecated)] /// use url::encode; /// /// let url = encode(\"https://example.com/Rust (programming language)\");"} {"_id":"q-en-rust-a357fa926d4c011565b93dbab99c4608a17c8f7e8ec245e728751271f7ade53d","text":"#[allow(unused_variables)] fn main() { let x2: i8 = --128; //~ error: literal out of range for i8 //~^ error: attempted to negate with overflow let x = -3.40282348e+38_f32; //~ error: literal out of range for f32 let x = 3.40282348e+38_f32; //~ error: literal out of range for f32"} {"_id":"q-en-rust-a39be98704f5fa6d37336810ccc79bcad5afcb53d25bc11c2932224cf7fcb8ec","text":"/// # Example /// /// ```no_run /// #![feature(seek_rewind)] /// use std::io::{Read, Seek, Write}; /// use std::fs::OpenOptions; ///"} {"_id":"q-en-rust-a3b406c05809be011aa4d817d0c46523c70a528a22772c3fc6310aade58afd63","text":"pub const PATH_BUF_AS_PATH: [&str; 4] = [\"std\", \"path\", \"PathBuf\", \"as_path\"]; pub const PATH_TO_PATH_BUF: [&str; 4] = [\"std\", \"path\", \"Path\", \"to_path_buf\"]; pub const PERMISSIONS: [&str; 3] = [\"std\", \"fs\", \"Permissions\"]; pub const PERMISSIONS_FROM_MODE: [&str; 7] = [\"std\", \"os\", \"imp\", \"unix\", \"fs\", \"PermissionsExt\", \"from_mode\"]; pub const PERMISSIONS_FROM_MODE: [&str; 6] = [\"std\", \"os\", \"unix\", \"fs\", \"PermissionsExt\", \"from_mode\"]; pub const POLL: [&str; 4] = [\"core\", \"task\", \"poll\", \"Poll\"]; pub const POLL_PENDING: [&str; 5] = [\"core\", \"task\", \"poll\", \"Poll\", \"Pending\"]; pub const POLL_READY: [&str; 5] = [\"core\", \"task\", \"poll\", \"Poll\", \"Ready\"];"} {"_id":"q-en-rust-a3c5e6c585ac07fa0ea64fbbed751a19e82a54e77e2404e1dbd03fc71bc962f0","text":"use super::{ForceCollect, Parser, TrailingToken}; use rustc_ast::token; use rustc_ast::{self as ast, AttrVec, GenericBounds, GenericParam, GenericParamKind, WhereClause}; use rustc_ast::{ self as ast, AttrVec, GenericBounds, GenericParam, GenericParamKind, TyKind, WhereClause, }; use rustc_errors::{Applicability, PResult}; use rustc_span::symbol::kw;"} {"_id":"q-en-rust-a3d11fe1e827403fdb6d1843d8b72bb43787225df344d3ef9b98aef720fc4e78","text":"# LLVM more often than necessary. # # This git command finds that commit SHA, looking for bors-authored # merges that modified src/llvm-project or other relevant version # commits that modified src/llvm-project or other relevant version # stamp files. # # This works even in a repository that has not yet initialized"} {"_id":"q-en-rust-a3f3b49344f0bec7b8b71c1eefea57fe01b0c8548f2027d227b59c6cb5c78f97","text":"match *source { CandidateSource::ImplSource(impl_did) => { // Provide the best span we can. Use the item, if local to crate, else // the impl, if local to crate (item may be defaulted), else the call site. // the impl, if local to crate (item may be defaulted), else nothing. let item = impl_item(fcx.tcx(), impl_did, item_name) .or_else(|| { trait_item("} {"_id":"q-en-rust-a413f397676fdec72ef025f52f1c4fc85ebc5177573f859d1b67cbe13f844ca0","text":" // compile-flags: --error-format pretty-json -Zunstable-options // build-pass // compile-flags: --error-format json -Zunstable-options // run-rustfix // The output for humans should just highlight the whole span without showing"} {"_id":"q-en-rust-a4183c9880daa283f11bda1ba84ce9adcd47d8dfc53f9012549f5ee9e84da5d0","text":"/// # Example /// /// ```rust /// # #![allow(deprecated)] /// let query = vec![(\"title\".to_string(), \"The Village\".to_string()), /// (\"north\".to_string(), \"52.91\".to_string()), /// (\"west\".to_string(), \"4.10\".to_string())];"} {"_id":"q-en-rust-a42355c9ef3ab9799b8ecb46285a0f4e72e15b0c11eb994249a6c91eba7c7c8a","text":"} }; span_note!(err, item_span, \"candidate #{} is defined in an impl{} for the type `{}`\", idx + 1, insertion, impl_ty); let note_str = format!(\"candidate #{} is defined in an impl{} for the type `{}`\", idx + 1, insertion, impl_ty); if let Some(note_span) = note_span { // We have a span pointing to the method. Show note with snippet. err.span_note(note_span, ¬e_str); } else { err.note(¬e_str); } } CandidateSource::TraitSource(trait_did) => { let item = trait_item(fcx.tcx(), trait_did, item_name).unwrap();"} {"_id":"q-en-rust-a42d7163251ff6d6d56c139265054443a96d37048d8c8ac4fc5c8d33f15af5d4","text":"base.supported_sanitizers = SanitizerSet::ADDRESS | SanitizerSet::CFI | SanitizerSet::THREAD; base.pre_link_args.insert(LinkerFlavor::Gcc, vec![\"-arch\".to_string(), \"arm64\".to_string()]); base.link_env.extend(super::apple_base::macos_link_env(\"arm64\")); base.link_env_remove.extend(super::apple_base::macos_link_env_remove()); // Clang automatically chooses a more specific target based on"} {"_id":"q-en-rust-a42d99100f9948930fa14d1c69ca3aa5f0635c3b4e336c377e618d0836cc75c9","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. // -C no-prepopulate-passes #![crate_type=\"staticlib\"] #[repr(C)] pub struct Foo(u64); // CHECK: define {{.*}} @foo( #[no_mangle] pub extern fn foo(_: Foo) -> Foo { loop {} } "} {"_id":"q-en-rust-a448356f8e6c41de209ca7f2b94f5b84a1c565ac864fe2e749fe4dd5934ebc04","text":" // edition:2018 use std::convert::{TryFrom, TryInto}; use std::io; pub struct MyStream; pub struct OtherStream; pub async fn connect() -> io::Result { let stream: MyStream = OtherStream.try_into()?; Ok(stream) } impl TryFrom for MyStream {} //~^ ERROR: missing fn main() {} "} {"_id":"q-en-rust-a468b6538250243c917ed9171120bd19a91f19368c21983712d808e368c9d17d","text":" // Nested impl-traits can impose different member constraints on the same region variable. // check-fail trait Cap<'a> {} impl Cap<'_> for T {} // Assuming the hidden type is `[&'_#15r u8; 1]`, we have two distinct member constraints: // - '_#15r member ['static, 'a, 'b] // from outer impl-trait // - '_#15r member ['static, 'a, 'b] // from inner impl-trait // To satisfy both we can choose 'a or 'b, so it's a failure due to ambiguity. fn fail_early_bound<'s, 'a, 'b>(a: &'s u8) -> impl IntoIterator + Cap<'b>> where 's: 'a, 's: 'b, { [a] //~^ E0700 //~| E0700 } // Same as the above but with late-bound regions. fn fail_late_bound<'s, 'a, 'b>( a: &'s u8, _: &'a &'s u8, _: &'b &'s u8, ) -> impl IntoIterator + Cap<'b>> { [a] //~^ E0700 //~| E0700 } fn main() {} "} {"_id":"q-en-rust-a46bf201ef5d6fa6ced5d327827f2bc09c74c72189162c6266f6da64bd71e229","text":" error: `panic_impl` language item function is not allowed to have `#[target_feature]` --> $DIR/panic-handler-with-target-feature.rs:11:1 | LL | #[target_feature(enable = \"avx2\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | LL | fn panic(info: &PanicInfo) -> ! { | ------------------------------- `panic_impl` language item function is not allowed to have `#[target_feature]` error: aborting due to previous error "} {"_id":"q-en-rust-a47f45326d665d88440f337adc838c3c9e08a0c03fdadc0eb8672871d5a4b122","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":"q-en-rust-a482512add36d8beb3cbbb1735da3318243ba8145443b0bb7fc5f5c00edf2467","text":" // run-pass #![allow(dead_code)] enum E { A, B } fn main() { match &&E::A { &&E::A => { } &&E::B => { } }; } "} {"_id":"q-en-rust-a487617ddebee625cf9c49c1d72542e857c6945534597b557edbdcbb472e955f","text":" error[E0311]: the parameter type `T` may not live long enough --> $DIR/issue-86483.rs:6:1 | LL | pub trait IceIce | ^ - help: consider adding an explicit lifetime bound...: `T: 'a` | _| | | LL | | where LL | | for<'a> T: 'a, LL | | { ... | LL | | LL | | } | |_^ ...so that the type `T` will meet its required lifetime bounds error[E0311]: the parameter type `T` may not live long enough --> $DIR/issue-86483.rs:10:5 | LL | pub trait IceIce | - help: consider adding an explicit lifetime bound...: `T: 'a` ... LL | type Ice<'v>: IntoIterator; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds error[E0309]: the parameter type `T` may not live long enough --> $DIR/issue-86483.rs:10:32 | LL | pub trait IceIce | - help: consider adding an explicit lifetime bound...: `T: 'v` ... LL | type Ice<'v>: IntoIterator; | ^^^^^^^^^^^^ ...so that the reference type `&'v T` does not outlive the data it points at error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0309`. "} {"_id":"q-en-rust-a496b1f9b064ed90ec194e9379a7059c56d4d552920fff9c56263592bf32211d","text":" error: to use a constant of type `Vec` in a pattern, `Vec` must be annotated with `#[derive(PartialEq, Eq)]` --> $DIR/issue-115599.rs:5:12 | LL | if let CONST_STRING = empty_str {} | ^^^^^^^^^^^^ | = note: the traits must be derived, manual `impl`s are not sufficient = note: see https://doc.rust-lang.org/stable/std/marker/trait.StructuralEq.html for details error: aborting due to previous error "} {"_id":"q-en-rust-a4a15db7407818f8193dc41832e5b7fc60911e063ab75aed8c3317134b000997","text":"/// Takes a path to a source file and cleans the path to it. This canonicalizes /// things like \"..\" to components which preserve the \"top down\" hierarchy of a /// static HTML tree. /// static HTML tree. Each component in the cleaned path will be passed as an /// argument to `f`. The very last component of the path (ie the file name) will /// be passed to `f` if `keep_filename` is true, and ignored otherwise. // FIXME (#9639): The closure should deal with &[u8] instead of &str // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths fn clean_srcpath(src_root: &Path, p: &Path, mut f: F) where fn clean_srcpath(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where F: FnMut(&str), { // make it relative, if possible let p = p.relative_from(src_root).unwrap_or(p); for c in p.iter().map(|x| x.to_str().unwrap()) { let mut iter = p.iter().map(|x| x.to_str().unwrap()).peekable(); while let Some(c) = iter.next() { if !keep_filename && iter.peek().is_none() { break; } if \"..\" == c { f(\"up\"); } else {"} {"_id":"q-en-rust-a4b6cf572f02e441d492f8f9dbb9d26de5067c3c6a98f880b0bd9a58727d6993","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":"q-en-rust-a509f91547d230f0edfb1c98b24d4e762d10f8579721a92891c17994ca92a66a","text":"self.suggest_cloning(err, ty, expr, None, Some(move_spans)); } } if let Some(pat) = finder.pat { self.suggest_ref_for_dbg_args(expr, place, move_span, err); // it's useless to suggest inserting `ref` when the span don't comes from local code if let Some(pat) = finder.pat && !move_span.is_dummy() && !self.infcx.tcx.sess.source_map().is_imported(move_span) { *in_pattern = true; let mut sugg = vec![(pat.span.shrink_to_lo(), \"ref \".to_string())]; if let Some(pat) = finder.parent_pat {"} {"_id":"q-en-rust-a566f1eda949caa038491e1644fb0cd6215d02321f0b0db291ac5e6331f4fbe5","text":"match outlives_bound { OutlivesBound::RegionSubRegion(r1, r2) => { // `where Type:` is lowered to `where Type: 'empty` so that // we check `Type` is well formed, but there's no use for // this bound here. if let ty::ReEmpty = r1 { return; } // The bound says that `r1 <= r2`; we store `r2: r1`. let r1 = self.universal_regions.to_region_vid(r1); let r2 = self.universal_regions.to_region_vid(r2);"} {"_id":"q-en-rust-a56bde7a6f7bcc22447c98ba814ae31671a376d03aa1060c425ddc1f9dfd2cbe","text":"} /// `parent_module` refers to the parent of the re-export, not the original item fn merge_attrs( pub(crate) fn merge_attrs( cx: &mut DocContext<'_>, parent_module: Option, old_attrs: Attrs<'_>,"} {"_id":"q-en-rust-a5834a441493dd48dd6e9511398821aa40ec96c6c98c623c94ff55135bd7922c","text":" // Nested impl-traits can impose different member constraints on the same region variable. // check-pass trait Cap<'a> {} impl Cap<'_> for T {} // Assuming the hidden type is `[&'_#15r u8; 1]`, we have two distinct member constraints: // - '_#15r member ['static, 'a, 'b] // from outer impl-trait // - '_#15r member ['static, 'a] // from inner impl-trait // To satisfy both we can only choose 'a. fn pass_early_bound<'s, 'a, 'b>(a: &'s u8) -> impl IntoIterator> + Cap<'b> where 's: 'a, 's: 'b, { [a] } // Same as the above but with late-bound regions. fn pass_late_bound<'s, 'a, 'b>( a: &'s u8, _: &'a &'s u8, _: &'b &'s u8, ) -> impl IntoIterator> + Cap<'b> { [a] } fn main() {} "} {"_id":"q-en-rust-a5bf01b0566c003bcc1d7900de97dccfd6cfbc53e2e7873bf054dd78ccb245c1","text":".chain(indeterminate_imports.iter().map(|i| (true, i))) { let unresolved_import_error = self.finalize_import(*import); // If this import is unresolved then create a dummy import // resolution for it so that later resolve stages won't complain. self.import_dummy_binding(*import, is_indeterminate);"} {"_id":"q-en-rust-a5d49ccec77e809a19352dc381e3e2f3b6489bd7fdd5ea12522af30299b29a5a","text":" // Documents that Rust currently does not permit the coercion &mut &mut T -> *mut *mut T // Making this compile was a feature request in rust-lang/rust#34117 but this is currently // \"working as intended\". Allowing \"deep pointer coercion\" seems footgun-prone, and would // require proceeding carefully. use std::ops::{Deref, DerefMut}; struct Foo(i32); struct SmartPtr(*mut T); impl SmartPtr { fn get_addr(&mut self) -> &mut *mut T { &mut self.0 } } impl Deref for SmartPtr { type Target = T; fn deref(&self) -> &T { unsafe { &*self.0 } } } impl DerefMut for SmartPtr { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.0 } } } /// Puts a Foo into the pointer provided by the caller fn make_foo(_: *mut *mut Foo) { unimplemented!() } fn main() { let mut result: SmartPtr = SmartPtr(std::ptr::null_mut()); make_foo(&mut &mut *result); //~ mismatched types //~^ expected `*mut *mut Foo`, found `&mut &mut Foo` make_foo(out(&mut result)); // works, but makes one wonder why above coercion cannot happen } fn out(ptr: &mut SmartPtr) -> &mut *mut T { ptr.get_addr() } "} {"_id":"q-en-rust-a5f08a735651583bd2a46e5e01567a4bbb4080fd5a90611e17afb3900cb0ca63","text":"// handled by the lint emitting logic above. } None => { // This is an 'unmarked' API, which should not exist // in the standard library. if self.sess.features.borrow().unmarked_api { self.sess.struct_span_warn(span, \"use of unmarked library feature\") .span_note(span, \"this is either a bug in the library you are using or a bug in the compiler - please report it in both places\") .emit() } else { self.sess.struct_span_err(span, \"use of unmarked library feature\") .span_note(span, \"this is either a bug in the library you are using or a bug in the compiler - please report it in both places\") .span_note(span, \"use #![feature(unmarked_api)] in the crate attributes to override this\") .emit() } span_bug!(span, \"encountered unmarked API\"); } } }"} {"_id":"q-en-rust-a5fe05c5c4cc607927c341222c3cbf6422cfe5ca937041414e7520c7459ba9e8","text":" error: unexpected `...` --> $DIR/issue-70388-recover-dotdotdot-rest-pat.rs:4:13 | LL | let Foo(...) = Foo(0); | ^^^ | | | not a valid pattern | help: for a rest pattern, use `..` instead of `...` error: unexpected `...` --> $DIR/issue-70388-recover-dotdotdot-rest-pat.rs:5:13 | LL | let [_, ..., _] = [0, 1]; | ^^^ | | | not a valid pattern | help: for a rest pattern, use `..` instead of `...` error[E0308]: mismatched types --> $DIR/issue-70388-recover-dotdotdot-rest-pat.rs:6:33 | LL | let _recovery_witness: () = 0; | -- ^ expected `()`, found integer | | | expected due to this error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-a62b6e498987e8b69225d2b240b1ffafd790cb912a1e3b95d403a81eb717d5c8","text":"#![feature(core_private_bignum)] #![feature(core_private_diy_float)] #![feature(dec2flt)] #![feature(div_duration)] #![feature(duration_abs_diff)] #![feature(duration_consts_float)] #![feature(duration_constants)]"} {"_id":"q-en-rust-a62bdde9308435b8b18b9695661f264ac202a109df01792f2f28cb9f27fce762","text":"let mut colon_span = None; let bounds = if self.eat(&token::Colon) { colon_span = Some(self.prev_token.span); // recover from `impl Trait` in type param bound if self.token.is_keyword(kw::Impl) { let impl_span = self.token.span; let snapshot = self.create_snapshot_for_diagnostic(); match self.parse_ty() { Ok(p) => { if let TyKind::ImplTrait(_, bounds) = &(*p).kind { let span = impl_span.to(self.token.span.shrink_to_lo()); let mut err = self.struct_span_err( span, \"expected trait bound, found `impl Trait` type\", ); err.span_label(span, \"not a trait\"); if let [bound, ..] = &bounds[..] { err.span_suggestion_verbose( impl_span.until(bound.span()), \"use the trait bounds directly\", String::new(), Applicability::MachineApplicable, ); } err.emit(); return Err(err); } } Err(err) => { err.cancel(); } } self.restore_snapshot(snapshot); } self.parse_generic_bounds(colon_span)? } else { Vec::new() }; let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None }; Ok(GenericParam { ident, id: ast::DUMMY_NODE_ID,"} {"_id":"q-en-rust-a663a5f2de603ec02e340c268330047effe9d92aa2696caba2e1234e5df4fc1b","text":" error[E0433]: failed to resolve: use of undeclared crate or module `n` --> $DIR/issue-120856.rs:1:37 | LL | pub type Archived = ::Archived; | ^ | | | use of undeclared crate or module `n` | help: a trait with a similar name exists: `Fn` error[E0433]: failed to resolve: use of undeclared crate or module `m` --> $DIR/issue-120856.rs:1:25 | LL | pub type Archived = ::Archived; | ^ | | | use of undeclared crate or module `m` | help: a type parameter with a similar name exists: `T` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0433`. "} {"_id":"q-en-rust-a679ee46ee013444ee5371e1e1d4d8445fe7852a8aa94fbc720bf9587904c3ce","text":" fn main() { let a_longer_variable_name = 1; println!(\"{}\", a_variable_longer_name); //~ ERROR E0425 } "} {"_id":"q-en-rust-a6919108e5b4c1fc9f156dec64c9a1968d10f03f3708148ec6b5a59e59110c8f","text":" const CONST_STRING: String = String::new(); fn main() { let empty_str = String::from(\"\"); if let CONST_STRING = empty_str {} //~^ ERROR to use a constant of type `Vec` in a pattern, `Vec` must be annotated with `#[derive(PartialEq, Eq)]` } "} {"_id":"q-en-rust-a6d8f4701019b6503ee3d46fcaacce03b674ba20adf21fae3edf1364b8ba22e7","text":" // Regression test of #86483. #![feature(generic_associated_types)] #![allow(incomplete_features)] pub trait IceIce //~ ERROR: the parameter type `T` may not live long enough where for<'a> T: 'a, { type Ice<'v>: IntoIterator; //~^ ERROR: the parameter type `T` may not live long enough //~| ERROR: the parameter type `T` may not live long enough } fn main() {} "} {"_id":"q-en-rust-a6ead1294bf2b808c3b5bfe80b212247cf21a1ee9e00c58d659ec08afb562e7c","text":" // compile-flags: -O // run-pass // Regression test for https://github.com/rust-lang/rust/issues/118328 #![allow(unused_assignments)] struct SizeOfConst(std::marker::PhantomData); impl SizeOfConst { const SIZE: usize = std::mem::size_of::(); } fn size_of() -> usize { let mut a = 0; a = SizeOfConst::::SIZE; a } fn main() { assert_eq!(size_of::(), std::mem::size_of::()); } "} {"_id":"q-en-rust-a70767f82477859b4f8389839d0007c03e7075c48d73e2231bb3a4cbd86c1e1a","text":"// to accidentally sneak into our dependency graph, in order to ensure we keep our CI times // under control. \"cargo\", \"rustc-ap-rustc_ast\", ]; /// Dependency checks."} {"_id":"q-en-rust-a707c47293bf60b4bb8f466b56f5026f34b748824715749cac648851f18ae5bb","text":"F: FnOnce(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>, { let _icx = push_ctxt(\"tvec::iter_vec_loop\"); let fcx = bcx.fcx; if bcx.unreachable.get() { return bcx; } let fcx = bcx.fcx; let loop_bcx = fcx.new_temp_block(\"expr_repeat\"); let next_bcx = fcx.new_temp_block(\"expr_repeat: next\");"} {"_id":"q-en-rust-a74ac354ae2d9b5f3dc63346db0c6ff4a68a42ad1ea35a23ca51f7141b1c63b2","text":" error: struct `T9` is never constructed --> $DIR/unconstructible-pub-struct.rs:30:12 | LL | pub struct T9 { | ^^ | note: the lint level is defined here --> $DIR/unconstructible-pub-struct.rs:2:9 | LL | #![deny(dead_code)] | ^^^^^^^^^ error: aborting due to 1 previous error "} {"_id":"q-en-rust-a78dba9a7f0fb7fca362a5dd303f95372a800a2180f48300e409406523e2f1f2","text":"let parse_only = matches.opt_present(\"parse-only\"); let no_trans = matches.opt_present(\"no-trans\"); let no_analysis = matches.opt_present(\"no-analysis\"); let no_rpath = matches.opt_present(\"no-rpath\"); let lint_levels = [lint::allow, lint::warn, lint::deny, lint::forbid];"} {"_id":"q-en-rust-a7a0e47a62b72c6be00e604fea5a87e04d07904872750479fd6ded004bf8d993","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":"q-en-rust-a82bfb19b68ce450823096bfe1273a58463086f17f1f4aef08b90a2580340080","text":"/// ``` /// /// ```rust /// #![feature(fmt_as_str)] /// /// assert_eq!(format_args!(\"hello\").as_str(), Some(\"hello\")); /// assert_eq!(format_args!(\"\").as_str(), Some(\"\")); /// assert_eq!(format_args!(\"{}\", 1).as_str(), None); /// ``` #[unstable(feature = \"fmt_as_str\", issue = \"74442\")] #[stable(feature = \"fmt_as_str\", since = \"1.52.0\")] #[inline] pub fn as_str(&self) -> Option<&'static str> { match (self.pieces, self.args) {"} {"_id":"q-en-rust-a874097ce97f771c22ce166447db71cc5b557b7f8d25cc91ab71613b134166d9","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":"q-en-rust-a88c1bfeac609fc628ec0b5e89ef279c85df081a72ad47d0e6d6d74df88e8c39","text":"#![feature(const_float_bits_conv)] #![feature(const_float_classify)] #![feature(f16)] #![feature(f128)] #![allow(unused_macro_rules)] // Don't promote const fn nop(x: T) -> T { x }"} {"_id":"q-en-rust-a89f1e3bad080b5148d35b6c80d0b6c1728448d78eef8eb2a565e4d165404865","text":" error: constant expression depends on a generic parameter --> $DIR/issue-50439.rs:25:22 | LL | let _ = [(); 0 - !!( as ReflectDrop>::REFLECT_DROP) as usize]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: this may fail depending on what value the parameter takes error: aborting due to previous error "} {"_id":"q-en-rust-a8a7334a0bcab56bd196e40e9943b30bf0609e25b25180469f4fb18802100aa5","text":"use crate::cmp; use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read}; use crate::mem; use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sys::cvt; use crate::sys_common::AsInner;"} {"_id":"q-en-rust-a8acc6d397a816f203d51bfb423b56ec221b84b5693cd0ce20406de0dbb61aec","text":"A(i32), B(i32), } // CHECK: %Enum4 = type { [2 x i32] } // CHECK: %Enum4 = type { [0 x i32], i32, [1 x i32] } // CHECK: %\"Enum4::A\" = type { [1 x i32], i32, [0 x i32] } pub enum Enum64 { A(Align64), B(i32), } // CHECK: %Enum64 = type { [16 x i64] } // CHECK: %Enum64 = type { [0 x i32], i32, [31 x i32] } // CHECK: %\"Enum64::A\" = type { [8 x i64], %Align64, [0 x i64] } // CHECK-LABEL: @align64"} {"_id":"q-en-rust-a8e21958f0ec6610380c4129acbb2817b2ea7b217afb9563e4e9fb14b3843957","text":"}, ); // Construct the list of in-scope lifetime parameters for async lowering. // We include all lifetime parameters, either named or \"Fresh\". // The order of those parameters does not matter, as long as it is // deterministic. if let Some((async_node_id, _)) = async_node_id { let mut extra_lifetime_params = this .r .extra_lifetime_params_map .get(&fn_id) .cloned() .unwrap_or_default(); for rib in this.lifetime_ribs.iter().rev() { extra_lifetime_params.extend( rib.bindings .iter() .map(|(&ident, &(node_id, res))| (ident, node_id, res)), ); match rib.kind { LifetimeRibKind::Item => break, LifetimeRibKind::AnonymousCreateParameter { binder, .. } => { if let Some(earlier_fresh) = this.r.extra_lifetime_params_map.get(&binder) { extra_lifetime_params.extend(earlier_fresh); } } _ => {} } } this.r .extra_lifetime_params_map .insert(async_node_id, extra_lifetime_params); } this.record_lifetime_params_for_async(fn_id, async_node_id); if let Some(body) = body { // Ignore errors in function bodies if this is rustdoc"} {"_id":"q-en-rust-a91bc3d246bab1431b9daf3ae63e6a44f1505d656b423fe8b965b25425930409","text":"self.truncate(0) } /// Returns the number of elements in the vector. /// Returns the number of elements in the vector, also referred to /// as its 'length'. /// /// # Examples ///"} {"_id":"q-en-rust-a949cfbdfa1b11238bcdee346975aebf902eb486bd4dc460ee8047c2098fed63","text":" fn main() { transmute(); // does not ICE } extern \"rust-intrinsic\" fn transmute() {} //~^ ERROR intrinsic has wrong number of type parameters: found 0, expected 2 //~| ERROR intrinsics are subject to change //~| ERROR intrinsic must be in `extern \"rust-intrinsic\" { ... }` block "} {"_id":"q-en-rust-a974bd08c090ebff35d2b52050143c5775ad99dfefc9f6a01fca512c2a43715e","text":"// Types of fields (other than the last) in a struct must be sized. FieldSized, // Constant expressions must be sized. ConstSized, // static items must have `Sync` type SharedStatic,"} {"_id":"q-en-rust-a9b0b81494bafe7509b105218b640d6eef833e713fae1465332196767faaf740","text":"pub fn list_file_metadata(os: Os, path: &Path, out: &mut io::Writer) -> io::IoResult<()> { match get_metadata_section(os, path) { Some(bytes) => decoder::list_crate_metadata(bytes.as_slice(), out), None => write!(out, \"could not find metadata in {}.n\", path.display()) Some(bytes) => decoder::list_crate_metadata(bytes.as_slice(), out), None => { write!(out, \"could not find metadata in {}.n\", path.display()) } } }"} {"_id":"q-en-rust-aa0dc225a5260541e3dc8931fee64c49545116f64a8038f2ad083a4dc0bc37fb","text":"# is a separate choice from whether to pass `-g` when building the # compiler and standard library themselves. CTEST_RUSTC_FLAGS := $$(subst -g,,$$(CTEST_RUSTC_FLAGS)) CTEST_RUSTC_FLAGS := $$(subst -Cdebuginfo=1,,$$(CTEST_RUSTC_FLAGS)) ifdef CFG_ENABLE_DEBUGINFO_TESTS CTEST_RUSTC_FLAGS += -g endif"} {"_id":"q-en-rust-aa3db8c949d80a581a09c52f727cfc76ee4228ec9df59cd98a32fb6466b96067","text":" --- name: Documentation problem about: Create a report for a documentation problem. labels: A-docs --- ### Location ### Summary "} {"_id":"q-en-rust-aa7551e493e8d0fecf8642bffeeb8c063538847a42ef8d5729276952fd011fb4","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":"q-en-rust-aa7c025e47a3cbbcd9eb45f6efaf1774b9e5e7d50cdd523d9f1870072c79cff1","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. // compile-flags: -D warnings -D unknown-lints #![allow(unknown_lints)] #![allow(random_lint_name)] fn main() {} "} {"_id":"q-en-rust-aa9434791fd797a7dac5db1c568f2ec9ba6a93bed0976eb3ea7e23c2b97663fe","text":"#[inline] fn plain_summary_line(s: Option<&str>) -> String { let md = markdown::plain_summary_line(s.unwrap_or(\"\")); shorter(Some(&md)).replace(\"n\", \" \") let line = shorter(s).replace(\"n\", \" \"); markdown::plain_summary_line(&line[..]) } fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {"} {"_id":"q-en-rust-aaa6332a71184df7e8282580e65350e96539dc7cfbce7c1960d9663058d7eb97","text":"}; debug!(\"make_shim({:?}) = untransformed {:?}\", instance, result); pm::run_passes( // We don't validate MIR here because the shims may generate code that's // only valid in a reveal-all param-env. However, since we do initial // validation with the MirBuilt phase, which uses a user-facing param-env. // This causes validation errors when TAITs are involved. pm::run_passes_no_validate( tcx, &mut result, &["} {"_id":"q-en-rust-aab93b737abf02b16378039a1e8f37752bcd2b1f2b64660d94f6e80ff8816ce4","text":"| LL | opaque!; | + help: a unit struct with a similar name exists | LL | Opaque; | ~~~~~~ error: aborting due to 3 previous errors"} {"_id":"q-en-rust-aacb74fcf25c2c3107e52989cefc12e4442446edaaada8080e1f62f241dcf0ac","text":"} } } else if let &Safety::Unsafe(span) = safety { this.dcx().emit_err(errors::UnsafeItem { span, kind: \"extern block\" }); let mut diag = this .dcx() .create_err(errors::UnsafeItem { span, kind: \"extern block\" }); rustc_session::parse::add_feature_diagnostics( &mut diag, self.session, sym::unsafe_extern_blocks, ); diag.emit(); } if abi.is_none() {"} {"_id":"q-en-rust-aafa1ce4d7cf433660445b5893b7d233baefbb11fe771ec3579ac9223fa6186a","text":" // Regression test for #![no_std] // @has blanket_impls.json // @has - \"$.index[*][?(@.name=='Error')].kind\" \"assoc_type\" // @has - \"$.index[*][?(@.name=='Error')].inner.default.kind\" \"resolved_path\" // @has - \"$.index[*][?(@.name=='Error')].inner.default.inner.name\" \"Infallible\" pub struct ForBlanketTryFromImpl; "} {"_id":"q-en-rust-ab0a4c2bbf230421c5b01d9ca56f899510c0b3da78d7be2a1972485c25323fcf","text":" Subproject commit 3bf51f591f7ffdd45f51cd1d42a4002482af2bd5 Subproject commit c388361cc2db82568d5e90fefea864f0af8d35e9 "} {"_id":"q-en-rust-ab13d67edf4122f93cbe71c1bccf03afdd9ea22b6ffcd5eed09be15ebcca6c32","text":"// build-fail // revisions: normal mir-opt // [mir-opt]compile-flags: -Zmir-opt-level=4 trait C { const BOO: usize;"} {"_id":"q-en-rust-ab326840489b530cc20b1890b7dfc65a4c11edbdac5fd4588fd9797da057e0b0","text":" Subproject commit 412fb00b37afb6b7f7fa96a35f2315c7e640b916 Subproject commit d9aa23a43ad29e3a10551a1425ef5d5baef28d70 "} {"_id":"q-en-rust-ab4c89325c70f5bdc4e6b3dfefc7653eb2898fa58da87eaef10bb42d477fe663","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":"q-en-rust-ab7e1b3632a40fbb0e59cd005eb09061a9071854f7e65fbca110f510e0fad45f","text":"impl Deref for Thing { //~^ ERROR not all trait items implemented, missing: `Target` [E0046] fn deref(&self) -> i8 { self.0 } //~^ ERROR method `deref` has an incompatible type for trait: expected &-ptr, found i8 [E0053] //~^ ERROR method `deref` has an incompatible type for trait //~| expected &-ptr //~| found i8 [E0053] } let thing = Thing(72);"} {"_id":"q-en-rust-ab87e9104d653f8b92549af0f7c9f6a1d4a187a5a92164d4ca135847cb6cc0ae","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":"q-en-rust-abad0be42752504202b35d3936b57fd611e1bc46766e66c4f2ffda5b7f38eacf","text":"fn visit_item(&mut self, item: &'tcx Item) { let mut item_hir_id = None; self.lctx.with_hir_id_owner(item.id, |lctx| { if let Some(hir_item) = lctx.lower_item(item) { item_hir_id = Some(hir_item.hir_id); lctx.insert_item(hir_item); } lctx.without_in_scope_lifetime_defs(|lctx| { if let Some(hir_item) = lctx.lower_item(item) { item_hir_id = Some(hir_item.hir_id); lctx.insert_item(hir_item); } }) }); if let Some(hir_id) = item_hir_id {"} {"_id":"q-en-rust-abcad7eb6f2cd2299feb9235fe2eb400af293c751f18978646eb8a85d5956bb5","text":"self.resolve_expr(elem, Some(expr)); self.visit_expr(idx); } ExprKind::Assign(..) => { let old = self.diagnostic_metadata.in_assignment.replace(expr); visit::walk_expr(self, expr); self.diagnostic_metadata.in_assignment = old; ExprKind::Assign(ref lhs, ref rhs, _) => { if !self.diagnostic_metadata.is_assign_rhs { self.diagnostic_metadata.in_assignment = Some(expr); } self.visit_expr(lhs); self.diagnostic_metadata.is_assign_rhs = true; self.diagnostic_metadata.in_assignment = None; self.visit_expr(rhs); self.diagnostic_metadata.is_assign_rhs = false; } _ => { visit::walk_expr(self, expr);"} {"_id":"q-en-rust-abcd87690e0e0684ce11bc1096cfd8d22c5d03b46164d0cd5c7e37c07ab7a82f","text":"return Ok(cycle_result); } let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack)); let (result, dep_node) = self.in_task(|this| { let mut result = this.evaluate_stack(&stack)?; // fix issue #103563, we don't normalize // nested obligations which produced by `TraitDef` candidate // (i.e. using bounds on assoc items as assumptions). // because we don't have enough information to // normalize these obligations before evaluating. // so we will try to normalize the obligation and evaluate again. // we will replace it with new solver in the future. if EvaluationResult::EvaluatedToErr == result && fresh_trait_pred.has_projections() && fresh_trait_pred.is_global() { let mut nested_obligations = Vec::new(); let predicate = try_normalize_with_depth_to( this, param_env, obligation.cause.clone(), obligation.recursion_depth + 1, obligation.predicate, &mut nested_obligations, ); if predicate != obligation.predicate { let mut nested_result = EvaluationResult::EvaluatedToOk; for obligation in nested_obligations { nested_result = cmp::max( this.evaluate_predicate_recursively(stack.list(), obligation)?, nested_result, ); } if nested_result.must_apply_modulo_regions() { let obligation = obligation.with(this.tcx(), predicate); result = cmp::max( nested_result, this.evaluate_trait_predicate_recursively(stack.list(), obligation)?, ); } } } Ok::<_, OverflowError>(result) }); let result = result?; if !result.must_apply_modulo_regions() {"} {"_id":"q-en-rust-abf40e6b299447226ee36762715c40a6a14ac08af8c1bf43dcd75957557aa48c","text":"!source_file.is_imported() }) .map(|source_file| { // When exporting SourceFiles, we expand all paths to absolute // paths because any relative paths are potentially relative to // a wrong directory. // However, if a path has been modified via // `--remap-path-prefix` we assume the user has already set // things up the way they want and don't touch the path values // anymore. match source_file.name { // This path of this SourceFile has been modified by // path-remapping, so we use it verbatim (and avoid // cloning the whole map in the process). _ if source_file.name_was_remapped => source_file.clone(), // Otherwise expand all paths to absolute paths because // any relative paths are potentially relative to a // wrong directory. FileName::Real(ref name) => { if source_file.name_was_remapped || (name.is_relative() && working_dir_was_remapped) { // This path of this SourceFile has been modified by // path-remapping, so we use it verbatim (and avoid cloning // the whole map in the process). source_file.clone() } else { let mut adapted = (**source_file).clone(); adapted.name = Path::new(&working_dir).join(name).into(); adapted.name_hash = { let mut hasher: StableHasher = StableHasher::new(); adapted.name.hash(&mut hasher); hasher.finish() }; Lrc::new(adapted) } let mut adapted = (**source_file).clone(); adapted.name = Path::new(&working_dir).join(name).into(); adapted.name_hash = { let mut hasher: StableHasher = StableHasher::new(); adapted.name.hash(&mut hasher); hasher.finish() }; Lrc::new(adapted) }, // expanded code, not from a file _ => source_file.clone(), }"} {"_id":"q-en-rust-ac00875c62fb0f2f5e1525fb1b707438a9af5d609c435e87c6d8103d0969e68e","text":"impl ApplyL<'a>> LambdaL for T {} // HACK(eddyb) work around projection limitations with a newtype // FIXME(#52812) replace with `&'a mut >::Out` pub struct RefMutL<'a, 'b, T: LambdaL>(&'a mut >::Out); impl<'a, 'b, T: LambdaL> Deref for RefMutL<'a, 'b, T> { type Target = >::Out; fn deref(&self) -> &Self::Target { self.0 } } impl<'a, 'b, T: LambdaL> DerefMut for RefMutL<'a, 'b, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.0 } } pub struct ScopedCell(Cell<>::Out>); impl ScopedCell {"} {"_id":"q-en-rust-ac0105d8952235eb10b627dd8ef3b85b10e2f88393e0a45e5bcf31820df15b23","text":"// mir. match tcx.at(expr.span).lit_to_const(lit_input) { Ok(c) => return Some(c), Err(_) if lit_input.ty.has_aliases() => { // allow the `ty` to be an alias type, though we cannot handle it here return None; } Err(e) => { tcx.dcx().span_delayed_bug( expr.span,"} {"_id":"q-en-rust-ac0ac1120c3fae901bb182ab58b9e26f7a7bd133e15275549864131e99a915fe","text":"assert-css: (\"#help-button .popover\", {\"display\": \"block\"}) press-key: \"Escape\" assert-css: (\"#help-button .popover\", {\"display\": \"none\"}) // Checking doc collapse and expand. // It should be displaying a \"-\": assert-text: (\"#toggle-all-docs\", \"[u2212]\") press-key: \"-\" wait-for-text: (\"#toggle-all-docs\", \"[+]\") assert-attribute: (\"#toggle-all-docs\", {\"class\": \"will-expand\"}) // Pressing it again shouldn't do anything. press-key: \"-\" assert-text: (\"#toggle-all-docs\", \"[+]\") assert-attribute: (\"#toggle-all-docs\", {\"class\": \"will-expand\"}) // Expanding now. press-key: \"+\" wait-for-text: (\"#toggle-all-docs\", \"[u2212]\") assert-attribute: (\"#toggle-all-docs\", {\"class\": \"\"}) // Pressing it again shouldn't do anything. press-key: \"+\" assert-text: (\"#toggle-all-docs\", \"[u2212]\") assert-attribute: (\"#toggle-all-docs\", {\"class\": \"\"}) "} {"_id":"q-en-rust-ac416a16f9b1014b15868bb40c9b9615a93bdfbc5eec28eb22e7036cddfc465c","text":"} } } fn expr_as_call_operand( &mut self, mut block: BasicBlock, scope: Option, expr: Expr<'tcx>, ) -> BlockAnd> { debug!(\"expr_as_call_operand(block={:?}, expr={:?})\", block, expr); let this = self; if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { let source_info = this.source_info(expr.span); let region_scope = (region_scope, source_info); return this.in_scope(region_scope, lint_level, |this| { this.as_call_operand(block, scope, value) }); } let tcx = this.hir.tcx(); if tcx.features().unsized_locals { let ty = expr.ty; let span = expr.span; let param_env = this.hir.param_env; if !ty.is_sized(tcx.at(span), param_env) { // !sized means !copy, so this is an unsized move assert!(!ty.is_copy_modulo_regions(tcx, param_env, span)); // As described above, detect the case where we are passing a value of unsized // type, and that value is coming from the deref of a box. if let ExprKind::Deref { ref arg } = expr.kind { let arg = this.hir.mirror(arg.clone()); // Generate let tmp0 = arg0 let operand = unpack!(block = this.as_temp(block, scope, arg, Mutability::Mut)); // Return the operand *tmp0 to be used as the call argument let place = Place { local: operand, projection: tcx.intern_place_elems(&[PlaceElem::Deref]), }; return block.and(Operand::Move(place)); } } } this.expr_as_operand(block, scope, expr) } }"} {"_id":"q-en-rust-ac4a47d11d80c226048be38bf36164d5649ab7086973bca87d6ca5b5262af6e6","text":"let pat = self.mk_pat(lo.to(self.prev_span), pat); let pat = self.maybe_recover_from_bad_qpath(pat, true)?; let pat = self.recover_intersection_pat(pat)?; if !allow_range_pat { self.ban_pat_range_if_ambiguous(&pat)?"} {"_id":"q-en-rust-ac73cd55658f4738286ff4c668c03c0c81dd14360edc9c5ec169057c14b8302e","text":" fn main() {} #[cfg(FALSE)] fn container() { const unsafe WhereIsFerris Now() {} //~^ ERROR expected one of `extern` or `fn` } "} {"_id":"q-en-rust-acde6a08d041b5f8ebcade3c9358c726adc85b4a74f04e9ef8dfb402ff53147c","text":"use fn_ctxt::FnCtxt; use rustc_data_structures::unord::UnordSet; use rustc_errors::codes::*; use rustc_errors::{struct_span_code_err, Applicability, ErrorGuaranteed}; use rustc_errors::{pluralize, struct_span_code_err, Applicability, ErrorGuaranteed}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::Visitor;"} {"_id":"q-en-rust-ace6161e325c88fd96e498bb598685f2be8eb0c0e36ae5412109b42896b926f8","text":" //@ known-bug: #97501 #![feature(core_intrinsics)] use std::intrinsics::wrapping_add; #[derive(Clone, Copy)] struct WrapInt8 { value: u8 } impl std::ops::Add for WrapInt8 { type Output = WrapInt8; fn add(self, other: WrapInt8) -> WrapInt8 { wrapping_add(self, other) } } fn main() { let p = WrapInt8 { value: 123 }; let q = WrapInt8 { value: 234 }; println!(\"{}\", (p + q).value); } "} {"_id":"q-en-rust-acf38c55fa4e9e0e95e2be1ed3926401e5a2144da248c677682d5eeb35545cba","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":"q-en-rust-ad0ba582a2dd3cbed4d34b8bfc967e392052648b674f52a2075b1eb1a345a152","text":"Ok(()) } pub fn remove_dir_all(p: &Path) -> io::Result<()> { fn remove_dir_all_modern(p: &Path) -> io::Result<()> { // We cannot just call remove_dir_all_recursive() here because that would not delete a passed // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse // into symlinks."} {"_id":"q-en-rust-ad258b08b417fc68e702472666b62b559873edbbe9c98533e3addd818dc9c89d","text":" // edition:2021 fn main() { &[1, 2, 3][1:2]; //~^ ERROR: expected one of //~| HELP: you might have meant a range expression } "} {"_id":"q-en-rust-ad2c0721e5809ea100979dcea906cbef2219837c8a499888463185ca98410653","text":"#[stable] pub trait Any: 'static { /// Get the `TypeId` of `self` #[stable] #[experimental = \"this method will likely be replaced by an associated static\"] fn get_type_id(&self) -> TypeId; }"} {"_id":"q-en-rust-ad359945428df992a5823ac9efa9d921ab167d39b2da0768c6815bb504a7bb78","text":"let x = self.parse_seq_to_before_end( &token::Gt, SeqSep::trailing_allowed(token::Comma), |p| p.parse_generic_arg(None), |p| match p.parse_generic_arg(None)? { Some(arg) => Ok(arg), // If we didn't eat a generic arg, then we should error. None => p.unexpected_any(), }, ); match x { Ok((_, _, Recovered::No)) => {"} {"_id":"q-en-rust-ad42ad3e19b4f9c08f20f337ef8b893b1a25beb7a80bd2bb0e0f17375e478be8","text":"let mut diag = cx.tcx.struct_span_lint_hir( lint::builtin::PRIVATE_DOC_TESTS, hir_id, span_of_attrs(&item.attrs), span_of_attrs(&item.attrs).unwrap_or(item.source.span()), \"Documentation test in private item\"); diag.emit(); } } /// Returns a span encompassing all the given attributes. crate fn span_of_attrs(attrs: &clean::Attributes) -> Span { crate fn span_of_attrs(attrs: &clean::Attributes) -> Option { if attrs.doc_strings.is_empty() { return DUMMY_SP; return None; } let start = attrs.doc_strings[0].span(); if start == DUMMY_SP { return None; } let end = attrs.doc_strings.last().expect(\"No doc strings provided\").span(); start.to(end) Some(start.to(end)) } /// Attempts to match a range of bytes from parsed markdown to a `Span` in the source code."} {"_id":"q-en-rust-ad5fe8f8feb6f0571be15f99ed9295f2e41580ced0a64fc560c4ef686cdb9ff2","text":".collect(), _ => Vec::new(), }; candidates.retain(|candidate| *candidate != self.tcx.parent(result.callee.def_id)); return Err(IllegalSizedBound(candidates, needs_mut, span)); }"} {"_id":"q-en-rust-ad73ccbc371628320380142030c6fbdd17f4d5b412e7bd0a88da5cebc255ba78","text":" // check-pass #![feature(c_variadic)] #![warn(function_item_references)] use std::fmt::Pointer; use std::fmt::Formatter; fn nop() { } fn foo() -> u32 { 42 } fn bar(x: u32) -> u32 { x } fn baz(x: u32, y: u32) -> u32 { x + y } unsafe fn unsafe_fn() { } extern \"C\" fn c_fn() { } unsafe extern \"C\" fn unsafe_c_fn() { } unsafe extern fn variadic(_x: u32, _args: ...) { } //function references passed to these functions should never lint fn call_fn(f: &dyn Fn(u32) -> u32, x: u32) { f(x); } fn parameterized_call_fn u32>(f: &F, x: u32) { f(x); } //function references passed to these functions should lint fn print_ptr(f: F) { println!(\"{:p}\", f); } fn bound_by_ptr_trait(_f: F) { } fn bound_by_ptr_trait_tuple(_t: (F, G)) { } fn implicit_ptr_trait(f: &F) { println!(\"{:p}\", f); } //case found in tinyvec that triggered a compiler error in an earlier version of the lint checker trait HasItem { type Item; fn assoc_item(&self) -> Self::Item; } fn _format_assoc_item(data: T, f: &mut Formatter) -> std::fmt::Result where T::Item: Pointer { //when the arg type bound by `Pointer` is an associated type, we shouldn't attempt to normalize Pointer::fmt(&data.assoc_item(), f) } //simple test to make sure that calls to `Pointer::fmt` aren't double counted fn _call_pointer_fmt(f: &mut Formatter) -> std::fmt::Result { let zst_ref = &foo; Pointer::fmt(&zst_ref, f) //~^ WARNING taking a reference to a function item does not give a function pointer } fn main() { //`let` bindings with function references shouldn't lint let _ = &foo; let _ = &mut foo; let zst_ref = &foo; let fn_item = foo; let indirect_ref = &fn_item; let _mut_zst_ref = &mut foo; let mut mut_fn_item = foo; let _mut_indirect_ref = &mut mut_fn_item; let cast_zst_ptr = &foo as *const _; let coerced_zst_ptr: *const _ = &foo; let _mut_cast_zst_ptr = &mut foo as *mut _; let _mut_coerced_zst_ptr: *mut _ = &mut foo; let _cast_zst_ref = &foo as &dyn Fn() -> u32; let _coerced_zst_ref: &dyn Fn() -> u32 = &foo; let _mut_cast_zst_ref = &mut foo as &mut dyn Fn() -> u32; let _mut_coerced_zst_ref: &mut dyn Fn() -> u32 = &mut foo; //the suggested way to cast to a function pointer let fn_ptr = foo as fn() -> u32; //correct ways to print function pointers println!(\"{:p}\", foo as fn() -> u32); println!(\"{:p}\", fn_ptr); //potential ways to incorrectly try printing function pointers println!(\"{:p}\", &foo); //~^ WARNING taking a reference to a function item does not give a function pointer print!(\"{:p}\", &foo); //~^ WARNING taking a reference to a function item does not give a function pointer format!(\"{:p}\", &foo); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &foo as *const _); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", zst_ref); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", cast_zst_ptr); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", coerced_zst_ptr); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &fn_item); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", indirect_ref); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &nop); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &bar); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &baz); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &unsafe_fn); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &c_fn); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &unsafe_c_fn); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &variadic); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p}\", &std::env::var::); //~^ WARNING taking a reference to a function item does not give a function pointer println!(\"{:p} {:p} {:p}\", &nop, &foo, &bar); //~^ WARNING taking a reference to a function item does not give a function pointer //~^^ WARNING taking a reference to a function item does not give a function pointer //~^^^ WARNING taking a reference to a function item does not give a function pointer //using a function reference to call a function shouldn't lint (&bar)(1); //passing a function reference to an arbitrary function shouldn't lint call_fn(&bar, 1); parameterized_call_fn(&bar, 1); std::mem::size_of_val(&foo); unsafe { //potential ways to incorrectly try transmuting function pointers std::mem::transmute::<_, usize>(&foo); //~^ WARNING taking a reference to a function item does not give a function pointer std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); //~^ WARNING taking a reference to a function item does not give a function pointer //~^^ WARNING taking a reference to a function item does not give a function pointer //the correct way to transmute function pointers std::mem::transmute::<_, usize>(foo as fn() -> u32); std::mem::transmute::<_, (usize, usize)>((foo as fn() -> u32, bar as fn(u32) -> u32)); } //function references as arguments required to be bound by std::fmt::Pointer should lint print_ptr(&bar); //~^ WARNING taking a reference to a function item does not give a function pointer bound_by_ptr_trait(&bar); //~^ WARNING taking a reference to a function item does not give a function pointer bound_by_ptr_trait_tuple((&foo, &bar)); //~^ WARNING taking a reference to a function item does not give a function pointer //~^^ WARNING taking a reference to a function item does not give a function pointer implicit_ptr_trait(&bar); // ignore //correct ways to pass function pointers as arguments bound by std::fmt::Pointer print_ptr(bar as fn(u32) -> u32); bound_by_ptr_trait(bar as fn(u32) -> u32); bound_by_ptr_trait_tuple((foo as fn() -> u32, bar as fn(u32) -> u32)); } "} {"_id":"q-en-rust-adb6143293c08bd96871b64232c1c81c7604a9b511f2b2e410b6331862fb8acf","text":"\"ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, expr_ty={:?}\", field, base, expr, expr_t ); let mut err = self.no_such_field_err(field.span, field, expr_t); let mut err = self.no_such_field_err(field, expr_t); match *expr_t.peel_refs().kind() { ty::Array(_, len) => {"} {"_id":"q-en-rust-ae07bb08d697e95b96a20955f23b5ed7f611e7e0e38cefdff50d32c098054c3a","text":" error: expected one of `extern` or `fn`, found `WhereIsFerris` --> $DIR/issue-68062-const-extern-fns-dont-need-fn-specifier-2.rs:5:18 | LL | const unsafe WhereIsFerris Now() {} | ^^^^^^^^^^^^^ expected one of `extern` or `fn` error: aborting due to previous error "} {"_id":"q-en-rust-ae15a8fa492b329292f0395503d64b74f329132acc869fffff62231fee12f126","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":"q-en-rust-ae5f00ddff053ca69f1d2a5e73c22fb23adc81db6c652adcd10ab4cf1395db4b","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":"q-en-rust-ae612c1a5d5fba8c446dbc8ab69fade11827500a1116f48bb6a7ecc07893bd0d","text":"use rustc_infer::infer::{self, InferOk}; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::subst::{InternalSubsts, SubstsRef}; use rustc_middle::ty::{self, DefIdTree, GenericParamDefKind, Ty, TypeVisitable}; use rustc_middle::ty::{self, GenericParamDefKind, Ty, TypeVisitable}; use rustc_span::symbol::Ident; use rustc_span::Span; use rustc_trait_selection::traits;"} {"_id":"q-en-rust-ae97269d9cd5901a2096a52465bd070dc9ef8a65e88953cf90f75933e80f0123","text":"return None; }; if new_ty.references_error() { return None; } self.state.steps.push((self.state.cur_ty, kind)); debug!( \"autoderef stage #{:?} is {:?} from {:?}\","} {"_id":"q-en-rust-aec62fdbfa3cb45adb2996623b8c3738fc827fabf758cdaf1c7ce460f0ed98d6","text":"/// # Examples /// /// ``` /// # #![feature(vec_remove_item)] /// let mut vec = vec![1, 2, 3, 1]; /// /// vec.remove_item(&1); /// /// assert_eq!(vec, vec![2, 3, 1]); /// ``` #[unstable(feature = \"vec_remove_item\", reason = \"recently added\", issue = \"40062\")] #[stable(feature = \"vec_remove_item\", since = \"1.42.0\")] pub fn remove_item(&mut self, item: &V) -> Option where T: PartialEq,"} {"_id":"q-en-rust-aedffe044c7fe440dede4fd58c1756a4794b0a14087a8e3d95d6c6939f74b5cf","text":"_ => None, } } fn host_dll_subdir() -> Option<&'static str> { if cfg!(target_arch = \"x86_64\") { Some(\"amd64\") } else if cfg!(target_arch = \"x86\") { Some(\"\") } else { None } } } // If we're not on Windows, then there's no registry to search through and MSVC // wouldn't be able to run, so we just call `link.exe` and hope for the best. #[cfg(not(windows))] pub fn link_exe_cmd(_sess: &Session) -> Command { Command::new(\"link.exe\") mod platform { use std::path::PathBuf; use std::process::Command; use session::Session; pub fn link_exe_cmd(_sess: &Session) -> Command { Command::new(\"link.exe\") } pub fn host_dll_path() -> Option { None } } pub use self::platform::*; "} {"_id":"q-en-rust-af3447b732c8bcfce3182d94b42da7e79c6dd779ce1a9622e67c280bd377b6e3","text":"let len = self.buf.len(); let mut ret = Ok(()); while written < len { match self.inner.as_mut().unwrap().write(&self.buf[written..]) { self.panicked = true; let r = self.inner.as_mut().unwrap().write(&self.buf[written..]); self.panicked = false; match r { Ok(0) => { ret = Err(Error::new(ErrorKind::WriteZero, \"failed to write the buffered data\"));"} {"_id":"q-en-rust-af858eef48d17f9fec1c3b42fe9b490fe4ca0a69a366e5968bbcf0030437c11b","text":"}, value_ns: match self.resolve( path_str, disambiguator, ValueNS, ¤t_item, base_node,"} {"_id":"q-en-rust-afc0c2ebcda797caffa7ff2955d0a7d3c93ba27d664b71b1c43d74efef5cd23a","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. // Tests the rustdoc --sort-modules-by-appearance option, that allows module declarations to appear // in the order they are declared in the source code, rather than only alphabetically. // compile-flags: -Z unstable-options --sort-modules-by-appearance pub mod module_b {} pub mod module_c {} pub mod module_a {} // @matches 'sort_modules_by_appearance/index.html' '(?s)module_b.*module_c.*module_a' // @matches 'sort_modules_by_appearance/sidebar-items.js' '\"module_b\".*\"module_c\".*\"module_a\"' "} {"_id":"q-en-rust-affad38e75aea1758f6d18fe33694c5b6647b87555dbecd90b71acd73de72e85","text":" error[E0609]: no field `c` on type `Foo` --> $DIR/non-existent-field-present-in-subfield.rs:37:24 | LL | let _test = &fooer.c; | ^ unknown field | = note: available fields are: `first`, `_second`, `_third` help: one of the expressions' fields has a field of the same name | LL | let _test = &fooer.first.bar.c; | ^^^^^^^^^^ error[E0609]: no field `test` on type `Foo` --> $DIR/non-existent-field-present-in-subfield.rs:40:24 | LL | let _test2 = fooer.test; | ^^^^ unknown field | = note: available fields are: `first`, `_second`, `_third` help: one of the expressions' fields has a field of the same name | LL | let _test2 = fooer.first.bar.c.test; | ^^^^^^^^^^^^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0609`. "} {"_id":"q-en-rust-b0025cdd9313feed75eea1cfc01d76122abb72bf5d618f91858ad685d027cb51","text":"mod stripper; pub(crate) use stripper::*; mod strip_aliased_non_local; pub(crate) use self::strip_aliased_non_local::STRIP_ALIASED_NON_LOCAL; mod strip_hidden; pub(crate) use self::strip_hidden::STRIP_HIDDEN;"} {"_id":"q-en-rust-b01cf93aaec4a94ef183b8740082d1a87e4135986d714929d98ffe4730a58399","text":"} fn test_26444() { assert_eq!(\"a , b , c , d , e\", foo_26444!(a, b; c; d, e)); assert_eq!(\"a, b, c, d, e\", foo_26444!(a, b; c; d, e)); assert_eq!(\"f\", foo_26444!(; f ;)); }"} {"_id":"q-en-rust-b053bc864458a695ec887b3dcdd43c1a6f0b457b9c286d7b457d013061984886","text":"# 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! - script: | powershell -Command \"$ProgressPreference = 'SilentlyContinue'; iwr -outf is-install.exe https://rust-lang-ci-mirrors.s3-us-west-1.amazonaws.com/rustc/2017-08-22-is.exe\" is-install.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP- echo ##vso[task.prependpath]C:Program Files (x86)Inno Setup 5 curl.exe -o is-install.exe https://rust-lang-ci-mirrors.s3-us-west-1.amazonaws.com/rustc/2017-08-22-is.exe is-install.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP- displayName: Install InnoSetup condition: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT'))"} {"_id":"q-en-rust-b059fd7d82f937efdce9337cb8020cfc2eae894c2cc9084d876a1801db1cf4fa","text":"let maybe_sysroot = matches.opt_str(\"sysroot\").map(PathBuf::from); let display_warnings = matches.opt_present(\"display-warnings\"); let linker = matches.opt_str(\"linker\").map(PathBuf::from); let sort_modules_alphabetically = !matches.opt_present(\"sort-modules-by-appearance\"); match (should_test, markdown_input) { (true, true) => {"} {"_id":"q-en-rust-b08164a05d3b8e28d4e474af16a85e92d7a78d5f268e59bbb44dcce1ac693467","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":"q-en-rust-b0a5a5675621c0e0ac8d2ae0ae3cca59ef26089c8556527805056c91ccd1de1f","text":"\"extra arguments to prepend to the linker invocation (space separated)\"), profile: bool = (false, parse_bool, [TRACKED], \"insert profiling code\"), disable_instrumentation_preinliner: bool = (false, parse_bool, [TRACKED], \"Disable the instrumentation pre-inliner, useful for profiling / PGO.\"), relro_level: Option = (None, parse_relro_level, [TRACKED], \"choose which RELRO level to use\"), nll_facts: bool = (false, parse_bool, [UNTRACKED],"} {"_id":"q-en-rust-b0b9863b403080f447e63ae0cf9327cf902a07dddbb167336016e902e8fc32b9","text":"use rustc_middle::bug; use rustc_middle::hir::nested_filter::OnlyBodies; use rustc_middle::mir::tcx::PlaceTy; use rustc_middle::mir::VarDebugInfoContents; use rustc_middle::mir::{ self, AggregateKind, BindingForm, BorrowKind, CallSource, ClearCrossCrate, ConstraintCategory, FakeBorrowKind, FakeReadCause, LocalDecl, LocalInfo, LocalKind, Location, MutBorrowKind,"} {"_id":"q-en-rust-b0d606c329a0b6e53bb9be79a994b5c7f8d6f99ab70feef628650ee8ab9699eb","text":") -> Item { let target_attrs = inline::load_attrs(cx, def_id); let attrs = if let Some(import_id) = import_id { // glob reexports are treated the same as `#[doc(inline)]` items. // // For glob re-exports the item may or may not exist to be re-exported (potentially the cfgs // on the path up until the glob can be removed, and only cfgs on the globbed item itself // matter), for non-inlined re-exports see #85043. let is_inline = inline::load_attrs(cx, import_id.to_def_id()) .lists(sym::doc) .get_word_attr(sym::inline) .is_some(); .is_some() || (is_glob_import(cx.tcx, import_id) && (cx.render_options.document_hidden || !cx.tcx.is_doc_hidden(def_id))); let mut attrs = get_all_import_attributes(cx, import_id, def_id, is_inline); add_without_unwanted_attributes(&mut attrs, target_attrs, is_inline, None); attrs"} {"_id":"q-en-rust-b0f0c821ddf254aad279ea0b53ecc53fde039ed6a0faeeff1d3319b1f729ed8d","text":"/// # Examples /// /// ``` /// #![feature(vec_spare_capacity)] /// /// // Allocate vector big enough for 10 elements. /// let mut v = Vec::with_capacity(10); ///"} {"_id":"q-en-rust-b11b9ed495ee1755bbac9cb3c7121c0e9f76ab7563e320a12ef3e6b53a43ad6c","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":"q-en-rust-b127f11bc1abeafe158fb50c618032059c948c3bbb3745f975545cf998ffc109","text":"/// Creates an iterator that skips the first `n` elements. /// /// After they have been consumed, the rest of the elements are yielded. /// Rather than overriding this method directly, instead override the `nth` method. /// /// # Examples ///"} {"_id":"q-en-rust-b12b65d3e2c80a68c849d5f7b384c7840f129f050d2772ed1ecc74a5cefb8971","text":"} } /// Constructs a new `Rc` using a closure `data_fn` that has access to a /// weak reference to the constructing `Rc`. /// Constructs a new `Rc` while giving you a `Weak` to the allocation, /// to allow you to construct a `T` which holds a weak pointer to itself. /// /// Generally, a structure circularly referencing itself, either directly or /// indirectly, should not hold a strong reference to prevent a memory leak. /// In `data_fn`, initialization of `T` can make use of the weak reference /// by cloning and storing it inside `T` for use at a later time. /// indirectly, should not hold a strong reference to itself to prevent a memory leak. /// Using this function, you get access to the weak pointer during the /// initialization of `T`, before the `Rc` is created, such that you can /// clone and store it inside the `T`. /// /// `new_cyclic` first allocates the managed allocation for the `Rc`, /// then calls your closure, giving it a `Weak` to this allocation, /// and only afterwards completes the construction of the `Rc` by placing /// the `T` returned from your closure into the allocation. /// /// Since the new `Rc` is not fully-constructed until `Rc::new_cyclic` /// returns, calling [`upgrade`] on the weak reference inside `data_fn` will /// returns, calling [`upgrade`] on the weak reference inside your closure will /// fail and result in a `None` value. /// /// # Panics /// /// If `data_fn` panics, the panic is propagated to the caller, and the /// temporary [`Weak`] is dropped normally. ///"} {"_id":"q-en-rust-b15904aede167d26caa238a9c5f32dfe385a67a6dd4fd45274b4dcf1fcd5df25","text":"// stripping away any starting or ending parenthesis characters—hence this // test of the JSON error format. #![warn(unused_parens)] #![deny(unused_parens)] #![allow(unreachable_code)] fn main() { // We want to suggest the properly-balanced expression `1 / (2 + 3)`, not // the malformed `1 / (2 + 3` let _a = 1 / (2 + 3); let _a = 1 / (2 + 3); //~ERROR unnecessary parentheses f(); }"} {"_id":"q-en-rust-b169a1e4e3b23d96469d2c8b1f973a0eb4331b55ada86ecda91b03739039d0d7","text":" //~ ERROR overflow evaluating the requirement `([isize; 0], _): Sized trait Foo { fn get(&self, A: &A) { } }"} {"_id":"q-en-rust-b1c12d9e41093b5f9f9336fec76a8d29472a99bb871f53dcda7cfe07edaed50d","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":"q-en-rust-b1f75d96ad6205a588182107d4cf0b2821a9d6a0beffb4f46346fdf4364e71cf","text":" error: expected `while`, `for`, `loop` or `{` after a label --> $DIR/str-as-char-butchered.rs:4:21 | LL | let _: &str = 'β; | ^ expected `while`, `for`, `loop` or `{` after a label | help: add `'` to close the char literal | LL | let _: &str = 'β'; | + error[E0308]: mismatched types --> $DIR/str-as-char-butchered.rs:4:19 | LL | let _: &str = 'β; | ---- ^^ expected `&str`, found `char` | | | expected due to this error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-b20d31d36e8505caf49135358ed435ca061a16188879f6044bdb72baf3d74b8d","text":"#[inline] unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { let mut out = ptr::null_mut(); let ret = libc::posix_memalign(&mut out, layout.align(), layout.size()); // posix_memalign requires that the alignment be a multiple of `sizeof(void*)`. // Since these are all powers of 2, we can just use max. let align = layout.align().max(crate::mem::size_of::()); let ret = libc::posix_memalign(&mut out, align, layout.size()); if ret != 0 { ptr::null_mut() } else {"} {"_id":"q-en-rust-b2878e09600e9b62fadcb4263d3356096e45cb14a08b19e5f399e9686322aeed","text":"// Explicitly check for lints associated with 'closure_id', since // it does not have a corresponding AST node if let ast::ExprKind::Closure(_, asyncness, ..) = e.kind { if let ast::Async::Yes { closure_id, .. } = asyncness { self.check_id(closure_id); } match e.kind { ast::ExprKind::Closure(_, ast::Async::Yes { closure_id, .. }, ..) | ast::ExprKind::Async(_, closure_id, ..) => self.check_id(closure_id), _ => {} } }"} {"_id":"q-en-rust-b29adaec8a4992dada6fa1e252699038a5d007b1291601ecc83f319cedf857d7","text":"ignore_fmt.add(&format!(\"!/{}\", untracked_path)).expect(&untracked_path); } if !check && paths.is_empty() { if let Some(files) = get_modified_files(build) { if let Some(files) = get_modified_rs_files(build) { for file in files { println!(\"formatting modified file {file}\"); ignore_fmt.add(&format!(\"/{file}\")).expect(&file);"} {"_id":"q-en-rust-b29e6abf3641bc56ca591872e8bf9ec13e2cc4e9cc579662973a1423898fc70c","text":" // check-pass use std::error::Error as StdError; use std::pin::Pin; use std::task::{Context, Poll}; pub trait Stream { type Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; fn size_hint(&self) -> (usize, Option) { (0, None) } } pub trait TryStream: Stream { type Ok; type Error; fn try_poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll>>; } impl TryStream for S where S: ?Sized + Stream>, { type Ok = T; type Error = E; fn try_poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll>> { self.poll_next(cx) } } pub trait ServerSentEvent: Sized + Send + Sync + 'static {} impl ServerSentEvent for T {} struct SseKeepAlive { event_stream: S, } struct SseComment(T); impl Stream for SseKeepAlive where S: TryStream + Send + 'static, S::Ok: ServerSentEvent, S::Error: StdError + Send + Sync + 'static, { type Item = Result, ()>; fn poll_next(self: Pin<&mut Self>, _cx: &mut Context) -> Poll> { unimplemented!() } } pub fn keep( event_stream: S, ) -> impl TryStream + Send + 'static where S: TryStream + Send + 'static, S::Ok: ServerSentEvent + Send, S::Error: StdError + Send + Sync + 'static, { SseKeepAlive { event_stream } } fn main() {} "} {"_id":"q-en-rust-b2ae1068f6a2448522e84a4557ccc1c44e98cf07f382cdc03ff7f4f2911377ab","text":"/// // Calculate how many bytes can be written without flushing /// let without_flush = capacity - buf_writer.buffer().len(); /// ``` #[unstable(feature = \"buffered_io_capacity\", issue = \"68833\")] #[stable(feature = \"buffered_io_capacity\", since = \"1.46.0\")] pub fn capacity(&self) -> usize { self.buf.capacity() }"} {"_id":"q-en-rust-b30772bf6ada6ed9c1c81c5e17f321bdd59d9f2f1470d48cb2fafb99a005cadf","text":" // edition:2021 // run-rustfix #![allow(dead_code)] async fn a() {} async fn foo() -> Result<(), i32> { Ok(a().await) //~ ERROR mismatched types } fn main() {} "} {"_id":"q-en-rust-b30ccf7170db4a32a0eea793913fc3e56357edcf728802c94b12cf4234034865","text":"/// # Examples /// /// ``` /// #![feature(osstring_ascii)] /// use std::ffi::OsString; /// let s = OsString::from(\"Grüße, Jürgen ❤\"); /// /// assert_eq!(\"grüße, jürgen ❤\", s.to_ascii_lowercase()); /// ``` #[unstable(feature = \"osstring_ascii\", issue = \"70516\")] #[stable(feature = \"osstring_ascii\", since = \"1.53.0\")] pub fn to_ascii_lowercase(&self) -> OsString { OsString::from_inner(self.inner.to_ascii_lowercase()) }"} {"_id":"q-en-rust-b376e9aa5675ce5f05851b88a294d12399f7bb4f166a75f4f19eaa3ecc48ff01","text":"--codeblock-error-color: rgba(255, 0, 0, .5); --codeblock-ignore-hover-color: rgb(255, 142, 0); --codeblock-ignore-color: rgba(255, 142, 0, .6); --warning-border-color: rgb(255, 142, 0); --type-link-color: #ad378a; --trait-link-color: #6e4fc9; --assoc-item-link-color: #3873ad;"} {"_id":"q-en-rust-b39781cb257409ef5f3ce753db3d57b563231bdeaec73909b84a0db3f3bc1fbc","text":" use rustc::hir::def_id::DefId; use rustc::mir; use rustc::ty::layout::HasTyCtxt; use rustc::ty::{self, Ty, TyCtxt}; use std::borrow::{Borrow, Cow}; use std::collections::hash_map::Entry; use std::hash::Hash; use rustc_data_structures::fx::FxHashMap; use syntax::source_map::Span; use crate::interpret::{ self, snapshot, AllocId, Allocation, AssertMessage, GlobalId, ImmTy, InterpCx, InterpResult, Memory, MemoryKind, OpTy, PlaceTy, Pointer, Scalar, }; use super::error::*; impl<'mir, 'tcx> InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>> { /// Evaluate a const function where all arguments (if any) are zero-sized types. /// The evaluation is memoized thanks to the query system. /// /// Returns `true` if the call has been evaluated. fn try_eval_const_fn_call( &mut self, instance: ty::Instance<'tcx>, ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, args: &[OpTy<'tcx>], ) -> InterpResult<'tcx, bool> { trace!(\"try_eval_const_fn_call: {:?}\", instance); // Because `#[track_caller]` adds an implicit non-ZST argument, we also cannot // perform this optimization on items tagged with it. if instance.def.requires_caller_location(self.tcx()) { return Ok(false); } // For the moment we only do this for functions which take no arguments // (or all arguments are ZSTs) so that we don't memoize too much. if args.iter().any(|a| !a.layout.is_zst()) { return Ok(false); } let gid = GlobalId { instance, promoted: None }; let place = self.const_eval_raw(gid)?; let dest = match ret { Some((dest, _)) => dest, // Don't memoize diverging function calls. None => return Ok(false), }; self.copy_op(place.into(), dest)?; self.return_to_block(ret.map(|r| r.1))?; self.dump_place(*dest); return Ok(true); } } /// Number of steps until the detector even starts doing anything. /// Also, a warning is shown to the user when this number is reached. const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000; /// The number of steps between loop detector snapshots. /// Should be a power of two for performance reasons. const DETECTOR_SNAPSHOT_PERIOD: isize = 256; // Extra machine state for CTFE, and the Machine instance pub struct CompileTimeInterpreter<'mir, 'tcx> { /// When this value is negative, it indicates the number of interpreter /// steps *until* the loop detector is enabled. When it is positive, it is /// the number of steps after the detector has been enabled modulo the loop /// detector period. pub(super) steps_since_detector_enabled: isize, /// Extra state to detect loops. pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>, } #[derive(Copy, Clone, Debug)] pub struct MemoryExtra { /// Whether this machine may read from statics can_access_statics: bool, } impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> { fn new() -> Self { CompileTimeInterpreter { loop_detector: Default::default(), steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED, } } } impl interpret::AllocMap for FxHashMap { #[inline(always)] fn contains_key(&mut self, k: &Q) -> bool where K: Borrow, { FxHashMap::contains_key(self, k) } #[inline(always)] fn insert(&mut self, k: K, v: V) -> Option { FxHashMap::insert(self, k, v) } #[inline(always)] fn remove(&mut self, k: &Q) -> Option where K: Borrow, { FxHashMap::remove(self, k) } #[inline(always)] fn filter_map_collect(&self, mut f: impl FnMut(&K, &V) -> Option) -> Vec { self.iter().filter_map(move |(k, v)| f(k, &*v)).collect() } #[inline(always)] fn get_or(&self, k: K, vacant: impl FnOnce() -> Result) -> Result<&V, E> { match self.get(&k) { Some(v) => Ok(v), None => { vacant()?; bug!(\"The CTFE machine shouldn't ever need to extend the alloc_map when reading\") } } } #[inline(always)] fn get_mut_or(&mut self, k: K, vacant: impl FnOnce() -> Result) -> Result<&mut V, E> { match self.entry(k) { Entry::Occupied(e) => Ok(e.into_mut()), Entry::Vacant(e) => { let v = vacant()?; Ok(e.insert(v)) } } } } crate type CompileTimeEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>; impl interpret::MayLeak for ! { #[inline(always)] fn may_leak(self) -> bool { // `self` is uninhabited self } } impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> { type MemoryKinds = !; type PointerTag = (); type ExtraFnVal = !; type FrameExtra = (); type MemoryExtra = MemoryExtra; type AllocExtra = (); type MemoryMap = FxHashMap, Allocation)>; const STATIC_KIND: Option = None; // no copying of statics allowed // We do not check for alignment to avoid having to carry an `Align` // in `ConstValue::ByRef`. const CHECK_ALIGN: bool = false; #[inline(always)] fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool { false // for now, we don't enforce validity } fn find_mir_or_eval_fn( ecx: &mut InterpCx<'mir, 'tcx, Self>, instance: ty::Instance<'tcx>, args: &[OpTy<'tcx>], ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, _unwind: Option, // unwinding is not supported in consts ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> { debug!(\"find_mir_or_eval_fn: {:?}\", instance); // Only check non-glue functions if let ty::InstanceDef::Item(def_id) = instance.def { // Execution might have wandered off into other crates, so we cannot do a stability- // sensitive check here. But we can at least rule out functions that are not const // at all. if ecx.tcx.is_const_fn_raw(def_id) { // If this function is a `const fn` then under certain circumstances we // can evaluate call via the query system, thus memoizing all future calls. if ecx.try_eval_const_fn_call(instance, ret, args)? { return Ok(None); } } else { // Some functions we support even if they are non-const -- but avoid testing // that for const fn! We certainly do *not* want to actually call the fn // though, so be sure we return here. return if ecx.hook_panic_fn(instance, args, ret)? { Ok(None) } else { throw_unsup_format!(\"calling non-const function `{}`\", instance) }; } } // This is a const fn. Call it. Ok(Some(match ecx.load_mir(instance.def, None) { Ok(body) => *body, Err(err) => { if let err_unsup!(NoMirFor(ref path)) = err.kind { return Err(ConstEvalError::NeedsRfc(format!( \"calling extern function `{}`\", path )) .into()); } return Err(err); } })) } fn call_extra_fn( _ecx: &mut InterpCx<'mir, 'tcx, Self>, fn_val: !, _args: &[OpTy<'tcx>], _ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, _unwind: Option, ) -> InterpResult<'tcx> { match fn_val {} } fn call_intrinsic( ecx: &mut InterpCx<'mir, 'tcx, Self>, span: Span, instance: ty::Instance<'tcx>, args: &[OpTy<'tcx>], ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, _unwind: Option, ) -> InterpResult<'tcx> { if ecx.emulate_intrinsic(span, instance, args, ret)? { return Ok(()); } // An intrinsic that we do not support let intrinsic_name = ecx.tcx.item_name(instance.def_id()); Err(ConstEvalError::NeedsRfc(format!(\"calling intrinsic `{}`\", intrinsic_name)).into()) } fn assert_panic( ecx: &mut InterpCx<'mir, 'tcx, Self>, _span: Span, msg: &AssertMessage<'tcx>, _unwind: Option, ) -> InterpResult<'tcx> { use rustc::mir::interpret::PanicInfo::*; Err(match msg { BoundsCheck { ref len, ref index } => { let len = ecx .read_immediate(ecx.eval_operand(len, None)?) .expect(\"can't eval len\") .to_scalar()? .to_machine_usize(&*ecx)?; let index = ecx .read_immediate(ecx.eval_operand(index, None)?) .expect(\"can't eval index\") .to_scalar()? .to_machine_usize(&*ecx)?; err_panic!(BoundsCheck { len, index }) } Overflow(op) => err_panic!(Overflow(*op)), OverflowNeg => err_panic!(OverflowNeg), DivisionByZero => err_panic!(DivisionByZero), RemainderByZero => err_panic!(RemainderByZero), ResumedAfterReturn(generator_kind) => err_panic!(ResumedAfterReturn(*generator_kind)), ResumedAfterPanic(generator_kind) => err_panic!(ResumedAfterPanic(*generator_kind)), Panic { .. } => bug!(\"`Panic` variant cannot occur in MIR\"), } .into()) } fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> { Err(ConstEvalError::NeedsRfc(\"pointer-to-integer cast\".to_string()).into()) } fn binary_ptr_op( _ecx: &InterpCx<'mir, 'tcx, Self>, _bin_op: mir::BinOp, _left: ImmTy<'tcx>, _right: ImmTy<'tcx>, ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> { Err(ConstEvalError::NeedsRfc(\"pointer arithmetic or comparison\".to_string()).into()) } fn find_foreign_static( _tcx: TyCtxt<'tcx>, _def_id: DefId, ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> { throw_unsup!(ReadForeignStatic) } #[inline(always)] fn init_allocation_extra<'b>( _memory_extra: &MemoryExtra, _id: AllocId, alloc: Cow<'b, Allocation>, _kind: Option>, ) -> (Cow<'b, Allocation>, Self::PointerTag) { // We do not use a tag so we can just cheaply forward the allocation (alloc, ()) } #[inline(always)] fn tag_static_base_pointer(_memory_extra: &MemoryExtra, _id: AllocId) -> Self::PointerTag { () } fn box_alloc( _ecx: &mut InterpCx<'mir, 'tcx, Self>, _dest: PlaceTy<'tcx>, ) -> InterpResult<'tcx> { Err(ConstEvalError::NeedsRfc(\"heap allocations via `box` keyword\".to_string()).into()) } fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { { let steps = &mut ecx.machine.steps_since_detector_enabled; *steps += 1; if *steps < 0 { return Ok(()); } *steps %= DETECTOR_SNAPSHOT_PERIOD; if *steps != 0 { return Ok(()); } } let span = ecx.frame().span; ecx.machine.loop_detector.observe_and_analyze(*ecx.tcx, span, &ecx.memory, &ecx.stack[..]) } #[inline(always)] fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { Ok(()) } fn before_access_static( memory_extra: &MemoryExtra, _allocation: &Allocation, ) -> InterpResult<'tcx> { if memory_extra.can_access_statics { Ok(()) } else { Err(ConstEvalError::ConstAccessesStatic.into()) } } } // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable // at the bottom of this file. "} {"_id":"q-en-rust-b3bcdba05e7dd6fa641ba1929b2f8853f66bb6f990358cbfcfbf73422e23a515","text":" // no-prefer-dynamic fn main() { let _ = std::io::stdin(); let _ = std::io::stdout();"} {"_id":"q-en-rust-b3c6bcc568d68497bd06f1b68f2c2b5969e2be42cf7255c4c6d1c624c3cb3640","text":"/// Returns the number of leading zeros in the binary representation of `self`. /// /// Depending on what you're doing with the value, you might also be interested in the /// [`ilog2`] function which returns a consistent number, even if the type widens. /// /// # Examples /// /// Basic usage:"} {"_id":"q-en-rust-b40beff24ee7e3202681dd14885b767136ecf666135dd6e3e248a0dd9924b54b","text":" fn main() { let x = (1, 2, 3); match x { (_a, _x @ ..) => {} _ => {} } } //~^^^^ ERROR `_x @` is not allowed in a tuple "} {"_id":"q-en-rust-b40cfc6c78c7fee231542eb17b4305126d4b775b78510c5360638826de890ded","text":" // no-prefer-dynamic static mut DROP_RAN: isize = 0; struct Foo;"} {"_id":"q-en-rust-b41c877679605316dfe9e8ca37935697977442902068ed78964d2c4e4a30220b","text":"return; } if self.in_scope_lifetimes.contains(&ident.modern()) { if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.modern())) { return; }"} {"_id":"q-en-rust-b430a425f0426eeae611189f854eb2285ce0c2e47902d47658886411e1897a5b","text":" mod b { pub struct A(u32); } trait Id { type Assoc; } impl Id for b::A { type Assoc = b::A; } impl Id for u32 { type Assoc = u32; } trait Trait { fn method(&self) where T: Id; } impl Trait for ::Assoc { fn method(&self) where T: Id, { let Self(a) = self; //~^ ERROR: tuple struct constructor `A` is private println!(\"{a}\"); } } fn main() {} "} {"_id":"q-en-rust-b435f7489b79a1269badc7cf7bddb4a710b3cef2fac2f4a03f3efc4b09d67171","text":"--set target.x86_64-unknown-linux-gnu.ranlib=/rustroot/bin/llvm-ranlib --set llvm.thin-lto=true --set llvm.ninja=false --set llvm.use-linker=lld --set rust.use-lld=true --set rust.jemalloc ENV SCRIPT ../src/ci/pgo.sh python3 ../x.py dist ENV SCRIPT ../src/ci/pgo.sh python2.7 ../x.py dist --host $HOSTS --target $HOSTS --include-default-paths src/tools/build-manifest"} {"_id":"q-en-rust-b48d06aabda7f9b520466ad78c1c6b91e45317e689dadc9b30938abe3b1cb05c","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. struct Foo<'r>(&'r mut i32); impl<'r> Drop for Foo<'r> { fn drop(&mut self) { *self.0 += 1; } } trait Trait {} impl<'r> Trait for Foo<'r> {} struct Holder(T); fn main() { let mut drops = 0; { let y = &Holder([Foo(&mut drops)]) as &Holder<[Foo]>; // this used to cause an extra drop of the Foo instance let x = &y.0; } assert_eq!(1, drops); drops = 0; { let y = &Holder(Foo(&mut drops)) as &Holder; // this used to cause an extra drop of the Foo instance let x = &y.0; } assert_eq!(1, drops); } "} {"_id":"q-en-rust-b49643160e8676bfe19dde00e2e1d0c7f67949cf60e28cf84a7078b649316c2c","text":"7331 })); assert_eq!(foo, 42); // Test trailing comma: assert_eq!((\"Yeah\",), dbg!((\"Yeah\",))); // Test multiple arguments: assert_eq!((1u8, 2u32), dbg!(1, 2)); // Test multiple arguments + trailing comma: assert_eq!((1u8, 2u32, \"Yeah\"), dbg!(1u8, 2u32, \"Yeah\",)); } fn validate_stderr(stderr: Vec) {"} {"_id":"q-en-rust-b4ca640f7e5d05cd2276b4836b8decfc60f429fe7eec3450650c181d8dc91dc7","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":"q-en-rust-b4ddaffb40c73906735c8b7f44e275cff99977f0c39234783cbf6fbe5c8b6a3e","text":"//! Types/fns concerning URLs (see RFC 3986) #![crate_name = \"url\"] #![experimental] #![deprecated=\"This is being removed. Use rust-url instead. http://servo.github.io/rust-url/\"] #![crate_type = \"rlib\"] #![crate_type = \"dylib\"] #![license = \"MIT/ASL2\"]"} {"_id":"q-en-rust-b4f395b6b3fb22f6aca7b6104177b94537af477301666425f5f8ca9484c118cf","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":"q-en-rust-b523cfd67ece5f2e6a8d67c450dd03609bee563d0fa77dd5e82575f00eb6a222","text":" error[E0425]: cannot find value `bogus` in this scope --> $DIR/issue-59134-0.rs:8:27 | LL | const FLAG: u32 = bogus.field; | ^^^^^ not found in this scope error: aborting due to previous error For more information about this error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-b52bc1eb1a5635da45d8d1fba08e094369fb034d1c9d39d737fbe75bcbf3384c","text":" //@ known-bug: #111699 //@ edition:2021 //@ compile-flags: -Copt-level=0 #![feature(core_intrinsics)] use std::intrinsics::offset; fn main() { let a = [1u8, 2, 3]; let ptr: *const u8 = a.as_ptr(); unsafe { assert_eq!(*offset(ptr, 0), 1); } } "} {"_id":"q-en-rust-b53be2f8e483b6864032ff0d8f638bd0474d74e2bac56c18251b8945aef93672","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":"q-en-rust-b560d2a6b66c4b08d42de194f83256b862772ebca3f1c0ddcbcc3df5d1e8088a","text":") -> R { I::with_global_cache(self, mode, f) } fn evaluation_is_concurrent(&self) -> bool { self.evaluation_is_concurrent() } }"} {"_id":"q-en-rust-b5a9c6e31eaa32712e8aa11ab0d01373687448aecee424c8a4aba71ecbf0722d","text":" // build-fail #![feature(track_caller)] fn main() { (0..) .map( #[target_feature(enable = \"\")] //~^ ERROR: the feature named `` is not valid for this target //~| ERROR: `#[target_feature(..)]` can only be applied to `unsafe` functions #[track_caller] //~^ ERROR: `#[track_caller]` requires Rust ABI |_| (), ) .next(); } "} {"_id":"q-en-rust-b5bb6d987adc48ffbe83f7bb116b503f054e90c08c0d059bcd27d5f296d028a9","text":"} _ => bug!(\"Detected `&*` but didn't find `&*`!\"), }; *rvalue = Rvalue::Use(match mtbl { Mutability::Mut => Operand::Move(new_place), Mutability::Not => Operand::Copy(new_place), }); *rvalue = Rvalue::Use(Operand::Copy(new_place)) } if let Some(constant) = self.optimizations.arrays_lengths.remove(&location) {"} {"_id":"q-en-rust-b5dc21aca58affde69b68dc86797637d6319e45250678bb806f5fd1d74eb2fec","text":" error[E0412]: cannot find type `Oper` in this scope --> $DIR/issue-54966.rs:3:27 | LL | fn generate_duration() -> Oper {} | ^^^^ not found in this scope error: aborting due to previous error For more information about this error, try `rustc --explain E0412`. "} {"_id":"q-en-rust-b5ef5fa830822948ff108f0fddf2c7cd1728e80c207d9f596d6c5ed0e53f74ec","text":" // run-rustfix fn main() { let a: usize = 123; let b: &usize = &a; if true { a } else { *b //~ ERROR `if` and `else` have incompatible types [E0308] }; if true { 1 } else { 1 //~ ERROR `if` and `else` have incompatible types [E0308] }; if true { 1 } else { 1 //~ ERROR `if` and `else` have incompatible types [E0308] }; } "} {"_id":"q-en-rust-b5fc17187cab9a36105bd514bc52cf3f3d1c7b7491a7811525562f90fc390f5b","text":" error: argument to `panic!()` in a const context must have type `&str` --> $DIR/issue-66693-panic-in-array-len.rs:8:20 | LL | let _ = [0i32; panic!(2f32)]; | ^^^^^^^^^^^^ | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/issue-66693-panic-in-array-len.rs:12:21 | LL | let _ = [false; panic!()]; | ^^^^^^^^ the evaluated program panicked at 'explicit panic', $DIR/issue-66693-panic-in-array-len.rs:12:21 | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0080`. "} {"_id":"q-en-rust-b60a83dd72393c8ce7821df6d7201b70738b0aac6736b8a20ffdb1e467f89214","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":"q-en-rust-b656140a4f67b9e5aee0254d0216c97e5ce2c0989eae9bdfad1a8fe31694b045","text":"// except according to those terms. struct Foo { field1: i32, //~ NOTE `field1` first declared here field1: i32, field1: i32, //~ ERROR E0124 //~^ ERROR field `field1` is already declared [E0124] //~| NOTE field already declared } fn main() {"} {"_id":"q-en-rust-b669fe7451b2cb61f28d9632782b8b14fc88eaaf91619f7d1ce0805bc2109230","text":"// for closures and async closures, respectively. match closure_kind { hir::ClosureKind::Closure if self.tcx.fn_trait_kind_from_def_id(trait_def_id).is_some() => {} if self.tcx.fn_trait_kind_from_def_id(trait_def_id).is_some() => { self.extract_sig_from_projection(cause_span, projection) } hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) if self.tcx.async_fn_trait_kind_from_def_id(trait_def_id).is_some() => { self.extract_sig_from_projection(cause_span, projection) } // It's possible we've passed the closure to a (somewhat out-of-fashion) // `F: FnOnce() -> Fut, Fut: Future` style bound. Let's still // guide inference here, since it's beneficial for the user. hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) if self.tcx.async_fn_trait_kind_from_def_id(trait_def_id).is_some() => {} _ => return None, if self.tcx.fn_trait_kind_from_def_id(trait_def_id).is_some() => { self.extract_sig_from_projection_and_future_bound(cause_span, projection) } _ => None, } } /// Given an `FnOnce::Output` or `AsyncFn::Output` projection, extract the args /// and return type to infer a [`ty::PolyFnSig`] for the closure. fn extract_sig_from_projection( &self, cause_span: Option, projection: ty::PolyProjectionPredicate<'tcx>, ) -> Option> { let projection = self.resolve_vars_if_possible(projection); let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1); let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty); debug!(?arg_param_ty); let ty::Tuple(input_tys) = *arg_param_ty.kind() else {"} {"_id":"q-en-rust-b66ce3448a2d89a8a4faa8a641ae3695e669190680434513382a10b12ea0263f","text":"match &mut fields { Fields::Vec(pats) => { for (i, pat) in new_pats { pats[i] = pat if let Some(p) = pats.get_mut(i) { *p = pat; } } } Fields::Filtered { fields, .. } => {"} {"_id":"q-en-rust-b6a36b1cbbaf11625a67ced26a6f621aa901bb5a0e78401f8c8c87bfe82605ae","text":"/// /// # Panics /// /// When the number is negative, zero, or if the base is not at least 2; it /// panics in debug mode and the return value is 0 in release /// mode. /// This function will panic if `self` is less than or equal to zero, /// or if `base` is less then 2. /// /// # Examples ///"} {"_id":"q-en-rust-b6fce8b14010d1ac2b789c639a3cf96b963d6e5b9e322de284588c7f73f7f5ab","text":"let lookup = &lookup.as_str(); let max_dist = dist.unwrap_or_else(|| cmp::max(lookup.len(), 3) / 3); let (case_insensitive_match, levenshtein_match) = name_vec // Priority of matches: // 1. Exact case insensitive match // 2. Levenshtein distance match // 3. Sorted word match if let Some(case_insensitive_match) = name_vec.iter().find(|candidate| candidate.as_str().to_uppercase() == lookup.to_uppercase()) { return Some(*case_insensitive_match); } let levenshtein_match = name_vec .iter() .filter_map(|&name| { let dist = lev_distance(lookup, &name.as_str()); if dist <= max_dist { Some((name, dist)) } else { None } }) // Here we are collecting the next structure: // (case_insensitive_match, (levenshtein_match, levenshtein_distance)) .fold((None, None), |result, (candidate, dist)| { ( if candidate.as_str().to_uppercase() == lookup.to_uppercase() { Some(candidate) } else { result.0 }, match result.1 { None => Some((candidate, dist)), Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) }), }, ) // (levenshtein_match, levenshtein_distance) .fold(None, |result, (candidate, dist)| match result { None => Some((candidate, dist)), Some((c, d)) => Some(if dist < d { (candidate, dist) } else { (c, d) }), }); // Priority of matches: // 1. Exact case insensitive match // 2. Levenshtein distance match // 3. Sorted word match if let Some(candidate) = case_insensitive_match { Some(candidate) } else if levenshtein_match.is_some() { if levenshtein_match.is_some() { levenshtein_match.map(|(candidate, _)| candidate) } else { find_match_by_sorted_words(name_vec, lookup)"} {"_id":"q-en-rust-b734b975bf355a2db233a26b4c4664ee17e27ef166b27409dbfc7a6cdeda113d","text":"= note: this expectation will create a diagnostic with the default lint level warning: this lint expectation is unfulfilled --> $DIR/expect_unfulfilled_expectation.rs:24:22 --> $DIR/expect_unfulfilled_expectation.rs:17:14 | LL | #[expect(unused_mut, reason = \"this expectation will create a diagnostic with the default lint level\")] | ^^^^^^^^^^ | = note: this expectation will create a diagnostic with the default lint level = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: this lint expectation is unfulfilled --> $DIR/expect_unfulfilled_expectation.rs:27:22 | LL | #[expect(unused, unfulfilled_lint_expectations, reason = \"the expectation for `unused` should be fulfilled\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the expectation for `unused` should be fulfilled = note: the `unfulfilled_lint_expectations` lint can't be expected and will always produce this message warning: this lint expectation is unfulfilled --> $DIR/expect_unfulfilled_expectation.rs:27:22 | LL | #[expect(unused, unfulfilled_lint_expectations, reason = \"the expectation for `unused` should be fulfilled\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the expectation for `unused` should be fulfilled = note: the `unfulfilled_lint_expectations` lint can't be expected and will always produce this message = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: 4 warnings emitted warning: 6 warnings emitted "} {"_id":"q-en-rust-b7662c6bc08650e717f64a63f2a805d2a528581f2aa9b51ab4ac0a400e068702","text":"severity: ChangeSeverity::Info, summary: \"The `build.profiler` option now tries to use source code from `download-ci-llvm` if possible, instead of checking out the `src/llvm-project` submodule.\", }, ChangeInfo { change_id: 129152, severity: ChangeSeverity::Info, summary: \"New option `build.cargo-clippy` added for supporting the use of custom/external clippy.\", }, ];"} {"_id":"q-en-rust-b8066812a2b29be804c901a93bda9dc8f9ab39927c33cc6b4231f62d7f86dea1","text":"// `Iterator::__iterator_get_unchecked`. unsafe { (self.a.__iterator_get_unchecked(idx), self.b.__iterator_get_unchecked(idx)) } } #[inline] fn fold(mut self, init: Acc, mut f: F) -> Acc where F: FnMut(Acc, Self::Item) -> Acc, { let mut accum = init; let len = ZipImpl::size_hint(&self).0; for i in 0..len { // SAFETY: since Self: TrustedRandomAccessNoCoerce we can trust the size-hint to // calculate the length and then use that to do unchecked iteration. // fold consumes the iterator so we don't need to fixup any state. unsafe { accum = f(accum, self.get_unchecked(i)); } } accum } } #[doc(hidden)]"} {"_id":"q-en-rust-b835fed51548cb75cde22607f3d8d683b804c766697ef9f18d14875c672c7023","text":"let fid = ccx.tcx.map.local_def_id(f.id); let dup_span = seen_fields.get(&f.name).cloned(); if let Some(prev_span) = dup_span { let mut err = struct_span_err!(ccx.tcx.sess, f.span, E0124, \"field `{}` is already declared\", f.name); span_note!(&mut err, prev_span, \"previously declared here\"); err.emit(); struct_span_err!(ccx.tcx.sess, f.span, E0124, \"field `{}` is already declared\", f.name) .span_label(f.span, &\"field already declared\") .span_label(prev_span, &format!(\"`{}` first declared here\", f.name)) .emit(); } else { seen_fields.insert(f.name, f.span); }"} {"_id":"q-en-rust-b86646c47b66942b67a638381159d9dc23f62a48039852798b18e9a9889c0428","text":" error[E0792]: expected generic lifetime parameter, found `'_` --> $DIR/issue-109054.rs:18:9 | LL | type ReturnType<'a> = impl std::future::Future + 'a; | -- this generic parameter must be used with a generic lifetime parameter ... LL | &inner | ^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0792`. "} {"_id":"q-en-rust-b8893fa8b6cf8f89813abe67cd299a5396d09c8a6e7af74e03eae4d7c4a865a5","text":" // check-pass // Regression test for #78507. fn foo() -> Option Option> { Some(|| Some(true)) } fn main() {} "} {"_id":"q-en-rust-b89109844cc838fee5e5e6bca5323dfdb43b887dc31f3ec9a844b2c19812e0a8","text":"--codeblock-error-color: rgba(255, 0, 0, .5); --codeblock-ignore-hover-color: rgb(255, 142, 0); --codeblock-ignore-color: rgba(255, 142, 0, .6); --warning-border-color: rgb(255, 142, 0); --type-link-color: #2dbfb8; --trait-link-color: #b78cf2; --assoc-item-link-color: #d2991d;"} {"_id":"q-en-rust-b897de19056698006a6d89056f5a037353cd39d173d9885e1a8b4c90477bffd2","text":"} } fn is_dir_writable_for_user(dir: &PathBuf) -> bool { let tmp_file = dir.join(\".tmp\"); match fs::File::create(&tmp_file) { Ok(_) => { fs::remove_file(tmp_file).unwrap(); true } Err(e) => { if e.kind() == std::io::ErrorKind::PermissionDenied { false } else { panic!(\"Failed the write access check for the current user. {}\", e); } } } } fn install_sh( builder: &Builder<'_>, package: &str,"} {"_id":"q-en-rust-b89a07102f94aa3d4af991b5a69478b7b581cbfd147de13de43e78ed9727f5a2","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":"q-en-rust-b8a354c85a55420d02d1eef44268ae5c72b5141df425d3a55f41148d9072ad39","text":" error: literal out of range for `u16` --> $DIR/issue-63364.rs:6:14 | LL | for n in 100_000.. { | ^^^^^^^ | = note: `#[deny(overflowing_literals)]` on by default error: aborting due to previous error "} {"_id":"q-en-rust-b8aa65178091608db1b49f5f228648a355c1f522bf122e22d0bc98a3ba22145b","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":"q-en-rust-b8ac91443d2babf2a1aecd0383233507f09f6a3f03782b1f5b98dfece287dc96","text":"specs.insert(*id, (level, src)); } } _ if !self.warn_about_weird_lints => {} CheckLintNameResult::Warning(ref msg) => { if self.warn_about_weird_lints { self.struct_lint(builtin::RENAMED_AND_REMOVED_LINTS, Some(li.span.into()), msg) .emit(); } let lint = builtin::RENAMED_AND_REMOVED_LINTS; let (level, src) = self.sets.get_lint_level(lint, self.cur, Some(&specs)); lint::struct_lint_level(self.sess, lint, level, src, Some(li.span.into()), msg) .emit(); } CheckLintNameResult::NoLint => { if self.warn_about_weird_lints { self.struct_lint(builtin::UNKNOWN_LINTS, Some(li.span.into()), &format!(\"unknown lint: `{}`\", name)) .emit(); } let lint = builtin::UNKNOWN_LINTS; let (level, src) = self.sets.get_lint_level(lint, self.cur, Some(&specs)); let msg = format!(\"unknown lint: `{}`\", name); lint::struct_lint_level(self.sess, lint, level, src, Some(li.span.into()), &msg) .emit(); } } }"} {"_id":"q-en-rust-b8b5ead8df2eef9ac560538cf1c3a8499060bee37a2201fd080469d2b30a545b","text":"ty::ty_struct(id, _) => { for field in fields { self.check_field(pattern.span, id, NamedField(field.node.ident)); NamedField(field.node.ident.name)); } } ty::ty_enum(_, _) => {"} {"_id":"q-en-rust-b8c0888211c00dd947f95170a292d4e1a6c3d13a4cf46510e5363421adf529d1","text":"margin: 0 auto; padding: 0 15px; font-size: 18px; color: #333; color: #000; line-height: 1.428571429; -webkit-box-sizing: unset; -moz-box-sizing: unset; box-sizing: unset; background: #fff; } @media (min-width: 768px) { body {"} {"_id":"q-en-rust-b8d314ace857dd925b8ab7975aca03b11183ddff6f462a4fe90627d21d10d635","text":" // Copyright 2012-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. // Make sure this compiles without getting a linker error because of missing // drop-glue because the collector missed adding drop-glue for the closure: fn create_fn() -> Box { let text = String::new(); Box::new(move || { let _ = &text; }) } fn main() { let _ = create_fn(); } "} {"_id":"q-en-rust-b92f54a56873fca84cad674c118574a29dda0dc9c93d62c094b3e371c0ae6fc4","text":"true } }) // ensure that we don't suggest unstable methods .filter(|candidate| { // note that `DUMMY_SP` is ok here because it is only used for // suggestions and macro stuff which isn't applicable here. !matches!( self.tcx.eval_stability(candidate.item.def_id, None, DUMMY_SP, None), stability::EvalResult::Deny { .. } ) }) .map(|candidate| candidate.item.ident(self.tcx)) .filter(|&name| set.insert(name)) .collect();"} {"_id":"q-en-rust-b935180a602639bfdca27b0d33f56275b732cc2242419a61cd9fbfd1e833a914","text":"} as usize; if k == n && c::GetLastError() == c::ERROR_INSUFFICIENT_BUFFER { n *= 2; } else if k >= n { } else if k > n { n = k; } else if k == n { // It is impossible to reach this point. // On success, k is the returned string length excluding the null. // On failure, k is the required buffer length including the null. // Therefore k never equals n. unreachable!(); } else { return Ok(f2(&buf[..k])); }"} {"_id":"q-en-rust-b947ab86e94b524a0765b0f88a14d15c52ed8dc3df016bb8f6960c58e217719d","text":"/// The root of the normal must_use lint with an optional message. Def(Span, DefId, Option), Boxed(Box), Pinned(Box), Opaque(Box), TraitObject(Box), TupleElement(Vec<(usize, Self)>),"} {"_id":"q-en-rust-b99c05cdf786dfafafbf292a5a3bd40411e0b9bc6f09441efd0eda86b23dc821","text":" // Test for // check-pass #![feature(const_if_match)] enum E { A, B, C } const fn f(e: E) { match e { E::A => {} E::B => {} E::C => {} } } fn main() {} "} {"_id":"q-en-rust-b9a198019267f2c210875a18466562c9b833c34c817790fc4ac0b652e847426f","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":"q-en-rust-b9b00255033645734549d958f94cf4764197b6e61fcef6665063802c48652c14","text":"sidebarElems.appendChild(ul); } function expandAllDocs() { const innerToggle = document.getElementById(toggleAllDocsId); removeClass(innerToggle, \"will-expand\"); onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"), e => { if (!hasClass(e, \"type-contents-toggle\")) { e.open = true; } }); innerToggle.title = \"collapse all docs\"; innerToggle.children[0].innerText = \"u2212\"; // \"u2212\" is \"−\" minus sign } function labelForToggleButton(sectionIsCollapsed) { if (sectionIsCollapsed) { // button will expand the section return \"+\"; } // button will collapse the section // note that this text is also set in the HTML template in ../render/mod.rs return \"u2212\"; // \"u2212\" is \"−\" minus sign function collapseAllDocs() { const innerToggle = document.getElementById(toggleAllDocsId); addClass(innerToggle, \"will-expand\"); onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"), e => { if (e.parentNode.id !== \"implementations-list\" || (!hasClass(e, \"implementors-toggle\") && !hasClass(e, \"type-contents-toggle\")) ) { e.open = false; } }); innerToggle.title = \"expand all docs\"; innerToggle.children[0].innerText = \"+\"; } function toggleAllDocs() {"} {"_id":"q-en-rust-b9d416c132b27bef98ca696c9bc400aba1846c0767e2bc26588ea0715d0c476a","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":"q-en-rust-b9d48c09677dc962c2400c45b40a5b827370c8c569672eca1126bec579328114","text":"// check that a comma comes after every field if !ate_comma { let mut err = self.dcx().create_err(ExpectedCommaAfterPatternField { span: self.token.span }); let err = if self.token == token::At { let prev_field = fields .last() .expect(\"Unreachable on first iteration, not empty otherwise\") .ident; self.report_misplaced_at_in_struct_pat(prev_field) } else { let mut err = self .dcx() .create_err(ExpectedCommaAfterPatternField { span: self.token.span }); self.recover_misplaced_pattern_modifiers(&fields, &mut err); err }; if let Some(delayed) = delayed_err { delayed.emit(); } self.recover_misplaced_pattern_modifiers(&fields, &mut err); return Err(err); } ate_comma = false;"} {"_id":"q-en-rust-b9d584ab9543574206577cab49f79478541fb7842408308ec2189cb9a0c7cc62","text":" // compile-flags: --edition 2018 #![feature(label_break_value, try_blocks)] // run-pass fn main() { let _: Result<(), ()> = try { 'foo: { Err(())?; break 'foo; } }; } "} {"_id":"q-en-rust-b9dc369945ad74dbf654e5581e3b0375c09b1c0c780fdf7d7ba3d15be8fea6c1","text":" A type parameter that is specified for `impl` is not constrained. A type, const or lifetime parameter that is specified for `impl` is not constrained. Erroneous code example:"} {"_id":"q-en-rust-ba02698506de592b6e2603177f027518559dbbf7b456195270dd59f80ca081c7","text":"impl<'a, T> Fn<(&'a T,)> for Foo { extern \"rust-call\" fn call(&self, (_,): (T,)) {} //~^ ERROR: has an incompatible type for trait: expected &-ptr //~^ ERROR: has an incompatible type for trait //~| expected &-ptr } impl<'a, T> FnMut<(&'a T,)> for Foo { extern \"rust-call\" fn call_mut(&mut self, (_,): (T,)) {} //~^ ERROR: has an incompatible type for trait: expected &-ptr //~^ ERROR: has an incompatible type for trait //~| expected &-ptr } impl<'a, T> FnOnce<(&'a T,)> for Foo { type Output = (); extern \"rust-call\" fn call_once(self, (_,): (T,)) {} //~^ ERROR: has an incompatible type for trait: expected &-ptr //~^ ERROR: has an incompatible type for trait //~| expected &-ptr } fn main() {}"} {"_id":"q-en-rust-ba03e96ecca3be77892d1deac27068b179b956c32bcf7434b417f2830dbc2842","text":"if let Some(trait_def_id) = trait_def_id { let found_kind = match closure_kind { hir::ClosureKind::Closure => self.tcx.fn_trait_kind_from_def_id(trait_def_id), hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => { self.tcx.async_fn_trait_kind_from_def_id(trait_def_id) } hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => self .tcx .async_fn_trait_kind_from_def_id(trait_def_id) .or_else(|| self.tcx.fn_trait_kind_from_def_id(trait_def_id)), _ => None, };"} {"_id":"q-en-rust-ba3fd74697ec461b1b165df6ed3e2972d15d35e42e039ebcb8399214636b1c32","text":"buf.len() as DWORD, ptr::null()); if res == 0 { fail!(\"[{}] FormatMessage failure\", errno()); // Sometimes FormatMessageW can fail e.g. system doesn't like langId, let fm_err = errno(); return format!(\"OS Error {} (FormatMessageW() returned error {})\", err, fm_err); } str::from_utf16(str::truncate_utf16_at_nul(buf)) .expect(\"FormatMessageW returned invalid UTF-16\") let msg = str::from_utf16(str::truncate_utf16_at_nul(buf)); match msg { Some(msg) => format!(\"OS Error {}: {}\", err, msg), None => format!(\"OS Error {} (FormatMessageW() returned invalid UTF-16)\", err), } } }"} {"_id":"q-en-rust-ba72eb695c87e9ed247d256157355498fbd51c7f21f14f7edbc09b0a17c7dc28","text":"crate fn unexpected(&mut self) -> PResult<'a, T> { match self.expect_one_of(&[], &[]) { Err(e) => Err(e), Ok(_) => unreachable!(), // We can get `Ok(true)` from `recover_closing_delimiter` // which is called in `expected_one_of_not_found`. Ok(_) => FatalError.raise(), } }"} {"_id":"q-en-rust-ba73f1c6cde8b8d73ef34d4941f73826bff52342a2c91b54fb0fa1ad04b099c7","text":" error: functions cannot be both `const` and `gen` --> $DIR/const_gen_fn.rs:6:1 | LL | const gen fn a() {} | ^^^^^-^^^---------- | | | | | `gen` because of this | `const` because of this error: functions cannot be both `const` and `async gen` --> $DIR/const_gen_fn.rs:9:1 | LL | const async gen fn b() {} | ^^^^^-^^^^^^^^^---------- | | | | | `async gen` because of this | `const` because of this error: aborting due to 2 previous errors "} {"_id":"q-en-rust-ba80d5651c5f0bad06b3ef1919624fbf99794661f247901fa98b3e871c150567","text":"ty::note_and_explain_type_err(tcx, terr); } } // Finally, resolve all regions. This catches wily misuses of lifetime // parameters. infcx.resolve_regions_and_report_errors(); } fn check_cast(fcx: &FnCtxt,"} {"_id":"q-en-rust-baa3974c1aafa6eed2bf52d0fffbcc14b6bdf3d4e33fe53ef344d4b0954956d3","text":"/// # Example /// /// ```rust /// # #![allow(deprecated)] /// use url::get_scheme; /// /// let scheme = match get_scheme(\"https://example.com/\") {"} {"_id":"q-en-rust-baf02ef8ba73b038f865f4c9b85457654fdd48ca272ad2302de2bd5784581f5a","text":"} fn struct_all_fields_are_public(tcx: TyCtxt<'_>, id: LocalDefId) -> bool { // treat PhantomData and positional ZST as public, // we don't want to lint types which only have them, // cause it's a common way to use such types to check things like well-formedness tcx.adt_def(id).all_fields().all(|field| { let adt_def = tcx.adt_def(id); // skip types contain fields of unit and never type, // it's usually intentional to make the type not constructible let not_require_constructor = adt_def.all_fields().any(|field| { let field_type = tcx.type_of(field.did).instantiate_identity(); if field_type.is_phantom_data() { return true; } let is_positional = field.name.as_str().starts_with(|c: char| c.is_ascii_digit()); if is_positional && tcx .layout_of(tcx.param_env(field.did).and(field_type)) .map_or(true, |layout| layout.is_zst()) { return true; } field.vis.is_public() }) field_type.is_unit() || field_type.is_never() }); not_require_constructor || adt_def.all_fields().all(|field| { let field_type = tcx.type_of(field.did).instantiate_identity(); // skip fields of PhantomData, // cause it's a common way to check things like well-formedness if field_type.is_phantom_data() { return true; } field.vis.is_public() }) } /// check struct and its fields are public or not,"} {"_id":"q-en-rust-bb20c2f7f96ae7ab366133765a659a9f3006cab72a984a28250c2cb811445e07","text":" error: expected one of `,` or `:`, found `(` --> $DIR/issue-66357-unexpected-unreachable.rs:12:13 | LL | fn f() { |[](* } | ^ expected one of `,` or `:` error: expected one of `)`, `-`, `_`, `box`, `mut`, `ref`, `|`, identifier, or path, found `*` --> $DIR/issue-66357-unexpected-unreachable.rs:12:14 | LL | fn f() { |[](* } | -^ help: `)` may belong here | | | unclosed delimiter error: aborting due to 2 previous errors "} {"_id":"q-en-rust-bb263248d8d44e217808fde8cf6e115f5d2c6ab6d12a74a5000a5c5e9c47736f","text":"} /* For the last child of a div, the margin will be taken care of by the margin-top of the next item. */ p:last-child { p:last-child, .docblock > .warning:last-child { margin: 0; }"} {"_id":"q-en-rust-bb51d2d27094d6e819b787a119373f19343f1b24f4323cdd6800fc620efc492b","text":"find_best_match_for_name(input.iter(), \"aaaa\", Some(4)), Some(Symbol::intern(\"AAAA\")) ); let input = vec![Symbol::intern(\"a_longer_variable_name\")]; assert_eq!( find_best_match_for_name(input.iter(), \"a_variable_longer_name\", None), Some(Symbol::intern(\"a_longer_variable_name\")) ); }) }"} {"_id":"q-en-rust-bb5ef033ada50aeccf7774d67386a1e0b34bf218c83949be2c2964f01dc9c1b1","text":"name_key(lhs).cmp(&name_key(rhs)) } indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2)); if cx.shared.sort_modules_alphabetically { indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2)); } // This call is to remove reexport duplicates in cases such as: // // ```"} {"_id":"q-en-rust-bb74c66fe2add80013a7bc59e979925c60d702bf486baef6043fe60d7cfff0eb","text":" Subproject commit 2adc17a5442614dbe34626fdd9b32de7c07b8086 Subproject commit 1d5d0e8b0e3134dc781adb98057e38ffdf200df2 "} {"_id":"q-en-rust-bc28764db8dc8d4abe3ae1fdcbed43fe538bbe48aa9783bc3fb42849457cc2b1","text":"None => continue, }; // Filter away \"empty import canaries\" and ambiguous imports. // Filter away ambiguous and gensymed imports. Gensymed imports // (e.g. implicitly injected `std`) cannot be properly encoded in metadata, // so they can cause name conflict errors downstream. let is_good_import = binding.is_import() && !binding.is_ambiguity() && binding.vis != ty::Visibility::Invisible; !(ident.name.is_gensymed() && ident.name != \"_\"); if is_good_import || binding.is_macro_def() { let def = binding.def(); if def != Def::Err {"} {"_id":"q-en-rust-bc5473c4757ba7f229beb777cee3f6cf12f47c68ca6b1783b4445ad855115606","text":"})), }; f(RefMutL(put_back_on_drop.value.as_mut().unwrap())) f(put_back_on_drop.value.as_mut().unwrap()) } /// Sets the value in `self` to `value` while running `f`."} {"_id":"q-en-rust-bcebc9fb1b73bc19ebcdef25dfe597d5d7b7d234525f545c1c16be200c65e441","text":" // When build the suggesttion take in consideration the `:?` // https://github.com/rust-lang/rust/issues/100648 #![deny(warnings)] fn main () { println!(\"hello {:?}\", world = \"world\"); //~^ ERROR named argument `world` is not used by name //~| HELP use the named argument by name to avoid ambiguity //~| SUGGESTION world } "} {"_id":"q-en-rust-bcffdc5aaf4941b2a7cab36790779916581bf5cd5e724876aa2d1fe36aebe7b6","text":"/// Ok(()) /// } /// ``` #[unstable(feature = \"rw_exact_all_at\", issue = \"51984\")] #[stable(feature = \"rw_exact_all_at\", since = \"1.33.0\")] fn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> { while !buf.is_empty() { match self.read_at(buf, offset) {"} {"_id":"q-en-rust-bd0aac182fbc1f26b282486a92f37bd4d1c04d64062e52c9f83d884bf86b080c","text":"//! call `next()` on your iterator, until it reaches `None`. Let's go over that //! next. //! //! Also note that `Iterator` provides a default implementation of methods such as `nth` and `fold` //! which call `next` internally. However, it is also possible to write a custom implementation of //! methods like `nth` and `fold` if an iterator can compute them more efficiently without calling //! `next`. //! //! # for Loops and IntoIterator //! //! Rust's `for` loop syntax is actually sugar for iterators. Here's a basic"} {"_id":"q-en-rust-bd32a53d59f024abe1f2b85eb3140699ba733c0899369aa827d776c195279707","text":"let prefix = default_path(&builder.config.prefix, \"/usr/local\"); let sysconfdir = prefix.join(default_path(&builder.config.sysconfdir, \"/etc\")); // Sanity check for the user write access on prefix and sysconfdir assert!( is_dir_writable_for_user(&prefix), \"User doesn't have write access on `install.prefix` path in the `config.toml`.\", ); assert!( is_dir_writable_for_user(&sysconfdir), \"User doesn't have write access on `install.sysconfdir` path in `config.toml`.\" ); let datadir = prefix.join(default_path(&builder.config.datadir, \"share\")); let docdir = prefix.join(default_path(&builder.config.docdir, \"share/doc/rust\")); let mandir = prefix.join(default_path(&builder.config.mandir, \"share/man\"));"} {"_id":"q-en-rust-bd4054ae6a0bb6337d57ffe49a1e7774e7a1c2d7835b1ef6a2f01dabe1e52dcc","text":"#[unstable(feature = \"context_ext\", issue = \"123392\")] #[rustc_const_unstable(feature = \"const_waker\", issue = \"102012\")] pub const fn ext(&mut self) -> &mut dyn Any { match &mut self.ext { // FIXME: this field makes Context extra-weird about unwind safety // can we justify AssertUnwindSafe if we stabilize this? do we care? match &mut *self.ext { ExtData::Some(data) => *data, ExtData::None(unit) => unit, }"} {"_id":"q-en-rust-bd66ea05d2817cf50ef12f45fbf676262c471a449caab3878ab1ef1c357514d8","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":"q-en-rust-bd878f2676233aa1f2a24eb9f575b83ed12dd68b1f00dbaafb49a129c887684b","text":"config.out = absolute(&config.out).expect(\"can't make empty path absolute\"); } if cargo_clippy.is_some() && rustc.is_none() { println!( \"WARNING: Using `build.cargo-clippy` without `build.rustc` usually fails due to toolchain conflict.\" ); } config.initial_cargo_clippy = cargo_clippy; config.initial_rustc = if let Some(rustc) = rustc { if !flags.skip_stage0_validation { config.check_stage0_version(&rustc, \"rustc\");"} {"_id":"q-en-rust-bda087516ab0f76f2a6241e31ae186ecca9b0b4f46214141232e650e627eb261","text":"[platform-support]: https://forge.rust-lang.org/platform-support.html ## Installing on Linux or Mac ## Installing Rust If we're on Linux or a Mac, all we need to do is open a terminal and type this: All you need to do on Unix systems like Linux and macOS is open a terminal and type this: ```bash $ curl -sSf https://static.rust-lang.org/rustup.sh | sh $ curl https://sh.rustup.rs -sSf | sh ``` This will download a script, and start the installation. If it all goes well, you’ll see this appear: It will download a script, and start the installation. If everything goes well, you’ll see this appear: ```text Rust is ready to roll. Rust is installed now. Great! ``` From here, press `y` for ‘yes’, and then follow the rest of the prompts. Installing on Windows is nearly as easy: download and run [rustup-init.exe]. It will start the installation in a console and present the above message on success. ## Installing on Windows For other installation options and information, visit the [install] page of the Rust website. If you're on Windows, please download the appropriate [installer][install-page]. [install-page]: https://www.rust-lang.org/install.html [rustup-init.exe]: https://win.rustup.rs [install]: https://www.rust-lang.org/install.html ## Uninstalling Uninstalling Rust is as easy as installing it. On Linux or Mac, run the uninstall script: Uninstalling Rust is as easy as installing it: ```bash $ sudo /usr/local/lib/rustlib/uninstall.sh $ rustup self uninstall ``` If we used the Windows installer, we can re-run the `.msi` and it will give us an uninstall option. ## Troubleshooting If we've got Rust installed, we can open up a shell, and type this:"} {"_id":"q-en-rust-bdd59bb5463198ffbc6a918e45dd520f0e72934cb13c18ae475aec0c8992d732","text":"} } #[cfg(target_arch = \"x86_64\")] fn f128() { const_assert!((1f128).to_bits(), 0x3fff0000000000000000000000000000); const_assert!(u128::from_be_bytes(1f128.to_be_bytes()), 0x3fff0000000000000000000000000000); const_assert!((12.5f128).to_bits(), 0x40029000000000000000000000000000); const_assert!(u128::from_le_bytes(12.5f128.to_le_bytes()), 0x40029000000000000000000000000000); const_assert!((1337f128).to_bits(), 0x40094e40000000000000000000000000); const_assert!(u128::from_ne_bytes(1337f128.to_ne_bytes()), 0x40094e40000000000000000000000000); const_assert!((-14.25f128).to_bits(), 0xc002c800000000000000000000000000); const_assert!(f128::from_bits(0x3fff0000000000000000000000000000), 1.0); const_assert!(f128::from_be_bytes(0x3fff0000000000000000000000000000u128.to_be_bytes()), 1.0); const_assert!(f128::from_bits(0x40029000000000000000000000000000), 12.5); const_assert!(f128::from_le_bytes(0x40029000000000000000000000000000u128.to_le_bytes()), 12.5); const_assert!(f128::from_bits(0x40094e40000000000000000000000000), 1337.0); assert_eq!(f128::from_ne_bytes(0x40094e40000000000000000000000000u128.to_ne_bytes()), 1337.0); const_assert!(f128::from_bits(0xc002c800000000000000000000000000), -14.25); // Check that NaNs roundtrip their bits regardless of signalingness // 0xA is 0b1010; 0x5 is 0b0101 -- so these two together clobbers all the mantissa bits // NOTE: These names assume `f{BITS}::NAN` is a quiet NAN and IEEE754-2008's NaN rules apply! const QUIET_NAN: u128 = f128::NAN.to_bits() | 0x0000_AAAA_AAAA_AAAA_AAAA_AAAA_AAAA_AAAA; const SIGNALING_NAN: u128 = f128::NAN.to_bits() ^ 0x0000_5555_5555_5555_5555_5555_5555_5555; const_assert!(f128::from_bits(QUIET_NAN).is_nan()); const_assert!(f128::from_bits(SIGNALING_NAN).is_nan()); const_assert!(f128::from_bits(QUIET_NAN).to_bits(), QUIET_NAN); if !has_broken_floats() { const_assert!(f128::from_bits(SIGNALING_NAN).to_bits(), SIGNALING_NAN); } } fn main() { #[cfg(target_arch = \"x86_64\")] { f16(); f128(); } f32(); f64(); }"} {"_id":"q-en-rust-bdf948d1625515fc81c71d3316ef7a97dfcc775d7ad44283f0670bf7eef2c3ad","text":"return Some(*c); } let mut dist = dist.unwrap_or_else(|| cmp::max(lookup.len(), 3) / 3); // `fn edit_distance()` use `chars()` to calculate edit distance, so we must // also use `chars()` (and not `str::len()`) to calculate length here. let lookup_len = lookup.chars().count(); let mut dist = dist.unwrap_or_else(|| cmp::max(lookup_len, 3) / 3); let mut best = None; // store the candidates with the same distance, only for `use_substring_score` current. let mut next_candidates = vec![];"} {"_id":"q-en-rust-be050eb9f949cb2e7c4b2728f733b94dbede903e59be6474cda1cc78b8a63e26","text":"fn f(a: u16, b: &str) {} fn main() { f(0); //~ ERROR E0061 f(0); //~^ ERROR E0061 //~| NOTE expected 2 parameters //~| NOTE the following parameter types were expected }"} {"_id":"q-en-rust-be15c1b9144a047f4658c626b1c50d398ccb960aefd6b356fad726d3caa1ee03","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":"q-en-rust-be2e0f353d57a6fcb3fda60a8025c17ee6cdf3324289a57df5e90210b4f77340","text":" // Checks that naked functions are never inlined. // compile-flags: -O -Zmir-opt-level=2 // ignore-wasm32 #![crate_type = \"lib\"] #![feature(asm)] #![feature(naked_functions)] #[inline(always)] #[naked] #[no_mangle] pub unsafe extern \"C\" fn f() { // Check that f has naked and noinline attributes. // // CHECK: define void @f() unnamed_addr [[ATTR:#[0-9]+]] // CHECK-NEXT: start: // CHECK-NEXT: call void asm asm!(\"\", options(noreturn)); } #[no_mangle] pub unsafe fn g() { // Check that call to f is not inlined. // // CHECK-LABEL: define void @g() // CHECK-NEXT: start: // CHECK-NEXT: call void @f() f(); } // CHECK: attributes [[ATTR]] = { naked noinline{{.*}} } "} {"_id":"q-en-rust-be3076d11d9fb71044a605d7bfff2ebfdf2e07cf5dfee7afe3ba1da48307ddcc","text":"// through and constrain Pi. let mut subcomponents = smallvec![]; let mut subvisited = SsoHashSet::new(); compute_components_recursive(tcx, ty.into(), &mut subcomponents, &mut subvisited); compute_alias_components_recursive(tcx, ty, &mut subcomponents, &mut subvisited); out.push(Component::EscapingAlias(subcomponents.into_iter().collect())); } }"} {"_id":"q-en-rust-be3acaadd1e488f29624964bfd93cca9186de33c1c315ff100b632a48036f25d","text":"pub fn report_error_if_loans_conflict(&self, old_loan: &Loan<'tcx>, new_loan: &Loan<'tcx>) { new_loan: &Loan<'tcx>) -> bool { //! Checks whether `old_loan` and `new_loan` can safely be issued //! simultaneously."} {"_id":"q-en-rust-be3e401423d96252e0f956c505a9d87d2b726cfd02928e8220eff36f5e3358a3","text":"fn method(&self) -> impl Trait; } trait Trait2 { type Type; fn method(&self) -> impl Trait2 + '_>; } fn main() {}"} {"_id":"q-en-rust-be44dbfcaf107d02475aa73de9fe89c16336c59e21ad3d7af526004189ef6c96","text":" // Traits in scope are collected for doc links in field attributes. // check-pass // aux-build: assoc-field-dep.rs extern crate assoc_field_dep; pub use assoc_field_dep::*; #[derive(Clone)] pub struct Struct; pub mod mod1 { pub struct Fields { /// [crate::Struct::clone] pub field: u8, } } pub mod mod2 { pub enum Fields { V { /// [crate::Struct::clone] field: u8, }, } } "} {"_id":"q-en-rust-be7d2e9ab80eea5420a3e22080b1f7de02552d07028f1633b82765fc7b0c3417","text":"} } /// A call to a `panic()` lang item where the first argument is _not_ a `&str`. #[derive(Debug)] pub struct PanicNonStr; impl NonConstOp for PanicNonStr { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { ccx.tcx.sess.struct_span_err( span, \"argument to `panic!()` in a const context must have type `&str`\", ) } } #[derive(Debug)] pub struct RawPtrComparison; impl NonConstOp for RawPtrComparison {"} {"_id":"q-en-rust-be93da8faa54c8a373918ad4eacfe76f12c017d5cf11dc2e4c106006fc2e72e6","text":"/// /// In other words, it zips two iterators together, into a single one. /// /// When either iterator returns [`None`], all further calls to [`next`] /// will return [`None`]. /// If either iterator returns [`None`], [`next`] will return [`None`]. /// /// # Examples ///"} {"_id":"q-en-rust-bedbb3c212c440f528f318e68fd64ac16d9a7fad10797b8f1c8152ebf67a6fff","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":"q-en-rust-bef9f0e8ca09af140a95e1c1c9d30c61243a6bdc8f469b304bbd5e72cbbd1944","text":"ObligationCauseCode::VariableType(hir_id) => { let parent_node = self.tcx.hir().get_parent_node(hir_id); match self.tcx.hir().find(parent_node) { Some(Node::Local(hir::Local { ty: Some(ty), .. })) => { err.span_suggestion_verbose( ty.span.shrink_to_lo(), \"consider borrowing here\", \"&\", Applicability::MachineApplicable, ); err.note(\"all local variables must have a statically known size\"); } Some(Node::Local(hir::Local { init: Some(hir::Expr { kind: hir::ExprKind::Index(_, _), span, .. }), .."} {"_id":"q-en-rust-befcf4ac885f1d734830dc2b3a94cbb9ef12d9cfefbdb2a81658b13c58e3eb80","text":" error[E0425]: cannot find value `读文` in this scope --> $DIR/non_ascii_ident.rs:3:13 | LL | let _ = 读文; | ^^^^ not found in this scope error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-bf4da314a5fc644d1effe1185ac8124997320f02c5e608badd7018d25762b3f5","text":"plugin_registrar, plugins, pointer, pointer_trait, pointer_trait_fmt, poll, position, post_dash_lto: \"post-lto\","} {"_id":"q-en-rust-bf8019dd229b992d96ae87a191306abe7e69413e4e6025628ff9215e356b5d18","text":" // compile-flags: --error-format pretty-json -Zunstable-options // build-pass (FIXME(62277): could be check-pass?) // compile-flags: --error-format json -Zunstable-options // run-rustfix // The output for humans should just highlight the whole span without showing"} {"_id":"q-en-rust-bf9a0b46fe3b6ecedcedeb84e8e894891ceaf97b4e6cfe03829c794c9a991d8a","text":"|| abi == SpecAbi::RustIntrinsic || abi == SpecAbi::PlatformIntrinsic { let fixup = |arg: &mut ArgAbi<'tcx, Ty<'tcx>>| { let fixup = |arg: &mut ArgAbi<'tcx, Ty<'tcx>>, is_ret: bool| { if arg.is_ignore() { return; }"} {"_id":"q-en-rust-bfb214c2871b33d5ddc9610dcb4451eeea1a3a0443ae3daa416429cd15747ee5","text":" error[E0080]: it is undefined behavior to use this value --> $DIR/issue-51559.rs:4:1 | LL | pub const FOO: usize = unsafe { BAR as usize }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered a pointer, but expected initialized plain (non-pointer) bytes | = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rust compiler repository if you believe it should not be considered undefined behavior error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. "} {"_id":"q-en-rust-bfc1eabfac7834a3e820eced388b8602562a46673f8aee8c6701f0f9a76589c5","text":"ast_passes_bound_in_context = bounds on `type`s in {$ctx} have no effect ast_passes_const_and_async = functions cannot be both `const` and `async` .const = `const` because of this .async = `async` because of this .label = {\"\"} ast_passes_const_and_c_variadic = functions cannot be both `const` and C-variadic .const = `const` because of this .variadic = C-variadic because of this ast_passes_const_and_coroutine = functions cannot be both `const` and `{$coroutine_kind}` .const = `const` because of this .coroutine = `{$coroutine_kind}` because of this .label = {\"\"} ast_passes_const_bound_trait_object = const trait bounds are not allowed in trait object types ast_passes_const_without_body ="} {"_id":"q-en-rust-bfc7c214f561927c82f2346b6844ea64aba7dc0643418ef769b7b241e862d07a","text":" error[E0425]: cannot find function `foo` in module `to_reuse` --> $DIR/ice-issue-124342.rs:7:21 | LL | reuse to_reuse::foo { foo } | ^^^ not found in `to_reuse` error[E0425]: cannot find value `foo` in this scope --> $DIR/ice-issue-124342.rs:7:27 | LL | reuse to_reuse::foo { foo } | ^^^ | help: you might have meant to refer to the associated function | LL | reuse to_reuse::foo { Self::foo } | ++++++ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-c0365acf3855ee5ed029b6e68c3ce6a6f4d78150230bf2e3cc20840d27313b87","text":"} let tcx = self.tcx(); let mut pred = cache_fresh_trait_pred.skip_binder(); param_env = param_env.with_constness(pred.constness.and(param_env.constness())); pred.remap_constness(tcx, &mut param_env); if self.can_use_global_caches(param_env) { if let Some(res) = tcx.selection_cache.get(¶m_env.and(pred), tcx) {"} {"_id":"q-en-rust-c06310be93043158632822254ac7def4489cba1042635e23fa1686770fd84153","text":"} } pub fn is_async(self) -> bool { matches!(self, CoroutineKind::Async { .. }) } pub fn is_gen(self) -> bool { matches!(self, CoroutineKind::Gen { .. }) pub fn as_str(self) -> &'static str { match self { CoroutineKind::Async { .. } => \"async\", CoroutineKind::Gen { .. } => \"gen\", CoroutineKind::AsyncGen { .. } => \"async gen\", } } pub fn closure_id(self) -> NodeId {"} {"_id":"q-en-rust-c069064680600f7762d205852c2a1cb434833a23fd268a2307cd56fa9905a501","text":"use rustc_middle::ty; // Please change the public `use` directives cautiously, as they might be used by external tools. // See issue #120130. pub use self::drop_flag_effects::{ drop_flag_effects_for_function_entry, drop_flag_effects_for_location, move_path_children_matching, on_all_children_bits, on_lookup_result_bits, }; pub use self::framework::{ fmt, lattice, visit_results, Analysis, AnalysisDomain, Direction, GenKill, GenKillAnalysis, JoinSemiLattice, MaybeReachable, Results, ResultsCursor, ResultsVisitable, ResultsVisitor, fmt, graphviz, lattice, visit_results, Analysis, AnalysisDomain, Backward, Direction, Engine, Forward, GenKill, GenKillAnalysis, JoinSemiLattice, MaybeReachable, Results, ResultsCursor, ResultsVisitable, ResultsVisitor, SwitchIntEdgeEffects, }; use self::framework::{Backward, SwitchIntEdgeEffects}; use self::move_paths::MoveData; pub mod debuginfo;"} {"_id":"q-en-rust-c0757cf611abdaa7a9faa93b38fb0bf42cf353e32dfee4364d810e259dae31b7","text":"let _ = &packed2.y; // ok, has align 2 in packed(2) struct let _ = &packed2.z; // ok, has align 1 } unsafe { struct U16(u16); impl Drop for U16 { fn drop(&mut self) { println!(\"{:p}\", self); } } struct HasDrop; impl Drop for HasDrop { fn drop(&mut self) {} } #[allow(unused)] struct Wrapper { a: U16, b: HasDrop, } #[allow(unused)] #[repr(packed(2))] struct Wrapper2 { a: U16, b: HasDrop, } // An outer struct with more restrictive packing than the inner struct -- make sure we // notice that! #[repr(packed)] struct Misalign(u8, T); let m1 = Misalign( 0, Wrapper { a: U16(10), b: HasDrop, }, ); let _ref = &m1.1.a; //~ ERROR reference to packed field //~^ previously accepted let m2 = Misalign( 0, Wrapper2 { a: U16(10), b: HasDrop, }, ); let _ref = &m2.1.a; //~ ERROR reference to packed field //~^ previously accepted } }"} {"_id":"q-en-rust-c0802fee18e4ec5c97eb2f7bcc48c43493ff19254bf47d53167e5159600adebc","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":"q-en-rust-c0ee825413641acc1fc0e93b40cfa2413a2ceb0107769024f868673ee5008d29","text":"use _Unwind_VRS_DataRepresentation::*; pub const UNWIND_POINTER_REG: c_int = 12; pub const UNWIND_SP_REG: c_int = 13; pub const UNWIND_IP_REG: c_int = 15; #[cfg_attr(all(feature = \"llvm-libunwind\","} {"_id":"q-en-rust-c0f33295db8c6df8babf9eb8cac03ef82fcd4ea2792c519d2e341b8c06887810","text":"TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, }; use rustc_session::config::TraitSolver; use rustc_span::def_id::{DefId, CRATE_DEF_ID}; use rustc_span::{ def_id::{DefId, CRATE_DEF_ID}, DUMMY_SP, }; use rustc_trait_selection::traits; fn sized_constraint_for_ty<'tcx>("} {"_id":"q-en-rust-c10ee1af38b8a8b06673fef8430c08039cfc3f101aa78ecedff7df0c3a36a576","text":" - // MIR for `bitwise_not` before JumpThreading + // MIR for `bitwise_not` after JumpThreading fn bitwise_not() -> i32 { let mut _0: i32; let mut _1: i32; let mut _2: bool; let mut _3: i32; let mut _4: i32; scope 1 { debug a => _1; } bb0: { StorageLive(_1); _1 = const 0_i32; _1 = const 1_i32; StorageLive(_2); StorageLive(_3); StorageLive(_4); _4 = copy _1; _3 = Not(move _4); StorageDead(_4); _2 = Eq(move _3, const 0_i32); switchInt(move _2) -> [0: bb2, otherwise: bb1]; } bb1: { StorageDead(_3); _0 = const 1_i32; goto -> bb3; } bb2: { StorageDead(_3); _0 = const 0_i32; goto -> bb3; } bb3: { StorageDead(_2); StorageDead(_1); return; } } "} {"_id":"q-en-rust-c17743cff1a9515c789b79899c94500756f10dbe3d6d586b59133c35427d8041","text":"} else { let args: Vec<_> = args .into_iter() .map(|arg| unpack!(block = this.as_local_operand(block, arg))) .map(|arg| unpack!(block = this.as_local_call_operand(block, arg))) .collect(); let success = this.cfg.start_new_block();"} {"_id":"q-en-rust-c181a9f5fb579f27ba1c1a12e8bacdf5eab50d3b3b0a9e5d16d42c175c755b65","text":"check_dispatch $1 beta nomicon src/doc/nomicon check_dispatch $1 beta reference src/doc/reference check_dispatch $1 beta rust-by-example src/doc/rust-by-example # Temporarily disabled until # https://github.com/rust-lang/rust/issues/60459 is fixed. # check_dispatch $1 beta edition-guide src/doc/edition-guide check_dispatch $1 beta edition-guide src/doc/edition-guide check_dispatch $1 beta rls src/tools/rls check_dispatch $1 beta rustfmt src/tools/rustfmt check_dispatch $1 beta clippy-driver src/tools/clippy"} {"_id":"q-en-rust-c18cc9c1a2a751a99331dd41c696791c144b78d5f6c1a2c01b874fd2b5cf19a2","text":"} #[derive(Subdiagnostic)] #[multipart_suggestion(passes_change_fields_to_be_of_unit_type, applicability = \"has-placeholders\")] pub struct ChangeFieldsToBeOfUnitType { pub num: usize, #[suggestion_part(code = \"()\")] pub spans: Vec, pub enum ChangeFields { #[multipart_suggestion( passes_change_fields_to_be_of_unit_type, applicability = \"has-placeholders\" )] ChangeToUnitTypeOrRemove { num: usize, #[suggestion_part(code = \"()\")] spans: Vec, }, #[help(passes_remove_fields)] Remove { num: usize }, } #[derive(Diagnostic)]"} {"_id":"q-en-rust-c1af91d5841b536f4d336661b67e871b43abc59a8556fdf9c2245958694d34f8","text":"LL | #[expect(invalid_nan_comparisons)] | ^^^^^^^^^^^^^^^^^^^^^^^ warning: 2 warnings emitted warning: this lint expectation is unfulfilled --> $DIR/expect_tool_lint_rfc_2383.rs:38:18 | LL | #[expect(invalid_nan_comparisons)] | ^^^^^^^^^^^^^^^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: 3 warnings emitted "} {"_id":"q-en-rust-c1f7ed062a0fa2c03a2fa2a890f6eedf4e86f4f4e4276b481992bdc0daad4c75","text":"let projections_b = &place_b.projections; let same_initial_projections = iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a == proj_b); iter::zip(projections_a, projections_b).all(|(proj_a, proj_b)| proj_a.kind == proj_b.kind); if same_initial_projections { use std::cmp::Ordering; // First min(n, m) projections are the same // Select Ancestor/Descendant if projections_b.len() >= projections_a.len() { PlaceAncestryRelation::Ancestor } else { PlaceAncestryRelation::Descendant match projections_b.len().cmp(&projections_a.len()) { Ordering::Greater => PlaceAncestryRelation::Ancestor, Ordering::Equal => PlaceAncestryRelation::SamePlace, Ordering::Less => PlaceAncestryRelation::Descendant, } } else { PlaceAncestryRelation::Divergent"} {"_id":"q-en-rust-c219e77cf6e61b0be4693886beca5b7a95b464794f8ba948a5d64b0a9b9467a6","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":"q-en-rust-c22ca7d3367dd3aa0402327451ba9ece41a098f41cafcc8cf7299909c0168633","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":"q-en-rust-c24c54a4eb0a0a9f6dce744b56a3fbb9caf2ec33b6e05c1f541666a8ad57248c","text":"#[cfg(test)] mod bench { use test::Bencher; use super::VecMap; use bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n}; #[bench] pub fn insert_rand_100(b: &mut Bencher) { let mut m = VecMap::new(); insert_rand_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); } #[bench] pub fn insert_rand_10_000(b: &mut Bencher) { let mut m = VecMap::new(); insert_rand_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); } // Insert seq #[bench] pub fn insert_seq_100(b: &mut Bencher) { let mut m = VecMap::new(); insert_seq_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); } #[bench] pub fn insert_seq_10_000(b: &mut Bencher) { let mut m = VecMap::new(); insert_seq_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.remove(&i); }); } map_insert_rand_bench!{insert_rand_100, 100, VecMap} map_insert_rand_bench!{insert_rand_10_000, 10_000, VecMap} // Find rand #[bench] pub fn find_rand_100(b: &mut Bencher) { let mut m = VecMap::new(); find_rand_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.get(&i); }); } #[bench] pub fn find_rand_10_000(b: &mut Bencher) { let mut m = VecMap::new(); find_rand_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.get(&i); }); } map_insert_seq_bench!{insert_seq_100, 100, VecMap} map_insert_seq_bench!{insert_seq_10_000, 10_000, VecMap} // Find seq #[bench] pub fn find_seq_100(b: &mut Bencher) { let mut m = VecMap::new(); find_seq_n(100, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.get(&i); }); } map_find_rand_bench!{find_rand_100, 100, VecMap} map_find_rand_bench!{find_rand_10_000, 10_000, VecMap} #[bench] pub fn find_seq_10_000(b: &mut Bencher) { let mut m = VecMap::new(); find_seq_n(10_000, &mut m, b, |m, i| { m.insert(i, 1); }, |m, i| { m.get(&i); }); } map_find_seq_bench!{find_seq_100, 100, VecMap} map_find_seq_bench!{find_seq_10_000, 10_000, VecMap} }"} {"_id":"q-en-rust-c26e37aafb4f975e77014afaa1b142a8f84324800ad4d4e2a597c20620ce077f","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":"q-en-rust-c27e32e0607842ade51f8b71fa48dae3b3175b2a3604fb2398790ca65002e6aa","text":" error[E0716]: temporary value dropped while borrowed --> $DIR/promote-no-mut.rs:3:50 | LL | static mut TEST1: Option<&mut [i32]> = Some(&mut [1, 2, 3]); | ----------^^^^^^^^^- | | | | | | | temporary value is freed at the end of this statement | | creates a temporary which is freed while still in use | using this value as a static requires that borrow lasts for `'static` error[E0716]: temporary value dropped while borrowed --> $DIR/promote-no-mut.rs:6:18 | LL | let x = &mut [1,2,3]; | ^^^^^^^ creates a temporary which is freed while still in use LL | x | - using this value as a static requires that borrow lasts for `'static` LL | }; | - temporary value is freed at the end of this statement error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0716`. "} {"_id":"q-en-rust-c280e0dfd2b240d84bb4047bfbe088cd24424c54fcc3657a4994cf725810206e","text":"( &ty::Dynamic(ref data_a, _, src_dyn_kind), &ty::Dynamic(ref data_b, _, target_dyn_kind), ) => { assert_eq!(src_dyn_kind, target_dyn_kind); ) if src_dyn_kind == target_dyn_kind => { let old_info = old_info.expect(\"unsized_info: missing old info for trait upcasting coercion\"); if data_a.principal_def_id() == data_b.principal_def_id() {"} {"_id":"q-en-rust-c2d33549e58f9455666de31d2a81ac5e01511f092c615a4ca8fe3ca1693e4dbe","text":" // compile-pass // edition:2018 // aux-build:gensymed.rs extern crate gensymed; fn main() {} "} {"_id":"q-en-rust-c2e41ccb5d2d9a8f2c0193b82d47ae35369e2a6f6f60ecfad25d93aed7c2bd3c","text":"self.per_ns(|this, ns| { let key = BindingKey::new(target, ns); let _ = this.try_define(import.parent_scope.module, key, dummy_binding, false); this.update_resolution(import.parent_scope.module, key, false, |_, resolution| { resolution.single_imports.remove(&import); }) }); self.record_use(target, dummy_binding, false); } else if import.imported_module.get().is_none() {"} {"_id":"q-en-rust-c2fba8d7f42bf599f0dbf12d38d9b717da95bb9d10765e84a1d59ea8fb1bf435","text":" error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:2:5 | LL | x = x = x; | ^ | help: you might have meant to introduce a new binding | LL | let x = x = x; | +++ error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:2:9 | LL | x = x = x; | ^ not found in this scope error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:2:13 | LL | x = x = x; | ^ not found in this scope error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:7:5 | LL | x = y = y = y; | ^ | help: you might have meant to introduce a new binding | LL | let x = y = y = y; | +++ error[E0425]: cannot find value `y` in this scope --> $DIR/issue-104086-suggest-let.rs:7:9 | LL | x = y = y = y; | ^ not found in this scope error[E0425]: cannot find value `y` in this scope --> $DIR/issue-104086-suggest-let.rs:7:13 | LL | x = y = y = y; | ^ not found in this scope error[E0425]: cannot find value `y` in this scope --> $DIR/issue-104086-suggest-let.rs:7:17 | LL | x = y = y = y; | ^ not found in this scope error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:13:5 | LL | x = y = y; | ^ | help: you might have meant to introduce a new binding | LL | let x = y = y; | +++ error[E0425]: cannot find value `y` in this scope --> $DIR/issue-104086-suggest-let.rs:13:9 | LL | x = y = y; | ^ not found in this scope error[E0425]: cannot find value `y` in this scope --> $DIR/issue-104086-suggest-let.rs:13:13 | LL | x = y = y; | ^ not found in this scope error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:18:5 | LL | x = x = y; | ^ | help: you might have meant to introduce a new binding | LL | let x = x = y; | +++ error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:18:9 | LL | x = x = y; | ^ not found in this scope error[E0425]: cannot find value `y` in this scope --> $DIR/issue-104086-suggest-let.rs:18:13 | LL | x = x = y; | ^ not found in this scope error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:23:5 | LL | x = x; // will suggest add `let` | ^ | help: you might have meant to introduce a new binding | LL | let x = x; // will suggest add `let` | +++ error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:23:9 | LL | x = x; // will suggest add `let` | ^ not found in this scope error[E0425]: cannot find value `x` in this scope --> $DIR/issue-104086-suggest-let.rs:27:5 | LL | x = y // will suggest add `let` | ^ | help: you might have meant to introduce a new binding | LL | let x = y // will suggest add `let` | +++ error[E0425]: cannot find value `y` in this scope --> $DIR/issue-104086-suggest-let.rs:27:9 | LL | x = y // will suggest add `let` | ^ not found in this scope error: aborting due to 17 previous errors For more information about this error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-c2fd2ed2355d376534d26efc4ce33ae0f3eb7bad2089d5b1ff809771aa2d8c1d","text":" error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:14:1 | LL | extern crate alloc; | ^^^^^^^^^^^^^^^^^^^ help: remove it | note: lint level defined here --> $DIR/unnecessary-extern-crate.rs:11:9 | LL | #![deny(unnecessary_extern_crate)] | ^^^^^^^^^^^^^^^^^^^^^^^^ error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:17:1 | LL | extern crate alloc as x; | ^^^^^^^^^^^^^^^^^^^^^^^^ help: use `use`: `use alloc as x` error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:23:1 | LL | pub extern crate test as y; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `pub use`: `pub use test as y` error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:26:1 | LL | pub extern crate libc; | ^^^^^^^^^^^^^^^^^^^^^^ help: use `pub use`: `pub use libc` error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:32:5 | LL | extern crate alloc; | ^^^^^^^^^^^^^^^^^^^ help: use `use`: `use alloc` error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:35:5 | LL | extern crate alloc as x; | ^^^^^^^^^^^^^^^^^^^^^^^^ help: use `use`: `use alloc as x` error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:38:5 | LL | pub extern crate test; | ^^^^^^^^^^^^^^^^^^^^^^ help: use `pub use`: `pub use test` error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:41:5 | LL | pub extern crate test as y; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `pub use`: `pub use test as y` error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:45:9 | LL | extern crate alloc; | ^^^^^^^^^^^^^^^^^^^ help: use `use`: `use alloc` error: `extern crate` is unnecessary in the new edition --> $DIR/unnecessary-extern-crate.rs:48:9 | LL | extern crate alloc as x; | ^^^^^^^^^^^^^^^^^^^^^^^^ help: use `use`: `use alloc as x` error: aborting due to 10 previous errors "} {"_id":"q-en-rust-c302fb32f5fadaf73c3e5f79cae8625bf86486a9d82607233fc0362f104ee188","text":"#[stable(feature = \"move_cell\", since = \"1.17.0\")] pub fn swap(&self, other: &Self) { if ptr::eq(self, other) { // Swapping wouldn't change anything. return; } if !is_nonoverlapping(self, other, 1) { // See for why we need to stop here. panic!(\"`Cell::swap` on overlapping non-identical `Cell`s\"); } // SAFETY: This can be risky if called from separate threads, but `Cell` // is `!Sync` so this won't happen. This also won't invalidate any // pointers since `Cell` makes sure nothing else will be pointing into // either of these `Cell`s. // either of these `Cell`s. We also excluded shenanigans like partially overlapping `Cell`s, // so `swap` will just properly copy two full values of type `T` back and forth. unsafe { ptr::swap(self.value.get(), other.value.get()); mem::swap(&mut *self.value.get(), &mut *other.value.get()); } }"} {"_id":"q-en-rust-c329264a9cb198dcab1e100beda5bb91281eb5052255108da6e6be97ed9c0ae1","text":" // issue-54966: ICE returning an unknown type with impl FnMut fn generate_duration() -> Oper {} //~^ ERROR cannot find type `Oper` in this scope fn main() {} "} {"_id":"q-en-rust-c33ef2d3f19dc91a7d0f74be68aafcb1f586aa3ba9e16d8d7ba5b4095e0b8349","text":" error: `#[target_feature(..)]` can only be applied to `unsafe` functions --> $DIR/issue-68060.rs:8:13 | LL | #[target_feature(enable = \"\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can only be applied to `unsafe` functions ... LL | |_| (), | ------ not an `unsafe` function error: the feature named `` is not valid for this target --> $DIR/issue-68060.rs:8:30 | LL | #[target_feature(enable = \"\")] | ^^^^^^^^^^^ `` is not valid for this target error[E0737]: `#[track_caller]` requires Rust ABI --> $DIR/issue-68060.rs:11:13 | LL | #[track_caller] | ^^^^^^^^^^^^^^^ error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0737`. "} {"_id":"q-en-rust-c344f034772db9ee8713266570beb16d10295a74ba42d6fdfb52790067240204","text":"pub projection_bounds: Vec>, } impl<'tcx> ExistentialBounds<'tcx> { pub fn new(region_bound: ty::Region, builtin_bounds: BuiltinBounds, projection_bounds: Vec>) -> Self { let mut projection_bounds = projection_bounds; ty::sort_bounds_list(&mut projection_bounds); ExistentialBounds { region_bound: region_bound, builtin_bounds: builtin_bounds, projection_bounds: projection_bounds } } } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct BuiltinBounds(EnumSet);"} {"_id":"q-en-rust-c37d141f43358f7e17a80fba2f593e5681b108435484e92f6708f72b0b43acf7","text":"}); let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| { bound.map_bound(|b| { if b.projection_ty.self_ty() != dummy_self { tcx.sess.delay_span_bug( DUMMY_SP, &format!(\"trait_ref_to_existential called on {:?} with non-dummy Self\", b), ); bound.map_bound(|mut b| { assert_eq!(b.projection_ty.self_ty(), dummy_self); // Like for trait refs, verify that `dummy_self` did not leak inside default type // parameters. let references_self = b.projection_ty.substs.iter().skip(1).any(|arg| { if arg.walk().any(|arg| arg == dummy_self.into()) { return true; } false }); if references_self { tcx.sess .delay_span_bug(span, \"trait object projection bounds reference `Self`\"); let substs: Vec<_> = b .projection_ty .substs .iter() .map(|arg| { if arg.walk().any(|arg| arg == dummy_self.into()) { return tcx.ty_error().into(); } arg }) .collect(); b.projection_ty.substs = tcx.intern_substs(&substs[..]); } ty::ExistentialProjection::erase_self_ty(tcx, b) }) });"} {"_id":"q-en-rust-c3be50ecd0c84fbf4c432d93276e427a25298d0c5a775cc1597a85944cc82aa7","text":" // only-x86_64 // compile-flags: -Ccode-model=large --crate-type lib // build-pass // // Regression test for issue #37508 #![no_main] #![no_std] #![feature(thread_local, lang_items)] #[lang = \"eh_personality\"] extern \"C\" fn eh_personality() {} use core::panic::PanicInfo; #[panic_handler] fn panic(_panic: &PanicInfo<'_>) -> ! { loop {} } pub struct BB; #[thread_local] static mut KEY: Key = Key { inner: BB, dtor_running: false }; pub unsafe fn set() -> Option<&'static BB> { if KEY.dtor_running { return None; } Some(&KEY.inner) } pub struct Key { inner: BB, dtor_running: bool, } "} {"_id":"q-en-rust-c3ee31413b6576b1a5d350cb10c34cdf54769ab42733d4ca07f1928444a2c03d","text":" // check-pass #![feature(type_alias_impl_trait)] struct MyTy<'a>(Vec, &'a ()); impl MyTy<'_> { fn one(&mut self) -> &mut impl Sized { &mut self.0 } fn two(&mut self) -> &mut (impl Sized + 'static) { self.one() } } type Opaque<'a> = impl Sized; fn define<'a>() -> Opaque<'a> {} fn test<'a>() { None::<&'static Opaque<'a>>; } fn one<'a, 'b: 'b>() -> &'a impl Sized { &() } fn two<'a, 'b>() { one::<'a, 'b>(); } fn main() {} "} {"_id":"q-en-rust-c40793f3858eaa62a093c1a244027cc1ebe04a593d5b7f04427896827b48121d","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":"q-en-rust-c43ffe42d1c06f3d3d4f6884a1a07255beee38f710660002ab5a0234aadec966","text":"#![feature(core_intrinsics)] #![feature(lang_items)] #![feature(link_llvm_intrinsics)] #![feature(panic_info_message)] extern crate alloc;"} {"_id":"q-en-rust-c4617a55d57b43aa9e8f99a4728c7c297104448498042ae742c77c36a8599916","text":" //@ known-bug: #101962 #![feature(core_intrinsics)] pub fn wrapping(a: T, b: T) { let _z = core::intrinsics::wrapping_mul(a, b); } fn main() { wrapping(1,2); } "} {"_id":"q-en-rust-c46712efeba11c7b0150648a9d6191c70098553ca6861a674ee3298e0d009657","text":" Subproject commit 891e1a859b52486936e021235fdc36fbdd9b4100 Subproject commit b7c802b5e33f5a402de3780bc5a8b05e7ebad409 "} {"_id":"q-en-rust-c4860b91906d4160d0071df526cc7ce2fda72b26af58a65823be29086b8e2ffa","text":"Some(ns @ ValueNS) => { match self.resolve( path_str, disambiguator, ns, ¤t_item, base_node,"} {"_id":"q-en-rust-c486739bc85374bc546bf2dd79edcd279aa3e8dbbcfda90e73a07d4ca9ca3b02","text":"relevant_pr_number, relevant_pr_user, labels, github_token, ): # Open an issue about the toolstate failure. # type: (str, str, typing.Iterable[str], str, str, typing.List[str], str) -> None '''Open an issue about the toolstate failure.''' if status == 'test-fail': status_description = 'has failing tests' else:"} {"_id":"q-en-rust-c4875221a239f20f717b5e22472e5e26f16bdbdc675a11773ddcd3656031cfa4","text":" fn main() { let x: [u8] = vec!(1, 2, 3)[..]; //~ ERROR E0277 let x: &[u8] = vec!(1, 2, 3)[..]; //~ ERROR E0308 let x: [u8] = &vec!(1, 2, 3)[..]; //~ ERROR E0308 //~^ ERROR E0277 let x: &[u8] = &vec!(1, 2, 3)[..]; } "} {"_id":"q-en-rust-c4b3fd61fa11284b6225aadde50d2e900e7524a13acd3059bf24e2d12282be4a","text":"// aux-build:struct_variant_privacy.rs extern crate struct_variant_privacy; fn f(b: struct_variant_privacy::Bar) { //~ ERROR enum `Bar` is private fn f(b: struct_variant_privacy::Bar) { //~^ ERROR enum `Bar` is private match b { struct_variant_privacy::Bar::Baz { a: _a } => {} //~ ERROR enum `Bar` is private }"} {"_id":"q-en-rust-c51252850b92800c7074fd85b620ebe382c98d6fb2e5ab3472187d233a4f0bf7","text":"\"type name\" }; let msg = format!(\"use of undeclared {} `{}`\", kind, path_names_to_string(path, 0)); let self_type_name = special_idents::type_self.name; let is_invalid_self_type_name = path.segments.len() > 0 && maybe_qself.is_none() && path.segments[0].identifier.name == self_type_name; let msg = if is_invalid_self_type_name { \"use of `Self` outside of an impl or trait\".to_string() } else { format!(\"use of undeclared {} `{}`\", kind, path_names_to_string(path, 0)) }; self.resolve_error(ty.span, &msg[..]); } }"} {"_id":"q-en-rust-c532414c694e851dc63aa62576cc260f8ef7bca3b762582dd3d84852cc1f1e58","text":" #![crate_type = \"lib\"] use super::A; //~ ERROR failed to resolve mod b { pub trait A {} pub trait B {} } /// [`A`] pub use b::*; "} {"_id":"q-en-rust-c5583a4dbafa9f12d03440d9e224e3afe9e962bea4fded8f752c05c07d9d9658","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. // ignore-pretty #![feature(unsafe_destructor)] use std::rc::Rc; use std::cell::Cell; struct Field { number: uint, state: Rc> } impl Field { fn new(number: uint, state: Rc>) -> Field { Field { number: number, state: state } } } #[unsafe_destructor] // because Field isn't Send impl Drop for Field { fn drop(&mut self) { println!(\"Dropping field {}\", self.number); assert_eq!(self.state.get(), self.number); self.state.set(self.state.get()+1); } } struct NoDropImpl { _one: Field, _two: Field, _three: Field } struct HasDropImpl { _one: Field, _two: Field, _three: Field } #[unsafe_destructor] // because HasDropImpl isn't Send impl Drop for HasDropImpl { fn drop(&mut self) { println!(\"HasDropImpl.drop()\"); assert_eq!(self._one.state.get(), 0); self._one.state.set(1); } } pub fn main() { let state = Rc::new(Cell::new(1)); let noImpl = NoDropImpl { _one: Field::new(1, state.clone()), _two: Field::new(2, state.clone()), _three: Field::new(3, state.clone()) }; drop(noImpl); assert_eq!(state.get(), 4); state.set(0); let hasImpl = HasDropImpl { _one: Field::new(1, state.clone()), _two: Field::new(2, state.clone()), _three: Field::new(3, state.clone()) }; drop(hasImpl); assert_eq!(state.get(), 4); } "} {"_id":"q-en-rust-c5719bbdc3b9e350136fa4404501e33df8d12b1b0fd8add4aa76fdc2407229fb","text":"/// # Example /// /// ```rust /// # #![allow(deprecated)] /// use url::decode; /// /// let url = decode(\"https://example.com/Rust%20(programming%20language)\");"} {"_id":"q-en-rust-c5ced770a01c256ff419a941afc15dad9dc22732184bcaaf160fee854a6d1044","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":"q-en-rust-c601d6477d3990de179ed1fcb7a4dcb627c569f613781237784347641df710fc","text":"&& key.ns == MacroNS && nonglob_binding.expansion != LocalExpnId::ROOT { resolution.binding = Some(self.ambiguity( resolution.binding = Some(this.ambiguity( AmbiguityKind::GlobVsExpanded, nonglob_binding, glob_binding,"} {"_id":"q-en-rust-c60ab1f34e6b4b0c553db2321aad7b05db2524e8eb671ad4891803f53ca7b979","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":"q-en-rust-c616aae5fed8b1f2c22535f301ba4c6c0c7f80d9d0c1b9c0e90991025f18898c","text":"debug!(\"(building reduced graph for external crate) building type {}\", final_ident); let modifiers = match new_parent.kind.get() { NormalModuleKind => modifiers, _ => modifiers & !DefModifiers::IMPORTABLE }; child_name_bindings.define_type(def, DUMMY_SP, modifiers); } DefStruct(def_id) => {"} {"_id":"q-en-rust-c65405e15b8b1ac7d3e26c9f411067acf5d49c74765dba596f948b22cd06848a","text":"Some(false) => { cvt(unsafe { unlinkat(fd, child.name_cstr().as_ptr(), 0) })?; } None => match cvt(unsafe { unlinkat(fd, child.name_cstr().as_ptr(), 0) }) { // type unknown - try to unlink Err(err) if err.raw_os_error() == Some(libc::EISDIR) || err.raw_os_error() == Some(libc::EPERM) => { // if the file is a directory unlink fails with EISDIR on Linux and EPERM everyhwere else remove_dir_all_recursive(Some(fd), Path::new(&child.file_name()))?; } result => { result?; } }, None => { // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed // if the process has the appropriate privileges. This however can causing orphaned // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing // into it first instead of trying to unlink() it. remove_dir_all_recursive(Some(fd), Path::new(&child.file_name()))?; } } }"} {"_id":"q-en-rust-c66aacc154c55a8ac830332d48376445baf921f85988d3318ed45e95fbec97f7","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":"q-en-rust-c671b102ed7c8d3281d9e4ef5dfffbeb768ed8a8863eeebc54586800a42feff3","text":"| help: change the delimiters to curly braces | LL | y!{ LL | Ϥ} | LL | y! { /* items */ } | ^^^^^^^^^^^^^^^ help: add a semicolon | LL | Ϥ,;"} {"_id":"q-en-rust-c69ab84edb69c037be43b2eae5031266cd3d65596bd9e4c01cdaf3d142cad4c5","text":"error!(\"This is an error log\") warn!(\"This is a warn log\") info!(\"this is an info log\") debug!(\"This is a dubug log\") debug!(\"This is a debug log\") } ```"} {"_id":"q-en-rust-c6a4025b763f6aa8814672dca11644e2a3b7f4c584396d851d8fac191a2a6c11","text":"// rustc internal (active, staged_api, \"1.0.0\", None), // Allows using items which are missing stability attributes // rustc internal (active, unmarked_api, \"1.0.0\", None), // Allows using #![no_core] (active, no_core, \"1.3.0\", Some(29639)),"} {"_id":"q-en-rust-c6ace66c818d73c1199cacbdce023002d2e124d894964611c637743b9bdf0887","text":"AssocTypeItem(t, b) => ItemEnum::AssocType { generics: t.generics.into_tcx(tcx), bounds: b.into_iter().map(|x| x.into_tcx(tcx)).collect(), default: t.item_type.map(|ty| ty.into_tcx(tcx)), default: Some(t.item_type.unwrap_or(t.type_).into_tcx(tcx)), }, // `convert_item` early returns `None` for striped items and keywords. StrippedItem(_) | KeywordItem(_) => unreachable!(),"} {"_id":"q-en-rust-c6c432421bb5c33e9421dc6571245fbe308d4781194b6aaa8915326c1c57a659","text":" use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; use rustc_middle::ty::{ self, subst::{GenericArgKind, Subst, SubstsRef}, PredicateAtom, Ty, TyCtxt, TyS, }; use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES; use rustc_span::{symbol::sym, Span}; use rustc_target::spec::abi::Abi; use crate::transform::MirPass; pub struct FunctionItemReferences; impl<'tcx> MirPass<'tcx> for FunctionItemReferences { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let mut checker = FunctionItemRefChecker { tcx, body }; checker.visit_body(&body); } } struct FunctionItemRefChecker<'a, 'tcx> { tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, } impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { /// Emits a lint for function reference arguments bound by `fmt::Pointer` or passed to /// `transmute`. This only handles arguments in calls outside macro expansions to avoid double /// counting function references formatted as pointers by macros. fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) { if let TerminatorKind::Call { func, args, destination: _, cleanup: _, from_hir_call: _, fn_span: _, } = &terminator.kind { let source_info = *self.body.source_info(location); // Only handle function calls outside macros if !source_info.span.from_expansion() { let func_ty = func.ty(self.body, self.tcx); if let ty::FnDef(def_id, substs_ref) = *func_ty.kind() { // Handle calls to `transmute` if self.tcx.is_diagnostic_item(sym::transmute, def_id) { let arg_ty = args[0].ty(self.body, self.tcx); for generic_inner_ty in arg_ty.walk() { if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() { if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(inner_ty) { let ident = self.tcx.item_name(fn_id).to_ident_string(); let span = self.nth_arg_span(&args, 0); self.emit_lint(ident, fn_id, source_info, span); } } } } else { self.check_bound_args(def_id, substs_ref, &args, source_info); } } } } self.super_terminator(terminator, location); } /// Emits a lint for function references formatted with `fmt::Pointer::fmt` by macros. These /// cases are handled as operands instead of call terminators to avoid any dependence on /// unstable, internal formatting details like whether `fmt` is called directly or not. fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) { let source_info = *self.body.source_info(location); if source_info.span.from_expansion() { let op_ty = operand.ty(self.body, self.tcx); if let ty::FnDef(def_id, substs_ref) = *op_ty.kind() { if self.tcx.is_diagnostic_item(sym::pointer_trait_fmt, def_id) { let param_ty = substs_ref.type_at(0); if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(param_ty) { // The operand's ctxt wouldn't display the lint since it's inside a macro so // we have to use the callsite's ctxt. let callsite_ctxt = source_info.span.source_callsite().ctxt(); let span = source_info.span.with_ctxt(callsite_ctxt); let ident = self.tcx.item_name(fn_id).to_ident_string(); self.emit_lint(ident, fn_id, source_info, span); } } } } self.super_operand(operand, location); } } impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { /// Emits a lint for function reference arguments bound by `fmt::Pointer` in calls to the /// function defined by `def_id` with the substitutions `substs_ref`. fn check_bound_args( &self, def_id: DefId, substs_ref: SubstsRef<'tcx>, args: &Vec>, source_info: SourceInfo, ) { let param_env = self.tcx.param_env(def_id); let bounds = param_env.caller_bounds(); for bound in bounds { if let Some(bound_ty) = self.is_pointer_trait(&bound.skip_binders()) { // Get the argument types as they appear in the function signature. let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs(); for (arg_num, arg_def) in arg_defs.iter().enumerate() { // For all types reachable from the argument type in the fn sig for generic_inner_ty in arg_def.walk() { if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() { // If the inner type matches the type bound by `Pointer` if TyS::same_type(inner_ty, bound_ty) { // Do a substitution using the parameters from the callsite let subst_ty = inner_ty.subst(self.tcx, substs_ref); if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(subst_ty) { let ident = self.tcx.item_name(fn_id).to_ident_string(); let span = self.nth_arg_span(args, arg_num); self.emit_lint(ident, fn_id, source_info, span); } } } } } } } } /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type. fn is_pointer_trait(&self, bound: &PredicateAtom<'tcx>) -> Option> { if let ty::PredicateAtom::Trait(predicate, _) = bound { if self.tcx.is_diagnostic_item(sym::pointer_trait, predicate.def_id()) { Some(predicate.trait_ref.self_ty()) } else { None } } else { None } } /// If a type is a reference or raw pointer to the anonymous type of a function definition, /// returns that function's `DefId`. fn is_fn_ref(ty: Ty<'tcx>) -> Option { let referent_ty = match ty.kind() { ty::Ref(_, referent_ty, _) => Some(referent_ty), ty::RawPtr(ty_and_mut) => Some(&ty_and_mut.ty), _ => None, }; referent_ty .map( |ref_ty| { if let ty::FnDef(def_id, _) = *ref_ty.kind() { Some(def_id) } else { None } }, ) .unwrap_or(None) } fn nth_arg_span(&self, args: &Vec>, n: usize) -> Span { match &args[n] { Operand::Copy(place) | Operand::Move(place) => { self.body.local_decls[place.local].source_info.span } Operand::Constant(constant) => constant.span, } } fn emit_lint(&self, ident: String, fn_id: DefId, source_info: SourceInfo, span: Span) { let lint_root = self.body.source_scopes[source_info.scope] .local_data .as_ref() .assert_crate_local() .lint_root; let fn_sig = self.tcx.fn_sig(fn_id); let unsafety = fn_sig.unsafety().prefix_str(); let abi = match fn_sig.abi() { Abi::Rust => String::from(\"\"), other_abi => { let mut s = String::from(\"extern \"\"); s.push_str(other_abi.name()); s.push_str(\"\" \"); s } }; let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder(); let variadic = if fn_sig.c_variadic() { \", ...\" } else { \"\" }; let ret = if fn_sig.output().skip_binder().is_unit() { \"\" } else { \" -> _\" }; self.tcx.struct_span_lint_hir(FUNCTION_ITEM_REFERENCES, lint_root, span, |lint| { lint.build(\"taking a reference to a function item does not give a function pointer\") .span_suggestion( span, &format!(\"cast `{}` to obtain a function pointer\", ident), format!( \"{} as {}{}fn({}{}){}\", ident, unsafety, abi, vec![\"_\"; num_args].join(\", \"), variadic, ret, ), Applicability::Unspecified, ) .emit(); }); } } "} {"_id":"q-en-rust-c6cf8f8fe6325c56792d673da520196a7f819e99765b6f773792654a91b93b18","text":"- [Rustc now catches more cases of `pub_use_of_private_extern_crate`][80763] - [Changes in how proc macros handle whitespace may lead to panics when used with older `proc-macro-hack` versions. A `cargo update` should be sufficient to fix this in all cases.][84136] - [Turn `#[derive]` into a regular macro attribute][79078] [84136]: https://github.com/rust-lang/rust/issues/84136 [80763]: https://github.com/rust-lang/rust/pull/80763"} {"_id":"q-en-rust-c6ec25520f882a79f4f1848973c647390ef7234748559bbd34627f3f098ec5fc","text":" // build-pass fn main() { let _ = &[(); usize::MAX]; } "} {"_id":"q-en-rust-c6fa1ee73b61e40f2702d915a230b400bce731ba4c2fe506c1f0b79fff8b547b","text":"}; if self.in_root && item.vis.node.is_pub() { self.derives.push(ProcMacroDerive { self.macros.push(ProcMacro::Derive(ProcMacroDerive { span: item.span, trait_name: trait_ident.name, function_name: item.ident, attrs: proc_attrs, }); })); } else { let msg = if !self.in_root { \"functions tagged with `#[proc_macro_derive]` must "} {"_id":"q-en-rust-c74ad61e8604b04cc73f922c05f88ef43a310d794c582b384968f5ae5eab402d","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":"q-en-rust-c76d4e2d6c369143ac382dc3c5011f19c290aa25542458e47011e1fd462eae58","text":" fn g() where 'static: 'static, dyn 'static: 'static + Copy, //~ ERROR at least one trait is required for an object type { } fn main() {} "} {"_id":"q-en-rust-c79937b22cc320e55249d590db0f152c5d8e35ae9f2b9cec3d64a36551e4d0ed","text":"// except according to those terms. struct BuildData { foo: isize, //~ NOTE `foo` first declared here foo: isize, foo: isize, //~ ERROR field `foo` is already declared //~^ ERROR field `foo` is already declared [E0124] //~| NOTE field already declared } fn main() {"} {"_id":"q-en-rust-c7a69bebc21a9e319ee3a7dfb8d2a5abd61722204013734edbe85f4c1ad9ff2e","text":"let ans = s(); //~^ ERROR this function takes 1 parameter but 0 parameters were supplied //~| NOTE the following parameter type was expected //~| NOTE expected 1 parameter let ans = s(\"burma\", \"shave\"); //~^ ERROR this function takes 1 parameter but 2 parameters were supplied //~| NOTE the following parameter type was expected //~| NOTE expected 1 parameter }"} {"_id":"q-en-rust-c7aa127e637a639bf9473487ab5e1448978411336ce3a132e3c8d83135f53b5f","text":"// FIXME we need to revisit this for #67176 if rvalue.has_param() { trace!(\"skipping, has param\"); return None; } if !rvalue"} {"_id":"q-en-rust-c7b42ad48bf870f173b8275bf4e17504d8db6f067fd609defa4b53ab4314566b","text":"relevant_pr_url, relevant_pr_user, pr_reviewer, current_datetime current_datetime, github_token, ): # type: (str, str, str, str, str, str, str) -> str '''Updates `_data/latest.json` to match build result of the given commit. ''' with open('_data/latest.json', 'r+') as f:"} {"_id":"q-en-rust-c7c432d4814fe9f2fb5cd23726fd75547c64cbff13cf7a6888b5d16fc83ca562","text":"impl ops::FnOnce<(),> for Debuger { type Output = (); fn call_once(self, _args: ()) { //~^ ERROR `call_once` has an incompatible type for trait: expected \"rust-call\" fn, found \"Rust\" fn //~^ ERROR `call_once` has an incompatible type for trait //~| expected \"rust-call\" fn, //~| found \"Rust\" fn println!(\"{:?}\", self.x); } }"} {"_id":"q-en-rust-c7d2687b8dd7ccc943f1579aad6f4e5592547b853f578fb4c0b2555b38d9fb2a","text":"error[E0038]: the trait alias `SelfInput` cannot be made into an object --> $DIR/self-in-generics.rs:5:19 --> $DIR/self-in-generics.rs:12:19 | LL | pub fn f(_f: &dyn SelfInput) {} | ^^^^^^^^^"} {"_id":"q-en-rust-c7e8c1878601ee207a971a90093acd63181deeee8c39a9b76f786ce9999abdde","text":"use crate::cmp::Ordering; use crate::fmt::{self, Debug, Display}; use crate::intrinsics::is_nonoverlapping; use crate::marker::{PhantomData, Unsize}; use crate::mem; use crate::ops::{CoerceUnsized, Deref, DerefMut, DispatchFromDyn};"} {"_id":"q-en-rust-c82a36882a63c5da2e77f8d4002450ad2068954ea9cbf38a92e218ba14ee8df4","text":" error[E0038]: the trait alias `BB` cannot be made into an object --> $DIR/self-in-const-generics.rs:9:16 | LL | fn foo(x: &dyn BB) {} | ^^ | = note: it cannot use `Self` as a type parameter in a supertrait or `where`-clause error: aborting due to previous error For more information about this error, try `rustc --explain E0038`. "} {"_id":"q-en-rust-c846f7be92dd23d872dce556725d6d6250338b62a6e74e8353a5430c19c629fc","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":"q-en-rust-c85fb2f26151c01a1e09cc246cd3f041ad9b5b14f0f49c34eb9c949e48b85b25","text":" error[E0658]: :literal fragment specifier is experimental and subject to change (see issue #35625) --> $DIR/feature-gate-macro-literal-matcher.rs:14:19 | LL | macro_rules! m { ($lt:literal) => {} } | ^^^^^^^^^^^ | = help: add #![feature(macro_literal_matcher)] to the crate attributes to enable error: aborting due to previous error For more information about this error, try `rustc --explain E0658`. "} {"_id":"q-en-rust-c8851f733914b45eb50adbb756282aafab4338d99e014072b6653b345aba1f52","text":"} else { resolution.binding = Some(nonglob_binding); } resolution.shadowed_glob = Some(glob_binding); if let Some(old_binding) = resolution.shadowed_glob { assert!(old_binding.is_glob_import()); if glob_binding.res() != old_binding.res() { resolution.shadowed_glob = Some(this.ambiguity( AmbiguityKind::GlobVsGlob, old_binding, glob_binding, )); } else if !old_binding.vis.is_at_least(binding.vis, this.tcx) { resolution.shadowed_glob = Some(glob_binding); } } else { resolution.shadowed_glob = Some(glob_binding); } } (false, false) => { return Err(old_binding);"} {"_id":"q-en-rust-c89fe7dc3a071934a8f8dee15a59652f3878e4806bd3eb91d54e7ad07da151d6","text":"snapshot.recover_diff_marker(); } if self.token == token::Colon { // if next token is following a colon, it's likely a path // and we can suggest a path separator self.bump(); if self.token.span.lo() == self.prev_token.span.hi() { // if a previous and next token of the current one is // integer literal (e.g. `1:42`), it's likely a range // expression for Pythonistas and we can suggest so. if self.prev_token.is_integer_lit() && self.may_recover() && self.look_ahead(1, |token| token.is_integer_lit()) { // FIXME(hkmatsumoto): Might be better to trigger // this only when parsing an index expression. err.span_suggestion_verbose( self.prev_token.span, \"maybe write a path separator here\", \"::\", self.token.span, \"you might have meant a range expression\", \"..\", Applicability::MaybeIncorrect, ); } if self.sess.unstable_features.is_nightly_build() { // FIXME(Nilstrieb): Remove this again after a few months. err.note(\"type ascription syntax has been removed, see issue #101728 \"); } else { // if next token is following a colon, it's likely a path // and we can suggest a path separator self.bump(); if self.token.span.lo() == self.prev_token.span.hi() { err.span_suggestion_verbose( self.prev_token.span, \"maybe write a path separator here\", \"::\", Applicability::MaybeIncorrect, ); } if self.sess.unstable_features.is_nightly_build() { // FIXME(Nilstrieb): Remove this again after a few months. err.note(\"type ascription syntax has been removed, see issue #101728 \"); } } }"} {"_id":"q-en-rust-c8cb43fc5a6d642b74e663d469525bc714453434dc305ef7299af379da39f3eb","text":"/// Creating a pointer `b` to contents of another reference Reborrow(Span), /// Creating a pointer `b` to contents of an upvar ReborrowUpvar(Span, ty::UpvarId), /// Data with type `Ty<'tcx>` was borrowed DataBorrowed(Ty<'tcx>, Span),"} {"_id":"q-en-rust-c8d9a4beea98ec3da55294de592df996998051c3d45c3db74eb32a98ae7c577f","text":"let ty = tcx.type_of(def_id).instantiate_identity(); if ty.references_error() { // If there is already another error, do not emit an error for not using a type parameter. assert!(tcx.dcx().has_errors().is_some()); // Without the `stashed_err_count` part this can fail (#120856). assert!(tcx.dcx().has_errors().is_some() || tcx.dcx().stashed_err_count() > 0); return; }"} {"_id":"q-en-rust-c8f58bf20b0ea7dad3da472beb54c2944006d5ca10488bc895001f67d345cafb","text":"#[proc_macro_attribute] pub fn expect_print_stmt(attr: TokenStream, item: TokenStream) -> TokenStream { assert!(attr.to_string().is_empty()); assert_eq!(item.to_string(), \"println!(\"{}\" , string);\"); assert_eq!(item.to_string(), \"println!(\"{}\", string);\"); item }"} {"_id":"q-en-rust-c8fcea88f5f1d9d1f4a48ceba2fe8b30c8f9cf1e5b0b7f171da166720a253a64","text":"parse_only: parse_only, no_trans: no_trans, no_analysis: no_analysis, no_rpath: no_rpath, debugging_opts: debugging_opts, android_cross_path: android_cross_path, write_dependency_info: write_dependency_info,"} {"_id":"q-en-rust-c945a3ec3433cd6c406c1849238734427d91041ebfb06dfc789ebe44ee61808f","text":"enum PlaceAncestryRelation { Ancestor, Descendant, SamePlace, Divergent, }"} {"_id":"q-en-rust-c96b645d4d726ab8d85820b1e507b3643672c7ebf3f2101bf8547b6722ec6717","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":"q-en-rust-c995a57850762fdfb98ed719113dd4dae4fa3c7da5c8918e978bb4865ed3affc","text":" error[E0700]: hidden type for `impl IntoIterator + Cap<'b>>` captures lifetime that does not appear in bounds --> $DIR/nested-impl-trait-fail.rs:17:5 | LL | fn fail_early_bound<'s, 'a, 'b>(a: &'s u8) -> impl IntoIterator + Cap<'b>> | -- hidden type `[&'s u8; 1]` captures the lifetime `'s` as defined here ... LL | [a] | ^^^ | help: to declare that `impl IntoIterator + Cap<'b>>` captures `'s`, you can add an explicit `'s` lifetime bound | LL | fn fail_early_bound<'s, 'a, 'b>(a: &'s u8) -> impl IntoIterator + Cap<'b>> + 's | ++++ help: to declare that `impl Cap<'a> + Cap<'b>` captures `'s`, you can add an explicit `'s` lifetime bound | LL | fn fail_early_bound<'s, 'a, 'b>(a: &'s u8) -> impl IntoIterator + Cap<'b> + 's> | ++++ error[E0700]: hidden type for `impl Cap<'a> + Cap<'b>` captures lifetime that does not appear in bounds --> $DIR/nested-impl-trait-fail.rs:17:5 | LL | fn fail_early_bound<'s, 'a, 'b>(a: &'s u8) -> impl IntoIterator + Cap<'b>> | -- hidden type `&'s u8` captures the lifetime `'s` as defined here ... LL | [a] | ^^^ | help: to declare that `impl IntoIterator + Cap<'b>>` captures `'s`, you can add an explicit `'s` lifetime bound | LL | fn fail_early_bound<'s, 'a, 'b>(a: &'s u8) -> impl IntoIterator + Cap<'b>> + 's | ++++ help: to declare that `impl Cap<'a> + Cap<'b>` captures `'s`, you can add an explicit `'s` lifetime bound | LL | fn fail_early_bound<'s, 'a, 'b>(a: &'s u8) -> impl IntoIterator + Cap<'b> + 's> | ++++ error[E0700]: hidden type for `impl IntoIterator + Cap<'b>>` captures lifetime that does not appear in bounds --> $DIR/nested-impl-trait-fail.rs:28:5 | LL | fn fail_late_bound<'s, 'a, 'b>( | -- hidden type `[&'s u8; 1]` captures the lifetime `'s` as defined here ... LL | [a] | ^^^ | help: to declare that `impl IntoIterator + Cap<'b>>` captures `'s`, you can add an explicit `'s` lifetime bound | LL | ) -> impl IntoIterator + Cap<'b>> + 's { | ++++ help: to declare that `impl Cap<'a> + Cap<'b>` captures `'s`, you can add an explicit `'s` lifetime bound | LL | ) -> impl IntoIterator + Cap<'b> + 's> { | ++++ error[E0700]: hidden type for `impl Cap<'a> + Cap<'b>` captures lifetime that does not appear in bounds --> $DIR/nested-impl-trait-fail.rs:28:5 | LL | fn fail_late_bound<'s, 'a, 'b>( | -- hidden type `&'s u8` captures the lifetime `'s` as defined here ... LL | [a] | ^^^ | help: to declare that `impl IntoIterator + Cap<'b>>` captures `'s`, you can add an explicit `'s` lifetime bound | LL | ) -> impl IntoIterator + Cap<'b>> + 's { | ++++ help: to declare that `impl Cap<'a> + Cap<'b>` captures `'s`, you can add an explicit `'s` lifetime bound | LL | ) -> impl IntoIterator + Cap<'b> + 's> { | ++++ error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0700`. "} {"_id":"q-en-rust-c9ab94e922de2fd0772fd6896338dbf326aa915ccf5b1b359c8769aaf29f5415","text":"# source tarball for a stable release you'll likely see `1.x.0` for rustc and # `0.(x+1).0` for Cargo where they were released on `date`. date: 2020-06-03 date: 2020-06-16 rustc: beta cargo: beta"} {"_id":"q-en-rust-c9c224db9487036fb6cff287b2d9139b75cb63fdedb749dad6ec332bb0604435","text":"base: &'tcx hir::Expr<'tcx>, field: Ident, ) -> Ty<'tcx> { debug!(\"check_field(expr: {:?}, base: {:?}, field: {:?})\", expr, base, field); let expr_t = self.check_expr(base); let expr_t = self.structurally_resolved_type(base.span, expr_t); let mut private_candidate = None; let mut autoderef = self.autoderef(expr.span, expr_t); while let Some((base_t, _)) = autoderef.next() { debug!(\"base_t: {:?}\", base_t); match base_t.kind() { ty::Adt(base_def, substs) if !base_def.is_enum() => { debug!(\"struct named {:?}\", base_t);"} {"_id":"q-en-rust-c9ce40d9f0c6626a5104dba94ed2f4f77f3e0edd11214b2bba037c693c1fde97","text":" error[E0603]: tuple struct constructor `A` is private --> $DIR/issue-111220-tuple-struct-fields.rs:8:13 | LL | let Self(x) = self; | ^^^^^^^ error[E0603]: tuple struct constructor `A` is private --> $DIR/issue-111220-tuple-struct-fields.rs:20:13 | LL | let Self(a) = self; | ^^^^^^^ error[E0603]: tuple struct constructor `A` is private --> $DIR/issue-111220-tuple-struct-fields.rs:40:13 | LL | let Self(a) = self; | ^^^^^^^ error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0603`. "} {"_id":"q-en-rust-c9d2dbf45a54a93526db7e64928f9524ec8063471a3553872c7ed9e76da4a762","text":"#![feature(core)] #![feature(core_intrinsics)] #![feature(core_prelude)] #![feature(core_slice_ext)] #![feature(custom_attribute)] #![feature(fundamental)] #![feature(lang_items)]"} {"_id":"q-en-rust-c9f23288d747730f8bc41609e334dbdbf9b597c2dfac94c28aa1044f3f5a8759","text":" //@edition:2021 macro_rules! foo { () => { println!('hello world'); //~^ ERROR unterminated character literal //~| ERROR prefix `world` is unknown } } fn main() {} "} {"_id":"q-en-rust-c9f64eaf4ac61510417c6247aabeae7f721d6d2a51c65296408c24ce9998fa7d","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":"q-en-rust-ca555277227186e35437089fe59bd5db7bedbaf38333fd2b1e96d9d25666c1d4","text":"LL | let ug = Graph::::new_undirected(); | ^^^^^^^^^^^^^^ function or associated item not found in `Graph` | note: if you're trying to build a new `issue_30123_aux::Graph`, consider using `issue_30123_aux::Graph::::new` which returns `issue_30123_aux::Graph<_, _>` --> $DIR/auxiliary/issue-30123-aux.rs:14:5 | LL | pub fn new() -> Self { | ^^^^^^^^^^^^^^^^^^^^ = note: the function or associated item was found for - `issue_30123_aux::Graph`"} {"_id":"q-en-rust-ca6a52090cee10af8496f2e33f91f8faed5e799c914a22c764f59300105f86a9","text":"# Find out where the pretty printer Python module is RUSTC_SYSROOT=\"$(\"$RUSTC\" --print=sysroot)\" GDB_PYTHON_MODULE_DIRECTORY=\"$RUSTC_SYSROOT/lib/rustlib/etc\" # Get the commit hash for path remapping RUSTC_COMMIT_HASH=\"$(\"$RUSTC\" -vV | sed -n 's/commit-hash: (w*)/1/p')\" # Run GDB with the additional arguments that load the pretty printers # Set the environment variable `RUST_GDB` to overwrite the call to a"} {"_id":"q-en-rust-ca9b636d9b97419100edac72cc67099220d96116224746a46ba4b541c44c6f32","text":"let msg = \"macro-expanded `extern crate` items cannot shadow names passed with `--extern`\"; self.r.tcx.sess.span_err(item.span, msg); // `return` is intended to discard this binding because it's an // unregistered ambiguity error which would result in a panic // caused by inconsistency `path_res` // more details: https://github.com/rust-lang/rust/pull/111761 return; } } let entry = self.r.extern_prelude.entry(ident.normalize_to_macros_2_0()).or_insert("} {"_id":"q-en-rust-caa378ae6b17a1433b3c76c47731782f25a98a9f0f21567eb3ccc0726cfeb368","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":"q-en-rust-cac4074faa36752e3dc39a95b71776815728ad2d1662165846297a96844c7018","text":"// relying on projections in the impl-trait-ref. // // e.g., `impl> Foo<::T> for V` substs.obligations.append(&mut impl_obligations); impl_obligations.extend(substs.obligations); ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: substs.obligations } ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations } } fn confirm_object_candidate("} {"_id":"q-en-rust-cad7690215a8bc96c93b358104343dcf9bf766848b6905e6a98cd3986ec2295a","text":"use core::prelude::*; use heap; use raw_vec::RawVec; use core::any::Any; use core::cmp::Ordering;"} {"_id":"q-en-rust-cb0d2fbf8735a2ed7d05f7191841d056600cf7e37692094097790afc9f9e9628","text":"| LL | E::Empty3() => () | ^^^^^^^^^^^ not a tuple struct or tuple variant | help: use the struct variant pattern syntax | LL | E::Empty3 {} => () | ~~ error[E0164]: expected tuple struct or tuple variant, found struct variant `XE::XEmpty3` --> $DIR/empty-struct-braces-pat-3.rs:21:9 | LL | XE::XEmpty3() => () | ^^^^^^^^^^^^^ not a tuple struct or tuple variant | help: use the struct variant pattern syntax | LL | XE::XEmpty3 {} => () | ~~ error[E0164]: expected tuple struct or tuple variant, found struct variant `E::Empty3` --> $DIR/empty-struct-braces-pat-3.rs:25:9 | LL | E::Empty3(..) => () | ^^^^^^^^^^^^^ not a tuple struct or tuple variant | help: use the struct variant pattern syntax | LL | E::Empty3 {} => () | ~~ error[E0164]: expected tuple struct or tuple variant, found struct variant `XE::XEmpty3` --> $DIR/empty-struct-braces-pat-3.rs:29:9 | LL | XE::XEmpty3(..) => () | ^^^^^^^^^^^^^^^ not a tuple struct or tuple variant | help: use the struct variant pattern syntax | LL | XE::XEmpty3 {} => () | ~~ error: aborting due to 4 previous errors"} {"_id":"q-en-rust-cb15ce1f1574d05f181ff72c6fc4be293031fa138ba995dc740ffa2138db0dcb","text":"//! symbol, but that caused Debian to detect an unnecessarily strict versioned //! dependency on libc6 (#23628). // There are a variety of `#[cfg]`s controlling which targets are involved in // each instance of `weak!` and `syscall!`. Rather than trying to unify all of // that, we'll just allow that some unix targets don't use this module at all. #![allow(dead_code, unused_macros)] use crate::ffi::CStr; use crate::marker; use crate::mem;"} {"_id":"q-en-rust-cb34eb9c37e1827c06a6b5ab9ec579bc512812d382c6e3b9364d1a94186716c9","text":"if level == Level::Forbid { continue } let forbid_src = match self.sets.get_lint_id_level(*id, self.cur) { let forbid_src = match self.sets.get_lint_id_level(*id, self.cur, None) { (Some(Level::Forbid), src) => src, _ => continue, };"} {"_id":"q-en-rust-cb64f9cf0e0208b79b977a1c6bfe787d9b34aad3caac2a9d0c2a19db0ecc7c7d","text":"panic_immediate_abort = [\"core/panic_immediate_abort\"] # Choose algorithms that are optimized for binary size instead of runtime performance optimize_for_size = [\"core/optimize_for_size\"] [lints.rust.unexpected_cfgs] level = \"warn\" # x.py uses beta cargo, so `check-cfg` entries do not yet take effect # for rust-lang/rust. But for users of `-Zbuild-std` it does. # The unused warning is waiting for rust-lang/cargo#13925 to reach beta. check-cfg = [ 'cfg(bootstrap)', 'cfg(no_global_oom_handling)', 'cfg(no_rc)', 'cfg(no_sync)', ] "} {"_id":"q-en-rust-cb71875421ff0cce2b243da37e01d6f8b209d9f1ba04a7a43d3578c45498514d","text":"pub use self::location::Location; #[stable(feature = \"panic_hooks\", since = \"1.10.0\")] pub use self::panic_info::PanicInfo; #[unstable(feature = \"panic_info_message\", issue = \"66745\")] #[stable(feature = \"panic_info_message\", since = \"CURRENT_RUSTC_VERSION\")] pub use self::panic_info::PanicMessage; #[stable(feature = \"catch_unwind\", since = \"1.9.0\")] pub use self::unwind_safe::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe};"} {"_id":"q-en-rust-cb7ccecccc5184687888e7a20ee10e3f93a810eb35b58ff8dddeae7811ca26d3","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":"q-en-rust-cb8b250b9580befb9eb53bf0369c1258883acf0a68d9432e9585d5da40383a9a","text":" error: the `wait` method cannot be invoked on a trait object --> $DIR/issue-35976.rs:20:9 | LL | fn wait(&self) where Self: Sized; | ----- this has a `Sized` requirement ... LL | arg.wait(); | ^^^^ | help: another candidate was found in the following trait, perhaps add a `use` for it: | LL | use private::Future; | error: aborting due to previous error "} {"_id":"q-en-rust-cb97ccf0434fafa7221037601a666b7919a0e3323b774bca0313909fb5ddfb91","text":"\"rustc_data_structures\", \"rustc_hir\", \"rustc_hir_pretty\", \"rustc_lexer\", \"rustc_middle\", \"rustc_parse\", \"rustc_session\", \"rustc_span\", \"serde_json\","} {"_id":"q-en-rust-cbb81e1248aa72a7269711e23058031217489ee2095f08ffc90f613211d2617f","text":"// Region folder impl<'tcx> TyCtxt<'tcx> { /// Folds the escaping and free regions in `value` using `f`, and /// sets `skipped_regions` to true if any late-bound region was found /// and skipped. /// Folds the escaping and free regions in `value` using `f`. pub fn fold_regions( self, value: T,"} {"_id":"q-en-rust-cbd541c1b02d8372d9760629736e9a20007074c931a5494a1e9861bdc84e95d9","text":" #![feature(stmt_expr_attributes)] fn foo() -> String { #[cfg(feature = \"validation\")] [1, 2, 3].iter().map(|c| c.to_string()).collect::() //~ ERROR expected `;`, found `#` #[cfg(not(feature = \"validation\"))] String::new() } fn bar() -> String { #[attr] [1, 2, 3].iter().map(|c| c.to_string()).collect::() //~ ERROR expected `;`, found `#` #[attr] //~ ERROR cannot find attribute `attr` in this scope String::new() } fn main() { println!(\"{}\", foo()); } "} {"_id":"q-en-rust-cbe82ed3cd04465455478cb6bbf40f29aeb6bdf238c104f5918b9d053e2cd787","text":"t!(fs::create_dir_all(&out_dir)); let mut cfg = cmake::Config::new(builder.src.join(\"src/llvm-project/lld\")); if let Some(ref linker) = builder.config.llvm_use_linker { cfg.define(\"LLVM_USE_LINKER\", linker); } configure_cmake(builder, target, &mut cfg, true); // This is an awful, awful hack. Discovered when we migrated to using"} {"_id":"q-en-rust-cbebdd0ac88f4162c1502b36557bf1a4a4dea8269769e7d98518e4c0a4d2f2be","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(core)] use std::boxed::FnBox; struct Obj where F: FnOnce() -> u32 { closure: F, not_closure: usize, } struct BoxedObj { boxed_closure: Box u32>, } struct Wrapper where F: FnMut() -> u32 { wrap: Obj, } fn func() -> u32 { 0 } fn check_expression() -> Obj u32>> { Obj { closure: Box::new(|| 42_u32) as Box u32>, not_closure: 42 } } fn main() { // test variations of function let o_closure = Obj { closure: || 42, not_closure: 42 }; o_closure.closure(); //~ ERROR no method named `closure` found //~^ NOTE use `(o_closure.closure)(...)` if you meant to call the function stored o_closure.not_closure(); //~ ERROR no method named `not_closure` found //~^ NOTE did you mean to write `o_closure.not_closure`? let o_func = Obj { closure: func, not_closure: 5 }; o_func.closure(); //~ ERROR no method named `closure` found //~^ NOTE use `(o_func.closure)(...)` if you meant to call the function stored let boxed_fn = BoxedObj { boxed_closure: Box::new(func) }; boxed_fn.boxed_closure();//~ ERROR no method named `boxed_closure` found //~^ NOTE use `(boxed_fn.boxed_closure)(...)` if you meant to call the function stored let boxed_closure = BoxedObj { boxed_closure: Box::new(|| 42_u32) as Box u32> }; boxed_closure.boxed_closure();//~ ERROR no method named `boxed_closure` found //~^ NOTE use `(boxed_closure.boxed_closure)(...)` if you meant to call the function stored // test expression writing in the notes let w = Wrapper { wrap: o_func }; w.wrap.closure();//~ ERROR no method named `closure` found //~^ NOTE use `(w.wrap.closure)(...)` if you meant to call the function stored w.wrap.not_closure();//~ ERROR no method named `not_closure` found //~^ NOTE did you mean to write `w.wrap.not_closure`? check_expression().closure();//~ ERROR no method named `closure` found //~^ NOTE use `(check_expression().closure)(...)` if you meant to call the function stored } "} {"_id":"q-en-rust-cc07212cec9892fdfc6721305ee82dcac6b0e21ccb4c799698645ae28fd3abfa","text":"match target { Some(ref target) if target.shadowable != Shadowable::Always => { let ns_word = match namespace { TypeNS => \"type\", TypeNS => { if let Some(ref ty_def) = *target.bindings.type_def.borrow() { match ty_def.module_def { Some(ref module) if module.kind.get() == ModuleKind::NormalModuleKind => \"module\", Some(ref module) if module.kind.get() == ModuleKind::TraitModuleKind => \"trait\", _ => \"type\", } } else { \"type\" } }, ValueNS => \"value\", }; span_err!(self.resolver.session, import_span, E0252,"} {"_id":"q-en-rust-cc3836db30d79f9e05ebbe8e183e29993a56517e9cb74856b3f8f45d986e7e13","text":"LL | pub fn has_error() -> TypeError {} | ^^^^^^^^^ not found in this scope error: aborting due to 1 previous error error[E0412]: cannot find type `TypeError` in this scope --> $DIR/type-errors.rs:18:29 | LL | pub fn autoderef_source(e: &TypeError) { | ^^^^^^^^^ not found in this scope error[E0412]: cannot find type `TypeError` in this scope --> $DIR/type-errors.rs:23:29 | LL | pub fn autoderef_target(_: &TypeError) {} | ^^^^^^^^^ not found in this scope error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0412`."} {"_id":"q-en-rust-cc69551c7f76c29280a4f16a3097e7882126c95eccdfefbb17e0543732a84fcb","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":"q-en-rust-cc7caa66fd6605546cc92a5d2028150a235c47a452232a2c4a3a50c689c95d1b","text":"name = \"stdbenches\" path = \"benches/lib.rs\" test = true [lints.rust.unexpected_cfgs] level = \"warn\" check-cfg = [ 'cfg(bootstrap)', 'cfg(backtrace_in_libstd)', 'cfg(netbsd10)', 'cfg(target_arch, values(\"xtensa\"))', 'cfg(feature, values(\"std\", \"as_crate\"))', ] "} {"_id":"q-en-rust-ccb2fd5d9ce91091e84710ce56fe85244bdcc4cdc02e3a9929723e65fc1780f4","text":"// SAFETY: left and right must be valid and part of v same for out. unsafe { let to_copy = if is_less(&*right.sub(1), &*left.sub(1)) { decrement_and_get(left) } else { decrement_and_get(right) }; ptr::copy_nonoverlapping(to_copy, decrement_and_get(&mut out), 1); let is_l = is_less(&*right.sub(1), &*left.sub(1)); *left = left.sub(is_l as usize); *right = right.sub(!is_l as usize); let to_copy = if is_l { *left } else { *right }; out = out.sub(1); ptr::copy_nonoverlapping(to_copy, out, 1); } } } // Finally, `hole` gets dropped. If the shorter run was not fully consumed, whatever remains of // it will now be copied into the hole in `v`. unsafe fn get_and_increment(ptr: &mut *mut T) -> *mut T { let old = *ptr; // SAFETY: ptr.add(1) must still be a valid pointer and part of `v`. *ptr = unsafe { ptr.add(1) }; old } unsafe fn decrement_and_get(ptr: &mut *mut T) -> *mut T { // SAFETY: ptr.sub(1) must still be a valid pointer and part of `v`. *ptr = unsafe { ptr.sub(1) }; *ptr } // When dropped, copies the range `start..end` into `dest..`. struct MergeHole { start: *mut T,"} {"_id":"q-en-rust-ccc8df4d0fddd28f0b94612e7daf298c389fb05f2643436d3d32522cf5062fb1","text":"| LL | nc.clone() | ^^ help: consider annotating `NotClone` with `#[derive(Clone)]` | LL | #[derive(Clone)] | error: aborting due to previous error"} {"_id":"q-en-rust-ccce5c158e8c9d2b98adb013eb2b42aa7ca0886d3c4a1091ed94e070619c7604","text":"err.note(\"only the last field of a struct or enum variant may have a dynamically sized type\"); } ObligationCauseCode::ConstSized => { err.note(\"constant expressions must have a statically known size\"); } ObligationCauseCode::SharedStatic => { err.note(\"shared static variables must have a type that implements `Sync`\"); }"} {"_id":"q-en-rust-cce43e4c312594f0c6ac54bb8049891deff25f0eca21c8bc2218848336f2b6ab","text":"let info = Load(bcx, get_len(bcx, base_datum.val)); Store(bcx, info, get_len(bcx, scratch.val)); DatumBlock::new(bcx, scratch.to_expr_datum()) // Always generate an lvalue datum, because this pointer doesn't own // the data and cleanup is scheduled elsewhere. DatumBlock::new(bcx, Datum::new(scratch.val, scratch.ty, LvalueExpr)) } })"} {"_id":"q-en-rust-cd8c876d644952790a1e064a553e8285912bf0fac40b63b238bfa3583b365629","text":"// @has proc_macro/macro.some_proc_macro.html // @has proc_macro/attr.some_proc_attr.html // @has proc_macro/derive.SomeDerive.html pub use some_macros::{some_proc_macro, some_proc_attr, SomeDerive}; // @has proc_macro/macro.some_proc_macro.html // @has - 'a proc-macro that swallows its input and does nothing.' pub use some_macros::some_proc_macro; // @has proc_macro/macro.reexported_macro.html // @has - 'Doc comment from the original crate' pub use some_macros::reexported_macro; // @has proc_macro/attr.some_proc_attr.html // @has - 'a proc-macro attribute that passes its item through verbatim.' pub use some_macros::some_proc_attr; // @has proc_macro/derive.SomeDerive.html // @has - 'a derive attribute that adds nothing to its input.' pub use some_macros::SomeDerive; "} {"_id":"q-en-rust-cdc0c448e2edf11ccebc5a61b31b96b39d2efda07a7bd8425f41225cce84e8c7","text":" error[E0491]: in type `&'static &'a ()`, reference has a longer lifetime than the data it references --> $DIR/rpitit-hidden-types-self-implied-wf-via-param.rs:8:38 | LL | fn extend<'a: 'a>(s: &'a str) -> (Option<&'static &'a ()>, &'static str) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the pointer is valid for the static lifetime note: but the referenced data is only valid for the lifetime `'a` as defined here --> $DIR/rpitit-hidden-types-self-implied-wf-via-param.rs:8:15 | LL | fn extend<'a: 'a>(s: &'a str) -> (Option<&'static &'a ()>, &'static str) | ^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0491`. "} {"_id":"q-en-rust-cddbcf8e472471148da5baaaa83fd15183b37ed20bf51db3da3eef6a078f3dc3","text":" struct X; fn main() {} "} {"_id":"q-en-rust-cde6ace8411e87cafd73e46b72248d819bec28d21a18d33c9eb4bce769808961","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":"q-en-rust-cdea1339b4e3b9ef41fe3acd946579ae330bca542f9bf671a1e95c421fd2523b","text":"//~ TRANS_ITEM fn vtable_through_const::mod1[0]::id[0] @@ vtable_through_const[Internal] mod1::ID_CHAR('x'); } //~ TRANS_ITEM drop-glue i8 "} {"_id":"q-en-rust-ce103fc2ca036e339e174ba33f42a6c6be78e61d9cf865c4efc8fa870b3d9bde","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: --test #![test] //~ ERROR only functions may be used as tests "} {"_id":"q-en-rust-ce18cf9f288fe64ffdd23fb816c0578184f6b218b83004eb9ceddeb4a321c27f","text":"}; } /// Instead of e.g. `vec![a, b, c]` in a pattern context, suggest `[a, b, c]`. fn suggest_slice_pat(e: &mut DiagnosticBuilder<'_>, site_span: Span, parser: &Parser<'_>) { let mut suggestion = None; if let Ok(code) = parser.sess.source_map().span_to_snippet(site_span) { if let Some(bang) = code.find('!') { suggestion = Some(code[bang + 1..].to_string()); } } if let Some(suggestion) = suggestion { e.span_suggestion( site_span, \"use a slice pattern here instead\", suggestion, Applicability::MachineApplicable, ); } else { e.span_label(site_span, \"use a slice pattern here instead\"); } e.help( \"for more information, see https://doc.rust-lang.org/edition-guide/ rust-2018/slice-patterns.html\" ); } impl<'a> ParserAnyMacro<'a> { crate fn make(mut self: Box>, kind: AstFragmentKind) -> AstFragment { let ParserAnyMacro { site_span, macro_ident, ref mut parser, arm_span } = *self;"} {"_id":"q-en-rust-ce4c9847eb3186dccf46ca2a32159d82bca4edcdf0ebb5ad2da2bce56ea3a34b","text":"{ value.fold_with(&mut RegionFolder::new(self, &mut f)) } pub fn super_fold_regions( self, value: T, mut f: impl FnMut(ty::Region<'tcx>, ty::DebruijnIndex) -> ty::Region<'tcx>, ) -> T where T: TypeSuperFoldable>, { value.super_fold_with(&mut RegionFolder::new(self, &mut f)) } } /// Folds over the substructure of a type, visiting its component"} {"_id":"q-en-rust-ce9a9fc0d16ef942cd5682197c2e1bc500a47d79769b8c00e8460514ddcfb1ba","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":"q-en-rust-cea16be22efb14856a365568fd00dc6e99eabc18eb154dce616fbc1295a1f4b1","text":"} if self.config.rust_remap_debuginfo { // FIXME: handle vendored sources let registry_src = t!(home::cargo_home()).join(\"registry\").join(\"src\"); let mut env_var = OsString::new(); for entry in t!(std::fs::read_dir(registry_src)) { if !env_var.is_empty() { env_var.push(\"t\"); } env_var.push(t!(entry).path()); if self.config.vendor { let vendor = self.build.src.join(\"vendor\"); env_var.push(vendor); env_var.push(\"=/rust/deps\"); } else { let registry_src = t!(home::cargo_home()).join(\"registry\").join(\"src\"); for entry in t!(std::fs::read_dir(registry_src)) { if !env_var.is_empty() { env_var.push(\"t\"); } env_var.push(t!(entry).path()); env_var.push(\"=/rust/deps\"); } } cargo.env(\"RUSTC_CARGO_REGISTRY_SRC_TO_REMAP\", env_var); }"} {"_id":"q-en-rust-ceec1e8b8253e908cf2b46af2edfd9c68cd49ebb7b9197d59ab3f02ec58c011f","text":" #![u={static N;}] fn main() {} "} {"_id":"q-en-rust-cf100235c30192ffe1b5222a70c42da3eb37432e6315d31e78ede2ac1319c895","text":" // Regression test for #61311 // We would ICE after failing to normalize `Self::Proj` in the `impl` below. // compile-pass pub struct Unit; trait Obj {} trait Bound {} impl Bound for Unit {} pub trait HasProj { type Proj; } impl HasProj for T { type Proj = Unit; } trait HasProjFn { type Proj; fn the_fn(_: Self::Proj); } impl HasProjFn for Unit where Box: HasProj, as HasProj>::Proj: Bound, { type Proj = Unit; fn the_fn(_: Self::Proj) {} } fn main() {} "} {"_id":"q-en-rust-cf51c2c6c90c4e6a862dd918ec1ab74b0b0bbd5a006c57990abbea8018db12f0","text":"'u{2004}', 'u{2005}', 'u{2006}', 'u{2007}', 'u{2008}', 'u{2009}', 'u{200A}', 'u{2028}', 'u{2029}', 'u{202F}', 'u{205F}', 'u{3000}']; for c in &chars { let ws = c.is_whitespace(); println!(\"{} {}\" , c , ws); } for c in &chars { let ws = c.is_whitespace(); println!(\"{} {}\", c, ws); } }"} {"_id":"q-en-rust-cf5e7ac7ec96d14e6e0c19a2169041e34ae8e7847a421f893faffa08161eb55c","text":"AWS_SECRET_ACCESS_KEY: $(AWS_SECRET_ACCESS_KEY) condition: and(succeeded(), or(eq(variables.DEPLOY, '1'), eq(variables.DEPLOY_ALT, '1'))) displayName: Upload artifacts # Upload CPU usage statistics that we've been gathering this whole time. Always # execute this step in case we want to inspect failed builds, but don't let # errors here ever fail the build since this is just informational. - bash: aws s3 cp --acl public-read cpu-usage.csv s3://$DEPLOY_BUCKET/rustc-builds/$BUILD_SOURCEVERSION/cpu-$SYSTEM_JOBNAME.csv env: AWS_SECRET_ACCESS_KEY: $(AWS_SECRET_ACCESS_KEY) condition: contains(variables, 'AWS_SECRET_ACCESS_KEY') continueOnError: true displayName: Upload CPU usage statistics "} {"_id":"q-en-rust-cfbf5588240745e979c68459184d41d17d2ce1c428ea99773b0b91c04111c304","text":" // Regression test for issue #130142 // Checks that we emit no warnings when a lint's level // is overridden by an expect or allow attr on a Stmt node //@ check-pass #[must_use] pub fn must_use_result() -> i32 { 42 } fn main() { #[expect(unused_must_use)] must_use_result(); #[allow(unused_must_use)] must_use_result(); } "} {"_id":"q-en-rust-cfdeb2c0fc4c4ecee87eeebeaa6303add49a56f6a1811bf93ce48e11a321e89f","text":"} let feed_visibility = |this: &mut Self, def_id| { let vis = this.r.tcx.visibility(def_id).expect_local(); let vis = this.r.tcx.visibility(def_id); let vis = if vis.is_visible_locally() { vis.expect_local() } else { this.r.dcx().span_delayed_bug( span, \"error should be emitted when an unexpected trait item is used\", ); rustc_middle::ty::Visibility::Public }; this.r.feed_visibility(this.r.local_def_id(id), vis); };"} {"_id":"q-en-rust-cfe44de9b0745542520c7908aadb43f0f9abdefeaa4f9770609b534b08188ea4","text":" // unit-test: Inline // compile-flags: --crate-type=lib -C panic=abort use std::any::Any; use std::any::TypeId; struct A { a: i32, b: T, } // EMIT_MIR dont_inline_type_id.call.Inline.diff pub fn call(s: &T) -> TypeId { s.type_id() } "} {"_id":"q-en-rust-cffbbb8958114606fc157e0632ee851c663ff976043b56ec8c1d892294932b3f","text":"#[inline] unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { // See the comment above in `alloc` for why this check looks the way it does. if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { libc::calloc(layout.size(), 1) as *mut u8 } else {"} {"_id":"q-en-rust-d018f0aab1c7fe2ecb9df4909e37e1ac17b7ba2e77a4ada893791bf3dac73572","text":" //@ edition:2021 macro_rules! a { ( ) => { impl<'b> c for d { e:: //~ ERROR prefix `f` is unknown } }; } fn main() {} "} {"_id":"q-en-rust-d02585d4c91f649add471d54edac21ca1e92f92bc2c0d0ce1d5caa3f4fa38c53","text":"Ok(pat) } /// Recover from a typoed `...` pattern that was encountered /// Ref: Issue #70388 fn recover_dotdotdot_rest_pat(&mut self, lo: Span) -> PatKind { // A typoed rest pattern `...`. self.bump(); // `...` // The user probably mistook `...` for a rest pattern `..`. self.struct_span_err(lo, \"unexpected `...`\") .span_label(lo, \"not a valid pattern\") .span_suggestion_short( lo, \"for a rest pattern, use `..` instead of `...`\", \"..\".to_owned(), Applicability::MachineApplicable, ) .emit(); PatKind::Rest } /// Try to recover the more general form `intersect ::= $pat_lhs @ $pat_rhs`. /// /// Allowed binding patterns generated by `binding ::= ref? mut? $ident @ $pat_rhs`"} {"_id":"q-en-rust-d07663c956878d5df7595833c80220e28fc8a1c460e3b4b8a447216da0d48081","text":"// Change value between simple literals --------------------------------------- #[cfg(cfail1)] const CONST_CHANGE_VALUE_1: i16 = 1; #[cfg(not(cfail1))] #[rustc_clean(cfg=\"cfail2\", except=\"HirBody\")] #[rustc_clean(cfg=\"cfail3\")] #[rustc_metadata_clean(cfg=\"cfail3\")] const CONST_CHANGE_VALUE_1: i16 = 2; const CONST_CHANGE_VALUE_1: i16 = { #[cfg(cfail1)] { 1 } #[cfg(not(cfail1))] { 2 } }; // Change value between expressions ------------------------------------------- #[cfg(cfail1)] const CONST_CHANGE_VALUE_2: i16 = 1 + 1; #[cfg(not(cfail1))] // Change value between expressions ------------------------------------------- #[rustc_clean(cfg=\"cfail2\", except=\"HirBody\")] #[rustc_clean(cfg=\"cfail3\")] #[rustc_metadata_dirty(cfg=\"cfail2\")] #[rustc_metadata_clean(cfg=\"cfail3\")] const CONST_CHANGE_VALUE_2: i16 = 1 + 2; const CONST_CHANGE_VALUE_2: i16 = { #[cfg(cfail1)] { 1 + 1 } #[cfg(cfail1)] const CONST_CHANGE_VALUE_3: i16 = 2 + 3; #[cfg(not(cfail1))] { 1 + 2 } }; #[cfg(not(cfail1))] #[rustc_clean(cfg=\"cfail2\", except=\"HirBody\")] #[rustc_clean(cfg=\"cfail3\")] #[rustc_metadata_dirty(cfg=\"cfail2\")] #[rustc_metadata_clean(cfg=\"cfail3\")] const CONST_CHANGE_VALUE_3: i16 = 2 * 3; const CONST_CHANGE_VALUE_3: i16 = { #[cfg(cfail1)] { 2 + 3 } #[cfg(cfail1)] const CONST_CHANGE_VALUE_4: i16 = 1 + 2 * 3; #[cfg(not(cfail1))] { 2 * 3 } }; #[cfg(not(cfail1))] #[rustc_clean(cfg=\"cfail2\", except=\"HirBody\")] #[rustc_clean(cfg=\"cfail3\")] #[rustc_metadata_dirty(cfg=\"cfail2\")] #[rustc_metadata_clean(cfg=\"cfail3\")] const CONST_CHANGE_VALUE_4: i16 = 1 + 2 * 4; const CONST_CHANGE_VALUE_4: i16 = { #[cfg(cfail1)] { 1 + 2 * 3 } #[cfg(not(cfail1))] { 1 + 2 * 4 } }; // Change type indirectly -----------------------------------------------------"} {"_id":"q-en-rust-d083f3b2f68de83cc8e3fd4ec2a66150b24fe91bfd661296c9f05018f50284c4","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. // ignore-tidy-linelength // compile-flags: -g --remap-path-prefix={{cwd}}=/the/aux-cwd --remap-path-prefix={{src-base}}/remap_path_prefix/auxiliary=/the/aux-src #![crate_type = \"lib\"] pub fn foo() {} "} {"_id":"q-en-rust-d0aecdfa32e9195b8a94ef3324e6772d716c6153ad3cac62e11b4677ed7becf0","text":" error[E0531]: cannot find tuple struct or tuple variant `Cons` in this scope --> $DIR/issue-90113.rs:17:9 | LL | Cons(..) => {} | ^^^^ not found in this scope | help: consider importing this tuple variant | LL | use list::List::Cons; | error: aborting due to previous error For more information about this error, try `rustc --explain E0531`. "} {"_id":"q-en-rust-d0d7aaf5bf9bbdeb3428e64d1985685c1b98d038c3b20f90c730030e733b3ae7","text":"/// assert_eq!(*x, 1); /// ``` #[inline] #[unstable(feature = \"mutex_unpoison\", issue = \"96469\")] #[stable(feature = \"mutex_unpoison\", since = \"CURRENT_RUSTC_VERSION\")] pub fn clear_poison(&self) { self.poison.clear(); }"} {"_id":"q-en-rust-d14d960b76f1b7eb4c271348f75a12ee93858e29f15cefdf92892d391f287879","text":"fn main() { macro_rules! test { ($($fn_name:ident,)*) => { $( ($($fn_name:expr,)*) => { $( test_future_yields_once_then_returns($fn_name); )* } } macro_rules! test_with_borrow { ($($fn_name:expr,)*) => { $( test_future_yields_once_then_returns(|x| { async move { await!($fn_name(&x)) } }); )* } } test! { async_block, async_nonmove_block, async_closure, async_fn, async_fn_with_internal_borrow, |x| { async move { unsafe { await!(unsafe_async_fn(x)) } } }, } test_with_borrow! { async_block_with_borrow_named_lifetime, async_fn_with_borrow, async_fn_with_borrow_named_lifetime, async_fn_with_impl_future_named_lifetime, |x| { async move { await!(async_fn_with_named_lifetime_multiple_args(x, x)) } }, } }"} {"_id":"q-en-rust-d1654db1f504e9dc54d8b9eb97edcae0b2aebff751f28f635ce82a144d1f0da0","text":" error[E0597]: `a` does not live long enough --> $DIR/location-insensitive-scopes-issue-117146.rs:10:18 | LL | let b = |_| &a; | --- -^ | | || | | |borrowed value does not live long enough | | returning this value requires that `a` is borrowed for `'static` | value captured here ... LL | } | - `a` dropped here while still borrowed | note: due to current limitations in the borrow checker, this implies a `'static` lifetime --> $DIR/location-insensitive-scopes-issue-117146.rs:20:22 | LL | fn bad &()>(_: F) {} | ^^^ error: implementation of `Fn` is not general enough --> $DIR/location-insensitive-scopes-issue-117146.rs:13:5 | LL | bad(&b); | ^^^^^^^ implementation of `Fn` is not general enough | = note: closure with signature `fn(&'2 ()) -> &()` must implement `Fn<(&'1 (),)>`, for any lifetime `'1`... = note: ...but it actually implements `Fn<(&'2 (),)>`, for some specific lifetime `'2` error: implementation of `FnOnce` is not general enough --> $DIR/location-insensitive-scopes-issue-117146.rs:13:5 | LL | bad(&b); | ^^^^^^^ implementation of `FnOnce` is not general enough | = note: closure with signature `fn(&'2 ()) -> &()` must implement `FnOnce<(&'1 (),)>`, for any lifetime `'1`... = note: ...but it actually implements `FnOnce<(&'2 (),)>`, for some specific lifetime `'2` error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0597`. "} {"_id":"q-en-rust-d18fd7e278b9abf554a18bb410b5712cf61605e93a68203705164daa028d8646","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":"q-en-rust-d1b500d207e744695b146396f03e7ee83a723b8db15d9b2c5cedc116a143cc05","text":"PYTHONPATH=\"$PYTHONPATH:$GDB_PYTHON_MODULE_DIRECTORY\" exec ${RUST_GDB} --directory=\"$GDB_PYTHON_MODULE_DIRECTORY\" -iex \"add-auto-load-safe-path $GDB_PYTHON_MODULE_DIRECTORY\" -iex \"set substitute-path /rustc/$RUSTC_COMMIT_HASH $RUSTC_SYSROOT/lib/rustlib/src/rust\" \"$@\" No newline at end of file"} {"_id":"q-en-rust-d1b8d11ec80d60462180765dc9e6c9e72e66ae44a8b1fc633e9281bd544afbc0","text":"initial_res: Option, res: Res| { if let Some(initial_res) = initial_res { if res != initial_res && res != Res::Err && this.ambiguity_errors.is_empty() { if res != initial_res { // Make sure compilation does not succeed if preferred macro resolution // has changed after the macro had been expanded. In theory all such // situations should be reported as ambiguity errors, so this is a bug. span_bug!(span, \"inconsistent resolution for a macro\"); // situations should be reported as errors, so this is a bug. this.session.delay_span_bug(span, \"inconsistent resolution for a macro\"); } } else { // It's possible that the macro was unresolved (indeterminate) and silently"} {"_id":"q-en-rust-d1e1e7a08674cc951ed20a04619ef1021891dd902827e631f369b11b2ae42f2c","text":" // aux-build:drop-shim-relates-opaque-aux.rs // compile-flags: -Zvalidate-mir --crate-type=lib // build-pass extern crate drop_shim_relates_opaque_aux; pub fn drop_foo(_: drop_shim_relates_opaque_aux::Foo) {} pub fn drop_bar(_: drop_shim_relates_opaque_aux::Bar) {} fn main() {} "} {"_id":"q-en-rust-d210189ab61e3e2450fbc983f2df7ae464326f9428dcd4e470271e8f78d420f5","text":" // compile-flags:--test /// A check of using various process termination strategies /// /// # Examples /// /// ```rust /// assert!(true); // this returns `()`, all is well /// ``` /// /// You can also simply return `Ok(())`, but you'll need to disambiguate the /// type using turbofish, because we cannot infer the type: /// /// ```rust /// Ok::<(), &'static str>(()) /// ``` /// /// You can err with anything that implements `Debug`: /// /// ```rust,should_panic /// Err(\"This is returned from `main`, leading to panic\")?; /// Ok::<(), &'static str>(()) /// ``` pub fn check_process_termination() {} "} {"_id":"q-en-rust-d222d8575c3ced3ddac6604617b3654fb2eed8b3bac38f58ec40cffdf48b9cf9","text":" #![feature(return_position_impl_trait_in_trait)] trait Iterable { type Item<'a> where Self: 'a; fn iter(&self) -> impl Iterator>; //~^ ERROR use of undeclared lifetime name `'missing` } fn main() {} "} {"_id":"q-en-rust-d2507e5768d906dfa51e17f785c27c1a9b2af95ed335bd1ff616062b877167f2","text":"out_filenames.push(out_filename); } if sess.opts.cg.save_temps { let _ = tmpdir.into_path(); } out_filenames }"} {"_id":"q-en-rust-d250c94e9c516a5b43662d33930f11a116acb34cd8915a9bc6d6cb938b4f1cdc","text":"passes.into_iter().collect(), css_file_extension, renderinfo, render_type) render_type, sort_modules_alphabetically) .expect(\"failed to generate documentation\"); 0 }"} {"_id":"q-en-rust-d296c234168087a8bd6bc856cf19738c9e82f077ad3ebc19e1d7f6d87e4bb982","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":"q-en-rust-d2d8b203972fa91b00353a7c7d62faf0f339783cb49262235a0ebd9f5fcbd190","text":"use crate::fluent_generated as fluent; use crate::parser; use crate::parser::attr::InnerAttrPolicy; use rustc_ast as ast; use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind};"} {"_id":"q-en-rust-d2d94eb4a2984758de08554754a06472ba3957b9a8a1b394a49c570f049e38af","text":" error[E0599]: no function or associated item named `mew` found for struct `Vec` in the current scope --> $DIR/bad-builder.rs:2:15 | LL | Vec::::mew() | ^^^ | | | function or associated item not found in `Vec` | help: there is an associated function with a similar name: `new` | note: if you're trying to build a new `Vec` consider using one of the following associated functions: Vec::::new Vec::::with_capacity Vec::::from_raw_parts Vec::::new_in and 2 others --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0599`. "} {"_id":"q-en-rust-d3030cf94810c0e28018e8ea068879f3230fa368a57f09b25d95404adfce76fa","text":" #![allow(incomplete_features)] #![feature(generic_const_exprs)] #![feature(trait_alias)] trait Bar {} trait BB = Bar<{ 2 + 1 }>; fn foo(x: &dyn BB) {} //~^ ERROR the trait alias `BB` cannot be made into an object [E0038] fn main() {} "} {"_id":"q-en-rust-d31a95ef718f0ca6d18b9fbcd5b52abc62cbff075f2d8fa040900bf23322e60a","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":"q-en-rust-d33dae8115062bcd8f458fafc13d9bd23761aae01449135c883169ca2f6de687","text":" error: `start` language item function is not allowed to have `#[target_feature]` --> $DIR/start_lang_item_with_target_feature.rs:13:1 | LL | #[target_feature(enable = \"avx2\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | LL | fn start(_main: fn() -> T, _argc: isize, _argv: *const *const u8, _sigpipe: u8) -> isize { | ------------------------------------------------------------------------------------------- `start` language item function is not allowed to have `#[target_feature]` error: aborting due to previous error "} {"_id":"q-en-rust-d3553e1c18c24da8fd4bf785335b167c626710a0f472a3484322cb7d9c2ceeaf","text":"{ debug!(?obligation, \"confirm_fn_pointer_candidate\"); // Okay to skip binder; it is reintroduced below. let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder()); let self_ty = self .infcx .shallow_resolve(obligation.self_ty().no_bound_vars()) .expect(\"fn pointer should not capture bound vars from predicate\"); let sig = self_ty.fn_sig(self.tcx()); let trait_ref = closure_trait_ref_and_return_type( self.tcx(),"} {"_id":"q-en-rust-d3b4ab2817b051432764410372f06757d87ff82e80fbfb0bc8b36b46de6a4ed6","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 foo::baz; use bar::baz; //~ ERROR a module named `baz` has already been imported use foo::Quux; use bar::Quux; //~ ERROR a trait named `Quux` has already been imported use foo::blah; use bar::blah; //~ ERROR a type named `blah` has already been imported use foo::WOMP; use bar::WOMP; //~ ERROR a value named `WOMP` has already been imported fn main() {} mod foo { pub mod baz {} pub trait Quux { } pub type blah = (f64, u32); pub const WOMP: u8 = 5; } mod bar { pub mod baz {} pub type Quux = i32; struct blah { x: i8 } pub const WOMP: i8 = -5; } "} {"_id":"q-en-rust-d43d198445a768013215536077db097a35c5266b2bdb1d15a53b42cbac22e4c7","text":"let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap(); let impl_trait_ref = tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap().instantiate_identity(); let param_env = tcx.param_env(impl_m_def_id); // First, check a few of the same things as `compare_impl_method`, // just so we don't ICE during substitution later. check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;"} {"_id":"q-en-rust-d45e18504f7fb56a6d602dd01cb85faeb374ec4a6bd6c6171be819427597ae53","text":"ENV RUST_CONFIGURE_ARGS --enable-extended --disable-docs ENV SCRIPT python2.7 ../x.py dist --host $HOSTS --target $HOSTS # FIXME(#36150) this will fail the bootstrap. Probably means something bad is # happening! ENV NO_LLVM_ASSERTIONS 1 "} {"_id":"q-en-rust-d485b68aecc027e13818c1f565d410ed64979746064d00f684bd3cc59e06b104","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":"q-en-rust-d4ba6b1d46076aa19a624bd54e3d2630eacb7821e1b9d7706fa83cb943e7b396","text":"//! [`PathBuf`]; note that the paths may differ syntactically by the //! normalization described in the documentation for the [`components`] method. //! //! ## Case sensitivity //! //! Unless otherwise indicated path methods that do not access the filesystem, //! such as [`Path::starts_with`] and [`Path::ends_with`], are case sensitive no //! matter the platform or filesystem. An exception to this is made for Windows //! drive letters. //! //! ## Simple usage //! //! Path manipulation includes both parsing components from slices and building"} {"_id":"q-en-rust-d4ce3545c5901bb881591dbb64de2c723a31a1958af51f81191bc2031d9b0f6f","text":"match expr.node { ast::ExprField(ref base, ident) => { if let ty::ty_struct(id, _) = ty::expr_ty_adjusted(self.tcx, &**base).sty { self.check_field(expr.span, id, NamedField(ident.node)); self.check_field(expr.span, id, NamedField(ident.node.name)); } } ast::ExprTupField(ref base, idx) => {"} {"_id":"q-en-rust-d4f00b74c9c6eeb988d62688c80db79acbf29c34c27c0461f309028c87b32371","text":"panic!(); } #[test] fn panic_in_write_doesnt_flush_in_drop() { static WRITES: AtomicUsize = AtomicUsize::new(0); struct PanicWriter; impl Write for PanicWriter { fn write(&mut self, _: &[u8]) -> io::Result { WRITES.fetch_add(1, Ordering::SeqCst); panic!(); } fn flush(&mut self) -> io::Result<()> { Ok(()) } } thread::spawn(|| { let mut writer = BufWriter::new(PanicWriter); writer.write(b\"hello world\"); writer.flush(); }).join().err().unwrap(); assert_eq!(WRITES.load(Ordering::SeqCst), 1); } #[bench] fn bench_buffered_reader(b: &mut test::Bencher) { b.iter(|| {"} {"_id":"q-en-rust-d51a1e608437a95bb1e11700dcd4efb444ba2f3fc2d232940a2e2d1668db58db","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":"q-en-rust-d5759d475a893188756bac7ddcd5515b24b8e1994fb555344eb60ddf695b1ecf","text":"| |_____| | || LL | || LL | || LL | || use std::ptr::null; LL | || use std::task::{Context, RawWaker, RawWakerVTable, Waker}; ... || LL | || drop(cx_ref); LL | || }); | ||_____-^ `&mut Context<'_>` may not be safely transferred across an unwind boundary | |_____| | within this `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}` | within this `{async block@$DIR/async-is-unwindsafe.rs:12:19: 29:6}` | = help: within `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}`, the trait `UnwindSafe` is not implemented for `&mut Context<'_>`, which is required by `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}: UnwindSafe` = help: within `{async block@$DIR/async-is-unwindsafe.rs:12:19: 29:6}`, the trait `UnwindSafe` is not implemented for `&mut Context<'_>`, which is required by `{async block@$DIR/async-is-unwindsafe.rs:12:19: 29:6}: UnwindSafe` = note: `UnwindSafe` is implemented for `&Context<'_>`, but not for `&mut Context<'_>` note: future does not implement `UnwindSafe` as this value is used across an await --> $DIR/async-is-unwindsafe.rs:26:18 --> $DIR/async-is-unwindsafe.rs:25:18 | LL | let cx_ref = &mut cx; | ------ has type `&mut Context<'_>` which does not implement `UnwindSafe`"} {"_id":"q-en-rust-d59f032aa8dfb920401f196b28b8b9a7e1885947a134bf877c7e31369c71604e","text":"Some(&def::DefVariant(_, variant_id, _)) => { for field in fields { self.check_field(pattern.span, variant_id, NamedField(field.node.ident)); NamedField(field.node.ident.name)); } } _ => self.tcx.sess.span_bug(pattern.span,"} {"_id":"q-en-rust-d614942aa4e737dbbd9da257ae6155c69f597cb5039b2938495dc8677098511e","text":"/// /// assert_eq!(n.leading_zeros(), 2); /// ``` #[doc = concat!(\"[`ilog2`]: \", stringify!($SelfT), \"::ilog2\")] #[stable(feature = \"rust1\", since = \"1.0.0\")] #[rustc_const_stable(feature = \"const_math\", since = \"1.32.0\")] #[must_use = \"this returns the result of the operation, "} {"_id":"q-en-rust-d6555ca75d9341c03aace7b0807ccce581ed5bdba82babe431bd2557da5c29a9","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":"q-en-rust-d67857dab8f253574844f52df928d802a2948b2563075ca15ee9c1396b54235b","text":"Attribute::NoInline.apply_llfn(Function, val); } } None if requires_inline => Attribute::InlineHint.apply_llfn(Function, val), None => {} }; }"} {"_id":"q-en-rust-d68027bab430ab594ab7a2efe336213d346ab76125a88c6b35516362cdd03ff3","text":" // Regression test for #89606. Used to ICE. // // check-pass // revisions: twenty_eighteen twenty_twentyone // [twenty_eighteen]compile-flags: --edition 2018 // [twenty_twentyone]compile-flags: --edition 2021 struct S<'a>(Option<&'a mut i32>); fn by_ref(s: &mut S<'_>) { (|| { let S(_o) = s; s.0 = None; })(); } fn by_value(s: S<'_>) { (|| { let S(ref _o) = s; let _g = s.0; })(); } struct V<'a>((Option<&'a mut i32>,)); fn nested(v: &mut V<'_>) { (|| { let V((_o,)) = v; v.0 = (None, ); })(); } fn main() { let mut s = S(None); by_ref(&mut s); by_value(s); let mut v = V((None, )); nested(&mut v); } "} {"_id":"q-en-rust-d6a0381a381c8485eb907dfdbd34eaf7b23fc7512fc032b902fc8800729ac3f6","text":"use rustc_span::edition::Edition; use rustc_span::lev_distance::find_best_match_for_name; use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use rustc_span::Span; use rustc_target::spec::abi; use rustc_trait_selection::traits; use rustc_trait_selection::traits::astconv_object_safety_violations;"} {"_id":"q-en-rust-d6ad85ee96a6829b8e90c96ae2dec2cd8bded57f9bc7d2e986f7d5adb7ca7c52","text":"\"anyhow\", \"cargo\", \"cargo-util\", \"cargo_metadata 0.12.0\", \"cargo_metadata 0.14.0\", \"clippy_lints\", \"crossbeam-channel\", \"difference\", \"env_logger 0.7.1\", \"env_logger 0.9.0\", \"futures 0.3.12\", \"heck\", \"home\", \"itertools 0.9.0\", \"itertools 0.10.1\", \"jsonrpc-core\", \"lazy_static\", \"log\","} {"_id":"q-en-rust-d6e017382a17f78416587dc0b26dc561d1f34bcec37d8276e3a2c26298695c59","text":" // ignore-tidy-filelength //! Error Reporting Code for the inference engine //! //! Because of the way inference, and in particular region inference,"} {"_id":"q-en-rust-d6f88d92afc0da0a5b73859707cbe4e342ae0b992e30cb07463570941ca9b2c8","text":"Err(err) } pub(super) fn attr_on_non_tail_expr(&self, expr: &Expr) { // Missing semicolon typo error. let span = self.prev_token.span.shrink_to_hi(); let mut err = self.sess.create_err(ExpectedSemi { span, token: self.token.clone(), unexpected_token_label: Some(self.token.span), sugg: ExpectedSemiSugg::AddSemi(span), }); let attr_span = match &expr.attrs[..] { [] => unreachable!(), [only] => only.span, [first, rest @ ..] => { for attr in rest { err.span_label(attr.span, \"\"); } first.span } }; err.span_label( attr_span, format!( \"only `;` terminated statements or tail expressions are allowed after {}\", if expr.attrs.len() == 1 { \"this attribute\" } else { \"these attributes\" }, ), ); if self.token == token::Pound && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Bracket)) { // We have // #[attr] // expr // #[not_attr] // other_expr err.span_label(span, \"expected `;` here\"); err.multipart_suggestion( \"alternatively, consider surrounding the expression with a block\", vec![ (expr.span.shrink_to_lo(), \"{ \".to_string()), (expr.span.shrink_to_hi(), \" }\".to_string()), ], Applicability::MachineApplicable, ); let mut snapshot = self.create_snapshot_for_diagnostic(); if let [attr] = &expr.attrs[..] && let ast::AttrKind::Normal(attr_kind) = &attr.kind && let [segment] = &attr_kind.item.path.segments[..] && segment.ident.name == sym::cfg && let Ok(next_attr) = snapshot.parse_attribute(InnerAttrPolicy::Forbidden(None)) && let ast::AttrKind::Normal(next_attr_kind) = next_attr.kind && let [next_segment] = &next_attr_kind.item.path.segments[..] && segment.ident.name == sym::cfg && let Ok(next_expr) = snapshot.parse_expr() { // We have for sure // #[cfg(..)] // expr // #[cfg(..)] // other_expr // So we suggest using `if cfg!(..) { expr } else if cfg!(..) { other_expr }`. let margin = self.sess.source_map().span_to_margin(next_expr.span).unwrap_or(0); let sugg = vec![ (attr.span.with_hi(segment.span().hi()), \"if cfg!\".to_string()), ( attr_kind.item.args.span().unwrap().shrink_to_hi().with_hi(attr.span.hi()), \" {\".to_string(), ), (expr.span.shrink_to_lo(), \" \".to_string()), ( next_attr.span.with_hi(next_segment.span().hi()), \"} else if cfg!\".to_string(), ), ( next_attr_kind .item .args .span() .unwrap() .shrink_to_hi() .with_hi(next_attr.span.hi()), \" {\".to_string(), ), (next_expr.span.shrink_to_lo(), \" \".to_string()), (next_expr.span.shrink_to_hi(), format!(\"n{}}}\", \" \".repeat(margin))), ]; err.multipart_suggestion( \"it seems like you are trying to provide different expressions depending on `cfg`, consider using `if cfg!(..)`\", sugg, Applicability::MachineApplicable, ); } } err.emit(); } fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool { let sm = self.sess.source_map(); match (&self.prev_token.kind, &self.token.kind) {"} {"_id":"q-en-rust-d756f1004d0524a0432aeefcc11c7704e03624a989a2f440007212f39b9d44fe","text":"all(target_vendor = \"fortanix\", target_env = \"sgx\") ) ))] mod doc { // On certain platforms right now the \"main modules\" modules that are // documented don't compile (missing things in `libc` which is empty), // so just omit them with an empty module. #[unstable(issue = \"none\", feature = \"std_internals\")] pub mod unix {} #[unstable(issue = \"none\", feature = \"std_internals\")] pub mod linux {} #[unstable(issue = \"none\", feature = \"std_internals\")] pub mod wasi {} #[unstable(issue = \"none\", feature = \"std_internals\")] pub mod windows {} } #[cfg(doc)] #[stable(feature = \"os\", since = \"1.0.0\")] pub use doc::*; #[cfg(not(doc))] #[path = \".\"] mod imp { // If we're not documenting std then we only expose modules appropriate for the // current platform. #[cfg(all(target_vendor = \"fortanix\", target_env = \"sgx\"))] pub mod fortanix_sgx; #[cfg(target_os = \"hermit\")] #[path = \"hermit/mod.rs\"] pub mod unix; #[unstable(issue = \"none\", feature = \"std_internals\")] pub mod linux {} #[cfg(all( doc, any( all(target_arch = \"wasm32\", not(target_os = \"wasi\")), all(target_vendor = \"fortanix\", target_env = \"sgx\") ) ))] #[unstable(issue = \"none\", feature = \"std_internals\")] pub mod wasi {} #[cfg(all( doc, any( all(target_arch = \"wasm32\", not(target_os = \"wasi\")), all(target_vendor = \"fortanix\", target_env = \"sgx\") ) ))] #[unstable(issue = \"none\", feature = \"std_internals\")] pub mod windows {} #[cfg(target_os = \"android\")] pub mod android; #[cfg(target_os = \"dragonfly\")] pub mod dragonfly; #[cfg(target_os = \"emscripten\")] pub mod emscripten; #[cfg(target_os = \"espidf\")] pub mod espidf; #[cfg(target_os = \"freebsd\")] pub mod freebsd; #[cfg(target_os = \"fuchsia\")] pub mod fuchsia; #[cfg(target_os = \"haiku\")] pub mod haiku; #[cfg(target_os = \"illumos\")] pub mod illumos; #[cfg(target_os = \"ios\")] pub mod ios; #[cfg(target_os = \"l4re\")] pub mod linux; #[cfg(target_os = \"linux\")] pub mod linux; #[cfg(target_os = \"macos\")] pub mod macos; #[cfg(target_os = \"netbsd\")] pub mod netbsd; #[cfg(target_os = \"openbsd\")] pub mod openbsd; #[cfg(target_os = \"redox\")] pub mod redox; #[cfg(target_os = \"solaris\")] pub mod solaris; #[cfg(unix)] pub mod unix; // unix #[cfg(not(all( doc, any( all(target_arch = \"wasm32\", not(target_os = \"wasi\")), all(target_vendor = \"fortanix\", target_env = \"sgx\") ) )))] #[cfg(target_os = \"hermit\")] #[path = \"hermit/mod.rs\"] pub mod unix; #[cfg(not(all( doc, any( all(target_arch = \"wasm32\", not(target_os = \"wasi\")), all(target_vendor = \"fortanix\", target_env = \"sgx\") ) )))] #[cfg(all(not(target_os = \"hermit\"), any(unix, doc)))] pub mod unix; #[cfg(target_os = \"vxworks\")] pub mod vxworks; // linux #[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 = \"l4re\", doc))] pub mod linux; #[cfg(target_os = \"wasi\")] pub mod wasi; // wasi #[cfg(not(all( doc, any( all(target_arch = \"wasm32\", not(target_os = \"wasi\")), all(target_vendor = \"fortanix\", target_env = \"sgx\") ) )))] #[cfg(any(target_os = \"wasi\", doc))] pub mod wasi; #[cfg(windows)] pub mod windows; } #[cfg(not(doc))] #[stable(feature = \"os\", since = \"1.0.0\")] pub use imp::*; // windows #[cfg(not(all( doc, any( all(target_arch = \"wasm32\", not(target_os = \"wasi\")), all(target_vendor = \"fortanix\", target_env = \"sgx\") ) )))] #[cfg(any(windows, doc))] pub mod windows; // Others. #[cfg(target_os = \"android\")] pub mod android; #[cfg(target_os = \"dragonfly\")] pub mod dragonfly; #[cfg(target_os = \"emscripten\")] pub mod emscripten; #[cfg(target_os = \"espidf\")] pub mod espidf; #[cfg(all(target_vendor = \"fortanix\", target_env = \"sgx\"))] pub mod fortanix_sgx; #[cfg(target_os = \"freebsd\")] pub mod freebsd; #[cfg(target_os = \"fuchsia\")] pub mod fuchsia; #[cfg(target_os = \"haiku\")] pub mod haiku; #[cfg(target_os = \"illumos\")] pub mod illumos; #[cfg(target_os = \"ios\")] pub mod ios; #[cfg(target_os = \"macos\")] pub mod macos; #[cfg(target_os = \"netbsd\")] pub mod netbsd; #[cfg(target_os = \"openbsd\")] pub mod openbsd; #[cfg(target_os = \"redox\")] pub mod redox; #[cfg(target_os = \"solaris\")] pub mod solaris; #[cfg(target_os = \"vxworks\")] pub mod vxworks; #[cfg(any(unix, target_os = \"wasi\", doc))] mod fd;"} {"_id":"q-en-rust-d785c769298bdb600eed6bedfdaed6917c40d14804c9fb2b7e0c3973ec00194c","text":"self.as_operand(block, local_scope, expr) } /// Returns an operand suitable for use until the end of the current scope expression and /// suitable also to be passed as function arguments. /// /// The operand returned from this function will *not be valid* after an ExprKind::Scope is /// passed, so please do *not* return it from functions to avoid bad miscompiles. Returns an /// operand suitable for use as a call argument. This is almost always equivalent to /// `as_operand`, except for the particular case of passing values of (potentially) unsized /// types \"by value\" (see details below). /// /// The operand returned from this function will *not be valid* /// after the current enclosing `ExprKind::Scope` has ended, so /// please do *not* return it from functions to avoid bad /// miscompiles. /// /// # Parameters of unsized types /// /// We tweak the handling of parameters of unsized type slightly to avoid the need to create a /// local variable of unsized type. For example, consider this program: /// /// ```rust /// fn foo(p: dyn Debug) { ... } /// /// fn bar(box_p: Box) { foo(*p); } /// ``` /// /// Ordinarily, for sized types, we would compile the call `foo(*p)` like so: /// /// ```rust /// let tmp0 = *box_p; // tmp0 would be the operand returned by this function call /// foo(tmp0) /// ``` /// /// But because the parameter to `foo` is of the unsized type `dyn Debug`, and because it is /// being moved the deref of a box, we compile it slightly differently. The temporary `tmp0` /// that we create *stores the entire box*, and the parameter to the call itself will be /// `*tmp0`: /// /// ```rust /// let tmp0 = box_p; call foo(*tmp0) /// ``` /// /// This way, the temporary `tmp0` that we create has type `Box`, which is sized. /// The value passed to the call (`*tmp0`) still has the `dyn Debug` type -- but the way that /// calls are compiled means that this parameter will be passed \"by reference\", meaning that we /// will actually provide a pointer to the interior of the box, and not move the `dyn Debug` /// value to the stack. /// /// See #68034 for more details. crate fn as_local_call_operand( &mut self, block: BasicBlock, expr: M, ) -> BlockAnd> where M: Mirror<'tcx, Output = Expr<'tcx>>, { let local_scope = self.local_scope(); self.as_call_operand(block, local_scope, expr) } /// Compile `expr` into a value that can be used as an operand. /// If `expr` is a place like `x`, this will introduce a /// temporary `tmp = x`, so that we capture the value of `x` at"} {"_id":"q-en-rust-d7c62cd3513034e1647ce37302a0742b01c09511d0b9ef1a89eee76bb165a4ae","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. //compile-flags: -Z borrowck=mir #![feature(slice_patterns)] fn nop(_s: &[& i32]) {} fn nop_subslice(_s: &[i32]) {} fn const_index_ok(s: &mut [i32]) { if let [ref first, ref second, _, ref fourth, ..] = *s { if let [_, _, ref mut third, ..] = *s { nop(&[first, second, third, fourth]); } } } fn const_index_err(s: &mut [i32]) { if let [ref first, ref second, ..] = *s { if let [_, ref mut second2, ref mut third, ..] = *s { //~ERROR nop(&[first, second, second2, third]); } } } fn const_index_from_end_ok(s: &mut [i32]) { if let [.., ref fourth, ref third, _, ref first] = *s { if let [.., ref mut second, _] = *s { nop(&[first, second, third, fourth]); } } } fn const_index_from_end_err(s: &mut [i32]) { if let [.., ref fourth, ref third, _, ref first] = *s { if let [.., ref mut third2, _, _] = *s { //~ERROR nop(&[first, third, third2, fourth]); } } } fn const_index_mixed(s: &mut [i32]) { if let [.., _, ref from_end4, ref from_end3, _, ref from_end1] = *s { if let [ref mut from_begin0, ..] = *s { nop(&[from_begin0, from_end1, from_end3, from_end4]); } if let [_, ref mut from_begin1, ..] = *s { //~ERROR nop(&[from_begin1, from_end1, from_end3, from_end4]); } if let [_, _, ref mut from_begin2, ..] = *s { //~ERROR nop(&[from_begin2, from_end1, from_end3, from_end4]); } if let [_, _, _, ref mut from_begin3, ..] = *s { //~ERROR nop(&[from_begin3, from_end1, from_end3, from_end4]); } } if let [ref from_begin0, ref from_begin1, _, ref from_begin3, _, ..] = *s { if let [.., ref mut from_end1] = *s { nop(&[from_begin0, from_begin1, from_begin3, from_end1]); } if let [.., ref mut from_end2, _] = *s { //~ERROR nop(&[from_begin0, from_begin1, from_begin3, from_end2]); } if let [.., ref mut from_end3, _, _] = *s { //~ERROR nop(&[from_begin0, from_begin1, from_begin3, from_end3]); } if let [.., ref mut from_end4, _, _, _] = *s { //~ERROR nop(&[from_begin0, from_begin1, from_begin3, from_end4]); } } } fn const_index_and_subslice_ok(s: &mut [i32]) { if let [ref first, ref second, ..] = *s { if let [_, _, ref mut tail..] = *s { nop(&[first, second]); nop_subslice(tail); } } } fn const_index_and_subslice_err(s: &mut [i32]) { if let [ref first, ref second, ..] = *s { if let [_, ref mut tail..] = *s { //~ERROR nop(&[first, second]); nop_subslice(tail); } } } fn const_index_and_subslice_from_end_ok(s: &mut [i32]) { if let [.., ref second, ref first] = *s { if let [ref mut tail.., _, _] = *s { nop(&[first, second]); nop_subslice(tail); } } } fn const_index_and_subslice_from_end_err(s: &mut [i32]) { if let [.., ref second, ref first] = *s { if let [ref mut tail.., _] = *s { //~ERROR nop(&[first, second]); nop_subslice(tail); } } } fn subslices(s: &mut [i32]) { if let [_, _, _, ref s1..] = *s { if let [ref mut s2.., _, _, _] = *s { //~ERROR nop_subslice(s1); nop_subslice(s2); } } } fn main() { let mut v = [1,2,3,4]; const_index_ok(&mut v); const_index_err(&mut v); const_index_from_end_ok(&mut v); const_index_from_end_err(&mut v); const_index_and_subslice_ok(&mut v); const_index_and_subslice_err(&mut v); const_index_and_subslice_from_end_ok(&mut v); const_index_and_subslice_from_end_err(&mut v); subslices(&mut v); } "} {"_id":"q-en-rust-d80bf5a1d90e5915371c7508301aae9caf7b0ecebfad4521b71b4d35e5fbe9d9","text":"LLVM_BUILD_DIR= LLVM_INST_DIR=$CFG_LLVM_ROOT do_reconfigure=0 # Check that LLVm FileCheck is available. Needed for the tests need_cmd $LLVM_INST_DIR/bin/FileCheck fi if [ ${do_reconfigure} -ne 0 ] then # because git is hilarious, it might have put the module index"} {"_id":"q-en-rust-d81b2e5e4868eff48e6aafa0239b3698274a040d4325e440ae404f1475567e03","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":"q-en-rust-d843cac72be6185107185e1270124dc07e494c42de09a7eafa23cedf1e945a37","text":"} tcx.sess.track_errors(|| { tcx.sess.time(\"impl_wf_inference\", || { tcx.hir().for_each_module(|module| tcx.ensure().check_mod_impl_wf(module)) }); })?; tcx.sess.track_errors(|| { tcx.sess.time(\"coherence_checking\", || { // Check impls constrain their parameters tcx.hir().for_each_module(|module| tcx.ensure().check_mod_impl_wf(module)); for &trait_def_id in tcx.all_local_trait_impls(()).keys() { tcx.ensure().coherent_trait(trait_def_id); }"} {"_id":"q-en-rust-d857738a1113cd802dd16bc20da505663875d20c23c596d3e0f0b10af796da71","text":"/// assert!(ptr::eq(ptr, inner.as_ptr())); /// ``` #[inline] #[unstable(feature = \"arc_unwrap_or_clone\", issue = \"93610\")] #[stable(feature = \"arc_unwrap_or_clone\", since = \"CURRENT_RUSTC_VERSION\")] pub fn unwrap_or_clone(this: Self) -> T { Arc::try_unwrap(this).unwrap_or_else(|arc| (*arc).clone()) }"} {"_id":"q-en-rust-d85c48ab06b0f9bdd5162e29caee792dbf2677f52215941172881668cd08f6c2","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":"q-en-rust-d88da50683464e4e0115f2159086a4ae4fc155a6de1845d57e7eacab7d0ee133","text":"); } let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig); let trait_sig = ocx.normalize(&misc_cause, param_env, unnormalized_trait_sig); trait_sig.error_reported()?; let trait_return_ty = trait_sig.output(); // RPITITs are allowed to use the implied predicates of the method that // defines them. This is because we want code like: // ``` // trait Foo { // fn test<'a, T>(_: &'a T) -> impl Sized; // } // impl Foo for () { // fn test<'a, T>(x: &'a T) -> &'a T { x } // } // ``` // .. to compile. However, since we use both the normalized and unnormalized // inputs and outputs from the substituted trait signature, we will end up // seeing the hidden type of an RPIT in the signature itself. Naively, this // means that we will use the hidden type to imply the hidden type's own // well-formedness. // // To avoid this, we replace the infer vars used for hidden type inference // with placeholders, which imply nothing about outlives bounds, and then // prove below that the hidden types are well formed. let universe = infcx.create_next_universe(); let mut idx = 0; let mapping: FxHashMap<_, _> = collector .types .iter() .map(|(_, &(ty, _))| { assert!( infcx.resolve_vars_if_possible(ty) == ty && ty.is_ty_var(), \"{ty:?} should not have been constrained via normalization\", ty = infcx.resolve_vars_if_possible(ty) ); idx += 1; ( ty, Ty::new_placeholder( tcx, ty::Placeholder { universe, bound: ty::BoundTy { var: ty::BoundVar::from_usize(idx), kind: ty::BoundTyKind::Anon, }, }, ), ) }) .collect(); let mut type_mapper = BottomUpFolder { tcx, ty_op: |ty| *mapping.get(&ty).unwrap_or(&ty), lt_op: |lt| lt, ct_op: |ct| ct, }; let wf_tys = FxIndexSet::from_iter( unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()), unnormalized_trait_sig .inputs_and_output .iter() .chain(trait_sig.inputs_and_output.iter()) .map(|ty| ty.fold_with(&mut type_mapper)), ); match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {"} {"_id":"q-en-rust-d894298843ee4fd88efab1f5dabe328fd35de58bd7f50fd3116479325e4eb77f","text":"\"README.md\", \"RELEASES.md\", \"configure\", \"Makefile.in\" \"Makefile.in\", \"x.py\", ]; let src_dirs = [ \"man\","} {"_id":"q-en-rust-d89853efc54c44a514573bc3e3ca7809d268fbb62b5c48cfea4e0c2eb5c8e95c","text":"attr: &Attribute, span: Span, target: Target, attrs: &[Attribute], ) -> bool { match target { Target::Fn | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, Target::Fn => { // `#[target_feature]` is not allowed in language items. if let Some((lang_item, _)) = hir::lang_items::extract(attrs) // Calling functions with `#[target_feature]` is // not unsafe on WASM, see #84988 && !self.tcx.sess.target.is_like_wasm && !self.tcx.sess.opts.actually_rustdoc { let hir::Node::Item(item) = self.tcx.hir().get(hir_id) else { unreachable!(); }; let hir::ItemKind::Fn(sig, _, _) = item.kind else { // target is `Fn` unreachable!(); }; self.tcx.sess.emit_err(errors::LangItemWithTargetFeature { attr_span: attr.span, name: lang_item, sig_span: sig.span, }); false } else { true } } Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, // FIXME: #[target_feature] was previously erroneously allowed on statements and some // crates used this, so only emit a warning. Target::Statement => {"} {"_id":"q-en-rust-d8d18e8e90a40440b3f1ef66725feb285189b97eb299b35065b51825aff8ea60","text":" use std::any::Any; fn foo(value: &T) -> Box { Box::new(value) as Box //~^ ERROR lifetime may not live long enough } fn main() { let _ = foo(&5); } "} {"_id":"q-en-rust-d90bf08a72563bfbd4e879036090a292f8621f359faf9177559f4b6faa4cb9b3","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::rc::Rc; struct Foo<'r>(&'r mut i32); impl<'r> Drop for Foo<'r> { fn drop(&mut self) { *self.0 += 1; } } fn main() { let mut drops = 0; { let _: Rc = Rc::new(Foo(&mut drops)); } assert_eq!(1, drops); } "} {"_id":"q-en-rust-d92a6f487169782135177ec8e2330c2a326856749605993169e788182738af22","text":" { \"message\": \"unnecessary parentheses around assigned value\", \"code\": { \"code\": \"unused_parens\", \"explanation\": null }, \"level\": \"warning\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_json_suggestion.rs\", \"byte_start\": 654, \"byte_end\": 667, \"line_start\": 17, \"line_end\": 17, \"column_start\": 14, \"column_end\": 27, \"is_primary\": true, \"text\": [ { \"text\": \" let _a = (1 / (2 + 3));\", \"highlight_start\": 14, \"highlight_end\": 27 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [ { \"message\": \"lint level defined here\", \"code\": null, \"level\": \"note\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_json_suggestion.rs\", \"byte_start\": 472, \"byte_end\": 485, \"line_start\": 11, \"line_end\": 11, \"column_start\": 9, \"column_end\": 22, \"is_primary\": true, \"text\": [ { \"text\": \"#![warn(unused_parens)]\", \"highlight_start\": 9, \"highlight_end\": 22 } ], \"label\": null, \"suggested_replacement\": null, \"suggestion_applicability\": null, \"expansion\": null } ], \"children\": [], \"rendered\": null }, { \"message\": \"remove these parentheses\", \"code\": null, \"level\": \"help\", \"spans\": [ { \"file_name\": \"$DIR/unused_parens_json_suggestion.rs\", \"byte_start\": 654, \"byte_end\": 667, \"line_start\": 17, \"line_end\": 17, \"column_start\": 14, \"column_end\": 27, \"is_primary\": true, \"text\": [ { \"text\": \" let _a = (1 / (2 + 3));\", \"highlight_start\": 14, \"highlight_end\": 27 } ], \"label\": null, \"suggested_replacement\": \"1 / (2 + 3)\", \"suggestion_applicability\": \"MachineApplicable\", \"expansion\": null } ], \"children\": [], \"rendered\": null } ], \"rendered\": \"warning: unnecessary parentheses around assigned value --> $DIR/unused_parens_json_suggestion.rs:17:14 {\"message\":\"unnecessary parentheses around assigned value\",\"code\":{\"code\":\"unused_parens\",\"explanation\":null},\"level\":\"error\",\"spans\":[{\"file_name\":\"$DIR/unused_parens_json_suggestion.rs\",\"byte_start\":596,\"byte_end\":609,\"line_start\":16,\"line_end\":16,\"column_start\":14,\"column_end\":27,\"is_primary\":true,\"text\":[{\"text\":\" let _a = (1 / (2 + 3)); --> $DIR/unused_parens_json_suggestion.rs:16:14 | LL | let _a = (1 / (2 + 3)); | ^^^^^^^^^^^^^ help: remove these parentheses | note: lint level defined here --> $DIR/unused_parens_json_suggestion.rs:11:9 --> $DIR/unused_parens_json_suggestion.rs:10:9 | LL | #![warn(unused_parens)] LL | #![deny(unused_parens)] | ^^^^^^^^^^^^^ \" } \"} {\"message\":\"aborting due to previous error\",\"code\":null,\"level\":\"error\",\"spans\":[],\"children\":[],\"rendered\":\"error: aborting due to previous error \"} "} {"_id":"q-en-rust-d936a584a4889ab2ea48d1d9b608322fb57dbe4f1499a6897f24286665501db1","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":"q-en-rust-d93790e5d01d1f72363f09eccf3436905105a0f633f4cd300922583167fd254a","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] impl Drop for BufWriter { fn drop(&mut self) { if self.inner.is_some() { if self.inner.is_some() && !self.panicked { // dtors should not panic, so we ignore a failed flush let _r = self.flush_buf(); }"} {"_id":"q-en-rust-d980f0249fc1e6be1edf9fc4035f44633b64abdcf5f8b0c46048879e449ad693","text":"/// /// # Panics /// /// When the number is zero, or if the base is not at least 2; /// it panics in debug mode and the return value is 0 in release mode. /// This function will panic if `self` is zero, or if `base` is less then 2. /// /// # Examples ///"} {"_id":"q-en-rust-d99ed47884ecb5cb52e47407f074587945f183fcfce57c4463b438169c78b794","text":" // Issue #3878 // Issue Name: Unused move causes a crash // Abstract: zero-fill to block after drop fn main() { let y = ~1; move y; } No newline at end of file"} {"_id":"q-en-rust-d9c3db99677044b4cb18080a4459355c581efdb99f867e63b6e99d3cd7518f48","text":"unsafe { foo(); //~ ERROR: this function takes at least 2 parameters but 0 parameters were supplied //~^ NOTE the following parameter types were expected //~| NOTE expected at least 2 parameters foo(1); //~ ERROR: this function takes at least 2 parameters but 1 parameter was supplied //~^ NOTE the following parameter types were expected //~| NOTE expected at least 2 parameters let x: unsafe extern \"C\" fn(f: isize, x: u8) = foo; //~^ ERROR: mismatched types"} {"_id":"q-en-rust-da036e884510d9261b80422df4780d81faccf75b6b4f4d3d0c3197cbf4797f4e","text":"fn inner() { let _ = foo!(third); } #[allow(semicolon_in_expressions_from_macros)] async { let _ = foo!(fourth); }; }"} {"_id":"q-en-rust-da1a6bed0f4116fac10eaaacba8e8642205cdfb824d58d4339339f2e45b9f222","text":" // check-pass // edition:2021 #![feature(async_fn_in_trait)] #![allow(incomplete_features)] use std::future::Future; async fn yield_now() {} trait AsyncIterator { type Item; async fn next(&mut self) -> Option; } struct YieldingRange { counter: u32, stop: u32, } impl AsyncIterator for YieldingRange { type Item = u32; async fn next(&mut self) -> Option { if self.counter == self.stop { None } else { let c = self.counter; self.counter += 1; yield_now().await; Some(c) } } } async fn async_main() { let mut x = YieldingRange { counter: 0, stop: 10 }; while let Some(v) = x.next().await { println!(\"Hi: {v}\"); } } fn main() { let _ = async_main(); } "} {"_id":"q-en-rust-da4184cfe2d13818a3d1b164213100f52c10f7651b78961d12280f89ce0339f3","text":"fn add_object(&mut self, path: &Path); fn gc_sections(&mut self, keep_metadata: bool); fn position_independent_executable(&mut self); fn no_position_independent_executable(&mut self); fn partial_relro(&mut self); fn full_relro(&mut self); fn optimize(&mut self);"} {"_id":"q-en-rust-da43484444ecbb49f7de044da64b2222fffbd860d84cae8c3af0a5b92ccaf186","text":"discr, variants }, // FIXME(eddyb): using `FieldPlacement::Arbitrary` here results // in lost optimizations, specifically around allocations, see // `test/codegen/{alloc-optimisation,vec-optimizes-away}.rs`. fields: FieldPlacement::Union(1), fields: FieldPlacement::Arbitrary { offsets: vec![Size::from_bytes(0)], memory_index: vec![0] }, abi, align, size"} {"_id":"q-en-rust-dac267e00caeabf47a4daf0c2e59d32bdabaed38597b41cf3aa26ed4033ceb3e","text":"fn remove_dir_all_recursive(parent_fd: Option, p: &Path) -> io::Result<()> { let pcstr = cstr(p)?; // entry is expected to be a directory, open as such let fd = openat_nofollow_dironly(parent_fd, &pcstr)?; // try opening as directory let fd = match openat_nofollow_dironly(parent_fd, &pcstr) { Err(err) if err.raw_os_error() == Some(libc::ENOTDIR) => { // not a directory - don't traverse further return match parent_fd { // unlink... Some(parent_fd) => { cvt(unsafe { unlinkat(parent_fd, pcstr.as_ptr(), 0) }).map(drop) } // ...unless this was supposed to be the deletion root directory None => Err(err), }; } result => result?, }; // open the directory passing ownership of the fd let (dir, fd) = fdreaddir(fd)?;"} {"_id":"q-en-rust-dadf3756a80a9dda755efd8bd90a1c6c939f8ca924affd5010aba6d82156ff9f","text":" - // MIR for `call` before Inline + // MIR for `call` after Inline fn call(_1: &T) -> i32 { debug s => _1; let mut _0: i32; let mut _2: &T; + scope 1 (inlined ::bar) { + debug self => _2; + } bb0: { StorageLive(_2); _2 = &(*_1); - _0 = ::bar(move _2) -> [return: bb1, unwind unreachable]; - } - - bb1: { + _0 = const 0_i32; StorageDead(_2); return; } } "} {"_id":"q-en-rust-daf6722297d4343b172991838f6beadb56f20b79778d64dc97c14027653b8188","text":"cx: X, input: X::Input, result: X::Result, origin_result: X::Result, dep_node: X::DepNodeIndex, additional_depth: usize, encountered_overflow: bool, nested_goals: NestedGoals, ) { let result = cx.mk_tracked(result, dep_node); let result = cx.mk_tracked(origin_result, dep_node); let entry = self.map.entry(input).or_default(); if encountered_overflow { let with_overflow = WithOverflow { nested_goals, result }; let prev = entry.with_overflow.insert(additional_depth, with_overflow); assert!(prev.is_none()); if let Some(prev) = &prev { assert!(cx.evaluation_is_concurrent()); assert_eq!(cx.get_tracked(&prev.result), origin_result); } } else { let prev = entry.success.replace(Success { additional_depth, nested_goals, result }); assert!(prev.is_none()); if let Some(prev) = &prev { assert!(cx.evaluation_is_concurrent()); assert_eq!(cx.get_tracked(&prev.result), origin_result); } } }"} {"_id":"q-en-rust-db058c8a34516dfa047b3bd8fa71f56ba523427bd46eb26f268f69c1c42c5158","text":" error[E0658]: generic associated types are unstable --> $DIR/gat-dont-ice-on-absent-feature.rs:7:5 | LL | type Item<'b> = &'b Foo; | ^^^^^^^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/44265 = help: add #![feature(generic_associated_types)] to the crate attributes to enable error: aborting due to previous error For more information about this error, try `rustc --explain E0658`. "} {"_id":"q-en-rust-db24a937fb2dcab5c8a626f02af123e82bb3d96e1c2606ba55cb976639441a08","text":"pub fn normal_test_fn() { #[expect(unused_mut, reason = \"this expectation will create a diagnostic with the default lint level\")] //~^ WARNING this lint expectation is unfulfilled //~| WARNING this lint expectation is unfulfilled //~| NOTE this expectation will create a diagnostic with the default lint level //~| NOTE this expectation will create a diagnostic with the default lint level //~| NOTE duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` let mut v = vec![1, 1, 2, 3, 5]; v.sort(); // Check that lint lists including `unfulfilled_lint_expectations` are also handled correctly #[expect(unused, unfulfilled_lint_expectations, reason = \"the expectation for `unused` should be fulfilled\")] //~^ WARNING this lint expectation is unfulfilled //~| WARNING this lint expectation is unfulfilled //~| NOTE the expectation for `unused` should be fulfilled //~| NOTE the expectation for `unused` should be fulfilled //~| NOTE the `unfulfilled_lint_expectations` lint can't be expected and will always produce this message //~| NOTE the `unfulfilled_lint_expectations` lint can't be expected and will always produce this message //~| NOTE duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` let value = \"I'm unused\"; }"} {"_id":"q-en-rust-db2f3fcee732f9ef1f471f8f89406147045688a69d09cfe2026f88f4875787d8","text":"} if (*task).unwinder.unwinding { rtabort!(\"unwinding again\"); // If a task fails while it's already unwinding then we // have limited options. Currently our preference is to // just abort. In the future we may consider resuming // unwinding or otherwise exiting the task cleanly. rterrln!(\"task failed during unwinding (double-failure - total drag!)\") rterrln!(\"rust must abort now. so sorry.\"); intrinsics::abort(); } }"} {"_id":"q-en-rust-db301bfbbf575f6b1fd84c1ec25df733b12c5e13a1610b8223db92f5f679da54","text":"// Verify that '>' is not both expected and found at the same time, as it used // to happen in #24780. For example, following should be an error: // expected one of ..., `>`, ... found `>`. No longer exactly this, but keeping for posterity. // expected one of ..., `>`, ... found `>`. fn foo() -> Vec> { //~ ERROR unmatched angle bracket fn foo() -> Vec> { //~ ERROR expected one of `!`, `+`, `::`, `;`, `where`, or `{`, found `>` Vec::new() }"} {"_id":"q-en-rust-dbab260dd79f37e8aeab70864654e1b942a79e1754debcc8e245b8ea4c8f5201","text":".emit(); } if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting { feature_err( if let Some((sub, sup)) = has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting { // Renders better when we erase regions, since they're not really the point here. let (sub, sup) = self.tcx.erase_regions((sub, sup)); let mut err = feature_err( &self.tcx.sess.parse_sess, sym::trait_upcasting, self.cause.span, \"trait upcasting coercion is experimental\", ) .emit(); &format!(\"cannot cast `{sub}` to `{sup}`, trait upcasting coercion is experimental\"), ); err.note(&format!(\"required when coercing `{source}` into `{target}`\")); err.emit(); } Ok(coercion)"} {"_id":"q-en-rust-dbeddbe9086354e9135438754f9a1d4a477658805ba5b116d0c70e550f868576","text":"ifdef TRACE CFG_RUSTC_FLAGS += -Z trace endif ifdef DISABLE_RPATH # NOTE: make this CFG_RUSTC_FLAGS after stage0 snapshot RUSTFLAGS_STAGE1 += --no-rpath RUSTFLAGS_STAGE2 += --no-rpath RUSTFLAGS_STAGE3 += --no-rpath endif # The executables crated during this compilation process have no need to include # static copies of libstd and libextra. We also generate dynamic versions of all"} {"_id":"q-en-rust-dbf24077bb68476f6851fcecabcefe3efc2c8069486cf5f45aa03e8eefc4e179","text":"use ascii; use borrow::{Cow, ToOwned, Borrow}; use boxed::Box; use clone::Clone; use convert::{Into, From}; use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; use error::Error;"} {"_id":"q-en-rust-dbfe2dce1d931d7970d99c5d006dc36521f118cf08662adb5c0b752edb4c6563","text":"#![feature(rustc_attrs)] fn main() { #![rustc_dummy(\"hi\" , 1 , 2 , 1.012 , pi = 3.14 , bye , name (\"John\"))] #![rustc_dummy(\"hi\", 1, 2, 1.012, pi = 3.14, bye, name (\"John\"))] #[rustc_dummy = 8] fn f() { } #[rustc_dummy(1 , 2 , 3)] #[rustc_dummy(1, 2, 3)] fn g() { } }"} {"_id":"q-en-rust-dc279090def4dcac327ab219af2ded297fced662f7d2f31249c83fcfbeba1570","text":"!msg.contains(\"if and else have incompatible types\") && !msg.contains(\"if may be missing an else clause\") && !msg.contains(\"match arms have incompatible types\") && !msg.contains(\"structure constructor specifies a structure of type\") { !msg.contains(\"structure constructor specifies a structure of type\") && !msg.contains(\"has an incompatible type for trait\") { return None } let first = msg.match_indices(\"expected\").filter(|s| {"} {"_id":"q-en-rust-dc43946da9652223a4a06215932e5104baf9d712814c830dcb79878ca7861254","text":"match ty.normalized.ty_adt_def() { Some(adt_def) if adt_def.has_ctor() => { let (ctor_kind, ctor_def_id) = adt_def.non_enum_variant().ctor.unwrap(); // Check the visibility of the ctor. let vis = tcx.visibility(ctor_def_id); if !vis.is_accessible_from(tcx.parent_module(hir_id).to_def_id(), tcx) { tcx.sess .emit_err(CtorIsPrivate { span, def: tcx.def_path_str(adt_def.did()) }); } let new_res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); let user_substs = Self::user_substs_for_adt(ty); user_self_ty = user_substs.user_self_ty;"} {"_id":"q-en-rust-dc445af0d638e45f99e4fe7d44ef445e7dcf7be51d2005a8d87ec3033160741d","text":"FfiUnsafe { ty: Ty<'tcx>, reason: String, help: Option }, } fn ty_is_known_nonnull<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { match ty.kind { ty::FnPtr(_) => true, ty::Ref(..) => true, ty::Adt(field_def, substs) if field_def.repr.transparent() && !field_def.is_union() => { for field in field_def.all_fields() { let field_ty = tcx.normalize_erasing_regions(ParamEnv::reveal_all(), field.ty(tcx, substs)); if field_ty.is_zst(tcx, field.did) { continue; } impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { /// Is type known to be non-null? fn ty_is_known_nonnull(&self, ty: Ty<'tcx>) -> bool { match ty.kind { ty::FnPtr(_) => true, ty::Ref(..) => true, ty::Adt(field_def, substs) if field_def.repr.transparent() && !field_def.is_union() => { for field in field_def.all_fields() { let field_ty = self.cx.tcx.normalize_erasing_regions( self.cx.param_env, field.ty(self.cx.tcx, substs), ); if field_ty.is_zst(self.cx.tcx, field.did) { continue; } let attrs = tcx.get_attrs(field_def.did); if attrs.iter().any(|a| a.check_name(sym::rustc_nonnull_optimization_guaranteed)) || ty_is_known_nonnull(tcx, field_ty) { return true; let attrs = self.cx.tcx.get_attrs(field_def.did); if attrs .iter() .any(|a| a.check_name(sym::rustc_nonnull_optimization_guaranteed)) || self.ty_is_known_nonnull(field_ty) { return true; } } } false false } _ => false, } _ => false, } } /// Check if this enum can be safely exported based on the /// \"nullable pointer optimization\". Currently restricted /// to function pointers, references, core::num::NonZero*, /// core::ptr::NonNull, and #[repr(transparent)] newtypes. /// FIXME: This duplicates code in codegen. fn is_repr_nullable_ptr<'tcx>( tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, ty_def: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>, ) -> bool { if ty_def.variants.len() != 2 { return false; } /// Check if this enum can be safely exported based on the \"nullable pointer optimization\". /// Currently restricted to function pointers, references, `core::num::NonZero*`, /// `core::ptr::NonNull`, and `#[repr(transparent)]` newtypes. fn is_repr_nullable_ptr( &self, ty: Ty<'tcx>, ty_def: &'tcx ty::AdtDef, substs: SubstsRef<'tcx>, ) -> bool { if ty_def.variants.len() != 2 { return false; } let get_variant_fields = |index| &ty_def.variants[VariantIdx::new(index)].fields; let variant_fields = [get_variant_fields(0), get_variant_fields(1)]; let fields = if variant_fields[0].is_empty() { &variant_fields[1] } else if variant_fields[1].is_empty() { &variant_fields[0] } else { return false; }; let get_variant_fields = |index| &ty_def.variants[VariantIdx::new(index)].fields; let variant_fields = [get_variant_fields(0), get_variant_fields(1)]; let fields = if variant_fields[0].is_empty() { &variant_fields[1] } else if variant_fields[1].is_empty() { &variant_fields[0] } else { return false; }; if fields.len() != 1 { return false; } if fields.len() != 1 { return false; } let field_ty = fields[0].ty(tcx, substs); if !ty_is_known_nonnull(tcx, field_ty) { return false; } let field_ty = fields[0].ty(self.cx.tcx, substs); if !self.ty_is_known_nonnull(field_ty) { return false; } // At this point, the field's type is known to be nonnull and the parent enum is Option-like. // If the computed size for the field and the enum are different, the nonnull optimization isn't // being applied (and we've got a problem somewhere). let compute_size_skeleton = |t| SizeSkeleton::compute(t, tcx, ParamEnv::reveal_all()).unwrap(); if !compute_size_skeleton(ty).same_size(compute_size_skeleton(field_ty)) { bug!(\"improper_ctypes: Option nonnull optimization not applied?\"); } // At this point, the field's type is known to be nonnull and the parent enum is // Option-like. If the computed size for the field and the enum are different, the non-null // optimization isn't being applied (and we've got a problem somewhere). let compute_size_skeleton = |t| SizeSkeleton::compute(t, self.cx.tcx, self.cx.param_env).unwrap(); if !compute_size_skeleton(ty).same_size(compute_size_skeleton(field_ty)) { bug!(\"improper_ctypes: Option nonnull optimization not applied?\"); } true } true } impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { /// Check if the type is array and emit an unsafe type lint. fn check_for_array_ty(&mut self, sp: Span, ty: Ty<'tcx>) -> bool { if let ty::Array(..) = ty.kind {"} {"_id":"q-en-rust-dc6c16c7b506f7f5fd7022a3fc2d169ca4620695bf0bdd0a7d5a6ec86f74f6e2","text":" error[E0224]: at least one trait is required for an object type --> $DIR/issue-79467.rs:4:5 | LL | dyn 'static: 'static + Copy, | ^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0224`. "} {"_id":"q-en-rust-dca75d2c49732838031649b101763d0760e8ff5717eae737205266d348c9e76e","text":"expr.span); } Err(..) => { rcx.fcx.tcx().sess.span_note(expr.span, \"cat_expr_unadjusted Errd during dtor check\"); let tcx = rcx.fcx.tcx(); if tcx.sess.has_errors() { // cannot run dropck; okay b/c in error state anyway. } else { tcx.sess.span_bug(expr.span, \"cat_expr_unadjusted Errd\"); } } } }"} {"_id":"q-en-rust-dca8d2db27537846c6ae5be342b781149db8fce8624a6eeb73d7b83dbf5bb14a","text":"#![crate_id=\"lint_stability#0.1\"] #![crate_type = \"lib\"] #![feature(macro_rules)] #![macro_escape] #[deprecated] pub fn deprecated() {} #[deprecated=\"text\"]"} {"_id":"q-en-rust-dcea1f6a7f6cdaeb741e65a2315d12926a23bfb651ab39eab86c76ad6a831222","text":"let receiver_ty = sig.inputs()[0]; let receiver_ty = wfcx.normalize(span, None, receiver_ty); // If the receiver already has errors reported, consider it valid to avoid // unnecessary errors (#58712). if receiver_ty.references_error() { return Ok(()); } if tcx.features().arbitrary_self_types { if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) { // Report error; `arbitrary_self_types` was enabled."} {"_id":"q-en-rust-dcec1ff147349f27a1c241ce2761ea31940af08123e498caf11141e18e8082a9","text":"let filename = \"tests/parser/unclosed-delims/issue_4466.rs\"; assert_parser_error(filename); } #[test] fn crate_parsing_stashed_diag() { // See also https://github.com/rust-lang/rust/issues/121450 let filename = \"tests/parser/stashed-diag.rs\"; assert_parser_error(filename); } "} {"_id":"q-en-rust-dcf1f43c42417158cfd1427fbf4f376f34a7ebd2d3fd3ceeb94af9c8e7f235aa","text":" #![feature(external_doc)] #![crate_name = \"foo\"] // @has foo/struct.Example.html // @matches - '//pre[@class=\"rust rust-example-rendered\"]' // '(?m)let example = Example::new()n .first()n .second()n .build();Z' /// ```rust /// let example = Example::new() /// .first() #[cfg_attr(not(feature = \"one\"), doc = \" .second()\")] /// .build(); /// ``` pub struct Example; // @has foo/struct.F.html // @matches - '//pre[@class=\"rust rust-example-rendered\"]' // '(?m)let example = Example::new()n .first()n .another()n .build();Z' ///```rust ///let example = Example::new() /// .first() #[cfg_attr(not(feature = \"one\"), doc = \" .another()\")] /// .build(); /// ``` pub struct F; // @has foo/struct.G.html // @matches - '//pre[@class=\"rust rust-example-rendered\"]' // '(?m)let example = Example::new()n.first()n .another()n.build();Z' ///```rust ///let example = Example::new() ///.first() #[cfg_attr(not(feature = \"one\"), doc = \" .another()\")] ///.build(); ///``` pub struct G; // @has foo/struct.H.html // @has - '//div[@class=\"docblock\"]/p' 'no whitespace lol' ///no whitespace #[doc = \" lol\"] pub struct H; // @has foo/struct.I.html // @matches - '//pre[@class=\"rust rust-example-rendered\"]' '(?m)4 whitespaces!Z' /// 4 whitespaces! #[doc = \"something\"] pub struct I; // @has foo/struct.J.html // @matches - '//div[@class=\"docblock\"]/p' '(?m)anno whitespacenJust some text.Z' ///a ///no whitespace #[doc(include = \"unindent.md\")] pub struct J; // @has foo/struct.K.html // @matches - '//pre[@class=\"rust rust-example-rendered\"]' '(?m)4 whitespaces!Z' ///a /// /// 4 whitespaces! /// #[doc(include = \"unindent.md\")] pub struct K; "} {"_id":"q-en-rust-dd2b18505fa76b7eff4dcf0a5fae5fcaa88ff821eb49da5938dc2ac2094f15ce","text":"#![crate_name = \"foo\"] // @has foo/fn.f.html // @has - '//*[@class=\"rust fn\"]' 'pub fn f(0u8 ...255: u8)' // @has - '//*[@class=\"rust fn\"]' 'pub fn f(_: u8)' pub fn f(0u8...255: u8) {}"} {"_id":"q-en-rust-dd99d0fdd769c99f87813cf75855c79bd182988ba059f0bda98386c8f495c6be","text":"} // Empty groups `a::b::{}` are turned into synthetic `self` imports // `a::b::c::{self as _}`, so that their prefixes are correctly // `a::b::c::{self as __dummy}`, so that their prefixes are correctly // resolved and checked for privacy/stability/etc. if items.is_empty() && !empty_for_self(&prefix) { let new_span = prefix[prefix.len() - 1].ident.span;"} {"_id":"q-en-rust-dde2214df25e9575de93bea8d2414f5cf24c7edf53a3ec04dafe3bae7a632e5f","text":" // error-pattern: requires `generator` lang_item #![feature(no_core, lang_items, unboxed_closures)] #![no_core] #[lang = \"sized\"] pub trait Sized { } #[lang = \"fn_once\"] #[rustc_paren_sugar] pub trait FnOnce { type Output; extern \"rust-call\" fn call_once(self, args: Args) -> Self::Output; } pub fn abc() -> impl FnOnce(f32) { |_| {} } fn main() {} "} {"_id":"q-en-rust-dde8ad0627481ea35548f9eb3126a07391320a4508060084173066c88c73c740","text":"\"num_cpus\", \"ordslice\", \"racer\", \"rand 0.7.3\", \"rand 0.8.4\", \"rayon\", \"regex\", \"rls-analysis\","} {"_id":"q-en-rust-ddea2bffcc042993a01b929d5e2daea658bb84856dab22b7abb7b540d565adf0","text":"pub mod c_str; pub mod os; pub mod path; pub mod path2; pub mod rand; pub mod run; pub mod sys;"} {"_id":"q-en-rust-de02523b56a174042c02b6080934c90169214dd724423558e388b8a5eeafeb77","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":"q-en-rust-de190ef5af3b9ac6c353221899d6c84e29a87e5c8e095cb49d3cb3cee5648195","text":"match self.find_library_crate() { Some(t) => t, None => { self.sess.abort_if_errors(); let message = match root_ident { None => format!(\"can't find crate for `{}`\", self.ident), Some(c) => format!(\"can't find crate for `{}` which `{}` depends on\","} {"_id":"q-en-rust-de193326748369fc8525d369772180fbeab56b1d8e2da177da78ac14114687cd","text":"#[cfg(any(target_os = \"horizon\", target_os = \"hurd\"))] pub fn modified(&self) -> io::Result { Ok(SystemTime::from(self.stat.st_mtim)) SystemTime::new(self.stat.st_mtim.tv_sec as i64, self.stat.st_mtim.tv_nsec as i64) } #[cfg(not(any("} {"_id":"q-en-rust-de367870a194fe263df68964da49d7c320bf1d1526ef855c3545af020fa863df","text":"let result = match e.node { hir::ExprUnary(hir::UnNeg, ref inner) => { // unary neg literals already got their sign during creation match inner.node { hir::ExprLit(ref lit) => { use syntax::ast::*; use syntax::ast::LitIntType::*; const I8_OVERFLOW: u64 = ::std::i8::MAX as u64 + 1; const I16_OVERFLOW: u64 = ::std::i16::MAX as u64 + 1; const I32_OVERFLOW: u64 = ::std::i32::MAX as u64 + 1; const I64_OVERFLOW: u64 = ::std::i64::MAX as u64 + 1; match (&lit.node, ety.map(|t| &t.sty)) { (&LitKind::Int(I8_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I8))) | (&LitKind::Int(I8_OVERFLOW, Signed(IntTy::I8)), _) => { return Ok(Integral(I8(::std::i8::MIN))) }, (&LitKind::Int(I16_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I16))) | (&LitKind::Int(I16_OVERFLOW, Signed(IntTy::I16)), _) => { return Ok(Integral(I16(::std::i16::MIN))) }, (&LitKind::Int(I32_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I32))) | (&LitKind::Int(I32_OVERFLOW, Signed(IntTy::I32)), _) => { return Ok(Integral(I32(::std::i32::MIN))) }, (&LitKind::Int(I64_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I64))) | (&LitKind::Int(I64_OVERFLOW, Signed(IntTy::I64)), _) => { return Ok(Integral(I64(::std::i64::MIN))) }, (&LitKind::Int(n, Unsuffixed), Some(&ty::TyInt(IntTy::Is))) | (&LitKind::Int(n, Signed(IntTy::Is)), _) => { match tcx.sess.target.int_type { IntTy::I16 => if n == I16_OVERFLOW { return Ok(Integral(Isize(Is16(::std::i16::MIN)))); }, IntTy::I32 => if n == I32_OVERFLOW { return Ok(Integral(Isize(Is32(::std::i32::MIN)))); }, IntTy::I64 => if n == I64_OVERFLOW { return Ok(Integral(Isize(Is64(::std::i64::MIN)))); }, _ => bug!(), } }, _ => {}, } }, hir::ExprUnary(hir::UnNeg, ref inner) => { // skip `--$expr` return eval_const_expr_partial(tcx, inner, ty_hint, fn_args); }, _ => {}, if let hir::ExprLit(ref lit) = inner.node { use syntax::ast::*; use syntax::ast::LitIntType::*; const I8_OVERFLOW: u64 = ::std::i8::MAX as u64 + 1; const I16_OVERFLOW: u64 = ::std::i16::MAX as u64 + 1; const I32_OVERFLOW: u64 = ::std::i32::MAX as u64 + 1; const I64_OVERFLOW: u64 = ::std::i64::MAX as u64 + 1; match (&lit.node, ety.map(|t| &t.sty)) { (&LitKind::Int(I8_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I8))) | (&LitKind::Int(I8_OVERFLOW, Signed(IntTy::I8)), _) => { return Ok(Integral(I8(::std::i8::MIN))) }, (&LitKind::Int(I16_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I16))) | (&LitKind::Int(I16_OVERFLOW, Signed(IntTy::I16)), _) => { return Ok(Integral(I16(::std::i16::MIN))) }, (&LitKind::Int(I32_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I32))) | (&LitKind::Int(I32_OVERFLOW, Signed(IntTy::I32)), _) => { return Ok(Integral(I32(::std::i32::MIN))) }, (&LitKind::Int(I64_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I64))) | (&LitKind::Int(I64_OVERFLOW, Signed(IntTy::I64)), _) => { return Ok(Integral(I64(::std::i64::MIN))) }, (&LitKind::Int(n, Unsuffixed), Some(&ty::TyInt(IntTy::Is))) | (&LitKind::Int(n, Signed(IntTy::Is)), _) => { match tcx.sess.target.int_type { IntTy::I16 => if n == I16_OVERFLOW { return Ok(Integral(Isize(Is16(::std::i16::MIN)))); }, IntTy::I32 => if n == I32_OVERFLOW { return Ok(Integral(Isize(Is32(::std::i32::MIN)))); }, IntTy::I64 => if n == I64_OVERFLOW { return Ok(Integral(Isize(Is64(::std::i64::MIN)))); }, _ => bug!(), } }, _ => {}, } } match eval_const_expr_partial(tcx, &inner, ty_hint, fn_args)? { Float(f) => Float(-f),"} {"_id":"q-en-rust-de4a7516747ebd0725ec2e0dd975eb2bbadb7839a39466e8298be36f785d89c0","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":"q-en-rust-de6c32c7b63e34e2474e02a497442fbe31b231ceeed865d85bdee52dbea88482","text":"use crate::build::expr::category::{Category, RvalueFunc}; use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; use crate::hair::*; use rustc_middle::mir::*; use rustc_middle::ty::{self, CanonicalUserTypeAnnotation}; use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_middle::mir::*; use rustc_middle::ty::{self, CanonicalUserTypeAnnotation}; use rustc_span::symbol::sym; use rustc_target::spec::abi::Abi;"} {"_id":"q-en-rust-de6f158570926e8a85146562a7326935e84398e0c5d0dad4d0e49b6782dd3de0","text":" // The problem in #66357 was that the call trace: // // - parse_fn_block_decl // - expect_or // - unexpected // - expect_one_of // - expected_one_of_not_found // - recover_closing_delimiter // // ended up bubbling up `Ok(true)` to `unexpected` which then used `unreachable!()`. fn f() { |[](* } //~^ ERROR expected one of `,` or `:`, found `(` //~| ERROR expected one of `)`, `-`, `_`, `box`, `mut`, `ref`, `|`, identifier, or path, found `*` "} {"_id":"q-en-rust-dea34ab2c5f951ff6f3f55a93048c504bbbcf7e7f3c0baac00abb84a880d8745","text":" const QUERY = 'MyForeignType::my_method'; const EXPECTED = { 'others': [ // Test case for https://github.com/rust-lang/rust/pull/96887#pullrequestreview-967154358 // Validates that the parent path for a foreign type method is correct. { 'path': 'foreign_type_path::aaaaaaa::MyForeignType', 'name': 'my_method' }, ], }; "} {"_id":"q-en-rust-dec2cfa99cd9b2f86124fef9dc53c358dc94d1841c5b1fe70125867d3be762d8","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":"q-en-rust-df4373c2782bcc924202fa885b51dc980e0fea46448d7254a61d1435ca835dc3","text":"#![forbid(dead_code)] #[derive(Debug)] pub struct Whatever { //~ ERROR struct `Whatever` is never constructed pub struct Whatever { pub field0: (), field1: (), field1: (), //~ ERROR fields `field1`, `field2`, `field3`, and `field4` are never read field2: (), field3: (), field4: (),"} {"_id":"q-en-rust-df61ae5bdb3fa7bbebea7581683b59ccc1a0ac050072f8c0731e27ece5cb295e","text":"issue_url = gh_url() + '/{}/comments'.format(number) response = urllib2.urlopen(urllib2.Request( issue_url, json.dumps({'body': maybe_delink(message)}), json.dumps({'body': maybe_delink(message)}).encode(), { 'Authorization': 'token ' + github_token, 'Content-Type': 'application/json', } )) response.read() except urllib2.HTTPError as e: print(\"HTTPError: %sn%s\" % (e, e.read())) except HTTPError as e: print(\"HTTPError: %sn%r\" % (e, e.read())) raise"} {"_id":"q-en-rust-df6eea57ea0b0eb12e599618878fb4af77180e8b4830634293dc84bcb75cb4cd","text":"= note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers) Future breakage diagnostic: error: reference to packed field is unaligned --> $DIR/unaligned_references.rs:90:20 | LL | let _ref = &m1.1.a; | ^^^^^^^ | note: the lint level is defined here --> $DIR/unaligned_references.rs:1:9 | LL | #![deny(unaligned_references)] | ^^^^^^^^^^^^^^^^^^^^ = 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 #82523 = note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers) Future breakage diagnostic: error: reference to packed field is unaligned --> $DIR/unaligned_references.rs:100:20 | LL | let _ref = &m2.1.a; | ^^^^^^^ | note: the lint level is defined here --> $DIR/unaligned_references.rs:1:9 | LL | #![deny(unaligned_references)] | ^^^^^^^^^^^^^^^^^^^^ = 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 #82523 = note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers) "} {"_id":"q-en-rust-df763650a9370a411fb171de761c1a1dd1ba249b51a2dbe40c8d18c0ce4284c2","text":"// + span: $DIR/nrvo-simple.rs:3:20: 3:21 // + literal: Const { ty: u8, val: Value(Scalar(0x00)) } StorageLive(_3); // scope 1 at $DIR/nrvo-simple.rs:4:5: 4:19 StorageLive(_5); // scope 1 at $DIR/nrvo-simple.rs:4:10: 4:18 StorageLive(_6); // scope 1 at $DIR/nrvo-simple.rs:4:10: 4:18 - _6 = &mut _2; // scope 1 at $DIR/nrvo-simple.rs:4:10: 4:18 + _6 = &mut _0; // scope 1 at $DIR/nrvo-simple.rs:4:10: 4:18 _3 = move _1(move _6) -> bb1; // scope 1 at $DIR/nrvo-simple.rs:4:5: 4:19 _5 = &mut (*_6); // scope 1 at $DIR/nrvo-simple.rs:4:10: 4:18 _3 = move _1(move _5) -> bb1; // scope 1 at $DIR/nrvo-simple.rs:4:5: 4:19 } bb1: { StorageDead(_5); // scope 1 at $DIR/nrvo-simple.rs:4:18: 4:19 StorageDead(_6); // scope 1 at $DIR/nrvo-simple.rs:4:19: 4:20 StorageDead(_3); // scope 1 at $DIR/nrvo-simple.rs:4:19: 4:20 - _0 = _2; // scope 1 at $DIR/nrvo-simple.rs:5:5: 5:8 - StorageDead(_2); // scope 0 at $DIR/nrvo-simple.rs:6:1: 6:2"} {"_id":"q-en-rust-df844c1ea3fbe0e52ce01764e5818be01ebd93e9b64fb89e6eba8cf28cadaeed","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":"q-en-rust-dfb26e0c8f1f756a927307678888fe4ab54c89ac492fa8aecc13579a95f54671","text":"} else { cmd = Command::new(&output_file); if doctest.is_multiple_tests { cmd.arg(\"*doctest-bin-path\"); cmd.arg(&output_file); cmd.env(\"RUSTDOC_DOCTEST_BIN_PATH\", &output_file); } } if let Some(run_directory) = &rustdoc_options.test_run_directory {"} {"_id":"q-en-rust-dfd279a46d00218a519d2904f8b638157718072d03134bcaac0cf3d2c85ef56b","text":"fn f() -> bool { let c = false; if c { if c { //~ ERROR unnecessary parentheses println!(\"next\"); } if c { if c { //~ ERROR unnecessary parentheses println!(\"prev\"); } while false && true { if c { if c { //~ ERROR unnecessary parentheses println!(\"norm\"); } } while true && false { for _ in 0 .. 3 { while true && false { //~ ERROR unnecessary parentheses for _ in 0 .. 3 { //~ ERROR unnecessary parentheses println!(\"e~\") } } for _ in 0 .. 3 { while true && false { for _ in 0 .. 3 { //~ ERROR unnecessary parentheses while true && false { //~ ERROR unnecessary parentheses println!(\"e~\") } }"} {"_id":"q-en-rust-dfdafd34107129d434959372636f118055dacd93227cd11e4b6b99cebfaa93bf","text":" fn foo() {} //~^ ERROR expected trait bound, found `impl Trait` type fn main() {} "} {"_id":"q-en-rust-dfe75959a89062c4a0829590e695e42eee7aec393de2d4ee1970234fa48c8d1a","text":" mod foo { pub struct B(()); } mod bar { use foo::B; fn foo() { B(()); //~ ERROR expected function, found struct `B` [E0423] } } mod baz { fn foo() { B(()); //~ ERROR cannot find function `B` in this scope [E0425] } } fn main() {} "} {"_id":"q-en-rust-e00b96053621cfb71625b9687db2edd0433ea2403764ad129a4e23dd6d867981","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":"q-en-rust-e0157fad0203f30e5f08898b7219d22d3dc3eb656861a1f055ad0bcad625549e","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":"q-en-rust-e059731fcb212445e7b1affaf5f889a806c148aadabe6fafd7375378950b28ea","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":"q-en-rust-e0599e71b698fba660ca0317352a97279b538c0dda19c80704f3a5ea6c33edcd","text":"| LL | unsafe extern \"C\" { | ^^^^^^ | = note: see issue #123743 for more information = help: add `#![feature(unsafe_extern_blocks)]` 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]: `unsafe extern {}` blocks and `safe` keyword are experimental --> $DIR/feature-gate-unsafe-extern-blocks.rs:9:5"} {"_id":"q-en-rust-e09eef73ea5b656b10d838d17498b8673e1bcbd7e508654885b3d6af18d462f7","text":"## missing_doc_code_examples This lint is **allowed by default**. It detects when a documentation block This lint is **allowed by default** and is **nightly-only**. It detects when a documentation block is missing a code example. For example: ```rust"} {"_id":"q-en-rust-e0bdbfac134e0eedcd115e79480d4d068c7c3339ccdaf1377bfc98ddacb5f215","text":"use std::cmp; use std::string::String; use crate::clean::{self, DocFragment, Item}; use crate::clean::{self, DocFragment, DocFragmentKind, Item}; use crate::core::DocContext; use crate::fold::{self, DocFolder}; use crate::passes::Pass;"} {"_id":"q-en-rust-e0eada1559c7b22531c3c7ceaaa3feede3664e179d7b59d42df54e7f70608d37","text":"Available passes for running rustdoc: check-custom-code-classes - check for custom code classes without the feature-gate enabled check_doc_test_visibility - run various visibility-related lints on doctests strip-aliased-non-local - strips all non-local private aliased items from the output strip-hidden - strips all `#[doc(hidden)]` items from the output strip-private - strips all private items from a crate which cannot be seen externally, implies strip-priv-imports strip-priv-imports - strips all private import statements (`use`, `extern crate`) from a crate"} {"_id":"q-en-rust-e130161d89f75a00854c1ea9508032bb0dfda3d3a9e84f5a47a831a8ffa2da7e","text":"mode: SolverMode, f: impl FnOnce(&mut GlobalCache) -> R, ) -> R; fn evaluation_is_concurrent(&self) -> bool; } pub trait Delegate {"} {"_id":"q-en-rust-e1496d7a12eba13af74b45696c622feaf9247d0228495cd40371e0d7f52fc1cb","text":"//~ TRANS_ITEM fn unsizing::{{impl}}[3]::foo[0] let _wrapper_sized = wrapper_sized as Wrapper; } //~ TRANS_ITEM drop-glue i8 "} {"_id":"q-en-rust-e17da45661982e8220b79437a01fb11def28c8a1b8e9ca64b0b4a2f18390c6bb","text":"LL | let _y = x; | ^ | help: a local variable with a similar name exists, consider changing it help: a local variable with a similar name exists, consider renaming `_x` into `x` | LL | let x = 42; | ~"} {"_id":"q-en-rust-e1cfceb64e951166d4d8df672f919ad42d44b45600caceab56df73e1ff39b8dd","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":"q-en-rust-e1da7270eb2d0bac937baee795e3062f3cb4070159fdc664a92dba1522e4120e","text":".. }, method, )) if Some(recv_ty.def_id()) == pin_did && method.ident.name == sym::new => { )) if recv_ty.opt_def_id() == pin_did && method.ident.name == sym::new => { err.span_suggestion( fn_name.span, \"use `Box::pin` to pin and box this expression\","} {"_id":"q-en-rust-e1e3e0f34ac9e30b75763ae89c618433fe7b081e5b8f96988f8f9800fb09dbb1","text":"fn main() { foo(1, 2, 3); //~^ ERROR this function takes 4 parameters but 3 //~^^ NOTE the following parameter types were expected //~| NOTE the following parameter types were expected //~| NOTE expected 4 parameters }"} {"_id":"q-en-rust-e23672cbf7a5b160dd36f772a09ecd4ec8fe35c0934809aa4cb880ddba5709ae","text":"/// Mark LLVM function to use provided inline heuristic. #[inline] fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr, requires_inline: bool) { fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) { use self::InlineAttr::*; match inline { Hint => Attribute::InlineHint.apply_llfn(Function, val),"} {"_id":"q-en-rust-e25cd833b11e45299a11b7c5c746c6c7089077ac531cf1e115669227c944d93e","text":" error[E0308]: mismatched types --> $DIR/proper-span-for-type-error.rs:8:5 | LL | a().await | ^^^^^^^^^ expected enum `Result`, found `()` | = note: expected enum `Result<(), i32>` found unit type `()` help: try wrapping the expression in `Ok` | LL | Ok(a().await) | +++ + error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-e27d5a3e493f6a044711cbef3da1e2b8f7cbfb1e10496ba6d04f69c9caf633ce","text":"// Because it is `?Sized`, it will always be the last field in memory. // Note: This is a detail of the current implementation of the compiler, // and is not a guaranteed language detail. Do not rely on it outside of std. unsafe { data_offset_align(align_of_val(&*ptr)) } unsafe { data_offset_align(align_of_val_raw(ptr)) } } #[inline]"} {"_id":"q-en-rust-e28c9a08616baa3021c6d227f24b2522f5c5edd2662dabcc18d44577c4545a9a","text":"#![feature(ptr_metadata)] #![feature(once_cell)] #![feature(unsized_tuple_coercion)] #![feature(nonzero_leading_trailing_zeros)] #![feature(const_option)] #![feature(integer_atomics)] #![feature(slice_group_by)]"} {"_id":"q-en-rust-e2b244281f09ce7985f628ed5660a8664fae4471694d85c3890fe8fbe64d8458","text":"} #[test] #[cfg(unix)] fn set_get_unix_permissions() { use os::unix::fs::PermissionsExt; let tmpdir = tmpdir(); let filename = &tmpdir.join(\"set_get_unix_permissions\"); check!(fs::create_dir(filename)); let mask = 0o7777; check!(fs::set_permissions(filename, fs::Permissions::from_mode(0))); let metadata0 = check!(fs::metadata(filename)); assert_eq!(mask & metadata0.permissions().mode(), 0); check!(fs::set_permissions(filename, fs::Permissions::from_mode(0o1777))); let metadata1 = check!(fs::metadata(filename)); assert_eq!(mask & metadata1.permissions().mode(), 0o1777); } #[test] #[cfg(windows)] fn file_test_io_seek_read_write() { use os::windows::fs::FileExt;"} {"_id":"q-en-rust-e2bc55b2a5f63e2266b69c11366941bfe0d0655961490b2aebad58dc7958c1bd","text":"LL - fn f1(x: &X) { LL + fn f1(x: &X) { | help: consider borrowing here | LL | let y: &Y; | + error[E0277]: the size for values of type `X` cannot be known at compilation time --> $DIR/unsized6.rs:7:12"} {"_id":"q-en-rust-e2cd955fe8768197d7dda142b9bb44bbdd1771e8992e8292f9afecaf89711a7a","text":"&Path(\"lib/libstd.so\")); assert_eq!(res.to_str(), ~\"@executable_path/../lib\"); } #[test] fn test_get_absolute_rpath() { let res = get_absolute_rpath(&Path(\"lib/libstd.so\")); debug!(\"test_get_absolute_rpath: %s vs. %s\", res.to_str(), os::make_absolute(&Path(\"lib\")).to_str()); assert_eq!(res, os::make_absolute(&Path(\"lib\"))); } }"} {"_id":"q-en-rust-e33f519f317ff6462a62ef68d4e29c0cd2218e6d2ec4b832f87b518ec428624d","text":"} #[derive(Diagnostic)] #[diag(parse_at_dot_dot_in_struct_pattern)] pub(crate) struct AtDotDotInStructPattern { #[primary_span] pub span: Span, #[suggestion(code = \"\", style = \"verbose\", applicability = \"machine-applicable\")] pub remove: Span, pub ident: Ident, } #[derive(Diagnostic)] #[diag(parse_at_in_struct_pattern)] #[note] #[help] pub(crate) struct AtInStructPattern { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(parse_dot_dot_dot_for_remaining_fields)] pub(crate) struct DotDotDotForRemainingFields { #[primary_span]"} {"_id":"q-en-rust-e35d504d55df20bda2e4739b259773cb51a056cd477d85fb58cf160d50dbd968","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":"q-en-rust-e397dd8567a57540dd94e7b691e76e64abf08d775ddaa1c4339db553d591b97b","text":"let libdir = builder.sysroot_libdir(target_compiler, target); let hostdir = builder.sysroot_libdir(target_compiler, compiler.host); add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target)); if compiler.stage == 0 { // special handling for stage0, to make `rustup toolchain link` and `x dist --stage 0` // work for stage0-sysroot let sysroot = builder.out.join(&compiler.host.triple).join(\"stage0-sysroot\"); let host_lib_dir = builder.initial_rustc.ancestors().nth(2).unwrap().join(\"lib\"); let host_bin_dir = builder.out.join(&builder.initial_rustc.parent().unwrap()); let host_codegen_backends = host_lib_dir.join(\"rustlib\").join(&compiler.host.triple).join(\"codegen-backends\"); let sysroot_bin_dir = sysroot.join(\"bin\"); let sysroot_lib_dir = sysroot.join(\"lib\"); let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler); // Create the `bin` directory in stage0-sysroot t!(fs::create_dir_all(&sysroot_bin_dir)); // copy bin files from `builder.initial_rustc/./` to `stage0-sysroot/bin` if let Ok(files) = fs::read_dir(&host_bin_dir) { for file in files { let file = t!(file); if file.file_name() == \"rustfmt\" { // This is when `rustc` and `cargo` are set in `config.toml` if !file.path().starts_with(&builder.out) { builder.copy( &file.path().into_boxed_path(), &sysroot_bin_dir.join(file.file_name()), ); } else { builder.copy( &builder .out .join(&compiler.host.triple) .join(\"rustfmt/bin/rustfmt\"), &sysroot_bin_dir.join(file.file_name()), ); } } else { builder.copy( &file.path().into_boxed_path(), &sysroot_bin_dir.join(file.file_name()), ); } } } // copy dylib files from `builder.initial_rustc/../lib/*` while excluding the `rustlib` directory to `stage0-sysroot/lib` if let Ok(files) = fs::read_dir(&host_lib_dir) { for file in files { let file = t!(file); let path = file.path(); if path.is_file() && is_dylib(&file.file_name().into_string().unwrap()) && !path.starts_with(sysroot_lib_dir.join(\"rustlib\").into_boxed_path()) { builder.copy(&path, &sysroot_lib_dir.join(path.file_name().unwrap())); } } } t!(fs::create_dir_all(&sysroot_codegen_backends)); // copy `codegen-backends` from `host_lib_dir/rustlib/codegen_backends` to `stage0-sysroot/lib/rustlib/host-triple/codegen-backends` if it exists. if host_codegen_backends.exists() { builder.cp_r(&host_codegen_backends, &sysroot_codegen_backends); } } } }"} {"_id":"q-en-rust-e39857587a356864d497bb46a886ad50204b32d85d4d2b04b70456c6073e0826","text":" // build-fail // ignore-emscripten no asm! support #![feature(asm)] fn main() { unsafe { asm!(\"nop\" : \"+r\"(\"r15\")); //~^ malformed inline assembly } } "} {"_id":"q-en-rust-e3a56df31ca7288f32b5815dbbb431461383b93339b735b09f95b6ef37821de2","text":"/// # Examples /// /// ```rust /// #![feature(fmt_as_str)] /// /// use std::fmt::Arguments; /// /// fn write_str(_: &str) { /* ... */ }"} {"_id":"q-en-rust-e3ade03b40ba011bb1d1f47f7c9798fcb32d4e2d5124077802b87332078b110f","text":"let fty = self.sanitize_type(place, fty); match self.field_ty(place, base, field, location) { Ok(ty) => { let ty = self.cx.normalize(ty, location); if let Err(terr) = self.cx.eq_types( ty, fty,"} {"_id":"q-en-rust-e3b586f042e98976c818cdceb041b9033f328ab44c9165b85232dccde06c046c","text":"} fn visit_rvalue(&mut self, rvalue: &mut Rvalue<'tcx>, location: Location) { if let Some(mtbl) = self.optimizations.and_stars.remove(&location) { if self.optimizations.and_stars.remove(&location) { debug!(\"replacing `&*`: {:?}\", rvalue); let new_place = match rvalue { Rvalue::Ref(_, _, place) => {"} {"_id":"q-en-rust-e3de18a2bde43b2a53e0c54b0af0d10dd5c4f0f13763cf5dac4b316b540baa96","text":"} } (false, false) => { t = Err(old_binding); return Err(old_binding); } } } else { resolution.binding = Some(binding); } } else { resolution.binding = Some(binding); }; Ok(()) }) } fn ambiguity( &self, kind: AmbiguityKind, primary_binding: &'a NameBinding<'a>, secondary_binding: &'a NameBinding<'a>, ) -> &'a NameBinding<'a> { self.arenas.alloc_name_binding(NameBinding { ambiguity: Some((secondary_binding, kind)), ..primary_binding.clone() }) } // Use `f` to mutate the resolution of the name in the module. // If the resolution becomes a success, define it in the module's glob importers. fn update_resolution(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T where F: FnOnce(&mut Resolver<'a, 'tcx>, &mut NameResolution<'a>) -> T, { // Ensure that `resolution` isn't borrowed when defining in the module's glob importers, // during which the resolution might end up getting re-defined via a glob cycle. let (binding, t) = match resolution.binding() { _ if old_binding.is_some() => return t, None => return t, Some(binding) => match old_binding { Some(old_binding) if ptr::eq(old_binding, binding) => return t, _ => (binding, t), }, let (binding, t) = { let resolution = &mut *self.resolution(module, key).borrow_mut(); let old_binding = resolution.binding(); let t = f(self, resolution); match resolution.binding() { _ if old_binding.is_some() => return t, None => return t, Some(binding) => match old_binding { Some(old_binding) if ptr::eq(old_binding, binding) => return t, _ => (binding, t), }, } }; drop(resolution); // Define `binding` in `module`s glob importers. for import in module.glob_importers.borrow_mut().iter() { let mut ident = key.ident;"} {"_id":"q-en-rust-e3eead0ba41db8a7e98425b0d2c315ee7a00d9c6e15835e0354a2c885d887984","text":"} }; let attrs = &item.attrs; let sp = span_of_attrs(attrs); let sp = span_of_attrs(attrs).unwrap_or(item.source.span()); let mut diag = cx.tcx.struct_span_lint_hir( lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE,"} {"_id":"q-en-rust-e4239cb4a580eb7fc076d2b09b65ddb58f394634d40abdaecb0be13f48e3ac34","text":"nightly ) msg \"overriding settings for $CFG_RELEASE_CHANNEL\" CFG_ENABLE_LLVM_ASSERTIONS=1 CFG_ENABLE_DEBUGINFO_LINES=1 # FIXME(#37364) shouldn't have to disable this on windows-gnu case \"$CFG_BUILD\" in *-pc-windows-gnu) ;; *) CFG_ENABLE_DEBUGINFO_LINES=1 ;; esac ;; beta | stable) msg \"overriding settings for $CFG_RELEASE_CHANNEL\" CFG_ENABLE_DEBUGINFO_LINES=1 case \"$CFG_BUILD\" in *-pc-windows-gnu) ;; *) CFG_ENABLE_DEBUGINFO_LINES=1 ;; esac ;; dev) ;;"} {"_id":"q-en-rust-e4a1baa2d47a776d7d668d2721ce151c1b4c0e244d4d7db744bc717f4693d208","text":"let trait_to_placeholder_args = impl_to_placeholder_args.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_args); let hybrid_preds = tcx .predicates_of(impl_m.container_id(tcx)) .instantiate_identity(tcx) .into_iter() .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_to_placeholder_args)) .map(|(clause, _)| clause); let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds), Reveal::UserFacing); let param_env = traits::normalize_param_env_or_error( tcx, param_env, ObligationCause::misc(tcx.def_span(impl_m_def_id), impl_m_def_id), ); let infcx = &tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(infcx); // Normalize the impl signature with fresh variables for lifetime inference. let norm_cause = ObligationCause::misc(return_span, impl_m_def_id); let misc_cause = ObligationCause::misc(return_span, impl_m_def_id); let impl_sig = ocx.normalize( &norm_cause, &misc_cause, param_env, tcx.liberate_late_bound_regions( impl_m.def_id,"} {"_id":"q-en-rust-e4a2aecfe15a4c44689407bfc923e77c1f0be0caf4ea0f93f11351019e05d129","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. // Check that we cannot have two sequence repetitions in a row. macro_rules! foo { ( $($a:expr)* $($b:tt)* ) => { }; //~ ERROR sequence repetition followed by another sequence ( $($a:tt)* $($b:tt)* ) => { }; //~ ERROR sequence repetition followed by another sequence } fn main() { } "} {"_id":"q-en-rust-e4b65eb7f2d88da3e9a76b658d37ddc7d7448c775415d833128e8f63cacb09da","text":"// #[rustc_main] let main_attr = ecx.attr_word(sym::rustc_main, sp); // #[no_coverage] let no_coverage_attr = ecx.attr_word(sym::no_coverage, sp); // pub fn main() { ... } let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(ThinVec::new()));"} {"_id":"q-en-rust-e501addd2b6e5b6aeb9c061d12a3da8b297980e20e02a5de9b141fa5689e92a8","text":"(Some(Mode::ToolRustc), \"rust_analyzer\", None), (Some(Mode::ToolStd), \"rust_analyzer\", None), (Some(Mode::Codegen), \"parallel_compiler\", None), // NOTE: consider updating `check-cfg` entries in `std/Cargo.toml` too. // cfg(bootstrap) remove these once the bootstrap compiler supports // `lints.rust.unexpected_cfgs.check-cfg` (Some(Mode::Std), \"stdarch_intel_sde\", None), (Some(Mode::Std), \"no_fp_fmt_parse\", None), (Some(Mode::Std), \"no_global_oom_handling\", None),"} {"_id":"q-en-rust-e50976a28609d07533c4f3519afc7a1db3e81179b17c5419fa5c56df246b7cc9","text":"write!(w, \"{}\", impl_header)?; for implementor in local { write!(w, \"
  • \")?; write!(w, \"
  • \")?; if let Some(item) = implementor2item(&cache, implementor) { if let Some(l) = (Item { cx, item }).src_href() { write!(w, \"
    \")?; write!(w, \"[src]\", l, \"goto source code\")?; write!(w, \"
    \")?; } } write!(w, \"\")?; // If there's already another implementor that has the same abbridged name, use the // full path, for example in `std::iter::ExactSizeIterator` let use_absolute = match implementor.impl_.for_ {"} {"_id":"q-en-rust-e50f877ba764c11100fac9b010c137cff2f70e4670e7b11ab5ea67955a246670","text":"// extensions pub fn get_args(&self) -> &[OsString] { &self.args } pub fn take_args(&mut self) -> Vec { mem::replace(&mut self.args, Vec::new()) }"} {"_id":"q-en-rust-e5114b155135cc94e51f000e463edebea3d58fe9b770371731fe8972fb13e120","text":"find_testable_code(&dox, &mut tests, ErrorCodes::No); if check_missing_code == true && tests.found_tests == 0 { let sp = span_of_attrs(&item.attrs).substitute_dummy(item.source.span()); let sp = span_of_attrs(&item.attrs).unwrap_or(item.source.span()); let mut diag = cx.tcx.struct_span_lint_hir( lint::builtin::MISSING_DOC_CODE_EXAMPLES, hir_id,"} {"_id":"q-en-rust-e522f4970d7fd2e0417ae1c596101b9eef94b2d78c1a73fe47f2f45d026bc593","text":"} } debug!(\"enforce_member_constraint: final least choice = {:?}\", least_choice); if least_choice != member_lower_bound { // (#72087) Different `ty::Regions` can be known to be equal, for // example, we know that `'a` and `'static` are equal in a function // with a parameter of type `&'static &'a ()`. // // When we have two equal regions like this `expansion` will use // `lub_concrete_regions` to pick a canonical representative. The same // choice is needed here so that we don't end up in a cycle of // `expansion` changing the region one way and the code here changing // it back. let lub = self.lub_concrete_regions(least_choice, member_lower_bound); debug!( \"enforce_member_constraint: final least choice = {:?}nlub = {:?}\", least_choice, lub ); if lub != member_lower_bound { *var_values.value_mut(member_vid) = VarValue::Value(least_choice); true } else {"} {"_id":"q-en-rust-e5bcdac85e322e06cb968441da5bd24a00ca55493eb511574c05481c1a639277","text":"const LEN: usize = 4; struct SingleUnused(i32, [u8; LEN], String); //~^ ERROR: field `1` is never read struct UnusedAtTheEnd(i32, f32, [u8; LEN], String, u8); //~^ ERROR:fields `1`, `2`, `3`, and `4` are never read //~| NOTE: fields in this struct //~| HELP: consider removing these fields struct UnusedJustOneField(i32); //~^ ERROR: field `0` is never read //~| NOTE: field in this struct //~| HELP: consider changing the field to be of unit type //~| HELP: consider removing this field struct MultipleUnused(i32, f32, String, u8); //~^ ERROR: fields `0`, `1`, `2`, and `3` are never read struct UnusedInTheMiddle(i32, f32, String, u8, u32); //~^ ERROR: fields `1`, `2`, and `4` are never read //~| NOTE: fields in this struct //~| HELP: consider changing the fields to be of unit type //~| HELP: consider changing the fields to be of unit type to suppress this warning while preserving the field numbering, or remove the fields struct GoodUnit(());"} {"_id":"q-en-rust-e5cc6500863551cbc02e536cec502a79604dfb175e013d7208689b70e982809f","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":"q-en-rust-e5db06437b437480c43847a8d764f7fcea2506bd9818b036ef0eb585a17478a5","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 to ensure we only report an error for the first issued loan that // conflicts with a new loan, as opposed to every issued loan. This keeps us // down to O(n) errors (for n problem lines), instead of O(n^2) errors. fn main() { let mut x = 1; let mut addr; loop { match 1 { 1 => { addr = &mut x; } //~^ ERROR cannot borrow `x` as mutable more than once at a time 2 => { addr = &mut x; } //~^ ERROR cannot borrow `x` as mutable more than once at a time _ => { addr = &mut x; } //~^ ERROR cannot borrow `x` as mutable more than once at a time } } } "} {"_id":"q-en-rust-e5e9c71310a95f763f2f0377e27cc3dc83c21c9ae2c013f5eb7ae4bbb102c63e","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":"q-en-rust-e607f6de68d775def133caec27a202770be7c1032877a4efc79ef22e51512d3f","text":"use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_trait_selection::traits::{self, ObligationCauseCode}; use std::fmt::Display; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_expr_eq_type(&self, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>) { let ty = self.check_expr_with_hint(expr, expected);"} {"_id":"q-en-rust-e60d352eff675fcce1605500b856267da0c9bae339da2ba4f9fcd7ac8bc23e32","text":"} } ast::TraitItemKind::Type(_, ref default) => { // We use two if statements instead of something like match guards so that both // of these errors can be emitted if both cases apply. // We use three if statements instead of something like match guards so that all // of these errors can be emitted if all cases apply. if default.is_some() { gate_feature_post!(&self, associated_type_defaults, ti.span, \"associated type defaults are unstable\");"} {"_id":"q-en-rust-e67f749aab4b9110a1c1afdea2e257d301db6be52ddbf532ce2281a6109a4928","text":" use crate::t; use crate::{t, VERSION}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{"} {"_id":"q-en-rust-e6ad0a20a0a3cd72bd1d7f34193476e7f072ea89a7a93935c8842dc85cb69a6d","text":"\"test/bench/shootout-meteor.rs\", # BSD \"test/bench/shootout-pidigits.rs\", # BSD \"test/bench/shootout-regex-dna.rs\", # BSD \"test/bench/shootout-reverse-complement.rs\", # BSD \"test/bench/shootout-threadring.rs\", # BSD ]"} {"_id":"q-en-rust-e6bbc1a6eac850fb2a0339ac174779781823e0d7e5d72095105c15148eb13363","text":"// collect results based on the filter function if ident.name == lookup_ident.name && ns == namespace { if filter_fn(name_binding.def()) { let def = name_binding.def(); if filter_fn(def) { // create the path let mut segms = path_segments.clone(); if lookup_ident.span.rust_2018() {"} {"_id":"q-en-rust-e6d3f84ec9d4b5d9ad8e83a4d8d881d35fed036aeb6b9470ed2a2d3897ac9a37","text":" // run-pass // ignore-emscripten no subprocess support #![feature(set_stdio)] use std::fmt; use std::fmt::{Display, Formatter}; use std::io::set_panic; pub struct A; impl Display for A { fn fmt(&self, _f: &mut Formatter<'_>) -> fmt::Result { panic!(); } } fn main() { set_panic(Some(Box::new(Vec::new()))); assert!(std::panic::catch_unwind(|| { eprintln!(\"{}\", A); }) .is_err()); } "} {"_id":"q-en-rust-e6f5bce32f349c4cfaf3a87790e3bdfcdca0d1f5e7e42bfdb605240ce513bda0","text":"fn main() -> () { let mut _0: (); // return place in scope 0 at $DIR/inline-generator.rs:8:11: 8:11 let _1: std::ops::GeneratorState< as std::ops::Generator>::Yield, as std::ops::Generator>::Return>; // in scope 0 at $DIR/inline-generator.rs:9:9: 9:11 let mut _2: std::pin::Pin<&mut impl std::ops::Generator>; // in scope 0 at $DIR/inline-generator.rs:9:14: 9:32 let mut _3: &mut impl std::ops::Generator; // in scope 0 at $DIR/inline-generator.rs:9:23: 9:31 let mut _4: impl std::ops::Generator; // in scope 0 at $DIR/inline-generator.rs:9:28: 9:31 let _1: std::ops::GeneratorState; // in scope 0 at $DIR/inline-generator.rs:9:9: 9:11 let mut _2: std::pin::Pin<&mut [generator@$DIR/inline-generator.rs:15:5: 15:41]>; // in scope 0 at $DIR/inline-generator.rs:9:14: 9:32 let mut _3: &mut [generator@$DIR/inline-generator.rs:15:5: 15:41]; // in scope 0 at $DIR/inline-generator.rs:9:23: 9:31 let mut _4: [generator@$DIR/inline-generator.rs:15:5: 15:41]; // in scope 0 at $DIR/inline-generator.rs:9:28: 9:31 + let mut _7: bool; // in scope 0 at $DIR/inline-generator.rs:9:14: 9:46 scope 1 { debug _r => _1; // in scope 1 at $DIR/inline-generator.rs:9:9: 9:11"} {"_id":"q-en-rust-e78ac72fac0d572cd0f54e0aa7d93178837aca239790ee32523d4e87e00513fd","text":"| = help: add #![feature(generic_associated_types)] to the crate attributes to enable error[E0658]: where clauses on associated types are unstable (see issue #44265) --> $DIR/feature-gate-generic_associated_types.rs:16:5 | LL | type Pointer2: Deref where T: Clone, U: Clone; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: add #![feature(generic_associated_types)] to the crate attributes to enable error[E0658]: generic associated types are unstable (see issue #44265) --> $DIR/feature-gate-generic_associated_types.rs:22:5 --> $DIR/feature-gate-generic_associated_types.rs:23:5 | LL | type Pointer = Box; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"} {"_id":"q-en-rust-e790c255b297e474bd5fee7860e3d869e40db62b7134b583c9f7cea963f7a893","text":" fn part(_: u16) -> u32 { 1 } fn main() { for n in 100_000.. { //~^ ERROR: literal out of range for `u16` let _ = part(n); } } "} {"_id":"q-en-rust-e7ac36f4474f8c909549840bc2c12bdee67bc0ad3625456d3dec69799d0119bb","text":" error[E0726]: implicit elided lifetime not allowed here --> $DIR/wf-in-foreign-fn-decls-issue-80468.rs:13:16 | LL | impl Trait for Ref {} | ^^^- help: indicate the anonymous lifetime: `<'_>` error[E0308]: mismatched types --> $DIR/wf-in-foreign-fn-decls-issue-80468.rs:16:21 | LL | pub fn repro(_: Wrapper); | ^^^^^^^^^^^^ lifetime mismatch | = note: expected trait `Trait` found trait `Trait` note: the anonymous lifetime #1 defined on the method body at 16:5... --> $DIR/wf-in-foreign-fn-decls-issue-80468.rs:16:5 | LL | pub fn repro(_: Wrapper); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: ...does not necessarily outlive the static lifetime error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-e7bbf5f78ef1850d8eb1d35e35864a2fe23e4d2854334bf96f228b0a71142e27","text":"} // walk type and init value self.visit_ty(typ); if let Some(expr) = expr { self.visit_expr(expr); } self.nest_tables(id, |v| { v.visit_ty(typ); if let Some(expr) = expr { v.visit_expr(expr); } }); } // FIXME tuple structs should generate tuple-specific data."} {"_id":"q-en-rust-e7c693d7a01ec8d18fb04b551b2a37a5dba71f5fcea97d5c9f9c241e0ca2a14b","text":"LL - fn f4(x1: Box, x2: Box, x3: Box) { LL + fn f4(x1: Box, x2: Box, x3: Box) { | help: consider borrowing here | LL | let y: &X = *x1; | + error[E0277]: the size for values of type `X` cannot be known at compilation time --> $DIR/unsized6.rs:32:9"} {"_id":"q-en-rust-e849e82e1b62b1909fd17f0206582630eff2ff1f9da5e60a64b3dbd00c24f455","text":" #![deny(unused_must_use)] use std::{ops::Deref, pin::Pin}; #[must_use] struct MustUse; #[must_use] struct MustUsePtr<'a, T>(&'a T); impl<'a, T> Deref for MustUsePtr<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.0 } } fn pin_ref() -> Pin<&'static ()> { Pin::new(&()) } fn pin_ref_mut() -> Pin<&'static mut ()> { Pin::new(unimplemented!()) } fn pin_must_use_ptr() -> Pin> { Pin::new(MustUsePtr(&())) } fn pin_box() -> Pin> { Box::pin(()) } fn pin_box_must_use() -> Pin> { Box::pin(MustUse) } fn main() { pin_ref(); pin_ref_mut(); pin_must_use_ptr(); //~ ERROR unused pinned `MustUsePtr` that must be used pin_box(); pin_box_must_use(); //~ ERROR unused pinned boxed `MustUse` that must be used } "} {"_id":"q-en-rust-e8c472858b8da5e909abb968dd72d8abd6ce3dfafdb55879a0e8a4190248ba80","text":"} else { // recent versions of gcc can be configured to generate position // independent executables by default. We have to pass -no-pie to // explicitly turn that off. if sess.target.target.options.linker_is_gnu { // explicitly turn that off. Not applicable to ld. if sess.target.target.options.linker_is_gnu && sess.linker_flavor() != LinkerFlavor::Ld { cmd.no_position_independent_executable(); } }"} {"_id":"q-en-rust-e8d28cf547f5d458be1e9467b59e9f362378dd25e2bef29b76910d6da2218172","text":" // Regression test for issue #124935 // Tests that we still emit an error after an item. fn main() { } ; //~ ERROR expected item, found `;` "} {"_id":"q-en-rust-e9104fddb1b54fc755c4b23a7a21201a66795ef1747cd059b551069a1adc9e93","text":"} } fn bound_from_single_component( &self, component: &Component<'tcx>, visited: &mut SsoHashSet>, ) -> VerifyBound<'tcx> { match *component { Component::Region(lt) => VerifyBound::OutlivedBy(lt), Component::Param(param_ty) => self.param_bound(param_ty), Component::Projection(projection_ty) => self.projection_bound(projection_ty, visited), Component::EscapingProjection(ref components) => { self.bound_from_components(components, visited) } Component::UnresolvedInferenceVariable(v) => { // ignore this, we presume it will yield an error // later, since if a type variable is not resolved by // this point it never will be self.tcx.sess.delay_span_bug( rustc_span::DUMMY_SP, &format!(\"unresolved inference variable in outlives: {:?}\", v), ); // add a bound that never holds VerifyBound::AnyBound(vec![]) } } } /// Searches the environment for where-clauses like `G: 'a` where /// `G` is either some type parameter `T` or a projection like /// `T::Item`. Returns a vector of the `'a` bounds it can find."} {"_id":"q-en-rust-e9268b72d9ca95642c930e36f83f5ea860a671a8ab2479910eda98e7682f110c","text":"for (region_a, region_a_idx) in ®ions { // Ignore `'static` lifetimes for the purpose of this lint: it's // because we know it outlives everything and so doesn't give meaningful // clues if let ty::ReStatic = **region_a { // clues. Also ignore `ReError`, to avoid knock-down errors. if let ty::ReStatic | ty::ReError(_) = **region_a { continue; } // For each region argument (e.g., `'a` in our example), check for a"} {"_id":"q-en-rust-e92b422ab3411c7ceea3a8c49d27fa42862ef4a4166c1071938d2c3294c61be4","text":" // edition:2018 use std::{future::Future, marker::PhantomData}; fn spawn(future: T) -> PhantomData where T: Future, { loop {} } #[derive(Debug)] struct IncomingServer {} impl IncomingServer { async fn connection_handler(handler: impl Sized) -> Result { //~^ ERROR expected type, found variant `Ok` [E0573] loop {} } async fn spawn(&self, request_handler: impl Sized) { async move { spawn(Self::connection_handler(&request_handler)); }; } } fn main() {} "} {"_id":"q-en-rust-e95d66186ae6b8cf52ccdbe33814d52a61f85499a35c051f97a0d26ab582cd5a","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 std::fmt::Debug; const CONST_0: Debug+Sync = *(&0 as &(Debug+Sync)); //~^ ERROR `std::fmt::Debug + Sync + 'static: std::marker::Sized` is not satisfied //~| NOTE does not have a constant size known at compile-time //~| NOTE constant expressions must have a statically known size const CONST_FOO: str = *\"foo\"; //~^ ERROR `str: std::marker::Sized` is not satisfied //~| NOTE does not have a constant size known at compile-time //~| NOTE constant expressions must have a statically known size static STATIC_1: Debug+Sync = *(&1 as &(Debug+Sync)); //~^ ERROR `std::fmt::Debug + Sync + 'static: std::marker::Sized` is not satisfied //~| NOTE does not have a constant size known at compile-time //~| NOTE constant expressions must have a statically known size static STATIC_BAR: str = *\"bar\"; //~^ ERROR `str: std::marker::Sized` is not satisfied //~| NOTE does not have a constant size known at compile-time //~| NOTE constant expressions must have a statically known size fn main() { println!(\"{:?} {:?} {:?} {:?}\", &CONST_0, &CONST_FOO, &STATIC_1, &STATIC_BAR); } "} {"_id":"q-en-rust-e9993b8c3cf00f6a602a9b834fdd2d1ade2b669f44f30eb45bd93153a5db920c","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":"q-en-rust-e9aaaf2cd065ac58a554e118e99d5416102756e8380f2eb365e0ce3766f05794","text":" #![deny(suspicious_auto_trait_impls)] auto trait Trait

    {} //~ ERROR auto traits cannot have generic parameters //~^ ERROR auto traits are experimental and possibly buggy impl

    Trait

    for () {} fn main() {} "} {"_id":"q-en-rust-e9b7c024e4df56d59a7a57a981d5bf699d1849b8e2c58d6f0ac551adf411a5e1","text":"} } fn async_block_with_borrow_named_lifetime<'a>(x: &'a u8) -> impl Future + 'a { async move { await!(wake_and_yield_once()); *x } } fn async_nonmove_block(x: u8) -> impl Future { async move { let future = async {"} {"_id":"q-en-rust-e9e073fffbdb9743cd2d6d8d0202a47f945d065ca888fa0445a133912a0b6705","text":"err.multipart_suggestion_verbose(descr, suggestion, Applicability::MaybeIncorrect); err } Res::Def(DefKind::Variant, _) if expr.is_none() => { err.span_label(span, format!(\"not a {expected}\")); let fields = &tcx.expect_variant_res(res).fields.raw; let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi()); let (msg, sugg) = if fields.is_empty() { (\"use the struct variant pattern syntax\".to_string(), \" {}\".to_string()) } else { let msg = format!( \"the struct variant's field{s} {are} being ignored\", s = pluralize!(fields.len()), are = pluralize!(\"is\", fields.len()) ); let fields = fields .iter() .map(|field| format!(\"{}: _\", field.name.to_ident_string())) .collect::>() .join(\", \"); let sugg = format!(\" {{ {} }}\", fields); (msg, sugg) }; err.span_suggestion_verbose( qpath.span().shrink_to_hi().to(span.shrink_to_hi()), msg, sugg, Applicability::HasPlaceholders, ); err } _ => err.with_span_label(span, format!(\"not a {expected}\")), } .emit()"} {"_id":"q-en-rust-e9f61a54197ce3688e6928b1e71da06c69968fd2e0129acbcb3363af166334f6","text":"LL - fn f3(x1: Box, x2: Box, x3: Box) { LL + fn f3(x1: Box, x2: Box, x3: Box) { | help: consider borrowing here | LL | let y: &X = *x1; | + error[E0277]: the size for values of type `X` cannot be known at compilation time --> $DIR/unsized6.rs:24:9"} {"_id":"q-en-rust-e9fe4c232018d65f9e79ed0bde17b2d832dc28d77ac7502b5e0eb990d9bba873","text":"if c.pgp { pgp::init(c.root); } else { warn(\"command \"gpg\" is not found\"); warn(\"you have to install \"gpg\" from source \" + \" or package manager to get it to work correctly\"); } c"} {"_id":"q-en-rust-ea0874a951079ef0431383bdf3c1947a28cd2fa5bad1121c8df79fb1128d4cc7","text":" error[E0425]: cannot find function `foo1` in crate `similar_unstable_method` --> $DIR/issue-109177.rs:7:30 | LL | similar_unstable_method::foo1(); | ^^^^ help: a function with a similar name exists: `foo` | ::: $DIR/auxiliary/similar-unstable-method.rs:5:1 | LL | pub fn foo() {} | ------------ similarly named function `foo` defined here error[E0599]: no method named `foo1` found for struct `Foo` in the current scope --> $DIR/issue-109177.rs:11:9 | LL | foo.foo1(); | ^^^^ method not found in `Foo` error: aborting due to 2 previous errors Some errors have detailed explanations: E0425, E0599. For more information about an error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-ea1c3dc248f4079bd9dcd9446d916ef4edd6e3261afa89671f763b3a80197af5","text":"n => { let m = cmp::min(n, self.steals); self.steals -= m; self.cnt.fetch_add(n - m, atomics::SeqCst); self.bump(n - m); } } assert!(self.steals >= 0); } self.steals += 1; match data { Data(t) => Ok(t), GoUp(up) => Err(Upgraded(up)),"} {"_id":"q-en-rust-ea2c503475b4dbd573a326124516ea98ac0941b1e1062ce4cae6b361816ffd57","text":"impl Foo for SignedBar { const BAR: i32 = -1; //~^ ERROR E0326 //~^ ERROR implemented const `BAR` has an incompatible type for trait //~| expected u32, //~| found i32 [E0326] } fn main() {}"} {"_id":"q-en-rust-ea41c675a4148ce4b9d5bdc6a2ec2a1c0f13d77be9891049eb25b5359c59b1e9","text":"}; fn a_test() {} #[rustc_main] #[no_coverage] pub fn main() -> () { extern crate test; test::test_main_static(&[&a_test, &m_test, &z_test])"} {"_id":"q-en-rust-ea431610114ba5dccf9f4e91c5d7f9dd25f5b30f295f08a7e97e1cd93977e0f2","text":"variant_index: VariantIdx, dest: PlaceTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx> { let variant_scalar = Scalar::from_u32(variant_index.as_u32()).into(); // Layout computation excludes uninhabited variants from consideration // therefore there's no way to represent those variants in the given layout. if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() { throw_ub!(Unreachable); } match dest.layout.variants { layout::Variants::Single { index } => { if index != variant_index { throw_ub!(InvalidDiscriminant(variant_scalar)); } assert_eq!(index, variant_index); } layout::Variants::Multiple { discr_kind: layout::DiscriminantKind::Tag,"} {"_id":"q-en-rust-ea96a155defecc4763d7b1db481c706afa971e53774e645d44cf7fb03f241f43","text":"/// expression of type `&'static str` which represents all of the literals /// concatenated left-to-right. /// /// Integer and floating point literals are stringified in order to be /// Integer and floating point literals are [stringified](core::stringify) in order to be /// concatenated. /// /// # Examples"} {"_id":"q-en-rust-eaa06fcf2643a031c92516d14ccbce7017737df7d10fe60ab3f230039a49acbe","text":"add_lint_group!(sess, \"rust_2018_idioms\", BARE_TRAIT_OBJECT, UNREACHABLE_PUB); UNREACHABLE_PUB, UNNECESSARY_EXTERN_CRATE); // Guidelines for creating a future incompatibility lint: //"} {"_id":"q-en-rust-eb5b0f3770118ee698a95f40e39c61a9ed312849078ab8b3950b4743095b4481","text":"//~^ ERROR generic associated types are unstable type Pointer2: Deref where T: Clone, U: Clone; //~^ ERROR generic associated types are unstable //~| ERROR where clauses on associated types are unstable } struct Foo;"} {"_id":"q-en-rust-eb6618fac980cae319c1ad807eca0fc5bf7be5cfad112416eb6319be16ed5bc4","text":"} } if dont_insert_main || already_has_main { // FIXME: This code cannot yet handle no_std test cases yet if dont_insert_main || already_has_main || prog.contains(\"![no_std]\") { prog.push_str(everything_else); } else { prog.push_str(\"fn main() {n\"); let returns_result = everything_else.trim_end().ends_with(\"(())\"); let (main_pre, main_post) = if returns_result { (\"fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {\", \"}n_inner().unwrap() }\") } else { (\"fn main() {n\", \"n}\") }; prog.extend([main_pre, everything_else, main_post].iter().cloned()); line_offset += 1; prog.push_str(everything_else); prog.push_str(\"n}\"); } debug!(\"final doctest:n{}\", prog);"} {"_id":"q-en-rust-eb97fb8e46aea26b7adfc1c2227d1042406a667901e024992cfeb314128fd405","text":"fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro { // DefIndex's in root.proc_macro_data have a one-to-one correspondence // with items in 'raw_proc_macros' // with items in 'raw_proc_macros'. // NOTE: If you update the order of macros in 'proc_macro_data' for any reason, // you must also update src/libsyntax_ext/proc_macro_harness.rs // Failing to do so will result in incorrect data being associated // with proc macros when deserialized. let pos = self.root.proc_macro_data.unwrap().decode(self).position(|i| i == id).unwrap(); &self.raw_proc_macros.unwrap()[pos] }"} {"_id":"q-en-rust-ebafbfaae69d31d7cab02992f1c529b1499c414e2aa506780762092251d971c9","text":"| LL | Enum::Foo(a, b) => {} | ^^^^^^^^^^^^^^^ not a tuple struct or tuple variant | help: the struct variant's fields are being ignored | LL | Enum::Foo { a: _, b: _ } => {} | ~~~~~~~~~~~~~~ error[E0769]: tuple variant `Enum::Bar` written as struct variant --> $DIR/recover-from-bad-variant.rs:12:9"} {"_id":"q-en-rust-ebba82269ca096a8b0388d72a161287f1c17a721a2b74c557cef0c14e73b11b1","text":"font-size: 19px; } ul.item-list > li > .out-of-band { font-size: 19px; } h4 > code, h3 > code, .invisible > code { position: inherit; }"} {"_id":"q-en-rust-ebe23e0ac3ae968fdfd766abce1e09d0a2e3fbfb289672220cfcbb15abc42ca7","text":"// We replace self[index] with the last element. Note that if the // bounds check above succeeds there must be a last element (which // can be self[index] itself). let last = ptr::read(self.as_ptr().add(len - 1)); let hole = self.as_mut_ptr().add(index); let value = ptr::read(self.as_ptr().add(index)); let base_ptr = self.as_mut_ptr(); ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); self.set_len(len - 1); ptr::replace(hole, last) value } }"} {"_id":"q-en-rust-ec95870d6e8651cb5bf56f33be65bca826d6c7c732e2a823a20e74be5492d089","text":"/// Swaps the values of two `Cell`s. /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference. /// /// # Panics /// /// This function will panic if `self` and `other` are different `Cell`s that partially overlap. /// (Using just standard library methods, it is impossible to create such partially overlapping `Cell`s. /// However, unsafe code is allowed to e.g. create two `&Cell<[i32; 2]>` that partially overlap.) /// /// # Examples /// /// ```"} {"_id":"q-en-rust-ecba11f2f9e530aa5686fdb95eecf45c844b8901e79b85299a19699da64853da","text":" // force-host // no-prefer-dynamic #![crate_type = \"proc-macro\"] extern crate proc_macro; struct Zeroable; #[proc_macro_derive(Zeroable)] pub fn derive_zeroable(_: proc_macro::TokenStream) -> proc_macro::TokenStream { proc_macro::TokenStream::default() } "} {"_id":"q-en-rust-ecc015723a600e0a6af8c62037a804bf76785cdbbc8595494c8551e377d1d182","text":"t!(std::fs::write(stamp_file, version)) } /// Returns the files modified between the `merge-base` of HEAD and /// Returns the Rust files modified between the `merge-base` of HEAD and /// rust-lang/master and what is now on the disk. /// /// Returns `None` if all files should be formatted. fn get_modified_files(build: &Builder<'_>) -> Option> { fn get_modified_rs_files(build: &Builder<'_>) -> Option> { let Ok(remote) = get_rust_lang_rust_remote() else {return None;}; if !verify_rustfmt_version(build) { return None;"} {"_id":"q-en-rust-ecc1bcf56571757a0315cb9e7786d07e3c5887d630271eca7118d2434883a93d","text":"ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(), _ => None, }; let prev_ambiguity_errors_len = self.ambiguity_errors.len(); let ambiguity_errors_len = |errors: &Vec>| errors.iter().filter(|error| !error.warning).count(); let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors); let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span); // We'll provide more context to the privacy errors later, up to `len`."} {"_id":"q-en-rust-ed1c7c0cf9052d3c7df00194da80ed058591f69ca63254d628a740047e8070e7","text":"// // If the issuing region outlives such a region, its loan escapes the function and // cannot go out of scope. We can early return. if self.regioncx.scc_is_live_at_all_points(scc) { if self.regioncx.is_region_live_at_all_points(successor) { return; } }"} {"_id":"q-en-rust-ed315265e3ba100fe5c8b0cb7cc1ee128edff47bd774ddaf806ba9b7eb66f620","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":"q-en-rust-ed86969ce1f5fe9f315286492fcc9312e8df501249c714f2d91530301983536e","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":"q-en-rust-edc390da0190ea4ae709f2e2ac1b39bd57db6593b5e61f68d12f60f78b7975b4","text":"self.tcx.sess.opts.debugging_opts.inline_mir_threshold }; if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) { debug!(\"#[naked] present - not inlining\"); return false; } if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) { debug!(\"#[cold] present - not inlining\"); return false;"} {"_id":"q-en-rust-edcbb11e350ab658bc208aff87fabf9a72e817bd545627286f6711d822ccca02","text":"Ok((fields, etc)) } #[deny(rustc::untranslatable_diagnostic)] fn report_misplaced_at_in_struct_pat(&self, prev_field: Ident) -> Diag<'a> { debug_assert_eq!(self.token, token::At); let span = prev_field.span.to(self.token.span); if let Some(dot_dot_span) = self.look_ahead(1, |t| if t == &token::DotDot { Some(t.span) } else { None }) { self.dcx().create_err(AtDotDotInStructPattern { span: span.to(dot_dot_span), remove: span.until(dot_dot_span), ident: prev_field, }) } else { self.dcx().create_err(AtInStructPattern { span: span }) } } /// If the user writes `S { ref field: name }` instead of `S { field: ref name }`, we suggest /// the correct code. fn recover_misplaced_pattern_modifiers(&self, fields: &ThinVec, err: &mut Diag<'a>) {"} {"_id":"q-en-rust-edd27e795647abaa01e65c7254ba4776e714d6165cdfe399e2d42f385cfef2b0","text":" // Regression test for #63033. // check-pass // edition: 2018 async fn test1(_: &'static u8, _: &'_ u8, _: &'_ u8) {} async fn test2<'s>(_: &'s u8, _: &'_ &'s u8, _: &'_ &'s u8) {} fn main() {} "} {"_id":"q-en-rust-ede81c77d88fadd2b69d637f1a1b701bd9c4b159734d71a0f1a159dc3a05e889","text":" error: only functions may be used as tests --> $DIR/issue-28134.rs:13:1 | LL | #![test] //~ ERROR only functions may be used as tests | ^^^^^^^^ error: aborting due to previous error "} {"_id":"q-en-rust-edf4511c5b93f48faea13102c553d078c766b843dfe411cd18c136c508f1da76","text":"without modifying the original\"] #[inline] #[track_caller] #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] pub const fn ilog2(self) -> u32 { match self.checked_ilog2() { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } self.checked_ilog2().expect(\"argument of integer logarithm must be positive\") } /// Returns the base 10 logarithm of the number, rounded down. /// /// # Panics /// /// When the number is negative or zero it panics in debug mode and the return value /// is 0 in release mode. /// This function will panic if `self` is less than or equal to zero. /// /// # Example ///"} {"_id":"q-en-rust-edfde4d848e1d05294644e6265709061de542c0d2d841921e16e5a9c861d5ddd","text":"std::env::var(\"TARGET\").is_ok_and(|v| v.contains(\"i586\")) } #[cfg(target_arch = \"x86_64\")] fn f16(){ const_assert!((1f16).to_bits(), 0x3c00); const_assert!(u16::from_be_bytes(1f16.to_be_bytes()), 0x3c00); const_assert!((12.5f16).to_bits(), 0x4a40); const_assert!(u16::from_le_bytes(12.5f16.to_le_bytes()), 0x4a40); const_assert!((1337f16).to_bits(), 0x6539); const_assert!(u16::from_ne_bytes(1337f16.to_ne_bytes()), 0x6539); const_assert!((-14.25f16).to_bits(), 0xcb20); const_assert!(f16::from_bits(0x3c00), 1.0); const_assert!(f16::from_be_bytes(0x3c00u16.to_be_bytes()), 1.0); const_assert!(f16::from_bits(0x4a40), 12.5); const_assert!(f16::from_le_bytes(0x4a40u16.to_le_bytes()), 12.5); const_assert!(f16::from_bits(0x5be0), 252.0); const_assert!(f16::from_ne_bytes(0x5be0u16.to_ne_bytes()), 252.0); const_assert!(f16::from_bits(0xcb20), -14.25); // Check that NaNs roundtrip their bits regardless of signalingness // 0xA is 0b1010; 0x5 is 0b0101 -- so these two together clobbers all the mantissa bits // NOTE: These names assume `f{BITS}::NAN` is a quiet NAN and IEEE754-2008's NaN rules apply! const QUIET_NAN: u16 = f16::NAN.to_bits() ^ 0x0155; const SIGNALING_NAN: u16 = f16::NAN.to_bits() ^ 0x02AA; const_assert!(f16::from_bits(QUIET_NAN).is_nan()); const_assert!(f16::from_bits(SIGNALING_NAN).is_nan()); const_assert!(f16::from_bits(QUIET_NAN).to_bits(), QUIET_NAN); if !has_broken_floats() { const_assert!(f16::from_bits(SIGNALING_NAN).to_bits(), SIGNALING_NAN); } } fn f32() { const_assert!((1f32).to_bits(), 0x3f800000); const_assert!(u32::from_be_bytes(1f32.to_be_bytes()), 0x3f800000);"} {"_id":"q-en-rust-ee1969dfe293d7842ff718a6e57c76f6841d0532b1f64958137644e6961a44e1","text":"suffix: &'pat [Pat<'tcx>], ) { let tcx = self.tcx; let (min_length, exact_size) = match place .clone() .into_place(tcx, self.typeck_results) .ty(&self.local_decls, tcx) .ty .kind() let (min_length, exact_size) = if let Ok(place_resolved) = place.clone().try_upvars_resolved(tcx, self.typeck_results) { ty::Array(_, length) => (length.eval_usize(tcx, self.param_env), true), _ => ((prefix.len() + suffix.len()).try_into().unwrap(), false), match place_resolved .into_place(tcx, self.typeck_results) .ty(&self.local_decls, tcx) .ty .kind() { ty::Array(_, length) => (length.eval_usize(tcx, self.param_env), true), _ => ((prefix.len() + suffix.len()).try_into().unwrap(), false), } } else { ((prefix.len() + suffix.len()).try_into().unwrap(), false) }; match_pairs.extend(prefix.iter().enumerate().map(|(idx, subpattern)| {"} {"_id":"q-en-rust-ee1b06b1ba120e82d03cda2b54cf96dbd8c01f9424ae71121eef6e2c5a33910c","text":" error[E0596]: cannot borrow data in a `&` reference as mutable --> $DIR/issue-52240.rs:9:27 | LL | if let (Some(Foo::Bar(ref mut val)), _) = (&arr.get(0), 0) { | ^^^^^^^^^^^ cannot borrow as mutable error: aborting due to previous error For more information about this error, try `rustc --explain E0596`. "} {"_id":"q-en-rust-ee211adc3e710542c6fb4b5ba0a5e11a7c8aabb9de51b97f5297d855630c0eb4","text":"rscope: &RegionScope, span: Span, principal_trait_ref: ty::PolyTraitRef<'tcx>, mut projection_bounds: Vec>, // Empty for boxed closures projection_bounds: Vec>, // Empty for boxed closures partitioned_bounds: PartitionedBounds) -> ty::ExistentialBounds<'tcx> {"} {"_id":"q-en-rust-ee5a133a619c4748305d18b9e2f8f8703076ccc86688f95fb86c0bb9fb5fa318","text":"/// A free importable items suggested in case of resolution failure. struct ImportSuggestion { did: Option, path: Path, }"} {"_id":"q-en-rust-ee65442dc6a3e5a226c1cecd5dbf9af4d222b440e50222c9c7ef08ca5cce71d8","text":"\"cargo_metadata 0.9.1\", \"clippy-mini-macro-test\", \"clippy_lints\", \"compiletest_rs\", \"compiletest_rs 0.5.0\", \"derive-new\", \"lazy_static 1.4.0\", \"regex\","} {"_id":"q-en-rust-ee7a8565674f1b5bd07fc0bf9a2e8dea24de6353a52dc98e1b4fef236b96b1e5","text":" error: pretty-print failed to write `/tmp/` due to $ERROR_MESSAGE error: aborting due to previous error "} {"_id":"q-en-rust-eea5dde6ac2882f3f073990525abea2479e4685d6ed92a28ced89500e8aac369","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. // ignore-cross-compile #![crate_name = \"foo\"] pub trait SomeTrait {} pub struct SomeStruct; // @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#19' impl SomeTrait for usize {} // @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#22-24' impl SomeTrait for SomeStruct { // deliberately multi-line impl } "} {"_id":"q-en-rust-eec160e17946ed6d3ff4166c8e54c778217c3135cf54bf6f236fada0b2462d22","text":"let gcx = self.infcx.tcx.global_tcx(); let mut orig_values = OriginalQueryValues::default(); let c_data = self.infcx.canonicalize_query( // HACK(matthewjasper) `'static` is special-cased in selection, // so we cannot canonicalize it. let c_data = self.infcx.canonicalize_hr_query_hack( &self.param_env.and(*data), &mut orig_values); debug!(\"QueryNormalizer: c_data = {:#?}\", c_data); debug!(\"QueryNormalizer: orig_values = {:#?}\", orig_values);"} {"_id":"q-en-rust-eee11fcfdf50e1ed51c5857271c24ee01f470b54f5f0f85d065f8b45822c4f00","text":"opt local-rust 0 \"use an installed rustc rather than downloading a snapshot\" opt pax-flags 0 \"apply PaX flags to rustc binaries (required for GRSecurity/PaX-patched kernels)\" opt inject-std-version 1 \"inject the current compiler version of libstd into programs\" opt rpath 1 \"build rpaths into rustc itself\" valopt prefix \"/usr/local\" \"set installation prefix\" valopt local-rust-root \"/usr/local\" \"set prefix for local rust binary\" valopt llvm-root \"\" \"set LLVM root\""} {"_id":"q-en-rust-eef680a99e77b2e036f31552bb022a717d6d60d1c661db6361c2f959b199208e","text":"# Make `RefCell` store additional debugging information, which is printed out when # a borrow error occurs debug_refcell = [] [lints.rust.unexpected_cfgs] level = \"warn\" # x.py uses beta cargo, so `check-cfg` entries do not yet take effect # for rust-lang/rust. But for users of `-Zbuild-std` it does. # The unused warning is waiting for rust-lang/cargo#13925 to reach beta. check-cfg = [ 'cfg(bootstrap)', 'cfg(no_fp_fmt_parse)', 'cfg(stdarch_intel_sde)', # This matches `EXTRA_CHECK_CFGS` in `src/bootstrap/src/lib.rs`. 'cfg(feature, values(any()))', ] "} {"_id":"q-en-rust-ef075b540bf8c941ed1b072710bc1cb7bef70918c2ebb78c4689e96237ff20f8","text":"/// Metadata encoding version. /// NB: increment this if you change the format of metadata such that /// the rustc version can't be found to compare with `RUSTC_VERSION`. pub const METADATA_VERSION: u8 = 3; /// the rustc version can't be found to compare with `rustc_version()`. pub const METADATA_VERSION: u8 = 4; /// Metadata header which includes `METADATA_VERSION`. /// To get older versions of rustc to ignore this metadata, /// there are 4 zero bytes at the start, which are treated /// as a length of 0 by old compilers. /// /// This header is followed by the position of the `CrateRoot`. /// This header is followed by the position of the `CrateRoot`, /// which is encoded as a 32-bit big-endian unsigned integer, /// and further followed by the rustc version string. pub const METADATA_HEADER: &'static [u8; 12] = &[0, 0, 0, 0, b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];"} {"_id":"q-en-rust-ef1b02e6a1f1ea971b9d817c4d2f158e0e018bdb1d1993de47d77e41276065a2","text":"pub struct BufWriter { inner: Option, buf: Vec, // #30888: If the inner writer panics in a call to write, we don't want to // write the buffered data a second time in BufWriter's destructor. This // flag tells the Drop impl if it should skip the flush. panicked: bool, } /// An error returned by `into_inner` which combines an error that"} {"_id":"q-en-rust-ef3e74a6f6c75e4b70b4d36695cc625f10d8fc71dd0300846fd658c5f2fe6a52","text":"unmapped_path, src, Pos::from_usize(start_pos), )); )?); let mut files = self.files.borrow_mut();"} {"_id":"q-en-rust-ef50fc9c666efee9aa03bb94ee4bdec97a2112c43108002e1f759cf12e12468d","text":"use std::env; use bootstrap::{Build, Config, Subcommand}; use bootstrap::{Build, Config, Subcommand, VERSION}; fn main() { let args = env::args().skip(1).collect::>(); let config = Config::parse(&args); let changelog_suggestion = check_version(&config); // check_version warnings are not printed during setup let changelog_suggestion = if matches!(config.cmd, Subcommand::Setup {..}) { None } else { check_version(&config) }; // NOTE: Since `./configure` generates a `config.toml`, distro maintainers will see the // changelog warning, not the `x.py setup` message."} {"_id":"q-en-rust-ef60a2ef6bb3985a3fd3b8e0f5dbd50d7d532c0f6aea928c58e62cfbc6d2ba4e","text":"let path_data = match path_data { Some(pd) => pd, None => { span_bug!(path.span, \"Unexpected def kind while looking up path in `{}`\", self.span.snippet(path.span)) return; } };"} {"_id":"q-en-rust-ef945189dd4e8823523ba99f957006562f23e986183a0ba5ac9ec518f4cac436","text":" error[E0310]: the parameter type `T` may not live long enough --> $DIR/implied-bounds-unnorm-associated-type-3.rs:19:5 | LL | fn zero_copy_from<'b>(cart: &'b [T]) -> &'b [T] { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider adding an explicit lifetime bound `T: 'static`... = note: ...so that the type `[T]` will meet its required lifetime bounds error: aborting due to previous error For more information about this error, try `rustc --explain E0310`. "} {"_id":"q-en-rust-efa1d12ec444e148f92cbf0828276880d7227bbc44c9bfd9f61d7fddf23d3455","text":" struct Bug([u8; panic!(1)]); //~ ERROR panicking in constants is unstable // Note: non-`&str` panic arguments gained a separate error in PR #80734 // which is why this doesn't match the issue struct Bug([u8; panic!(\"panic\")]); //~ ERROR panicking in constants is unstable fn main() {}"} {"_id":"q-en-rust-efac5abc02554e1d108f26bd0ed4c7f75374265572cc071b27dfba475f1abee4","text":"asm_args: cvs![\"-mthumb-interwork\", \"-march=armv4t\", \"-mlittle-endian\",], // minimum extra features, these cannot be disabled via -C features: \"+soft-float,+strict-align\".into(), // Also force-enable 32-bit atomics, which allows the use of atomic load/store only. // The resulting atomics are ABI incompatible with atomics backed by libatomic. features: \"+soft-float,+strict-align,+atomics-32\".into(), panic_strategy: PanicStrategy::Abort, relocation_model: RelocModel::Static,"} {"_id":"q-en-rust-efef4a20b03ad908b92c508fc8fc992f7e169c28030195b05c45fc9477111faa","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":"q-en-rust-eff4ab1745ca288c2c894f72ee23285603eacdca8a466ba28c17e3deb2e9b93e","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":"q-en-rust-f05ce288481453a9127917ff0ee50378f9a71a808bca65680b75c451b6c5ca71","text":"ConditionalPass::always(CHECK_CUSTOM_CODE_CLASSES), ConditionalPass::always(COLLECT_TRAIT_IMPLS), ConditionalPass::always(CHECK_DOC_TEST_VISIBILITY), ConditionalPass::always(STRIP_ALIASED_NON_LOCAL), ConditionalPass::new(STRIP_HIDDEN, WhenNotDocumentHidden), ConditionalPass::new(STRIP_PRIVATE, WhenNotDocumentPrivate), ConditionalPass::new(STRIP_PRIV_IMPORTS, WhenDocumentPrivate),"} {"_id":"q-en-rust-f07362d3113b05726567d26d7a574253e66af471ca5f0d8c5690f32483453cb4","text":"| (ProjectionElem::Index(..), ProjectionElem::ConstantIndex { .. }) | (ProjectionElem::Index(..), ProjectionElem::Subslice { .. }) | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Index(..)) | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::ConstantIndex { .. }) | (ProjectionElem::ConstantIndex { .. }, ProjectionElem::Subslice { .. }) | (ProjectionElem::Subslice { .. }, ProjectionElem::Index(..)) | (ProjectionElem::Subslice { .. }, ProjectionElem::ConstantIndex { .. }) | (ProjectionElem::Subslice { .. }, ProjectionElem::Subslice { .. }) => { | (ProjectionElem::Subslice { .. }, ProjectionElem::Index(..)) => { // Array indexes (`a[0]` vs. `a[i]`). These can either be disjoint // (if the indexes differ) or equal (if they are the same), so this // is the recursive case that gives \"equal *or* disjoint\" its meaning. // // Note that by construction, MIR at borrowck can't subdivide // `Subslice` accesses (e.g. `a[2..3][i]` will never be present) - they // are only present in slice patterns, and we \"merge together\" nested // slice patterns. That means we don't have to think about these. It's // probably a good idea to assert this somewhere, but I'm too lazy. // // FIXME(#8636) we might want to return Disjoint if // both projections are constant and disjoint. debug!(\"place_element_conflict: DISJOINT-OR-EQ-ARRAY\"); debug!(\"place_element_conflict: DISJOINT-OR-EQ-ARRAY-INDEX\"); Overlap::EqualOrDisjoint } (ProjectionElem::ConstantIndex { offset: o1, min_length: _, from_end: false }, ProjectionElem::ConstantIndex { offset: o2, min_length: _, from_end: false }) | (ProjectionElem::ConstantIndex { offset: o1, min_length: _, from_end: true }, ProjectionElem::ConstantIndex { offset: o2, min_length: _, from_end: true }) => { if o1 == o2 { debug!(\"place_element_conflict: DISJOINT-OR-EQ-ARRAY-CONSTANT-INDEX\"); Overlap::EqualOrDisjoint } else { debug!(\"place_element_conflict: DISJOINT-ARRAY-CONSTANT-INDEX\"); Overlap::Disjoint } } (ProjectionElem::ConstantIndex { offset: offset_from_begin, min_length: min_length1, from_end: false }, ProjectionElem::ConstantIndex { offset: offset_from_end, min_length: min_length2, from_end: true }) | (ProjectionElem::ConstantIndex { offset: offset_from_end, min_length: min_length1, from_end: true }, ProjectionElem::ConstantIndex { offset: offset_from_begin, min_length: min_length2, from_end: false }) => { // both patterns matched so it must be at least the greater of the two let min_length = max(min_length1, min_length2); // `offset_from_end` can be in range `[1..min_length]`, 1 indicates the last // element (like -1 in Python) and `min_length` the first. // Therefore, `min_length - offset_from_end` gives the minimal possible // offset from the beginning if *offset_from_begin >= min_length - offset_from_end { debug!(\"place_element_conflict: DISJOINT-OR-EQ-ARRAY-CONSTANT-INDEX-FE\"); Overlap::EqualOrDisjoint } else { debug!(\"place_element_conflict: DISJOINT-ARRAY-CONSTANT-INDEX-FE\"); Overlap::Disjoint } } (ProjectionElem::ConstantIndex { offset, min_length: _, from_end: false }, ProjectionElem::Subslice {from, .. }) | (ProjectionElem::Subslice {from, .. }, ProjectionElem::ConstantIndex { offset, min_length: _, from_end: false }) => { if offset >= from { debug!( \"place_element_conflict: DISJOINT-OR-EQ-ARRAY-CONSTANT-INDEX-SUBSLICE\"); Overlap::EqualOrDisjoint } else { debug!(\"place_element_conflict: DISJOINT-ARRAY-CONSTANT-INDEX-SUBSLICE\"); Overlap::Disjoint } } (ProjectionElem::ConstantIndex { offset, min_length: _, from_end: true }, ProjectionElem::Subslice {from: _, to }) | (ProjectionElem::Subslice {from: _, to }, ProjectionElem::ConstantIndex { offset, min_length: _, from_end: true }) => { if offset > to { debug!(\"place_element_conflict: DISJOINT-OR-EQ-ARRAY-CONSTANT-INDEX-SUBSLICE-FE\"); Overlap::EqualOrDisjoint } else { debug!(\"place_element_conflict: DISJOINT-ARRAY-CONSTANT-INDEX-SUBSLICE-FE\"); Overlap::Disjoint } } (ProjectionElem::Subslice { .. }, ProjectionElem::Subslice { .. }) => { debug!(\"place_element_conflict: DISJOINT-OR-EQ-ARRAY-SUBSLICES\"); Overlap::EqualOrDisjoint } (ProjectionElem::Deref, _) | (ProjectionElem::Field(..), _) | (ProjectionElem::Index(..), _)"} {"_id":"q-en-rust-f0a410de8c8597b117ce1b6a8470c3e809da14af0d57c042b6763c6b8cd9d82f","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. // Regression test for issue #25436: check that things which can be // followed by any token also permit X* to come afterwards. macro_rules! foo { ( $a:expr $($b:tt)* ) => { }; //~ ERROR not allowed for `expr` fragments ( $a:ty $($b:tt)* ) => { }; //~ ERROR not allowed for `ty` fragments } fn main() { } "} {"_id":"q-en-rust-f0c63ed35c906c054b6913cba63bb2f3cdc010a947be63d3dd5ac73b701c3cc6","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":"q-en-rust-f0c6d56a8dc340e3844796183452c00ffe8019dc4335a191112cd5dc6a426d9d","text":" error: `_x @` is not allowed in a tuple --> $DIR/issue-72574-1.rs:4:14 | LL | (_a, _x @ ..) => {} | ^^^^^^^ this is only allowed in slice patterns | = help: remove this and bind each tuple field independently help: if you don't need to use the contents of _x, discard the tuple's remaining fields | LL | (_a, ..) => {} | ^^ error: aborting due to previous error "} {"_id":"q-en-rust-f0f7570dc1baa0ad7d5b2dd9eb385db7879b2687a01a829178a624b014323d5d","text":" #![feature(half_open_range_patterns)] macro_rules! funny { ($a:expr, $b:ident) => { match [1, 2] { [$a, $b] => {} } }; } fn main() { funny!(a, a); //~^ ERROR cannot find value `a` in this scope //~| ERROR arbitrary expressions aren't allowed in patterns } "} {"_id":"q-en-rust-f1370de04b304f0392182dadfccbd24e46eb7de5114473b2908f029e1db1e549","text":" //@ edition: 2021 //@ check-pass //@ revisions: current next //@ ignore-compare-mode-next-solver (explicit revisions) //@[next] compile-flags: -Znext-solver #![feature(async_closure)] use std::future::Future; use std::any::Any; struct Struct; impl Struct { fn method(&self) {} } fn fake_async_closure(_: F) where F: Fn(Struct) -> Fut, Fut: Future, {} fn main() { fake_async_closure(async |s| { s.method(); }) } "} {"_id":"q-en-rust-f1496eec00a00a28550af767860fda4743a39d8abb5b96b319fde348e50f8fec","text":"let gen_sig = substs.as_generator().poly_sig(); // (1) Feels icky to skip the binder here, but OTOH we know // that the self-type is an generator type and hence is // NOTE: The self-type is a generator type and hence is // in fact unparameterized (or at least does not reference any // regions bound in the obligation). Still probably some // refactoring could make this nicer. // regions bound in the obligation). let self_ty = obligation .predicate .self_ty() .no_bound_vars() .expect(\"unboxed closure type should not capture bound vars from the predicate\"); let trait_ref = super::util::generator_trait_ref_and_outputs( self.tcx(), obligation.predicate.def_id(), obligation.predicate.skip_binder().self_ty(), // (1) self_ty, gen_sig, ) .map_bound(|(trait_ref, ..)| trait_ref);"} {"_id":"q-en-rust-f155377e39659987c096b505d2ac3d9172dd4d1b596374bdcc239af87484f893","text":"LL | fn is_unwindsafe(_: impl std::panic::UnwindSafe) {} | ^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_unwindsafe` error[E0277]: the type `&mut (dyn Any + 'static)` may not be safely transferred across an unwind boundary --> $DIR/async-is-unwindsafe.rs:12:5 | LL | is_unwindsafe(async { | _____^_____________- | |_____| | || LL | || LL | || LL | || use std::ptr::null; ... || LL | || drop(cx_ref); LL | || }); | ||_____-^ `&mut (dyn Any + 'static)` may not be safely transferred across an unwind boundary | |_____| | within this `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}` | = help: within `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}`, the trait `UnwindSafe` is not implemented for `&mut (dyn Any + 'static)`, which is required by `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}: UnwindSafe` note: future does not implement `UnwindSafe` as this value is used across an await --> $DIR/async-is-unwindsafe.rs:26:18 | LL | let mut cx = Context::from_waker(&waker); | ------ has type `Context<'_>` which does not implement `UnwindSafe` ... LL | async {}.await; // this needs an inner await point | ^^^^^ await occurs here, with `mut cx` maybe used later note: required by a bound in `is_unwindsafe` --> $DIR/async-is-unwindsafe.rs:3:26 | LL | fn is_unwindsafe(_: impl std::panic::UnwindSafe) {} | ^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_unwindsafe` error: aborting due to 2 previous errors error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0277`."} {"_id":"q-en-rust-f1b0fae89bfd07c38c7b05307750bdd1d168d4d8c7858077dd60f3b0297dd2aa","text":" Subproject commit d30da544a8afc5d78391dee270bdf40e74a215d3 Subproject commit c8a8767c56ad3d3f4eb45c87b95026936fb9aa35 "} {"_id":"q-en-rust-f1bb32c3235f87b1e2ed4e27910efb712bb4519b417a29063c3b5aa3588d91d6","text":".map(|res| (res, extra_fragment.clone())), type_ns: match self.resolve( path_str, disambiguator, TypeNS, ¤t_item, base_node,"} {"_id":"q-en-rust-f1d239be0dfe5d0e0f474dbc4722998542c559d16af3ddf44e3482eb6bc06c21","text":"assert_eq!(find_best_match_for_name(&input, Symbol::intern(\"1111111111\"), None), None); let input = vec![Symbol::intern(\"aAAA\")]; let input = vec![Symbol::intern(\"AAAA\")]; assert_eq!( find_best_match_for_name(&input, Symbol::intern(\"AAAA\"), None), Some(Symbol::intern(\"aAAA\")) find_best_match_for_name(&input, Symbol::intern(\"aaaa\"), None), Some(Symbol::intern(\"AAAA\")) ); let input = vec![Symbol::intern(\"AAAA\")]; // Returns None because `lev_distance > max_dist / 3` assert_eq!(find_best_match_for_name(&input, Symbol::intern(\"aaaa\"), None), None); let input = vec![Symbol::intern(\"AAAA\")]; assert_eq!( find_best_match_for_name(&input, Symbol::intern(\"aaaa\"), Some(4)), Some(Symbol::intern(\"AAAA\"))"} {"_id":"q-en-rust-f1d7a4453d594235b3374adf406de82b0537df3d4a6dd2ec2af95656c0e1e600","text":"let mut _4: &mut [T]; // in scope 0 at $DIR/issue-58867-inline-as-ref-as-mut.rs:3:5: 3:6 scope 1 { debug self => _4; // in scope 1 at $SRC_DIR/libcore/convert/mod.rs:LL:COL let mut _5: &mut [T]; // in scope 1 at $DIR/issue-58867-inline-as-ref-as-mut.rs:3:5: 3:15 } bb0: {"} {"_id":"q-en-rust-f1da61bae2a13ae3cd71037d2b2669fd01e5fb5ef51e6fcf3f931c8024bfd61f","text":"let prog = time(sess.time_passes(), \"running linker\", || cmd.output()); match prog { Ok(prog) => { fn escape_string(s: &[u8]) -> String { str::from_utf8(s).map(|s| s.to_owned()) .unwrap_or_else(|_| { let mut x = \"Non-UTF-8 output: \".to_string(); x.extend(s.iter() .flat_map(|&b| ascii::escape_default(b)) .map(|b| char::from_u32(b as u32).unwrap())); x }) } if !prog.status.success() { sess.err(&format!(\"linking with `{}` failed: {}\", pname,"} {"_id":"q-en-rust-f1fdaaa237e38421ae195cb642abc0ef0029238584fff4faee3c670498404b7e","text":" Subproject commit 097d8908339e20435078233a55a1a3335fe7c2eb Subproject commit 9ed6f96f2ff85753c5a6ac290ee88ecb2831ab2e "} {"_id":"q-en-rust-f231daaa99862eff128573c58507909f093546aab8bcc48857110ad541219fd3","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":"q-en-rust-f24aa3b0b615278a943fad5391ee82d97e859e43a820efb533e4a320871a478f","text":"fn f(f: F) where F: Fn(isize) { f(10) } fn main() { f(|i| { assert_eq!(i , 10) }) } fn main() { f(|i| { assert_eq!(i, 10) }) } "} {"_id":"q-en-rust-f274508619a7be8465dd90e0e5d46d78fca673c78f059fa23e92203c5704a5cc","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":"q-en-rust-f2745cb762cb76c3104f9464e0033a50a48dd09000f49d307d57ade7828e51c5","text":"source_file } } }; Ok(lrc_sf) } /// Allocates a new SourceFile representing a source file from an external"} {"_id":"q-en-rust-f28a2dcadd1808e007e7abcf609702f883dbdb6f28a884598351dc8f8154e1aa","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":"q-en-rust-f2991926e611e1a4979859a9af68fc46e205b06bb53ecefc8008c1282dd705df","text":" // aux-build: similar-unstable-method.rs extern crate similar_unstable_method; fn main() { // FIXME: this function should not suggest the `foo` function. similar_unstable_method::foo1(); //~^ ERROR cannot find function `foo1` in crate `similar_unstable_method` [E0425] let foo = similar_unstable_method::Foo; foo.foo1(); //~^ ERROR no method named `foo1` found for struct `Foo` in the current scope [E0599] } "} {"_id":"q-en-rust-f2bc73144ab9c5c31b1225da88364e2b06202cd74bf8407810ff7ecb610f1daf","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() { *return; //~ ERROR type `!` cannot be dereferenced } "} {"_id":"q-en-rust-f2c5b4d6e3c14cf9345d767738799ddeb10680fbf46c107b4c10c60a4780c048","text":" Subproject commit 50ab09fb43f038e4f824eea6cb278f560d3e8621 Subproject commit 859fb269364623b17e092efaba3f94e70ce97c5e "} {"_id":"q-en-rust-f2ecb1b495fcf0e7f5c61d4aa0d6aa5db97e7b48db48511ccc483c666911c224","text":"use rustc::mir::{Mir, Place}; use rustc::mir::{Projection, ProjectionElem}; use rustc::ty::{self, TyCtxt}; use std::cmp::max; pub(super) fn places_conflict<'gcx, 'tcx>( tcx: TyCtxt<'_, 'gcx, 'tcx>,"} {"_id":"q-en-rust-f30a4a313f877b3bbcc8c6bf08f0e468ccaa46514db69c115a3d06715268e1fc","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":"q-en-rust-f30be7581831d0c62372aede5df3c7290fc6710933abfb92a644e58d3b72bc5d","text":" warning: trait-associated function `from_iter` will become ambiguous in Rust 2021 --> $DIR/future-prelude-collision-generic.rs:28:5 | LL | Generic::from_iter(1); | ^^^^^^^^^^^^^^^^^^ help: disambiguate the associated function: ` as MyFromIter>::from_iter` | note: the lint level is defined here --> $DIR/future-prelude-collision-generic.rs:5:9 | LL | #![warn(rust_2021_prelude_collisions)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = warning: this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! = note: for more information, see issue #85684 warning: trait-associated function `from_iter` will become ambiguous in Rust 2021 --> $DIR/future-prelude-collision-generic.rs:31:5 | LL | Generic::::from_iter(1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: disambiguate the associated function: ` as MyFromIter>::from_iter` | = warning: this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! = note: for more information, see issue #85684 warning: trait-associated function `from_iter` will become ambiguous in Rust 2021 --> $DIR/future-prelude-collision-generic.rs:34:5 | LL | Generic::<_, _>::from_iter(1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: disambiguate the associated function: ` as MyFromIter>::from_iter` | = warning: this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! = note: for more information, see issue #85684 warning: 3 warnings emitted "} {"_id":"q-en-rust-f365b528b0bf4575edd5d716ec424da44afd2ebb0e332c96b2a5032c44bfdd4e","text":"rustdocflags.arg(\"-Dwarnings\"); } // FIXME(#58633) hide \"unused attribute\" errors in incremental // builds of the standard library, as the underlying checks are // not yet properly integrated with incremental recompilation. if mode == Mode::Std && compiler.stage == 0 && self.config.incremental { lint_flags.push(\"-Aunused-attributes\"); } // This does not use RUSTFLAGS due to caching issues with Cargo. // Clippy is treated as an \"in tree\" tool, but shares the same // cache as other \"submodule\" tools. With these options set in"} {"_id":"q-en-rust-f3e5546421b47ba9d35e20126136eb22110a1352506c229ea570a32209b878ad","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\"] extern crate proc_macro; use proc_macro::*; #[proc_macro_derive(A, attributes(b))] pub fn foo(_x: TokenStream) -> TokenStream { TokenStream::new() } "} {"_id":"q-en-rust-f421e6a0d369c3ed2d8fef78a83b311b487e71b8d818de819d44cfaef9403e55","text":"#[cfg(any(target_os = \"horizon\", target_os = \"hurd\"))] pub fn accessed(&self) -> io::Result { Ok(SystemTime::from(self.stat.st_atim)) SystemTime::new(self.stat.st_atim.tv_sec as i64, self.stat.st_atim.tv_nsec as i64) } #[cfg(any("} {"_id":"q-en-rust-f461d3d2d94abec75a8589a3bd6014ff50be4a3cc524a512d9d98f3677a2ea11","text":"use DefModifiers; use Module; use ModuleKind; use Namespace::{self, TypeNS, ValueNS}; use NameBindings; use NamespaceResult::{BoundResult, UnboundResult, UnknownResult};"} {"_id":"q-en-rust-f4898fcbf48a5d8227ff6dd605d7a09a2749619752e270eecb1b15178b2c44c5","text":" error[E0308]: mismatched types --> $DIR/clone-on-unconstrained-borrowed-type-param.rs:3:5 | LL | fn wat(t: &T) -> T { | - - expected `T` because of return type | | | this type parameter LL | t.clone() | ^^^^^^^^^ expected type parameter `T`, found `&T` | = note: expected type parameter `T` found reference `&T` note: `T` does not implement `Clone`, so `&T` was cloned instead --> $DIR/clone-on-unconstrained-borrowed-type-param.rs:3:5 | LL | t.clone() | ^ help: consider restricting type parameter `T` | LL | fn wat(t: &T) -> T { | +++++++ error[E0308]: mismatched types --> $DIR/clone-on-unconstrained-borrowed-type-param.rs:9:5 | LL | fn wut(t: &Foo) -> Foo { | --- expected `Foo` because of return type LL | t.clone() | ^^^^^^^^^ expected struct `Foo`, found `&Foo` | note: `Foo` does not implement `Clone`, so `&Foo` was cloned instead --> $DIR/clone-on-unconstrained-borrowed-type-param.rs:9:5 | LL | t.clone() | ^ help: consider annotating `Foo` with `#[derive(Clone)]` | LL | #[derive(Clone)] | error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"q-en-rust-f48c3e52558fc79383a56c5e2cb73f68e00b7050e283923b744e7c6caf6ac1f9","text":" // Regression test for #72051, hang when resolving regions. // check-pass // edition:2018 pub async fn query<'a>(_: &(), _: &(), _: (&(dyn std::any::Any + 'a),) ) {} fn main() {} "} {"_id":"q-en-rust-f4d6ec07215a1a32663b89912b6987b6ce425def3d306872ad55a6423dedac7f","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":"q-en-rust-f51dd86c6fe0650bd4639055873731075bc189ae821d3087bea34461a4b6298a","text":"} } fn type_bound( &self, ty: Ty<'tcx>, visited: &mut SsoHashSet>, ) -> VerifyBound<'tcx> { match *ty.kind() { ty::Param(p) => self.param_bound(p), ty::Projection(data) => self.projection_bound(data, visited), ty::FnDef(_, substs) => { // HACK(eddyb) ignore lifetimes found shallowly in `substs`. // This is inconsistent with `ty::Adt` (including all substs), // but consistent with previous (accidental) behavior. // See https://github.com/rust-lang/rust/issues/70917 // for further background and discussion. let mut bounds = substs .iter() .filter_map(|child| match child.unpack() { GenericArgKind::Type(ty) => Some(self.type_bound(ty, visited)), GenericArgKind::Lifetime(_) => None, GenericArgKind::Const(_) => Some(self.recursive_bound(child, visited)), }) .filter(|bound| { // Remove bounds that must hold, since they are not interesting. !bound.must_hold() }); match (bounds.next(), bounds.next()) { (Some(first), None) => first, (first, second) => VerifyBound::AllBounds( first.into_iter().chain(second).chain(bounds).collect(), ), } } _ => self.recursive_bound(ty.into(), visited), } } fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound<'tcx> { debug!(\"param_bound(param_ty={:?})\", param_ty);"} {"_id":"q-en-rust-f5231b8a9335563d55fcb100a9ea19eb224a9ed40c5fbc8a340643cb82f14472","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":"q-en-rust-f5270a5165ba02c25a54faba4a8b97d9a21a554d3819023852ea07de851c3d87","text":"let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None); let gen_future_span = self.mark_span_with_reason( DesugaringKind::Await, await_span, full_span, self.allow_gen_future.clone(), ); let expr = self.lower_expr_mut(expr);"} {"_id":"q-en-rust-f5381b874b000365ae4d7c50b352a58809f993b0e91f9c2972df99fc70e6b3c7","text":"pub fn output(cmd: &mut Command) -> String { let output = match cmd.stderr(Stdio::inherit()).output() { Ok(status) => status, Err(e) => fail(&format!(\"failed to execute command: {}\", e)), Err(e) => fail(&format!(\"failed to execute command: {:?}nerror: {}\", cmd, e)), }; if !output.status.success() { panic!(\"command did not execute successfully: {:?}n"} {"_id":"q-en-rust-f549aca04f9fdc4e2ebdde4f9c0b5400c79f4577af8fc65b8f2c0f39f3eb438a","text":"return; }; let doc = item.doc_value(); if doc.is_empty() { 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 hunks = prepare_to_doc_link_resolution(&item.attrs.doc_strings); for (item_id, doc) in hunks { if let Some(item_id) = item_id.or(item.def_id()) && !doc.is_empty() { check_redundant_explicit_link_for_did(cx, item, item_id, hir_id, &doc); } } }"} {"_id":"q-en-rust-f54d283b2834018bac8f44a89d608fb45836eb6e5047765d5c8303b1b55a7e32","text":" // check-pass trait Factory { type Product; } impl Factory for () { type Product = (); } trait ProductConsumer

    { fn consume(self, product: P); } impl

    ProductConsumer

    for () { fn consume(self, _: P) {} } fn make_product_consumer(_: F) -> impl ProductConsumer { () } fn main() { let consumer = make_product_consumer(()); consumer.consume(()); } "} {"_id":"q-en-rust-f55a3c1148fa7411a25c3b70f8b97829bb7c8150d1ee4d8e32d591798b89c147","text":"check_expr_with_expectation_and_lvalue_pref( fcx, &**oprnd, expected_inner, lvalue_pref); let mut oprnd_t = fcx.expr_ty(&**oprnd); if !ty::type_is_error(oprnd_t) && !ty::type_is_bot(oprnd_t) { if !ty::type_is_error(oprnd_t) { match unop { ast::UnBox => { oprnd_t = ty::mk_box(tcx, oprnd_t) if !ty::type_is_bot(oprnd_t) { oprnd_t = ty::mk_box(tcx, oprnd_t) } } ast::UnUniq => { oprnd_t = ty::mk_uniq(tcx, oprnd_t); if !ty::type_is_bot(oprnd_t) { oprnd_t = ty::mk_uniq(tcx, oprnd_t); } } ast::UnDeref => { oprnd_t = structurally_resolved_type(fcx, expr.span, oprnd_t);"} {"_id":"q-en-rust-f5705b1b8bcdc16efb7595022f88f2d3c99cf2d937ba27704e3e71052a07a0f3","text":"#![allow(rustc::untranslatable_diagnostic)] use either::Either; use hir::ClosureKind; use hir::{ClosureKind, Path}; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag, MultiSpan};"} {"_id":"q-en-rust-f57d5ce5998d7c563924192f7ff16dc93befe8db96de6c7ef0693d5a20ac64d3","text":" error[E0658]: `#[thread_local]` is an experimental feature, and does not currently handle destructors. There is no corresponding `#[task_local]` mapping to the task model (see issue #29594) error[E0658]: `#[thread_local]` is an experimental feature, and does not currently handle destructors. (see issue #29594) --> $DIR/feature-gate-thread_local.rs:18:1 | 18 | #[thread_local] //~ ERROR `#[thread_local]` is an experimental feature"} {"_id":"q-en-rust-f585893ba90bff36b6dd1bd6682787492633b47be18625c11992edae7bb251a7","text":"/// let num_trailing = unsafe { cttz_nonzero(x) }; /// assert_eq!(num_trailing, 3); /// ``` #[rustc_const_unstable(feature = \"const_cttz\", issue = \"none\")] #[rustc_const_stable(feature = \"const_cttz\", since = \"1.53.0\")] pub fn cttz_nonzero(x: T) -> T; /// Reverses the bytes in an integer type `T`."} {"_id":"q-en-rust-f5a29efa4da0cfd210a12f483def8dcc3e3f9a2e20830b24a7d2cd887f062964","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":"q-en-rust-f5a97b8f0e390eab6bfab2f9b3468517a1861d95d79ee3d498005dd36b656ca5","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":"q-en-rust-f5b3eac6b5cfbd1729ccd0109aa6b763d1a37ecd58d1e34c9acf85e52a086246","text":" // check-fail // See issue #91899. If we treat unnormalized args as WF, `Self` can also be a // source of unsoundness. pub trait Yokeable<'a>: 'static { type Output: 'a; } impl<'a, T: 'static + ?Sized> Yokeable<'a> for &'static T { type Output = &'a T; } pub trait ZeroCopyFrom: for<'a> Yokeable<'a> { /// Clone the cart `C` into a [`Yokeable`] struct, which may retain references into `C`. fn zero_copy_from<'b>(cart: &'b C) -> >::Output; } impl ZeroCopyFrom<[T]> for &'static [T] { fn zero_copy_from<'b>(cart: &'b [T]) -> &'b [T] { //~^ the parameter cart } } fn main() {} "} {"_id":"q-en-rust-f5bff31b16b30e39012abb446074ad81101ee9483c8db3b1bd189316a4f480be","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(associated_consts)] use Trait::foo; //~^ ERROR `foo` is not directly importable use Trait::Assoc; //~^ ERROR `Assoc` is not directly importable use Trait::C; //~^ ERROR `C` is not directly importable use Foo::new; //~^ ERROR unresolved import `Foo::new`. Not a module `Foo` use Foo::C2; //~^ ERROR unresolved import `Foo::C2`. Not a module `Foo` pub trait Trait { fn foo(); type Assoc; const C: u32; } struct Foo; impl Foo { fn new() {} const C2: u32 = 0; } fn main() {}"} {"_id":"q-en-rust-f5dcc7fa624915a1e82cad1ad87bd249f56418a8d2653bdc88cd407cf163bf98","text":" error[E0425]: cannot find value `a_variable_longer_name` in this scope --> $DIR/issue-66968-suggest-sorted-words.rs:3:20 | LL | println!(\"{}\", a_variable_longer_name); | ^^^^^^^^^^^^^^^^^^^^^^ help: a local variable with a similar name exists: `a_longer_variable_name` error: aborting due to previous error For more information about this error, try `rustc --explain E0425`. "} {"_id":"q-en-rust-f60427df5013a901c6e8c724c74d4ac47ad069e4cb20cb5e824b34372cb14460","text":"let archive = ArchiveRO::open(&path).expect(\"wanted an rlib\"); debug!(\"reading {}\", name); let bc = time(sess.time_passes(), format!(\"read {}.bc\", name), (), |_| archive.read(format!(\"{}.bc\", name))); let bc = bc.expect(\"missing bytecode in archive!\"); let bc = time(sess.time_passes(), format!(\"read {}.bc.deflate\", name), (), |_| archive.read(format!(\"{}.bc.deflate\", name))); let bc = bc.expect(\"missing compressed bytecode in archive!\"); let bc = time(sess.time_passes(), format!(\"inflate {}.bc\", name), (), |_| flate::inflate_bytes(bc)); let ptr = bc.as_slice().as_ptr();"} {"_id":"q-en-rust-f606b1ed4bd71c3c50e03b588922b91ddcc5f09d9e14187a496020dd1ae8e8b3","text":"} fn main() { unsafe { printf(); } //~ ERROR E0060 unsafe { printf(); } //~^ ERROR E0060 //~| NOTE expected at least 1 parameter //~| NOTE the following parameter type was expected }"} {"_id":"q-en-rust-f64453506f8b7b7666fda53b63f3622fbe3b6a2241275b9a5c18725402a10985","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":"q-en-rust-f6577815cb6be8d1c05e0fdb7264304af09963edb0cf056db2b96b7f2d15e250","text":" // Regression test for #61315 // // `dyn T:` is lowered to `dyn T: ReEmpty` - check that we don't ICE in NLL for // the unexpected region. // compile-pass trait T {} fn f() where dyn T: {} fn main() {} "} {"_id":"q-en-rust-f679427bf61fa0f305d53680e6bf4b4b9ad0760ab9a1fbc31f214f13dffc2023","text":"} else if attr.check_name(sym::thread_local) { codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL; } else if attr.check_name(sym::track_caller) { if tcx.fn_sig(id).abi() != abi::Abi::Rust { if tcx.is_closure(id) || tcx.fn_sig(id).abi() != abi::Abi::Rust { struct_span_err!(tcx.sess, attr.span, E0737, \"`#[track_caller]` requires Rust ABI\") .emit(); }"} {"_id":"q-en-rust-f6880aad3dffbb273f15543e5baf91d517cc2e0e2af1943b5f16971779d54e82","text":"

    pub fn create( ) -> Padding00000000000000000000000000000000000000000000000000000000000000000000000000000000
    No newline at end of file
    pub fn create() -> Padding00000000000000000000000000000000000000000000000000000000000000000000000000000000
    No newline at end of file"} {"_id":"q-en-rust-f69fc48cc9723d5839a325e0d704b67d2dad3c28676c8026b88ac3f1379ac1bc","text":" // check-pass trait MyCmp { fn cmp(&self) {} } impl MyCmp for f32 {} fn main() { // Ensure that `impl Ord for F` is never considered for int and float infer vars. 0.0.cmp(); } "} {"_id":"q-en-rust-f6e54a511fee9ea002d18da521bb92eac06e3b9ee7804e91df6354b6dd35780c","text":"\"URL\": \"struct.ZyxwvutMethodDisambiguation.html#method.method_impl_disambiguation-1\" }, ENDS_WITH) assert: \"section:target\" // Checks that, if a type has two methods with the same name, // and if it has multiple inherent impl blocks, that the numeric // impl block's disambiguator is also acted upon. go-to: \"file://\" + |DOC_PATH| + \"/lib2/index.html?search=MultiImplBlockStruct->bool\" wait-for: \"#search-tabs\" assert-count: (\"a.result-method\", 1) assert-attribute: (\"a.result-method\", { \"href\": \"../lib2/another_mod/struct.MultiImplBlockStruct.html#impl-MultiImplBlockStruct/method.second_fn\" }) click: \"a.result-method\" wait-for: \"details:has(summary > #impl-MultiImplBlockStruct-1) > div section[id='method.second_fn']:target\" go-to: \"file://\" + |DOC_PATH| + \"/lib2/index.html?search=MultiImplBlockStruct->u32\" wait-for: \"#search-tabs\" assert-count: (\"a.result-method\", 1) assert-attribute: (\"a.result-method\", { \"href\": \"../lib2/another_mod/struct.MultiImplBlockStruct.html#impl-MultiImplBlockTrait-for-MultiImplBlockStruct/method.second_fn\" }) click: \"a.result-method\" wait-for: \"details:has(summary > #impl-MultiImplBlockTrait-for-MultiImplBlockStruct) > div section[id='method.second_fn-1']:target\" "} {"_id":"q-en-rust-f6e6ae8e17afafac5d9c10044c92753fce1f0ff74a599a2e7442ad4a9ed1b67e","text":"- checkout: self fetchDepth: 2 # Spawn a background process to collect CPU usage statistics which we'll upload # at the end of the build. See the comments in the script here for more # information. - bash: python src/ci/cpu-usage-over-time.py &> cpu-usage.csv & displayName: \"Collect CPU-usage statistics in the background\" - bash: printenv | sort displayName: Show environment variables"} {"_id":"q-en-rust-f6ed4607499e9b43192fd02f760d9f54c99a7818d999909f1b5d54bda6aa25b0","text":"modified: Option, } #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] #[derive(Copy, Clone, Eq, Debug)] pub struct FileType { mode: mode_t, } impl PartialEq for FileType { fn eq(&self, other: &Self) -> bool { self.masked() == other.masked() } } impl core::hash::Hash for FileType { fn hash(&self, state: &mut H) { self.masked().hash(state); } } #[derive(Debug)] pub struct DirBuilder { mode: mode_t,"} {"_id":"q-en-rust-f702e0276be6d1efb43ca1f613f78a983c5afdcd119418cb2e4607f81bfa3e3c","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":"q-en-rust-f757d888cc82bf981e36dcbbd9e4ad836e5634c5115cdf0277e557eaa67e88b0","text":"can_unwind: fn_can_unwind(cx.tcx().sess.panic_strategy(), codegen_fn_attr_flags, conv), }; fn_abi.adjust_for_abi(cx, sig.abi); debug!(\"FnAbi::new_internal = {:?}\", fn_abi); fn_abi }"} {"_id":"q-en-rust-f76926ee18748cf4053b4357b7686f90bdfe549ca16155644a707e4d731bdd5c","text":"LinkerFlavor::Gcc, vec![\"-m64\".to_string(), \"-arch\".to_string(), \"x86_64\".to_string()], ); base.link_env.extend(super::apple_base::macos_link_env(\"x86_64\")); base.link_env_remove.extend(super::apple_base::macos_link_env_remove()); // don't use probe-stack=inline-asm until rust#83139 and rust#84667 are resolved base.stack_probes = StackProbeType::Call;"} {"_id":"q-en-rust-f79971ef2c8a09fdfebbfee6b7109a1767f607cacf7fc6fba27c5aac2c50c1ef","text":"ty::ReErased => { flags = flags | TypeFlags::HAS_RE_ERASED; } ty::ReError(_) => {} ty::ReError(_) => { flags = flags | TypeFlags::HAS_FREE_REGIONS; } } debug!(\"type_flags({:?}) = {:?}\", self, flags);"} {"_id":"q-en-rust-f7b7174b3675e3ed26cccc2d1f6f5eb8ea393dd9ff97d0ebf251b36d6d85f8de","text":"#[rustc_main] fn main() -> std::process::ExitCode {{ const TESTS: [test::TestDescAndFn; {nb_tests}] = [{ids}]; let bin_marker = std::ffi::OsStr::new(__doctest_mod::BIN_OPTION); let test_marker = std::ffi::OsStr::new(__doctest_mod::RUN_OPTION); let test_args = &[{test_args}]; const ENV_BIN: &'static str = \"RUSTDOC_DOCTEST_BIN_PATH\"; let mut args = std::env::args_os().skip(1); while let Some(arg) = args.next() {{ if arg == bin_marker {{ let Some(binary) = args.next() else {{ panic!(\"missing argument after `{{}}`\", __doctest_mod::BIN_OPTION); }}; if crate::__doctest_mod::BINARY_PATH.set(binary.into()).is_err() {{ panic!(\"`{{}}` option was used more than once\", bin_marker.to_string_lossy()); }} return std::process::Termination::report(test::test_main(test_args, Vec::from(TESTS), None)); }} else if arg == test_marker {{ let Some(nb_test) = args.next() else {{ panic!(\"missing argument after `{{}}`\", __doctest_mod::RUN_OPTION); }}; if let Some(nb_test) = nb_test.to_str().and_then(|nb| nb.parse::().ok()) {{ if let Some(test) = TESTS.get(nb_test) {{ if let test::StaticTestFn(f) = test.testfn {{ return std::process::Termination::report(f()); }} if let Ok(binary) = std::env::var(ENV_BIN) {{ let _ = crate::__doctest_mod::BINARY_PATH.set(binary.into()); unsafe {{ std::env::remove_var(ENV_BIN); }} return std::process::Termination::report(test::test_main(test_args, Vec::from(TESTS), None)); }} else if let Ok(nb_test) = std::env::var(__doctest_mod::RUN_OPTION) {{ if let Ok(nb_test) = nb_test.parse::() {{ if let Some(test) = TESTS.get(nb_test) {{ if let test::StaticTestFn(f) = test.testfn {{ return std::process::Termination::report(f()); }} }} panic!(\"Unexpected value after `{{}}`\", __doctest_mod::RUN_OPTION); }} panic!(\"Unexpected value for `{{}}`\", __doctest_mod::RUN_OPTION); }} eprintln!(\"WARNING: No argument provided so doctests will be run in the same process\"); eprintln!(\"WARNING: No rustdoc doctest environment variable provided so doctests will be run in the same process\"); std::process::Termination::report(test::test_main(test_args, Vec::from(TESTS), None)) }}\", nb_tests = self.nb_tests,"} {"_id":"q-en-rust-f7ef4ac2f3ae280502f77ddbf3be488fe6bea84f7add8c3970eaf79cb9075191","text":"ItemsInTraitsAreNotImportable, }; use crate::Determinacy::{self, *}; use crate::Namespace::*; use crate::{module_to_string, names_to_string, ImportSuggestion}; use crate::{AmbiguityError, Namespace::*}; use crate::{AmbiguityKind, BindingKey, ResolutionError, Resolver, Segment}; use crate::{Finalize, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet}; use crate::{NameBinding, NameBindingData, NameBindingKind, PathResult, Used};"} {"_id":"q-en-rust-f8063b18557b837dc16956b674f0dfe4a897088d8d8bf251781ba170cd512d42","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. // To work around #46855 // compile-flags: -Z mir-opt-level=0 // Regression test for the inhabitedness of unions with uninhabited variants, issue #46845 use std::mem; #[derive(Copy, Clone)] enum Never { } // A single uninhabited variant shouldn't make the whole union uninhabited. union Foo { a: u64, _b: Never } // If all the variants are uninhabited, however, the union should be uninhabited. union Bar { _a: (Never, u64), _b: (u64, Never) } fn main() { assert_eq!(mem::size_of::(), 8); assert_eq!(mem::size_of::(), 0); let f = [Foo { a: 42 }, Foo { a: 10 }]; println!(\"{}\", unsafe { f[0].a }); assert_eq!(unsafe { f[1].a }, 10); } "} {"_id":"q-en-rust-f81ebe68f402b390268785a4abffecebfd0e719e099b29da5acc0d172d94812c","text":" #![feature(specialization)] #![allow(incomplete_features)] pub trait ReflectDrop { const REFLECT_DROP: bool = false; } impl ReflectDrop for T where T: Clone {} pub trait PinDropInternal { fn is_valid() where Self: ReflectDrop; } struct Bears(T); default impl ReflectDrop for Bears {} impl PinDropInternal for Bears { fn is_valid() where Self: ReflectDrop, { let _ = [(); 0 - !!( as ReflectDrop>::REFLECT_DROP) as usize]; //~ ERROR constant expression depends on a generic parameter } } fn main() {} "} {"_id":"q-en-rust-f8509ccab9d3edaaeb3a306df33835fd17f951a24311047804851b3a9f8f7e20","text":" // aux-build:issue-119463-extern.rs extern crate issue_119463_extern; struct S; impl issue_119463_extern::PrivateTrait for S { //~^ ERROR: trait `PrivateTrait` is private const FOO: usize = 1; fn nonexistent() {} //~^ ERROR: method `nonexistent` is not a member of trait } fn main() {} "} {"_id":"q-en-rust-f8858a619c57e323bcbd2435caff31b7ec8de2ec801ff33bb6f0f8283f5b805a","text":"cmd.env(\"MIRI_BE_RUSTC\", \"target\"); // we better remember to *unset* this in the other phases! // Set rustdoc to us as well, so we can run doctests. if let Some(orig_rustdoc) = env::var_os(\"RUSTDOC\") { cmd.env(\"MIRI_ORIG_RUSTDOC\", orig_rustdoc); } cmd.env(\"RUSTDOC\", &cargo_miri_path); cmd.env(\"MIRI_LOCAL_CRATES\", local_crates(&metadata));"} {"_id":"q-en-rust-f88f1719efed32e678f37754c49c7121ce5df8112f440a7b9c93b9256b18356d","text":"parse_async_move_order_incorrect = the order of `move` and `async` is incorrect .suggestion = try switching the order parse_at_dot_dot_in_struct_pattern = `@ ..` is not supported in struct patterns .suggestion = bind to each field separately or, if you don't need them, just remove `{$ident} @` parse_at_in_struct_pattern = Unexpected `@` in struct pattern .note = struct patterns use `field: pattern` syntax to bind to fields .help = consider replacing `new_name @ field_name` with `field_name: new_name` if that is what you intended parse_attr_after_generic = trailing attribute after generic parameter .label = attributes must go before parameters"} {"_id":"q-en-rust-f8e9248e2990f47165609cf76f051261050a680f5707507b8e06d07167773f95","text":"use crate::generated_code; use rustc_ast::token::{self, TokenKind}; use rustc_parse::lexer::{self, StringReader}; use rustc_data_structures::sync::Lrc; use rustc_lexer::{tokenize, TokenKind}; use rustc_session::Session; use rustc_span::*;"} {"_id":"q-en-rust-f9077a8ffd5fbd5546135e75943683e2a35e03ba844c579eb1fad9191a8af5c7","text":"if let Some(positional_arg_to_replace) = position_sp_to_replace { let name = if is_formatting_arg { named_arg_name + \"$\" } else { named_arg_name }; let span_to_replace = if let Ok(positional_arg_content) = self.sess().source_map().span_to_snippet(positional_arg_to_replace) && positional_arg_content.starts_with(\":\") { positional_arg_to_replace.shrink_to_lo() } else { positional_arg_to_replace }; db.span_suggestion_verbose( positional_arg_to_replace, span_to_replace, \"use the named argument by name to avoid ambiguity\", name, Applicability::MaybeIncorrect,"} {"_id":"q-en-rust-f9226c14d84e4fd0f140fab75b17ba60b650c19d54ad7e6b425f40d2078da84b","text":"pub item_name: Ident, pub action_or_ty: String, } #[derive(Diagnostic)] #[diag(hir_typeck_ctor_is_private, code = \"E0603\")] pub struct CtorIsPrivate { #[primary_span] pub span: Span, pub def: String, } "} {"_id":"q-en-rust-f926511c9e4338b5ef9732fabdf16292a663578281b3edf680c727bc01e3d20c","text":" error: expected `fn`, found `PUT_ANYTHING_YOU_WANT_HERE` --> $DIR/issue-68062-const-extern-fns-dont-need-fn-specifier.rs:5:25 | LL | const extern \"Rust\" PUT_ANYTHING_YOU_WANT_HERE bug() -> usize { 1 } | ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `fn` error[E0658]: `const extern fn` definitions are unstable --> $DIR/issue-68062-const-extern-fns-dont-need-fn-specifier.rs:5:5 | LL | const extern \"Rust\" PUT_ANYTHING_YOU_WANT_HERE bug() -> usize { 1 } | ^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/64926 = help: add `#![feature(const_extern_fn)]` to the crate attributes to enable error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0658`. "} {"_id":"q-en-rust-f947d7096af983d401ed027d151f494a1c409e0fcda4f29248055af515354876","text":"trace!(\"Running RemoveUnneededDrops on {:?}\", body.source); let did = body.source.def_id(); let param_env = tcx.param_env(did); let param_env = tcx.param_env_reveal_all_normalized(did); let mut should_simplify = false; let (basic_blocks, local_decls) = body.basic_blocks_and_local_decls_mut();"} {"_id":"q-en-rust-f980713367b675c8f3b7bc57e2a6e6da7df06350e280db2591dd2fb78e622225","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. // Regression test for #27042. Test that a loop's label is included in its span. fn main() { let _: i32 = 'a: //~ ERROR mismatched types loop { break }; let _: i32 = 'b: //~ ERROR mismatched types while true { break }; let _: i32 = 'c: //~ ERROR mismatched types for _ in None { break }; let _: i32 = 'd: //~ ERROR mismatched types while let Some(_) = None { break }; } "} {"_id":"q-en-rust-fa62b2f39b5f36c0c95d44ac0fba34e22558edf44bcb4f22b1c3cea25694efc6","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":"q-en-rust-fa6f03db51a658602b9d0e379b5f897f55b29009ef4e9cb9aed5e01c9e58fd96","text":"LL | #[expect(clippy::overly_complex_bool_expr)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 6 previous errors error: aborting due to 7 previous errors "} {"_id":"q-en-rust-fa79c4faeb6b08a9078bfc42d5da38fad49f4c36746d97cb572ef940bbce3999","text":"cx: &mut DocContext<'_>, cfg: Option>, ) -> Item { trace!(\"name={:?}, def_id={:?}\", name, def_id); trace!(\"name={:?}, def_id={:?} cfg={:?}\", name, def_id, cfg); // Primitives and Keywords are written in the source code as private modules. // The modules need to be private so that nobody actually uses them, but the"} {"_id":"q-en-rust-fa97511fc84407f97ba67ed8588da43662921b63736c56e7fbc97dd7e13f6fcb","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":"q-en-rust-faa63ae1f6892abc6de9be7efb399a92f14b20d0db8a18948c6bddc597705a7f","text":" // check-pass // edition:2021 // compile-flags: -Zunstable-options fn main() { let _: u16 = 123i32.try_into().unwrap(); } "} {"_id":"q-en-rust-faa9ff6aed2d83c015e23a53ea93ce8f5d53dd22367124d08833114c8a1adb83","text":"let byte_pos = self.to_span_index(end); let start = InnerOffset(byte_pos.0 + 1); let field = self.argument(start); // We can only parse `foo.bar` field access, any deeper nesting, // or another type of expression, like method calls, are not supported // We can only parse simple `foo.bar` field access or `foo.0` tuple index access, any // deeper nesting, or another type of expression, like method calls, are not supported if !self.consume('}') { return; } if let ArgumentNamed(_) = arg.position { if let ArgumentNamed(_) = field.position { self.errors.insert( 0, ParseError { description: \"field access isn't supported\".to_string(), note: None, label: \"not supported\".to_string(), span: InnerSpan::new(arg.position_span.start, field.position_span.end), secondary_label: None, suggestion: Suggestion::UsePositional, }, ); } match field.position { ArgumentNamed(_) => { self.errors.insert( 0, ParseError { description: \"field access isn't supported\".to_string(), note: None, label: \"not supported\".to_string(), span: InnerSpan::new( arg.position_span.start, field.position_span.end, ), secondary_label: None, suggestion: Suggestion::UsePositional, }, ); } ArgumentIs(_) => { self.errors.insert( 0, ParseError { description: \"tuple index access isn't supported\".to_string(), note: None, label: \"not supported\".to_string(), span: InnerSpan::new( arg.position_span.start, field.position_span.end, ), secondary_label: None, suggestion: Suggestion::UsePositional, }, ); } _ => {} }; } } }"} {"_id":"q-en-rust-fb22b98fe151bf82082334c2f2ba8538f7b9c5df8f3e5865dbea230c17d2f5bf","text":"// Error codes that don't yet have a UI test. This list will eventually be removed. const IGNORE_UI_TEST_CHECK: &[&str] = &[ \"E0313\", \"E0461\", \"E0465\", \"E0476\", \"E0490\", \"E0514\", \"E0523\", \"E0554\", \"E0640\", \"E0717\", \"E0729\", \"E0789\", \"E0461\", \"E0465\", \"E0476\", \"E0490\", \"E0514\", \"E0523\", \"E0554\", \"E0640\", \"E0717\", \"E0729\", \"E0789\", ]; macro_rules! verbose_print {"} {"_id":"q-en-rust-fb26a89096bd11f572b876af8ce27edbae169914a2dbad959fd533a7f05dd575","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":"q-en-rust-fb6f00d298fba2a008cef0b53b1f39e2167fc0db6d0e4e1160893565939865c7","text":" // test for https://github.com/rust-lang/rust/issues/86940 // run-rustfix // edition:2018 // check-pass #![warn(rust_2021_prelude_collisions)] #![allow(dead_code)] #![allow(unused_imports)] struct Generic(T, U); trait MyFromIter { fn from_iter(_: i32) -> Self; } impl MyFromIter for Generic { fn from_iter(x: i32) -> Self { Self(x, x) } } impl std::iter::FromIterator for Generic { fn from_iter>(_: T) -> Self { todo!() } } fn main() { as MyFromIter>::from_iter(1); //~^ WARNING trait-associated function `from_iter` will become ambiguous in Rust 2021 //~| this is accepted in the current edition (Rust 2018) as MyFromIter>::from_iter(1); //~^ WARNING trait-associated function `from_iter` will become ambiguous in Rust 2021 //~| this is accepted in the current edition (Rust 2018) as MyFromIter>::from_iter(1); //~^ WARNING trait-associated function `from_iter` will become ambiguous in Rust 2021 //~| this is accepted in the current edition (Rust 2018) } "} {"_id":"q-en-rust-fbbe76b165b0fbd3a2c06446c5c529c6b8a4e5ecb8476ac8f01611371a8ccfbf","text":"matching,' which `match` is an implementation of. So what's the big advantage here? Well, there are a few. First of all, `match` does 'exhaustiveness checking.' Do you see that last arm, the one with the enforces 'exhaustiveness checking.' Do you see that last arm, the one with the underscore (`_`)? If we remove that arm, Rust will give us an error: ```{ignore,notrust}"} {"_id":"q-en-rust-fbd7375920eb3c09a2e906a77fb2b4f954bac4c77ae32f446c5da8dbbc07b906","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(_: Self) { //~^ ERROR use of `Self` outside of an impl or trait } fn main() {} "} {"_id":"q-en-rust-fc499c7ccbdeeaac910ef5b07627a0aed1799f633c1d3bd5a680b8d4983fe232","text":"printer.s.eof() } // This makes comma-separated lists look slightly nicer, // and also addresses a specific regression described in issue #63896. fn tt_prepend_space(tt: &TokenTree) -> bool { match tt { TokenTree::Token(token) => match token.kind { token::Comma => false, _ => true, } _ => true, } } fn binop_to_string(op: BinOpToken) -> &'static str { match op { token::Plus => \"+\","} {"_id":"q-en-rust-fc4d842bdc63906652ecff954cd6e7a1a7228cdfc39a57e82077fecc0db415b2","text":" error[E0407]: method `nonexistent` is not a member of trait `issue_119463_extern::PrivateTrait` --> $DIR/issue-119463.rs:11:5 | LL | fn nonexistent() {} | ^^^^^^^^^^^^^^^^^^^ not a member of trait `issue_119463_extern::PrivateTrait` error[E0603]: trait `PrivateTrait` is private --> $DIR/issue-119463.rs:7:27 | LL | impl issue_119463_extern::PrivateTrait for S { | ^^^^^^^^^^^^ private trait | note: the trait `PrivateTrait` is defined here --> $DIR/auxiliary/issue-119463-extern.rs:1:1 | LL | trait PrivateTrait { | ^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors Some errors have detailed explanations: E0407, E0603. For more information about an error, try `rustc --explain E0407`. "} {"_id":"q-en-rust-fc8d1ffdd12b60843f644abbf7f001671b6e439b5e174029ec4f71a1177665d1","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":"q-en-rust-fc9f20a66f1ced9ea85941683c3d26bf550ae51ba25feb5b04a82c44514bfb5a","text":"match &mut stmt.kind { // Expression without semicolon. StmtKind::Expr(expr) if classify::expr_requires_semi_to_be_stmt(expr) && !expr.attrs.is_empty() && ![token::Eof, token::Semi, token::CloseDelim(Delimiter::Brace)] .contains(&self.token.kind) => { // The user has written `#[attr] expr` which is unsupported. (#106020) self.attr_on_non_tail_expr(&expr); // We already emitted an error, so don't emit another type error let sp = expr.span.to(self.prev_token.span); *expr = self.mk_expr_err(sp); } // Expression without semicolon. StmtKind::Expr(expr) if self.token != token::Eof && classify::expr_requires_semi_to_be_stmt(expr) => { // Just check for errors and recover; do not eat semicolon yet."} {"_id":"q-en-rust-fca02f7c2521d4a55567cc33383cb474134372fa1a0f5fb426f0a55d4ac7bb7a","text":" //@ known-bug: rust-lang/rust#125081 use std::cell::Cell; fn main() { let _: Cell<&str, \"a\"> = Cell::new('β); } "} {"_id":"q-en-rust-fcc51202254a8f68a9750455dcf8857173447f2c4bb5e3448869ca33d5222039","text":"parse_only: false, no_trans: false, no_analysis: false, no_rpath: false, debugging_opts: 0, android_cross_path: None, write_dependency_info: (false, None),"} {"_id":"q-en-rust-fced8c7855f929d8c243390010b2a5f2318c6f291b6b7a2c9ad3122dd261f6e8","text":"fs::metadata(hiberfil).unwrap(); assert_eq!(true, hiberfil.exists()); } /// Test that two different ways of obtaining the FileType give the same result. /// Cf. https://github.com/rust-lang/rust/issues/104900 #[test] fn test_eq_direntry_metadata() { let tmpdir = tmpdir(); let file_path = tmpdir.join(\"file\"); File::create(file_path).unwrap(); for e in fs::read_dir(tmpdir.path()).unwrap() { let e = e.unwrap(); let p = e.path(); let ft1 = e.file_type().unwrap(); let ft2 = p.metadata().unwrap().file_type(); assert_eq!(ft1, ft2); } } "} {"_id":"q-en-rust-fd0ec0ab269fa739370b4594d1c6b1f5d43073b0e124d711f6a307f2bed314f4","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":"q-en-rust-fd8620ef20e1e543a0f596c63e961b1b99703b5aab0cd05aa93223d50933e73f","text":" fn f1() -> impl Sized { & 2E } //~ ERROR expected at least one digit in exponent fn f2() -> impl Sized { && 2E } //~ ERROR expected at least one digit in exponent fn f3() -> impl Sized { &'a 2E } //~ ERROR expected at least one digit in exponent //~^ ERROR borrow expressions cannot be annotated with lifetimes fn f4() -> impl Sized { &'static 2E } //~ ERROR expected at least one digit in exponent //~^ ERROR borrow expressions cannot be annotated with lifetimes fn f5() -> impl Sized { *& 2E } //~ ERROR expected at least one digit in exponent fn f6() -> impl Sized { &'_ 2E } //~ ERROR expected at least one digit in exponent //~^ ERROR borrow expressions cannot be annotated with lifetimes fn main() {} "} {"_id":"q-en-rust-fdb0ab238dce0702ab0b975d73150456fa4f88f2079ae4b0fe12c6ea02cf72d8","text":" // edition: 2021 trait Foo { type T; async fn foo(&self) -> Self::T; } struct Bar; impl Foo for Bar { type T = (); async fn foo(&self) {} //~^ ERROR type annotations needed: cannot satisfy `::T == ()` } impl Foo for Bar { //~^ ERROR conflicting implementations of trait `Foo` for type `Bar` type T = (); async fn foo(&self) {} //~^ ERROR type annotations needed: cannot satisfy `::T == ()` } fn main() {} "} {"_id":"q-en-rust-fdc48aae76f0bfec0470518d52fe4712c2957155702ca7e152de0095da2724db","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":"q-en-rust-fdfa0a2b1e8f8e643bc3dd02f5d2b6f69c688e5ac70cff030385df7d6e1f04bd","text":"} } fn evaluation_is_concurrent(&self) -> bool { self.sess.threads() > 1 } fn expand_abstract_consts>>(self, t: T) -> T { self.expand_abstract_consts(t) }"} {"_id":"q-en-rust-fdfa68d49a37819648e4a07abd73c21a997d573c0b474a16c86fa158a6fd4508","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":"q-en-rust-fe09d28093aceb2a35f5ed493727a9400adb8f6df82fa2dfe9eda23b04243762","text":"import textwrap try: import urllib2 from urllib2 import HTTPError except ImportError: import urllib.request as urllib2 from urllib.error import HTTPError try: import typing except ImportError: pass # List of people to ping when the status of a tool or a book changed. # These should be collaborators of the rust-lang/rust repository (with at least"} {"_id":"q-en-rust-fe1179042e7657dbccbc28eb08cd0fe7bf66c4022bea7933a954276be17cd77d","text":"self.error_on_extra_if(&cond)?; // Parse block, which will always fail, but we can add a nice note to the error self.parse_block().map_err(|mut err| { err.span_note( cond_span, \"the `if` expression is missing a block after this condition\", ); if self.prev_token == token::Semi && self.token == token::AndAnd && let maybe_let = self.look_ahead(1, |t| t.clone()) && maybe_let.is_keyword(kw::Let) { err.span_suggestion( self.prev_token.span, \"consider removing this semicolon to parse the `let` as part of the same chain\", \"\", Applicability::MachineApplicable, ).span_note( self.token.span.to(maybe_let.span), \"you likely meant to continue parsing the let-chain starting here\", ); } else { err.span_note( cond_span, \"the `if` expression is missing a block after this condition\", ); } err })? }"} {"_id":"q-en-rust-fe2629a0b8f5a68369d8c4f12b93cc2aca4239c78dd5be5fbf771eccbd87374a","text":"check_safety_of_rvalue_destructor_if_necessary(rcx, head_cmt, expr.span); } Err(..) => { rcx.fcx.tcx().sess.span_note(expr.span, \"cat_expr Errd during dtor check\"); let tcx = rcx.fcx.tcx(); if tcx.sess.has_errors() { // cannot run dropck; okay b/c in error state anyway. } else { tcx.sess.span_bug(expr.span, \"cat_expr Errd\"); } } }"} {"_id":"q-en-rust-fe446200d24856f9ca62c0a65e75f81ddb4a6f7ba2aa9875c40bb76adccc0fc6","text":"self.maybe_annotate_with_ascription(&mut err, false); err.emit(); self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore); Some(Stmt { id: DUMMY_NODE_ID, kind: StmtKind::Expr(self.mk_expr_err(self.token.span)), span: self.token.span, }) Some(self.mk_stmt( self.token.span, StmtKind::Expr(self.mk_expr_err(self.token.span)), )) } Ok(stmt) => stmt, };"} {"_id":"q-en-rust-fe4535d9229e3bffc6b9fc9fa773a1961114f87bcf6ee5138cdaef5055e03daf","text":"_ => return, } let max_by_val_size = if is_ret { call::max_ret_by_val(cx) } else { Pointer.size(cx) }; let size = arg.layout.size; if arg.layout.is_unsized() || size > Pointer.size(cx) { if arg.layout.is_unsized() || size > max_by_val_size { arg.make_indirect(); } else { // We want to pass small aggregates as immediates, but using"} {"_id":"q-en-rust-fe4f64a727dd79c57ca8cf4f82510995242b26897c9c7eeb584a6bbd65260660","text":"arg_count, if arg_count == 1 {\" was\"} else {\"s were\"}), error_code); err.span_label(sp, &format!(\"expected {}{} parameter{}\", if variadic {\"at least \"} else {\"\"}, expected_count, if expected_count == 1 {\"\"} else {\"s\"})); let input_types = fn_inputs.iter().map(|i| format!(\"{:?}\", i)).collect::>(); if input_types.len() > 0 { err.note(&format!(\"the following parameter type{} expected: {}\","} {"_id":"q-en-rust-fe5faa5533e10b982273b9d674ac3e38ce48381f17e1b501294f7aec37d98159","text":"impl<'tcx> TypeVisitor<'tcx> for GATSubstCollector<'tcx> { type BreakTy = !; fn visit_binder>( &mut self, t: &ty::Binder<'tcx, T>, ) -> ControlFlow { self.tcx.liberate_late_bound_regions(self.gat, t.clone()).visit_with(self) } fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow { match t.kind() { ty::Projection(p) if p.item_def_id == self.gat => {"} {"_id":"q-en-rust-fe6507662bf287d57df323eca5194314e3cd6789f77155908d91da44c745d350","text":"} pub fn store_fn_arg(&self, bx: &Builder<'a, 'tcx>, idx: &mut usize, dst: PlaceRef<'tcx>) { if self.pad.is_some() { *idx += 1; } let mut next = || { let val = llvm::get_param(bx.llfn(), *idx as c_uint); *idx += 1;"} {"_id":"q-en-rust-fe92356b3e54f1e64f6f4ba88bf3c9893288152944bbaeff5eb8a7c8e9d044af","text":" Subproject commit af5940b73153b2a4ea2922aa803abac45d029982 Subproject commit 6651c1b9b2a1b3e995565467218ff7eca7479c5e "} {"_id":"q-en-rust-fe9ece3a644ab582e33c660873897d47c6ea83d03ee36d275027a5996bd800d3","text":" Subproject commit 10419b3f2fc625bb9d746c16d768e433a894484d Subproject commit a6c28f08458e15cead0e80f3b5b7009786bce4a4 "} {"_id":"q-en-rust-feda5d12fa0f118b059bde28fe983e2e2fe9dd02bca92c1c7a9ba33dcfdcb287","text":" // Tests that the compiler does not ICE when const-evaluating a `panic!()` invocation with a // non-`&str` argument. #![feature(const_panic)] const _: () = panic!(1); //~^ ERROR: argument to `panic!()` in a const context must have type `&str` static _FOO: () = panic!(true); //~^ ERROR: argument to `panic!()` in a const context must have type `&str` const fn _foo() { panic!(&1); //~ ERROR: argument to `panic!()` in a const context must have type `&str` } // ensure that conforming panics don't cause an error const _: () = panic!(); static _BAR: () = panic!(\"panic in static\"); const fn _bar() { panic!(\"panic in const fn\"); } fn main() {} "} {"_id":"q-en-rust-fedbed21ca0fcd8a211a5cdb0109e51e2b4e21fe0c8dd1eab26daf9cfbcfe8ad","text":"discr_index, .. } => { if !variant_index.as_usize() < dest.layout.ty.ty_adt_def().unwrap().variants.len() { throw_ub!(InvalidDiscriminant(variant_scalar)); } // No need to validate that the discriminant here because the // `TyLayout::for_variant()` call earlier already checks the variant is valid. if variant_index != dataful_variant { let variants_start = niche_variants.start().as_u32(); let variant_index_relative = variant_index.as_u32()"} {"_id":"q-en-rust-ff0bc443c5f1aed86dc9d7635eb60d787b0c8102b108679f14e17b52cc8f56d0","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":"q-en-rust-ff271e02d5926d282ca289eef55935606b77934e90d1873e8197934dbd31ba1d","text":" // ignore-order const QUERY = 'RawFd::as_raw_fd'; const EXPECTED = { 'others': [ // Reproduction test for https://github.com/rust-lang/rust/issues/78724 // Validate that type alias methods get the correct path. { 'path': 'std::os::unix::io::AsRawFd', 'name': 'as_raw_fd' }, { 'path': 'std::os::wasi::io::AsRawFd', 'name': 'as_raw_fd' }, { 'path': 'std::os::linux::process::PidFd', 'name': 'as_raw_fd' }, { 'path': 'std::os::unix::io::RawFd', 'name': 'as_raw_fd' }, ], }; "} {"_id":"q-en-rust-ff58e361c7da43b5902463ebb6e596df2379319cdb367a36cef561dc80f6162f","text":"/// assert!(ptr::eq(ptr, inner.as_ptr())); /// ``` #[inline] #[unstable(feature = \"arc_unwrap_or_clone\", issue = \"93610\")] #[stable(feature = \"arc_unwrap_or_clone\", since = \"CURRENT_RUSTC_VERSION\")] pub fn unwrap_or_clone(this: Self) -> T { Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone()) }"} {"_id":"q-en-rust-ff8864708616c35d4aa6bcdbf5c3873800e0b1080c850e4dedb89e1c908a0578","text":" Subproject commit 5faf5a5ca059f6eb067fc86e47480f5668ac6e8c Subproject commit 41f3fe64317a6ef144d2ac33e4e5870d894d6038 "} {"_id":"q-en-rust-ffb392c76ae1cc09b19cc9c53e903a1561d5495ca0156d1dc5954806fa466522","text":"&& data_a.principal_def_id() != data_b.principal_def_id() { debug!(\"coerce_unsized: found trait upcasting coercion\"); has_trait_upcasting_coercion = true; has_trait_upcasting_coercion = Some((self_ty, unsize_ty)); } if let ty::Tuple(..) = unsize_ty.kind() { debug!(\"coerce_unsized: found unsized tuple coercion\");"} {"_id":"q-en-rust-ffc1ce68d99cb0e3b0da67263aa82500c4ec6eb596c36243eb0d2aa931c252e7","text":"} // Transfer the conditions on the copy rhs, after inversing polarity. Rvalue::UnaryOp(UnOp::Not, Operand::Move(place) | Operand::Copy(place)) => { if !place.ty(self.body, self.tcx).ty.is_bool() { // Constructing the conditions by inverting the polarity // of equality is only correct for bools. That is to say, // `!a == b` is not `a != b` for integers greater than 1 bit. return; } let Some(conditions) = state.try_get_idx(lhs, &self.map) else { return }; let Some(place) = self.map.find(place.as_ref()) else { return }; // FIXME: I think This could be generalized to not bool if we // actually perform a logical not on the condition's value. let conds = conditions.map(self.arena, Condition::inv); state.insert_value_idx(place, conds, &self.map); }"} {"_id":"q-en-rust-fff0903df48085ee2805d20a00be89080e359120938ec6aa772a35786d1c49b2","text":"35 | #[rustc_deprecated = \"1500\"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 9 previous errors error: aborting due to 8 previous errors "} {"_id":"q-en-rust-fff91c001a65cd841d83397dd3273fe65ac47c679da4f10cf8a7351d9ad1263b","text":" // unit-test: Inline // compile-flags: --crate-type=lib -C panic=abort trait Foo { fn bar(&self) -> i32; } impl Foo for T { fn bar(&self) -> i32 { 0 } } // EMIT_MIR inline_generically_if_sized.call.Inline.diff pub fn call(s: &T) -> i32 { s.bar() } "}
  • {} | ^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #13231 for more information = help: add `#![feature(auto_traits)]` to the crate attributes to enable error: aborting due to 2 previous errors Some errors have detailed explanations: E0567, E0658. For more information about an error, try `rustc --explain E0567`. "} {"_id":"q-en-rust-5bbe757a8c8de234a1bddfdaec92e083209080a9bb9a4f99cac348b688561fe2","text":"LL | fn d<'a, const C: S<'a>>() {} | +++ ++++ error[E0771]: use of non-static lifetime `'a` in const generic --> $DIR/unusual-rib-combinations.rs:29:22 | LL | struct Bar Foo<'a>)>; | ^^ | = note: for more information, see issue #74052 error[E0214]: parenthesized type parameters may only be used with a `Fn` trait --> $DIR/unusual-rib-combinations.rs:7:16 |"} {"_id":"q-en-rust-5bec87ba584d1b625cb68029465fd3cc40b5c6fa85de05359c10c39639e2e1e6","text":" // run-pass // edition:2021 struct Props { field_1: u32, //~ WARNING: field is never read: `field_1` field_2: u32, //~ WARNING: field is never read: `field_2` } fn main() { // Test 1 let props_2 = Props { //~ WARNING: unused variable: `props_2` field_1: 1, field_2: 1, }; let _ = || { let _: Props = props_2; }; // Test 2 let mut arr = [1, 3, 4, 5]; let mref = &mut arr; let _c = || match arr { [_, _, _, _] => println!(\"A\") }; println!(\"{:#?}\", mref); } "} {"_id":"q-en-rust-5c0609dec407afbffb9000ec06a852efda5bf36862f277def4d368cac2ef5f86","text":" // edition:2021 #![feature(type_alias_impl_trait)] struct CallMe; type ReturnType<'a> = impl std::future::Future + 'a; type FnType = impl Fn(&u32) -> ReturnType; impl std::ops::Deref for CallMe { type Target = FnType; fn deref(&self) -> &Self::Target { fn inner(val: &u32) -> ReturnType { async move { *val * 2 } } &inner //~ ERROR: expected generic lifetime parameter, found `'_` } } fn main() {} "} {"_id":"q-en-rust-5c185cef6745a4f831459971214094018eeaf25638ba34530965b4083fb7f6dc","text":" // Regression test for issue #124935 // Tests that we do not erroneously emit an error about // missing main function when the mod starts with a `;` ; //~ ERROR expected item, found `;` fn main() { } "} {"_id":"q-en-rust-5c1c20ed8c81b498f7f76af1453e94c766fa9b5ec3be2f0e8f0256fbd662e7ec","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":"q-en-rust-5c403273909425ec01c762dcda1727b548953d9bdc8d4d969c4ee3927be2404c","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. //! Windows file path handling use ascii::AsciiCast; use c_str::{CString, ToCStr}; use cast; use cmp::Eq; use from_str::FromStr; use iter::{AdditiveIterator, Extendable, Iterator}; use option::{Option, Some, None}; use str; use str::{OwnedStr, Str, StrVector}; use util; use vec::Vector; use super::{GenericPath, GenericPathUnsafe}; /// Iterator that yields successive components of a Path pub type ComponentIter<'self> = str::CharSplitIterator<'self, char>; /// Represents a Windows path // Notes for Windows path impl: // The MAX_PATH is 260, but 253 is the practical limit due to some API bugs // See http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx for good information // about windows paths. // That same page puts a bunch of restrictions on allowed characters in a path. // `foo.txt` means \"relative to current drive\", but will not be considered to be absolute here // as `∃P | P.join(\"foo.txt\") != \"foo.txt\"`. // `C:` is interesting, that means \"the current directory on drive C\". // Long absolute paths need to have ? prefix (or, for UNC, ?UNC). I think that can be // ignored for now, though, and only added in a hypothetical .to_pwstr() function. // However, if a path is parsed that has ?, this needs to be preserved as it disables the // processing of \".\" and \"..\" components and / as a separator. // Experimentally, ?foo is not the same thing as foo. // Also, foo is not valid either (certainly not equivalent to foo). // Similarly, C:Users is not equivalent to C:Users, although C:Usersfoo is equivalent // to C:Usersfoo. In fact the command prompt treats C:foobar as UNC path. But it might be // best to just ignore that and normalize it to C:foobar. // // Based on all this, I think the right approach is to do the following: // * Require valid utf-8 paths. Windows API may use WCHARs, but we don't, and utf-8 is convertible // to UTF-16 anyway (though does Windows use UTF-16 or UCS-2? Not sure). // * Parse the prefixes ?UNC, ?, and . explicitly. // * If ?UNC, treat following two path components as servershare. Don't error for missing // servershare. // * If ?, parse disk from following component, if present. Don't error for missing disk. // * If ., treat rest of path as just regular components. I don't know how . and .. are handled // here, they probably aren't, but I'm not going to worry about that. // * Else if starts with , treat following two components as servershare. Don't error for missing // servershare. // * Otherwise, attempt to parse drive from start of path. // // The only error condition imposed here is valid utf-8. All other invalid paths are simply // preserved by the data structure; let the Windows API error out on them. #[deriving(Clone, DeepClone)] pub struct Path { priv repr: ~str, // assumed to never be empty priv prefix: Option, priv sepidx: Option // index of the final separator in the non-prefix portion of repr } impl Eq for Path { #[inline] fn eq(&self, other: &Path) -> bool { self.repr == other.repr } } impl FromStr for Path { fn from_str(s: &str) -> Option { if contains_nul(s.as_bytes()) { None } else { Some(unsafe { GenericPathUnsafe::from_str_unchecked(s) }) } } } impl ToCStr for Path { #[inline] fn to_c_str(&self) -> CString { // The Path impl guarantees no embedded NULs unsafe { self.as_vec().to_c_str_unchecked() } } #[inline] unsafe fn to_c_str_unchecked(&self) -> CString { self.as_vec().to_c_str_unchecked() } } impl GenericPathUnsafe for Path { /// See `GenericPathUnsafe::from_vec_unchecked`. /// /// # Failure /// /// Raises the `str::not_utf8` condition if not valid UTF-8. #[inline] unsafe fn from_vec_unchecked(path: &[u8]) -> Path { if !str::is_utf8(path) { let path = str::from_utf8(path); // triggers not_utf8 condition GenericPathUnsafe::from_str_unchecked(path) } else { GenericPathUnsafe::from_str_unchecked(cast::transmute(path)) } } #[inline] unsafe fn from_str_unchecked(path: &str) -> Path { let (prefix, path) = Path::normalize_(path); assert!(!path.is_empty()); let mut ret = Path{ repr: path, prefix: prefix, sepidx: None }; ret.update_sepidx(); ret } /// See `GenericPathUnsafe::set_dirname_unchecked`. /// /// # Failure /// /// Raises the `str::not_utf8` condition if not valid UTF-8. #[inline] unsafe fn set_dirname_unchecked(&mut self, dirname: &[u8]) { if !str::is_utf8(dirname) { let dirname = str::from_utf8(dirname); // triggers not_utf8 condition self.set_dirname_str_unchecked(dirname); } else { self.set_dirname_str_unchecked(cast::transmute(dirname)) } } unsafe fn set_dirname_str_unchecked(&mut self, dirname: &str) { match self.sepidx_or_prefix_len() { None if \".\" == self.repr || \"..\" == self.repr => { self.update_normalized(dirname); } None => { let mut s = str::with_capacity(dirname.len() + self.repr.len() + 1); s.push_str(dirname); s.push_char(sep); s.push_str(self.repr); self.update_normalized(s); } Some((_,idxa,end)) if self.repr.slice(idxa,end) == \"..\" => { self.update_normalized(dirname); } Some((_,idxa,end)) if dirname.is_empty() => { let (prefix, path) = Path::normalize_(self.repr.slice(idxa,end)); self.repr = path; self.prefix = prefix; self.update_sepidx(); } Some((idxb,idxa,end)) => { let idx = if dirname.ends_with(\"\") { idxa } else { let prefix = parse_prefix(dirname); if prefix == Some(DiskPrefix) && prefix_len(prefix) == dirname.len() { idxa } else { idxb } }; let mut s = str::with_capacity(dirname.len() + end - idx); s.push_str(dirname); s.push_str(self.repr.slice(idx,end)); self.update_normalized(s); } } } /// See `GenericPathUnsafe::set_filename_unchecekd`. /// /// # Failure /// /// Raises the `str::not_utf8` condition if not valid UTF-8. #[inline] unsafe fn set_filename_unchecked(&mut self, filename: &[u8]) { if !str::is_utf8(filename) { let filename = str::from_utf8(filename); // triggers not_utf8 condition self.set_filename_str_unchecked(filename) } else { self.set_filename_str_unchecked(cast::transmute(filename)) } } unsafe fn set_filename_str_unchecked(&mut self, filename: &str) { match self.sepidx_or_prefix_len() { None if \"..\" == self.repr => { let mut s = str::with_capacity(3 + filename.len()); s.push_str(\"..\"); s.push_char(sep); s.push_str(filename); self.update_normalized(s); } None => { self.update_normalized(filename); } Some((_,idxa,end)) if self.repr.slice(idxa,end) == \"..\" => { let mut s = str::with_capacity(end + 1 + filename.len()); s.push_str(self.repr.slice_to(end)); s.push_char(sep); s.push_str(filename); self.update_normalized(s); } Some((idxb,idxa,_)) if self.prefix == Some(DiskPrefix) && idxa == self.prefix_len() => { let mut s = str::with_capacity(idxb + filename.len()); s.push_str(self.repr.slice_to(idxb)); s.push_str(filename); self.update_normalized(s); } Some((idxb,_,_)) => { let mut s = str::with_capacity(idxb + 1 + filename.len()); s.push_str(self.repr.slice_to(idxb)); s.push_char(sep); s.push_str(filename); self.update_normalized(s); } } } /// See `GenericPathUnsafe::push_unchecked`. /// /// # Failure /// /// Raises the `str::not_utf8` condition if not valid UTF-8. unsafe fn push_unchecked(&mut self, path: &[u8]) { if !str::is_utf8(path) { let path = str::from_utf8(path); // triggers not_utf8 condition self.push_str_unchecked(path); } else { self.push_str_unchecked(cast::transmute(path)); } } /// See `GenericPathUnsafe::push_str_unchecked`. /// /// Concatenating two Windows Paths is rather complicated. /// For the most part, it will behave as expected, except in the case of /// pushing a volume-relative path, e.g. `C:foo.txt`. Because we have no /// concept of per-volume cwds like Windows does, we can't behave exactly /// like Windows will. Instead, if the receiver is an absolute path on /// the same volume as the new path, it will be treated as the cwd that /// the new path is relative to. Otherwise, the new path will be treated /// as if it were absolute and will replace the receiver outright. unsafe fn push_str_unchecked(&mut self, path: &str) { fn is_vol_abs(path: &str, prefix: Option) -> bool { // assume prefix is Some(DiskPrefix) let rest = path.slice_from(prefix_len(prefix)); !rest.is_empty() && rest[0].is_ascii() && is_sep2(rest[0] as char) } fn shares_volume(me: &Path, path: &str) -> bool { // path is assumed to have a prefix of Some(DiskPrefix) match me.prefix { Some(DiskPrefix) => me.repr[0] == path[0].to_ascii().to_upper().to_byte(), Some(VerbatimDiskPrefix) => me.repr[4] == path[0].to_ascii().to_upper().to_byte(), _ => false } } fn is_sep_(prefix: Option, u: u8) -> bool { u.is_ascii() && if prefix_is_verbatim(prefix) { is_sep(u as char) } else { is_sep2(u as char) } } fn replace_path(me: &mut Path, path: &str, prefix: Option) { let newpath = Path::normalize__(path, prefix); me.repr = match newpath { Some(p) => p, None => path.to_owned() }; me.prefix = prefix; me.update_sepidx(); } fn append_path(me: &mut Path, path: &str) { // appends a path that has no prefix // if me is verbatim, we need to pre-normalize the new path let path_ = if me.is_verbatim() { Path::normalize__(path, None) } else { None }; let pathlen = path_.map_default(path.len(), |p| p.len()); let mut s = str::with_capacity(me.repr.len() + 1 + pathlen); s.push_str(me.repr); let plen = me.prefix_len(); if !(me.repr.len() > plen && me.repr[me.repr.len()-1] == sep as u8) { s.push_char(sep); } match path_ { None => s.push_str(path), Some(p) => s.push_str(p) }; me.update_normalized(s) } if !path.is_empty() { let prefix = parse_prefix(path); match prefix { Some(DiskPrefix) if !is_vol_abs(path, prefix) && shares_volume(self, path) => { // cwd-relative path, self is on the same volume append_path(self, path.slice_from(prefix_len(prefix))); } Some(_) => { // absolute path, or cwd-relative and self is not same volume replace_path(self, path, prefix); } None if !path.is_empty() && is_sep_(self.prefix, path[0]) => { // volume-relative path if self.prefix().is_some() { // truncate self down to the prefix, then append let n = self.prefix_len(); self.repr.truncate(n); append_path(self, path); } else { // we have no prefix, so nothing to be relative to replace_path(self, path, prefix); } } None => { // relative path append_path(self, path); } } } } } impl GenericPath for Path { /// See `GenericPath::as_str` for info. /// Always returns a `Some` value. #[inline] fn as_str<'a>(&'a self) -> Option<&'a str> { Some(self.repr.as_slice()) } #[inline] fn as_vec<'a>(&'a self) -> &'a [u8] { self.repr.as_bytes() } #[inline] fn dirname<'a>(&'a self) -> &'a [u8] { self.dirname_str().unwrap().as_bytes() } /// See `GenericPath::dirname_str` for info. /// Always returns a `Some` value. fn dirname_str<'a>(&'a self) -> Option<&'a str> { Some(match self.sepidx_or_prefix_len() { None if \"..\" == self.repr => self.repr.as_slice(), None => \".\", Some((_,idxa,end)) if self.repr.slice(idxa, end) == \"..\" => { self.repr.as_slice() } Some((idxb,_,end)) if self.repr.slice(idxb, end) == \"\" => { self.repr.as_slice() } Some((0,idxa,_)) => self.repr.slice_to(idxa), Some((idxb,idxa,_)) => { match self.prefix { Some(DiskPrefix) | Some(VerbatimDiskPrefix) if idxb == self.prefix_len() => { self.repr.slice_to(idxa) } _ => self.repr.slice_to(idxb) } } }) } #[inline] fn filename<'a>(&'a self) -> &'a [u8] { self.filename_str().unwrap().as_bytes() } /// See `GenericPath::filename_str` for info. /// Always returns a `Some` value. fn filename_str<'a>(&'a self) -> Option<&'a str> { Some(match self.sepidx_or_prefix_len() { None if \".\" == self.repr || \"..\" == self.repr => \"\", None => self.repr.as_slice(), Some((_,idxa,end)) if self.repr.slice(idxa, end) == \"..\" => \"\", Some((_,idxa,end)) => self.repr.slice(idxa, end) }) } /// See `GenericPath::filestem_str` for info. /// Always returns a `Some` value. #[inline] fn filestem_str<'a>(&'a self) -> Option<&'a str> { // filestem() returns a byte vector that's guaranteed valid UTF-8 Some(unsafe { cast::transmute(self.filestem()) }) } #[inline] fn extension_str<'a>(&'a self) -> Option<&'a str> { // extension() returns a byte vector that's guaranteed valid UTF-8 self.extension().map_move(|v| unsafe { cast::transmute(v) }) } fn dir_path(&self) -> Path { unsafe { GenericPathUnsafe::from_str_unchecked(self.dirname_str().unwrap()) } } fn file_path(&self) -> Option { match self.filename_str() { None | Some(\"\") => None, Some(s) => Some(unsafe { GenericPathUnsafe::from_str_unchecked(s) }) } } #[inline] fn push_path(&mut self, path: &Path) { self.push_str(path.as_str().unwrap()) } #[inline] fn pop_opt(&mut self) -> Option<~[u8]> { self.pop_opt_str().map_move(|s| s.into_bytes()) } fn pop_opt_str(&mut self) -> Option<~str> { match self.sepidx_or_prefix_len() { None if \".\" == self.repr => None, None => { let mut s = ~\".\"; util::swap(&mut s, &mut self.repr); self.sepidx = None; Some(s) } Some((idxb,idxa,end)) if idxb == idxa && idxb == end => None, Some((idxb,_,end)) if self.repr.slice(idxb, end) == \"\" => None, Some((idxb,idxa,end)) => { let s = self.repr.slice(idxa, end).to_owned(); let trunc = match self.prefix { Some(DiskPrefix) | Some(VerbatimDiskPrefix) | None => { let plen = self.prefix_len(); if idxb == plen { idxa } else { idxb } } _ => idxb }; self.repr.truncate(trunc); self.update_sepidx(); Some(s) } } } /// See `GenericPath::is_absolute` for info. /// /// A Windows Path is considered absolute only if it has a non-volume prefix, /// or if it has a volume prefix and the path starts with ''. /// A path of `foo` is not considered absolute because it's actually /// relative to the \"current volume\". A separate method `Path::is_vol_relative` /// is provided to indicate this case. Similarly a path of `C:foo` is not /// considered absolute because it's relative to the cwd on volume C:. A /// separate method `Path::is_cwd_relative` is provided to indicate this case. #[inline] fn is_absolute(&self) -> bool { match self.prefix { Some(DiskPrefix) => { let rest = self.repr.slice_from(self.prefix_len()); rest.len() > 0 && rest[0] == sep as u8 } Some(_) => true, None => false } } fn is_ancestor_of(&self, other: &Path) -> bool { if !self.equiv_prefix(other) { false } else if self.is_absolute() != other.is_absolute() || self.is_vol_relative() != other.is_vol_relative() { false } else { let mut ita = self.component_iter(); let mut itb = other.component_iter(); if \".\" == self.repr { return itb.next() != Some(\"..\"); } loop { match (ita.next(), itb.next()) { (None, _) => break, (Some(a), Some(b)) if a == b => { loop }, (Some(a), _) if a == \"..\" => { // if ita contains only .. components, it's an ancestor return ita.all(|x| x == \"..\"); } _ => return false } } true } } fn path_relative_from(&self, base: &Path) -> Option { fn comp_requires_verbatim(s: &str) -> bool { s == \".\" || s == \"..\" || s.contains_char(sep2) } if !self.equiv_prefix(base) { // prefixes differ if self.is_absolute() { Some(self.clone()) } else if self.prefix == Some(DiskPrefix) && base.prefix == Some(DiskPrefix) { // both drives, drive letters must differ or they'd be equiv Some(self.clone()) } else { None } } else if self.is_absolute() != base.is_absolute() { if self.is_absolute() { Some(self.clone()) } else { None } } else if self.is_vol_relative() != base.is_vol_relative() { if self.is_vol_relative() { Some(self.clone()) } else { None } } else { let mut ita = self.component_iter(); let mut itb = base.component_iter(); let mut comps = ~[]; let a_verb = self.is_verbatim(); let b_verb = base.is_verbatim(); loop { match (ita.next(), itb.next()) { (None, None) => break, (Some(a), None) if a_verb && comp_requires_verbatim(a) => { return Some(self.clone()) } (Some(a), None) => { comps.push(a); if !a_verb { comps.extend(&mut ita); break; } } (None, _) => comps.push(\"..\"), (Some(a), Some(b)) if comps.is_empty() && a == b => (), (Some(a), Some(b)) if !b_verb && b == \".\" => { if a_verb && comp_requires_verbatim(a) { return Some(self.clone()) } else { comps.push(a) } } (Some(_), Some(b)) if !b_verb && b == \"..\" => return None, (Some(a), Some(_)) if a_verb && comp_requires_verbatim(a) => { return Some(self.clone()) } (Some(a), Some(_)) => { comps.push(\"..\"); for _ in itb { comps.push(\"..\"); } comps.push(a); if !a_verb { comps.extend(&mut ita); break; } } } } Some(Path::from_str(comps.connect(\"\"))) } } } impl Path { /// Returns a new Path from a byte vector /// /// # Failure /// /// Raises the `null_byte` condition if the vector contains a NUL. /// Raises the `str::not_utf8` condition if invalid UTF-8. #[inline] pub fn new(v: &[u8]) -> Path { GenericPath::from_vec(v) } /// Returns a new Path from a string /// /// # Failure /// /// Raises the `null_byte` condition if the vector contains a NUL. #[inline] pub fn from_str(s: &str) -> Path { GenericPath::from_str(s) } /// Converts the Path into an owned byte vector pub fn into_vec(self) -> ~[u8] { self.repr.into_bytes() } /// Converts the Path into an owned string /// Returns an Option for compatibility with posix::Path, but the /// return value will always be Some. pub fn into_str(self) -> Option<~str> { Some(self.repr) } /// Returns a normalized string representation of a path, by removing all empty /// components, and unnecessary . and .. components. pub fn normalize(s: S) -> ~str { let (_, path) = Path::normalize_(s); path } /// Returns an iterator that yields each component of the path in turn. /// Does not yield the path prefix (including server/share components in UNC paths). /// Does not distinguish between volume-relative and relative paths, e.g. /// abc and abc. /// Does not distinguish between absolute and cwd-relative paths, e.g. /// C:foo and C:foo. pub fn component_iter<'a>(&'a self) -> ComponentIter<'a> { let s = match self.prefix { Some(_) => { let plen = self.prefix_len(); if self.repr.len() > plen && self.repr[plen] == sep as u8 { self.repr.slice_from(plen+1) } else { self.repr.slice_from(plen) } } None if self.repr[0] == sep as u8 => self.repr.slice_from(1), None => self.repr.as_slice() }; let ret = s.split_terminator_iter(sep); ret } /// Returns whether the path is considered \"volume-relative\", which means a path /// that looks like \"foo\". Paths of this form are relative to the current volume, /// but absolute within that volume. #[inline] pub fn is_vol_relative(&self) -> bool { self.prefix.is_none() && self.repr[0] == sep as u8 } /// Returns whether the path is considered \"cwd-relative\", which means a path /// with a volume prefix that is not absolute. This look like \"C:foo.txt\". Paths /// of this form are relative to the cwd on the given volume. #[inline] pub fn is_cwd_relative(&self) -> bool { self.prefix == Some(DiskPrefix) && !self.is_absolute() } /// Returns the PathPrefix for this Path #[inline] pub fn prefix(&self) -> Option { self.prefix } /// Returns whether the prefix is a verbatim prefix, i.e. ? #[inline] pub fn is_verbatim(&self) -> bool { prefix_is_verbatim(self.prefix) } fn equiv_prefix(&self, other: &Path) -> bool { match (self.prefix, other.prefix) { (Some(DiskPrefix), Some(VerbatimDiskPrefix)) => { self.is_absolute() && self.repr[0].to_ascii().eq_ignore_case(other.repr[4].to_ascii()) } (Some(VerbatimDiskPrefix), Some(DiskPrefix)) => { other.is_absolute() && self.repr[4].to_ascii().eq_ignore_case(other.repr[0].to_ascii()) } (Some(VerbatimDiskPrefix), Some(VerbatimDiskPrefix)) => { self.repr[4].to_ascii().eq_ignore_case(other.repr[4].to_ascii()) } (Some(UNCPrefix(_,_)), Some(VerbatimUNCPrefix(_,_))) => { self.repr.slice(2, self.prefix_len()) == other.repr.slice(8, other.prefix_len()) } (Some(VerbatimUNCPrefix(_,_)), Some(UNCPrefix(_,_))) => { self.repr.slice(8, self.prefix_len()) == other.repr.slice(2, other.prefix_len()) } (None, None) => true, (a, b) if a == b => { self.repr.slice_to(self.prefix_len()) == other.repr.slice_to(other.prefix_len()) } _ => false } } fn normalize_(s: S) -> (Option, ~str) { // make borrowck happy let (prefix, val) = { let prefix = parse_prefix(s.as_slice()); let path = Path::normalize__(s.as_slice(), prefix); (prefix, path) }; (prefix, match val { None => s.into_owned(), Some(val) => val }) } fn normalize__(s: &str, prefix: Option) -> Option<~str> { if prefix_is_verbatim(prefix) { // don't do any normalization match prefix { Some(VerbatimUNCPrefix(x, 0)) if s.len() == 8 + x => { // the server component has no trailing '' let mut s = s.into_owned(); s.push_char(sep); Some(s) } _ => None } } else { let (is_abs, comps) = normalize_helper(s, prefix); let mut comps = comps; match (comps.is_some(),prefix) { (false, Some(DiskPrefix)) => { if s[0] >= 'a' as u8 && s[0] <= 'z' as u8 { comps = Some(~[]); } } (false, Some(VerbatimDiskPrefix)) => { if s[4] >= 'a' as u8 && s[0] <= 'z' as u8 { comps = Some(~[]); } } _ => () } match comps { None => None, Some(comps) => { if prefix.is_some() && comps.is_empty() { match prefix.unwrap() { DiskPrefix => { let len = prefix_len(prefix) + is_abs as uint; let mut s = s.slice_to(len).to_owned(); s[0] = s[0].to_ascii().to_upper().to_byte(); if is_abs { s[2] = sep as u8; // normalize C:/ to C: } Some(s) } VerbatimDiskPrefix => { let len = prefix_len(prefix) + is_abs as uint; let mut s = s.slice_to(len).to_owned(); s[4] = s[4].to_ascii().to_upper().to_byte(); Some(s) } _ => { let plen = prefix_len(prefix); if s.len() > plen { Some(s.slice_to(plen).to_owned()) } else { None } } } } else if is_abs && comps.is_empty() { Some(str::from_char(sep)) } else { let prefix_ = s.slice_to(prefix_len(prefix)); let n = prefix_.len() + if is_abs { comps.len() } else { comps.len() - 1} + comps.iter().map(|v| v.len()).sum(); let mut s = str::with_capacity(n); match prefix { Some(DiskPrefix) => { s.push_char(prefix_[0].to_ascii().to_upper().to_char()); s.push_char(':'); } Some(VerbatimDiskPrefix) => { s.push_str(prefix_.slice_to(4)); s.push_char(prefix_[4].to_ascii().to_upper().to_char()); s.push_str(prefix_.slice_from(5)); } Some(UNCPrefix(a,b)) => { s.push_str(\"\"); s.push_str(prefix_.slice(2, a+2)); s.push_char(sep); s.push_str(prefix_.slice(3+a, 3+a+b)); } Some(_) => s.push_str(prefix_), None => () } let mut it = comps.move_iter(); if !is_abs { match it.next() { None => (), Some(comp) => s.push_str(comp) } } for comp in it { s.push_char(sep); s.push_str(comp); } Some(s) } } } } } fn update_sepidx(&mut self) { let s = if self.has_nonsemantic_trailing_slash() { self.repr.slice_to(self.repr.len()-1) } else { self.repr.as_slice() }; let idx = s.rfind(if !prefix_is_verbatim(self.prefix) { is_sep2 } else { is_sep }); let prefixlen = self.prefix_len(); self.sepidx = idx.and_then(|x| if x < prefixlen { None } else { Some(x) }); } fn prefix_len(&self) -> uint { prefix_len(self.prefix) } // Returns a tuple (before, after, end) where before is the index of the separator // and after is the index just after the separator. // end is the length of the string, normally, or the index of the final character if it is // a non-semantic trailing separator in a verbatim string. // If the prefix is considered the separator, before and after are the same. fn sepidx_or_prefix_len(&self) -> Option<(uint,uint,uint)> { match self.sepidx { None => match self.prefix_len() { 0 => None, x => Some((x,x,self.repr.len())) }, Some(x) => { if self.has_nonsemantic_trailing_slash() { Some((x,x+1,self.repr.len()-1)) } else { Some((x,x+1,self.repr.len())) } } } } fn has_nonsemantic_trailing_slash(&self) -> bool { self.is_verbatim() && self.repr.len() > self.prefix_len()+1 && self.repr[self.repr.len()-1] == sep as u8 } fn update_normalized(&mut self, s: S) { let (prefix, path) = Path::normalize_(s); self.repr = path; self.prefix = prefix; self.update_sepidx(); } } /// The standard path separator character pub static sep: char = ''; /// The alternative path separator character pub static sep2: char = '/'; /// Returns whether the given byte is a path separator. /// Only allows the primary separator ''; use is_sep2 to allow '/'. #[inline] pub fn is_sep(c: char) -> bool { c == sep } /// Returns whether the given byte is a path separator. /// Allows both the primary separator '' and the alternative separator '/'. #[inline] pub fn is_sep2(c: char) -> bool { c == sep || c == sep2 } /// Prefix types for Path #[deriving(Eq, Clone, DeepClone)] pub enum PathPrefix { /// Prefix `?`, uint is the length of the following component VerbatimPrefix(uint), /// Prefix `?UNC`, uints are the lengths of the UNC components VerbatimUNCPrefix(uint, uint), /// Prefix `?C:` (for any alphabetic character) VerbatimDiskPrefix, /// Prefix `.`, uint is the length of the following component DeviceNSPrefix(uint), /// UNC prefix `servershare`, uints are the lengths of the server/share UNCPrefix(uint, uint), /// Prefix `C:` for any alphabetic character DiskPrefix } /// Internal function; only public for tests. Don't use. // FIXME (#8169): Make private once visibility is fixed pub fn parse_prefix<'a>(mut path: &'a str) -> Option { if path.starts_with(\"\") { // path = path.slice_from(2); if path.starts_with(\"?\") { // ? path = path.slice_from(2); if path.starts_with(\"UNC\") { // ?UNCservershare path = path.slice_from(4); let (idx_a, idx_b) = match parse_two_comps(path, is_sep) { Some(x) => x, None => (path.len(), 0) }; return Some(VerbatimUNCPrefix(idx_a, idx_b)); } else { // ?path let idx = path.find(''); if idx == Some(2) && path[1] == ':' as u8 { let c = path[0]; if c.is_ascii() && ::char::is_alphabetic(c as char) { // ?C: path return Some(VerbatimDiskPrefix); } } let idx = idx.unwrap_or(path.len()); return Some(VerbatimPrefix(idx)); } } else if path.starts_with(\".\") { // .path path = path.slice_from(2); let idx = path.find('').unwrap_or(path.len()); return Some(DeviceNSPrefix(idx)); } match parse_two_comps(path, is_sep2) { Some((idx_a, idx_b)) if idx_a > 0 && idx_b > 0 => { // servershare return Some(UNCPrefix(idx_a, idx_b)); } _ => () } } else if path.len() > 1 && path[1] == ':' as u8 { // C: let c = path[0]; if c.is_ascii() && ::char::is_alphabetic(c as char) { return Some(DiskPrefix); } } return None; fn parse_two_comps<'a>(mut path: &'a str, f: &fn(char)->bool) -> Option<(uint, uint)> { let idx_a = match path.find(|x| f(x)) { None => return None, Some(x) => x }; path = path.slice_from(idx_a+1); let idx_b = path.find(f).unwrap_or(path.len()); Some((idx_a, idx_b)) } } // None result means the string didn't need normalizing fn normalize_helper<'a>(s: &'a str, prefix: Option) -> (bool,Option<~[&'a str]>) { let f = if !prefix_is_verbatim(prefix) { is_sep2 } else { is_sep }; let is_abs = s.len() > prefix_len(prefix) && f(s.char_at(prefix_len(prefix))); let s_ = s.slice_from(prefix_len(prefix)); let s_ = if is_abs { s_.slice_from(1) } else { s_ }; if is_abs && s_.is_empty() { return (is_abs, match prefix { Some(DiskPrefix) | None => (if is_sep(s.char_at(prefix_len(prefix))) { None } else { Some(~[]) }), Some(_) => Some(~[]), // need to trim the trailing separator }); } let mut comps: ~[&'a str] = ~[]; let mut n_up = 0u; let mut changed = false; for comp in s_.split_iter(f) { if comp.is_empty() { changed = true } else if comp == \".\" { changed = true } else if comp == \"..\" { let has_abs_prefix = match prefix { Some(DiskPrefix) => false, Some(_) => true, None => false }; if (is_abs || has_abs_prefix) && comps.is_empty() { changed = true } else if comps.len() == n_up { comps.push(\"..\"); n_up += 1 } else { comps.pop_opt(); changed = true } } else { comps.push(comp) } } if !changed && !prefix_is_verbatim(prefix) { changed = s.find(is_sep2).is_some(); } if changed { if comps.is_empty() && !is_abs && prefix.is_none() { if s == \".\" { return (is_abs, None); } comps.push(\".\"); } (is_abs, Some(comps)) } else { (is_abs, None) } } // FIXME (#8169): Pull this into parent module once visibility works #[inline(always)] fn contains_nul(v: &[u8]) -> bool { v.iter().any(|&x| x == 0) } fn prefix_is_verbatim(p: Option) -> bool { match p { Some(VerbatimPrefix(_)) | Some(VerbatimUNCPrefix(_,_)) | Some(VerbatimDiskPrefix) => true, Some(DeviceNSPrefix(_)) => true, // not really sure, but I think so _ => false } } fn prefix_len(p: Option) -> uint { match p { None => 0, Some(VerbatimPrefix(x)) => 4 + x, Some(VerbatimUNCPrefix(x,y)) => 8 + x + 1 + y, Some(VerbatimDiskPrefix) => 6, Some(UNCPrefix(x,y)) => 2 + x + 1 + y, Some(DeviceNSPrefix(x)) => 4 + x, Some(DiskPrefix) => 2 } } fn prefix_is_sep(p: Option, c: u8) -> bool { c.is_ascii() && if !prefix_is_verbatim(p) { is_sep2(c as char) } else { is_sep(c as char) } } #[cfg(test)] mod tests { use super::*; use option::{Some,None}; use iter::Iterator; use vec::Vector; macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = $path; assert_eq!(path.as_str(), Some($exp)); } ); (v: $path:expr, $exp:expr) => ( { let path = $path; assert_eq!(path.as_vec(), $exp); } ) ) macro_rules! b( ($($arg:expr),+) => ( bytes!($($arg),+) ) ) #[test] fn test_parse_prefix() { macro_rules! t( ($path:expr, $exp:expr) => ( { let path = $path; let exp = $exp; let res = parse_prefix(path); assert!(res == exp, \"parse_prefix(\"%s\"): expected %?, found %?\", path, exp, res); } ) ) t!(\"SERVERsharefoo\", Some(UNCPrefix(6,5))); t!(\"\", None); t!(\"SERVER\", None); t!(\"SERVER\", None); t!(\"SERVER\", None); t!(\"SERVERfoo\", None); t!(\"SERVERshare\", Some(UNCPrefix(6,5))); t!(\"SERVER/share/foo\", Some(UNCPrefix(6,5))); t!(\"SERVERshare/foo\", Some(UNCPrefix(6,5))); t!(\"//SERVER/share/foo\", None); t!(\"abc\", None); t!(\"?abc\", Some(VerbatimPrefix(1))); t!(\"?a/b/c\", Some(VerbatimPrefix(5))); t!(\"//?/a/b/c\", None); t!(\".ab\", Some(DeviceNSPrefix(1))); t!(\".a/b\", Some(DeviceNSPrefix(3))); t!(\"//./a/b\", None); t!(\"?UNCserversharefoo\", Some(VerbatimUNCPrefix(6,5))); t!(\"?UNCsharefoo\", Some(VerbatimUNCPrefix(0,5))); t!(\"?UNC\", Some(VerbatimUNCPrefix(0,0))); t!(\"?UNCserver/share/foo\", Some(VerbatimUNCPrefix(16,0))); t!(\"?UNCserver\", Some(VerbatimUNCPrefix(6,0))); t!(\"?UNCserver\", Some(VerbatimUNCPrefix(6,0))); t!(\"?UNC/server/share\", Some(VerbatimPrefix(16))); t!(\"?UNC\", Some(VerbatimPrefix(3))); t!(\"?C:ab.txt\", Some(VerbatimDiskPrefix)); t!(\"?z:\", Some(VerbatimDiskPrefix)); t!(\"?C:\", Some(VerbatimPrefix(2))); t!(\"?C:a.txt\", Some(VerbatimPrefix(7))); t!(\"?C:ab.txt\", Some(VerbatimPrefix(3))); t!(\"?C:/a\", Some(VerbatimPrefix(4))); t!(\"C:foo\", Some(DiskPrefix)); t!(\"z:/foo\", Some(DiskPrefix)); t!(\"d:\", Some(DiskPrefix)); t!(\"ab:\", None); t!(\"ü:foo\", None); t!(\"3:foo\", None); t!(\" :foo\", None); t!(\"::foo\", None); t!(\"?C:\", Some(VerbatimPrefix(2))); t!(\"?z:\", Some(VerbatimDiskPrefix)); t!(\"?ab:\", Some(VerbatimPrefix(3))); t!(\"?C:a\", Some(VerbatimDiskPrefix)); t!(\"?C:/a\", Some(VerbatimPrefix(4))); t!(\"?C:a/b\", Some(VerbatimDiskPrefix)); } #[test] fn test_paths() { t!(v: Path::new([]), b!(\".\")); t!(v: Path::new(b!(\"\")), b!(\"\")); t!(v: Path::new(b!(\"abc\")), b!(\"abc\")); t!(s: Path::from_str(\"\"), \".\"); t!(s: Path::from_str(\"\"), \"\"); t!(s: Path::from_str(\"hi\"), \"hi\"); t!(s: Path::from_str(\"hi\"), \"hi\"); t!(s: Path::from_str(\"lib\"), \"lib\"); t!(s: Path::from_str(\"lib\"), \"lib\"); t!(s: Path::from_str(\"hithere\"), \"hithere\"); t!(s: Path::from_str(\"hithere.txt\"), \"hithere.txt\"); t!(s: Path::from_str(\"/\"), \"\"); t!(s: Path::from_str(\"hi/\"), \"hi\"); t!(s: Path::from_str(\"/lib\"), \"lib\"); t!(s: Path::from_str(\"/lib/\"), \"lib\"); t!(s: Path::from_str(\"hi/there\"), \"hithere\"); t!(s: Path::from_str(\"hithere\"), \"hithere\"); t!(s: Path::from_str(\"hi..there\"), \"there\"); t!(s: Path::from_str(\"hi/../there\"), \"there\"); t!(s: Path::from_str(\"..hithere\"), \"..hithere\"); t!(s: Path::from_str(\"..hithere\"), \"hithere\"); t!(s: Path::from_str(\"/../hi/there\"), \"hithere\"); t!(s: Path::from_str(\"foo..\"), \".\"); t!(s: Path::from_str(\"foo..\"), \"\"); t!(s: Path::from_str(\"foo....\"), \"\"); t!(s: Path::from_str(\"foo....bar\"), \"bar\"); t!(s: Path::from_str(\".hi.there.\"), \"hithere\"); t!(s: Path::from_str(\".hi.there...\"), \"hi\"); t!(s: Path::from_str(\"foo....\"), \"..\"); t!(s: Path::from_str(\"foo......\"), \"....\"); t!(s: Path::from_str(\"foo....bar\"), \"..bar\"); assert_eq!(Path::new(b!(\"foobar\")).into_vec(), b!(\"foobar\").to_owned()); assert_eq!(Path::new(b!(\"foo....bar\")).into_vec(), b!(\"bar\").to_owned()); assert_eq!(Path::from_str(\"foobar\").into_str(), Some(~\"foobar\")); assert_eq!(Path::from_str(\"foo....bar\").into_str(), Some(~\"bar\")); t!(s: Path::from_str(\"a\"), \"a\"); t!(s: Path::from_str(\"a\"), \"a\"); t!(s: Path::from_str(\"ab\"), \"ab\"); t!(s: Path::from_str(\"ab\"), \"ab\"); t!(s: Path::from_str(\"ab/\"), \"ab\"); t!(s: Path::from_str(\"b\"), \"b\"); t!(s: Path::from_str(\"ab\"), \"ab\"); t!(s: Path::from_str(\"abc\"), \"abc\"); t!(s: Path::from_str(\"servershare/path\"), \"serversharepath\"); t!(s: Path::from_str(\"server/share/path\"), \"serversharepath\"); t!(s: Path::from_str(\"C:ab.txt\"), \"C:ab.txt\"); t!(s: Path::from_str(\"C:a/b.txt\"), \"C:ab.txt\"); t!(s: Path::from_str(\"z:ab.txt\"), \"Z:ab.txt\"); t!(s: Path::from_str(\"z:/a/b.txt\"), \"Z:ab.txt\"); t!(s: Path::from_str(\"ab:/a/b.txt\"), \"ab:ab.txt\"); t!(s: Path::from_str(\"C:\"), \"C:\"); t!(s: Path::from_str(\"C:\"), \"C:\"); t!(s: Path::from_str(\"q:\"), \"Q:\"); t!(s: Path::from_str(\"C:/\"), \"C:\"); t!(s: Path::from_str(\"C:foo..\"), \"C:\"); t!(s: Path::from_str(\"C:foo..\"), \"C:\"); t!(s: Path::from_str(\"C:a\"), \"C:a\"); t!(s: Path::from_str(\"C:a/\"), \"C:a\"); t!(s: Path::from_str(\"C:ab\"), \"C:ab\"); t!(s: Path::from_str(\"C:ab/\"), \"C:ab\"); t!(s: Path::from_str(\"C:a\"), \"C:a\"); t!(s: Path::from_str(\"C:a/\"), \"C:a\"); t!(s: Path::from_str(\"C:ab\"), \"C:ab\"); t!(s: Path::from_str(\"C:ab/\"), \"C:ab\"); t!(s: Path::from_str(\"?z:ab.txt\"), \"?z:ab.txt\"); t!(s: Path::from_str(\"?C:/a/b.txt\"), \"?C:/a/b.txt\"); t!(s: Path::from_str(\"?C:a/b.txt\"), \"?C:a/b.txt\"); t!(s: Path::from_str(\"?testab.txt\"), \"?testab.txt\"); t!(s: Path::from_str(\"?foobar\"), \"?foobar\"); t!(s: Path::from_str(\".foobar\"), \".foobar\"); t!(s: Path::from_str(\".\"), \".\"); t!(s: Path::from_str(\"?UNCserversharefoo\"), \"?UNCserversharefoo\"); t!(s: Path::from_str(\"?UNCserver/share\"), \"?UNCserver/share\"); t!(s: Path::from_str(\"?UNCserver\"), \"?UNCserver\"); t!(s: Path::from_str(\"?UNC\"), \"?UNC\"); t!(s: Path::from_str(\"?UNC\"), \"?UNC\"); // I'm not sure whether .foo/bar should normalize to .foobar // as information is sparse and this isn't really googleable. // I'm going to err on the side of not normalizing it, as this skips the filesystem t!(s: Path::from_str(\".foo/bar\"), \".foo/bar\"); t!(s: Path::from_str(\".foobar\"), \".foobar\"); } #[test] fn test_null_byte() { use path2::null_byte::cond; let mut handled = false; let mut p = do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!(\"foobar\", 0)); (b!(\"bar\").to_owned()) }).inside { Path::new(b!(\"foobar\", 0)) }; assert!(handled); assert_eq!(p.as_vec(), b!(\"bar\")); handled = false; do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!(\"f\", 0, \"o\")); (b!(\"foo\").to_owned()) }).inside { p.set_filename(b!(\"f\", 0, \"o\")) }; assert!(handled); assert_eq!(p.as_vec(), b!(\"foo\")); handled = false; do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!(\"null\", 0, \"byte\")); (b!(\"nullbyte\").to_owned()) }).inside { p.set_dirname(b!(\"null\", 0, \"byte\")); }; assert!(handled); assert_eq!(p.as_vec(), b!(\"nullbytefoo\")); handled = false; do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!(\"f\", 0, \"o\")); (b!(\"foo\").to_owned()) }).inside { p.push(b!(\"f\", 0, \"o\")); }; assert!(handled); assert_eq!(p.as_vec(), b!(\"nullbytefoofoo\")); } #[test] fn test_null_byte_fail() { use path2::null_byte::cond; use task; macro_rules! t( ($name:expr => $code:block) => ( { let mut t = task::task(); t.supervised(); t.name($name); let res = do t.try $code; assert!(res.is_err()); } ) ) t!(~\"new() wnul\" => { do cond.trap(|_| { (b!(\"null\", 0).to_owned()) }).inside { Path::new(b!(\"foobar\", 0)) }; }) t!(~\"set_filename wnul\" => { let mut p = Path::new(b!(\"foobar\")); do cond.trap(|_| { (b!(\"null\", 0).to_owned()) }).inside { p.set_filename(b!(\"foo\", 0)) }; }) t!(~\"set_dirname wnul\" => { let mut p = Path::new(b!(\"foobar\")); do cond.trap(|_| { (b!(\"null\", 0).to_owned()) }).inside { p.set_dirname(b!(\"foo\", 0)) }; }) t!(~\"push wnul\" => { let mut p = Path::new(b!(\"foobar\")); do cond.trap(|_| { (b!(\"null\", 0).to_owned()) }).inside { p.push(b!(\"foo\", 0)) }; }) } #[test] #[should_fail] fn test_not_utf8_fail() { Path::new(b!(\"hello\", 0x80, \".txt\")); } #[test] fn test_components() { macro_rules! t( (s: $path:expr, $op:ident, $exp:expr) => ( { let path = Path::from_str($path); assert_eq!(path.$op(), Some($exp)); } ); (s: $path:expr, $op:ident, $exp:expr, opt) => ( { let path = Path::from_str($path); let left = path.$op(); assert_eq!(left, $exp); } ); (v: $path:expr, $op:ident, $exp:expr) => ( { let path = Path::new($path); assert_eq!(path.$op(), $exp); } ) ) t!(v: b!(\"abc\"), filename, b!(\"c\")); t!(s: \"abc\", filename_str, \"c\"); t!(s: \"abc\", filename_str, \"c\"); t!(s: \"a\", filename_str, \"a\"); t!(s: \"a\", filename_str, \"a\"); t!(s: \".\", filename_str, \"\"); t!(s: \"\", filename_str, \"\"); t!(s: \"..\", filename_str, \"\"); t!(s: \"....\", filename_str, \"\"); t!(s: \"c:foo.txt\", filename_str, \"foo.txt\"); t!(s: \"C:\", filename_str, \"\"); t!(s: \"C:\", filename_str, \"\"); t!(s: \"serversharefoo.txt\", filename_str, \"foo.txt\"); t!(s: \"servershare\", filename_str, \"\"); t!(s: \"server\", filename_str, \"server\"); t!(s: \"?barfoo.txt\", filename_str, \"foo.txt\"); t!(s: \"?bar\", filename_str, \"\"); t!(s: \"?\", filename_str, \"\"); t!(s: \"?UNCserversharefoo.txt\", filename_str, \"foo.txt\"); t!(s: \"?UNCserver\", filename_str, \"\"); t!(s: \"?UNC\", filename_str, \"\"); t!(s: \"?C:foo.txt\", filename_str, \"foo.txt\"); t!(s: \"?C:\", filename_str, \"\"); t!(s: \"?C:\", filename_str, \"\"); t!(s: \"?foo/bar\", filename_str, \"\"); t!(s: \"?C:/foo\", filename_str, \"\"); t!(s: \".foobar\", filename_str, \"bar\"); t!(s: \".foo\", filename_str, \"\"); t!(s: \".foo/bar\", filename_str, \"\"); t!(s: \".foobar/baz\", filename_str, \"bar/baz\"); t!(s: \".\", filename_str, \"\"); t!(s: \"?ab\", filename_str, \"b\"); t!(v: b!(\"abc\"), dirname, b!(\"ab\")); t!(s: \"abc\", dirname_str, \"ab\"); t!(s: \"abc\", dirname_str, \"ab\"); t!(s: \"a\", dirname_str, \".\"); t!(s: \"a\", dirname_str, \"\"); t!(s: \".\", dirname_str, \".\"); t!(s: \"\", dirname_str, \"\"); t!(s: \"..\", dirname_str, \"..\"); t!(s: \"....\", dirname_str, \"....\"); t!(s: \"c:foo.txt\", dirname_str, \"C:\"); t!(s: \"C:\", dirname_str, \"C:\"); t!(s: \"C:\", dirname_str, \"C:\"); t!(s: \"C:foo.txt\", dirname_str, \"C:\"); t!(s: \"serversharefoo.txt\", dirname_str, \"servershare\"); t!(s: \"servershare\", dirname_str, \"servershare\"); t!(s: \"server\", dirname_str, \"\"); t!(s: \"?barfoo.txt\", dirname_str, \"?bar\"); t!(s: \"?bar\", dirname_str, \"?bar\"); t!(s: \"?\", dirname_str, \"?\"); t!(s: \"?UNCserversharefoo.txt\", dirname_str, \"?UNCservershare\"); t!(s: \"?UNCserver\", dirname_str, \"?UNCserver\"); t!(s: \"?UNC\", dirname_str, \"?UNC\"); t!(s: \"?C:foo.txt\", dirname_str, \"?C:\"); t!(s: \"?C:\", dirname_str, \"?C:\"); t!(s: \"?C:\", dirname_str, \"?C:\"); t!(s: \"?C:/foo/bar\", dirname_str, \"?C:/foo/bar\"); t!(s: \"?foo/bar\", dirname_str, \"?foo/bar\"); t!(s: \".foobar\", dirname_str, \".foo\"); t!(s: \".foo\", dirname_str, \".foo\"); t!(s: \"?ab\", dirname_str, \"?a\"); t!(v: b!(\"hithere.txt\"), filestem, b!(\"there\")); t!(s: \"hithere.txt\", filestem_str, \"there\"); t!(s: \"hithere\", filestem_str, \"there\"); t!(s: \"there.txt\", filestem_str, \"there\"); t!(s: \"there\", filestem_str, \"there\"); t!(s: \".\", filestem_str, \"\"); t!(s: \"\", filestem_str, \"\"); t!(s: \"foo.bar\", filestem_str, \".bar\"); t!(s: \".bar\", filestem_str, \".bar\"); t!(s: \"..bar\", filestem_str, \".\"); t!(s: \"hithere..txt\", filestem_str, \"there.\"); t!(s: \"..\", filestem_str, \"\"); t!(s: \"....\", filestem_str, \"\"); // filestem is based on filename, so we don't need the full set of prefix tests t!(v: b!(\"hithere.txt\"), extension, Some(b!(\"txt\"))); t!(v: b!(\"hithere\"), extension, None); t!(s: \"hithere.txt\", extension_str, Some(\"txt\"), opt); t!(s: \"hithere\", extension_str, None, opt); t!(s: \"there.txt\", extension_str, Some(\"txt\"), opt); t!(s: \"there\", extension_str, None, opt); t!(s: \".\", extension_str, None, opt); t!(s: \"\", extension_str, None, opt); t!(s: \"foo.bar\", extension_str, None, opt); t!(s: \".bar\", extension_str, None, opt); t!(s: \"..bar\", extension_str, Some(\"bar\"), opt); t!(s: \"hithere..txt\", extension_str, Some(\"txt\"), opt); t!(s: \"..\", extension_str, None, opt); t!(s: \"....\", extension_str, None, opt); // extension is based on filename, so we don't need the full set of prefix tests } #[test] fn test_push() { macro_rules! t( (s: $path:expr, $join:expr) => ( { let path = ($path); let join = ($join); let mut p1 = Path::from_str(path); let p2 = p1.clone(); p1.push_str(join); assert_eq!(p1, p2.join_str(join)); } ) ) t!(s: \"abc\", \"..\"); t!(s: \"abc\", \"d\"); t!(s: \"ab\", \"cd\"); t!(s: \"ab\", \"cd\"); // this is just a sanity-check test. push_str and join_str share an implementation, // so there's no need for the full set of prefix tests // we do want to check one odd case though to ensure the prefix is re-parsed let mut p = Path::from_str(\"?C:\"); assert_eq!(p.prefix(), Some(VerbatimPrefix(2))); p.push_str(\"foo\"); assert_eq!(p.prefix(), Some(VerbatimDiskPrefix)); assert_eq!(p.as_str(), Some(\"?C:foo\")); // and another with verbatim non-normalized paths let mut p = Path::from_str(\"?C:a\"); p.push_str(\"foo\"); assert_eq!(p.as_str(), Some(\"?C:afoo\")); } #[test] fn test_push_path() { macro_rules! t( (s: $path:expr, $push:expr, $exp:expr) => ( { let mut p = Path::from_str($path); let push = Path::from_str($push); p.push_path(&push); assert_eq!(p.as_str(), Some($exp)); } ) ) t!(s: \"abc\", \"d\", \"abcd\"); t!(s: \"abc\", \"d\", \"abcd\"); t!(s: \"ab\", \"cd\", \"abcd\"); t!(s: \"ab\", \"cd\", \"cd\"); t!(s: \"ab\", \".\", \"ab\"); t!(s: \"ab\", \"..c\", \"ac\"); t!(s: \"ab\", \"C:a.txt\", \"C:a.txt\"); t!(s: \"ab\", \"......c\", \"..c\"); t!(s: \"ab\", \"C:a.txt\", \"C:a.txt\"); t!(s: \"C:a\", \"C:b.txt\", \"C:b.txt\"); t!(s: \"C:abc\", \"C:d\", \"C:abcd\"); t!(s: \"C:abc\", \"C:d\", \"C:abcd\"); t!(s: \"C:ab\", \"......c\", \"C:..c\"); t!(s: \"C:ab\", \"......c\", \"C:c\"); t!(s: \"serversharefoo\", \"bar\", \"serversharefoobar\"); t!(s: \"serversharefoo\", \"....bar\", \"serversharebar\"); t!(s: \"serversharefoo\", \"C:baz\", \"C:baz\"); t!(s: \"?C:ab\", \"C:cd\", \"?C:abcd\"); t!(s: \"?C:ab\", \"C:cd\", \"C:cd\"); t!(s: \"?C:ab\", \"C:cd\", \"C:cd\"); t!(s: \"?foobar\", \"baz\", \"?foobarbaz\"); t!(s: \"?C:ab\", \"......c\", \"?C:ab......c\"); t!(s: \"?foobar\", \"....c\", \"?foobar....c\"); t!(s: \"?\", \"foo\", \"?foo\"); t!(s: \"?UNCserversharefoo\", \"bar\", \"?UNCserversharefoobar\"); t!(s: \"?UNCservershare\", \"C:a\", \"C:a\"); t!(s: \"?UNCservershare\", \"C:a\", \"C:a\"); t!(s: \"?UNCserver\", \"foo\", \"?UNCserverfoo\"); t!(s: \"C:a\", \"?UNCservershare\", \"?UNCservershare\"); t!(s: \".foobar\", \"baz\", \".foobarbaz\"); t!(s: \".foobar\", \"C:a\", \"C:a\"); // again, not sure about the following, but I'm assuming . should be verbatim t!(s: \".foo\", \"..bar\", \".foo..bar\"); t!(s: \"?C:\", \"foo\", \"?C:foo\"); // this is a weird one } #[test] fn test_pop() { macro_rules! t( (s: $path:expr, $left:expr, $right:expr) => ( { let pstr = $path; let mut p = Path::from_str(pstr); let file = p.pop_opt_str(); let left = $left; assert!(p.as_str() == Some(left), \"`%s`.pop() failed; expected remainder `%s`, found `%s`\", pstr, left, p.as_str().unwrap()); let right = $right; let res = file.map(|s| s.as_slice()); assert!(res == right, \"`%s`.pop() failed; expected `%?`, found `%?`\", pstr, right, res); } ); (v: [$($path:expr),+], [$($left:expr),+], Some($($right:expr),+)) => ( { let mut p = Path::new(b!($($path),+)); let file = p.pop_opt(); assert_eq!(p.as_vec(), b!($($left),+)); assert_eq!(file.map(|v| v.as_slice()), Some(b!($($right),+))); } ); (v: [$($path:expr),+], [$($left:expr),+], None) => ( { let mut p = Path::new(b!($($path),+)); let file = p.pop_opt(); assert_eq!(p.as_vec(), b!($($left),+)); assert_eq!(file, None); } ) ) t!(s: \"abc\", \"ab\", Some(\"c\")); t!(s: \"a\", \".\", Some(\"a\")); t!(s: \".\", \".\", None); t!(s: \"a\", \"\", Some(\"a\")); t!(s: \"\", \"\", None); t!(v: [\"abc\"], [\"ab\"], Some(\"c\")); t!(v: [\"a\"], [\".\"], Some(\"a\")); t!(v: [\".\"], [\".\"], None); t!(v: [\"a\"], [\"\"], Some(\"a\")); t!(v: [\"\"], [\"\"], None); t!(s: \"C:ab\", \"C:a\", Some(\"b\")); t!(s: \"C:a\", \"C:\", Some(\"a\")); t!(s: \"C:\", \"C:\", None); t!(s: \"C:ab\", \"C:a\", Some(\"b\")); t!(s: \"C:a\", \"C:\", Some(\"a\")); t!(s: \"C:\", \"C:\", None); t!(s: \"servershareab\", \"serversharea\", Some(\"b\")); t!(s: \"serversharea\", \"servershare\", Some(\"a\")); t!(s: \"servershare\", \"servershare\", None); t!(s: \"?abc\", \"?ab\", Some(\"c\")); t!(s: \"?ab\", \"?a\", Some(\"b\")); t!(s: \"?a\", \"?a\", None); t!(s: \"?C:ab\", \"?C:a\", Some(\"b\")); t!(s: \"?C:a\", \"?C:\", Some(\"a\")); t!(s: \"?C:\", \"?C:\", None); t!(s: \"?UNCservershareab\", \"?UNCserversharea\", Some(\"b\")); t!(s: \"?UNCserversharea\", \"?UNCservershare\", Some(\"a\")); t!(s: \"?UNCservershare\", \"?UNCservershare\", None); t!(s: \".abc\", \".ab\", Some(\"c\")); t!(s: \".ab\", \".a\", Some(\"b\")); t!(s: \".a\", \".a\", None); t!(s: \"?ab\", \"?a\", Some(\"b\")); } #[test] fn test_join() { t!(s: Path::from_str(\"abc\").join_str(\"..\"), \"ab\"); t!(s: Path::from_str(\"abc\").join_str(\"d\"), \"abcd\"); t!(s: Path::from_str(\"ab\").join_str(\"cd\"), \"abcd\"); t!(s: Path::from_str(\"ab\").join_str(\"cd\"), \"cd\"); t!(s: Path::from_str(\".\").join_str(\"ab\"), \"ab\"); t!(s: Path::from_str(\"\").join_str(\"ab\"), \"ab\"); t!(v: Path::new(b!(\"abc\")).join(b!(\"..\")), b!(\"ab\")); t!(v: Path::new(b!(\"abc\")).join(b!(\"d\")), b!(\"abcd\")); // full join testing is covered under test_push_path, so no need for // the full set of prefix tests } #[test] fn test_join_path() { macro_rules! t( (s: $path:expr, $join:expr, $exp:expr) => ( { let path = Path::from_str($path); let join = Path::from_str($join); let res = path.join_path(&join); assert_eq!(res.as_str(), Some($exp)); } ) ) t!(s: \"abc\", \"..\", \"ab\"); t!(s: \"abc\", \"d\", \"abcd\"); t!(s: \"ab\", \"cd\", \"abcd\"); t!(s: \"ab\", \"cd\", \"cd\"); t!(s: \".\", \"ab\", \"ab\"); t!(s: \"\", \"ab\", \"ab\"); // join_path is implemented using push_path, so there's no need for // the full set of prefix tests } #[test] fn test_with_helpers() { macro_rules! t( (s: $path:expr, $op:ident, $arg:expr, $res:expr) => ( { let pstr = $path; let path = Path::from_str(pstr); let arg = $arg; let res = path.$op(arg); let exp = $res; assert!(res.as_str() == Some(exp), \"`%s`.%s(\"%s\"): Expected `%s`, found `%s`\", pstr, stringify!($op), arg, exp, res.as_str().unwrap()); } ) ) t!(s: \"abc\", with_dirname_str, \"d\", \"dc\"); t!(s: \"abc\", with_dirname_str, \"de\", \"dec\"); t!(s: \"abc\", with_dirname_str, \"\", \"c\"); t!(s: \"abc\", with_dirname_str, \"\", \"c\"); t!(s: \"abc\", with_dirname_str, \"/\", \"c\"); t!(s: \"abc\", with_dirname_str, \".\", \"c\"); t!(s: \"abc\", with_dirname_str, \"..\", \"..c\"); t!(s: \"\", with_dirname_str, \"foo\", \"foo\"); t!(s: \"\", with_dirname_str, \"\", \".\"); t!(s: \"foo\", with_dirname_str, \"bar\", \"barfoo\"); t!(s: \"..\", with_dirname_str, \"foo\", \"foo\"); t!(s: \"....\", with_dirname_str, \"foo\", \"foo\"); t!(s: \"..\", with_dirname_str, \"\", \".\"); t!(s: \"....\", with_dirname_str, \"\", \".\"); t!(s: \".\", with_dirname_str, \"foo\", \"foo\"); t!(s: \"foo\", with_dirname_str, \"..\", \"..foo\"); t!(s: \"foo\", with_dirname_str, \"....\", \"....foo\"); t!(s: \"C:ab\", with_dirname_str, \"foo\", \"foob\"); t!(s: \"foo\", with_dirname_str, \"C:ab\", \"C:abfoo\"); t!(s: \"C:ab\", with_dirname_str, \"servershare\", \"servershareb\"); t!(s: \"a\", with_dirname_str, \"servershare\", \"serversharea\"); t!(s: \"ab\", with_dirname_str, \"?\", \"?b\"); t!(s: \"ab\", with_dirname_str, \"C:\", \"C:b\"); t!(s: \"ab\", with_dirname_str, \"C:\", \"C:b\"); t!(s: \"ab\", with_dirname_str, \"C:/\", \"C:b\"); t!(s: \"C:\", with_dirname_str, \"foo\", \"foo\"); t!(s: \"C:\", with_dirname_str, \"foo\", \"foo\"); t!(s: \".\", with_dirname_str, \"C:\", \"C:\"); t!(s: \".\", with_dirname_str, \"C:/\", \"C:\"); t!(s: \"?C:foo\", with_dirname_str, \"C:\", \"C:foo\"); t!(s: \"?C:\", with_dirname_str, \"bar\", \"bar\"); t!(s: \"foobar\", with_dirname_str, \"?C:baz\", \"?C:bazbar\"); t!(s: \"?foo\", with_dirname_str, \"C:bar\", \"C:bar\"); t!(s: \"?afoo\", with_dirname_str, \"C:bar\", \"C:barfoo\"); t!(s: \"?afoo/bar\", with_dirname_str, \"C:baz\", \"C:bazfoobar\"); t!(s: \"?UNCserversharebaz\", with_dirname_str, \"a\", \"abaz\"); t!(s: \"foobar\", with_dirname_str, \"?UNCserversharebaz\", \"?UNCserversharebazbar\"); t!(s: \".foo\", with_dirname_str, \"bar\", \"bar\"); t!(s: \".foobar\", with_dirname_str, \"baz\", \"bazbar\"); t!(s: \".foobar\", with_dirname_str, \"baz\", \"bazbar\"); t!(s: \".foobar\", with_dirname_str, \"baz/\", \"bazbar\"); t!(s: \"abc\", with_filename_str, \"d\", \"abd\"); t!(s: \".\", with_filename_str, \"foo\", \"foo\"); t!(s: \"abc\", with_filename_str, \"d\", \"abd\"); t!(s: \"\", with_filename_str, \"foo\", \"foo\"); t!(s: \"a\", with_filename_str, \"foo\", \"foo\"); t!(s: \"foo\", with_filename_str, \"bar\", \"bar\"); t!(s: \"\", with_filename_str, \"foo\", \"foo\"); t!(s: \"a\", with_filename_str, \"foo\", \"foo\"); t!(s: \"abc\", with_filename_str, \"\", \"ab\"); t!(s: \"abc\", with_filename_str, \".\", \"ab\"); t!(s: \"abc\", with_filename_str, \"..\", \"a\"); t!(s: \"a\", with_filename_str, \"\", \"\"); t!(s: \"foo\", with_filename_str, \"\", \".\"); t!(s: \"abc\", with_filename_str, \"de\", \"abde\"); t!(s: \"abc\", with_filename_str, \"d\", \"abd\"); t!(s: \"..\", with_filename_str, \"foo\", \"..foo\"); t!(s: \"....\", with_filename_str, \"foo\", \"....foo\"); t!(s: \"..\", with_filename_str, \"\", \"..\"); t!(s: \"....\", with_filename_str, \"\", \"....\"); t!(s: \"C:foobar\", with_filename_str, \"baz\", \"C:foobaz\"); t!(s: \"C:foo\", with_filename_str, \"bar\", \"C:bar\"); t!(s: \"C:\", with_filename_str, \"foo\", \"C:foo\"); t!(s: \"C:foobar\", with_filename_str, \"baz\", \"C:foobaz\"); t!(s: \"C:foo\", with_filename_str, \"bar\", \"C:bar\"); t!(s: \"C:\", with_filename_str, \"foo\", \"C:foo\"); t!(s: \"C:foo\", with_filename_str, \"\", \"C:\"); t!(s: \"C:foo\", with_filename_str, \"\", \"C:\"); t!(s: \"C:foobar\", with_filename_str, \"..\", \"C:\"); t!(s: \"C:foo\", with_filename_str, \"..\", \"C:\"); t!(s: \"C:\", with_filename_str, \"..\", \"C:\"); t!(s: \"C:foobar\", with_filename_str, \"..\", \"C:\"); t!(s: \"C:foo\", with_filename_str, \"..\", \"C:..\"); t!(s: \"C:\", with_filename_str, \"..\", \"C:..\"); t!(s: \"serversharefoo\", with_filename_str, \"bar\", \"serversharebar\"); t!(s: \"servershare\", with_filename_str, \"foo\", \"serversharefoo\"); t!(s: \"serversharefoo\", with_filename_str, \"\", \"servershare\"); t!(s: \"servershare\", with_filename_str, \"\", \"servershare\"); t!(s: \"serversharefoo\", with_filename_str, \"..\", \"servershare\"); t!(s: \"servershare\", with_filename_str, \"..\", \"servershare\"); t!(s: \"?C:foobar\", with_filename_str, \"baz\", \"?C:foobaz\"); t!(s: \"?C:foo\", with_filename_str, \"bar\", \"?C:bar\"); t!(s: \"?C:\", with_filename_str, \"foo\", \"?C:foo\"); t!(s: \"?C:foo\", with_filename_str, \"..\", \"?C:..\"); t!(s: \"?foobar\", with_filename_str, \"baz\", \"?foobaz\"); t!(s: \"?foo\", with_filename_str, \"bar\", \"?foobar\"); t!(s: \"?\", with_filename_str, \"foo\", \"?foo\"); t!(s: \"?foobar\", with_filename_str, \"..\", \"?foo..\"); t!(s: \".foobar\", with_filename_str, \"baz\", \".foobaz\"); t!(s: \".foo\", with_filename_str, \"bar\", \".foobar\"); t!(s: \".foobar\", with_filename_str, \"..\", \".foo..\"); t!(s: \"hithere.txt\", with_filestem_str, \"here\", \"hihere.txt\"); t!(s: \"hithere.txt\", with_filestem_str, \"\", \"hi.txt\"); t!(s: \"hithere.txt\", with_filestem_str, \".\", \"hi..txt\"); t!(s: \"hithere.txt\", with_filestem_str, \"..\", \"hi...txt\"); t!(s: \"hithere.txt\", with_filestem_str, \"\", \"hi.txt\"); t!(s: \"hithere.txt\", with_filestem_str, \"foobar\", \"hifoobar.txt\"); t!(s: \"hithere.foo.txt\", with_filestem_str, \"here\", \"hihere.txt\"); t!(s: \"hithere\", with_filestem_str, \"here\", \"hihere\"); t!(s: \"hithere\", with_filestem_str, \"\", \"hi\"); t!(s: \"hi\", with_filestem_str, \"\", \".\"); t!(s: \"hi\", with_filestem_str, \"\", \"\"); t!(s: \"hithere\", with_filestem_str, \"..\", \".\"); t!(s: \"hithere\", with_filestem_str, \".\", \"hi\"); t!(s: \"hithere.\", with_filestem_str, \"foo\", \"hifoo.\"); t!(s: \"hithere.\", with_filestem_str, \"\", \"hi\"); t!(s: \"hithere.\", with_filestem_str, \".\", \".\"); t!(s: \"hithere.\", with_filestem_str, \"..\", \"hi...\"); t!(s: \"\", with_filestem_str, \"foo\", \"foo\"); t!(s: \".\", with_filestem_str, \"foo\", \"foo\"); t!(s: \"hithere..\", with_filestem_str, \"here\", \"hihere.\"); t!(s: \"hithere..\", with_filestem_str, \"\", \"hi\"); // filestem setter calls filename setter internally, no need for extended tests t!(s: \"hithere.txt\", with_extension_str, \"exe\", \"hithere.exe\"); t!(s: \"hithere.txt\", with_extension_str, \"\", \"hithere\"); t!(s: \"hithere.txt\", with_extension_str, \".\", \"hithere..\"); t!(s: \"hithere.txt\", with_extension_str, \"..\", \"hithere...\"); t!(s: \"hithere\", with_extension_str, \"txt\", \"hithere.txt\"); t!(s: \"hithere\", with_extension_str, \".\", \"hithere..\"); t!(s: \"hithere\", with_extension_str, \"..\", \"hithere...\"); t!(s: \"hithere.\", with_extension_str, \"txt\", \"hithere.txt\"); t!(s: \"hi.foo\", with_extension_str, \"txt\", \"hi.foo.txt\"); t!(s: \"hithere.txt\", with_extension_str, \".foo\", \"hithere..foo\"); t!(s: \"\", with_extension_str, \"txt\", \"\"); t!(s: \"\", with_extension_str, \".\", \"\"); t!(s: \"\", with_extension_str, \"..\", \"\"); t!(s: \".\", with_extension_str, \"txt\", \".\"); // extension setter calls filename setter internally, no need for extended tests } #[test] fn test_setters() { macro_rules! t( (s: $path:expr, $set:ident, $with:ident, $arg:expr) => ( { let path = $path; let arg = $arg; let mut p1 = Path::from_str(path); p1.$set(arg); let p2 = Path::from_str(path); assert_eq!(p1, p2.$with(arg)); } ); (v: $path:expr, $set:ident, $with:ident, $arg:expr) => ( { let path = $path; let arg = $arg; let mut p1 = Path::new(path); p1.$set(arg); let p2 = Path::new(path); assert_eq!(p1, p2.$with(arg)); } ) ) t!(v: b!(\"abc\"), set_dirname, with_dirname, b!(\"d\")); t!(v: b!(\"abc\"), set_dirname, with_dirname, b!(\"de\")); t!(s: \"abc\", set_dirname_str, with_dirname_str, \"d\"); t!(s: \"abc\", set_dirname_str, with_dirname_str, \"de\"); t!(s: \"\", set_dirname_str, with_dirname_str, \"foo\"); t!(s: \"foo\", set_dirname_str, with_dirname_str, \"bar\"); t!(s: \"abc\", set_dirname_str, with_dirname_str, \"\"); t!(s: \"....\", set_dirname_str, with_dirname_str, \"x\"); t!(s: \"foo\", set_dirname_str, with_dirname_str, \"....\"); t!(v: b!(\"abc\"), set_filename, with_filename, b!(\"d\")); t!(v: b!(\"\"), set_filename, with_filename, b!(\"foo\")); t!(s: \"abc\", set_filename_str, with_filename_str, \"d\"); t!(s: \"\", set_filename_str, with_filename_str, \"foo\"); t!(s: \".\", set_filename_str, with_filename_str, \"foo\"); t!(s: \"ab\", set_filename_str, with_filename_str, \"\"); t!(s: \"a\", set_filename_str, with_filename_str, \"\"); t!(v: b!(\"hithere.txt\"), set_filestem, with_filestem, b!(\"here\")); t!(s: \"hithere.txt\", set_filestem_str, with_filestem_str, \"here\"); t!(s: \"hithere.\", set_filestem_str, with_filestem_str, \"here\"); t!(s: \"hithere\", set_filestem_str, with_filestem_str, \"here\"); t!(s: \"hithere.txt\", set_filestem_str, with_filestem_str, \"\"); t!(s: \"hithere\", set_filestem_str, with_filestem_str, \"\"); t!(v: b!(\"hithere.txt\"), set_extension, with_extension, b!(\"exe\")); t!(s: \"hithere.txt\", set_extension_str, with_extension_str, \"exe\"); t!(s: \"hithere.\", set_extension_str, with_extension_str, \"txt\"); t!(s: \"hithere\", set_extension_str, with_extension_str, \"txt\"); t!(s: \"hithere.txt\", set_extension_str, with_extension_str, \"\"); t!(s: \"hithere\", set_extension_str, with_extension_str, \"\"); t!(s: \".\", set_extension_str, with_extension_str, \"txt\"); // with_ helpers use the setter internally, so the tests for the with_ helpers // will suffice. No need for the full set of prefix tests. } #[test] fn test_getters() { macro_rules! t( (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; assert_eq!(path.filename_str(), $filename); assert_eq!(path.dirname_str(), $dirname); assert_eq!(path.filestem_str(), $filestem); assert_eq!(path.extension_str(), $ext); } ); (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; assert_eq!(path.filename(), $filename); assert_eq!(path.dirname(), $dirname); assert_eq!(path.filestem(), $filestem); assert_eq!(path.extension(), $ext); } ) ) t!(v: Path::new(b!(\"abc\")), b!(\"c\"), b!(\"ab\"), b!(\"c\"), None); t!(s: Path::from_str(\"abc\"), Some(\"c\"), Some(\"ab\"), Some(\"c\"), None); t!(s: Path::from_str(\".\"), Some(\"\"), Some(\".\"), Some(\"\"), None); t!(s: Path::from_str(\"\"), Some(\"\"), Some(\"\"), Some(\"\"), None); t!(s: Path::from_str(\"..\"), Some(\"\"), Some(\"..\"), Some(\"\"), None); t!(s: Path::from_str(\"....\"), Some(\"\"), Some(\"....\"), Some(\"\"), None); t!(s: Path::from_str(\"hithere.txt\"), Some(\"there.txt\"), Some(\"hi\"), Some(\"there\"), Some(\"txt\")); t!(s: Path::from_str(\"hithere\"), Some(\"there\"), Some(\"hi\"), Some(\"there\"), None); t!(s: Path::from_str(\"hithere.\"), Some(\"there.\"), Some(\"hi\"), Some(\"there\"), Some(\"\")); t!(s: Path::from_str(\"hi.there\"), Some(\".there\"), Some(\"hi\"), Some(\".there\"), None); t!(s: Path::from_str(\"hi..there\"), Some(\"..there\"), Some(\"hi\"), Some(\".\"), Some(\"there\")); // these are already tested in test_components, so no need for extended tests } #[test] fn test_dir_file_path() { t!(s: Path::from_str(\"hithere\").dir_path(), \"hi\"); t!(s: Path::from_str(\"hi\").dir_path(), \".\"); t!(s: Path::from_str(\"hi\").dir_path(), \"\"); t!(s: Path::from_str(\"\").dir_path(), \"\"); t!(s: Path::from_str(\"..\").dir_path(), \"..\"); t!(s: Path::from_str(\"....\").dir_path(), \"....\"); macro_rules! t( ($path:expr, $exp:expr) => ( { let path = $path; let left = path.and_then_ref(|p| p.as_str()); assert_eq!(left, $exp); } ); ) t!(Path::from_str(\"hithere\").file_path(), Some(\"there\")); t!(Path::from_str(\"hi\").file_path(), Some(\"hi\")); t!(Path::from_str(\".\").file_path(), None); t!(Path::from_str(\"\").file_path(), None); t!(Path::from_str(\"..\").file_path(), None); t!(Path::from_str(\"....\").file_path(), None); // dir_path and file_path are just dirname and filename interpreted as paths. // No need for extended tests } #[test] fn test_is_absolute() { macro_rules! t( ($path:expr, $abs:expr, $vol:expr, $cwd:expr) => ( { let path = Path::from_str($path); let (abs, vol, cwd) = ($abs, $vol, $cwd); let b = path.is_absolute(); assert!(b == abs, \"Path '%s'.is_absolute(): expected %?, found %?\", path.as_str().unwrap(), abs, b); let b = path.is_vol_relative(); assert!(b == vol, \"Path '%s'.is_vol_relative(): expected %?, found %?\", path.as_str().unwrap(), vol, b); let b = path.is_cwd_relative(); assert!(b == cwd, \"Path '%s'.is_cwd_relative(): expected %?, found %?\", path.as_str().unwrap(), cwd, b); } ) ) t!(\"abc\", false, false, false); t!(\"abc\", false, true, false); t!(\"a\", false, false, false); t!(\"a\", false, true, false); t!(\".\", false, false, false); t!(\"\", false, true, false); t!(\"..\", false, false, false); t!(\"....\", false, false, false); t!(\"C:ab.txt\", false, false, true); t!(\"C:ab.txt\", true, false, false); t!(\"servershareab.txt\", true, false, false); t!(\"?abc.txt\", true, false, false); t!(\"?C:ab.txt\", true, false, false); t!(\"?C:ab.txt\", true, false, false); // NB: not equivalent to C:ab.txt t!(\"?UNCservershareab.txt\", true, false, false); t!(\".ab\", true, false, false); } #[test] fn test_is_ancestor_of() { macro_rules! t( (s: $path:expr, $dest:expr, $exp:expr) => ( { let path = Path::from_str($path); let dest = Path::from_str($dest); let exp = $exp; let res = path.is_ancestor_of(&dest); assert!(res == exp, \"`%s`.is_ancestor_of(`%s`): Expected %?, found %?\", path.as_str().unwrap(), dest.as_str().unwrap(), exp, res); } ) ) t!(s: \"abc\", \"abcd\", true); t!(s: \"abc\", \"abc\", true); t!(s: \"abc\", \"ab\", false); t!(s: \"abc\", \"abc\", true); t!(s: \"ab\", \"abc\", true); t!(s: \"abcd\", \"abc\", false); t!(s: \"ab\", \"abc\", false); t!(s: \"ab\", \"abc\", false); t!(s: \"abc\", \"abd\", false); t!(s: \"..abc\", \"abc\", false); t!(s: \"abc\", \"..abc\", false); t!(s: \"abc\", \"abcd\", false); t!(s: \"abcd\", \"abc\", false); t!(s: \"..ab\", \"..abc\", true); t!(s: \".\", \"ab\", true); t!(s: \".\", \".\", true); t!(s: \"\", \"\", true); t!(s: \"\", \"ab\", true); t!(s: \"..\", \"ab\", true); t!(s: \"....\", \"ab\", true); t!(s: \"foobar\", \"foobar\", false); t!(s: \"foobar\", \"foobar\", false); t!(s: \"foo\", \"C:foo\", false); t!(s: \"C:foo\", \"foo\", false); t!(s: \"C:foo\", \"C:foobar\", true); t!(s: \"C:foobar\", \"C:foo\", false); t!(s: \"C:foo\", \"C:foobar\", true); t!(s: \"C:\", \"C:\", true); t!(s: \"C:\", \"C:\", false); t!(s: \"C:\", \"C:\", false); t!(s: \"C:\", \"C:\", true); t!(s: \"C:foobar\", \"C:foo\", false); t!(s: \"C:foobar\", \"C:foo\", false); t!(s: \"C:foo\", \"foo\", false); t!(s: \"foo\", \"C:foo\", false); t!(s: \"serversharefoo\", \"serversharefoobar\", true); t!(s: \"servershare\", \"serversharefoo\", true); t!(s: \"serversharefoo\", \"servershare\", false); t!(s: \"C:foo\", \"serversharefoo\", false); t!(s: \"serversharefoo\", \"C:foo\", false); t!(s: \"?foobar\", \"?foobarbaz\", true); t!(s: \"?foobarbaz\", \"?foobar\", false); t!(s: \"?foobar\", \"foobarbaz\", false); t!(s: \"foobar\", \"?foobarbaz\", false); t!(s: \"?C:foobar\", \"?C:foobarbaz\", true); t!(s: \"?C:foobarbaz\", \"?C:foobar\", false); t!(s: \"?C:\", \"?C:foo\", true); t!(s: \"?C:\", \"?C:\", false); // this is a weird one t!(s: \"?C:\", \"?C:\", false); t!(s: \"?C:a\", \"?c:ab\", true); t!(s: \"?c:a\", \"?C:ab\", true); t!(s: \"?C:a\", \"?D:ab\", false); t!(s: \"?foo\", \"?foobar\", false); t!(s: \"?ab\", \"?abc\", true); t!(s: \"?ab\", \"?ab\", true); t!(s: \"?ab\", \"?ab\", true); t!(s: \"?abc\", \"?ab\", false); t!(s: \"?abc\", \"?ab\", false); t!(s: \"?UNCabc\", \"?UNCabcd\", true); t!(s: \"?UNCabcd\", \"?UNCabc\", false); t!(s: \"?UNCab\", \"?UNCabc\", true); t!(s: \".foobar\", \".foobarbaz\", true); t!(s: \".foobarbaz\", \".foobar\", false); t!(s: \".foo\", \".foobar\", true); t!(s: \".foo\", \".foobar\", false); t!(s: \"ab\", \"?ab\", false); t!(s: \"?ab\", \"ab\", false); t!(s: \"ab\", \"?C:ab\", false); t!(s: \"?C:ab\", \"ab\", false); t!(s: \"Z:ab\", \"?z:ab\", true); t!(s: \"C:ab\", \"?D:ab\", false); t!(s: \"ab\", \"?ab\", false); t!(s: \"?ab\", \"ab\", false); t!(s: \"C:ab\", \"?C:ab\", true); t!(s: \"?C:ab\", \"C:ab\", true); t!(s: \"C:ab\", \"?C:ab\", false); t!(s: \"C:ab\", \"?C:ab\", false); t!(s: \"?C:ab\", \"C:ab\", false); t!(s: \"?C:ab\", \"C:ab\", false); t!(s: \"C:ab\", \"?C:ab\", true); t!(s: \"?C:ab\", \"C:ab\", true); t!(s: \"abc\", \"?UNCabc\", true); t!(s: \"?UNCabc\", \"abc\", true); } #[test] fn test_path_relative_from() { macro_rules! t( (s: $path:expr, $other:expr, $exp:expr) => ( { let path = Path::from_str($path); let other = Path::from_str($other); let res = path.path_relative_from(&other); let exp = $exp; assert!(res.and_then_ref(|x| x.as_str()) == exp, \"`%s`.path_relative_from(`%s`): Expected %?, got %?\", path.as_str().unwrap(), other.as_str().unwrap(), exp, res.and_then_ref(|x| x.as_str())); } ) ) t!(s: \"abc\", \"ab\", Some(\"c\")); t!(s: \"abc\", \"abd\", Some(\"..c\")); t!(s: \"abc\", \"abcd\", Some(\"..\")); t!(s: \"abc\", \"abc\", Some(\".\")); t!(s: \"abc\", \"abcde\", Some(\"....\")); t!(s: \"abc\", \"ade\", Some(\"....bc\")); t!(s: \"abc\", \"def\", Some(\"......abc\")); t!(s: \"abc\", \"abc\", None); t!(s: \"abc\", \"abc\", Some(\"abc\")); t!(s: \"abc\", \"abcd\", Some(\"..\")); t!(s: \"abc\", \"ab\", Some(\"c\")); t!(s: \"abc\", \"abcde\", Some(\"....\")); t!(s: \"abc\", \"ade\", Some(\"....bc\")); t!(s: \"abc\", \"def\", Some(\"......abc\")); t!(s: \"hithere.txt\", \"hithere\", Some(\"..there.txt\")); t!(s: \".\", \"a\", Some(\"..\")); t!(s: \".\", \"ab\", Some(\"....\")); t!(s: \".\", \".\", Some(\".\")); t!(s: \"a\", \".\", Some(\"a\")); t!(s: \"ab\", \".\", Some(\"ab\")); t!(s: \"..\", \".\", Some(\"..\")); t!(s: \"abc\", \"abc\", Some(\".\")); t!(s: \"abc\", \"abc\", Some(\".\")); t!(s: \"\", \"\", Some(\".\")); t!(s: \"\", \".\", Some(\"\")); t!(s: \"....a\", \"b\", Some(\"......a\")); t!(s: \"a\", \"....b\", None); t!(s: \"....a\", \"....b\", Some(\"..a\")); t!(s: \"....a\", \"....ab\", Some(\"..\")); t!(s: \"....ab\", \"....a\", Some(\"b\")); t!(s: \"C:abc\", \"C:ab\", Some(\"c\")); t!(s: \"C:ab\", \"C:abc\", Some(\"..\")); t!(s: \"C:\" ,\"C:ab\", Some(\"....\")); t!(s: \"C:ab\", \"C:cd\", Some(\"....ab\")); t!(s: \"C:ab\", \"D:cd\", Some(\"C:ab\")); t!(s: \"C:ab\", \"C:..c\", None); t!(s: \"C:..a\", \"C:bc\", Some(\"......a\")); t!(s: \"C:abc\", \"C:ab\", Some(\"c\")); t!(s: \"C:ab\", \"C:abc\", Some(\"..\")); t!(s: \"C:\", \"C:ab\", Some(\"....\")); t!(s: \"C:ab\", \"C:cd\", Some(\"....ab\")); t!(s: \"C:ab\", \"C:ab\", Some(\"C:ab\")); t!(s: \"C:ab\", \"C:ab\", None); t!(s: \"ab\", \"C:ab\", None); t!(s: \"ab\", \"C:ab\", None); t!(s: \"ab\", \"C:ab\", None); t!(s: \"ab\", \"C:ab\", None); t!(s: \"abc\", \"ab\", Some(\"c\")); t!(s: \"ab\", \"abc\", Some(\"..\")); t!(s: \"abce\", \"abcd\", Some(\"..e\")); t!(s: \"acd\", \"abd\", Some(\"acd\")); t!(s: \"bcd\", \"acd\", Some(\"bcd\")); t!(s: \"abc\", \"de\", Some(\"abc\")); t!(s: \"de\", \"abc\", None); t!(s: \"de\", \"abc\", None); t!(s: \"C:abc\", \"abc\", Some(\"C:abc\")); t!(s: \"C:c\", \"abc\", Some(\"C:c\")); t!(s: \"?ab\", \"ab\", Some(\"?ab\")); t!(s: \"?ab\", \"ab\", Some(\"?ab\")); t!(s: \"?ab\", \"b\", Some(\"?ab\")); t!(s: \"?ab\", \"b\", Some(\"?ab\")); t!(s: \"?ab\", \"?abc\", Some(\"..\")); t!(s: \"?abc\", \"?ab\", Some(\"c\")); t!(s: \"?ab\", \"?cd\", Some(\"?ab\")); t!(s: \"?a\", \"?b\", Some(\"?a\")); t!(s: \"?C:ab\", \"?C:a\", Some(\"b\")); t!(s: \"?C:a\", \"?C:ab\", Some(\"..\")); t!(s: \"?C:a\", \"?C:b\", Some(\"..a\")); t!(s: \"?C:a\", \"?D:a\", Some(\"?C:a\")); t!(s: \"?C:ab\", \"?c:a\", Some(\"b\")); t!(s: \"?C:ab\", \"C:a\", Some(\"b\")); t!(s: \"?C:a\", \"C:ab\", Some(\"..\")); t!(s: \"C:ab\", \"?C:a\", Some(\"b\")); t!(s: \"C:a\", \"?C:ab\", Some(\"..\")); t!(s: \"?C:a\", \"D:a\", Some(\"?C:a\")); t!(s: \"?c:ab\", \"C:a\", Some(\"b\")); t!(s: \"?C:ab\", \"C:ab\", Some(\"?C:ab\")); t!(s: \"?C:a.b\", \"C:a\", Some(\"?C:a.b\")); t!(s: \"?C:ab/c\", \"C:a\", Some(\"?C:ab/c\")); t!(s: \"?C:a..b\", \"C:a\", Some(\"?C:a..b\")); t!(s: \"C:ab\", \"?C:ab\", None); t!(s: \"?C:a.b\", \"?C:a\", Some(\"?C:a.b\")); t!(s: \"?C:ab/c\", \"?C:a\", Some(\"?C:ab/c\")); t!(s: \"?C:a..b\", \"?C:a\", Some(\"?C:a..b\")); t!(s: \"?C:ab\", \"?C:a\", Some(\"b\")); t!(s: \"?C:.b\", \"?C:.\", Some(\"b\")); t!(s: \"C:b\", \"?C:.\", Some(\"..b\")); t!(s: \"?a.bc\", \"?a.b\", Some(\"c\")); t!(s: \"?abc\", \"?a.d\", Some(\"....bc\")); t!(s: \"?a..b\", \"?a..\", Some(\"b\")); t!(s: \"?ab..\", \"?ab\", Some(\"?ab..\")); t!(s: \"?abc\", \"?a..b\", Some(\"....bc\")); t!(s: \"?UNCabc\", \"?UNCab\", Some(\"c\")); t!(s: \"?UNCab\", \"?UNCabc\", Some(\"..\")); t!(s: \"?UNCabc\", \"?UNCacd\", Some(\"?UNCabc\")); t!(s: \"?UNCbcd\", \"?UNCacd\", Some(\"?UNCbcd\")); t!(s: \"?UNCabc\", \"?abc\", Some(\"?UNCabc\")); t!(s: \"?UNCabc\", \"?C:abc\", Some(\"?UNCabc\")); t!(s: \"?UNCabc/d\", \"?UNCab\", Some(\"?UNCabc/d\")); t!(s: \"?UNCab.\", \"?UNCab\", Some(\"?UNCab.\")); t!(s: \"?UNCab..\", \"?UNCab\", Some(\"?UNCab..\")); t!(s: \"?UNCabc\", \"ab\", Some(\"c\")); t!(s: \"?UNCab\", \"abc\", Some(\"..\")); t!(s: \"?UNCabc\", \"acd\", Some(\"?UNCabc\")); t!(s: \"?UNCbcd\", \"acd\", Some(\"?UNCbcd\")); t!(s: \"?UNCab.\", \"ab\", Some(\"?UNCab.\")); t!(s: \"?UNCabc/d\", \"ab\", Some(\"?UNCabc/d\")); t!(s: \"?UNCab..\", \"ab\", Some(\"?UNCab..\")); t!(s: \"abc\", \"?UNCab\", Some(\"c\")); t!(s: \"abc\", \"?UNCacd\", Some(\"abc\")); } #[test] fn test_component_iter() { macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = Path::from_str($path); let comps = path.component_iter().to_owned_vec(); let exp: &[&str] = $exp; assert_eq!(comps.as_slice(), exp); } ); (v: [$($arg:expr),+], $exp:expr) => ( { let path = Path::new(b!($($arg),+)); let comps = path.component_iter().to_owned_vec(); let exp: &[&str] = $exp; assert_eq!(comps.as_slice(), exp); } ) ) t!(v: [\"abc\"], [\"a\", \"b\", \"c\"]); t!(s: \"abc\", [\"a\", \"b\", \"c\"]); t!(s: \"abd\", [\"a\", \"b\", \"d\"]); t!(s: \"abcd\", [\"a\", \"b\", \"cd\"]); t!(s: \"abc\", [\"a\", \"b\", \"c\"]); t!(s: \"a\", [\"a\"]); t!(s: \"a\", [\"a\"]); t!(s: \"\", []); t!(s: \".\", [\".\"]); t!(s: \"..\", [\"..\"]); t!(s: \"....\", [\"..\", \"..\"]); t!(s: \"....foo\", [\"..\", \"..\", \"foo\"]); t!(s: \"C:foobar\", [\"foo\", \"bar\"]); t!(s: \"C:foo\", [\"foo\"]); t!(s: \"C:\", []); t!(s: \"C:foobar\", [\"foo\", \"bar\"]); t!(s: \"C:foo\", [\"foo\"]); t!(s: \"C:\", []); t!(s: \"serversharefoobar\", [\"foo\", \"bar\"]); t!(s: \"serversharefoo\", [\"foo\"]); t!(s: \"servershare\", []); t!(s: \"?foobarbaz\", [\"bar\", \"baz\"]); t!(s: \"?foobar\", [\"bar\"]); t!(s: \"?foo\", []); t!(s: \"?\", []); t!(s: \"?ab\", [\"b\"]); t!(s: \"?ab\", [\"b\"]); t!(s: \"?foobarbaz\", [\"bar\", \"\", \"baz\"]); t!(s: \"?C:foobar\", [\"foo\", \"bar\"]); t!(s: \"?C:foo\", [\"foo\"]); t!(s: \"?C:\", []); t!(s: \"?C:foo\", [\"foo\"]); t!(s: \"?UNCserversharefoobar\", [\"foo\", \"bar\"]); t!(s: \"?UNCserversharefoo\", [\"foo\"]); t!(s: \"?UNCservershare\", []); t!(s: \".foobarbaz\", [\"bar\", \"baz\"]); t!(s: \".foobar\", [\"bar\"]); t!(s: \".foo\", []); } } "} {"_id":"q-en-rust-5cb8cde1af8ca1abd1d84eae7a66de58e76baaff688842d5cf1cc47024f0dd8d","text":"- [rustdoc: Only look at blanket impls in `get_blanket_impls`][83681] - [Rework rustdoc const type][82873] [85667]: https://github.com/rust-lang/rust/pull/85667 [83386]: https://github.com/rust-lang/rust/pull/83386 [82771]: https://github.com/rust-lang/rust/pull/82771 [84147]: https://github.com/rust-lang/rust/pull/84147"} {"_id":"q-en-rust-5ce3dbdd6620efe4974137b9fc2a3ed9f2c5e47626f5951d8705e312a8f6b911","text":" // Out-of-line module is found on the filesystem if passed through a proc macro (issue #58818). // check-pass // aux-build:test-macros.rs #[macro_use] extern crate test_macros; mod outer { identity! { mod inner; } } fn main() {} "} {"_id":"q-en-rust-5cebaa722c8ddb42da922342169ca497276968610a7f32ae18ce844bab0f0ad8","text":"} _ => { Err(if self.prev_token_kind == PrevTokenKind::DocComment { self.span_fatal_err(self.prev_span, Error::UselessDocComment) } else { self.expected_ident_found() }) self.span_fatal_err(self.prev_span, Error::UselessDocComment) } else { self.expected_ident_found() }) } } }"} {"_id":"q-en-rust-5e2c8a61712c0d53263d3cf260ebc028ea8068fdbd7676310a15a94c9de87015","text":"#[rustc_const_unstable(feature = \"const_waker\", issue = \"102012\")] #[unstable(feature = \"context_ext\", issue = \"123392\")] pub const fn from(cx: &'a mut Context<'_>) -> Self { let ext = match &mut cx.ext { let ext = match &mut *cx.ext { ExtData::Some(ext) => ExtData::Some(*ext), ExtData::None(()) => ExtData::None(()), };"} {"_id":"q-en-rust-5e61bea41f23c737508ba5bc5029c04bf352c2d223e8e2763e198ebc244091db","text":" error[E0599]: no method named `clone` found for struct `issue_69725::Struct` in the current scope --> $DIR/issue-69725.rs:7:32 | LL | let _ = Struct::::new().clone(); | ^^^^^ method not found in `issue_69725::Struct` | ::: $DIR/auxiliary/issue-69725.rs:2:1 | LL | pub struct Struct(A); | ------------------------ doesn't satisfy `issue_69725::Struct: std::clone::Clone` | = note: the method `clone` exists but the following trait bounds were not satisfied: `A: std::clone::Clone` which is required by `issue_69725::Struct: std::clone::Clone` error: aborting due to previous error For more information about this error, try `rustc --explain E0599`. "} {"_id":"q-en-rust-5e6ae733304d448c9cc31431d251ebfcf3d083b73e23fde25cc59a575da46781","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":"q-en-rust-5e71e48aaaeafa2ae65f251673373de4f7322d6b7c87d83017415f3ef61f27f9","text":"use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use rustc_span::Span; use crate::constraints::graph::{self, NormalConstraintGraph, RegionGraph}; use crate::dataflow::BorrowIndex; use crate::{ constraints::{ graph::NormalConstraintGraph, ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet, }, constraints::{ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet}, diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo}, member_constraints::{MemberConstraintSet, NllMemberConstraintIndex}, nll::PoloniusOutput,"} {"_id":"q-en-rust-5e8cc674e5048a4582f0f7bae15b090ed7539a9fa8de291016abe9170c500d86","text":" struct Binder(i32, i32, i32); fn main() { let x = Binder(1, 2, 3); match x { Binder(_a, _x @ ..) => {} _ => {} } } //~^^^^ ERROR `_x @` is not allowed in a tuple struct "} {"_id":"q-en-rust-5ec8c07e73b2a4e3d398a7d4036023ba9bd8c392e097168d2e477118ff4dcf40","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":"q-en-rust-5ecb6e8b84f8f7b19d6b170155a5561a03a33ce56a777764f741988757f059c4","text":" #![feature(return_position_impl_trait_in_trait)] trait Extend { fn extend<'a: 'a>(_: &'a str) -> (impl Sized + 'a, &'static str); } impl Extend for () { fn extend<'a: 'a>(s: &'a str) -> (Option<&'static &'a ()>, &'static str) //~^ ERROR in type `&'static &'a ()`, reference has a longer lifetime than the data it references where 'a: 'static, { (None, s) } } // This indirection is not necessary for reproduction, // but it makes this test future-proof against #114936. fn extend(s: &str) -> &'static str { ::extend(s).1 } fn main() { let use_after_free = extend::<()>(&String::from(\"temporary\")); println!(\"{}\", use_after_free); } "} {"_id":"q-en-rust-5ef5ac6a2a5939f4aecf823f5bbdc9847e18484f5ff3355b5409a3fbbee419b9","text":" use super::{error_to_const_error, CompileTimeEvalContext, CompileTimeInterpreter}; use crate::interpret::eval_nullary_intrinsic; use crate::interpret::{ intern_const_alloc_recursive, Allocation, ConstValue, GlobalId, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy, MemoryKind, OpTy, RawConst, RefTracking, Scalar, ScalarMaybeUndef, StackPopCleanup, }; use rustc::hir::def::DefKind; use rustc::mir; use rustc::mir::interpret::{ConstEvalErr, ErrorHandled}; use rustc::traits::Reveal; use rustc::ty::{self, layout, layout::LayoutOf, subst::Subst, TyCtxt}; use std::convert::TryInto; use syntax::source_map::Span; pub fn note_on_undefined_behavior_error() -> &'static str { \"The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.\" } // Returns a pointer to where the result lives fn eval_body_using_ecx<'mir, 'tcx>( ecx: &mut CompileTimeEvalContext<'mir, 'tcx>, cid: GlobalId<'tcx>, body: &'mir mir::Body<'tcx>, ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { debug!(\"eval_body_using_ecx: {:?}, {:?}\", cid, ecx.param_env); let tcx = ecx.tcx.tcx; let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?; assert!(!layout.is_unsized()); let ret = ecx.allocate(layout, MemoryKind::Stack); let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id())); let prom = cid.promoted.map_or(String::new(), |p| format!(\"::promoted[{:?}]\", p)); trace!(\"eval_body_using_ecx: pushing stack frame for global: {}{}\", name, prom); // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't // make sense if the body is expecting nontrivial arguments. // (The alternative would be to use `eval_fn_call` with an args slice.) for arg in body.args_iter() { let decl = body.local_decls.get(arg).expect(\"arg missing from local_decls\"); let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?; assert!(layout.is_zst()) } ecx.push_stack_frame( cid.instance, body.span, body, Some(ret.into()), StackPopCleanup::None { cleanup: false }, )?; // The main interpreter loop. ecx.run()?; // Intern the result intern_const_alloc_recursive(ecx, tcx.static_mutability(cid.instance.def_id()), ret)?; debug!(\"eval_body_using_ecx done: {:?}\", *ret); Ok(ret) } /// The `InterpCx` is only meant to be used to do field and index projections into constants for /// `simd_shuffle` and const patterns in match arms. /// /// The function containing the `match` that is currently being analyzed may have generic bounds /// that inform us about the generic bounds of the constant. E.g., using an associated constant /// of a function's generic parameter will require knowledge about the bounds on the generic /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument. pub(super) fn mk_eval_cx<'mir, 'tcx>( tcx: TyCtxt<'tcx>, span: Span, param_env: ty::ParamEnv<'tcx>, can_access_statics: bool, ) -> CompileTimeEvalContext<'mir, 'tcx> { debug!(\"mk_eval_cx: {:?}\", param_env); InterpCx::new( tcx.at(span), param_env, CompileTimeInterpreter::new(), MemoryExtra { can_access_statics }, ) } pub(super) fn op_to_const<'tcx>( ecx: &CompileTimeEvalContext<'_, 'tcx>, op: OpTy<'tcx>, ) -> &'tcx ty::Const<'tcx> { // We do not have value optimizations for everything. // Only scalars and slices, since they are very common. // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result // from scalar unions that are initialized with one of their zero sized variants. We could // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all // the usual cases of extracting e.g. a `usize`, without there being a real use case for the // `Undef` situation. let try_as_immediate = match op.layout.abi { layout::Abi::Scalar(..) => true, layout::Abi::ScalarPair(..) => match op.layout.ty.kind { ty::Ref(_, inner, _) => match inner.kind { ty::Slice(elem) => elem == ecx.tcx.types.u8, ty::Str => true, _ => false, }, _ => false, }, _ => false, }; let immediate = if try_as_immediate { Err(ecx.read_immediate(op).expect(\"normalization works on validated constants\")) } else { // It is guaranteed that any non-slice scalar pair is actually ByRef here. // When we come back from raw const eval, we are always by-ref. The only way our op here is // by-val is if we are in const_field, i.e., if this is (a field of) something that we // \"tried to make immediate\" before. We wouldn't do that for non-slice scalar pairs or // structs containing such. op.try_as_mplace() }; let val = match immediate { Ok(mplace) => { let ptr = mplace.ptr.to_ptr().unwrap(); let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id); ConstValue::ByRef { alloc, offset: ptr.offset } } // see comment on `let try_as_immediate` above Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x { ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s), ScalarMaybeUndef::Undef => { // When coming out of \"normal CTFE\", we'll always have an `Indirect` operand as // argument and we will not need this. The only way we can already have an // `Immediate` is when we are called from `const_field`, and that `Immediate` // comes from a constant so it can happen have `Undef`, because the indirect // memory that was read had undefined bytes. let mplace = op.assert_mem_place(); let ptr = mplace.ptr.to_ptr().unwrap(); let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id); ConstValue::ByRef { alloc, offset: ptr.offset } } }, Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => { let (data, start) = match a.not_undef().unwrap() { Scalar::Ptr(ptr) => { (ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id), ptr.offset.bytes()) } Scalar::Raw { .. } => ( ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(b\"\" as &[u8])), 0, ), }; let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap(); let start = start.try_into().unwrap(); let len: usize = len.try_into().unwrap(); ConstValue::Slice { data, start, end: start + len } } }; ecx.tcx.mk_const(ty::Const { val: ty::ConstKind::Value(val), ty: op.layout.ty }) } fn validate_and_turn_into_const<'tcx>( tcx: TyCtxt<'tcx>, constant: RawConst<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> { let cid = key.value; let def_id = cid.instance.def.def_id(); let is_static = tcx.is_static(def_id); let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static); let val = (|| { let mplace = ecx.raw_const_to_mplace(constant)?; let mut ref_tracking = RefTracking::new(mplace); while let Some((mplace, path)) = ref_tracking.todo.pop() { ecx.validate_operand(mplace.into(), path, Some(&mut ref_tracking))?; } // Now that we validated, turn this into a proper constant. // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides // whether they become immediates. if is_static || cid.promoted.is_some() { let ptr = mplace.ptr.to_ptr()?; Ok(tcx.mk_const(ty::Const { val: ty::ConstKind::Value(ConstValue::ByRef { alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id), offset: ptr.offset, }), ty: mplace.layout.ty, })) } else { Ok(op_to_const(&ecx, mplace.into())) } })(); val.map_err(|error| { let err = error_to_const_error(&ecx, error); match err.struct_error(ecx.tcx, \"it is undefined behavior to use this value\") { Ok(mut diag) => { diag.note(note_on_undefined_behavior_error()); diag.emit(); ErrorHandled::Reported } Err(err) => err, } }) } pub fn const_eval_validated_provider<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> { // see comment in const_eval_raw_provider for what we're doing here if key.param_env.reveal == Reveal::All { let mut key = key.clone(); key.param_env.reveal = Reveal::UserFacing; match tcx.const_eval_validated(key) { // try again with reveal all as requested Err(ErrorHandled::TooGeneric) => { // Promoteds should never be \"too generic\" when getting evaluated. // They either don't get evaluated, or we are in a monomorphic context assert!(key.value.promoted.is_none()); } // dedupliate calls other => return other, } } // We call `const_eval` for zero arg intrinsics, too, in order to cache their value. // Catch such calls and evaluate them instead of trying to load a constant's MIR. if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def { let ty = key.value.instance.ty(tcx); let substs = match ty.kind { ty::FnDef(_, substs) => substs, _ => bug!(\"intrinsic with type {:?}\", ty), }; return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| { let span = tcx.def_span(def_id); let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span }; error.report_as_error(tcx.at(span), \"could not evaluate nullary intrinsic\") }); } tcx.const_eval_raw(key).and_then(|val| validate_and_turn_into_const(tcx, val, key)) } pub fn const_eval_raw_provider<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> { // Because the constant is computed twice (once per value of `Reveal`), we are at risk of // reporting the same error twice here. To resolve this, we check whether we can evaluate the // constant in the more restrictive `Reveal::UserFacing`, which most likely already was // computed. For a large percentage of constants that will already have succeeded. Only // associated constants of generic functions will fail due to not enough monomorphization // information being available. // In case we fail in the `UserFacing` variant, we just do the real computation. if key.param_env.reveal == Reveal::All { let mut key = key.clone(); key.param_env.reveal = Reveal::UserFacing; match tcx.const_eval_raw(key) { // try again with reveal all as requested Err(ErrorHandled::TooGeneric) => {} // dedupliate calls other => return other, } } if cfg!(debug_assertions) { // Make sure we format the instance even if we do not print it. // This serves as a regression test against an ICE on printing. // The next two lines concatenated contain some discussion: // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/ // subject/anon_const_instance_printing/near/135980032 let instance = key.value.instance.to_string(); trace!(\"const eval: {:?} ({})\", key, instance); } let cid = key.value; let def_id = cid.instance.def.def_id(); if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors { return Err(ErrorHandled::Reported); } let is_static = tcx.is_static(def_id); let span = tcx.def_span(cid.instance.def_id()); let mut ecx = InterpCx::new( tcx.at(span), key.param_env, CompileTimeInterpreter::new(), MemoryExtra { can_access_statics: is_static }, ); let res = ecx.load_mir(cid.instance.def, cid.promoted); res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, *body)) .and_then(|place| { Ok(RawConst { alloc_id: place.ptr.assert_ptr().alloc_id, ty: place.layout.ty }) }) .map_err(|error| { let err = error_to_const_error(&ecx, error); // errors in statics are always emitted as fatal errors if is_static { // Ensure that if the above error was either `TooGeneric` or `Reported` // an error must be reported. let v = err.report_as_error(ecx.tcx, \"could not evaluate static initializer\"); tcx.sess.delay_span_bug( err.span, &format!(\"static eval failure did not emit an error: {:#?}\", v), ); v } else if def_id.is_local() { // constant defined in this crate, we can figure out a lint level! match tcx.def_kind(def_id) { // constants never produce a hard error at the definition site. Anything else is // a backwards compatibility hazard (and will break old versions of winapi for sure) // // note that validation may still cause a hard error on this very same constant, // because any code that existed before validation could not have failed validation // thus preventing such a hard error from being a backwards compatibility hazard Some(DefKind::Const) | Some(DefKind::AssocConst) => { let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); err.report_as_lint( tcx.at(tcx.def_span(def_id)), \"any use of this value will cause an error\", hir_id, Some(err.span), ) } // promoting runtime code is only allowed to error if it references broken constants // any other kind of error will be reported to the user as a deny-by-default lint _ => { if let Some(p) = cid.promoted { let span = tcx.promoted_mir(def_id)[p].span; if let err_inval!(ReferencedConstant) = err.error { err.report_as_error( tcx.at(span), \"evaluation of constant expression failed\", ) } else { err.report_as_lint( tcx.at(span), \"reaching this expression at runtime will panic or abort\", tcx.hir().as_local_hir_id(def_id).unwrap(), Some(err.span), ) } // anything else (array lengths, enum initializers, constant patterns) are reported // as hard errors } else { err.report_as_error(ecx.tcx, \"evaluation of constant value failed\") } } } } else { // use of broken constant from other crate err.report_as_error(ecx.tcx, \"could not evaluate constant\") } }) } "} {"_id":"q-en-rust-5efe73deafa2bcd79432f894e2d52dd88224cead01801125f57ad93b82a25603","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 a weird corner case in our dep-graph reduction // code. When we solve `CoerceUnsized`, we find no impls, so we // don't end up with an edge to any HIR nodes, but it still gets // preserved in the dep graph. // revisions:rpass1 rpass2 // compile-flags: -Z query-dep-graph use std::sync::Arc; #[cfg(rpass1)] struct Foo { x: usize } #[cfg(rpass1)] fn main() { let x: Arc = Arc::new(Foo { x: 22 }); let y: Arc = x; } #[cfg(rpass2)] struct FooX { x: usize } #[cfg(rpass2)] fn main() { let x: Arc = Arc::new(FooX { x: 22 }); let y: Arc = x; } "} {"_id":"q-en-rust-5f54ec721e615f41e9daef115b67784451da43c54720427c0022ad941ccf6d6a","text":"} } #[unstable(feature = \"panic_info_message\", issue = \"66745\")] #[stable(feature = \"panic_info_message\", since = \"CURRENT_RUSTC_VERSION\")] impl fmt::Debug for PanicMessage<'_> { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {"} {"_id":"q-en-rust-5f74f6b20a42dd80ffbadce29bbbbeecae86804d9575b557500e96f29bf34a05","text":"endif endif ifdef CFG_DISABLE_RPATH ifeq ($$(OSTYPE_$(3)),apple-darwin) RPATH_VAR$(1)_T_$(2)_H_$(3) := DYLD_LIBRARY_PATH=\"$$$$DYLD_LIBRARY_PATH:$$(HLIB$(1)_H_$(3))\" else RPATH_VAR$(1)_T_$(2)_H_$(3) := LD_LIBRARY_PATH=\"$$$$LD_LIBRARY_PATH:$$(HLIB$(1)_H_$(3))\" endif else RPATH_VAR$(1)_T_$(2)_H_$(3) := endif STAGE$(1)_T_$(2)_H_$(3) := \t\t\t\t\t\t $$(Q)$$(call CFG_RUN_TARG_$(3),$(1),\t\t\t\t $$(Q)$$(RPATH_VAR$(1)_T_$(2)_H_$(3)) $$(call CFG_RUN_TARG_$(3),$(1),\t\t\t\t $$(CFG_VALGRIND_COMPILE$(1)) \t\t\t $$(HBIN$(1)_H_$(3))/rustc$$(X_$(3))\t\t\t --cfg $$(CFGFLAG$(1)_T_$(2)_H_$(3))\t\t\t"} {"_id":"q-en-rust-5f7d0cab676f93824d921ba00e72bdafefb3d059c4df7aabe7728d43292d7f2b","text":"[[package]] name = \"unicase\" version = \"2.6.0\" version = \"2.7.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6\" checksum = \"f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89\" dependencies = [ \"version_check\", ]"} {"_id":"q-en-rust-6002b04b26427b0b689baec46243c8bde49d32ce6504d4f2255ce45cb66a85ed","text":" error[E0432]: unresolved import `self::a::E` --> $DIR/unresolved-seg-after-ambiguous.rs:19:14 | LL | use self::a::E::in_exist; | ^ `E` is a struct, not a module warning: `E` is ambiguous --> $DIR/unresolved-seg-after-ambiguous.rs:19:14 | LL | use self::a::E::in_exist; | ^ ambiguous name | = 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 #114095 = note: ambiguous because of multiple glob imports of a name in the same module note: `E` could refer to the struct imported here --> $DIR/unresolved-seg-after-ambiguous.rs:13:17 | LL | pub use self::c::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `E` to disambiguate note: `E` could also refer to the struct imported here --> $DIR/unresolved-seg-after-ambiguous.rs:12:17 | LL | pub use self::d::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `E` to disambiguate = note: `#[warn(ambiguous_glob_imports)]` on by default error: aborting due to 1 previous error; 1 warning emitted For more information about this error, try `rustc --explain E0432`. "} {"_id":"q-en-rust-6009af558fab00f8d19b9c8335030024be7997a15c4a217cdc400ebaf1b89fd1","text":"self.raw_bytes().starts_with(METADATA_HEADER) } pub fn get_rustc_version(&self) -> String { Lazy::with_position(METADATA_HEADER.len() + 4).decode(self) } pub fn get_root(&self) -> CrateRoot { let slice = self.raw_bytes(); let offset = METADATA_HEADER.len();"} {"_id":"q-en-rust-6027cef56941fcf4f19e51345850d81b1b3aae380d4fdfbe89430e27ae2af350","text":"check_operand(tcx, discr, span, def_id, body) } // FIXME(ecstaticmorse): We probably want to allow `Unreachable` unconditionally. TerminatorKind::Unreachable if tcx.features().const_if_match => Ok(()), | TerminatorKind::Abort | TerminatorKind::Unreachable => { Err((span, \"const fn with unreachable code is not stable\".into())) }"} {"_id":"q-en-rust-6052510ef438aede4895989792058c89356ccbedcb13e1c039bac01b80ffcc77","text":" // ignore-tidy-linelength // We do not promote mutable references. static mut TEST1: Option<&mut [i32]> = Some(&mut [1, 2, 3]); //~ ERROR temporary value dropped while borrowed static mut TEST2: &'static mut [i32] = { let x = &mut [1,2,3]; //~ ERROR temporary value dropped while borrowed x }; fn main() {} "} {"_id":"q-en-rust-60927f352a2e2587ed0c9b5e1dafe616811f6d1156a44ae84545b41a3c0b42c5","text":" error[E0423]: expected function, found struct `B` --> $DIR/issue-42944.rs:9:9 | LL | B(()); //~ ERROR expected function, found struct `B` [E0423] | ^ constructor is not visible here due to private fields error[E0425]: cannot find function `B` in this scope --> $DIR/issue-42944.rs:15:9 | LL | B(()); //~ ERROR cannot find function `B` in this scope [E0425] | ^ not found in this scope help: possible candidate is found in another module, you can import it into scope | LL | use foo::B; | error: aborting due to 2 previous errors Some errors occurred: E0423, E0425. For more information about an error, try `rustc --explain E0423`. "} {"_id":"q-en-rust-60a93986dc2148222b698b25c52a2ba21f61ee3bbc692b02fe4a08dc446997cd","text":"= note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers) error: aborting due to 7 previous errors error: reference to packed field is unaligned --> $DIR/unaligned_references.rs:90:20 | LL | let _ref = &m1.1.a; | ^^^^^^^ | = 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 #82523 = note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers) error: reference to packed field is unaligned --> $DIR/unaligned_references.rs:100:20 | LL | let _ref = &m2.1.a; | ^^^^^^^ | = 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 #82523 = note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers) error: aborting due to 9 previous errors Future incompatibility report: Future breakage diagnostic: error: reference to packed field is unaligned"} {"_id":"q-en-rust-61043b9b735737fc9f42b8ea47ecec735d2abb30f40b48f8a480571f27823b7e","text":"| = note: see issue #65991 for more information = help: add `#![feature(trait_upcasting)]` to the crate attributes to enable = note: required when coercing `Box<(dyn Fn() + 'static)>` into `Box<(dyn FnMut() + 'static)>` error: aborting due to previous error"} {"_id":"q-en-rust-61123fdc6db372f9a66c7817d8b8c3028f281cf43a3af7183a1c65ed191abaed","text":"} ast::ExprStruct(_, ref fields, _) => { match ty::expr_ty(self.tcx, expr).sty { ty::ty_struct(id, _) => { for field in &(*fields) { self.check_field(expr.span, id, NamedField(field.ident.node)); ty::ty_struct(ctor_id, _) => { // RFC 736: ensure all unmentioned fields are visible. // Rather than computing the set of unmentioned fields // (i.e. `all_fields - fields`), just check them all. let all_fields = ty::lookup_struct_fields(self.tcx, ctor_id); for field in all_fields { self.check_field(expr.span, ctor_id, NamedField(field.name)); } } ty::ty_enum(_, _) => {"} {"_id":"q-en-rust-611978a39e191c94d07dfddc613335efc8562f7b784b7cd01d4cf2fca4ebc042","text":" error[E0491]: in type `&'static &()`, reference has a longer lifetime than the data it references --> $DIR/rpitit-hidden-types-self-implied-wf.rs:8:27 | LL | fn extend(s: &str) -> (Option<&'static &'_ ()>, &'static str) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the pointer is valid for the static lifetime note: but the referenced data is only valid for the anonymous lifetime defined here --> $DIR/rpitit-hidden-types-self-implied-wf.rs:8:18 | LL | fn extend(s: &str) -> (Option<&'static &'_ ()>, &'static str) { | ^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0491`. "} {"_id":"q-en-rust-61314521de84f66f2625eb43c63e03155ce36b8f1624c705067cb518ff9709e6","text":" // ignore-tidy-linelength // Verify that span interning correctly handles having a span of exactly MAX_LEN length. // compile-flags: --crate-type=lib // check-pass #![allow(dead_code)] fn a<'a, T>() -> &'a T { todo!()//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } "} {"_id":"q-en-rust-61397016d359181c97e04b7e3999ae57227440d8db76e093fa1ebb0c5e811f8a","text":"version = \"0.18.2\" dependencies = [ \"derive-new\", \"env_logger 0.7.1\", \"env_logger 0.9.0\", \"fst\", \"itertools 0.9.0\", \"itertools 0.10.1\", \"json\", \"lazy_static\", \"log\","} {"_id":"q-en-rust-614137e41658b494328f1cf865e0e04d656785179b3030275fdb4ede360507dc","text":"} impl Foo for U { // OK, T, U are used everywhere. Note that the coherence check // hasn't executed yet, so no errors about overlap. //~^ ERROR conflicting implementations of trait `Foo<_>` for type `[isize; 0]` } impl Bar for T {"} {"_id":"q-en-rust-61437691895cc7e0f5c09967f6826605cd15d388980f8737de9719992c3aea0d","text":"needlesArr.iter().fold(|x, y| { }); //~^^ ERROR this function takes 2 parameters but 1 parameter was supplied //~^^^ NOTE the following parameter types were expected // //~| NOTE the following parameter types were expected //~| NOTE expected 2 parameters // the first error is, um, non-ideal. }"} {"_id":"q-en-rust-61476c907914973156625c7ea3d9adbb6ebc2b72eb825ef5b233a9185be448c7","text":"// of a macro that is not vendored by Rust and included in the toolchain. // See https://github.com/rust-analyzer/rust-analyzer/issues/6038. // On certain platforms right now the \"main modules\" modules that are // documented don't compile (missing things in `libc` which is empty), // so just omit them with an empty module and add the \"unstable\" attribute. // Unix, linux, wasi and windows are handled a bit differently. #[cfg(all( doc, not(any( any( all(target_arch = \"wasm32\", not(target_os = \"wasi\")), all(target_vendor = \"fortanix\", target_env = \"sgx\") )) ) ))] #[path = \".\"] mod doc { // When documenting std we want to show the `unix`, `windows`, `linux` and `wasi` // modules as these are the \"main modules\" that are used across platforms, // so these modules are enabled when `cfg(doc)` is set. // This should help show platform-specific functionality in a hopefully cross-platform // way in the documentation. pub mod unix; pub mod linux; pub mod wasi; pub mod windows; } #[unstable(issue = \"none\", feature = \"std_internals\")] pub mod unix {} #[cfg(all( doc, any("} {"_id":"q-en-rust-6167a2d58ee7c53ffad20e6ab97c8765897f8441e123dd014c74dcb3499c3285","text":"None); // If the item has the name of a field, give a help note if let (&ty::TyStruct(did, _), Some(_)) = (&rcvr_ty.sty, rcvr_expr) { if let (&ty::TyStruct(did, substs), Some(expr)) = (&rcvr_ty.sty, rcvr_expr) { let fields = ty::lookup_struct_fields(cx, did); if fields.iter().any(|f| f.name == item_name) { cx.sess.span_note(span, &format!(\"use `(s.{0})(...)` if you meant to call the function stored in the `{0}` field\", item_name)); if let Some(field) = fields.iter().find(|f| f.name == item_name) { let expr_string = match cx.sess.codemap().span_to_snippet(expr.span) { Ok(expr_string) => expr_string, _ => \"s\".into() // Default to a generic placeholder for the // expression when we can't generate a string // snippet }; let span_stored_function = || { cx.sess.span_note(span, &format!(\"use `({0}.{1})(...)` if you meant to call the function stored in the `{1}` field\", expr_string, item_name)); }; let span_did_you_mean = || { cx.sess.span_note(span, &format!(\"did you mean to write `{0}.{1}`?\", expr_string, item_name)); }; // Determine if the field can be used as a function in some way let field_ty = ty::lookup_field_type(cx, did, field.id, substs); if let Ok(fn_once_trait_did) = cx.lang_items.require(FnOnceTraitLangItem) { let infcx = fcx.infcx(); infcx.probe(|_| { let fn_once_substs = Substs::new_trait(vec![infcx.next_ty_var()], Vec::new(), field_ty); let trait_ref = ty::TraitRef::new(fn_once_trait_did, cx.mk_substs(fn_once_substs)); let poly_trait_ref = trait_ref.to_poly_trait_ref(); let obligation = Obligation::misc(span, fcx.body_id, poly_trait_ref.as_predicate()); let mut selcx = SelectionContext::new(infcx, fcx); if selcx.evaluate_obligation(&obligation) { span_stored_function(); } else { span_did_you_mean(); } }); } else { match field_ty.sty { // fallback to matching a closure or function pointer ty::TyClosure(..) | ty::TyBareFn(..) => span_stored_function(), _ => span_did_you_mean(), } } } }"} {"_id":"q-en-rust-617182d78c02595d4a9628a45e0bef0873789a7a1ad2c3d6bd6b357f795b5bc2","text":"debug!(\"overloaded_deref_ty({:?})\", ty); let tcx = self.infcx.tcx; if ty.references_error() { return None; } // let trait_ref = ty::TraitRef::new(tcx, tcx.lang_items().deref_trait()?, [ty]); let cause = traits::ObligationCause::misc(self.span, self.body_id);"} {"_id":"q-en-rust-61877c0d59d8b8f27ac44a30d609b029849f1d99fb0f00654f6af0d9ee9b2e83","text":"/// impl Gadget { /// /// Construct a reference counted Gadget. /// fn new() -> Arc { /// Arc::new_cyclic(|me| Gadget { me: me.clone() }) /// // `me` is a `Weak` pointing at the new allocation of the /// // `Arc` we're constructing. /// Arc::new_cyclic(|me| { /// // Create the actual struct here. /// Gadget { me: me.clone() } /// }) /// } /// /// /// Return a reference counted pointer to Self."} {"_id":"q-en-rust-61b75c04e08bb651c35abcf86c09d38cc503729fb9c030159498d3a0c545d5df","text":" // check-pass pub struct Bar<'a>(&'a Self) where Self: ; fn main() {} "} {"_id":"q-en-rust-61bfca5a65833bd47f7f9817ba2fc31779db625c9e423a7e3ff1c3f48117c907","text":"fn f() -> bool { let c = false; if(c) { if(c) { //~ ERROR unnecessary parentheses println!(\"next\"); } if (c){ if (c){ //~ ERROR unnecessary parentheses println!(\"prev\"); } while (false && true){ if (c) { if (c) { //~ ERROR unnecessary parentheses println!(\"norm\"); } } while(true && false) { for _ in (0 .. 3){ while(true && false) { //~ ERROR unnecessary parentheses for _ in (0 .. 3){ //~ ERROR unnecessary parentheses println!(\"e~\") } } for _ in (0 .. 3) { while (true && false) { for _ in (0 .. 3) { //~ ERROR unnecessary parentheses while (true && false) { //~ ERROR unnecessary parentheses println!(\"e~\") } }"} {"_id":"q-en-rust-61f8ae8adb93346bc59d10278d8e74ee054fb8e7d4d100b5b3b6635985dfbe97","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-cloudabi no processes // ignore-emscripten no processes use std::io::ErrorKind; use std::process::Command; fn main() { assert_eq!(Command::new(\"nonexistent\") .spawn() .unwrap_err() .kind(), ErrorKind::NotFound); } "} {"_id":"q-en-rust-6202d6e9c7ed5849057eebe71c3c9fb04e337cf22a933e55f9aa439ce5a11cf6","text":"} match kind { AstFragmentKind::Pat if macro_ident.name == sym::vec => { let mut suggestion = None; if let Ok(code) = parser.sess.source_map().span_to_snippet(site_span) { if let Some(bang) = code.find('!') { suggestion = Some(code[bang + 1..].to_string()); } } if let Some(suggestion) = suggestion { e.span_suggestion( site_span, \"use a slice pattern here instead\", suggestion, Applicability::MachineApplicable, ); } else { e.span_label( site_span, \"use a slice pattern here instead\", ); } e.help(\"for more information, see https://doc.rust-lang.org/edition-guide/ rust-2018/slice-patterns.html\"); suggest_slice_pat(&mut e, site_span, parser); } _ => annotate_err_with_kind(&mut e, kind, site_span), };"} {"_id":"q-en-rust-62271503b1fb157e1ff9adb59b938d28a1a1742c5b2fa900e46dc3bb493d147e","text":"debug!(\"region_bound: {:?}\", region_bound); ty::sort_bounds_list(&mut projection_bounds); ty::ExistentialBounds { region_bound: region_bound, builtin_bounds: builtin_bounds, projection_bounds: projection_bounds, } ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds) } /// Given the bounds on an object, determines what single region bound"} {"_id":"q-en-rust-622f524481c8ba4e5408fa931eaf95662b69049149fd2f84e6426aebd19c0a29","text":"x => tcx.ty_error_with_message( DUMMY_SP, &format!(\"unexpected const parent in type_of_def_id(): {:?}\", x), &format!(\"unexpected const parent in type_of(): {:?}\", x), ), } }"} {"_id":"q-en-rust-62e633d0e453c2bcd053d73fd496562e2c4fb6d342201c7ef28c9f3ffd293114","text":" // aux-build:issue-69725.rs extern crate issue_69725; use issue_69725::Struct; fn crash() { let _ = Struct::::new().clone(); //~^ ERROR: no method named `clone` found } fn main() {} "} {"_id":"q-en-rust-62f9b04cbc42e1f2b7ae308ef90f99708310e5ae29b08d697d2fb79f5fdbf7b4","text":"use core::mem::*; #[cfg(panic = \"unwind\")] use std::rc::Rc; #[test]"} {"_id":"q-en-rust-63292a20dddbe4d7ae14367a6aa7352d161fdde582aa7043c21a61212f38bd11","text":"}).collect::, _>>() }).collect::, _>>()?; let (inh_first, inh_second) = { let mut inh_variants = (0..variants.len()).filter(|&v| { variants[v].iter().all(|f| f.abi != Abi::Uninhabited) }); (inh_variants.next(), inh_variants.next()) }; if inh_first.is_none() { // Uninhabited because it has no variants, or only uninhabited ones. return Ok(tcx.intern_layout(LayoutDetails::uninhabited(0))); } if def.is_union() { let packed = def.repr.packed(); if packed && def.repr.align > 0 {"} {"_id":"q-en-rust-632e93628f3cb5a2467645fc39fd8cd40d8e9c02a739b6d7cbdfce1fbec0ddca","text":" error: expected at least one digit in exponent --> $DIR/issue-104390.rs:1:27 | LL | fn f1() -> impl Sized { & 2E } | ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:2:28 | LL | fn f2() -> impl Sized { && 2E } | ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:3:29 | LL | fn f3() -> impl Sized { &'a 2E } | ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:5:34 | LL | fn f4() -> impl Sized { &'static 2E } | ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:7:28 | LL | fn f5() -> impl Sized { *& 2E } | ^^ error: expected at least one digit in exponent --> $DIR/issue-104390.rs:8:29 | LL | fn f6() -> impl Sized { &'_ 2E } | ^^ error: borrow expressions cannot be annotated with lifetimes --> $DIR/issue-104390.rs:3:25 | LL | fn f3() -> impl Sized { &'a 2E } | ^--^^^ | | | annotated with lifetime here | help: remove the lifetime annotation error: borrow expressions cannot be annotated with lifetimes --> $DIR/issue-104390.rs:5:25 | LL | fn f4() -> impl Sized { &'static 2E } | ^-------^^^ | | | annotated with lifetime here | help: remove the lifetime annotation error: borrow expressions cannot be annotated with lifetimes --> $DIR/issue-104390.rs:8:25 | LL | fn f6() -> impl Sized { &'_ 2E } | ^--^^^ | | | annotated with lifetime here | help: remove the lifetime annotation error: aborting due to 9 previous errors "} {"_id":"q-en-rust-6378e4243879e5441538c532ac808304722e5ce5710e3f279813a36e589c892d","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":"q-en-rust-637b24e00c829742c52e26fd0c37613fc930931b301f8f7fff6aba47a5bfabc1","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":"q-en-rust-639113cdc8e1f67588703006ad055c88bc62bd6562aa57456cbca285c200ee62","text":"} fn visit_ty(&mut self, ty: Ty<'tcx>) -> std::ops::ControlFlow { if let ty::Alias(ty::Projection, alias_ty) = *ty.kind() && self.tcx.is_impl_trait_in_trait(alias_ty.def_id) && self.tcx.impl_trait_in_trait_parent_fn(alias_ty.def_id) == self.fn_def_id && self.seen.insert(alias_ty.def_id) if let ty::Alias(ty::Projection, unshifted_alias_ty) = *ty.kind() && self.tcx.is_impl_trait_in_trait(unshifted_alias_ty.def_id) && self.tcx.impl_trait_in_trait_parent_fn(unshifted_alias_ty.def_id) == self.fn_def_id && self.seen.insert(unshifted_alias_ty.def_id) { // We have entered some binders as we've walked into the // bounds of the RPITIT. Shift these binders back out when // constructing the top-level projection predicate. let alias_ty = self.tcx.fold_regions(alias_ty, |re, _| { let shifted_alias_ty = self.tcx.fold_regions(unshifted_alias_ty, |re, depth| { if let ty::ReLateBound(index, bv) = re.kind() { if depth != ty::INNERMOST { return self.tcx.mk_re_error_with_message( DUMMY_SP, \"we shouldn't walk non-predicate binders with `impl Trait`...\", ); } self.tcx.mk_re_late_bound(index.shifted_out_to_binder(self.depth), bv) } else { re"} {"_id":"q-en-rust-639da726326d75a3ce136dd3fa96d5b89c5680cadfd8a115b18361a5c1a04f23","text":"a: ty::Region<'tcx>, bound: VerifyBound<'tcx>, ) { if let ty::ReEmpty = a { return; } let type_test = self.verify_to_type_test(kind, a, bound); self.add_type_test(type_test); }"} {"_id":"q-en-rust-63c1f41ae01dbe933b1b4abde9d0551e12e6ff731b5f6247e903c2841e515bd1","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:issue-11908-2.rs // no-prefer-dynamic // ignore-android this test is incompatible with the android test runner // error-pattern: multiple rlib candidates for `collections` found // see comments in issue-11908-1 for what's going on here extern crate collections; fn main() {} "} {"_id":"q-en-rust-63e6924d34287b6235583c0814359b38f48c7bc0eb7485da8456cedf9a619217","text":"| help: change the delimiters to curly braces | LL | macro_rules! abc{ؼ} | ^ ^ LL | macro_rules! abc { /* items */ } | ^^^^^^^^^^^^^^^ help: add a semicolon | LL | macro_rules! abc(ؼ;"} {"_id":"q-en-rust-63ef60010bd109220be3472f077545f10a41c2782cb3a4ab722b85003dfc5705","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":"q-en-rust-64ccc67aaa0894ded25afe823441f253f34c49c8e214ed272bc35d3aa241638f","text":"# Gotta do some hackery to tell python about our custom OpenSSL build, but other # than that fairly normal. CFLAGS='-I /rustroot/include' LDFLAGS='-L /rustroot/lib -L /rustroot/lib64' hide_output ../Python-3.9.1/configure --prefix=/rustroot hide_output ../Python-2.7.12/configure --prefix=/rustroot hide_output make -j10 hide_output make install cd .. rm -rf python-build rm -rf Python-3.9.1 rm -rf Python-2.7.12 "} {"_id":"q-en-rust-6527bc0c8fd566846861729e941e5dcdb30204b99c626bc2357437429f46c284","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":"q-en-rust-6539dc96d42474a5cd6360a22d1ccf8b44bd50aa57f8651f9018439975b7ea20","text":"// Not in interpret to make sure we do not use private implementation details use std::borrow::{Borrow, Cow}; use std::collections::hash_map::Entry; use std::convert::TryInto; use std::error::Error; use std::fmt; use std::hash::Hash; use crate::interpret::eval_nullary_intrinsic; use rustc::hir::def::DefKind; use rustc::hir::def_id::DefId; use rustc::mir; use rustc::mir::interpret::{ConstEvalErr, ErrorHandled, ScalarMaybeUndef}; use rustc::traits::Reveal; use rustc::ty::layout::{self, HasTyCtxt, LayoutOf, VariantIdx}; use rustc::ty::{self, subst::Subst, Ty, TyCtxt}; use rustc_data_structures::fx::FxHashMap; use syntax::{ source_map::{Span, DUMMY_SP}, symbol::Symbol, }; use crate::interpret::{ self, intern_const_alloc_recursive, snapshot, AllocId, Allocation, AssertMessage, ConstValue, GlobalId, ImmTy, Immediate, InterpCx, InterpErrorInfo, InterpResult, MPlaceTy, Machine, Memory, MemoryKind, OpTy, PlaceTy, Pointer, RawConst, RefTracking, Scalar, StackPopCleanup, }; /// Number of steps until the detector even starts doing anything. /// Also, a warning is shown to the user when this number is reached. const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000; /// The number of steps between loop detector snapshots. /// Should be a power of two for performance reasons. const DETECTOR_SNAPSHOT_PERIOD: isize = 256; /// The `InterpCx` is only meant to be used to do field and index projections into constants for /// `simd_shuffle` and const patterns in match arms. /// /// The function containing the `match` that is currently being analyzed may have generic bounds /// that inform us about the generic bounds of the constant. E.g., using an associated constant /// of a function's generic parameter will require knowledge about the bounds on the generic /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument. fn mk_eval_cx<'mir, 'tcx>( tcx: TyCtxt<'tcx>, span: Span, param_env: ty::ParamEnv<'tcx>, can_access_statics: bool, ) -> CompileTimeEvalContext<'mir, 'tcx> { debug!(\"mk_eval_cx: {:?}\", param_env); InterpCx::new( tcx.at(span), param_env, CompileTimeInterpreter::new(), MemoryExtra { can_access_statics }, ) } fn op_to_const<'tcx>( ecx: &CompileTimeEvalContext<'_, 'tcx>, op: OpTy<'tcx>, ) -> &'tcx ty::Const<'tcx> { // We do not have value optimizations for everything. // Only scalars and slices, since they are very common. // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result // from scalar unions that are initialized with one of their zero sized variants. We could // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all // the usual cases of extracting e.g. a `usize`, without there being a real use case for the // `Undef` situation. let try_as_immediate = match op.layout.abi { layout::Abi::Scalar(..) => true, layout::Abi::ScalarPair(..) => match op.layout.ty.kind { ty::Ref(_, inner, _) => match inner.kind { ty::Slice(elem) => elem == ecx.tcx.types.u8, ty::Str => true, _ => false, }, _ => false, }, _ => false, }; let immediate = if try_as_immediate { Err(ecx.read_immediate(op).expect(\"normalization works on validated constants\")) } else { // It is guaranteed that any non-slice scalar pair is actually ByRef here. // When we come back from raw const eval, we are always by-ref. The only way our op here is // by-val is if we are in const_field, i.e., if this is (a field of) something that we // \"tried to make immediate\" before. We wouldn't do that for non-slice scalar pairs or // structs containing such. op.try_as_mplace() }; let val = match immediate { Ok(mplace) => { let ptr = mplace.ptr.to_ptr().unwrap(); let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id); ConstValue::ByRef { alloc, offset: ptr.offset } } // see comment on `let try_as_immediate` above Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x { ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s), ScalarMaybeUndef::Undef => { // When coming out of \"normal CTFE\", we'll always have an `Indirect` operand as // argument and we will not need this. The only way we can already have an // `Immediate` is when we are called from `const_field`, and that `Immediate` // comes from a constant so it can happen have `Undef`, because the indirect // memory that was read had undefined bytes. let mplace = op.assert_mem_place(); let ptr = mplace.ptr.to_ptr().unwrap(); let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id); ConstValue::ByRef { alloc, offset: ptr.offset } } }, Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => { let (data, start) = match a.not_undef().unwrap() { Scalar::Ptr(ptr) => { (ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id), ptr.offset.bytes()) } Scalar::Raw { .. } => ( ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(b\"\" as &[u8])), 0, ), }; let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap(); let start = start.try_into().unwrap(); let len: usize = len.try_into().unwrap(); ConstValue::Slice { data, start, end: start + len } } }; ecx.tcx.mk_const(ty::Const { val: ty::ConstKind::Value(val), ty: op.layout.ty }) } // Returns a pointer to where the result lives fn eval_body_using_ecx<'mir, 'tcx>( ecx: &mut CompileTimeEvalContext<'mir, 'tcx>, cid: GlobalId<'tcx>, body: &'mir mir::Body<'tcx>, ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { debug!(\"eval_body_using_ecx: {:?}, {:?}\", cid, ecx.param_env); let tcx = ecx.tcx.tcx; let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?; assert!(!layout.is_unsized()); let ret = ecx.allocate(layout, MemoryKind::Stack); let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id())); let prom = cid.promoted.map_or(String::new(), |p| format!(\"::promoted[{:?}]\", p)); trace!(\"eval_body_using_ecx: pushing stack frame for global: {}{}\", name, prom); // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't // make sense if the body is expecting nontrivial arguments. // (The alternative would be to use `eval_fn_call` with an args slice.) for arg in body.args_iter() { let decl = body.local_decls.get(arg).expect(\"arg missing from local_decls\"); let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?; assert!(layout.is_zst()) } ecx.push_stack_frame( cid.instance, body.span, body, Some(ret.into()), StackPopCleanup::None { cleanup: false }, )?; // The main interpreter loop. ecx.run()?; // Intern the result intern_const_alloc_recursive(ecx, tcx.static_mutability(cid.instance.def_id()), ret)?; debug!(\"eval_body_using_ecx done: {:?}\", *ret); Ok(ret) } #[derive(Clone, Debug)] pub enum ConstEvalError { NeedsRfc(String), ConstAccessesStatic, } impl<'tcx> Into> for ConstEvalError { fn into(self) -> InterpErrorInfo<'tcx> { err_unsup!(Unsupported(self.to_string())).into() } } impl fmt::Display for ConstEvalError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::ConstEvalError::*; match *self { NeedsRfc(ref msg) => { write!(f, \"\"{}\" needs an rfc before being allowed inside constants\", msg) } ConstAccessesStatic => write!(f, \"constant accesses static\"), } } } impl Error for ConstEvalError {} // Extra machine state for CTFE, and the Machine instance pub struct CompileTimeInterpreter<'mir, 'tcx> { /// When this value is negative, it indicates the number of interpreter /// steps *until* the loop detector is enabled. When it is positive, it is /// the number of steps after the detector has been enabled modulo the loop /// detector period. pub(super) steps_since_detector_enabled: isize, /// Extra state to detect loops. pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>, } #[derive(Copy, Clone, Debug)] pub struct MemoryExtra { /// Whether this machine may read from statics can_access_statics: bool, } impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> { fn new() -> Self { CompileTimeInterpreter { loop_detector: Default::default(), steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED, } } } impl interpret::AllocMap for FxHashMap { #[inline(always)] fn contains_key(&mut self, k: &Q) -> bool where K: Borrow, { FxHashMap::contains_key(self, k) } #[inline(always)] fn insert(&mut self, k: K, v: V) -> Option { FxHashMap::insert(self, k, v) } #[inline(always)] fn remove(&mut self, k: &Q) -> Option where K: Borrow, { FxHashMap::remove(self, k) } #[inline(always)] fn filter_map_collect(&self, mut f: impl FnMut(&K, &V) -> Option) -> Vec { self.iter().filter_map(move |(k, v)| f(k, &*v)).collect() } #[inline(always)] fn get_or(&self, k: K, vacant: impl FnOnce() -> Result) -> Result<&V, E> { match self.get(&k) { Some(v) => Ok(v), None => { vacant()?; bug!(\"The CTFE machine shouldn't ever need to extend the alloc_map when reading\") } } } #[inline(always)] fn get_mut_or(&mut self, k: K, vacant: impl FnOnce() -> Result) -> Result<&mut V, E> { match self.entry(k) { Entry::Occupied(e) => Ok(e.into_mut()), Entry::Vacant(e) => { let v = vacant()?; Ok(e.insert(v)) } } } } crate type CompileTimeEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>; use rustc::ty::layout::VariantIdx; use rustc::ty::{self, TyCtxt}; impl interpret::MayLeak for ! { #[inline(always)] fn may_leak(self) -> bool { // `self` is uninhabited self } } impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> { type MemoryKinds = !; type PointerTag = (); type ExtraFnVal = !; type FrameExtra = (); type MemoryExtra = MemoryExtra; type AllocExtra = (); type MemoryMap = FxHashMap, Allocation)>; const STATIC_KIND: Option = None; // no copying of statics allowed // We do not check for alignment to avoid having to carry an `Align` // in `ConstValue::ByRef`. const CHECK_ALIGN: bool = false; #[inline(always)] fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool { false // for now, we don't enforce validity } fn find_mir_or_eval_fn( ecx: &mut InterpCx<'mir, 'tcx, Self>, instance: ty::Instance<'tcx>, args: &[OpTy<'tcx>], ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, _unwind: Option, // unwinding is not supported in consts ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> { debug!(\"find_mir_or_eval_fn: {:?}\", instance); // Only check non-glue functions if let ty::InstanceDef::Item(def_id) = instance.def { // Execution might have wandered off into other crates, so we cannot do a stability- // sensitive check here. But we can at least rule out functions that are not const // at all. if ecx.tcx.is_const_fn_raw(def_id) { // If this function is a `const fn` then as an optimization we can query this // evaluation immediately. // // For the moment we only do this for functions which take no arguments // (or all arguments are ZSTs) so that we don't memoize too much. // // Because `#[track_caller]` adds an implicit non-ZST argument, we also cannot // perform this optimization on items tagged with it. let no_implicit_args = !instance.def.requires_caller_location(ecx.tcx()); if args.iter().all(|a| a.layout.is_zst()) && no_implicit_args { let gid = GlobalId { instance, promoted: None }; ecx.eval_const_fn_call(gid, ret)?; return Ok(None); } } else { // Some functions we support even if they are non-const -- but avoid testing // that for const fn! We certainly do *not* want to actually call the fn // though, so be sure we return here. return if ecx.hook_panic_fn(instance, args, ret)? { Ok(None) } else { throw_unsup_format!(\"calling non-const function `{}`\", instance) }; } } // This is a const fn. Call it. Ok(Some(match ecx.load_mir(instance.def, None) { Ok(body) => *body, Err(err) => { if let err_unsup!(NoMirFor(ref path)) = err.kind { return Err(ConstEvalError::NeedsRfc(format!( \"calling extern function `{}`\", path )) .into()); } return Err(err); } })) } fn call_extra_fn( _ecx: &mut InterpCx<'mir, 'tcx, Self>, fn_val: !, _args: &[OpTy<'tcx>], _ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, _unwind: Option, ) -> InterpResult<'tcx> { match fn_val {} } fn call_intrinsic( ecx: &mut InterpCx<'mir, 'tcx, Self>, span: Span, instance: ty::Instance<'tcx>, args: &[OpTy<'tcx>], ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>, _unwind: Option, ) -> InterpResult<'tcx> { if ecx.emulate_intrinsic(span, instance, args, ret)? { return Ok(()); } // An intrinsic that we do not support let intrinsic_name = ecx.tcx.item_name(instance.def_id()); Err(ConstEvalError::NeedsRfc(format!(\"calling intrinsic `{}`\", intrinsic_name)).into()) } use syntax::{source_map::DUMMY_SP, symbol::Symbol}; fn assert_panic( ecx: &mut InterpCx<'mir, 'tcx, Self>, _span: Span, msg: &AssertMessage<'tcx>, _unwind: Option, ) -> InterpResult<'tcx> { use rustc::mir::interpret::PanicInfo::*; Err(match msg { BoundsCheck { ref len, ref index } => { let len = ecx .read_immediate(ecx.eval_operand(len, None)?) .expect(\"can't eval len\") .to_scalar()? .to_machine_usize(&*ecx)?; let index = ecx .read_immediate(ecx.eval_operand(index, None)?) .expect(\"can't eval index\") .to_scalar()? .to_machine_usize(&*ecx)?; err_panic!(BoundsCheck { len, index }) } Overflow(op) => err_panic!(Overflow(*op)), OverflowNeg => err_panic!(OverflowNeg), DivisionByZero => err_panic!(DivisionByZero), RemainderByZero => err_panic!(RemainderByZero), ResumedAfterReturn(generator_kind) => err_panic!(ResumedAfterReturn(*generator_kind)), ResumedAfterPanic(generator_kind) => err_panic!(ResumedAfterPanic(*generator_kind)), Panic { .. } => bug!(\"`Panic` variant cannot occur in MIR\"), } .into()) } use crate::interpret::{intern_const_alloc_recursive, ConstValue, InterpCx}; fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> { Err(ConstEvalError::NeedsRfc(\"pointer-to-integer cast\".to_string()).into()) } mod error; mod eval_queries; fn binary_ptr_op( _ecx: &InterpCx<'mir, 'tcx, Self>, _bin_op: mir::BinOp, _left: ImmTy<'tcx>, _right: ImmTy<'tcx>, ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> { Err(ConstEvalError::NeedsRfc(\"pointer arithmetic or comparison\".to_string()).into()) } fn find_foreign_static( _tcx: TyCtxt<'tcx>, _def_id: DefId, ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> { throw_unsup!(ReadForeignStatic) } #[inline(always)] fn init_allocation_extra<'b>( _memory_extra: &MemoryExtra, _id: AllocId, alloc: Cow<'b, Allocation>, _kind: Option>, ) -> (Cow<'b, Allocation>, Self::PointerTag) { // We do not use a tag so we can just cheaply forward the allocation (alloc, ()) } #[inline(always)] fn tag_static_base_pointer(_memory_extra: &MemoryExtra, _id: AllocId) -> Self::PointerTag { () } fn box_alloc( _ecx: &mut InterpCx<'mir, 'tcx, Self>, _dest: PlaceTy<'tcx>, ) -> InterpResult<'tcx> { Err(ConstEvalError::NeedsRfc(\"heap allocations via `box` keyword\".to_string()).into()) } fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { { let steps = &mut ecx.machine.steps_since_detector_enabled; *steps += 1; if *steps < 0 { return Ok(()); } *steps %= DETECTOR_SNAPSHOT_PERIOD; if *steps != 0 { return Ok(()); } } let span = ecx.frame().span; ecx.machine.loop_detector.observe_and_analyze(*ecx.tcx, span, &ecx.memory, &ecx.stack[..]) } #[inline(always)] fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> { Ok(()) } fn before_access_static( memory_extra: &MemoryExtra, _allocation: &Allocation, ) -> InterpResult<'tcx> { if memory_extra.can_access_statics { Ok(()) } else { Err(ConstEvalError::ConstAccessesStatic.into()) } } } pub use error::*; pub use eval_queries::*; /// Extracts a field of a (variant of a) const. // this function uses `unwrap` copiously, because an already validated constant must have valid // fields and can thus never fail outside of compiler bugs pub fn const_field<'tcx>( pub(crate) fn const_field<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, variant: Option,"} {"_id":"q-en-rust-653e5a2668fb597108ca9e54e5824efd7ccfc6c34788679629239cbdc5da8afd","text":"return None; } pub fn return_type_impl_trait(self, scope_def_id: LocalDefId) -> Option<(Ty<'tcx>, Span)> { // `type_of()` will fail on these (#55796, #86483), so only allow `fn`s or closures. match self.hir().get_by_def_id(scope_def_id) { Node::Item(&hir::Item { kind: ItemKind::Fn(..), .. }) => {} Node::TraitItem(&hir::TraitItem { kind: TraitItemKind::Fn(..), .. }) => {} Node::ImplItem(&hir::ImplItem { kind: ImplItemKind::Fn(..), .. }) => {} Node::Expr(&hir::Expr { kind: ExprKind::Closure { .. }, .. }) => {} _ => return None, } let ret_ty = self.type_of(scope_def_id).instantiate_identity(); match ret_ty.kind() { ty::FnDef(_, _) => { let sig = ret_ty.fn_sig(self); let output = self.erase_late_bound_regions(sig.output()); output.is_impl_trait().then(|| { let hir_id = self.hir().local_def_id_to_hir_id(scope_def_id); let fn_decl = self.hir().fn_decl_by_hir_id(hir_id).unwrap(); (output, fn_decl.output.span()) }) } _ => None, } } /// Checks if the bound region is in Impl Item. pub fn is_bound_region_in_impl_item(self, suitable_region_binding_scope: LocalDefId) -> bool { let container_id = self.parent(suitable_region_binding_scope.to_def_id());"} {"_id":"q-en-rust-655b75cf5575c22d7da54fd59113d1f12a5704e86c60a4f3e9e18017406d29bf","text":"self.parent_cfg = new_cfg.clone(); item.cfg = new_cfg; let old_parent = if let Some(def_id) = item.item_id.as_def_id().and_then(|def_id| def_id.as_local()) { self.parent.replace(def_id) } else { self.parent.take() }; let result = self.fold_item_recur(item); self.parent_cfg = old_parent_cfg; self.parent = old_parent; Some(result) }"} {"_id":"q-en-rust-6581c8b756873bbdda57640a7e62838aa0b4b67e9e4779df0bfa01e20a7567e7","text":"} PatKind::Binding { name, mutability, mode, var, ty, ref subpattern, is_primary: _ } => { candidate.bindings.push(Binding { name, mutability, span: match_pair.pattern.span, source: match_pair.place.clone().into_place(self.tcx, self.typeck_results), var_id: var, var_ty: ty, binding_mode: mode, }); if let Ok(place_resolved) = match_pair.place.clone().try_upvars_resolved(self.tcx, self.typeck_results) { candidate.bindings.push(Binding { name, mutability, span: match_pair.pattern.span, source: place_resolved.into_place(self.tcx, self.typeck_results), var_id: var, var_ty: ty, binding_mode: mode, }); } if let Some(subpattern) = subpattern.as_ref() { // this is the `x @ P` case; have to keep matching against `P` now"} {"_id":"q-en-rust-65b3fee4b4681f532930442240ddce5b76983d77f7c3485c0a65e6441eb1dc86","text":"}; add_to_sysroot(builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target)); // Special case for stage0, to make `rustup toolchain link` and `x dist --stage 0` // work for stage0-sysroot. We only do this if the stage0 compiler comes from beta, // and is not set to a custom path. if compiler.stage == 0 && builder .build .config .initial_rustc .starts_with(builder.out.join(&compiler.host.triple).join(\"stage0/bin\")) { // Copy bin files from stage0/bin to stage0-sysroot/bin let sysroot = builder.out.join(&compiler.host.triple).join(\"stage0-sysroot\"); let host = compiler.host.triple; let stage0_bin_dir = builder.out.join(&host).join(\"stage0/bin\"); let sysroot_bin_dir = sysroot.join(\"bin\"); t!(fs::create_dir_all(&sysroot_bin_dir)); builder.cp_r(&stage0_bin_dir, &sysroot_bin_dir); // Copy all *.so files from stage0/lib to stage0-sysroot/lib let stage0_lib_dir = builder.out.join(&host).join(\"stage0/lib\"); if let Ok(files) = fs::read_dir(&stage0_lib_dir) { for file in files { let file = t!(file); let path = file.path(); if path.is_file() && is_dylib(&file.file_name().into_string().unwrap()) { builder.copy(&path, &sysroot.join(\"lib\").join(path.file_name().unwrap())); } } } // Copy codegen-backends from stage0 let sysroot_codegen_backends = builder.sysroot_codegen_backends(compiler); t!(fs::create_dir_all(&sysroot_codegen_backends)); let stage0_codegen_backends = builder .out .join(&host) .join(\"stage0/lib/rustlib\") .join(&host) .join(\"codegen-backends\"); builder.cp_r(&stage0_codegen_backends, &sysroot_codegen_backends); } } }"} {"_id":"q-en-rust-65d67a8c9c9e875613b8ac0c0a92af897f39854f7946257e449ffb3da5247e58","text":"let source_map = self.tcx.sess.source_map(); let all_source_files = source_map.files(); let (working_dir, working_dir_was_remapped) = self.tcx.sess.working_dir.clone(); let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone(); let adapted = all_source_files.iter() .filter(|source_file| {"} {"_id":"q-en-rust-65f5bceee9c1749a7a549da2e04707d247228d0748d6ad71106fcf915839e3b2","text":"raise RuntimeError(\"failed to find config line for {}\".format(key)) for section_key in config: section_config = config[section_key] if section_key not in sections: raise RuntimeError(\"config key {} not in sections\".format(section_key)) def configure_top_level_key(lines, top_level_key, value): for i, line in enumerate(lines): if line.startswith('#' + top_level_key + ' = ') or line.startswith(top_level_key + ' = '): lines[i] = \"{} = {}\".format(top_level_key, value) return if section_key == 'target': raise RuntimeError(\"failed to find config line for {}\".format(top_level_key)) for section_key, section_config in config.items(): if section_key not in sections and section_key not in top_level_keys: raise RuntimeError(\"config key {} not in sections or top_level_keys\".format(section_key)) if section_key in top_level_keys: configure_top_level_key(sections[None], section_key, section_config) elif section_key == 'target': for target in section_config: configure_section(targets[target], section_config[target]) else:"} {"_id":"q-en-rust-660c67808a9813783de74bcd3851ef97e0aeb465b39da843ba5828b934527f7e","text":"unsafe { self.__iterator_get_unchecked(index) } } } trait SpecFold: Iterator { fn spec_fold(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B; } impl SpecFold for Zip { // Adapted from default impl from the Iterator trait #[inline] default fn spec_fold(mut self, init: Acc, mut f: F) -> Acc where F: FnMut(Acc, Self::Item) -> Acc, { let mut accum = init; while let Some(x) = ZipImpl::next(&mut self) { accum = f(accum, x); } accum } } impl SpecFold for Zip { #[inline] fn spec_fold(mut self, init: Acc, mut f: F) -> Acc where F: FnMut(Acc, Self::Item) -> Acc, { let mut accum = init; loop { let (upper, more) = if let Some(upper) = ZipImpl::size_hint(&self).1 { (upper, false) } else { // Per TrustedLen contract a None upper bound means more than usize::MAX items (usize::MAX, true) }; for _ in 0..upper { let pair = // SAFETY: TrustedLen guarantees that at least `upper` many items are available // therefore we know they can't be None unsafe { (self.a.next().unwrap_unchecked(), self.b.next().unwrap_unchecked()) }; accum = f(accum, pair); } if !more { break; } } accum } } "} {"_id":"q-en-rust-663106109792107651ef4364aebb2cc000e0bac25d021c08d6ff725e5d55ee48","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":"q-en-rust-6678fbfcfba2c2903014f3f96461fb61b78d0c0e0be649e322d1b71fc58abcee","text":"}).collect::, _>>()?; let offset = st[i].fields.offset(field_index) + offset; let LayoutDetails { size, mut align, .. } = st[i]; let LayoutDetails { mut size, mut align, .. } = st[i]; let mut niche_align = niche.value.align(dl); let abi = if offset.bytes() == 0 && niche.value.size(dl) == size {"} {"_id":"q-en-rust-6693252d2b41ffadf666bd5153de2b915eae8537f473b0bad0ee7ac3ef865182","text":" Subproject commit 3abdd2f1ced4cf3a44c7de88c5e39b3bb5037c4d Subproject commit 86b8643586aa39f36fb7a02e98c8d64d31415e70 "} {"_id":"q-en-rust-66b7a30f152e33888ac4e3f2389b7739956aee147d1f438277d1e3cdd0df399d","text":"self.register_unsize_obligations(span, &**u) } ty::UnsizeVtable(ref ty_trait, self_ty) => { // If the type is `Foo+'a`, ensures that the type // being cast to `Foo+'a` implements `Foo`: vtable2::register_object_cast_obligations(self, span, ty_trait, self_ty); // If the type is `Foo+'a`, ensures that the type // being cast to `Foo+'a` outlives `'a`: let origin = infer::RelateObjectBound(span); self.register_region_obligation(origin, self_ty, ty_trait.bounds.region_bound); } } }"} {"_id":"q-en-rust-66bec023196de7b6654db72ea964294adc9afdaff115c20120c000e0e4315663","text":"} pub fn create_sysroot(build: &Build, compiler: &Compiler) { // nothing to do in stage0 if compiler.stage == 0 { return } let sysroot = build.sysroot(compiler); let _ = fs::remove_dir_all(&sysroot); t!(fs::create_dir_all(&sysroot));"} {"_id":"q-en-rust-66c4680809c15f2b470117dc2438f3a5076b802311dc2b99600d07fa10afd15e","text":"if (!innerToggle) { return; } let sectionIsCollapsed = false; if (hasClass(innerToggle, \"will-expand\")) { removeClass(innerToggle, \"will-expand\"); onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"), e => { if (!hasClass(e, \"type-contents-toggle\")) { e.open = true; } }); innerToggle.title = \"collapse all docs\"; expandAllDocs(); } else { addClass(innerToggle, \"will-expand\"); onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"), e => { if (e.parentNode.id !== \"implementations-list\" || (!hasClass(e, \"implementors-toggle\") && !hasClass(e, \"type-contents-toggle\")) ) { e.open = false; } }); sectionIsCollapsed = true; innerToggle.title = \"expand all docs\"; collapseAllDocs(); } innerToggle.children[0].innerText = labelForToggleButton(sectionIsCollapsed); } (function() {"} {"_id":"q-en-rust-66cd9fe95571bc5754b952dc8f04f5c3124779a464c5a12d111c3de21f30c5da","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. // ignore-tidy-linelength #![deny(deprecated)] extern crate url; fn main() { let _ = url::Url::parse(\"http://example.com\"); //~^ ERROR use of deprecated item: This is being removed. Use rust-url instead. http://servo.github.io/rust-url/ } "} {"_id":"q-en-rust-67039d2da50844bc5f63eef05534ce382dd5d1a94390719234a6e5776e30bd3c","text":" // This is a separate test from `issue-66693.rs` because array lengths are evaluated // in a separate stage before `const`s and `statics` and so the error below is hit and // the compiler exits before generating errors for the others. #![feature(const_panic)] fn main() { let _ = [0i32; panic!(2f32)]; //~^ ERROR: argument to `panic!()` in a const context must have type `&str` // ensure that conforming panics are handled correctly let _ = [false; panic!()]; //~^ ERROR: evaluation of constant value failed // typechecking halts before getting to this one let _ = ['a', panic!(\"panic in array len\")]; } "} {"_id":"q-en-rust-671c83b3d20db1cef3742c268bf8af66e40b64909ad88ebf06bdb306c6f8d830","text":"mod remove_unneeded_drops; mod remove_zsts; mod required_consts; mod reveal_all; mod separate_const_switch; mod shim; mod simplify;"} {"_id":"q-en-rust-6744fa8293ca9b83f08320bd9c80da6a460b2f710006a5fb1b8cd60b8c2b0304","text":"//~^ ERROR any use of this value will cause an error //~| WARN this was previously accepted by the compiler but is being phased out // capture fault with zero value const _: u32 = unsafe { std::intrinsics::ctlz_nonzero(0) }; //~^ ERROR any use of this value will cause an error //~| WARN this was previously accepted by the compiler but is being phased out const _: u32 = unsafe { std::intrinsics::cttz_nonzero(0) }; //~^ ERROR any use of this value will cause an error //~| WARN this was previously accepted by the compiler but is being phased out fn main() {}"} {"_id":"q-en-rust-678cf9198c6cc15cfadd822f111d44f391a53b356090defd82bc165447d1a46c","text":" error: `?` may only modify trait bounds, not lifetime bounds --> $DIR/issue-68890.rs:1:11 | LL | enum e{A((?'a a+?+l))} | ^ error: expected one of `)`, `+`, or `,`, found `a` --> $DIR/issue-68890.rs:1:15 | LL | enum e{A((?'a a+?+l))} | ^ expected one of `)`, `+`, or `,` error: expected trait bound, not lifetime bound --> $DIR/issue-68890.rs:1:11 | LL | enum e{A((?'a a+?+l))} | ^^^ error: aborting due to 3 previous errors "} {"_id":"q-en-rust-67b6f8a07fabf5a41f70f1b622357703534bccc88a5f7b962b523a40c6407e57","text":" // Regression test for #65553 // // `D::Error:` is lowered to `D::Error: ReEmpty` - check that we don't ICE in // NLL for the unexpected region. // check-pass trait Deserializer { type Error; } fn d1() where D::Error: {} fn d2() { d1::(); } fn main() {} "} {"_id":"q-en-rust-67d5d1fb8ecc6105712f9767d62104ce4bb42a1ddc5c2c05eed3c61b26b77152","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":"q-en-rust-682ad45db2e111f22f956f56d131af9c68feafd0efb53533861144481018d6d4","text":"pat_src: PatternSource, bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet); 1]>, ) { // We walk the pattern before declaring the pattern's inner bindings, // so that we avoid resolving a literal expression to a binding defined // by the pattern. visit::walk_pat(self, pat); self.resolve_pattern_inner(pat, pat_src, bindings); // This has to happen *after* we determine which pat_idents are variants: self.check_consistent_bindings_top(pat); visit::walk_pat(self, pat); } /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`."} {"_id":"q-en-rust-689a6438590aa36ed16caf490360ae683fad67aa225765edfce4e77254658a3f","text":"} fn main() { print_x(X); //~error this function takes 2 parameters but 1 parameter was supplied //~^ NOTE the following parameter types were expected: &Foo, &str print_x(X); //~^ ERROR this function takes 2 parameters but 1 parameter was supplied //~| NOTE the following parameter types were expected: &Foo, &str //~| NOTE expected 2 parameters }"} {"_id":"q-en-rust-68a2cb5efc2a89c514b37e68e2b6e88c99f5a91be21d166aa746e4c0968465d6","text":"}; let last_type_ascription_set = self.last_type_ascription.is_some(); match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) { (true, None) => { self.last_type_ascription = None; // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071 return Ok(lhs); } (false, _) => {} // continue parsing the expression // An exhaustive check is done in the following block, but these are checked first // because they *are* ambiguous but also reasonable looking incorrect syntax, so we // want to keep their span info to improve diagnostics in these cases in a later stage. (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3` (true, Some(AssocOp::Subtract)) | // `{ 42 } -5` (true, Some(AssocOp::LAnd)) | // `{ 42 } &&x` (#61475) (true, Some(AssocOp::Add)) // `{ 42 } + 42 // If the next token is a keyword, then the tokens above *are* unambiguously incorrect: // `if x { a } else { b } && if y { c } else { d }` if !self.look_ahead(1, |t| t.is_reserved_ident()) => { self.last_type_ascription = None; // These cases are ambiguous and can't be identified in the parser alone let sp = self.sess.source_map().start_point(self.token.span); self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span); return Ok(lhs); } (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => { self.last_type_ascription = None; return Ok(lhs); } (true, Some(_)) => { // We've found an expression that would be parsed as a statement, but the next // token implies this should be parsed as an expression. // For example: `if let Some(x) = x { x } else { 0 } / 2` let mut err = self.struct_span_err(self.token.span, &format!( \"expected expression, found `{}`\", pprust::token_to_string(&self.token), )); err.span_label(self.token.span, \"expected expression\"); self.sess.expr_parentheses_needed( &mut err, lhs.span, Some(pprust::expr_to_string(&lhs), )); err.emit(); } if !self.should_continue_as_assoc_expr(&lhs) { self.last_type_ascription = None; return Ok(lhs); } self.expected_tokens.push(TokenType::Operator); while let Some(op) = AssocOp::from_token(&self.token) { self.expected_tokens.push(TokenType::Operator); while let Some(op) = self.check_assoc_op() { // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what // it refers to. Interpolated identifiers are unwrapped early and never show up here // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process"} {"_id":"q-en-rust-68c0d2169c87835f0b4c33adc05ee6f02cd0f5561df8487bbc96d9e69e50325a","text":" // run-rustfix use std::any::Any; fn foo(value: &T) -> Box { Box::new(value) as Box //~^ ERROR lifetime may not live long enough } fn main() { let _ = foo(&5); } "} {"_id":"q-en-rust-68c3d2b4d5169c8b9d39145667913097c26c020a9620cf463ed2a73d4143102c","text":" // check-pass #![deny(unused_lifetimes)] trait Trait2 { type As; } // we should not warn about an unused lifetime about code generated from this proc macro here #[derive(Clone)] struct ShimMethod4(pub &'static dyn for<'s> Fn(&'s mut T::As)); pub fn main() {} "} {"_id":"q-en-rust-68c7da930d76ded950c60723ed6b25c223323e266836530a337645cd96f6b64a","text":" error: expected trait bound, found `impl Trait` type --> $DIR/issue-102182-impl-trait-recover.rs:1:11 | LL | fn foo() {} | ^^^^^^^^^^ not a trait | help: use the trait bounds directly | LL - fn foo() {} LL + fn foo() {} | error: aborting due to previous error "} {"_id":"q-en-rust-68cfd77b0b6f7fa92bb90122c7b44653a6d5d7ab12d1334d2ae40052821b4ac0","text":"/// # Examples /// /// ```no_run /// #![feature(buffered_io_capacity)] /// use std::io::{BufReader, BufRead}; /// use std::fs::File; ///"} {"_id":"q-en-rust-68f8f9bb35ea606efc594300e9e204348e63d48ad901f424b0d2a1b76be683b9","text":"- it is bound as an associated type, e.g. `impl SomeTrait for T where T: AnotherTrait` Any unconstrained lifetime parameter of an `impl` is not supported if the lifetime parameter is used by an associated type. ### Error example 1 Suppose we have a struct `Foo` and we would like to define some methods for it."} {"_id":"q-en-rust-6943e4bc18da1eefc62edb7aa418fe43d57f6855e88095d7f75e79caac9a4148","text":"= help: the trait `Sized` is not implemented for `[u8]` = note: all local variables must have a statically known size = help: unsized locals are gated as an unstable feature help: consider borrowing here | LL | let _foo: &[u8] = *foo; | + error: aborting due to 3 previous errors"} {"_id":"q-en-rust-69517d268a83c668cdef01c25e13a3085a4970963b5b7d15577f5e54ef45e91f","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":"q-en-rust-6954909598c39886c3f29b40c26fb89eca23b86df8b67630479ff04a0f7469a5","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":"q-en-rust-6977e261d9dd0054ba4180001d05e39fc3313ceae1c794a61681175d62ab4538","text":"LL | use V; | ^ ambiguous name | = note: ambiguous because of multiple potential import sources = note: ambiguous because of multiple glob imports of a name in the same module note: `V` could refer to the variant imported here --> $DIR/issue-105069.rs:1:5 | LL | use self::A::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `V` to disambiguate note: `V` could also refer to the variant imported here --> $DIR/issue-105069.rs:3:5 | LL | use self::B::*; | ^^^^^^^^^^ = help: consider adding an explicit import of `V` to disambiguate error: aborting due to previous error"} {"_id":"q-en-rust-697969d889017abdaf135b381282ae2573eec1a896290b0d44a6ef65a20fa3c9","text":"// (We do this separately from the above so that when the setup actually // happens we get some output.) // We re-use the `cargo` from above. cargo.arg(\"--env\"); cargo.arg(\"--print-sysroot\"); // FIXME: Is there a way in which we can re-use the usual `run` helpers? let miri_sysroot = if builder.config.dry_run {"} {"_id":"q-en-rust-69c74f3a5daa5eeec838d8a6294e31fe68cf51253ba379f25f51b47663b36c7b","text":" // ... continued from ./min-choice.rs // check-fail trait Cap<'a> {} impl Cap<'_> for T {} fn type_test<'a, T: 'a>() -> &'a u8 { &0 } // Make sure we don't pick `'b`. fn test_b<'a, 'b, 'c, T>() -> impl Cap<'a> + Cap<'b> + Cap<'c> where 'a: 'b, 'a: 'c, T: 'b, { type_test::<'_, T>() // This should pass if we pick 'b. //~^ ERROR the parameter type `T` may not live long enough } // Make sure we don't pick `'c`. fn test_c<'a, 'b, 'c, T>() -> impl Cap<'a> + Cap<'b> + Cap<'c> where 'a: 'b, 'a: 'c, T: 'c, { type_test::<'_, T>() // This should pass if we pick 'c. //~^ ERROR the parameter type `T` may not live long enough } // We need to pick min_choice from `['b, 'c]`, but it's ambiguous which one to pick because // they're incomparable. fn test_ambiguous<'a, 'b, 'c>(s: &'a u8) -> impl Cap<'b> + Cap<'c> where 'a: 'b, 'a: 'c, { s //~^ ERROR captures lifetime that does not appear in bounds } fn main() {} "} {"_id":"q-en-rust-69c80c5b340bbde2cde7614a5623f643acade984b4bc0019f8c51097ff28d18d","text":"let verbose = std::env::var(\"MIRI_VERBOSE\") .map_or(0, |verbose| verbose.parse().expect(\"verbosity flag must be an integer\")); // phase_cargo_miri sets the RUSTDOC env var to ourselves, so we can't use that here; // just default to a straight-forward invocation for now: let mut cmd = Command::new(\"rustdoc\"); // phase_cargo_miri sets the RUSTDOC env var to ourselves, and puts a backup // of the old value into MIRI_ORIG_RUSTDOC. So that's what we have to invoke now. let rustdoc = env::var(\"MIRI_ORIG_RUSTDOC\").unwrap_or(\"rustdoc\".to_string()); let mut cmd = Command::new(rustdoc); let extern_flag = \"--extern\"; let runtool_flag = \"--runtool\";"} {"_id":"q-en-rust-69ca342e554cf9c809904ce2415ca236928b8c2f202c577c74a36df9c75319c2","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::*; use std::rand; use std::rand::Rng; use test::{Bencher, black_box}; pub fn insert_rand_n(n: usize, map: &mut M, b: &mut Bencher, mut insert: I, mut remove: R) where I: FnMut(&mut M, usize), R: FnMut(&mut M, usize), { // setup let mut rng = rand::weak_rng(); for _ in 0..n { insert(map, rng.gen::() % n); } // measure b.iter(|| { let k = rng.gen::() % n; insert(map, k); remove(map, k); }); black_box(map); macro_rules! map_insert_rand_bench { ($name: ident, $n: expr, $map: ident) => ( #[bench] pub fn $name(b: &mut ::test::Bencher) { use std::rand; use std::rand::Rng; use test::black_box; let n: usize = $n; let mut map = $map::new(); // setup let mut rng = rand::weak_rng(); for _ in 0..n { let i = rng.gen() % n; map.insert(i, i); } // measure b.iter(|| { let k = rng.gen() % n; map.insert(k, k); map.remove(&k); }); black_box(map); } ) } pub fn insert_seq_n(n: usize, map: &mut M, b: &mut Bencher, mut insert: I, mut remove: R) where I: FnMut(&mut M, usize), R: FnMut(&mut M, usize), { // setup for i in 0..n { insert(map, i * 2); } // measure let mut i = 1; b.iter(|| { insert(map, i); remove(map, i); i = (i + 2) % n; }); black_box(map); macro_rules! map_insert_seq_bench { ($name: ident, $n: expr, $map: ident) => ( #[bench] pub fn $name(b: &mut ::test::Bencher) { use test::black_box; let mut map = $map::new(); let n: usize = $n; // setup for i in 0..n { map.insert(i * 2, i * 2); } // measure let mut i = 1; b.iter(|| { map.insert(i, i); map.remove(&i); i = (i + 2) % n; }); black_box(map); } ) } pub fn find_rand_n(n: usize, map: &mut M, b: &mut Bencher, mut insert: I, mut find: F) where I: FnMut(&mut M, usize), F: FnMut(&M, usize) -> T, { // setup let mut rng = rand::weak_rng(); let mut keys: Vec<_> = (0..n).map(|_| rng.gen::() % n).collect(); for k in &keys { insert(map, *k); } rng.shuffle(&mut keys); // measure let mut i = 0; b.iter(|| { let t = find(map, keys[i]); i = (i + 1) % n; black_box(t); }) macro_rules! map_find_rand_bench { ($name: ident, $n: expr, $map: ident) => ( #[bench] pub fn $name(b: &mut ::test::Bencher) { use std::rand; use std::rand::Rng; use test::black_box; let mut map = $map::new(); let n: usize = $n; // setup let mut rng = rand::weak_rng(); let mut keys: Vec<_> = (0..n).map(|_| rng.gen() % n).collect(); for &k in &keys { map.insert(k, k); } rng.shuffle(&mut keys); // measure let mut i = 0; b.iter(|| { let t = map.get(&keys[i]); i = (i + 1) % n; black_box(t); }) } ) } pub fn find_seq_n(n: usize, map: &mut M, b: &mut Bencher, mut insert: I, mut find: F) where I: FnMut(&mut M, usize), F: FnMut(&M, usize) -> T, { // setup for i in 0..n { insert(map, i); } // measure let mut i = 0; b.iter(|| { let x = find(map, i); i = (i + 1) % n; black_box(x); }) macro_rules! map_find_seq_bench { ($name: ident, $n: expr, $map: ident) => ( #[bench] pub fn $name(b: &mut ::test::Bencher) { use test::black_box; let mut map = $map::new(); let n: usize = $n; // setup for i in 0..n { map.insert(i, i); } // measure let mut i = 0; b.iter(|| { let x = map.get(&i); i = (i + 1) % n; black_box(x); }) } ) }"} {"_id":"q-en-rust-6a1df6a2735390134a49df9d50c19a33bb9b9a7ed5452296e43259a3914ad0be","text":" // unit-test: ConstProp // compile-flags: -O // Regression test for https://github.com/rust-lang/rust/issues/118328 #![allow(unused_assignments)] struct SizeOfConst(std::marker::PhantomData); impl SizeOfConst { const SIZE: usize = std::mem::size_of::(); } // EMIT_MIR overwrite_with_const_with_params.size_of.ConstProp.diff fn size_of() -> usize { // CHECK-LABEL: fn size_of( // CHECK: _1 = const 0_usize; // CHECK-NEXT: _1 = const _; // CHECK-NEXT: _0 = _1; let mut a = 0; a = SizeOfConst::::SIZE; a } fn main() { assert_eq!(size_of::(), std::mem::size_of::()); } "} {"_id":"q-en-rust-6a27a1c5df6a33f48200ba1bf93d020b31dba1c798b74ce4645e752c5c70a78f","text":" // no-prefer-dynamic #![feature(unsized_tuple_coercion)] static mut DROP_RAN: isize = 0;"} {"_id":"q-en-rust-6a2b5ee8271d37bf4b2523a59587beae69f8f53e4d5ba5cb133a64cb4828dd46","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 moves of unsized values within closures are caught // and rejected. fn main() { (|| box *[0u].as_slice())(); //~^ ERROR cannot move a value of type [uint] } "} {"_id":"q-en-rust-6a2e07615246d396548518c4f221369e8624b2922f7066df96bb26887fa7dc52","text":"struct GoodVoid(Void); fn main() { let w = SingleUnused(42, [0, 1, 2, 3], \"abc\".to_string()); let _ = w.0; let _ = w.2; let u1 = UnusedAtTheEnd(42, 3.14, [0, 1, 2, 3], \"def\".to_string(), 4u8); let _ = u1.0; let _ = UnusedJustOneField(42); let u2 = UnusedInTheMiddle(42, 3.14, \"def\".to_string(), 4u8, 5); let _ = u2.0; let _ = u2.3; let m = MultipleUnused(42, 3.14, \"def\".to_string(), 4u8); let gu = GoodUnit(()); let gp = GoodPhantom(PhantomData); let gv = GoodVoid(Void); let _ = (gu, gp, gv, m); let _ = (gu, gp, gv); }"} {"_id":"q-en-rust-6a4f3c374e6da4d0e3de85805605c46401a31cd4e6b3e0b6244838cdd21568df","text":"let size = mem::size_of::() .checked_mul(count) .expect(\"is_nonoverlapping: `size_of::() * count` overflows a usize\"); let diff = if src_usize > dst_usize { src_usize - dst_usize } else { dst_usize - src_usize }; let diff = src_usize.abs_diff(dst_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"} {"_id":"q-en-rust-6a62325baa76834a2446437640a9d819901e30a08a472ecf16607beadb59c2c9","text":"// discriminant. if !def.repr.c() && !def.repr.transparent() && def.repr.int.is_none() { // Special-case types like `Option`. if !is_repr_nullable_ptr(cx, ty, def, substs) { if !self.is_repr_nullable_ptr(ty, def, substs) { return FfiUnsafe { ty, reason: \"enum has no representation hint\".into(),"} {"_id":"q-en-rust-6ad1da629137970f04f0f803db118d1a23aceac3a766c3f77c661fe7d0b0c2bd","text":"// Associated types in traits don't necessarily have a type that we can visit try_visit!(visitor.visit(ty.span, tcx.type_of(item).instantiate_identity())); } for (pred, span) in tcx.predicates_of(item).instantiate_identity(tcx) { for (pred, span) in tcx.explicit_predicates_of(item).instantiate_identity(tcx) { try_visit!(visitor.visit(span, pred)); } }"} {"_id":"q-en-rust-6ad6739ebdf74dec0a15e56bf5e2d124d613a765f5439198d69dafa562808102","text":"/// let src = [1, 2, 3, 4]; /// let mut dst = [0, 0]; /// /// // Because the slices have to be the same length, /// // we slice the source slice from four elements /// // to two. It will panic if we don't do this. /// dst.clone_from_slice(&src[2..]); /// /// assert_eq!(src, [1, 2, 3, 4]);"} {"_id":"q-en-rust-6aefabe3e3dde5bec8464314eaa7335530a9827d25a697fae5b317dac045e89a","text":" Subproject commit 7b8e8293d08d298579470f9d6c74731043c6601a Subproject commit 7a943a9dfcdca98e5988da6d0b7d2f83a364b5ba "} {"_id":"q-en-rust-6b1bc322100a5a4345f5468157dbfd292d6a197499b25c8389991cc520c7f7d6","text":"}); } fn get_lint_level(&self, lint: &'static Lint, idx: u32) fn get_lint_level(&self, lint: &'static Lint, idx: u32, aux: Option<&FxHashMap>) -> (Level, LintSource) { let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx); let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux); // If `level` is none then we actually assume the default level for this // lint."} {"_id":"q-en-rust-6b375d7e2dc4fcae96d7559dda8d9fd47be427fdf85016198ea0367f85de3e20","text":"let fcx = FnCtxt::new(&inh, param_env, id); if !inh.tcx.features().trivial_bounds { // As predicates are cached rather than obligations, this // needsto be called first so that they are checked with an // needs to be called first so that they are checked with an // empty `param_env`. check_false_global_bounds(&fcx, span, id); }"} {"_id":"q-en-rust-6b8555c5ad499af3d104445ffc2f6039a01e8fa0cddd3aacb3269ef936fe0394","text":"//! `&foo()` or `match foo() { ref x => ... }`, where the user is //! implicitly requesting a temporary. //! //! Somewhat surprisingly, not all lvalue expressions yield lvalue datums //! when trans'd. Ultimately the reason for this is to micro-optimize //! the resulting LLVM. For example, consider the following code: //! //! fn foo() -> Box { ... } //! let x = *foo(); //! //! The expression `*foo()` is an lvalue, but if you invoke `expr::trans`, //! it will return an rvalue datum. See `deref_once` in expr.rs for //! more details. //! //! ### Rvalues in detail //! //! Rvalues datums are values with no cleanup scheduled. One must be"} {"_id":"q-en-rust-6babb0d0458590ab53c58fd74e911bee9a2d240b25203804e6285c1721bbc88f","text":"f: impl FnOnce(&mut search_graph::GlobalCache) -> R, ) -> R; fn evaluation_is_concurrent(&self) -> bool; fn expand_abstract_consts>(self, t: T) -> T; type GenericsOf: GenericsOf;"} {"_id":"q-en-rust-6bfdadf1deae1597793d2faee2473dd126f1903d605cf6e0ec353a53b07c8ab2","text":"ignore_binding, ); let no_ambiguity = self.ambiguity_errors.len() == prev_ambiguity_errors_len; let no_ambiguity = ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len; import.vis.set(orig_vis); let module = match path_res { PathResult::Module(module) => {"} {"_id":"q-en-rust-6c02937cf93e998557f543b0132d2407cbb945a0065cca61d07cc2ba98dea010","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":"q-en-rust-6c5dde4ba37b1c99b07cb660cf31ed0693dca52100d4ae755df22a2eaf97798d","text":" // compile-flags: -Z mir-opt-level=3 -Z inline-mir // ignore-wasm32-bare compiled with panic=abort by default #![crate_type = \"lib\"] // EMIT_MIR issue_78442.bar.RevealAll.diff // EMIT_MIR issue_78442.bar.Inline.diff pub fn bar