{"_id":"doc-en-rust-7056667870caa5c4389e2132ba66549631ab02685b24cbf766c50c4b7f4912ca","title":"","text":"// MACRO_RULES ITEM self.parse_item_macro_rules(vis, has_bang)? } else if self.isnt_macro_invocation() && (self.token.is_ident_named(sym::import) || self.token.is_ident_named(sym::using)) && (self.token.is_ident_named(sym::import) || self.token.is_ident_named(sym::using) || self.token.is_ident_named(sym::include) || self.token.is_ident_named(sym::require)) { return self.recover_import_as_use(); } else if self.isnt_macro_invocation() && vis.kind.is_pub() {"} {"_id":"doc-en-rust-2090e57d0624a1568785c284618483d213821ec3385063743ba70736df9c22f8","title":"","text":"repr_packed, repr_simd, repr_transparent, require, residual, result, rhs,"} {"_id":"doc-en-rust-3937befccddb58fa4371176614abea8e7a98d3b3e724af484a168849f34a4552","title":"","text":"rc::Rc, }; use std::time::Duration; //~^ ERROR expected item, found `require` use std::time::Instant; //~^ ERROR expected item, found `include` pub use std::io; //~^ ERROR expected item, found `using` fn main() { let x = Rc::new(1); let _ = write!(io::stdout(), \"{:?}\", x); let _ = Duration::new(5, 0); let _ = Instant::now(); }"} {"_id":"doc-en-rust-2d160c63e6053f1422eb434106ecea94f5004727466568380059d3de309db222","title":"","text":"rc::Rc, }; require std::time::Duration; //~^ ERROR expected item, found `require` include std::time::Instant; //~^ ERROR expected item, found `include` pub using std::io; //~^ ERROR expected item, found `using` fn main() { let x = Rc::new(1); let _ = write!(io::stdout(), \"{:?}\", x); let _ = Duration::new(5, 0); let _ = Instant::now(); }"} {"_id":"doc-en-rust-fd29f124f5f6d13bdfde292b1855d240b3e6d73dcca6558fe433fd27f477a5a2","title":"","text":"LL | import std::{ | ^^^^^^ help: items are imported using the `use` keyword error: expected item, found `require` --> $DIR/use_instead_of_import.rs:9:1 | LL | require std::time::Duration; | ^^^^^^^ help: items are imported using the `use` keyword error: expected item, found `include` --> $DIR/use_instead_of_import.rs:12:1 | LL | include std::time::Instant; | ^^^^^^^ help: items are imported using the `use` keyword error: expected item, found `using` --> $DIR/use_instead_of_import.rs:9:5 --> $DIR/use_instead_of_import.rs:15:5 | LL | pub using std::io; | ^^^^^ help: items are imported using the `use` keyword error: aborting due to 2 previous errors error: aborting due to 4 previous errors "} {"_id":"doc-en-rust-c6b37c06a0fc1d4f666438c70792297baddee9f0dc3f75dbd46c5d205321aa3b","title":"","text":"evaluation_cache: self.evaluation_cache.clone(), reported_trait_errors: self.reported_trait_errors.clone(), reported_closure_mismatch: self.reported_closure_mismatch.clone(), tainted_by_errors_flag: self.tainted_by_errors_flag.clone(), tainted_by_errors: self.tainted_by_errors.clone(), err_count_on_creation: self.err_count_on_creation, in_snapshot: self.in_snapshot.clone(), universe: self.universe.clone(),"} {"_id":"doc-en-rust-3bf783b08325d9235213c336bd399a49cc8ebfc3d43f5ae374e85ea4264cb855","title":"","text":"use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt}; use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid}; use rustc_span::symbol::Symbol; use rustc_span::Span; use rustc_span::{Span, DUMMY_SP}; use std::cell::{Cell, Ref, RefCell}; use std::fmt;"} {"_id":"doc-en-rust-c34ff36c5819853993b0ba0b8c9e7541b4720bc72be278b801d9497722981b24","title":"","text":"/// /// Don't read this flag directly, call `is_tainted_by_errors()` /// and `set_tainted_by_errors()`. tainted_by_errors_flag: Cell, tainted_by_errors: Cell>, /// Track how many errors were reported when this infcx is created. /// If the number of errors increases, that's also a sign (line /// `tainted_by_errors`) to avoid reporting certain kinds of errors. // FIXME(matthewjasper) Merge into `tainted_by_errors_flag` // FIXME(matthewjasper) Merge into `tainted_by_errors` err_count_on_creation: usize, /// This flag is true while there is an active snapshot."} {"_id":"doc-en-rust-0a306832aa6a000b833284314c28c8451cd42f0ec85f49f6c97d77ccb9a86b54","title":"","text":"evaluation_cache: Default::default(), reported_trait_errors: Default::default(), reported_closure_mismatch: Default::default(), tainted_by_errors_flag: Cell::new(false), tainted_by_errors: Cell::new(None), err_count_on_creation: tcx.sess.err_count(), in_snapshot: Cell::new(false), skip_leak_check: Cell::new(false),"} {"_id":"doc-en-rust-4257c97358de787c6649111b827e92c9916beb60830e911a33d925523ca5e5b8","title":"","text":"pub fn is_tainted_by_errors(&self) -> bool { debug!( \"is_tainted_by_errors(err_count={}, err_count_on_creation={}, tainted_by_errors_flag={})\", tainted_by_errors={})\", self.tcx.sess.err_count(), self.err_count_on_creation, self.tainted_by_errors_flag.get() self.tainted_by_errors.get().is_some() ); if self.tcx.sess.err_count() > self.err_count_on_creation { return true; // errors reported since this infcx was made } self.tainted_by_errors_flag.get() self.tainted_by_errors.get().is_some() } /// Set the \"tainted by errors\" flag to true. We call this when we /// observe an error from a prior pass. pub fn set_tainted_by_errors(&self) { debug!(\"set_tainted_by_errors()\"); self.tainted_by_errors_flag.set(true) self.tainted_by_errors.set(Some( self.tcx.sess.delay_span_bug(DUMMY_SP, \"`InferCtxt` incorrectly tainted by errors\"), )); } pub fn skip_region_resolution(&self) {"} {"_id":"doc-en-rust-2ba17c1a3a62b6ad460d48d265c3512dbdada175b91cdd5b67d86f177c17f3f8","title":"","text":"debug!(\"impossible_predicates(predicates={:?})\", predicates); let result = tcx.infer_ctxt().enter(|infcx| { // HACK: Set tainted by errors to gracefully exit in case of overflow. infcx.set_tainted_by_errors(); let param_env = ty::ParamEnv::reveal_all(); let ocx = ObligationCtxt::new(&infcx); let predicates = ocx.normalize(ObligationCause::dummy(), param_env, predicates);"} {"_id":"doc-en-rust-54d344af229ce5bc15c53b3cacf0604457cbbc8368c57cc58f67974baa6fa4c3","title":"","text":") -> io::Result<(Process, StdioPipes)> { let maybe_env = self.env.capture_if_changed(); let mut si = zeroed_startupinfo(); si.cb = mem::size_of::() as c::DWORD; si.dwFlags = c::STARTF_USESTDHANDLES; let child_paths = if let Some(env) = maybe_env.as_ref() { env.get(&EnvKey::new(\"PATH\")).map(|s| s.as_os_str()) } else {"} {"_id":"doc-en-rust-ecaf766429da3cb39a24662faf2fba601016acd17963794365ed16d77add8e14","title":"","text":"let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?; let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?; let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?; si.hStdInput = stdin.as_raw_handle(); si.hStdOutput = stdout.as_raw_handle(); si.hStdError = stderr.as_raw_handle(); let mut si = zeroed_startupinfo(); si.cb = mem::size_of::() as c::DWORD; // If at least one of stdin, stdout or stderr are set (i.e. are non null) // then set the `hStd` fields in `STARTUPINFO`. // Otherwise skip this and allow the OS to apply its default behaviour. // This provides more consistent behaviour between Win7 and Win8+. let is_set = |stdio: &Handle| !stdio.as_raw_handle().is_null(); if is_set(&stderr) || is_set(&stdout) || is_set(&stdin) { si.dwFlags |= c::STARTF_USESTDHANDLES; si.hStdInput = stdin.as_raw_handle(); si.hStdOutput = stdout.as_raw_handle(); si.hStdError = stderr.as_raw_handle(); } unsafe { cvt(c::CreateProcessW("} {"_id":"doc-en-rust-6af0fa357d87249fcbdcb679bb77bef51807ac4a63f9bfb14e129e24cfdb105d","title":"","text":"impl Stdio { fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option) -> io::Result { match *self { // If no stdio handle is available, then inherit means that it // should still be unavailable so propagate the // INVALID_HANDLE_VALUE. Stdio::Inherit => match stdio::get_handle(stdio_id) { Ok(io) => unsafe { let io = Handle::from_raw_handle(io);"} {"_id":"doc-en-rust-cd2229b39040254922f5a71432e893609b54c849643880396f46f9976e3f4ada","title":"","text":"io.into_raw_handle(); ret }, Err(..) => unsafe { Ok(Handle::from_raw_handle(c::INVALID_HANDLE_VALUE)) }, // If no stdio handle is available, then propagate the null value. Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) }, }, Stdio::MakePipe => {"} {"_id":"doc-en-rust-9db789eb9ce0ad62e91b3e3b6ce649e5337381d0570b1f7163831c4db438eac9","title":"","text":"wShowWindow: 0, cbReserved2: 0, lpReserved2: ptr::null_mut(), hStdInput: c::INVALID_HANDLE_VALUE, hStdOutput: c::INVALID_HANDLE_VALUE, hStdError: c::INVALID_HANDLE_VALUE, hStdInput: ptr::null_mut(), hStdOutput: ptr::null_mut(), hStdError: ptr::null_mut(), } }"} {"_id":"doc-en-rust-05645dbc1cbb823f58a73250d2b17eb9dac19efbe05da71700edf033e3ac3193","title":"","text":" #![feature(type_alias_impl_trait)] // check-pass trait Trait {} type TAIT = impl Trait; struct Concrete; impl Trait for Concrete {} fn tait() -> TAIT { Concrete } trait OuterTrait { type Item; } struct Dummy { t: T, } impl OuterTrait for Dummy { type Item = T; } fn tait_and_impl_trait() -> impl OuterTrait { Dummy { t: (tait(), Concrete), } } fn tait_and_dyn_trait() -> impl OuterTrait)> { let b: Box = Box::new(Concrete); Dummy { t: (tait(), b) } } fn main() {} "} {"_id":"doc-en-rust-44633bfd8f6c39a40e9abfe980c14386621afa388b76d9f091bafcfbd3fe8e84","title":"","text":"/// For more, see [this pull request](https://github.com/rust-lang/rust/pull/100591). pub const VERSION_\": &str = \"CURRENT_RUSTC_VERSION\"; pub fn rust_version_symbol() -> Symbol { let version = option_env!(\"CFG_VERSION\").unwrap_or(\"\"); let version = version.split(' ').next().unwrap(); Symbol::intern(&version) } pub fn is_builtin_attr(attr: &Attribute) -> bool { attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some() }"} {"_id":"doc-en-rust-b7647d6b2ced098605b8fc4bccfc9b21bfe930f6ecda0c352201711711570744","title":"","text":"} if let Some(s) = since && s.as_str() == VERSION_\" { let version = option_env!(\"CFG_VERSION\").unwrap_or(\"\"); let version = version.split(' ').next().unwrap(); since = Some(Symbol::intern(&version)); since = Some(rust_version_symbol()); } match (feature, since) {"} {"_id":"doc-en-rust-2976d489441441226a188893de77650f51659ed992e3fa78d9ba3b4ebce2c4ba","title":"","text":"//! collect them instead. use rustc_ast::{Attribute, MetaItemKind}; use rustc_attr::VERSION_\"; use rustc_attr::{rust_version_symbol, VERSION_\"}; use rustc_errors::struct_span_err; use rustc_hir::intravisit::Visitor; use rustc_middle::hir::nested_filter;"} {"_id":"doc-en-rust-9d8f89a9adf9bf975aaeff9b44f46ce9868086d88da01a33e9414795e655fa4b","title":"","text":"} if let Some(s) = since && s.as_str() == VERSION_\" { let version = option_env!(\"CFG_VERSION\").unwrap_or(\"\"); let version = version.split(' ').next().unwrap(); since = Some(Symbol::intern(&version)); since = Some(rust_version_symbol()); } if let Some(feature) = feature {"} {"_id":"doc-en-rust-85a4b4a59ea49777c3b80cf80a90c4b7b1465824ff51535c94626de4efa02ea4","title":"","text":"//! propagating default levels lexically from parent to children ast nodes. use rustc_attr::{ self as attr, ConstStability, Stability, StabilityLevel, Unstable, UnstableReason, self as attr, rust_version_symbol, ConstStability, Stability, StabilityLevel, Unstable, UnstableReason, VERSION_\", }; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_errors::{struct_span_err, Applicability};"} {"_id":"doc-en-rust-441a9cf30e741a15f9a0a737c65293235af8ee3b3ae271ea8b20d472ea2d811d","title":"","text":"}); } fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) { fn unnecessary_stable_feature_lint( tcx: TyCtxt<'_>, span: Span, feature: Symbol, mut since: Symbol, ) { if since.as_str() == VERSION_\" { since = rust_version_symbol(); } tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| { lint.build(&format!( \"the feature `{feature}` has been stable since {since} and no longer requires an "} {"_id":"doc-en-rust-0182e7b02ee886a9103ad63d5d10a5dbf305eb563bcde7ff26999f74b07c8142","title":"","text":"use rustc_middle::ty::layout::{LayoutError, LayoutOf}; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::ToPredicate; use rustc_middle::ty::TypeVisitableExt; use rustc_middle::ty::{self, Instance, Ty, TyCtxt, VariantDef}; use rustc_session::config::ExpectedValues;"} {"_id":"doc-en-rust-db3496e111c9f26cefa2d189071bab94ef0e8f092c608a0ae1eb25be2b0138dd","title":"","text":"use rustc_span::{BytePos, InnerSpan, Span}; use rustc_target::abi::{Abi, FIRST_VARIANT}; use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt}; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; use rustc_trait_selection::traits::{self, misc::type_allowed_to_implement_copy}; use crate::nonstandard_style::{method_context, MethodLateContext};"} {"_id":"doc-en-rust-f9b49c64a5dd752173a312fc981fa90f666d649e95698e2751d64cf2aa87e9e9","title":"","text":"if ty.is_copy_modulo_regions(cx.tcx, param_env) { return; } if type_implements_negative_copy_modulo_regions(cx.tcx, ty, param_env) { return; } // We shouldn't recommend implementing `Copy` on stateful things, // such as iterators."} {"_id":"doc-en-rust-56c820a632968938e0b04f79fcf45c273660c28612d677c71ac328679bb66568","title":"","text":"} } /// Check whether a `ty` has a negative `Copy` implementation, ignoring outlives constraints. fn type_implements_negative_copy_modulo_regions<'tcx>( tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, param_env: ty::ParamEnv<'tcx>, ) -> bool { let trait_ref = ty::TraitRef::new(tcx, tcx.require_lang_item(hir::LangItem::Copy, None), [ty]); let pred = ty::TraitPredicate { trait_ref, polarity: ty::ImplPolarity::Negative }; let obligation = traits::Obligation { cause: traits::ObligationCause::dummy(), param_env, recursion_depth: 0, predicate: ty::Binder::dummy(pred).to_predicate(tcx), }; tcx.infer_ctxt().build().predicate_must_hold_modulo_regions(&obligation) } declare_lint! { /// The `missing_debug_implementations` lint detects missing /// implementations of [`fmt::Debug`] for public types."} {"_id":"doc-en-rust-24892396c291ca234c5fcddbc1ebaa73e7c2768b65a8d1b89aec8d9929935f2d","title":"","text":" // Regression test for issue #101980. // Ensure that we don't suggest impl'ing `Copy` for a type if it already impl's `!Copy`. // check-pass #![feature(negative_impls)] #![deny(missing_copy_implementations)] pub struct Struct { pub field: i32, } impl !Copy for Struct {} fn main() {} "} {"_id":"doc-en-rust-02e3a766dff3bf66db915472ba62a57c8e018d242df50cb51cd72e1b481a2a34","title":"","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":"doc-en-rust-a8e21958f0ec6610380c4129acbb2817b2ea7b217afb9563e4e9fb14b3843957","title":"","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":"doc-en-rust-9fb0599d05137dd818c9e4b2c1e86f8ff2902c9f05836ff418a3af713785d9ea","title":"","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":"doc-en-rust-da1a6bed0f4116fac10eaaacba8e8642205cdfb824d58d4339339f2e45b9f222","title":"","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":"doc-en-rust-77734f58fb8629179652a8a9d0a77c01c314c1309a90a82c4ac9425542a88265","title":"","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":"doc-en-rust-92afa4c517d574ea738d12ce891ab5dda486a706939b9b6862f9c5fb70ee3f1d","title":"","text":"ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span, _ => return, }; match ( trait_ref.skip_binder().self_ty().kind(), trait_ref.skip_binder().substs.type_at(1).kind(), ) { (ty::Float(_), ty::Infer(InferTy::IntVar(_))) => { err.span_suggestion_verbose( rhs_span.shrink_to_hi(), \"consider using a floating-point literal by writing it with `.0`\", \".0\", Applicability::MaybeIncorrect, ); } _ => {} if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind() && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind() { err.span_suggestion_verbose( rhs_span.shrink_to_hi(), \"consider using a floating-point literal by writing it with `.0`\", \".0\", Applicability::MaybeIncorrect, ); } }"} {"_id":"doc-en-rust-fda898e805a955831d4473dde614d16dcebde74e7ee066da515af713ceff86d0","title":"","text":" // normalize-stderr-test \"loaded from .*libcore-.*.rlib\" -> \"loaded from SYSROOT/libcore-*.rlib\" #![feature(lang_items)] #[lang=\"sized\"] trait Sized { } //~ ERROR found duplicate lang item `sized` fn ref_Struct(self: &Struct, f: &u32) -> &u32 { //~^ ERROR `self` parameter is only allowed in associated functions //~| ERROR cannot find type `Struct` in this scope //~| ERROR mismatched types let x = x << 1; //~^ ERROR the size for values of type `{integer}` cannot be known at compilation time //~| ERROR cannot find value `x` in this scope } fn main() {} "} {"_id":"doc-en-rust-47144db209e1940cb25db3df84cb41043230e6bbfc1ec86596306b61d4330788","title":"","text":" error: `self` parameter is only allowed in associated functions --> $DIR/issue-102989.rs:7:15 | LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 { | ^^^^ not semantically valid as function parameter | = note: associated functions are those in `impl` or `trait` definitions error[E0412]: cannot find type `Struct` in this scope --> $DIR/issue-102989.rs:7:22 | LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 { | ^^^^^^ not found in this scope error[E0425]: cannot find value `x` in this scope --> $DIR/issue-102989.rs:11:13 | LL | let x = x << 1; | ^ help: a local variable with a similar name exists: `f` error[E0152]: found duplicate lang item `sized` --> $DIR/issue-102989.rs:5:1 | LL | trait Sized { } | ^^^^^^^^^^^ | = note: the lang item is first defined in crate `core` (which `std` depends on) = note: first definition in `core` loaded from SYSROOT/libcore-*.rlib = note: second definition in the local crate (`issue_102989`) error[E0277]: the size for values of type `{integer}` cannot be known at compilation time --> $DIR/issue-102989.rs:11:15 | LL | let x = x << 1; | ^^ doesn't have a size known at compile-time | = help: the trait `std::marker::Sized` is not implemented for `{integer}` error[E0308]: mismatched types --> $DIR/issue-102989.rs:7:42 | LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 { | ---------- ^^^^ expected `&u32`, found `()` | | | implicitly returns `()` as its body has no tail or `return` expression | note: consider returning one of these bindings --> $DIR/issue-102989.rs:7:30 | LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 { | ^ ... LL | let x = x << 1; | ^ error: aborting due to 6 previous errors Some errors have detailed explanations: E0152, E0277, E0308, E0412, E0425. For more information about an error, try `rustc --explain E0152`. "} {"_id":"doc-en-rust-a9c6233e752f9fb8cb0e7282740f64cf89ab6f060a66c16bc4dabea907ce7d03","title":"","text":"if self.eat(&token::ModSep) { self.parse_use_tree_glob_or_nested()? } else { // Recover from using a colon as path separator. while self.eat_noexpect(&token::Colon) { self.struct_span_err(self.prev_token.span, \"expected `::`, found `:`\") .span_suggestion_short( self.prev_token.span, \"use double colon\", \"::\", Applicability::MachineApplicable, ) .note_once(\"import paths are delimited using `::`\") .emit(); // We parse the rest of the path and append it to the original prefix. self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?; prefix.span = lo.to(self.prev_token.span); } UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID) } };"} {"_id":"doc-en-rust-fa5b03ec9710e45f391403c90b13846340e9993e03218ee5f434be34949992a6","title":"","text":" // Recover from using a colon as a path separator. use std::process:Command; //~^ ERROR expected `::`, found `:` use std:fs::File; //~^ ERROR expected `::`, found `:` use std:collections:HashMap; //~^ ERROR expected `::`, found `:` //~| ERROR expected `::`, found `:` fn main() { } "} {"_id":"doc-en-rust-df889ba31afc3a50434345e10a55e3c7659c210560e588d2096ca81c05e504b1","title":"","text":" error: expected `::`, found `:` --> $DIR/use-colon-as-mod-sep.rs:3:17 | LL | use std::process:Command; | ^ help: use double colon | = note: import paths are delimited using `::` error: expected `::`, found `:` --> $DIR/use-colon-as-mod-sep.rs:5:8 | LL | use std:fs::File; | ^ help: use double colon error: expected `::`, found `:` --> $DIR/use-colon-as-mod-sep.rs:7:8 | LL | use std:collections:HashMap; | ^ help: use double colon error: expected `::`, found `:` --> $DIR/use-colon-as-mod-sep.rs:7:20 | LL | use std:collections:HashMap; | ^ help: use double colon error: aborting due to 4 previous errors "} {"_id":"doc-en-rust-58e9ff172c034e4991db0bcc12b7e9048afa66bde5bc5b560f93f53a1b93d50a","title":"","text":"#include_next // mingw 4.0.x has broken headers (#9246) but mingw-w64 does not. #if defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION == 4 typedef struct pollfd { SOCKET fd; short events;"} {"_id":"doc-en-rust-9e89ecf45186ab847f40849727c621b7a719d62a9429c54490cff10fc0ba0a71","title":"","text":"} WSAPOLLFD, *PWSAPOLLFD, *LPWSAPOLLFD; #endif #endif // _FIX_WINSOCK2_H "} {"_id":"doc-en-rust-837eeb911501a35af3d3c2cac8b9dc5eb77d393cb1e24e916b69cbce45a4b1f8","title":"","text":"use smallvec::{smallvec, SmallVec}; use rustc_span::source_map::{respan, Spanned}; use std::assert_matches::debug_assert_matches; use std::collections::{hash_map::Entry, BTreeSet}; use std::mem::{replace, take};"} {"_id":"doc-en-rust-4fbf3e80629176effa7581f4a0f3d57e82e6f697ef0423f0de619c38d63cbf3e","title":"","text":"/// They will be used to determine the correct lifetime for the fn return type. /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named /// lifetimes. lifetime_elision_candidates: Option>, lifetime_elision_candidates: Option>, /// The trait that the current context can refer to. current_trait_ref: Option<(Module<'a>, TraitRef)>,"} {"_id":"doc-en-rust-9b1328d7b3a6cba5c7fa35efd8b23e6f7c749f653154697886a4ecedaf382f5b","title":"","text":"match res { LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => { if let Some(ref mut candidates) = self.lifetime_elision_candidates { candidates.insert(res, candidate); candidates.push((res, candidate)); } } LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}"} {"_id":"doc-en-rust-fa0f8312b9ad0beff90fd9077d1f9bfeff45aaf7aec38cc7af940920851565a4","title":"","text":"has_self: bool, inputs: impl Iterator, &'ast Ty)>, ) -> Result, Vec)> { let outer_candidates = replace(&mut self.lifetime_elision_candidates, Some(Default::default())); enum Elision { /// We have not found any candidate. None, /// We have a candidate bound to `self`. Self_(LifetimeRes), /// We have a candidate bound to a parameter. Param(LifetimeRes), /// We failed elision. Err, } let mut elision_lifetime = None; let mut lifetime_count = 0; // Save elision state to reinstate it later. let outer_candidates = self.lifetime_elision_candidates.take(); // Result of elision. let mut elision_lifetime = Elision::None; // Information for diagnostics. let mut parameter_info = Vec::new(); let mut all_candidates = Vec::new(); let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; for (index, (pat, ty)) in inputs.enumerate() {"} {"_id":"doc-en-rust-189261a499bb08681b9183b981e66e8bde9cb3111e2695c6a972222b68383b08","title":"","text":"this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings); } }); // Record elision candidates only for this parameter. debug_assert_matches!(self.lifetime_elision_candidates, None); self.lifetime_elision_candidates = Some(Default::default()); self.visit_ty(ty); let local_candidates = self.lifetime_elision_candidates.take(); if let Some(ref candidates) = self.lifetime_elision_candidates { let new_count = candidates.len(); let local_count = new_count - lifetime_count; if local_count != 0 { if let Some(candidates) = local_candidates { let distinct: FxHashSet<_> = candidates.iter().map(|(res, _)| *res).collect(); let lifetime_count = distinct.len(); if lifetime_count != 0 { parameter_info.push(ElisionFnParameter { index, ident: if let Some(pat) = pat && let PatKind::Ident(_, ident, _) = pat.kind {"} {"_id":"doc-en-rust-6c449252388b9c1801c7e335801bcfec3bbd9412ca05e481c24f75e38aa91054","title":"","text":"} else { None }, lifetime_count: local_count, lifetime_count, span: ty.span, }); all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| { match candidate { LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => { None } LifetimeElisionCandidate::Missing(missing) => Some(missing), } })); } let mut distinct_iter = distinct.into_iter(); if let Some(res) = distinct_iter.next() { match elision_lifetime { // We are the first parameter to bind lifetimes. Elision::None => { if distinct_iter.next().is_none() { // We have a single lifetime => success. elision_lifetime = Elision::Param(res) } else { // We have have multiple lifetimes => error. elision_lifetime = Elision::Err; } } // We have 2 parameters that bind lifetimes => error. Elision::Param(_) => elision_lifetime = Elision::Err, // `self` elision takes precedence over everything else. Elision::Self_(_) | Elision::Err => {} } } lifetime_count = new_count; } // Handle `self` specially. if index == 0 && has_self { let self_lifetime = self.find_lifetime_for_self(ty); if let Set1::One(lifetime) = self_lifetime { elision_lifetime = Some(lifetime); self.lifetime_elision_candidates = None; // We found `self` elision. elision_lifetime = Elision::Self_(lifetime); } else { self.lifetime_elision_candidates = Some(Default::default()); lifetime_count = 0; // We do not have `self` elision: disregard the `Elision::Param` that we may // have found. elision_lifetime = Elision::None; } } debug!(\"(resolving function / closure) recorded parameter\"); } let all_candidates = replace(&mut self.lifetime_elision_candidates, outer_candidates); debug!(?all_candidates); // Reinstate elision state. debug_assert_matches!(self.lifetime_elision_candidates, None); self.lifetime_elision_candidates = outer_candidates; if let Some(res) = elision_lifetime { if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime { return Ok(res); } // We do not have a `self` candidate, look at the full list. let all_candidates = all_candidates.unwrap(); if all_candidates.len() == 1 { Ok(*all_candidates.first().unwrap().0) } else { let all_candidates = all_candidates .into_iter() .filter_map(|(_, candidate)| match candidate { LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => None, LifetimeElisionCandidate::Missing(missing) => Some(missing), }) .collect(); Err((all_candidates, parameter_info)) } // We do not have a candidate. Err((all_candidates, parameter_info)) } /// List all the lifetimes that appear in the provided type."} {"_id":"doc-en-rust-4d395f6c0c9e5bccc7cde6c602a6be43fbe9fe7fb958dffaf6ffa5799c06a707","title":"","text":"// Do not account for the parameters we just bound for function lifetime elision. if let Some(ref mut candidates) = self.lifetime_elision_candidates { for (_, res) in function_lifetime_rib.bindings.values() { candidates.remove(res); candidates.retain(|(r, _)| r != res); } }"} {"_id":"doc-en-rust-fe57bb6977b9fc0c261f90e7f63aa99b75e2faf69723f81d747f9eb2d0510874","title":"","text":"//! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`. #![doc(html_root_url = \"https://doc.rust-lang.org/nightly/nightly-rustc/\")] #![feature(assert_matches)] #![feature(box_patterns)] #![feature(drain_filter)] #![feature(if_let_guard)]"} {"_id":"doc-en-rust-b6121ff6258fa2a1cab677cd83456d4e8eb9aa5a3dfb766e909d334b6d4b8c61","title":"","text":"panic!() } fn l<'a>(_: &'a str, _: &'a str) -> &str { \"\" } //~^ ERROR missing lifetime specifier // This is ok because both `'a` are for the same parameter. fn m<'a>(_: &'a Foo<'a>) -> &str { \"\" } fn main() {}"} {"_id":"doc-en-rust-af6146891cf519acdecd15708dc0a1eccd9fde4de714be1fa2bb414b830bfed9","title":"","text":"LL | fn k<'a, T: WithLifetime<'a>>(_x: T::Output) -> &'a isize { | ++ error: aborting due to 6 previous errors error[E0106]: missing lifetime specifier --> $DIR/lifetime-elision-return-type-requires-explicit-lifetime.rs:45:37 | LL | fn l<'a>(_: &'a str, _: &'a str) -> &str { \"\" } | ------- ------- ^ expected named lifetime parameter | = help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments help: consider using the `'a` lifetime | LL | fn l<'a>(_: &'a str, _: &'a str) -> &'a str { \"\" } | ++ error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0106`."} {"_id":"doc-en-rust-b61f4d4b794d49b9cc3c6f043867c4ae93b1ca9a020a32bd11707036750f2bef","title":"","text":"// FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <= // 1, where the method versions of these operations are not inlined. use intrinsics::{ cttz_nonzero, exact_div, unchecked_rem, unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub, cttz_nonzero, exact_div, mul_with_overflow, unchecked_rem, unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub, }; /// Calculate multiplicative modular inverse of `x` modulo `m`."} {"_id":"doc-en-rust-7e92a16472b175cdf275debbb8f28c131923b7bd0804e0e3b35593e73a3c77fb","title":"","text":"const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15]; /// Modulo for which the `INV_TABLE_MOD_16` is intended. const INV_TABLE_MOD: usize = 16; /// INV_TABLE_MOD² const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD; let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize; // SAFETY: `m` is required to be a power-of-two, hence non-zero. let m_minus_one = unsafe { unchecked_sub(m, 1) }; if m <= INV_TABLE_MOD { table_inverse & m_minus_one } else { // We iterate \"up\" using the following formula: // // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$ let mut inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize; let mut mod_gate = INV_TABLE_MOD; // We iterate \"up\" using the following formula: // // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$ // // This application needs to be applied at least until `2²ⁿ ≥ m`, at which point we can // finally reduce the computation to our desired `m` by taking `inverse mod m`. // // This computation is `O(log log m)`, which is to say, that on 64-bit machines this loop // will always finish in at most 4 iterations. loop { // y = y * (2 - xy) mod n // // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`. let mut inverse = table_inverse; let mut going_mod = INV_TABLE_MOD_SQUARED; loop { // y = y * (2 - xy) mod n // // Note, that we use wrapping operations here intentionally – the original formula // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod // usize::MAX` instead, because we take the result `mod n` at the end // anyway. inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse))); if going_mod >= m { return inverse & m_minus_one; } going_mod = wrapping_mul(going_mod, going_mod); // Note, that we use wrapping operations here intentionally – the original formula // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod // usize::MAX` instead, because we take the result `mod n` at the end // anyway. if mod_gate >= m { break; } inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse))); let (new_gate, overflow) = mul_with_overflow(mod_gate, mod_gate); if overflow { break; } mod_gate = new_gate; } inverse & m_minus_one } let addr = p.addr();"} {"_id":"doc-en-rust-cfd2b472a1aa37b156c4d75892890f70d9522e782e8fd815d3d0a530658959fb","title":"","text":"} #[test] fn align_offset_issue_103361() { #[cfg(target_pointer_width = \"64\")] const SIZE: usize = 1 << 47; #[cfg(target_pointer_width = \"32\")] const SIZE: usize = 1 << 30; #[cfg(target_pointer_width = \"16\")] const SIZE: usize = 1 << 13; struct HugeSize([u8; SIZE - 1]); let _ = (SIZE as *const HugeSize).align_offset(SIZE); } #[test] fn offset_from() { let mut a = [0; 5]; let ptr1: *mut i32 = &mut a[1];"} {"_id":"doc-en-rust-a02db5cb0c5862407fa3cad72dacc7d9cc16c640206d9dad7cfcd8bbd746a4d5","title":"","text":"add_constraints(&infcx, region_bound_pairs); infcx.process_registered_region_obligations( outlives_environment.region_bound_pairs(), param_env, ); let errors = infcx.resolve_regions(&outlives_environment); debug!(?errors, \"errors\");"} {"_id":"doc-en-rust-8f3f755e0adf34f4068994b7c1d3c6f2048992ed82320af639256093a62f79c9","title":"","text":" trait TraitA { type TypeA; } trait TraitD { type TypeD; } pub trait TraitB { type TypeB: TraitD; fn f(_: &::TypeD); } pub trait TraitC { type TypeC<'a>: TraitB; fn g<'a>(_: &< as TraitB>::TypeB as TraitA>::TypeA); //~^ ERROR the trait bound `<>::TypeC<'a> as TraitB>::TypeB: TraitA` is not satisfied } fn main() {} "} {"_id":"doc-en-rust-d6d48d86ce7d3d39944d489bf261342b568eb08e17d3bee711a8aee371f63c1c","title":"","text":" error[E0277]: the trait bound `<>::TypeC<'a> as TraitB>::TypeB: TraitA` is not satisfied --> $DIR/issue-103573.rs:18:5 | LL | fn g<'a>(_: &< as TraitB>::TypeB as TraitA>::TypeA); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TraitA` is not implemented for `<>::TypeC<'a> as TraitB>::TypeB` | help: consider further restricting the associated type | LL | fn g<'a>(_: &< as TraitB>::TypeB as TraitA>::TypeA) where <>::TypeC<'a> as TraitB>::TypeB: TraitA; | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-f92517481c39cce4c818af4d9a5c196dcc3900cb2866b062e2e2ff6c8e6ff0aa","title":"","text":"}); if check_params && let Some(args) = path.segments.last().unwrap().args { let params_in_repr = tcx.params_in_repr(def_id); for (i, arg) in args.args.iter().enumerate() { // the domain size check is needed because the HIR may not be well-formed at this point for (i, arg) in args.args.iter().enumerate().take(params_in_repr.domain_size()) { if let hir::GenericArg::Type(ty) = arg && params_in_repr.contains(i as u32) { find_item_ty_spans(tcx, ty, needle, spans, seen_representable); }"} {"_id":"doc-en-rust-4b78a8edf4917c34202be60ba8343b377be5ce2c3368263a863bd7c0c1fe039a","title":"","text":" #![crate_type = \"lib\"] struct Apple((Apple, Option(Banana ? Citron))); //~^ ERROR invalid `?` in type //~| ERROR expected one of `)` or `,`, found `Citron` //~| ERROR cannot find type `Citron` in this scope [E0412] //~| ERROR parenthesized type parameters may only be used with a `Fn` trait [E0214] //~| ERROR recursive type `Apple` has infinite size [E0072] "} {"_id":"doc-en-rust-214e132c49b265cedd29b99033be89db0bddf44e3ba013806046b6f06b09995d","title":"","text":" error: invalid `?` in type --> $DIR/issue-103748-ICE-wrong-braces.rs:3:36 | LL | struct Apple((Apple, Option(Banana ? Citron))); | ^ `?` is only allowed on expressions, not types | help: if you meant to express that the type might not contain a value, use the `Option` wrapper type | LL | struct Apple((Apple, Option(Option Citron))); | +++++++ ~ error: expected one of `)` or `,`, found `Citron` --> $DIR/issue-103748-ICE-wrong-braces.rs:3:38 | LL | struct Apple((Apple, Option(Banana ? Citron))); | -^^^^^^ expected one of `)` or `,` | | | help: missing `,` error[E0412]: cannot find type `Citron` in this scope --> $DIR/issue-103748-ICE-wrong-braces.rs:3:38 | LL | struct Apple((Apple, Option(Banana ? Citron))); | ^^^^^^ not found in this scope error[E0214]: parenthesized type parameters may only be used with a `Fn` trait --> $DIR/issue-103748-ICE-wrong-braces.rs:3:22 | LL | struct Apple((Apple, Option(Banana ? Citron))); | ^^^^^^^^^^^^^^^^^^^^^^^ only `Fn` traits may use parentheses | help: use angle brackets instead | LL | struct Apple((Apple, Option)); | ~ ~ error[E0072]: recursive type `Apple` has infinite size --> $DIR/issue-103748-ICE-wrong-braces.rs:3:1 | LL | struct Apple((Apple, Option(Banana ? Citron))); | ^^^^^^^^^^^^ ----- recursive without indirection | help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle | LL | struct Apple((Box, Option(Banana ? Citron))); | ++++ + error: aborting due to 5 previous errors Some errors have detailed explanations: E0072, E0214, E0412. For more information about an error, try `rustc --explain E0072`. "} {"_id":"doc-en-rust-b9a5644be7969802135a608b20cb1c6f74015dd483e136bb26929cba6a40a2d3","title":"","text":"[submodule \"src/llvm-project\"] path = src/llvm-project url = https://github.com/rust-lang/llvm-project.git branch = rustc/15.0-2022-08-09 branch = rustc/15.0-2022-12-07 [submodule \"src/doc/embedded-book\"] path = src/doc/embedded-book url = https://github.com/rust-embedded/book.git"} {"_id":"doc-en-rust-017f997a7430e643d73dc38a0754e5c799d6b5b9b8fd5d2420559c9c1117e8b5","title":"","text":" Subproject commit a1232c451fc27173f8718e05d174b2503ca0b607 Subproject commit 3dfd4d93fa013e1c0578d3ceac5c8f4ebba4b6ec "} {"_id":"doc-en-rust-b0ba11d306adc9de6450acc368f432a7ff1985019abc4fef6e963b28e5d98133","title":"","text":" Subproject commit 3dfd4d93fa013e1c0578d3ceac5c8f4ebba4b6ec Subproject commit 9ad24035fea8d309753f5e39e6eb53d1d0eb39ce "} {"_id":"doc-en-rust-05acab0984f3fb697017dd8f06193a02ac9cd3abe3b8a71a79dd098e22ae42d1","title":"","text":"assert!(self_ty.is_some()); } } else { assert!(self_ty.is_none() && parent_substs.is_empty()); assert!(self_ty.is_none()); } let arg_count = Self::check_generic_arg_count("} {"_id":"doc-en-rust-7e6d7197e05ced1834aa5f04c986c38beff9078a34938b08d6dd037dad26106b","title":"","text":"// Check if we have an enum variant. let mut variant_resolution = None; if let ty::Adt(adt_def, _) = qself_ty.kind() { if let ty::Adt(adt_def, adt_substs) = qself_ty.kind() { if adt_def.is_enum() { let variant_def = adt_def .variants()"} {"_id":"doc-en-rust-3f94dcdc7615435c26d892b5dae1e889f15aa7e2c5ef2f3d0d3253002aa88c79","title":"","text":"let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, impl_) else { continue; }; // FIXME(inherent_associated_types): This does not substitute parameters. let ty = tcx.type_of(assoc_ty_did); let item_substs = self.create_substs_for_associated_item( span, assoc_ty_did, assoc_segment, adt_substs, ); let ty = tcx.bound_type_of(assoc_ty_did).subst(tcx, item_substs); return Ok((ty, DefKind::AssocTy, assoc_ty_did)); } }"} {"_id":"doc-en-rust-2258414bf7cfd8eeaa8a2beae452d601589f1f35170aa4c43b9db2b1985b6149","title":"","text":" // check-pass #![feature(inherent_associated_types)] #![allow(incomplete_features)] struct S(T); impl S { type P = T; } fn main() { type A = S<()>::P; let _: A = (); } "} {"_id":"doc-en-rust-7db83585bd4e6e58443a34c66c26106c181e90406627654f892e0ab9d272f6d3","title":"","text":"} // see if we can satisfy using an inherent associated type for impl_ in tcx.inherent_impls(adt_def.did()) { let assoc_ty = tcx.associated_items(impl_).find_by_name_and_kind( tcx, assoc_ident, ty::AssocKind::Type, *impl_, ); if let Some(assoc_ty) = assoc_ty { let ty = tcx.type_of(assoc_ty.def_id); return Ok((ty, DefKind::AssocTy, assoc_ty.def_id)); } for &impl_ in tcx.inherent_impls(adt_def.did()) { let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, impl_) else { continue; }; // FIXME(inherent_associated_types): This does not substitute parameters. let ty = tcx.type_of(assoc_ty_did); return Ok((ty, DefKind::AssocTy, assoc_ty_did)); } }"} {"_id":"doc-en-rust-c81afa26c7ab7af9d2d4f42166a14a2c1de6220b56ffd83b4c9b9fec5b30d104","title":"","text":"}; let trait_did = bound.def_id(); let (assoc_ident, def_scope) = tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id); // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead // of calling `filter_by_name_and_kind`. let item = tcx.associated_items(trait_did).in_definition_order().find(|i| { i.kind.namespace() == Namespace::TypeNS && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident }); // Assume that if it's not matched, there must be a const defined with the same name // but it was used in a type position. let Some(item) = item else { let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) else { // Assume that if it's not matched, there must be a const defined with the same name // but it was used in a type position. let msg = format!(\"found associated const `{assoc_ident}` when type was expected\"); let guar = tcx.sess.struct_span_err(span, &msg).emit(); return Err(guar); }; let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound); let ty = self.projected_ty_from_poly_trait_ref(span, assoc_ty_did, assoc_segment, bound); let ty = self.normalize_ty(span, ty); let kind = DefKind::AssocTy; if !item.visibility(tcx).is_accessible_from(def_scope, tcx) { let kind = kind.descr(item.def_id); let msg = format!(\"{} `{}` is private\", kind, assoc_ident); tcx.sess .struct_span_err(span, &msg) .span_label(span, &format!(\"private {}\", kind)) .emit(); } tcx.check_stability(item.def_id, Some(hir_ref_id), span, None); if let Some(variant_def_id) = variant_resolution { tcx.struct_span_lint_hir( AMBIGUOUS_ASSOCIATED_ITEMS,"} {"_id":"doc-en-rust-ba8ffb29554e947e2a550289a95006fb89181d5aa6f8d59a11daf3424f68a062","title":"","text":"}; could_refer_to(DefKind::Variant, variant_def_id, \"\"); could_refer_to(kind, item.def_id, \" also\"); could_refer_to(DefKind::AssocTy, assoc_ty_did, \" also\"); lint.span_suggestion( span,"} {"_id":"doc-en-rust-9e3fe72290f34d2b427a204710b1f5f4dcc2ca9bfec70242078c0d5a8e319b85","title":"","text":"}, ); } Ok((ty, kind, item.def_id)) Ok((ty, DefKind::AssocTy, assoc_ty_did)) } fn lookup_assoc_ty( &self, ident: Ident, block: hir::HirId, span: Span, scope: DefId, ) -> Option { let tcx = self.tcx(); let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block); // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead // of calling `find_by_name_and_kind`. let item = tcx.associated_items(scope).in_definition_order().find(|i| { i.kind.namespace() == Namespace::TypeNS && i.ident(tcx).normalize_to_macros_2_0() == ident })?; let kind = DefKind::AssocTy; if !item.visibility(tcx).is_accessible_from(def_scope, tcx) { let kind = kind.descr(item.def_id); let msg = format!(\"{kind} `{ident}` is private\"); let def_span = self.tcx().def_span(item.def_id); tcx.sess .struct_span_err_with_code(span, &msg, rustc_errors::error_code!(E0624)) .span_label(span, &format!(\"private {kind}\")) .span_label(def_span, &format!(\"{kind} defined here\")) .emit(); } tcx.check_stability(item.def_id, Some(block), span, None); Some(item.def_id) } fn qpath_to_ty("} {"_id":"doc-en-rust-5f544aed759098fa7984613b398c12008d0b1244718b7a2546d0301b1a032d81","title":"","text":" #![feature(inherent_associated_types)] #![allow(incomplete_features)] mod m { pub struct T; impl T { type P = (); } } type U = m::T::P; //~ ERROR associated type `P` is private mod n { pub mod n { pub struct T; impl T { pub(super) type P = bool; } } type U = n::T::P; } type V = n::n::T::P; //~ ERROR associated type `P` is private fn main() {} "} {"_id":"doc-en-rust-201d247bbff9c8d0c61ea58f05f3e53aecc6939ecd33534dab1aada1d3338ab8","title":"","text":" error[E0624]: associated type `P` is private --> $DIR/assoc-inherent-private.rs:10:10 | LL | type P = (); | ------ associated type defined here ... LL | type U = m::T::P; | ^^^^^^^ private associated type error[E0624]: associated type `P` is private --> $DIR/assoc-inherent-private.rs:21:10 | LL | pub(super) type P = bool; | ----------------- associated type defined here ... LL | type V = n::n::T::P; | ^^^^^^^^^^ private associated type error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0624`. "} {"_id":"doc-en-rust-b236a15281c4b12f62e28aeaa0a66898eed5f8eabe6b81965ee0f84502b71648","title":"","text":" // aux-crate:aux=assoc-inherent-unstable.rs // edition: 2021 type Data = aux::Owner::Data; //~ ERROR use of unstable library feature 'data' fn main() {} "} {"_id":"doc-en-rust-be37deacec43611c6fcee98a0c274e9f591b4543595a0e3e8af660b5f511e102","title":"","text":" error[E0658]: use of unstable library feature 'data' --> $DIR/assoc-inherent-unstable.rs:4:13 | LL | type Data = aux::Owner::Data; | ^^^^^^^^^^^^^^^^ | = help: add `#![feature(data)]` to the crate attributes to enable error: aborting due to previous error For more information about this error, try `rustc --explain E0658`. "} {"_id":"doc-en-rust-c9a9b6dc76ca22832af92b9ada0d913cd913d12c61127e5132d732717cb491d1","title":"","text":" #![feature(staged_api)] #![feature(inherent_associated_types)] #![stable(feature = \"main\", since = \"1.0.0\")] #[stable(feature = \"main\", since = \"1.0.0\")] pub struct Owner; impl Owner { #[unstable(feature = \"data\", issue = \"none\")] pub type Data = (); } "} {"_id":"doc-en-rust-691cbe4bbc0722e43948ac73abafbfb7025c00a41869e050db05574037d93bcb","title":"","text":"LL | let _: S::C; | ^^^^ help: use fully-qualified syntax: `::C` error: associated type `A` is private error[E0624]: associated type `A` is private --> $DIR/item-privacy.rs:119:12 | LL | type A = u8; | ------ associated type defined here ... LL | let _: T::A; | ^^^^ private associated type"} {"_id":"doc-en-rust-0e133ec912fd41620cc6adaf8104b1cc7ea9a392f56b078710cbf8929b9f5cc3","title":"","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":"doc-en-rust-b3c6bcc568d68497bd06f1b68f2c2b5969e2be42cf7255c4c6d1c624c3cb3640","title":"","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":"doc-en-rust-d614942aa4e737dbbd9da257ae6155c69f597cb5039b2938495dc8677098511e","title":"","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":"doc-en-rust-d26cc5d6d75fa090c3874abcf870d28893afb8d69177b689584e381f5f9e4c24","title":"","text":"}; e_flags } Architecture::Riscv64 if sess.target.options.features.contains(\"+d\") => { // copied from `riscv64-linux-gnu-gcc foo.c -c`, note though // that the `+d` target feature represents whether the double // float abi is enabled. let e_flags = elf::EF_RISCV_RVC | elf::EF_RISCV_FLOAT_ABI_DOUBLE; Architecture::Riscv32 | Architecture::Riscv64 => { // Source: https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/079772828bd10933d34121117a222b4cc0ee2200/riscv-elf.adoc let mut e_flags: u32 = 0x0; let features = &sess.target.options.features; // Check if compressed is enabled if features.contains(\"+c\") { e_flags |= elf::EF_RISCV_RVC; } // Select the appropriate floating-point ABI if features.contains(\"+d\") { e_flags |= elf::EF_RISCV_FLOAT_ABI_DOUBLE; } else if features.contains(\"+f\") { e_flags |= elf::EF_RISCV_FLOAT_ABI_SINGLE; } else { e_flags |= elf::EF_RISCV_FLOAT_ABI_SOFT; } e_flags } _ => 0,"} {"_id":"doc-en-rust-3d3cafcfac938777cdfce1914731da0fb34128abf30b62ee56c7ecb880a6b66a","title":"","text":"// In the algorithm above, we can change // cast(relative_tag) + niche_variants.start() // into // cast(tag) + (niche_variants.start() - niche_start) // cast(tag + (niche_variants.start() - niche_start)) // if either the casted type is no larger than the original // type, or if the niche values are contiguous (in either the // signed or unsigned sense). let can_incr_after_cast = cast_smaller || niches_ule || niches_sle; let can_incr = cast_smaller || niches_ule || niches_sle; let data_for_boundary_niche = || -> Option<(IntPredicate, u128)> { if !can_incr_after_cast { if !can_incr { None } else if niche_start == low_unsigned { Some((IntPredicate::IntULE, niche_end))"} {"_id":"doc-en-rust-33356910c92947902932ddfe4d09047e084649fa0b789d9e3b41b07434d7f4f3","title":"","text":"// The algorithm is now this: // is_niche = tag <= niche_end // discr = if is_niche { // cast(tag) + (niche_variants.start() - niche_start) // cast(tag + (niche_variants.start() - niche_start)) // } else { // untagged_variant // } // (the first line may instead be tag >= niche_start, // and may be a signed or unsigned comparison) // The arithmetic must be done before the cast, so we can // have the correct wrapping behavior. See issue #104519 for // the consequences of getting this wrong. let is_niche = bx.icmp(predicate, tag, bx.cx().const_uint_big(tag_llty, constant)); let delta = (niche_variants.start().as_u32() as u128).wrapping_sub(niche_start); let incr_tag = if delta == 0 { tag } else { bx.add(tag, bx.cx().const_uint_big(tag_llty, delta)) }; let cast_tag = if cast_smaller { bx.intcast(tag, cast_to, false) bx.intcast(incr_tag, cast_to, false) } else if niches_ule { bx.zext(tag, cast_to) bx.zext(incr_tag, cast_to) } else { bx.sext(tag, cast_to) bx.sext(incr_tag, cast_to) }; let delta = (niche_variants.start().as_u32() as u128).wrapping_sub(niche_start); (is_niche, cast_tag, delta) (is_niche, cast_tag, 0) } else { // The special cases don't apply, so we'll have to go with // the general algorithm."} {"_id":"doc-en-rust-d65a3fcee363818f43a04549cafd1029864c9a16471ac97d11793e45d91b9744","title":"","text":"// CHECK: define i8 @match1{{.*}} // CHECK-NEXT: start: // CHECK-NEXT: %1 = icmp ugt i8 %0, 1 // CHECK-NEXT: %2 = zext i8 %0 to i64 // CHECK-NEXT: %3 = add nsw i64 %2, -1 // CHECK-NEXT: %_2 = select i1 %1, i64 %3, i64 0 // CHECK-NEXT: switch i64 %_2, label {{.*}} [ // CHECK-NEXT: %1 = {{.*}}call i8 @llvm.usub.sat.i8(i8 %0, i8 1) // CHECK-NEXT: switch i8 %1, label {{.*}} [ #[no_mangle] pub fn match1(e: Enum1) -> u8 { use Enum1::*;"} {"_id":"doc-en-rust-3ca7a30377fb32a30f1ff3ec6cb3d1b02296da28685581689b7bae690c0043d9","title":"","text":" // run-pass #![allow(dead_code)] enum OpenResult { Ok(()), Err(()), TransportErr(TransportErr), } #[repr(i32)] enum TransportErr { UnknownMethod = -2, } #[inline(never)] fn some_match(result: OpenResult) -> u8 { match result { OpenResult::Ok(()) => 0, _ => 1, } } fn main() { let result = OpenResult::Ok(()); assert_eq!(some_match(result), 0); let result = OpenResult::Ok(()); match result { OpenResult::Ok(()) => (), _ => unreachable!(\"message a\"), } match result { OpenResult::Ok(()) => (), _ => unreachable!(\"message b\"), } } "} {"_id":"doc-en-rust-46ce4db73d3ea20d2548c3b8e7598c1d8948404f32cab4b2385916eedb87bf13","title":"","text":"} } /// Create an `Rc<[T]>` by reusing the underlying memory /// of a `Vec`. This will return the vector if the existing allocation /// is not large enough. #[cfg(not(no_global_oom_handling))] fn try_from_vec_in_place(mut v: Vec) -> Result, Vec> { let layout_elements = Layout::array::(v.len()).unwrap(); let layout_allocation = Layout::array::(v.capacity()).unwrap(); let layout_rcbox = rcbox_layout_for_value_layout(layout_elements); let mut ptr = NonNull::new(v.as_mut_ptr()).expect(\"`Vec` stores `NonNull`\"); if layout_rcbox.size() > layout_allocation.size() || layout_rcbox.align() > layout_allocation.align() { // Can't fit - calling `grow` would involve `realloc` // (which copies the elements), followed by copying again. return Err(v); } if layout_rcbox.size() < layout_allocation.size() || layout_rcbox.align() < layout_allocation.align() { // We need to shrink the allocation so that it fits // https://doc.rust-lang.org/nightly/std/alloc/trait.Allocator.html#memory-fitting // SAFETY: // - Vec allocates by requesting `Layout::array::(capacity)`, so this capacity matches // - `layout_rcbox` is smaller // If this fails, the ownership has not been transferred if let Ok(p) = unsafe { Global.shrink(ptr.cast(), layout_allocation, layout_rcbox) } { ptr = p.cast(); } else { return Err(v); } } // Make sure the vec's memory isn't deallocated now let v = mem::ManuallyDrop::new(v); let ptr: *mut RcBox<[T]> = ptr::slice_from_raw_parts_mut(ptr.as_ptr(), v.len()) as _; unsafe { ptr::copy(ptr.cast::(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); ptr::write(&mut (*ptr).strong, Cell::new(1)); ptr::write(&mut (*ptr).weak, Cell::new(1)); Ok(Self::from_ptr(ptr)) } } /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size. /// /// Behavior is undefined should the size be wrong."} {"_id":"doc-en-rust-d46532ff3bb71345b6de2294fbd0d7ccfd79a2938a1ac87d2a3c0801b1bd9479","title":"","text":"/// assert_eq!(vec![1, 2, 3], *shared); /// ``` #[inline] fn from(v: Vec) -> Rc<[T]> { match Rc::try_from_vec_in_place(v) { Ok(rc) => rc, Err(mut v) => { unsafe { let rc = Rc::copy_from_slice(&v); // Allow the Vec to free its memory, but not destroy its contents v.set_len(0); rc } } fn from(mut v: Vec) -> Rc<[T]> { unsafe { let rc = Rc::copy_from_slice(&v); // Allow the Vec to free its memory, but not destroy its contents v.set_len(0); rc } } }"} {"_id":"doc-en-rust-6a229649cf4995ec1fa3cf3c587edc3cb98b202687f56678ce6487bb18a81d7a","title":"","text":"} } /// Create an `Arc<[T]>` by reusing the underlying memory /// of a `Vec`. This will return the vector if the existing allocation /// is not large enough. #[cfg(not(no_global_oom_handling))] fn try_from_vec_in_place(mut v: Vec) -> Result, Vec> { let layout_elements = Layout::array::(v.len()).unwrap(); let layout_allocation = Layout::array::(v.capacity()).unwrap(); let layout_arcinner = arcinner_layout_for_value_layout(layout_elements); let mut ptr = NonNull::new(v.as_mut_ptr()).expect(\"`Vec` stores `NonNull`\"); if layout_arcinner.size() > layout_allocation.size() || layout_arcinner.align() > layout_allocation.align() { // Can't fit - calling `grow` would involve `realloc` // (which copies the elements), followed by copying again. return Err(v); } if layout_arcinner.size() < layout_allocation.size() || layout_arcinner.align() < layout_allocation.align() { // We need to shrink the allocation so that it fits // https://doc.rust-lang.org/nightly/std/alloc/trait.Allocator.html#memory-fitting // SAFETY: // - Vec allocates by requesting `Layout::array::(capacity)`, so this capacity matches // - `layout_arcinner` is smaller // If this fails, the ownership has not been transferred if let Ok(p) = unsafe { Global.shrink(ptr.cast(), layout_allocation, layout_arcinner) } { ptr = p.cast(); } else { return Err(v); } } // Make sure the vec's memory isn't deallocated now let v = mem::ManuallyDrop::new(v); let ptr: *mut ArcInner<[T]> = ptr::slice_from_raw_parts_mut(ptr.as_ptr(), v.len()) as _; unsafe { ptr::copy(ptr.cast::(), &mut (*ptr).data as *mut [T] as *mut T, v.len()); ptr::write(&mut (*ptr).strong, atomic::AtomicUsize::new(1)); ptr::write(&mut (*ptr).weak, atomic::AtomicUsize::new(1)); Ok(Self::from_ptr(ptr)) } } /// Constructs an `Arc<[T]>` from an iterator known to be of a certain size. /// /// Behavior is undefined should the size be wrong."} {"_id":"doc-en-rust-5b09e84216ffa2f8f84d7a3d00a24a295487efb1421ab8620f4ba30609112f45","title":"","text":"/// assert_eq!(&[1, 2, 3], &shared[..]); /// ``` #[inline] fn from(v: Vec) -> Arc<[T]> { match Arc::try_from_vec_in_place(v) { Ok(rc) => rc, Err(mut v) => { unsafe { let rc = Arc::copy_from_slice(&v); // Allow the Vec to free its memory, but not destroy its contents v.set_len(0); rc } } fn from(mut v: Vec) -> Arc<[T]> { unsafe { let rc = Arc::copy_from_slice(&v); // Allow the Vec to free its memory, but not destroy its contents v.set_len(0); rc } } }"} {"_id":"doc-en-rust-58d07b82c23d5e115886fea22c1b77c33b1f7878c96b4053ab50ffce7eb6e229","title":"","text":"// `val` dropped here while still borrowed // borrow might be used here, when `val` is dropped and runs the `Drop` code for type `std::sync::Weak` } #[test] fn arc_from_vec_opt() { let mut v = Vec::with_capacity(64); v.push(0usize); let addr = v.as_ptr().cast::(); let arc: Arc<[_]> = v.into(); unsafe { assert_eq!( arc.as_ptr().cast::().offset_from(addr), (std::mem::size_of::() * 2) as isize, \"Vector allocation not reused\" ); } } "} {"_id":"doc-en-rust-f32929845634721c278676303fa5e5e820f5b7bb3352051311e4a40c6b12c0bf","title":"","text":"// `val` dropped here while still borrowed // borrow might be used here, when `val` is dropped and runs the `Drop` code for type `std::rc::Weak` } #[test] fn rc_from_vec_opt() { let mut v = Vec::with_capacity(64); v.push(0usize); let addr = v.as_ptr().cast::(); let rc: Rc<[_]> = v.into(); unsafe { assert_eq!( rc.as_ptr().cast::().offset_from(addr), (std::mem::size_of::() * 2) as isize, \"Vector allocation not reused\" ); } } "} {"_id":"doc-en-rust-18d0ba2194b8aae1052814daae004b78c68d16b597c3848965f3b322d5ce7204","title":"","text":"} ty::FnPtr(sig) => (sig, None), _ => { for arg in arg_exprs { self.check_expr(arg); } if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind && let [segment] = path.segments && let Some(mut diag) = self"} {"_id":"doc-en-rust-f4d908aa8b9cfa9fbbca9c326eb1b5813dbffd57524457b260c428ea675a8cf9","title":"","text":"expected: Expectation<'tcx>, ) -> Option> { if let [callee_expr, rest @ ..] = arg_exprs { let callee_ty = self.check_expr(callee_expr); let callee_ty = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)?; // First, do a probe with `IsSuggestion(true)` to avoid emitting // any strange errors. If it's successful, then we'll do a true // method lookup."} {"_id":"doc-en-rust-bfc9359b50978cae1c6041a183b1598095e4e12e2dd7c9d11f15e723b44607e3","title":"","text":" fn main() -> Result<(), ()> { a(b(c(d(e( //~^ ERROR cannot find function `a` in this scope //~| ERROR cannot find function `b` in this scope //~| ERROR cannot find function `c` in this scope //~| ERROR cannot find function `d` in this scope //~| ERROR cannot find function `e` in this scope z???????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????????? //~^^^ ERROR cannot find value `z` in this scope ))))) } "} {"_id":"doc-en-rust-aaa9b69d0960241daf1de0c0723ae40b3eec09a2a62605ec70c6aec9280b4759","title":"","text":" error[E0425]: cannot find value `z` in this scope --> $DIR/fn-to-method-deeply-nested.rs:8:9 | LL | z???????????????????????????????????????????????????????????????????????????????????????? | ^ not found in this scope error[E0425]: cannot find function `e` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:13 | LL | a(b(c(d(e( | ^ not found in this scope error[E0425]: cannot find function `d` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:11 | LL | a(b(c(d(e( | ^ not found in this scope error[E0425]: cannot find function `c` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:9 | LL | a(b(c(d(e( | ^ not found in this scope error[E0425]: cannot find function `b` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:7 | LL | a(b(c(d(e( | ^ not found in this scope error[E0425]: cannot find function `a` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:5 | LL | a(b(c(d(e( | ^ not found in this scope error: aborting due to 6 previous errors For more information about this error, try `rustc --explain E0425`. "} {"_id":"doc-en-rust-17b720c902de637d51aa34a96d0fbdfb888467fd5b0dbedc2c8e59c223ffbd8c","title":"","text":" fn main() { a((), 1i32 == 2u32); //~^ ERROR cannot find function `a` in this scope //~| ERROR mismatched types } "} {"_id":"doc-en-rust-bce566408450f8713a3ee5047f9d88cbc05f1b6b956b38dfe5074cf84e78e5b5","title":"","text":" error[E0308]: mismatched types --> $DIR/check-args-on-fn-err-2.rs:2:19 | LL | a((), 1i32 == 2u32); | ---- ^^^^ expected `i32`, found `u32` | | | expected because this is `i32` | help: change the type of the numeric literal from `u32` to `i32` | LL | a((), 1i32 == 2i32); | ~~~ error[E0425]: cannot find function `a` in this scope --> $DIR/check-args-on-fn-err-2.rs:2:5 | LL | a((), 1i32 == 2u32); | ^ not found in this scope error: aborting due to 2 previous errors Some errors have detailed explanations: E0308, E0425. For more information about an error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-fd562c34adda8629857570dc5437982c77280b3756a4330a5b63392efba5b64c","title":"","text":" fn main() { unknown(1, |glyf| { //~^ ERROR: cannot find function `unknown` in this scope let actual = glyf; }); } "} {"_id":"doc-en-rust-e52e2b89015415c2c6e74e8d625cb6038c6fb13f45fa4f8ae46a50449701e561","title":"","text":" error[E0425]: cannot find function `unknown` in this scope --> $DIR/check-args-on-fn-err.rs:2:5 | LL | unknown(1, |glyf| { | ^^^^^^^ not found in this scope error: aborting due to previous error For more information about this error, try `rustc --explain E0425`. "} {"_id":"doc-en-rust-e83b2d8b2f7e315dfb74f5e50b1c4431c9680d2a88a53e98018dc15e773f8682","title":"","text":"_ => {} } } let lines = origtext.lines().filter_map(|l| map_line(l).for_html()); let text = lines.intersperse(\"n\".into()).collect::(); let parse_result = match kind { CodeBlockKind::Fenced(ref lang) => {"} {"_id":"doc-en-rust-b12d6844623033b9cfcf308ab6ff620335bdf64742d91b4d394154f06f94a7f8","title":"","text":"
{}
\", lang, Escape(&text), Escape(&origtext), ) .into(), ));"} {"_id":"doc-en-rust-6ed5d5d610517e77ed9a4687b39cc78c5ac86f81ebf38573a032941748ed9d61","title":"","text":"CodeBlockKind::Indented => Default::default(), }; let lines = origtext.lines().filter_map(|l| map_line(l).for_html()); let text = lines.intersperse(\"n\".into()).collect::(); compile_fail = parse_result.compile_fail; should_panic = parse_result.should_panic; ignore = parse_result.ignore;"} {"_id":"doc-en-rust-9af0962eb85b7e442fb8b97de634919714be796d294e1392f71faedafa768c66","title":"","text":"t(\"```rustn```n```rustn```\", &[1, 3]); t(\"```rustn```n ```rustn```\", &[1, 3]); } #[test] fn test_ascii_with_prepending_hashtag() { fn t(input: &str, expect: &str) { let mut map = IdMap::new(); let output = Markdown { content: input, links: &[], ids: &mut map, error_codes: ErrorCodes::Yes, edition: DEFAULT_EDITION, playground: &None, heading_offset: HeadingOffset::H2, } .into_string(); assert_eq!(output, expect, \"original: {}\", input); } t( r#\"```ascii #..#.####.#....#.....##.. #..#.#....#....#....#..#. ####.###..#....#....#..#. #..#.#....#....#....#..#. #..#.#....#....#....#..#. #..#.####.####.####..##.. ```\"#, \"
 #..#.####.#....#.....##.. #..#.#....#....#....#..#. ####.###..#....#....#..#. #..#.#....#....#....#..#. #..#.#....#....#....#..#. #..#.####.####.####..##.. 
\", ); }
"} {"_id":"doc-en-rust-08c047090122345af8734da7b6ef616a45979689800faed00ab694e9d83c6fa5","title":"","text":"let entry = spanned_predicates.entry(spans); entry.or_insert_with(|| (path, tr_self_ty, Vec::new())).2.push(p); } Some(Node::Item(hir::Item { kind: hir::ItemKind::Trait(rustc_ast::ast::IsAuto::Yes, ..), span: item_span, .. })) => { tcx.sess.delay_span_bug( *item_span, \"auto trait is invoked with no method error, but no error reported?\", ); } Some(_) => unreachable!(), None => (), }"} {"_id":"doc-en-rust-44997c8035a50b1e0751882529c65f4adb171c403a1053e0816d533287865a09","title":"","text":" #![feature(auto_traits)] auto trait Foo { fn g(&self); //~ ERROR auto traits cannot have associated items } trait Bar { fn f(&self) { self.g(); //~ ERROR the method `g` exists for reference `&Self`, but its trait bounds were not satisfied } } fn main() {} "} {"_id":"doc-en-rust-cc9aadb57cfd2aa0187450c49ddaf2e4147542cf66e815fb23b85c4bd4bb8490","title":"","text":" error[E0380]: auto traits cannot have associated items --> $DIR/issue-105732.rs:4:8 | LL | auto trait Foo { | --- auto trait cannot have associated items LL | fn g(&self); | ---^-------- help: remove these associated items error[E0599]: the method `g` exists for reference `&Self`, but its trait bounds were not satisfied --> $DIR/issue-105732.rs:9:14 | LL | self.g(); | ^ | = note: the following trait bounds were not satisfied: `Self: Foo` which is required by `&Self: Foo` `&Self: Foo` = help: items from traits can only be used if the type parameter is bounded by the trait help: the following trait defines an item `g`, perhaps you need to add a supertrait for it: | LL | trait Bar: Foo { | +++++ error: aborting due to 2 previous errors Some errors have detailed explanations: E0380, E0599. For more information about an error, try `rustc --explain E0380`. "} {"_id":"doc-en-rust-4b07a6b87a070e7352474b1c0d71a235e5478fbe10b228395cae440c42f765bd","title":"","text":"GenericParamKind, HirId, Node, }; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, TyCtxt}; use rustc_session::lint;"} {"_id":"doc-en-rust-2a607b0b61c984c976cc6fe6fb87a1c01e2d9b265f0e6912dce0632438989c66","title":"","text":"Some(tcx.typeck_root_def_id(def_id)) } Node::Item(item) => match item.kind { ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => { ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id) | hir::OpaqueTyOrigin::AsyncFn(fn_def_id), in_trait, .. }) => { if in_trait { assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn)) } else { assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn)) } Some(fn_def_id.to_def_id()) } ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias, .. }) => { let parent_id = tcx.hir().get_parent_item(hir_id); assert_ne!(parent_id, hir::CRATE_OWNER_ID); debug!(\"generics_of: parent of opaque ty {:?} is {:?}\", def_id, parent_id);"} {"_id":"doc-en-rust-f6f283fe0a740cbb9996bb3ace1dd306066b068285ea40405c8cf7e2db0ad7ed","title":"","text":" // check-pass // edition: 2021 // known-bug: #105197 // failure-status:101 // dont-check-compiler-stderr #![feature(async_fn_in_trait)] #![feature(return_position_impl_trait_in_trait)]"} {"_id":"doc-en-rust-428c04975df5ad50f3d633036449d469cf471f19e62a7117668e4e108025b01c","title":"","text":"self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id) } hir::ExprKind::Call(ref inner_callee, _) => { // If the call spans more than one line and the callee kind is // itself another `ExprCall`, that's a clue that we might just be // missing a semicolon (Issue #51055) let call_is_multiline = self.tcx.sess.source_map().is_multiline(call_expr.span); if call_is_multiline { err.span_suggestion( callee_expr.span.shrink_to_hi(), \"consider using a semicolon here\", \";\", Applicability::MaybeIncorrect, ); } if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind { inner_callee_path = Some(inner_qpath); self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)"} {"_id":"doc-en-rust-78d175d27cfbed36e5b865c5466a55a99eabcbff557316bcc5d6aa196b242460","title":"","text":"}; if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) { // If the call spans more than one line and the callee kind is // itself another `ExprCall`, that's a clue that we might just be // missing a semicolon (#51055, #106515). let call_is_multiline = self .tcx .sess .source_map() .is_multiline(call_expr.span.with_lo(callee_expr.span.hi())) && call_expr.span.ctxt() == callee_expr.span.ctxt(); if call_is_multiline { err.span_suggestion( callee_expr.span.shrink_to_hi(), \"consider using a semicolon here to finish the statement\", \";\", Applicability::MaybeIncorrect, ); } if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty) && !self.type_is_sized_modulo_regions(self.param_env, output_ty) {"} {"_id":"doc-en-rust-4d656c101519d866e2a9a4c16d416ee800dd1240cf7a5f7a902509bc9c2349d8","title":"","text":"| ----------------------- `vindictive` defined here returns `bool` ... LL | vindictive() | -^^^^^^^^^^^- help: consider using a semicolon here: `;` | -^^^^^^^^^^^- help: consider using a semicolon here to finish the statement: `;` | _____| | | LL | | (1, 2)"} {"_id":"doc-en-rust-49d1ca63a7fef2cfab30c4e36af103643dd91dff9543c79eafbc5546ab03a486","title":"","text":" // run-rustfix #![allow(dead_code, unused_variables, path_statements)] fn a() { let x = 5; let y = x; //~ ERROR expected function (); //~ ERROR expected `;`, found `}` } fn b() { let x = 5; let y = x; //~ ERROR expected function (); } fn c() { let x = 5; x; //~ ERROR expected function () } fn d() { // ok let x = || (); x () } fn e() { // ok let x = || (); x (); } fn f() { let y = 5; //~ ERROR expected function (); //~ ERROR expected `;`, found `}` } fn g() { 5; //~ ERROR expected function (); } fn main() {} "} {"_id":"doc-en-rust-43fef71aeacb631a582a6c6ba9acb4c667abcfe9f7a3a6f381e1b5355497e2ba","title":"","text":" // run-rustfix #![allow(dead_code, unused_variables, path_statements)] fn a() { let x = 5; let y = x //~ ERROR expected function () //~ ERROR expected `;`, found `}` } fn b() { let x = 5; let y = x //~ ERROR expected function (); } fn c() { let x = 5; x //~ ERROR expected function () } fn d() { // ok let x = || (); x () } fn e() { // ok let x = || (); x (); } fn f() { let y = 5 //~ ERROR expected function () //~ ERROR expected `;`, found `}` } fn g() { 5 //~ ERROR expected function (); } fn main() {} "} {"_id":"doc-en-rust-f2c16ad0daae35a939b3a30e303553d86f7b4a0b8894cbb904e0ab1f3179592d","title":"","text":" error: expected `;`, found `}` --> $DIR/missing-semicolon.rs:6:7 | LL | () | ^ help: add `;` here LL | } | - unexpected token error: expected `;`, found `}` --> $DIR/missing-semicolon.rs:32:7 | LL | () | ^ help: add `;` here LL | } | - unexpected token error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:5:13 | LL | let x = 5; | - `x` has type `{integer}` LL | let y = x | ^- help: consider using a semicolon here to finish the statement: `;` | _____________| | | LL | | () | |______- call expression requires function error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:11:13 | LL | let x = 5; | - `x` has type `{integer}` LL | let y = x | ^- help: consider using a semicolon here to finish the statement: `;` | _____________| | | LL | | (); | |______- call expression requires function error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:16:5 | LL | let x = 5; | - `x` has type `{integer}` LL | x | ^- help: consider using a semicolon here to finish the statement: `;` | _____| | | LL | | () | |______- call expression requires function error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:31:13 | LL | let y = 5 | ^- help: consider using a semicolon here to finish the statement: `;` | _____________| | | LL | | () | |______- call expression requires function error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:35:5 | LL | 5 | ^- help: consider using a semicolon here to finish the statement: `;` | _____| | | LL | | (); | |______- call expression requires function error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0618`. "} {"_id":"doc-en-rust-a785693731099ea40e2ac514216e5610eb64206f46e3b954af96173ba2acab6c","title":"","text":"note = \"if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end`\" ), on( _Self = \"{float}\", note = \"if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end`\" ), label = \"`{Self}` is not an iterator\", message = \"`{Self}` is not an iterator\" )]"} {"_id":"doc-en-rust-6909fccc96f5d97be145e450bc723f5705fdbe25873852a808546886e8cabe95","title":"","text":" // #106728 fn main() { for i in 0.2 { //~^ ERROR `{float}` is not an iterator //~| `{float}` is not an iterator //~| NOTE in this expansion of desugaring of `for` loop //~| NOTE in this expansion of desugaring of `for` loop //~| NOTE in this expansion of desugaring of `for` loop //~| NOTE in this expansion of desugaring of `for` loop //~| NOTE if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` //~| NOTE required for `{float}` to implement `IntoIterator` println!(); } } "} {"_id":"doc-en-rust-9852cf898f323704560454a01895519154f97af59ae974548addf0161cb0949b","title":"","text":" error[E0277]: `{float}` is not an iterator --> $DIR/float_iterator_hint.rs:4:14 | LL | for i in 0.2 { | ^^^ `{float}` is not an iterator | = help: the trait `Iterator` is not implemented for `{float}` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `{float}` to implement `IntoIterator` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-ac608463a734c150320b3d1ed98e6db00d9bb96eb3aff7af962a9ca3212c788e","title":"","text":"| ^^^^ `{float}` is not an iterator | = help: the trait `Iterator` is not implemented for `{float}` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `{float}` to implement `IntoIterator` error: aborting due to 12 previous errors"} {"_id":"doc-en-rust-cd2376f1f324e296cb61b47dafcec2f57ddb93d363536d9e8a437435b722be7d","title":"","text":"if !check && paths.is_empty() { match get_modified_rs_files(build) { Ok(Some(files)) => { if files.len() <= 10 { for file in &files { println!(\"formatting modified file {file}\"); } } else { println!(\"formatting {} modified files\", files.len()); } for file in files { println!(\"formatting modified file {file}\"); ignore_fmt.add(&format!(\"/{file}\")).expect(&file); } }"} {"_id":"doc-en-rust-94071e4acf6f5c0915e331f9061a16e09f887c1947a58645b490954b9a6f93cf","title":"","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":"doc-en-rust-65f5bceee9c1749a7a549da2e04707d247228d0748d6ad71106fcf915839e3b2","title":"","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":"doc-en-rust-d04d99a91d1b39c7c8b56787097248094ac19d2977f00828c60e89a0c66e73b6","title":"","text":"all(target_vendor = \"fortanix\", target_env = \"sgx\"), feature(slice_index_methods, coerce_unsized, sgx_platform) )] #![cfg_attr(windows, feature(round_char_boundary))] // // Language features: #![feature(alloc_error_handler)]"} {"_id":"doc-en-rust-7c4cf518769fbf19cd76f0d002c44322baf833d706d6baf24684f25476ff4bc7","title":"","text":"use crate::ffi::CStr; use crate::mem; use crate::os::raw::{c_char, c_int, c_long, c_longlong, c_uint, c_ulong, c_ushort}; use crate::os::raw::{c_char, c_long, c_longlong, c_uint, c_ulong, c_ushort}; use crate::os::windows::io::{BorrowedHandle, HandleOrInvalid, HandleOrNull}; use crate::ptr; use core::ffi::NonZero_c_ulong; use libc::{c_void, size_t, wchar_t}; pub use crate::os::raw::c_int; #[path = \"c/errors.rs\"] // c.rs is included from two places so we need to specify this mod errors; pub use errors::*;"} {"_id":"doc-en-rust-8deb8fdda823b79945f44f3db92107245e9285ec49952bc857f8795cc4c60468","title":"","text":"pub type LPBOOL = *mut BOOL; pub type LPBYTE = *mut BYTE; pub type LPCCH = *const CHAR; pub type LPCSTR = *const CHAR; pub type LPCWCH = *const WCHAR; pub type LPCWSTR = *const WCHAR; pub type LPCVOID = *const c_void; pub type LPDWORD = *mut DWORD; pub type LPHANDLE = *mut HANDLE; pub type LPOVERLAPPED = *mut OVERLAPPED; pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION; pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; pub type LPSTARTUPINFO = *mut STARTUPINFO; pub type LPSTR = *mut CHAR; pub type LPVOID = *mut c_void; pub type LPCVOID = *const c_void; pub type LPWCH = *mut WCHAR; pub type LPWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW; pub type LPWSADATA = *mut WSADATA;"} {"_id":"doc-en-rust-9602aaaf9568f0a6e14b73c897ea554d07869e497a0b7c9d037405f2ded07d09","title":"","text":"pub const FILE_TYPE_PIPE: u32 = 3; pub const CP_UTF8: DWORD = 65001; pub const MB_ERR_INVALID_CHARS: DWORD = 0x08; pub const WC_ERR_INVALID_CHARS: DWORD = 0x80; #[repr(C)] #[derive(Copy)] pub struct WIN32_FIND_DATAW {"} {"_id":"doc-en-rust-024fa20b175c6b3e4f8ef0de7a3976df60c39cc33c90c2bc9c14ef2051cdb484","title":"","text":"lpFilePart: *mut LPWSTR, ) -> DWORD; pub fn GetFileAttributesW(lpFileName: LPCWSTR) -> DWORD; pub fn MultiByteToWideChar( CodePage: UINT, dwFlags: DWORD, lpMultiByteStr: LPCCH, cbMultiByte: c_int, lpWideCharStr: LPWSTR, cchWideChar: c_int, ) -> c_int; pub fn WideCharToMultiByte( CodePage: UINT, dwFlags: DWORD, lpWideCharStr: LPCWCH, cchWideChar: c_int, lpMultiByteStr: LPSTR, cbMultiByte: c_int, lpDefaultChar: LPCCH, lpUsedDefaultChar: LPBOOL, ) -> c_int; } #[link(name = \"ws2_32\")]"} {"_id":"doc-en-rust-9f9cfac09ad524a283bcbccb6f17892aa9c139abd26d35f11be30ca9a74a8cde","title":"","text":"} fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result { debug_assert!(!utf8.is_empty()); let mut utf16 = [MaybeUninit::::uninit(); MAX_BUFFER_SIZE / 2]; let mut len_utf16 = 0; for (chr, dest) in utf8.encode_utf16().zip(utf16.iter_mut()) { *dest = MaybeUninit::new(chr); len_utf16 += 1; } // Safety: We've initialized `len_utf16` values. let utf16: &[u16] = unsafe { MaybeUninit::slice_assume_init_ref(&utf16[..len_utf16]) }; let utf8 = &utf8[..utf8.floor_char_boundary(utf16.len())]; let utf16: &[u16] = unsafe { // Note that this theoretically checks validity twice in the (most common) case // where the underlying byte sequence is valid utf-8 (given the check in `write()`). let result = c::MultiByteToWideChar( c::CP_UTF8, // CodePage c::MB_ERR_INVALID_CHARS, // dwFlags utf8.as_ptr() as c::LPCCH, // lpMultiByteStr utf8.len() as c::c_int, // cbMultiByte utf16.as_mut_ptr() as c::LPWSTR, // lpWideCharStr utf16.len() as c::c_int, // cchWideChar ); assert!(result != 0, \"Unexpected error in MultiByteToWideChar\"); // Safety: MultiByteToWideChar initializes `result` values. MaybeUninit::slice_assume_init_ref(&utf16[..result as usize]) }; let mut written = write_u16s(handle, &utf16)?;"} {"_id":"doc-en-rust-90b1d01c323ddb0a9ce545bb7f2cefc22731e4d4a52cf5d4e863248da9940544","title":"","text":"// a missing surrogate can be produced (and also because of the UTF-8 validation above), // write the missing surrogate out now. // Buffering it would mean we have to lie about the number of bytes written. let first_char_remaining = utf16[written]; if first_char_remaining >= 0xDCEE && first_char_remaining <= 0xDFFF { let first_code_unit_remaining = utf16[written]; if first_code_unit_remaining >= 0xDCEE && first_code_unit_remaining <= 0xDFFF { // low surrogate // We just hope this works, and give up otherwise let _ = write_u16s(handle, &utf16[written..written + 1]);"} {"_id":"doc-en-rust-2f245b11f846beb7037c085ca8b6a127deaa4cd751ceb5f5254b07b5ca8a7e60","title":"","text":"} fn write_u16s(handle: c::HANDLE, data: &[u16]) -> io::Result { debug_assert!(data.len() < u32::MAX as usize); let mut written = 0; cvt(unsafe { c::WriteConsoleW("} {"_id":"doc-en-rust-a00840a7caacf7682f470ca6b4350c2322113fe752d3a67a2121c208b482ee49","title":"","text":"Ok(amount as usize) } #[allow(unused)] fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result { let mut written = 0; for chr in char::decode_utf16(utf16.iter().cloned()) { match chr { Ok(chr) => { chr.encode_utf8(&mut utf8[written..]); written += chr.len_utf8(); } Err(_) => { // We can't really do any better than forget all data and return an error. return Err(io::const_io_error!( io::ErrorKind::InvalidData, \"Windows stdin in console mode does not support non-UTF-16 input; encountered unpaired surrogate\", )); } } debug_assert!(utf16.len() <= c::c_int::MAX as usize); debug_assert!(utf8.len() <= c::c_int::MAX as usize); let result = unsafe { c::WideCharToMultiByte( c::CP_UTF8, // CodePage c::WC_ERR_INVALID_CHARS, // dwFlags utf16.as_ptr(), // lpWideCharStr utf16.len() as c::c_int, // cchWideChar utf8.as_mut_ptr() as c::LPSTR, // lpMultiByteStr utf8.len() as c::c_int, // cbMultiByte ptr::null(), // lpDefaultChar ptr::null_mut(), // lpUsedDefaultChar ) }; if result == 0 { // We can't really do any better than forget all data and return an error. Err(io::const_io_error!( io::ErrorKind::InvalidData, \"Windows stdin in console mode does not support non-UTF-16 input; encountered unpaired surrogate\", )) } else { Ok(result as usize) } Ok(written) } impl IncompleteUtf8 {"} {"_id":"doc-en-rust-4c58651cdd73604ad12f1562c8f6cb064da4e4e9fb23da16e9d796af96d2c09f","title":"","text":"invalid monomorphization of `{$name}` intrinsic: unsupported {$name} from `{$in_ty}` with element `{$elem_ty}` to `{$ret_ty}` codegen_gcc_invalid_monomorphization_invalid_bitmask = invalid monomorphization of `{$name}` intrinsic: invalid bitmask `{ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]` invalid monomorphization of `{$name}` intrinsic: invalid bitmask `{$ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]` codegen_gcc_invalid_monomorphization_simd_shuffle = invalid monomorphization of `{$name}` intrinsic: simd_shuffle index must be an array of `u32`, got `{$ty}`"} {"_id":"doc-en-rust-292146ccba7fb38437c86976476a3c6e6361ba5a6d360784b41d3fbe955a048f","title":"","text":"codegen_ssa_unsupported_arch = unsupported arch `{$arch}` for os `{$os}` codegen_ssa_apple_sdk_error_sdk_path = failed to get {$sdk_name} SDK path: {error} codegen_ssa_apple_sdk_error_sdk_path = failed to get {$sdk_name} SDK path: {$error} codegen_ssa_read_file = failed to read file: {message} codegen_ssa_read_file = failed to read file: {$message} codegen_ssa_unsupported_link_self_contained = option `-C link-self-contained` is not supported on this target"} {"_id":"doc-en-rust-c510633ed7db2fbba23754e7ff880c8f7d02e5269870069f356e01d3a0cc03b1","title":"","text":"}; use fluent_bundle::{FluentBundle, FluentError, FluentResource}; use fluent_syntax::{ ast::{Attribute, Entry, Identifier, Message}, ast::{ Attribute, Entry, Expression, Identifier, InlineExpression, Message, Pattern, PatternElement, }, parser::ParserError, }; use proc_macro::{Diagnostic, Level, Span};"} {"_id":"doc-en-rust-aa83151887ab49215a3bd158aa86e8ede1d23cce1639afb457c038d2fc1c765a","title":"","text":"}; let mut constants = TokenStream::new(); let mut messagerefs = Vec::new(); for entry in resource.entries() { let span = res.krate.span(); if let Entry::Message(Message { id: Identifier { name }, attributes, .. }) = entry { if let Entry::Message(Message { id: Identifier { name }, attributes, value, .. }) = entry { let _ = previous_defns.entry(name.to_string()).or_insert(path_span); if name.contains('-') {"} {"_id":"doc-en-rust-81ecf0c9ba5675c05bcd1846616a0636eb732ea077b2e5d8aefdb803fb9e8b94","title":"","text":".emit(); } if let Some(Pattern { elements }) = value { for elt in elements { if let PatternElement::Placeable { expression: Expression::Inline(InlineExpression::MessageReference { id, .. }), } = elt { messagerefs.push((id.name, *name)); } } } // Require that the message name starts with the crate name // `hir_typeck_foo_bar` (in `hir_typeck.ftl`) // `const_eval_baz` (in `const_eval.ftl`)"} {"_id":"doc-en-rust-4e6f6cc961c82ffe16c067274e7ec245e73e05a0f2a3d93ae5824f59bd56c389","title":"","text":"} } for (mref, name) in messagerefs.into_iter() { if !previous_defns.contains_key(mref) { Diagnostic::spanned( path_span, Level::Error, format!(\"referenced message `{mref}` does not exist (in message `{name}`)\"), ) .help(&format!(\"you may have meant to use a variable reference (`{{${mref}}}`)\")) .emit(); } } if let Err(errs) = bundle.add_resource(resource) { for e in errs { match e {"} {"_id":"doc-en-rust-93b778151e3f4e792ca2abee2c58468a35f3a4e948d55a27facd42e8b35e1e76","title":"","text":"use self::fluent_generated::{DEFAULT_LOCALE_RESOURCES, test_crate_foo, with_hyphens}; } mod missing_message_ref { use super::fluent_messages; fluent_messages! { missing => \"./missing-message-ref.ftl\" //~^ ERROR referenced message `message` does not exist } } "} {"_id":"doc-en-rust-b2bc88e58696cdda9efbe7cafd6a04545f12ae9a55c72bcb29797fc317dbdc25","title":"","text":"| = help: replace any '-'s with '_'s error: aborting due to 10 previous errors error: referenced message `message` does not exist (in message `missing_message_ref`) --> $DIR/test.rs:104:20 | LL | missing => \"./missing-message-ref.ftl\" | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: you may have meant to use a variable reference (`{$message}`) error: aborting due to 11 previous errors For more information about this error, try `rustc --explain E0428`."} {"_id":"doc-en-rust-0871c8f59b1cda45799a5c0bb1619db59940176ca32ca213a9f982d6becaf95e","title":"","text":"\"{place_name} {partially_str}moved due to this method call{loop_message}\", ), ); let infcx = tcx.infer_ctxt().build(); // Erase and shadow everything that could be passed to the new infcx. let ty = tcx.erase_regions(moved_place.ty(self.body, tcx).ty); let method_substs = tcx.erase_regions(method_substs); if let ty::Adt(def, substs) = ty.kind() && Some(def.did()) == tcx.lang_items().pin_type() && let ty::Ref(_, _, hir::Mutability::Mut) = substs.type_at(0).kind()"} {"_id":"doc-en-rust-82f9bf9fc4f9c6186e47e34df25b19d8d2205b3e4e36d5c43f650a6493d16049","title":"","text":" // run-rustfix use std::pin::Pin; fn foo(_: &mut ()) {} fn main() { let mut uwu = (); let mut r = Pin::new(&mut uwu); foo(r.as_mut().get_mut()); foo(r.get_mut()); //~ ERROR use of moved value } "} {"_id":"doc-en-rust-1bfcc44cab5dc923b9f98b3ba26e0f7d388f9955abd1f35fc7f36a6631124e63","title":"","text":" // run-rustfix use std::pin::Pin; fn foo(_: &mut ()) {} fn main() { let mut uwu = (); let mut r = Pin::new(&mut uwu); foo(r.get_mut()); foo(r.get_mut()); //~ ERROR use of moved value } "} {"_id":"doc-en-rust-547c996341dd8aaa37a8bd324b3e36d92fe1638250aa1004f5490d0eb968b2a5","title":"","text":" error[E0382]: use of moved value: `r` --> $DIR/pin-mut-reborrow-infer-var-issue-107419.rs:10:9 | LL | let mut r = Pin::new(&mut uwu); | ----- move occurs because `r` has type `Pin<&mut ()>`, which does not implement the `Copy` trait LL | foo(r.get_mut()); | --------- `r` moved due to this method call LL | foo(r.get_mut()); | ^ value used here after move | note: `Pin::<&'a mut T>::get_mut` takes ownership of the receiver `self`, which moves `r` --> $SRC_DIR/core/src/pin.rs:LL:COL help: consider reborrowing the `Pin` instead of moving it | LL | foo(r.as_mut().get_mut()); | +++++++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0382`. "} {"_id":"doc-en-rust-0bfd7b1c2c7f0d337ecb37a4a51ea93ff9e4fb51be1eb9fd49df6d14846bd79f","title":"","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":"doc-en-rust-5830570f612ee84a42cfd553e8c6d2357222a6d5669ca00fd9d654ccec1d992d","title":"","text":"self.mark_as_used_if_union(*adt, fields); } } hir::ExprKind::Closure(cls) => { self.insert_def_id(cls.def_id.to_def_id()); } _ => (), }"} {"_id":"doc-en-rust-7a3a2c9bdff588f2ee7ed0ae6cb2748afcb5f464f28245d9383fdd222c0aa397","title":"","text":" // edition: 2021 #![deny(dead_code)] pub fn foo() { let closure = || { fn a() {} //~ ERROR function `a` is never used }; closure() } pub async fn async_foo() { const A: usize = 1; //~ ERROR constant `A` is never used } fn main() {} "} {"_id":"doc-en-rust-4ddfcb9397040f18d76dfc3d674814cef12ef18ac0588d6596b59f35af73b08b","title":"","text":" error: function `a` is never used --> $DIR/in-closure.rs:7:12 | LL | fn a() {} | ^ | note: the lint level is defined here --> $DIR/in-closure.rs:3:9 | LL | #![deny(dead_code)] | ^^^^^^^^^ error: constant `A` is never used --> $DIR/in-closure.rs:13:11 | LL | const A: usize = 1; | ^ error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-be3076d11d9fb71044a605d7bfff2ebfdf2e07cf5dfee7afe3ba1da48307ddcc","title":"","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":"doc-en-rust-0e5187b435a93a81d78a1b2e383fc74748a37bbc89414eb65ac2a54fc467dc53","title":"","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":"doc-en-rust-9b71b5fde73fcc1554bd061a4d5624f89293614d24d87cb9fa0dd02db921ffba","title":"","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":"doc-en-rust-383533e1ffc9f9a7de0e73c3da075c5b1e57f57297d1fe819bf1b82e65982a45","title":"","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":"doc-en-rust-8bcbda56104edc5078582ff7c2e72c90a938cb9771dc46356b113f653ee82ddc","title":"","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":"doc-en-rust-1270aafa272eb93aceab26cbd0ba0cc14f1cbf6980560701cf1c359c824a93ae","title":"","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":"doc-en-rust-c3ee31413b6576b1a5d350cb10c34cdf54769ab42733d4ca07f1928444a2c03d","title":"","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":"doc-en-rust-3f9f0805fa0df31fe1c63fa293eeb4ec5b7e32339ba025b0b5c19fff77ee52a6","title":"","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":"doc-en-rust-7750522f0c30036cdcc03f8f16c07f6e168c013aec93b8c5aee322c9247ed136","title":"","text":"pub fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) { if let DefKind::AssocFn = tcx.def_kind(id) { let parent_id = tcx.local_parent(id); if let DefKind::Impl { of_trait: true } = tcx.def_kind(parent_id) { if let DefKind::Trait | DefKind::Impl { of_trait: true } = tcx.def_kind(parent_id) { tcx.sess .struct_span_err( attr_span,"} {"_id":"doc-en-rust-483d1d9a278cc4290a2e5fee770061113f2d3d2a88612f8a0e3caaea07035f5d","title":"","text":"unsafe fn unsf_foo(&self) {} } trait Qux { #[target_feature(enable = \"sse2\")] //~^ ERROR cannot be applied to safe trait method fn foo(&self) {} } fn main() {}"} {"_id":"doc-en-rust-c402dbdb426463989328b0f9fd5bf1ac35acc52cc089ebafd283d69f5700b404","title":"","text":"error: `#[target_feature(..)]` cannot be applied to safe trait method --> $DIR/trait-impl.rs:22:5 | LL | #[target_feature(enable = \"sse2\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot be applied to safe trait method LL | LL | fn foo(&self) {} | ------------- not an `unsafe` function error: `#[target_feature(..)]` cannot be applied to safe trait method --> $DIR/trait-impl.rs:13:5 | LL | #[target_feature(enable = \"sse2\")]"} {"_id":"doc-en-rust-cafac23b6f1dd2021c4ce8569042b989ec7a4f5fcd730a20211322eb84a13725","title":"","text":"LL | fn foo(&self) {} | ------------- not an `unsafe` function error: aborting due to previous error error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-c64863de2e310a7dfffc32c84c68f3812a2d2229b16a984e578c54eb04878b88","title":"","text":"false, ); // HACK: This avoids putting the newly built artifacts in the sysroot if we're using // `download-rustc`, to avoid \"multiple candidates for `rmeta`\" errors. Technically, that's // not quite right: people can set `download-rustc = true` to download even if there are // changes to the compiler, and in that case ideally we would put the *new* artifacts in the // sysroot, in case there are API changes that should be used by tools. In practice, // though, that should be very uncommon, and people can still disable download-rustc. if !builder.download_rustc() { let libdir = builder.sysroot_libdir(compiler, target); let hostdir = builder.sysroot_libdir(compiler, compiler.host); add_to_sysroot(&builder, &libdir, &hostdir, &librustc_stamp(builder, compiler, target)); } let libdir = builder.sysroot_libdir(compiler, target); let hostdir = builder.sysroot_libdir(compiler, compiler.host); add_to_sysroot(&builder, &libdir, &hostdir, &librustc_stamp(builder, compiler, target)); } }"} {"_id":"doc-en-rust-03905ca7bf6739059c62cca51f607eb955ba1bc253070611c6b4a9065f0ff775","title":"","text":"use std::borrow::Cow; use std::collections::HashSet; use std::env; use std::ffi::OsStr; use std::fs; use std::io::prelude::*; use std::io::BufReader;"} {"_id":"doc-en-rust-6b0ad601969ee6bcf7796362d41107fc977c9d18a3cd6b35a253a87f32eb54fa","title":"","text":"// so its artifacts can't be reused. if builder.download_rustc() && compiler.stage != 0 { // Copy the existing artifacts instead of rebuilding them. // NOTE: this path is only taken for tools linking to rustc-dev. builder.ensure(Sysroot { compiler }); // NOTE: this path is only taken for tools linking to rustc-dev (including ui-fulldeps tests). let sysroot = builder.ensure(Sysroot { compiler }); let ci_rustc_dir = builder.out.join(&*builder.build.build.triple).join(\"ci-rustc\"); for file in builder.config.rustc_dev_contents() { let src = ci_rustc_dir.join(&file); let dst = sysroot.join(file); if src.is_dir() { t!(fs::create_dir_all(dst)); } else { builder.copy(&src, &dst); } } return; }"} {"_id":"doc-en-rust-adccc4e980337402afe640673cd6c898d5d08b4146395da648883d74977f0b1d","title":"","text":"} // Copy the compiler into the correct sysroot. builder.cp_r(&builder.ci_rustc_dir(builder.build.build), &sysroot); // NOTE(#108767): We intentionally don't copy `rustc-dev` artifacts until they're requested with `builder.ensure(Rustc)`. // This fixes an issue where we'd have multiple copies of libc in the sysroot with no way to tell which to load. // There are a few quirks of bootstrap that interact to make this reliable: // 1. The order `Step`s are run is hard-coded in `builder.rs` and not configurable. This // avoids e.g. reordering `test::UiFulldeps` before `test::Ui` and causing the latter to // fail because of duplicate metadata. // 2. The sysroot is deleted and recreated between each invocation, so running `x test // ui-fulldeps && x test ui` can't cause failures. let mut filtered_files = Vec::new(); // Don't trim directories or files that aren't loaded per-target; they can't cause conflicts. let suffix = format!(\"lib/rustlib/{}/lib\", compiler.host); for path in builder.config.rustc_dev_contents() { let path = Path::new(&path); if path.parent().map_or(false, |parent| parent.ends_with(&suffix)) { filtered_files.push(path.file_name().unwrap().to_owned()); } } let filtered_extensions = [OsStr::new(\"rmeta\"), OsStr::new(\"rlib\"), OsStr::new(\"so\")]; let ci_rustc_dir = builder.ci_rustc_dir(builder.config.build); builder.cp_filtered(&ci_rustc_dir, &sysroot, &|path| { if path.extension().map_or(true, |ext| !filtered_extensions.contains(&ext)) { return true; } if !path.parent().map_or(true, |p| p.ends_with(&suffix)) { return true; } if !filtered_files.iter().all(|f| f != path.file_name().unwrap()) { builder.verbose_than(1, &format!(\"ignoring {}\", path.display())); false } else { true } }); return INTERNER.intern_path(sysroot); }"} {"_id":"doc-en-rust-dd6359dad8d7bcc90d22b62f8fb849e5f54eec6f328b8e66bb8f2a1ea9b70038","title":"","text":"env, ffi::{OsStr, OsString}, fs::{self, File}, io::{BufRead, BufReader, ErrorKind}, io::{BufRead, BufReader, BufWriter, ErrorKind, Write}, path::{Path, PathBuf}, process::{Command, Stdio}, };"} {"_id":"doc-en-rust-a03cf1c3dd948614a0ed12bfd2a663d5d3f2c32271f7fa5b14aba91789d6ae20","title":"","text":"let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap()); // decompress the file let data = t!(File::open(tarball)); let data = t!(File::open(tarball), format!(\"file {} not found\", tarball.display())); let decompressor = XzDecoder::new(BufReader::new(data)); let mut tar = tar::Archive::new(decompressor); // `compile::Sysroot` needs to know the contents of the `rustc-dev` tarball to avoid adding // it to the sysroot unless it was explicitly requested. But parsing the 100 MB tarball is slow. // Cache the entries when we extract it so we only have to read it once. let mut recorded_entries = if dst.ends_with(\"ci-rustc\") && pattern == \"rustc-dev\" { Some(BufWriter::new(t!(File::create(dst.join(\".rustc-dev-contents\"))))) } else { None }; for member in t!(tar.entries()) { let mut member = t!(member); let original_path = t!(member.path()).into_owned();"} {"_id":"doc-en-rust-3f1ab69dc365633cc26367fa7559ccbf00c49ee764173dd4c9991a32c6e313a4","title":"","text":"if !t!(member.unpack_in(dst)) { panic!(\"path traversal attack ??\"); } if let Some(record) = &mut recorded_entries { t!(writeln!(record, \"{}\", short_path.to_str().unwrap())); } let src_path = dst.join(original_path); if src_path.is_dir() && dst_path.exists() { continue; } t!(fs::rename(src_path, dst_path)); } t!(fs::remove_dir_all(dst.join(directory_prefix))); let dst_dir = dst.join(directory_prefix); if dst_dir.exists() { t!(fs::remove_dir_all(&dst_dir), format!(\"failed to remove {}\", dst_dir.display())); } } /// Returns whether the SHA256 checksum of `path` matches `expected`."} {"_id":"doc-en-rust-b4c0988620d9024428e34db5622a8c981d6399436439d808d14e859b05c20647","title":"","text":"Some(rustfmt_path) } pub(crate) fn rustc_dev_contents(&self) -> Vec { assert!(self.download_rustc()); let ci_rustc_dir = self.out.join(&*self.build.triple).join(\"ci-rustc\"); let rustc_dev_contents_file = t!(File::open(ci_rustc_dir.join(\".rustc-dev-contents\"))); t!(BufReader::new(rustc_dev_contents_file).lines().collect()) } pub(crate) fn download_ci_rustc(&self, commit: &str) { self.verbose(&format!(\"using downloaded stage2 artifacts from CI (commit {commit})\"));"} {"_id":"doc-en-rust-d3091dbdd4a781b54c4c2b440bb0e8a784d75c370f84ae2372509c801be29a9b","title":"","text":" // Test that `download-rustc` doesn't put duplicate copies of libc in the sysroot. // check-pass #![crate_type = \"lib\"] #![no_std] #![feature(rustc_private)] extern crate libc; "} {"_id":"doc-en-rust-8d9865a27092f45c912d85e4ecca1ed1413b44104b738208f9a4ccd9889d0406","title":"","text":".iter() .enumerate() .map(|(i, ty)| Argument { name: name_from_pat(&body.params[i].pat), name: Symbol::intern(&rustc_hir_pretty::param_to_string(&body.params[i])), type_: ty.clean(cx), }) .collect(),"} {"_id":"doc-en-rust-aff37c95101343fcee3195e932bce2b72cf2d2a1d59914f6f1947f97bcf54c84","title":"","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":"doc-en-rust-526ca719b953f8382fc5f06b27593cd84a0f6071325a5c70b0cb9d9487f433ac","title":"","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(..) => panic!( \"tried to get argument name from PatKind::Range, which is not allowed in function arguments\" ), 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":"doc-en-rust-df43ba6bf4aefc7e35203040f51dca21aa05fb95e6ed8060c53a1d518338290b","title":"","text":" // check-pass fn func(0u8..=255: u8) {} "} {"_id":"doc-en-rust-857e1d25fb89cef025bd38243dc6175e05d6605766295975c711bf3c5c41b93d","title":"","text":" #![crate_name = \"foo\"] // @has foo/fn.f.html // @has - '//*[@class=\"rust fn\"]' 'pub fn f(0u8 ...255: u8)' pub fn f(0u8...255: u8) {} "} {"_id":"doc-en-rust-b2807740b707ef2b8ae129c625c6449d751ef8dbc4aed4e89e094c40c5430147","title":"","text":" error[E0637]: `&` without an explicit lifetime name cannot be used here --> $DIR/issue-109071.rs:8:17 | LL | type Item = &[T]; | ^ explicit lifetime name needed here error[E0107]: missing generics for struct `Windows` --> $DIR/issue-109071.rs:7:9 | LL | impl Windows { | ^^^^^^^ expected 1 generic argument | note: struct defined here, with 1 generic parameter: `T` --> $DIR/issue-109071.rs:5:8 | LL | struct Windows {} | ^^^^^^^ - help: add missing generic argument | LL | impl Windows { | +++ error[E0658]: inherent associated types are unstable --> $DIR/issue-109071.rs:8:5 | LL | type Item = &[T]; | ^^^^^^^^^^^^^^^^^ | = note: see issue #8995 for more information = help: add `#![feature(inherent_associated_types)]` to the crate attributes to enable error: aborting due to 3 previous errors Some errors have detailed explanations: E0107, E0637, E0658. For more information about an error, try `rustc --explain E0107`. "} {"_id":"doc-en-rust-6f4df27f06947c83de719d1583949626b2f173d078d2fe9f3ea95751c803b75a","title":"","text":" // revisions: with_gate no_gate #![cfg_attr(with_gate, feature(inherent_associated_types))] #![cfg_attr(with_gate, allow(incomplete_features))] struct Windows {} impl Windows { //~ ERROR: missing generics for struct `Windows` type Item = &[T]; //~ ERROR: `&` without an explicit lifetime name cannot be used here //[no_gate]~^ ERROR: inherent associated types are unstable fn next() -> Option {} } impl Windows { fn T() -> Option {} } fn main() {} "} {"_id":"doc-en-rust-7ff5a4cf1725d90bf964c4a79109de9063a0dff5444f7bece240d85ff7a097b2","title":"","text":" error[E0637]: `&` without an explicit lifetime name cannot be used here --> $DIR/issue-109071.rs:8:17 | LL | type Item = &[T]; | ^ explicit lifetime name needed here error[E0107]: missing generics for struct `Windows` --> $DIR/issue-109071.rs:7:9 | LL | impl Windows { | ^^^^^^^ expected 1 generic argument | note: struct defined here, with 1 generic parameter: `T` --> $DIR/issue-109071.rs:5:8 | LL | struct Windows {} | ^^^^^^^ - help: add missing generic argument | LL | impl Windows { | +++ error: aborting due to 2 previous errors Some errors have detailed explanations: E0107, E0637. For more information about an error, try `rustc --explain E0107`. "} {"_id":"doc-en-rust-a90f713392ff119a8866a5e7b8b5fc801d1abf06a3d18b4ea16dcec1cfb13440","title":"","text":"} pub fn stat(path: &Path) -> io::Result { metadata(path, ReparsePoint::Follow) match metadata(path, ReparsePoint::Follow) { Err(err) if err.raw_os_error() == Some(c::ERROR_CANT_ACCESS_FILE as i32) => { if let Ok(attrs) = lstat(path) { if !attrs.file_type().is_symlink() { return Ok(attrs); } } Err(err) } result => result, } } pub fn lstat(path: &Path) -> io::Result {"} {"_id":"doc-en-rust-c8851f733914b45eb50adbb756282aafab4338d99e014072b6653b345aba1f52","title":"","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":"doc-en-rust-6977e261d9dd0054ba4180001d05e39fc3313ceae1c794a61681175d62ab4538","title":"","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":"doc-en-rust-9607d1e0a7f28fdc7194d38fd476735713570aa6e5c0b36e85d4f4ee33995cab","title":"","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":"doc-en-rust-10cb2834c62ba15fa1ffe3766402ebe566aad84fa249051c2dd33c5210bdb2ef","title":"","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":"doc-en-rust-fb5211bbc433a7a4708e749ecf691ed4934449150a243bbc9c7c3e7dbfe2e2e0","title":"","text":"ct_op: |ct| ct, ty_op: |ty| match *ty.kind() { ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) if replace_opaque_type(def_id) => if replace_opaque_type(def_id) && !ty.has_escaping_bound_vars() => { let def_span = self.tcx.def_span(def_id); let span = if span.contains(def_span) { def_span } else { span };"} {"_id":"doc-en-rust-527b53af5eb4bd7dd64e2f13f5bd14317aeb87bb316cc9b5fb17236e2b950318","title":"","text":"//! This test checks that opaque type collection doesn't try to normalize the projection //! without respecting its binders (which would ICE). //! Unfortunately we don't even reach opaque type collection, as we ICE in typeck before that. // known-bug: #109281 // failure-status: 101 // error-pattern:internal compiler error // normalize-stderr-test \"internal compiler error.*\" -> \"\" // normalize-stderr-test \"DefId([^)]*)\" -> \"...\" // normalize-stderr-test \"nerror: internal compiler error.*nn\" -> \"\" // normalize-stderr-test \"note:.*unexpectedly panicked.*nn\" -> \"\" // normalize-stderr-test \"note: we would appreciate a bug report.*nn\" -> \"\" // normalize-stderr-test \"note: compiler flags.*nn\" -> \"\" // normalize-stderr-test \"note: rustc.*running on.*nn\" -> \"\" // normalize-stderr-test \"thread.*panicked.*:n.*n\" -> \"\" // normalize-stderr-test \"stack backtrace:n\" -> \"\" // normalize-stderr-test \"sd{1,}: .*n\" -> \"\" // normalize-stderr-test \"s at .*n\" -> \"\" // normalize-stderr-test \".*note: Some details.*n\" -> \"\" // normalize-stderr-test \"nn[ ]*n\" -> \"\" // normalize-stderr-test \"compiler/.*: projection\" -> \"projection\" // normalize-stderr-test \".*omitted d{1,} frame.*n\" -> \"\" // normalize-stderr-test \"error: [sn]*query stack\" -> \"error: query stack\" // normalize-stderr-test \"[ns]*nquery stack during panic:\" -> \"query stack during panic:\" //! See #109281 for the original report. // edition:2018 // error-pattern: expected generic lifetime parameter, found `'a` #![feature(type_alias_impl_trait)] #![allow(incomplete_features)]"} {"_id":"doc-en-rust-fee9ee19347bf383529fae47719334b017724885d10958606a776cf2e88221fb","title":"","text":" error: --> $DIR/issue-90014-tait2.rs:44:27 | LL | fn make_fut(&self) -> Box Trait<'a, Thing = Fut<'a>>> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^query stack during panic: #0 [typeck] type-checking `::make_fut` #1 [type_of] computing type of `Fut::{opaque#0}` #2 [check_mod_item_types] checking item types in top-level module #3 [analysis] running analysis passes on this crate end of query stack error[E0792]: expected generic lifetime parameter, found `'a` error: aborting due to previous error For more information about this error, try `rustc --explain E0792`. "} {"_id":"doc-en-rust-e2e822978a8e44a168f9e7e104e4fc49b401ba6769d59eff06b25b2b07bd2df8","title":"","text":" #![feature(type_alias_impl_trait)] type Opaque<'a> = impl Sized + 'a; fn test(f: fn(u8)) -> fn(Opaque<'_>) { f //~ ERROR E0792 } fn main() {} "} {"_id":"doc-en-rust-90b88845116e8585113b85b7064d26048042aa5883209f3d539ff3af3c3b10e7","title":"","text":" error[E0792]: expected generic lifetime parameter, found `'_` --> $DIR/under-binder.rs:6:5 | LL | type Opaque<'a> = impl Sized + 'a; | -- this generic parameter must be used with a generic lifetime parameter ... LL | f | ^ error: aborting due to previous error For more information about this error, try `rustc --explain E0792`. "} {"_id":"doc-en-rust-4aa04c0d91a78bcaeeea5f545c43bcd30c0d7b638a6c95d8c67c63e2a8bbf9fa","title":"","text":"for (i, proj) in place.projections.iter().enumerate() { match proj.kind { ProjectionKind::Index => { // Arrays are completely captured, so we drop Index projections ProjectionKind::Index | ProjectionKind::Subslice => { // Arrays are completely captured, so we drop Index and Subslice projections truncate_place_to_len_and_update_capture_kind(&mut place, &mut curr_mode, i); return (place, curr_mode); } ProjectionKind::Deref => {} ProjectionKind::Field(..) => {} // ignore ProjectionKind::Subslice => {} // We never capture this } }"} {"_id":"doc-en-rust-48b74484eb6fad6b4c77cbf71d127fb08891f56ade506ebb38fe4938e45341fe","title":"","text":" // regression test for #109298 // edition: 2021 pub fn subslice_array(x: [u8; 3]) { let f = || { let [_x @ ..] = x; let [ref y, ref mut z @ ..] = x; //~ ERROR cannot borrow `x[..]` as mutable }; f(); //~ ERROR cannot borrow `f` as mutable } fn main() {} "} {"_id":"doc-en-rust-45ffe405ab053c5fee016ad199b6ab6597009d4a3ac411028cb029d04e94826c","title":"","text":" error[E0596]: cannot borrow `x[..]` as mutable, as `x` is not declared as mutable --> $DIR/array_subslice.rs:7:21 | LL | pub fn subslice_array(x: [u8; 3]) { | - help: consider changing this to be mutable: `mut x` ... LL | let [ref y, ref mut z @ ..] = x; | ^^^^^^^^^ cannot borrow as mutable error[E0596]: cannot borrow `f` as mutable, as it is not declared as mutable --> $DIR/array_subslice.rs:10:5 | LL | let [ref y, ref mut z @ ..] = x; | - calling `f` requires mutable binding due to mutable borrow of `x` ... LL | f(); | ^ cannot borrow as mutable | help: consider changing this to be mutable | LL | let mut f = || { | +++ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0596`. "} {"_id":"doc-en-rust-c88e4bb2d1c33f7d2f89bea814e6341e642686b820ea4feeac11b7e87e41e25f","title":"","text":" //@ assembly-output: emit-asm //@ compile-flags:-Copt-level=3 //@ only-x86_64 #![crate_type = \"lib\"] #[no_mangle] type T = u8; type T1 = (T, T, T, T, T, T, T, T); type T2 = [T; 8]; #[no_mangle] // CHECK-LABEL: foo1a // CHECK: cmp // CHECK-NEXT: set // CHECK-NEXT: ret pub fn foo1a(a: T1, b: T1) -> bool { a == b } #[no_mangle] // CHECK-LABEL: foo1b // CHECK: mov // CHECK-NEXT: cmp // CHECK-NEXT: set // CHECK-NEXT: ret pub fn foo1b(a: &T1, b: &T1) -> bool { a == b } "} {"_id":"doc-en-rust-1f1622d7078c48d54749e4b08b4f15fc029376c2b730dbd3ca6d59da6353f53c","title":"","text":" //@ compile-flags: -O //@ min-llvm-version: 17 #![crate_type = \"lib\"] #[no_mangle] // CHECK-LABEL: @foo // CHECK: getelementptr inbounds // CHECK-NEXT: load i64 // CHECK-NEXT: icmp eq i64 // CHECK-NEXT: br i1 #[no_mangle] pub fn foo(input: &mut &[u64]) -> Option { let (first, rest) = input.split_first()?; *input = rest; Some(*first) } "} {"_id":"doc-en-rust-35f320816bcb0ba41943216784220e3866b16b66c408ed09581f2e2415ac3af1","title":"","text":" //@ compile-flags: -O // XXX: The x86-64 assembly get optimized correclty. But llvm-ir output is not until llvm 18? //@ min-llvm-version: 18 #![crate_type = \"lib\"] pub enum K{ A(Box<[i32]>), B(Box<[u8]>), C(Box<[String]>), D(Box<[u16]>), } #[no_mangle] // CHECK-LABEL: @get_len // CHECK: getelementptr inbounds // CHECK-NEXT: load // CHECK-NEXT: ret i64 // CHECK-NOT: switch pub fn get_len(arg: &K)->usize{ match arg { K::A(ref lst)=>lst.len(), K::B(ref lst)=>lst.len(), K::C(ref lst)=>lst.len(), K::D(ref lst)=>lst.len(), } } "} {"_id":"doc-en-rust-03f975a8d25650388370b27a01341ee6f7e6a2234bcf6a0a1d827001db81941d","title":"","text":" //@ compile-flags: -O // This regress since Rust version 1.72. //@ min-llvm-version: 18.1.4 #![crate_type = \"lib\"] use std::convert::TryInto; const N: usize = 24; #[no_mangle] // CHECK-LABEL: @example // CHECK-NOT: unwrap_failed pub fn example(a: Vec) -> u8 { if a.len() != 32 { return 0; } let a: [u8; 32] = a.try_into().unwrap(); a[15] + a[N] } "} {"_id":"doc-en-rust-e281b5a1f8828b3cc909f2562a53e8540735d74a2381090c9a5386068291d804","title":"","text":" //@ compile-flags: -O //@ min-llvm-version: 17 #![crate_type = \"lib\"] // CHECK-LABEL: @write_u8_variant_a // CHECK: getelementptr // CHECK-NEXT: icmp ugt #[no_mangle] pub fn write_u8_variant_a( bytes: &mut [u8], buf: u8, offset: usize, ) -> Option<&mut [u8]> { let buf = buf.to_le_bytes(); bytes .get_mut(offset..).and_then(|bytes| bytes.get_mut(..buf.len())) } "} {"_id":"doc-en-rust-7838ca78214a6ee13a087be8cc2ae6aca58d0f0c720a96241c39cf2d7fdcad1f","title":"","text":" // in Rust 1.73, -O and opt-level=3 optimizes differently //@ compile-flags: -C opt-level=3 //@ min-llvm-version: 17 #![crate_type = \"lib\"] use std::cmp::max; #[no_mangle] // CHECK-LABEL: @foo // CHECK-NOT: slice_start_index_len_fail // CHECK-NOT: unreachable pub fn foo(v: &mut Vec, size: usize)-> Option<&mut [u8]> { if v.len() > max(1, size) { let start = v.len() - size; Some(&mut v[start..]) } else { None } } "} {"_id":"doc-en-rust-d65100dd9bb73ba9d0b249df14f671d2e895bf46f659dab449ab263ba1f1de22","title":"","text":" //@ compile-flags: -O //@ min-llvm-version: 18 #![crate_type = \"lib\"] // CHECK-LABEL: @div2 // CHECK: ashr i32 %a, 1 // CHECK-NEXT: ret i32 #[no_mangle] pub fn div2(a: i32) -> i32 { a.div_euclid(2) } "} {"_id":"doc-en-rust-5a11803cbc7421cb836b5645b72141c0f0ddad499d0c81bd40e088f1edb0a766","title":"","text":" //@ compile-flags: -O #![crate_type = \"lib\"] const N: usize = 3; pub type T = u8; #[no_mangle] // CHECK-LABEL: @split_mutiple // CHECK-NOT: unreachable pub fn split_mutiple(slice: &[T]) -> (&[T], &[T]) { let len = slice.len() / N; slice.split_at(len * N) } "} {"_id":"doc-en-rust-0035aa3b0eaca9981e8ef57f78a52308876952e6cb8366776db1ab4385ec1dfa","title":"","text":" //@ compile-flags: -O //@ min-llvm-version: 17 #![crate_type = \"lib\"] #[no_mangle] // CHECK-LABEL: @foo // CHECK: {{.*}}: // CHECK: ret // CHECK-NOT: unreachable pub fn foo(arr: &mut [u32]) { for i in 0..arr.len() { for j in 0..i { assert!(j < arr.len()); } } } "} {"_id":"doc-en-rust-bf221456c6835cf0d5b999371402841d3ffd3eca443d079f355c1b5157df7edb","title":"","text":" //@ compile-flags: -O //@ min-llvm-version: 18 #![crate_type = \"lib\"] use std::ptr::NonNull; // CHECK-LABEL: @slice_ptr_len_1 // CHECK: {{.*}}: // CHECK-NEXT: ret i64 %ptr.1 #[no_mangle] pub fn slice_ptr_len_1(ptr: *const [u8]) -> usize { let ptr = ptr.cast_mut(); if let Some(ptr) = NonNull::new(ptr) { ptr.len() } else { // We know ptr is null, so we know ptr.wrapping_byte_add(1) is not null. NonNull::new(ptr.wrapping_byte_add(1)).unwrap().len() } } "} {"_id":"doc-en-rust-8cccc557bbb897a16095005ee621c7ec3b6bad7d7579ceda5c9e41f2620fd571","title":"","text":"resolve_module_only = visibility must resolve to a module resolve_macro_expected_found = expected {$expected}, found {$found} `{$macro_path}` resolve_remove_surrounding_derive = remove from the surrounding `derive()` resolve_add_as_non_derive = add as non-Derive macro `#[{$macro_path}]` "} {"_id":"doc-en-rust-76705641d9b1b09943b43f0635db853252b46fe094d6c94f1a3715054606022f","title":"","text":"#[derive(Diagnostic)] #[diag(resolve_module_only)] pub(crate) struct ModuleOnly(#[primary_span] pub(crate) Span); #[derive(Diagnostic, Default)] #[diag(resolve_macro_expected_found)] pub(crate) struct MacroExpectedFound<'a> { #[primary_span] pub(crate) span: Span, pub(crate) found: &'a str, pub(crate) expected: &'a str, pub(crate) macro_path: &'a str, #[subdiagnostic] pub(crate) remove_surrounding_derive: Option, #[subdiagnostic] pub(crate) add_as_non_derive: Option>, } #[derive(Subdiagnostic)] #[help(resolve_remove_surrounding_derive)] pub(crate) struct RemoveSurroundingDerive { #[primary_span] pub(crate) span: Span, } #[derive(Subdiagnostic)] #[help(resolve_add_as_non_derive)] pub(crate) struct AddAsNonDerive<'a> { pub(crate) macro_path: &'a str, } "} {"_id":"doc-en-rust-33d8a2d19c33d139f9d7bb5d075ec160af09eaba0d46a25f856f23858edaa665","title":"","text":"//! A bunch of methods and structures more or less related to resolving macros and //! interface provided by `Resolver` to macro expander. use crate::errors::{AddAsNonDerive, MacroExpectedFound, RemoveSurroundingDerive}; use crate::Namespace::*; use crate::{BuiltinMacroState, Determinacy}; use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet};"} {"_id":"doc-en-rust-298127f5e10575f2aa3954069880b8766885a810ced2c1417d5f2d0f380809e7","title":"","text":"}; if let Some((article, expected)) = unexpected_res { let path_str = pprust::path_to_string(path); let msg = format!(\"expected {}, found {} `{}`\", expected, res.descr(), path_str); self.tcx .sess .struct_span_err(path.span, &msg) .span_label(path.span, format!(\"not {} {}\", article, expected)) .emit(); let mut err = MacroExpectedFound { span: path.span, expected, found: res.descr(), macro_path: &path_str, ..Default::default() // Subdiagnostics default to None }; // Suggest moving the macro out of the derive() if the macro isn't Derive if !path.span.from_expansion() && kind == MacroKind::Derive && ext.macro_kind() != MacroKind::Derive { err.remove_surrounding_derive = Some(RemoveSurroundingDerive { span: path.span }); err.add_as_non_derive = Some(AddAsNonDerive { macro_path: &path_str }); } let mut err = self.tcx.sess.create_err(err); err.span_label(path.span, format!(\"not {} {}\", article, expected)); err.emit(); return Ok((self.dummy_ext(kind), Res::Err)); }"} {"_id":"doc-en-rust-ab8f94842075ac92bed6b179ffeac1da558914494c94193e7fe448ad45e97ec5","title":"","text":"| LL | #[derive(inline)] | ^^^^^^ not a derive macro | help: remove from the surrounding `derive()` --> $DIR/macro-path-prelude-fail-4.rs:1:10 | LL | #[derive(inline)] | ^^^^^^ = help: add as non-Derive macro `#[inline]` error: aborting due to previous error"} {"_id":"doc-en-rust-178eef223314271eaf255cfdb37a0165301b246581a44626dba4149fb22cb2f6","title":"","text":" #[derive(Clone, Debug)] // OK struct S; #[derive(Debug, inline)] //~ ERROR expected derive macro, found built-in attribute `inline` struct T; #[derive(inline, Debug)] //~ ERROR expected derive macro, found built-in attribute `inline` struct U; fn main() {} "} {"_id":"doc-en-rust-f2664f2e9882bb354b52801a467176e5e16d66ce56bd50eeae02f3708fb4bc6c","title":"","text":" error: expected derive macro, found built-in attribute `inline` --> $DIR/macro-path-prelude-fail-5.rs:4:17 | LL | #[derive(Debug, inline)] | ^^^^^^ not a derive macro | help: remove from the surrounding `derive()` --> $DIR/macro-path-prelude-fail-5.rs:4:17 | LL | #[derive(Debug, inline)] | ^^^^^^ = help: add as non-Derive macro `#[inline]` error: expected derive macro, found built-in attribute `inline` --> $DIR/macro-path-prelude-fail-5.rs:7:10 | LL | #[derive(inline, Debug)] | ^^^^^^ not a derive macro | help: remove from the surrounding `derive()` --> $DIR/macro-path-prelude-fail-5.rs:7:10 | LL | #[derive(inline, Debug)] | ^^^^^^ = help: add as non-Derive macro `#[inline]` error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-316f6238c0b0aedc554c82c8bd6238c75337dad1168877a35a664513e0971cff","title":"","text":"| LL | #[derive(my_macro_attr)] | ^^^^^^^^^^^^^ not a derive macro | help: remove from the surrounding `derive()` --> $DIR/macro-namespace-reserved-2.rs:53:10 | LL | #[derive(my_macro_attr)] | ^^^^^^^^^^^^^ = help: add as non-Derive macro `#[my_macro_attr]` error: can't use a procedural macro from the same crate that defines it --> $DIR/macro-namespace-reserved-2.rs:56:10"} {"_id":"doc-en-rust-abc5309373c2e34d4bf1f051addfd3dd68b1bef77f4cfa38b60d8dfef4faff55","title":"","text":"| LL | #[derive(crate::my_macro)] | ^^^^^^^^^^^^^^^ not a derive macro | help: remove from the surrounding `derive()` --> $DIR/macro-namespace-reserved-2.rs:50:10 | LL | #[derive(crate::my_macro)] | ^^^^^^^^^^^^^^^ = help: add as non-Derive macro `#[crate::my_macro]` error: cannot find macro `my_macro_attr` in this scope --> $DIR/macro-namespace-reserved-2.rs:28:5"} {"_id":"doc-en-rust-f259d33995b84327300ae9723317634e23e2f2bd89b8f6f6deb96734e85a2b5d","title":"","text":"| LL | #[derive(rustfmt::skip)] | ^^^^^^^^^^^^^ not a derive macro | help: remove from the surrounding `derive()` --> $DIR/tool-attributes-misplaced-2.rs:1:10 | LL | #[derive(rustfmt::skip)] | ^^^^^^^^^^^^^ = help: add as non-Derive macro `#[rustfmt::skip]` error: expected macro, found tool attribute `rustfmt::skip` --> $DIR/tool-attributes-misplaced-2.rs:5:5"} {"_id":"doc-en-rust-de296a669f888411831f4186c2ed14f8a5dfb85cda31ecae11ad5dad20611913","title":"","text":"#[macro_use] mod print; mod session_diagnostics; #[cfg(all(unix, any(target_env = \"gnu\", target_os = \"macos\")))] mod signal_handler; #[cfg(not(all(unix, any(target_env = \"gnu\", target_os = \"macos\"))))] mod signal_handler { /// On platforms which don't support our signal handler's requirements, /// simply use the default signal handler provided by std. pub(super) fn install() {} } use crate::session_diagnostics::{ RLinkEmptyVersionNumber, RLinkEncodingVersionMismatch, RLinkRustcVersionMismatch,"} {"_id":"doc-en-rust-56d4968f271bcd26a752042eee64ee33fab114d8cd71ae0cad3d76e475fa79c7","title":"","text":"} } #[cfg(all(unix, any(target_env = \"gnu\", target_os = \"macos\")))] mod signal_handler { extern \"C\" { fn backtrace_symbols_fd( buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int, ); } extern \"C\" fn print_stack_trace(_: libc::c_int) { const MAX_FRAMES: usize = 256; static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] = [std::ptr::null_mut(); MAX_FRAMES]; unsafe { let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32); if depth == 0 { return; } backtrace_symbols_fd(STACK_TRACE.as_ptr(), depth, 2); } } /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the /// process, print a stack trace and then exit. pub(super) fn install() { use std::alloc::{alloc, Layout}; unsafe { let alt_stack_size: usize = min_sigstack_size() + 64 * 1024; let mut alt_stack: libc::stack_t = std::mem::zeroed(); alt_stack.ss_sp = alloc(Layout::from_size_align(alt_stack_size, 1).unwrap()).cast(); alt_stack.ss_size = alt_stack_size; libc::sigaltstack(&alt_stack, std::ptr::null_mut()); let mut sa: libc::sigaction = std::mem::zeroed(); sa.sa_sigaction = print_stack_trace as libc::sighandler_t; sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK; libc::sigemptyset(&mut sa.sa_mask); libc::sigaction(libc::SIGSEGV, &sa, std::ptr::null_mut()); } } /// Modern kernels on modern hardware can have dynamic signal stack sizes. #[cfg(any(target_os = \"linux\", target_os = \"android\"))] fn min_sigstack_size() -> usize { const AT_MINSIGSTKSZ: core::ffi::c_ulong = 51; let dynamic_sigstksz = unsafe { libc::getauxval(AT_MINSIGSTKSZ) }; // If getauxval couldn't find the entry, it returns 0, // so take the higher of the \"constant\" and auxval. // This transparently supports older kernels which don't provide AT_MINSIGSTKSZ libc::MINSIGSTKSZ.max(dynamic_sigstksz as _) } /// Not all OS support hardware where this is needed. #[cfg(not(any(target_os = \"linux\", target_os = \"android\")))] fn min_sigstack_size() -> usize { libc::MINSIGSTKSZ } } #[cfg(not(all(unix, any(target_env = \"gnu\", target_os = \"macos\"))))] mod signal_handler { pub(super) fn install() {} } pub fn main() -> ! { let start_time = Instant::now(); let start_rss = get_resident_set_size();"} {"_id":"doc-en-rust-7d87cd3362eaa3e2313c1adae1dac848e4031edc560f546f90c5c08fc3fdbfde","title":"","text":" //! Signal handler for rustc //! Primarily used to extract a backtrace from stack overflow use std::alloc::{alloc, Layout}; use std::{fmt, mem, ptr}; extern \"C\" { fn backtrace_symbols_fd(buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int); } fn backtrace_stderr(buffer: &[*mut libc::c_void]) { let size = buffer.len().try_into().unwrap_or_default(); unsafe { backtrace_symbols_fd(buffer.as_ptr(), size, libc::STDERR_FILENO) }; } /// Unbuffered, unsynchronized writer to stderr. /// /// Only acceptable because everything will end soon anyways. struct RawStderr(()); impl fmt::Write for RawStderr { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { let ret = unsafe { libc::write(libc::STDERR_FILENO, s.as_ptr().cast(), s.len()) }; if ret == -1 { Err(fmt::Error) } else { Ok(()) } } } /// We don't really care how many bytes we actually get out. SIGSEGV comes for our head. /// Splash stderr with letters of our own blood to warn our friends about the monster. macro raw_errln($tokens:tt) { let _ = ::core::fmt::Write::write_fmt(&mut RawStderr(()), format_args!($tokens)); let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), 'n'); } /// Signal handler installed for SIGSEGV extern \"C\" fn print_stack_trace(_: libc::c_int) { const MAX_FRAMES: usize = 256; // Reserve data segment so we don't have to malloc in a signal handler, which might fail // in incredibly undesirable and unexpected ways due to e.g. the allocator deadlocking static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] = [ptr::null_mut(); MAX_FRAMES]; let stack = unsafe { // Collect return addresses let depth = libc::backtrace(STACK_TRACE.as_mut_ptr(), MAX_FRAMES as i32); if depth == 0 { return; } &STACK_TRACE.as_slice()[0..(depth as _)] }; // Just a stack trace is cryptic. Explain what we're doing. raw_errln!(\"error: rustc interrupted by SIGSEGV, printing backtracen\"); let mut written = 1; let mut consumed = 0; // Begin elaborating return addrs into symbols and writing them directly to stderr // Most backtraces are stack overflow, most stack overflows are from recursion // Check for cycles before writing 250 lines of the same ~5 symbols let cycled = |(runner, walker)| runner == walker; let mut cyclic = false; if let Some(period) = stack.iter().skip(1).step_by(2).zip(stack).position(cycled) { let period = period.saturating_add(1); // avoid \"what if wrapped?\" branches let Some(offset) = stack.iter().skip(period).zip(stack).position(cycled) else { // impossible. return; }; // Count matching trace slices, else we could miscount \"biphasic cycles\" // with the same period + loop entry but a different inner loop let next_cycle = stack[offset..].chunks_exact(period).skip(1); let cycles = 1 + next_cycle .zip(stack[offset..].chunks_exact(period)) .filter(|(next, prev)| next == prev) .count(); backtrace_stderr(&stack[..offset]); written += offset; consumed += offset; if cycles > 1 { raw_errln!(\"n### cycle encountered after {offset} frames with period {period}\"); backtrace_stderr(&stack[consumed..consumed + period]); raw_errln!(\"### recursed {cycles} timesn\"); written += period + 4; consumed += period * cycles; cyclic = true; }; } let rem = &stack[consumed..]; backtrace_stderr(rem); raw_errln!(\"\"); written += rem.len() + 1; let random_depth = || 8 * 16; // chosen by random diceroll (2d20) if cyclic || stack.len() > random_depth() { // technically speculation, but assert it with confidence anyway. // rustc only arrived in this signal handler because bad things happened // and this message is for explaining it's not the programmer's fault raw_errln!(\"note: rustc unexpectedly overflowed its stack! this is a bug\"); written += 1; } if stack.len() == MAX_FRAMES { raw_errln!(\"note: maximum backtrace depth reached, frames may have been lost\"); written += 1; } raw_errln!(\"note: we would appreciate a report at https://github.com/rust-lang/rust\"); written += 1; if written > 24 { // We probably just scrolled the earlier \"we got SIGSEGV\" message off the terminal raw_errln!(\"note: backtrace dumped due to SIGSEGV! resuming signal\"); }; } /// When SIGSEGV is delivered to the process, print a stack trace and then exit. pub(super) fn install() { unsafe { let alt_stack_size: usize = min_sigstack_size() + 64 * 1024; let mut alt_stack: libc::stack_t = mem::zeroed(); alt_stack.ss_sp = alloc(Layout::from_size_align(alt_stack_size, 1).unwrap()).cast(); alt_stack.ss_size = alt_stack_size; libc::sigaltstack(&alt_stack, ptr::null_mut()); let mut sa: libc::sigaction = mem::zeroed(); sa.sa_sigaction = print_stack_trace as libc::sighandler_t; sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK; libc::sigemptyset(&mut sa.sa_mask); libc::sigaction(libc::SIGSEGV, &sa, ptr::null_mut()); } } /// Modern kernels on modern hardware can have dynamic signal stack sizes. #[cfg(any(target_os = \"linux\", target_os = \"android\"))] fn min_sigstack_size() -> usize { const AT_MINSIGSTKSZ: core::ffi::c_ulong = 51; let dynamic_sigstksz = unsafe { libc::getauxval(AT_MINSIGSTKSZ) }; // If getauxval couldn't find the entry, it returns 0, // so take the higher of the \"constant\" and auxval. // This transparently supports older kernels which don't provide AT_MINSIGSTKSZ libc::MINSIGSTKSZ.max(dynamic_sigstksz as _) } /// Not all OS support hardware where this is needed. #[cfg(not(any(target_os = \"linux\", target_os = \"android\")))] fn min_sigstack_size() -> usize { libc::MINSIGSTKSZ } "} {"_id":"doc-en-rust-663644571deade5e1e9f8bcc536072e77b115f1234656de9786608e8523aa947","title":"","text":"[[package]] name = \"gccjit\" version = \"1.0.0\" source = \"git+https://github.com/antoyo/gccjit.rs#eefb8c662d61477f34b7c32d26bcda5f1ef08432\" source = \"git+https://github.com/antoyo/gccjit.rs#fe242b7eb26980e6c78859d51c8d4cc1e43381a3\" dependencies = [ \"gccjit_sys\", ]"} {"_id":"doc-en-rust-361fa5771e4e991ace4556712031d6dd8a97aaf22c93fdcbcb1a02576fe60fc1","title":"","text":"[[package]] name = \"gccjit_sys\" version = \"0.0.1\" source = \"git+https://github.com/antoyo/gccjit.rs#eefb8c662d61477f34b7c32d26bcda5f1ef08432\" source = \"git+https://github.com/antoyo/gccjit.rs#fe242b7eb26980e6c78859d51c8d4cc1e43381a3\" dependencies = [ \"libc 0.1.12\", \"libc\", ] [[package]]"} {"_id":"doc-en-rust-3c5fa3ddcb57d1977cae1486cee45f6ce65035093021a97ecdd6679c027e637c","title":"","text":"checksum = \"7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753\" dependencies = [ \"cfg-if\", \"libc 0.2.112\", \"libc\", \"wasi\", ]"} {"_id":"doc-en-rust-e9d1464466aede799fa3e194e830bd3e76f067424054a8d53d36952a7be5661e","title":"","text":"source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33\" dependencies = [ \"libc 0.2.112\", \"libc\", ] [[package]]"} {"_id":"doc-en-rust-46ffab6f5e8d8c09612f9cc7eb55f2bb4bf8fb4d4c031eb4291ed63d2384f1f7","title":"","text":"dependencies = [ \"fm\", \"getopts\", \"libc 0.2.112\", \"libc\", \"num_cpus\", \"termcolor\", \"threadpool\","} {"_id":"doc-en-rust-d036240af68a05d3ffe39ca80ecc037d58ade0a3df6165c1194e5f4fc3bc977e","title":"","text":"[[package]] name = \"libc\" version = \"0.1.12\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"e32a70cf75e5846d53a673923498228bbec6a8624708a9ea5645f075d6276122\" [[package]] name = \"libc\" version = \"0.2.112\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"1b03d17f364a3a042d5e5d46b053bbbf82c92c9430c592dd4c064dc6ee997125\""} {"_id":"doc-en-rust-104102bd782f0fba6e1893fe933f36625b8e7ca0b182f56ef80c20831a8f995a","title":"","text":"checksum = \"05499f3756671c15885fee9034446956fff3f243d6077b91e5767df161f766b3\" dependencies = [ \"hermit-abi\", \"libc 0.2.112\", \"libc\", ] [[package]]"} {"_id":"doc-en-rust-0c11f4f055b746444255c2800a86d7aafc783b078af163c9c1c4881c7e5e72cc","title":"","text":"source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"2e7573632e6454cf6b99d7aac4ccca54be06da05aca2ef7423d22d27d4d4bcd8\" dependencies = [ \"libc 0.2.112\", \"libc\", \"rand_chacha\", \"rand_core\", \"rand_hc\","} {"_id":"doc-en-rust-2eecb4d630c95336b203e9b2091ab59bc53288e85a38694fc6bebfc5d243245c","title":"","text":"checksum = \"dac1c663cfc93810f88aed9b8941d48cabf856a1b111c29a40439018d870eb22\" dependencies = [ \"cfg-if\", \"libc 0.2.112\", \"libc\", \"rand\", \"redox_syscall\", \"remove_dir_all\","} {"_id":"doc-en-rust-aa1d8a9122109f8c63077083893f7bc934831c9f74585db4a477e61f3af72230","title":"","text":"source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6\" dependencies = [ \"libc 0.2.112\", \"libc\", ] [[package]]"} {"_id":"doc-en-rust-82338ff14fdeb563be9f15dba88e5a990a0972735c524766b9a651264410e8c7","title":"","text":"// index position where it *should have been*, which is *after* the previous one. if let Some(provided_idx) = provided_idx { prev = provided_idx.index() as i64; continue; } let idx = ProvidedIdx::from_usize((prev + 1) as usize); if let None = provided_idx && let Some((_, arg_span)) = provided_arg_tys.get(idx) { if let Some((_, arg_span)) = provided_arg_tys.get(idx) { prev += 1; // There is a type that was *not* found anywhere, so it isn't a move, but a // replacement and we look at what type it should have been. This will allow us // To suggest a multipart suggestion when encountering `foo(1, \"\")` where the def"} {"_id":"doc-en-rust-5db59d44dfd59430b6efc69de60da8b1ad5cfdf9008caa4ef83dd3609b6efc44","title":"","text":" struct A; struct B; fn f(b1: B, b2: B, a2: C) {} //~ ERROR E0412 fn main() { f(A, A, B, C); //~ ERROR E0425 //~^ ERROR E0061 } "} {"_id":"doc-en-rust-8f05fa786ea1a47ff1234efdfdc09c56fdf7751d44c30504810bacffadd964b6","title":"","text":" error[E0412]: cannot find type `C` in this scope --> $DIR/issue-109831.rs:4:24 | LL | struct A; | --------- similarly named struct `A` defined here ... LL | fn f(b1: B, b2: B, a2: C) {} | ^ | help: a struct with a similar name exists | LL | fn f(b1: B, b2: B, a2: A) {} | ~ help: you might be missing a type parameter | LL | fn f(b1: B, b2: B, a2: C) {} | +++ error[E0425]: cannot find value `C` in this scope --> $DIR/issue-109831.rs:7:16 | LL | struct A; | --------- similarly named unit struct `A` defined here ... LL | f(A, A, B, C); | ^ help: a unit struct with a similar name exists: `A` error[E0061]: this function takes 3 arguments but 4 arguments were supplied --> $DIR/issue-109831.rs:7:5 | LL | f(A, A, B, C); | ^ - - - unexpected argument | | | | | expected `B`, found `A` | expected `B`, found `A` | note: function defined here --> $DIR/issue-109831.rs:4:4 | LL | fn f(b1: B, b2: B, a2: C) {} | ^ ----- ----- ----- help: remove the extra argument | LL - f(A, A, B, C); LL + f(/* B */, /* B */, B); | error: aborting due to 3 previous errors Some errors have detailed explanations: E0061, E0412, E0425. For more information about an error, try `rustc --explain E0061`. "} {"_id":"doc-en-rust-81fb057c353b530318402da780dbf61e2e7e4dc6c054d5966d6d4e5a18479b74","title":"","text":"let tcx = self.tcx; let def_id = instance.def_id(); let containing_scope = get_containing_scope(self, instance); let (containing_scope, is_method) = get_containing_scope(self, instance); let span = tcx.def_span(def_id); let loc = self.lookup_debug_loc(span.lo()); let file_metadata = file_metadata(self, &loc.file);"} {"_id":"doc-en-rust-273c7e6bbc3125a4901e982b47f083a82e0bb3bf34ad31bbe719cd431d914e8b","title":"","text":"} } unsafe { return llvm::LLVMRustDIBuilderCreateFunction( // When we're adding a method to a type DIE, we only want a DW_AT_declaration there, because // LLVM LTO can't unify type definitions when a child DIE is a full subprogram definition. // When we use this `decl` below, the subprogram definition gets created at the CU level // with a DW_AT_specification pointing back to the type's declaration. let decl = is_method.then(|| unsafe { llvm::LLVMRustDIBuilderCreateMethod( DIB(self), containing_scope, name.as_ptr().cast(), name.len(), linkage_name.as_ptr().cast(), linkage_name.len(), file_metadata, loc.line, function_type_metadata, flags, spflags & !DISPFlags::SPFlagDefinition, template_parameters, ) }); return unsafe { llvm::LLVMRustDIBuilderCreateFunction( DIB(self), containing_scope, name.as_ptr().cast(),"} {"_id":"doc-en-rust-004b0f27c043622f4cf292a91cb7d1d01dc2407189414de16781512a28d9c3d7","title":"","text":"spflags, maybe_definition_llfn, template_parameters, None, ); } decl, ) }; fn get_function_signature<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>,"} {"_id":"doc-en-rust-577347ff97a897de52aeafa2b5ea174a38d8065492229dedd255a8acc7029c42","title":"","text":"names } /// Returns a scope, plus `true` if that's a type scope for \"class\" methods, /// otherwise `false` for plain namespace scopes. fn get_containing_scope<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>, ) -> &'ll DIScope { ) -> (&'ll DIScope, bool) { // First, let's see if this is a method within an inherent impl. Because // if yes, we want to make the result subroutine DIE a child of the // subroutine's self-type. let self_type = cx.tcx.impl_of_method(instance.def_id()).and_then(|impl_def_id| { if let Some(impl_def_id) = cx.tcx.impl_of_method(instance.def_id()) { // If the method does *not* belong to a trait, proceed if cx.tcx.trait_id_of_impl(impl_def_id).is_none() { let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions("} {"_id":"doc-en-rust-812257b9bdeb685c50874e6f128920f13b777316032b980e574632fdda214a1c","title":"","text":"// Only \"class\" methods are generally understood by LLVM, // so avoid methods on other types (e.g., `<*mut T>::null`). match impl_self_ty.kind() { ty::Adt(def, ..) if !def.is_box() => { // Again, only create type information if full debuginfo is enabled if cx.sess().opts.debuginfo == DebugInfo::Full && !impl_self_ty.has_param() { Some(type_di_node(cx, impl_self_ty)) } else { Some(namespace::item_namespace(cx, def.did())) } if let ty::Adt(def, ..) = impl_self_ty.kind() && !def.is_box() { // Again, only create type information if full debuginfo is enabled if cx.sess().opts.debuginfo == DebugInfo::Full && !impl_self_ty.has_param() { return (type_di_node(cx, impl_self_ty), true); } else { return (namespace::item_namespace(cx, def.did()), false); } _ => None, } } else { // For trait method impls we still use the \"parallel namespace\" // strategy None } }); } self_type.unwrap_or_else(|| { namespace::item_namespace( cx, DefId { krate: instance.def_id().krate, index: cx .tcx .def_key(instance.def_id()) .parent .expect(\"get_containing_scope: missing parent?\"), }, ) }) let scope = namespace::item_namespace( cx, DefId { krate: instance.def_id().krate, index: cx .tcx .def_key(instance.def_id()) .parent .expect(\"get_containing_scope: missing parent?\"), }, ); (scope, false) } }"} {"_id":"doc-en-rust-0be7240ef85bc21347d918bc5d890d696866e23a0db884eb854b166a26b2507e","title":"","text":"Decl: Option<&'a DIDescriptor>, ) -> &'a DISubprogram; pub fn LLVMRustDIBuilderCreateMethod<'a>( Builder: &DIBuilder<'a>, Scope: &'a DIDescriptor, Name: *const c_char, NameLen: size_t, LinkageName: *const c_char, LinkageNameLen: size_t, File: &'a DIFile, LineNo: c_uint, Ty: &'a DIType, Flags: DIFlags, SPFlags: DISPFlags, TParam: &'a DIArray, ) -> &'a DISubprogram; pub fn LLVMRustDIBuilderCreateBasicType<'a>( Builder: &DIBuilder<'a>, Name: *const c_char,"} {"_id":"doc-en-rust-4e8f316ef48671535b797caecef9dca4f9964f383067bca8b9067100a3c86f70","title":"","text":"return wrap(Sub); } extern \"C\" LLVMMetadataRef LLVMRustDIBuilderCreateMethod( LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, size_t NameLen, const char *LinkageName, size_t LinkageNameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, LLVMRustDIFlags Flags, LLVMRustDISPFlags SPFlags, LLVMMetadataRef TParam) { DITemplateParameterArray TParams = DITemplateParameterArray(unwrap(TParam)); DISubprogram::DISPFlags llvmSPFlags = fromRust(SPFlags); DINode::DIFlags llvmFlags = fromRust(Flags); DISubprogram *Sub = Builder->createMethod( unwrapDI(Scope), StringRef(Name, NameLen), StringRef(LinkageName, LinkageNameLen), unwrapDI(File), LineNo, unwrapDI(Ty), 0, 0, nullptr, // VTable params aren't used llvmFlags, llvmSPFlags, TParams); return wrap(Sub); } extern \"C\" LLVMMetadataRef LLVMRustDIBuilderCreateBasicType( LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen, uint64_t SizeInBits, unsigned Encoding) {"} {"_id":"doc-en-rust-04b039140e9d55e2882bf916372c154de5846db9f452826e34f921a8d9a56423","title":"","text":" # ignore-cross-compile include ../tools.mk # With the upgrade to LLVM 16, this was getting: # # error: Cannot represent a difference across sections # # The error stemmed from DI function definitions under type scopes, fixed by # only declaring in type scope and defining the subprogram elsewhere. all: $(RUSTC) lib.rs --test -C lto=fat -C debuginfo=2 -C incremental=$(TMPDIR)/inc-fat "} {"_id":"doc-en-rust-3832c1dda031dac89de40e50c7c43769c33998421d496b0b2e5f0bd53e2bae8d","title":"","text":" extern crate alloc; #[cfg(test)] mod tests { #[test] fn something_alloc() { assert_eq!(Vec::::new(), Vec::::new()); } } "} {"_id":"doc-en-rust-7b8470178e22d34a4a768d3b0d5d1dd10b71d7a45f797f4951a866a990d3363e","title":"","text":"/// use std::sync::Arc; /// use std::task::{Context, Poll, Wake}; /// use std::thread::{self, Thread}; /// use core::pin::pin; /// /// /// A waker that wakes up the current thread when called. /// struct ThreadWaker(Thread);"} {"_id":"doc-en-rust-dd8d3690ad863d2d9c58b8048cedb838a3086a0681cb8102d208db01420cc335","title":"","text":"/// /// Run a future to completion on the current thread. /// fn block_on(fut: impl Future) -> T { /// // Pin the future so it can be polled. /// let mut fut = Box::pin(fut); /// let mut fut = pin!(fut); /// /// // Create a new context to be passed to the future. /// let t = thread::current();"} {"_id":"doc-en-rust-b6c985e48cd1f939c7fb5148d0cd1a1217f5751435946274ba643d0c652b1239","title":"","text":"eprint('ERROR: vendoring required, but vendor directory does not exist.') eprint(' Run `cargo vendor {}` to initialize the ' 'vendor directory.'.format(sync_dirs)) eprint('Alternatively, use the pre-vendored `rustc-src` dist component.') eprint(' Alternatively, use the pre-vendored `rustc-src` dist component.') eprint(' To get a stable/beta/nightly version, download it from: ') eprint(' ' 'https://forge.rust-lang.org/infra/other-installation-methods.html#source-code') eprint(' To get a specific commit version, download it using the below URL,') eprint(' replacing with a specific commit checksum: ') eprint(' ' 'https://ci-artifacts.rust-lang.org/rustc-builds//rustc-nightly-src.tar.xz') eprint(' Once you have the source downloaded, place the vendor directory') eprint(' from the archive in the root of the rust project.') raise Exception(\"{} not found\".format(vendor_dir)) if not os.path.exists(cargo_dir):"} {"_id":"doc-en-rust-d7514bb3a9004d913bf53caa85671efa145055bdc25ac192686e79ecb01ca9db","title":"","text":"Change this file to make users of the `download-ci-llvm` configuration download a new version of LLVM from CI, even if the LLVM submodule hasn’t changed. Last change is for: https://github.com/rust-lang/rust/pull/109373 Last change is for: https://github.com/rust-lang/rust/pull/96971 "} {"_id":"doc-en-rust-1d3afb7741b3198cd8e331375d346b9b28ad7921eda43d4ba4a96cc7a6087cba","title":"","text":" // run-fail // check-run-results // exec-env:RUST_BACKTRACE=0 // Test that we format the panic message only once. // Regression test for https://github.com/rust-lang/rust/issues/110717 use std::fmt; struct PrintOnFmt; impl fmt::Display for PrintOnFmt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { eprintln!(\"fmt\"); f.write_str(\"PrintOnFmt\") } } fn main() { panic!(\"{}\", PrintOnFmt) } "} {"_id":"doc-en-rust-906341e3370c619a372661afedbd5f1fd1c15cf61a76ecfbf326be680c6774b3","title":"","text":" fmt thread 'main' panicked at 'PrintOnFmt', $DIR/fmt-only-once.rs:20:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace "} {"_id":"doc-en-rust-d9b8aeab89561be9d97900d8e63bb7711fe527faa07aaea90e66896576768eed","title":"","text":"if self.target.contains(\"windows\") { build_cred( \"cargo-credential-wincred\", \"src/tools/cargo/crates/credential/cargo-credential-wincred\", \"src/tools/cargo/credential/cargo-credential-wincred\", ); } if self.target.contains(\"apple-darwin\") { build_cred( \"cargo-credential-macos-keychain\", \"src/tools/cargo/crates/credential/cargo-credential-macos-keychain\", \"src/tools/cargo/credential/cargo-credential-macos-keychain\", ); } build_cred( \"cargo-credential-1password\", \"src/tools/cargo/crates/credential/cargo-credential-1password\", \"src/tools/cargo/credential/cargo-credential-1password\", ); cargo_bin_path }"} {"_id":"doc-en-rust-e2b19d6a339d4505b28b529b801ebf24dfa18df00439d1310e2e20b8774feecd","title":"","text":" // check-pass #![feature(inline_const)] fn main() { let _my_usize = const { let a = 10_usize; let b: &'_ usize = &a; *b }; } "} {"_id":"doc-en-rust-6fd3adef6cdef84f2c60b79c2dba15e9225f9a1a08739662d82344d93cd06996","title":"","text":"} } impl Visitor<'_> for CanConstProp { impl<'tcx> Visitor<'tcx> for CanConstProp { fn visit_place(&mut self, place: &Place<'tcx>, mut context: PlaceContext, loc: Location) { use rustc_middle::mir::visit::PlaceContext::*; // Dereferencing just read the addess of `place.local`. if place.projection.first() == Some(&PlaceElem::Deref) { context = NonMutatingUse(NonMutatingUseContext::Copy); } self.visit_local(place.local, context, loc); self.visit_projection(place.as_ref(), context, loc); } fn visit_local(&mut self, local: Local, context: PlaceContext, _: Location) { use rustc_middle::mir::visit::PlaceContext::*; match context { // Projections are fine, because `&mut foo.x` will be caught by // `MutatingUseContext::Borrow` elsewhere. MutatingUse(MutatingUseContext::Projection) // These are just stores, where the storing is not propagatable, but there may be later // mutations of the same local via `Store` | MutatingUse(MutatingUseContext::Call)"} {"_id":"doc-en-rust-fc357a6f51e9d232ffc749d71901d0e6013b2cd051de03886c9f9d3a24bb3205","title":"","text":"NonMutatingUse(NonMutatingUseContext::Copy) | NonMutatingUse(NonMutatingUseContext::Move) | NonMutatingUse(NonMutatingUseContext::Inspect) | NonMutatingUse(NonMutatingUseContext::Projection) | NonMutatingUse(NonMutatingUseContext::PlaceMention) | NonUse(_) => {}"} {"_id":"doc-en-rust-7ea96dc80132c28d530f8d64135f62ed99df6c11b9df30427247a1b12017ee8d","title":"","text":"trace!(\"local {:?} can't be propagated because it's used: {:?}\", local, context); self.can_const_prop[local] = ConstPropMode::NoPropagation; } MutatingUse(MutatingUseContext::Projection) | NonMutatingUse(NonMutatingUseContext::Projection) => bug!(\"visit_place should not pass {context:?} for {local:?}\"), } } }"} {"_id":"doc-en-rust-821b034e81071b732d9b4ec2cdff4ab205d2a217cb90a172ceeb5969af622e1c","title":"","text":" - // MIR for `fn0` before ConstProp + // MIR for `fn0` after ConstProp fn fn0() -> bool { let mut _0: bool; // return place in scope 0 at $DIR/address_of_pair.rs:+0:17: +0:21 let mut _1: !; // in scope 0 at $DIR/address_of_pair.rs:+0:22: +9:2 let mut _2: (i32, bool); // in scope 0 at $DIR/address_of_pair.rs:+1:9: +1:17 let _4: (); // in scope 0 at $DIR/address_of_pair.rs:+4:5: +6:6 let mut _6: bool; // in scope 0 at $DIR/address_of_pair.rs:+7:16: +7:22 scope 1 { debug pair => _2; // in scope 1 at $DIR/address_of_pair.rs:+1:9: +1:17 let _3: *mut bool; // in scope 1 at $DIR/address_of_pair.rs:+2:9: +2:12 scope 2 { debug ptr => _3; // in scope 2 at $DIR/address_of_pair.rs:+2:9: +2:12 let _5: bool; // in scope 2 at $DIR/address_of_pair.rs:+7:9: +7:12 scope 3 { } scope 4 { debug ret => _5; // in scope 4 at $DIR/address_of_pair.rs:+7:9: +7:12 } } } bb0: { StorageLive(_2); // scope 0 at $DIR/address_of_pair.rs:+1:9: +1:17 _2 = (const 1_i32, const false); // scope 0 at $DIR/address_of_pair.rs:+1:20: +1:30 StorageLive(_3); // scope 1 at $DIR/address_of_pair.rs:+2:9: +2:12 _3 = &raw mut (_2.1: bool); // scope 1 at $SRC_DIR/core/src/ptr/mod.rs:LL:COL _2 = (const 1_i32, const false); // scope 2 at $DIR/address_of_pair.rs:+3:5: +3:22 StorageLive(_4); // scope 2 at $DIR/address_of_pair.rs:+4:5: +6:6 (*_3) = const true; // scope 3 at $DIR/address_of_pair.rs:+5:9: +5:20 _4 = const (); // scope 3 at $DIR/address_of_pair.rs:+4:5: +6:6 StorageDead(_4); // scope 2 at $DIR/address_of_pair.rs:+6:5: +6:6 StorageLive(_5); // scope 2 at $DIR/address_of_pair.rs:+7:9: +7:12 StorageLive(_6); // scope 2 at $DIR/address_of_pair.rs:+7:16: +7:22 _6 = (_2.1: bool); // scope 2 at $DIR/address_of_pair.rs:+7:16: +7:22 _5 = Not(move _6); // scope 2 at $DIR/address_of_pair.rs:+7:15: +7:22 StorageDead(_6); // scope 2 at $DIR/address_of_pair.rs:+7:21: +7:22 _0 = _5; // scope 4 at $DIR/address_of_pair.rs:+8:12: +8:15 StorageDead(_5); // scope 2 at $DIR/address_of_pair.rs:+9:1: +9:2 StorageDead(_3); // scope 1 at $DIR/address_of_pair.rs:+9:1: +9:2 StorageDead(_2); // scope 0 at $DIR/address_of_pair.rs:+9:1: +9:2 return; // scope 0 at $DIR/address_of_pair.rs:+9:2: +9:2 } } "} {"_id":"doc-en-rust-31bddfa01e47235dee4f6e08a505da560fa3b1f9d19431bf3c2634af7b0d7c30","title":"","text":" // unit-test: ConstProp // EMIT_MIR address_of_pair.fn0.ConstProp.diff pub fn fn0() -> bool { let mut pair = (1, false); let ptr = core::ptr::addr_of_mut!(pair.1); pair = (1, false); unsafe { *ptr = true; } let ret = !pair.1; return ret; } pub fn main() { println!(\"{}\", fn0()); } "} {"_id":"doc-en-rust-b968d6af7ddf633d31d20fbeaa179c116008563b10566dde59e25c6b69f2b3a2","title":"","text":"bb0: { StorageLive(_1); // scope 0 at $DIR/const_prop_miscompile.rs:+1:9: +1:14 - _1 = (const 1_i32,); // scope 0 at $DIR/const_prop_miscompile.rs:+1:17: +1:21 + _1 = const (1_i32,); // scope 0 at $DIR/const_prop_miscompile.rs:+1:17: +1:21 _1 = (const 1_i32,); // scope 0 at $DIR/const_prop_miscompile.rs:+1:17: +1:21 StorageLive(_2); // scope 1 at $DIR/const_prop_miscompile.rs:+2:5: +4:6 StorageLive(_3); // scope 2 at $DIR/const_prop_miscompile.rs:+3:10: +3:22 _3 = &raw mut (_1.0: i32); // scope 2 at $DIR/const_prop_miscompile.rs:+3:10: +3:22"} {"_id":"doc-en-rust-8b4adb16785348a03738b11bf9d6150a31d4a6c8443e60d4342f5c46eae961a8","title":"","text":"bb0: { StorageLive(_1); // scope 0 at $DIR/const_prop_miscompile.rs:+1:9: +1:14 - _1 = (const 1_i32,); // scope 0 at $DIR/const_prop_miscompile.rs:+1:17: +1:21 + _1 = const (1_i32,); // scope 0 at $DIR/const_prop_miscompile.rs:+1:17: +1:21 _1 = (const 1_i32,); // scope 0 at $DIR/const_prop_miscompile.rs:+1:17: +1:21 StorageLive(_2); // scope 1 at $DIR/const_prop_miscompile.rs:+2:6: +2:14 _2 = &mut (_1.0: i32); // scope 1 at $DIR/const_prop_miscompile.rs:+2:6: +2:14 (*_2) = const 5_i32; // scope 1 at $DIR/const_prop_miscompile.rs:+2:5: +2:18"} {"_id":"doc-en-rust-dc4e85bce1a0dcfb87ba31b04f5af3817d409bc2b64c9e674b3363c9f3a006e9","title":"","text":"assert_eq!(self.metas.len(), self.stable_crate_ids.len()); let num = CrateNum::new(self.stable_crate_ids.len()); if let Some(&existing) = self.stable_crate_ids.get(&root.stable_crate_id()) { let crate_name0 = root.name(); if let Some(crate_name1) = self.metas[existing].as_ref().map(|data| data.name()) { // Check for (potential) conflicts with the local crate if existing == LOCAL_CRATE { Err(CrateError::SymbolConflictsCurrent(root.name())) } else if let Some(crate_name1) = self.metas[existing].as_ref().map(|data| data.name()) { let crate_name0 = root.name(); Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1)) } else { Err(CrateError::SymbolConflictsCurrent(crate_name0)) Err(CrateError::NotFound(root.name())) } } else { self.metas.push(None);"} {"_id":"doc-en-rust-259cea2dd5ec305282ae176e870e05a6da512225c404b523e905311b38f42f80","title":"","text":"DlSym(String), LocatorCombined(Box), NonDylibPlugin(Symbol), NotFound(Symbol), } enum MetadataError<'a> {"} {"_id":"doc-en-rust-926e9144f3dc38114f10d99aff4e05481880c60545c48c9f7147e6568a4768e6","title":"","text":"CrateError::NonDylibPlugin(crate_name) => { sess.emit_err(errors::NoDylibPlugin { span, crate_name }); } CrateError::NotFound(crate_name) => { sess.emit_err(errors::CannotFindCrate { span, crate_name, add_info: String::new(), missing_core, current_crate: sess.opts.crate_name.clone().unwrap_or(\"\".to_string()), is_nightly_build: sess.is_nightly_build(), profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime), locator_triple: sess.opts.target_triple.clone(), }); } } } }"} {"_id":"doc-en-rust-3422ea0a879ca7af393e22f9f837c9b5a12b5c02592c0722a4e1334ae0c83fa2","title":"","text":"--crate-type=rlib --edition=2018 c.rs 2>&1 | tee $(TMPDIR)/output.txt || exit 0 $(CGREP) E0519 < $(TMPDIR)/output.txt $(CGREP) E0463 < $(TMPDIR)/output.txt $(CGREP) -v \"internal compiler error\" < $(TMPDIR)/output.txt"} {"_id":"doc-en-rust-099062084e57c7cc80fe60467d6e670cea5137aee5fe805d9ed5ee0357b69400","title":"","text":"} if tcx.sess.opts.unstable_opts.drop_tracking_mir && let DefKind::Generator = tcx.def_kind(closure_def_id) && let Some(generator_layout) = tcx.mir_generator_witnesses(closure_def_id) { let generator_layout = tcx.mir_generator_witnesses(closure_def_id); for interior_ty in &generator_layout.field_tys { label_match(interior_ty.ty, interior_ty.source_info.span); }"} {"_id":"doc-en-rust-7c83496548e5ee94285107c6b63ef02be581a76cb2b1146909a439b00b3db6f0","title":"","text":"if encode_opt { record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id)); if tcx.sess.opts.unstable_opts.drop_tracking_mir && let DefKind::Generator = self.tcx.def_kind(def_id) { record!(self.tables.mir_generator_witnesses[def_id.to_def_id()] <- tcx.mir_generator_witnesses(def_id)); if tcx.sess.opts.unstable_opts.drop_tracking_mir && let DefKind::Generator = self.tcx.def_kind(def_id) && let Some(witnesses) = tcx.mir_generator_witnesses(def_id) { record!(self.tables.mir_generator_witnesses[def_id.to_def_id()] <- witnesses); } } if encode_const {"} {"_id":"doc-en-rust-f1b57a1f570fe440503d0e1eacbb51ba09a875625066a1038e049f1326237a43","title":"","text":"} } query mir_generator_witnesses(key: DefId) -> &'tcx mir::GeneratorLayout<'tcx> { query mir_generator_witnesses(key: DefId) -> &'tcx Option> { arena_cache desc { |tcx| \"generator witness types for `{}`\", tcx.def_path_str(key) } cache_on_disk_if { key.is_local() }"} {"_id":"doc-en-rust-5abec4cab45fb60839ba15a9d02a0959b9c08d3e9fa273e2d70bb48ab485d37b","title":"","text":"self, def_id: DefId, ) -> impl Iterator>> { let generator_layout = &self.mir_generator_witnesses(def_id); let generator_layout = self.mir_generator_witnesses(def_id); generator_layout .field_tys .iter() .as_ref() .map_or_else(|| [].iter(), |l| l.field_tys.iter()) .filter(|decl| !decl.ignore_for_traits) .map(|decl| ty::EarlyBinder(decl.ty)) }"} {"_id":"doc-en-rust-0011cdc8b74b2c4b16a4be9e511512721107bbe97978329916e69bf1e9b537fa","title":"","text":"pub(crate) fn mir_generator_witnesses<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, ) -> GeneratorLayout<'tcx> { ) -> Option> { assert!(tcx.sess.opts.unstable_opts.drop_tracking_mir); let (body, _) = tcx.mir_promoted(def_id);"} {"_id":"doc-en-rust-3c47bfb9d1f28abdbb3706471b7b3a0438736230b2eadafd113a6dd2df517f4c","title":"","text":"// Get the interior types and substs which typeck computed let movable = match *gen_ty.kind() { ty::Generator(_, _, movability) => movability == hir::Movability::Movable, ty::Error(_) => return None, _ => span_bug!(body.span, \"unexpected generator type {}\", gen_ty), };"} {"_id":"doc-en-rust-8b5c335daa3e46e80020d427c615a1874db219e8aaaba5fb4209f62300e5c329","title":"","text":"check_suspend_tys(tcx, &generator_layout, &body); generator_layout Some(generator_layout) } impl<'tcx> MirPass<'tcx> for StateTransform {"} {"_id":"doc-en-rust-23f44ba6427f2322e6da4fb1a41d45f2a74e862afff041903cedac017145f969","title":"","text":"&& generator_did.is_local() // Try to avoid cycles. && !generator_within_in_progress_typeck && let Some(generator_info) = self.tcx.mir_generator_witnesses(generator_did) { let generator_info = &self.tcx.mir_generator_witnesses(generator_did); debug!(?generator_info); 'find_source: for (variant, source_info) in generator_info.variant_fields.iter().zip(&generator_info.variant_source_info) {"} {"_id":"doc-en-rust-2fe800436eae729a9a970fc26f8a8447d0d6dba96aa587ad1a3ff35c8492c4ce","title":"","text":" // compile-flags: -Zdrop-tracking-mir --edition=2021 #![feature(generators)] pub async fn async_bad_body() { match true {} //~ ERROR non-exhaustive patterns: type `bool` is non-empty } pub fn generator_bad_body() { || { // 'non-exhaustive pattern' only seems to be reported once, so this annotation doesn't work // keep the function around so we can make sure it doesn't ICE match true {}; // ERROR non-exhaustive patterns: type `bool` is non-empty yield (); }; } fn main() {} "} {"_id":"doc-en-rust-b29191af38dc535c14bf3032227cfd55e238c5c4d0d73c0f346477067b3ac514","title":"","text":" error[E0004]: non-exhaustive patterns: type `bool` is non-empty --> $DIR/drop-tracking-error-body.rs:6:11 | LL | match true {} | ^^^^ | = note: the matched value is of type `bool` help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern as shown | LL ~ match true { LL + _ => todo!(), LL ~ } | error: aborting due to previous error For more information about this error, try `rustc --explain E0004`. "} {"_id":"doc-en-rust-cb98809d9e1a26d5bccd7921726e7f905e7d5c243b7521b5c27a7b88bdf9b017","title":"","text":"[submodule \"src/llvm-project\"] path = src/llvm-project url = https://github.com/rust-lang/llvm-project.git branch = rustc/16.0-2023-04-05 branch = rustc/16.0-2023-06-05 [submodule \"src/doc/embedded-book\"] path = src/doc/embedded-book url = https://github.com/rust-embedded/book.git"} {"_id":"doc-en-rust-278a5941520658e431671c87a9f67203fa4df844dc83f7c3386ce2d9116276ee","title":"","text":" Subproject commit 533d3f338b804d54e5d0ac4fba6276af23002d9c Subproject commit 22897bce7bfedc9cd3953a33419b346936263500 "} {"_id":"doc-en-rust-8b2628bc47edf80fb5bd5cf1c39509b816852d75d7820d3bceca789ab6494542","title":"","text":"let scope = Scope::TraitRefBoundary { s: self.scope }; self.with(scope, |this| { walk_list!(this, visit_generic_param, generics.params); for param in generics.params { match param.kind { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { default, .. } => { if let Some(ty) = default { this.visit_ty(ty); } } GenericParamKind::Const { ty, default } => { this.visit_ty(ty); if let Some(default) = default { this.visit_body(this.tcx.hir().body(default.body)); } } } } walk_list!(this, visit_where_predicate, generics.predicates); }) }"} {"_id":"doc-en-rust-1b7e28837d54d279bc9e95a2d76ef6b7d22cb2917e8762a1a96f0208500a750e","title":"","text":"// like implicit `?Sized` or const-param-has-ty predicates. } } match p.kind { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { default, .. } => { if let Some(ty) = default { self.visit_ty(ty); } } GenericParamKind::Const { ty, default } => { self.visit_ty(ty); if let Some(default) = default { self.visit_body(self.tcx.hir().body(default.body)); } } } } }"} {"_id":"doc-en-rust-667463a6b05b5d44578b58a9e05a62c6121900437374ae005a7562264744144e","title":"","text":" #![feature(non_lifetime_binders)] //~^ WARNING the feature `non_lifetime_binders` is incomplete and may not be safe to use and/or cause compiler crashes pub fn bar() where for V: IntoIterator //~^ ERROR cannot find type `V` in this scope [E0412] { } fn main() { bar(); } "} {"_id":"doc-en-rust-103e53271f253a11102e5b4498846f8a16292a5d919c0513d86f4543c7b7386e","title":"","text":" error[E0412]: cannot find type `V` in this scope --> $DIR/issue-112547.rs:8:4 | LL | }> V: IntoIterator | ^ not found in this scope | help: you might be missing a type parameter | LL | pub fn bar() | +++ warning: the feature `non_lifetime_binders` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/issue-112547.rs:1:12 | LL | #![feature(non_lifetime_binders)] | ^^^^^^^^^^^^^^^^^^^^ | = note: see issue #108185 for more information = note: `#[warn(incomplete_features)]` on by default error: aborting due to previous error; 1 warning emitted For more information about this error, try `rustc --explain E0412`. "} {"_id":"doc-en-rust-b730197f6c5904d96cc3c8cc160c17108333ca0393cec8545db26e6942e15f62","title":"","text":" #![feature(const_trait_impl, effects)] const fn test() -> impl ~const Fn() { //~ ERROR ~const can only be applied to `#[const_trait]` traits const move || { //~ ERROR const closures are experimental let sl: &[u8] = b\"foo\"; match sl { [first, remainder @ ..] => { assert_eq!(first, &b'f'); } [] => panic!(), } } } fn main() {} "} {"_id":"doc-en-rust-71a8dd18fa4e52ddacc1c211048ded9e0fb165799a92c3ecab825e5e7039e8d3","title":"","text":" error[E0658]: const closures are experimental --> $DIR/ice-112822-expected-type-for-param.rs:4:5 | LL | const move || { | ^^^^^ | = note: see issue #106003 for more information = help: add `#![feature(const_closures)]` to the crate attributes to enable error: ~const can only be applied to `#[const_trait]` traits --> $DIR/ice-112822-expected-type-for-param.rs:3:32 | LL | const fn test() -> impl ~const Fn() { | ^^^^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0658`. "} {"_id":"doc-en-rust-caa7d289f72a336861164ee21a83029df0a07dd3f5ef8f71c02e9be83ddb8cdb","title":"","text":"\"rustc_hir\", \"rustc_middle\", \"rustc_span\", \"scoped-tls\", \"tracing\", ]"} {"_id":"doc-en-rust-90bdb397e5c6d1fac402541aacf9b144ba116531a890bcc9baed4098d9b9d315","title":"","text":"rustc_middle = { path = \"../rustc_middle\", optional = true } rustc_span = { path = \"../rustc_span\", optional = true } tracing = \"0.1\" scoped-tls = \"1.0\" [features] default = ["} {"_id":"doc-en-rust-ea2dd1d7e340e0f45157c785cfc94ee342421a693b421d65a01eb6bcad7b2b4b","title":"","text":"// Make this module private for now since external users should not call these directly. mod rustc_smir; #[macro_use] extern crate scoped_tls; "} {"_id":"doc-en-rust-601b28195caaab5ccade86eac8c3b9407320098e3bd0cf5c039de7c262243fdd","title":"","text":"fn rustc_tables(&mut self, f: &mut dyn FnMut(&mut Tables<'_>)); } thread_local! { /// A thread local variable that stores a pointer to the tables mapping between TyCtxt /// datastructures and stable MIR datastructures. static TLV: Cell<*mut ()> = const { Cell::new(std::ptr::null_mut()) }; } // A thread local variable that stores a pointer to the tables mapping between TyCtxt // datastructures and stable MIR datastructures scoped_thread_local! (static TLV: Cell<*mut ()>); pub fn run(mut context: impl Context, f: impl FnOnce()) { assert!(TLV.get().is_null()); assert!(!TLV.is_set()); fn g<'a>(mut context: &mut (dyn Context + 'a), f: impl FnOnce()) { TLV.set(&mut context as *mut &mut _ as _); f(); TLV.replace(std::ptr::null_mut()); let ptr: *mut () = &mut context as *mut &mut _ as _; TLV.set(&Cell::new(ptr), || { f(); }); } g(&mut context, f); }"} {"_id":"doc-en-rust-78d6916150aec0d9f9610d8db89f016724133b6d92a9556a03457e8dd54a16bf","title":"","text":"/// Loads the current context and calls a function with it. /// Do not nest these, as that will ICE. pub(crate) fn with(f: impl FnOnce(&mut dyn Context) -> R) -> R { let ptr = TLV.replace(std::ptr::null_mut()) as *mut &mut dyn Context; assert!(!ptr.is_null()); let ret = f(unsafe { *ptr }); TLV.set(ptr as _); ret assert!(TLV.is_set()); TLV.with(|tlv| { let ptr = tlv.get(); assert!(!ptr.is_null()); f(unsafe { *(ptr as *mut &mut dyn Context) }) }) }"} {"_id":"doc-en-rust-fe1c8987fadce911bfaabf4e13713cfaa44bed85f9597f24ac2642cd4e514ccc","title":"","text":"use rustc_hir::{HirId, Pat, PatKind}; use rustc_infer::infer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::{self, Adt, BindingMode, Ty, TypeVisitableExt}; use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS; use rustc_span::edit_distance::find_best_match_for_name;"} {"_id":"doc-en-rust-861cf111bf902d81240b4bb9044842a8deb640b4ff152f558473d9887b9a414d","title":"","text":"len: ty::Const<'tcx>, min_len: u64, ) -> (Option>, Ty<'tcx>) { let guar = if let Some(len) = len.try_eval_target_usize(self.tcx, self.param_env) { let len = match len.eval(self.tcx, self.param_env, None) { Ok(val) => val .try_to_scalar() .and_then(|scalar| scalar.try_to_int().ok()) .and_then(|int| int.try_to_target_usize(self.tcx).ok()), Err(ErrorHandled::Reported(..)) => { let guar = self.error_scrutinee_unfixed_length(span); return (Some(Ty::new_error(self.tcx, guar)), arr_ty); } Err(ErrorHandled::TooGeneric(..)) => None, }; let guar = if let Some(len) = len { // Now we know the length... if slice.is_none() { // ...and since there is no variable-length pattern,"} {"_id":"doc-en-rust-00f30a84d6fa488cf512baa7f24404fb075648c8bd96d89199abf9799f2836ca","title":"","text":" #![allow(incomplete_features)] #![feature(generic_const_exprs)] fn something(path: [usize; N]) -> impl Clone { //~^ ERROR cannot find value `N` in this scope match path { [] => 0, //~ ERROR cannot pattern-match on an array without a fixed length _ => 1, }; } fn main() {} "} {"_id":"doc-en-rust-d9c88e88f788353099742a7cf07ecc979f42859c12b1847dfd802b86488dc827","title":"","text":" error[E0425]: cannot find value `N` in this scope --> $DIR/issue-116186.rs:4:28 | LL | fn something(path: [usize; N]) -> impl Clone { | ^ not found in this scope | help: you might be missing a const parameter | LL | fn something(path: [usize; N]) -> impl Clone { | +++++++++++++++++++++ error[E0730]: cannot pattern-match on an array without a fixed length --> $DIR/issue-116186.rs:7:9 | LL | [] => 0, | ^^ error: aborting due to 2 previous errors Some errors have detailed explanations: E0425, E0730. For more information about an error, try `rustc --explain E0425`. "} {"_id":"doc-en-rust-503641ca1ea60e21ea6eb70ae2dfd01dab39b661c7147fab6c9fa7d2b977d9d4","title":"","text":" // test for #113326 #![feature(type_alias_impl_trait)] pub type Diff = impl Fn(usize) -> usize; pub fn lift() -> Diff { |_: usize |loop {} } pub fn add( n: Diff, m: Diff, ) -> Diff { move |x: usize| m(n(x)) //~ ERROR: concrete type differs } fn main() {} "} {"_id":"doc-en-rust-1be3509e311051f48b16fb5e826b5b85436eec6299dac0a6aae707b06e16b968","title":"","text":" error: concrete type differs from previous defining opaque type use --> $DIR/recursive-fn-tait.rs:14:5 | LL | move |x: usize| m(n(x)) | ^^^^^^^^^^^^^^^^^^^^^^^ expected `{closure@$DIR/recursive-fn-tait.rs:7:5: 7:16}`, got `{closure@$DIR/recursive-fn-tait.rs:14:5: 14:20}` | note: previous use here --> $DIR/recursive-fn-tait.rs:7:5 | LL | |_: usize |loop {} | ^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-bcff1dc3e0a8f410406ba9c0d931062c9d5b89a122cb21c0744424f27ba3e866","title":"","text":"use std::path::{Path, PathBuf}; use std::process::Command; use build_helper::ci::CiEnv; use tracing::*; use crate::common::{Config, Debugger, FailMode, Mode, PassMode};"} {"_id":"doc-en-rust-5e43e2f3512897897890ad6b8dbf5511cf4944db815a2a3bc1e9e88b5ea40ecc","title":"","text":"/// `//[foo]`), then the property is ignored unless `cfg` is /// `Some(\"foo\")`. fn load_from(&mut self, testfile: &Path, cfg: Option<&str>, config: &Config) { // In CI, we've sometimes encountered non-determinism related to truncating very long paths. // Set a consistent (short) prefix to avoid issues, but only in CI to avoid regressing the // contributor experience. if CiEnv::is_ci() { self.remap_src_base = config.mode == Mode::Ui && !config.suite.contains(\"rustdoc\"); } let mut has_edition = false; if !testfile.is_dir() { let file = File::open(testfile).unwrap();"} {"_id":"doc-en-rust-2f90053f3fc34b398ce3d3ec5c506e7b967ac7d9b46a62bb931089c933447019","title":"","text":"use rustc_middle::ty::{ self, fold::BottomUpFolder, print::TraitPredPrintModifiersAndPath, Ty, TypeFoldable, }; use rustc_span::Span; use rustc_span::{symbol::kw, Span}; use rustc_trait_selection::traits; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;"} {"_id":"doc-en-rust-477897e687659744c894fe1aac9e3800ca4e0a0d8d655da2d9e7dbd6b511c7b1","title":"","text":"continue; } // HACK: `async fn() -> Self` in traits is \"ok\"... // This is not really that great, but it's similar to why the `-> Self` // return type is well-formed in traits even when `Self` isn't sized. if let ty::Param(param_ty) = *proj_term.kind() && param_ty.name == kw::SelfUpper && matches!(opaque.origin, hir::OpaqueTyOrigin::AsyncFn(_)) && opaque.in_trait { continue; } let proj_ty = Ty::new_projection(cx.tcx, proj.projection_ty.def_id, proj.projection_ty.args); // For every instance of the projection type in the bounds,"} {"_id":"doc-en-rust-0276d8dac2b7f88c5249cd99a3cf76c2ca4f922345994bf841c2225de8821661","title":"","text":" // check-pass // edition:2021 #![deny(opaque_hidden_inferred_bound)] trait Repository /* : ?Sized */ { async fn new() -> Self; } struct MyRepository {} impl Repository for MyRepository { async fn new() -> Self { todo!() } } fn main() {} "} {"_id":"doc-en-rust-d7eec9063b83aed3edd2781f2755af157ed4ff0047d5ff9236173d5ad34ffb26","title":"","text":"let mut tool = tool::ErrorIndex::command(builder); tool.arg(\"markdown\").arg(&output); let _guard = let guard = builder.msg(Kind::Test, compiler.stage, \"error-index\", compiler.host, compiler.host); let _time = util::timeit(&builder); builder.run_quiet(&mut tool); drop(guard); // The tests themselves need to link to std, so make sure it is // available. builder.ensure(compile::Std::new(compiler, compiler.host));"} {"_id":"doc-en-rust-aaa6332a71184df7e8282580e65350e96539dc7cfbce7c1960d9663058d7eb97","title":"","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":"doc-en-rust-171d98dbe51daec91807434732d1b5b140d74136e8d6c1d493e0ae5b6924726f","title":"","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":"doc-en-rust-d1e1e7a08674cc951ed20a04619ef1021891dd902827e631f369b11b2ae42f2c","title":"","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":"doc-en-rust-aec29356923f4dcb36085d3f2f76100239eaf4a9b2c5259495ac23e436219ca1","title":"","text":"use super::ResolverAstLoweringExt; use rustc_ast::visit::{self, BoundKind, LifetimeCtxt, Visitor}; use rustc_ast::{GenericBounds, Lifetime, NodeId, PathSegment, PolyTraitRef, Ty, TyKind}; use rustc_hir::def::LifetimeRes; use rustc_hir::def::{DefKind, LifetimeRes, Res}; use rustc_middle::span_bug; use rustc_middle::ty::ResolverAstLowering; use rustc_span::symbol::{kw, Ident};"} {"_id":"doc-en-rust-f3fd3eac16054972d183636bd90acd0d710197c7b611ba5fe501e518af604dbc","title":"","text":"} fn visit_ty(&mut self, t: &'ast Ty) { match t.kind { match &t.kind { TyKind::Path(None, _) => { // We can sometimes encounter bare trait objects // which are represented in AST as paths. if let Some(partial_res) = self.resolver.get_partial_res(t.id) && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res() { self.current_binders.push(t.id); visit::walk_ty(self, t); self.current_binders.pop(); } else { visit::walk_ty(self, t); } } TyKind::BareFn(_) => { self.current_binders.push(t.id); visit::walk_ty(self, t);"} {"_id":"doc-en-rust-9dd3bb29559979ec21e8234b62f29d2b716cff1364c78f5b84cef4986bc72fbf","title":"","text":" // edition:2015 // check-pass // issue: 114664 fn ice() -> impl AsRef { //~^ WARN trait objects without an explicit `dyn` are deprecated //~| WARN trait objects without an explicit `dyn` are deprecated //~| WARN trait objects without an explicit `dyn` are deprecated //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! Foo } struct Foo; impl AsRef for Foo { fn as_ref(&self) -> &(dyn for<'a> Fn(&'a ()) + 'static) { todo!() } } pub fn main() {} "} {"_id":"doc-en-rust-641f6821622d5a52b401124645d4059df11fa5839d65774b3c0e5e9f2f3f50e6","title":"","text":" warning: trait objects without an explicit `dyn` are deprecated --> $DIR/fresh-lifetime-from-bare-trait-obj-114664.rs:5:24 | LL | fn ice() -> impl AsRef { | ^^^^^^^ | = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! = note: for more information, see = note: `#[warn(bare_trait_objects)]` on by default help: use `dyn` | LL | fn ice() -> impl AsRef { | +++ warning: trait objects without an explicit `dyn` are deprecated --> $DIR/fresh-lifetime-from-bare-trait-obj-114664.rs:5:24 | LL | fn ice() -> impl AsRef { | ^^^^^^^ | = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! = note: for more information, see help: use `dyn` | LL | fn ice() -> impl AsRef { | +++ warning: trait objects without an explicit `dyn` are deprecated --> $DIR/fresh-lifetime-from-bare-trait-obj-114664.rs:5:24 | LL | fn ice() -> impl AsRef { | ^^^^^^^ | = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! = note: for more information, see help: use `dyn` | LL | fn ice() -> impl AsRef { | +++ warning: 3 warnings emitted "} {"_id":"doc-en-rust-256fa959aa7ee708685bcd7f40498fda9ba80898b43d090bfaa104c6834a3925","title":"","text":"return; } }; let (sig, map) = tcx.instantiate_bound_regions(sig, |br| { let (unnormalized_sig, map) = tcx.instantiate_bound_regions(sig, |br| { use crate::renumber::RegionCtxt; let region_ctxt_fn = || {"} {"_id":"doc-en-rust-25bd64db2ce2e460b55c407dc974551fbef355198a903eea0434e5a3feb88f53","title":"","text":"region_ctxt_fn, ) }); debug!(?sig); debug!(?unnormalized_sig); // IMPORTANT: We have to prove well formed for the function signature before // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc` // get normalized away, causing us to ignore the `'b: 'a` bound used by the function."} {"_id":"doc-en-rust-597f5444e94753f6cc13498508357cb412e65b4911259ceb2639fcd7d7f1a1d2","title":"","text":"// // See #91068 for an example. self.prove_predicates( sig.inputs_and_output.iter().map(|ty| { unnormalized_sig.inputs_and_output.iter().map(|ty| { ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed( ty.into(), )))"} {"_id":"doc-en-rust-9a3a5d54df7a4f0f0b5a9bf9e8b39c54120ff9c10768cb4013a0f337e8e93026","title":"","text":"term_location.to_locations(), ConstraintCategory::Boring, ); let sig = self.normalize(sig, term_location); let sig = self.normalize(unnormalized_sig, term_location); // HACK(#114936): `WF(sig)` does not imply `WF(normalized(sig))` // with built-in `Fn` implementations, since the impl may not be // well-formed itself. if sig != unnormalized_sig { self.prove_predicates( sig.inputs_and_output.iter().map(|ty| { ty::Binder::dummy(ty::PredicateKind::Clause( ty::ClauseKind::WellFormed(ty.into()), )) }), term_location.to_locations(), ConstraintCategory::Boring, ); } self.check_call_dest(body, term, &sig, *destination, *target, term_location); // The ordinary liveness rules will ensure that all"} {"_id":"doc-en-rust-b27bc0c8c0c31a771e387a12370bab75454de050ee36f37ad3a7c324ad51e1cb","title":"","text":" // fn whoops( s: String, f: impl for<'s> FnOnce(&'s str) -> (&'static str, [&'static &'s (); 0]), ) -> &'static str { f(&s).0 //~^ ERROR `s` does not live long enough } // fn extend(input: &T) -> &'static T { struct Bounded<'a, 'b: 'static, T>(&'a T, [&'b (); 0]); let n: Box Bounded<'static, '_, T>> = Box::new(|x| Bounded(x, [])); n(input).0 //~^ ERROR borrowed data escapes outside of function } // fn extend_mut<'a, T>(input: &'a mut T) -> &'static mut T { struct Bounded<'a, 'b: 'static, T>(&'a mut T, [&'b (); 0]); let mut n: Box Bounded<'static, '_, T>> = Box::new(|x| Bounded(x, [])); n(input).0 //~^ ERROR borrowed data escapes outside of function } fn main() {} "} {"_id":"doc-en-rust-845f15e032a32ccafbb42a11825b3ecb1205bc128c545b3fe71dc21dc9f0a60a","title":"","text":" error[E0597]: `s` does not live long enough --> $DIR/check-normalized-sig-for-wf.rs:7:7 | LL | s: String, | - binding `s` declared here ... LL | f(&s).0 | --^^- | | | | | borrowed value does not live long enough | argument requires that `s` is borrowed for `'static` LL | LL | } | - `s` dropped here while still borrowed error[E0521]: borrowed data escapes outside of function --> $DIR/check-normalized-sig-for-wf.rs:15:5 | LL | fn extend(input: &T) -> &'static T { | ----- - let's call the lifetime of this reference `'1` | | | `input` is a reference that is only valid in the function body ... LL | n(input).0 | ^^^^^^^^ | | | `input` escapes the function body here | argument requires that `'1` must outlive `'static` error[E0521]: borrowed data escapes outside of function --> $DIR/check-normalized-sig-for-wf.rs:23:5 | LL | fn extend_mut<'a, T>(input: &'a mut T) -> &'static mut T { | -- ----- `input` is a reference that is only valid in the function body | | | lifetime `'a` defined here ... LL | n(input).0 | ^^^^^^^^ | | | `input` escapes the function body here | argument requires that `'a` must outlive `'static` error: aborting due to 3 previous errors Some errors have detailed explanations: E0521, E0597. For more information about an error, try `rustc --explain E0521`. "} {"_id":"doc-en-rust-e00dc585ec9ef1cc9862bc51413f4f381ae50dd5650e09dafbdb8f2a3986e2dd","title":"","text":"// Vectors, even for non-power-of-two sizes, have the same layout as // arrays but don't count as aggregate types // While LLVM theoretically supports non-power-of-two sizes, and they // often work fine, sometimes x86-isel deals with them horribly // (see #115212) so for now only use power-of-two ones. if let FieldsShape::Array { count, .. } = self.layout.fields() && count.is_power_of_two() && let element = self.field(cx, 0) && element.ty.is_integral() {"} {"_id":"doc-en-rust-f71fa9c37de1a48e306015092bfb162ec3e20d80720d33a1f15ffa1e18fd9a61","title":"","text":"} #[no_mangle] // CHECK-LABEL: @replace_short_array( pub fn replace_short_array(r: &mut [u32; 3], v: [u32; 3]) -> [u32; 3] { // CHECK-LABEL: @replace_short_array_3( pub fn replace_short_array_3(r: &mut [u32; 3], v: [u32; 3]) -> [u32; 3] { // CHECK-NOT: alloca // CHECK: %[[R:.+]] = load <3 x i32>, ptr %r, align 4 // CHECK: store <3 x i32> %[[R]], ptr %result // CHECK: %[[V:.+]] = load <3 x i32>, ptr %v, align 4 // CHECK: store <3 x i32> %[[V]], ptr %r // CHECK: call void @llvm.memcpy.p0.p0.i64(ptr align 4 %result, ptr align 4 %r, i64 12, i1 false) // CHECK: call void @llvm.memcpy.p0.p0.i64(ptr align 4 %r, ptr align 4 %v, i64 12, i1 false) std::mem::replace(r, v) } #[no_mangle] // CHECK-LABEL: @replace_short_array_4( pub fn replace_short_array_4(r: &mut [u32; 4], v: [u32; 4]) -> [u32; 4] { // CHECK-NOT: alloca // CHECK: %[[R:.+]] = load <4 x i32>, ptr %r, align 4 // CHECK: store <4 x i32> %[[R]], ptr %result // CHECK: %[[V:.+]] = load <4 x i32>, ptr %v, align 4 // CHECK: store <4 x i32> %[[V]], ptr %r std::mem::replace(r, v) }"} {"_id":"doc-en-rust-ceb21e38396ea81811e317f1b589e0c93b6a6e32d8647c07b0c9afcd0d3b9c2f","title":"","text":"// CHECK-LABEL: @swap_rgb48_manually( #[no_mangle] pub fn swap_rgb48_manually(x: &mut RGB48, y: &mut RGB48) { // CHECK-NOT: alloca // CHECK: %[[TEMP0:.+]] = load <3 x i16>, ptr %x, align 2 // CHECK: %[[TEMP1:.+]] = load <3 x i16>, ptr %y, align 2 // CHECK: store <3 x i16> %[[TEMP1]], ptr %x, align 2 // CHECK: store <3 x i16> %[[TEMP0]], ptr %y, align 2 // FIXME: See #115212 for why this has an alloca again // CHECK: alloca [3 x i16], align 2 // CHECK: call void @llvm.memcpy.p0.p0.i64({{.+}}, i64 6, i1 false) // CHECK: call void @llvm.memcpy.p0.p0.i64({{.+}}, i64 6, i1 false) // CHECK: call void @llvm.memcpy.p0.p0.i64({{.+}}, i64 6, i1 false) let temp = *x; *x = *y;"} {"_id":"doc-en-rust-65a3addc18fa4db46c7f1e552d225fd23261858ea8a68e762df177525916e82e","title":"","text":"// CHECK-LABEL: @swap_rgb48 #[no_mangle] pub fn swap_rgb48(x: &mut RGB48, y: &mut RGB48) { // FIXME: See #115212 for why this has an alloca again // CHECK: alloca [3 x i16], align 2 // CHECK: call void @llvm.memcpy.p0.p0.i64({{.+}}, i64 6, i1 false) // CHECK: call void @llvm.memcpy.p0.p0.i64({{.+}}, i64 6, i1 false) // CHECK: call void @llvm.memcpy.p0.p0.i64({{.+}}, i64 6, i1 false) swap(x, y) } type RGBA64 = [u16; 4]; // CHECK-LABEL: @swap_rgba64 #[no_mangle] pub fn swap_rgba64(x: &mut RGBA64, y: &mut RGBA64) { // CHECK-NOT: alloca // CHECK: load <3 x i16> // CHECK: load <3 x i16> // CHECK: store <3 x i16> // CHECK: store <3 x i16> // CHECK-DAG: %[[XVAL:.+]] = load <4 x i16>, ptr %x, align 2 // CHECK-DAG: %[[YVAL:.+]] = load <4 x i16>, ptr %y, align 2 // CHECK-DAG: store <4 x i16> %[[YVAL]], ptr %x, align 2 // CHECK-DAG: store <4 x i16> %[[XVAL]], ptr %y, align 2 swap(x, y) }"} {"_id":"doc-en-rust-dc8658df917a8ef64d48358325f79ec80dccb731be70143dd6596c52362b4352","title":"","text":"// needs drop. let adt_has_dtor = |adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant); let res = drop_tys_helper(tcx, query.value, query.param_env, adt_has_dtor, false).next().is_some(); let res = drop_tys_helper(tcx, query.value, query.param_env, adt_has_dtor, false) .filter(filter_array_elements(tcx, query.param_env)) .next() .is_some(); debug!(\"needs_drop_raw({:?}) = {:?}\", query, res); res } /// HACK: in order to not mistakenly assume that `[PhantomData; N]` requires drop glue /// we check the element type for drop glue. The correct fix would be looking at the /// entirety of the code around `needs_drop_components` and this file and come up with /// logic that is easier to follow while not repeating any checks that may thus diverge. fn filter_array_elements<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, ) -> impl Fn(&Result, AlwaysRequiresDrop>) -> bool { move |ty| match ty { Ok(ty) => match *ty.kind() { ty::Array(elem, _) => tcx.needs_drop_raw(param_env.and(elem)), _ => true, }, Err(AlwaysRequiresDrop) => true, } } fn has_significant_drop_raw<'tcx>( tcx: TyCtxt<'tcx>, query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,"} {"_id":"doc-en-rust-bf5373f7164dec7e04d3de85753a6fe0109391b40b7b87c8193f45e4a93c5ed4","title":"","text":"adt_consider_insignificant_dtor(tcx), true, ) .filter(filter_array_elements(tcx, query.param_env)) .next() .is_some(); debug!(\"has_significant_drop_raw({:?}) = {:?}\", query, res);"} {"_id":"doc-en-rust-dddb6a29d4309efd7dfab105d4f4c9910c4f6acb2e58a6848321fcb1208691fc","title":"","text":" // build-pass pub const fn f(_: [std::mem::MaybeUninit; N]) {} pub struct Blubb(*const T); pub const fn g(_: [Blubb; N]) {} pub struct Blorb([String; N]); pub const fn h(_: Blorb<0>) {} pub struct Wrap(Blorb<0>); pub const fn i(_: Wrap) {} fn main() {} "} {"_id":"doc-en-rust-e458b0eb0c14b01b633b8c4b625f62323b515b41d9eb9fad3a7071e649cdde75","title":"","text":"}; let vis = self.tcx.local_visibility(local_def_id); let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id); let span = self.tcx.def_span(self.item_def_id.to_def_id()); let vis_span = self.tcx.def_span(def_id); if self.in_assoc_ty && !vis.is_at_least(self.required_visibility, self.tcx) { let vis_descr = match vis { ty::Visibility::Public => \"public\", ty::Visibility::Restricted(vis_def_id) => { if vis_def_id == self.tcx.parent_module(hir_id).to_local_def_id() { if vis_def_id == self.tcx.parent_module_from_def_id(local_def_id).to_local_def_id() { \"private\" } else if vis_def_id.is_top_level_module() { \"crate-private\""} {"_id":"doc-en-rust-f1c6e7df29501d31e88a7f2a5140d6885dd5c244663f250c20024cedd3de4361","title":"","text":"}; self.tcx.emit_spanned_lint( lint, hir_id, self.tcx.hir().local_def_id_to_hir_id(self.item_def_id), span, PrivateInterfacesOrBoundsLint { item_span: span,"} {"_id":"doc-en-rust-ec785ea44bf2479ddd403808ccbbfddd11b7c2b44d1c8d181f5dd77eba9c8f60","title":"","text":" // check-pass // compile-flags: --crate-type=lib #[allow(private_bounds)] pub trait Foo: FooImpl {} trait FooImpl {} "} {"_id":"doc-en-rust-b9f62ef6b102e7241e179ecdfff0abebe352f4adbee17201d66b2d3bcae6f61b","title":"","text":" // Test for issues/115517 which is fixed by pull/115486 // This should not ice trait Test {} trait Elide { fn call(); } pub fn test() where (): Test<{ 1 + (<() as Elide(&())>::call) }>, //~^ ERROR cannot capture late-bound lifetime in constant { } fn main() {} "} {"_id":"doc-en-rust-8bc91d3f9439e79d63418145b669e183196731e488355158ef0a0b42d0406f5e","title":"","text":" error: cannot capture late-bound lifetime in constant --> $DIR/escaping_bound_vars.rs:11:35 | LL | (): Test<{ 1 + (<() as Elide(&())>::call) }>, | -^ | | | lifetime defined here error: aborting due to previous error "} {"_id":"doc-en-rust-b297a45bea1ac6b96b1490e7adbd5e4a0f13cc8073bcfb1c6c54528d2fa1656d","title":"","text":" Subproject commit 42263494d29febc26d3c1ebdaa7b63677573ec47 Subproject commit d404cba4e39df595710869988ded7cbe1104b52f "} {"_id":"doc-en-rust-6001c71651b741b511a60f029260f73245c7ecc692832d87c24baae713cebfc2","title":"","text":"/// The difference between `unimplemented!` and [`todo!`] is that while `todo!` /// conveys an intent of implementing the functionality later and the message is \"not yet /// implemented\", `unimplemented!` makes no such claims. Its message is \"not implemented\". /// Also some IDEs will mark `todo!`s. /// /// Also, some IDEs will mark `todo!`s. /// /// # Panics ///"} {"_id":"doc-en-rust-b00975ae8775fcd5c9c5a807341365a098c2136483b1f673e82aa4adf1dfeab1","title":"","text":"/// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys /// an intent of implementing the functionality later and the message is \"not yet /// implemented\", `unimplemented!` makes no such claims. Its message is \"not implemented\". /// Also some IDEs will mark `todo!`s. /// /// Also, some IDEs will mark `todo!`s. /// /// # Panics /// /// This will always [`panic!`]. /// This will always [`panic!`] because `todo!` is just a shorthand for `panic!` with a /// fixed, specific message. /// /// Like `panic!`, this macro has a second form for displaying custom values. /// /// # Examples ///"} {"_id":"doc-en-rust-543636cff17794f5325ad9e8d35b08f3e54a842f5e7cf01c39e248f869b73c5f","title":"","text":"/// /// ``` /// trait Foo { /// fn bar(&self); /// fn bar(&self) -> u8; /// fn baz(&self); /// fn qux(&self) -> Result; /// } /// ``` /// /// We want to implement `Foo` on one of our types, but we also want to work on /// just `bar()` first. In order for our code to compile, we need to implement /// `baz()`, so we can use `todo!`: /// `baz()` and `qux()`, so we can use `todo!`: /// /// ``` /// # trait Foo { /// # fn bar(&self); /// # fn bar(&self) -> u8; /// # fn baz(&self); /// # fn qux(&self) -> Result; /// # } /// struct MyStruct; /// /// impl Foo for MyStruct { /// fn bar(&self) { /// // implementation goes here /// fn bar(&self) -> u8 { /// 1 + 1 /// } /// /// fn baz(&self) { /// // let's not worry about implementing baz() for now /// // Let's not worry about implementing baz() for now /// todo!(); /// } /// /// fn qux(&self) -> Result { /// // We can add a message to todo! to display our omission. /// // This will display: /// // \"thread 'main' panicked at 'not yet implemented: MyStruct is not yet quxable'\". /// todo!(\"MyStruct is not yet quxable\"); /// } /// } /// /// fn main() { /// let s = MyStruct; /// s.bar(); /// /// // we aren't even using baz(), so this is fine. /// // We aren't even using baz() or qux(), so this is fine. /// } /// ``` #[macro_export]"} {"_id":"doc-en-rust-99bf56d6526d3fdbdc148b77e0cc77ff17a0055169431f4ad06d31553230d87e","title":"","text":"cargo.arg(\"--all-targets\"); } // Enable internal lints for clippy and rustdoc // NOTE: this doesn't enable lints for any other tools unless they explicitly add `#![warn(rustc::internal)]` // See https://github.com/rust-lang/rust/pull/80573#issuecomment-754010776 cargo.rustflag(\"-Zunstable-options\"); let _guard = builder.msg_check(&concat!(stringify!($name), \" artifacts\").to_lowercase(), target); run_cargo( builder,"} {"_id":"doc-en-rust-1f8311e1cbc81959c1789d26b88cc1831d0aeab68d28a5649e6224afaab857a9","title":"","text":"if !features.is_empty() { cargo.arg(\"--features\").arg(&features.join(\", \")); } // Enable internal lints for clippy and rustdoc // NOTE: this doesn't enable lints for any other tools unless they explicitly add `#![warn(rustc::internal)]` // See https://github.com/rust-lang/rust/pull/80573#issuecomment-754010776 // // NOTE: We unconditionally set this here to avoid recompiling tools between `x check $tool` // and `x test $tool` executions. // See https://github.com/rust-lang/rust/issues/116538 cargo.rustflag(\"-Zunstable-options\"); cargo }"} {"_id":"doc-en-rust-139416846b51d9186d103b4527f3fa60c2f7cac1b5640008dcf8f73faeeed3f2","title":"","text":"loan_issued_at: Location, ) { 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) { // 1. Via member constraints // 1. Via applied member constraints // // The issuing region can flow into the choice regions, and they are either: // - placeholders or free regions themselves, // - or also transitively outlive a free region. // // That is to say, if there are member constraints here, the loan escapes the function // and cannot go out of scope. We can early return. if self.regioncx.scc_has_member_constraints(scc) { return; // That is to say, if there are applied member constraints here, the loan escapes the // function and cannot go out of scope. We could early return here. // // 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. for constraint in self.regioncx.applied_member_constraints(scc) { if universal_regions.is_universal_region(constraint.min_choice) { return; } } // 2. Via regions that are live at all points: placeholders and free regions."} {"_id":"doc-en-rust-f929ac5b369e75ffce37fc1e82ad05689b9bcbaa770be0f80c1242f0044ca49f","title":"","text":"let mut polonius_prec = PoloniusOutOfScopePrecomputer::new(body, regioncx); for (loan_idx, loan_data) in borrow_set.iter_enumerated() { let issuing_region = loan_data.region; let issued_location = loan_data.reserve_location; let loan_issued_at = loan_data.reserve_location; polonius_prec.precompute_loans_out_of_scope( loan_idx, issuing_region, issued_location, loan_issued_at, ); }"} {"_id":"doc-en-rust-38187da5e1276eb6d5e0af20dba61dff6a31ab70b848012e22289c1c6aec7779","title":"","text":"self.scc_universes[scc] } /// Once region solving has completed, this function will return /// the member constraints that were applied to the value of a given /// region `r`. See `AppliedMemberConstraint`. pub(crate) fn applied_member_constraints(&self, r: RegionVid) -> &[AppliedMemberConstraint] { let scc = self.constraint_sccs.scc(r); /// Once region solving has completed, this function will return the member constraints that /// were applied to the value of a given SCC `scc`. See `AppliedMemberConstraint`. pub(crate) fn applied_member_constraints( &self, scc: ConstraintSccIndex, ) -> &[AppliedMemberConstraint] { binary_search_util::binary_search_slice( &self.member_constraints_applied, |applied| applied.member_region_scc,"} {"_id":"doc-en-rust-90e1eeac2cd10889391eba5735d3c4caebbac56abd6752fcc8018ce07a2ac1d1","title":"","text":"// Member constraints can also give rise to `'r: 'x` edges that // were not part of the graph initially, so watch out for those. // (But they are extremely rare; this loop is very cold.) for constraint in self.applied_member_constraints(r) { for constraint in self.applied_member_constraints(self.constraint_sccs.scc(r)) { let p_c = &self.member_constraints[constraint.member_constraint_index]; let constraint = OutlivesConstraint { sup: r,"} {"_id":"doc-en-rust-66a555a1e2c1a75608aee9a67b2b9437b70ba302e494abf010eed0d0dd27c508","title":"","text":"self.constraint_sccs.as_ref() } /// Returns whether the given SCC has any member constraints. pub(crate) fn scc_has_member_constraints(&self, scc: ConstraintSccIndex) -> bool { self.member_constraints.indices(scc).next().is_some() } /// Returns whether the given SCC is live at all points: whether the representative is a /// placeholder or a free region. pub(crate) fn scc_is_live_at_all_points(&self, scc: ConstraintSccIndex) -> bool {"} {"_id":"doc-en-rust-41fe27d2baaef90dbf337309c03929cd6c4b7d597b3354311b2650891418ffb7","title":"","text":"/// `-Zpolonius` values, enabling the borrow checker polonius analysis, and which version: legacy, /// or future prototype. #[derive(Clone, Copy, PartialEq, Hash, Debug)] #[derive(Clone, Copy, PartialEq, Hash, Debug, Default)] pub enum Polonius { /// The default value: disabled. #[default] Off, /// Legacy version, using datalog and the `polonius-engine` crate. Historical value for `-Zpolonius`."} {"_id":"doc-en-rust-939e10b34519bd98c60e719ab172d53497903984c2729a1cc1cb315e34145803","title":"","text":"Next, } impl Default for Polonius { fn default() -> Self { Polonius::Off } } impl Polonius { /// Returns whether the legacy version of polonius is enabled pub fn is_legacy_enabled(&self) -> bool {"} {"_id":"doc-en-rust-a196cf563737eb85ee3aecede990d57b5682178f715299579f17c3526daef4e9","title":"","text":" error[E0046]: not all trait items implemented, missing: `call` --> $DIR/location-insensitive-scopes-issue-116657.rs:18:1 | LL | fn call(x: Self) -> Self::Output; | --------------------------------- `call` from trait ... LL | impl Callable for T { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `call` in implementation error: unconstrained opaque type --> $DIR/location-insensitive-scopes-issue-116657.rs:22:19 | LL | type Output = impl PlusOne; | ^^^^^^^^^^^^ | = note: `Output` must be used in combination with a concrete type within the same impl error[E0700]: hidden type for `impl PlusOne` captures lifetime that does not appear in bounds --> $DIR/location-insensitive-scopes-issue-116657.rs:28:5 | LL | fn test<'a>(y: &'a mut i32) -> impl PlusOne { | -- ------------ opaque type defined here | | | hidden type `<&'a mut i32 as Callable>::Output` captures the lifetime `'a` as defined here LL | <&mut i32 as Callable>::call(y) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: to declare that `impl PlusOne` captures `'a`, you can add an explicit `'a` lifetime bound | LL | fn test<'a>(y: &'a mut i32) -> impl PlusOne + 'a { | ++++ error: aborting due to 3 previous errors Some errors have detailed explanations: E0046, E0700. For more information about an error, try `rustc --explain E0046`. "} {"_id":"doc-en-rust-308cd5fea4cbad523a75d0f51a447a62e7e7ff03b387aad6adfe6b2926ce1bac","title":"","text":" // This is a non-regression test for issue #116657, where NLL and `-Zpolonius=next` computed // different loan scopes when a member constraint was not ultimately applied. // revisions: nll polonius // [polonius] compile-flags: -Zpolonius=next #![feature(impl_trait_in_assoc_type)] trait Callable { type Output; fn call(x: Self) -> Self::Output; } trait PlusOne {} impl<'a> PlusOne for &'a mut i32 {} impl Callable for T { //[nll]~^ ERROR not all trait items implemented //[polonius]~^^ ERROR not all trait items implemented type Output = impl PlusOne; //[nll]~^ ERROR unconstrained opaque type //[polonius]~^^ ERROR unconstrained opaque type } fn test<'a>(y: &'a mut i32) -> impl PlusOne { <&mut i32 as Callable>::call(y) //[nll]~^ ERROR hidden type for `impl PlusOne` captures lifetime //[polonius]~^^ ERROR hidden type for `impl PlusOne` captures lifetime } fn main() {} "} {"_id":"doc-en-rust-b4121ad7b2fbdf7abf93f1f0aacdfcaef4f3fc00270b37c520607e168ac77591","title":"","text":"// Parse the arguments, starting out with `self` being allowed... let (mut params, _) = self.parse_paren_comma_seq(|p| { p.recover_diff_marker(); let snapshot = p.create_snapshot_for_diagnostic(); let param = p.parse_param_general(req_name, first_param).or_else(|mut e| { e.emit(); let lo = p.prev_token.span; p.restore_snapshot(snapshot); // Skip every token until next possible arg or end. p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(Delimiter::Parenthesis)]); // Create a placeholder argument for proper arg count (issue #34264)."} {"_id":"doc-en-rust-911b4ae292d0da12d7a9df7c27781f770ac7c2d3774541da9cb3d3920f740a53","title":"","text":" #[derive(Debug)] struct Foo { #[cfg(all())] field: fn(($),), //~ ERROR expected pattern, found `$` //~^ ERROR expected pattern, found `$` } fn main() {} "} {"_id":"doc-en-rust-dae778b97a0d932d41811441987f75a5c82092fe86963a54bf29d828de83b690","title":"","text":" error: expected pattern, found `$` --> $DIR/issue-116781.rs:4:16 | LL | field: fn(($),), | ^ expected pattern error: expected pattern, found `$` --> $DIR/issue-116781.rs:4:16 | LL | field: fn(($),), | ^ expected pattern | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-06a402ddc90584cceb8edc932d09564e9219eabff254e5be47f277846a1371f5","title":"","text":" Subproject commit febc39711a7c91560eb0f0980916ae23c343b99d Subproject commit fef3d7b14ede45d051dc688aae0bb8c8b02a0566 "} {"_id":"doc-en-rust-8237bb08fe0c9828170aa62814a16bb69ef518468a80b7a89d873dc0982605f5","title":"","text":"let specialized = pat.specialize(pcx, &ctor); for (subpat, column) in specialized.iter().zip(&mut specialized_columns) { if subpat.is_or_pat() { column.patterns.extend(subpat.iter_fields()) column.patterns.extend(subpat.flatten_or_pat()) } else { column.patterns.push(subpat) }"} {"_id":"doc-en-rust-0d81726bb95ad5915bbd13ca493d9b0a8ace62c6413b3c931e3dc0c813d33623","title":"","text":"((0, 0) | (1, 0),) => {} _ => {} } // This one caused ICE https://github.com/rust-lang/rust/issues/117378 match (0u8, 0) { (x @ 0 | x @ (1 | 2), _) => {} (3.., _) => {} } }"} {"_id":"doc-en-rust-fe1179042e7657dbccbc28eb08cd0fe7bf66c4022bea7933a954276be17cd77d","title":"","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":"doc-en-rust-9cd421c8532235a9996184b485063971504d628247031e3e4f4f79fffd97b7f1","title":"","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":"doc-en-rust-501273af67428a03efdc6a5d5beb1252b68b13c60112c506253704e98d3587b4","title":"","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":"doc-en-rust-c462bf71c374ac00909cc74ea397060d40df06c6d092d3e24364238f4762ee54","title":"","text":"/// Check whether peekable iterator is empty or not. #[inline] pub fn is_empty(&mut self) -> bool { self.peek().is_some() self.peek().is_none() } }"} {"_id":"doc-en-rust-902682a2b36b189e483eac2f5d7be796a5f9c54d46e72d6fd357c7a7a842d3ee","title":"","text":"assert_eq!(ys, [5, 4, 3, 2, 1]); } #[test] fn test_peekable_is_empty() { let a = [1]; let mut it = a.iter().peekable();"} {"_id":"doc-en-rust-bc5e3f154233518cf97f5ef95b9b7c9ed8173827a3421be664c961ddd84b8b3a","title":"","text":"[[package]] name = \"compiler_builtins\" version = \"0.1.103\" version = \"0.1.104\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"a3b73c3443a5fd2438d7ba4853c64e4c8efc2404a9e28a9234cc2d5eebc6c242\" checksum = \"99c3f9035afc33f4358773239573f7d121099856753e1bbd2a6a5207098fc741\" dependencies = [ \"cc\", \"rustc-std-workspace-core\","} {"_id":"doc-en-rust-f0ce4fbc6c2722a46eb43518590757541d4634bb50374f43d1f96690963779f0","title":"","text":"panic_abort = { path = \"../panic_abort\" } core = { path = \"../core\", public = true } libc = { version = \"0.2.150\", default-features = false, features = ['rustc-dep-of-std'], public = true } compiler_builtins = { version = \"0.1.103\" } compiler_builtins = { version = \"0.1.104\" } profiler_builtins = { path = \"../profiler_builtins\", optional = true } unwind = { path = \"../unwind\" } hashbrown = { version = \"0.14\", default-features = false, features = ['rustc-dep-of-std'] }"} {"_id":"doc-en-rust-48a7309f63f33832ab46e397e9c8e2bf056542c359004058db2d193f1bce1691","title":"","text":"wasi = { version = \"0.11.0\", features = ['rustc-dep-of-std'], default-features = false } [target.'cfg(target_os = \"uefi\")'.dependencies] r-efi = { version = \"4.2.0\", features = ['rustc-dep-of-std']} r-efi-alloc = { version = \"1.0.0\", features = ['rustc-dep-of-std']} r-efi = { version = \"4.2.0\", features = ['rustc-dep-of-std'] } r-efi-alloc = { version = \"1.0.0\", features = ['rustc-dep-of-std'] } [features] backtrace = ["} {"_id":"doc-en-rust-f7435836f5bda4936b7e5c353a3e129b3805ac58bc594d9b46300f7a5355473c","title":"","text":"let debugger_visualizers = stat!(\"debugger-visualizers\", || self.encode_debugger_visualizers()); // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode // this as late as possible to give the prefetching as much time as possible to complete. // Encode exported symbols info. This is prefetched in `encode_metadata`. let exported_symbols = stat!(\"exported-symbols\", || { self.encode_exported_symbols(tcx.exported_symbols(LOCAL_CRATE)) });"} {"_id":"doc-en-rust-aeaf9350318a4bb3663bf6f1cc32436b9ac77bf894497db0416c3d8a83d46eed","title":"","text":"// there's no need to do dep-graph tracking for any of it. tcx.dep_graph.assert_ignored(); join( || encode_metadata_impl(tcx, path), || { if tcx.sess.threads() == 1 { return; } // Prefetch some queries used by metadata encoding. // This is not necessary for correctness, but is only done for performance reasons. // It can be removed if it turns out to cause trouble or be detrimental to performance. join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE)); }, ); } if tcx.sess.threads() != 1 { // Prefetch some queries used by metadata encoding. // This is not necessary for correctness, but is only done for performance reasons. // It can be removed if it turns out to cause trouble or be detrimental to performance. join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE)); } fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) { let mut encoder = opaque::FileEncoder::new(path) .unwrap_or_else(|err| tcx.sess.emit_fatal(FailCreateFileEncoder { err })); encoder.emit_raw_bytes(METADATA_HEADER);"} {"_id":"doc-en-rust-1a557fb31e7ec9f746921bfcd9b009993dbefdecb04dc7c922e90f4fc95d9c86","title":"","text":"// Simple cases, which don't need DST adjustment: // * no metadata available - just log the case // * known alignment - sized types, `[T]`, `str` or a foreign type // * packed struct - there is no alignment padding // Note that looking at `field.align` is incorrect since that is not necessarily equal // to the dynamic alignment of the type. match field.ty.kind() { _ if self.llextra.is_none() => { debug!("} {"_id":"doc-en-rust-9562da9971496335b3d7b396d935145731951f1c6245bd0eb85c92ffea4adfc0","title":"","text":"} _ if field.is_sized() => return simple(), ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(), ty::Adt(def, _) => { if def.repr().packed() { // FIXME(eddyb) generalize the adjustment when we // start supporting packing to larger alignments. assert_eq!(self.layout.align.abi.bytes(), 1); return simple(); } } _ => {} }"} {"_id":"doc-en-rust-e7c228713cc4f46e95eff2646cd0c8032f4c27ab50609c2ed5e2e6e57791b66f","title":"","text":"let unaligned_offset = bx.cx().const_usize(offset.bytes()); // Get the alignment of the field let (_, unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta); let (_, mut unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta); // For packed types, we need to cap alignment. if let ty::Adt(def, _) = self.layout.ty.kind() && let Some(packed) = def.repr().pack { let packed = bx.const_usize(packed.bytes()); let cmp = bx.icmp(IntPredicate::IntULT, unsized_align, packed); unsized_align = bx.select(cmp, unsized_align, packed) } // Bump the unaligned offset up to the appropriate alignment let offset = round_up_const_value_to_alignment(bx, unaligned_offset, unsized_align);"} {"_id":"doc-en-rust-3d06baae59aa5ca1db059efd578d6f3b14489a1ee7f3576cd617e5e07e52cb47","title":"","text":"// With custom DSTS, this *will* execute user-defined code, but the same // happens at run-time so that's okay. match self.size_and_align_of(&base_meta, &field_layout)? { Some((_, align)) => (base_meta, offset.align_to(align)), Some((_, align)) => { // For packed types, we need to cap alignment. let align = if let ty::Adt(def, _) = base.layout().ty.kind() && let Some(packed) = def.repr().pack { align.min(packed) } else { align }; (base_meta, offset.align_to(align)) } None => { // For unsized types with an extern type tail we perform no adjustments. // NOTE: keep this in sync with `PlaceRef::project_field` in the codegen backend."} {"_id":"doc-en-rust-cbc1b9676d7827bd520026f5c9b2c1e7b531d7eafc4748b8c7d6c3ec38880e5f","title":"","text":" #![feature(layout_for_ptr)] use std::mem; #[repr(packed, C)] struct PackedSized { f: u8, d: [u32; 4], } #[repr(packed, C)] struct PackedUnsized { f: u8, d: [u32], } impl PackedSized { fn unsize(&self) -> &PackedUnsized { // We can't unsize via a generic type since then we get the error // that packed structs with unsized tail don't work if the tail // might need dropping. let len = 4usize; unsafe { mem::transmute((self, len)) } } } fn main() { unsafe { let p = PackedSized { f: 0, d: [1, 2, 3, 4] }; let p = p.unsize() as *const PackedUnsized; // Make sure the size computation does *not* think there is // any padding in front of the `d` field. assert_eq!(mem::size_of_val_raw(p), 1 + 4*4); // And likewise for the offset computation. let d = std::ptr::addr_of!((*p).d); assert_eq!(d.cast::().read_unaligned(), 1); } } "} {"_id":"doc-en-rust-df5870788bb36a3168740414f5afc8d084ee554a9cecc357c2c72cd0338b9b47","title":"","text":" #![feature(layout_for_ptr)] use std::mem; #[repr(packed(4))] struct Slice([u32]); #[repr(packed(2), C)] struct PackedSized { f: u8, d: [u32; 4], } #[repr(packed(2), C)] struct PackedUnsized { f: u8, d: Slice, } impl PackedSized { fn unsize(&self) -> &PackedUnsized { // We can't unsize via a generic type since then we get the error // that packed structs with unsized tail don't work if the tail // might need dropping. let len = 4usize; unsafe { mem::transmute((self, len)) } } } fn main() { unsafe { let p = PackedSized { f: 0, d: [1, 2, 3, 4] }; let p = p.unsize() as *const PackedUnsized; // Make sure the size computation correctly adds exact 1 byte of padding // in front of the `d` field. assert_eq!(mem::size_of_val_raw(p), 1 + 1 + 4*4); // And likewise for the offset computation. let d = std::ptr::addr_of!((*p).d); assert_eq!(d.cast::().read_unaligned(), 1); } } "} {"_id":"doc-en-rust-a7d280a50e9d8b3899f11ba7eeca8482fec40e9b5c1ea4d3f8ef48741ab53330","title":"","text":" // run-pass #![feature(layout_for_ptr)] use std::mem; #[repr(packed(4))] struct Slice([u32]); #[repr(packed(2), C)] struct PackedSized { f: u8, d: [u32; 4], } #[repr(packed(2), C)] struct PackedUnsized { f: u8, d: Slice, } impl PackedSized { fn unsize(&self) -> &PackedUnsized { // We can't unsize via a generic type since then we get the error // that packed structs with unsized tail don't work if the tail // might need dropping. let len = 4usize; unsafe { mem::transmute((self, len)) } } } fn main() { unsafe { let p = PackedSized { f: 0, d: [1, 2, 3, 4] }; let p = p.unsize() as *const PackedUnsized; // Make sure the size computation correctly adds exact 1 byte of padding // in front of the `d` field. assert_eq!(mem::size_of_val_raw(p), 1 + 1 + 4*4); // And likewise for the offset computation. let d = std::ptr::addr_of!((*p).d); assert_eq!(d.cast::().read_unaligned(), 1); } } "} {"_id":"doc-en-rust-3a5fa1635d4938780437774936d546d2333e8b8ccb5584daa4f565110c1549d9","title":"","text":" // run-pass #![feature(layout_for_ptr)] use std::mem; #[repr(packed, C)] struct PackedSized { f: u8, d: [u32; 4], } #[repr(packed, C)] struct PackedUnsized { f: u8, d: [u32], } impl PackedSized { fn unsize(&self) -> &PackedUnsized { // We can't unsize via a generic type since then we get the error // that packed structs with unsized tail don't work if the tail // might need dropping. let len = 4usize; unsafe { mem::transmute((self, len)) } } } fn main() { unsafe { let p = PackedSized { f: 0, d: [1, 2, 3, 4] }; let p = p.unsize() as *const PackedUnsized; // Make sure the size computation does *not* think there is // any padding in front of the `d` field. assert_eq!(mem::size_of_val_raw(p), 1 + 4*4); // And likewise for the offset computation. let d = std::ptr::addr_of!((*p).d); assert_eq!(d.cast::().read_unaligned(), 1); } } "} {"_id":"doc-en-rust-e624bf0b377143ef96b8a4d71675a6112e33dca3db1ebfebf95f367e87ea59ef","title":"","text":"| Range(_, Some(e), _) | Ret(Some(e)) | Unary(_, e) | Yield(Some(e)) => { | Yield(Some(e)) | Yeet(Some(e)) | Become(e) => { expr = e; } Closure(closure) => { expr = &closure.body; } Gen(..) | Block(..) | ForLoop(..) | If(..) | Loop(..) | Match(..) | Struct(..) | TryBlock(..) | While(..) => break Some(expr), _ => break None, | TryBlock(..) | While(..) | ConstBlock(_) => break Some(expr), // FIXME: These can end in `}`, but changing these would break stable code. InlineAsm(_) | OffsetOf(_, _) | MacCall(_) | IncludedBytes(_) | FormatArgs(_) => { break None; } Break(_, None) | Range(_, None, _) | Ret(None) | Yield(None) | Array(_) | Call(_, _) | MethodCall(_) | Tup(_) | Lit(_) | Cast(_, _) | Type(_, _) | Await(_, _) | Field(_, _) | Index(_, _, _) | Underscore | Path(_, _) | Continue(_) | Repeat(_, _) | Paren(_) | Try(_) | Yeet(None) | Err => break None, } } }"} {"_id":"doc-en-rust-72ab6992aa6e9c29709de68326df83a42e20800aba0f33b90230f95d07d37a5e","title":"","text":" #![feature(inline_const)] #![feature(yeet_expr)] #![allow(incomplete_features)] // Necessary for now, while explicit_tail_calls is incomplete #![feature(explicit_tail_calls)] fn a() { let foo = { 1 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn b() { let foo = for i in 1..2 { break; } else { //~^ ERROR `for...else` loops are not supported return; }; } fn c() { let foo = if true { 1 } else { 0 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn d() { let foo = loop { break; } else { //~^ ERROR loop...else` loops are not supported return; }; } fn e() { let foo = match true { true => 1, false => 0 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } struct X {a: i32} fn f() { let foo = X { a: 1 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn g() { let foo = while false { break; } else { //~^ ERROR `while...else` loops are not supported return; }; } fn h() { let foo = const { 1 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn i() { let foo = &{ 1 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn j() { let bar = 0; let foo = bar = { 1 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn k() { let foo = 1 + { 1 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn l() { let foo = 1..{ 1 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn m() { let foo = return { () } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn n() { let foo = -{ 1 } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn o() -> Result<(), ()> { let foo = do yeet { () } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return Ok(()); }; } fn p() { let foo = become { () } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn q() { let foo = |x: i32| { x } else { //~^ ERROR right curly brace `}` before `else` in a `let...else` statement not allowed return; }; } fn main() {} "} {"_id":"doc-en-rust-c0aff8b03e517ec022c40c4052ccbac0e1619643fc0829cea214525b4c4bbfe1","title":"","text":" error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:9:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = ({ LL | 1 LL ~ }) else { | error: `for...else` loops are not supported --> $DIR/bad-let-else-statement.rs:18:7 | LL | let foo = for i in 1..2 { | --- `else` is attached to this loop LL | break; LL | } else { | _______^ LL | | LL | | return; LL | | }; | |_____^ | = note: consider moving this `else` clause to a separate `if` statement and use a `bool` variable to control if it should run error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:29:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = (if true { LL | 1 LL | } else { LL | 0 LL ~ }) else { | error: `loop...else` loops are not supported --> $DIR/bad-let-else-statement.rs:38:7 | LL | let foo = loop { | ---- `else` is attached to this loop LL | break; LL | } else { | _______^ LL | | LL | | return; LL | | }; | |_____^ | = note: consider moving this `else` clause to a separate `if` statement and use a `bool` variable to control if it should run error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:48:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = (match true { LL | true => 1, LL | false => 0 LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:58:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = (X { LL | a: 1 LL ~ }) else { | error: `while...else` loops are not supported --> $DIR/bad-let-else-statement.rs:67:7 | LL | let foo = while false { | ----- `else` is attached to this loop LL | break; LL | } else { | _______^ LL | | LL | | return; LL | | }; | |_____^ | = note: consider moving this `else` clause to a separate `if` statement and use a `bool` variable to control if it should run error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:76:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = (const { LL | 1 LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:85:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = &({ LL | 1 LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:95:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = bar = ({ LL | 1 LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:104:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = 1 + ({ LL | 1 LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:113:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = 1..({ LL | 1 LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:122:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = return ({ LL | () LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:131:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = -({ LL | 1 LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:140:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = do yeet ({ LL | () LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:149:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = become ({ LL | () LL ~ }) else { | error: right curly brace `}` before `else` in a `let...else` statement not allowed --> $DIR/bad-let-else-statement.rs:158:5 | LL | } else { | ^ | help: wrap the expression in parentheses | LL ~ let foo = |x: i32| ({ LL | x LL ~ }) else { | error: aborting due to 17 previous errors "} {"_id":"doc-en-rust-2c0572f88deddbc95f70193852ee5d85950aa1bb6f056a10acbd8c0a1ce844c3","title":"","text":"use std::mem; use std::num::NonZeroUsize; use std::ops::{ControlFlow, Deref}; use std::ptr::NonNull; /// An entity in the Rust type system, which can be one of /// several kinds (types, lifetimes, and consts)."} {"_id":"doc-en-rust-827fa37984f152967b7b7b36e569214a6e1741c7a99cda361159d8d90b06ad77","title":"","text":"/// `Region` and `Const` are all interned. #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct GenericArg<'tcx> { ptr: NonZeroUsize, ptr: NonNull<()>, marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>)>, } #[cfg(parallel_compiler)] unsafe impl<'tcx> rustc_data_structures::sync::DynSend for GenericArg<'tcx> where &'tcx (Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>): rustc_data_structures::sync::DynSend { } #[cfg(parallel_compiler)] unsafe impl<'tcx> rustc_data_structures::sync::DynSync for GenericArg<'tcx> where &'tcx (Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>): rustc_data_structures::sync::DynSync { } unsafe impl<'tcx> Send for GenericArg<'tcx> where &'tcx (Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>): Send { } unsafe impl<'tcx> Sync for GenericArg<'tcx> where &'tcx (Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>): Sync { } impl<'tcx> IntoDiagnosticArg for GenericArg<'tcx> { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { self.to_string().into_diagnostic_arg()"} {"_id":"doc-en-rust-310489668f3762c52a2aa576a380ecb3de3fb305dfc9bb98aae7ef103c1c5fa6","title":"","text":"GenericArgKind::Lifetime(lt) => { // Ensure we can use the tag bits. assert_eq!(mem::align_of_val(&*lt.0.0) & TAG_MASK, 0); (REGION_TAG, lt.0.0 as *const ty::RegionKind<'tcx> as usize) (REGION_TAG, NonNull::from(lt.0.0).cast()) } GenericArgKind::Type(ty) => { // Ensure we can use the tag bits. assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0); (TYPE_TAG, ty.0.0 as *const WithCachedTypeInfo> as usize) (TYPE_TAG, NonNull::from(ty.0.0).cast()) } GenericArgKind::Const(ct) => { // Ensure we can use the tag bits. assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0); (CONST_TAG, ct.0.0 as *const WithCachedTypeInfo> as usize) (CONST_TAG, NonNull::from(ct.0.0).cast()) } }; GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } GenericArg { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData } } }"} {"_id":"doc-en-rust-d00de2ffb22de6b93e9f7b7691550cbd66f7860ee10dea6c7786961bc10639b6","title":"","text":"impl<'tcx> GenericArg<'tcx> { #[inline] pub fn unpack(self) -> GenericArgKind<'tcx> { let ptr = self.ptr.get(); let ptr = unsafe { self.ptr.map_addr(|addr| NonZeroUsize::new_unchecked(addr.get() & !TAG_MASK)) }; // SAFETY: use of `Interned::new_unchecked` here is ok because these // pointers were originally created from `Interned` types in `pack()`, // and this is just going in the other direction. unsafe { match ptr & TAG_MASK { match self.ptr.addr().get() & TAG_MASK { REGION_TAG => GenericArgKind::Lifetime(ty::Region(Interned::new_unchecked( &*((ptr & !TAG_MASK) as *const ty::RegionKind<'tcx>), ptr.cast::>().as_ref(), ))), TYPE_TAG => GenericArgKind::Type(Ty(Interned::new_unchecked( &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo>), ptr.cast::>>().as_ref(), ))), CONST_TAG => GenericArgKind::Const(ty::Const(Interned::new_unchecked( &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo>), ptr.cast::>>().as_ref(), ))), _ => intrinsics::unreachable(), }"} {"_id":"doc-en-rust-eabaa4e63897d7df6730921b5ecdb9fbfa50b1bcdab27fe5df387322788595ac","title":"","text":"use std::mem; use std::num::NonZeroUsize; use std::ops::ControlFlow; use std::ptr::NonNull; use std::{fmt, str}; pub use crate::ty::diagnostics::*;"} {"_id":"doc-en-rust-ed84ea95de0b187c085de2d54e7c4680276199f8e9882e4740b095fd20b1a145","title":"","text":"#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Term<'tcx> { ptr: NonZeroUsize, ptr: NonNull<()>, marker: PhantomData<(Ty<'tcx>, Const<'tcx>)>, } #[cfg(parallel_compiler)] unsafe impl<'tcx> rustc_data_structures::sync::DynSend for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSend { } #[cfg(parallel_compiler)] unsafe impl<'tcx> rustc_data_structures::sync::DynSync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): rustc_data_structures::sync::DynSync { } unsafe impl<'tcx> Send for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Send {} unsafe impl<'tcx> Sync for Term<'tcx> where &'tcx (Ty<'tcx>, Const<'tcx>): Sync {} impl Debug for Term<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let data = if let Some(ty) = self.ty() {"} {"_id":"doc-en-rust-53926b51f3629aa7897b42ecc94d03546de3891e850f795c8fcdb392c1a3ba9a","title":"","text":"impl<'tcx> Term<'tcx> { #[inline] pub fn unpack(self) -> TermKind<'tcx> { let ptr = self.ptr.get(); let ptr = unsafe { self.ptr.map_addr(|addr| NonZeroUsize::new_unchecked(addr.get() & !TAG_MASK)) }; // SAFETY: use of `Interned::new_unchecked` here is ok because these // pointers were originally created from `Interned` types in `pack()`, // and this is just going in the other direction. unsafe { match ptr & TAG_MASK { match self.ptr.addr().get() & TAG_MASK { TYPE_TAG => TermKind::Ty(Ty(Interned::new_unchecked( &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo>), ptr.cast::>>().as_ref(), ))), CONST_TAG => TermKind::Const(ty::Const(Interned::new_unchecked( &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo>), ptr.cast::>>().as_ref(), ))), _ => core::intrinsics::unreachable(), }"} {"_id":"doc-en-rust-47e2763c2faf2d00fc0d26d389d9b9c091d8a69cf5f54c958bff6bf3e0ad9f39","title":"","text":"TermKind::Ty(ty) => { // Ensure we can use the tag bits. assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0); (TYPE_TAG, ty.0.0 as *const WithCachedTypeInfo> as usize) (TYPE_TAG, NonNull::from(ty.0.0).cast()) } TermKind::Const(ct) => { // Ensure we can use the tag bits. assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0); (CONST_TAG, ct.0.0 as *const WithCachedTypeInfo> as usize) (CONST_TAG, NonNull::from(ct.0.0).cast()) } }; Term { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } Term { ptr: ptr.map_addr(|addr| addr | tag), marker: PhantomData } } }"} {"_id":"doc-en-rust-70df76e9f877c60d1b839a1397363797c78b3b5b1e010b84cc19d715a221dcd6","title":"","text":"dividing by zero const_eval_division_overflow = overflow in signed division (dividing MIN by -1) const_eval_double_storage_live = StorageLive on a local that was already live const_eval_dyn_call_not_a_method = `dyn` call trying to call something that is not a method"} {"_id":"doc-en-rust-7707a124f9a328e348c2d152352b8fc9cf6f9f454fd176c5a55105a738a29591","title":"","text":"Operand::Immediate(Immediate::Uninit) }); // StorageLive expects the local to be dead, and marks it live. // If the local is already live, deallocate its old memory. let old = mem::replace(&mut self.frame_mut().locals[local].value, local_val); if !matches!(old, LocalValue::Dead) { throw_ub_custom!(fluent::const_eval_double_storage_live); } self.deallocate_local(old)?; Ok(()) }"} {"_id":"doc-en-rust-0f840d2f2f0f789a0962a422d9ad3626ca2e363eac6fe3608f0e38828144edf3","title":"","text":"assert!(local != mir::RETURN_PLACE, \"Cannot make return place dead\"); trace!(\"{:?} is now dead\", local); // It is entirely okay for this local to be already dead (at least that's how we currently generate MIR) // If the local is already dead, this is a NOP. let old = mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead); self.deallocate_local(old)?; Ok(())"} {"_id":"doc-en-rust-bb17b8bef4e345902db31f4bbabde33df8fe9189e80a33072f3cc9d0fe43d9b1","title":"","text":"/// At any point during the execution of a function, each local is either allocated or /// unallocated. Except as noted below, all locals except function parameters are initially /// unallocated. `StorageLive` statements cause memory to be allocated for the local while /// `StorageDead` statements cause the memory to be freed. Using a local in any way (not only /// reading/writing from it) while it is unallocated is UB. /// `StorageDead` statements cause the memory to be freed. In other words, /// `StorageLive`/`StorageDead` act like the heap operations `allocate`/`deallocate`, but for /// stack-allocated local variables. Using a local in any way (not only reading/writing from it) /// while it is unallocated is UB. /// /// Some locals have no `StorageLive` or `StorageDead` statements within the entire MIR body. /// These locals are implicitly allocated for the full duration of the function. There is a /// convenience method at `rustc_mir_dataflow::storage::always_storage_live_locals` for /// computing these locals. /// /// If the local is already allocated, calling `StorageLive` again is UB. However, for an /// unallocated local an additional `StorageDead` all is simply a nop. /// If the local is already allocated, calling `StorageLive` again will implicitly free the /// local and then allocate fresh uninitilized memory. If a local is already deallocated, /// calling `StorageDead` again is a NOP. StorageLive(Local), /// See `StorageLive` above."} {"_id":"doc-en-rust-e19c889347cfdde12c688206967d99d20c295acf9616fa779e46ec39ec4ad39a","title":"","text":" #![feature(core_intrinsics, custom_mir)] use std::intrinsics::mir::*; #[custom_mir(dialect = \"runtime\")] fn main() { mir! { let val: i32; { val = 42; //~ERROR: accessing a dead local variable StorageLive(val); // too late... (but needs to be here to make `val` not implicitly live) Return() } } } "} {"_id":"doc-en-rust-8a22929f6b1b33db82f9799fed9cfd52683005419e81790de018629a1a509ade","title":"","text":" error: Undefined Behavior: accessing a dead local variable --> $DIR/storage-live-dead-var.rs:LL:CC | LL | val = 42; | ^^^^^^^^ accessing a dead local variable | = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = note: BACKTRACE: = note: inside `main` at $DIR/storage-live-dead-var.rs:LL:CC note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error "} {"_id":"doc-en-rust-5cff5c04f8d7e1830b40b78254a5fe59b3de353ed4492ecb03dabd3562cf3f4a","title":"","text":" #![feature(core_intrinsics, custom_mir)] use std::intrinsics::mir::*; #[custom_mir(dialect = \"runtime\")] fn main() { mir! { let val: i32; let _val2: i32; { StorageLive(val); val = 42; StorageLive(val); // reset val to `uninit` _val2 = val; //~ERROR: uninitialized Return() } } } "} {"_id":"doc-en-rust-66951e5725a3cc789c54b71ffc16306e75648566a96e666efae5f89aeaa808fa","title":"","text":" error: Undefined Behavior: constructing invalid value: encountered uninitialized memory, but expected an integer --> $DIR/storage-live-resets-var.rs:LL:CC | LL | _val2 = val; | ^^^^^^^^^^^ constructing invalid value: encountered uninitialized memory, but expected an integer | = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = note: BACKTRACE: = note: inside `main` at $DIR/storage-live-resets-var.rs:LL:CC note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error "} {"_id":"doc-en-rust-56af6338b9be8e520f3afe0791424870f0db744c4b2a775991d8dc66d21db7a1","title":"","text":"], Applicability::MachineApplicable, ); } else { // FIXME: we may suggest array::repeat instead err.help(\"consider using `core::array::from_fn` to initialize the array\"); err.help(\"see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html# for more information\"); } if self.tcx.sess.is_nightly_build()"} {"_id":"doc-en-rust-e2410335bbfb023d5582d97a66885ac8750e75ae5d99b721741173417919b495","title":"","text":"| ^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `Header<'_>` | = note: the `Copy` trait is required because this value will be copied for each element of the array = help: consider using `core::array::from_fn` to initialize the array = help: see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html# for more information help: consider annotating `Header<'_>` with `#[derive(Copy)]` | LL + #[derive(Copy)]"} {"_id":"doc-en-rust-5bcec63070916e7bef220ef0383c9b6acdfd6cf89bc288930a4a1402688f1c0e","title":"","text":"| ^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `Header<'_>` | = note: the `Copy` trait is required because this value will be copied for each element of the array = help: consider using `core::array::from_fn` to initialize the array = help: see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html# for more information help: consider annotating `Header<'_>` with `#[derive(Copy)]` | LL + #[derive(Copy)]"} {"_id":"doc-en-rust-8b5193701bf4f062116d2842a6fb8aca2875a662cd1ec72df4c9b0747a5bf3c6","title":"","text":"| ^ the trait `Copy` is not implemented for `T` | = note: the `Copy` trait is required because this value will be copied for each element of the array = help: consider using `core::array::from_fn` to initialize the array = help: see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html# for more information help: consider restricting type parameter `T` | LL | fn g(x: T) -> [T; N] {"} {"_id":"doc-en-rust-15fe4e7ff26dfe7fa9d5cf04f89af2113f9671afae288ce0db09eb9298970419","title":"","text":"| = note: required for `Option` to implement `Copy` = note: the `Copy` trait is required because this value will be copied for each element of the array = help: consider using `core::array::from_fn` to initialize the array = help: see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html# for more information help: consider annotating `Bar` with `#[derive(Copy)]` | LL + #[derive(Copy)]"} {"_id":"doc-en-rust-af970157c447ffcdb8fd16c3576d6392474be24eaab77bdc50f8eed975d37bc0","title":"","text":"| ^ the trait `Copy` is not implemented for `Foo` | = note: the `Copy` trait is required because this value will be copied for each element of the array = help: consider using `core::array::from_fn` to initialize the array = help: see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html# for more information help: consider annotating `Foo` with `#[derive(Copy)]` | LL + #[derive(Copy)]"} {"_id":"doc-en-rust-44eae88b5136554fd5a69153a4580f91b4f47aed105b76159aa4b3003324c732","title":"","text":" fn foo() -> String { String::new() } fn main() { let string_arr = [foo(); 64]; //~ ERROR the trait bound `String: Copy` is not satisfied } "} {"_id":"doc-en-rust-271f0f84ca77e0e0c73c67ba5fbb64deb74c3620abc8d89864e194b5baf900cf","title":"","text":" error[E0277]: the trait bound `String: Copy` is not satisfied --> $DIR/issue-119530-sugg-from-fn.rs:4:23 | LL | let string_arr = [foo(); 64]; | ^^^^^ the trait `Copy` is not implemented for `String` | = note: the `Copy` trait is required because this value will be copied for each element of the array = help: consider using `core::array::from_fn` to initialize the array = help: see https://doc.rust-lang.org/stable/std/array/fn.from_fn.html# for more information error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-5f41b027be722a1834bef2546b1b9c414e478f088248594e1b0cc216763dba6f","title":"","text":"P: FnMut(Self::Item) -> bool, { #[inline] fn check( mut predicate: impl FnMut(T) -> bool, ) -> impl FnMut(usize, T) -> ControlFlow { fn check<'a, T>( mut predicate: impl FnMut(T) -> bool + 'a, acc: &'a mut usize, ) -> impl FnMut((), T) -> ControlFlow + 'a { #[rustc_inherit_overflow_checks] move |i, x| { if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) } move |_, x| { if predicate(x) { ControlFlow::Break(*acc) } else { *acc += 1; ControlFlow::Continue(()) } } } self.try_fold(0, check(predicate)).break_value() let mut acc = 0; self.try_fold((), check(predicate, &mut acc)).break_value() } /// Searches for an element in an iterator from the right, returning its"} {"_id":"doc-en-rust-c084cb288ab91115219674ed16bed5966fa641b475079dbe9b41431759ef365c","title":"","text":"// Free the allocation without dropping its contents let (bptr, alloc) = Box::into_raw_with_allocator(src); let src = Box::from_raw(bptr as *mut mem::ManuallyDrop); let src = Box::from_raw_in(bptr as *mut mem::ManuallyDrop, alloc.by_ref()); drop(src); Self::from_ptr_in(ptr, alloc)"} {"_id":"doc-en-rust-b746631e9f114a61df3674f0a8c62f82c71736bd800c0de2e9c1b92fda220dfe","title":"","text":"//! Runtime calls emitted by the compiler. use c_str::ToCStr; use c_str::CString; use libc::c_char; use cast; use option::Some; #[cold] #[lang=\"fail_\"]"} {"_id":"doc-en-rust-1ad2fe09beaecb7ace3efd0bd2af1f9469bfe2244409bb0d31e66889f9ee7e8b","title":"","text":"pub fn fail_bounds_check(file: *u8, line: uint, index: uint, len: uint) -> ! { let msg = format!(\"index out of bounds: the len is {} but the index is {}\", len as uint, index as uint); msg.with_c_str(|buf| fail_(buf as *u8, file, line)) let file_str = match unsafe { CString::new(file as *c_char, false) }.as_str() { // This transmute is safe because `file` is always stored in rodata. Some(s) => unsafe { cast::transmute::<&str, &'static str>(s) }, None => \"file wasn't UTF-8 safe\" }; ::rt::begin_unwind(msg, file_str, line) } #[lang=\"malloc\"]"} {"_id":"doc-en-rust-62acb1866df474e82e681dfc403d172d74fa9ebbe93cd0857721ea1cdcae871b","title":"","text":"UnresolvedFloatTy(FloatVid), UnresolvedTy(TyVid), UnresolvedConst(ConstVid), UnresolvedEffect(EffectVid), } /// See the `region_obligations` field for more information."} {"_id":"doc-en-rust-66616e5cdd7fc044d06825dc37a82fa3de041f7aba06d09fa84204b1d1007c65","title":"","text":"), UnresolvedTy(_) => write!(f, \"unconstrained type\"), UnresolvedConst(_) => write!(f, \"unconstrained const value\"), UnresolvedEffect(_) => write!(f, \"unconstrained effect value\"), } } }"} {"_id":"doc-en-rust-0023e05d4ea96590b6c49bacc00f95e6df1fb5618781e9ba7d41ecf8191e3797","title":"","text":"ty::ConstKind::Infer(InferConst::Fresh(_)) => { bug!(\"Unexpected const in full const resolver: {:?}\", c); } ty::ConstKind::Infer(InferConst::EffectVar(evid)) => { return Err(FixupError::UnresolvedEffect(evid)); } _ => {} } c.try_super_fold_with(self)"} {"_id":"doc-en-rust-8fa8e52dc5ccfb782ac2f0d81d647ecee56c9528fa61aed13af7d664547afbcd","title":"","text":" //@ known-bug: #119830 #![feature(effects)] #![feature(min_specialization)] trait Specialize {} trait Foo {} impl const Foo for T {} impl const Foo for T where T: const Specialize {} "} {"_id":"doc-en-rust-9a44ef8bc856585cb493dc7084530ccafe46449e035b6cc6b61a67c30266a799","title":"","text":" //@ check-fail // Fixes #119830 #![feature(effects)] #![feature(min_specialization)] #![feature(const_trait_impl)] trait Specialize {} trait Foo {} impl const Foo for T {} //~^ error: const `impl` for trait `Foo` which is not marked with `#[const_trait]` //~| error: the const parameter `host` is not constrained by the impl trait, self type, or predicates [E0207] impl const Foo for T where T: const Specialize {} //~^ error: const `impl` for trait `Foo` which is not marked with `#[const_trait]` //~| error: `const` can only be applied to `#[const_trait]` traits //~| error: the const parameter `host` is not constrained by the impl trait, self type, or predicates [E0207] //~| error: specialization impl does not specialize any associated items //~| error: could not resolve generic parameters on overridden impl fn main() { } "} {"_id":"doc-en-rust-15e9b3d650f0b5a229dab18b3eec51b8da548b3069f0749f6ff95c49187018ad","title":"","text":" error: const `impl` for trait `Foo` which is not marked with `#[const_trait]` --> $DIR/spec-effectvar-ice.rs:12:15 | LL | trait Foo {} | - help: mark `Foo` as const: `#[const_trait]` LL | LL | impl const Foo for T {} | ^^^ | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change error: const `impl` for trait `Foo` which is not marked with `#[const_trait]` --> $DIR/spec-effectvar-ice.rs:16:15 | LL | trait Foo {} | - help: mark `Foo` as const: `#[const_trait]` ... LL | impl const Foo for T where T: const Specialize {} | ^^^ | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change error: `const` can only be applied to `#[const_trait]` traits --> $DIR/spec-effectvar-ice.rs:16:40 | LL | impl const Foo for T where T: const Specialize {} | ^^^^^^^^^^ error[E0207]: the const parameter `host` is not constrained by the impl trait, self type, or predicates --> $DIR/spec-effectvar-ice.rs:12:9 | LL | impl const Foo for T {} | ^^^^^ unconstrained const parameter | = note: expressions using a const parameter must map each value to a distinct output value = note: proving the result of expressions other than the parameter are unique is not supported error[E0207]: the const parameter `host` is not constrained by the impl trait, self type, or predicates --> $DIR/spec-effectvar-ice.rs:16:9 | LL | impl const Foo for T where T: const Specialize {} | ^^^^^ unconstrained const parameter | = note: expressions using a const parameter must map each value to a distinct output value = note: proving the result of expressions other than the parameter are unique is not supported error: specialization impl does not specialize any associated items --> $DIR/spec-effectvar-ice.rs:16:1 | LL | impl const Foo for T where T: const Specialize {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: impl is a specialization of this impl --> $DIR/spec-effectvar-ice.rs:12:1 | LL | impl const Foo for T {} | ^^^^^^^^^^^^^^^^^^^^^^^ error: could not resolve generic parameters on overridden impl --> $DIR/spec-effectvar-ice.rs:16:1 | LL | impl const Foo for T where T: const Specialize {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0207`. "} {"_id":"doc-en-rust-f798505d9043deb42f6cc6f17e78bf9f06bbcd74eee0fb343ddb3c37698c6fe5","title":"","text":".extend( // Group the return ty with its def id, if we had one. entry.return_ty.map(|ty| { (tcx.require_lang_item(LangItem::FnOnce, None), ty) (tcx.require_lang_item(LangItem::FnOnceOutput, None), ty) }), ); }"} {"_id":"doc-en-rust-c539228302df8ec411bfeee07cff2ad4d1290b2d636dc1fcd7cf7cbba06a58c3","title":"","text":" //! This is a regression test to avoid an ICE in diagnostics code. //! A typo in the compiler used to get the DefId of FnOnce, and //! use it where an associated item was expected. fn frob() -> impl Fn + '_ {} //~^ ERROR missing lifetime specifier //~| ERROR cannot find type `P` //~| ERROR cannot find type `T` //~| ERROR `Fn`-family traits' type parameters is subject to change fn open_parent<'path>() { todo!() } fn main() { let old_path = frob(\"hello\"); //~^ ERROR function takes 0 arguments open_parent(&old_path) //~^ ERROR function takes 0 arguments } "} {"_id":"doc-en-rust-59cfc0b100385c5d2ef278b8338f726553a0f68a540527226cda0d7773001365","title":"","text":" error[E0106]: missing lifetime specifier --> $DIR/opaque-used-in-extraneous-argument.rs:5:39 | LL | fn frob() -> impl Fn + '_ {} | ^^ expected named lifetime parameter | = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`, or if you will only have owned values | LL | fn frob() -> impl Fn + 'static {} | ~~~~~~~ error[E0412]: cannot find type `P` in this scope --> $DIR/opaque-used-in-extraneous-argument.rs:5:22 | LL | fn frob() -> impl Fn + '_ {} | ^ not found in this scope | help: you might be missing a type parameter | LL | fn frob

() -> impl Fn + '_ {} | +++ error[E0412]: cannot find type `T` in this scope --> $DIR/opaque-used-in-extraneous-argument.rs:5:34 | LL | fn frob() -> impl Fn + '_ {} | ^ not found in this scope | help: you might be missing a type parameter | LL | fn frob() -> impl Fn + '_ {} | +++ error[E0658]: the precise format of `Fn`-family traits' type parameters is subject to change --> $DIR/opaque-used-in-extraneous-argument.rs:5:19 | LL | fn frob() -> impl Fn + '_ {} | ^^^^^^^^^^^^^^^^^ help: use parenthetical notation instead: `Fn(P) -> T` | = note: see issue #29625 for more information = help: add `#![feature(unboxed_closures)]` 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[E0061]: this function takes 0 arguments but 1 argument was supplied --> $DIR/opaque-used-in-extraneous-argument.rs:16:20 | LL | let old_path = frob(\"hello\"); | ^^^^ ------- | | | unexpected argument of type `&'static str` | help: remove the extra argument | note: function defined here --> $DIR/opaque-used-in-extraneous-argument.rs:5:4 | LL | fn frob() -> impl Fn + '_ {} | ^^^^ error[E0061]: this function takes 0 arguments but 1 argument was supplied --> $DIR/opaque-used-in-extraneous-argument.rs:19:5 | LL | open_parent(&old_path) | ^^^^^^^^^^^ --------- | | | unexpected argument of type `&impl FnOnce<{type error}, Output = {type error}> + Fn<{type error}> + 'static` | help: remove the extra argument | note: function defined here --> $DIR/opaque-used-in-extraneous-argument.rs:11:4 | LL | fn open_parent<'path>() { | ^^^^^^^^^^^ error: aborting due to 6 previous errors Some errors have detailed explanations: E0061, E0106, E0412, E0658. For more information about an error, try `rustc --explain E0061`. "} {"_id":"doc-en-rust-988de1176f1ee259f54e6a823ca2325648c658e4256163b1220205e7cc830832","title":"","text":" #![feature(associated_type_bounds)] // Test for . pub trait Iter { type Item<'a>: 'a where Self: 'a; fn next<'a>(&'a mut self) -> Option>; //~^ ERROR associated type bindings are not allowed here } impl Iter for () { type Item<'a> = &'a mut [()]; fn next<'a>(&'a mut self) -> Option> { None } } fn main() {} "} {"_id":"doc-en-rust-ef0e53ce4aaf9314e01bbd93038c2a85f587ca5fcaf435181a2d152793370935","title":"","text":" error[E0229]: associated type bindings are not allowed here --> $DIR/no-gat-position.rs:8:56 | LL | fn next<'a>(&'a mut self) -> Option>; | ^^^^^^^^^ associated type not allowed here error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0229`. "} {"_id":"doc-en-rust-dcfdd3146f531e528e65bd64b263b944703f2907c7ef6723f75b97debeb74cbf","title":"","text":" #![feature(generic_const_exprs)] //~^ WARN the feature `generic_const_exprs` is incomplete #![feature(non_lifetime_binders)] //~^ WARN the feature `non_lifetime_binders` is incomplete // Test for , // which originally relied on associated_type_bounds, but was // minimized away from that. trait TraitA { type AsA; } trait TraitB { type AsB; } trait TraitC {} fn foo() where for T: TraitA>, //~^ ERROR defaults for generic parameters are not allowed in `for<...>` binders //~| ERROR `impl Trait` is not allowed in bounds { } fn main() {} "} {"_id":"doc-en-rust-906dba148e9d3ba3c86d991c24a8d525f0e69466117e915f6c25a9161350df0c","title":"","text":" warning: the feature `generic_const_exprs` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/bad-suggestion-on-missing-assoc.rs:1:12 | LL | #![feature(generic_const_exprs)] | ^^^^^^^^^^^^^^^^^^^ | = note: see issue #76560 for more information = note: `#[warn(incomplete_features)]` on by default warning: the feature `non_lifetime_binders` is incomplete and may not be safe to use and/or cause compiler crashes --> $DIR/bad-suggestion-on-missing-assoc.rs:3:12 | LL | #![feature(non_lifetime_binders)] | ^^^^^^^^^^^^^^^^^^^^ | = note: see issue #108185 for more information error: defaults for generic parameters are not allowed in `for<...>` binders --> $DIR/bad-suggestion-on-missing-assoc.rs:20:9 | LL | for T: TraitA>, | ^^^^^^^^^^^^^^^^^^^^^^ error[E0562]: `impl Trait` is not allowed in bounds --> $DIR/bad-suggestion-on-missing-assoc.rs:20:49 | LL | for T: TraitA>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `impl Trait` is only allowed in arguments and return types of functions and methods error: aborting due to 2 previous errors; 2 warnings emitted For more information about this error, try `rustc --explain E0562`. "} {"_id":"doc-en-rust-f5705b1b8bcdc16efb7595022f88f2d3c99cf2d937ba27704e3e71052a07a0f3","title":"","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":"doc-en-rust-b0b9863b403080f447e63ae0cf9327cf902a07dddbb167336016e902e8fc32b9","title":"","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":"doc-en-rust-a509f91547d230f0edfb1c98b24d4e762d10f8579721a92891c17994ca92a66a","title":"","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":"doc-en-rust-2128e9fd06f41f49832d4e566037b422794f3aa8ff576207120a9095511b4968","title":"","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":"doc-en-rust-829ef606971383bd0beae6327fad90a3896165fda6edcecc2d2448e74bf86f4c","title":"","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":"doc-en-rust-505d050da985bd66ee4158271f64ac7c98fc819265ee9fa355078232a1333a64","title":"","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":"doc-en-rust-054012863feed619bb0fee6ee44e9da98f182f51d6ada3d677a535788e56b7b4","title":"","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":"doc-en-rust-772b0f77720e77cecbb9acff8a445e6003766378ac3bba0e2cc045da69f6cfa8","title":"","text":"// This makes several assumptions about what layouts we will encounter; we match what // codegen does as good as we can (see `extract_field` in `rustc_codegen_ssa/src/mir/operand.rs`). let inner_val: Immediate<_> = match (**self, self.layout.abi) { // if the entire value is uninit, then so is the field (can happen in ConstProp) // If the entire value is uninit, then so is the field (can happen in ConstProp). (Immediate::Uninit, _) => Immediate::Uninit, // If the field is uninhabited, we can forget the data (can happen in ConstProp). // `enum S { A(!), B, C }` is an example of an enum with Scalar layout that // has an `Uninhabited` variant, which means this case is possible. _ if layout.abi.is_uninhabited() => Immediate::Uninit, // the field contains no information, can be left uninit // (Scalar/ScalarPair can contain even aligned ZST, not just 1-ZST) _ if layout.is_zst() => Immediate::Uninit,"} {"_id":"doc-en-rust-a8452d2c523f5ae674443dd4c1c493896792dad8999d63cf3383ec2b6ffbd81d","title":"","text":"// see https://github.com/rust-lang/rust/issues/93688#issuecomment-1032929496.) // So we just \"offset\" by 0. let layout = base.layout().for_variant(self, variant); // In the future we might want to allow this to permit code like this: // (this is a Rust/MIR pseudocode mix) // ``` // enum Option2 { // Some(i32, !), // None, // } // // fn panic() -> ! { panic!() } // // let x: Option2; // x.Some.0 = 42; // x.Some.1 = panic(); // SetDiscriminant(x, Some); // ``` // However, for now we don't generate such MIR, and this check here *has* found real // bugs (see https://github.com/rust-lang/rust/issues/115145), so we will keep rejecting // it. assert!(!layout.abi.is_uninhabited()); // This variant may in fact be uninhabited. // See . // This cannot be `transmute` as variants *can* have a smaller size than the entire enum. base.offset(Size::ZERO, layout, self)"} {"_id":"doc-en-rust-9a1f0bb6df224909bb1cfdd60c443c26300301590e241841db58792c918fe30f","title":"","text":"/// \"Downcast\" to a variant of an enum or a coroutine. /// /// The included Symbol is the name of the variant, used for printing MIR. /// /// This operation itself is never UB, all it does is change the type of the place. Downcast(Option, VariantIdx), /// Like an explicit cast from an opaque type to a concrete type, but without"} {"_id":"doc-en-rust-5aad11bcd333b1845faf32818770b66f45b3664d66d7484ec486bbba70c53f6f","title":"","text":"operand, &mut |elem, op| match elem { TrackElem::Field(idx) => self.ecx.project_field(op, idx.as_usize()).ok(), TrackElem::Variant(idx) => { if op.layout.for_variant(&self.ecx, idx).abi.is_uninhabited() { return None; } self.ecx.project_downcast(op, idx).ok() } TrackElem::Variant(idx) => self.ecx.project_downcast(op, idx).ok(), TrackElem::Discriminant => { let variant = self.ecx.read_discriminant(op).ok()?; let discr_value ="} {"_id":"doc-en-rust-cf340f020c06db2bfdd41b6df49e930ff32ea1927d9a9ec28cd9f5a2c10d37b2","title":"","text":" // Validation stops the test before the ICE we used to hit //@compile-flags: -Zmiri-disable-validation #![feature(never_type)] #[derive(Copy, Clone)] pub enum E { A(!), } pub union U { u: (), e: E, } fn main() { let E::A(ref _a) = unsafe { &(&U { u: () }).e }; } "} {"_id":"doc-en-rust-bc1aaf00da96fbf7420acc08cf2e1b7f30a3cdf2b0d5538a0e35bb40dff06c5f","title":"","text":" - // MIR for `f` before GVN + // MIR for `f` after GVN fn f() -> u32 { let mut _0: u32; let _1: u32; let mut _2: E; let mut _3: &U; let _4: U; scope 1 { debug i => _1; } scope 2 { let mut _5: &U; } bb0: { StorageLive(_2); StorageLive(_3); _5 = const _; _3 = &(*_5); _2 = ((*_3).1: E); StorageLive(_1); - _1 = ((_2 as A).1: u32); + _1 = const 0_u32; StorageDead(_3); StorageDead(_2); - _0 = _1; + _0 = const 0_u32; StorageDead(_1); return; } } "} {"_id":"doc-en-rust-82cd4c4f9b887d1d00815cb17a54a7179d11a3ef2e03499e5df69a6c16e4f487","title":"","text":" // unit-test: GVN // compile-flags: -O // EMIT_MIR_FOR_EACH_PANIC_STRATEGY // skip-filecheck #![feature(never_type)] #[derive(Copy, Clone)] pub enum E { A(!, u32), } pub union U { i: u32, e: E, } // EMIT_MIR gvn_uninhabited.f.GVN.diff pub const fn f() -> u32 { let E::A(_, i) = unsafe { (&U { i: 0 }).e }; i } fn main() {} "} {"_id":"doc-en-rust-da8c3516a0ba0f487d175bf442266d94f92e6dcb683eaff0c582c6040de47de6","title":"","text":" // check-pass #![feature(never_type)] #[derive(Copy, Clone)] pub enum E { A(!), } pub union U { u: (), e: E, } pub const C: () = { let E::A(ref a) = unsafe { &(&U { u: () }).e}; }; fn main() {} "} {"_id":"doc-en-rust-c48bd0887c3309c6e13dedd5054a3f2b96b5521846e180847b3dee3286421f90","title":"","text":"BuiltinLintDiagnostics::UnexpectedCfgName((name, name_span), value) => { let possibilities: Vec = sess.parse_sess.check_config.expecteds.keys().copied().collect(); let mut names_possibilities: Vec<_> = if value.is_none() { // We later sort and display all the possibilities, so the order here does not matter. #[allow(rustc::potential_query_instability)] sess.parse_sess .check_config .expecteds .iter() .filter_map(|(k, v)| match v { ExpectedValues::Some(v) if v.contains(&Some(name)) => Some(k), _ => None, }) .collect() } else { Vec::new() }; let is_from_cargo = std::env::var_os(\"CARGO\").is_some(); let mut is_feature_cfg = name == sym::feature;"} {"_id":"doc-en-rust-86ee4b512e02b3f6431d05e964f033dc3d73c8b0faf21bdfb2266eb61212c529","title":"","text":"} is_feature_cfg |= best_match == sym::feature; } else if !possibilities.is_empty() { let mut possibilities = possibilities.iter().map(Symbol::as_str).collect::>(); possibilities.sort(); let possibilities = possibilities.join(\"`, `\"); } else { if !names_possibilities.is_empty() && names_possibilities.len() <= 3 { names_possibilities.sort(); for cfg_name in names_possibilities.iter() { db.span_suggestion( name_span, \"found config with similar value\", format!(\"{cfg_name} = \"{name}\"\"), Applicability::MaybeIncorrect, ); } } if !possibilities.is_empty() { let mut possibilities = possibilities.iter().map(Symbol::as_str).collect::>(); possibilities.sort(); let possibilities = possibilities.join(\"`, `\"); // The list of expected names can be long (even by default) and // so the diagnostic produced can take a lot of space. To avoid // cloging the user output we only want to print that diagnostic // once. db.help_once(format!(\"expected names are: `{possibilities}`\")); // The list of expected names can be long (even by default) and // so the diagnostic produced can take a lot of space. To avoid // cloging the user output we only want to print that diagnostic // once. db.help_once(format!(\"expected names are: `{possibilities}`\")); } } let inst = if let Some((value, _value_span)) = value {"} {"_id":"doc-en-rust-55b0219ea374a296f263a3dae9db41aa11d75294ccb6b3fafc09766f436aa550","title":"","text":" // #120427 // This test checks we won't suggest more than 3 span suggestions for cfg names // // check-pass // compile-flags: -Z unstable-options // compile-flags: --check-cfg=cfg(foo,values(\"value\")) --check-cfg=cfg(bar,values(\"value\")) --check-cfg=cfg(bee,values(\"value\")) --check-cfg=cfg(cow,values(\"value\")) #[cfg(value)] //~^ WARNING unexpected `cfg` condition name: `value` fn x() {} fn main() {} "} {"_id":"doc-en-rust-e7feec955af46fb2b9df3ee90a2d56509012bcb6c506d2bfc0837aeeda07caf7","title":"","text":" warning: unexpected `cfg` condition name: `value` --> $DIR/cfg-value-for-cfg-name-duplicate.rs:8:7 | LL | #[cfg(value)] | ^^^^^ | = help: expected names are: `bar`, `bee`, `cow`, `debug_assertions`, `doc`, `doctest`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(value)` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: 1 warning emitted "} {"_id":"doc-en-rust-36d1045473ee29dce8f278fa04f6967933c22f234890904889088c6841c296ce","title":"","text":" // #120427 // This test checks that when a single cfg has a value for user's specified name // // check-pass // compile-flags: -Z unstable-options // compile-flags: --check-cfg=cfg(foo,values(\"my_value\")) --check-cfg=cfg(bar,values(\"my_value\")) #[cfg(my_value)] //~^ WARNING unexpected `cfg` condition name: `my_value` fn x() {} fn main() {} "} {"_id":"doc-en-rust-f16fac23ffe751f0044d38ce0bdae01d0645740c7d13285f8f5cc01e411416f9","title":"","text":" warning: unexpected `cfg` condition name: `my_value` --> $DIR/cfg-value-for-cfg-name-multiple.rs:8:7 | LL | #[cfg(my_value)] | ^^^^^^^^ | = help: expected names are: `bar`, `debug_assertions`, `doc`, `doctest`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(my_value)` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default help: found config with similar value | LL | #[cfg(foo = \"my_value\")] | ~~~~~~~~~~~~~~~~ help: found config with similar value | LL | #[cfg(bar = \"my_value\")] | ~~~~~~~~~~~~~~~~ warning: 1 warning emitted "} {"_id":"doc-en-rust-aa8a9c19dcb8e76b1bb6f62946eef8a84f989dea993d0345de119c7d9d6137fb","title":"","text":" // #120427 // This test checks that when a single cfg has a value for user's specified name // suggest to use `#[cfg(target_os = \"linux\")]` instead of `#[cfg(linux)]` // // check-pass // compile-flags: -Z unstable-options // compile-flags: --check-cfg=cfg() #[cfg(linux)] //~^ WARNING unexpected `cfg` condition name: `linux` fn x() {} // will not suggest if the cfg has a value #[cfg(linux = \"os-name\")] //~^ WARNING unexpected `cfg` condition name: `linux` fn y() {} fn main() {} "} {"_id":"doc-en-rust-6cfc7e8047950d4b7d1402a12e9d29d4d851fe2e9055d4bf388db0ef86fbc982","title":"","text":" warning: unexpected `cfg` condition name: `linux` --> $DIR/cfg-value-for-cfg-name.rs:9:7 | LL | #[cfg(linux)] | ^^^^^ help: found config with similar value: `target_os = \"linux\"` | = help: expected names are: `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(linux)` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition name: `linux` --> $DIR/cfg-value-for-cfg-name.rs:14:7 | LL | #[cfg(linux = \"os-name\")] | ^^^^^^^^^^^^^^^^^ | = help: to expect this configuration use `--check-cfg=cfg(linux, values(\"os-name\"))` = note: see for more information about checking conditional configuration warning: 2 warnings emitted "} {"_id":"doc-en-rust-cda7d8f90282aa8cc965ef2baa96c25ca9f80dd402475b8d74e53d2d743bfe77","title":"","text":"type summary add -F lldb_lookup.summary_lookup -e -x -h \"^(core::([a-z_]+::)+)RefMut<.+>$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^(core::([a-z_]+::)+)RefCell<.+>$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^(core::([a-z_]+::)+)NonZero<.+>$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^core::num::([a-z_]+::)*NonZero.+$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^(std::([a-z_]+::)+)PathBuf$\" --category Rust type summary add -F lldb_lookup.summary_lookup -e -x -h \"^&(mut )?(std::([a-z_]+::)+)Path$\" --category Rust type category enable Rust"} {"_id":"doc-en-rust-2daf96f681e90b0faf8e73311a65573fd97198b7133c5dcbd4c01e57cbd27e0c","title":"","text":"if rust_type == RustType.STD_NONZERO_NUMBER: return StdNonZeroNumberSummaryProvider(valobj, dict) if rust_type == RustType.STD_PATHBUF: return StdPathBufSummaryProvider(valobj, dict) if rust_type == RustType.STD_PATH: return StdPathSummaryProvider(valobj, dict) return \"\""} {"_id":"doc-en-rust-672148d0f0327da9f82c34210e2a7dd5c15c2c1898e595eac9d570cff74af32d","title":"","text":"return '\"%s\"' % data def StdPathBufSummaryProvider(valobj, dict): # type: (SBValue, dict) -> str # logger = Logger.Logger() # logger >> \"[StdPathBufSummaryProvider] for \" + str(valobj.GetName()) return StdOsStringSummaryProvider(valobj.GetChildMemberWithName(\"inner\"), dict) def StdPathSummaryProvider(valobj, dict): # type: (SBValue, dict) -> str # logger = Logger.Logger() # logger >> \"[StdPathSummaryProvider] for \" + str(valobj.GetName()) length = valobj.GetChildMemberWithName(\"length\").GetValueAsUnsigned() if length == 0: return '\"\"' data_ptr = valobj.GetChildMemberWithName(\"data_ptr\") start = data_ptr.GetValueAsUnsigned() error = SBError() process = data_ptr.GetProcess() data = process.ReadMemory(start, length, error) if PY3: try: data = data.decode(encoding='UTF-8') except UnicodeDecodeError: return '%r' % data return '\"%s\"' % data class StructSyntheticProvider: \"\"\"Pretty-printer for structs and struct enum variants\"\"\""} {"_id":"doc-en-rust-49ee4e4ef741dffadf904d236a1fbc4f8d79ab9038e1c2e5d81690c2f5c3a28e","title":"","text":"STD_REF_MUT = \"StdRefMut\" STD_REF_CELL = \"StdRefCell\" STD_NONZERO_NUMBER = \"StdNonZeroNumber\" STD_PATH = \"StdPath\" STD_PATHBUF = \"StdPathBuf\" STD_STRING_REGEX = re.compile(r\"^(alloc::([a-z_]+::)+)String$\")"} {"_id":"doc-en-rust-52470893c6e9441a70c897d474610a648a9a910cb7c910bf58f6b4b58d2e3859","title":"","text":"STD_REF_MUT_REGEX = re.compile(r\"^(core::([a-z_]+::)+)RefMut<.+>$\") STD_REF_CELL_REGEX = re.compile(r\"^(core::([a-z_]+::)+)RefCell<.+>$\") STD_NONZERO_NUMBER_REGEX = re.compile(r\"^(core::([a-z_]+::)+)NonZero<.+>$\") STD_PATHBUF_REGEX = re.compile(r\"^(std::([a-z_]+::)+)PathBuf$\") STD_PATH_REGEX = re.compile(r\"^&(mut )?(std::([a-z_]+::)+)Path$\") TUPLE_ITEM_REGEX = re.compile(r\"__d+$\")"} {"_id":"doc-en-rust-d5b711272d579d925303b1b8fdd1817eb6e01d69d30d0fd0201600b587186a83","title":"","text":"RustType.STD_REF_CELL: STD_REF_CELL_REGEX, RustType.STD_CELL: STD_CELL_REGEX, RustType.STD_NONZERO_NUMBER: STD_NONZERO_NUMBER_REGEX, RustType.STD_PATHBUF: STD_PATHBUF_REGEX, RustType.STD_PATH: STD_PATH_REGEX, } def is_tuple_fields(fields):"} {"_id":"doc-en-rust-761e54ad2c40c71056600557f3d85bce73afe1ca485c01f736901170de77ca22","title":"","text":" //@ ignore-gdb //@ compile-flags:-g // === LLDB TESTS ================================================================================= // lldb-command:run // lldb-command:print pathbuf // lldb-check:[...] \"/some/path\" { inner = \"/some/path\" { inner = { inner = size=10 { [0] = '/' [1] = 's' [2] = 'o' [3] = 'm' [4] = 'e' [5] = '/' [6] = 'p' [7] = 'a' [8] = 't' [9] = 'h' } } } } // lldb-command:po pathbuf // lldb-check:\"/some/path\" // lldb-command:print path // lldb-check:[...] \"/some/path\" { data_ptr = [...] length = 10 } // lldb-command:po path // lldb-check:\"/some/path\" use std::path::Path; fn main() { let path = Path::new(\"/some/path\"); let pathbuf = path.to_path_buf(); zzz(); // #break } fn zzz() { () } "} {"_id":"doc-en-rust-edfef1d31c7835d58e0e011aa7001eb054fe428db9acee3e974d6b226fc3ec9d","title":"","text":"padding: 2px 4px; box-shadow: 0 0 4px var(--main-background-color); } .item-table > li > .item-name { width: 33%; } .item-table > li > div { padding-bottom: 5px; word-break: break-all; } } @media print {"} {"_id":"doc-en-rust-948b89188cc2f0679d1c2179049ca1bb49bd36feba1d41bc38e36c090f44b196","title":"","text":"pub type ReallyLongTypeNameLongLongLong = Option *const u8>; /// Short doc. pub const ReallyLongTypeNameLongLongLongConstBecauseWhyNotAConstRightGigaGigaSupraLong: u32 = 0; /// This also has a really long doccomment. Lorem ipsum dolor sit amet,"} {"_id":"doc-en-rust-8cedf14a36e2f8da5d1b90a456b5169cc1594cdfa6cec52d17ea5d207fdef0bf","title":"","text":"// In the table-ish view on the module index, the name should not be wrapped more than necessary. go-to: \"file://\" + |DOC_PATH| + \"/lib2/too_long/index.html\" assert-property: (\".item-table .struct\", {\"offsetWidth\": \"684\"}) // We'll ensure that items with short documentation have the same width. store-property: (\"//*[@class='item-table']//*[@class='struct']/..\", {\"offsetWidth\": offset_width}) assert: |offset_width| == \"277\" assert-property: (\"//*[@class='item-table']//*[@class='constant']/..\", {\"offsetWidth\": |offset_width|}) // We now make the same check on type declaration... go-to: \"file://\" + |DOC_PATH| + \"/lib2/too_long/type.ReallyLongTypeNameLongLongLong.html\""} {"_id":"doc-en-rust-9455f9422a324e05f06b7e62e1e686e3c9683cbaf84b4e15941efe4a922dda13","title":"","text":"self.lookup_and_handle_method(expr.hir_id); } hir::ExprKind::Field(ref lhs, ..) => { self.handle_field_access(lhs, expr.hir_id); if self.typeck_results().opt_field_index(expr.hir_id).is_some() { self.handle_field_access(lhs, expr.hir_id); } else { self.tcx.dcx().span_delayed_bug(expr.span, \"couldn't resolve index for field\"); } } hir::ExprKind::Struct(qpath, fields, _) => { let res = self.typeck_results().qpath_res(qpath, expr.hir_id);"} {"_id":"doc-en-rust-09e7137943226c525a696ddc6d84cb24a16b75c29b0a4be44d5a35e739d7156c","title":"","text":" // Regression test for issue #120615. fn main() { [(); loop {}].field; //~ ERROR constant evaluation is taking a long time } "} {"_id":"doc-en-rust-909fc8b3cd93a6d7278a50a71e98ac91238cf6871dbf486b24ad1e7d49af9b22","title":"","text":" error: constant evaluation is taking a long time --> $DIR/field-access-after-const-eval-fail-in-ty.rs:4:10 | LL | [(); loop {}].field; | ^^^^^^^ | = 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/field-access-after-const-eval-fail-in-ty.rs:4:10 | LL | [(); loop {}].field; | ^^^^^^^ = note: `#[deny(long_running_const_eval)]` on by default error: aborting due to 1 previous error "} {"_id":"doc-en-rust-3da1f13b025b559c13bb79a351403827433ee5b7879aaadcb2c0caaca44de531","title":"","text":"}); } let path = if trees.is_empty() && !prefix.segments.is_empty() { // Condition should match `build_reduced_graph_for_use_tree`. let path = if trees.is_empty() && !(prefix.segments.is_empty() || prefix.segments.len() == 1 && prefix.segments[0].ident.name == kw::PathRoot) { // For empty lists we need to lower the prefix so it is checked for things // like stability later. let res = self.lower_import_res(id, span);"} {"_id":"doc-en-rust-b2eb505f89890688129bba6b4b87c17755375b88cd177b14b637d1d54c52e6aa","title":"","text":" // check-pass // edition:2015 use {}; use {{}}; use ::{}; use {::{}}; fn main() {} "} {"_id":"doc-en-rust-dc2adf8fad18401b2f1ed221e35e2b25702d46614b14b01cf7625af577ebe225","title":"","text":" // check-pass // edition:2018 use {}; use {{}}; use ::{}; use {::{}}; fn main() {} "} {"_id":"doc-en-rust-bf6ebb904aebc413cd646645b3ad689fe4e97d9736ef187f4c67fcad616e1276","title":"","text":"use crate::common; use crate::traits::*; use rustc_hir as hir; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::mir::mono::MonoItem; use rustc_middle::mir::mono::{Linkage, Visibility}; use rustc_middle::ty;"} {"_id":"doc-en-rust-59ac3bf4e3ac41c6bf22ba3ce64dfbaa830791ea889796f4b8b5248c50dd7408","title":"","text":".iter() .map(|(op, op_sp)| match *op { hir::InlineAsmOperand::Const { ref anon_const } => { let const_value = cx .tcx() .const_eval_poly(anon_const.def_id.to_def_id()) .unwrap_or_else(|_| { span_bug!(*op_sp, \"asm const cannot be resolved\") }); let ty = cx .tcx() .typeck_body(anon_const.body) .node_type(anon_const.hir_id); let string = common::asm_const_to_str( cx.tcx(), *op_sp, const_value, cx.layout_of(ty), ); GlobalAsmOperandRef::Const { string } match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) { Ok(const_value) => { let ty = cx .tcx() .typeck_body(anon_const.body) .node_type(anon_const.hir_id); let string = common::asm_const_to_str( cx.tcx(), *op_sp, const_value, cx.layout_of(ty), ); GlobalAsmOperandRef::Const { string } } Err(ErrorHandled::Reported { .. }) => { // An error has already been reported and // compilation is guaranteed to fail if execution // hits this path. So an empty string instead of // a stringified constant value will suffice. GlobalAsmOperandRef::Const { string: String::new() } } Err(ErrorHandled::TooGeneric(_)) => { span_bug!( *op_sp, \"asm const cannot be resolved; too generic\" ) } } } hir::InlineAsmOperand::SymFn { ref anon_const } => { let ty = cx"} {"_id":"doc-en-rust-cba7d63cf34e5100360b021e480ab179cc27e3ca99cef94a1027b2a730190e86","title":"","text":" //@ build-fail //@ needs-asm-support #![feature(asm_const)] use std::arch::global_asm; fn main() {} global_asm!(\"/* {} */\", const 1 << 500); //~ ERROR evaluation of constant value failed [E0080] global_asm!(\"/* {} */\", const 1 / 0); //~ ERROR evaluation of constant value failed [E0080] "} {"_id":"doc-en-rust-c5e1b6277b3706ee18f80ce7da07258a94f5be92b99e7c1189249792cc99d8dd","title":"","text":" error[E0080]: evaluation of constant value failed --> $DIR/fail-const-eval-issue-121099.rs:9:31 | LL | global_asm!(\"/* {} */\", const 1 << 500); | ^^^^^^^^ attempt to shift left by `500_i32`, which would overflow error[E0080]: evaluation of constant value failed --> $DIR/fail-const-eval-issue-121099.rs:11:31 | LL | global_asm!(\"/* {} */\", const 1 / 0); | ^^^^^ attempt to divide `1_i32` by zero error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-d294bccbde25ad65ab8422f984f6b14d50fd5b37f6115c8f3822a584d407c83a","title":"","text":"} (PlaceElem::Index(idx), Value::Aggregate { fields, .. }) => { let idx = prop.get_const(idx.into())?.immediate()?; let idx = prop.ecx.read_target_usize(idx).ok()?; fields.get(FieldIdx::from_u32(idx.try_into().ok()?)).unwrap_or(&Value::Uninit) let idx = prop.ecx.read_target_usize(idx).ok()?.try_into().ok()?; if idx <= FieldIdx::MAX_AS_U32 { fields.get(FieldIdx::from_u32(idx)).unwrap_or(&Value::Uninit) } else { return None; } } ( PlaceElem::ConstantIndex { offset, min_length: _, from_end: false },"} {"_id":"doc-en-rust-c50f9d78f4ceae6c46c41e146581f4c7ed7fb40ba89d8270da319bfff578d871","title":"","text":" //@ known-bug: #121126 fn main() { let _n = 1i64 >> [64][4_294_967_295]; } "} {"_id":"doc-en-rust-95064fcc10bb2005450c1e2f406558b57b1058910b19ec051f55fa38a3b3ccc8","title":"","text":" //@ build-fail fn main() { let _n = [64][200]; //~^ ERROR this operation will panic at runtime [unconditional_panic] // issue #121126, test index value between 0xFFFF_FF00 and u32::MAX let _n = [64][u32::MAX as usize - 1]; //~^ ERROR this operation will panic at runtime [unconditional_panic] } "} {"_id":"doc-en-rust-97b3bce9232ee93449485486ce1afabe9160024e7bbacdff991027b99a7500dd","title":"","text":" error: this operation will panic at runtime --> $DIR/index-bounds.rs:4:14 | LL | let _n = [64][200]; | ^^^^^^^^^ index out of bounds: the length is 1 but the index is 200 | = note: `#[deny(unconditional_panic)]` on by default error: this operation will panic at runtime --> $DIR/index-bounds.rs:8:14 | LL | let _n = [64][u32::MAX as usize - 1]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ index out of bounds: the length is 1 but the index is 4294967294 error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-556a70d91ec77637dae96320aedbe4b059e5b409351b8fcd4a3580d67e7ccbe2","title":"","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":"doc-en-rust-dcec1ff147349f27a1c241ce2761ea31940af08123e498caf11141e18e8082a9","title":"","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":"doc-en-rust-ceec1e8b8253e908cf2b46af2edfd9c68cd49ebb7b9197d59ab3f02ec58c011f","title":"","text":" #![u={static N;}] fn main() {} "} {"_id":"doc-en-rust-b8c0888211c00dd947f95170a292d4e1a6c3d13a4cf46510e5363421adf529d1","title":"","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":"doc-en-rust-4808cfa1ea1d35f2c202a5e5b332bfd824b55d48fd7e75380e6d66ddfe579575","title":"","text":"padding: 5px 10px; } h5, h6 { color: black; text-decoration: underline; }"} {"_id":"doc-en-rust-cac7414a63918b92c9851b33a8806324d3eaf1d50db8ac3ef791dd50409ab2aa","title":"","text":" Subproject commit 7973f3560287d750500718314a0fd4025bd8ac0e Subproject commit 84f190a4abf58bbd5301c0fc831f7a96acea246f "} {"_id":"doc-en-rust-a9ccd2594edb34f4c7c8a562733c7589a153123d3756e2ea9e1db01376c4e7f9","title":"","text":"use rustc_middle::query::on_disk_cache::AbsoluteBytePos; use rustc_middle::query::on_disk_cache::{CacheDecoder, CacheEncoder, EncodedDepNodeIndex}; use rustc_middle::query::Key; use rustc_middle::ty::print::with_reduced_queries; use rustc_middle::ty::tls::{self, ImplicitCtxt}; use rustc_middle::ty::{self, TyCtxt}; use rustc_query_system::dep_graph::{DepNodeParams, HasDepContext};"} {"_id":"doc-en-rust-fc478d6e67e0e9eb6188dcb214f6ce7039989aac3608c8f3e8b5b43f0ca66be9","title":"","text":"kind: DepKind, name: &'static str, ) -> QueryStackFrame { // If reduced queries are requested, we may be printing a query stack due // to a panic. Avoid using `default_span` and `def_kind` in that case. let reduce_queries = with_reduced_queries(); // Avoid calling queries while formatting the description let description = ty::print::with_no_queries!(do_describe(tcx, key)); let description = if tcx.sess.verbose_internals() {"} {"_id":"doc-en-rust-ec9408c05b35a055f4db05fa5c106a573e37231247435328bd9f50baaaaf0ecc","title":"","text":"} else { description }; let span = if kind == dep_graph::dep_kinds::def_span { let span = if kind == dep_graph::dep_kinds::def_span || reduce_queries { // The `def_span` query is used to calculate `default_span`, // so exit to avoid infinite recursion. None"} {"_id":"doc-en-rust-6396f21ec5bbf786258db8338942a0a8d2e94851daac0c706a6b63cb75752367","title":"","text":"Some(key.default_span(tcx)) }; let def_id = key.key_as_def_id(); let def_kind = if kind == dep_graph::dep_kinds::def_kind { let def_kind = if kind == dep_graph::dep_kinds::def_kind || reduce_queries { // Try to avoid infinite recursion. None } else {"} {"_id":"doc-en-rust-deff5c76a99240c45cb38e1fb0f8dd9b3aa8be66e79627840f72514b01bfec50","title":"","text":"#[unstable(feature = \"slice_index_methods\", issue = \"none\")] fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>; /// Returns a shared reference to the output at this location, without /// Returns a pointer to the output at this location, without /// performing any bounds checking. /// Calling this method with an out-of-bounds index or a dangling `slice` pointer /// is *[undefined behavior]* even if the resulting reference is not used. /// is *[undefined behavior]* even if the resulting pointer is not used. /// /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html #[unstable(feature = \"slice_index_methods\", issue = \"none\")] unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output; /// Returns a mutable reference to the output at this location, without /// Returns a mutable pointer to the output at this location, without /// performing any bounds checking. /// Calling this method with an out-of-bounds index or a dangling `slice` pointer /// is *[undefined behavior]* even if the resulting reference is not used. /// is *[undefined behavior]* even if the resulting pointer is not used. /// /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html #[unstable(feature = \"slice_index_methods\", issue = \"none\")]"} {"_id":"doc-en-rust-cedc211ec9fe77d0e5d50a1220e89b04e2f54d0102db76083682e5341020ce17","title":"","text":"trait_selection_closure_kind_requirement = the requirement to implement `{$trait_prefix}{$expected}` derives from here trait_selection_disallowed_positional_argument = positional format arguments are not allowed here .help = only named format arguments with the name of one of the generic types are allowed in this context trait_selection_dump_vtable_entries = vtable entries for `{$trait_ref}`: {$entries} trait_selection_empty_on_clause_in_rustc_on_unimplemented = empty `on`-clause in `#[rustc_on_unimplemented]`"} {"_id":"doc-en-rust-3a52e45d874d3cb74a772e058b19cbef4bbbd3116d589ab336081c8f72151a96","title":"","text":"trait_selection_inherent_projection_normalization_overflow = overflow evaluating associated type `{$ty}` trait_selection_invalid_format_specifier = invalid format specifier .help = no format specifier are supported in this position trait_selection_invalid_on_clause_in_rustc_on_unimplemented = invalid `on`-clause in `#[rustc_on_unimplemented]` .label = invalid on-clause here"} {"_id":"doc-en-rust-b62a0aaa40a6db96e71954a1973e01090520775837fa5a6b9ccf532d5367a351","title":"","text":"trait_selection_unknown_format_parameter_for_on_unimplemented_attr = there is no parameter `{$argument_name}` on trait `{$trait_name}` .help = expect either a generic argument name or {\"`{Self}`\"} as format argument trait_selection_wrapped_parser_error = {$description} .label = {$label} "} {"_id":"doc-en-rust-acd22cf5c3b79f52573feb509dfc6477f807433c9df8f3da70352c36c6960615","title":"","text":"trait_name: Symbol, } #[derive(LintDiagnostic)] #[diag(trait_selection_disallowed_positional_argument)] #[help] pub struct DisallowedPositionalArgument; #[derive(LintDiagnostic)] #[diag(trait_selection_invalid_format_specifier)] #[help] pub struct InvalidFormatSpecifier; #[derive(LintDiagnostic)] #[diag(trait_selection_wrapped_parser_error)] pub struct WrappedParserError { description: String, label: String, } impl<'tcx> OnUnimplementedDirective { fn parse( tcx: TyCtxt<'tcx>,"} {"_id":"doc-en-rust-6b5143ed19a4a864ac3ad2f1cfa2a89e5294ec06e819f273ff321f6fe0dedbfe","title":"","text":"let trait_name = tcx.item_name(trait_def_id); let generics = tcx.generics_of(item_def_id); let s = self.symbol.as_str(); let parser = Parser::new(s, None, None, false, ParseMode::Format); let mut parser = Parser::new(s, None, None, false, ParseMode::Format); let mut result = Ok(()); for token in parser { for token in &mut parser { match token { Piece::String(_) => (), // Normal string, no need to check it Piece::NextArgument(a) => match a.position { Position::ArgumentNamed(s) => { match Symbol::intern(s) { // `{ThisTraitsName}` is allowed s if s == trait_name && !self.is_diagnostic_namespace_variant => (), s if ALLOWED_FORMAT_SYMBOLS.contains(&s) && !self.is_diagnostic_namespace_variant => { () } // So is `{A}` if A is a type parameter s if generics.params.iter().any(|param| param.name == s) => (), s => { if self.is_diagnostic_namespace_variant { tcx.emit_node_span_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, tcx.local_def_id_to_hir_id(item_def_id.expect_local()), self.span, UnknownFormatParameterForOnUnimplementedAttr { argument_name: s, trait_name, }, ); } else { result = Err(struct_span_code_err!( tcx.dcx(), self.span, E0230, \"there is no parameter `{}` on {}\", s, if trait_def_id == item_def_id { format!(\"trait `{trait_name}`\") } else { \"impl\".to_string() } ) .emit()); Piece::NextArgument(a) => { let format_spec = a.format; if self.is_diagnostic_namespace_variant && (format_spec.ty_span.is_some() || format_spec.width_span.is_some() || format_spec.precision_span.is_some() || format_spec.fill_span.is_some()) { tcx.emit_node_span_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, tcx.local_def_id_to_hir_id(item_def_id.expect_local()), self.span, InvalidFormatSpecifier, ); } match a.position { Position::ArgumentNamed(s) => { match Symbol::intern(s) { // `{ThisTraitsName}` is allowed s if s == trait_name && !self.is_diagnostic_namespace_variant => (), s if ALLOWED_FORMAT_SYMBOLS.contains(&s) && !self.is_diagnostic_namespace_variant => { () } // So is `{A}` if A is a type parameter s if generics.params.iter().any(|param| param.name == s) => (), s => { if self.is_diagnostic_namespace_variant { tcx.emit_node_span_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, tcx.local_def_id_to_hir_id(item_def_id.expect_local()), self.span, UnknownFormatParameterForOnUnimplementedAttr { argument_name: s, trait_name, }, ); } else { result = Err(struct_span_code_err!( tcx.dcx(), self.span, E0230, \"there is no parameter `{}` on {}\", s, if trait_def_id == item_def_id { format!(\"trait `{trait_name}`\") } else { \"impl\".to_string() } ) .emit()); } } } } // `{:1}` and `{}` are not to be used Position::ArgumentIs(..) | Position::ArgumentImplicitlyIs(_) => { if self.is_diagnostic_namespace_variant { tcx.emit_node_span_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, tcx.local_def_id_to_hir_id(item_def_id.expect_local()), self.span, DisallowedPositionalArgument, ); } else { let reported = struct_span_code_err!( tcx.dcx(), self.span, E0231, \"only named generic parameters are allowed\" ) .emit(); result = Err(reported); } } } // `{:1}` and `{}` are not to be used Position::ArgumentIs(..) | Position::ArgumentImplicitlyIs(_) => { let reported = struct_span_code_err!( tcx.dcx(), self.span, E0231, \"only named generic parameters are allowed\" ) .emit(); result = Err(reported); } }, } } } // we cannot return errors from processing the format string as hard error here // as the diagnostic namespace gurantees that malformed input cannot cause an error // // if we encounter any error while processing we nevertheless want to show it as warning // so that users are aware that something is not correct for e in parser.errors { if self.is_diagnostic_namespace_variant { tcx.emit_node_span_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, tcx.local_def_id_to_hir_id(item_def_id.expect_local()), self.span, WrappedParserError { description: e.description, label: e.label }, ); } else { let reported = struct_span_code_err!(tcx.dcx(), self.span, E0231, \"{}\", e.description,).emit(); result = Err(reported); } }"} {"_id":"doc-en-rust-12e50760880a8eee69696600a115118d76f30c0189b6d5e56f87281df2e6721b","title":"","text":"let empty_string = String::new(); let s = self.symbol.as_str(); let parser = Parser::new(s, None, None, false, ParseMode::Format); let mut parser = Parser::new(s, None, None, false, ParseMode::Format); let item_context = (options.get(&sym::ItemContext)).unwrap_or(&empty_string); parser let constructed_message = (&mut parser) .map(|p| match p { Piece::String(s) => s.to_owned(), Piece::NextArgument(a) => match a.position {"} {"_id":"doc-en-rust-231b420ec2c07c3a47d46d6a8f7f86c99f0cea3d86682500b8fd738bdea6f950","title":"","text":"} } } Position::ArgumentImplicitlyIs(_) if self.is_diagnostic_namespace_variant => { String::from(\"{}\") } Position::ArgumentIs(idx) if self.is_diagnostic_namespace_variant => { format!(\"{{{idx}}}\") } _ => bug!(\"broken on_unimplemented {:?} - bad format arg\", self.symbol), }, }) .collect() .collect(); // we cannot return errors from processing the format string as hard error here // as the diagnostic namespace gurantees that malformed input cannot cause an error // // if we encounter any error while processing the format string // we don't want to show the potentially half assembled formated string, // therefore we fall back to just showing the input string in this case // // The actual parser errors are emitted earlier // as lint warnings in OnUnimplementedFormatString::verify if self.is_diagnostic_namespace_variant && !parser.errors.is_empty() { String::from(s) } else { constructed_message } } }"} {"_id":"doc-en-rust-e2385a1c9177e9e6ab017cd9b5a60104074b85e344a6f3f8b2429372d2136c15","title":"","text":" #[diagnostic::on_unimplemented(message = \"{{Test } thing\")] //~^WARN unmatched `}` found //~|WARN unmatched `}` found trait ImportantTrait1 {} #[diagnostic::on_unimplemented(message = \"Test {}\")] //~^WARN positional format arguments are not allowed here //~|WARN positional format arguments are not allowed here trait ImportantTrait2 {} #[diagnostic::on_unimplemented(message = \"Test {1:}\")] //~^WARN positional format arguments are not allowed here //~|WARN positional format arguments are not allowed here trait ImportantTrait3 {} #[diagnostic::on_unimplemented(message = \"Test {Self:123}\")] //~^WARN invalid format specifier //~|WARN invalid format specifier trait ImportantTrait4 {} #[diagnostic::on_unimplemented(message = \"Test {Self:!}\")] //~^WARN expected `'}'`, found `'!'` //~|WARN expected `'}'`, found `'!'` //~|WARN unmatched `}` found //~|WARN unmatched `}` found trait ImportantTrait5 {} fn check_1(_: impl ImportantTrait1) {} fn check_2(_: impl ImportantTrait2) {} fn check_3(_: impl ImportantTrait3) {} fn check_4(_: impl ImportantTrait4) {} fn check_5(_: impl ImportantTrait5) {} fn main() { check_1(()); //~^ERROR {{Test } thing check_2(()); //~^ERROR Test {} check_3(()); //~^ERROR Test {1} check_4(()); //~^ERROR Test () check_5(()); //~^ERROR Test {Self:!} } "} {"_id":"doc-en-rust-4b5715ea039ec1cb35317a791b6d0596512d64892081e6ab8d241d1abf4b89da","title":"","text":" warning: unmatched `}` found --> $DIR/broken_format.rs:1:32 | LL | #[diagnostic::on_unimplemented(message = \"{{Test } thing\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unknown_or_malformed_diagnostic_attributes)]` on by default warning: positional format arguments are not allowed here --> $DIR/broken_format.rs:6:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {}\")] | ^^^^^^^^^^^^^^^^^^^ | = help: only named format arguments with the name of one of the generic types are allowed in this context warning: positional format arguments are not allowed here --> $DIR/broken_format.rs:11:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {1:}\")] | ^^^^^^^^^^^^^^^^^^^^^ | = help: only named format arguments with the name of one of the generic types are allowed in this context warning: invalid format specifier --> $DIR/broken_format.rs:16:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {Self:123}\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: no format specifier are supported in this position warning: expected `'}'`, found `'!'` --> $DIR/broken_format.rs:21:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {Self:!}\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^ warning: unmatched `}` found --> $DIR/broken_format.rs:21:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {Self:!}\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^ warning: unmatched `}` found --> $DIR/broken_format.rs:1:32 | LL | #[diagnostic::on_unimplemented(message = \"{{Test } thing\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0277]: {{Test } thing --> $DIR/broken_format.rs:35:13 | LL | check_1(()); | ------- ^^ the trait `ImportantTrait1` is not implemented for `()` | | | required by a bound introduced by this call | help: this trait has no implementations, consider adding one --> $DIR/broken_format.rs:4:1 | LL | trait ImportantTrait1 {} | ^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `check_1` --> $DIR/broken_format.rs:28:20 | LL | fn check_1(_: impl ImportantTrait1) {} | ^^^^^^^^^^^^^^^ required by this bound in `check_1` warning: positional format arguments are not allowed here --> $DIR/broken_format.rs:6:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {}\")] | ^^^^^^^^^^^^^^^^^^^ | = help: only named format arguments with the name of one of the generic types are allowed in this context = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0277]: Test {} --> $DIR/broken_format.rs:37:13 | LL | check_2(()); | ------- ^^ the trait `ImportantTrait2` is not implemented for `()` | | | required by a bound introduced by this call | help: this trait has no implementations, consider adding one --> $DIR/broken_format.rs:9:1 | LL | trait ImportantTrait2 {} | ^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `check_2` --> $DIR/broken_format.rs:29:20 | LL | fn check_2(_: impl ImportantTrait2) {} | ^^^^^^^^^^^^^^^ required by this bound in `check_2` warning: positional format arguments are not allowed here --> $DIR/broken_format.rs:11:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {1:}\")] | ^^^^^^^^^^^^^^^^^^^^^ | = help: only named format arguments with the name of one of the generic types are allowed in this context = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0277]: Test {1} --> $DIR/broken_format.rs:39:13 | LL | check_3(()); | ------- ^^ the trait `ImportantTrait3` is not implemented for `()` | | | required by a bound introduced by this call | help: this trait has no implementations, consider adding one --> $DIR/broken_format.rs:14:1 | LL | trait ImportantTrait3 {} | ^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `check_3` --> $DIR/broken_format.rs:30:20 | LL | fn check_3(_: impl ImportantTrait3) {} | ^^^^^^^^^^^^^^^ required by this bound in `check_3` warning: invalid format specifier --> $DIR/broken_format.rs:16:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {Self:123}\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: no format specifier are supported in this position = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0277]: Test () --> $DIR/broken_format.rs:41:13 | LL | check_4(()); | ------- ^^ the trait `ImportantTrait4` is not implemented for `()` | | | required by a bound introduced by this call | help: this trait has no implementations, consider adding one --> $DIR/broken_format.rs:19:1 | LL | trait ImportantTrait4 {} | ^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `check_4` --> $DIR/broken_format.rs:31:20 | LL | fn check_4(_: impl ImportantTrait4) {} | ^^^^^^^^^^^^^^^ required by this bound in `check_4` warning: expected `'}'`, found `'!'` --> $DIR/broken_format.rs:21:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {Self:!}\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` warning: unmatched `}` found --> $DIR/broken_format.rs:21:32 | LL | #[diagnostic::on_unimplemented(message = \"Test {Self:!}\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0277]: Test {Self:!} --> $DIR/broken_format.rs:43:13 | LL | check_5(()); | ------- ^^ the trait `ImportantTrait5` is not implemented for `()` | | | required by a bound introduced by this call | help: this trait has no implementations, consider adding one --> $DIR/broken_format.rs:26:1 | LL | trait ImportantTrait5 {} | ^^^^^^^^^^^^^^^^^^^^^ note: required by a bound in `check_5` --> $DIR/broken_format.rs:32:20 | LL | fn check_5(_: impl ImportantTrait5) {} | ^^^^^^^^^^^^^^^ required by this bound in `check_5` error: aborting due to 5 previous errors; 12 warnings emitted For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-96eda8ba510a946a0466b13da9bde5a9c3413f81952556aee78758be7a53800c","title":"","text":" //@ check-pass #![feature(type_alias_impl_trait)] fn spawn(future: F) -> impl Sized where F: FnOnce() -> T, { future } fn spawn_task(sender: &'static ()) -> impl Sized { type Tait = impl Sized + 'static; spawn::(move || sender) } fn main() {} "} {"_id":"doc-en-rust-0d1fd910709f408c06e3fcf47c0cd5aa5270cf14c84525f90f0de3d08060138d","title":"","text":"// FIXME: We should investigate the perf implications of not uniquifying // `ReErased`. We may be able to short-circuit registering region // obligations if we encounter a `ReErased` on one side, for example. ty::ReStatic | ty::ReErased => match self.canonicalize_mode { ty::ReStatic | ty::ReErased | ty::ReError(_) => match self.canonicalize_mode { CanonicalizeMode::Input => CanonicalVarKind::Region(ty::UniverseIndex::ROOT), CanonicalizeMode::Response { .. } => return r, },"} {"_id":"doc-en-rust-7f5cd00012feea2852f233f05e5009230ac435066665331b363ef05568113e55","title":"","text":"} } } ty::ReError(_) => return r, }; let existing_bound_var = match self.canonicalize_mode {"} {"_id":"doc-en-rust-fcb7a5595efb3d88743b57106b3aa4b03cc280e7a64dbceb2a12a268214a9ec5","title":"","text":" //@ compile-flags: -Znext-solver trait Tr<'a> {} // Fulfillment in the new solver relies on an invariant to hold: Either // `has_changed` is true, or computing a goal's certainty is idempotent. // This isn't true for `ReError`, which we used to pass through in the // canonicalizer even on input mode, which can cause a goal to go from // ambig => pass, but we don't consider `has_changed` when the response // only contains region constraints (since we usually uniquify regions). // // In this test: // Implicit negative coherence tries to prove `W: Constrain<'?1>`, // which will then match with the impl below. This constrains `'?1` to // `ReError`, but still bails w/ ambiguity bc we can't prove `?0: Sized`. // Then, when we recompute the goal `W: Constrain<'error>`, when // collecting ambiguities and overflows, we end up assembling a default // error candidate w/o ambiguity, which causes the goal to pass, and ICE. impl<'a, A: ?Sized> Tr<'a> for W {} struct W(A); impl<'a, A: ?Sized> Tr<'a> for A where A: Constrain<'a> {} //~^ ERROR conflicting implementations of trait `Tr<'_>` for type `W<_>` trait Constrain<'a> {} impl Constrain<'missing> for W {} //~^ ERROR use of undeclared lifetime name `'missing` fn main() {} "} {"_id":"doc-en-rust-227f87664095050acaa854589c3f4ba4bfa7da3ec05f9810dfe102f8a0d3dfb2","title":"","text":" error[E0261]: use of undeclared lifetime name `'missing` --> $DIR/dont-canonicalize-re-error.rs:25:26 | LL | impl Constrain<'missing> for W {} | - ^^^^^^^^ undeclared lifetime | | | help: consider introducing lifetime `'missing` here: `'missing,` error[E0119]: conflicting implementations of trait `Tr<'_>` for type `W<_>` --> $DIR/dont-canonicalize-re-error.rs:21:1 | LL | impl<'a, A: ?Sized> Tr<'a> for W {} | ----------------------------------- first implementation here LL | struct W(A); LL | impl<'a, A: ?Sized> Tr<'a> for A where A: Constrain<'a> {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `W<_>` error: aborting due to 2 previous errors Some errors have detailed explanations: E0119, E0261. For more information about an error, try `rustc --explain E0119`. "} {"_id":"doc-en-rust-87be1cd687c17176949a3a05eb80f6c9395b1baefd76722748dd9c20cb234c04","title":"","text":"tcx: TyCtxt<'tcx>, predicates: &List>, ) -> &'tcx List> { let predicates: Vec> = predicates .iter() .filter_map(|predicate| match predicate.skip_binder() { tcx.mk_poly_existential_predicates_from_iter(predicates.iter().filter_map(|predicate| { match predicate.skip_binder() { ty::ExistentialPredicate::Trait(trait_ref) => { let trait_ref = ty::TraitRef::identity(tcx, trait_ref.def_id); Some(ty::Binder::dummy(ty::ExistentialPredicate::Trait("} {"_id":"doc-en-rust-429eff47ce7dba6b4aa08653c8b358e3f61d523da88b35773b4e8095b01c9658","title":"","text":"} ty::ExistentialPredicate::Projection(..) => None, ty::ExistentialPredicate::AutoTrait(..) => Some(predicate), }) .collect(); tcx.mk_poly_existential_predicates(&predicates) } })) } /// Transforms args for being encoded and used in the substitution dictionary."} {"_id":"doc-en-rust-64c2dafe2b99a384cb3196f8a745fcc958a4046f8df99dba12d693eb8ff6f5fe","title":"","text":"let ty::Dynamic(preds, lifetime, kind) = ty.kind() else { bug!(\"Tried to strip auto traits from non-dynamic type {ty}\"); }; let filtered_preds = if preds.principal().is_some() { let new_rcvr = if preds.principal().is_some() { let filtered_preds = tcx.mk_poly_existential_predicates_from_iter(preds.into_iter().filter(|pred| { !matches!(pred.skip_binder(), ty::ExistentialPredicate::AutoTrait(..)) })) } else { ty::List::empty() }; let new_rcvr = Ty::new_dynamic(tcx, filtered_preds, *lifetime, *kind); })); Ty::new_dynamic(tcx, filtered_preds, *lifetime, *kind) } else { // If there's no principal type, re-encode it as a unit, since we don't know anything // about it. This technically discards the knowledge that it was a type that was made // into a trait object at some point, but that's not a lot. tcx.types.unit }; tcx.mk_args_trait(new_rcvr, args.into_iter().skip(1)) }"} {"_id":"doc-en-rust-0ebec3a6f6f0c4b49db58de5b9a1c9e99765748c4897f4af0f01714e0f99106a","title":"","text":" // Check that dropping a trait object without a principal trait succeeds //@ needs-sanitizer-cfi // FIXME(#122848) Remove only-linux once OSX CFI binaries works //@ only-linux //@ compile-flags: --crate-type=bin -Cprefer-dynamic=off -Clto -Zsanitizer=cfi //@ compile-flags: -C target-feature=-crt-static -C codegen-units=1 -C opt-level=0 // FIXME(#118761) Should be run-pass once the labels on drop are compatible. // This test is being landed ahead of that to test that the compiler doesn't ICE while labeling the // callsite for a drop, but the vtable doesn't have the correct label yet. //@ build-pass struct CustomDrop; impl Drop for CustomDrop { fn drop(&mut self) {} } fn main() { let _ = Box::new(CustomDrop) as Box; } "} {"_id":"doc-en-rust-0b9fed5f5bdff3a77caf196c401db25574a1e2dd1da23a6075d07b379f33f0a7","title":"","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":"doc-en-rust-37680bb17ce26bb7fba40af4244b4f770c4a037414da950a051dbaa21f7d5846","title":"","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":"doc-en-rust-a349c8f1e2e54d141134363fc729e548d1eb23573b03e3c23275a78bc3ae7374","title":"","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":"doc-en-rust-ea1c3dc248f4079bd9dcd9446d916ef4edd6e3261afa89671f763b3a80197af5","title":"","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":"doc-en-rust-689eb8387e5c8fd723a137cb9088e1980185f5d4d747696f184e4aea930a36ed","title":"","text":"binder: EarlyBinder>, mut did_has_local_parent: impl FnMut(DefId) -> bool, ) -> bool { let infcx = tcx.infer_ctxt().build(); let infcx = tcx .infer_ctxt() // We use the new trait solver since the obligation we are trying to // prove here may overflow and those are fatal in the old trait solver. // Which is unacceptable for a lint. // // Thanksfully the part we use here are very similar to the // new-trait-solver-as-coherence, which is in stabilization. // // https://github.com/rust-lang/rust/issues/123573 .with_next_trait_solver(true) .build(); let trait_ref = binder.instantiate(tcx, infcx.fresh_args_for_item(infer_span, trait_def_id)); let trait_ref = trait_ref.fold_with(&mut ReplaceLocalTypesWithInfer {"} {"_id":"doc-en-rust-e9426edfe3345ff6e06b63a4c9be440189c9b6ef6a08436ffcb682c3653772a0","title":"","text":" //@ check-pass //@ edition:2021 // https://github.com/rust-lang/rust/issues/123573#issue-2229428739 pub trait Test {} impl<'a, T: 'a> Test for &[T] where &'a T: Test {} fn main() { struct Local {} impl Test for &Local {} //~^ WARN non-local `impl` definition } "} {"_id":"doc-en-rust-e897b48568ab2c8bff977bf3ad01156253844e4bd3dd77df5aa381c872402e38","title":"","text":" warning: non-local `impl` definition, they should be avoided as they go against expectation --> $DIR/trait-solver-overflow-123573.rs:12:5 | LL | impl Test for &Local {} | ^^^^^^^^^^^^^^^^^^^^^^^ | = help: move this `impl` block outside the of the current function `main` = note: an `impl` definition is non-local if it is nested inside an item and may impact type checking outside of that item. This can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: one exception to the rule are anon-const (`const _: () = { ... }`) at top-level module and anon-const at the same nesting as the trait or type = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue = note: `#[warn(non_local_definitions)]` on by default warning: 1 warning emitted "} {"_id":"doc-en-rust-1093eeabbccb407ff2e3475e8595f87184f7e5b775c59a799f9a4d8a1c41955e","title":"","text":"use rustc_middle::mir::FakeReadCause; use rustc_middle::traits::ObligationCauseCode; use rustc_middle::ty::{ self, ClosureSizeProfileData, Ty, TyCtxt, TypeckResults, UpvarArgs, UpvarCapture, self, ClosureSizeProfileData, Ty, TyCtxt, TypeVisitableExt as _, TypeckResults, UpvarArgs, UpvarCapture, }; use rustc_session::lint; use rustc_span::sym;"} {"_id":"doc-en-rust-75a81037ca7d36acfd56ef02009fdbb98900906757771c5147fa2c761e69f32c","title":"","text":"); } }; let args = self.resolve_vars_if_possible(args); let closure_def_id = closure_def_id.expect_local(); assert_eq!(self.tcx.hir().body_owner_def_id(body.id()), closure_def_id);"} {"_id":"doc-en-rust-591173dee6f033b2d124d6e249122ff2d58c72beabfe96687765ae0cd4ff719c","title":"","text":"// For coroutine-closures, we additionally must compute the // `coroutine_captures_by_ref_ty` type, which is used to generate the by-ref // version of the coroutine-closure's output coroutine. if let UpvarArgs::CoroutineClosure(args) = args { if let UpvarArgs::CoroutineClosure(args) = args && !args.references_error() { let closure_env_region: ty::Region<'_> = ty::Region::new_bound( self.tcx, ty::INNERMOST,"} {"_id":"doc-en-rust-7188b7b75d7410b398add729fbe82ec7c81f9a042003a4c88cdb21bc125324a5","title":"","text":"} } #[derive(Debug, Copy, Clone, HashStable)] #[derive(Debug, Copy, Clone, HashStable, TypeFoldable, TypeVisitable)] pub enum UpvarArgs<'tcx> { Closure(GenericArgsRef<'tcx>), Coroutine(GenericArgsRef<'tcx>),"} {"_id":"doc-en-rust-5e459e5a804d52c3798cd74db47353e704c774626f14ccc71ab03eca5c295b90","title":"","text":" //@ edition: 2021 #![feature(async_closure)] struct DropMe; trait Impossible {} fn trait_error() {} pub fn main() { let b = DropMe; let async_closure = async move || { // Type error here taints the environment. This causes us to fallback all // variables to `Error`. This means that when we compute the upvars for the // *outer* coroutine-closure, we don't actually see any upvars since `MemCategorization` // and `ExprUseVisitor`` will bail early when it sees error. This means // that our underlying assumption that the parent and child captures are // compatible ends up being broken, previously leading to an ICE. trait_error::<()>(); //~^ ERROR the trait bound `(): Impossible` is not satisfied let _b = b; }; } "} {"_id":"doc-en-rust-7857980207de0c0ddaa31137eeaa02d6c8ffa467fa65dcf26e6d46d85f6bd5ea","title":"","text":" error[E0277]: the trait bound `(): Impossible` is not satisfied --> $DIR/dont-ice-when-body-tainted-by-errors.rs:19:23 | LL | trait_error::<()>(); | ^^ the trait `Impossible` is not implemented for `()` | help: this trait has no implementations, consider adding one --> $DIR/dont-ice-when-body-tainted-by-errors.rs:7:1 | LL | trait Impossible {} | ^^^^^^^^^^^^^^^^ note: required by a bound in `trait_error` --> $DIR/dont-ice-when-body-tainted-by-errors.rs:8:19 | LL | fn trait_error() {} | ^^^^^^^^^^ required by this bound in `trait_error` error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-0170e0b3b3494a209a3dff74c969a2f289be78e6951a8ed7c228e664e0748920","title":"","text":"passes_both_ffi_const_and_pure = `#[ffi_const]` function cannot be `#[ffi_pure]` passes_break_inside_async_block = `{$name}` inside of an `async` block .label = cannot `{$name}` inside of an `async` block .async_block_label = enclosing `async` block passes_break_inside_closure = `{$name}` inside of a closure .label = cannot `{$name}` inside of a closure .closure_label = enclosing closure passes_break_inside_coroutine = `{$name}` inside `{$kind}` {$source} .label = cannot `{$name}` inside `{$kind}` {$source} .coroutine_label = enclosing `{$kind}` {$source} passes_break_non_loop = `break` with value from a `{$kind}` loop .label = can only break with a value inside `loop` or breakable block"} {"_id":"doc-en-rust-a7f27742166fb3988bfaa7503d5acb4d87c6cbb1e75b4e77aed49e0dcbb067dc","title":"","text":"} #[derive(Diagnostic)] #[diag(passes_break_inside_async_block, code = E0267)] pub struct BreakInsideAsyncBlock<'a> { #[diag(passes_break_inside_coroutine, code = E0267)] pub struct BreakInsideCoroutine<'a> { #[primary_span] #[label] pub span: Span, #[label(passes_async_block_label)] pub closure_span: Span, #[label(passes_coroutine_label)] pub coroutine_span: Span, pub name: &'a str, pub kind: &'a str, pub source: &'a str, } #[derive(Diagnostic)]"} {"_id":"doc-en-rust-9e12d3f630354d7d9ad1a5fd3d8693d8bf46dd0aae8e520f2b53cecd71acb3c7","title":"","text":"use rustc_span::{BytePos, Span}; use crate::errors::{ BreakInsideAsyncBlock, BreakInsideClosure, BreakNonLoop, ContinueLabeledBlock, OutsideLoop, BreakInsideClosure, BreakInsideCoroutine, BreakNonLoop, ContinueLabeledBlock, OutsideLoop, OutsideLoopSuggestion, UnlabeledCfInWhileCondition, UnlabeledInLabeledBlock, };"} {"_id":"doc-en-rust-ed2610909c795d8a55a603120bc548ae7c8801c56090d77863b90d44a40feb2f","title":"","text":"Fn, Loop(hir::LoopSource), Closure(Span), AsyncClosure(Span), Coroutine { coroutine_span: Span, kind: hir::CoroutineDesugaring, source: hir::CoroutineSource }, UnlabeledBlock(Span), LabeledBlock, Constant,"} {"_id":"doc-en-rust-a49e3a08ed2806e6db6013fca6bc152745e918116474a2b001b4430b2cad8cbc","title":"","text":"hir::ExprKind::Closure(&hir::Closure { ref fn_decl, body, fn_decl_span, kind, .. }) => { // FIXME(coroutines): This doesn't handle coroutines correctly let cx = match kind { hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared( hir::CoroutineDesugaring::Async, hir::CoroutineSource::Block, )) => AsyncClosure(fn_decl_span), hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(kind, source)) => { Coroutine { coroutine_span: fn_decl_span, kind, source } } _ => Closure(fn_decl_span), }; self.visit_fn_decl(fn_decl);"} {"_id":"doc-en-rust-6d5bcc55c42f5007799882de2004905b7cdb1b736182c076e530f6a6ed9ecaa6","title":"","text":"Closure(closure_span) => { self.sess.dcx().emit_err(BreakInsideClosure { span, closure_span, name }); } AsyncClosure(closure_span) => { self.sess.dcx().emit_err(BreakInsideAsyncBlock { span, closure_span, name }); Coroutine { coroutine_span, kind, source } => { let kind = match kind { hir::CoroutineDesugaring::Async => \"async\", hir::CoroutineDesugaring::Gen => \"gen\", hir::CoroutineDesugaring::AsyncGen => \"async gen\", }; let source = match source { hir::CoroutineSource::Block => \"block\", hir::CoroutineSource::Closure => \"closure\", hir::CoroutineSource::Fn => \"function\", }; self.sess.dcx().emit_err(BreakInsideCoroutine { span, coroutine_span, name, kind, source, }); } UnlabeledBlock(block_span) if is_break && block_span.eq_ctxt(break_span) => { let suggestion = Some(OutsideLoopSuggestion { block_span, break_span });"} {"_id":"doc-en-rust-1f9adeeb38aaab97d095abd7f235b6fc68adae3a42dfb41ca6676ecf660fcbb6","title":"","text":"fn no_break_in_async_block() { async { break 0u8; //~ ERROR `break` inside of an `async` block break 0u8; //~ ERROR `break` inside `async` block }; } fn no_break_in_async_block_even_with_outer_loop() { loop { async { break 0u8; //~ ERROR `break` inside of an `async` block break 0u8; //~ ERROR `break` inside `async` block }; } }"} {"_id":"doc-en-rust-c92af28aa93afebb5367cf95fcbc82c130ffab9ca4b20cf669fd46fe4b2e1434","title":"","text":" error[E0267]: `break` inside of an `async` block error[E0267]: `break` inside `async` block --> $DIR/async-block-control-flow-static-semantics.rs:32:9 | LL | / async { LL | | break 0u8; | | ^^^^^^^^^ cannot `break` inside of an `async` block | | ^^^^^^^^^ cannot `break` inside `async` block LL | | }; | |_____- enclosing `async` block error[E0267]: `break` inside of an `async` block error[E0267]: `break` inside `async` block --> $DIR/async-block-control-flow-static-semantics.rs:39:13 | LL | / async { LL | | break 0u8; | | ^^^^^^^^^ cannot `break` inside of an `async` block | | ^^^^^^^^^ cannot `break` inside `async` block LL | | }; | |_________- enclosing `async` block"} {"_id":"doc-en-rust-ee315f13ce24cbd1f1309cddea0b72bf1e994bda4afab09cb9c7a5fe5beaa44d","title":"","text":" //@ edition: 2024 //@ compile-flags: -Z unstable-options #![feature(gen_blocks)] #![feature(async_closure)] async fn async_fn() { break; //~ ERROR `break` inside `async` function } gen fn gen_fn() { break; //~ ERROR `break` inside `gen` function } async gen fn async_gen_fn() { break; //~ ERROR `break` inside `async gen` function } fn main() { let _ = async { break; }; //~ ERROR `break` inside `async` block let _ = async || { break; }; //~ ERROR `break` inside `async` closure let _ = gen { break; }; //~ ERROR `break` inside `gen` block let _ = async gen { break; }; //~ ERROR `break` inside `async gen` block } "} {"_id":"doc-en-rust-570a217820cf0d9067ebbf309ac8e58b918ff7902405fd2f1693baf5d59c0eff","title":"","text":" error[E0267]: `break` inside `async` function --> $DIR/break-inside-coroutine-issue-124495.rs:8:5 | LL | async fn async_fn() { | _____________________- LL | | break; | | ^^^^^ cannot `break` inside `async` function LL | | } | |_- enclosing `async` function error[E0267]: `break` inside `gen` function --> $DIR/break-inside-coroutine-issue-124495.rs:12:5 | LL | gen fn gen_fn() { | _________________- LL | | break; | | ^^^^^ cannot `break` inside `gen` function LL | | } | |_- enclosing `gen` function error[E0267]: `break` inside `async gen` function --> $DIR/break-inside-coroutine-issue-124495.rs:16:5 | LL | async gen fn async_gen_fn() { | _____________________________- LL | | break; | | ^^^^^ cannot `break` inside `async gen` function LL | | } | |_- enclosing `async gen` function error[E0267]: `break` inside `async` block --> $DIR/break-inside-coroutine-issue-124495.rs:20:21 | LL | let _ = async { break; }; | --------^^^^^--- | | | | | cannot `break` inside `async` block | enclosing `async` block error[E0267]: `break` inside `async` closure --> $DIR/break-inside-coroutine-issue-124495.rs:21:24 | LL | let _ = async || { break; }; | --^^^^^--- | | | | | cannot `break` inside `async` closure | enclosing `async` closure error[E0267]: `break` inside `gen` block --> $DIR/break-inside-coroutine-issue-124495.rs:23:19 | LL | let _ = gen { break; }; | ------^^^^^--- | | | | | cannot `break` inside `gen` block | enclosing `gen` block error[E0267]: `break` inside `async gen` block --> $DIR/break-inside-coroutine-issue-124495.rs:25:25 | LL | let _ = async gen { break; }; | ------------^^^^^--- | | | | | cannot `break` inside `async gen` block | enclosing `async gen` block error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0267`. "} {"_id":"doc-en-rust-884f6210d960f8a92f443f51e5030895725e9a48d6b0cd75b30d9825f7583eda","title":"","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":"doc-en-rust-9f342cd547aaf6d148122ca30a202bd7b24cdff36461511c4d05c72a24e57327","title":"","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":"doc-en-rust-4e283e7b1b9c4e8ecd32e1a30e0908954def9d5b1a0e6af0e604be057d99b433","title":"","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":"doc-en-rust-32d63d7c04ad7d9a01ced489295c1a5d1e7393be4004641a91c49c9f367a86ed","title":"","text":"participle: &'tcx str, name_list: DiagSymbolList, #[subdiagnostic] change_fields_suggestion: ChangeFieldsToBeOfUnitType, change_fields_suggestion: ChangeFields, #[subdiagnostic] parent_info: Option>, #[subdiagnostic]"} {"_id":"doc-en-rust-c18cc9c1a2a751a99331dd41c696791c144b78d5f6c1a2c01b874fd2b5cf19a2","title":"","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":"doc-en-rust-e5bcdac85e322e06cb968441da5bd24a00ca55493eb511574c05481c1a639277","title":"","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":"doc-en-rust-6a2e07615246d396548518c4f221369e8624b2922f7066df96bb26887fa7dc52","title":"","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":"doc-en-rust-7117f77926ccf00bcaa9cf291e1f9b510431d111ad32d92d6e61af29b863d8e2","title":"","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":"doc-en-rust-3f19086fcb897b6ddd8d2eee6042b8f84be1308e98e761f63c92af372a153a71","title":"","text":"// Get the arguments for the found method, only specifying that `Self` is the receiver type. let Some(possible_rcvr_ty) = typeck_results.node_type_opt(rcvr.hir_id) else { return }; let args = GenericArgs::for_item(tcx, method_def_id, |param, _| { if param.index == 0 { if let ty::GenericParamDefKind::Lifetime = param.kind { tcx.lifetimes.re_erased.into() } else if param.index == 0 && param.name == kw::SelfUpper { possible_rcvr_ty.into() } else if param.index == closure_param.index { closure_ty.into()"} {"_id":"doc-en-rust-dec2cfa99cd9b2f86124fef9dc53c358dc94d1841c5b1fe70125867d3be762d8","title":"","text":"Obligation::misc(tcx, span, self.mir_def_id(), self.param_env, pred) })); if ocx.select_all_or_error().is_empty() { if ocx.select_all_or_error().is_empty() && count > 0 { diag.span_suggestion_verbose( tcx.hir().body(*body).value.peel_blocks().span.shrink_to_lo(), \"dereference the return value\","} {"_id":"doc-en-rust-3cdb716568947800dc660665d46637966e4ec7ae4633aad377ba78cbad116ae9","title":"","text":" //@ known-bug: rust-lang/rust#124563 use std::marker::PhantomData; pub trait Trait {} pub trait Foo { type Trait: Trait; type Bar: Bar; fn foo(&mut self); } pub struct FooImpl<'a, 'b, A: Trait>(PhantomData<&'a &'b A>); impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> where T: Trait, { type Trait = T; type Bar = BarImpl<'a, 'b, T>; fn foo(&mut self) { self.enter_scope(|ctx| { BarImpl(ctx); }); } } impl<'a, 'b, T> FooImpl<'a, 'b, T> where T: Trait, { fn enter_scope(&mut self, _scope: impl FnOnce(&mut Self)) {} } pub trait Bar { type Foo: Foo; } pub struct BarImpl<'a, 'b, T: Trait>(&'b mut FooImpl<'a, 'b, T>); impl<'a, 'b, T> Bar for BarImpl<'a, 'b, T> where T: Trait, { type Foo = FooImpl<'a, 'b, T>; } "} {"_id":"doc-en-rust-35a5c0249ea42732e8d74ef0a7471e5d9f5e2e32dbc1ada67b3a2dfd2a739cc4","title":"","text":" // #125634 struct Thing; // Invariant in 'a, Covariant in 'b struct TwoThings<'a, 'b>(*mut &'a (), &'b mut ()); impl Thing { fn enter_scope<'a>(self, _scope: impl for<'b> FnOnce(TwoThings<'a, 'b>)) {} } fn foo() { Thing.enter_scope(|ctx| { SameLifetime(ctx); //~ ERROR lifetime may not live long enough }); } struct SameLifetime<'a>(TwoThings<'a, 'a>); fn main() {} "} {"_id":"doc-en-rust-aa7551e493e8d0fecf8642bffeeb8c063538847a42ef8d5729276952fd011fb4","title":"","text":" error: lifetime may not live long enough --> $DIR/account-for-lifetimes-in-closure-suggestion.rs:13:22 | LL | Thing.enter_scope(|ctx| { | --- | | | has type `TwoThings<'_, '1>` | has type `TwoThings<'2, '_>` LL | SameLifetime(ctx); | ^^^ this usage requires that `'1` must outlive `'2` | = note: requirement occurs because of the type `TwoThings<'_, '_>`, which makes the generic argument `'_` invariant = note: the struct `TwoThings<'a, 'b>` is invariant over the parameter `'a` = help: see for more information about variance error: aborting due to 1 previous error "} {"_id":"doc-en-rust-9fcf30aae380e0b344e6962951ecdbae3316d6ab725ff821f65d1319407ae067","title":"","text":" // #124563 use std::marker::PhantomData; pub trait Trait {} pub trait Foo { type Trait: Trait; type Bar: Bar; fn foo(&mut self); } pub struct FooImpl<'a, 'b, A: Trait>(PhantomData<&'a &'b A>); impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> where T: Trait, { type Trait = T; type Bar = BarImpl<'a, 'b, T>; //~ ERROR lifetime bound not satisfied fn foo(&mut self) { self.enter_scope(|ctx| { //~ ERROR lifetime may not live long enough BarImpl(ctx); //~ ERROR lifetime may not live long enough }); } } impl<'a, 'b, T> FooImpl<'a, 'b, T> where T: Trait, { fn enter_scope(&mut self, _scope: impl FnOnce(&mut Self)) {} } pub trait Bar { type Foo: Foo; } pub struct BarImpl<'a, 'b, T: Trait>(&'b mut FooImpl<'a, 'b, T>); impl<'a, 'b, T> Bar for BarImpl<'a, 'b, T> where T: Trait, { type Foo = FooImpl<'a, 'b, T>; } fn main() {} "} {"_id":"doc-en-rust-915c9a2973d1864c4d78fecd55efdeb2f3cafc35584cbbe7774339ffb97b5ad6","title":"","text":" error[E0478]: lifetime bound not satisfied --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:19:16 | LL | type Bar = BarImpl<'a, 'b, T>; | ^^^^^^^^^^^^^^^^^^ | note: lifetime parameter instantiated with the lifetime `'a` as defined here --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:14:6 | LL | impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> | ^^ note: but lifetime parameter must outlive the lifetime `'b` as defined here --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:14:10 | LL | impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> | ^^ error: lifetime may not live long enough --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:23:21 | LL | self.enter_scope(|ctx| { | --- | | | has type `&'1 mut FooImpl<'_, '_, T>` | has type `&mut FooImpl<'2, '_, T>` LL | BarImpl(ctx); | ^^^ this usage requires that `'1` must outlive `'2` error: lifetime may not live long enough --> $DIR/lifetime-not-long-enough-suggestion-regression-test-124563.rs:22:9 | LL | impl<'a, 'b, T> Foo for FooImpl<'a, 'b, T> | -- -- lifetime `'b` defined here | | | lifetime `'a` defined here ... LL | / self.enter_scope(|ctx| { LL | | BarImpl(ctx); LL | | }); | |__________^ argument requires that `'a` must outlive `'b` | = help: consider adding the following bound: `'a: 'b` = note: requirement occurs because of a mutable reference to `FooImpl<'_, '_, T>` = note: mutable references are invariant over their type parameter = help: see for more information about variance error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0478`. "} {"_id":"doc-en-rust-0a99a285e7ac3914b3d61861da40db981efced525063cd82de948ceb5c475ce7","title":"","text":" // Test a method call where the parameter `B` would (illegally) be // inferred to a region bound in the method argument. If this program // were accepted, then the closure passed to `s.f` could escape its // argument. //@ run-rustfix struct S; impl S { fn f(&self, _: F) where F: FnOnce(&i32) -> B { } } fn main() { let s = S; s.f(|p| *p) //~ ERROR lifetime may not live long enough } "} {"_id":"doc-en-rust-e35d504d55df20bda2e4739b259773cb51a056cd477d85fb58cf160d50dbd968","title":"","text":"// inferred to a region bound in the method argument. If this program // were accepted, then the closure passed to `s.f` could escape its // argument. //@ run-rustfix struct S;"} {"_id":"doc-en-rust-9149a8334bf96711483d753411c4bbf57175d981daa3ca2cc442c67a4ede7dab","title":"","text":"error: lifetime may not live long enough --> $DIR/regions-escape-method.rs:15:13 --> $DIR/regions-escape-method.rs:16:13 | LL | s.f(|p| p) | -- ^ returning this value requires that `'1` must outlive `'2` | || | |return type of closure is &'2 i32 | has type `&'1 i32` | help: dereference the return value | LL | s.f(|p| *p) | + error: aborting due to 1 previous error"} {"_id":"doc-en-rust-6b491b97957f22b6ea5e5dd9d3c18e23f2d747fe4e1b44d1a2d1945a8a275690","title":"","text":"cfg_if::cfg_if! { if #[cfg(any( target_os = \"android\", target_os = \"illumos\", target_os = \"redox\", target_os = \"solaris\", target_os = \"espidf\", target_os = \"horizon\", target_os = \"vita\","} {"_id":"doc-en-rust-69ed9ccdd2df09080c308b432a934a7f751d28deed0d6b4e16171c9f20284775","title":"","text":"let Some(module) = single_import.imported_module.get() else { return Err((Undetermined, Weak::No)); }; let ImportKind::Single { source: ident, source_bindings, .. } = &single_import.kind let ImportKind::Single { source: ident, target, target_bindings, .. } = &single_import.kind else { unreachable!(); }; if binding.map_or(false, |binding| binding.module().is_some()) && source_bindings.iter().all(|binding| matches!(binding.get(), Err(Undetermined))) { // This branch allows the binding to be defined or updated later, if (ident != target) && target_bindings.iter().all(|binding| binding.get().is_none()) { // This branch allows the binding to be defined or updated later if the target name // can hide the source but these bindings are not obtained. // avoiding module inconsistency between the resolve process and the finalize process. // See more details in #124840 return Err((Undetermined, Weak::No));"} {"_id":"doc-en-rust-68b1cc219f3a239e432204e2818368a735c4447c23cd96678f076923658d3f8d","title":"","text":" //@ edition: 2018 // https://github.com/rust-lang/rust/issues/124490 use ops::{self as std}; //~^ ERROR: unresolved import `ops` use std::collections::{self as ops}; fn main() {} "} {"_id":"doc-en-rust-73027e2126ffb410f05d8ced5c8ed9f73a7f38217630b0d74a2a909da860438a","title":"","text":" error[E0432]: unresolved import `ops` --> $DIR/cycle-import-in-std-1.rs:5:11 | LL | use ops::{self as std}; | ^^^^^^^^^^^ no external crate `ops` | = help: consider importing one of these items instead: core::ops std::ops error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0432`. "} {"_id":"doc-en-rust-4b57e50eef3160e30495ed2a01c2d84df0c0914dd65249b086dc05609a47528f","title":"","text":" //@ edition: 2018 // https://github.com/rust-lang/rust/issues/125013 use ops::{self as std}; //~^ ERROR: unresolved import `ops` use std::ops::Deref::{self as ops}; fn main() {} "} {"_id":"doc-en-rust-6fc6be3c45d977c7e6cafaa42550ccc3e96f7071f87c9b62e814395e4daa51db","title":"","text":" error[E0432]: unresolved import `ops` --> $DIR/cycle-import-in-std-2.rs:5:11 | LL | use ops::{self as std}; | ^^^^^^^^^^^ no external crate `ops` | = help: consider importing one of these items instead: core::ops std::ops error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0432`. "} {"_id":"doc-en-rust-7ec7daff12cec5df14208122074fd936048e4fa17112e8df5588a95e4e7843ab","title":"","text":"use rustc_hir::def::{CtorOf, Res}; use rustc_hir::def_id::LocalDefId; use rustc_hir::{HirId, PatKind}; use rustc_middle::{bug, span_bug}; use rustc_middle::hir::place::ProjectionKind; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty::{ self, adjustment, AdtKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt as _, }; use rustc_middle::{bug, span_bug}; use rustc_span::{ErrorGuaranteed, Span}; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; use rustc_trait_selection::infer::InferCtxtExt;"} {"_id":"doc-en-rust-dde97c41bf6f574fdd90cbbf6b20af52670727061d11d04c1b79e587ffeff8e4","title":"","text":"debug!(\"pat_ty(pat={:?}) found adjusted ty `{:?}`\", pat, first_ty); return Ok(*first_ty); } } else if let PatKind::Ref(subpat, _) = pat.kind && self.cx.typeck_results().skipped_ref_pats().contains(pat.hir_id) { return self.pat_ty_adjusted(subpat); } self.pat_ty_unadjusted(pat)"} {"_id":"doc-en-rust-e02641f68d74608b3b7de9eae88d67f9edcf3d4fbf23b0efa98630f07a53dfe8","title":"","text":"self.cat_pattern(place_with_id, subpat, op)?; } PatKind::Ref(subpat, _) if self.cx.typeck_results().skipped_ref_pats().contains(pat.hir_id) => { self.cat_pattern(place_with_id, subpat, op)?; } PatKind::Box(subpat) | PatKind::Ref(subpat, _) => { // box p1, &p1, &mut p1. we can ignore the mutability of // PatKind::Ref since that information is already contained"} {"_id":"doc-en-rust-76fffe1865002e8fae3d0c5a6cc1810c22f008d47f0a29855e27983c454a7376","title":"","text":" //@ run-pass //@ edition: 2024 //@ compile-flags: -Zunstable-options #![allow(incomplete_features)] #![feature(ref_pat_eat_one_layer_2024)] struct Foo; //~^ WARN struct `Foo` is never constructed fn main() { || { //~^ WARN unused closure that must be used if let Some(Some(&mut x)) = &mut Some(&mut Some(0)) { let _: u32 = x; } }; } "} {"_id":"doc-en-rust-7478168d57873be6247926f7a729227183ef4afdb7276a33d01f2283fed36b46","title":"","text":" warning: struct `Foo` is never constructed --> $DIR/skipped-ref-pats-issue-125058.rs:8:8 | LL | struct Foo; | ^^^ | = note: `#[warn(dead_code)]` on by default warning: unused closure that must be used --> $DIR/skipped-ref-pats-issue-125058.rs:12:5 | LL | / || { LL | | LL | | if let Some(Some(&mut x)) = &mut Some(&mut Some(0)) { LL | | let _: u32 = x; LL | | } LL | | }; | |_____^ | = note: closures are lazy and do nothing unless called = note: `#[warn(unused_must_use)]` on by default warning: 2 warnings emitted "} {"_id":"doc-en-rust-077dfc1161c651344e1d269055e62dcf2731521cfa7ea2d4db3a177ba91dc09f","title":"","text":"codegen_ssa_select_cpp_build_tool_workload = in the Visual Studio installer, ensure the \"C++ build tools\" workload is selected codegen_ssa_self_contained_linker_missing = the self-contained linker was requested, but it wasn't found in the target's sysroot, or in rustc's sysroot codegen_ssa_shuffle_indices_evaluation = could not evaluate shuffle_indices at compile time codegen_ssa_specify_libraries_to_link = use the `-l` flag to specify native libraries to link"} {"_id":"doc-en-rust-7452057a42604899636274d10c67d7116af1c40e3c5245383d83c7be48316ca9","title":"","text":"let self_contained_linker = self_contained_cli || self_contained_target; if self_contained_linker && !sess.opts.cg.link_self_contained.is_linker_disabled() { let mut linker_path_exists = false; for path in sess.get_tools_search_paths(false) { let linker_path = path.join(\"gcc-ld\"); linker_path_exists |= linker_path.exists(); cmd.arg({ let mut arg = OsString::from(\"-B\"); arg.push(path.join(\"gcc-ld\")); arg.push(linker_path); arg }); } if !linker_path_exists { // As a sanity check, we emit an error if none of these paths exist: we want // self-contained linking and have no linker. sess.dcx().emit_fatal(errors::SelfContainedLinkerMissing); } } // 2. Implement the \"linker flavor\" part of this feature by asking `cc` to use some kind of"} {"_id":"doc-en-rust-b6e2a05bdcd0b4bb1deec57b0fc7371c017906dfb63146bb2609acbdbc8330b7","title":"","text":"pub struct MsvcMissingLinker; #[derive(Diagnostic)] #[diag(codegen_ssa_self_contained_linker_missing)] pub struct SelfContainedLinkerMissing; #[derive(Diagnostic)] #[diag(codegen_ssa_check_installed_visual_studio)] pub struct CheckInstalledVisualStudio;"} {"_id":"doc-en-rust-692794394728d193c742cf59c51d7757e5ab50a3f9c95a588a2b43910a463b08","title":"","text":"PathBuf::from_iter([sysroot, Path::new(&rustlib_path), Path::new(\"lib\")]) } /// Returns a path to the target's `bin` folder within its `rustlib` path in the sysroot. This is /// where binaries are usually installed, e.g. the self-contained linkers, lld-wrappers, LLVM tools, /// etc. pub fn make_target_bin_path(sysroot: &Path, target_triple: &str) -> PathBuf { let rustlib_path = rustc_target::target_rustlib_path(sysroot, target_triple); PathBuf::from_iter([sysroot, Path::new(&rustlib_path), Path::new(\"bin\")]) } #[cfg(unix)] fn current_dll_path() -> Result { use std::ffi::{CStr, OsStr};"} {"_id":"doc-en-rust-6b26c2bb3a9fef9ba74911216bae8c090841d91259cf8d6cb20d6df9d13d0410","title":"","text":") } /// Returns a list of directories where target-specific tool binaries are located. /// Returns a list of directories where target-specific tool binaries are located. Some fallback /// directories are also returned, for example if `--sysroot` is used but tools are missing /// (#125246): we also add the bin directories to the sysroot where rustc is located. pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec { let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, config::host_triple()); let p = PathBuf::from_iter([ Path::new(&self.sysroot), Path::new(&rustlib_path), Path::new(\"bin\"), ]); if self_contained { vec![p.clone(), p.join(\"self-contained\")] } else { vec![p] } let bin_path = filesearch::make_target_bin_path(&self.sysroot, config::host_triple()); let fallback_sysroot_paths = filesearch::sysroot_candidates() .into_iter() .map(|sysroot| filesearch::make_target_bin_path(&sysroot, config::host_triple())); let search_paths = std::iter::once(bin_path).chain(fallback_sysroot_paths); if self_contained { // The self-contained tools are expected to be e.g. in `bin/self-contained` in the // sysroot's `rustlib` path, so we add such a subfolder to the bin path, and the // fallback paths. search_paths.flat_map(|path| [path.clone(), path.join(\"self-contained\")]).collect() } else { search_paths.collect() } } pub fn init_incr_comp_session(&self, session_dir: PathBuf, lock_file: flock::Lock) {"} {"_id":"doc-en-rust-74f641873a99df58de71303c85d821ea2911ef32272e95c5920f9f3e1ce326cf","title":"","text":"(\"avx512bw\", Unstable(sym::avx512_target_feature)), (\"avx512cd\", Unstable(sym::avx512_target_feature)), (\"avx512dq\", Unstable(sym::avx512_target_feature)), (\"avx512er\", Unstable(sym::avx512_target_feature)), (\"avx512f\", Unstable(sym::avx512_target_feature)), (\"avx512fp16\", Unstable(sym::avx512_target_feature)), (\"avx512ifma\", Unstable(sym::avx512_target_feature)), (\"avx512pf\", Unstable(sym::avx512_target_feature)), (\"avx512vbmi\", Unstable(sym::avx512_target_feature)), (\"avx512vbmi2\", Unstable(sym::avx512_target_feature)), (\"avx512vl\", Unstable(sym::avx512_target_feature)),"} {"_id":"doc-en-rust-ef862ee23e87868ec40c16e608a512cbc441fc0f8d3eb74eed3eb933aa216368","title":"","text":"println!(\"avx512bw: {:?}\", is_x86_feature_detected!(\"avx512bw\")); println!(\"avx512cd: {:?}\", is_x86_feature_detected!(\"avx512cd\")); println!(\"avx512dq: {:?}\", is_x86_feature_detected!(\"avx512dq\")); println!(\"avx512er: {:?}\", is_x86_feature_detected!(\"avx512er\")); println!(\"avx512f: {:?}\", is_x86_feature_detected!(\"avx512f\")); println!(\"avx512ifma: {:?}\", is_x86_feature_detected!(\"avx512ifma\")); println!(\"avx512pf: {:?}\", is_x86_feature_detected!(\"avx512pf\")); println!(\"avx512vbmi2: {:?}\", is_x86_feature_detected!(\"avx512vbmi2\")); println!(\"avx512vbmi: {:?}\", is_x86_feature_detected!(\"avx512vbmi\")); println!(\"avx512vl: {:?}\", is_x86_feature_detected!(\"avx512vl\"));"} {"_id":"doc-en-rust-a1e9c41af4aac74ee90f5ed2f8df12b25b981a340697d5c43668b5d39627d668","title":"","text":"LL | cfg!(target_feature = \"zebra\"); | ^^^^^^^^^^^^^^^^^^^^^^^^ | = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512er`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512pf`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, `avx512vpopcntdq`, `bf16`, `bmi1`, and `bmi2` and 188 more = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, `avx512vpopcntdq`, `bf16`, `bmi1`, `bmi2`, `bti`, and `bulk-memory` and 186 more = note: see for more information about checking conditional configuration warning: 27 warnings emitted"} {"_id":"doc-en-rust-a67618a960415c46a5456831532fcb49d62a169b899105d69988cf581e5106b5","title":"","text":"LL | target_feature = \"_UNEXPECTED_VALUE\", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512er`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512pf`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, `avx512vpopcntdq`, `bf16`, `bmi1`, `bmi2`, `bti`, `bulk-memory`, `c`, `cache`, `cmpxchg16b`, `crc`, `crt-static`, `d`, `d32`, `dit`, `doloop`, `dotprod`, `dpb`, `dpb2`, `dsp`, `dsp1e2`, `dspe60`, `e`, `e1`, `e2`, `edsp`, `elrw`, `ermsb`, `exception-handling`, `extended-const`, `f`, `f16c`, `f32mm`, `f64mm`, `fcma`, `fdivdu`, `fhm`, `flagm`, `float1e2`, `float1e3`, `float3e4`, `float7e60`, `floate1`, `fma`, `fp-armv8`, `fp16`, `fp64`, `fpuv2_df`, `fpuv2_sf`, `fpuv3_df`, `fpuv3_hf`, `fpuv3_hi`, `fpuv3_sf`, `frecipe`, `frintts`, `fxsr`, `gfni`, `hard-float`, `hard-float-abi`, `hard-tp`, `high-registers`, `hvx`, `hvx-length128b`, `hwdiv`, `i8mm`, `jsconv`, `lahfsahf`, `lasx`, `lbt`, `lor`, `lse`, `lsx`, `lvz`, `lzcnt`, `m`, `mclass`, `movbe`, `mp`, `mp1e2`, `msa`, `mte`, `multivalue`, `mutable-globals`, `neon`, `nontrapping-fptoint`, `nvic`, `paca`, `pacg`, `pan`, `pclmulqdq`, `pmuv3`, `popcnt`, `power10-vector`, `power8-altivec`, `power8-vector`, `power9-altivec`, `power9-vector`, `prfchw`, `rand`, `ras`, `rclass`, `rcpc`, `rcpc2`, `rdm`, `rdrand`, `rdseed`, `reference-types`, `relax`, `relaxed-simd`, `rtm`, `sb`, `sha`, `sha2`, `sha3`, `sign-ext`, `simd128`, `sm4`, `spe`, `ssbs`, `sse`, `sse2`, `sse3`, `sse4.1`, `sse4.2`, `sse4a`, `ssse3`, `sve`, `sve2`, `sve2-aes`, `sve2-bitperm`, `sve2-sha3`, `sve2-sm4`, `tbm`, `thumb-mode`, `thumb2`, `tme`, `trust`, `trustzone`, `ual`, `unaligned-scalar-mem`, `v`, `v5te`, `v6`, `v6k`, `v6t2`, `v7`, `v8`, `v8.1a`, `v8.2a`, `v8.3a`, `v8.4a`, `v8.5a`, `v8.6a`, `v8.7a`, `vaes`, `vdsp2e60f`, `vdspv1`, `vdspv2`, `vfp2`, `vfp3`, `vfp4`, `vh`, `virt`, `virtualization`, `vpclmulqdq`, `vsx`, `xsave`, `xsavec`, `xsaveopt`, `xsaves`, `zba`, `zbb`, `zbc`, `zbkb`, `zbkc`, `zbkx`, `zbs`, `zdinx`, `zfh`, `zfhmin`, `zfinx`, `zhinx`, `zhinxmin`, `zk`, `zkn`, `zknd`, `zkne`, `zknh`, `zkr`, `zks`, `zksed`, `zksh`, and `zkt` = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, `avx512vpopcntdq`, `bf16`, `bmi1`, `bmi2`, `bti`, `bulk-memory`, `c`, `cache`, `cmpxchg16b`, `crc`, `crt-static`, `d`, `d32`, `dit`, `doloop`, `dotprod`, `dpb`, `dpb2`, `dsp`, `dsp1e2`, `dspe60`, `e`, `e1`, `e2`, `edsp`, `elrw`, `ermsb`, `exception-handling`, `extended-const`, `f`, `f16c`, `f32mm`, `f64mm`, `fcma`, `fdivdu`, `fhm`, `flagm`, `float1e2`, `float1e3`, `float3e4`, `float7e60`, `floate1`, `fma`, `fp-armv8`, `fp16`, `fp64`, `fpuv2_df`, `fpuv2_sf`, `fpuv3_df`, `fpuv3_hf`, `fpuv3_hi`, `fpuv3_sf`, `frecipe`, `frintts`, `fxsr`, `gfni`, `hard-float`, `hard-float-abi`, `hard-tp`, `high-registers`, `hvx`, `hvx-length128b`, `hwdiv`, `i8mm`, `jsconv`, `lahfsahf`, `lasx`, `lbt`, `lor`, `lse`, `lsx`, `lvz`, `lzcnt`, `m`, `mclass`, `movbe`, `mp`, `mp1e2`, `msa`, `mte`, `multivalue`, `mutable-globals`, `neon`, `nontrapping-fptoint`, `nvic`, `paca`, `pacg`, `pan`, `pclmulqdq`, `pmuv3`, `popcnt`, `power10-vector`, `power8-altivec`, `power8-vector`, `power9-altivec`, `power9-vector`, `prfchw`, `rand`, `ras`, `rclass`, `rcpc`, `rcpc2`, `rdm`, `rdrand`, `rdseed`, `reference-types`, `relax`, `relaxed-simd`, `rtm`, `sb`, `sha`, `sha2`, `sha3`, `sign-ext`, `simd128`, `sm4`, `spe`, `ssbs`, `sse`, `sse2`, `sse3`, `sse4.1`, `sse4.2`, `sse4a`, `ssse3`, `sve`, `sve2`, `sve2-aes`, `sve2-bitperm`, `sve2-sha3`, `sve2-sm4`, `tbm`, `thumb-mode`, `thumb2`, `tme`, `trust`, `trustzone`, `ual`, `unaligned-scalar-mem`, `v`, `v5te`, `v6`, `v6k`, `v6t2`, `v7`, `v8`, `v8.1a`, `v8.2a`, `v8.3a`, `v8.4a`, `v8.5a`, `v8.6a`, `v8.7a`, `vaes`, `vdsp2e60f`, `vdspv1`, `vdspv2`, `vfp2`, `vfp3`, `vfp4`, `vh`, `virt`, `virtualization`, `vpclmulqdq`, `vsx`, `xsave`, `xsavec`, `xsaveopt`, `xsaves`, `zba`, `zbb`, `zbc`, `zbkb`, `zbkc`, `zbkx`, `zbs`, `zdinx`, `zfh`, `zfhmin`, `zfinx`, `zhinx`, `zhinxmin`, `zk`, `zkn`, `zknd`, `zkne`, `zknh`, `zkr`, `zks`, `zksed`, `zksh`, and `zkt` = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE`"} {"_id":"doc-en-rust-cd097b0cc0bbfa6370f4d528c7e1fa2a04e0ea57746c006d42fbd8d2dd114744","title":"","text":"} fn is_internal_abi(&self, abi: SpecAbi) -> bool { matches!(abi, SpecAbi::Rust | SpecAbi::RustCall | SpecAbi::RustIntrinsic) matches!( abi, SpecAbi::Rust | SpecAbi::RustCall | SpecAbi::RustCold | SpecAbi::RustIntrinsic ) } /// Find any fn-ptr types with external ABIs in `ty`."} {"_id":"doc-en-rust-27a0ec0e26af47c44354400a16f0ef10ea5a9e85d96458e33e7d8e0fadbed124","title":"","text":" //@ check-pass #![feature(rust_cold_cc)] // extern \"rust-cold\" is a \"Rust\" ABI so we accept `repr(Rust)` types as arg/ret without warnings. pub extern \"rust-cold\" fn f(_: ()) -> Result<(), ()> { Ok(()) } extern \"rust-cold\" { pub fn g(_: ()) -> Result<(), ()>; } fn main() {} "} {"_id":"doc-en-rust-d61fa04713df96c055e94ca2fb8db9db90cfba759ac2952880298b6d37a042b5","title":"","text":"AR_loongarch64_unknown_linux_gnu=loongarch64-unknown-linux-gnu-ar CXX_loongarch64_unknown_linux_gnu=loongarch64-unknown-linux-gnu-g++ # We re-use the Linux toolchain for bare-metal, because upstream bare-metal # target support for LoongArch is only available from GCC 14+. # # See: https://github.com/gcc-mirror/gcc/commit/976f4f9e4770 ENV CC_loongarch64_unknown_none=loongarch64-unknown-linux-gnu-gcc AR_loongarch64_unknown_none=loongarch64-unknown-linux-gnu-ar CXX_loongarch64_unknown_none=loongarch64-unknown-linux-gnu-g++ CFLAGS_loongarch64_unknown_none=\"-ffreestanding -mabi=lp64d\" CXXFLAGS_loongarch64_unknown_none=\"-ffreestanding -mabi=lp64d\" CC_loongarch64_unknown_none_softfloat=loongarch64-unknown-linux-gnu-gcc AR_loongarch64_unknown_none_softfloat=loongarch64-unknown-linux-gnu-ar CXX_loongarch64_unknown_none_softfloat=loongarch64-unknown-linux-gnu-g++ CFLAGS_loongarch64_unknown_none_softfloat=\"-ffreestanding -mabi=lp64s -mfpu=none\" CXXFLAGS_loongarch64_unknown_none_softfloat=\"-ffreestanding -mabi=lp64s -mfpu=none\" ENV HOSTS=loongarch64-unknown-linux-gnu ENV TARGETS=$HOSTS ENV TARGETS=$TARGETS,loongarch64-unknown-none ENV TARGETS=$TARGETS,loongarch64-unknown-none-softfloat ENV RUST_CONFIGURE_ARGS --enable-extended "} {"_id":"doc-en-rust-bf34f7f24483ff5be36e5ad187d0e7753a0f9fe70be49b346a898715da130514","title":"","text":"--enable-profiler --disable-docs ENV SCRIPT python3 ../x.py dist --host $HOSTS --target $HOSTS ENV SCRIPT python3 ../x.py dist --host $HOSTS --target $TARGETS "} {"_id":"doc-en-rust-65934332ae8269fd7485b645a5fe8aa49babf7bbbdaf8c0ca31f9961b68355e4","title":"","text":"ENV TARGETS=$TARGETS,armv7-unknown-linux-musleabi ENV TARGETS=$TARGETS,i686-unknown-freebsd ENV TARGETS=$TARGETS,x86_64-unknown-none ENV TARGETS=$TARGETS,loongarch64-unknown-none ENV TARGETS=$TARGETS,loongarch64-unknown-none-softfloat ENV TARGETS=$TARGETS,aarch64-unknown-uefi ENV TARGETS=$TARGETS,i686-unknown-uefi ENV TARGETS=$TARGETS,x86_64-unknown-uefi"} {"_id":"doc-en-rust-e6d2ce56f22777e66038d0cdadbd360a589f3edd9d85ffdfc4aaa815fe89e422","title":"","text":"unsafe { self.current = unlinked_node.as_ref().next; self.list.unlink_node(unlinked_node); let unlinked_node = Box::from_raw(unlinked_node.as_ptr()); let unlinked_node = Box::from_raw_in(unlinked_node.as_ptr(), &self.list.alloc); Some(unlinked_node.element) } }"} {"_id":"doc-en-rust-432e4d8a2c1564b702890f34dc7d86988ea779612b1a9684f912b81410078d5d","title":"","text":"if (self.pred)(&mut node.as_mut().element) { // `unlink_node` is okay with aliasing `element` references. self.list.unlink_node(node); return Some(Box::from_raw(node.as_ptr()).element); return Some(Box::from_raw_in(node.as_ptr(), &self.list.alloc).element); } } }"} {"_id":"doc-en-rust-9a4c53105982a9020668746123894d8520820a41448f292eb6eb142df8697b2f","title":"","text":"assert_eq!(unsafe { DROPS }, 8); } #[test] fn test_allocator() { use core::alloc::AllocError; use core::alloc::Allocator; use core::alloc::Layout; use core::cell::Cell; struct A { has_allocated: Cell, has_deallocated: Cell, } unsafe impl Allocator for A { fn allocate(&self, layout: Layout) -> Result, AllocError> { assert!(!self.has_allocated.get()); self.has_allocated.set(true); Global.allocate(layout) } unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { assert!(!self.has_deallocated.get()); self.has_deallocated.set(true); unsafe { Global.deallocate(ptr, layout) } } } let alloc = &A { has_allocated: Cell::new(false), has_deallocated: Cell::new(false) }; { let mut list = LinkedList::new_in(alloc); list.push_back(5u32); list.remove(0); } assert!(alloc.has_allocated.get()); assert!(alloc.has_deallocated.get()); } "} {"_id":"doc-en-rust-4edec4f629fe09f5ea77fd78da6befd397b083f554a0c5a42027544832b213bb","title":"","text":"} } pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; pub const DEFAULT_MIN_STACK_SIZE: usize = 64 * 1024; impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements"} {"_id":"doc-en-rust-b27ccf26e8e01f741c444b428c084a0ac4031c47d622e726596cb65871dda5c4","title":"","text":"pub struct Thread(!); pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; pub const DEFAULT_MIN_STACK_SIZE: usize = 64 * 1024; impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements"} {"_id":"doc-en-rust-7256ba3346742f57f198b924a9127fb0818ab8d9f7e3d2d2e92b3b888c81c61b","title":"","text":"use std::hash::Hash; use super::{ err_ub, format_interp_error, machine::AllocMap, throw_ub, AllocId, CheckInAllocMsg, err_ub, format_interp_error, machine::AllocMap, throw_ub, AllocId, AllocKind, CheckInAllocMsg, GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy, Pointer, Projectable, Scalar, ValueVisitor, };"} {"_id":"doc-en-rust-45893a6df1dc4dab79c6691bf469bcc572c8d71b006563c95b3dc70797b3c7bf","title":"","text":"Ub(PointerOutOfBounds { .. }) => DanglingPtrOutOfBounds { ptr_kind }, // This cannot happen during const-eval (because interning already detects // dangling pointers), but it can happen in Miri. Ub(PointerUseAfterFree(..)) => DanglingPtrUseAfterFree { ptr_kind, },"} {"_id":"doc-en-rust-51f0a6d42da9a84b6e38ddd4f12528bf2793f198044c23b29625964612554975","title":"","text":"} } // Mutability check. // Dangling and Mutability check. let (size, _align, alloc_kind) = self.ecx.get_alloc_info(alloc_id); if alloc_kind == AllocKind::Dead { // This can happen for zero-sized references. We can't have *any* references to non-existing // allocations though, interning rejects them all as the rest of rustc isn't happy with them... // so we throw an error, even though this isn't really UB. // A potential future alternative would be to resurrect this as a zero-sized allocation // (which codegen will then compile to an aligned dummy pointer anyway). throw_validation_failure!(self.path, DanglingPtrUseAfterFree { ptr_kind }); } // If this allocation has size zero, there is no actual mutability here. let (size, _align, _alloc_kind) = self.ecx.get_alloc_info(alloc_id); if size != Size::ZERO { let alloc_actual_mutbl = mutability(self.ecx, alloc_id); // Mutable pointer to immutable memory is no good."} {"_id":"doc-en-rust-775a3c2e2ccc94e53a2f7eb7c8a210b8f18f5a5d73630678ed56a7e884cd8221","title":"","text":"} const FOO: &() = { //~^ ERROR encountered dangling pointer //~^ ERROR it is undefined behavior to use this value let y = (); unsafe { Foo { y: &y }.long_live_the_unit } };"} {"_id":"doc-en-rust-1d7205ef2d1cdce997a37938cab34772a64437c802084a4b8cc74945148072b2","title":"","text":" error: encountered dangling pointer in final value of constant error[E0080]: it is undefined behavior to use this value --> $DIR/dangling-alloc-id-ice.rs:12:1 | LL | const FOO: &() = { | ^^^^^^^^^^^^^^ | ^^^^^^^^^^^^^^ constructing invalid value: encountered a dangling reference (use-after-free) | = note: 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. = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { HEX_DUMP } error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-a79491717afa25314e4aaea837646e735ebc5333ca38ee96b203e7491c011b17","title":"","text":" // Strip out raw byte dumps to make comparison platform-independent: //@ normalize-stderr-test \"(the raw bytes of the constant) (size: [0-9]*, align: [0-9]*)\" -> \"$1 (size: $$SIZE, align: $$ALIGN)\" //@ normalize-stderr-test \"([0-9a-f][0-9a-f] |╾─*A(LLOC)?[0-9]+(+[a-z0-9]+)?()?─*╼ )+ *│.*\" -> \"HEX_DUMP\" //@ normalize-stderr-test \"HEX_DUMPs*ns*HEX_DUMP\" -> \"HEX_DUMP\" pub struct Wrapper; pub static MAGIC_FFI_REF: &'static Wrapper = unsafe { //~^ERROR: it is undefined behavior to use this value std::mem::transmute(&{ let y = 42; y }) }; fn main() {} "} {"_id":"doc-en-rust-87538a581b02627077edcb4c6dabb7a8d80e91cddb9f68ae8a3fdcc3ae40c42f","title":"","text":" error[E0080]: it is undefined behavior to use this value --> $DIR/dangling-zst-ice-issue-126393.rs:7:1 | LL | pub static MAGIC_FFI_REF: &'static Wrapper = unsafe { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a dangling reference (use-after-free) | = note: 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. = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { HEX_DUMP } error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-0a4d2b856166a27c6f6f54c96436e4ac5e7c580080dd36883722dc11327eef9b","title":"","text":"variant_index: VariantIdx, ) -> InterpResult<'tcx, Option<(ScalarInt, usize)>> { match self.layout_of(ty)?.variants { abi::Variants::Single { .. } => Ok(None), abi::Variants::Single { .. } => { // The tag of a `Single` enum is like the tag of the niched // variant: there's no tag as the discriminant is encoded // entirely implicitly. If `write_discriminant` ever hits this // case, we do a \"validation read\" to ensure the the right // discriminant is encoded implicitly, so any attempt to write // the wrong discriminant for a `Single` enum will reliably // result in UB. Ok(None) } abi::Variants::Multiple { tag_encoding: TagEncoding::Direct,"} {"_id":"doc-en-rust-d5422c0584080a2feeb4098ecac661d0797151dbbf4d9a1d16a3db338cb7f388","title":"","text":"// We consider three kinds of enums, each demanding a different // treatment of their layout computation: // 1. enums that are uninhabited // 2. enums for which all but one variant is uninhabited // 3. enums with multiple inhabited variants // 1. enums that are uninhabited ZSTs // 2. enums that delegate their layout to a variant // 3. enums with multiple variants match layout.variants() { _ if layout.abi.is_uninhabited() => { // Uninhabited enums are usually (always?) zero-sized. In // the (unlikely?) event that an uninhabited enum is // non-zero-sized, this assert will trigger an ICE, and this // code should be modified such that a `layout.size` amount // of uninhabited bytes is returned instead. // // Uninhabited enums are currently implemented such that // their layout is described with `Variants::Single`, even // though they don't necessarily have a 'single' variant to // defer to. That said, we don't bother specifically // matching on `Variants::Single` in this arm because the // behavioral principles here remain true even if, for // whatever reason, the compiler describes an uninhabited // enum with `Variants::Multiple`. assert_eq!(layout.size, Size::ZERO); Variants::Single { .. } if layout.abi.is_uninhabited() && layout.size == Size::ZERO => { // The layout representation of uninhabited, ZST enums is // defined to be like that of the `!` type, as opposed of a // typical enum. Consequently, they cannot be descended into // as if they typical enums. We therefore special-case this // scenario and simply return an uninhabited `Tree`. Ok(Self::uninhabited()) } Variants::Single { index } => { // `Variants::Single` on non-uninhabited enums denotes that // `Variants::Single` on enums with variants denotes that // the enum delegates its layout to the variant at `index`. layout_of_variant(*index) } Variants::Multiple { tag_field, .. } => { // `Variants::Multiple` denotes an enum with multiple // inhabited variants. The layout of such an enum is the // disjunction of the layouts of its tagged variants. // variants. The layout of such an enum is the disjunction // of the layouts of its tagged variants. // For enums (but not coroutines), the tag field is // currently always the first field of the layout."} {"_id":"doc-en-rust-96cf101a5830b87be4693b1660806b6a5f995878493e9805ac4446e2f92ea263","title":"","text":"Y(Uninhabited), } enum MultipleUninhabited { X(u8, Uninhabited), Y(Uninhabited, u16), } fn main() { assert_transmutable::(); assert_transmutable::(); assert_transmutable::(); assert_transmutable::(); }"} {"_id":"doc-en-rust-5f59221148764dc60e34746dc3a805c9fee624d72b28449ee41af6c030b7295d","title":"","text":"} // Non-ZST uninhabited types are, nonetheless, uninhabited. fn yawning_void() { fn yawning_void_struct() { enum Void {} struct YawningVoid(Void, u128);"} {"_id":"doc-en-rust-ef506e68475906629a10370022a0e7b74af54aa740dfc8bbe9558c4235e22830","title":"","text":"assert::is_maybe_transmutable::<(), Void>(); //~ ERROR: cannot be safely transmuted } // Non-ZST uninhabited types are, nonetheless, uninhabited. fn yawning_void_enum() { enum Void {} enum YawningVoid { A(Void, u128), } const _: () = { assert!(std::mem::size_of::() == std::mem::size_of::()); // Just to be sure the above constant actually evaluated: assert!(false); //~ ERROR: evaluation of constant value failed }; // This transmutation is vacuously acceptable; since one cannot construct a // `Void`, unsoundness cannot directly arise from transmuting a void into // anything else. assert::is_maybe_transmutable::(); assert::is_maybe_transmutable::<(), Void>(); //~ ERROR: cannot be safely transmuted } // References to uninhabited types are, logically, uninhabited, but for layout // purposes are not ZSTs, and aren't treated as uninhabited when they appear in // enum variants."} {"_id":"doc-en-rust-af59ca616396d51e0e260dccee168c9cf4a217152ef11722096aa33fe9d2dc4c","title":"","text":"= note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/uninhabited.rs:65:9 --> $DIR/uninhabited.rs:63:9 | LL | assert!(false); | ^^^^^^^^^^^^^^ the evaluated program panicked at 'assertion failed: false', $DIR/uninhabited.rs:65:9 | ^^^^^^^^^^^^^^ the evaluated program panicked at 'assertion failed: false', $DIR/uninhabited.rs:63:9 | = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/uninhabited.rs:87:9 | LL | assert!(false); | ^^^^^^^^^^^^^^ the evaluated program panicked at 'assertion failed: false', $DIR/uninhabited.rs:87:9 | = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info)"} {"_id":"doc-en-rust-cc9d1e90323245f0606e541237d0014d48840ab17ca5444460229c519da56254","title":"","text":"LL | | }> | |__________^ required by this bound in `is_maybe_transmutable` error[E0277]: `()` cannot be safely transmuted into `yawning_void::Void` error[E0277]: `()` cannot be safely transmuted into `yawning_void_struct::Void` --> $DIR/uninhabited.rs:49:41 | LL | assert::is_maybe_transmutable::<(), Void>(); | ^^^^ `yawning_void::Void` is uninhabited | ^^^^ `yawning_void_struct::Void` is uninhabited | note: required by a bound in `is_maybe_transmutable` --> $DIR/uninhabited.rs:10:14 | LL | pub fn is_maybe_transmutable() | --------------------- required by a bound in this function LL | where LL | Dst: BikeshedIntrinsicFrom | |__________^ required by this bound in `is_maybe_transmutable` error[E0277]: `()` cannot be safely transmuted into `yawning_void_enum::Void` --> $DIR/uninhabited.rs:71:41 | LL | assert::is_maybe_transmutable::<(), Void>(); | ^^^^ `yawning_void_enum::Void` is uninhabited | note: required by a bound in `is_maybe_transmutable` --> $DIR/uninhabited.rs:10:14"} {"_id":"doc-en-rust-4f9fe29ac001edf59ce5a9a54504749c0f8dc9b31a49fadc8287525adfb54a2c","title":"","text":"| |__________^ required by this bound in `is_maybe_transmutable` error[E0277]: `u128` cannot be safely transmuted into `DistantVoid` --> $DIR/uninhabited.rs:70:43 --> $DIR/uninhabited.rs:92:43 | LL | assert::is_maybe_transmutable::(); | ^^^^^^^^^^^ at least one value of `u128` isn't a bit-valid value of `DistantVoid`"} {"_id":"doc-en-rust-53bff1178a55a3a739a5b7c9d2318cedb645678f50dfc933a502dc8e81a88ab1","title":"","text":"LL | | }> | |__________^ required by this bound in `is_maybe_transmutable` error: aborting due to 5 previous errors error: aborting due to 7 previous errors Some errors have detailed explanations: E0080, E0277. For more information about an error, try `rustc --explain E0080`."} {"_id":"doc-en-rust-548a654e90aa716f14fa210a2f3f4de0017ce45745d96bd9b3b07ed72df8c284","title":"","text":" Subproject commit e6a6470d1eb4c88fee4b1ea98cd8e0ac4a181c16 Subproject commit c54cff0e6e4d1a0d0a2df7c1ce3d96cdd554763e "} {"_id":"doc-en-rust-f6894dfb333b945079fbde9712b0e392515b365490dd79c2d45e393ee2154bd6","title":"","text":"if let Some(candidate) = candidates.get(0) { let path = { // remove the possible common prefix of the path let start_index = (0..failed_segment_idx) .find(|&i| path[i].ident != candidate.path.segments[i].ident) let len = candidate.path.segments.len(); let start_index = (0..=failed_segment_idx.min(len - 1)) .find(|&i| path[i].ident.name != candidate.path.segments[i].ident.name) .unwrap_or_default(); let segments = (start_index..=failed_segment_idx) .map(|s| candidate.path.segments[s].clone()) .collect(); let segments = (start_index..len).map(|s| candidate.path.segments[s].clone()).collect(); Path { segments, span: Span::default(), tokens: None } }; ("} {"_id":"doc-en-rust-fc961517396f7b095aebab76959a22a0b34cbbbfec8a4881fadac8398b8e33f3","title":"","text":" error[E0583]: file not found for module `config` --> $DIR/suggest-import-ice-issue-127302.rs:3:1 | LL | mod config; | ^^^^^^^^^^^ | = help: to create the module `config`, create file \"$DIR/config.rs\" or \"$DIR/config/mod.rs\" = note: if there is a `mod config` elsewhere in the crate already, import it with `use crate::...` instead error: format argument must be a string literal --> $DIR/suggest-import-ice-issue-127302.rs:10:14 | LL | println!(args.ctx.compiler.display()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | help: you might be missing a string literal to format with | LL | println!(\"{}\", args.ctx.compiler.display()); | +++++ error[E0425]: cannot find value `args` in this scope --> $DIR/suggest-import-ice-issue-127302.rs:6:12 | LL | match &args.cmd { | ^^^^ not found in this scope | help: consider importing this function | LL + use std::env::args; | error[E0532]: expected unit struct, unit variant or constant, found module `crate::config` --> $DIR/suggest-import-ice-issue-127302.rs:7:9 | LL | crate::config => {} | ^^^^^^^^^^^^^ not a unit struct, unit variant or constant error: aborting due to 4 previous errors Some errors have detailed explanations: E0425, E0532, E0583. For more information about an error, try `rustc --explain E0425`. "} {"_id":"doc-en-rust-0f42c85fa48a39a2accfa34800aa846528fbe4a596ccac86fa0ca8f71c2731ee","title":"","text":" //@ revisions: edition2015 edition2021 mod config; //~ ERROR file not found for module fn main() { match &args.cmd { //~ ERROR cannot find value `args` in this scope crate::config => {} //~ ERROR expected unit struct, unit variant or constant, found module `crate::config` } println!(args.ctx.compiler.display()); //~^ ERROR format argument must be a string literal } "} {"_id":"doc-en-rust-e59a84118bc3be801c47d5595e22104f806c7bd20042e722a5b9a66ce4da6df6","title":"","text":" error[E0433]: failed to resolve: unresolved import --> $DIR/suggest-import-issue-120074.rs:12:35 | LL | println!(\"Hello, {}!\", crate::bar::do_the_thing); | ^^^ unresolved import | help: a similar path exists | LL | println!(\"Hello, {}!\", crate::foo::bar::do_the_thing); | ~~~~~~~~ help: consider importing this module | LL + use foo::bar; | help: if you import `bar`, refer to it directly | LL - println!(\"Hello, {}!\", crate::bar::do_the_thing); LL + println!(\"Hello, {}!\", bar::do_the_thing); | error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0433`. "} {"_id":"doc-en-rust-fd72ca144fe8c800ad07475aded9eaa00ee1be446a71079af2053fe538834a0c","title":"","text":" //@ revisions: edition2015 edition2021 pub mod foo { pub mod bar { pub fn do_the_thing() -> usize {"} {"_id":"doc-en-rust-4988953cd8e748cd5fdb46279284cec307a5b16c29b48514382cbde2e2c67f10","title":"","text":" error[E0433]: failed to resolve: unresolved import --> $DIR/suggest-import-issue-120074.rs:10:35 | LL | println!(\"Hello, {}!\", crate::bar::do_the_thing); | ^^^ unresolved import | help: a similar path exists | LL | println!(\"Hello, {}!\", crate::foo::bar::do_the_thing); | ~~~~~~~~ help: consider importing this module | LL + use foo::bar; | help: if you import `bar`, refer to it directly | LL - println!(\"Hello, {}!\", crate::bar::do_the_thing); LL + println!(\"Hello, {}!\", bar::do_the_thing); | error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0433`. "} {"_id":"doc-en-rust-baf02ef8ba73b038f865f4c9b85457654fdd48ca272ad2302de2bd5784581f5a","title":"","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":"doc-en-rust-df4373c2782bcc924202fa885b51dc980e0fea46448d7254a61d1435ca835dc3","title":"","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":"doc-en-rust-7d49cb0c1c28911544ef219b4dd6e3e21f6fcc4ce45880631ff8903bd807697f","title":"","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":"doc-en-rust-0d2558f6a742582c622a646607fbb198ef44d9a075f9f76b9ac44bbd9ac2621c","title":"","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":"doc-en-rust-a74ac354ae2d9b5f3dc63346db0c6ff4a68a42ad1ea35a23ca51f7141b1c63b2","title":"","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":"doc-en-rust-f57110111a32d0d828a7fe850a3896b3b9c78a94f656934e9ce7fc08a2b33290","title":"","text":"[[package]] name = \"compiler_builtins\" version = \"0.1.114\" version = \"0.1.117\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"eb58b199190fcfe0846f55a3b545cd6b07a34bdd5930a476ff856f3ebcc5558a\" checksum = \"a91dae36d82fe12621dfb5b596d7db766187747749b22e33ac068e1bfc356f4a\" dependencies = [ \"cc\", \"rustc-std-workspace-core\","} {"_id":"doc-en-rust-458097da950ec73b1580b21c6e2853992946e901d33970069de8e47ddd9f26b4","title":"","text":"[dependencies] core = { path = \"../core\" } compiler_builtins = { version = \"0.1.114\", features = ['rustc-dep-of-std'] } [target.'cfg(not(any(target_arch = \"aarch64\", target_arch = \"x86\", target_arch = \"x86_64\")))'.dependencies] compiler_builtins = { version = \"0.1.114\", features = [\"no-f16-f128\"] } compiler_builtins = { version = \"0.1.117\", features = ['rustc-dep-of-std'] } [dev-dependencies] rand = { version = \"0.8.5\", default-features = false, features = [\"alloc\"] }"} {"_id":"doc-en-rust-c70c61db5e9da4571b1e639badafd453f8a77b508d9c7f0a20bd5aa1cec20d8d","title":"","text":"panic_unwind = { path = \"../panic_unwind\", optional = true } panic_abort = { path = \"../panic_abort\" } core = { path = \"../core\", public = true } compiler_builtins = { version = \"0.1.114\" } compiler_builtins = { version = \"0.1.117\" } profiler_builtins = { path = \"../profiler_builtins\", optional = true } unwind = { path = \"../unwind\" } hashbrown = { version = \"0.14\", default-features = false, features = ["} {"_id":"doc-en-rust-30925a2040cc2376da29181f5233430d049c081e63b399364de491b2f90e3b4d","title":"","text":".suggestion = escape `box` to use it as an identifier parse_box_syntax_removed = `box_syntax` has been removed .suggestion = use `Box::new()` instead parse_box_syntax_removed_suggestion = use `Box::new()` instead parse_cannot_be_raw_ident = `{$ident}` cannot be a raw identifier"} {"_id":"doc-en-rust-5873305defdb0bca0c4cf5edf29084df8495dcd8ed3279a050e50663b27a1fa6","title":"","text":"#[derive(Diagnostic)] #[diag(parse_box_syntax_removed)] pub struct BoxSyntaxRemoved<'a> { pub struct BoxSyntaxRemoved { #[primary_span] #[suggestion( code = \"Box::new({code})\", applicability = \"machine-applicable\", style = \"verbose\" )] pub span: Span, pub code: &'a str, #[subdiagnostic] pub sugg: AddBoxNew, } #[derive(Subdiagnostic)] #[multipart_suggestion( parse_box_syntax_removed_suggestion, applicability = \"machine-applicable\", style = \"verbose\" )] pub struct AddBoxNew { #[suggestion_part(code = \"Box::new(\")] pub box_kw_and_lo: Span, #[suggestion_part(code = \")\")] pub hi: Span, } #[derive(Diagnostic)]"} {"_id":"doc-en-rust-69e8b500ffc074d6bb676e0fc27fdfc45725eaf5487ca26e7f30da5dfc40217b","title":"","text":"/// Parse `box expr` - this syntax has been removed, but we still parse this /// for now to provide a more useful error fn parse_expr_box(&mut self, box_kw: Span) -> PResult<'a, (Span, ExprKind)> { let (span, _) = self.parse_expr_prefix_common(box_kw)?; let inner_span = span.with_lo(box_kw.hi()); let code = self.psess.source_map().span_to_snippet(inner_span).unwrap(); let guar = self.dcx().emit_err(errors::BoxSyntaxRemoved { span: span, code: code.trim() }); let (span, expr) = self.parse_expr_prefix_common(box_kw)?; // Make a multipart suggestion instead of `span_to_snippet` in case source isn't available let box_kw_and_lo = box_kw.until(self.interpolated_or_expr_span(&expr)); let hi = span.shrink_to_hi(); let sugg = errors::AddBoxNew { box_kw_and_lo, hi }; let guar = self.dcx().emit_err(errors::BoxSyntaxRemoved { span, sugg }); Ok((span, ExprKind::Err(guar))) }"} {"_id":"doc-en-rust-062519635901a3f4652647d44e8e5424e7eeadaf830cdd0b89c0d964ad94aa17","title":"","text":"help: use `Box::new()` instead | LL | let _ = Box::new(()); | ~~~~~~~~~~~~ | ~~~~~~~~~ + error: `box_syntax` has been removed --> $DIR/removed-syntax-box.rs:10:13"} {"_id":"doc-en-rust-1904c19a9ef9d72bb6a9417d360c691c35d2db737cd8bc490768b6b23fd67557","title":"","text":"help: use `Box::new()` instead | LL | let _ = Box::new(1); | ~~~~~~~~~~~ | ~~~~~~~~~ + error: `box_syntax` has been removed --> $DIR/removed-syntax-box.rs:11:13"} {"_id":"doc-en-rust-023f1069594dec117476161d6d83bdc6280d0b96ce667b3667680e8a1262dbb2","title":"","text":"help: use `Box::new()` instead | LL | let _ = Box::new(T { a: 12, b: 18 }); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~ + error: `box_syntax` has been removed --> $DIR/removed-syntax-box.rs:12:13"} {"_id":"doc-en-rust-fbf9b291d9177451bfe859b047f180f6ab2648c166d72fb1a2105105de3f67c9","title":"","text":"help: use `Box::new()` instead | LL | let _ = Box::new([5; 30]); | ~~~~~~~~~~~~~~~~~ | ~~~~~~~~~ + error: `box_syntax` has been removed --> $DIR/removed-syntax-box.rs:13:22"} {"_id":"doc-en-rust-087e3807696973291fc92c6c20021805a6785f15f22b93773e4474760b570a20","title":"","text":"help: use `Box::new()` instead | LL | let _: Box<()> = Box::new(()); | ~~~~~~~~~~~~ | ~~~~~~~~~ + error: aborting due to 5 previous errors"} {"_id":"doc-en-rust-245db72a5708ada532305614d5645137322f9c97c2f507b80a88cda1d8ae0981","title":"","text":") -> Result<(), &'static str> { let tcx = self.tcx; if let Some(_) = callee_body.tainted_by_errors { return Err(\"Body is tainted\"); } let mut threshold = if self.caller_is_inline_forwarder { self.tcx.sess.opts.unstable_opts.inline_mir_forwarder_threshold.unwrap_or(30) } else if cross_crate_inlinable {"} {"_id":"doc-en-rust-8c3da7c3c359a1d69ddd42c31963a9dc6c1d69cf6922fff8f3aed720b705fb6d","title":"","text":" //@ compile-flags: -Zvalidate-mir -Zinline-mir=yes //@ known-bug: #122909 use std::sync::{Arc, Context, Weak}; pub struct WeakOnce(); impl WeakOnce { extern \"rust-call\" fn try_get(&self) -> Option> {} pub fn get(&self) -> Arc { self.try_get() .unwrap_or_else(|| panic!(\"Singleton {} not available\", std::any::type_name::())) } } "} {"_id":"doc-en-rust-bb0648102e73810d3ab62e4ce96c241e301f6dc73f05451fd239dc1fa28606f9","title":"","text":" //@ compile-flags: -Zvalidate-mir -Zinline-mir=yes #![feature(unboxed_closures)] use std::sync::Arc; pub struct WeakOnce(); //~^ ERROR type parameter `T` is never used impl WeakOnce { extern \"rust-call\" fn try_get(&self) -> Option> {} //~^ ERROR functions with the \"rust-call\" ABI must take a single non-self tuple argument //~| ERROR mismatched types pub fn get(&self) -> Arc { self.try_get() .unwrap_or_else(|| panic!(\"Singleton {} not available\", std::any::type_name::())) } } fn main() {} "} {"_id":"doc-en-rust-077feec693a18ac2299cf312f001ce3cb3a0674c5dec52e8ac23e5cbb01e8c4b","title":"","text":" error[E0392]: type parameter `T` is never used --> $DIR/inline-tainted-body.rs:7:21 | LL | pub struct WeakOnce(); | ^ unused type parameter | = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData` = help: if you intended `T` to be a const parameter, use `const T: /* Type */` instead error: functions with the \"rust-call\" ABI must take a single non-self tuple argument --> $DIR/inline-tainted-body.rs:11:35 | LL | extern \"rust-call\" fn try_get(&self) -> Option> {} | ^^^^^ error[E0308]: mismatched types --> $DIR/inline-tainted-body.rs:11:45 | LL | extern \"rust-call\" fn try_get(&self) -> Option> {} | ------- ^^^^^^^^^^^^^^ expected `Option>`, found `()` | | | implicitly returns `()` as its body has no tail or `return` expression | = note: expected enum `Option>` found unit type `()` error: aborting due to 3 previous errors Some errors have detailed explanations: E0308, E0392. For more information about an error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-8c50c876adfd43f9eb2521ad8b6295d8ba674e4180ebba07ca1b48e12c0ff4be","title":"","text":" warning-crlf.rs eol=crlf warning-crlf.rs -text "} {"_id":"doc-en-rust-d7e7843b75e4d048bc140a8fc94e037675fe83706daf54565e7ebfd3939a7fbe","title":"","text":" // ignore-tidy-cr //@ check-pass // This file checks the spans of intra-link warnings in a file with CRLF line endings. The // .gitattributes file in this directory should enforce it. /// [error] pub struct A; //~^^ WARNING `error` /// /// docs [error1] //~^ WARNING `error1` /// docs [error2] /// pub struct B; //~^^^ WARNING `error2` /** * This is a multi-line comment. * * It also has an [error]. */ pub struct C; //~^^^ WARNING `error` // ignore-tidy-cr //@ check-pass // This file checks the spans of intra-link warnings in a file with CRLF line endings. The // .gitattributes file in this directory should enforce it. /// [error] pub struct A; //~^^ WARNING `error` /// /// docs [error1] //~^ WARNING `error1` /// docs [error2] /// pub struct B; //~^^^ WARNING `error2` /** * This is a multi-line comment. * * It also has an [error]. */ pub struct C; //~^^^ WARNING `error` "} {"_id":"doc-en-rust-79ac2a0e7feca41f379a7833c222d002af7bccdd0eb0d53629d4919eff2a56b9","title":"","text":"use rustc_middle::{bug, span_bug}; use rustc_session::Session; use rustc_span::symbol::{kw, Ident}; use rustc_span::{sym, BytePos, Span, DUMMY_SP}; use rustc_span::{sym, Span, DUMMY_SP}; use rustc_trait_selection::error_reporting::infer::{FailureCode, ObligationCauseExt}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{self, ObligationCauseCode, SelectionContext};"} {"_id":"doc-en-rust-a24a8f4960d88faae665e62615544cd0bbe19b60bc35128dcdae8f8f5e63d418","title":"","text":".get(arg_idx + 1) .map(|&(_, sp)| sp) .unwrap_or_else(|| { // Subtract one to move before `)` call_expr.span.with_lo(call_expr.span.hi() - BytePos(1)) // Try to move before `)`. Note that `)` here is not necessarily // the latin right paren, it could be a Unicode-confusable that // looks like a `)`, so we must not use `- BytePos(1)` // manipulations here. self.tcx().sess.source_map().end_point(call_expr.span) }); // Include next comma"} {"_id":"doc-en-rust-91a8bb2653054e26559f482fc56ae51c7829f1784bc83a4d550c88deadc21b74","title":"","text":" //! Previously, we tried to remove extra arg commas when providing extra arg removal suggestions. //! One of the edge cases is having to account for an arg that has a closing delimiter `)` //! following it. However, the previous suggestion code assumed that the delimiter is in fact //! exactly the 1-byte `)` character. This assumption was proven incorrect, because we recover //! from Unicode-confusable delimiters in the parser, which means that the ending delimiter could be //! a multi-byte codepoint that looks *like* a `)`. Subtracing 1 byte could land us in the middle of //! a codepoint, triggering a codepoint boundary assertion. //! //! issue: rust-lang/rust#128717 fn main() { // The following example has been modified from #128717 to remove irrelevant Unicode as they do // not otherwise partake in the right delimiter calculation causing the codepoint boundary // assertion. main(rahh); //~^ ERROR unknown start of token //~| ERROR this function takes 0 arguments but 1 argument was supplied //~| ERROR cannot find value `rahh` in this scope } "} {"_id":"doc-en-rust-e2e155e03f7613865326bb49af0e062068594903a98cac8bb80e8202f110dc5c","title":"","text":" error: unknown start of token: u{ff09} --> $DIR/suggest-arg-comma-delete-ice.rs:15:14 | LL | main(rahh); | ^^ | help: Unicode character ')' (Fullwidth Right Parenthesis) looks like ')' (Right Parenthesis), but it is not | LL | main(rahh); | ~ error[E0425]: cannot find value `rahh` in this scope --> $DIR/suggest-arg-comma-delete-ice.rs:15:10 | LL | main(rahh); | ^^^^ not found in this scope error[E0061]: this function takes 0 arguments but 1 argument was supplied --> $DIR/suggest-arg-comma-delete-ice.rs:15:5 | LL | main(rahh); | ^^^^ ---- unexpected argument | note: function defined here --> $DIR/suggest-arg-comma-delete-ice.rs:11:4 | LL | fn main() { | ^^^^ help: remove the extra argument | LL - main(rahh); LL + main(); | error: aborting due to 3 previous errors Some errors have detailed explanations: E0061, E0425. For more information about an error, try `rustc --explain E0061`. "} {"_id":"doc-en-rust-b4b136ef9ccc449d539e4a7da53b68f67657ea77d3215020c7db03755b716c04","title":"","text":"fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option>> { let eq_consumed = match self.token.kind { token::BinOpEq(..) => { // Recover `let x = 1` as `let x = 1` // Recover `let x = 1` as `let x = 1` We must not use `+ BytePos(1)` here // because `` can be a multi-byte lookalike that was recovered, e.g. `➖=` (the // `➖` is a U+2796 Heavy Minus Sign Unicode Character) that was recovered as a // `-=`. let extra_op_span = self.psess.source_map().start_point(self.token.span); self.dcx().emit_err(errors::CompoundAssignmentExpressionInLet { span: self.token.span, suggestion: self.token.span.with_hi(self.token.span.lo() + BytePos(1)), suggestion: extra_op_span, }); self.bump(); true"} {"_id":"doc-en-rust-54509f0b5e9dccc4badee72dc27dd1e78cc8286d45c93dddc8484099ecd7b7f0","title":"","text":" //! Previously we would try to issue a suggestion for `let x = 1`, i.e. a compound assignment //! within a `let` binding, to remove the ``. The suggestion code unfortunately incorrectly //! assumed that the `` is an exactly-1-byte ASCII character, but this assumption is incorrect //! because we also recover Unicode-confusables like `➖=` as `-=`. In this example, the suggestion //! code used a `+ BytePos(1)` to calculate the span of the `` codepoint that looks like `-` but //! the mult-byte Unicode look-alike would cause the suggested removal span to be inside a //! multi-byte codepoint boundary, triggering a codepoint boundary assertion. //! //! issue: rust-lang/rust#128845 fn main() { // Adapted from #128845 but with irrelevant components removed and simplified. let x ➖= 1; //~^ ERROR unknown start of token: u{2796} //~| ERROR: can't reassign to an uninitialized variable } "} {"_id":"doc-en-rust-bafa3136766065545b214f9578a233d7ba0db2ecc8884eb4fd934f9b5aabed65","title":"","text":" error: unknown start of token: u{2796} --> $DIR/suggest-remove-compount-assign-let-ice.rs:13:11 | LL | let x ➖= 1; | ^^ | help: Unicode character '➖' (Heavy Minus Sign) looks like '-' (Minus/Hyphen), but it is not | LL | let x -= 1; | ~ error: can't reassign to an uninitialized variable --> $DIR/suggest-remove-compount-assign-let-ice.rs:13:11 | LL | let x ➖= 1; | ^^^ | = help: if you meant to overwrite, remove the `let` binding help: initialize the variable | LL - let x ➖= 1; LL + let x = 1; | error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-f4b1df7e34f634ebc57f6ecee6040df169bc3d59d2311e9a07cb0c36231556da","title":"","text":"// gdb-command:run // gdb-command:print some // gdb-check:$1 = core::option::Option<&u32>::Some(0x12345678) // gdb-check:$1 = core::option::Option<&u32>::Some(0x[...]) // gdb-command:print none // gdb-check:$2 = core::option::Option<&u32>::None // gdb-command:print full // gdb-check:$3 = option_like_enum::MoreFields::Full(454545, 0x87654321, 9988) // gdb-check:$3 = option_like_enum::MoreFields::Full(454545, 0x[...], 9988) // gdb-command:print empty_gdb.discr // gdb-check:$4 = (*mut isize) 0x1 // gdb-command:print empty // gdb-check:$4 = option_like_enum::MoreFields::Empty // gdb-command:print droid // gdb-check:$5 = option_like_enum::NamedFields::Droid{id: 675675, range: 10000001, internals: 0x43218765} // gdb-check:$5 = option_like_enum::NamedFields::Droid{id: 675675, range: 10000001, internals: 0x[...]} // gdb-command:print void_droid_gdb.internals // gdb-check:$6 = (*mut isize) 0x1 // gdb-command:print void_droid // gdb-check:$6 = option_like_enum::NamedFields::Void // gdb-command:print nested_non_zero_yep // gdb-check:$7 = option_like_enum::NestedNonZero::Yep(10.5, option_like_enum::NestedNonZeroField {a: 10, b: 20, c: 0x[...]})"} {"_id":"doc-en-rust-bcf83209188efe26dcaf20747d61bbcf6a4b4fd795bc3670bb11aa046a664025","title":"","text":"// lldb-command:run // lldb-command:v some // lldb-check:[...] Some(&0x12345678) // lldb-check:[...] Some(&0x[...]) // lldb-command:v none // lldb-check:[...] None // lldb-command:v full // lldb-check:[...] Full(454545, &0x87654321, 9988) // lldb-check:[...] Full(454545, &0x[...], 9988) // lldb-command:v empty // lldb-check:[...] Empty // lldb-command:v droid // lldb-check:[...] Droid { id: 675675, range: 10000001, internals: &0x43218765 } // lldb-check:[...] Droid { id: 675675, range: 10000001, internals: &0x[...] } // lldb-command:v void_droid // lldb-check:[...] Void"} {"_id":"doc-en-rust-bf78fe5941322e3a4c0ec2b59e305da09ae32064b02dd98e7e651aeccb376ca9","title":"","text":"// contains a non-nullable pointer, then this value is used as the discriminator. // The test cases in this file make sure that something readable is generated for // this kind of types. // If the non-empty variant contains a single non-nullable pointer than the whole // item is represented as just a pointer and not wrapped in a struct. // Unfortunately (for these test cases) the content of the non-discriminant fields // in the null-case is not defined. So we just read the discriminator field in // this case (by casting the value to a memory-equivalent struct). enum MoreFields<'a> { Full(u32, &'a isize, i16),"} {"_id":"doc-en-rust-0d9e139c914e842b3849662f3f05374ffe40a1270cf839564f00c2d0fb6bf3c4","title":"","text":"let some_str: Option<&'static str> = Some(\"abc\"); let none_str: Option<&'static str> = None; let some: Option<&u32> = Some(unsafe { std::mem::transmute(0x12345678_usize) }); let some: Option<&u32> = Some(&1234); let none: Option<&u32> = None; let full = MoreFields::Full(454545, unsafe { std::mem::transmute(0x87654321_usize) }, 9988); let full = MoreFields::Full(454545, &1234, 9988); let empty = MoreFields::Empty; let empty_gdb: &MoreFieldsRepr = unsafe { std::mem::transmute(&MoreFields::Empty) }; let droid = NamedFields::Droid { id: 675675, range: 10000001, internals: unsafe { std::mem::transmute(0x43218765_usize) } internals: &1234, }; let void_droid = NamedFields::Void; let void_droid_gdb: &NamedFieldsRepr = unsafe { std::mem::transmute(&NamedFields::Void) }; let x = 'x'; let nested_non_zero_yep = NestedNonZero::Yep( 10.5, NestedNonZeroField { a: 10, b: 20, c: &x c: &'x', }); let nested_non_zero_nope = NestedNonZero::Nope; zzz(); // #break"} {"_id":"doc-en-rust-e3940459d46698a98722a35a2811b44b0d6ab4ab9ffc87127c602aa1ea41e6a8","title":"","text":".find_ancestor_inside(value.span) .map(|span| (value.span.with_hi(span.lo()), value.span.with_lo(span.hi()))), ast::ExprKind::Paren(ref expr) => { expr.span.find_ancestor_inside(value.span).map(|expr_span| { // For the expr with attributes, like `let _ = (#[inline] || println!(\"Hello!\"));`, // the span should contains the attributes, or the suggestion will remove them. let expr_span_with_attrs = if let Some(attr_lo) = expr.attrs.iter().map(|attr| attr.span.lo()).min() { expr.span.with_lo(attr_lo) } else { expr.span }; expr_span_with_attrs.find_ancestor_inside(value.span).map(|expr_span| { (value.span.with_hi(expr_span.lo()), value.span.with_lo(expr_span.hi())) }) }"} {"_id":"doc-en-rust-e8b9d947ea467c4b7cea20c57858749609feacf11cbd795063e24518f891ecbb","title":"","text":" //@ run-rustfix // Check the `unused_parens` suggestion for paren_expr with attributes. // The suggestion should retain attributes in the front. #![feature(stmt_expr_attributes)] #![deny(unused_parens)] pub fn foo() -> impl Fn() { let _ = #[inline] #[allow(dead_code)] || println!(\"Hello!\"); //~ERROR unnecessary parentheses #[inline] #[allow(dead_code)] || println!(\"Hello!\") //~ERROR unnecessary parentheses } fn main() { let _ = foo(); } "} {"_id":"doc-en-rust-40270ec2a030828a0f18fc0ca5c6822e18741ec5304d9b51ba1599fdb53445b8","title":"","text":" //@ run-rustfix // Check the `unused_parens` suggestion for paren_expr with attributes. // The suggestion should retain attributes in the front. #![feature(stmt_expr_attributes)] #![deny(unused_parens)] pub fn foo() -> impl Fn() { let _ = (#[inline] #[allow(dead_code)] || println!(\"Hello!\")); //~ERROR unnecessary parentheses (#[inline] #[allow(dead_code)] || println!(\"Hello!\")) //~ERROR unnecessary parentheses } fn main() { let _ = foo(); } "} {"_id":"doc-en-rust-4c122bb795acc9799fbd60f297daf4d75b3d2e27040da47f00c12d5944bbecd0","title":"","text":" error: unnecessary parentheses around assigned value --> $DIR/unused-parens-for-stmt-expr-attributes-issue-129833.rs:9:13 | LL | let _ = (#[inline] #[allow(dead_code)] || println!(\"Hello!\")); | ^ ^ | note: the lint level is defined here --> $DIR/unused-parens-for-stmt-expr-attributes-issue-129833.rs:6:9 | LL | #![deny(unused_parens)] | ^^^^^^^^^^^^^ help: remove these parentheses | LL - let _ = (#[inline] #[allow(dead_code)] || println!(\"Hello!\")); LL + let _ = #[inline] #[allow(dead_code)] || println!(\"Hello!\"); | error: unnecessary parentheses around block return value --> $DIR/unused-parens-for-stmt-expr-attributes-issue-129833.rs:10:5 | LL | (#[inline] #[allow(dead_code)] || println!(\"Hello!\")) | ^ ^ | help: remove these parentheses | LL - (#[inline] #[allow(dead_code)] || println!(\"Hello!\")) LL + #[inline] #[allow(dead_code)] || println!(\"Hello!\") | error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-858956bfbeacc4a26c50bcf4452304c01e84baadaa75e070afdc168fcca7090c","title":"","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":"doc-en-rust-fdfa0a2b1e8f8e643bc3dd02f5d2b6f69c688e5ac70cff030385df7d6e1f04bd","title":"","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":"doc-en-rust-6babb0d0458590ab53c58fd74e911bee9a2d240b25203804e6285c1721bbc88f","title":"","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":"doc-en-rust-b560d2a6b66c4b08d42de194f83256b862772ebca3f1c0ddcbcc3df5d1e8088a","title":"","text":") -> R { I::with_global_cache(self, mode, f) } fn evaluation_is_concurrent(&self) -> bool { self.evaluation_is_concurrent() } }"} {"_id":"doc-en-rust-daf6722297d4343b172991838f6beadb56f20b79778d64dc97c14027653b8188","title":"","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":"doc-en-rust-e130161d89f75a00854c1ea9508032bb0dfda3d3a9e84f5a47a831a8ffa2da7e","title":"","text":"mode: SolverMode, f: impl FnOnce(&mut GlobalCache) -> R, ) -> R; fn evaluation_is_concurrent(&self) -> bool; } pub trait Delegate {"} {"_id":"doc-en-rust-21042bba8124db1f43b36d8bc447dafa576de846de5d9c995628d76fe4d3634b","title":"","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":"doc-en-rust-496d056cfae95062ed5ba639706d3252d31abc888706828a3c2254344cc4d447","title":"","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":"doc-en-rust-c06310be93043158632822254ac7def4489cba1042635e23fa1686770fd84153","title":"","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":"doc-en-rust-bfc1eabfac7834a3e820eced388b8602562a46673f8aee8c6701f0f9a76589c5","title":"","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":"doc-en-rust-1dbb75c1a7a05e588bd321a5a3aa81d5201d64f51e69e9fdee68c24fcead2f51","title":"","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":"doc-en-rust-1095c86314a09036287669a20080bc8a574823c01c9e364c4848fc94b1c106c7","title":"","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":"doc-en-rust-6dd5ca973f3aaa9fa3c0cc4f59386cd990f3525a0e029376e9223ef5ddd3923f","title":"","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":"doc-en-rust-70650facd78c1e6390bab57b8c75f2bc365c8c58abfdbf638bb4b8df02a564e3","title":"","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":"doc-en-rust-5b5bd393c9584aea250df7b8f1fcf9a7ee6b5f975196c68d1aea729c0694d3f4","title":"","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":"doc-en-rust-ba73f1c6cde8b8d73ef34d4941f73826bff52342a2c91b54fb0fa1ad04b099c7","title":"","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":"doc-en-rust-ce476fea9e1b5201cc7e672a5bd3dbd244b81ebbf04b259dbd82190d9ca05f81","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Foo { fn bar(&mut self, other: &mut Foo); } struct Baz; impl Foo for Baz { fn bar(&mut self, other: &Foo) {} //~^ ERROR method `bar` has an incompatible type for trait: values differ in mutability [E0053] } fn main() {} "} {"_id":"doc-en-rust-cb6d5a935649bbd754bfa189aacfa66f7b39a0e06034fa5dee13461cc96b69b9","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(overloaded_calls)] use std::{fmt, ops}; struct Shower { x: T } impl ops::Fn<(), ()> for Shower { fn call(&self, _args: ()) { //~^ ERROR `call` has an incompatible type for trait: expected \"rust-call\" fn but found \"Rust\" fn println!(\"{}\", self.x); } } fn make_shower(x: T) -> Shower { Shower { x: x } } pub fn main() { let show3 = make_shower(3i); show3(); } "} {"_id":"doc-en-rust-1d0614006af5408906bbd9599bc43a6d02cbc1709f55d3645a95a9eab552018c","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum Foo { A = 1i64, //~^ ERROR mismatched types: expected `int` but found `i64` B = 2u8 //~^ ERROR mismatched types: expected `int` but found `u8` } fn main() {} "} {"_id":"doc-en-rust-ce11e8c5b3f9367ba0a00118503b636f9634a58d31db41d59d2d05688efc82e1","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { if true { return } match () { () => { static MAGIC: uint = 0; } } } "} {"_id":"doc-en-rust-ba3fd74697ec461b1b165df6ed3e2972d15d35e42e039ebcb8399214636b1c32","title":"","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":"doc-en-rust-dfb26e0c8f1f756a927307678888fe4ab54c89ac492fa8aecc13579a95f54671","title":"","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":"doc-en-rust-2ef5b5e2eb60692e1eab8ad0a38d69421c14112e6faef323a92f5fed30ddeff0","title":"","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":"doc-en-rust-8b35b59110368adb05880f53682f667dce5c05bad77fb02e2f4e102240e92e0c","title":"","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":"doc-en-rust-f7b7174b3675e3ed26cccc2d1f6f5eb8ea393dd9ff97d0ebf251b36d6d85f8de","title":"","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":"doc-en-rust-86264f9e4b502fab1543482369acc0031b682e47f18fdd742b10f50fa4375b1d","title":"","text":"cmd.args(lint_flags.split_whitespace()); } // Conditionally pass `-Zon-broken-pipe=kill` to underlying rustc. Not all binaries want // `-Zon-broken-pipe=kill`, which includes cargo itself. if env::var_os(\"FORCE_ON_BROKEN_PIPE_KILL\").is_some() { cmd.arg(\"-Z\").arg(\"on-broken-pipe=kill\"); } if target.is_some() { // The stage0 compiler has a special sysroot distinct from what we // actually downloaded, so we just always pass the `--sysroot` option,"} {"_id":"doc-en-rust-1f1df2202cf7e9ff68b78cc8a9869fa2bf819f41fb8e9cbbc7af8167a5275e61","title":"","text":"cargo.rustdocflag(\"-Zcrate-attr=warn(rust_2018_idioms)\"); // If the rustc output is piped to e.g. `head -n1` we want the process to be // killed, rather than having an error bubble up and cause a panic. // If the rustc output is piped to e.g. `head -n1` we want the process to be killed, rather than // having an error bubble up and cause a panic. // // FIXME(jieyouxu): this flag is load-bearing for rustc to not ICE on broken pipes, because // rustc internally sometimes uses std `println!` -- but std `println!` by default will panic on // broken pipes, and uncaught panics will manifest as an ICE. The compiler *should* handle this // properly, but this flag is set in the meantime to paper over the I/O errors. // // See for details. // // Also see the discussion for properly handling I/O errors related to broken pipes, i.e. safe // variants of `println!` in // . cargo.rustflag(\"-Zon-broken-pipe=kill\"); if builder.config.llvm_enzyme {"} {"_id":"doc-en-rust-9bc4226dedf6b9c8a82341a57d8b92dc3794be45353edbf8e0ee4d7045c68009","title":"","text":"// See https://github.com/rust-lang/rust/issues/116538 cargo.rustflag(\"-Zunstable-options\"); // `-Zon-broken-pipe=kill` breaks cargo tests // NOTE: The root cause of needing `-Zon-broken-pipe=kill` in the first place is because `rustc` // and `rustdoc` doesn't gracefully handle I/O errors due to usages of raw std `println!` macros // which panics upon encountering broken pipes. `-Zon-broken-pipe=kill` just papers over that // and stops rustc/rustdoc ICEing on e.g. `rustc --print=sysroot | false`. // // cargo explicitly does not want the `-Zon-broken-pipe=kill` paper because it does actually use // variants of `println!` that handles I/O errors gracefully. It's also a breaking change for a // spawn process not written in Rust, especially if the language default handler is not // `SIG_IGN`. Thankfully cargo tests will break if we do set the flag. // // For the cargo discussion, see // . // // For the rustc discussion, see // // for proper solutions. if !path.ends_with(\"cargo\") { // If the output is piped to e.g. `head -n1` we want the process to be killed, // rather than having an error bubble up and cause a panic. cargo.rustflag(\"-Zon-broken-pipe=kill\"); // Use an untracked env var `FORCE_ON_BROKEN_PIPE_KILL` here instead of `RUSTFLAGS`. // `RUSTFLAGS` is tracked by cargo. Conditionally omitting `-Zon-broken-pipe=kill` from // `RUSTFLAGS` causes unnecessary tool rebuilds due to cache invalidation from building e.g. // cargo *without* `-Zon-broken-pipe=kill` but then rustdoc *with* `-Zon-broken-pipe=kill`. cargo.env(\"FORCE_ON_BROKEN_PIPE_KILL\", \"-Zon-broken-pipe=kill\"); } cargo"} {"_id":"doc-en-rust-14a5c03afb92eacdf9efd6134b60afcf65fcf37007ba87e02c7de965491470b3","title":"","text":" //! Check that `rustc` and `rustdoc` does not ICE upon encountering a broken pipe due to unhandled //! panics from raw std `println!` usages. //! //! Regression test for . //@ ignore-cross-compile (needs to run test binary) #![feature(anonymous_pipe)] use std::io::Read; use std::process::{Command, Stdio}; use run_make_support::env_var; #[derive(Debug, PartialEq)] enum Binary { Rustc, Rustdoc, } fn check_broken_pipe_handled_gracefully(bin: Binary, mut cmd: Command) { let (reader, writer) = std::pipe::pipe().unwrap(); drop(reader); // close read-end cmd.stdout(writer).stderr(Stdio::piped()); let mut child = cmd.spawn().unwrap(); let mut stderr = String::new(); child.stderr.as_mut().unwrap().read_to_string(&mut stderr).unwrap(); let status = child.wait().unwrap(); assert!(!status.success(), \"{bin:?} unexpectedly succeeded\"); const PANIC_ICE_EXIT_CODE: i32 = 101; #[cfg(not(windows))] { // On non-Windows, rustc/rustdoc built with `-Zon-broken-pipe=kill` shouldn't have an exit // code of 101 because it should have an wait status that corresponds to SIGPIPE signal // number. assert_ne!(status.code(), Some(PANIC_ICE_EXIT_CODE), \"{bin:?}\"); // And the stderr should be empty because rustc/rustdoc should've gotten killed. assert!(stderr.is_empty(), \"{bin:?} stderr:n{}\", stderr); } #[cfg(windows)] { match bin { // On Windows, rustc has a paper that propagates the panic exit code of 101 but converts // broken pipe errors into fatal errors instead of ICEs. Binary::Rustc => { assert_eq!(status.code(), Some(PANIC_ICE_EXIT_CODE), \"{bin:?}\"); // But make sure it doesn't manifest as an ICE. assert!(!stderr.contains(\"internal compiler error\"), \"{bin:?} ICE'd\"); } // On Windows, rustdoc seems to cleanly exit with exit code of 1. Binary::Rustdoc => { assert_eq!(status.code(), Some(1), \"{bin:?}\"); assert!(!stderr.contains(\"panic\"), \"{bin:?} stderr contains panic\"); } } } } fn main() { let mut rustc = Command::new(env_var(\"RUSTC\")); rustc.arg(\"--print=sysroot\"); check_broken_pipe_handled_gracefully(Binary::Rustc, rustc); let mut rustdoc = Command::new(env_var(\"RUSTDOC\")); rustdoc.arg(\"--version\"); check_broken_pipe_handled_gracefully(Binary::Rustdoc, rustdoc); } "} {"_id":"doc-en-rust-aa0565575c3e09821a90b0f886d35ac6d302b288a02af5c027526c9267158d1c","title":"","text":"if !verify_rustfmt_version(build) { return Ok(None); } get_git_modified_files(&build.config.git_config(), Some(&build.config.src), &[\"rs\"]) }"} {"_id":"doc-en-rust-805a301a99d8856df1ccad3e5fe982204acc9fb7939a0369052fd6c8aa7a65ee","title":"","text":"use std::path::PathBuf; use std::{env, fs}; use build_helper::git::warn_old_master_branch; use crate::Build; #[cfg(not(feature = \"bootstrap-self-test\"))] use crate::builder::Builder;"} {"_id":"doc-en-rust-7bec0cf1c2a0c0c784e1822de03ed9fdeef886e368f9afadd11fa2e2ae43668e","title":"","text":"if let Some(ref s) = build.config.ccache { cmd_finder.must_have(s); } warn_old_master_branch(&build.config.git_config(), &build.config.src); }"} {"_id":"doc-en-rust-7a884f9b37a698604f9eee69d853d2595d6ce4e7fb0cc6ae553bcdd6de3b2b5e","title":"","text":".collect(); Ok(Some(files)) } /// Print a warning if the branch returned from `updated_master_branch` is old /// /// For certain configurations of git repository, this remote will not be /// updated when running `git pull`. /// /// This can result in formatting thousands of files instead of a dozen, /// so we should warn the user something is wrong. pub fn warn_old_master_branch(config: &GitConfig<'_>, git_dir: &Path) { if crate::ci::CiEnv::is_ci() { // this warning is useless in CI, // and CI probably won't have the right branches anyway. return; } // this will be overwritten by the actual name, if possible let mut updated_master = \"the upstream master branch\".to_string(); match warn_old_master_branch_(config, git_dir, &mut updated_master) { Ok(branch_is_old) => { if !branch_is_old { return; } // otherwise fall through and print the rest of the warning } Err(err) => { eprintln!(\"warning: unable to check if {updated_master} is old due to error: {err}\") } } eprintln!( \"warning: {updated_master} is used to determine if files have been modifiedn warning: if it is not updated, this may cause files to be needlessly reformatted\" ); } pub fn warn_old_master_branch_( config: &GitConfig<'_>, git_dir: &Path, updated_master: &mut String, ) -> Result> { use std::time::Duration; *updated_master = updated_master_branch(config, Some(git_dir))?; let branch_path = git_dir.join(\".git/refs/remotes\").join(&updated_master); const WARN_AFTER: Duration = Duration::from_secs(60 * 60 * 24 * 10); let meta = match std::fs::metadata(&branch_path) { Ok(meta) => meta, Err(err) => { let gcd = git_common_dir(&git_dir)?; if branch_path.starts_with(&gcd) { return Err(Box::new(err)); } std::fs::metadata(Path::new(&gcd).join(\"refs/remotes\").join(&updated_master))? } }; if meta.modified()?.elapsed()? > WARN_AFTER { eprintln!(\"warning: {updated_master} has not been updated in 10 days\"); Ok(true) } else { Ok(false) } } fn git_common_dir(dir: &Path) -> Result { output_result(Command::new(\"git\").arg(\"-C\").arg(dir).arg(\"rev-parse\").arg(\"--git-common-dir\")) .map(|x| x.trim().to_string()) } "} {"_id":"doc-en-rust-a5ba39b7bcf27c282d841d940fcb3e140f6de1687e3700749e0a3f5ed56524e0","title":"","text":"}, Primitive::F32 => types::F32, Primitive::F64 => types::F64, Primitive::Pointer => pointer_ty(tcx), // FIXME(erikdesjardins): handle non-default addrspace ptr sizes Primitive::Pointer(_) => pointer_ty(tcx), } }"} {"_id":"doc-en-rust-5aae347605bb4660140896e7509a3d620ae7490dc4ab5527751813c1d58b58a0","title":"","text":"pub(crate) use cpuid::codegen_cpuid_call; pub(crate) use llvm::codegen_llvm_intrinsic_call; use rustc_middle::ty::layout::HasParamEnv; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::subst::SubstsRef; use rustc_span::symbol::{kw, sym, Symbol};"} {"_id":"doc-en-rust-528d627c63f00b8fcaddc0425a6cc6641358718e683d5ec9eca2f3441a3ab4e8","title":"","text":"return; } if intrinsic == sym::assert_zero_valid && !fx.tcx.permits_zero_init(layout) { if intrinsic == sym::assert_zero_valid && !fx.tcx.permits_zero_init(fx.param_env().and(layout)) { with_no_trimmed_paths!({ crate::base::codegen_panic( fx,"} {"_id":"doc-en-rust-1bce2b20d247fab559d4607d9cf57493df300b13b0bc5b81ccd0b4208efe195e","title":"","text":"} if intrinsic == sym::assert_mem_uninitialized_valid && !fx.tcx.permits_uninit_init(layout) && !fx.tcx.permits_uninit_init(fx.param_env().and(layout)) { with_no_trimmed_paths!({ crate::base::codegen_panic("} {"_id":"doc-en-rust-8659227658fbfb5aa409e123898d07bb1956bfea9c6d555bca9f36a6e51bcaa6","title":"","text":"is_main_fn: bool, sigpipe: u8, ) { let main_ret_ty = tcx.fn_sig(rust_main_def_id).output(); let main_ret_ty = tcx.bound_fn_sig(rust_main_def_id).subst_identity().output(); // Given that `main()` has no arguments, // then its return type cannot have // late-bound regions, since late-bound"} {"_id":"doc-en-rust-8a8d324a17b540a90c83e611e7ba00643e6b0d5c28b061e8598443ce13d6eba1","title":"","text":"let _ = write!(&mut w, \"{}\", args); let msg = str::from_utf8(&w.buf[0..w.pos]).unwrap_or(\"aborted\"); let msg = if msg.is_empty() {\"aborted\"} else {msg}; // Give some context to the message let hash = msg.bytes().fold(0, |accum, val| accum + (val as uint) ); let quote = match hash % 10 { 0 => \" It was from the artists and poets that the pertinent answers came, and I know that panic would have broken loose had they been able to compare notes. As it was, lacking their original letters, I half suspected the compiler of having asked leading questions, or of having edited the correspondence in corroboration of what he had latently resolved to see.\", 1 => \" There are not many persons who know what wonders are opened to them in the stories and visions of their youth; for when as children we listen and dream, we think but half-formed thoughts, and when as men we try to remember, we are dulled and prosaic with the poison of life. But some of us awake in the night with strange phantasms of enchanted hills and gardens, of fountains that sing in the sun, of golden cliffs overhanging murmuring seas, of plains that stretch down to sleeping cities of bronze and stone, and of shadowy companies of heroes that ride caparisoned white horses along the edges of thick forests; and then we know that we have looked back through the ivory gates into that world of wonder which was ours before we were wise and unhappy.\", 2 => \" Instead of the poems I had hoped for, there came only a shuddering blackness and ineffable loneliness; and I saw at last a fearful truth which no one had ever dared to breathe before — the unwhisperable secret of secrets — The fact that this city of stone and stridor is not a sentient perpetuation of Old New York as London is of Old London and Paris of Old Paris, but that it is in fact quite dead, its sprawling body imperfectly embalmed and infested with queer animate things which have nothing to do with it as it was in life.\", 3 => \" The ocean ate the last of the land and poured into the smoking gulf, thereby giving up all it had ever conquered. From the new-flooded lands it flowed again, uncovering death and decay; and from its ancient and immemorial bed it trickled loathsomely, uncovering nighted secrets of the years when Time was young and the gods unborn. Above the waves rose weedy remembered spires. The moon laid pale lilies of light on dead London, and Paris stood up from its damp grave to be sanctified with star-dust. Then rose spires and monoliths that were weedy but not remembered; terrible spires and monoliths of lands that men never knew were lands...\", 4 => \" There was a night when winds from unknown spaces whirled us irresistibly into limitless vacuum beyond all thought and entity. Perceptions of the most maddeningly untransmissible sort thronged upon us; perceptions of infinity which at the time convulsed us with joy, yet which are now partly lost to my memory and partly incapable of presentation to others.\", _ => \"You've met with a terrible fate, haven't you?\" }; rterrln!(\"{}\", \"\"); rterrln!(\"{}\", quote); rterrln!(\"{}\", \"\"); rterrln!(\"fatal runtime error: {}\", msg); unsafe { intrinsics::abort(); } }"} {"_id":"doc-en-rust-8edeae1330276a8770077e003ad1cbba64a554bbc70d490031becfe19c09fbc5","title":"","text":"\"libstd/sync/spsc_queue.rs\", # BSD \"libstd/sync/mpmc_bounded_queue.rs\", # BSD \"libsync/mpsc_intrusive.rs\", # BSD \"test/bench/shootout-binarytrees.rs\", # BSD \"test/bench/shootout-fannkuch-redux.rs\", # BSD \"test/bench/shootout-meteor.rs\", # BSD \"test/bench/shootout-regex-dna.rs\", # BSD"} {"_id":"doc-en-rust-ee0db9f6886de7a6b863a18f98de10abd6e39a9f794c5d6478793c9ca7fa21a7","title":"","text":" // Copyright 2012-2013 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) 2012-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. extern crate sync; extern crate arena;"} {"_id":"doc-en-rust-f30a4a313f877b3bbcc8c6bf08f0e468ccaa46514db69c115a3d06715268e1fc","title":"","text":"rustup toolchain install --profile minimal nightly-${TOOLCHAIN} # Sanity check to see if the nightly exists echo nightly-${TOOLCHAIN} > rust-toolchain echo \"=> Uninstalling all old nighlies\" echo \"=> Uninstalling all old nightlies\" for nightly in $(rustup toolchain list | grep nightly | grep -v $TOOLCHAIN | grep -v nightly-x86_64); do rustup toolchain uninstall $nightly done"} {"_id":"doc-en-rust-0de57ad815da55c60f29375af01abc3adcabb776ac8c583d7f2953eaa398b8f2","title":"","text":"} } (&ty::ty_param(ref a_p), &ty::ty_param(ref b_p)) if a_p.idx == b_p.idx => { (&ty::ty_param(ref a_p), &ty::ty_param(ref b_p)) if a_p.idx == b_p.idx && a_p.space == b_p.space => { Ok(a) }"} {"_id":"doc-en-rust-287f506bfb853e1eed85a3bfdd7ab8ae4fee680699f45b24adbf865c20957ec7","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::num::Num; trait BrokenAdd: Num { fn broken_add(&self, rhs: T) -> Self { *self + rhs //~ ERROR mismatched types } } impl BrokenAdd for T {} pub fn main() { let foo: u8 = 0u8; let x: u8 = foo.broken_add(\"hello darkness my old friend\".to_string()); println!(\"{}\", x); } "} {"_id":"doc-en-rust-a4cabb6a8b263dc1e4200bc826348e49b587680790314673a673e689e56688b8","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Tr { fn op(T) -> Self; } // these compile as if Self: Tr, even tho only Self: Tr trait A: Tr { fn test(u: U) -> Self { Tr::op(u) //~ ERROR expected Tr, but found Tr } } trait B: Tr { fn test(u: U) -> Self { Tr::op(u) //~ ERROR expected Tr, but found Tr } } impl Tr for T { fn op(t: T) -> T { t } } impl A for T {} fn main() { std::io::println(A::test((&7306634593706211700, 8))); } "} {"_id":"doc-en-rust-46f13758ec037b88a92608c7df547fa8b30aeb4309f8aec7bf9d30fa3d117d83","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Tr { fn test(u: X) -> Self { u //~ ERROR mismatched types } } fn main() {} "} {"_id":"doc-en-rust-c28011ded6fdb631ff16a2538f863a9097f82eb569d5e0633f28eae24beb28eb","title":"","text":"CFG_LIBDIR_RELATIVE=bin fi if [ \"$CFG_OSTYPE\" = \"pc-mingw32\" ] || [ \"$CFG_OSTYPE\" = \"w64-mingw32\" ] then CFG_LD_PATH_VAR=PATH CFG_OLD_LD_PATH_VAR=$PATH elif [ \"$CFG_OSTYPE\" = \"Darwin\" ] then CFG_LD_PATH_VAR=DYLD_LIBRARY_PATH CFG_OLD_LD_PATH_VAR=$DYLD_LIBRARY_PATH else CFG_LD_PATH_VAR=LD_LIBRARY_PATH CFG_OLD_LD_PATH_VAR=$LD_LIBRARY_PATH fi flag uninstall \"only uninstall from the installation prefix\" opt verify 1 \"verify that the installed binaries run correctly\" valopt prefix \"/usr/local\" \"set installation prefix\""} {"_id":"doc-en-rust-e4bddfae5b49a910515cc937faafebc2e46779fadf6899e21fc809bf14e95cae","title":"","text":"if [ -z \"${CFG_UNINSTALL}\" ] then msg \"verifying platform can run binaries\" export $CFG_LD_PATH_VAR=\"${CFG_SRC_DIR}/lib\":$CFG_OLD_LD_PATH_VAR \"${CFG_SRC_DIR}/bin/rustc\" --version > /dev/null if [ $? -ne 0 ] then err \"can't execute rustc binary on this platform\" fi export $CFG_LD_PATH_VAR=$CFG_OLD_LD_PATH_VAR fi fi"} {"_id":"doc-en-rust-aedd2125ed847a6ea0d9abb9b1990718cd8c897d779a57f5d700b9ce170f8561","title":"","text":"done < \"${CFG_SRC_DIR}/${CFG_LIBDIR_RELATIVE}/rustlib/manifest.in\" # Sanity check: can we run the installed binaries? # # As with the verification above, make sure the right LD_LIBRARY_PATH-equivalent # is in place. Try first without this variable, and if that fails try again with # the variable. If the second time tries, print a hopefully helpful message to # add something to the appropriate environment variable. if [ -z \"${CFG_DISABLE_VERIFY}\" ] then msg \"verifying installed binaries are executable\" \"${CFG_PREFIX}/bin/rustc\" --version > /dev/null \"${CFG_PREFIX}/bin/rustc\" --version 2> /dev/null 1> /dev/null if [ $? -ne 0 ] then ERR=\"can't execute installed rustc binary. \" ERR=\"${ERR}installation may be broken. \" ERR=\"${ERR}if this is expected then rerun install.sh with `--disable-verify` \" ERR=\"${ERR}or `make install` with `--disable-verify-install`\" err \"${ERR}\" export $CFG_LD_PATH_VAR=\"${CFG_PREFIX}/lib\":$CFG_OLD_LD_PATH_VAR \"${CFG_PREFIX}/bin/rustc\" --version > /dev/null if [ $? -ne 0 ] then ERR=\"can't execute installed rustc binary. \" ERR=\"${ERR}installation may be broken. \" ERR=\"${ERR}if this is expected then rerun install.sh with `--disable-verify` \" ERR=\"${ERR}or `make install` with `--disable-verify-install`\" err \"${ERR}\" else echo echo \" please ensure '${CFG_PREFIX}/lib' is added to ${CFG_LD_PATH_VAR}\" echo fi fi fi"} {"_id":"doc-en-rust-c23d4e10ab6c0b51097190df93aa74ad9bfe719c59eb2a5ff34a3500fe1f1f28","title":"","text":"TTNonterminal(Span, Ident) } /// Matchers are nodes defined-by and recognized-by the main rust parser and /// language, but they're only ever found inside syntax-extension invocations; /// indeed, the only thing that ever _activates_ the rules in the rust parser /// for parsing a matcher is a matcher looking for the 'matchers' nonterminal /// itself. Matchers represent a small sub-language for pattern-matching /// token-trees, and are thus primarily used by the macro-defining extension /// itself. /// /// MatchTok /// -------- /// /// A matcher that matches a single token, denoted by the token itself. So /// long as there's no $ involved. /// /// /// MatchSeq /// -------- /// /// A matcher that matches a sequence of sub-matchers, denoted various /// possible ways: /// /// $(M)* zero or more Ms /// $(M)+ one or more Ms /// $(M),+ one or more comma-separated Ms /// $(A B C);* zero or more semi-separated 'A B C' seqs /// /// /// MatchNonterminal /// ----------------- /// /// A matcher that matches one of a few interesting named rust /// nonterminals, such as types, expressions, items, or raw token-trees. A /// black-box matcher on expr, for example, binds an expr to a given ident, /// and that ident can re-occur as an interpolation in the RHS of a /// macro-by-example rule. For example: /// /// $foo:expr => 1 + $foo // interpolate an expr /// $foo:tt => $foo // interpolate a token-tree /// $foo:tt => bar! $foo // only other valid interpolation /// // is in arg position for another /// // macro /// /// As a final, horrifying aside, note that macro-by-example's input is /// also matched by one of these matchers. Holy self-referential! It is matched /// by a MatchSeq, specifically this one: /// /// $( $lhs:matchers => $rhs:tt );+ /// /// If you understand that, you have closed the loop and understand the whole /// macro system. Congratulations. // Matchers are nodes defined-by and recognized-by the main rust parser and // language, but they're only ever found inside syntax-extension invocations; // indeed, the only thing that ever _activates_ the rules in the rust parser // for parsing a matcher is a matcher looking for the 'matchers' nonterminal // itself. Matchers represent a small sub-language for pattern-matching // token-trees, and are thus primarily used by the macro-defining extension // itself. // // MatchTok // -------- // // A matcher that matches a single token, denoted by the token itself. So // long as there's no $ involved. // // // MatchSeq // -------- // // A matcher that matches a sequence of sub-matchers, denoted various // possible ways: // // $(M)* zero or more Ms // $(M)+ one or more Ms // $(M),+ one or more comma-separated Ms // $(A B C);* zero or more semi-separated 'A B C' seqs // // // MatchNonterminal // ----------------- // // A matcher that matches one of a few interesting named rust // nonterminals, such as types, expressions, items, or raw token-trees. A // black-box matcher on expr, for example, binds an expr to a given ident, // and that ident can re-occur as an interpolation in the RHS of a // macro-by-example rule. For example: // // $foo:expr => 1 + $foo // interpolate an expr // $foo:tt => $foo // interpolate a token-tree // $foo:tt => bar! $foo // only other valid interpolation // // is in arg position for another // // macro // // As a final, horrifying aside, note that macro-by-example's input is // also matched by one of these matchers. Holy self-referential! It is matched // by a MatchSeq, specifically this one: // // $( $lhs:matchers => $rhs:tt );+ // // If you understand that, you have closed the loop and understand the whole // macro system. Congratulations. pub type Matcher = Spanned; #[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Hash)]"} {"_id":"doc-en-rust-5c5a28a08afa9e9a1bca597f5da3fea72c5beea09a322d41a6ab0cc6b389b37d","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern: too big for the current architecture #[cfg(target_pointer_width = \"32\")] fn main() { let x = [0usize; 0xffff_ffff]; } #[cfg(target_pointer_width = \"64\")] fn main() { let x = [0usize; 0xffff_ffff_ffff_ffff]; } "} {"_id":"doc-en-rust-d36d32fd3d4345a3bf226c229abe0dae9016f24f81ce217e95a40d851aa2b4d6","title":"","text":" Subproject commit 2751bdcef125468ea2ee006c11992cd1405aebe5 Subproject commit 34fca48ed284525b2f124bf93c51af36d6685492 "} {"_id":"doc-en-rust-4486230c5649bfb99f8b8b2a73149a6e84bc6ed0ad65fcb881fca7e59c882606","title":"","text":" Subproject commit 388750b081c0893c275044d37203f97709e058ba Subproject commit e3f3af69dce71cd37a785bccb7e58449197d940c "} {"_id":"doc-en-rust-fc90d79d15ff6d2cf104695d5e4e15cfbf996a2a921b483b76249444bbd3e0ce","title":"","text":" Subproject commit d43038932adeb16ada80e206d4c073d851298101 Subproject commit ee7c676fd6e287459cb407337652412c990686c0 "} {"_id":"doc-en-rust-b2a11c6984f4036649711b8c163467eea27f9c2d2d043354ba5e884f779a2a20","title":"","text":" Subproject commit 07e0df2f006e59d171c6bf3cafa9d61dbeb520d8 Subproject commit c954202c1e1720cba5628f99543cc01188c7d6fc "} {"_id":"doc-en-rust-a5f5f68f24cab9f177c848c1dd6b9756981899e73e2c1635bc805746cfffb84b","title":"","text":" Subproject commit b123ab4754127d822ffb38349ce0fbf561f1b2fd Subproject commit 08bb147d51e815b96e8db7ba4cf870f201c11ff8 "} {"_id":"doc-en-rust-19132abfb27af4f49ca30d8e2d0e18e3a621078a8576851670f89aa7943f27a1","title":"","text":"**Source:** https://github.com/rust-lang/rust-analyzer/blob/master/crates/rust-analyzer/src/config.rs[config.rs] The <<_installation,Installation>> section contains details on configuration for some of the editors. The <> section contains details on configuration for some of the editors. In general `rust-analyzer` is configured via LSP messages, which means that it's up to the editor to decide on the exact format and location of configuration files. Some clients, such as <> or <> provide `rust-analyzer` specific configuration UIs. Others may require you to know a bit more about the interaction with `rust-analyzer`."} {"_id":"doc-en-rust-c179906366701996c3e746a1184066cf25db4b271bde26e80c510772e515a2f8","title":"","text":"let stability_index = time(time_passes, \"stability index\", (), |_| stability::Index::build(krate)); time(time_passes, \"static item recursion checking\", (), |_| middle::check_static_recursion::check_crate(&sess, krate, &def_map, &ast_map)); let ty_cx = ty::mk_ctxt(sess, type_arena, def_map,"} {"_id":"doc-en-rust-b1909a43e0a7b2681695308637fae53ed4409eccbde35c82eb12e83cf5afae64","title":"","text":"pub mod borrowck; pub mod cfg; pub mod check_const; pub mod check_static_recursion; pub mod check_loop; pub mod check_match; pub mod check_rvalues;"} {"_id":"doc-en-rust-533565ffca50e2317793e19db02767a8cda696ed4b6ac871d9176d4c67cba88c","title":"","text":"// except according to those terms. use driver::session::Session; use middle::def::*; use middle::resolve; use middle::ty; use middle::typeck; use util::ppaux; use syntax::ast::*; use syntax::{ast_util, ast_map}; use syntax::ast_util; use syntax::visit::Visitor; use syntax::visit;"} {"_id":"doc-en-rust-c58d041ecdb9c4a91b6fac4dd2886bbb4f36dda7349357790bc41f12973abacb","title":"","text":"match it.node { ItemStatic(_, _, ref ex) => { v.inside_const(|v| v.visit_expr(&**ex)); check_item_recursion(&v.tcx.sess, &v.tcx.map, &v.tcx.def_map, it); } ItemEnum(ref enum_definition, _) => { for var in (*enum_definition).variants.iter() {"} {"_id":"doc-en-rust-849c04e400f26dedabc4a8dff4e33f6d7b742b5ef7bdeac33c33e4a76c5d0447","title":"","text":"} visit::walk_expr(v, e); } struct CheckItemRecursionVisitor<'a, 'ast: 'a> { root_it: &'a Item, sess: &'a Session, ast_map: &'a ast_map::Map<'ast>, def_map: &'a resolve::DefMap, idstack: Vec } // Make sure a const item doesn't recursively refer to itself // FIXME: Should use the dependency graph when it's available (#1356) pub fn check_item_recursion<'a>(sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, it: &'a Item) { let mut visitor = CheckItemRecursionVisitor { root_it: it, sess: sess, ast_map: ast_map, def_map: def_map, idstack: Vec::new() }; visitor.visit_item(it); } impl<'a, 'ast, 'v> Visitor<'v> for CheckItemRecursionVisitor<'a, 'ast> { fn visit_item(&mut self, it: &Item) { if self.idstack.iter().any(|x| x == &(it.id)) { self.sess.span_fatal(self.root_it.span, \"recursive constant\"); } self.idstack.push(it.id); visit::walk_item(self, it); self.idstack.pop(); } fn visit_expr(&mut self, e: &Expr) { match e.node { ExprPath(..) => { match self.def_map.borrow().find(&e.id) { Some(&DefStatic(def_id, _)) if ast_util::is_local(def_id) => { self.visit_item(&*self.ast_map.expect_item(def_id.node)); } _ => () } }, _ => () } visit::walk_expr(self, e); } } "} {"_id":"doc-en-rust-9775302ddf9ce19807147945c99da99c41a4b5621f377d8220fc29ceda073f38","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This compiler pass detects static items that refer to themselves // recursively. use driver::session::Session; use middle::resolve; use middle::def::DefStatic; use syntax::ast::{Crate, Expr, ExprPath, Item, ItemStatic, NodeId}; use syntax::{ast_util, ast_map}; use syntax::visit::Visitor; use syntax::visit; struct CheckCrateVisitor<'a, 'ast: 'a> { sess: &'a Session, def_map: &'a resolve::DefMap, ast_map: &'a ast_map::Map<'ast> } impl<'v, 'a, 'ast> Visitor<'v> for CheckCrateVisitor<'a, 'ast> { fn visit_item(&mut self, i: &Item) { check_item(self, i); } } pub fn check_crate<'ast>(sess: &Session, krate: &Crate, def_map: &resolve::DefMap, ast_map: &ast_map::Map<'ast>) { let mut visitor = CheckCrateVisitor { sess: sess, def_map: def_map, ast_map: ast_map }; visit::walk_crate(&mut visitor, krate); sess.abort_if_errors(); } fn check_item(v: &mut CheckCrateVisitor, it: &Item) { match it.node { ItemStatic(_, _, ref ex) => { check_item_recursion(v.sess, v.ast_map, v.def_map, it); visit::walk_expr(v, &**ex) }, _ => visit::walk_item(v, it) } } struct CheckItemRecursionVisitor<'a, 'ast: 'a> { root_it: &'a Item, sess: &'a Session, ast_map: &'a ast_map::Map<'ast>, def_map: &'a resolve::DefMap, idstack: Vec } // Make sure a const item doesn't recursively refer to itself // FIXME: Should use the dependency graph when it's available (#1356) pub fn check_item_recursion<'a>(sess: &'a Session, ast_map: &'a ast_map::Map, def_map: &'a resolve::DefMap, it: &'a Item) { let mut visitor = CheckItemRecursionVisitor { root_it: it, sess: sess, ast_map: ast_map, def_map: def_map, idstack: Vec::new() }; visitor.visit_item(it); } impl<'a, 'ast, 'v> Visitor<'v> for CheckItemRecursionVisitor<'a, 'ast> { fn visit_item(&mut self, it: &Item) { if self.idstack.iter().any(|x| x == &(it.id)) { self.sess.span_err(self.root_it.span, \"recursive constant\"); return; } self.idstack.push(it.id); visit::walk_item(self, it); self.idstack.pop(); } fn visit_expr(&mut self, e: &Expr) { match e.node { ExprPath(..) => { match self.def_map.borrow().find(&e.id) { Some(&DefStatic(def_id, _)) if ast_util::is_local(def_id) => { self.visit_item(&*self.ast_map.expect_item(def_id.node)); } _ => () } }, _ => () } visit::walk_expr(self, e); } } "} {"_id":"doc-en-rust-4fd3b5fe5f73fb4ed6aabb3590e086c22b03f0ce2f037e91f636912e10b82c25","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. static FOO: uint = FOO; //~ ERROR recursive constant fn main() { let _x: [u8, ..FOO]; // caused stack overflow prior to fix let _y: uint = 1 + { static BAR: uint = BAR; //~ ERROR recursive constant let _z: [u8, ..BAR]; // caused stack overflow prior to fix 1 }; } "} {"_id":"doc-en-rust-1d9ed2d556f6f3723a9c495ddfb4083726dde618afa0c3fa68ac6ec3b2ee1e82","title":"","text":"euv::AutoRef(..) | euv::ClosureInvocation(..) | euv::ForLoop(..) | euv::RefBinding(..) => { euv::RefBinding(..) | euv::MatchDiscriminant(..) => { format!(\"previous borrow of `{}` occurs here\", self.bccx.loan_path_to_string(&*old_loan.loan_path)) }"} {"_id":"doc-en-rust-8fb78beaf826eae51154114cba362d288503e49fa4e78f695f6c5266d31fbb7b","title":"","text":"euv::AddrOf | euv::RefBinding | euv::AutoRef | euv::ForLoop => { euv::ForLoop | euv::MatchDiscriminant => { format!(\"cannot borrow {} as mutable\", descr) } euv::ClosureInvocation => {"} {"_id":"doc-en-rust-016685476a62622310251de040610fe56e03ebee04acd84b80532bca1cbca340","title":"","text":"BorrowViolation(euv::OverloadedOperator) | BorrowViolation(euv::AddrOf) | BorrowViolation(euv::AutoRef) | BorrowViolation(euv::RefBinding) => { BorrowViolation(euv::RefBinding) | BorrowViolation(euv::MatchDiscriminant) => { \"cannot borrow data mutably\" }"} {"_id":"doc-en-rust-e5f0f286a6044cd03fb2a2515ecf70804946a3cf79394990387079810ffd1680","title":"","text":"OverloadedOperator, ClosureInvocation, ForLoop, MatchDiscriminant } #[deriving(PartialEq,Show)]"} {"_id":"doc-en-rust-fc09eab11a1b6be20355e489ae2f307b01b9ed4d8003aac0361cbf38e0025f42","title":"","text":"} ast::ExprMatch(ref discr, ref arms) => { // treatment of the discriminant is handled while // walking the arms: self.walk_expr(&**discr); let discr_cmt = return_if_err!(self.mc.cat_expr(&**discr)); self.borrow_expr(&**discr, ty::ReEmpty, ty::ImmBorrow, MatchDiscriminant); // treatment of the discriminant is handled while walking the arms. for arm in arms.iter() { self.walk_arm(discr_cmt.clone(), arm); }"} {"_id":"doc-en-rust-fd37ac97447eb5eeac81e0070892e0989f6c5d87857a2e1f303e5365166f9853","title":"","text":"ref s => { tcx.sess.span_bug( span, format!(\"ty_region() invoked on in appropriate ty: {:?}\", format!(\"ty_region() invoked on an inappropriate ty: {:?}\", s).as_slice()); } }"} {"_id":"doc-en-rust-82268035238162cf5088440a8a821f1f3c0861f2faaefd58bb2094295a4d3388","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn foo(_s: i16) { } fn bar(_s: u32) { } fn main() { foo(1*(1 as int)); //~^ ERROR: mismatched types: expected `i16`, found `int` (expected `i16`, found `int`) bar(1*(1 as uint)); //~^ ERROR: mismatched types: expected `u32`, found `uint` (expected `u32`, found `uint`) } "} {"_id":"doc-en-rust-d845f28c0e6fb3aafbf9b0cc8d6338405098b18e9e3365bca1f066397dd6837c","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct X(int); enum Enum { Variant1, Variant2 } impl Drop for X { fn drop(&mut self) {} } impl Drop for Enum { fn drop(&mut self) {} } fn main() { let foo = X(1i); drop(foo); match foo { //~ ERROR use of moved value X(1i) => (), _ => unreachable!() } let e = Variant2; drop(e); match e { //~ ERROR use of moved value Variant1 => unreachable!(), Variant2 => () } } "} {"_id":"doc-en-rust-c135a622274e276af9b78d0a702556dbd164b96bcf9f891b2e979a1c4795359b","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn foo(_s: i16) { } fn bar(_s: u32) { } fn main() { foo(1*(1 as int)); //~^ ERROR: mismatched types: expected `i16`, found `int` (expected `i16`, found `int`) bar(1*(1 as uint)); //~^ ERROR: mismatched types: expected `u32`, found `uint` (expected `u32`, found `uint`) } "} {"_id":"doc-en-rust-f9b93a71773c25d0181f68e5cbca4b40914917a202ba1d03bf7416703b9bc8bc","title":"","text":"{ let parent = self.get_parent(id); let parent = match self.find_entry(id) { Some(EntryForeignItem(..)) | Some(EntryVariant(..)) => { // Anonymous extern items, enum variants and struct ctors // go in the parent scope. Some(EntryForeignItem(..)) => { // Anonymous extern items go in the parent scope. self.get_parent(parent) } // But tuple struct ctors don't have names, so use the path of its"} {"_id":"doc-en-rust-ebcd74389ede4290e4c5af07f2ed630e582f9ea4841a1e24fa3cb10e21e867f0","title":"","text":"prim_ty_to_ty(tcx, base_segments, prim_ty) } _ => { let node = def.def_id().node; span_err!(tcx.sess, span, E0248, \"found value name used as a type: {:?}\", *def); \"found value `{}` used as a type\", tcx.map.path_to_string(node)); return this.tcx().types.err; } }"} {"_id":"doc-en-rust-811b351450a0343ce7380c32cc93caa1cd1687e0fd4976fbf56f70b8ef1bb520","title":"","text":"Bar } fn foo(x: Foo::Bar) {} //~ERROR found value name used as a type fn foo(x: Foo::Bar) {} //~ERROR found value `Foo::Bar` used as a type fn main() {}"} {"_id":"doc-en-rust-95485d66c01546882055e9a56fa31bbf266fc4f7536ce706a455c968636d3b71","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use foo::MyEnum::Result; use foo::NoResult; // Through a re-export mod foo { pub use self::MyEnum::NoResult; enum MyEnum { Result, NoResult } fn new() -> NoResult { //~^ ERROR: found value `foo::MyEnum::NoResult` used as a type unimplemented!() } } mod bar { use foo::MyEnum::Result; use foo; fn new() -> Result { //~^ ERROR: found value `foo::MyEnum::Result` used as a type unimplemented!() } } fn new() -> Result { //~^ ERROR: found value `foo::MyEnum::Result` used as a type unimplemented!() } fn newer() -> NoResult { //~^ ERROR: found value `foo::MyEnum::NoResult` used as a type unimplemented!() } fn main() { let _ = new(); } "} {"_id":"doc-en-rust-8e6c69b38bf2824f4613d8b8144de439e9c049a521c69587a57bd9cacf66ec9b","title":"","text":"#[rustc_move_fragments] pub fn test_match_partial(p: Lonely) { //~^ ERROR parent_of_fragments: `$(local p)` //~| ERROR assigned_leaf_path: `($(local p) as Zero)` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::Zero)` match p { Zero(..) => {} _ => {}"} {"_id":"doc-en-rust-b37d649e1458a97ca15d9db1ce2444c5522bd71d252718f893a08553101c3647","title":"","text":"#[rustc_move_fragments] pub fn test_match_full(p: Lonely) { //~^ ERROR parent_of_fragments: `$(local p)` //~| ERROR assigned_leaf_path: `($(local p) as Zero)` //~| ERROR assigned_leaf_path: `($(local p) as One)` //~| ERROR assigned_leaf_path: `($(local p) as Two)` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::Zero)` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::One)` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::Two)` match p { Zero(..) => {} One(..) => {}"} {"_id":"doc-en-rust-e571967450a62871ffebeeeafab3b647ccbd345a34489715c4ece4999cc2b778","title":"","text":"#[rustc_move_fragments] pub fn test_match_bind_one(p: Lonely) { //~^ ERROR parent_of_fragments: `$(local p)` //~| ERROR assigned_leaf_path: `($(local p) as Zero)` //~| ERROR parent_of_fragments: `($(local p) as One)` //~| ERROR moved_leaf_path: `($(local p) as One).#0` //~| ERROR assigned_leaf_path: `($(local p) as Two)` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::Zero)` //~| ERROR parent_of_fragments: `($(local p) as Lonely::One)` //~| ERROR moved_leaf_path: `($(local p) as Lonely::One).#0` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::Two)` //~| ERROR assigned_leaf_path: `$(local data)` match p { Zero(..) => {}"} {"_id":"doc-en-rust-3055714d0a0076ed06eb06970e8c5a2fefad109c00b2fa737b9b13c45f77e277","title":"","text":"#[rustc_move_fragments] pub fn test_match_bind_many(p: Lonely) { //~^ ERROR parent_of_fragments: `$(local p)` //~| ERROR assigned_leaf_path: `($(local p) as Zero)` //~| ERROR parent_of_fragments: `($(local p) as One)` //~| ERROR moved_leaf_path: `($(local p) as One).#0` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::Zero)` //~| ERROR parent_of_fragments: `($(local p) as Lonely::One)` //~| ERROR moved_leaf_path: `($(local p) as Lonely::One).#0` //~| ERROR assigned_leaf_path: `$(local data)` //~| ERROR parent_of_fragments: `($(local p) as Two)` //~| ERROR moved_leaf_path: `($(local p) as Two).#0` //~| ERROR moved_leaf_path: `($(local p) as Two).#1` //~| ERROR parent_of_fragments: `($(local p) as Lonely::Two)` //~| ERROR moved_leaf_path: `($(local p) as Lonely::Two).#0` //~| ERROR moved_leaf_path: `($(local p) as Lonely::Two).#1` //~| ERROR assigned_leaf_path: `$(local left)` //~| ERROR assigned_leaf_path: `$(local right)` match p {"} {"_id":"doc-en-rust-d2ad1581699f1bf6f4b31bb4c3edda02cf70003bb64b97852be0570474e26fa5","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //"} {"_id":"doc-en-rust-072931f0a08736b1d98904e8786be145a1e189dd6632aa1e277cc87101b84593","title":"","text":"#[rustc_move_fragments] pub fn test_match_bind_and_underscore(p: Lonely) { //~^ ERROR parent_of_fragments: `$(local p)` //~| ERROR assigned_leaf_path: `($(local p) as Zero)` //~| ERROR assigned_leaf_path: `($(local p) as One)` //~| ERROR parent_of_fragments: `($(local p) as Two)` //~| ERROR moved_leaf_path: `($(local p) as Two).#0` //~| ERROR unmoved_fragment: `($(local p) as Two).#1` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::Zero)` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::One)` //~| ERROR parent_of_fragments: `($(local p) as Lonely::Two)` //~| ERROR moved_leaf_path: `($(local p) as Lonely::Two).#0` //~| ERROR unmoved_fragment: `($(local p) as Lonely::Two).#1` //~| ERROR assigned_leaf_path: `$(local left)` match p {"} {"_id":"doc-en-rust-24e10520017e04927b4bc99996d854b5a18f60900296f26c214e6596e7c44988","title":"","text":"impl<'a> Writer for &'a mut Writer+'a { #[inline] fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.write(buf) } fn write(&mut self, buf: &[u8]) -> IoResult<()> { (**self).write(buf) } #[inline] fn flush(&mut self) -> IoResult<()> { self.flush() } fn flush(&mut self) -> IoResult<()> { (**self).flush() } } /// A `RefWriter` is a struct implementing `Writer` which contains a reference"} {"_id":"doc-en-rust-f47b1748fd17d8d4077a5d4299b23180667da74da10daaf668f7be18b7c6ea1e","title":"","text":"It generally helps our diagnosis to include your specific OS (for example: Mac OS X 10.8.3, Windows 7, Ubuntu 12.04) and your hardware architecture (for example: i686, x86_64). It's also helpful to copy/paste the output of re-running the erroneous rustc command with the `-v` flag. Finally, if you can run the offending command under gdb, pasting a stack trace can be useful; to do so, you will need to set a breakpoint on `rust_fail`. It's also helpful to provide the exact version and host by copying the output of re-running the erroneous rustc command with the `--version=verbose` flag, which will produce something like this: ```{ignore} rustc 0.12.0 (ba4081a5a 2014-10-07 13:44:41 -0700) binary: rustc commit-hash: ba4081a5a8573875fed17545846f6f6902c8ba8d commit-date: 2014-10-07 13:44:41 -0700 host: i686-apple-darwin release: 0.12.0 ``` Finally, if you can run the offending command under gdb, pasting a stack trace can be useful; to do so, you will need to set a breakpoint on `rust_fail`. # I submitted a bug, but nobody has commented on it!"} {"_id":"doc-en-rust-ecab79986a5f5b15d76efb8b078cd8104d835fe14f2319271e612c58a99a54c7","title":"","text":"# Some less critical tests that are not prone to breakage. # Not run as part of the normal test suite, but tested by bors on checkin. check-secondary: check-lexer check-pretty check-secondary: check-build-compiletest check-lexer check-pretty # check + check-secondary. check-all: check check-secondary # # Issue #17883: build check-secondary first so hidden dependencies in # e.g. building compiletest are exercised (resolve those by adding # deps to rules that need them; not by putting `check` first here). check-all: check-secondary check # Pretty-printing tests. check-pretty: check-stage2-T-$(CFG_BUILD)-H-$(CFG_BUILD)-pretty-exec define DEF_CHECK_BUILD_COMPILETEST_FOR_STAGE check-stage$(1)-build-compiletest: \t$$(HBIN$(1)_H_$(CFG_BUILD))/compiletest$$(X_$(CFG_BUILD)) endef $(foreach stage,$(STAGES), $(eval $(call DEF_CHECK_BUILD_COMPILETEST_FOR_STAGE,$(stage)))) check-build-compiletest: check-stage1-build-compiletest check-stage2-build-compiletest .PHONY: cleantmptestlogs cleantestlibs cleantmptestlogs:"} {"_id":"doc-en-rust-29310bb14b15d5beb5024aa6f9b12246d5e25e23b7009e52024a78850fc668c5","title":"","text":"PRETTY_DEPS_pretty-rfail = $(RFAIL_TESTS) PRETTY_DEPS_pretty-bench = $(BENCH_TESTS) PRETTY_DEPS_pretty-pretty = $(PRETTY_TESTS) # The stage- and host-specific dependencies are for e.g. macro_crate_test which pulls in # external crates. PRETTY_DEPS$(1)_H_$(3)_pretty-rpass = PRETTY_DEPS$(1)_H_$(3)_pretty-rpass-full = $$(HLIB$(1)_H_$(3))/stamp.syntax $$(HLIB$(1)_H_$(3))/stamp.rustc PRETTY_DEPS$(1)_H_$(3)_pretty-rfail = PRETTY_DEPS$(1)_H_$(3)_pretty-bench = PRETTY_DEPS$(1)_H_$(3)_pretty-pretty = PRETTY_DIRNAME_pretty-rpass = run-pass PRETTY_DIRNAME_pretty-rpass-full = run-pass-fulldeps PRETTY_DIRNAME_pretty-rfail = run-fail"} {"_id":"doc-en-rust-a5611babb5a32dcc78fe69805b515f2412dc6a1727c35003c1159f83aeef126e","title":"","text":"$$(call TEST_OK_FILE,$(1),$(2),$(3),$(4)): $$(TEST_SREQ$(1)_T_$(2)_H_$(3)) $$(PRETTY_DEPS_$(4)) $$(PRETTY_DEPS_$(4)) $$(PRETTY_DEPS$(1)_H_$(3)_$(4)) @$$(call E, run pretty-rpass [$(2)]: $$<) $$(Q)$$(call CFG_RUN_CTEST_$(2),$(1),$$<,$(3)) $$(PRETTY_ARGS$(1)-T-$(2)-H-$(3)-$(4)) "} {"_id":"doc-en-rust-b366ef045ef1049cdf63d4d8f45bb12c9863cd4306c56a94b3af612efa8efa2a","title":"","text":"impl fmt::Show for Duration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let days = self.num_days(); let secs = self.secs - days * SECS_PER_DAY; // technically speaking, negative duration is not valid ISO 8601, // but we need to print it anyway. let (abs, sign) = if self.secs < 0 { (-self, \"-\") } else { (*self, \"\") }; let days = abs.secs / SECS_PER_DAY; let secs = abs.secs - days * SECS_PER_DAY; let hasdate = days != 0; let hastime = (secs != 0 || self.nanos != 0) || !hasdate; let hastime = (secs != 0 || abs.nanos != 0) || !hasdate; try!(write!(f, \"{}P\", sign)); try!(write!(f, \"P\")); if hasdate { // technically speaking the negative part is not the valid ISO 8601, // but we need to print it anyway. try!(write!(f, \"{}D\", days)); } if hastime { if self.nanos == 0 { if abs.nanos == 0 { try!(write!(f, \"T{}S\", secs)); } else if self.nanos % NANOS_PER_MILLI == 0 { try!(write!(f, \"T{}.{:03}S\", secs, self.nanos / NANOS_PER_MILLI)); } else if self.nanos % NANOS_PER_MICRO == 0 { try!(write!(f, \"T{}.{:06}S\", secs, self.nanos / NANOS_PER_MICRO)); } else if abs.nanos % NANOS_PER_MILLI == 0 { try!(write!(f, \"T{}.{:03}S\", secs, abs.nanos / NANOS_PER_MILLI)); } else if abs.nanos % NANOS_PER_MICRO == 0 { try!(write!(f, \"T{}.{:06}S\", secs, abs.nanos / NANOS_PER_MICRO)); } else { try!(write!(f, \"T{}.{:09}S\", secs, self.nanos)); try!(write!(f, \"T{}.{:09}S\", secs, abs.nanos)); } } Ok(())"} {"_id":"doc-en-rust-d69a06d5cf88439ab664c2a05f9d905ae5bc70a4ea96bd64850c9782d9b56be5","title":"","text":"let d: Duration = Zero::zero(); assert_eq!(d.to_string(), \"PT0S\".to_string()); assert_eq!(Duration::days(42).to_string(), \"P42D\".to_string()); assert_eq!(Duration::days(-42).to_string(), \"P-42D\".to_string()); assert_eq!(Duration::days(-42).to_string(), \"-P42D\".to_string()); assert_eq!(Duration::seconds(42).to_string(), \"PT42S\".to_string()); assert_eq!(Duration::milliseconds(42).to_string(), \"PT0.042S\".to_string()); assert_eq!(Duration::microseconds(42).to_string(), \"PT0.000042S\".to_string()); assert_eq!(Duration::nanoseconds(42).to_string(), \"PT0.000000042S\".to_string()); assert_eq!((Duration::days(7) + Duration::milliseconds(6543)).to_string(), \"P7DT6.543S\".to_string()); assert_eq!(Duration::seconds(-86401).to_string(), \"-P1DT1S\".to_string()); assert_eq!(Duration::nanoseconds(-1).to_string(), \"-PT0.000000001S\".to_string()); // the format specifier should have no effect on `Duration` assert_eq!(format!(\"{:30}\", Duration::days(1) + Duration::milliseconds(2345)),"} {"_id":"doc-en-rust-5a64775c8133565cc5ef4a9d94cd7af013ee6fd714f1702d23e068ee505df233","title":"","text":"return found def make_win_dist(dist_root, target_triple): # Ask gcc where it keeps its' stuff # Ask gcc where it keeps its stuff gcc_out = subprocess.check_output([\"gcc.exe\", \"-print-search-dirs\"]) bin_path = os.environ[\"PATH\"].split(os.pathsep) lib_path = []"} {"_id":"doc-en-rust-7352202efc5f8c2b688f1c17f135a04122fba4f87c2675c2eed1b068e1714fde","title":"","text":"else: rustc_dlls.append(\"libgcc_s_seh-1.dll\") target_libs = [\"crtbegin.o\", \"crtend.o\", \"crt2.o\", \"dllcrt2.o\", \"libadvapi32.a\", \"libcrypt32.a\", \"libgcc.a\", \"libgcc_eh.a\", \"libgcc_s.a\", \"libimagehlp.a\", \"libiphlpapi.a\", \"libkernel32.a\", \"libm.a\", \"libmingw32.a\", \"libmingwex.a\", \"libmsvcrt.a\", \"libpsapi.a\", \"libshell32.a\", \"libstdc++.a\", \"libuser32.a\", \"libws2_32.a\", \"libiconv.a\", \"libmoldname.a\"] target_libs = [ # MinGW libs \"crtbegin.o\", \"crtend.o\", \"crt2.o\", \"dllcrt2.o\", \"libgcc.a\", \"libgcc_eh.a\", \"libgcc_s.a\", \"libm.a\", \"libmingw32.a\", \"libmingwex.a\", \"libstdc++.a\", \"libiconv.a\", \"libmoldname.a\", # Windows import libs \"libadvapi32.a\", \"libbcrypt.a\", \"libcomctl32.a\", \"libcomdlg32.a\", \"libcrypt32.a\", \"libctl3d32.a\", \"libgdi32.a\", \"libimagehlp.a\", \"libiphlpapi.a\", \"libkernel32.a\", \"libmsvcrt.a\", \"libodbc32.a\", \"libole32.a\", \"liboleaut32.a\", \"libopengl32.a\", \"libpsapi.a\", \"librpcrt4.a\", \"libsetupapi.a\", \"libshell32.a\", \"libuser32.a\", \"libuuid.a\", \"libwinhttp.a\", \"libwinmm.a\", \"libwinspool.a\", \"libws2_32.a\", \"libwsock32.a\", ] # Find mingw artifacts we want to bundle target_tools = find_files(target_tools, bin_path)"} {"_id":"doc-en-rust-f3d1b2ee3c688634debb3fdfc86ec3275bb56afec99cd371a51fffade30f8cc5","title":"","text":"shutil.copy(src, dist_bin_dir) # Copy platform tools to platform-specific bin directory target_bin_dir = os.path.join(dist_root, \"bin\", \"rustlib\", target_triple, \"gcc\", \"bin\") target_bin_dir = os.path.join(dist_root, \"bin\", \"rustlib\", target_triple, \"bin\") if not os.path.exists(target_bin_dir): os.makedirs(target_bin_dir) for src in target_tools: shutil.copy(src, target_bin_dir) # Copy platform libs to platform-spcific lib directory target_lib_dir = os.path.join(dist_root, \"bin\", \"rustlib\", target_triple, \"gcc\", \"lib\") target_lib_dir = os.path.join(dist_root, \"bin\", \"rustlib\", target_triple, \"lib\") if not os.path.exists(target_lib_dir): os.makedirs(target_lib_dir) for src in target_libs:"} {"_id":"doc-en-rust-edfcbb80f35184875d93829291391d692c0720b88643782c304fe5053aecbfc3","title":"","text":"cmd.arg(obj_filename.with_extension(\"metadata.o\")); } // Rust does its' own LTO cmd.arg(\"-fno-lto\"); if t.options.is_like_osx { // The dead_strip option to the linker specifies that functions and data // unreachable by the entry point will be removed. This is quite useful"} {"_id":"doc-en-rust-29d8a8c9b4820cddb7e2682607c23d70ffd9d905c299846a9497236e348c69ad","title":"","text":"trans: &CrateTranslation, outputs: &OutputFilenames) { let old_path = os::getenv(\"PATH\").unwrap_or_else(||String::new()); let mut new_path = os::split_paths(old_path.as_slice()); new_path.extend(sess.host_filesearch().get_tools_search_paths().into_iter()); let mut new_path = sess.host_filesearch().get_tools_search_paths(); new_path.extend(os::split_paths(old_path.as_slice()).into_iter()); os::setenv(\"PATH\", os::join_paths(new_path.as_slice()).unwrap()); time(sess.time_passes(), \"linking\", (), |_|"} {"_id":"doc-en-rust-7e07e3b4132822e8a2c7fa4748fc7d92a65fd3a478956874acae98ac3fae5de3","title":"","text":"p.push(find_libdir(self.sysroot)); p.push(rustlibdir()); p.push(self.triple); let mut p1 = p.clone(); p1.push(\"bin\"); let mut p2 = p.clone(); p2.push(\"gcc\"); p2.push(\"bin\"); vec![p1, p2] p.push(\"bin\"); vec![p] } }"} {"_id":"doc-en-rust-b5e9aa863015262e06ab2a37490611ea1d2e5d72c81fee09baead9eab2f0ab08","title":"","text":"unsafe { let ccx = cx.fcx.ccx; let ty = val_ty(fn_); let retty = if ty.kind() == llvm::Integer { let retty = if ty.kind() == llvm::Function { ty.return_type() } else { ccx.int_type()"} {"_id":"doc-en-rust-e4d5add07b5fa87133853e5d329e892b8ddc3526d32af5dfdcadb75dd443c083","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:stop // #18576 // Make sure that an calling extern function pointer in an unreachable // context doesn't cause an LLVM assertion #[allow(unreachable_code)] fn main() { panic!(\"stop\"); let pointer = other; pointer(); } extern fn other() {} "} {"_id":"doc-en-rust-5cee976ca2181387d2d6b2fa468ac944811ec96c8e33acd21528030fe840a4dc","title":"","text":"use common::{CodegenCx, val_ty}; use declare; use monomorphize::Instance; use syntax_pos::Span; use syntax_pos::symbol::LocalInternedString; use type_::Type; use type_of::LayoutLlvmExt; use rustc::ty; use rustc::ty::{self, Ty}; use rustc::ty::layout::{Align, LayoutOf}; use rustc::hir::{self, CodegenFnAttrFlags}; use rustc::hir::{self, CodegenFnAttrs, CodegenFnAttrFlags}; use std::ffi::{CStr, CString};"} {"_id":"doc-en-rust-a2b792b6c02802e532211ebd80563bb5f432526afa16c814eaf6a391c1753aad","title":"","text":"let ty = instance.ty(cx.tcx); let sym = cx.tcx.symbol_name(instance).as_str(); debug!(\"get_static: sym={} instance={:?}\", sym, instance); let g = if let Some(id) = cx.tcx.hir.as_local_node_id(def_id) { let llty = cx.layout_of(ty).llvm_type(cx);"} {"_id":"doc-en-rust-318b3ac5f2ec07849df1c79698c379f480406bae59be166603870eea318c8274","title":"","text":"hir_map::NodeForeignItem(&hir::ForeignItem { ref attrs, span, node: hir::ForeignItemKind::Static(..), .. }) => { let g = if let Some(linkage) = cx.tcx.codegen_fn_attrs(def_id).linkage { // If this is a static with a linkage specified, then we need to handle // it a little specially. The typesystem prevents things like &T and // extern \"C\" fn() from being non-null, so we can't just declare a // static and call it a day. Some linkages (like weak) will make it such // that the static actually has a null value. let llty2 = match ty.sty { ty::TyRawPtr(ref mt) => cx.layout_of(mt.ty).llvm_type(cx), _ => { cx.sess().span_fatal(span, \"must have type `*const T` or `*mut T`\"); } }; unsafe { // Declare a symbol `foo` with the desired linkage. let g1 = declare::declare_global(cx, &sym, llty2); llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage)); // Declare an internal global `extern_with_linkage_foo` which // is initialized with the address of `foo`. If `foo` is // discarded during linking (for example, if `foo` has weak // linkage and there are no definitions), then // `extern_with_linkage_foo` will instead be initialized to // zero. let mut real_name = \"_rust_extern_with_linkage_\".to_string(); real_name.push_str(&sym); let g2 = declare::define_global(cx, &real_name, llty).unwrap_or_else(||{ cx.sess().span_fatal(span, &format!(\"symbol `{}` is already defined\", &sym)) }); llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage); llvm::LLVMSetInitializer(g2, g1); g2 } } else { // Generate an external declaration. declare::declare_global(cx, &sym, llty) }; (g, attrs) let fn_attrs = cx.tcx.codegen_fn_attrs(def_id); (check_and_apply_linkage(cx, &fn_attrs, ty, sym, Some(span)), attrs) } item => bug!(\"get_static: expected static, found {:?}\", item) }; debug!(\"get_static: sym={} attrs={:?}\", sym, attrs); for attr in attrs { if attr.check_name(\"thread_local\") { llvm::set_thread_local_mode(g, cx.tls_model);"} {"_id":"doc-en-rust-68bc26f3d58da61ad193376712dd0cf98554e5aed8baa00b65890d6fffcb44df","title":"","text":"g } else { // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow? // FIXME(nagisa): investigate whether it can be changed into define_global let g = declare::declare_global(cx, &sym, cx.layout_of(ty).llvm_type(cx)); debug!(\"get_static: sym={} item_attr={:?}\", sym, cx.tcx.item_attrs(def_id)); let attrs = cx.tcx.codegen_fn_attrs(def_id); let g = check_and_apply_linkage(cx, &attrs, ty, sym, None); // Thread-local statics in some other crate need to *always* be linked // against in a thread-local fashion, so we need to be sure to apply the // thread-local attribute locally if it was present remotely. If we // don't do this then linker errors can be generated where the linker // complains that one object files has a thread local version of the // symbol and another one doesn't. for attr in cx.tcx.get_attrs(def_id).iter() { if attr.check_name(\"thread_local\") { llvm::set_thread_local_mode(g, cx.tls_model); } if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) { llvm::set_thread_local_mode(g, cx.tls_model); } if cx.use_dll_storage_attrs && !cx.tcx.is_foreign_item(def_id) { // This item is external but not foreign, i.e. it originates from an external Rust // crate. Since we don't know whether this crate will be linked dynamically or"} {"_id":"doc-en-rust-ffdea37f271aa115c8be581deff56497e651f233aaa307a965a4af1cf39ad956","title":"","text":"g } fn check_and_apply_linkage<'tcx>( cx: &CodegenCx<'_, 'tcx>, attrs: &CodegenFnAttrs, ty: Ty<'tcx>, sym: LocalInternedString, span: Option ) -> ValueRef { let llty = cx.layout_of(ty).llvm_type(cx); if let Some(linkage) = attrs.linkage { debug!(\"get_static: sym={} linkage={:?}\", sym, linkage); // If this is a static with a linkage specified, then we need to handle // it a little specially. The typesystem prevents things like &T and // extern \"C\" fn() from being non-null, so we can't just declare a // static and call it a day. Some linkages (like weak) will make it such // that the static actually has a null value. let llty2 = match ty.sty { ty::TyRawPtr(ref mt) => cx.layout_of(mt.ty).llvm_type(cx), _ => { if span.is_some() { cx.sess().span_fatal(span.unwrap(), \"must have type `*const T` or `*mut T`\") } else { bug!(\"must have type `*const T` or `*mut T`\") } } }; unsafe { // Declare a symbol `foo` with the desired linkage. let g1 = declare::declare_global(cx, &sym, llty2); llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage)); // Declare an internal global `extern_with_linkage_foo` which // is initialized with the address of `foo`. If `foo` is // discarded during linking (for example, if `foo` has weak // linkage and there are no definitions), then // `extern_with_linkage_foo` will instead be initialized to // zero. let mut real_name = \"_rust_extern_with_linkage_\".to_string(); real_name.push_str(&sym); let g2 = declare::define_global(cx, &real_name, llty).unwrap_or_else(||{ if span.is_some() { cx.sess().span_fatal( span.unwrap(), &format!(\"symbol `{}` is already defined\", &sym) ) } else { bug!(\"symbol `{}` is already defined\", &sym) } }); llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage); llvm::LLVMSetInitializer(g2, g1); g2 } } else { // Generate an external declaration. // FIXME(nagisa): investigate whether it can be changed into define_global declare::declare_global(cx, &sym, llty) } } pub fn codegen_static<'a, 'tcx>( cx: &CodegenCx<'a, 'tcx>, def_id: DefId,"} {"_id":"doc-en-rust-567c2b5d02a723fbedef3eaa51665a4b6afc0ac1083bb3915a6354d86ce4cf4c","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![crate_type = \"rlib\"] #![feature(linkage)] pub fn foo() -> *const() { extern { #[linkage = \"extern_weak\"] static FOO: *const(); } unsafe { FOO } } "} {"_id":"doc-en-rust-25301a74a2b188ce9e6063016a54016b5d19f38478938b159c5b1ea8a53e2d07","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test for issue #18804, #[linkage] does not propagate thorugh generic // functions. Failure results in a linker error. // ignore-asmjs no weak symbol support // ignore-emscripten no weak symbol support // aux-build:lib.rs extern crate lib; fn main() { lib::foo::(); } "} {"_id":"doc-en-rust-9645b58d260d7a93b752bbf04f0b6be63696b6e0c01fc37299478989f063d3b1","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Tup { type T0; type T1; } impl Tup for isize { type T0 = f32; type T1 = (); } fn main() {} "} {"_id":"doc-en-rust-278e618702f4a8813822af7d5e53c603ce3ae1e7c31f08b57e61ac63884915e0","title":"","text":"clean::TypedefItem(ref t) => item_typedef(fmt, self.item, t), clean::MacroItem(ref m) => item_macro(fmt, self.item, m), clean::PrimitiveItem(ref p) => item_primitive(fmt, self.item, p), clean::StaticItem(ref i) => item_static(fmt, self.item, i), clean::ConstantItem(ref c) => item_constant(fmt, self.item, c), _ => Ok(()) } }"} {"_id":"doc-en-rust-e7afe6d75972f759f592694ed4cd9b09ee1d2ddfb7bbf1c7fd41f8d5cde27bca","title":"","text":"return s } fn blank<'a>(s: Option<&'a str>) -> &'a str { match s { Some(s) => s, None => \"\" } } fn shorter<'a>(s: Option<&'a str>) -> &'a str { match s { Some(s) => match s.find_str(\"nn\") {"} {"_id":"doc-en-rust-fe44281601ef46cdad99ffe32b59b5f531ae4cea381950e28eacc3750478bb68","title":"","text":"id = short, name = name)); } struct Initializer<'a>(&'a str, Item<'a>); impl<'a> fmt::Show for Initializer<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Initializer(s, item) = *self; if s.len() == 0 { return Ok(()); } try!(write!(f, \" = \")); if s.contains(\"n\") { match item.href() { Some(url) => { write!(f, \"[definition]\", url) } None => Ok(()), } } else { write!(f, \"{}\", s.as_slice()) } } } match myitem.inner { clean::StaticItem(ref s) | clean::ForeignStaticItem(ref s) => { try!(write!(w, \" {}{}static {}{}: {}{} {}  \", ConciseStability(&myitem.stability), VisSpace(myitem.visibility), MutableSpace(s.mutability), *myitem.name.as_ref().unwrap(), s.type_, Initializer(s.expr.as_slice(), Item { cx: cx, item: myitem }), Markdown(blank(myitem.doc_value())))); } clean::ConstantItem(ref s) => { try!(write!(w, \" {}{}const {}: {}{} {}  \", ConciseStability(&myitem.stability), VisSpace(myitem.visibility), *myitem.name.as_ref().unwrap(), s.type_, Initializer(s.expr.as_slice(), Item { cx: cx, item: myitem }), Markdown(blank(myitem.doc_value())))); } clean::ViewItemItem(ref item) => { match item.inner { clean::ExternCrate(ref name, ref src, _) => {"} {"_id":"doc-en-rust-a2df27e29da610839f330476dea2be54d786d608ea961e628767a93fccebb29e","title":"","text":"write!(w, \"\") } struct Initializer<'a>(&'a str); impl<'a> fmt::Show for Initializer<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Initializer(s) = *self; if s.len() == 0 { return Ok(()); } try!(write!(f, \" = \")); write!(f, \"{}\", s.as_slice()) } } fn item_constant(w: &mut fmt::Formatter, it: &clean::Item, c: &clean::Constant) -> fmt::Result { try!(write!(w, \"

{vis}const  {name}: {typ}{init}
\", vis = VisSpace(it.visibility), name = it.name.as_ref().unwrap().as_slice(), typ = c.type_, init = Initializer(c.expr.as_slice()))); document(w, it) } fn item_static(w: &mut fmt::Formatter, it: &clean::Item, s: &clean::Static) -> fmt::Result { try!(write!(w, \"
{vis}static {mutability} {name}: {typ}{init}
\", vis = VisSpace(it.visibility), mutability = MutableSpace(s.mutability), name = it.name.as_ref().unwrap().as_slice(), typ = s.type_, init = Initializer(s.expr.as_slice()))); document(w, it) }
fn item_function(w: &mut fmt::Formatter, it: &clean::Item, f: &clean::Function) -> fmt::Result { try!(write!(w, \"
{vis}{fn_style}fn "}
{"_id":"doc-en-rust-4a95538432201e87ca988f2705cfd4f08e33471577528b2d1030d031abc4142c","title":"","text":"} }  /// Creates a `Vec` directly from the raw constituents.   /// Creates a `Vec` directly from the raw components of another vector.  ///  /// This is highly unsafe: /// /// - if `ptr` is null, then `length` and `capacity` should be 0 /// - `ptr` must point to an allocation of size `capacity` /// - there must be `length` valid instances of type `T` at the ///   beginning of that allocation /// - `ptr` must be allocated by the default `Vec` allocator   /// This is highly unsafe, due to the number of invariants that aren't checked.  /// /// # Example ///"}
{"_id":"doc-en-rust-89777ca1a307a97e6d350cb970476e70632cc4f0634805ba04e43f9edbaa787d","title":"","text":"use syntax::ast_util::{local_def}; use syntax::attr; use syntax::codemap::Span;  use syntax::parse::token;  use syntax::visit; use syntax::visit::Visitor;"}
{"_id":"doc-en-rust-456eecb7eec26a55daa5bcfafe37bb7ca7ca7bb974d611e8353c924e21bbd65a","title":"","text":"} }  fn reject_shadowing_type_parameters<'tcx>(tcx: &ty::ctxt<'tcx>, span: Span, generics: &ty::Generics<'tcx>) { let impl_params = generics.types.get_slice(subst::TypeSpace).iter() .map(|tp| tp.name).collect::>(); for method_param in generics.types.get_slice(subst::FnSpace).iter() { if impl_params.contains(&method_param.name) { tcx.sess.span_err( span, &*format!(\"type parameter `{}` shadows another type parameter of the same name\", token::get_name(method_param.name))); } } }  impl<'ccx, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'ccx, 'tcx> { fn visit_item(&mut self, i: &ast::Item) { self.check_item_well_formed(i); visit::walk_item(self, i); }  fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl, b: &'v ast::Block, span: Span, id: ast::NodeId) { match fk { visit::FkFnBlock | visit::FkItemFn(..) => {} visit::FkMethod(..) => { match ty::impl_or_trait_item(self.ccx.tcx, local_def(id)) { ty::ImplOrTraitItem::MethodTraitItem(ty_method) => { reject_shadowing_type_parameters(self.ccx.tcx, span, &ty_method.generics) } _ => {} } } } visit::walk_fn(self, fk, fd, b, span) } fn visit_trait_item(&mut self, t: &'v ast::TraitItem) { match t { &ast::TraitItem::ProvidedMethod(_) | &ast::TraitItem::TypeTraitItem(_) => {}, &ast::TraitItem::RequiredMethod(ref method) => { match ty::impl_or_trait_item(self.ccx.tcx, local_def(method.id)) { ty::ImplOrTraitItem::MethodTraitItem(ty_method) => { reject_shadowing_type_parameters( self.ccx.tcx, method.span, &ty_method.generics) } _ => {} } } } visit::walk_trait_item(self, t) }  } pub struct BoundsChecker<'cx,'tcx:'cx> {"}
{"_id":"doc-en-rust-c463ddaa581880478f49f148527ab1669091e14e677b346cb4fd3b8724992c8d","title":"","text":"self.ch == Some(c) }  fn error(&self, reason: ErrorCode) -> Result {   fn error(&self, reason: ErrorCode) -> Result {  Err(SyntaxError(reason, self.line, self.col)) }"}
{"_id":"doc-en-rust-e1f57f4a672b64e03b4d7a90973274aec453430b32451bbd1709d96c224a3617","title":"","text":" // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that shadowed lifetimes generate an error. struct Foo; impl Foo { fn shadow_in_method(&self) {} //~^ ERROR type parameter `T` shadows another type parameter fn not_shadow_in_item(&self) { struct Bar; // not a shadow, separate item fn foo() {} // same } } trait Bar { fn shadow_in_required(&self); //~^ ERROR type parameter `T` shadows another type parameter fn shadow_in_provided(&self) {} //~^ ERROR type parameter `T` shadows another type parameter fn not_shadow_in_required(&self); fn not_shadow_in_provided(&self) {} } fn main() {} "}
{"_id":"doc-en-rust-44fa3d3073952316c3d02b7d96f362eee4837a39678eddf1de2a691220ae8dc0","title":"","text":"// aux-build:issue-13560-1.rs // aux-build:issue-13560-2.rs // aux-build:issue-13560-3.rs  // ignore-pretty FIXME #19501  // ignore-stage1 // Regression test for issue #13560, the test itself is all in the dependent"}
{"_id":"doc-en-rust-b58c6d80a6167028b5034e1080dcba92e8c28849def2d53a103d836b1c930cac","title":"","text":"match probe.kind { InherentImplCandidate(impl_def_id, ref substs) | ExtensionImplCandidate(impl_def_id, _, ref substs, _) => {  let selcx = &mut traits::SelectionContext::new(self.infcx(), self.fcx); let cause = traits::ObligationCause::misc(self.span, self.fcx.body_id);  // Check whether the impl imposes obligations we have to worry about. let impl_generics = ty::lookup_item_type(self.tcx(), impl_def_id).generics; let impl_bounds = impl_generics.to_bounds(self.tcx(), substs);  // FIXME(#20378) assoc type normalization here? // Erase any late-bound regions bound in the impl // which appear in the bounds. let impl_bounds = self.erase_late_bound_regions(&ty::Binder(impl_bounds));   let traits::Normalized { value: impl_bounds, obligations: norm_obligations } = traits::normalize(selcx, cause.clone(), &impl_bounds);  // Convert the bounds into obligations. let obligations =  traits::predicates_for_generics( self.tcx(), traits::ObligationCause::misc(self.span, self.fcx.body_id), &impl_bounds);   traits::predicates_for_generics(self.tcx(), cause.clone(), &impl_bounds);  debug!(\"impl_obligations={}\", obligations.repr(self.tcx())); // Evaluate those obligations to see if they might possibly hold.  let mut selcx = traits::SelectionContext::new(self.infcx(), self.fcx); obligations.all(|o| selcx.evaluate_obligation(o))   obligations.all(|o| selcx.evaluate_obligation(o)) && norm_obligations.iter().all(|o| selcx.evaluate_obligation(o))  } ObjectCandidate(..) |"}
{"_id":"doc-en-rust-528025b5d28509a0972e8631772b2a319994794a7aa43e9734b4cdb77d7990cc","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we handle projection types which wind up important for // resolving methods. This test was reduced from a larger example; the // call to `foo()` at the end was failing to resolve because the // winnowing stage of method resolution failed to handle an associated // type projection. #![feature(associated_types)] trait Hasher { type Output; fn finish(&self) -> Self::Output; } trait Hash { fn hash(&self, h: &mut H); } trait HashState { type Wut: Hasher; fn hasher(&self) -> Self::Wut; } struct SipHasher; impl Hasher for SipHasher { type Output = u64; fn finish(&self) -> u64 { 4 } } impl Hash for int { fn hash(&self, h: &mut SipHasher) {} } struct SipState; impl HashState for SipState { type Wut = SipHasher; fn hasher(&self) -> SipHasher { SipHasher } } struct Map { s: S, } impl Map where S: HashState, ::Wut: Hasher, { fn foo(&self, k: K) where K: Hash< ::Wut> {} } fn foo>(map: &Map) { map.foo(22); } fn main() {} "}
{"_id":"doc-en-rust-9ea7b65a4296f0f96c01e16ec544e2874ba83c1632f6b6deaca86efe4a0c9a83","title":"","text":"(_, \"size_of\") => { let tp_ty = *substs.types.get(FnSpace, 0); let lltp_ty = type_of::type_of(ccx, tp_ty);  C_uint(ccx, machine::llsize_of_real(ccx, lltp_ty))   C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty))  } (_, \"min_align_of\") => { let tp_ty = *substs.types.get(FnSpace, 0);"}
{"_id":"doc-en-rust-41d9a997de6b5ce2ebe6d97fc6f668e2799f79b8271cb519217ed3b2d743ea90","title":"","text":"// Returns, as near as we can figure, the \"real\" size of a type. As in, the // bits in this number of bytes actually carry data related to the datum  // with the type. Not junk, padding, accidentally-damaged words, or // whatever. Rounds up to the nearest byte though, so if you have a 1-bit   // with the type. Not junk, accidentally-damaged words, or whatever. // Note that padding of the type will be included for structs, but not for the // other types (i.e. SIMD types). // Rounds up to the nearest byte though, so if you have a 1-bit  // value, we return 1 here, not 0. Most of rustc works in bytes. Be warned // that LLVM *does* distinguish between e.g. a 1-bit value and an 8-bit value // at the codegen level! In general you should prefer `llbitsize_of_real`"}
{"_id":"doc-en-rust-79853a854b8bae5940234c5a3d95726b3fd18c54a273284079b55e8516cc7898","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(simd)] #![allow(non_camel_case_types)] use std::mem; /// `T` should satisfy `size_of T (mod min_align_of T) === 0` to be stored at `Vec` properly /// Please consult the issue #20460 fn check() { assert_eq!(mem::size_of::() % mem::min_align_of::(), 0) } fn main() { check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); check::(); } #[simd] struct u8x2(u8, u8); #[simd] struct u8x3(u8, u8, u8); #[simd] struct u8x4(u8, u8, u8, u8); #[simd] struct u8x5(u8, u8, u8, u8, u8); #[simd] struct u8x6(u8, u8, u8, u8, u8, u8); #[simd] struct u8x7(u8, u8, u8, u8, u8, u8, u8); #[simd] struct u8x8(u8, u8, u8, u8, u8, u8, u8, u8); #[simd] struct i16x2(i16, i16); #[simd] struct i16x3(i16, i16, i16); #[simd] struct i16x4(i16, i16, i16, i16); #[simd] struct i16x5(i16, i16, i16, i16, i16); #[simd] struct i16x6(i16, i16, i16, i16, i16, i16); #[simd] struct i16x7(i16, i16, i16, i16, i16, i16, i16); #[simd] struct i16x8(i16, i16, i16, i16, i16, i16, i16, i16); #[simd] struct f32x2(f32, f32); #[simd] struct f32x3(f32, f32, f32); #[simd] struct f32x4(f32, f32, f32, f32); #[simd] struct f32x5(f32, f32, f32, f32, f32); #[simd] struct f32x6(f32, f32, f32, f32, f32, f32); #[simd] struct f32x7(f32, f32, f32, f32, f32, f32, f32); #[simd] struct f32x8(f32, f32, f32, f32, f32, f32, f32, f32); "}
{"_id":"doc-en-rust-1e7f44f5f99712d4e9ebb5128580bdf03cb9bd66a64c784143359f8796c60811","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait T : Iterator //~^ ERROR unsupported cyclic reference between types/traits detected {} fn main() {} "}
{"_id":"doc-en-rust-e57a974343effe1492bf6154a4796baa9fe6b38a919d80f86ecb9c37dd338c9a","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Foo {} impl<'a> Foo for Foo+'a {} //~^ ERROR the object type `Foo + 'a` automatically implements the trait `Foo` fn main() {} "}
{"_id":"doc-en-rust-ed899a4bf96bda080df85f9cbbee51b3a907f2c5647a2adf19b0c7da21055ba7","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-tidy-linelength use std::ops::Add; fn main() { let x = &10 as //~^ ERROR the value of the associated type `Output` (from the trait `core::ops::Add`) must be specified &Add; //~^ ERROR the type parameter `RHS` must be explicitly specified in an object type because its default value `Self` references the type `Self` } "}
{"_id":"doc-en-rust-f035e29f043c18da5f44f4b64b7cd1d83900ee60d1b64741f102d860965d791b","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate libc; fn main() { let foo: *mut libc::c_void; let cb: &mut Fn() = unsafe { &mut *(foo as *mut Fn()) //~^ ERROR use of possibly uninitialized variable: `foo` }; } "}
{"_id":"doc-en-rust-f866337939cc132a7b9dfd41f7951c1d508868ee52c36706e85bd7ff53e2e6cc","title":"","text":"use self::Arch::*; #[allow(non_camel_case_types)]  #[derive(Copy)]  pub enum Arch { Armv7, Armv7s,"}
{"_id":"doc-en-rust-211cc30b5607b951f96636600dfd73ca8364f9e1e3bc71ce969841e791f18bc8","title":"","text":"\"-Wl,-syslibroot\".to_string(), get_sdk_root(sdk_name)] }  fn target_cpu(arch: Arch) -> String { match arch { X86_64 => \"x86-64\", _ => \"generic\", }.to_string() }  pub fn opts(arch: Arch) -> TargetOptions { TargetOptions {  cpu: target_cpu(arch),  dynamic_linking: false, executables: true, // Although there is an experimental implementation of LLVM which"}
{"_id":"doc-en-rust-5b23d6c5822ec2d0f4f8dcfa75785262374f4b500fd3cefe274514a5a0502826","title":"","text":"pub fn target() -> Target { let mut base = super::apple_base::opts();  base.cpu = \"x86-64\".to_string();  base.eliminate_frame_pointer = false; base.pre_link_args.push(\"-m64\".to_string());"}
{"_id":"doc-en-rust-0951b070a1547d153db55b10efc54c42e3ef28d96905f984b27c66467642f913","title":"","text":"pub fn target() -> Target { let mut base = super::windows_base::opts();  base.cpu = \"x86-64\".to_string();  // On Win64 unwinding is handled by the OS, so we can link libgcc statically. base.pre_link_args.push(\"-static-libgcc\".to_string()); base.pre_link_args.push(\"-m64\".to_string());"}
{"_id":"doc-en-rust-a488feeb223f332e7cf3befa6fd836ebdf5f644f66d9e1f437fd49f5ce6ad7ac","title":"","text":"pub fn target() -> Target { let mut base = super::dragonfly_base::opts();  base.cpu = \"x86-64\".to_string();  base.pre_link_args.push(\"-m64\".to_string()); Target {"}
{"_id":"doc-en-rust-e82349d06c9d0f3733ffa0c8cfd0391966f8efd2ddb7115f1f9c05eb9a63b70c","title":"","text":"pub fn target() -> Target { let mut base = super::freebsd_base::opts();  base.cpu = \"x86-64\".to_string();  base.pre_link_args.push(\"-m64\".to_string()); Target {"}
{"_id":"doc-en-rust-f7edf9af99d2ea5ae6c1c0da2684eaf734a6e5b7a3d6b9420f7b0de5d3674903","title":"","text":"pub fn target() -> Target { let mut base = super::linux_base::opts();  base.cpu = \"x86-64\".to_string();  base.pre_link_args.push(\"-m64\".to_string()); Target {"}
{"_id":"doc-en-rust-efa350e048daedcc8636596b81abdeeac03aba1d9b962d11779bb4f0a9208ff7","title":"","text":"ext::log_syntax::expand_syntax_ext)); syntax_expanders.insert(intern(\"derive\"), Decorator(box ext::deriving::expand_meta_derive));  syntax_expanders.insert(intern(\"deriving\"), Decorator(box ext::deriving::expand_deprecated_deriving));  if ecfg.enable_quotes { // Quasi-quoting expanders"}
{"_id":"doc-en-rust-be0bd8700990d6b0fb73e9b2d42c47658d226356351f2f6f4abf86ad9e9c8ccd","title":"","text":"pub mod generic;  pub fn expand_deprecated_deriving(cx: &mut ExtCtxt, span: Span, _: &MetaItem, _: &Item, _: Box)>) { cx.span_err(span, \"`deriving` has been renamed to `derive`\"); }  pub fn expand_meta_derive(cx: &mut ExtCtxt, _span: Span, mitem: &MetaItem,"}
{"_id":"doc-en-rust-c72f6db564bb92c8173fdf923146c87bbaa2057b71c11a7d2ee6922615728f2c","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[deriving(Clone)] //~ ERROR `deriving` has been renamed to `derive` struct Foo; fn main() {} "}
{"_id":"doc-en-rust-eb10f8e4be849d19e6276e969acbe51dc50553f4def2f4094ca563971d8fcb23","title":"","text":"use middle::infer::InferCtxt; use middle::ty::{self, ToPredicate, HasTypeFlags, ToPolyTraitRef, TraitRef, Ty}; use middle::ty::fold::TypeFoldable;  use std::collections::HashMap;   use util::nodemap::{FnvHashMap, FnvHashSet};  use std::fmt; use syntax::codemap::Span; use syntax::attr::{AttributeMethods, AttrMetaMethods};"}
{"_id":"doc-en-rust-039c2ea4634f1fe96512e9a34613ca67450f05eee74651b3fd251c32e3fd50d1","title":"","text":"(gen.name.as_str().to_string(), trait_ref.substs.types.get(param, i) .to_string())  }).collect::>();   }).collect::>();  generic_map.insert(\"Self\".to_string(), trait_ref.self_ty().to_string()); let parser = Parser::new(&istring);"}
{"_id":"doc-en-rust-fca38b286c6c17f2ea85918e0e6c55a1b27d18d5eda17ba0408cbee3a56de49e","title":"","text":"\"the trait `{}` cannot be made into an object\", tcx.item_path_str(trait_def_id));  let mut reported_violations = FnvHashSet();  for violation in violations {  if !reported_violations.insert(violation.clone()) { continue; }  match violation { ObjectSafetyViolation::SizedSelf => { tcx.sess.fileline_note("}
{"_id":"doc-en-rust-45ca4613a8dc6c46bc99ed89a3027fe038601d654c84b746ef031ae5cfc4a4cb","title":"","text":"use std::rc::Rc; use syntax::ast;  #[derive(Debug)]   #[derive(Clone, Debug, PartialEq, Eq, Hash)]  pub enum ObjectSafetyViolation<'tcx> { /// Self : Sized declared on the trait SizedSelf,"}
{"_id":"doc-en-rust-bb6a93520a6e22bce1be20a1000c64ee162831a8165ee8337cfd2e33c03b8430","title":"","text":"} }  impl<'tcx> PartialEq for Method<'tcx> { #[inline] fn eq(&self, other: &Self) -> bool { self.def_id == other.def_id } } impl<'tcx> Eq for Method<'tcx> {} impl<'tcx> Hash for Method<'tcx> { #[inline] fn hash(&self, s: &mut H) { self.def_id.hash(s) } }  #[derive(Clone, Copy, Debug)] pub struct AssociatedConst<'tcx> { pub name: Name,"}
{"_id":"doc-en-rust-07e2a87c376380eba1937590132cbdf632da75903ba08115acfb22af02165fd2","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Array: Sized {} fn f(x: &T) { let _ = x //~^ ERROR `Array` cannot be made into an object //~| NOTE the trait cannot require that `Self : Sized` as &Array; //~^ ERROR `Array` cannot be made into an object //~| NOTE the trait cannot require that `Self : Sized` } fn main() {} "}
{"_id":"doc-en-rust-4739ae8f269e940e9fa34f585de61ab01a4a1d18513b6dd80ed4a3d05b1d10bf","title":"","text":"projection_ty: projection_ty, ty: ty_var });  let obligation = Obligation::with_depth(cause, depth+1, projection.to_predicate());   let obligation = Obligation::with_depth( cause, depth + 1, projection.to_predicate());  Normalized { value: ty_var, obligations: vec!(obligation)"}
{"_id":"doc-en-rust-42121c77b3bf7a56eb37e5e08b121c723f19a536b71eb70e6abb7461c55c14c1","title":"","text":"obligations); if projected_ty.has_projection_types() {  let mut normalizer = AssociatedTypeNormalizer::new(selcx, cause, depth);   let mut normalizer = AssociatedTypeNormalizer::new(selcx, cause, depth+1);  let normalized_ty = normalizer.fold(&projected_ty); debug!(\"normalize_projection_type: normalized_ty={:?} depth={}\","}
{"_id":"doc-en-rust-1ed6c5d93365145556b1ee0565d611a9eb22d79a82e8601a21ad35d3670248e4","title":"","text":"/// contexts around the same size. n_llvm_insns: Cell,  /// Depth of the current type-of computation - used to bail out type_of_depth: Cell,  trait_cache: RefCell, traits::Vtable<'tcx, ()>>>, }"}
{"_id":"doc-en-rust-47f0b76478a860c97558775f6aec956f608341694013c7ce89fc5b3e2bca3515","title":"","text":"unwind_resume_hooked: Cell::new(false), intrinsics: RefCell::new(FnvHashMap()), n_llvm_insns: Cell::new(0),  type_of_depth: Cell::new(0),  trait_cache: RefCell::new(FnvHashMap()), };"}
{"_id":"doc-en-rust-792cfb7ea7a08ae1061542709be6d4eeb0820aa8d6c09bd644cff9abb17fbbd3","title":"","text":"obj)) }  pub fn enter_type_of(&self, ty: Ty<'tcx>) -> TypeOfDepthLock<'b, 'tcx> { let current_depth = self.local.type_of_depth.get(); debug!(\"enter_type_of({:?}) at depth {:?}\", ty, current_depth); if current_depth > self.sess().recursion_limit.get() { self.sess().fatal( &format!(\"overflow representing the type `{}`\", ty)) } self.local.type_of_depth.set(current_depth + 1); TypeOfDepthLock(self.local) }  pub fn check_overflow(&self) -> bool { self.shared.check_overflow }"}
{"_id":"doc-en-rust-d9c0702395fa9a5fadc48644aa7e8a6e62847d116ccc96b0e94e98a551f4c56e","title":"","text":"} }  pub struct TypeOfDepthLock<'a, 'tcx: 'a>(&'a LocalCrateContext<'tcx>); impl<'a, 'tcx> Drop for TypeOfDepthLock<'a, 'tcx> { fn drop(&mut self) { self.0.type_of_depth.set(self.0.type_of_depth.get() - 1); } }  /// Declare any llvm intrinsics that you might need fn declare_intrinsic(ccx: &CrateContext, key: &str) -> Option { macro_rules! ifn {"}
{"_id":"doc-en-rust-22c045375c349b83e3f6504eaa23cb64f34d761163d3a6e3728020fda0d4cc50","title":"","text":"} debug!(\"sizing_type_of {:?}\", t);  let _recursion_lock = cx.enter_type_of(t);  let llsizingty = match t.sty { _ if !type_is_sized(cx.tcx(), t) => { Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)"}
{"_id":"doc-en-rust-186e67878d90629ed66a78f3db4ebc3c780a005e2d3987cf504a0be5b5d64005","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Foo { type A; } struct FooStruct; impl Foo for FooStruct { //~^ ERROR overflow evaluating the requirement `::A` type A = ::A; } fn main() {} "}
{"_id":"doc-en-rust-fdb29b24586672cf748f370e2c4a90318ba67237a911ad1b030269796ca67c0b","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern: overflow representing the type `S` trait Mirror { type It; } impl Mirror for T { type It = Self; } struct S(Option<::It>); fn main() { let _s = S(None); } "}
{"_id":"doc-en-rust-87f8812a336e3b5525fd548dc292505eb09270703c99071ecf42f02db26da7c3","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct Outer(T); pub struct Inner<'a> { value: &'a bool } pub trait Trait { type Error; fn ready(self) -> Self::Error; } impl<'a> Trait for Inner<'a> { type Error = Outer>; fn ready(self) -> Outer> { Outer(self) } } fn main() { let value = true; let inner = Inner { value: &value }; assert_eq!(inner.ready().0.value, &value); } "}
{"_id":"doc-en-rust-8a29fe66cc332b1eb046fc7021ff40ab260685b07306541bc0ed9a99238e1e2b","title":"","text":"/// /// ``` /// let a = [1, 2, 3, 4, 5];  /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);   /// assert!(a.iter().fold(0, |acc, &item| acc + item) == 15);  /// ``` #[inline] #[stable(feature = \"rust1\", since = \"1.0.0\")]"}
{"_id":"doc-en-rust-c33189cbe91450bc13174ff116fddbddf58255692634f51f9b09855695512040","title":"","text":"/// instance, it will behave *as if* an instance of the type `T` were /// present for the purpose of various automatic analyses. ///  /// For example, embedding a `PhantomData` will inform the compiler   /// # 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. /// /// ``` /// # trait ResType { fn foo(&self); }; /// # struct ParamType; /// # mod foreign_lib { /// # pub fn new(_: usize) -> *mut () { 42 as *mut () } /// # pub fn do_stuff(_: *mut (), _: usize) {} /// # } /// # fn convert_params(_: ParamType) -> usize { 42 } /// use std::marker::PhantomData; /// use std::mem; /// /// struct ExternalResource { ///    resource_handle: *mut (), ///    resource_type: PhantomData, /// } /// /// impl ExternalResource { ///     fn new() -> ExternalResource { ///         let size_of_res = mem::size_of::(); ///         ExternalResource { ///             resource_handle: foreign_lib::new(size_of_res), ///             resource_type: PhantomData, ///         } ///     } /// ///     fn do_stuff(&self, param: ParamType) { ///         let foreign_params = convert_params(param); ///         foreign_lib::do_stuff(self.resource_handle, foreign_params); ///     } /// } /// ``` /// /// Another example: embedding a `PhantomData` will inform the compiler  /// that one or more instances of the type `T` could be dropped when /// instances of the type itself is dropped, though that may not be /// apparent from the other structure of the type itself. This is"}
{"_id":"doc-en-rust-a90839f4405ef9ebc1435e9d5406430361986f94f663ce1b422df469f046c014","title":"","text":"/// The different kinds of types recognized by the compiler pub enum Ty_ { TyVec(P),  /// A fixed length array (`[T, ..n]`)   /// A fixed length array (`[T; n]`)  TyFixedLengthVec(P, P), /// A raw pointer (`*const T` or `*mut T`) TyPtr(MutTy),"}
{"_id":"doc-en-rust-c616aae5fed8b1f2c22535f301ba4c6c0c7f80d9d0c1b9c0e90991025f18898c","title":"","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":"doc-en-rust-04ad3eb841a10c0144ee3d2fb9467ee4fc2cf6145014fd05e00a91c6fe6279df","title":"","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":"doc-en-rust-55a37e08d63fd3f6d5d71d99c02dd06fe03e36225686d970b29093dd26e1e63f","title":"","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":"doc-en-rust-f5bff31b16b30e39012abb446074ad81101ee9483c8db3b1bd189316a4f480be","title":"","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":"doc-en-rust-1ec3ce660e019cb07c90d91c5f57bf816f9624da641b9cd893f60e0f87a6378a","title":"","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":"doc-en-rust-e31a1078f0434ac8d84ba0538837f151ad2be0bd92d7fd9749d1584018a9324d","title":"","text":" // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. enum Foo { Bar } fn main() { Foo::Bar.a; //~^ ERROR: attempted access of field `a` on type `Foo`, but no field with that name was found } "}
{"_id":"doc-en-rust-8c7895ab4dd244c2c307d49731e38263d0bbd157aa98d348d9ec73048ba098c5","title":"","text":"} }  /// Returns the inner `T` of a `Some(T)`.   /// Moves the value `v` out of the `Option` if the content of the `Option` is a `Some(v)`.  /// /// # Panics ///"}
{"_id":"doc-en-rust-86e06093394db0235b44920b304ae9befe7869fc7a07fc91b3b078b14bb14955","title":"","text":" // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT   // 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. //"}
{"_id":"doc-en-rust-2e3c9ca65531c23843c27f355503a6a04e9c4c59a037fd56ce0e3ba0453e2a25","title":"","text":"use std::num::wrapping::OverflowingOps; use std::cmp::Ordering; use std::collections::hash_map::Entry::Vacant;  use std::{i8, i16, i32, i64};   use std::{i8, i16, i32, i64, u8, u16, u32, u64};  use std::rc::Rc; fn lookup_const<'a>(tcx: &'a ty::ctxt, e: &Expr) -> Option<&'a Expr> {"}
{"_id":"doc-en-rust-41318b337e2287c8f7b8ca0f496d5840b3e3f533d89183225770bafe31e50e6c","title":"","text":"Ok(const_uint((!a).wrapping_add(1))) }  fn const_uint_not(a: u64, opt_ety: Option) -> const_val { let mask = match opt_ety { Some(UintTy::U8) => u8::MAX as u64, Some(UintTy::U16) => u16::MAX as u64, Some(UintTy::U32) => u32::MAX as u64, None | Some(UintTy::U64) => u64::MAX, }; const_uint(!a & mask) }  macro_rules! overflow_checking_body { ($a:ident, $b:ident, $ety:ident, $overflowing_op:ident, lhs: $to_8_lhs:ident $to_16_lhs:ident $to_32_lhs:ident,"}
{"_id":"doc-en-rust-5d0ab9996a398dfcd6b50fd2ec6542a0c60696487de53c6e2bb71b778fbb82d6","title":"","text":"ast::ExprUnary(ast::UnNot, ref inner) => { match try!(eval_const_expr_partial(tcx, &**inner, ety)) { const_int(i) => const_int(!i),  const_uint(i) => const_uint(!i),   const_uint(i) => const_uint_not(i, expr_uint_type),  const_bool(b) => const_bool(!b), const_str(_) => signal!(e, NotOnString), const_float(_) => signal!(e, NotOnFloat),"}
{"_id":"doc-en-rust-353a5768fce6b2d8df7b8383ac9a7bcd5dbf9a0ec716a0ae213577c078e28993","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0  or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. const U8_MAX_HALF: u8 = !0u8 / 2; const U16_MAX_HALF: u16 = !0u16 / 2; const U32_MAX_HALF: u32 = !0u32 / 2; const U64_MAX_HALF: u64 = !0u64 / 2; fn main() { assert_eq!(U8_MAX_HALF, 0x7f); assert_eq!(U16_MAX_HALF, 0x7fff); assert_eq!(U32_MAX_HALF, 0x7fff_ffff); assert_eq!(U64_MAX_HALF, 0x7fff_ffff_ffff_ffff); } "}
{"_id":"doc-en-rust-5a10ff57a83e930409cd34135652215518fe464c1e138577b290a49535e2910b","title":"","text":"let mut where_predicates = where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect::>();  // Type parameters have a Sized bound by default unless removed with // ?Sized. Scan through the predicates and mark any type parameter with // a Sized bound, removing the bounds as we find them.   // In the surface language, all type parameters except `Self` have an // implicit `Sized` bound unless removed with `?Sized`. // However, in the list of where-predicates below, `Sized` appears like a // normal bound: It's either present (the type is sized) or // absent (the type is unsized) but never *maybe* (i.e. `?Sized`).  //  // Note that associated types also have a sized bound by default, but we   // This is unsuitable for rendering. // Thus, as a first step remove all `Sized` bounds that should be implicit. // // Note that associated types also have an implicit `Sized` bound but we  // don't actually know the set of associated types right here so that's  // handled in cleaning associated types   // handled when cleaning associated types.  let mut sized_params = FxHashSet::default();  where_predicates.retain(|pred| match *pred { WherePredicate::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => { if bounds.iter().any(|b| b.is_sized_bound(cx)) { sized_params.insert(*g); false } else { true }   where_predicates.retain(|pred| { if let WherePredicate::BoundPredicate { ty: Generic(g), bounds, .. } = pred && *g != kw::SelfUpper && bounds.iter().any(|b| b.is_sized_bound(cx)) { sized_params.insert(*g); false } else { true  }  _ => true,  });  // Run through the type parameters again and insert a ?Sized // unbound for any we didn't find to be Sized.   // As a final step, go through the type parameters again and insert a // `?Sized` bound for each one we didn't find to be `Sized`.  for tp in &stripped_params {  if matches!(tp.kind, types::GenericParamDefKind::Type { .. }) && !sized_params.contains(&tp.name)   if let types::GenericParamDefKind::Type { .. } = tp.kind && !sized_params.contains(&tp.name)  { where_predicates.push(WherePredicate::BoundPredicate { ty: Type::Generic(tp.name),"}
{"_id":"doc-en-rust-4b949a7fc4e5c4a571898f63b0b5bb234602fef107e80869e08d9e2f022c97e2","title":"","text":" #![crate_type = \"lib\"] pub trait U/*: ?Sized */ { fn modified(self) -> Self where Self: Sized { self } fn touch(&self)/* where Self: ?Sized */{} } pub trait S: Sized {} "}
{"_id":"doc-en-rust-e51ae2a4ab4aa7a540d5488b0640f363144d931c7351ff1427ed1829b2685344","title":"","text":" 

fn touch(&self)

No newline at end of file"} {"_id":"doc-en-rust-f2f099824f423f3d945108b774c2b8706bb4743e7267a133f4f687d85762e985","title":"","text":" #![crate_type = \"lib\"] #![crate_name = \"usr\"] // aux-crate:issue_24183=issue-24183.rs // edition: 2021 // @has usr/trait.U.html // @has - '//*[@class=\"item-decl\"]' \"pub trait U {\" // @has - '//*[@id=\"method.modified\"]' // \"fn modified(self) -> Self // where // Self: Sized\" // @snapshot method_no_where_self_sized - '//*[@id=\"method.touch\"]/*[@class=\"code-header\"]' pub use issue_24183::U; // @has usr/trait.S.html // @has - '//*[@class=\"item-decl\"]' 'pub trait S: Sized {' pub use issue_24183::S; "} {"_id":"doc-en-rust-e2c94ba8d51e77083996e436c6b14fbcec822a2907325c26996529ce86b7c039","title":"","text":"AutoTraitFinder { cx } } fn generate_for_trait( &mut self, ty: Ty<'tcx>, trait_def_id: DefId, param_env: ty::ParamEnv<'tcx>, param_env_def_id: DefId, f: &auto_trait::AutoTraitFinder<'tcx>, // If this is set, show only negative trait implementations, not positive ones. discard_positive_impl: bool, ) -> Option { let tcx = self.cx.tcx; let trait_ref = ty::TraitRef { def_id: trait_def_id, substs: tcx.mk_substs_trait(ty, &[]) }; if !self.cx.generated_synthetics.borrow_mut().insert((ty, trait_def_id)) { debug!(\"get_auto_trait_impl_for({:?}): already generated, aborting\", trait_ref); return None; } let result = f.find_auto_trait_generics(ty, param_env, trait_def_id, |infcx, info| { let region_data = info.region_data; let names_map = tcx .generics_of(param_env_def_id) .params .iter() .filter_map(|param| match param.kind { ty::GenericParamDefKind::Lifetime => Some(param.name), _ => None, }) .map(|name| (name, Lifetime(name))) .collect(); let lifetime_predicates = Self::handle_lifetimes(®ion_data, &names_map); let new_generics = self.param_env_to_generics( infcx.tcx, param_env_def_id, info.full_user_env, lifetime_predicates, info.vid_to_region, ); debug!( \"find_auto_trait_generics(param_env_def_id={:?}, trait_def_id={:?}): finished with {:?}\", param_env_def_id, trait_def_id, new_generics ); new_generics }); let negative_polarity; let new_generics = match result { AutoTraitResult::PositiveImpl(new_generics) => { negative_polarity = false; if discard_positive_impl { return None; } new_generics } AutoTraitResult::NegativeImpl => { negative_polarity = true; // For negative impls, we use the generic params, but *not* the predicates, // from the original type. Otherwise, the displayed impl appears to be a // conditional negative impl, when it's really unconditional. // // For example, consider the struct Foo(*mut T). Using // the original predicates in our impl would cause us to generate // `impl !Send for Foo`, which makes it appear that Foo // implements Send where T is not copy. // // Instead, we generate `impl !Send for Foo`, which better // expresses the fact that `Foo` never implements `Send`, // regardless of the choice of `T`. let params = (tcx.generics_of(param_env_def_id), ty::GenericPredicates::default()) .clean(self.cx) .params; Generics { params, where_predicates: Vec::new() } } AutoTraitResult::ExplicitImpl => return None, }; Some(Item { source: Span::dummy(), name: None, attrs: Default::default(), visibility: Inherited, def_id: self.cx.next_def_id(param_env_def_id.krate), kind: box ImplItem(Impl { unsafety: hir::Unsafety::Normal, generics: new_generics, provided_trait_methods: Default::default(), trait_: Some(trait_ref.clean(self.cx).get_trait_type().unwrap()), for_: ty.clean(self.cx), items: Vec::new(), negative_polarity, synthetic: true, blanket_impl: None, }), }) } // FIXME(eddyb) figure out a better way to pass information about // parametrization of `ty` than `param_env_def_id`. crate fn get_auto_trait_impls(&mut self, ty: Ty<'tcx>, param_env_def_id: DefId) -> Vec {"} {"_id":"doc-en-rust-45cb89551beefc274876cc8f84699202f9b7388d4246d736090704c39c7b62c3","title":"","text":"debug!(\"get_auto_trait_impls({:?})\", ty); let auto_traits: Vec<_> = self.cx.auto_traits.iter().cloned().collect(); auto_traits let mut auto_traits: Vec = auto_traits .into_iter() .filter_map(|trait_def_id| { let trait_ref = ty::TraitRef { def_id: trait_def_id, substs: tcx.mk_substs_trait(ty, &[]) }; if !self.cx.generated_synthetics.borrow_mut().insert((ty, trait_def_id)) { debug!(\"get_auto_trait_impl_for({:?}): already generated, aborting\", trait_ref); return None; } let result = f.find_auto_trait_generics(ty, param_env, trait_def_id, |infcx, info| { let region_data = info.region_data; let names_map = tcx .generics_of(param_env_def_id) .params .iter() .filter_map(|param| match param.kind { ty::GenericParamDefKind::Lifetime => Some(param.name), _ => None, }) .map(|name| (name, Lifetime(name))) .collect(); let lifetime_predicates = Self::handle_lifetimes(®ion_data, &names_map); let new_generics = self.param_env_to_generics( infcx.tcx, param_env_def_id, info.full_user_env, lifetime_predicates, info.vid_to_region, ); debug!( \"find_auto_trait_generics(param_env_def_id={:?}, trait_def_id={:?}): finished with {:?}\", param_env_def_id, trait_def_id, new_generics ); new_generics }); let negative_polarity; let new_generics = match result { AutoTraitResult::PositiveImpl(new_generics) => { negative_polarity = false; new_generics } AutoTraitResult::NegativeImpl => { negative_polarity = true; // For negative impls, we use the generic params, but *not* the predicates, // from the original type. Otherwise, the displayed impl appears to be a // conditional negative impl, when it's really unconditional. // // For example, consider the struct Foo(*mut T). Using // the original predicates in our impl would cause us to generate // `impl !Send for Foo`, which makes it appear that Foo // implements Send where T is not copy. // // Instead, we generate `impl !Send for Foo`, which better // expresses the fact that `Foo` never implements `Send`, // regardless of the choice of `T`. let params = (tcx.generics_of(param_env_def_id), ty::GenericPredicates::default()) .clean(self.cx) .params; Generics { params, where_predicates: Vec::new() } } AutoTraitResult::ExplicitImpl => return None, }; Some(Item { source: Span::dummy(), name: None, attrs: Default::default(), visibility: Inherited, def_id: self.cx.next_def_id(param_env_def_id.krate), kind: box ImplItem(Impl { unsafety: hir::Unsafety::Normal, generics: new_generics, provided_trait_methods: Default::default(), trait_: Some(trait_ref.clean(self.cx).get_trait_type().unwrap()), for_: ty.clean(self.cx), items: Vec::new(), negative_polarity, synthetic: true, blanket_impl: None, }), }) self.generate_for_trait(ty, trait_def_id, param_env, param_env_def_id, &f, false) }) .collect() .collect(); // We are only interested in case the type *doesn't* implement the Sized trait. if !ty.is_sized(self.cx.tcx.at(rustc_span::DUMMY_SP), param_env) { // In case `#![no_core]` is used, `sized_trait` returns nothing. if let Some(item) = self.cx.tcx.lang_items().sized_trait().and_then(|sized_trait_did| { self.generate_for_trait(ty, sized_trait_did, param_env, param_env_def_id, &f, true) }) { auto_traits.push(item); } } auto_traits } fn get_lifetime(region: Region<'_>, names_map: &FxHashMap) -> Lifetime {"} {"_id":"doc-en-rust-5a3a7f73cb6f7cb0aaf296b09ae9396ece3bb27ac6fa4108512dfb8b201e26b5","title":"","text":"}; use crate::clean; use crate::clean::inline::build_external_trait; use crate::clean::{AttributesExt, MAX_DEF_IDX}; use crate::config::{Options as RustdocOptions, RenderOptions}; use crate::config::{OutputFormat, RenderInfo};"} {"_id":"doc-en-rust-95792df943b8d29c62b9a2d971259aca1a42e5d521e79567069001f80d2ce613","title":"","text":"module_trait_cache: RefCell::new(FxHashMap::default()), cache: Cache::default(), }; // Small hack to force the Sized trait to be present. // // Note that in case of `#![no_core]`, the trait is not available. if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() { let mut sized_trait = build_external_trait(&mut ctxt, sized_trait_did); sized_trait.is_auto = true; ctxt.external_traits.borrow_mut().insert(sized_trait_did, sized_trait); } debug!(\"crate: {:?}\", tcx.hir().krate()); let mut krate = tcx.sess.time(\"clean_crate\", || clean::krate(&mut ctxt));"} {"_id":"doc-en-rust-67f2626c60586a76af5511ad68dc81d1f8aa4068c367350d637c7ef88a631d71","title":"","text":" #![crate_name = \"foo\"] // @has foo/struct.Bar.html // @!has - '//h3[@id=\"impl-Sized\"]' pub struct Bar { a: u16, } // @has foo/struct.Foo.html // @!has - '//h3[@id=\"impl-Sized\"]' pub struct Foo(T); // @has foo/struct.Unsized.html // @has - '//h3[@id=\"impl-Sized\"]/code' 'impl !Sized for Unsized' pub struct Unsized { data: [u8], } "} {"_id":"doc-en-rust-1e209d5b6e00231e3efc6f5d731064bb84ba0e17102e26bc091cad3768f69ea8","title":"","text":"// except according to those terms. // xfail-test fn foo() -> &'a int { fn foo<'a>() -> &'a int { //~ ERROR unconstrained region return &x; } static x: int = 5;"} {"_id":"doc-en-rust-8fed32ecb5ee462031326e921409a93e814fe00c0a4ae796dce29dbca6b4aaf1","title":"","text":"BOOL_OPTIONS=\"\" VAL_OPTIONS=\"\" opt debug 0 \"debug mode\" opt debug 0 \"debug mode; disables optimization unless `--enable-optimize` given\" opt valgrind 0 \"run tests with valgrind (memcheck by default)\" opt helgrind 0 \"run tests with helgrind instead of memcheck\" opt valgrind-rpass 1 \"run rpass-valgrind tests with valgrind\""} {"_id":"doc-en-rust-0c70ce0b8262c36129d25e4524164d2cd9158ad4898c334846c76a4dc76ef0d7","title":"","text":" # `char_error_internals` This feature is internal to the Rust compiler and is not intended for general use. ------------------------ "} {"_id":"doc-en-rust-dba9de2de9c5f1e768e4ca00e78a6c4133fd3f62ac91bd04075bf8c50c2b14cd","title":"","text":"use convert::TryFrom; use fmt::{self, Write}; use slice; use str::from_utf8_unchecked_mut; use str::{from_utf8_unchecked_mut, FromStr}; use iter::FusedIterator; use mem::transmute;"} {"_id":"doc-en-rust-f3737eb375c8cfd516f76fdd8cf03ff32b1ce9d59678c7c952e5fc30432d6b6e","title":"","text":"} } /// An error which can be returned when parsing a char. #[stable(feature = \"char_from_str\", since = \"1.19.0\")] #[derive(Clone, Debug)] pub struct ParseCharError { kind: CharErrorKind, } impl ParseCharError { #[unstable(feature = \"char_error_internals\", reason = \"this method should not be available publicly\", issue = \"0\")] #[doc(hidden)] pub fn __description(&self) -> &str { match self.kind { CharErrorKind::EmptyString => { \"cannot parse char from empty string\" }, CharErrorKind::TooManyChars => \"too many characters in string\" } } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum CharErrorKind { EmptyString, TooManyChars, } #[stable(feature = \"char_from_str\", since = \"1.19.0\")] impl fmt::Display for ParseCharError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.__description().fmt(f) } } #[stable(feature = \"char_from_str\", since = \"1.19.0\")] impl FromStr for char { type Err = ParseCharError; #[inline] fn from_str(s: &str) -> Result { let mut chars = s.chars(); match (chars.next(), chars.next()) { (None, _) => { Err(ParseCharError { kind: CharErrorKind::EmptyString }) }, (Some(c), None) => Ok(c), _ => { Err(ParseCharError { kind: CharErrorKind::TooManyChars }) } } } } #[unstable(feature = \"try_from\", issue = \"33417\")] impl TryFrom for char { type Error = CharTryFromError;"} {"_id":"doc-en-rust-3271f02c7cf2b4503bd56db881bcf0c3cc940825dab2fa4acb69d28d011cfe99","title":"","text":"use std::{char,str}; use std::convert::TryFrom; use std::str::FromStr; #[test] fn test_convert() {"} {"_id":"doc-en-rust-1f4626a369d47bd4168a58d0a0517380dca0e8326553f35aa675f7ba9b43f5a5","title":"","text":"} #[test] fn test_from_str() { assert_eq!(char::from_str(\"a\").unwrap(), 'a'); assert_eq!(char::try_from(\"a\").unwrap(), 'a'); assert_eq!(char::from_str(\"0\").unwrap(), '0'); assert_eq!(char::from_str(\"u{D7FF}\").unwrap(), 'u{d7FF}'); assert!(char::from_str(\"\").is_err()); assert!(char::from_str(\"abc\").is_err()); } #[test] fn test_is_lowercase() { assert!('a'.is_lowercase()); assert!('ö'.is_lowercase());"} {"_id":"doc-en-rust-3c73eac32577e89af9301c99aaf15f9d21a72e89b21e70a995ce4e44f51c0fb1","title":"","text":"} } #[stable(feature = \"char_from_str\", since = \"1.19.0\")] impl Error for char::ParseCharError { fn description(&self) -> &str { self.__description() } } // copied from any.rs impl Error + 'static { /// Returns true if the boxed type is the same as `T`"} {"_id":"doc-en-rust-c3d6eb4707e3cf1923d958404291e63f4e205cb8db1459e20aef2e05d21f6769","title":"","text":"#![feature(cfg_target_thread_local)] #![feature(cfg_target_vendor)] #![feature(char_escape_debug)] #![feature(char_error_internals)] #![feature(char_internals)] #![feature(collections)] #![feature(collections_range)]"} {"_id":"doc-en-rust-7faa806c96567b80baad151d77dfe1a5b9f2d2d3b5edb8f75d1d426f704976e0","title":"","text":"pub use core::char::{MAX, from_digit, from_u32, from_u32_unchecked}; #[stable(feature = \"rust1\", since = \"1.0.0\")] pub use core::char::{EscapeDebug, EscapeDefault, EscapeUnicode}; #[stable(feature = \"char_from_str\", since = \"1.19.0\")] pub use core::char::ParseCharError; // unstable reexports #[unstable(feature = \"try_from\", issue = \"33417\")]"} {"_id":"doc-en-rust-82166f32f9b841da7ef4b3cf145d348714de808ee180cc8c3169d5e23401cf4c","title":"","text":"use types::os::arch::posix88::{uid_t}; pub type nlink_t = u16; pub type blksize_t = i32; pub type blksize_t = u32; pub type blkcnt_t = i64; pub type fflags_t = u32; #[repr(C)]"} {"_id":"doc-en-rust-ea2e675d94a44e7fe0db1a7eb065521c265607c1d8eff30312dcb69deeec47aa","title":"","text":"pub st_lspare: int32_t, pub st_birthtime: time_t, pub st_birthtime_nsec: c_long, pub __unused: [uint8_t; 2], pub __unused: [u8; 8], } #[repr(C)]"} {"_id":"doc-en-rust-0a37d4b08472faaaaef262de78f9fc737378030a5a9f69a0a8ce4975d428256d","title":"","text":"use types::os::arch::posix88::{uid_t}; pub type nlink_t = u16; pub type blksize_t = i64; pub type blksize_t = u32; pub type blkcnt_t = i64; pub type fflags_t = u32; #[repr(C)]"} {"_id":"doc-en-rust-07527ed9885288181fb588821e709c29e6f0fb8768e2303c150727745b0f1150","title":"","text":"pub st_lspare: int32_t, pub st_birthtime: time_t, pub st_birthtime_nsec: c_long, pub __unused: [uint8_t; 2], } #[repr(C)]"} {"_id":"doc-en-rust-7bc38d1ca23130f61e2398eda3efbe55e2d412b00945299db986f6e004bb6bce","title":"","text":"#![stable(feature = \"raw_ext\", since = \"1.1.0\")] use os::raw::c_long; use os::unix::raw::{uid_t, gid_t}; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type off_t = i64; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type dev_t = u32; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type ino_t = u32; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type mode_t = u16; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type nlink_t = u16; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type blksize_t = u32; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type blkcnt_t = i64; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type fflags_t = u32; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type blkcnt_t = i64; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type blksize_t = i64; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type dev_t = u32; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type fflags_t = u32; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type ino_t = u32; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type mode_t = u16; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type nlink_t = u16; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type off_t = i64; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type time_t = i64; #[doc(inline)] pub use self::arch::{stat, time_t}; #[repr(C)] #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub struct stat { #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_dev: dev_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_ino: ino_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_mode: mode_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_nlink: nlink_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_uid: uid_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_gid: gid_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_rdev: dev_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_atime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_atime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_mtime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_mtime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_ctime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_ctime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_size: off_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_blocks: blkcnt_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_blksize: blksize_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_flags: fflags_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_gen: u32, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_lspare: i32, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_birthtime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_birthtime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub __unused: [u8; 2], #[cfg(target_arch = \"x86\")] mod arch { use super::{off_t, dev_t, ino_t, mode_t, nlink_t, blksize_t, blkcnt_t, fflags_t}; use os::raw::c_long; use os::unix::raw::{uid_t, gid_t}; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type time_t = i32; #[repr(C)] #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub struct stat { #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_dev: dev_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_ino: ino_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_mode: mode_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_nlink: nlink_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_uid: uid_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_gid: gid_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_rdev: dev_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_atime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_atime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_mtime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_mtime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_ctime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_ctime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_size: off_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_blocks: blkcnt_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_blksize: blksize_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_flags: fflags_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_gen: u32, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_lspare: i32, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_birthtime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_birthtime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub __unused: [u8; 8], } } #[cfg(target_arch = \"x86_64\")] mod arch { use super::{off_t, dev_t, ino_t, mode_t, nlink_t, blksize_t, blkcnt_t, fflags_t}; use os::raw::c_long; use os::unix::raw::{uid_t, gid_t}; #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub type time_t = i64; #[repr(C)] #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub struct stat { #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_dev: dev_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_ino: ino_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_mode: mode_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_nlink: nlink_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_uid: uid_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_gid: gid_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_rdev: dev_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_atime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_atime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_mtime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_mtime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_ctime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_ctime_nsec: c_long, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_size: off_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_blocks: blkcnt_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_blksize: blksize_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_flags: fflags_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_gen: u32, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_lspare: i32, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_birthtime: time_t, #[stable(feature = \"raw_ext\", since = \"1.1.0\")] pub st_birthtime_nsec: c_long, } } "} {"_id":"doc-en-rust-cce43e4c312594f0c6ac54bb8049891deff25f0eca21c8bc2218848336f2b6ab","title":"","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":"doc-en-rust-d90bf08a72563bfbd4e879036090a292f8621f359faf9177559f4b6faa4cb9b3","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::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":"doc-en-rust-b48d06aabda7f9b520466ad78c1c6b91e45317e689dadc9b30938abe3b1cb05c","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. 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":"doc-en-rust-99282afac793c6e456ae1f2fa3818f71d1adc43ed5619fbd80bd5003d713c58d","title":"","text":"## Macros ```antlr expr_macro_rules : \"macro_rules\" '!' ident '(' macro_rule * ')' ; expr_macro_rules : \"macro_rules\" '!' ident '(' macro_rule * ')' ';' | \"macro_rules\" '!' ident '{' macro_rule * '}' ; macro_rule : '(' matcher * ')' \"=>\" '(' transcriber * ')' ';' ; matcher : '(' matcher * ')' | '[' matcher * ']' | '{' matcher * '}' | '$' ident ':' ident"} {"_id":"doc-en-rust-d784fa2bce03729a439ef87c9ba1242dda68f9596b7a69a3d36869f3871f4561","title":"","text":"use dep_graph::DepGraph; use middle::infer::InferCtxt; use middle::ty::{self, Ty, TypeFoldable}; use middle::ty::{self, Ty, TypeFoldable, ToPolyTraitRef}; use rustc_data_structures::obligation_forest::{Backtrace, ObligationForest, Error}; use std::iter; use syntax::ast;"} {"_id":"doc-en-rust-8c8bb1ca461fa46b5986efd86b093b0059fc42dc66712d3dda1fb6fc7956b329","title":"","text":"} } /// Return the set of type variables contained in a trait ref fn trait_ref_type_vars<'a, 'tcx>(selcx: &mut SelectionContext<'a, 'tcx>, t: ty::PolyTraitRef<'tcx>) -> Vec> { t.skip_binder() // ok b/c this check doesn't care about regions .input_types() .iter() .map(|t| selcx.infcx().resolve_type_vars_if_possible(t)) .filter(|t| t.has_infer_types()) .flat_map(|t| t.walk()) .filter(|t| match t.sty { ty::TyInfer(_) => true, _ => false }) .collect() } /// Processes a predicate obligation and returns either: /// - `Ok(Some(v))` if the predicate is true, presuming that `v` are also true /// - `Ok(None)` if we don't have enough info to be sure"} {"_id":"doc-en-rust-c2fced8f7288c40b65f204d9ab8011f5b4336e2eea06ffc121e48f59f96eebed","title":"","text":"// doing more work yet if !pending_obligation.stalled_on.is_empty() { if pending_obligation.stalled_on.iter().all(|&ty| { let resolved_ty = selcx.infcx().resolve_type_vars_if_possible(&ty); let resolved_ty = selcx.infcx().shallow_resolve(&ty); resolved_ty == ty // nothing changed here }) { debug!(\"process_predicate: pending obligation {:?} still stalled on {:?}\","} {"_id":"doc-en-rust-4bb3080ec0ec37ce82aee74e3a95339a8e6c30511ab1ba7a69b82e5a50c5dfb9","title":"","text":"// of its type, and those types are resolved at // the same time. pending_obligation.stalled_on = data.skip_binder() // ok b/c this check doesn't care about regions .input_types() .iter() .map(|t| selcx.infcx().resolve_type_vars_if_possible(t)) .filter(|t| t.has_infer_types()) .flat_map(|t| t.walk()) .filter(|t| match t.sty { ty::TyInfer(_) => true, _ => false }) .collect(); trait_ref_type_vars(selcx, data.to_poly_trait_ref()); debug!(\"process_predicate: pending obligation {:?} now stalled on {:?}\", selcx.infcx().resolve_type_vars_if_possible(obligation),"} {"_id":"doc-en-rust-099309a69a6129b0f60e5c184d05c73e0fa04fdaf72d0209a5a1d7859b49eb07","title":"","text":"ty::Predicate::Projection(ref data) => { let project_obligation = obligation.with(data.clone()); match project::poly_project_and_unify_type(selcx, &project_obligation) { Ok(None) => { pending_obligation.stalled_on = trait_ref_type_vars(selcx, data.to_poly_trait_ref()); Ok(None) } Ok(v) => Ok(v), Err(e) => Err(CodeProjectionError(e)) }"} {"_id":"doc-en-rust-9c82590bb32940596cafd2e7898cb5872d1ef035a1b1dbf355e6461f823a9688","title":"","text":"} ty::Predicate::WellFormed(ty) => { Ok(ty::wf::obligations(selcx.infcx(), obligation.cause.body_id, ty, obligation.cause.span)) match ty::wf::obligations(selcx.infcx(), obligation.cause.body_id, ty, obligation.cause.span) { None => { pending_obligation.stalled_on = vec![ty]; Ok(None) } s => Ok(s) } } } }"} {"_id":"doc-en-rust-8bdd64b0c570332837fe78e9fe1c5cd5ddb5852128f265cff60302b320b59390","title":"","text":"impl<'tcx> ToPolyTraitRef<'tcx> for PolyTraitPredicate<'tcx> { fn to_poly_trait_ref(&self) -> PolyTraitRef<'tcx> { self.map_bound_ref(|trait_pred| trait_pred.trait_ref.clone()) self.map_bound_ref(|trait_pred| trait_pred.trait_ref) } }"} {"_id":"doc-en-rust-8e0dbc24296bcdc5ef2df3ba9da32c48fc1632a98ab8d5ec4d81c869ba4a6cf6","title":"","text":"// This is because here `self` has a `Binder` and so does our // return value, so we are preserving the number of binding // levels. ty::Binder(self.0.projection_ty.trait_ref.clone()) ty::Binder(self.0.projection_ty.trait_ref) } }"} {"_id":"doc-en-rust-b988ab557ae6a9c9282d51c341e0978c283767e077fef43894a689c4a526845a","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { macro_rules! f { () => { 0 + 0 } } // 16 per line f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!();f!(); } "} {"_id":"doc-en-rust-b657d052b3941171aa991f82ab0f3960ea2e5dc8dcfb7e7c9bb485d158c4962f","title":"","text":"tts: vec![TtToken(sp, token::Ident(token::str_to_ident(\"doc\"), token::Plain)), TtToken(sp, token::Eq), TtToken(sp, token::Literal(token::Str_(name), None))], TtToken(sp, token::Literal(token::StrRaw(name, 0), None))], close_span: sp, })) }"} {"_id":"doc-en-rust-4af76201cfc106df52f64774e84ee890ed0d5d17a6fb7f1d9d391ae117d7c2e6","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // When expanding a macro, documentation attributes (including documentation comments) must be // passed \"as is\" without being parsed. Otherwise, some text will be incorrectly interpreted as // escape sequences, leading to an ICE. // // Related issues: #25929, #25943 macro_rules! homura { (#[$x:meta]) => () } homura! { /// madoka x41 } fn main() { } "} {"_id":"doc-en-rust-242bd8c7cb90e923d9eab73cf768651597c279d3bd7359b178f4f1ef433bee2e","title":"","text":" // ignore-tidy-linelength // regression test for #26376 trait Foo { fn foo(&self) -> [u8]; } fn foo(f: Option<&dyn Foo>) { if let Some(f) = f { let _ = f.foo(); //~^ ERROR cannot move a value of type [u8]: the size of [u8] cannot be statically determined } } fn main() { foo(None) } "} {"_id":"doc-en-rust-b08e9f2929a7ae72963ca0e00e6677c35e8ea3e4c1dbd38cc35c4cdc7ff98a84","title":"","text":" error[E0161]: cannot move a value of type [u8]: the size of [u8] cannot be statically determined --> $DIR/return-unsized-from-trait-method.rs:11:17 | LL | let _ = f.foo(); | ^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0161`. "} {"_id":"doc-en-rust-849db4f23288620883d0e3cf5984d29b1640d4114a5547ab3c0332e2cfe20262","title":"","text":"//! //! where `&.T` and `*T` are references of either mutability, //! and where unsize_kind(`T`) is the kind of the unsize info //! in `T` - a vtable or a length (or `()` if `T: Sized`). //! in `T` - the vtable for a trait definition (e.g. `fmt::Display` or //! `Iterator`, not `Iterator`) or a length (or `()` if `T: Sized`). //! //! Note that lengths are not adjusted when casting raw slices - //! `T: *const [u16] as *const [u8]` creates a slice that only includes //! half of the original memory. //! //! Casting is not transitive, that is, even if `e as U1 as U2` is a valid //! expression, `e as U2` is not necessarily so (in fact it will only be valid if"} {"_id":"doc-en-rust-2a2fdf3f7742792676600bef3d44bb18ed3f3aad8f45ceef8ed006c6564b2863","title":"","text":"/// fat pointers if their unsize-infos have the same kind. #[derive(Copy, Clone, PartialEq, Eq)] enum UnsizeKind<'tcx> { Vtable, Vtable(ast::DefId), Length, /// The unsize info of this projection OfProjection(&'tcx ty::ProjectionTy<'tcx>),"} {"_id":"doc-en-rust-43d6176dfd60f671c5d92f18a135aa25484240480aa8f2f15fe3586a19084fe4","title":"","text":"-> Option> { match t.sty { ty::TySlice(_) | ty::TyStr => Some(UnsizeKind::Length), ty::TyTrait(_) => Some(UnsizeKind::Vtable), ty::TyTrait(ref tty) => Some(UnsizeKind::Vtable(tty.principal_def_id())), ty::TyStruct(did, substs) => { match ty::struct_fields(fcx.tcx(), did, substs).pop() { None => None,"} {"_id":"doc-en-rust-3c9f20479e4729f2c52d0e6acfff91eba74fc7076bdd18c15458648cf7f46b46","title":"","text":"trait Foo { fn foo(&self) {} } impl Foo for T {} trait Bar { fn foo(&self) {} } impl Bar for T {} enum E { A, B }"} {"_id":"doc-en-rust-8ab0f4db7424069e14bdfea640119c8c0f4f910ae7d9f73a892eb5a29109256f","title":"","text":"// check no error cascade let _ = main.f as *const u32; //~ ERROR attempted access of field let cf: *const Foo = &0; let _ = cf as *const [u8]; //~ ERROR vtable kinds let _ = cf as *const Bar; //~ ERROR vtable kinds }"} {"_id":"doc-en-rust-a2825d467fffd45c7b54807b4955ee97440bf6e99c995153a06ea1623a15e8c2","title":"","text":"impl Foo for u32 { fn foo(&self, _: u32) -> u32 { self+43 } } impl Bar for () {} unsafe fn fool<'a>(t: *const (Foo+'a)) -> u32 { let bar : *const Bar = t as *const Bar; unsafe fn round_trip_and_call<'a>(t: *const (Foo+'a)) -> u32 { let foo_e : *const Foo = t as *const _; let r_1 = foo_e as *mut Foo; (&*r_1).foo(0)*(&*(bar as *const Foo)).foo(0) (&*r_1).foo(0) } #[repr(C)]"} {"_id":"doc-en-rust-1dea7b9f653c61585e6991495888bcfe2316a36e899e163db85e556d81eeb09d","title":"","text":"fn main() { let x = 4u32; let y : &Foo = &x; let fl = unsafe { fool(y as *const Foo) }; assert_eq!(fl, (43+4)*(43+4)); let fl = unsafe { round_trip_and_call(y as *const Foo) }; assert_eq!(fl, (43+4)); let s = FooS([0,1,2]); let u: &FooS<[u32]> = &s;"} {"_id":"doc-en-rust-0a75249c4338e68e72e7b7575aad3651aee9dd3b64619f923fdce00d9fcff971","title":"","text":"assert_eq!(u as *const u8, p as *const u8); assert_eq!(u as *const u16, p as *const u16); // ptr-ptr-cast (both vk=Length) // ptr-ptr-cast (Length vtables) let mut l : [u8; 2] = [0,1]; let w: *mut [u16; 2] = &mut l as *mut [u8; 2] as *mut _; let w: *mut [u16] = unsafe {&mut *w};"} {"_id":"doc-en-rust-4504e8170ecd5fcc46caed139f9442f6496ed748643695d70f698bbbe173cbbc","title":"","text":"let l_via_str = unsafe{&*(s as *const [u8])}; assert_eq!(&l, l_via_str); // ptr-ptr-cast (Length vtables, check length is preserved) let l: [[u8; 3]; 2] = [[3, 2, 6], [4, 5, 1]]; let p: *const [[u8; 3]] = &l; let p: &[[u8; 2]] = unsafe {&*(p as *const [[u8; 2]])}; assert_eq!(p, [[3, 2], [6, 4]]); // enum-cast assert_eq!(Simple::A as u8, 0); assert_eq!(Simple::B as u8, 1);"} {"_id":"doc-en-rust-caec82172341739f7b261010d5823d336df96af99574a7495613d264c6f9d82c","title":"","text":"let impl_m = &cm.mty; if impl_m.fty.meta.purity != trait_m.fty.meta.purity { tcx.sess.span_err( cm.span, fmt!(\"method `%s`'s purity does not match the trait method's purity\", tcx.sess.str_of(impl_m.ident))); } // is this check right? // FIXME(#2687)---this check is too strict. For example, a trait // method with self type `&self` or `&mut self` should be // implementable by an `&const self` method (the impl assumes less // than the trait provides). if impl_m.self_ty != trait_m.self_ty { tcx.sess.span_err( cm.span,"} {"_id":"doc-en-rust-b902e8c01413639a602dfadb7f12f9af28e0c2733f74dc8724c2a7c761329465","title":"","text":"return; } // FIXME(#2687)---we should be checking that the bounds of the // trait imply the bounds of the subtype, but it appears // we are...not checking this. for trait_m.tps.eachi() |i, trait_param_bounds| { // For each of the corresponding impl ty param's bounds... let impl_param_bounds = impl_m.tps[i];"} {"_id":"doc-en-rust-0570e7ca245bccd66eab5eaa5b761bdcb1e3fc04b60fee1b55c8203304ef0740","title":"","text":"debug!(\"trait_fty (pre-subst): %s\", ty_to_str(tcx, trait_fty)); ty::subst(tcx, &substs, trait_fty) }; debug!(\"trait_fty: %s\", ty_to_str(tcx, trait_fty)); require_same_types( tcx, None, false, cm.span, impl_fty, trait_fty, || fmt!(\"method `%s` has an incompatible type\", tcx.sess.str_of(trait_m.ident))); let infcx = infer::new_infer_ctxt(tcx); match infer::mk_subty(infcx, false, cm.span, impl_fty, trait_fty) { result::Ok(()) => {} result::Err(ref terr) => { tcx.sess.span_err( cm.span, fmt!(\"method `%s` has an incompatible type: %s\", tcx.sess.str_of(trait_m.ident), ty::type_err_to_str(tcx, terr))); ty::note_and_explain_type_err(tcx, terr); } } return; // Replaces bound references to the self region with `with_r`."} {"_id":"doc-en-rust-bf3dd5226517d75e056d0b6175d50ee7feea04bdd81f483f891899405c40de43","title":"","text":" trait Mumbo { pure fn jumbo(&self, x: @uint) -> uint; fn jambo(&self, x: @const uint) -> uint; fn jbmbo(&self) -> @uint; } impl uint: Mumbo { // Cannot have a larger effect than the trait: fn jumbo(&self, x: @uint) { *self + *x; } //~^ ERROR expected pure fn but found impure fn // Cannot accept a narrower range of parameters: fn jambo(&self, x: @uint) { *self + *x; } //~^ ERROR values differ in mutability // Cannot return a wider range of values: fn jbmbo(&self) -> @const uint { @const 0 } //~^ ERROR values differ in mutability } fn main() {} "} {"_id":"doc-en-rust-500537c687a9e841c09ee5facf3fe1da66a6c3bd64b6b527245f1c0d52622760","title":"","text":" trait Mumbo { fn jumbo(&self, x: @uint) -> uint; } impl uint: Mumbo { // Note: this method def is ok, it is more accepting and // less effecting than the trait method: pure fn jumbo(&self, x: @const uint) -> uint { *self + *x } } fn main() { let a = 3u; let b = a.jumbo(@mut 6); let x = @a as @Mumbo; let y = x.jumbo(@mut 6); //~ ERROR values differ in mutability let z = x.jumbo(@6); } "} {"_id":"doc-en-rust-f2d5d42807374dcc52259d67ec5852c9c214b55e039e3dd0a5c827b150c928d2","title":"","text":"fn bar<'a>(...) ``` This part declares our lifetimes. This says that `bar` has one lifetime, `'a`. If we had two reference parameters, it would look like this: We previously talked a little about [function syntax][functions], but we didn’t discuss the `<>`s after a function’s name. A function can have ‘generic parameters’ between the `<>`s, of which lifetimes are one kind. We’ll discuss other kinds of generics [later in the book][generics], but for now, let’s just focus on the lifteimes aspect. [functions]: functions.html [generics]: generics.html We use `<>` to declare our lifetimes. This says that `bar` has one lifetime, `'a`. If we had two reference parameters, it would look like this: ```rust,ignore fn bar<'a, 'b>(...)"} {"_id":"doc-en-rust-408b716fb47786f807f48dc315e134b4ac30c3ca7a7a01b28aaaa8c6d3ec3b34","title":"","text":"let mut sign = None; if !is_positive { sign = Some('-'); width += 1; } else if self.flags & (1 << (FlagV1::SignPlus as u32)) != 0 { } else if self.sign_plus() { sign = Some('+'); width += 1; } let mut prefixed = false; if self.flags & (1 << (FlagV1::Alternate as u32)) != 0 { if self.alternate() { prefixed = true; width += prefix.char_len(); }"} {"_id":"doc-en-rust-c9c1cf0acb0342c33397d0bc973020c4513ca10cc1f4f7f014a27ada71ac7c45","title":"","text":"} // The sign and prefix goes before the padding if the fill character // is zero Some(min) if self.flags & (1 << (FlagV1::SignAwareZeroPad as u32)) != 0 => { Some(min) if self.sign_aware_zero_pad() => { self.fill = '0'; try!(write_prefix(self)); self.with_padding(min - width, Alignment::Right, |f| {"} {"_id":"doc-en-rust-d7734815f6ce1d7b906f0ab305877f7beb3d3478f6321805929325128f4a4c24","title":"","text":"let mut formatted = formatted.clone(); let mut align = self.align; let old_fill = self.fill; if self.flags & (1 << (FlagV1::SignAwareZeroPad as u32)) != 0 { if self.sign_aware_zero_pad() { // a sign always goes first let sign = unsafe { str::from_utf8_unchecked(formatted.sign) }; try!(self.buf.write_str(sign));"} {"_id":"doc-en-rust-01f77f18243bddaeca35fc50314de03cb4b44453ab63b886b0c01531b02cd507","title":"","text":"issue = \"27726\")] pub fn precision(&self) -> Option { self.precision } /// Determines if the `+` flag was specified. #[unstable(feature = \"fmt_flags\", reason = \"method was just created\", issue = \"27726\")] pub fn sign_plus(&self) -> bool { self.flags & (1 << FlagV1::SignPlus as u32) != 0 } /// Determines if the `-` flag was specified. #[unstable(feature = \"fmt_flags\", reason = \"method was just created\", issue = \"27726\")] pub fn sign_minus(&self) -> bool { self.flags & (1 << FlagV1::SignMinus as u32) != 0 } /// Determines if the `#` flag was specified. #[unstable(feature = \"fmt_flags\", reason = \"method was just created\", issue = \"27726\")] pub fn alternate(&self) -> bool { self.flags & (1 << FlagV1::Alternate as u32) != 0 } /// Determines if the `0` flag was specified. #[unstable(feature = \"fmt_flags\", reason = \"method was just created\", issue = \"27726\")] pub fn sign_aware_zero_pad(&self) -> bool { self.flags & (1 << FlagV1::SignAwareZeroPad as u32) != 0 } /// Creates a `DebugStruct` builder designed to assist with creation of /// `fmt::Debug` implementations for structs. ///"} {"_id":"doc-en-rust-6d5ed29038552fbe1fd1c8574d6e6711f73f69ffe162c3c35a3803906aad6610","title":"","text":"// it denotes whether to prefix with 0x. We use it to work out whether // or not to zero extend, and then unconditionally set it to get the // prefix. if f.flags & 1 << (FlagV1::Alternate as u32) > 0 { if f.alternate() { f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32); if let None = f.width {"} {"_id":"doc-en-rust-4fd85a1b7ccc1b049c44ba911c40e8b40aa89b849d0dad479204e75d0ae89b19","title":"","text":"fn float_to_decimal_common(fmt: &mut Formatter, num: &T, negative_zero: bool) -> Result where T: flt2dec::DecodableFloat { let force_sign = fmt.flags & (1 << (FlagV1::SignPlus as u32)) != 0; let force_sign = fmt.sign_plus(); let sign = match (force_sign, negative_zero) { (false, false) => flt2dec::Sign::Minus, (false, true) => flt2dec::Sign::MinusRaw,"} {"_id":"doc-en-rust-56bedd0a125417bb071cd1f797e30aa1c8973f38445d3c1b46001a08b47deda7","title":"","text":"fn float_to_exponential_common(fmt: &mut Formatter, num: &T, upper: bool) -> Result where T: flt2dec::DecodableFloat { let force_sign = fmt.flags & (1 << (FlagV1::SignPlus as u32)) != 0; let force_sign = fmt.sign_plus(); let sign = match force_sign { false => flt2dec::Sign::Minus, true => flt2dec::Sign::MinusPlus,"} {"_id":"doc-en-rust-d37399cb719695b7f94573c73bfaae9b8e85014e0d623d2dc52b4457a53b6837","title":"","text":"// // Local Variables: // mode: C++ // mode: rust // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4"} {"_id":"doc-en-rust-e7d7c73d404ba3abc87ef5bc3675006d1d04271ca22478af988066b238167d40","title":"","text":"} function startSearch() { $(\".search-input\").on(\"keyup\",function() { if ($(this).val().length === 0) { window.history.replaceState(\"\", \"std - Rust\", \"?search=\"); $('#main.content').removeClass('hidden'); $('#search.content').addClass('hidden'); } }); var keyUpTimeout; $('.do-search').on('click', search); $('.search-input').on('keyup', function() {"} {"_id":"doc-en-rust-16655e1b66b04d4ea8eab2e01e78493177e16bbabf6080fec191548dc7724e81","title":"","text":"E0495, // cannot infer an appropriate lifetime due to conflicting requirements E0496, // .. name `..` shadows a .. name that is already in scope E0498, // malformed plugin attribute E0514, // metadata version mismatch }"} {"_id":"doc-en-rust-c482e36f801dd43bcbef4be3c51849d45e732064154bf16056292d54b5963a56","title":"","text":"pub const tag_impl_coerce_unsized_kind: usize = 0xa5; pub const tag_items_data_item_constness: usize = 0xa6; pub const tag_rustc_version: usize = 0x10f; pub fn rustc_version() -> String { format!( \"rustc {}\", option_env!(\"CFG_VERSION\").unwrap_or(\"unknown version\") ) } "} {"_id":"doc-en-rust-a0df95f6c0155d1f330f444e6806b5c0ea06795206b068bd61f0d3707a12ce86","title":"","text":"use back::svh::Svh; use session::{config, Session}; use session::search_paths::PathKind; use metadata::common::rustc_version; use metadata::cstore; use metadata::cstore::{CStore, CrateSource, MetadataBlob}; use metadata::decoder;"} {"_id":"doc-en-rust-dc7528e35ac4f58f9db16503ee8f69b940c94dea1ed697dc2701068de8957af7","title":"","text":"return ret; } fn verify_rustc_version(&self, name: &str, span: Span, metadata: &MetadataBlob) { let crate_rustc_version = decoder::crate_rustc_version(metadata.as_slice()); if crate_rustc_version != Some(rustc_version()) { span_err!(self.sess, span, E0514, \"the crate `{}` has been compiled with {}, which is incompatible with this version of rustc\", name, crate_rustc_version .as_ref().map(|s|&**s) .unwrap_or(\"an old version of rustc\") ); self.sess.abort_if_errors(); } } fn register_crate(&mut self, root: &Option, ident: &str,"} {"_id":"doc-en-rust-657f2bb26cd7c265ac3d44371d515caf2e222196191149277b9645f13137f63f","title":"","text":"explicitly_linked: bool) -> (ast::CrateNum, Rc, cstore::CrateSource) { self.verify_rustc_version(name, span, &lib.metadata); // Claim this crate number and cache it let cnum = self.next_crate_num; self.next_crate_num += 1;"} {"_id":"doc-en-rust-7d4d287c064721db4d7c56513410fefb46550f0487660403746af45329096484","title":"","text":"index::Index::from_buf(index.data, index.start, index.end) } pub fn crate_rustc_version(data: &[u8]) -> Option { let doc = rbml::Doc::new(data); reader::maybe_get_doc(doc, tag_rustc_version).map(|s| s.as_str()) } #[derive(Debug, PartialEq)] enum Family { ImmStatic, // c"} {"_id":"doc-en-rust-964c47af66daa0c54d4f44cf54a601c968f3052f4e9fa68c603933d15cfbb4fb","title":"","text":"rbml_w.wr_tagged_str(tag_crate_hash, hash.as_str()); } fn encode_rustc_version(rbml_w: &mut Encoder) { rbml_w.wr_tagged_str(tag_rustc_version, &rustc_version()); } fn encode_crate_name(rbml_w: &mut Encoder, crate_name: &str) { rbml_w.wr_tagged_str(tag_crate_crate_name, crate_name); }"} {"_id":"doc-en-rust-e89bd50a665ad879c1ebdbaaa02720641663c87b5ef3a88c5732b8d6b26813e6","title":"","text":"let mut rbml_w = Encoder::new(wr); encode_rustc_version(&mut rbml_w); encode_crate_name(&mut rbml_w, &ecx.link_meta.crate_name); encode_crate_triple(&mut rbml_w, &tcx.sess.opts.target_triple); encode_hash(&mut rbml_w, &ecx.link_meta.crate_hash);"} {"_id":"doc-en-rust-7b0faa7fa43ff1376cf740c0b3f25ffe61550d758db1d2105d1683211fe87f5a","title":"","text":"// can just use the tcx as the typer. // // FIXME(stage0): the :'t here is probably only important for stage0 pub struct ExprUseVisitor<'d, 't, 'a: 't, 'tcx:'a+'d+'t> { pub struct ExprUseVisitor<'d, 't, 'a: 't, 'tcx:'a+'d> { typer: &'t infer::InferCtxt<'a, 'tcx>, mc: mc::MemCategorizationContext<'t, 'a, 'tcx>, delegate: &'d mut Delegate<'tcx>,"} {"_id":"doc-en-rust-b536b3aeb7a32be04f8b83bfe28ca29f11bd9ebcc2dbf2951bea982df2c84d03","title":"","text":"impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> { pub fn new(delegate: &'d mut Delegate<'tcx>, typer: &'t infer::InferCtxt<'a, 'tcx>) -> ExprUseVisitor<'d,'t,'a,'tcx> -> ExprUseVisitor<'d,'t,'a,'tcx> where 'tcx:'a { ExprUseVisitor { typer: typer,"} {"_id":"doc-en-rust-f879b28a420cb50f348a3c9897d52286e6156286ea222e37988a0687cabfbdfe","title":"","text":"% Closures Rust not only has named functions, but anonymous functions as well. Anonymous functions that have an associated environment are called ‘closures’, because they close over an environment. Rust has a really great implementation of them, as we’ll see. Sometimes it is useful to wrap up a function and _free variables_ for better clarity and reuse. The free variables that can be used come from the enclosing scope and are ‘closed over’ when used in the function. From this, we get the name ‘closures’ and Rust provides a really great implementation of them, as we’ll see. # Syntax"} {"_id":"doc-en-rust-b57792600f3fdfde7082944216655f0c6377540e26ac8e20d4b13cc27c2c38e8","title":"","text":"``` You’ll notice a few things about closures that are a bit different from regular functions defined with `fn`. The first is that we did not need to named functions defined with `fn`. The first is that we did not need to annotate the types of arguments the closure takes or the values it returns. We can:"} {"_id":"doc-en-rust-997f7ad35b3af6173a7160aa267f7be5b0809cd920770d5c32a5f8827224721f","title":"","text":"assert_eq!(2, plus_one(1)); ``` But we don’t have to. Why is this? Basically, it was chosen for ergonomic reasons. While specifying the full type for named functions is helpful with things like documentation and type inference, the types of closures are rarely documented since they’re anonymous, and they don’t cause the kinds of error-at-a-distance problems that inferring named function types can. But we don’t have to. Why is this? Basically, it was chosen for ergonomic reasons. While specifying the full type for named functions is helpful with things like documentation and type inference, the full type signatures of closures are rarely documented since they’re anonymous, and they don’t cause the kinds of error-at-a-distance problems that inferring named function types can. The second is that the syntax is similar, but a bit different. I’ve added spaces here for easier comparison: The second is that the syntax is similar, but a bit different. I’ve added spaces here for easier comparison: ```rust fn plus_one_v1 (x: i32) -> i32 { x + 1 }"} {"_id":"doc-en-rust-32c942591c15ff961f71cac4329167bf81e26ff5c1fefedfd3368e65f5b6b47f","title":"","text":"# Closures and their environment Closures are called such because they ‘close over their environment’. It looks like this: The environment for a closure can include bindings from its enclosing scope in addition to parameters and local bindings. It looks like this: ```rust let num = 5;"} {"_id":"doc-en-rust-0de7cf9b66e3be6b35ae7f518b8d1b2e76eeeb642e759902776596c4f016a2c9","title":"","text":"it, while a `move` closure is self-contained. This means that you cannot generally return a non-`move` closure from a function, for example. But before we talk about taking and returning closures, we should talk some more about the way that closures are implemented. As a systems language, Rust gives you tons of control over what your code does, and closures are no different. But before we talk about taking and returning closures, we should talk some more about the way that closures are implemented. As a systems language, Rust gives you tons of control over what your code does, and closures are no different. # Closure implementation"} {"_id":"doc-en-rust-e336995a7a063325da7876e3c8a0d8c0c70be9613c42d087dfec827301d350d5","title":"","text":"# some_closure(1) } ``` Because `Fn` is a trait, we can bound our generic with it. In this case, our closure takes a `i32` as an argument and returns an `i32`, and so the generic bound we use is `Fn(i32) -> i32`. Because `Fn` is a trait, we can bound our generic with it. In this case, our closure takes a `i32` as an argument and returns an `i32`, and so the generic bound we use is `Fn(i32) -> i32`. There’s one other key point here: because we’re bounding a generic with a trait, this will get monomorphized, and therefore, we’ll be doing static"} {"_id":"doc-en-rust-3d62a91e9065e5d5b760b55ff466c2f1a66b3a2acc9ea5dc0053e1b19659c41d","title":"","text":"The error also points out that the return type is expected to be a reference, but what we are trying to return is not. Further, we cannot directly assign a `'static` lifetime to an object. So we'll take a different approach and return a \"trait object\" by `Box`ing up the `Fn`. This _almost_ works: a ‘trait object’ by `Box`ing up the `Fn`. This _almost_ works: ```rust,ignore fn factory() -> Box i32> {"} {"_id":"doc-en-rust-8417a8ce0044bd436d5b08aa057ad9197853b8cad0c983fb25b5ffbca00a42c4","title":"","text":"#[inline] fn last(self) -> Option { match self.state { ChainState::Both => self.b.last().or(self.a.last()), ChainState::Both => { // Must exhaust a before b. let a_last = self.a.last(); let b_last = self.b.last(); b_last.or(a_last) }, ChainState::Front => self.a.last(), ChainState::Back => self.b.last() }"} {"_id":"doc-en-rust-321915c765e4a76eb93458930bff97ac962d3f629b4606b3bbf4a1af9f52baa1","title":"","text":"talk about what you do want instead. There are three broad classes of things that are relevant here: iterators, *iterator adapters*, and *consumers*. Here's some definitions: *iterator adaptors*, and *consumers*. Here's some definitions: * *iterators* give you a sequence of values. * *iterator adapters* operate on an iterator, producing a new iterator with a * *iterator adaptors* operate on an iterator, producing a new iterator with a different output sequence. * *consumers* operate on an iterator, producing some final set of values."} {"_id":"doc-en-rust-37ff3598971b4d3ff40cee4dcd2ced84dcf9daab85cebd24523f69aca805fea1","title":"","text":"These two basic iterators should serve you well. There are some more advanced iterators, including ones that are infinite. That's enough about iterators. Iterator adapters are the last concept That's enough about iterators. Iterator adaptors are the last concept we need to talk about with regards to iterators. Let's get to it! ## Iterator adapters ## Iterator adaptors *Iterator adapters* take an iterator and modify it somehow, producing *Iterator adaptors* take an iterator and modify it somehow, producing a new iterator. The simplest one is called `map`: ```rust,ignore"} {"_id":"doc-en-rust-bedaa54d1a4ae3af6fe8ebd07cf2d514a0951c6223e3ee5a9d66bad0b9646af1","title":"","text":"If you are trying to execute a closure on an iterator for its side effects, just use `for` instead. There are tons of interesting iterator adapters. `take(n)` will return an There are tons of interesting iterator adaptors. `take(n)` will return an iterator over the next `n` elements of the original iterator. Let's try it out with an infinite iterator:"} {"_id":"doc-en-rust-a6e20417b37e108841264de8d2c07b9dc647699309a0db8701567912bc46ece9","title":"","text":"This will give you a vector containing `6`, `12`, `18`, `24`, and `30`. This is just a small taste of what iterators, iterator adapters, and consumers This is just a small taste of what iterators, iterator adaptors, and consumers can help you with. There are a number of really useful iterators, and you can write your own as well. Iterators provide a safe, efficient way to manipulate all kinds of lists. They're a little unusual at first, but if you play with"} {"_id":"doc-en-rust-42d470b2795ab6d25736169ebd86a62c9a5eaa0f6fe2040c0992d02bfa01a165","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] impl Drop for IntoIter { #[unsafe_destructor_blind_to_params] fn drop(&mut self) { // destroy the remaining elements for _x in self {}"} {"_id":"doc-en-rust-ca3bfd6146e26138af6ebba0ca152cd744ec275abeb99ebbe7c98404df59d644","title":"","text":" // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This test ensures that vec.into_iter does not overconstrain element lifetime. pub fn main() { original_report(); revision_1(); revision_2(); } fn original_report() { drop(vec![&()].into_iter()) } fn revision_1() { // below is what above `vec!` expands into at time of this writing. drop(<[_]>::into_vec(::std::boxed::Box::new([&()])).into_iter()) } fn revision_2() { drop((match (Vec::new(), &()) { (mut v, b) => { v.push(b); v } }).into_iter()) } "} {"_id":"doc-en-rust-f2d1476a859347c798cebed1968b169f31eacb8df99fc80bd871cbce1504a2f2","title":"","text":"/// use std::io::Cursor; /// let mut buff = Cursor::new(vec![0; 15]); /// /// write_ten_bytes(&mut buff).unwrap(); /// write_ten_bytes_at_end(&mut buff).unwrap(); /// /// assert_eq!(&buff.get_ref()[5..15], &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); /// }"} {"_id":"doc-en-rust-24bfc2158eeb67a8db90acfeb56c9b90b5eacf29cf21f58770bfdfd7304be236","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. //! A Unicode scalar value //! Unicode scalar values //! //! This module provides the `CharExt` trait, as well as its //! implementation for the primitive `char` type, in order to allow"} {"_id":"doc-en-rust-ba1183a7d196d1a851226e35d98ea31b611e8610d2a8c642f19c2b498acd3961","title":"","text":"/// character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. /// where `NNNN` is the shortest hexadecimal representation. /// /// # Examples /// /// Basic usage: /// /// ``` /// for c in '❤'.escape_unicode() { /// print!(\"{}\", c);"} {"_id":"doc-en-rust-7f21086aeaafa839fb37b115c7dfef64a7d99ba7b8578a026e4bb508e176d7e5","title":"","text":"/// /// # Examples /// /// Basic usage: /// /// ``` /// let n = 'ß'.len_utf16(); /// assert_eq!(n, 1);"} {"_id":"doc-en-rust-0e029c1231faf4e20a4e9e07713290da95d4ceba44a0343a84df88343b621ac6","title":"","text":"/// /// # Examples /// /// Basic usage: /// /// ``` /// #![feature(decode_utf16)] ///"} {"_id":"doc-en-rust-70ff6a0999fad25b6f87651b9b24f6494e7226b97000f648f809918854311e0a","title":"","text":"#[doc(primitive = \"char\")] // /// A Unicode scalar value. /// A character type. /// /// A `char` represents a /// *[Unicode scalar /// value](http://www.unicode.org/glossary/#unicode_scalar_value)*, as it can /// contain any Unicode code point except high-surrogate and low-surrogate code /// points. /// The `char` type represents a single character. More specifically, since /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode /// scalar value]', which is similar to, but not the same as, a '[Unicode code /// point]'. /// /// As such, only values in the ranges [0x0,0xD7FF] and [0xE000,0x10FFFF] /// (inclusive) are allowed. A `char` can always be safely cast to a `u32`; /// however the converse is not always true due to the above range limits /// and, as such, should be performed via the `from_u32` function. /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value /// [Unicode code point]: http://www.unicode.org/glossary/#code_point /// /// *[See also the `std::char` module](char/index.html).* /// This documentation describes a number of methods and trait implementations on the /// `char` type. For technical reasons, there is additional, separate /// documentation in [the `std::char` module](char/index.html) as well. /// /// # Representation /// /// `char` is always four bytes in size. This is a different representation than /// a given character would have as part of a [`String`], for example: /// /// ``` /// let v = vec!['h', 'e', 'l', 'l', 'o']; /// /// // five elements times four bytes for each element /// assert_eq!(20, v.len() * std::mem::size_of::()); /// /// let s = String::from(\"hello\"); /// /// // five elements times one byte per element /// assert_eq!(5, s.len() * std::mem::size_of::()); /// ``` /// /// [`String`]: string/struct.String.html /// /// As always, remember that a human intuition for 'character' may not map to /// Unicode's definitions. For example, emoji symbols such as '❤️' are more than /// one byte; ❤️ in particular is six: /// /// ``` /// let s = String::from(\"❤️\"); /// /// // six bytes times one byte for each element /// assert_eq!(6, s.len() * std::mem::size_of::()); /// ``` /// /// This also means it won't fit into a `char`, and so trying to create a /// literal with `let heart = '❤️';` gives an error: /// /// ```text /// error: character literal may only contain one codepoint: '❤ /// let heart = '❤️'; /// ^~ /// ``` /// /// Another implication of this is that if you want to do per-`char`acter /// processing, it can end up using a lot more memory: /// /// ``` /// let s = String::from(\"love: ❤️\"); /// let v: Vec = s.chars().collect(); /// /// assert_eq!(12, s.len() * std::mem::size_of::()); /// assert_eq!(32, v.len() * std::mem::size_of::()); /// ``` /// /// Or may give you results you may not expect: /// /// ``` /// let s = String::from(\"❤️\"); /// /// let mut iter = s.chars(); /// /// // we get two chars out of a single ❤️ /// assert_eq!(Some('u{2764}'), iter.next()); /// assert_eq!(Some('u{fe0f}'), iter.next()); /// assert_eq!(None, iter.next()); /// ``` mod prim_char { } #[doc(primitive = \"unit\")]"} {"_id":"doc-en-rust-2a889f9fb345cd084727dd9535ee780deff33c73f884c3de20617d404e43116a","title":"","text":"//! Like many traits, these are often used as bounds for generic functions, to //! support arguments of multiple types. //! //! - Impl the `As*` traits for reference-to-reference conversions //! - Impl the `Into` trait when you want to consume the value in the conversion //! - The `From` trait is the most flexible, usefull for values _and_ references conversions //! //! As a library writer, you should prefer implementing `From` rather than //! `Into`, as `From` provides greater flexibility and offer the equivalent `Into` //! implementation for free, thanks to a blanket implementation in the standard library. //! //! **Note: these traits must not fail**. If the conversion can fail, you must use a dedicated //! method which return an `Option` or a `Result`. //! //! # Generic impl //! //! - `AsRef` and `AsMut` auto-dereference if the inner type is a reference //! - `From for T` implies `Into for U` //! - `From` and `Into` are reflexive, which means that all types can `into()` //! themselves and `from()` themselves //! //! See each trait for usage examples. #![stable(feature = \"rust1\", since = \"1.0.0\")]"} {"_id":"doc-en-rust-e034ff9ad93df0abfbb06f539fa111582da503d747b55979ce105d9a2d8d9967","title":"","text":"/// /// [book]: ../../book/borrow-and-asref.html /// /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which /// return an `Option` or a `Result`. /// /// # Examples /// /// Both `String` and `&str` implement `AsRef`:"} {"_id":"doc-en-rust-66907cda6fa2032f8bf50711b123815003c51ab46befd00475c2ab384e2441d9","title":"","text":"/// let s = \"hello\".to_string(); /// is_hello(s); /// ``` /// /// # Generic Impls /// /// - `AsRef` auto-dereference if the inner type is a reference or a mutable /// reference (eg: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`) /// #[stable(feature = \"rust1\", since = \"1.0.0\")] pub trait AsRef { /// Performs the conversion."} {"_id":"doc-en-rust-66156038a9f4dc98268003f2f6732c3be6413b0171eb80049bf37fa1e6282ace","title":"","text":"} /// A cheap, mutable reference-to-mutable reference conversion. /// /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which /// return an `Option` or a `Result`. /// /// # Generic Impls /// /// - `AsMut` auto-dereference if the inner type is a reference or a mutable /// reference (eg: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`) /// #[stable(feature = \"rust1\", since = \"1.0.0\")] pub trait AsMut { /// Performs the conversion."} {"_id":"doc-en-rust-9b1ce6279b01d439468d7aa9e545b7dcd7ec9cc251fd4eaea490c1e20e2aca60","title":"","text":"/// A conversion that consumes `self`, which may or may not be expensive. /// /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which /// return an `Option` or a `Result`. /// /// Library writer should not implement directly this trait, but should prefer the implementation /// of the `From` trait, which offer greater flexibility and provide the equivalent `Into` /// implementation for free, thanks to a blanket implementation in the standard library. /// /// # Examples /// /// `String` implements `Into>`:"} {"_id":"doc-en-rust-33969ce7768aa7378c9026f61c9733b5f1383d4e5942747a4f9794a70e87a1c3","title":"","text":"/// let s = \"hello\".to_string(); /// is_hello(s); /// ``` /// /// # Generic Impls /// /// - `From for U` implies `Into for T` /// - `into()` is reflexive, which means that `Into for T` is implemented /// #[stable(feature = \"rust1\", since = \"1.0.0\")] pub trait Into: Sized { /// Performs the conversion."} {"_id":"doc-en-rust-38449d79b50ac025ceb3ccf085184c4b17fa22e1a2439148784adabd3e85b150","title":"","text":"/// Construct `Self` via a conversion. /// /// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which /// return an `Option` or a `Result`. /// /// # Examples /// /// `String` implements `From<&str>`:"} {"_id":"doc-en-rust-5d7d3ac44d9820ee1934e98fcaae75bb2d9a11a437ca17b1770513b29b6e7dee","title":"","text":"/// /// assert_eq!(string, other_string); /// ``` /// # Generic impls /// /// - `From for U` implies `Into for T` /// - `from()` is reflexive, which means that `From for T` is implemented /// #[stable(feature = \"rust1\", since = \"1.0.0\")] pub trait From: Sized { /// Performs the conversion."} {"_id":"doc-en-rust-8d5c08b056c28ae89b4083eb4d1333b20cfd0e26b23b3972cd5de1360eaf65c1","title":"","text":"} } pub fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: DefId, ty: Ty<'tcx>) -> ValueRef { if let Some(node_id) = ccx.tcx().map.as_local_node_id(did) { base::get_item_val(ccx, node_id) } else { base::get_extern_const(ccx, did, ty) } } "} {"_id":"doc-en-rust-7ebbd33064fb9082db77853b665d2f15d24d552e771b9aa1949769dd3e000812","title":"","text":"use middle::def_id::DefId; use trans::{adt, closure, debuginfo, expr, inline, machine}; use trans::base::{self, push_ctxt}; use trans::common::{self, type_is_sized, ExprOrMethodCall, node_id_substs, C_nil, const_get_elt}; use trans::common::{CrateContext, C_integral, C_floating, C_bool, C_str_slice, C_bytes, val_ty}; use trans::common::{type_is_sized, ExprOrMethodCall, node_id_substs, C_nil, const_get_elt}; use trans::common::{C_struct, C_undef, const_to_opt_int, const_to_opt_uint, VariantInfo, C_uint}; use trans::common::{type_is_fat_ptr, Field, C_vector, C_array, C_null, ExprId, MethodCallKey}; use trans::declare;"} {"_id":"doc-en-rust-769c3e38081c07d4171195c44d723e3b24835ab406aa9f4e028ce12966c48d9b","title":"","text":"} let opt_def = cx.tcx().def_map.borrow().get(&cur.id).map(|d| d.full_def()); if let Some(def::DefStatic(def_id, _)) = opt_def { get_static_val(cx, def_id, ety) common::get_static_val(cx, def_id, ety) } else { // If this isn't the address of a static, then keep going through // normal constant evaluation."} {"_id":"doc-en-rust-2adc89f506d8365cec35c37ce8783c4ff9fc59b567ecc36fbfbd16fe412e60cd","title":"","text":"Ok(g) } } fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: DefId, ty: Ty<'tcx>) -> ValueRef { if let Some(node_id) = ccx.tcx().map.as_local_node_id(did) { base::get_item_val(ccx, node_id) } else { base::trans_external_path(ccx, did, ty) } } "} {"_id":"doc-en-rust-feb5dded6f41bd92b336e5c9eebfff6173cbe72d3ff59f40d981f3dbb67c0e40","title":"","text":"DatumBlock::new(bcx, datum.to_expr_datum()) } def::DefStatic(did, _) => { // There are two things that may happen here: // 1) If the static item is defined in this crate, it will be // translated using `get_item_val`, and we return a pointer to // the result. // 2) If the static item is defined in another crate then we add // (or reuse) a declaration of an external global, and return a // pointer to that. let const_ty = expr_ty(bcx, ref_expr); // For external constants, we don't inline. let val = if let Some(node_id) = bcx.tcx().map.as_local_node_id(did) { // Case 1. // The LLVM global has the type of its initializer, // which may not be equal to the enum's type for // non-C-like enums. let val = base::get_item_val(bcx.ccx(), node_id); let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to(); PointerCast(bcx, val, pty) } else { // Case 2. base::get_extern_const(bcx.ccx(), did, const_ty) }; let val = get_static_val(bcx.ccx(), did, const_ty); let lval = Lvalue::new(\"expr::trans_def\"); DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr(lval))) }"} {"_id":"doc-en-rust-a871a9726838a6af1fa7e17538c18c790f74751a3f848cc6c1d74f04b246af2d","title":"","text":"tcx.sess.bug(&format!(\"using operand temp {:?} as lvalue\", lvalue)), }, mir::Lvalue::Arg(index) => self.args[index as usize], mir::Lvalue::Static(_def_id) => unimplemented!(), mir::Lvalue::Static(def_id) => { let const_ty = self.mir.lvalue_ty(tcx, lvalue); LvalueRef::new(common::get_static_val(ccx, def_id, const_ty.to_ty(tcx)), const_ty) }, mir::Lvalue::ReturnPointer => { let return_ty = bcx.monomorphize(&self.mir.return_ty); let llval = fcx.get_ret_slot(bcx, return_ty, \"return\");"} {"_id":"doc-en-rust-cb37be509f1015ad3a82b3608f8bc9a75babb2110990b82cd117036d1aa2a613","title":"","text":"[rust]: https://www.rust-lang.org “The Rust Programming Language” is split into eight sections. This introduction “The Rust Programming Language” is split into sections. This introduction is the first. After this: * [Getting started][gs] - Set up your computer for Rust development. * [Learn Rust][lr] - Learn Rust programming through small projects. * [Effective Rust][er] - Higher-level concepts for writing excellent Rust code. * [Tutorial: Guessing Game][gg] - Learn some Rust with a small project. * [Syntax and Semantics][ss] - Each bit of Rust, broken down into small chunks. * [Effective Rust][er] - Higher-level concepts for writing excellent Rust code. * [Nightly Rust][nr] - Cutting-edge features that aren’t in stable builds yet. * [Glossary][gl] - A reference of terms used in the book. * [Bibliography][bi] - Background on Rust's influences, papers about Rust. [gs]: getting-started.html [lr]: learn-rust.html [gg]: guessing-game.html [er]: effective-rust.html [ss]: syntax-and-semantics.html [nr]: nightly-rust.html [gl]: glossary.html [bi]: bibliography.html After reading this introduction, you’ll want to dive into either ‘Learn Rust’ or ‘Syntax and Semantics’, depending on your preference: ‘Learn Rust’ if you want to dive in with a project, or ‘Syntax and Semantics’ if you prefer to start small, and learn a single concept thoroughly before moving onto the next. Copious cross-linking connects these parts together. ### Contributing The source files from which this book is generated can be found on"} {"_id":"doc-en-rust-a11cc19f04b6df079bcae0078fc7ddc7655cc41746b6ae9775d3cf0d725aef49","title":"","text":"# Summary * [Getting Started](getting-started.md) * [Learn Rust](learn-rust.md) * [Guessing Game](guessing-game.md) * [Dining Philosophers](dining-philosophers.md) * [Rust Inside Other Languages](rust-inside-other-languages.md) * [Tutorial: Guessing Game](guessing-game.md) * [Syntax and Semantics](syntax-and-semantics.md) * [Variable Bindings](variable-bindings.md) * [Functions](functions.md)"} {"_id":"doc-en-rust-43c553a0cb0b3d9660ff937229b67968c4bd6faaad1f931ce501069bb2ef3536","title":"","text":" % Dining Philosophers For our second project, let’s look at a classic concurrency problem. It’s called ‘the dining philosophers’. It was originally conceived by Dijkstra in 1965, but we’ll use a lightly adapted version from [this paper][paper] by Tony Hoare in 1985. [paper]: http://www.usingcsp.com/cspbook.pdf > In ancient times, a wealthy philanthropist endowed a College to accommodate > five eminent philosophers. Each philosopher had a room in which they could > engage in their professional activity of thinking; there was also a common > dining room, furnished with a circular table, surrounded by five chairs, each > labelled by the name of the philosopher who was to sit in it. They sat > anticlockwise around the table. To the left of each philosopher there was > laid a golden fork, and in the center stood a large bowl of spaghetti, which > was constantly replenished. A philosopher was expected to spend most of > their time thinking; but when they felt hungry, they went to the dining > room, sat down in their own chair, picked up their own fork on their left, > and plunged it into the spaghetti. But such is the tangled nature of > spaghetti that a second fork is required to carry it to the mouth. The > philosopher therefore had also to pick up the fork on their right. When > they were finished they would put down both their forks, get up from their > chair, and continue thinking. Of course, a fork can be used by only one > philosopher at a time. If the other philosopher wants it, they just have > to wait until the fork is available again. This classic problem shows off a few different elements of concurrency. The reason is that it's actually slightly tricky to implement: a simple implementation can deadlock. For example, let's consider a simple algorithm that would solve this problem: 1. A philosopher picks up the fork on their left. 2. They then pick up the fork on their right. 3. They eat. 4. They return the forks. Now, let’s imagine this sequence of events: 1. Philosopher 1 begins the algorithm, picking up the fork on their left. 2. Philosopher 2 begins the algorithm, picking up the fork on their left. 3. Philosopher 3 begins the algorithm, picking up the fork on their left. 4. Philosopher 4 begins the algorithm, picking up the fork on their left. 5. Philosopher 5 begins the algorithm, picking up the fork on their left. 6. ... ? All the forks are taken, but nobody can eat! There are different ways to solve this problem. We’ll get to our solution in the tutorial itself. For now, let’s get started and create a new project with `cargo`: ```bash $ cd ~/projects $ cargo new dining_philosophers --bin $ cd dining_philosophers ``` Now we can start modeling the problem itself. We’ll start with the philosophers in `src/main.rs`: ```rust struct Philosopher { name: String, } impl Philosopher { fn new(name: &str) -> Philosopher { Philosopher { name: name.to_string(), } } } fn main() { let p1 = Philosopher::new(\"Judith Butler\"); let p2 = Philosopher::new(\"Gilles Deleuze\"); let p3 = Philosopher::new(\"Karl Marx\"); let p4 = Philosopher::new(\"Emma Goldman\"); let p5 = Philosopher::new(\"Michel Foucault\"); } ``` Here, we make a [`struct`][struct] to represent a philosopher. For now, a name is all we need. We choose the [`String`][string] type for the name, rather than `&str`. Generally speaking, working with a type which owns its data is easier than working with one that uses references. [struct]: structs.html [string]: strings.html Let’s continue: ```rust # struct Philosopher { # name: String, # } impl Philosopher { fn new(name: &str) -> Philosopher { Philosopher { name: name.to_string(), } } } ``` This `impl` block lets us define things on `Philosopher` structs. In this case, we define an ‘associated function’ called `new`. The first line looks like this: ```rust # struct Philosopher { # name: String, # } # impl Philosopher { fn new(name: &str) -> Philosopher { # Philosopher { # name: name.to_string(), # } # } # } ``` We take one argument, a `name`, of type `&str`. This is a reference to another string. It returns an instance of our `Philosopher` struct. ```rust # struct Philosopher { # name: String, # } # impl Philosopher { # fn new(name: &str) -> Philosopher { Philosopher { name: name.to_string(), } # } # } ``` This creates a new `Philosopher`, and sets its `name` to our `name` argument. Not just the argument itself, though, as we call `.to_string()` on it. This will create a copy of the string that our `&str` points to, and give us a new `String`, which is the type of the `name` field of `Philosopher`. Why not accept a `String` directly? It’s nicer to call. If we took a `String`, but our caller had a `&str`, they’d have to call this method themselves. The downside of this flexibility is that we _always_ make a copy. For this small program, that’s not particularly important, as we know we’ll just be using short strings anyway. One last thing you’ll notice: we just define a `Philosopher`, and seemingly don’t do anything with it. Rust is an ‘expression based’ language, which means that almost everything in Rust is an expression which returns a value. This is true of functions as well — the last expression is automatically returned. Since we create a new `Philosopher` as the last expression of this function, we end up returning it. This name, `new()`, isn’t anything special to Rust, but it is a convention for functions that create new instances of structs. Before we talk about why, let’s look at `main()` again: ```rust # struct Philosopher { # name: String, # } # # impl Philosopher { # fn new(name: &str) -> Philosopher { # Philosopher { # name: name.to_string(), # } # } # } # fn main() { let p1 = Philosopher::new(\"Judith Butler\"); let p2 = Philosopher::new(\"Gilles Deleuze\"); let p3 = Philosopher::new(\"Karl Marx\"); let p4 = Philosopher::new(\"Emma Goldman\"); let p5 = Philosopher::new(\"Michel Foucault\"); } ``` Here, we create five variable bindings with five new philosophers. If we _didn’t_ define that `new()` function, it would look like this: ```rust # struct Philosopher { # name: String, # } fn main() { let p1 = Philosopher { name: \"Judith Butler\".to_string() }; let p2 = Philosopher { name: \"Gilles Deleuze\".to_string() }; let p3 = Philosopher { name: \"Karl Marx\".to_string() }; let p4 = Philosopher { name: \"Emma Goldman\".to_string() }; let p5 = Philosopher { name: \"Michel Foucault\".to_string() }; } ``` That’s much noisier. Using `new` has other advantages too, but even in this simple case, it ends up being nicer to use. Now that we’ve got the basics in place, there’s a number of ways that we can tackle the broader problem here. I like to start from the end first: let’s set up a way for each philosopher to finish eating. As a tiny step, let’s make a method, and then loop through all the philosophers, calling it: ```rust struct Philosopher { name: String, } impl Philosopher { fn new(name: &str) -> Philosopher { Philosopher { name: name.to_string(), } } fn eat(&self) { println!(\"{} is done eating.\", self.name); } } fn main() { let philosophers = vec![ Philosopher::new(\"Judith Butler\"), Philosopher::new(\"Gilles Deleuze\"), Philosopher::new(\"Karl Marx\"), Philosopher::new(\"Emma Goldman\"), Philosopher::new(\"Michel Foucault\"), ]; for p in &philosophers { p.eat(); } } ``` Let’s look at `main()` first. Rather than have five individual variable bindings for our philosophers, we make a `Vec` of them instead. `Vec` is also called a ‘vector’, and it’s a growable array type. We then use a [`for`][for] loop to iterate through the vector, getting a reference to each philosopher in turn. [for]: loops.html#for In the body of the loop, we call `p.eat()`, which is defined above: ```rust,ignore fn eat(&self) { println!(\"{} is done eating.\", self.name); } ``` In Rust, methods take an explicit `self` parameter. That’s why `eat()` is a method, but `new` is an associated function: `new()` has no `self`. For our first version of `eat()`, we just print out the name of the philosopher, and mention they’re done eating. Running this program should give you the following output: ```text Judith Butler is done eating. Gilles Deleuze is done eating. Karl Marx is done eating. Emma Goldman is done eating. Michel Foucault is done eating. ``` Easy enough, they’re all done! We haven’t actually implemented the real problem yet, though, so we’re not done yet! Next, we want to make our philosophers not just finish eating, but actually eat. Here’s the next version: ```rust use std::thread; use std::time::Duration; struct Philosopher { name: String, } impl Philosopher { fn new(name: &str) -> Philosopher { Philosopher { name: name.to_string(), } } fn eat(&self) { println!(\"{} is eating.\", self.name); thread::sleep(Duration::from_millis(1000)); println!(\"{} is done eating.\", self.name); } } fn main() { let philosophers = vec![ Philosopher::new(\"Judith Butler\"), Philosopher::new(\"Gilles Deleuze\"), Philosopher::new(\"Karl Marx\"), Philosopher::new(\"Emma Goldman\"), Philosopher::new(\"Michel Foucault\"), ]; for p in &philosophers { p.eat(); } } ``` Just a few changes. Let’s break it down. ```rust,ignore use std::thread; ``` `use` brings names into scope. We’re going to start using the `thread` module from the standard library, and so we need to `use` it. ```rust,ignore fn eat(&self) { println!(\"{} is eating.\", self.name); thread::sleep(Duration::from_millis(1000)); println!(\"{} is done eating.\", self.name); } ``` We now print out two messages, with a `sleep` in the middle. This will simulate the time it takes a philosopher to eat. If you run this program, you should see each philosopher eat in turn: ```text Judith Butler is eating. Judith Butler is done eating. Gilles Deleuze is eating. Gilles Deleuze is done eating. Karl Marx is eating. Karl Marx is done eating. Emma Goldman is eating. Emma Goldman is done eating. Michel Foucault is eating. Michel Foucault is done eating. ``` Excellent! We’re getting there. There’s just one problem: we aren’t actually operating in a concurrent fashion, which is a core part of the problem! To make our philosophers eat concurrently, we need to make a small change. Here’s the next iteration: ```rust use std::thread; use std::time::Duration; struct Philosopher { name: String, } impl Philosopher { fn new(name: &str) -> Philosopher { Philosopher { name: name.to_string(), } } fn eat(&self) { println!(\"{} is eating.\", self.name); thread::sleep(Duration::from_millis(1000)); println!(\"{} is done eating.\", self.name); } } fn main() { let philosophers = vec![ Philosopher::new(\"Judith Butler\"), Philosopher::new(\"Gilles Deleuze\"), Philosopher::new(\"Karl Marx\"), Philosopher::new(\"Emma Goldman\"), Philosopher::new(\"Michel Foucault\"), ]; let handles: Vec<_> = philosophers.into_iter().map(|p| { thread::spawn(move || { p.eat(); }) }).collect(); for h in handles { h.join().unwrap(); } } ``` All we’ve done is change the loop in `main()`, and added a second one! Here’s the first change: ```rust,ignore let handles: Vec<_> = philosophers.into_iter().map(|p| { thread::spawn(move || { p.eat(); }) }).collect(); ``` While this is only five lines, they’re a dense five. Let’s break it down. ```rust,ignore let handles: Vec<_> = ``` We introduce a new binding, called `handles`. We’ve given it this name because we are going to make some new threads, and that will return some handles to those threads that let us control their operation. We need to explicitly annotate the type here, though, due to an issue we’ll talk about later. The `_` is a type placeholder. We’re saying “`handles` is a vector of something, but you can figure out what that something is, Rust.” ```rust,ignore philosophers.into_iter().map(|p| { ``` We take our list of philosophers and call `into_iter()` on it. This creates an iterator that takes ownership of each philosopher. We need to do this to pass them to our threads. We take that iterator and call `map` on it, which takes a closure as an argument and calls that closure on each element in turn. ```rust,ignore thread::spawn(move || { p.eat(); }) ``` Here’s where the concurrency happens. The `thread::spawn` function takes a closure as an argument and executes that closure in a new thread. This closure needs an extra annotation, `move`, to indicate that the closure is going to take ownership of the values it’s capturing. In this case, it's the `p` variable of the `map` function. Inside the thread, all we do is call `eat()` on `p`. Also note that the call to `thread::spawn` lacks a trailing semicolon, making this an expression. This distinction is important, yielding the correct return value. For more details, read [Expressions vs. Statements][es]. [es]: functions.html#expressions-vs-statements ```rust,ignore }).collect(); ``` Finally, we take the result of all those `map` calls and collect them up. `collect()` will make them into a collection of some kind, which is why we needed to annotate the return type: we want a `Vec`. The elements are the return values of the `thread::spawn` calls, which are handles to those threads. Whew! ```rust,ignore for h in handles { h.join().unwrap(); } ``` At the end of `main()`, we loop through the handles and call `join()` on them, which blocks execution until the thread has completed execution. This ensures that the threads complete their work before the program exits. If you run this program, you’ll see that the philosophers eat out of order! We have multi-threading! ```text Judith Butler is eating. Gilles Deleuze is eating. Karl Marx is eating. Emma Goldman is eating. Michel Foucault is eating. Judith Butler is done eating. Gilles Deleuze is done eating. Karl Marx is done eating. Emma Goldman is done eating. Michel Foucault is done eating. ``` But what about the forks? We haven’t modeled them at all yet. To do that, let’s make a new `struct`: ```rust use std::sync::Mutex; struct Table { forks: Vec>, } ``` This `Table` has a vector of `Mutex`es. A mutex is a way to control concurrency: only one thread can access the contents at once. This is exactly the property we need with our forks. We use an empty tuple, `()`, inside the mutex, since we’re not actually going to use the value, just hold onto it. Let’s modify the program to use the `Table`: ```rust use std::thread; use std::time::Duration; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, } } fn eat(&self, table: &Table) { let _left = table.forks[self.left].lock().unwrap(); thread::sleep(Duration::from_millis(150)); let _right = table.forks[self.right].lock().unwrap(); println!(\"{} is eating.\", self.name); thread::sleep(Duration::from_millis(1000)); println!(\"{} is done eating.\", self.name); } } struct Table { forks: Vec>, } fn main() { let table = Arc::new(Table { forks: vec![ Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), ]}); let philosophers = vec![ Philosopher::new(\"Judith Butler\", 0, 1), Philosopher::new(\"Gilles Deleuze\", 1, 2), Philosopher::new(\"Karl Marx\", 2, 3), Philosopher::new(\"Emma Goldman\", 3, 4), Philosopher::new(\"Michel Foucault\", 0, 4), ]; let handles: Vec<_> = philosophers.into_iter().map(|p| { let table = table.clone(); thread::spawn(move || { p.eat(&table); }) }).collect(); for h in handles { h.join().unwrap(); } } ``` Lots of changes! However, with this iteration, we’ve got a working program. Let’s go over the details: ```rust,ignore use std::sync::{Mutex, Arc}; ``` We’re going to use another structure from the `std::sync` package: `Arc`. We’ll talk more about it when we use it. ```rust,ignore struct Philosopher { name: String, left: usize, right: usize, } ``` We need to add two more fields to our `Philosopher`. Each philosopher is going to have two forks: the one on their left, and the one on their right. We’ll use the `usize` type to indicate them, as it’s the type that you index vectors with. These two values will be the indexes into the `forks` our `Table` has. ```rust,ignore fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, } } ``` We now need to construct those `left` and `right` values, so we add them to `new()`. ```rust,ignore fn eat(&self, table: &Table) { let _left = table.forks[self.left].lock().unwrap(); thread::sleep(Duration::from_millis(150)); let _right = table.forks[self.right].lock().unwrap(); println!(\"{} is eating.\", self.name); thread::sleep(Duration::from_millis(1000)); println!(\"{} is done eating.\", self.name); } ``` We have three new lines. We’ve added an argument, `table`. We access the `Table`’s list of forks, and then use `self.left` and `self.right` to access the fork at that particular index. That gives us access to the `Mutex` at that index, and we call `lock()` on it. If the mutex is currently being accessed by someone else, we’ll block until it becomes available. We have also a call to `thread::sleep` between the moment the first fork is picked and the moment the second forked is picked, as the process of picking up the fork is not immediate. The call to `lock()` might fail, and if it does, we want to crash. In this case, the error that could happen is that the mutex is [‘poisoned’][poison], which is what happens when the thread panics while the lock is held. Since this shouldn’t happen, we just use `unwrap()`. [poison]: ../std/sync/struct.Mutex.html#poisoning One other odd thing about these lines: we’ve named the results `_left` and `_right`. What’s up with that underscore? Well, we aren’t planning on _using_ the value inside the lock. We just want to acquire it. As such, Rust will warn us that we never use the value. By using the underscore, we tell Rust that this is what we intended, and it won’t throw a warning. What about releasing the lock? Well, that will happen when `_left` and `_right` go out of scope, automatically. ```rust,ignore let table = Arc::new(Table { forks: vec![ Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), Mutex::new(()), ]}); ``` Next, in `main()`, we make a new `Table` and wrap it in an `Arc`. ‘arc’ stands for ‘atomic reference count’, and we need that to share our `Table` across multiple threads. As we share it, the reference count will go up, and when each thread ends, it will go back down. ```rust,ignore let philosophers = vec![ Philosopher::new(\"Judith Butler\", 0, 1), Philosopher::new(\"Gilles Deleuze\", 1, 2), Philosopher::new(\"Karl Marx\", 2, 3), Philosopher::new(\"Emma Goldman\", 3, 4), Philosopher::new(\"Michel Foucault\", 0, 4), ]; ``` We need to pass in our `left` and `right` values to the constructors for our `Philosopher`s. But there’s one more detail here, and it’s _very_ important. If you look at the pattern, it’s all consistent until the very end. Monsieur Foucault should have `4, 0` as arguments, but instead, has `0, 4`. This is what prevents deadlock, actually: one of our philosophers is left handed! This is one way to solve the problem, and in my opinion, it’s the simplest. If you change the order of the parameters, you will be able to observe the deadlock taking place. ```rust,ignore let handles: Vec<_> = philosophers.into_iter().map(|p| { let table = table.clone(); thread::spawn(move || { p.eat(&table); }) }).collect(); ``` Finally, inside of our `map()`/`collect()` loop, we call `table.clone()`. The `clone()` method on `Arc` is what bumps up the reference count, and when it goes out of scope, it decrements the count. This is needed so that we know how many references to `table` exist across our threads. If we didn’t have a count, we wouldn’t know how to deallocate it. You’ll notice we can introduce a new binding to `table` here, and it will shadow the old one. This is often used so that you don’t need to come up with two unique names. With this, our program works! Only two philosophers can eat at any one time, and so you’ll get some output like this: ```text Gilles Deleuze is eating. Emma Goldman is eating. Emma Goldman is done eating. Gilles Deleuze is done eating. Judith Butler is eating. Karl Marx is eating. Judith Butler is done eating. Michel Foucault is eating. Karl Marx is done eating. Michel Foucault is done eating. ``` Congrats! You’ve implemented a classic concurrency problem in Rust. "} {"_id":"doc-en-rust-b61ee9be3fa762c7b8fd2212493de15737331d7996e4ec0bd013c7cdff59669a","title":"","text":"% Guessing Game For our first project, we’ll implement a classic beginner programming problem: the guessing game. Here’s how it works: Our program will generate a random integer between one and a hundred. It will then prompt us to enter a guess. Upon entering our guess, it will tell us if we’re too low or too high. Once we guess correctly, it will congratulate us. Sounds good? Let’s learn some Rust! For our first project, we’ll implement a classic beginner programming problem: the guessing game. Here’s how it works: Our program will generate a random integer between one and a hundred. It will then prompt us to enter a guess. Upon entering our guess, it will tell us if we’re too low or too high. Once we guess correctly, it will congratulate us. Sounds good? Along the way, we’ll learn a little bit about Rust. The next section, ‘Syntax and Semantics’, will dive deeper into each part. # Set up"} {"_id":"doc-en-rust-ee9291f62ecc808e147f53e7bf560f443fbc7603a7c3fdef646df7cecd834766","title":"","text":" % Rust Inside Other Languages For our third project, we’re going to choose something that shows off one of Rust’s greatest strengths: a lack of a substantial runtime. As organizations grow, they increasingly rely on a multitude of programming languages. Different programming languages have different strengths and weaknesses, and a polyglot stack lets you use a particular language where its strengths make sense and a different one where it’s weak. A very common area where many programming languages are weak is in runtime performance of programs. Often, using a language that is slower, but offers greater programmer productivity, is a worthwhile trade-off. To help mitigate this, they provide a way to write some of your system in C and then call that C code as though it were written in the higher-level language. This is called a ‘foreign function interface’, often shortened to ‘FFI’. Rust has support for FFI in both directions: it can call into C code easily, but crucially, it can also be called _into_ as easily as C. Combined with Rust’s lack of a garbage collector and low runtime requirements, this makes Rust a great candidate to embed inside of other languages when you need that extra oomph. There is a whole [chapter devoted to FFI][ffi] and its specifics elsewhere in the book, but in this chapter, we’ll examine this particular use-case of FFI, with examples in Ruby, Python, and JavaScript. [ffi]: ffi.html # The problem There are many different projects we could choose here, but we’re going to pick an example where Rust has a clear advantage over many other languages: numeric computing and threading. Many languages, for the sake of consistency, place numbers on the heap, rather than on the stack. Especially in languages that focus on object-oriented programming and use garbage collection, heap allocation is the default. Sometimes optimizations can stack allocate particular numbers, but rather than relying on an optimizer to do its job, we may want to ensure that we’re always using primitive number types rather than some sort of object type. Second, many languages have a ‘global interpreter lock’ (GIL), which limits concurrency in many situations. This is done in the name of safety, which is a positive effect, but it limits the amount of work that can be done at the same time, which is a big negative. To emphasize these two aspects, we’re going to create a little project that uses these two aspects heavily. Since the focus of the example is to embed Rust into other languages, rather than the problem itself, we’ll just use a toy example: > Start ten threads. Inside each thread, count from one to five million. After > all ten threads are finished, print out ‘done!’. I chose five million based on my particular computer. Here’s an example of this code in Ruby: ```ruby threads = [] 10.times do threads << Thread.new do count = 0 5_000_000.times do count += 1 end count end end threads.each do |t| puts \"Thread finished with count=#{t.value}\" end puts \"done!\" ``` Try running this example, and choose a number that runs for a few seconds. Depending on your computer’s hardware, you may have to increase or decrease the number. On my system, running this program takes `2.156` seconds. And, if I use some sort of process monitoring tool, like `top`, I can see that it only uses one core on my machine. That’s the GIL kicking in. While it’s true that this is a synthetic program, one can imagine many problems that are similar to this in the real world. For our purposes, spinning up a few busy threads represents some sort of parallel, expensive computation. # A Rust library Let’s rewrite this problem in Rust. First, let’s make a new project with Cargo: ```bash $ cargo new embed $ cd embed ``` This program is fairly easy to write in Rust: ```rust use std::thread; fn process() { let handles: Vec<_> = (0..10).map(|_| { thread::spawn(|| { let mut x = 0; for _ in 0..5_000_000 { x += 1 } x }) }).collect(); for h in handles { println!(\"Thread finished with count={}\", h.join().map_err(|_| \"Could not join a thread!\").unwrap()); } } ``` Some of this should look familiar from previous examples. We spin up ten threads, collecting them into a `handles` vector. Inside of each thread, we loop five million times, and add one to `x` each time. Finally, we join on each thread. Right now, however, this is a Rust library, and it doesn’t expose anything that’s callable from C. If we tried to hook this up to another language right now, it wouldn’t work. We only need to make two small changes to fix this, though. The first is to modify the beginning of our code: ```rust,ignore #[no_mangle] pub extern fn process() { ``` We have to add a new attribute, `no_mangle`. When you create a Rust library, it changes the name of the function in the compiled output. The reasons for this are outside the scope of this tutorial, but in order for other languages to know how to call the function, we can’t do that. This attribute turns that behavior off. The other change is the `pub extern`. The `pub` means that this function should be callable from outside of this module, and the `extern` says that it should be able to be called from C. That’s it! Not a whole lot of change. The second thing we need to do is to change a setting in our `Cargo.toml`. Add this at the bottom: ```toml [lib] name = \"embed\" crate-type = [\"dylib\"] ``` This tells Rust that we want to compile our library into a standard dynamic library. By default, Rust compiles an ‘rlib’, a Rust-specific format. Let’s build the project now: ```bash $ cargo build --release Compiling embed v0.1.0 (file:///home/steve/src/embed) ``` We’ve chosen `cargo build --release`, which builds with optimizations on. We want this to be as fast as possible! You can find the output of the library in `target/release`: ```bash $ ls target/release/ build deps examples libembed.so native ``` That `libembed.so` is our ‘shared object’ library. We can use this file just like any shared object library written in C! As an aside, this may be `embed.dll` (Microsoft Windows) or `libembed.dylib` (Mac OS X), depending on your operating system. Now that we’ve got our Rust library built, let’s use it from our Ruby. # Ruby Open up an `embed.rb` file inside of our project, and do this: ```ruby require 'ffi' module Hello extend FFI::Library ffi_lib 'target/release/libembed.so' attach_function :process, [], :void end Hello.process puts 'done!' ``` Before we can run this, we need to install the `ffi` gem: ```bash $ gem install ffi # this may need sudo Fetching: ffi-1.9.8.gem (100%) Building native extensions. This could take a while... Successfully installed ffi-1.9.8 Parsing documentation for ffi-1.9.8 Installing ri documentation for ffi-1.9.8 Done installing documentation for ffi after 0 seconds 1 gem installed ``` And finally, we can try running it: ```bash $ ruby embed.rb Thread finished with count=5000000 Thread finished with count=5000000 Thread finished with count=5000000 Thread finished with count=5000000 Thread finished with count=5000000 Thread finished with count=5000000 Thread finished with count=5000000 Thread finished with count=5000000 Thread finished with count=5000000 Thread finished with count=5000000 done! done! $ ``` Whoa, that was fast! On my system, this took `0.086` seconds, rather than the two seconds the pure Ruby version took. Let’s break down this Ruby code: ```ruby require 'ffi' ``` We first need to require the `ffi` gem. This lets us interface with our Rust library like a C library. ```ruby module Hello extend FFI::Library ffi_lib 'target/release/libembed.so' ``` The `Hello` module is used to attach the native functions from the shared library. Inside, we `extend` the necessary `FFI::Library` module and then call `ffi_lib` to load up our shared object library. We just pass it the path that our library is stored, which, as we saw before, is `target/release/libembed.so`. ```ruby attach_function :process, [], :void ``` The `attach_function` method is provided by the FFI gem. It’s what connects our `process()` function in Rust to a Ruby function of the same name. Since `process()` takes no arguments, the second parameter is an empty array, and since it returns nothing, we pass `:void` as the final argument. ```ruby Hello.process ``` This is the actual call into Rust. The combination of our `module` and the call to `attach_function` sets this all up. It looks like a Ruby function but is actually Rust! ```ruby puts 'done!' ``` Finally, as per our project’s requirements, we print out `done!`. That’s it! As we’ve seen, bridging between the two languages is really easy, and buys us a lot of performance. Next, let’s try Python! # Python Create an `embed.py` file in this directory, and put this in it: ```python from ctypes import cdll lib = cdll.LoadLibrary(\"target/release/libembed.so\") lib.process() print(\"done!\") ``` Even easier! We use `cdll` from the `ctypes` module. A quick call to `LoadLibrary` later, and we can call `process()`. On my system, this takes `0.017` seconds. Speedy! # Node.js Node isn’t a language, but it’s currently the dominant implementation of server-side JavaScript. In order to do FFI with Node, we first need to install the library: ```bash $ npm install ffi ``` After that installs, we can use it: ```javascript var ffi = require('ffi'); var lib = ffi.Library('target/release/libembed', { 'process': ['void', []] }); lib.process(); console.log(\"done!\"); ``` It looks more like the Ruby example than the Python example. We use the `ffi` module to get access to `ffi.Library()`, which loads up our shared object. We need to annotate the return type and argument types of the function, which are `void` for return and an empty array to signify no arguments. From there, we just call it and print the result. On my system, this takes a quick `0.092` seconds. # Conclusion As you can see, the basics of doing this are _very_ easy. Of course, there's a lot more that we could do here. Check out the [FFI][ffi] chapter for more details. "} {"_id":"doc-en-rust-f4d6ec07215a1a32663b89912b6987b6ce425def3d306872ad55a6423dedac7f","title":"","text":"``` ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType` ``` Note that this does not move `v` (unlike `transmute`), and may need a call to `mem::forget(v)` in case you want to avoid destructors being called. \"##, E0152: r##\""} {"_id":"doc-en-rust-6636f990a39255ba74688b8fb175988ea52afdbab1647bcbf476ad7d73749fdf","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] impl Ord for Ipv4Addr { fn cmp(&self, other: &Ipv4Addr) -> Ordering { self.inner.s_addr.cmp(&other.inner.s_addr) self.octets().cmp(&other.octets()) } }"} {"_id":"doc-en-rust-ae57fb92b8300ccdde4af82f61abb84f8d987019d221aa0f9515fbe51c9272bf","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] impl Ord for Ipv6Addr { fn cmp(&self, other: &Ipv6Addr) -> Ordering { self.inner.s6_addr.cmp(&other.inner.s6_addr) self.segments().cmp(&other.segments()) } }"} {"_id":"doc-en-rust-21c02b5cc2cd4d8c1ba6360d77af994dac635dd907712c91e935a84f09769917","title":"","text":"let a = Ipv4Addr::new(127, 0, 0, 1); assert_eq!(Ipv4Addr::from(2130706433), a); } #[test] fn ord() { assert!(Ipv4Addr::new(100, 64, 3, 3) < Ipv4Addr::new(192, 0, 2, 2)); assert!(\"2001:db8:f00::1002\".parse::().unwrap() < \"2001:db8:f00::2001\".parse::().unwrap()); } }"} {"_id":"doc-en-rust-35a7083761c329b8dd635ddd44271be2f6324524f952444696f07fffd2357c3d","title":"","text":" // Regression test for #29988 // compile-flags: -C no-prepopulate-passes // only-x86_64 // ignore-windows #[repr(C)] struct S { f1: i32, f2: i32, f3: i32, } extern { fn foo(s: S); } fn main() { let s = S { f1: 1, f2: 2, f3: 3 }; unsafe { // CHECK: load { i64, i32 }, { i64, i32 }* {{.*}}, align 4 // CHECK: call void @foo({ i64, i32 } {{.*}}) foo(s); } } "} {"_id":"doc-en-rust-698c3311aa3dbf2d1b8427d5e0c10ba4e04ac276670370dbd5aaae7dd31d41a9","title":"","text":" enum Bug { Var = { let x: S = 0; //~ ERROR: mismatched types 0 }, } fn main() {} "} {"_id":"doc-en-rust-c63951d94861c953072be302539c9e4563b619eb81d8e12ec352648e834e6a4f","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-67945-1.rs:3:20 | LL | enum Bug { | - this type parameter LL | Var = { LL | let x: S = 0; | - ^ expected type parameter `S`, found integer | | | expected due to this | = note: expected type parameter `S` found type `{integer}` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-f652d675ec8f5fcfd73aa32554f64e24f3a2e41e5201ba93acb1cdb2977965e1","title":"","text":" #![feature(type_ascription)] enum Bug { Var = 0: S, //~^ ERROR: mismatched types //~| ERROR: mismatched types } fn main() {} "} {"_id":"doc-en-rust-2c693447b59b202cb8bcd7918ac10104329e775c2027f37598f5cd44b5935973","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-67945-2.rs:4:11 | LL | enum Bug { | - this type parameter LL | Var = 0: S, | ^ expected type parameter `S`, found integer | = note: expected type parameter `S` found type `{integer}` error[E0308]: mismatched types --> $DIR/issue-67945-2.rs:4:11 | LL | enum Bug { | - this type parameter LL | Var = 0: S, | ^^^^ expected `isize`, found type parameter `S` | = note: expected type `isize` found type parameter `S` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-bb986ae4763f2ed124451eb7b166e2d5f84f7a021234a61a9b2038d442dab406","title":"","text":" trait Foo {} impl<'a, T> Foo for &'a T {} struct Ctx<'a>(&'a ()) where &'a (): Foo, //~ ERROR: type annotations needed &'static (): Foo; fn main() {} "} {"_id":"doc-en-rust-ce30cd927de832b35372c5bdbb7413ecfee46e8e5e0e7e00fe7f022990f3cfb4","title":"","text":" error[E0283]: type annotations needed --> $DIR/issue-34979.rs:6:13 | LL | trait Foo {} | --------- required by this bound in `Foo` ... LL | &'a (): Foo, | ^^^ cannot infer type for reference `&'a ()` | = note: cannot satisfy `&'a (): Foo` error: aborting due to previous error For more information about this error, try `rustc --explain E0283`. "} {"_id":"doc-en-rust-92915fbf0416dad279364540de35e3fc116f68fbf108df3fd14dc6b8191297b0","title":"","text":"fn consume(&mut self, amt: usize) { self.pos += amt as u64; } } // Non-resizing write implementation fn slice_write(pos_mut: &mut u64, slice: &mut [u8], buf: &[u8]) -> io::Result { let pos = cmp::min(*pos_mut, slice.len() as u64); let amt = (&mut slice[(pos as usize)..]).write(buf)?; *pos_mut += amt as u64; Ok(amt) } // Resizing write implementation fn vec_write(pos_mut: &mut u64, vec: &mut Vec, buf: &[u8]) -> io::Result { let pos: usize = (*pos_mut).try_into().map_err(|_| { Error::new(ErrorKind::InvalidInput, \"cursor position exceeds maximum possible vector length\") })?; // Make sure the internal buffer is as least as big as where we // currently are let len = vec.len(); if len < pos { // use `resize` so that the zero filling is as efficient as possible vec.resize(pos, 0); } // Figure out what bytes will be used to overwrite what's currently // there (left), and what will be appended on the end (right) { let space = vec.len() - pos; let (left, right) = buf.split_at(cmp::min(space, buf.len())); vec[pos..pos + left.len()].copy_from_slice(left); vec.extend_from_slice(right); } // Bump us forward *pos_mut = (pos + buf.len()) as u64; Ok(buf.len()) } #[stable(feature = \"rust1\", since = \"1.0.0\")] impl<'a> Write for Cursor<&'a mut [u8]> { #[inline] fn write(&mut self, data: &[u8]) -> io::Result { let pos = cmp::min(self.pos, self.inner.len() as u64); let amt = (&mut self.inner[(pos as usize)..]).write(data)?; self.pos += amt as u64; Ok(amt) fn write(&mut self, buf: &[u8]) -> io::Result { slice_write(&mut self.pos, self.inner, buf) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[unstable(feature = \"cursor_mut_vec\", issue = \"30132\")] impl<'a> Write for Cursor<&'a mut Vec> { fn write(&mut self, buf: &[u8]) -> io::Result { vec_write(&mut self.pos, self.inner, buf) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }"} {"_id":"doc-en-rust-3c61b1cc876b3905b331d32a67286644cded4cb372afc9ce9414c94f40c70c6b","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] impl Write for Cursor> { fn write(&mut self, buf: &[u8]) -> io::Result { let pos: usize = self.position().try_into().map_err(|_| { Error::new(ErrorKind::InvalidInput, \"cursor position exceeds maximum possible vector length\") })?; // Make sure the internal buffer is as least as big as where we // currently are let len = self.inner.len(); if len < pos { // use `resize` so that the zero filling is as efficient as possible self.inner.resize(pos, 0); } // Figure out what bytes will be used to overwrite what's currently // there (left), and what will be appended on the end (right) { let space = self.inner.len() - pos; let (left, right) = buf.split_at(cmp::min(space, buf.len())); self.inner[pos..pos + left.len()].copy_from_slice(left); self.inner.extend_from_slice(right); } // Bump us forward self.set_position((pos + buf.len()) as u64); Ok(buf.len()) vec_write(&mut self.pos, &mut self.inner, buf) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }"} {"_id":"doc-en-rust-741f038fc50c28e424ce49abfd0d1bbb27bc8d5262e9523e7ced9b3c52b2cfe5","title":"","text":"impl Write for Cursor> { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result { let pos = cmp::min(self.pos, self.inner.len() as u64); let amt = (&mut self.inner[(pos as usize)..]).write(buf)?; self.pos += amt as u64; Ok(amt) slice_write(&mut self.pos, &mut self.inner, buf) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }"} {"_id":"doc-en-rust-d294d85f957a8619ec557145cfe86dcf6b802e5c9ebdf160b251a1ee8f8d47b8","title":"","text":"} #[test] fn test_mem_mut_writer() { let mut vec = Vec::new(); let mut writer = Cursor::new(&mut vec); assert_eq!(writer.write(&[0]).unwrap(), 1); assert_eq!(writer.write(&[1, 2, 3]).unwrap(), 3); assert_eq!(writer.write(&[4, 5, 6, 7]).unwrap(), 4); let b: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7]; assert_eq!(&writer.get_ref()[..], b); } #[test] fn test_box_slice_writer() { let mut writer = Cursor::new(vec![0u8; 9].into_boxed_slice()); assert_eq!(writer.position(), 0);"} {"_id":"doc-en-rust-f9f432b28713f634fb92606023a0fb35fde84c10e4187821fada48fccaee8957","title":"","text":"``` You'll notice that you don't need a `fn main()` or anything here. `rustdoc` will automatically add a `main()` wrapper around your code, and in the right place. For example: automatically add a `main()` wrapper around your code, using heuristics to attempt to put it in the right place. For example: ```rust /// ```"} {"_id":"doc-en-rust-d6839759505fb3c5f6f84fa7073980019ebf094e7de9fdb99a97595c28048b2e","title":"","text":"`unused_attributes`, and `dead_code`. Small examples often trigger these lints. 3. If the example does not contain `extern crate`, then `extern crate ;` is inserted. 2. Finally, if the example does not contain `fn main`, the remainder of the text is wrapped in `fn main() { your_code }` Sometimes, this isn't enough, though. For example, all of these code samples ;` is inserted (note the lack of `#[macro_use]`). 4. Finally, if the example does not contain `fn main`, the remainder of the text is wrapped in `fn main() { your_code }`. This generated `fn main` can be a problem! If you have `extern crate` or a `mod` statements in the example code that are referred to by `use` statements, they will fail to resolve unless you include at least `fn main() {}` to inhibit step 4. `#[macro_use] extern crate` also does not work except at the crate root, so when testing macros an explicit `main` is always required. It doesn't have to clutter up your docs, though -- keep reading! Sometimes this algorithm isn't enough, though. For example, all of these code samples with `///` we've been talking about? The raw text: ```text"} {"_id":"doc-en-rust-203ec5b5c7ed82d71572d3ba01c1f5bb447afa29d9505d2583825b03a17fa6d0","title":"","text":"You’ll note three things: we need to add our own `extern crate` line, so that we can add the `#[macro_use]` attribute. Second, we’ll need to add our own `main()` as well. Finally, a judicious use of `#` to comment out those two things, so they don’t show up in the output. `main()` as well (for reasons discussed above). Finally, a judicious use of `#` to comment out those two things, so they don’t show up in the output. Another case where the use of `#` is handy is when you want to ignore error handling. Lets say you want the following,"} {"_id":"doc-en-rust-f204fc99f2aa6379497b74ec81e4ca3d611d662dd977591485e5369e5d2cd5b0","title":"","text":"// the merge has confused the heck out of josh in the past. // We pass `--no-verify` to avoid running git hooks like `./miri fmt` that could in turn // trigger auto-actions. sh.write_file(\"rust-version\", &commit)?; sh.write_file(\"rust-version\", format!(\"{commit}n\"))?; const PREPARING_COMMIT_MESSAGE: &str = \"Preparing for merge from rustc\"; cmd!(sh, \"git commit rust-version --no-verify -m {PREPARING_COMMIT_MESSAGE}\") .run()"} {"_id":"doc-en-rust-13547713196d3df676561f599d894c1cf65ff098e8d9f9e78b076c44caa880dd","title":"","text":"// interleaving, but wether UB happens can depend on whether a write occurs in the // future... let is_write = new_perm.initial_state.is_active() || (new_perm.initial_state.is_resrved() && new_perm.protector.is_some()); || (new_perm.initial_state.is_reserved() && new_perm.protector.is_some()); if is_write { // Need to get mutable access to alloc_extra. // (Cannot always do this as we can do read-only reborrowing on read-only allocations.)"} {"_id":"doc-en-rust-3ae5c75c7e70e6f94fb2a14a00738d579ed341579feed3e3595ce2fe234510bd","title":"","text":"matches!(self.inner, Active) } pub fn is_resrved(self) -> bool { pub fn is_reserved(self) -> bool { matches!(self.inner, Reserved { .. }) }"} {"_id":"doc-en-rust-198fc16bb90497cfb332e19864f84c3ae04617279a7858caad47d20bc7526e5e","title":"","text":"/// in an existing allocation, then returns Err containing the position /// where such allocation should be inserted fn find_offset(&self, offset: Size) -> Result { // We do a binary search. let mut left = 0usize; // inclusive let mut right = self.v.len(); // exclusive loop { if left == right { // No element contains the given offset. But the // position is where such element should be placed at. return Err(left); } let candidate = left.checked_add(right).unwrap() / 2; let elem = &self.v[candidate]; self.v.binary_search_by(|elem| -> std::cmp::Ordering { if offset < elem.range.start { // We are too far right (offset is further left). debug_assert!(candidate < right); // we are making progress right = candidate; std::cmp::Ordering::Greater } else if offset >= elem.range.end() { // We are too far left (offset is further right). debug_assert!(candidate >= left); // we are making progress left = candidate + 1; std::cmp::Ordering::Less } else { // This is it! return Ok(candidate); std::cmp::Ordering::Equal } } }) } /// Determines whether a given access on `range` overlaps with"} {"_id":"doc-en-rust-761f50ba59787d1f702bc334dab2bdb5bd092cc344eac4320b858e0b7738412b","title":"","text":"} ``` Your structure can still contain `&mut` pointers, which will let you do some kinds of mutation: ```rust struct Point { x: i32, y: i32, } struct PointRef<'a> { x: &'a mut i32, y: &'a mut i32, } fn main() { let mut point = Point { x: 0, y: 0 }; { let r = PointRef { x: &mut point.x, y: &mut point.y }; *r.x = 5; *r.y = 6; } assert_eq!(5, point.x); assert_eq!(6, point.y); } ``` # Update syntax A `struct` can include `..` to indicate that you want to use a copy of some"} {"_id":"doc-en-rust-72a411545c02d15e15782fe210c9779a3cb4733b8f2d2de50b85e16612878864","title":"","text":"self } /// Configuration for the child process’s standard input (stdin) handle. /// /// See [`std::process::Command::stdin`]. pub fn stdin>(&mut self, cfg: T) -> &mut Self { self.cmd.stdin(cfg); self } /// Configuration for the child process’s standard output (stdout) handle. /// /// See [`std::process::Command::stdout`]. pub fn stdout>(&mut self, cfg: T) -> &mut Self { self.cmd.stdout(cfg); self } /// Configuration for the child process’s standard error (stderr) handle. /// /// See [`std::process::Command::stderr`]. pub fn stderr>(&mut self, cfg: T) -> &mut Self { self.cmd.stderr(cfg); self } /// Inspect what the underlying [`Command`] is up to the /// current construction. pub fn inspect(&mut self, inspector: I) -> &mut Self"} {"_id":"doc-en-rust-be4bf8aa43796e52bfc1b58b6ab2d983645f06d3e52bd26a9ef9e90a91bbe790","title":"","text":"run-make/branch-protection-check-IBT/Makefile run-make/cat-and-grep-sanity-check/Makefile run-make/emit-to-stdout/Makefile run-make/extern-fn-reachable/Makefile run-make/incr-add-rust-src-component/Makefile run-make/issue-84395-lto-embed-bitcode/Makefile"} {"_id":"doc-en-rust-aa3e033b859bc2ad8a46194d619233d05b7962048198a569e7a5315e82fb9455","title":"","text":"ui/consts/issue-73976-monomorphic.rs ui/consts/issue-73976-polymorphic.rs ui/consts/issue-76064.rs ui/consts/issue-77062-large-zst-array.rs ui/consts/issue-78655.rs ui/consts/issue-79137-monomorphic.rs ui/consts/issue-79137-toogeneric.rs"} {"_id":"doc-en-rust-715608a4e7fd8b4d4848152043bfe12747cf1bd2233fed303ce01ba46e9a10ca","title":"","text":" include ../tools.mk SRC=test.rs OUT=$(TMPDIR)/out all: asm llvm-ir dep-info mir llvm-bc obj metadata link multiple-types multiple-types-option-o asm: $(OUT) $(RUSTC) --emit asm=$(OUT)/$@ $(SRC) $(RUSTC) --emit asm=- $(SRC) | diff - $(OUT)/$@ llvm-ir: $(OUT) $(RUSTC) --emit llvm-ir=$(OUT)/$@ $(SRC) $(RUSTC) --emit llvm-ir=- $(SRC) | diff - $(OUT)/$@ dep-info: $(OUT) $(RUSTC) -Z dep-info-omit-d-target=yes --emit dep-info=$(OUT)/$@ $(SRC) $(RUSTC) --emit dep-info=- $(SRC) | diff - $(OUT)/$@ mir: $(OUT) $(RUSTC) --emit mir=$(OUT)/$@ $(SRC) $(RUSTC) --emit mir=- $(SRC) | diff - $(OUT)/$@ llvm-bc: $(OUT) $(RUSTC) --emit llvm-bc=- $(SRC) 1>/dev/ptmx 2>$(OUT)/$@ || true diff $(OUT)/$@ emit-llvm-bc.stderr obj: $(OUT) $(RUSTC) --emit obj=- $(SRC) 1>/dev/ptmx 2>$(OUT)/$@ || true diff $(OUT)/$@ emit-obj.stderr # For metadata output, a temporary directory will be created to hold the temporary # metadata file. But when output is stdout, the temporary directory will be located # in the same place as $(SRC), which is mounted as read-only in the tests. Thus as # a workaround, $(SRC) is copied to the test output directory $(OUT) and we compile # it there. metadata: $(OUT) cp $(SRC) $(OUT) (cd $(OUT); $(RUSTC) --emit metadata=- $(SRC) 1>/dev/ptmx 2>$(OUT)/$@ || true) diff $(OUT)/$@ emit-metadata.stderr link: $(OUT) $(RUSTC) --emit link=- $(SRC) 1>/dev/ptmx 2>$(OUT)/$@ || true diff $(OUT)/$@ emit-link.stderr multiple-types: $(OUT) $(RUSTC) --emit asm=- --emit llvm-ir=- --emit dep-info=- --emit mir=- $(SRC) 2>$(OUT)/$@ || true diff $(OUT)/$@ emit-multiple-types.stderr multiple-types-option-o: $(OUT) $(RUSTC) -o - --emit asm,llvm-ir,dep-info,mir $(SRC) 2>$(OUT)/$@ || true diff $(OUT)/$@ emit-multiple-types.stderr $(OUT): mkdir -p $(OUT) "} {"_id":"doc-en-rust-25d69cb41dd162ab07c7be474e971b99d45ff4fd914ff46ef9466459ce140a68","title":"","text":" //! If `-o -` or `--emit KIND=-` is provided, output should be written to stdout //! instead. Binary output (`obj`, `llvm-bc`, `link` and `metadata`) //! being written this way will result in an error if stdout is a tty. //! Multiple output types going to stdout will trigger an error too, //! as they would all be mixed together. //! //! See . use std::fs::File; use run_make_support::{diff, run_in_tmpdir, rustc}; // Test emitting text outputs to stdout works correctly fn run_diff(name: &str, file_args: &[&str]) { rustc().emit(format!(\"{name}={name}\")).input(\"test.rs\").args(file_args).run(); let out = rustc().emit(format!(\"{name}=-\")).input(\"test.rs\").run().stdout_utf8(); diff().expected_file(name).actual_text(\"stdout\", &out).run(); } // Test that emitting binary formats to a terminal gives the correct error fn run_terminal_err_diff(name: &str) { #[cfg(not(windows))] let terminal = File::create(\"/dev/ptmx\").unwrap(); // FIXME: If this test fails and the compiler does print to the console, // then this will produce a lot of output. // We should spawn a new console instead to print stdout. #[cfg(windows)] let terminal = File::options().read(true).write(true).open(r\".CONOUT$\").unwrap(); let err = File::create(name).unwrap(); rustc().emit(format!(\"{name}=-\")).input(\"test.rs\").stdout(terminal).stderr(err).run_fail(); diff().expected_file(format!(\"emit-{name}.stderr\")).actual_file(name).run(); } fn main() { run_in_tmpdir(|| { run_diff(\"asm\", &[]); run_diff(\"llvm-ir\", &[]); run_diff(\"dep-info\", &[\"-Zdep-info-omit-d-target=yes\"]); run_diff(\"mir\", &[]); run_terminal_err_diff(\"llvm-bc\"); run_terminal_err_diff(\"obj\"); run_terminal_err_diff(\"metadata\"); run_terminal_err_diff(\"link\"); // Test error for emitting multiple types to stdout rustc() .input(\"test.rs\") .emit(\"asm=-\") .emit(\"llvm-ir=-\") .emit(\"dep-info=-\") .emit(\"mir=-\") .stderr(File::create(\"multiple-types\").unwrap()) .run_fail(); diff().expected_file(\"emit-multiple-types.stderr\").actual_file(\"multiple-types\").run(); // Same as above, but using `-o` rustc() .input(\"test.rs\") .output(\"-\") .emit(\"asm,llvm-ir,dep-info,mir\") .stderr(File::create(\"multiple-types-option-o\").unwrap()) .run_fail(); diff() .expected_file(\"emit-multiple-types.stderr\") .actual_file(\"multiple-types-option-o\") .run(); // Test that `-o -` redirected to a file works correctly (#26719) rustc().input(\"test.rs\").output(\"-\").stdout(File::create(\"out-stdout\").unwrap()).run(); }); } "} {"_id":"doc-en-rust-ef498a5b44eeef24c4f40595e7d15b8537e13b59d0e55f0d3de5e1f64c868016","title":"","text":" //@ build-pass fn main() { let _ = &[(); usize::MAX]; } "} {"_id":"doc-en-rust-2165871f623fb75a8c4854b95b1622db6ea54d1c27e6731ebb2c970e40bc4a73","title":"","text":" //@ build-pass pub static FOO: [(); usize::MAX] = [(); usize::MAX]; fn main() { let _ = &[(); usize::MAX]; } "} {"_id":"doc-en-rust-f976594a0535e33bf80687fa37b9c9d3a55eaac371e52db67b486f828dff3ba7","title":"","text":" //@ check-pass //! Tests that associated type projections normalize properly in the presence of HRTBs. //! Original issue: pub trait MyFrom {} impl MyFrom for T {} pub trait MyInto {} impl MyInto for T where U: MyFrom {} pub trait A<'self_> { type T; } pub trait B: for<'self_> A<'self_> { // Originally caused the `type U = usize` example below to fail with a type mismatch error type U: for<'self_> MyFrom<>::T>; } pub struct M; impl<'self_> A<'self_> for M { type T = usize; } impl B for M { type U = usize; } fn main() {} "} {"_id":"doc-en-rust-354f887786d8d3ff3ea451f61c8df22cbac1b63c4b612a113099faaa918d4248","title":"","text":" //@ check-pass //! Tests that a HRTB + FnOnce bound involving an associated type don't prevent //! a function pointer from implementing `Fn` traits. //! Test for trait LifetimeToType<'a> { type Out; } impl<'a> LifetimeToType<'a> for () { type Out = &'a (); } fn id<'a>(val: &'a ()) -> <() as LifetimeToType<'a>>::Out { val } fn assert_fn FnOnce(&'a ()) -> <() as LifetimeToType<'a>>::Out>(_func: F) { } fn main() { assert_fn(id); } "} {"_id":"doc-en-rust-de76ec1c527e3e751a913feabd503ff0ce24c34283eb58b9f8de1db7d2955a67","title":"","text":" //@ check-pass //! Tests that HRTB impl selection covers type parameters not directly related //! to the trait. //! Test for #![crate_type = \"lib\"] trait Unary {} impl U> Unary for F {} fn unary Unary<&'a T>, T>() {} pub fn test Fn(&'a i32) -> &'a i32>() { unary::() } "} {"_id":"doc-en-rust-62aae9ffca07801c4c02852e0118000188ff7580bc506d7813dcea9af032d209","title":"","text":"// These items live in the type namespace. ItemTy(..) => { let parent_link = ModuleParentLink(parent, name); let def = Def::TyAlias(self.ast_map.local_def_id(item.id)); let module = self.new_module(parent_link, Some(def), false, is_public); self.define(parent, name, TypeNS, (module, sp)); self.define(parent, name, TypeNS, (def, sp, modifiers)); parent }"} {"_id":"doc-en-rust-3d6ba1bf6cc5d650c1eb634cf0785a6a7d882ec5f01bb87e2f7d382c17d0ab5a","title":"","text":"} match def { Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) | Def::TyAlias(..) => { Def::Mod(_) | Def::ForeignMod(_) | Def::Enum(..) => { debug!(\"(building reduced graph for external crate) building module {} {}\", final_ident, is_public);"} {"_id":"doc-en-rust-e259e0eaf5d12d162cc288e89f7512658c20e42fb8a8b698c0e131ca455e015c","title":"","text":"let module = self.new_module(parent_link, Some(def), true, is_public); self.try_define(new_parent, name, TypeNS, (module, DUMMY_SP)); } Def::AssociatedTy(..) => { Def::TyAlias(..) | Def::AssociatedTy(..) => { debug!(\"(building reduced graph for external crate) building type {}\", final_ident); self.try_define(new_parent, name, TypeNS, (def, DUMMY_SP, modifiers));"} {"_id":"doc-en-rust-39f798ae9849d5de4bfd079de52bcfe276f623f3d5122345f2effe36c70c4e24","title":"","text":"target_module: Module<'b>, directive: &'b ImportDirective) -> ResolveResult<()> { if let Some(Def::Trait(_)) = target_module.def { self.resolver.session.span_err(directive.span, \"items in traits are not importable.\"); } if module_.def_id() == target_module.def_id() { // This means we are trying to glob import a module into itself, and it is a no-go let msg = \"Cannot glob-import a module into itself.\".into();"} {"_id":"doc-en-rust-8df80afe3cb494eccf9554fbb990ed8da5e8d86187ae8cfe81e23738f4d698c4","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. type Alias = (); use Alias::*; //~ ERROR Not a module use std::io::Result::*; //~ ERROR Not a module trait T {} use T::*; //~ ERROR items in traits are not importable fn main() {} "} {"_id":"doc-en-rust-1b7696abc3f419163f3184c80b01cc347eb9716073610e0d1d3eb594f45f34aa","title":"","text":"#[stable(feature = \"rust1\", since = \"1.0.0\")] pub trait Drop { /// A method called when the value goes out of scope. /// /// When this method has been called, `self` has not yet been deallocated. /// If it were, `self` would be a dangling reference. /// /// After this function is over, the memory of `self` will be deallocated. /// /// # Panics /// /// Given that a `panic!` will call `drop()` as it unwinds, any `panic!` in /// a `drop()` implementation will likely abort. #[stable(feature = \"rust1\", since = \"1.0.0\")] fn drop(&mut self); }"} {"_id":"doc-en-rust-3d1d613a403dde3b157ed18807721f478be8430bb13fb9f5955878261e23151d","title":"","text":"/// /// assert!(ecode.success()); /// ``` /// /// # Note /// /// Take note that there is no implementation of /// [`Drop`](../../core/ops/trait.Drop.html) for child processes, so if you /// do not ensure the `Child` has exited then it will continue to run, even /// after the `Child` handle to the child process has gone out of scope. /// /// Calling `wait` (or other functions that wrap around it) will make the /// parent process wait until the child has actually exited before continuing. #[stable(feature = \"process\", since = \"1.0.0\")] pub struct Child { handle: imp::Process,"} {"_id":"doc-en-rust-32b1cd5eb91134a3a026e6991cda0840c9372d508022048d00a1ca782ccf8f37","title":"","text":"use something::Foo; // error: unresolved import `something::Foo`. ``` Please verify you didn't misspell the import name or the import does exist in the module from where you tried to import it. Example: Paths in `use` statements are relative to the crate root. To import items relative to the current and parent modules, use the `self::` and `super::` prefixes, respectively. Also verify that you didn't misspell the import name and that the import exists in the module from where you tried to import it. Example: ```ignore use something::Foo; // ok! use self::something::Foo; // ok! mod something { pub struct Foo;"} {"_id":"doc-en-rust-409daa07628c5eab5a3d998d58512d2835a8c3c4c010b272486f4204209365b6","title":"","text":"``` Or, if you tried to use a module from an external crate, you may have missed the `extern crate` declaration: the `extern crate` declaration (which is usually placed in the crate root): ```ignore extern crate homura; // Required to use the `homura` crate"} {"_id":"doc-en-rust-a90caf70b1a527aca7bdfec9be38c26d62c24fbfa85afcd7f016789d00437e50","title":"","text":"// has anchors for the line numbers that we're linking to. } else if self.item.def_id.is_local() { self.cx.local_sources.get(&PathBuf::from(&self.item.source.filename)).map(|path| { format!(\"{root}src/{krate}/{path}.html#{href}\", format!(\"{root}src/{krate}/{path}#{href}\", root = self.cx.root_path, krate = self.cx.layout.krate, path = path,"} {"_id":"doc-en-rust-0eb3a2ef6ae2ba2ceb051567d2e6d862d5fd173e3be2207f3db8d0c9ee7aebe0","title":"","text":"} } fn increment_outstanding_references(&mut self, is_public: bool) { self.outstanding_references += 1; if is_public { self.pub_outstanding_references += 1; } } fn decrement_outstanding_references(&mut self, is_public: bool) { let decrement_references = |count: &mut _| { assert!(*count > 0); *count -= 1; }; decrement_references(&mut self.outstanding_references); if is_public { decrement_references(&mut self.pub_outstanding_references); } } fn report_conflicts(&self, mut report: F) { let binding = match self.binding { Some(binding) => binding,"} {"_id":"doc-en-rust-53d423c7b93fbbc610416e1dcb06f8004f7bcac466dd8fe10fd8852f7f0c5c92","title":"","text":"} pub fn increment_outstanding_references_for(&self, name: Name, ns: Namespace, is_public: bool) { let mut resolutions = self.resolutions.borrow_mut(); let resolution = resolutions.entry((name, ns)).or_insert_with(Default::default); resolution.outstanding_references += 1; if is_public { resolution.pub_outstanding_references += 1; } } fn decrement_outstanding_references_for(&self, name: Name, ns: Namespace, is_public: bool) { let decrement_references = |count: &mut _| { assert!(*count > 0); *count -= 1; }; self.update_resolution(name, ns, |resolution| { decrement_references(&mut resolution.outstanding_references); if is_public { decrement_references(&mut resolution.pub_outstanding_references); } }) self.resolutions.borrow_mut().entry((name, ns)).or_insert_with(Default::default) .increment_outstanding_references(is_public); } // Use `update` to mutate the resolution for the name."} {"_id":"doc-en-rust-efe07827c2a8a00221a654d844a57f0ec275463dd42e2a31555d5395223e30a1","title":"","text":"// Temporarily count the directive as determined so that the resolution fails // (as opposed to being indeterminate) when it can only be defined by the directive. if !determined { module_.decrement_outstanding_references_for(target, ns, directive.is_public) module_.resolutions.borrow_mut().get_mut(&(target, ns)).unwrap() .decrement_outstanding_references(directive.is_public); } let result = self.resolver.resolve_name_in_module(target_module, source, ns, false, true);"} {"_id":"doc-en-rust-91ab42eb7faf4f6e47a2ec66426ba38022c680b7c4740582c9f9b07797b46009","title":"","text":"self.report_conflict(target, ns, &directive.import(binding, None), old_binding); } } module_.decrement_outstanding_references_for(target, ns, directive.is_public); module_.update_resolution(target, ns, |resolution| { resolution.decrement_outstanding_references(directive.is_public); }) } match (&value_result, &type_result) {"} {"_id":"doc-en-rust-95a5222989c78f3ff8f6367c46cd3a6b4d12e78e84148080a658042419da77b2","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(rustc_attrs)] #![allow(warnings)] mod foo { pub fn bar() {} } pub use foo::*; use b::bar; mod foobar { use super::*; } mod a { pub mod bar {} } mod b { pub use a::bar; } #[rustc_error] fn main() {} //~ ERROR compilation successful "} {"_id":"doc-en-rust-d5c7df3c254f81e9f3fa0bad5829000fe7d95425b2d041b45d3edd70f0da6f4b","title":"","text":"* * # Safety note * * This function fails if `c` is not a valid char * This function returns none if `c` is not a valid char * * # Return value *"} {"_id":"doc-en-rust-7054cb99a9861645ef7b58f040dd2248a55e73e8e0b786788a4a659f6d466fc9","title":"","text":"/// println!(\"{}\", now.elapsed().as_secs()); /// } /// ``` /// /// # Underlying System calls /// Currently, the following system calls are being used to get the current time using `now()`: /// /// | Platform | System call | /// |:---------:|:--------------------------------------------------------------------:| /// | Cloud ABI | [clock_time_get (Monotonic Clock)] | /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] | /// | UNIX | [clock_time_get (Monotonic Clock)] | /// | Darwin | [mach_absolute_time] | /// | VXWorks | [clock_gettime (Monotonic Clock)] | /// | WASI | [__wasi_clock_time_get (Monotonic Clock)] | /// | Windows | [QueryPerformanceCounter] | /// /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/CraneStation/wasmtime/blob/master/docs/WASI-api.md#clock_time_get /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime /// [mach_absolute_time]: https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/services/services.html /// [clock_time_get (Monotonic Clock)]: https://github.com/NuxiNL/cloudabi/blob/master/cloudabi.txt /// /// **Disclaimer:** These system calls might change over time. /// #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[stable(feature = \"time2\", since = \"1.8.0\")] pub struct Instant(time::Instant);"} {"_id":"doc-en-rust-53c2b8dd4a86fda169927657a042b9dfb9009f7da7339c45153daf10340b3be8","title":"","text":"/// } /// } /// ``` /// /// # Underlying System calls /// Currently, the following system calls are being used to get the current time using `now()`: /// /// | Platform | System call | /// |:---------:|:--------------------------------------------------------------------:| /// | Cloud ABI | [clock_time_get (Realtime Clock)] | /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] | /// | UNIX | [clock_gettime (Realtime Clock)] | /// | DARWIN | [gettimeofday] | /// | VXWorks | [clock_gettime (Realtime Clock)] | /// | WASI | [__wasi_clock_time_get (Realtime Clock)] | /// | Windows | [GetSystemTimeAsFileTime] | /// /// [clock_time_get (Realtime Clock)]: https://github.com/NuxiNL/cloudabi/blob/master/cloudabi.txt /// [gettimeofday]: http://man7.org/linux/man-pages/man2/gettimeofday.2.html /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/CraneStation/wasmtime/blob/master/docs/WASI-api.md#clock_time_get /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime /// /// **Disclaimer:** These system calls might change over time. /// #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[stable(feature = \"time2\", since = \"1.8.0\")] pub struct SystemTime(time::SystemTime);"} {"_id":"doc-en-rust-2e71df928ce7bf217c4c0dfd859b8cf69f6ce4ff771daede15c2dcc04b00ccdb","title":"","text":"ret }); // Needs to go *after* expansion to be able to check the results // of macro expansion. This runs before #[cfg] to try to catch as // much as possible (e.g. help the programmer avoid platform // specific differences) time(time_passes, \"complete gated feature checking 1\", || { sess.track_errors(|| { let features = syntax::feature_gate::check_crate(sess.codemap(), &sess.parse_sess.span_diagnostic, &krate, &attributes, sess.opts.unstable_features); *sess.features.borrow_mut() = features; }) })?; // JBC: make CFG processing part of expansion to avoid this problem: // strip again, in case expansion added anything with a #[cfg]."} {"_id":"doc-en-rust-c843c3bd41f3df79540d8bfc8b83aab0c94cd1a4de42d62524fc47e9740b6b76","title":"","text":"\"checking for inline asm in case the target doesn't support it\", || no_asm::check_crate(sess, &krate)); // One final feature gating of the true AST that gets compiled // later, to make sure we've got everything (e.g. configuration // can insert new attributes via `cfg_attr`) time(time_passes, \"complete gated feature checking 2\", || { // Needs to go *after* expansion to be able to check the results of macro expansion. time(time_passes, \"complete gated feature checking\", || { sess.track_errors(|| { let features = syntax::feature_gate::check_crate(sess.codemap(), &sess.parse_sess.span_diagnostic,"} {"_id":"doc-en-rust-4d783f03143fcfd8f54fe201aebdd2da979c4ec9d47c13616620d7f6f6efdbf9","title":"","text":"// When we enter a module, record it, for the sake of `module!` pub fn expand_item(it: P, fld: &mut MacroExpander) -> SmallVector> { let it = expand_item_multi_modifier(Annotatable::Item(it), fld); expand_annotatable(it, fld) expand_annotatable(Annotatable::Item(it), fld) .into_iter().map(|i| i.expect_item()).collect() }"} {"_id":"doc-en-rust-8a1e84c9676fe716d00cfbeec35a44fc5a97ea42529bdc49e3ece5f9be4e7fcd","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(rustc_attrs)] macro_rules! mac { {} => { #[cfg(attr)] mod m { #[lang_item] fn f() {} } } } mac! {} #[rustc_error] fn main() {} //~ ERROR compilation successful "} {"_id":"doc-en-rust-664627b8b4b9a836a942d462cbb75ce8d3f5febbb70341d1956e5b98920e6545","title":"","text":"libc::realloc(ptr as *mut libc::c_void, size as libc::size_t) as *mut u8 } else { let new_ptr = allocate(size, align); ptr::copy(ptr, new_ptr, cmp::min(size, old_size)); deallocate(ptr, old_size, align); if !new_ptr.is_null() { ptr::copy(ptr, new_ptr, cmp::min(size, old_size)); deallocate(ptr, old_size, align); } new_ptr } }"} {"_id":"doc-en-rust-319465190e7d3737ab23f558710d6f58a83ceba5bcf35666661b4653bc84ec5a","title":"","text":"glob_importers: RefCell, &'a ImportDirective<'a>)>>, globs: RefCell>>, // Used to memoize the traits in this module for faster searches through all traits in scope. traits: RefCell]>>>, // Whether this module is populated. If not populated, any attempt to // access the children must be preceded with a // `populate_module_if_necessary` call."} {"_id":"doc-en-rust-bc2707b437b7604bc1245aec0f714b49a4e02a735cc1aeccc7ac0677e0417816","title":"","text":"prelude: RefCell::new(None), glob_importers: RefCell::new(Vec::new()), globs: RefCell::new((Vec::new())), traits: RefCell::new(None), populated: Cell::new(!external), arenas: arenas }"} {"_id":"doc-en-rust-3dfd3a4162d2b24206e6157d74d64fef8fe3d85826d5c13e6e3e6b3da9138767","title":"","text":"let mut search_module = self.current_module; loop { // Look for trait children. let mut search_in_module = |module: Module<'a>| module.for_each_child(|_, ns, binding| { if ns != TypeNS { return } let trait_def_id = match binding.def() { Some(Def::Trait(trait_def_id)) => trait_def_id, Some(..) | None => return, }; if self.trait_item_map.contains_key(&(name, trait_def_id)) { add_trait_info(&mut found_traits, trait_def_id, name); let trait_name = self.get_trait_name(trait_def_id); self.record_use(trait_name, TypeNS, binding); let mut search_in_module = |module: Module<'a>| { let mut traits = module.traits.borrow_mut(); if traits.is_none() { let mut collected_traits = Vec::new(); module.for_each_child(|_, ns, binding| { if ns != TypeNS { return } if let Some(Def::Trait(_)) = binding.def() { collected_traits.push(binding); } }); *traits = Some(collected_traits.into_boxed_slice()); } }); for binding in traits.as_ref().unwrap().iter() { let trait_def_id = binding.def().unwrap().def_id(); if self.trait_item_map.contains_key(&(name, trait_def_id)) { add_trait_info(&mut found_traits, trait_def_id, name); let trait_name = self.get_trait_name(trait_def_id); self.record_use(trait_name, TypeNS, binding); } } }; search_in_module(search_module); match search_module.parent_link {"} {"_id":"doc-en-rust-98800dbc71b2c8918d6accba945d4cc965d3490141f5b662d51521d4e482a07a","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use foo.bar; //~ ERROR expected one of `::`, `;`, or `as`, found `.` "} {"_id":"doc-en-rust-c2390243834c7d0fc5dd136269eb46cf6648c311d675cd38d6e1b0470940e349","title":"","text":"return os.path.join(self.bin_root(), '.cargo-stamp') def rustc_out_of_date(self): if not os.path.exists(self.rustc_stamp()): if not os.path.exists(self.rustc_stamp()) or self.clean: return True with open(self.rustc_stamp(), 'r') as f: return self.stage0_rustc_date() != f.read() def cargo_out_of_date(self): if not os.path.exists(self.cargo_stamp()): if not os.path.exists(self.cargo_stamp()) or self.clean: return True with open(self.cargo_stamp(), 'r') as f: return self.stage0_cargo_date() != f.read()"} {"_id":"doc-en-rust-a7525ed96805665467b62d3f796c2ec735b3cf490f69c383cbf3cf683e4e4a9a","title":"","text":"return '' def build_bootstrap(self): build_dir = os.path.join(self.build_dir, \"bootstrap\") if self.clean and os.path.exists(build_dir): shutil.rmtree(build_dir) env = os.environ.copy() env[\"CARGO_TARGET_DIR\"] = os.path.join(self.build_dir, \"bootstrap\") env[\"CARGO_TARGET_DIR\"] = build_dir env[\"RUSTC\"] = self.rustc() env[\"LD_LIBRARY_PATH\"] = os.path.join(self.bin_root(), \"lib\") env[\"DYLD_LIBRARY_PATH\"] = os.path.join(self.bin_root(), \"lib\")"} {"_id":"doc-en-rust-ad850e0c783007976584f6829b38980a717032bb71173a9aa28a3d5c8160348f","title":"","text":"def main(): parser = argparse.ArgumentParser(description='Build rust') parser.add_argument('--config') parser.add_argument('--clean', action='store_true') parser.add_argument('-v', '--verbose', action='store_true') args = [a for a in sys.argv if a != '-h']"} {"_id":"doc-en-rust-cc13989c36eb40f8b69377233f00b80e31c7c7c87f425459847e052fd5ad1ac6","title":"","text":"rb.rust_root = os.path.abspath(os.path.join(__file__, '../../..')) rb.build_dir = os.path.join(os.getcwd(), \"build\") rb.verbose = args.verbose rb.clean = args.clean try: with open(args.config or 'config.toml') as config:"} {"_id":"doc-en-rust-b1d54e385ea164094b8e04d30d72890eb838c01d0f373a06329a51f593ed0804","title":"","text":"asm!(\"xor %eax, %eax\" : : : \"{eax}\" : \"eax\" ); # } } ```"} {"_id":"doc-en-rust-727a0780e24d618962e673d38bc11f2f3c142b8ca1bb78d060ba280109f2716f","title":"","text":"# #![feature(asm)] # #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))] # fn main() { unsafe { asm!(\"xor %eax, %eax\" ::: \"{eax}\"); asm!(\"xor %eax, %eax\" ::: \"eax\"); # } } ```"} {"_id":"doc-en-rust-4d6e98f9e04985cfee3b87b307b5c34c306ebaf9c622f8e116984f6f2277e30f","title":"","text":"# #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))] # fn main() { unsafe { // Put the value 0x200 in eax asm!(\"mov $$0x200, %eax\" : /* no outputs */ : /* no inputs */ : \"{eax}\"); asm!(\"mov $$0x200, %eax\" : /* no outputs */ : /* no inputs */ : \"eax\"); # } } ```"} {"_id":"doc-en-rust-1d604524d84e25804c5f1f9600ed0b1d966dc265c6de68a3638e1a15c8d96597","title":"","text":"if OPTIONS.iter().any(|&opt| s == opt) { cx.span_warn(p.last_span, \"expected a clobber, found an option\"); } else if s.starts_with(\"{\") || s.ends_with(\"}\") { cx.span_err(p.last_span, \"clobber should not be surrounded by braces\"); } clobs.push(s); } }"} {"_id":"doc-en-rust-9f65aaeb7a5953252377a300b771c2afe7af0a5cbcd410ce5968f23d729cabfb","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-android // ignore-arm // ignore-aarch64 #![feature(asm, rustc_attrs)] #[cfg(any(target_arch = \"x86\", target_arch = \"x86_64\"))] #[rustc_error] pub fn main() { unsafe { // clobber formatted as register input/output asm!(\"xor %eax, %eax\" : : : \"{eax}\"); //~^ ERROR clobber should not be surrounded by braces } } "} {"_id":"doc-en-rust-1dcbf8c67be9156d0970a76306fb061aad0bbe69444f65bdccb3517d9b442da3","title":"","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":"doc-en-rust-8a1f611e556499a71797c7410c3498ef93d52d8232dfa74b65fa45b1b815049d","title":"","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":"doc-en-rust-8b03aac4696597a5afa99e04df7a6aa00e9b331a038bee1bb030a419814701a9","title":"","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":"doc-en-rust-202cb349464e09a2933ea80dd476d2911beb1701192ceff05cb0077e599d390a","title":"","text":"self.suggest_derive(err, &preds); } fn suggest_derive( pub fn suggest_derive( &self, err: &mut Diagnostic, unsatisfied_predicates: &[("} {"_id":"doc-en-rust-37803f41c877da45c819ac39518649b45c072ea71750cfa4038f8e0f55bd18aa","title":"","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":"doc-en-rust-7d17d3e2464ca4b22297db044749e1391143854f19b29b60f58d15b8c4d74965","title":"","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":"doc-en-rust-f4898fcbf48a5d8227ff6dd605d7a09a2749619752e270eecb1b15178b2c44c5","title":"","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":"doc-en-rust-ccc8df4d0fddd28f0b94612e7daf298c389fb05f2643436d3d32522cf5062fb1","title":"","text":"| LL | nc.clone() | ^^ help: consider annotating `NotClone` with `#[derive(Clone)]` | LL | #[derive(Clone)] | error: aborting due to previous error"} {"_id":"doc-en-rust-b0a4fc36f2d2163a9b0cccaf614f538b3a8e828825e08a1606290e5ab2eb7200","title":"","text":"//! in this case, if one uses the format string `{:.*}`, then the `` part refers //! to the *value* to print, and the `precision` must come in the input preceding ``. //! //! For example, these: //! For example, the following calls all print the same thing `Hello x is 0.01000`: //! //! ``` //! // Hello {arg 0 (x)} is {arg 1 (0.01) with precision specified inline (5)} //! // Hello {arg 0 (\"x\")} is {arg 1 (0.01) with precision specified inline (5)} //! println!(\"Hello {0} is {1:.5}\", \"x\", 0.01); //! //! // Hello {arg 1 (x)} is {arg 2 (0.01) with precision specified in arg 0 (5)} //! // Hello {arg 1 (\"x\")} is {arg 2 (0.01) with precision specified in arg 0 (5)} //! println!(\"Hello {1} is {2:.0$}\", 5, \"x\", 0.01); //! //! // Hello {arg 0 (x)} is {arg 2 (0.01) with precision specified in arg 1 (5)} //! // Hello {arg 0 (\"x\")} is {arg 2 (0.01) with precision specified in arg 1 (5)} //! println!(\"Hello {0} is {2:.1$}\", \"x\", 5, 0.01); //! //! // Hello {next arg (x)} is {second of next two args (0.01) with precision //! // Hello {next arg (\"x\")} is {second of next two args (0.01) with precision //! // specified in first of next two args (5)} //! println!(\"Hello {} is {:.*}\", \"x\", 5, 0.01); //! //! // Hello {next arg (x)} is {arg 2 (0.01) with precision //! // Hello {next arg (\"x\")} is {arg 2 (0.01) with precision //! // specified in its predecessor (5)} //! println!(\"Hello {} is {2:.*}\", \"x\", 5, 0.01); //! //! // Hello {next arg (x)} is {arg \"number\" (0.01) with precision specified //! // Hello {next arg (\"x\")} is {arg \"number\" (0.01) with precision specified //! // in arg \"prec\" (5)} //! println!(\"Hello {} is {number:.prec$}\", \"x\", prec = 5, number = 0.01); //! ``` //! //! All print the same thing: //! //! ```text //! Hello x is 0.01000 //! ``` //! //! While these: //! //! ```"} {"_id":"doc-en-rust-16da9f2bf0a84a71964433a08b9ebd21b8bc6609c84744a2dd2d7684c7e44c34","title":"","text":"/// ``` #[stable(feature = \"move_cell\", since = \"1.17.0\")] pub fn into_inner(self) -> T { unsafe { self.value.into_inner() } self.value.into_inner() } }"} {"_id":"doc-en-rust-c6c890d736bf918b58a99677d7ce4c57e82bba6dea0ed6ff4f5fd462f825975b","title":"","text":"// compiler statically verifies that it is not currently borrowed. // Therefore the following assertion is just a `debug_assert!`. debug_assert!(self.borrow.get() == UNUSED); unsafe { self.value.into_inner() } self.value.into_inner() } /// Replaces the wrapped value with a new one, returning the old value,"} {"_id":"doc-en-rust-64b3f025f7044d1ddff8acb6b0ffe7dd386a6390fbf860aafe0566b7308134d7","title":"","text":"/// Unwraps the value. /// /// # Safety /// /// This function is unsafe because this thread or another thread may currently be /// inspecting the inner value. /// /// # Examples /// /// ```"} {"_id":"doc-en-rust-a1af952078c4e2b21fc389d658b8f11b36a5bc00d83a63e47d6787cc9bace151","title":"","text":"/// /// let uc = UnsafeCell::new(5); /// /// let five = unsafe { uc.into_inner() }; /// let five = uc.into_inner(); /// ``` #[inline] #[stable(feature = \"rust1\", since = \"1.0.0\")] pub unsafe fn into_inner(self) -> T { pub fn into_inner(self) -> T { self.value } }"} {"_id":"doc-en-rust-406d0fe7110cd57dd6e1e7a5c1ed7494da6b617a3616ca32e75f792f638aa7dc","title":"","text":"#[inline] #[stable(feature = \"atomic_access\", since = \"1.15.0\")] pub fn into_inner(self) -> bool { unsafe { self.v.into_inner() != 0 } self.v.into_inner() != 0 } /// Loads a value from the bool."} {"_id":"doc-en-rust-0eb161898bda2bdeaddd72afbb0217e5fada8d47dd64bd741d6c407e6a5b3c12","title":"","text":"#[inline] #[stable(feature = \"atomic_access\", since = \"1.15.0\")] pub fn into_inner(self) -> *mut T { unsafe { self.p.into_inner() } self.p.into_inner() } /// Loads a value from the pointer."} {"_id":"doc-en-rust-e7b470a8ba30c5c4d612a5cfe7f8c8c7ee16ba380f9e27de9c47ea975e2747fd","title":"","text":"#[inline] #[$stable_access] pub fn into_inner(self) -> $int_type { unsafe { self.v.into_inner() } self.v.into_inner() } /// Loads a value from the atomic integer."} {"_id":"doc-en-rust-4c63558cc9d3a7d49de2099dde6fed65293235d399582099d4ea5d910ad53337","title":"","text":"let &(ref first_arm_pats, _) = &arms[0]; let first_pat = &first_arm_pats[0]; let span = first_pat.span; span_err!(cx.tcx.sess, span, E0165, \"irrefutable while-let pattern\"); struct_span_err!(cx.tcx.sess, span, E0165, \"irrefutable while-let pattern\") .span_label(span, &format!(\"irrefutable pattern\")) .emit(); }, hir::MatchSource::ForLoopDesugar => {"} {"_id":"doc-en-rust-8b08f0d27415a104fa48b934f0765a0355d43ca6fc67afd713dc36a5a957c834","title":"","text":"tcx.sess.add_lint(lint::builtin::MATCH_OF_UNIT_VARIANT_VIA_PAREN_DOTDOT, pat.id, pat.span, msg); } else { span_err!(tcx.sess, pat.span, E0164, \"{}\", msg); struct_span_err!(tcx.sess, pat.span, E0164, \"{}\", msg) .span_label(pat.span, &format!(\"not a tuple variant or struct\")).emit(); on_error(); } };"} {"_id":"doc-en-rust-ff8270d0215ddbada1cc300e82fad9e762a3ece3b4bbee04e4bcb0dce691dc6b","title":"","text":".emit(); } Err(CopyImplementationError::HasDestructor) => { span_err!(tcx.sess, span, E0184, struct_span_err!(tcx.sess, span, E0184, \"the trait `Copy` may not be implemented for this type; the type has a destructor\"); the type has a destructor\") .span_label(span, &format!(\"Copy not allowed on types with destructors\")) .emit(); } } });"} {"_id":"doc-en-rust-89b81bc2ced1e642ad37d83220c291f95b6679f99542f755cb9e538c06b880f2","title":"","text":"fn bar(foo: Foo) -> u32 { match foo { Foo::B(i) => i, //~ ERROR E0164 //~| NOTE not a tuple variant or struct } }"} {"_id":"doc-en-rust-5ac9244c3a6c15fbdae0e13a10f6fd45a8109f654a92720dd619ed7e268a3979","title":"","text":"fn main() { let irr = Irrefutable(0); while let Irrefutable(x) = irr { //~ ERROR E0165 //~| irrefutable pattern // ... } }"} {"_id":"doc-en-rust-2c8aa37c87b67ffc2fb3043a235cfa0e3690b6a6bb14675adbdd13e85870289f","title":"","text":"// except according to those terms. #[derive(Copy)] //~ ERROR E0184 //~| NOTE Copy not allowed on types with destructors //~| NOTE in this expansion of #[derive(Copy)] struct Foo; impl Drop for Foo {"} {"_id":"doc-en-rust-38a9cbb8d7784ac6e58b0f388834f185efbcbac0f357b13904c143e24fa94b01","title":"","text":"let lifetime_j = &lifetimes[j]; if lifetime_i.lifetime.name == lifetime_j.lifetime.name { span_err!(self.sess, lifetime_j.lifetime.span, E0263, \"lifetime name `{}` declared twice in the same scope\", lifetime_j.lifetime.name); struct_span_err!(self.sess, lifetime_j.lifetime.span, E0263, \"lifetime name `{}` declared twice in the same scope\", lifetime_j.lifetime.name) .span_label(lifetime_j.lifetime.span, &format!(\"declared twice\")) .span_label(lifetime_i.lifetime.span, &format!(\"previous declaration here\")) .emit(); } }"} {"_id":"doc-en-rust-c092baab073064214101ca07b352e059950a1f86d7a817d05cdddd9420fd0404","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { } //~ ERROR E0263 fn foo<'a, 'b, 'a>(x: &'a str, y: &'b str) { //~^ ERROR E0263 //~| NOTE declared twice //~| NOTE previous declaration here } fn main() {}"} {"_id":"doc-en-rust-3e310c59d818cf186ba206df2ff602e523016faba098a47a19c1fc182368190f","title":"","text":"\"tempfile\", \"thorin-dwp\", \"tracing\", \"windows 0.46.0\", ] [[package]]"} {"_id":"doc-en-rust-d75178a812a0c4446607096a6908b31cffdac187df1d605ac77b17af7f47a77a","title":"","text":"version = \"0.30.1\" default-features = false features = [\"read_core\", \"elf\", \"macho\", \"pe\", \"unaligned\", \"archive\", \"write\"] [target.'cfg(windows)'.dependencies.windows] version = \"0.46.0\" features = [\"Win32_Globalization\"] "} {"_id":"doc-en-rust-6051f9024d454ecd6c0122ea5d2a3ff370f4690246f59e55aeb952e2ecabf673","title":"","text":"if !prog.status.success() { let mut output = prog.stderr.clone(); output.extend_from_slice(&prog.stdout); let escaped_output = escape_string(&output); let escaped_output = escape_linker_output(&output, flavor); // FIXME: Add UI tests for this error. let err = errors::LinkingFailed { linker_path: &linker_path,"} {"_id":"doc-en-rust-e31fad30eb1a03dc28c092f0cd0313b70028c639e3f1d04d78cf3128ef1f4854","title":"","text":"} } #[cfg(not(windows))] fn escape_linker_output(s: &[u8], _flavour: LinkerFlavor) -> String { escape_string(s) } /// If the output of the msvc linker is not UTF-8 and the host is Windows, /// then try to convert the string from the OEM encoding. #[cfg(windows)] fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String { // This only applies to the actual MSVC linker. if flavour != LinkerFlavor::Msvc(Lld::No) { return escape_string(s); } match str::from_utf8(s) { Ok(s) => return s.to_owned(), Err(_) => match win::locale_byte_str_to_string(s, win::oem_code_page()) { Some(s) => s, // The string is not UTF-8 and isn't valid for the OEM code page None => format!(\"Non-UTF-8 output: {}\", s.escape_ascii()), }, } } /// Wrappers around the Windows API. #[cfg(windows)] mod win { use windows::Win32::Globalization::{ GetLocaleInfoEx, MultiByteToWideChar, CP_OEMCP, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, }; /// Get the Windows system OEM code page. This is most notably the code page /// used for link.exe's output. pub fn oem_code_page() -> u32 { unsafe { let mut cp: u32 = 0; // We're using the `LOCALE_RETURN_NUMBER` flag to return a u32. // But the API requires us to pass the data as though it's a [u16] string. let len = std::mem::size_of::() / std::mem::size_of::(); let data = std::slice::from_raw_parts_mut(&mut cp as *mut u32 as *mut u16, len); let len_written = GetLocaleInfoEx( LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_IUSEUTF8LEGACYOEMCP | LOCALE_RETURN_NUMBER, Some(data), ); if len_written as usize == len { cp } else { CP_OEMCP } } } /// Try to convert a multi-byte string to a UTF-8 string using the given code page /// The string does not need to be null terminated. /// /// This is implemented as a wrapper around `MultiByteToWideChar`. /// See /// /// It will fail if the multi-byte string is longer than `i32::MAX` or if it contains /// any invalid bytes for the expected encoding. pub fn locale_byte_str_to_string(s: &[u8], code_page: u32) -> Option { // `MultiByteToWideChar` requires a length to be a \"positive integer\". if s.len() > isize::MAX as usize { return None; } // Error if the string is not valid for the expected code page. let flags = MB_ERR_INVALID_CHARS; // Call MultiByteToWideChar twice. // First to calculate the length then to convert the string. let mut len = unsafe { MultiByteToWideChar(code_page, flags, s, None) }; if len > 0 { let mut utf16 = vec![0; len as usize]; len = unsafe { MultiByteToWideChar(code_page, flags, s, Some(&mut utf16)) }; if len > 0 { return utf16.get(..len as usize).map(String::from_utf16_lossy); } } None } } fn add_sanitizer_libraries(sess: &Session, crate_type: CrateType, linker: &mut dyn Linker) { // On macOS the runtimes are distributed as dylibs which should be linked to // both executables and dynamic shared objects. Everywhere else the runtimes"} {"_id":"doc-en-rust-b77d2be166e4d19e95bd6f7660bfd6f24dcc63df48dc19b669e2897eaf9c2698","title":"","text":" // build-fail // compile-flags:-C link-arg=märchenhaft // only-msvc // error-pattern:= note: LINK : fatal error LNK1181: // normalize-stderr-test \"(s*|n)s*= note: .*n\" -> \"$1\" pub fn main() {} "} {"_id":"doc-en-rust-b423d86be32781bbde83dc4f37b13beb499a9a18f09b245824818eb20605c688","title":"","text":" error: linking with `link.exe` failed: exit code: 1181 | = note: LINK : fatal error LNK1181: cannot open input file 'märchenhaft.obj' error: aborting due to previous error "} {"_id":"doc-en-rust-6c7d29d8abc506094a9c058991bd31b2177ab4f9307642b2e58704a4abe635e8","title":"","text":"linker_error.emit(); if sess.target.target.options.is_like_msvc && linker_not_found { sess.note_without_error(\"the msvc targets depend on the msvc linker but `link.exe` was not found\"); sess.note_without_error(\"please ensure that VS 2013, VS 2015 or VS 2017 was installed with the Visual C++ option\"); sess.note_without_error( \"the msvc targets depend on the msvc linker but `link.exe` was not found\", ); sess.note_without_error( \"please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 was installed with the Visual C++ option\", ); } sess.abort_if_errors(); }"} {"_id":"doc-en-rust-110741c6b5677bb67eda59812bd0aafcb890919d102f39238e5c95969a5b756b","title":"","text":"target_family: Some(\"windows\".to_string()), is_like_windows: true, is_like_msvc: true, // set VSLANG to 1033 can prevent link.exe from using // language packs, and avoid generating Non-UTF-8 error // messages if a link error occurred. link_env: vec![(\"VSLANG\".to_string(), \"1033\".to_string())], pre_link_args: args, crt_static_allows_dylibs: true, crt_static_respected: true,"} {"_id":"doc-en-rust-33d88fc4d63788241bab0b19fdeb0138b797967a82480118f275d7a9c64d46cc","title":"","text":" // check-pass #![feature(coerce_unsized, unsize)] use std::marker::Unsize; use std::ops::CoerceUnsized; struct Foo(Box); impl CoerceUnsized> for Foo where T: Unsize {} struct Bar; trait Baz {} impl Baz for Bar {} fn main() { let foo = Foo(Box::new(Bar)); let foobar: Foo = foo; } "} {"_id":"doc-en-rust-3490b13f275bcd57eed102c6146556f4c1339de0d1703afa28dde07fd6bc1632","title":"","text":"impl<'a> CheckAttrVisitor<'a> { fn check_inline(&self, attr: &ast::Attribute, target: Target) { if target != Target::Fn { span_err!(self.sess, attr.span, E0518, \"attribute should be applied to function\"); struct_span_err!(self.sess, attr.span, E0518, \"attribute should be applied to function\") .span_label(attr.span, &format!(\"requires a function\")) .emit(); } }"} {"_id":"doc-en-rust-bc314c73168e88a7c15842616ac60006caae9ef82d34a44203fc91ad3eacf348","title":"","text":"let mut conflicting_reprs = 0; for word in words { let name = match word.name() { Some(word) => word, None => continue, }; let message = match &*name { let (message, label) = match &*name { \"C\" => { conflicting_reprs += 1; if target != Target::Struct && target != Target::Union && target != Target::Enum { \"attribute should be applied to struct, enum or union\" (\"attribute should be applied to struct, enum or union\", \"a struct, enum or union\") } else { continue }"} {"_id":"doc-en-rust-8e004b91e36946a683cf0d2ddfa2165162aab568a4a192d5b8a42ea3d9c130c8","title":"","text":"// can be used to modify another repr hint if target != Target::Struct && target != Target::Union { \"attribute should be applied to struct or union\" (\"attribute should be applied to struct or union\", \"a struct or union\") } else { continue }"} {"_id":"doc-en-rust-ca79b0a8cb85e2437aa96c81c0bad9d445614aec3627cda12df067ea0401aa31","title":"","text":"\"simd\" => { conflicting_reprs += 1; if target != Target::Struct { \"attribute should be applied to struct\" (\"attribute should be applied to struct\", \"a struct\") } else { continue }"} {"_id":"doc-en-rust-50dbd5dd77dd7f3a8ba98cd0e5efb5dc08852355c22491ecc067cd064bb49b65","title":"","text":"\"isize\" | \"usize\" => { conflicting_reprs += 1; if target != Target::Enum { \"attribute should be applied to enum\" (\"attribute should be applied to enum\", \"an enum\") } else { continue } } _ => continue, }; span_err!(self.sess, attr.span, E0517, \"{}\", message); struct_span_err!(self.sess, attr.span, E0517, \"{}\", message) .span_label(attr.span, &format!(\"requires {}\", label)) .emit(); } if conflicting_reprs > 1 { span_warn!(self.sess, attr.span, E0566,"} {"_id":"doc-en-rust-0816672dbafa9664c695b1e816878bb858dff07804f5951367a89aed28385a02","title":"","text":"} } hir::TyTypeof(ref _e) => { span_err!(tcx.sess, ast_ty.span, E0516, \"`typeof` is a reserved keyword but unimplemented\"); struct_span_err!(tcx.sess, ast_ty.span, E0516, \"`typeof` is a reserved keyword but unimplemented\") .span_label(ast_ty.span, &format!(\"reserved keyword\")) .emit(); tcx.types.err } hir::TyInfer => {"} {"_id":"doc-en-rust-bf5a0314a920bfc9afc1345d183557b74e851497f94b8e8a8071db407e065e52","title":"","text":"fn main() { let x: typeof(92) = 92; //~ ERROR E0516 //~| reserved keyword }"} {"_id":"doc-en-rust-abcc4947a3fe570f51c5ecb2132c7d14d8bd1eeba43118d1687260d96b481049","title":"","text":"// except according to those terms. #[repr(C)] //~ ERROR E0517 //~| requires a struct, enum or union type Foo = u8; #[repr(packed)] //~ ERROR E0517 //~| requires a struct enum Foo2 {Bar, Baz} #[repr(u8)] //~ ERROR E0517 //~| requires an enum struct Foo3 {bar: bool, baz: bool} #[repr(C)] //~ ERROR E0517 //~| requires a struct, enum or union impl Foo3 { }"} {"_id":"doc-en-rust-1f1ea0fd958fc5e95def6df18cd5141e050b0221ddad2c0aaa60c9d2edd595b2","title":"","text":"// except according to those terms. #[inline(always)] //~ ERROR E0518 //~| requires a function struct Foo; #[inline(never)] //~ ERROR E0518 //~| requires a function impl Foo { }"} {"_id":"doc-en-rust-357b5c5f3be59e86feebb290e879b4d19bb89b1a0269543572ab938e4f81af1d","title":"","text":"// If the resolution doesn't depend on glob definability, check privacy and return. if let Some(result) = self.try_result(&resolution, ns) { return result.and_then(|binding| { if self.is_accessible(binding.vis) && !is_disallowed_private_import(binding) { if self.is_accessible(binding.vis) && !is_disallowed_private_import(binding) || binding.is_extern_crate() { // c.f. issue #37020 Success(binding) } else { Failed(None)"} {"_id":"doc-en-rust-dab5a3e824f0ecfb2a9520f9dd5dcd03ed58946fd30eef69b66507c52df35923","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(private_in_public)] mod foo { pub mod bar { extern crate core; } } mod baz { pub use foo::bar::core; } fn main() { baz::core::cell::Cell::new(0u32); } "} {"_id":"doc-en-rust-60fa033408aa4e6c3ac0c73286f591787d4c092fe399f225782b492521ca8de4","title":"","text":"let bindir_default = PathBuf::from(\"bin\"); let libdir_default = PathBuf::from(\"lib\"); let mandir_default = datadir_default.join(\"man\"); let prefix = build.config.prefix.as_ref().unwrap_or(&prefix_default); let prefix = build.config.prefix.as_ref().map_or(prefix_default, |p| { fs::canonicalize(p).expect(&format!(\"could not canonicalize {}\", p.display())) }); let sysconfdir = build.config.sysconfdir.as_ref().unwrap_or(&sysconfdir_default); let datadir = build.config.datadir.as_ref().unwrap_or(&datadir_default); let docdir = build.config.docdir.as_ref().unwrap_or(&docdir_default);"} {"_id":"doc-en-rust-f4c8a6a268765e5d494766425a7c20e55cffdc28c6d3b71090e3b081f5ef5c2d","title":"","text":") fn mk_ident_interner() -> @ident_interner { /* the indices here must correspond to the numbers in special_idents */ let init_vec = ~[@~\"_\", @~\"anon\", @~\"drop\", @~\"\", @~\"unary\", @~\"!\", @~\"[]\", @~\"unary-\", @~\"__extensions__\", @~\"self\", @~\"item\", @~\"block\", @~\"stmt\", @~\"pat\", @~\"expr\", @~\"ty\", @~\"ident\", @~\"path\", @~\"tt\", @~\"matchers\", @~\"str\", @~\"TyVisitor\", @~\"arg\", @~\"descrim\", @~\"__rust_abi\", @~\"__rust_stack_shim\", @~\"TyDesc\", @~\"dtor\", @~\"main\", @~\"\", @~\"blk\", @~\"static\", @~\"intrinsic\", @~\"__foreign_mod__\"]; let rv = @ident_interner { interner: interner::mk_prefill::<@~str>(init_vec) }; /* having multiple interners will just confuse the serializer */ unsafe { assert task::local_data::local_data_get(interner_key!()).is_none() }; unsafe { task::local_data::local_data_set(interner_key!(), @rv) }; rv match task::local_data::local_data_get(interner_key!()) { Some(interner) => *interner, None => { // the indices here must correspond to the numbers in // special_idents. let init_vec = ~[ @~\"_\", @~\"anon\", @~\"drop\", @~\"\", @~\"unary\", @~\"!\", @~\"[]\", @~\"unary-\", @~\"__extensions__\", @~\"self\", @~\"item\", @~\"block\", @~\"stmt\", @~\"pat\", @~\"expr\", @~\"ty\", @~\"ident\", @~\"path\", @~\"tt\", @~\"matchers\", @~\"str\", @~\"TyVisitor\", @~\"arg\", @~\"descrim\", @~\"__rust_abi\", @~\"__rust_stack_shim\", @~\"TyDesc\", @~\"dtor\", @~\"main\", @~\"\", @~\"blk\", @~\"static\", @~\"intrinsic\", @~\"__foreign_mod__\" ]; let rv = @ident_interner { interner: interner::mk_prefill(init_vec) }; task::local_data::local_data_set(interner_key!(), @rv); rv } } } } /* for when we don't care about the contents; doesn't interact with TLD or"} {"_id":"doc-en-rust-67dc97ccc1ad22d212cd4cbddc2c08e9b9e300ef46316d50ab3bfc8ff7b41249","title":"","text":"pub llvm_version_check: bool, pub llvm_static_stdcpp: bool, pub llvm_link_shared: bool, pub llvm_targets: Option, // rust codegen options pub rust_optimize: bool,"} {"_id":"doc-en-rust-795e64e4bb31e39a4d62be45a2d5efd2fe874d3c80115e14ce4090ed366335d7","title":"","text":"release_debuginfo: Option, version_check: Option, static_libstdcpp: Option, targets: Option, } #[derive(RustcDecodable)]"} {"_id":"doc-en-rust-908ccb65c23de1025d0ac81ee11db51ae407ca62d51bd58e7db28504a53d60bb","title":"","text":"set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo); set(&mut config.llvm_version_check, llvm.version_check); set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp); config.llvm_targets = llvm.targets.clone(); } if let Some(ref rust) = toml.rust {"} {"_id":"doc-en-rust-f0cfb69be4da5e45ba8089558889370bc23e564abb7485ede385ffec51d45ea7","title":"","text":"# example. #ninja = false # LLVM targets to build support for. # Note: this is NOT related to Rust compilation targets. However, as Rust is # dependent on LLVM for code generation, turning targets off here WILL lead to # the resulting rustc being unable to compile for the disabled architectures. # Also worth pointing out is that, in case support for new targets are added to # LLVM, enabling them here doesn't mean Rust is automatically gaining said # support. You'll need to write a target specification at least, and most # likely, teach rustc about the C ABI of the target. Get in touch with the # Rust team and file an issue if you need assistance in porting! #targets = \"X86;ARM;AArch64;Mips;PowerPC;SystemZ;JSBackend;MSP430;Sparc\" # ============================================================================= # General build configuration options # ============================================================================="} {"_id":"doc-en-rust-466a118f137d9c91e8cfcd7c3dd64378d072ffc08e538aec03302dfb6841df51","title":"","text":"(true, true) => \"RelWithDebInfo\", }; // NOTE: remember to also update `config.toml.example` when changing the defaults! let llvm_targets = match build.config.llvm_targets { Some(ref s) => s, None => \"X86;ARM;AArch64;Mips;PowerPC;SystemZ;JSBackend;MSP430;Sparc\", }; cfg.target(target) .host(&build.config.build) .out_dir(&dst) .profile(profile) .define(\"LLVM_ENABLE_ASSERTIONS\", assertions) .define(\"LLVM_TARGETS_TO_BUILD\", \"X86;ARM;AArch64;Mips;PowerPC;SystemZ;JSBackend;MSP430;Sparc\") .define(\"LLVM_TARGETS_TO_BUILD\", llvm_targets) .define(\"LLVM_INCLUDE_EXAMPLES\", \"OFF\") .define(\"LLVM_INCLUDE_TESTS\", \"OFF\") .define(\"LLVM_INCLUDE_DOCS\", \"OFF\")"} {"_id":"doc-en-rust-0c60f965108a0d513566a80eb3eeb6dc69f6df4804f79dd73b7f9ace7de5c10f","title":"","text":"} } #[derive(Copy, Clone)] #[derive(Copy, Clone, PartialEq)] enum PathScope { Global, Lexical,"} {"_id":"doc-en-rust-baa66de69a1108c2f80d978361c77b8154dab8bda147864dc400b08f0f688592","title":"","text":"// // Such behavior is required for backward compatibility. // The same fallback is used when `a` resolves to nothing. _ if self.primitive_type_table.primitive_types.contains_key(&path[0].name) => { PathResult::Module(..) | PathResult::Failed(..) if scope == PathScope::Lexical && (ns == TypeNS || path.len() > 1) && self.primitive_type_table.primitive_types.contains_key(&path[0].name) => { PathResolution { base_def: Def::PrimTy(self.primitive_type_table.primitive_types[&path[0].name]), depth: segments.len() - 1,"} {"_id":"doc-en-rust-bcd24b48389024dcf5f4052aad3e529bf9c4848c63289df7cc8388eb3aff3765","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { // Make sure primitive type fallback doesn't work in value namespace std::mem::size_of(u16); //~^ ERROR unresolved name `u16` //~| ERROR this function takes 0 parameters but 1 parameter was supplied // Make sure primitive type fallback doesn't work with global paths let _: ::u8; //~^ ERROR type name `u8` is undefined or not in scope } "} {"_id":"doc-en-rust-0b28f8d12b3cd87e4c7e80cfcc3658714cc449f46d3c3488a1be50ea748a48c9","title":"","text":"} contents.truncate(0); t!(t!(File::open(file)).read_to_string(&mut contents)); t!(t!(File::open(&file), &file).read_to_string(&mut contents)); for (i, line) in contents.lines().enumerate() { let mut err = |msg: &str| {"} {"_id":"doc-en-rust-5939311dabf0066d4d34b29777915db61bfd86ed868db3bb2f02a1cf4266e8ff","title":"","text":"pub const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15; pub const PIPE_ACCESS_INBOUND: DWORD = 0x00000001; pub const PIPE_ACCESS_OUTBOUND: DWORD = 0x00000002; pub const FILE_FLAG_FIRST_PIPE_INSTANCE: DWORD = 0x00080000; pub const FILE_FLAG_OVERLAPPED: DWORD = 0x40000000; pub const PIPE_WAIT: DWORD = 0x00000000;"} {"_id":"doc-en-rust-9561082ee84244120b3792b794b1e8d7341bfaeafe83012757c7e90004d3b851","title":"","text":"inner: Handle, } pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { pub struct Pipes { pub ours: AnonPipe, pub theirs: AnonPipe, } /// Although this looks similar to `anon_pipe` in the Unix module it's actually /// subtly different. Here we'll return two pipes in the `Pipes` return value, /// but one is intended for \"us\" where as the other is intended for \"someone /// else\". /// /// Currently the only use case for this function is pipes for stdio on /// processes in the standard library, so \"ours\" is the one that'll stay in our /// process whereas \"theirs\" will be inherited to a child. /// /// The ours/theirs pipes are *not* specifically readable or writable. Each /// one only supports a read or a write, but which is which depends on the /// boolean flag given. If `ours_readable` is true then `ours` is readable where /// `theirs` is writable. Conversely if `ours_readable` is false then `ours` is /// writable where `theirs` is readable. /// /// Also note that the `ours` pipe is always a handle opened up in overlapped /// mode. This means that technically speaking it should only ever be used /// with `OVERLAPPED` instances, but also works out ok if it's only ever used /// once at a time (which we do indeed guarantee). pub fn anon_pipe(ours_readable: bool) -> io::Result { // Note that we specifically do *not* use `CreatePipe` here because // unfortunately the anonymous pipes returned do not support overlapped // operations. // // Instead, we create a \"hopefully unique\" name and create a named pipe // which has overlapped operations enabled. // operations. Instead, we create a \"hopefully unique\" name and create a // named pipe which has overlapped operations enabled. // // Once we do this, we connect do it as usual via `CreateFileW`, and then we // return those reader/writer halves. // Once we do this, we connect do it as usual via `CreateFileW`, and then // we return those reader/writer halves. Note that the `ours` pipe return // value is always the named pipe, whereas `theirs` is just the normal file. // This should hopefully shield us from child processes which assume their // stdout is a named pipe, which would indeed be odd! unsafe { let reader; let ours; let mut name; let mut tries = 0; let mut reject_remote_clients_flag = c::PIPE_REJECT_REMOTE_CLIENTS;"} {"_id":"doc-en-rust-cf5d2b6facd02f2d09a99da40c284f624b3a163eacaf04f1cf0eb8cd848b35eb","title":"","text":".encode_wide() .chain(Some(0)) .collect::>(); let mut flags = c::FILE_FLAG_FIRST_PIPE_INSTANCE | c::FILE_FLAG_OVERLAPPED; if ours_readable { flags |= c::PIPE_ACCESS_INBOUND; } else { flags |= c::PIPE_ACCESS_OUTBOUND; } let handle = c::CreateNamedPipeW(wide_name.as_ptr(), c::PIPE_ACCESS_INBOUND | c::FILE_FLAG_FIRST_PIPE_INSTANCE | c::FILE_FLAG_OVERLAPPED, flags, c::PIPE_TYPE_BYTE | c::PIPE_READMODE_BYTE | c::PIPE_WAIT |"} {"_id":"doc-en-rust-5ccdeec0afa6f00ec65113b74013d6a79bf0ad208808f5485782a29790f45b09","title":"","text":"} return Err(err) } reader = Handle::new(handle); ours = Handle::new(handle); break } // Connect to the named pipe we just created in write-only mode (also // overlapped for async I/O below). // Connect to the named pipe we just created. This handle is going to be // returned in `theirs`, so if `ours` is readable we want this to be // writable, otherwise if `ours` is writable we want this to be // readable. // // Additionally we don't enable overlapped mode on this because most // client processes aren't enabled to work with that. let mut opts = OpenOptions::new(); opts.write(true); opts.read(false); opts.write(ours_readable); opts.read(!ours_readable); opts.share_mode(0); opts.attributes(c::FILE_FLAG_OVERLAPPED); let writer = File::open(Path::new(&name), &opts)?; let writer = AnonPipe { inner: writer.into_handle() }; let theirs = File::open(Path::new(&name), &opts)?; let theirs = AnonPipe { inner: theirs.into_handle() }; Ok((AnonPipe { inner: reader }, AnonPipe { inner: writer.into_handle() })) Ok(Pipes { ours: AnonPipe { inner: ours }, theirs: AnonPipe { inner: theirs.into_handle() }, }) } }"} {"_id":"doc-en-rust-2ffb49a90751c89a242bc63e5e15c2acc831505405b6bda9dec747eeb1b8e4c8","title":"","text":"} Stdio::MakePipe => { let (reader, writer) = pipe::anon_pipe()?; let (ours, theirs) = if stdio_id == c::STD_INPUT_HANDLE { (writer, reader) } else { (reader, writer) }; *pipe = Some(ours); let ours_readable = stdio_id != c::STD_INPUT_HANDLE; let pipes = pipe::anon_pipe(ours_readable)?; *pipe = Some(pipes.ours); cvt(unsafe { c::SetHandleInformation(theirs.handle().raw(), c::SetHandleInformation(pipes.theirs.handle().raw(), c::HANDLE_FLAG_INHERIT, c::HANDLE_FLAG_INHERIT) })?; Ok(theirs.into_handle()) Ok(pipes.theirs.into_handle()) } Stdio::Handle(ref handle) => {"} {"_id":"doc-en-rust-b9290598b10b334b853ae1b622c1f8491c935a9e8fefe31ab494fb421d3723da","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::env; use std::io::prelude::*; use std::process::Command; use std::thread; const THREADS: usize = 20; const WRITES: usize = 100; const WRITE_SIZE: usize = 1024 * 32; fn main() { let args = env::args().collect::>(); if args.len() == 1 { parent(); } else { child(); } } fn parent() { let me = env::current_exe().unwrap(); let mut cmd = Command::new(me); cmd.arg(\"run-the-test\"); let output = cmd.output().unwrap(); assert!(output.status.success()); assert_eq!(output.stderr.len(), 0); assert_eq!(output.stdout.len(), WRITES * THREADS * WRITE_SIZE); for byte in output.stdout.iter() { assert_eq!(*byte, b'a'); } } fn child() { let threads = (0..THREADS).map(|_| { thread::spawn(|| { let buf = [b'a'; WRITE_SIZE]; for _ in 0..WRITES { write_all(&buf); } }) }).collect::>(); for thread in threads { thread.join().unwrap(); } } #[cfg(unix)] fn write_all(buf: &[u8]) { use std::fs::File; use std::mem; use std::os::unix::prelude::*; let mut file = unsafe { File::from_raw_fd(1) }; let res = file.write_all(buf); mem::forget(file); res.unwrap(); } #[cfg(windows)] fn write_all(buf: &[u8]) { use std::fs::File; use std::mem; use std::os::windows::raw::*; use std::os::windows::prelude::*; const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32; extern \"system\" { fn GetStdHandle(handle: u32) -> HANDLE; } let mut file = unsafe { let handle = GetStdHandle(STD_OUTPUT_HANDLE); assert!(!handle.is_null()); File::from_raw_handle(handle) }; let res = file.write_all(buf); mem::forget(file); res.unwrap(); } "} {"_id":"doc-en-rust-e3c4c0d4bfd27633eb8c4665fbd4f3ecf19b7f1e19cb0fd8cd29cbc3d1b84ab5","title":"","text":" // check-pass use std::borrow::Borrow; trait TNode: Sized { type ConcreteElement: TElement; } trait TElement: Sized { type ConcreteNode: TNode; } trait DomTraversal { type BorrowElement: Borrow; } #[allow(dead_code)] fn recalc_style_at() where E: TElement, D: DomTraversal, { } fn main() {} "} {"_id":"doc-en-rust-a4c6db4001376ff8b7a2409fd48cce2d3375d01ce7a3ca1e145c0ecbf801841b","title":"","text":" // check-pass pub trait Test { type Item; type Bundle: From; } fn fails() where T: Test, { } fn main() {} "} {"_id":"doc-en-rust-b653c440adf97cb3e43ea3529e592e87240e9b665114b90bd5ad4b3644b50aca","title":"","text":" // check-pass trait Foo { type FooT: Foo; } impl Foo for () { type FooT = (); } trait Bar { type BarT: Bar; } impl Bar<()> for () { type BarT = (); } #[allow(dead_code)] fn test>() { } fn main() { } "} {"_id":"doc-en-rust-036d815f008df995ae701c1ebfea2cb48ddc97992382556e74e4010b7856b95f","title":"","text":" // check-pass #![feature(associated_type_bounds)] #![feature(type_alias_impl_trait)] fn main() {} trait Bar { type Assoc; } trait Thing { type Out; fn func() -> Self::Out; } struct AssocIsCopy; impl Bar for AssocIsCopy { type Assoc = u8; } impl Thing for AssocIsCopy { type Out = impl Bar; fn func() -> Self::Out { AssocIsCopy } } "} {"_id":"doc-en-rust-3d94abff533a72c4a5d126c8c7a56e32a82fcb9cd93fdcfef2d02aad166c8605","title":"","text":"# Next, download the NetBSD libc and relevant header files mkdir netbsd curl https://ftp.netbsd.org/pub/NetBSD/NetBSD-7.0/amd64/binary/sets/base.tgz | # originally from: # https://ftp.netbsd.org/pub/NetBSD/NetBSD-7.0/amd64/binary/sets/base.tgz curl https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror/2017-01-16-netbsd-base.tgz | tar xzf - -C netbsd ./usr/include ./usr/lib ./lib curl https://ftp.netbsd.org/pub/NetBSD/NetBSD-7.0/amd64/binary/sets/comp.tgz | # originally from: # https://ftp.netbsd.org/pub/NetBSD/NetBSD-7.0/amd64/binary/sets/comp.tgz curl https://s3.amazonaws.com/rust-lang-ci/rust-ci-mirror/2017-01-16-netbsd-comp.tgz | tar xzf - -C netbsd ./usr/include ./usr/lib dst=/usr/local/x86_64-unknown-netbsd"} {"_id":"doc-en-rust-87c70bcc51a018ebe6ffda8965835f2b1a9a44037c8838725dbdd2f5fdae41d4","title":"","text":"# # * `CFG_ENABLE_VALGRIND=1` - Run tests under valgrind # * `VALGRIND_COMPILE=1` - Run the compiler itself under valgrind # (may require `CFG_ENABLE_VALGRIND`) # (requires `CFG_ENABLE_VALGRIND`) # # * `NO_REBUILD=1` - Don't rebootstrap when testing std # (and possibly other crates)"} {"_id":"doc-en-rust-95f059540574f68f0170a733b0418bbf00af910b84e2c651f163c8a8c3022f2f","title":"","text":"# see https://blog.mozilla.org/jseward/2012/06/05/valgrind-now-supports-jemalloc-builds-directly/ ifdef CFG_VALGRIND CFG_VALGRIND += --error-exitcode=100 --soname-synonyms=somalloc=NONE --fair-sched=try --quiet --soname-synonyms=somalloc=NONE --suppressions=$(CFG_SRC_DIR)src/etc/x86.supp $(OS_SUPP) ifdef CFG_ENABLE_HELGRIND"} {"_id":"doc-en-rust-0d90bacf7eb0344ce84e4f030f0b7fd0511125cb6d1d4560489dbea99efd0610","title":"","text":"#![feature(box_into_raw_non_null)] #![feature(box_patterns)] #![feature(box_syntax)] #![feature(cfg_sanitize)] #![feature(cfg_target_has_atomic)] #![feature(coerce_unsized)] #![feature(const_generic_impls_guard)]"} {"_id":"doc-en-rust-a3ee8caa89a84b2db9bf2474bf6db387f439dd3e8a810db21ad48be341170877","title":"","text":"/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references. const MAX_REFCOUNT: usize = (isize::MAX) as usize; #[cfg(not(sanitize = \"thread\"))] macro_rules! acquire { ($x:expr) => { atomic::fence(Acquire) }; } // ThreadSanitizer does not support memory fences. To avoid false positive // reports in Arc / Weak implementation use atomic loads for synchronization // instead. #[cfg(sanitize = \"thread\")] macro_rules! acquire { ($x:expr) => { $x.load(Acquire) }; } /// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically /// Reference Counted'. ///"} {"_id":"doc-en-rust-1cbc89a79500b7ce12c51c52b4e3d245f21568687a848b120fc5350b5eed378c","title":"","text":"return Err(this); } atomic::fence(Acquire); acquire!(this.inner().strong); unsafe { let elem = ptr::read(&this.ptr.as_ref().data);"} {"_id":"doc-en-rust-e37fbc1b5259db46cdcf6f5a7a8f488acf304165e024b1916e40b946ed1d64b9","title":"","text":"ptr::drop_in_place(&mut self.ptr.as_mut().data); if self.inner().weak.fetch_sub(1, Release) == 1 { atomic::fence(Acquire); acquire!(self.inner().weak); Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())) } }"} {"_id":"doc-en-rust-8d277ee33a00eb24568b845c6239fa38ce47b40563729254570f30eb8940737c","title":"","text":"// // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html) // [2]: (https://github.com/rust-lang/rust/pull/41714) atomic::fence(Acquire); acquire!(self.inner().strong); unsafe { self.drop_slow();"} {"_id":"doc-en-rust-374727ef5d7b19b7e4a0bc3aa427cc44e90d3418e7ea54af90f90bd11950629b","title":"","text":"let inner = if let Some(inner) = self.inner() { inner } else { return }; if inner.weak.fetch_sub(1, Release) == 1 { atomic::fence(Acquire); acquire!(inner.weak); unsafe { Global.dealloc(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())) } } }"} {"_id":"doc-en-rust-ecf9c77444194f214359e00de5beb03de9b6fcbfdc8a8069c3fae7c439fa5f69","title":"","text":"use common::{Codegen, DebugInfoLldb, DebugInfoGdb, Rustdoc, CodegenUnits}; use common::{Incremental, RunMake, Ui, MirOpt}; use errors::{self, ErrorKind, Error}; use filetime::FileTime; use json; use header::TestProps; use header;"} {"_id":"doc-en-rust-62bbcde066965a1440ca537fa336b6b024dbca45b6da69893571a21a02023eb4","title":"","text":"} } fn check_mir_test_timestamp(&self, test_name: &str, output_file: &Path) { let t = |file| FileTime::from_last_modification_time(&fs::metadata(file).unwrap()); let source_file = &self.testpaths.file; let output_time = t(output_file); let source_time = t(source_file); if source_time > output_time { debug!(\"source file time: {:?} output file time: {:?}\", source_time, output_time); panic!(\"test source file `{}` is newer than potentially stale output file `{}`.\", source_file.display(), test_name); } } fn compare_mir_test_output(&self, test_name: &str, expected_content: &Vec<&str>) { let mut output_file = PathBuf::new(); output_file.push(self.get_mir_dump_dir()); output_file.push(test_name); debug!(\"comparing the contests of: {:?}\", output_file); debug!(\"with: {:?}\", expected_content); self.check_mir_test_timestamp(test_name, &output_file); let mut dumped_file = fs::File::open(output_file.clone()).unwrap(); let mut dumped_string = String::new();"} {"_id":"doc-en-rust-56c334414ae786e1375f0af1e202f92a4066d02f2f3270f3da053aaef0d31f5e","title":"","text":"{ debug!(\"note_issue_32330: terr={:?}\", terr); match *terr { TypeError::RegionsInsufficientlyPolymorphic(_, &Region::ReVar(vid)) | TypeError::RegionsOverlyPolymorphic(_, &Region::ReVar(vid)) => { match self.region_vars.var_origin(vid) { RegionVariableOrigin::EarlyBoundRegion(_, _, Some(Issue32330 { fn_def_id, region_name })) => { diag.note( &format!(\"lifetime parameter `{0}` declared on fn `{1}` appears only in the return type, but here is required to be higher-ranked, which means that `{0}` must appear in both argument and return types\", region_name, self.tcx.item_path_str(fn_def_id))); diag.note( &format!(\"this error is the result of a recent bug fix; for more information, see issue #33685 \")); } _ => { } } TypeError::RegionsInsufficientlyPolymorphic(_, _, Some(box Issue32330 { fn_def_id, region_name })) | TypeError::RegionsOverlyPolymorphic(_, _, Some(box Issue32330 { fn_def_id, region_name })) => { diag.note( &format!(\"lifetime parameter `{0}` declared on fn `{1}` appears only in the return type, but here is required to be higher-ranked, which means that `{0}` must appear in both argument and return types\", region_name, self.tcx.item_path_str(fn_def_id))); diag.note( &format!(\"this error is the result of a recent bug fix; for more information, see issue #33685 \")); } _ => { } _ => {} } }"} {"_id":"doc-en-rust-ececc6a21c239600858e0a18d40a6add53be15c03dfaf62146b019d2bee64059","title":"","text":"InferCtxt, LateBoundRegion, HigherRankedType, RegionVariableOrigin, SubregionOrigin, SkolemizationMap}; use super::combine::CombineFields;"} {"_id":"doc-en-rust-4127d0c4ade060856fb50c080fa253c5b883cc26fd00e6185c2386697cc05a39","title":"","text":"skol_br, tainted_region); let issue_32330 = if let &ty::ReVar(vid) = tainted_region { match self.region_vars.var_origin(vid) { RegionVariableOrigin::EarlyBoundRegion(_, _, issue_32330) => { issue_32330.map(Box::new) } _ => None } } else { None }; if overly_polymorphic { debug!(\"Overly polymorphic!\"); return Err(TypeError::RegionsOverlyPolymorphic(skol_br, tainted_region)); tainted_region, issue_32330)); } else { debug!(\"Not as polymorphic!\"); return Err(TypeError::RegionsInsufficientlyPolymorphic(skol_br, tainted_region)); tainted_region, issue_32330)); } } }"} {"_id":"doc-en-rust-e8b710f9964f6c78cf89b6f2dda0bfd7b801e247b34d8e31f5adddde0051390a","title":"","text":"RegionsDoesNotOutlive(&'tcx Region, &'tcx Region), RegionsNotSame(&'tcx Region, &'tcx Region), RegionsNoOverlap(&'tcx Region, &'tcx Region), RegionsInsufficientlyPolymorphic(BoundRegion, &'tcx Region), RegionsOverlyPolymorphic(BoundRegion, &'tcx Region), RegionsInsufficientlyPolymorphic(BoundRegion, &'tcx Region, Option>), RegionsOverlyPolymorphic(BoundRegion, &'tcx Region, Option>), Sorts(ExpectedFound>), IntMismatch(ExpectedFound), FloatMismatch(ExpectedFound),"} {"_id":"doc-en-rust-23783be57618aa5b29c5d339fa885721e8761adb749d7de8f2d210d83c0747ce","title":"","text":"RegionsNoOverlap(..) => { write!(f, \"lifetimes do not intersect\") } RegionsInsufficientlyPolymorphic(br, _) => { RegionsInsufficientlyPolymorphic(br, _, _) => { write!(f, \"expected bound lifetime parameter {}, found concrete lifetime\", br) } RegionsOverlyPolymorphic(br, _) => { RegionsOverlyPolymorphic(br, _, _) => { write!(f, \"expected concrete lifetime, found bound lifetime parameter {}\", br) }"} {"_id":"doc-en-rust-eaab4b3e8edfef4dc72c494b13f527522c30d0f55e4fceb95d141e0079bfdfef","title":"","text":"self.note_and_explain_region(db, \"...does not overlap \", region2, \"\"); } RegionsInsufficientlyPolymorphic(_, conc_region) => { RegionsInsufficientlyPolymorphic(_, conc_region, _) => { self.note_and_explain_region(db, \"concrete lifetime that was found is \", conc_region, \"\"); } RegionsOverlyPolymorphic(_, &ty::ReVar(_)) => { RegionsOverlyPolymorphic(_, &ty::ReVar(_), _) => { // don't bother to print out the message below for // inference variables, it's not very illuminating. } RegionsOverlyPolymorphic(_, conc_region) => { RegionsOverlyPolymorphic(_, conc_region, _) => { self.note_and_explain_region(db, \"expected concrete lifetime is \", conc_region, \"\"); }"} {"_id":"doc-en-rust-e600f228bac748b50e4b226439b5282005c9e4716779a39df733308eca749d5b","title":"","text":"RegionsNoOverlap(a, b) => { return tcx.lift(&(a, b)).map(|(a, b)| RegionsNoOverlap(a, b)) } RegionsInsufficientlyPolymorphic(a, b) => { return tcx.lift(&b).map(|b| RegionsInsufficientlyPolymorphic(a, b)) RegionsInsufficientlyPolymorphic(a, b, ref c) => { let c = c.clone(); return tcx.lift(&b).map(|b| RegionsInsufficientlyPolymorphic(a, b, c)) } RegionsOverlyPolymorphic(a, b) => { return tcx.lift(&b).map(|b| RegionsOverlyPolymorphic(a, b)) RegionsOverlyPolymorphic(a, b, ref c) => { let c = c.clone(); return tcx.lift(&b).map(|b| RegionsOverlyPolymorphic(a, b, c)) } IntMismatch(x) => IntMismatch(x), FloatMismatch(x) => FloatMismatch(x),"} {"_id":"doc-en-rust-7a9fdcbf178ac2bc032bf11c2d75e7dbfd80c8a22f98dd683834bfec0f1f35aa","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(closure_to_fn_coercion)] fn main() { let bar: fn(&mut u32) = |_| {}; //~ ERROR mismatched types //~| expected concrete lifetime, found bound lifetime parameter fn foo(x: Box) {} let bar = Box::new(|x: &i32| {}) as Box; foo(bar); //~ ERROR mismatched types //~| expected concrete lifetime, found bound lifetime parameter } "} {"_id":"doc-en-rust-aac4241fe35233a5c745edc7d3c4619bf6671ddc3fa824281ee317ac8871c7c4","title":"","text":"- [abi_sysv64](abi-sysv64.md) - [abi_unadjusted](abi-unadjusted.md) - [abi_vectorcall](abi-vectorcall.md) - [abi_x86_interrupt](abi-x86-interrupt.md) - [advanced_slice_patterns](advanced-slice-patterns.md) - [alloc_jemalloc](alloc-jemalloc.md) - [alloc_system](alloc-system.md)"} {"_id":"doc-en-rust-cf44730a93cd60c94a8175c8803e94dea5ce989d1291af3a3ba490fef0aac329","title":"","text":" # `abi_x86_interrupt` The tracking issue for this feature is: [#40180] [#40180]: https://github.com/rust-lang/rust/issues/40180 ------------------------ "} {"_id":"doc-en-rust-fd2549adb07eaec00d9c4563777148605a8a3b167840506df39637b851e8279c","title":"","text":"/// # Examples /// /// ``` /// #![feature(float_bits_conv)] /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting! /// assert_eq!((12.5f32).to_bits(), 0x41480000); /// /// ``` #[unstable(feature = \"float_bits_conv\", reason = \"recently added\", issue = \"40470\")] #[stable(feature = \"float_bits_conv\", since = \"1.21.0\")] #[inline] pub fn to_bits(self) -> u32 { unsafe { ::mem::transmute(self) }"} {"_id":"doc-en-rust-f01a8fba15b78725ff78713d08c9694c4e12598532acf3df4c26da7c88682dec","title":"","text":"/// # Examples /// /// ``` /// #![feature(float_bits_conv)] /// use std::f32; /// let v = f32::from_bits(0x41480000); /// let difference = (v - 12.5).abs();"} {"_id":"doc-en-rust-db5fbfd31fe7be6a294201200629fa7c2d1f743c554ea9c3d1e9b1dec84ef7d7","title":"","text":"/// let snan = 0x7F800001; /// assert_ne!(f32::from_bits(snan).to_bits(), snan); /// ``` #[unstable(feature = \"float_bits_conv\", reason = \"recently added\", issue = \"40470\")] #[stable(feature = \"float_bits_conv\", since = \"1.21.0\")] #[inline] pub fn from_bits(mut v: u32) -> Self { const EXP_MASK: u32 = 0x7F800000;"} {"_id":"doc-en-rust-8ac7ea38854b1b2539d388ebba293f12b52f399e228c1f780be55e0075c8a1cb","title":"","text":"/// # Examples /// /// ``` /// #![feature(float_bits_conv)] /// assert!((1f64).to_bits() != 1f64 as u64); // to_bits() is not casting! /// assert_eq!((12.5f64).to_bits(), 0x4029000000000000); /// /// ``` #[unstable(feature = \"float_bits_conv\", reason = \"recently added\", issue = \"40470\")] #[stable(feature = \"float_bits_conv\", since = \"1.21.0\")] #[inline] pub fn to_bits(self) -> u64 { unsafe { ::mem::transmute(self) }"} {"_id":"doc-en-rust-81e22e293913008e97d05cf0998179d69d046e2e6ff7f0f9963cb9c027b0d1d2","title":"","text":"/// # Examples /// /// ``` /// #![feature(float_bits_conv)] /// use std::f64; /// let v = f64::from_bits(0x4029000000000000); /// let difference = (v - 12.5).abs();"} {"_id":"doc-en-rust-af5e825d6cb0cbbc220cd4861e9258860ec5dd461dcb68f2455551e5588cad9e","title":"","text":"/// let snan = 0x7FF0000000000001; /// assert_ne!(f64::from_bits(snan).to_bits(), snan); /// ``` #[unstable(feature = \"float_bits_conv\", reason = \"recently added\", issue = \"40470\")] #[stable(feature = \"float_bits_conv\", since = \"1.21.0\")] #[inline] pub fn from_bits(mut v: u64) -> Self { const EXP_MASK: u64 = 0x7FF0000000000000;"} {"_id":"doc-en-rust-a4858843032b14978be22a2e82ffe8375eab729b67390485d8d4afad31a0aed8","title":"","text":"#![feature(unwind_attributes)] #![feature(vec_push_all)] #![cfg_attr(test, feature(update_panic_count))] #![cfg_attr(test, feature(float_bits_conv))] #![cfg_attr(not(stage0), default_lib_allocator)]"} {"_id":"doc-en-rust-d313e46446158776bc2f956db5a6018b6c2e20a601387ca9ad49d98a9c269d0b","title":"","text":"} impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedMut { fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { if let hir::ExprMatch(_, ref arms, _) = e.node { for a in arms { self.check_unused_mut_pat(cx, &a.pats) } } fn check_arm(&mut self, cx: &LateContext, a: &hir::Arm) { self.check_unused_mut_pat(cx, &a.pats) } fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) { if let hir::StmtDecl(ref d, _) = s.node { if let hir::DeclLocal(ref l) = d.node { self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat)); } } fn check_local(&mut self, cx: &LateContext, l: &hir::Local) { self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat)); } fn check_fn(&mut self,"} {"_id":"doc-en-rust-6ebdeb259da38d9ff4705af196fd7e0eb590aa5666397a679e19dc0ade240757","title":"","text":"let mut a = 3; let mut b = vec![2]; } // make sure the lint attribute can be turned off on let statements #[deny(unused_mut)] fn bar() { #[allow(unused_mut)] let mut a = 3; let mut b = vec![2]; //~ ERROR: variable does not need to be mutable } "} {"_id":"doc-en-rust-9417ff5d8857cea86a9501bbc093d77a821903ad079ed1090493447a5d1b71f0","title":"","text":"This flag will set which lints should be set to the [forbid level](lints/levels.html#forbid). ## `-Z`: set unstable options This flag will allow you to set unstable options of rustc. In order to set multiple options, the -Z flag can be used multiple times. For example: `rustc -Z verbose -Z time`. Specifying options with -Z is only available on nightly. To view all available options run: `rustc -Z help`. ## `--cap-lints`: set the most restrictive lint level This flag lets you 'cap' lints, for more, [see here](lints/levels.html#capping-lints)."} {"_id":"doc-en-rust-1370349b163d24e2d8e9be13ab2c1d2a98319de39e0a0defe99d2bfffc8ac750","title":"","text":"} let message = \"Usage: rustc [OPTIONS] INPUT\"; let nightly_help = if nightly_options::is_nightly_build() { \"n -Z help Print internal options for debugging rustc\" \"n -Z help Print unstable compiler options\" } else { \"\" };"} {"_id":"doc-en-rust-66c77863dbcaeca69f9d771d2334eb4ddd12803a081e510138dd8ffa5898e9ee","title":"","text":"} fn describe_debug_flags() { println!(\"nAvailable debug options:n\"); println!(\"nAvailable options:n\"); print_flag_list(\"-Z\", config::DB_OPTIONS); }"} {"_id":"doc-en-rust-80cb11b02e9a65f5c4fb42b2fcc1b532e097d7e602600ce90f6503f5b2775bf7","title":"","text":"impl NonCamelCaseTypes { fn check_case(&self, cx: &LateContext, sort: &str, name: ast::Name, span: Span) { fn char_has_case(c: char) -> bool { c.is_lowercase() || c.is_uppercase() } fn is_camel_case(name: ast::Name) -> bool { let name = name.as_str(); if name.is_empty() {"} {"_id":"doc-en-rust-7fd9086aae2ada4e4b69a857e6bf2892556bf43732e2b7b1362918a09d0e7cde","title":"","text":"// start with a non-lowercase letter rather than non-uppercase // ones (some scripts don't have a concept of upper/lowercase) !name.is_empty() && !name.chars().next().unwrap().is_lowercase() && !name.contains('_') !name.is_empty() && !name.chars().next().unwrap().is_lowercase() && !name.contains(\"__\") && !name.chars().collect::>().windows(2).any(|pair| { // contains a capitalisable character followed by, or preceded by, an underscore char_has_case(pair[0]) && pair[1] == '_' || char_has_case(pair[1]) && pair[0] == '_' }) } fn to_camel_case(s: &str) -> String { s.split('_') .flat_map(|word| { s.trim_matches('_') .split('_') .map(|word| { word.chars().enumerate().map(|(i, c)| if i == 0 { c.to_uppercase().collect::() } else { c.to_lowercase().collect() }) .collect::>() .concat() }) .filter(|x| !x.is_empty()) .collect::>() .concat() .iter().fold((String::new(), None), |(acc, prev): (String, Option<&String>), next| { // separate two components with an underscore if their boundary cannot // be distinguished using a uppercase/lowercase case distinction let join = if let Some(prev) = prev { let l = prev.chars().last().unwrap(); let f = next.chars().next().unwrap(); !char_has_case(l) && !char_has_case(f) } else { false }; (acc + if join { \"_\" } else { \"\" } + next, Some(next)) }).0 } if !is_camel_case(name) {"} {"_id":"doc-en-rust-95255ae1b20cf4f06cfe311612a59cd20dc550d72e147f25f2056044129053b7","title":"","text":"type __ = isize; //~ ERROR type `__` should have a camel case name such as `CamelCase` struct X86_64; struct X86__64; //~ ERROR type `X86__64` should have a camel case name such as `X86_64` struct Abc_123; //~ ERROR type `Abc_123` should have a camel case name such as `Abc123` struct A1_b2_c3; //~ ERROR type `A1_b2_c3` should have a camel case name such as `A1B2C3` fn main() { }"} {"_id":"doc-en-rust-a3e71c2cd1e092b40fef48aa898cc2d9a2388db656dbc3881593bf61c25f92f0","title":"","text":"// required. #[cfg(stage1)] #[cfg(stage2)] #[cfg(stage3)] pub impl Chan { fn send(&self, x: T) { chan_send(self, x) } fn try_send(&self, x: T) -> bool { chan_try_send(self, x) }"} {"_id":"doc-en-rust-bde3e7628f9bf5e6506c73fae498f1c5cf5d9ab6b47ac17156bfcaaab60c076e","title":"","text":"// Use an inherent impl so that imports are not required: #[cfg(stage1)] #[cfg(stage2)] #[cfg(stage3)] pub impl Port { fn recv(&self) -> T { port_recv(self) } fn try_recv(&self) -> Option { port_try_recv(self) }"} {"_id":"doc-en-rust-bc67762efa8181127bcc4062d1fd38da0fbdc44aeed1debcc191b505894685dd","title":"","text":"// Use an inherent impl so that imports are not required: #[cfg(stage1)] #[cfg(stage2)] #[cfg(stage3)] pub impl PortSet { fn recv(&self) -> T { port_set_recv(self) } fn try_recv(&self) -> Option { port_set_try_recv(self) }"} {"_id":"doc-en-rust-c446723ea530ee69d20d19b71715071b022a36842b5ba35f83b62c0c1122a8ac","title":"","text":"#[cfg(stage1)] #[cfg(stage2)] #[cfg(stage3)] pub impl SharedChan { fn send(&self, x: T) { shared_chan_send(self, x) } fn try_send(&self, x: T) -> bool { shared_chan_try_send(self, x) }"} {"_id":"doc-en-rust-305c9ffccf3eb07666ac8b0792da7c769ae1534cc9877b8c8932521312b177ed","title":"","text":"#[cfg(stage1)] #[cfg(stage2)] #[cfg(stage3)] impl Reader for @Reader { fn read(&self, bytes: &mut [u8], len: uint) -> uint { self.read(bytes, len)"} {"_id":"doc-en-rust-0c6602570fc08d4028376298790633e6f9c65979d83e79166091dca67f685e0d","title":"","text":"#[cfg(stage1)] #[cfg(stage2)] #[cfg(stage3)] impl Writer for @Writer { fn write(&self, v: &[const u8]) { self.write(v) } fn seek(&self, a: int, b: SeekStyle) { self.seek(a, b) }"} {"_id":"doc-en-rust-fce3660b18b0280e7e92c924fa5f34d4b536aad4066465bde36532aa21933058","title":"","text":"#[cfg(stage1)] #[cfg(stage2)] #[cfg(stage3)] fn mk_tests(cx: &TestCtxt) -> @ast::item { let ext_cx = cx.ext_cx;"} {"_id":"doc-en-rust-aa1151b780ff654d521d541efdcb6ecde27cefa0c05e64187c96060abc0915b6","title":"","text":"// Allow these methods to be used without import: #[cfg(stage1)] #[cfg(stage2)] #[cfg(stage3)] pub impl DuplexStream { fn send(&self, x: T) { self.chan.send(x)"} {"_id":"doc-en-rust-175986c5b94b5a9be6e9ba4acf18582f14139a426fedd3104c0fb7723522c81b","title":"","text":"} #[stable(feature = \"collection_debug\", since = \"1.17.0\")] impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Keys<'a, K, V> { impl<'a, K: 'a + fmt::Debug, V: 'a> fmt::Debug for Keys<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.inner.clone()).finish() f.debug_list().entries(self.clone()).finish() } }"} {"_id":"doc-en-rust-61db9cd8bb9c684b2a7310de694cec70e30a2188ef68fe810e25fa74dd4813f0","title":"","text":"} #[stable(feature = \"collection_debug\", since = \"1.17.0\")] impl<'a, K: 'a + fmt::Debug, V: 'a + fmt::Debug> fmt::Debug for Values<'a, K, V> { impl<'a, K: 'a, V: 'a + fmt::Debug> fmt::Debug for Values<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list().entries(self.inner.clone()).finish() f.debug_list().entries(self.clone()).finish() } }"} {"_id":"doc-en-rust-f7df009e535e14dcde516109b81491b1da422bc70043ef2adc801b89c59ca187","title":"","text":"} #[stable(feature = \"std_debug\", since = \"1.16.0\")] impl<'a, K: Debug, V: Debug> fmt::Debug for Keys<'a, K, V> { impl<'a, K: Debug, V> fmt::Debug for Keys<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list() .entries(self.clone())"} {"_id":"doc-en-rust-17984c63e9c27980d41568b37a02d724b0b7e3688379a31e85e139c39f634499","title":"","text":"} #[stable(feature = \"std_debug\", since = \"1.16.0\")] impl<'a, K: Debug, V: Debug> fmt::Debug for Values<'a, K, V> { impl<'a, K, V: Debug> fmt::Debug for Values<'a, K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_list() .entries(self.clone())"} {"_id":"doc-en-rust-ef8dc20ef86eb7e04f3e0dabe8cdfc023a01183660f5317b0d4a2c71ff45c7ef","title":"","text":"} } fn trace_macros_note(cx: &mut ExtCtxt, sp: Span, message: String) { let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp); let mut values: &mut Vec = cx.expansions.entry(sp).or_insert_with(Vec::new); values.push(message); } /// Given `lhses` and `rhses`, this is the new macro we create fn generic_extension<'cx>(cx: &'cx mut ExtCtxt, sp: Span,"} {"_id":"doc-en-rust-e54b9aa9d45958514e42f918d16bcb78cd646f6401d9f34465ff82bd0a9a871c","title":"","text":"rhses: &[quoted::TokenTree]) -> Box { if cx.trace_macros() { let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp); let mut values: &mut Vec = cx.expansions.entry(sp).or_insert_with(Vec::new); values.push(format!(\"expands to `{}! {{ {} }}`\", name, arg)); trace_macros_note(cx, sp, format!(\"expanding `{}! {{ {} }}`\", name, arg)); } // Which arm's failure should we report? (the one furthest along)"} {"_id":"doc-en-rust-431fe7339dd9dcbdf4ecae5336a17fe625bf820ac699dee046b93b3295423592","title":"","text":"}; // rhs has holes ( `$id` and `$(...)` that need filled) let tts = transcribe(&cx.parse_sess.span_diagnostic, Some(named_matches), rhs); if cx.trace_macros() { trace_macros_note(cx, sp, format!(\"to `{}`\", tts)); } let directory = Directory { path: cx.current_expansion.module.directory.clone(), ownership: cx.current_expansion.directory_ownership,"} {"_id":"doc-en-rust-a25e8ba0316bf14b24c0f114cd5cddfe4a2a25708fc2210c9c4c2820a4ff6279","title":"","text":"14 | println!(\"Hello, World!\"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: expands to `println! { \"Hello, World!\" }` = note: expands to `print! { concat ! ( \"Hello, World!\" , \"/n\" ) }` = note: expanding `println! { \"Hello, World!\" }` = note: to `print ! ( concat ! ( \"Hello, World!\" , \"/n\" ) )` = note: expanding `print! { concat ! ( \"Hello, World!\" , \"/n\" ) }` = note: to `$crate :: io :: _print ( format_args ! ( concat ! ( \"Hello, World!\" , \"/n\" ) ) )` "} {"_id":"doc-en-rust-6aa088d8cad06a4856e706508109e1bc91144a7164e48adfa31aae5b4a9575a6","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let value = 1; match SomeStruct(value) { StructConst1(_) => { }, //~^ ERROR expected tuple struct/variant, found constant `StructConst1` _ => { }, } struct SomeStruct(u8); const StructConst1 : SomeStruct = SomeStruct(1); const StructConst2 : SomeStruct = SomeStruct(2); } "} {"_id":"doc-en-rust-71a4dcf7b27158c237438c308e686464338c8fef75775f444d5ed64b4d052522","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(associated_consts)] trait Foo { const BAR: i32; fn foo(self) -> &'static i32 { //~^ ERROR the trait bound `Self: std::marker::Sized` is not satisfied &::BAR } } fn main() {} "} {"_id":"doc-en-rust-c0c355ec7fb88d20e63912f37091367a3f69fdc279d91d652d7b0ae70df56028","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. macro_rules! get_opt { ($tgt:expr, $field:ident) => { if $tgt.has_$field() {} } } fn main() { get_opt!(bar, foo); //~^ ERROR expected `{`, found `foo` } "} {"_id":"doc-en-rust-15b59e0982c744644ab995833220d86cd89283dfe32780f30b8e0519c36813cb","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let a = |r: f64| if r != 0.0(r != 0.0) { 1.0 } else { 0.0 }; //~^ ERROR expected function, found `{float}` } "} {"_id":"doc-en-rust-ffcd9654c0b272a29400915b9fdc4c0cf3ef36cfe3878d420724bdd08e8521d2","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // #45662 #![feature(repr_align)] #![feature(attr_literals)] #[repr(align(16))] pub struct A { y: i64, } pub extern \"C\" fn foo(x: A) {} fn main() {} "} {"_id":"doc-en-rust-38717a969f04d331e6126719e75d72e2fdd21cb4acd9f253055bef83282df4b2","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(conservative_impl_trait)] use std::iter::once; struct Foo { x: i32, } impl Foo { fn inside(&self) -> impl Iterator { once(&self.x) } } fn main() { println!(\"hi\"); } "} {"_id":"doc-en-rust-d7f8820af12943fe08475a3168112f3dfb84c5ee5a06dfc5aab833ca0551b74e","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(unsize, coerce_unsized)] #[repr(packed)] struct UnalignedPtr<'a, T: ?Sized> where T: 'a, { data: &'a T, } fn main() { impl<'a, T, U> std::ops::CoerceUnsized> for UnalignedPtr<'a, T> where T: std::marker::Unsize + ?Sized, U: ?Sized, { } let arr = [1, 2, 3]; let arr_unaligned: UnalignedPtr<[i32; 3]> = UnalignedPtr { data: &arr }; let arr_unaligned: UnalignedPtr<[i32]> = arr_unaligned; } "} {"_id":"doc-en-rust-476a6c171f7d206fde4d22c4e8585c6bd044b15d7f845792c2b29d17c7fc2e9b","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // #42164 #![feature(decl_macro)] #![allow(dead_code)] pub macro m($inner_str:expr) { #[doc = $inner_str] struct S; } macro_rules! define_f { ($name:expr) => { #[export_name = $name] fn f() {} } } fn main() { define_f!(concat!(\"exported_\", \"f\")); m!(stringify!(foo)); } "} {"_id":"doc-en-rust-763e61b797e7de3696144f7437c337f6d9492a57637b62a809c9482a3f0babba","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. use rustc_serialize::{Encodable, Decodable, Encoder, Decoder}; use rustc_data_structures::stable_hasher; use std::mem; use std::slice; #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy)] #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone, Copy, RustcEncodable, RustcDecodable)] pub struct Fingerprint(u64, u64); impl Fingerprint {"} {"_id":"doc-en-rust-be6700ce96385fb332de835e2b33531ded879f60d82aacac48303d5af9c6d31b","title":"","text":"} } impl Encodable for Fingerprint { #[inline] fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_u64(self.0.to_le())?; s.emit_u64(self.1.to_le()) } } impl Decodable for Fingerprint { #[inline] fn decode(d: &mut D) -> Result { let _0 = u64::from_le(d.read_u64()?); let _1 = u64::from_le(d.read_u64()?); Ok(Fingerprint(_0, _1)) } } impl ::std::fmt::Display for Fingerprint { fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(formatter, \"{:x}-{:x}\", self.0, self.1)"} {"_id":"doc-en-rust-3001b6b7f843e36be145dee395dc219adcfba7ba7875386ee0c7ca3a21802b82","title":"","text":"let ast::Path { ref segments, span } = *path; let path: Vec<_> = segments.iter().map(|seg| respan(seg.span, seg.identifier)).collect(); let invocation = self.invocations[&scope]; self.current_module = invocation.module.get(); let module = invocation.module.get(); self.current_module = if module.is_trait() { module.parent.unwrap() } else { module }; if path.len() > 1 { if !self.use_extern_macros && self.gated_errors.insert(span) {"} {"_id":"doc-en-rust-49ec1c5080fc2b18998b9105adae027ce07406614ce81f8fea0b2a1814598b76","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:attr-on-trait.rs #![feature(proc_macro)] extern crate attr_on_trait; trait Foo { #[attr_on_trait::foo] fn foo() {} } impl Foo for i32 { fn foo(&self) {} } fn main() { 3i32.foo(); } "} {"_id":"doc-en-rust-c82dfb9156956800329225ebbbb28a11c586ec4022860d327ed3236b30f80b3d","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // no-prefer-dynamic #![feature(proc_macro)] #![crate_type = \"proc-macro\"] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_attribute] pub fn foo(attr: TokenStream, item: TokenStream) -> TokenStream { drop(attr); assert_eq!(item.to_string(), \"fn foo() { }\"); \"fn foo(&self);\".parse().unwrap() } "} {"_id":"doc-en-rust-351342804b825814162b9bee81fe778f4750f8e153f47d84837a7c359965285e","title":"","text":"/// # Examples /// /// ```should_panic /// #![feature(panic_col)] /// use std::panic; /// /// panic::set_hook(Box::new(|panic_info| {"} {"_id":"doc-en-rust-4999d2ff15165b3243f2b13aba012e190569c18d182599edabc24989e0c8993e","title":"","text":"/// /// panic!(\"Normal panic\"); /// ``` #[unstable(feature = \"panic_col\", reason = \"recently added\", issue = \"42939\")] #[stable(feature = \"panic_col\", since = \"1.25\")] pub fn column(&self) -> u32 { self.col }"} {"_id":"doc-en-rust-54fc3dd964382d24ef6b2bd6a388679548ab108856d1dfa7c2cd27d6ab3107df","title":"","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":"doc-en-rust-cabd0ca23e756d61e87ab9362a783abc3cd6cadb6526e24b4ef4106e32d58d4e","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // only-x86_64 #![allow(dead_code, non_upper_case_globals)] #![feature(asm)] #[repr(C)] pub struct D32x4(f32,f32,f32,f32); impl D32x4 { fn add(&self, vec: Self) -> Self { unsafe { let ret: Self; asm!(\" movaps $1, %xmm1 movaps $2, %xmm2 addps %xmm1, %xmm2 movaps $xmm1, $0 \" : \"=r\"(ret) : \"1\"(self), \"2\"(vec) : \"xmm1\", \"xmm2\" ); ret } } } fn main() { } "} {"_id":"doc-en-rust-0dda8e9e39b3e044c9aa64fc3e74feb14cb376908fec01ca82f6438703c99fb1","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. const C: *const u8 = &0; fn foo(x: *const u8) { match x { C => {} _ => {} } } const D: *const [u8; 4] = b\"abcd\"; fn main() { match D { D => {} _ => {} } } "} {"_id":"doc-en-rust-4d84933d82c5467785f6157fd25a318cd00cdbcc61907aced8b9ec2e5785220c","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait Foo<'a> { type Bar; fn foo(&'a self) -> Self::Bar; } impl<'a, 'b, T: 'a> Foo<'a> for &'b T { type Bar = &'a T; fn foo(&'a self) -> &'a T { self } } pub fn uncallable(x: T, f: F) where T: for<'a> Foo<'a>, F: for<'a> Fn(>::Bar) { f(x.foo()); } pub fn catalyst(x: &i32) { broken(x, |_| {}) } pub fn broken(x: &i32, f: F) { uncallable(x, |y| f(y)); } fn main() { } "} {"_id":"doc-en-rust-1a58369126ac1d900fe2ceffe1830987593d495681341ec1ffeb1bdbf8185f92","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let thing = (); let other: typeof(thing) = thing; //~ ERROR attempt to use a non-constant value in a constant //~^ ERROR `typeof` is a reserved keyword but unimplemented [E0516] } fn f(){ let q = 1; ::N //~ ERROR attempt to use a non-constant value in a constant //~^ ERROR `typeof` is a reserved keyword but unimplemented [E0516] } "} {"_id":"doc-en-rust-1fc0b8c93993efc73c68c66a6503e782997f22897fbddcd01788dcb57f787c47","title":"","text":" error[E0435]: attempt to use a non-constant value in a constant --> $DIR/issue-42060.rs:13:23 | LL | let other: typeof(thing) = thing; //~ ERROR attempt to use a non-constant value in a constant | ^^^^^ non-constant value error[E0435]: attempt to use a non-constant value in a constant --> $DIR/issue-42060.rs:19:13 | LL | ::N //~ ERROR attempt to use a non-constant value in a constant | ^ non-constant value error[E0516]: `typeof` is a reserved keyword but unimplemented --> $DIR/issue-42060.rs:13:16 | LL | let other: typeof(thing) = thing; //~ ERROR attempt to use a non-constant value in a constant | ^^^^^^^^^^^^^ reserved keyword error[E0516]: `typeof` is a reserved keyword but unimplemented --> $DIR/issue-42060.rs:19:6 | LL | ::N //~ ERROR attempt to use a non-constant value in a constant | ^^^^^^^^^ reserved keyword error: aborting due to 4 previous errors Some errors occurred: E0435, E0516. For more information about an error, try `rustc --explain E0435`. "} {"_id":"doc-en-rust-82e2e207ac72d350587cde4e89f093f9fe113ab7e404a81f99d64d535f673d48","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { | } //~^ ERROR expected `|`, found `}` | //~^ ERROR expected item, found `|` "} {"_id":"doc-en-rust-4e71d00751d53e41329683d008a5b01fdee1f2904b1082996b4b6dc321f8d361","title":"","text":" error: expected `|`, found `}` --> $DIR/issue-43196.rs:13:1 | LL | | | - expected `|` here LL | } | ^ unexpected token error: expected item, found `|` --> $DIR/issue-43196.rs:15:1 | LL | | | ^ expected item error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-df3d362b11230240f9621aeb21ec0f7741651165610b261d778a83ba12efd6f2","title":"","text":"use tvec; use value::Value; use super::MirContext; use super::{MirContext, LocalRef}; use super::constant::const_scalar_checked_binop; use super::operand::{OperandRef, OperandValue}; use super::lvalue::LvalueRef;"} {"_id":"doc-en-rust-4f67c1c402ed652ffca2f3f4a25bcad630cbbe057da44b43bab5660935a8f894","title":"","text":"} mir::Rvalue::Len(ref lvalue) => { let tr_lvalue = self.trans_lvalue(&bcx, lvalue); let size = self.evaluate_array_len(&bcx, lvalue); let operand = OperandRef { val: OperandValue::Immediate(tr_lvalue.len(bcx.ccx)), val: OperandValue::Immediate(size), ty: bcx.tcx().types.usize, }; (bcx, operand)"} {"_id":"doc-en-rust-9e548218d033d975c449d10e00be7fa96561bdff1ac49c328e3a9338ac7a1df7","title":"","text":"} } fn evaluate_array_len(&mut self, bcx: &Builder<'a, 'tcx>, lvalue: &mir::Lvalue<'tcx>) -> ValueRef { // ZST are passed as operands and require special handling // because trans_lvalue() panics if Local is operand. if let mir::Lvalue::Local(index) = *lvalue { if let LocalRef::Operand(Some(op)) = self.locals[index] { if common::type_is_zero_size(bcx.ccx, op.ty) { if let ty::TyArray(_, n) = op.ty.sty { return common::C_uint(bcx.ccx, n); } } } } // use common size calculation for non zero-sized types let tr_value = self.trans_lvalue(&bcx, lvalue); return tr_value.len(bcx.ccx); } pub fn trans_scalar_binop(&mut self, bcx: &Builder<'a, 'tcx>, op: mir::BinOp,"} {"_id":"doc-en-rust-44ae3f81bea7de82a8daa5e2465e063bbbf62931b384b9b24526faed6a52a717","title":"","text":" // Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { &&[()][0]; println!(\"{:?}\", &[(),()][1]); } "} {"_id":"doc-en-rust-b02af5748bf13d8fda87d55c42490e3e009db81d7644ac87785fcd286bac3643","title":"","text":" pub trait Trait<'a> { type Assoc; } pub struct Type; impl<'a> Trait<'a> for Type { type Assoc = (); } pub fn break_me(f: F) where T: for<'b> Trait<'b>, F: for<'b> FnMut(>::Assoc) { break_me::; //~^ ERROR: type mismatch in function arguments //~| ERROR: type mismatch resolving } fn main() {} "} {"_id":"doc-en-rust-b54b6bf53ae90e09021510892c64a36aa72024b01be7bb5e5ffcaa19d33a9dd1","title":"","text":" error[E0631]: type mismatch in function arguments --> $DIR/issue-43623.rs:14:5 | LL | break_me::; | ^^^^^^^^^^^^^^^^^^^^^^^ | | | expected signature of `for<'b> fn(>::Assoc) -> _` | found signature of `fn(_) -> _` | note: required by `break_me` --> $DIR/issue-43623.rs:11:1 | LL | / pub fn break_me(f: F) LL | | where T: for<'b> Trait<'b>, LL | | F: for<'b> FnMut(>::Assoc) { LL | | break_me::; LL | | LL | | LL | | } | |_^ error[E0271]: type mismatch resolving `for<'b> >::Assoc,)>>::Output == ()` --> $DIR/issue-43623.rs:14:5 | LL | break_me::; | ^^^^^^^^^^^^^^^^^^^^^^^ expected bound lifetime parameter 'b, found concrete lifetime | note: required by `break_me` --> $DIR/issue-43623.rs:11:1 | LL | / pub fn break_me(f: F) LL | | where T: for<'b> Trait<'b>, LL | | F: for<'b> FnMut(>::Assoc) { LL | | break_me::; LL | | LL | | LL | | } | |_^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0271`. "} {"_id":"doc-en-rust-a287460175c349e076f5602d4e710532246364c78c7325281e23afc0f946d8ac","title":"","text":" use std::ops::Index; struct Test; struct Container(Test); impl Test { fn test(&mut self) {} } impl<'a> Index<&'a bool> for Container { type Output = Test; fn index(&self, _index: &'a bool) -> &Test { &self.0 } } fn main() { let container = Container(Test); let mut val = true; container[&mut val].test(); //~ ERROR: cannot borrow data } "} {"_id":"doc-en-rust-00891e61eb315fe9da6470c946fb3e0a06bca19d1a2a7d68ccf42209b2049300","title":"","text":" error[E0596]: cannot borrow data in an index of `Container` as mutable --> $DIR/issue-44405.rs:21:5 | LL | container[&mut val].test(); | ^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable | = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `Container` error: aborting due to previous error For more information about this error, try `rustc --explain E0596`. "} {"_id":"doc-en-rust-814a159519b9cbe4f71b58ec7e6a7f0cf847515c84cb0ee7f214ca4d9f565ded","title":"","text":"// Building with a static libstdc++ is only supported on linux right now, // not for MSVC or macOS if build.config.llvm_static_stdcpp && !target.contains(\"freebsd\") && !target.contains(\"windows\") && !target.contains(\"apple\") { cargo.env(\"LLVM_STATIC_STDCPP\","} {"_id":"doc-en-rust-d430cfb99b119c7a7b1fd7ffbadba16efc1a45ed734662981620c96334f582f6","title":"","text":"libssl-dev pkg-config COPY dist-i686-freebsd/build-toolchain.sh /tmp/ RUN /tmp/build-toolchain.sh i686 COPY scripts/freebsd-toolchain.sh /tmp/ RUN /tmp/freebsd-toolchain.sh i686 COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh ENV AR_i686_unknown_freebsd=i686-unknown-freebsd10-ar CC_i686_unknown_freebsd=i686-unknown-freebsd10-gcc CXX_i686_unknown_freebsd=i686-unknown-freebsd10-g++ CC_i686_unknown_freebsd=i686-unknown-freebsd10-clang CXX_i686_unknown_freebsd=i686-unknown-freebsd10-clang++ ENV HOSTS=i686-unknown-freebsd"} {"_id":"doc-en-rust-f43be0dd38b3adfdd81d77e16569ad2dac730954e961aea7c03052de7a95768c","title":"","text":"FROM ubuntu:16.04 RUN apt-get update && apt-get install -y --no-install-recommends g++ clang make file curl "} {"_id":"doc-en-rust-cb739ac321b2600af9dca769b083f2af653cc2705f15c2af8f01c11be1811825","title":"","text":"libssl-dev pkg-config COPY dist-x86_64-freebsd/build-toolchain.sh /tmp/ RUN /tmp/build-toolchain.sh x86_64 COPY scripts/freebsd-toolchain.sh /tmp/ RUN /tmp/freebsd-toolchain.sh x86_64 COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh ENV AR_x86_64_unknown_freebsd=x86_64-unknown-freebsd10-ar CC_x86_64_unknown_freebsd=x86_64-unknown-freebsd10-gcc CXX_x86_64_unknown_freebsd=x86_64-unknown-freebsd10-g++ CC_x86_64_unknown_freebsd=x86_64-unknown-freebsd10-clang CXX_x86_64_unknown_freebsd=x86_64-unknown-freebsd10-clang++ ENV HOSTS=x86_64-unknown-freebsd"} {"_id":"doc-en-rust-e458fc54eefaa2caed11e4bce9257a5a3063f2040aac4893266093929989f446","title":"","text":" #!/usr/bin/env bash # 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. set -ex ARCH=$1 BINUTILS=2.25.1 GCC=6.4.0 hide_output() { set +x on_err=\" echo ERROR: An error was encountered with the build. cat /tmp/build.log exit 1 \" trap \"$on_err\" ERR bash -c \"while true; do sleep 30; echo $(date) - building ...; done\" & PING_LOOP_PID=$! $@ &> /tmp/build.log trap - ERR kill $PING_LOOP_PID set -x } mkdir binutils cd binutils # First up, build binutils curl https://ftp.gnu.org/gnu/binutils/binutils-$BINUTILS.tar.bz2 | tar xjf - mkdir binutils-build cd binutils-build hide_output ../binutils-$BINUTILS/configure --target=$ARCH-unknown-freebsd10 hide_output make -j10 hide_output make install cd ../.. rm -rf binutils # Next, download the FreeBSD libc and relevant header files mkdir freebsd case \"$ARCH\" in x86_64) URL=ftp://ftp.freebsd.org/pub/FreeBSD/releases/amd64/10.2-RELEASE/base.txz ;; i686) URL=ftp://ftp.freebsd.org/pub/FreeBSD/releases/i386/10.2-RELEASE/base.txz ;; esac curl $URL | tar xJf - -C freebsd ./usr/include ./usr/lib ./lib dst=/usr/local/$ARCH-unknown-freebsd10 cp -r freebsd/usr/include $dst/ cp freebsd/usr/lib/crt1.o $dst/lib cp freebsd/usr/lib/Scrt1.o $dst/lib cp freebsd/usr/lib/crti.o $dst/lib cp freebsd/usr/lib/crtn.o $dst/lib cp freebsd/usr/lib/libc.a $dst/lib cp freebsd/usr/lib/libutil.a $dst/lib cp freebsd/usr/lib/libutil_p.a $dst/lib cp freebsd/usr/lib/libm.a $dst/lib cp freebsd/usr/lib/librt.so.1 $dst/lib cp freebsd/usr/lib/libexecinfo.so.1 $dst/lib cp freebsd/lib/libc.so.7 $dst/lib cp freebsd/lib/libm.so.5 $dst/lib cp freebsd/lib/libutil.so.9 $dst/lib cp freebsd/lib/libthr.so.3 $dst/lib/libpthread.so ln -s libc.so.7 $dst/lib/libc.so ln -s libm.so.5 $dst/lib/libm.so ln -s librt.so.1 $dst/lib/librt.so ln -s libutil.so.9 $dst/lib/libutil.so ln -s libexecinfo.so.1 $dst/lib/libexecinfo.so rm -rf freebsd # Finally, download and build gcc to target FreeBSD mkdir gcc cd gcc curl https://ftp.gnu.org/gnu/gcc/gcc-$GCC/gcc-$GCC.tar.gz | tar xzf - cd gcc-$GCC ./contrib/download_prerequisites mkdir ../gcc-build cd ../gcc-build hide_output ../gcc-$GCC/configure --enable-languages=c,c++ --target=$ARCH-unknown-freebsd10 --disable-multilib --disable-nls --disable-libgomp --disable-libquadmath --disable-libssp --disable-libvtv --disable-libcilkrts --disable-libada --disable-libsanitizer --disable-libquadmath-support --disable-lto hide_output make -j10 hide_output make install cd ../.. rm -rf gcc "} {"_id":"doc-en-rust-7eb4064eb5f35b9e9996e162c41bd72e4ff71c09389c24d1437a5c67120c9db1","title":"","text":" #!/bin/bash # Copyright 2016-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. set -eux arch=$1 binutils_version=2.25.1 freebsd_version=10.3 triple=$arch-unknown-freebsd10 sysroot=/usr/local/$triple hide_output() { set +x local on_err=\" echo ERROR: An error was encountered with the build. cat /tmp/build.log exit 1 \" trap \"$on_err\" ERR bash -c \"while true; do sleep 30; echo $(date) - building ...; done\" & local ping_loop_pid=$! $@ &> /tmp/build.log trap - ERR kill $ping_loop_pid set -x } # First up, build binutils mkdir binutils cd binutils curl https://ftp.gnu.org/gnu/binutils/binutils-${binutils_version}.tar.bz2 | tar xjf - mkdir binutils-build cd binutils-build hide_output ../binutils-${binutils_version}/configure --target=\"$triple\" --with-sysroot=\"$sysroot\" hide_output make -j\"$(getconf _NPROCESSORS_ONLN)\" hide_output make install cd ../.. rm -rf binutils # Next, download the FreeBSD libraries and header files mkdir -p \"$sysroot\" case $arch in (x86_64) freebsd_arch=amd64 ;; (i686) freebsd_arch=i386 ;; esac files_to_extract=( \"./usr/include\" \"./usr/lib/*crt*.o\" ) # Try to unpack only the libraries the build needs, to save space. for lib in c cxxrt gcc_s m thr util; do files_to_extract=(\"${files_to_extract[@]}\" \"./lib/lib${lib}.*\" \"./usr/lib/lib${lib}.*\") done for lib in c++ c_nonshared compiler_rt execinfo gcc pthread rt ssp_nonshared; do files_to_extract=(\"${files_to_extract[@]}\" \"./usr/lib/lib${lib}.*\") done URL=https://download.freebsd.org/ftp/releases/${freebsd_arch}/${freebsd_version}-RELEASE/base.txz curl \"$URL\" | tar xJf - -C \"$sysroot\" --wildcards \"${files_to_extract[@]}\" # Fix up absolute symlinks from the system image. This can be removed # for FreeBSD 11. (If there's an easy way to make them relative # symlinks instead, feel free to change this.) set +x find \"$sysroot\" -type l | while read symlink_path; do symlink_target=$(readlink \"$symlink_path\") case $symlink_target in (/*) echo \"Fixing symlink ${symlink_path} -> ${sysroot}${symlink_target}\" >&2 ln -nfs \"${sysroot}${symlink_target}\" \"${symlink_path}\" ;; esac done set -x # Clang can do cross-builds out of the box, if we give it the right # flags. (The local binutils seem to work, but they set the ELF # header \"OS/ABI\" (EI_OSABI) field to SysV rather than FreeBSD, so # there might be other problems.) # # The --target option is last because the cross-build of LLVM uses # --target without an OS version (\"-freebsd\" vs. \"-freebsd10\"). This # makes Clang default to libstdc++ (which no longer exists), and also # controls other features, like GNU-style symbol table hashing and # anything predicated on the version number in the __FreeBSD__ # preprocessor macro. for tool in clang clang++; do tool_path=/usr/local/bin/${triple}-${tool} cat > \"$tool_path\" <"} {"_id":"doc-en-rust-abe1491706e2d09c344da08af90d26ccd45ba88c8c13e7f70128ee7f0c2f6b92","title":"","text":"let stdcppname = if target.contains(\"openbsd\") { // llvm-config on OpenBSD doesn't mention stdlib=libc++ \"c++\" } else if target.contains(\"freebsd\") { \"c++\" } else if target.contains(\"netbsd\") && llvm_static_stdcpp.is_some() { // NetBSD uses a separate library when relocation is required \"stdc++_pic\""} {"_id":"doc-en-rust-600abfd11f44b28bb2ffc038cd6865efa9d2e2d38b12e2572ed76586561eb90c","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unused)] #![feature(nll)] #[derive(Clone, Copy, Default)] struct S { a: u8, b: u8, } #[derive(Clone, Copy, Default)] struct Z { c: u8, d: u8, } union U { s: S, z: Z, } fn main() { unsafe { let mut u = U { s: Default::default() }; let mref = &mut u.s.a; *mref = 22; let nref = &u.z.c; //~^ ERROR cannot borrow `u.z.c` as immutable because it is also borrowed as mutable [E0502] println!(\"{} {}\", mref, nref) //~^ ERROR cannot borrow `u.s.a` as mutable because it is also borrowed as immutable [E0502] } } "} {"_id":"doc-en-rust-f836d4a94463aa8ae031f0f88ae407d5cc60ebcb9e101a29ca9c04e8a6f384a7","title":"","text":" error[E0502]: cannot borrow `u.z.c` as immutable because it is also borrowed as mutable --> $DIR/issue-45157.rs:37:20 | 34 | let mref = &mut u.s.a; | ---------- mutable borrow occurs here ... 37 | let nref = &u.z.c; | ^^^^^^ immutable borrow occurs here error[E0502]: cannot borrow `u.s.a` as mutable because it is also borrowed as immutable --> $DIR/issue-45157.rs:39:27 | 37 | let nref = &u.z.c; | ------ immutable borrow occurs here 38 | //~^ ERROR cannot borrow `u.z.c` as immutable because it is also borrowed as mutable [E0502] 39 | println!(\"{} {}\", mref, nref) | ^^^^ mutable borrow occurs here error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-87ac04833daa9327e95f76fac97f1e4487675e9db2da2f77d8b0c5ebaa7aff21","title":"","text":"[[package]] name = \"bitflags\" version = \"0.8.2\" source = \"registry+https://github.com/rust-lang/crates.io-index\" [[package]] name = \"bitflags\" version = \"0.9.1\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"doc-en-rust-dc8f317de13abe52e63288ce62a368e745646ac1f00b40845f83e1fc4f58338e","title":"","text":"[[package]] name = \"pulldown-cmark\" version = \"0.0.14\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"bitflags 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"pulldown-cmark\" version = \"0.0.15\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = ["} {"_id":"doc-en-rust-0d2b9be350dbea0ffe71875b2643413cbd75b05cf8bc0fd3b2b3fd859782d124","title":"","text":"\"env_logger 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)\", \"html-diff 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)\", \"log 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)\", \"pulldown-cmark 0.0.14 (registry+https://github.com/rust-lang/crates.io-index)\", \"pulldown-cmark 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]]"} {"_id":"doc-en-rust-64ee7aff51da1c035cec665b1ad6d61948954f7ab089de3bed35073bf0be7385","title":"","text":"\"checksum backtrace 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"99f2ce94e22b8e664d95c57fff45b98a966c2252b60691d0b7aeeccd88d70983\" \"checksum backtrace-sys 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)\" = \"c63ea141ef8fdb10409d0f5daf30ac51f84ef43bff66f16627773d2a292cd189\" \"checksum bitflags 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"aad18937a628ec6abcd26d1489012cc0e18c21798210f491af69ded9b881106d\" \"checksum bitflags 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"1370e9fc2a6ae53aea8b7a5110edbd08836ed87c88736dfabccade1c2b44bff4\" \"checksum bitflags 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"4efd02e230a02e18f92fc2735f44597385ed02ad8f831e7c1c1156ee5e1ab3a5\" \"checksum bitflags 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"f5cde24d1b2e2216a726368b2363a273739c91f4e3eb4e0dd12d672d396ad989\" \"checksum bufstream 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"f2f382711e76b9de6c744cc00d0497baba02fb00a787f088c879f01d09468e32\""} {"_id":"doc-en-rust-3efae0781d9bea1f58fd26275198b7fd5ede569569c5373638cad8895b714b48","title":"","text":"\"checksum precomputed-hash 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"cdf1fc3616b3ef726a847f2cd2388c646ef6a1f1ba4835c2629004da48184150\" \"checksum procedural-masquerade 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"c93cdc1fb30af9ddf3debc4afbdb0f35126cbd99daa229dd76cdd5349b41d989\" \"checksum psapi-sys 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"abcd5d1a07d360e29727f757a9decb3ce8bc6e0efa8969cfaad669a8317a2478\" \"checksum pulldown-cmark 0.0.14 (registry+https://github.com/rust-lang/crates.io-index)\" = \"d9ab1e588ef8efd702c7ed9d2bd774db5e6f4d878bb5a1a9f371828fbdff6973\" \"checksum pulldown-cmark 0.0.15 (registry+https://github.com/rust-lang/crates.io-index)\" = \"378e941dbd392c101f2cb88097fa4d7167bc421d4b88de3ff7dbee503bc3233b\" \"checksum pulldown-cmark 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"a656fdb8b6848f896df5e478a0eb9083681663e37dcb77dd16981ff65329fe8b\" \"checksum quick-error 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"eda5fe9b71976e62bc81b781206aaa076401769b2143379d3eb2118388babac4\""} {"_id":"doc-en-rust-a243f1fb1d7282a33e98f2b9ba8242021d6edd4790a1108ddea1a68e6a4f366d","title":"","text":"[dependencies] env_logger = { version = \"0.4\", default-features = false } log = \"0.3\" pulldown-cmark = { version = \"0.0.14\", default-features = false } pulldown-cmark = { version = \"0.1.0\", default-features = false } html-diff = \"0.0.4\" [build-dependencies]"} {"_id":"doc-en-rust-9bfbd62dd3e8c6443cbe0215b081fa95b7eb60020c3323f3286d56f2b3fcb23f","title":"","text":"match self.inner.next() { Some(Event::FootnoteReference(ref reference)) => { let entry = self.get_entry(&reference); let reference = format!(\"{0} let reference = format!(\"{0} \", (*entry).1); return Some(Event::Html(reference.into()));"} {"_id":"doc-en-rust-dfca98d48cf15ae7508025d30e3a140507ba05b3db6ed288a04794ba2d17a018","title":"","text":"v.sort_by(|a, b| a.1.cmp(&b.1)); let mut ret = String::from(\"

    \"); for (mut content, id) in v { write!(ret, \"
  1. \", id).unwrap(); write!(ret, \"
  2. \", id).unwrap(); let mut is_paragraph = false; if let Some(&Event::End(Tag::Paragraph)) = content.last() { content.pop();"} {"_id":"doc-en-rust-06d59849faf213f3043585eb7c5500a45bdae9610b669b7a58b0ad8b3845fc84","title":"","text":"} html::push_html(&mut ret, content.into_iter()); write!(ret, \" \", \" \", id).unwrap(); if is_paragraph { ret.push_str(\"

    \");"} {"_id":"doc-en-rust-6fb9f940d966b57cb742063c69d9a40c04806dd4416bdd27f9d73d16d5639ceb","title":"","text":"} // See note at the top of this module to understand why these are used: // // These casts are safe as OsStr is internally a wrapper around [u8] on all // platforms. // // Note that currently this relies on the special knowledge that libstd has; // these types are single-element structs but are not marked repr(transparent) // or repr(C) which would make these casts allowable outside std. fn os_str_as_u8_slice(s: &OsStr) -> &[u8] { unsafe { &*(s as *const OsStr as *const [u8]) } }"} {"_id":"doc-en-rust-460114894fb10599b720633abe9819bc613d1f42e13bd34517ad5a88d7f5faa7","title":"","text":" // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // 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. //"} {"_id":"doc-en-rust-d2b9a4fcf51ea22676a3f2c8bf063af47cb3cf4f7a58c04fd8000b8fc9201a5f","title":"","text":"// except according to those terms. extern mod std; use std::oldmap; use std::treemap::TreeMap; use core::hashmap::linear::*; use core::io::WriterUtil; struct Results { sequential_ints: float, random_ints: float, delete_ints: float, sequential_strings: float, random_strings: float, delete_strings: float } fn timed(result: &mut float, op: &fn()) { let start = std::time::precise_time_s(); op(); let end = std::time::precise_time_s(); *result = (end - start); use core::io; use std::time; use std::treemap::TreeMap; use core::hashmap::linear::{LinearMap, LinearSet}; use core::trie::TrieMap; fn timed(label: &str, f: &fn()) { let start = time::precise_time_s(); f(); let end = time::precise_time_s(); io::println(fmt!(\" %s: %f\", label, end - start)); } fn old_int_benchmarks(rng: @rand::Rng, num_keys: uint, results: &mut Results) { { let map = oldmap::HashMap(); do timed(&mut results.sequential_ints) { for uint::range(0, num_keys) |i| { map.insert(i, i+1); } fn ascending>(map: &mut M, n_keys: uint) { io::println(\" Ascending integers:\"); for uint::range(0, num_keys) |i| { fail_unless!(map.get(&i) == i+1); } do timed(\"insert\") { for uint::range(0, n_keys) |i| { map.insert(i, i + 1); } } { let map = oldmap::HashMap(); do timed(&mut results.random_ints) { for uint::range(0, num_keys) |i| { map.insert(rng.next() as uint, i); } do timed(\"search\") { for uint::range(0, n_keys) |i| { fail_unless!(map.find(&i).unwrap() == &(i + 1)); } } { let map = oldmap::HashMap(); for uint::range(0, num_keys) |i| { map.insert(i, i);; } do timed(&mut results.delete_ints) { for uint::range(0, num_keys) |i| { fail_unless!(map.remove(&i)); } do timed(\"remove\") { for uint::range(0, n_keys) |i| { fail_unless!(map.remove(&i)); } } } fn old_str_benchmarks(rng: @rand::Rng, num_keys: uint, results: &mut Results) { { let map = oldmap::HashMap(); do timed(&mut results.sequential_strings) { for uint::range(0, num_keys) |i| { let s = uint::to_str(i); map.insert(s, i); } fn descending>(map: &mut M, n_keys: uint) { io::println(\" Descending integers:\"); for uint::range(0, num_keys) |i| { let s = uint::to_str(i); fail_unless!(map.get(&s) == i); } do timed(\"insert\") { for uint::range(0, n_keys) |i| { map.insert(i, i + 1); } } { let map = oldmap::HashMap(); do timed(&mut results.random_strings) { for uint::range(0, num_keys) |i| { let s = uint::to_str(rng.next() as uint); map.insert(s, i); } do timed(\"search\") { for uint::range(0, n_keys) |i| { fail_unless!(map.find(&i).unwrap() == &(i + 1)); } } { let map = oldmap::HashMap(); for uint::range(0, num_keys) |i| { map.insert(uint::to_str(i), i); } do timed(&mut results.delete_strings) { for uint::range(0, num_keys) |i| { fail_unless!(map.remove(&uint::to_str(i))); } do timed(\"remove\") { for uint::range(0, n_keys) |i| { fail_unless!(map.remove(&i)); } } } fn linear_int_benchmarks(rng: @rand::Rng, num_keys: uint, results: &mut Results) { { let mut map = LinearMap::new(); do timed(&mut results.sequential_ints) { for uint::range(0, num_keys) |i| { map.insert(i, i+1); } fn vector>(map: &mut M, n_keys: uint, dist: &[uint]) { for uint::range(0, num_keys) |i| { fail_unless!(map.find(&i).unwrap() == &(i+1)); } do timed(\"insert\") { for uint::range(0, n_keys) |i| { map.insert(dist[i], i + 1); } } { let mut map = LinearMap::new(); do timed(&mut results.random_ints) { for uint::range(0, num_keys) |i| { map.insert(rng.next() as uint, i); } do timed(\"search\") { for uint::range(0, n_keys) |i| { fail_unless!(map.find(&dist[i]).unwrap() == &(i + 1)); } } { let mut map = LinearMap::new(); for uint::range(0, num_keys) |i| { map.insert(i, i);; } do timed(&mut results.delete_ints) { for uint::range(0, num_keys) |i| { fail_unless!(map.remove(&i)); } do timed(\"remove\") { for uint::range(0, n_keys) |i| { fail_unless!(map.remove(&dist[i])); } } } fn linear_str_benchmarks(rng: @rand::Rng, num_keys: uint, results: &mut Results) { { let mut map = LinearMap::new(); do timed(&mut results.sequential_strings) { for uint::range(0, num_keys) |i| { let s = uint::to_str(i); map.insert(s, i); } for uint::range(0, num_keys) |i| { let s = uint::to_str(i); fail_unless!(map.find(&s).unwrap() == &i); } fn main() { let args = os::args(); let n_keys = { if args.len() == 2 { uint::from_str(args[1]).get() } else { 1000000 } } }; { let mut map = LinearMap::new(); do timed(&mut results.random_strings) { for uint::range(0, num_keys) |i| { let s = uint::to_str(rng.next() as uint); map.insert(s, i); } } } let mut rand = vec::with_capacity(n_keys); { let mut map = LinearMap::new(); for uint::range(0, num_keys) |i| { map.insert(uint::to_str(i), i); } do timed(&mut results.delete_strings) { for uint::range(0, num_keys) |i| { fail_unless!(map.remove(&uint::to_str(i))); let rng = core::rand::seeded_rng([1, 1, 1, 1, 1, 1, 1]); let mut set = LinearSet::new(); while set.len() != n_keys { let next = rng.next() as uint; if set.insert(next) { rand.push(next); } } } } fn tree_int_benchmarks(rng: @rand::Rng, num_keys: uint, results: &mut Results) { { let mut map = TreeMap::new(); do timed(&mut results.sequential_ints) { for uint::range(0, num_keys) |i| { map.insert(i, i+1); } io::println(fmt!(\"%? keys\", n_keys)); for uint::range(0, num_keys) |i| { fail_unless!(map.find(&i).unwrap() == &(i+1)); } } } io::println(\"nTreeMap:\"); { let mut map = TreeMap::new(); do timed(&mut results.random_ints) { for uint::range(0, num_keys) |i| { map.insert(rng.next() as uint, i); } } let mut map = TreeMap::new::(); ascending(&mut map, n_keys); } { let mut map = TreeMap::new(); for uint::range(0, num_keys) |i| { map.insert(i, i);; } do timed(&mut results.delete_ints) { for uint::range(0, num_keys) |i| { fail_unless!(map.remove(&i)); } } let mut map = TreeMap::new::(); descending(&mut map, n_keys); } } fn tree_str_benchmarks(rng: @rand::Rng, num_keys: uint, results: &mut Results) { { let mut map = TreeMap::new(); do timed(&mut results.sequential_strings) { for uint::range(0, num_keys) |i| { let s = uint::to_str(i); map.insert(s, i); } for uint::range(0, num_keys) |i| { let s = uint::to_str(i); fail_unless!(map.find(&s).unwrap() == &i); } } io::println(\" Random integers:\"); let mut map = TreeMap::new::(); vector(&mut map, n_keys, rand); } io::println(\"nLinearMap:\"); { let mut map = TreeMap::new(); do timed(&mut results.random_strings) { for uint::range(0, num_keys) |i| { let s = uint::to_str(rng.next() as uint); map.insert(s, i); } } let mut map = LinearMap::new::(); ascending(&mut map, n_keys); } { let mut map = TreeMap::new(); for uint::range(0, num_keys) |i| { map.insert(uint::to_str(i), i); } do timed(&mut results.delete_strings) { for uint::range(0, num_keys) |i| { fail_unless!(map.remove(&uint::to_str(i))); } } let mut map = LinearMap::new::(); descending(&mut map, n_keys); } } fn write_header(header: &str) { io::stdout().write_str(header); io::stdout().write_str(\"n\"); } fn write_row(label: &str, value: float) { io::stdout().write_str(fmt!(\"%30s %f sn\", label, value)); } fn write_results(label: &str, results: &Results) { write_header(label); write_row(\"sequential_ints\", results.sequential_ints); write_row(\"random_ints\", results.random_ints); write_row(\"delete_ints\", results.delete_ints); write_row(\"sequential_strings\", results.sequential_strings); write_row(\"random_strings\", results.random_strings); write_row(\"delete_strings\", results.delete_strings); } fn empty_results() -> Results { Results { sequential_ints: 0f, random_ints: 0f, delete_ints: 0f, sequential_strings: 0f, random_strings: 0f, delete_strings: 0f, { io::println(\" Random integers:\"); let mut map = LinearMap::new::(); vector(&mut map, n_keys, rand); } } fn main() { let args = os::args(); let num_keys = { if args.len() == 2 { uint::from_str(args[1]).get() } else { 100 // woefully inadequate for any real measurement } }; let seed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; io::println(\"nTrieMap:\"); { let rng = rand::seeded_rng(seed); let mut results = empty_results(); old_int_benchmarks(rng, num_keys, &mut results); old_str_benchmarks(rng, num_keys, &mut results); write_results(\"std::oldmap::HashMap\", &results); let mut map = TrieMap::new::(); ascending(&mut map, n_keys); } { let rng = rand::seeded_rng(seed); let mut results = empty_results(); linear_int_benchmarks(rng, num_keys, &mut results); linear_str_benchmarks(rng, num_keys, &mut results); write_results(\"core::hashmap::linear::LinearMap\", &results); let mut map = TrieMap::new::(); descending(&mut map, n_keys); } { let rng = rand::seeded_rng(seed); let mut results = empty_results(); tree_int_benchmarks(rng, num_keys, &mut results); tree_str_benchmarks(rng, num_keys, &mut results); write_results(\"std::treemap::TreeMap\", &results); io::println(\" Random integers:\"); let mut map = TrieMap::new::(); vector(&mut map, n_keys, rand); } }"} {"_id":"doc-en-rust-b8175fa287fd65e467b4790edc5f04bb11396b43690cfce8beaa3b8046bcc696","title":"","text":"/// Simple usage: /// /// ``` /// #![feature(box_leak)] /// /// fn main() { /// let x = Box::new(41); /// let static_ref: &'static mut usize = Box::leak(x);"} {"_id":"doc-en-rust-8249ce9d6c380064acf32b954380f5137c30349f016c3fdc5b8e433305b88ee7","title":"","text":"/// Unsized data: /// /// ``` /// #![feature(box_leak)] /// /// fn main() { /// let x = vec![1, 2, 3].into_boxed_slice(); /// let static_ref = Box::leak(x);"} {"_id":"doc-en-rust-2d74c0eafb3963f8f8e1ee8446b8608ee2ec207c4dbb1dab916d500538b2bf32","title":"","text":"/// assert_eq!(*static_ref, [4, 2, 3]); /// } /// ``` #[unstable(feature = \"box_leak\", reason = \"needs an FCP to stabilize\", issue = \"46179\")] #[stable(feature = \"box_leak\", since = \"1.26.0\")] #[inline] pub fn leak<'a>(b: Box) -> &'a mut T where"} {"_id":"doc-en-rust-51214220e5b31595de0c37197d6723d6af4f122c1a6f8eba888a9fed6edc945c","title":"","text":"return; } let (_, line_hi, col_hi) = match ctx.byte_pos_to_line_and_col(span.hi) { Some(pos) => pos, None => { Hash::hash(&TAG_INVALID_SPAN, hasher); span.ctxt.hash_stable(ctx, hasher); return; } }; Hash::hash(&TAG_VALID_SPAN, hasher); // We truncate the stable ID hash and line and column numbers. The chances // of causing a collision this way should be minimal. Hash::hash(&(file_lo.name_hash as u64), hasher); let col = (col_lo.0 as u64) & 0xFF; let line = ((line_lo as u64) & 0xFF_FF_FF) << 8; let len = ((span.hi - span.lo).0 as u64) << 32; let line_col_len = col | line | len; Hash::hash(&line_col_len, hasher); // Hash both the length and the end location (line/column) of a span. If we // hash only the length, for example, then two otherwise equal spans with // different end locations will have the same hash. This can cause a problem // during incremental compilation wherein a previous result for a query that // depends on the end location of a span will be incorrectly reused when the // end location of the span it depends on has changed (see issue #74890). A // similar analysis applies if some query depends specifically on the length // of the span, but we only hash the end location. So hash both. let col_lo_trunc = (col_lo.0 as u64) & 0xFF; let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; let len = (span.hi - span.lo).0; Hash::hash(&col_line, hasher); Hash::hash(&len, hasher); span.ctxt.hash_stable(ctx, hasher); } }"} {"_id":"doc-en-rust-44765efb3f3d67d33668bb98e690f398fa812059fa50e353eef1c76dc7e155a4","title":"","text":" include ../../run-make-fulldeps/tools.mk # FIXME https://github.com/rust-lang/rust/issues/78911 # ignore-32bit wrong/no cross compiler and sometimes we pass wrong gcc args (-m64) # Tests that we don't ICE during incremental compilation after modifying a # function span such that its previous end line exceeds the number of lines # in the new file, but its start line/column and length remain the same. SRC=$(TMPDIR)/src INCR=$(TMPDIR)/incr all: mkdir $(SRC) mkdir $(INCR) cp a.rs $(SRC)/main.rs $(RUSTC) -C incremental=$(INCR) $(SRC)/main.rs cp b.rs $(SRC)/main.rs $(RUSTC) -C incremental=$(INCR) $(SRC)/main.rs "} {"_id":"doc-en-rust-2dd9dafe076fbf295bc70c7f860aa6e3ed726228d3f4d85520467c716799d72e","title":"","text":" fn main() { // foo must be used. foo(); } // For this test to operate correctly, foo's body must start on exactly the same // line and column and have the exact same length in bytes in a.rs and b.rs. In // a.rs, the body must end on a line number which does not exist in b.rs. // Basically, avoid modifying this file, including adding or removing whitespace! fn foo() { assert_eq!(1, 1); } "} {"_id":"doc-en-rust-ca230d5e18bba74e60b1cdfff1714f362c7735739b7fce812a2052404d595c44","title":"","text":" fn main() { // foo must be used. foo(); } // For this test to operate correctly, foo's body must start on exactly the same // line and column and have the exact same length in bytes in a.rs and b.rs. In // a.rs, the body must end on a line number which does not exist in b.rs. // Basically, avoid modifying this file, including adding or removing whitespace! fn foo() { assert_eq!(1, 1);//// } "} {"_id":"doc-en-rust-fa86e930fb387826ec73795c6b563d7f243349db35a973d5ee234aa8d9960cda","title":"","text":"include ../../run-make-fulldeps/tools.mk # FIXME https://github.com/rust-lang/rust/issues/78911 # ignore-32bit wrong/no cross compiler and sometimes we pass wrong gcc args (-m64) all: foo"} {"_id":"doc-en-rust-d26cc4e78fb8a3c07b6c09839d3455856b5189a06f5206dd567e636412a55aa1","title":"","text":"let (span, e) = self.interpolated_or_expr_span(e)?; (lo.to(span), ExprKind::Box(e)) } _ => return self.parse_dot_or_call_expr(Some(attrs)) token::Ident(..) if self.token.is_ident_named(\"not\") => { // `not` is just an ordinary identifier in Rust-the-language, // but as `rustc`-the-compiler, we can issue clever diagnostics // for confused users who really want to say `!` let token_cannot_continue_expr = |t: &token::Token| match *t { // These tokens can start an expression after `!`, but // can't continue an expression after an ident token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw), token::Literal(..) | token::Pound => true, token::Interpolated(ref nt) => match nt.0 { token::NtIdent(..) | token::NtExpr(..) | token::NtBlock(..) | token::NtPath(..) => true, _ => false, }, _ => false }; let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr); if cannot_continue_expr { self.bump(); // Emit the error ... let mut err = self.diagnostic() .struct_span_err(self.span, &format!(\"unexpected {} after identifier\", self.this_token_descr())); // span the `not` plus trailing whitespace to avoid // trailing whitespace after the `!` in our suggestion let to_replace = self.sess.codemap() .span_until_non_whitespace(lo.to(self.span)); err.span_suggestion_short(to_replace, \"use `!` to perform logical negation\", \"!\".to_owned()); err.emit(); // —and recover! (just as if we were in the block // for the `token::Not` arm) let e = self.parse_prefix_expr(None); let (span, e) = self.interpolated_or_expr_span(e)?; (lo.to(span), self.mk_unary(UnOp::Not, e)) } else { return self.parse_dot_or_call_expr(Some(attrs)); } } _ => { return self.parse_dot_or_call_expr(Some(attrs)); } }; return Ok(self.mk_expr(lo.to(hi), ex, attrs)); }"} {"_id":"doc-en-rust-9624e351cf4bad0520ea726b7c62ecbe9bd282479f3cd7913a1c02a042f1910f","title":"","text":"// 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)) { // 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 return Err(e); } let mut stmt_span = stmt.span; // expand the span to include the semicolon, if it exists if self.eat(&token::Semi) {"} {"_id":"doc-en-rust-7afa98cf0c3fc68fbc297f2ddd7842c43f00a33bcc0b8688c2ab41f17953f0fe","title":"","text":"} } fn ident_can_begin_expr(ident: ast::Ident, is_raw: bool) -> bool { pub(crate) fn ident_can_begin_expr(ident: ast::Ident, is_raw: bool) -> bool { let ident_token: Token = Ident(ident, is_raw); !ident_token.is_reserved_ident() ||"} {"_id":"doc-en-rust-fa4c0741eadf067ab39d78425020e16d8ef5bb7d52ad34532a14b5eb5ebf9368","title":"","text":"self.lifetime().is_some() } /// Returns `true` if the token is a identifier whose name is the given /// string slice. pub fn is_ident_named(&self, name: &str) -> bool { match self.ident() { Some((ident, _)) => ident.name.as_str() == name, None => false } } /// Returns `true` if the token is a documentation comment. pub fn is_doc_comment(&self) -> bool { match *self {"} {"_id":"doc-en-rust-c1cf2c57629d64b5a14d8d63f5653bd0435a0a3d7741462ff686862e428fd799","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn gratitude() { let for_you = false; if not for_you { //~^ ERROR unexpected `for_you` after identifier println!(\"I couldn't\"); } } fn qualification() { let the_worst = true; while not the_worst { //~^ ERROR unexpected `the_worst` after identifier println!(\"still pretty bad\"); } } fn should_we() { let not = true; if not // lack of braces is [sic] println!(\"Then when?\"); //~^ ERROR expected `{`, found `; //~| ERROR unexpected `println` after identifier } fn sleepy() { let resource = not 2; //~^ ERROR unexpected `2` after identifier } fn main() { let be_smothered_out_before = true; let young_souls = not be_smothered_out_before; //~^ ERROR unexpected `be_smothered_out_before` after identifier } "} {"_id":"doc-en-rust-d4cabfe3953a9d01ee42fc62554ace4cd85c0233cfe9817e35891a3835786572","title":"","text":" error: unexpected `for_you` after identifier --> $DIR/issue-46836-identifier-not-instead-of-negation.rs:13:12 | LL | if not for_you { | ----^^^^^^^ | | | help: use `!` to perform logical negation error: unexpected `the_worst` after identifier --> $DIR/issue-46836-identifier-not-instead-of-negation.rs:21:15 | LL | while not the_worst { | ----^^^^^^^^^ | | | help: use `!` to perform logical negation error: unexpected `println` after identifier --> $DIR/issue-46836-identifier-not-instead-of-negation.rs:30:9 | LL | if not // lack of braces is [sic] | ----- help: use `!` to perform logical negation LL | println!(\"Then when?\"); | ^^^^^^^ error: expected `{`, found `;` --> $DIR/issue-46836-identifier-not-instead-of-negation.rs:30:31 | LL | if not // lack of braces is [sic] | -- this `if` statement has a condition, but no block LL | println!(\"Then when?\"); | ^ error: unexpected `2` after identifier --> $DIR/issue-46836-identifier-not-instead-of-negation.rs:36:24 | LL | let resource = not 2; | ----^ | | | help: use `!` to perform logical negation error: unexpected `be_smothered_out_before` after identifier --> $DIR/issue-46836-identifier-not-instead-of-negation.rs:42:27 | LL | let young_souls = not be_smothered_out_before; | ----^^^^^^^^^^^^^^^^^^^^^^^ | | | help: use `!` to perform logical negation error: aborting due to 6 previous errors "} {"_id":"doc-en-rust-b531e525b0c28830d790c19742bdd0d42b2f13dcf4e9b22363db7c00b2d9d683","title":"","text":"has_elf_tls: version >= (10, 7), abi_return_struct_as_int: true, emit_debug_gdb_scripts: false, // This environment variable is pretty magical but is intended for // producing deterministic builds. This was first discovered to be used // by the `ar` tool as a way to control whether or not mtime entries in // the archive headers were set to zero or not. It appears that // eventually the linker got updated to do the same thing and now reads // this environment variable too in recent versions. // // For some more info see the commentary on #47086 link_env: vec![(\"ZERO_AR_DATE\".to_string(), \"1\".to_string())], ..Default::default() } }"} {"_id":"doc-en-rust-8be9023bfece88e4bc01d760106669b6a8a6366c9170301de0c7ec5f26e508de","title":"","text":"# ignore-musl # ignore-windows # ignore-macos (rust-lang/rust#66568) # Objects are reproducible but their path is not. all: "} {"_id":"doc-en-rust-82e04b7a5a03d5180740161a60dacaa1cb036288f719ec2c57f0e9f5952973b0","title":"","text":"rm -rf $(TMPDIR) && mkdir $(TMPDIR) $(RUSTC) reproducible-build-aux.rs $(RUSTC) reproducible-build.rs --crate-type rlib --sysroot $(shell $(RUSTC) --print sysroot) --remap-path-prefix=$(shell $(RUSTC) --print sysroot)=/sysroot cp -r $(shell $(RUSTC) --print sysroot) $(TMPDIR)/sysroot cp -R $(shell $(RUSTC) --print sysroot) $(TMPDIR)/sysroot cp $(TMPDIR)/libreproducible_build.rlib $(TMPDIR)/libfoo.rlib $(RUSTC) reproducible-build.rs --crate-type rlib --sysroot $(TMPDIR)/sysroot --remap-path-prefix=$(TMPDIR)/sysroot=/sysroot cmp \"$(TMPDIR)/libreproducible_build.rlib\" \"$(TMPDIR)/libfoo.rlib\" || exit 1"} {"_id":"doc-en-rust-e1bac876801e44f8f11ade170aa42df1269990b4eed86124b80bfdc0a70eeee1","title":"","text":"// A tuple index may not have a suffix self.expect_no_suffix(sp, \"tuple index\", suf); let dot_span = self.prev_span; hi = self.span; let idx_span = self.span; self.bump(); let invalid_msg = \"invalid tuple or struct index\";"} {"_id":"doc-en-rust-081ea6a2bd57e3b98e77a3c39181b981b1e25f22fa48473718c6fd3de07d75bc","title":"","text":"n.to_string()); err.emit(); } let id = respan(dot_span.to(hi), n); let field = self.mk_tup_field(e, id); e = self.mk_expr(lo.to(hi), field, ThinVec::new()); let field = self.mk_tup_field(e, respan(idx_span, n)); e = self.mk_expr(lo.to(idx_span), field, ThinVec::new()); } None => { let prev_span = self.prev_span;"} {"_id":"doc-en-rust-5220983bc183be2aa1cf1b5245052153651e550fc14c338fb92f401c6054f982","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-pretty pretty-printing is unhygienic #![feature(decl_macro)] #![allow(unused)] mod foo { pub macro m($s:tt, $i:tt) { $s.$i } } mod bar { struct S(i32); fn f() { let s = S(0); ::foo::m!(s, 0); } } fn main() {} "} {"_id":"doc-en-rust-a515099f01efd599dbbe5e02f074cee54a764cdc328d3229606764c9410af7ca","title":"","text":"use rustc::mir::{BasicBlock, Location, Mir}; use rustc::mir::Local; use rustc::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc::traits; use rustc::infer::InferOk; use rustc::util::common::ErrorReported; use borrow_check::nll::type_check::AtLocation; use rustc_data_structures::fx::FxHashSet; use syntax::codemap::DUMMY_SP; use util::liveness::LivenessResults;"} {"_id":"doc-en-rust-d70f31622a4edde7bd5fbae2707d3681a548577f692b857dbbe4dfa87f91e35b","title":"","text":"location ); let tcx = self.cx.infcx.tcx; let mut types = vec![(dropped_ty, 0)]; let mut known = FxHashSet(); while let Some((ty, depth)) = types.pop() { let span = DUMMY_SP; // FIXME let result = match tcx.dtorck_constraint_for_ty(span, dropped_ty, depth, ty) { Ok(result) => result, Err(ErrorReported) => { continue; } }; let ty::DtorckConstraint { outlives, dtorck_types, } = result; // All things in the `outlives` array may be touched by // the destructor and must be live at this point. for outlive in outlives { let cause = Cause::DropVar(dropped_local, location); self.push_type_live_constraint(outlive, location, cause); } // If we end visiting the same type twice (usually due to a cycle involving // associated types), we need to ensure that its region types match up with the type // we added to the 'known' map the first time around. For this reason, we need // our infcx to hold onto its calculated region constraints after each call // to dtorck_constraint_for_ty. Otherwise, normalizing the corresponding associated // type will end up instantiating the type with a new set of inference variables // Since this new type will never be in 'known', we end up looping forever. // // For this reason, we avoid calling TypeChecker.normalize, instead doing all normalization // ourselves in one large 'fully_perform_op' callback. let (type_constraints, kind_constraints) = self.cx.fully_perform_op(location.at_self(), |cx| { let tcx = cx.infcx.tcx; let mut selcx = traits::SelectionContext::new(cx.infcx); let cause = cx.misc(cx.last_span); let mut types = vec![(dropped_ty, 0)]; let mut final_obligations = Vec::new(); let mut type_constraints = Vec::new(); let mut kind_constraints = Vec::new(); // However, there may also be some types that // `dtorck_constraint_for_ty` could not resolve (e.g., // associated types and parameters). We need to normalize // associated types here and possibly recursively process. for ty in dtorck_types { let ty = self.cx.normalize(&ty, location); let ty = self.cx.infcx.resolve_type_and_region_vars_if_possible(&ty); match ty.sty { ty::TyParam(..) | ty::TyProjection(..) | ty::TyAnon(..) => { let cause = Cause::DropVar(dropped_local, location); self.push_type_live_constraint(ty, location, cause); let mut known = FxHashSet(); while let Some((ty, depth)) = types.pop() { let span = DUMMY_SP; // FIXME let result = match tcx.dtorck_constraint_for_ty(span, dropped_ty, depth, ty) { Ok(result) => result, Err(ErrorReported) => { continue; } }; let ty::DtorckConstraint { outlives, dtorck_types, } = result; // All things in the `outlives` array may be touched by // the destructor and must be live at this point. for outlive in outlives { let cause = Cause::DropVar(dropped_local, location); kind_constraints.push((outlive, location, cause)); } _ => if known.insert(ty) { types.push((ty, depth + 1)); }, // However, there may also be some types that // `dtorck_constraint_for_ty` could not resolve (e.g., // associated types and parameters). We need to normalize // associated types here and possibly recursively process. for ty in dtorck_types { let traits::Normalized { value: ty, obligations } = traits::normalize(&mut selcx, cx.param_env, cause.clone(), &ty); final_obligations.extend(obligations); let ty = cx.infcx.resolve_type_and_region_vars_if_possible(&ty); match ty.sty { ty::TyParam(..) | ty::TyProjection(..) | ty::TyAnon(..) => { let cause = Cause::DropVar(dropped_local, location); type_constraints.push((ty, location, cause)); } _ => if known.insert(ty) { types.push((ty, depth + 1)); }, } } } Ok(InferOk { value: (type_constraints, kind_constraints), obligations: final_obligations }) }).unwrap(); for (ty, location, cause) in type_constraints { self.push_type_live_constraint(ty, location, cause); } for (kind, location, cause) in kind_constraints { self.push_type_live_constraint(kind, location, cause); } } }"} {"_id":"doc-en-rust-9334535e2f7df9a81d012b03120511124fb3646a69d18f6806248531d859a1b6","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(nll)] pub struct DescriptorSet<'a> { pub slots: Vec> } pub trait ResourcesTrait<'r>: Sized { type DescriptorSet: 'r; } pub struct Resources; impl<'a> ResourcesTrait<'a> for Resources { type DescriptorSet = DescriptorSet<'a>; } pub enum AttachInfo<'a, R: ResourcesTrait<'a>> { NextDescriptorSet(Box) } fn main() { let _x = DescriptorSet {slots: Vec::new()}; } "} {"_id":"doc-en-rust-897dbf9fde51f1b79b6e33bbd8fd3b603307f4336792325c8ac1f708fa445add","title":"","text":"// Put the lint store levels and passes back in the session. cx.lint_sess.restore(&sess.lint_store); // Emit all buffered lints from early on in the session now that we've // calculated the lint levels for all AST nodes. for (_id, lints) in cx.buffered.map { for early_lint in lints { span_bug!(early_lint.span, \"failed to process buffered lint here\"); // All of the buffered lints should have been emitted at this point. // If not, that means that we somehow buffered a lint for a node id // that was not lint-checked (perhaps it doesn't exist?). This is a bug. // // Rustdoc runs everybody-loops before the early lints and removes // function bodies, so it's totally possible for linted // node ids to not exist (e.g. macros defined within functions for the // unused_macro lint) anymore. So we only run this check // when we're not in rustdoc mode. (see issue #47639) if !sess.opts.actually_rustdoc { for (_id, lints) in cx.buffered.map { for early_lint in lints { span_bug!(early_lint.span, \"failed to process buffered lint here\"); } } } }"} {"_id":"doc-en-rust-f2d6ad73cd35021d5acd920c2cfc404783b0e3a4d97afa1ea87a7c5bacf731d1","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This should not ICE pub fn test() { macro_rules! foo { () => () } } "} {"_id":"doc-en-rust-0b90683f7be94eb7ed44bc993377633f678d7303fc0b66d0b55e1e6759cd023c","title":"","text":"let task = get_task_id(); // Expect the weak task service to be alive assert service.try_send(RegisterWeakTask(task, shutdown_chan)); unsafe { rust_inc_kernel_live_count(); } unsafe { rust_dec_kernel_live_count(); } do fn&() { let shutdown_port = swap_unwrap(&mut *shutdown_port); f(shutdown_port) }.finally || { unsafe { rust_dec_kernel_live_count(); } unsafe { rust_inc_kernel_live_count(); } // Service my have already exited service.send(UnregisterWeakTask(task)); }"} {"_id":"doc-en-rust-9fea85231ddd20a247ef2af9b8985073e5d7c24d60a875b948c4cb4a7ad6ac54","title":"","text":"let port = swap_unwrap(&mut *port); // The weak task service is itself a weak task debug!(\"weakening the weak service task\"); unsafe { rust_inc_kernel_live_count(); } unsafe { rust_dec_kernel_live_count(); } run_weak_task_service(port); }.finally { debug!(\"unweakening the weak service task\"); unsafe { rust_dec_kernel_live_count(); } unsafe { rust_inc_kernel_live_count(); } } }"} {"_id":"doc-en-rust-7c79db9fd3ee1476cadff9b8510e982305de351b4d19e872415fec81b21b110d","title":"","text":" // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that multibyte characters don't crash the compiler fn main() { io::println(\"마이너스 사인이 없으면\"); } "} {"_id":"doc-en-rust-377db672e80a18128623bee7f065ea2881bb8c4e68a42a355d4ac07f2384ad52","title":"","text":"/// #[stable(feature = \"rust1\", since = \"1.0.0\")] pub trait BufRead: Read { /// Fills the internal buffer of this object, returning the buffer contents. /// Returns the contents of the internal buffer, filling it with more data /// from the inner reader if it is empty. /// /// This function is a lower-level call. It needs to be paired with the /// [`consume`] method to function properly. When calling this"} {"_id":"doc-en-rust-fab4224f3636af569ef97d0e377dd3003dc1dd0aad80fdc2b5fef9b728048ad2","title":"","text":"(accepted, type_alias_enum_variants, \"1.37.0\", Some(49683)), /// Allows macros to appear in the type position. (accepted, type_macros, \"1.13.0\", Some(27245)), /// Allows using type privacy lints (`private_interfaces`, `private_bounds`, `unnameable_types`). (accepted, type_privacy_lints, \"CURRENT_RUSTC_VERSION\", Some(48054)), /// Allows `const _: TYPE = VALUE`. (accepted, underscore_const_names, \"1.37.0\", Some(54912)), /// Allows `use path as _;` and `extern crate c as _;`."} {"_id":"doc-en-rust-614d50832407964311ce1f05e966fdc3a3374bd8c0f11ca7ade159a50c840459","title":"","text":"/// Allows creation of instances of a struct by moving fields that have /// not changed from prior instances of the same struct (RFC #2528) (unstable, type_changing_struct_update, \"1.58.0\", Some(86555)), /// Allows using type privacy lints (`private_interfaces`, `private_bounds`, `unnameable_types`). (unstable, type_privacy_lints, \"1.72.0\", Some(48054)), /// Enables rustc to generate code that instructs libstd to NOT ignore SIGPIPE. (unstable, unix_sigpipe, \"1.65.0\", Some(97889)), /// Allows unnamed fields of struct and union type"} {"_id":"doc-en-rust-a98e07f5387d93434f8c09939c8fe2a19cdcad49f4df4714754f4812652c3c95","title":"","text":"} declare_lint! { /// The `unreachable_pub` lint triggers for `pub` items not reachable from /// the crate root. /// The `unreachable_pub` lint triggers for `pub` items not reachable from other crates - that /// means neither directly accessible, nor reexported, nor leaked through things like return /// types. /// /// ### Example ///"} {"_id":"doc-en-rust-6b7e19e8df95ea3f7888e2585197ceda12b6ab37b2d3972a4a958e78a44b4652","title":"","text":"/// ### Example /// /// ```rust,compile_fail /// # #![feature(type_privacy_lints)] /// # #![allow(unused)] /// #![deny(unnameable_types)] /// mod m {"} {"_id":"doc-en-rust-7aca63a11e64e7403a8a4a0416ac59099e3e8db572be671d653232c237779a7c","title":"","text":"/// /// It is often expected that if you can obtain an object of type `T`, then /// you can name the type `T` as well, this lint attempts to enforce this rule. /// The recommended action is to either reexport the type properly to make it nameable, /// or document that users are not supposed to be able to name it for one reason or another. /// /// Besides types, this lint applies to traits because traits can also leak through signatures, /// and you may obtain objects of their `dyn Trait` or `impl Trait` types. pub UNNAMEABLE_TYPES, Allow, \"effective visibility of a type is larger than the area in which it can be named\", @feature_gate = sym::type_privacy_lints; } declare_lint! {"} {"_id":"doc-en-rust-9a6d172ec92a7576e7f7491660f6f48630324c1a2af07b31abb0370713f266b4","title":"","text":" //@ check-pass #![warn(unnameable_types)] //~ WARN unknown lint fn main() {} "} {"_id":"doc-en-rust-b5501c020466915ed4c489ec829b6bf93fc8ba0676ec8a393997ba5acf1176f5","title":"","text":" warning: unknown lint: `unnameable_types` --> $DIR/feature-gate-type_privacy_lints.rs:3:1 | LL | #![warn(unnameable_types)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the `unnameable_types` lint is unstable = note: see issue #48054 for more information = help: add `#![feature(type_privacy_lints)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date = note: `#[warn(unknown_lints)]` on by default warning: 1 warning emitted "} {"_id":"doc-en-rust-28ab6a27e70abd7e461a9b8f89d0ca0fdb1146d9adb0a1e2e34f8636a47b6fb4","title":"","text":" #![feature(type_privacy_lints)] #![deny(unnameable_types)] mod m {"} {"_id":"doc-en-rust-f1eefacfcec7a61309fb3145677c27ba15e32bc55f844e6da7ec5edfdbf2affc","title":"","text":"error: struct `PubStruct` is reachable but cannot be named --> $DIR/unnameable_types.rs:5:5 --> $DIR/unnameable_types.rs:4:5 | LL | pub struct PubStruct(pub i32); | ^^^^^^^^^^^^^^^^^^^^ reachable at visibility `pub`, but can only be named at visibility `pub(crate)` | note: the lint level is defined here --> $DIR/unnameable_types.rs:2:9 --> $DIR/unnameable_types.rs:1:9 | LL | #![deny(unnameable_types)] | ^^^^^^^^^^^^^^^^ error: enum `PubE` is reachable but cannot be named --> $DIR/unnameable_types.rs:7:5 --> $DIR/unnameable_types.rs:6:5 | LL | pub enum PubE { | ^^^^^^^^^^^^^ reachable at visibility `pub`, but can only be named at visibility `pub(crate)` error: trait `PubTr` is reachable but cannot be named --> $DIR/unnameable_types.rs:11:5 --> $DIR/unnameable_types.rs:10:5 | LL | pub trait PubTr { | ^^^^^^^^^^^^^^^ reachable at visibility `pub`, but can only be named at visibility `pub(crate)`"} {"_id":"doc-en-rust-a7ce838a7d130dc685d99b9059a299d91f8a580262377e39f18016badcf00305","title":"","text":"``` \", $Feature, \"let x: \", stringify!($SelfT), \" = 2; // or any other integer type assert_eq!(x.pow(4), 16);\", assert_eq!(x.pow(5), 32);\", $EndFeature, \" ```\"), #[stable(feature = \"rust1\", since = \"1.0.0\")]"} {"_id":"doc-en-rust-5cacde338521445d339ec3b94f430427e114ccce8e6a651c5b0d6a5cc3c6a68c","title":"","text":"Basic usage: ``` \", $Feature, \"assert_eq!(2\", stringify!($SelfT), \".pow(4), 16);\", $EndFeature, \" \", $Feature, \"assert_eq!(2\", stringify!($SelfT), \".pow(5), 32);\", $EndFeature, \" ```\"), #[stable(feature = \"rust1\", since = \"1.0.0\")] #[inline]"} {"_id":"doc-en-rust-f6e6ae8e17afafac5d9c10044c92753fce1f0ff74a599a2e7442ad4a9ed1b67e","title":"","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":"doc-en-rust-cf5e7ac7ec96d14e6e0c19a2169041e34ae8e7847a421f893faffa08161eb55c","title":"","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":"doc-en-rust-8ab9e0a27c1da409968a249131796085dc211fe1dd96aaa82ab6267f3719955b","title":"","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":"doc-en-rust-4f04670d5bf66f58d0b6ad0f1cd3d0720b9158978c20aab7875293b778b7f0d7","title":"","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":"doc-en-rust-e8c472858b8da5e909abb968dd72d8abd6ce3dfafdb55879a0e8a4190248ba80","title":"","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":"doc-en-rust-5e3e96aaa7e42a126e0f703fe5643d3293d219692e9df72ced5554211f0d9686","title":"","text":"#[unstable(feature = \"proc_macro\", issue = \"38356\")] impl iter::FromIterator for TokenStream { fn from_iter>(trees: I) -> Self { trees.into_iter().map(TokenStream::from).collect() } } #[unstable(feature = \"proc_macro\", issue = \"38356\")] impl iter::FromIterator for TokenStream { fn from_iter>(streams: I) -> Self { let mut builder = tokenstream::TokenStreamBuilder::new(); for tree in trees { builder.push(tree.to_internal()); for stream in streams { builder.push(stream.0); } TokenStream(builder.build()) }"} {"_id":"doc-en-rust-47939c0e492d3e1ea12fd762792dccddce09168a51075f06fa7512f488643a56","title":"","text":"assigned_map: FxHashMap, FxHashSet>, /// Locations which activate borrows. /// NOTE: A given location may activate more than one borrow in the future /// when more general two-phase borrow support is introduced, but for now we /// only need to store one borrow index activation_map: FxHashMap, activation_map: FxHashMap>, /// Every borrow has a region; this maps each such regions back to /// its borrow-indexes."} {"_id":"doc-en-rust-1a1713cf9c2e35b0f29c922a4b96dc08d9ac13e6a03221bbef88bae4bfcbb631","title":"","text":"idx_vec: IndexVec>, location_map: FxHashMap, assigned_map: FxHashMap, FxHashSet>, activation_map: FxHashMap, activation_map: FxHashMap>, region_map: FxHashMap, FxHashSet>, local_map: FxHashMap>, region_span_map: FxHashMap,"} {"_id":"doc-en-rust-724584acba2194cf29c111c6fda6849c8ade487f3cdb899c91dae3c76dd35617","title":"","text":"let idx = self.idx_vec.push(borrow); self.location_map.insert(location, idx); // This assert is a good sanity check until more general 2-phase borrow // support is introduced. See NOTE on the activation_map field for more assert!(!self.activation_map.contains_key(&activate_location), \"More than one activation introduced at the same location.\"); self.activation_map.insert(activate_location, idx); insert(&mut self.activation_map, &activate_location, idx); insert(&mut self.assigned_map, assigned_place, idx); insert(&mut self.region_map, ®ion, idx); if let Some(local) = root_local(borrowed_place) {"} {"_id":"doc-en-rust-b8098b4610d9b99304f3d159cc585ec983833f3d60d122c34882818f0f0e9990","title":"","text":"location: Location) { // Handle activations match self.activation_map.get(&location) { Some(&activated) => { debug!(\"activating borrow {:?}\", activated); sets.gen(&ReserveOrActivateIndex::active(activated)) Some(activations) => { for activated in activations { debug!(\"activating borrow {:?}\", activated); sets.gen(&ReserveOrActivateIndex::active(*activated)) } } None => {} }"} {"_id":"doc-en-rust-3c925445703941c9515139f54fe48cbf849517ec23b4b925dc8a9c057a66537b","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(nll)] struct Foo { } impl Foo { fn method(&mut self, foo: &mut Foo) { } } fn main() { let mut foo = Foo { }; foo.method(&mut foo); //~^ cannot borrow `foo` as mutable more than once at a time //~^^ cannot borrow `foo` as mutable more than once at a time } "} {"_id":"doc-en-rust-688a6e8f90fc820b3dd35ccdebdd2bf8162f1469a5eb81df8c1bdb7d8589e130","title":"","text":" error[E0499]: cannot borrow `foo` as mutable more than once at a time --> $DIR/two-phase-multi-mut.rs:23:16 | LL | foo.method(&mut foo); | -----------^^^^^^^^- | | | | | second mutable borrow occurs here | first mutable borrow occurs here | borrow later used here error[E0499]: cannot borrow `foo` as mutable more than once at a time --> $DIR/two-phase-multi-mut.rs:23:5 | LL | foo.method(&mut foo); | ^^^^^^^^^^^--------^ | | | | | first mutable borrow occurs here | second mutable borrow occurs here | borrow later used here error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0499`. "} {"_id":"doc-en-rust-2493e2649d6c53ea3dbfee92d86c7059b3a88975d5898198ec9ad03e3b7a2349","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // revisions: lxl nll //[lxl]compile-flags: -Z borrowck=mir -Z two-phase-borrows //[nll]compile-flags: -Z borrowck=mir -Z two-phase-borrows -Z nll // run-pass use std::io::Result; struct Foo {} pub trait FakeRead { fn read_to_end(&mut self, buf: &mut Vec) -> Result; } impl FakeRead for Foo { fn read_to_end(&mut self, buf: &mut Vec) -> Result { Ok(4) } } fn main() { let mut a = Foo {}; let mut v = Vec::new(); a.read_to_end(&mut v); } "} {"_id":"doc-en-rust-068930f6c07d30639ab6f1641e301734325d253bdd705d179a7da2bc914f1e45","title":"","text":"} } #[stable(feature = \"os_str_str_ref_eq\", since = \"1.28.0\")] impl<'a> PartialEq<&'a str> for OsString { fn eq(&self, other: &&'a str) -> bool { **self == **other } } #[stable(feature = \"os_str_str_ref_eq\", since = \"1.28.0\")] impl<'a> PartialEq for &'a str { fn eq(&self, other: &OsString) -> bool { **other == **self } } #[stable(feature = \"rust1\", since = \"1.0.0\")] impl Eq for OsString {}"} {"_id":"doc-en-rust-936ff5d089e753b4d7338e0e9d361efbbecf3ebe04c19b02e5d4e89d466546b2","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::ffi::OsString; fn main() { let os_str = OsString::from(\"Hello Rust!\"); assert_eq!(os_str, \"Hello Rust!\"); assert_eq!(\"Hello Rust!\", os_str); } "} {"_id":"doc-en-rust-376c528e2ce2d4d87a48e4fcb56a484e52ee096435590591eed46685c8624ddf","title":"","text":"impl Sealed for ops::RangeInclusive {} #[stable(feature = \"slice_get_slice\", since = \"1.28.0\")] impl Sealed for ops::RangeToInclusive {} #[stable(feature = \"slice_index_with_ops_bound_pair\", since = \"1.53.0\")] impl Sealed for (ops::Bound, ops::Bound) {} } /// A helper trait used for indexing operations."} {"_id":"doc-en-rust-7d551a989a48d205980ef1a00b53d1a395122770361b9cdaf8da34f5d67f6699","title":"","text":"ops::Range { start, end } } /// Convert pair of `ops::Bound`s into `ops::Range` without performing any bounds checking and (in debug) overflow checking fn into_range_unchecked( len: usize, (start, end): (ops::Bound, ops::Bound), ) -> ops::Range { use ops::Bound; let start = match start { Bound::Included(i) => i, Bound::Excluded(i) => i + 1, Bound::Unbounded => 0, }; let end = match end { Bound::Included(i) => i + 1, Bound::Excluded(i) => i, Bound::Unbounded => len, }; start..end } /// Convert pair of `ops::Bound`s into `ops::Range`. /// Returns `None` on overflowing indices. fn into_range( len: usize, (start, end): (ops::Bound, ops::Bound), ) -> Option> { use ops::Bound; let start = match start { Bound::Included(start) => start, Bound::Excluded(start) => start.checked_add(1)?, Bound::Unbounded => 0, }; let end = match end { Bound::Included(end) => end.checked_add(1)?, Bound::Excluded(end) => end, Bound::Unbounded => len, }; // Don't bother with checking `start < end` and `end <= len` // since these checks are handled by `Range` impls Some(start..end) } /// Convert pair of `ops::Bound`s into `ops::Range`. /// Panics on overflowing indices. fn into_slice_range( len: usize, (start, end): (ops::Bound, ops::Bound), ) -> ops::Range { use ops::Bound; let start = match start { Bound::Included(start) => start, Bound::Excluded(start) => { start.checked_add(1).unwrap_or_else(|| slice_start_index_overflow_fail()) } Bound::Unbounded => 0, }; let end = match end { Bound::Included(end) => { end.checked_add(1).unwrap_or_else(|| slice_end_index_overflow_fail()) } Bound::Excluded(end) => end, Bound::Unbounded => len, }; // Don't bother with checking `start < end` and `end <= len` // since these checks are handled by `Range` impls start..end } #[stable(feature = \"slice_index_with_ops_bound_pair\", since = \"1.53.0\")] unsafe impl SliceIndex<[T]> for (ops::Bound, ops::Bound) { type Output = [T]; #[inline] fn get(self, slice: &[T]) -> Option<&Self::Output> { into_range(slice.len(), self)?.get(slice) } #[inline] fn get_mut(self, slice: &mut [T]) -> Option<&mut Self::Output> { into_range(slice.len(), self)?.get_mut(slice) } #[inline] unsafe fn get_unchecked(self, slice: *const [T]) -> *const Self::Output { // SAFETY: the caller has to uphold the safety contract for `get_unchecked`. unsafe { into_range_unchecked(slice.len(), self).get_unchecked(slice) } } #[inline] unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut Self::Output { // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`. unsafe { into_range_unchecked(slice.len(), self).get_unchecked_mut(slice) } } #[inline] fn index(self, slice: &[T]) -> &Self::Output { into_slice_range(slice.len(), self).index(slice) } #[inline] fn index_mut(self, slice: &mut [T]) -> &mut Self::Output { into_slice_range(slice.len(), self).index_mut(slice) } } "} {"_id":"doc-en-rust-7f9f4b9e13e7c735c92ea25306530f54e4053bee03214748288aeffbd72d21e6","title":"","text":"} )*) => {$( mod $case_name { #[allow(unused_imports)] use core::ops::Bound; #[test] fn pass() { let mut v = $data;"} {"_id":"doc-en-rust-0ff9bfc39d077bb52392091ef2f89eed99f1c3f569c6729929dfe7d67448879b","title":"","text":"bad: data[7..=6]; message: \"out of range\"; } in mod boundpair_len { data: [0, 1, 2, 3, 4, 5]; good: data[(Bound::Included(6), Bound::Unbounded)] == []; good: data[(Bound::Unbounded, Bound::Included(5))] == [0, 1, 2, 3, 4, 5]; good: data[(Bound::Unbounded, Bound::Excluded(6))] == [0, 1, 2, 3, 4, 5]; good: data[(Bound::Included(0), Bound::Included(5))] == [0, 1, 2, 3, 4, 5]; good: data[(Bound::Included(0), Bound::Excluded(6))] == [0, 1, 2, 3, 4, 5]; good: data[(Bound::Included(2), Bound::Excluded(4))] == [2, 3]; good: data[(Bound::Excluded(1), Bound::Included(4))] == [2, 3, 4]; good: data[(Bound::Excluded(5), Bound::Excluded(6))] == []; good: data[(Bound::Included(6), Bound::Excluded(6))] == []; good: data[(Bound::Excluded(5), Bound::Included(5))] == []; good: data[(Bound::Included(6), Bound::Included(5))] == []; bad: data[(Bound::Unbounded, Bound::Included(6))]; message: \"out of range\"; } } panic_cases! {"} {"_id":"doc-en-rust-f1cc330f4d190c15bda9ebdb10b5c2042f2454af1f91bfbede6c0234998c5f74","title":"","text":"bad: data[4..=2]; message: \"but ends at\"; } in mod boundpair_neg_width { data: [0, 1, 2, 3, 4, 5]; good: data[(Bound::Included(4), Bound::Excluded(4))] == []; bad: data[(Bound::Included(4), Bound::Excluded(3))]; message: \"but ends at\"; } } panic_cases! {"} {"_id":"doc-en-rust-5d558175e4ba1cb0425d5760098cecabc70304eeede42dd42714ff5201671339","title":"","text":"bad: data[..= usize::MAX]; message: \"maximum usize\"; } in mod boundpair_overflow_end { data: [0; 1]; bad: data[(Bound::Unbounded, Bound::Included(usize::MAX))]; message: \"maximum usize\"; } in mod boundpair_overflow_start { data: [0; 1]; bad: data[(Bound::Excluded(usize::MAX), Bound::Unbounded)]; message: \"maximum usize\"; } } // panic_cases! }"} {"_id":"doc-en-rust-fcfce7f65b02de96cc1532f1b1e9574dd8fed392252759318775e8d8164886a0","title":"","text":"//! which do not. use rustc_data_structures::bitvec::BitVector; use rustc_data_structures::control_flow_graph::dominators::Dominators; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; use rustc::mir::{self, Location, TerminatorKind}; use rustc::mir::visit::{Visitor, PlaceContext};"} {"_id":"doc-en-rust-02e5f62691a9d4c07ba873a0d74e011272bdaf28c296603ce51b764e1977830e","title":"","text":"use type_of::LayoutLlvmExt; use super::FunctionCx; pub fn memory_locals<'a, 'tcx>(fx: &FunctionCx<'a, 'tcx>) -> BitVector { pub fn non_ssa_locals<'a, 'tcx>(fx: &FunctionCx<'a, 'tcx>) -> BitVector { let mir = fx.mir; let mut analyzer = LocalAnalyzer::new(fx);"} {"_id":"doc-en-rust-21fd2ae3a8b7f55b78e548a4b17a3f408dbb7a8c099893d8a325aecd38e09a07","title":"","text":"// (e.g. structs) into an alloca unconditionally, just so // that we don't have to deal with having two pathways // (gep vs extractvalue etc). analyzer.mark_as_memory(mir::Local::new(index)); analyzer.not_ssa(mir::Local::new(index)); } } analyzer.memory_locals analyzer.non_ssa_locals } struct LocalAnalyzer<'mir, 'a: 'mir, 'tcx: 'a> { fx: &'mir FunctionCx<'a, 'tcx>, memory_locals: BitVector, seen_assigned: BitVector dominators: Dominators, non_ssa_locals: BitVector, // The location of the first visited direct assignment to each // local, or an invalid location (out of bounds `block` index). first_assignment: IndexVec } impl<'mir, 'a, 'tcx> LocalAnalyzer<'mir, 'a, 'tcx> { fn new(fx: &'mir FunctionCx<'a, 'tcx>) -> LocalAnalyzer<'mir, 'a, 'tcx> { let invalid_location = mir::BasicBlock::new(fx.mir.basic_blocks().len()).start_location(); let mut analyzer = LocalAnalyzer { fx, memory_locals: BitVector::new(fx.mir.local_decls.len()), seen_assigned: BitVector::new(fx.mir.local_decls.len()) dominators: fx.mir.dominators(), non_ssa_locals: BitVector::new(fx.mir.local_decls.len()), first_assignment: IndexVec::from_elem(invalid_location, &fx.mir.local_decls) }; // Arguments get assigned to by means of the function being called for idx in 0..fx.mir.arg_count { analyzer.seen_assigned.insert(idx + 1); for arg in fx.mir.args_iter() { analyzer.first_assignment[arg] = mir::START_BLOCK.start_location(); } analyzer } fn mark_as_memory(&mut self, local: mir::Local) { debug!(\"marking {:?} as memory\", local); self.memory_locals.insert(local.index()); fn first_assignment(&self, local: mir::Local) -> Option { let location = self.first_assignment[local]; if location.block.index() < self.fx.mir.basic_blocks().len() { Some(location) } else { None } } fn mark_assigned(&mut self, local: mir::Local) { if !self.seen_assigned.insert(local.index()) { self.mark_as_memory(local); fn not_ssa(&mut self, local: mir::Local) { debug!(\"marking {:?} as non-SSA\", local); self.non_ssa_locals.insert(local.index()); } fn assign(&mut self, local: mir::Local, location: Location) { if self.first_assignment(local).is_some() { self.not_ssa(local); } else { self.first_assignment[local] = location; } } }"} {"_id":"doc-en-rust-fd37b77010d9fae078b1c5f6c388f85f5f53889c8ff7eb67ce3019a3818d9ade","title":"","text":"debug!(\"visit_assign(block={:?}, place={:?}, rvalue={:?})\", block, place, rvalue); if let mir::Place::Local(index) = *place { self.mark_assigned(index); self.assign(index, location); if !self.fx.rvalue_creates_operand(rvalue) { self.mark_as_memory(index); self.not_ssa(index); } } else { self.visit_place(place, PlaceContext::Store, location);"} {"_id":"doc-en-rust-d192cc8bb2369d941821ea7e0062a0dbd1646f02290dd9e361d6b24ccafcba66","title":"","text":"if layout.is_llvm_immediate() || layout.is_llvm_scalar_pair() { // Recurse with the same context, instead of `Projection`, // potentially stopping at non-operand projections, // which would trigger `mark_as_memory` on locals. // which would trigger `not_ssa` on locals. self.visit_place(&proj.base, context, location); return; }"} {"_id":"doc-en-rust-6904f1290897186eb4fde172750a8aa3ab54f24f4629feea1f79ea1715c4453e","title":"","text":"} fn visit_local(&mut self, &index: &mir::Local, &local: &mir::Local, context: PlaceContext<'tcx>, _: Location) { location: Location) { match context { PlaceContext::Call => { self.mark_assigned(index); self.assign(local, location); } PlaceContext::StorageLive | PlaceContext::StorageDead | PlaceContext::Validate | PlaceContext::Validate => {} PlaceContext::Copy | PlaceContext::Move => {} PlaceContext::Move => { // Reads from uninitialized variables (e.g. in dead code, after // optimizations) require locals to be in (uninitialized) memory. // NB: there can be uninitialized reads of a local visited after // an assignment to that local, if they happen on disjoint paths. let ssa_read = match self.first_assignment(local) { Some(assignment_location) => { assignment_location.dominates(location, &self.dominators) } None => false }; if !ssa_read { self.not_ssa(local); } } PlaceContext::Inspect | PlaceContext::Store | PlaceContext::AsmOutput | PlaceContext::Borrow { .. } | PlaceContext::Projection(..) => { self.mark_as_memory(index); self.not_ssa(local); } PlaceContext::Drop => { let ty = mir::Place::Local(index).ty(self.fx.mir, self.fx.cx.tcx); let ty = mir::Place::Local(local).ty(self.fx.mir, self.fx.cx.tcx); let ty = self.fx.monomorphize(&ty.to_ty(self.fx.cx.tcx)); // Only need the place if we're actually dropping it. if self.fx.cx.type_needs_drop(ty) { self.mark_as_memory(index); self.not_ssa(local); } } }"} {"_id":"doc-en-rust-60b5fa2bfdb77d8d67a1b948d31c2c9dc477ab531bd33074b9a6c2164d71cfff","title":"","text":"}, }; let memory_locals = analyze::memory_locals(&fx); let memory_locals = analyze::non_ssa_locals(&fx); // Allocate variable and temp allocas fx.locals = {"} {"_id":"doc-en-rust-370b94bc5b44edae3b733a3c8ed8438123a981a213b848cbc52be4497314655a","title":"","text":"} #[test] fn connect_timeout_unroutable() { // this IP is unroutable, so connections should always time out, // provided the network is reachable to begin with. let addr = \"10.255.255.1:80\".parse().unwrap(); let e = TcpStream::connect_timeout(&addr, Duration::from_millis(250)).unwrap_err(); assert!(e.kind() == io::ErrorKind::TimedOut || e.kind() == io::ErrorKind::Other, \"bad error: {} {:?}\", e, e.kind()); } #[test] fn connect_timeout_unbound() { // bind and drop a socket to track down a \"probably unassigned\" port let socket = TcpListener::bind(\"127.0.0.1:0\").unwrap();"} {"_id":"doc-en-rust-404d6e78cf72132ed2f1e1b6234d4326bef6c8d83632640ebcca042ecd619e22","title":"","text":"touch \"$TOOLSTATE_FILE\" # Try to test all the tools and store the build/test success in the TOOLSTATE_FILE set +e python2.7 \"$X_PY\" test --no-fail-fast src/doc/book "} {"_id":"doc-en-rust-80adeffd8f7aea2e506dd9af7a37033dbede7940eb63883a53160c95e71230e4","title":"","text":"cat \"$TOOLSTATE_FILE\" echo # This function checks that if a tool's submodule changed, the tool's state must improve verify_status() { echo \"Verifying status of $1...\" if echo \"$CHANGED_FILES\" | grep -q \"^M[[:blank:]]$2$\"; then"} {"_id":"doc-en-rust-dc22cdea4e93d83e8022dd65f88645e01893f33b2129d0de9e9bb06b3a6516ce","title":"","text":"fi } # deduplicates the submodule check and the assertion that on beta some tools MUST be passing check_dispatch() { if [ \"$1\" = submodule_changed ]; then # ignore $2 (branch id) verify_status $3 $4 elif [ \"$2\" = beta ]; then echo \"Requiring test passing for $3...\" if grep -q '\"'\"$3\"'\":\"(test|build)-fail\"' \"$TOOLSTATE_FILE\"; then exit 4 fi fi } # list all tools here status_check() { check_dispatch $1 beta book src/doc/book 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 check_dispatch $1 beta rls src/tool/rls check_dispatch $1 beta rustfmt src/tool/rustfmt # these tools are not required for beta to successfully branch check_dispatch $1 nightly clippy-driver src/tool/clippy check_dispatch $1 nightly miri src/tool/miri } # If this PR is intended to update one of these tools, do not let the build pass # when they do not test-pass. verify_status book src/doc/book verify_status nomicon src/doc/nomicon verify_status reference src/doc/reference verify_status rust-by-example src/doc/rust-by-example verify_status rls src/tool/rls verify_status rustfmt src/tool/rustfmt verify_status clippy-driver src/tool/clippy verify_status miri src/tool/miri status_check \"submodule_changed\" if [ \"$RUST_RELEASE_CHANNEL\" = nightly -a -n \"${TOOLSTATE_REPO_ACCESS_TOKEN+is_set}\" ]; then . \"$(dirname $0)/repo.sh\""} {"_id":"doc-en-rust-c07a8d7c3780da87d21f3d68ce8d02ab9576f8692fa07bdc2c2cf13cc2b9d862","title":"","text":"exit 0 fi if grep -q fail \"$TOOLSTATE_FILE\"; then exit 4 fi # abort compilation if an important tool doesn't build # (this code is reachable if not on the nightly channel) status_check \"beta_required\" "} {"_id":"doc-en-rust-455d3c934cdcc095a8dae7b3162c33e8cb9a6a88b485d76e2c8943772edeb940","title":"","text":"// FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005 // Force cargo to output binaries with disambiguating hashes in the name cargo.env(\"__CARGO_DEFAULT_LIB_METADATA\", &self.config.channel); let metadata = if compiler.stage == 0 { // Treat stage0 like special channel, whether it's a normal prior- // release rustc or a local rebuild with the same version, so we // never mix these libraries by accident. \"bootstrap\" } else { &self.config.channel }; cargo.env(\"__CARGO_DEFAULT_LIB_METADATA\", &metadata); let stage; if compiler.stage == 0 && self.local_rebuild {"} {"_id":"doc-en-rust-2bef0edcdf7865127c0d209c39b604a30f1689341a38d38f4cbfc1ac522249a9","title":"","text":" Subproject commit 8b7f7e667268921c278af94ae30a61e87a22b22b Subproject commit 329923edec41d0ddbea7f30ab12fca0436d459ae "} {"_id":"doc-en-rust-5bddb5543d6f5ab8230be1cfadf1ad41d4d3bd205a6f7f8090a7f4a5ed8bc869","title":"","text":" #![feature(const_raw_ptr_to_usize_cast)] fn main() { [(); &(static |x| {}) as *const _ as usize]; //~^ ERROR: closures cannot be static //~| ERROR: type annotations needed [(); &(static || {}) as *const _ as usize]; //~^ ERROR: closures cannot be static //~| ERROR: evaluation of constant value failed } "} {"_id":"doc-en-rust-72554819f1e09f22a198a99bff5992474411083d7ca6fd279f1de1acee4146d5","title":"","text":" error[E0697]: closures cannot be static --> $DIR/issue-52432.rs:4:12 | LL | [(); &(static |x| {}) as *const _ as usize]; | ^^^^^^^^^^ error[E0697]: closures cannot be static --> $DIR/issue-52432.rs:7:12 | LL | [(); &(static || {}) as *const _ as usize]; | ^^^^^^^^^ error[E0282]: type annotations needed --> $DIR/issue-52432.rs:4:20 | LL | [(); &(static |x| {}) as *const _ as usize]; | ^ consider giving this closure parameter a type error[E0080]: evaluation of constant value failed --> $DIR/issue-52432.rs:7:10 | LL | [(); &(static || {}) as *const _ as usize]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ \"pointer-to-integer cast\" needs an rfc before being allowed inside constants error: aborting due to 4 previous errors Some errors have detailed explanations: E0080, E0282, E0697. For more information about an error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-724d6dc7cfbe8265036e53ed5f6630adf31768d81ecf2bbd8f5c263f4af2e870","title":"","text":" // check-pass #![allow(dead_code)] trait Structure: Sized where E: Encoding { type RefTarget: ?Sized; type FfiPtr; unsafe fn borrow_from_ffi_ptr<'a>(ptr: Self::FfiPtr) -> Option<&'a Self::RefTarget>; } enum Slice {} impl Structure for Slice where E: Encoding { type RefTarget = [E::Unit]; type FfiPtr = (*const E::FfiUnit, usize); unsafe fn borrow_from_ffi_ptr<'a>(_ptr: Self::FfiPtr) -> Option<&'a Self::RefTarget> { panic!() } } trait Encoding { type Unit: Unit; type FfiUnit; } trait Unit {} enum Utf16 {} impl Encoding for Utf16 { type Unit = Utf16Unit; type FfiUnit = u16; } struct Utf16Unit(pub u16); impl Unit for Utf16Unit {} type SUtf16Str = SeStr; struct SeStr where S: Structure, E: Encoding { _data: S::RefTarget, } impl SeStr where S: Structure, E: Encoding { pub unsafe fn from_ptr<'a>(_ptr: S::FfiPtr) -> Option<&'a Self> { panic!() } } fn main() { const TEXT_U16: &'static [u16] = &[]; let _ = unsafe { SUtf16Str::from_ptr((TEXT_U16.as_ptr(), TEXT_U16.len())).unwrap() }; } "} {"_id":"doc-en-rust-7a2023dc841bbdb6763ce545eb991f16eb5ab4a88d0cbaa4960c58233974444a","title":"","text":" // check-pass #![allow(dead_code)] trait Structure: Sized where E: Encoding { type RefTarget: ?Sized; type FfiPtr; unsafe fn borrow_from_ffi_ptr<'a>(ptr: Self::FfiPtr) -> Option<&'a Self::RefTarget>; } enum Slice {} impl Structure for Slice where E: Encoding { type RefTarget = [E::Unit]; type FfiPtr = (*const E::FfiUnit, usize); unsafe fn borrow_from_ffi_ptr<'a>(_ptr: Self::FfiPtr) -> Option<&'a Self::RefTarget> { panic!() } } trait Encoding { type Unit: Unit; type FfiUnit; } trait Unit {} enum Utf16 {} impl Encoding for Utf16 { type Unit = Utf16Unit; type FfiUnit = u16; } struct Utf16Unit(pub u16); impl Unit for Utf16Unit {} struct SUtf16Str { _data: >::RefTarget, } impl SUtf16Str { pub unsafe fn from_ptr<'a>(ptr: >::FfiPtr) -> Option<&'a Self> { std::mem::transmute::::Unit]>, _>( >::borrow_from_ffi_ptr(ptr)) } } fn main() { const TEXT_U16: &'static [u16] = &[]; let _ = unsafe { SUtf16Str::from_ptr((TEXT_U16.as_ptr(), TEXT_U16.len())).unwrap() }; } "} {"_id":"doc-en-rust-63cdceff39b03b3a624a307128146e4fc945f0bfda9e06d2581da336ccd434d2","title":"","text":" #![feature(type_alias_impl_trait)] type Closure = impl FnOnce(); //~ ERROR: type mismatch resolving fn c() -> Closure { || -> Closure { || () } } fn main() {} "} {"_id":"doc-en-rust-d03a2925b19751e5f2dabe6f0a8ffa721f0e21c364be453372e0a85437892d1e","title":"","text":" error[E0271]: type mismatch resolving `<[closure@$DIR/issue-63279.rs:6:5: 6:28] as std::ops::FnOnce<()>>::Output == ()` --> $DIR/issue-63279.rs:3:1 | LL | type Closure = impl FnOnce(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected opaque type, found () | = note: expected type `Closure` found type `()` = note: the return type of a function must have a statically known size error: aborting due to previous error For more information about this error, try `rustc --explain E0271`. "} {"_id":"doc-en-rust-d88079ddf8cdb4aa938bdd88198f72713c0215a618a851aa4e4ae5591d89e28a","title":"","text":" #![feature(fn_traits, unboxed_closures)] fn test FnOnce<(&'x str,)>>(_: F) {} struct Compose(F,G); impl FnOnce<(T,)> for Compose where F: FnOnce<(T,)>, G: FnOnce<(F::Output,)> { type Output = G::Output; extern \"rust-call\" fn call_once(self, (x,): (T,)) -> G::Output { (self.1)((self.0)(x)) } } struct Str<'a>(&'a str); fn mk_str<'a>(s: &'a str) -> Str<'a> { Str(s) } fn main() { let _: for<'a> fn(&'a str) -> Str<'a> = mk_str; // expected concrete lifetime, found bound lifetime parameter 'a let _: for<'a> fn(&'a str) -> Str<'a> = Str; //~^ ERROR: mismatched types test(|_: &str| {}); test(mk_str); // expected concrete lifetime, found bound lifetime parameter 'x test(Str); //~ ERROR: type mismatch in function arguments test(Compose(|_: &str| {}, |_| {})); test(Compose(mk_str, |_| {})); // internal compiler error: cannot relate bound region: // ReLateBound(DebruijnIndex { depth: 2 }, // BrNamed(DefId { krate: 0, node: DefIndex(6) => test::'x }, 'x(65))) //<= ReSkolemized(0, // BrNamed(DefId { krate: 0, node: DefIndex(6) => test::'x }, 'x(65))) test(Compose(Str, |_| {})); } "} {"_id":"doc-en-rust-624ef5eb0ef9044e70456adbae6f8e2f92deb4ba30e110f9235aaf91650252a9","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-30904.rs:20:45 | LL | let _: for<'a> fn(&'a str) -> Str<'a> = Str; | ^^^ expected concrete lifetime, found bound lifetime parameter 'a | = note: expected type `for<'a> fn(&'a str) -> Str<'a>` found type `fn(&str) -> Str<'_> {Str::<'_>}` error[E0631]: type mismatch in function arguments --> $DIR/issue-30904.rs:26:10 | LL | fn test FnOnce<(&'x str,)>>(_: F) {} | ---- -------------------------- required by this bound in `test` ... LL | struct Str<'a>(&'a str); | ------------------------ found signature of `fn(&str) -> _` ... LL | test(Str); | ^^^ expected signature of `for<'x> fn(&'x str) -> _` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-2e3ef301d645c708fb9e497f5291c1a7a2b690d238c59b06b5681e331c78616c","title":"","text":"use cmp; use io::{self, Initializer, SeekFrom, Error, ErrorKind}; /// A `Cursor` wraps another type and provides it with a /// A `Cursor` wraps an in-memory buffer and provides it with a /// [`Seek`] implementation. /// /// `Cursor`s are typically used with in-memory buffers to allow them to /// implement [`Read`] and/or [`Write`], allowing these buffers to be used /// anywhere you might use a reader or writer that does actual I/O. /// `Cursor`s are used with in-memory buffers, anything implementing /// `AsRef<[u8]>`, to allow them to implement [`Read`] and/or [`Write`], /// allowing these buffers to be used anywhere you might use a reader or writer /// that does actual I/O. /// /// The standard library implements some I/O traits on various types which /// are commonly used as a buffer, like `Cursor<`[`Vec`]`>` and"} {"_id":"doc-en-rust-3e97c2ca0309021232a95bfd62f7b80d1239e3582966b528f5ad890af6142c49","title":"","text":"} impl Cursor { /// Creates a new cursor wrapping the provided underlying I/O object. /// Creates a new cursor wrapping the provided underlying in-memory buffer. /// /// Cursor initial position is `0` even if underlying object (e. /// g. `Vec`) is not empty. So writing to cursor starts with /// overwriting `Vec` content, not with appending to it. /// Cursor initial position is `0` even if underlying buffer (e.g. `Vec`) /// is not empty. So writing to cursor starts with overwriting `Vec` /// content, not with appending to it. /// /// # Examples ///"} {"_id":"doc-en-rust-387b544c914de95389b319be1aeeb1b4522cfe26858749aa86ec2fba8dfe66c6","title":"","text":"err.span_label(arm_span, msg); } } hir::MatchSource::TryDesugar => { // Issue #51632 if let Ok(try_snippet) = self.tcx.sess.source_map().span_to_snippet(arm_span) { err.span_suggestion_with_applicability( arm_span, \"try wrapping with a success variant\", format!(\"Ok({})\", try_snippet), Applicability::MachineApplicable, ); } } hir::MatchSource::TryDesugar => {} _ => { let msg = \"match arm with an incompatible type\"; if self.tcx.sess.source_map().is_multiline(arm_span) {"} {"_id":"doc-en-rust-1e4985b5942246975c7be74a00b242e8c3492d4b3d8bdb2fd41296d89a828bf4","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-rustfix #![allow(dead_code)] fn missing_discourses() -> Result { Ok(1) } fn forbidden_narratives() -> Result { Ok(missing_discourses()?) //~^ ERROR try expression alternatives have incompatible types //~| HELP try wrapping with a success variant } fn main() {} "} {"_id":"doc-en-rust-1feaf58101a17b5147829d1ea1aad9e4f0c635e3a34ff7a32f221616708e1c27","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. // run-rustfix #![allow(dead_code)] fn missing_discourses() -> Result {"} {"_id":"doc-en-rust-652e2841c72ee5c9c0a667ffd834e6c8873dbfffe4bb99ef5eda7faea21772c8","title":"","text":"fn forbidden_narratives() -> Result { missing_discourses()? //~^ ERROR try expression alternatives have incompatible types //~| HELP try wrapping with a success variant } fn main() {}"} {"_id":"doc-en-rust-d1bc2b172cb70190c65a14b5dfa6b929349378348910929ad014f2a551242d21","title":"","text":"error[E0308]: try expression alternatives have incompatible types --> $DIR/issue-51632-try-desugar-incompatible-types.rs:20:5 --> $DIR/issue-51632-try-desugar-incompatible-types.rs:18:5 | LL | missing_discourses()? | ^^^^^^^^^^^^^^^^^^^^^ | | | expected enum `std::result::Result`, found isize | help: try wrapping with a success variant: `Ok(missing_discourses()?)` | ^^^^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found isize | = note: expected type `std::result::Result` found type `isize`"} {"_id":"doc-en-rust-4d1c7ea146258e2324587df58ac52377b3ad49cf3a83295da99bd1c4df56c533","title":"","text":")); } let needs_parens = match expr.kind { // parenthesize if needed (Issue #46756) hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true, // parenthesize borrows of range literals (Issue #54505) _ if is_range_literal(expr) => true, _ => false, }; if let Some((sugg, msg)) = self.can_use_as_ref(expr) { return Some(( sugg,"} {"_id":"doc-en-rust-d223e2ab36f653deb9912566cb5c7bb5c434bdf2454f2045948851d15c8bd99c","title":"","text":"} } let sugg = mutability.ref_prefix_str(); let (sugg, verbose) = if needs_parens { ( vec![ (sp.shrink_to_lo(), format!(\"{prefix}{sugg}(\")), (sp.shrink_to_hi(), \")\".to_string()), ], false, ) } else { (vec![(sp.shrink_to_lo(), format!(\"{prefix}{sugg}\"))], true) let make_sugg = |expr: &Expr<'_>, span: Span, sugg: &str| { let needs_parens = match expr.kind { // parenthesize if needed (Issue #46756) hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true, // parenthesize borrows of range literals (Issue #54505) _ if is_range_literal(expr) => true, _ => false, }; if needs_parens { ( vec![ (span.shrink_to_lo(), format!(\"{prefix}{sugg}(\")), (span.shrink_to_hi(), \")\".to_string()), ], false, ) } else { (vec![(span.shrink_to_lo(), format!(\"{prefix}{sugg}\"))], true) } }; // Suggest dereferencing the lhs for expressions such as `&T == T` if let Some(hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(_, lhs, ..), .. })) = self.tcx.hir().find_parent(expr.hir_id) && let &ty::Ref(..) = self.check_expr(lhs).kind() { let (sugg, verbose) = make_sugg(lhs, lhs.span, \"*\"); return Some(( sugg, \"consider dereferencing the borrow\".to_string(), Applicability::MachineApplicable, verbose, false, )); } let sugg = mutability.ref_prefix_str(); let (sugg, verbose) = make_sugg(expr, sp, sugg); return Some(( sugg, format!(\"consider {}borrowing here\", mutability.mutably_str()),"} {"_id":"doc-en-rust-f833f809f6018123a4cd82c7c611d42e06773fcf0db10038b0564cc2584b1c68","title":"","text":" // Issue #52544 // run-rustfix fn main() { let i: &i64 = &1; if *i < 0 {} //~^ ERROR mismatched types [E0308] } "} {"_id":"doc-en-rust-b18cab1014b16f40e1857dc1a95dfc6b2ff0bee5237140b898eeba8c352a17a4","title":"","text":" // Issue #52544 // run-rustfix fn main() { let i: &i64 = &1; if i < 0 {} //~^ ERROR mismatched types [E0308] } "} {"_id":"doc-en-rust-16fba7d278e6ed78dbcc7975d18153fceee45d28976373cfafcd43dfc24f53bb","title":"","text":" error[E0308]: mismatched types --> $DIR/binary-op-suggest-deref.rs:6:12 | LL | if i < 0 {} | ^ expected `&i64`, found integer | help: consider dereferencing the borrow | LL | if *i < 0 {} | + error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-89114cf93667acef9c5533306d97b6025a5c721cced0206ef06002e1ec04c08f","title":"","text":" Subproject commit 52a6a4d7087d14a35d44a11c39c77fa79d71378d Subproject commit d549d85b1735dc5066b2973f8549557a813bb9c8 "} {"_id":"doc-en-rust-22a5e40badb1b6003ca1c24e2ec339ee53d50ed6d40326eb9c5cd6964b9ae7f3","title":"","text":" Subproject commit 03684905101f0b7e49dfe530e54dc1aeac6ef0fb Subproject commit e19f07f5a6e5546ab4f6ea951e3c6b8627edeaa7 "} {"_id":"doc-en-rust-87641d3cfe5a484aa36a83a0fbf84b531b0529853af4fefdce2fe4982a28ca4b","title":"","text":"# If this file is modified, then llvm will be (optionally) 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. 2018-07-12 No newline at end of file 2018-08-02 "} {"_id":"doc-en-rust-0d1fbd9cf0143e1ef1401934c2ffd99bc8f0fb146bc57a1d4c2495b66fb7f7b1","title":"","text":" Subproject commit 8214ccf861d538671b0a1436dbf4538dc4a64d09 Subproject commit f76ea3ca16ed22dde8ef929db74a4b4df6f2f899 "} {"_id":"doc-en-rust-e68a094130bc34e776668d5a8e9fd57a5b9b3efa64770ae91d04a1207a7b529e","title":"","text":"len); } /// Returns a pair of slices which contain the contents of the buffer not used by the VecDeque. #[inline] unsafe fn unused_as_mut_slices<'a>(&'a mut self) -> (&'a mut [T], &'a mut [T]) { let head = self.head; let tail = self.tail; let buf = self.buffer_as_mut_slice(); if head != tail { // In buf, head..tail contains the VecDeque and tail..head is unused. // So calling `ring_slices` with tail and head swapped returns unused slices. RingSlices::ring_slices(buf, tail, head) } else { // Swapping doesn't help when head == tail. let (before, after) = buf.split_at_mut(head); (after, before) } } /// Copies a potentially wrapping block of memory len long from src to dest. /// (abs(dst - src) + len) must be no larger than cap() (There must be at /// most one continuous overlapping region between src and dest)."} {"_id":"doc-en-rust-e9c2a515680d38eccf153498a6362b560c8f878485fd11e0b992614eda839220","title":"","text":"#[inline] #[stable(feature = \"append\", since = \"1.4.0\")] pub fn append(&mut self, other: &mut Self) { // Copies all values from `src_slice` to the start of `dst_slice`. unsafe fn copy_whole_slice(src_slice: &[T], dst_slice: &mut [T]) { let len = src_slice.len(); ptr::copy_nonoverlapping(src_slice.as_ptr(), dst_slice[..len].as_mut_ptr(), len); } let src_total = other.len(); // Guarantees there is space in `self` for `other`. self.reserve(src_total); self.head = { let original_head = self.head; // The goal is to copy all values from `other` into `self`. To avoid any // mismatch, all valid values in `other` are retrieved... let (src_high, src_low) = other.as_slices(); // and unoccupied parts of self are retrieved. let (dst_high, dst_low) = unsafe { self.unused_as_mut_slices() }; // Then all that is needed is to copy all values from // src (src_high and src_low) to dst (dst_high and dst_low). // // other [o o o . . . . . o o o o] // [5 6 7] [1 2 3 4] // src_low src_high // // self [. . . . . . o o o o . .] // [3 4 5 6 7 .] [1 2] // dst_low dst_high // // Values are not copied one by one but as slices in `copy_whole_slice`. // What slices are used depends on various properties of src and dst. // There are 6 cases in total: // 1. `src` is contiguous and fits in dst_high // 2. `src` is contiguous and does not fit in dst_high // 3. `src` is discontiguous and fits in dst_high // 4. `src` is discontiguous and does not fit in dst_high // + src_high is smaller than dst_high // 5. `src` is discontiguous and does not fit in dst_high // + dst_high is smaller than src_high // 6. `src` is discontiguous and does not fit in dst_high // + dst_high is the same size as src_high let src_contiguous = src_low.is_empty(); let dst_high_fits_src = dst_high.len() >= src_total; match (src_contiguous, dst_high_fits_src) { (true, true) => { // 1. // other [. . . o o o . . . . . .] // [] [1 1 1] // // self [. o o o o o . . . . . .] // [.] [1 1 1 . . .] unsafe { copy_whole_slice(src_high, dst_high); } original_head + src_total } (true, false) => { // 2. // other [. . . o o o o o . . . .] // [] [1 1 2 2 2] // // self [. . . . . . . o o o . .] // [2 2 2 . . . .] [1 1] let (src_1, src_2) = src_high.split_at(dst_high.len()); unsafe { copy_whole_slice(src_1, dst_high); copy_whole_slice(src_2, dst_low); } src_total - dst_high.len() } (false, true) => { // 3. // other [o o . . . . . . . o o o] // [2 2] [1 1 1] // // self [. o o . . . . . . . . .] // [.] [1 1 1 2 2 . . . .] let (dst_1, dst_2) = dst_high.split_at_mut(src_high.len()); unsafe { copy_whole_slice(src_high, dst_1); copy_whole_slice(src_low, dst_2); } original_head + src_total } (false, false) => { if src_high.len() < dst_high.len() { // 4. // other [o o o . . . . . . o o o] // [2 3 3] [1 1 1] // // self [. . . . . . o o . . . .] // [3 3 . . . .] [1 1 1 2] let (dst_1, dst_2) = dst_high.split_at_mut(src_high.len()); let (src_2, src_3) = src_low.split_at(dst_2.len()); unsafe { copy_whole_slice(src_high, dst_1); copy_whole_slice(src_2, dst_2); copy_whole_slice(src_3, dst_low); } src_3.len() } else if src_high.len() > dst_high.len() { // 5. // other [o o o . . . . . o o o o] // [3 3 3] [1 1 2 2] // // self [. . . . . . o o o o . .] // [2 2 3 3 3 .] [1 1] let (src_1, src_2) = src_high.split_at(dst_high.len()); let (dst_2, dst_3) = dst_low.split_at_mut(src_2.len()); unsafe { copy_whole_slice(src_1, dst_high); copy_whole_slice(src_2, dst_2); copy_whole_slice(src_low, dst_3); } dst_2.len() + src_low.len() } else { // 6. // other [o o . . . . . . . o o o] // [2 2] [1 1 1] // // self [. . . . . . . o o . . .] // [2 2 . . . . .] [1 1 1] unsafe { copy_whole_slice(src_high, dst_high); copy_whole_slice(src_low, dst_low); } src_low.len() } } } }; // Some values now exist in both `other` and `self` but are made inaccessible in `other`. other.tail = other.head; // naive impl self.extend(other.drain(..)); } /// Retains only the elements specified by the predicate."} {"_id":"doc-en-rust-f88313dea544dd53a4c9091cda01919e5d1263ab4d069d31388e81f2a7781db2","title":"","text":"#[stable(feature = \"collection_debug\", since = \"1.17.0\")] impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (front, back) = RingSlices::ring_slices(self.ring, self.head, self.tail); f.debug_tuple(\"Iter\") .field(&self.ring) .field(&self.tail) .field(&self.head) .finish() .field(&front) .field(&back) .finish() } }"} {"_id":"doc-en-rust-e199f83e8dba418ef3afe133c9ed65feaa3a6954cbc147b820e44ce99f2b9a9a","title":"","text":"#[stable(feature = \"collection_debug\", since = \"1.17.0\")] impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let (front, back) = RingSlices::ring_slices(&*self.ring, self.head, self.tail); f.debug_tuple(\"IterMut\") .field(&self.ring) .field(&self.tail) .field(&self.head) .finish() .field(&front) .field(&back) .finish() } }"} {"_id":"doc-en-rust-4a6baeae60b91afd87168ee1eaab6840ef99d52bcda6ebd366029596843292c4","title":"","text":"} } #[test] fn issue_53529() { use boxed::Box; let mut dst = VecDeque::new(); dst.push_front(Box::new(1)); dst.push_front(Box::new(2)); assert_eq!(*dst.pop_back().unwrap(), 1); let mut src = VecDeque::new(); src.push_front(Box::new(2)); dst.append(&mut src); for a in dst { assert_eq!(*a, 2); } } }"} {"_id":"doc-en-rust-0efe230a644798eef370dbc02275a6e99f7202a5be7534a598554d569974cb19","title":"","text":" // ignore-tidy-linelength #![feature(type_alias_impl_trait)] use std::fmt::Debug; pub trait Foo { type Item: Debug; fn foo(_: T) -> Self::Item; } #[derive(Debug)] pub struct S(std::marker::PhantomData); pub struct S2; impl Foo for S2 { type Item = impl Debug; fn foo(_: T) -> Self::Item { //~^ Error type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias S::(Default::default()) } } fn main() { S2::foo(123); } "} {"_id":"doc-en-rust-72ebb4c626c708755b313d8eb04f08eec7f7990a031147348d076ea0fec374c1","title":"","text":" error: type parameter `T` is part of concrete type but not used in parameter list for the `impl Trait` type alias --> $DIR/issue-53598.rs:20:42 | LL | fn foo(_: T) -> Self::Item { | __________________________________________^ LL | | LL | | S::(Default::default()) LL | | } | |_____^ error: aborting due to previous error "} {"_id":"doc-en-rust-c2893578412453f47df0497bee972b249ab8d2d126a9d5a15679fe41d6b9c520","title":"","text":" // ignore-tidy-linelength #![feature(arbitrary_self_types)] #![feature(type_alias_impl_trait)] use std::ops::Deref; trait Foo { type Bar: Foo; fn foo(self: impl Deref) -> Self::Bar; } impl Foo for C { type Bar = impl Foo; fn foo(self: impl Deref) -> Self::Bar { //~^ Error type parameter `impl Deref` is part of concrete type but not used in parameter list for the `impl Trait` type alias self } } fn main() {} "} {"_id":"doc-en-rust-2613bd79cb21c5ea0b34928b1727da3b11fa011a355ebc3f3783a15fa91f3f03","title":"","text":" error: type parameter `impl Deref` is part of concrete type but not used in parameter list for the `impl Trait` type alias --> $DIR/issue-57700.rs:16:58 | LL | fn foo(self: impl Deref) -> Self::Bar { | __________________________________________________________^ LL | | LL | | self LL | | } | |_____^ error: aborting due to previous error "} {"_id":"doc-en-rust-fc5d2bec7de6aab3f522e7b8ab504f6af043503ea41ddc8e08e87498b517003d","title":"","text":" //compile-pass #![feature(nll)] fn main() { let _: &'static usize = &(loop {}, 1).1; } "} {"_id":"doc-en-rust-a15022094b672e1f66f79c04e7967d26c55045934ae92234f1c71cd58ffa3832","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // New test for #53818: modifying static memory at compile-time is not allowed. // The test should never succeed. #![feature(const_raw_ptr_deref)] #![feature(const_let)] use std::cell::UnsafeCell; struct Foo(UnsafeCell); unsafe impl Send for Foo {} unsafe impl Sync for Foo {} static FOO: Foo = Foo(UnsafeCell::new(42)); static BAR: () = unsafe { *FOO.0.get() = 5; //~^ ERROR calls in statics are limited to constant functions, tuple structs and tuple variants // This error is caused by a separate bug that the feature gate error is reported // even though the feature gate \"const_let\" is active. //~| statements in statics are unstable (see issue #48821) }; fn main() { println!(\"{}\", unsafe { *FOO.0.get() }); } "} {"_id":"doc-en-rust-0da99ce0d99e71614ad5a65ea0cfd75c45e36868244daaead5c5475ca42e1b5b","title":"","text":" error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants --> $DIR/mod-static-with-const-fn.rs:27:6 | LL | *FOO.0.get() = 5; | ^^^^^^^^^^^ error[E0658]: statements in statics are unstable (see issue #48821) --> $DIR/mod-static-with-const-fn.rs:27:5 | LL | *FOO.0.get() = 5; | ^^^^^^^^^^^^^^^^ | = help: add #![feature(const_let)] to the crate attributes to enable error: aborting due to 2 previous errors Some errors occurred: E0015, E0658. For more information about an error, try `rustc --explain E0015`. "} {"_id":"doc-en-rust-80e55fd209c223fb00aed2ff7ea3ec1d0a53c463c93b8182cb57d55f2841cf74","title":"","text":"let mut cargo = Command::new(&self.initial_cargo); let out_dir = self.stage_out(compiler, mode); // command specific path, we call clear_if_dirty with this let mut my_out = match cmd { \"build\" => self.cargo_out(compiler, mode, target), // This is the intended out directory for crate documentation. \"doc\" | \"rustdoc\" => self.crate_doc_out(target), _ => self.stage_out(compiler, mode), }; // This is for the original compiler, but if we're forced to use stage 1, then // std/test/rustc stamps won't exist in stage 2, so we need to get those from stage 1, since // we copy the libs forward. let cmp = self.compiler_for(compiler.stage, compiler.host, target); let libstd_stamp = match cmd { \"check\" | \"clippy\" | \"fix\" => check::libstd_stamp(self, cmp, target), _ => compile::libstd_stamp(self, cmp, target), }; let libtest_stamp = match cmd { \"check\" | \"clippy\" | \"fix\" => check::libtest_stamp(self, cmp, target), _ => compile::libtest_stamp(self, cmp, target), }; let librustc_stamp = match cmd { \"check\" | \"clippy\" | \"fix\" => check::librustc_stamp(self, cmp, target), _ => compile::librustc_stamp(self, cmp, target), }; // Codegen backends are not yet tracked by -Zbinary-dep-depinfo, // so we need to explicitly clear out if they've been updated. for backend in self.codegen_backends(compiler) { self.clear_if_dirty(&out_dir, &backend); } if cmd == \"doc\" || cmd == \"rustdoc\" { if mode == Mode::Rustc || mode == Mode::ToolRustc || mode == Mode::Codegen { let my_out = match mode { // This is the intended out directory for compiler documentation. my_out = self.compiler_doc_out(target); } Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target), _ => self.crate_doc_out(target), }; let rustdoc = self.rustdoc(compiler); self.clear_if_dirty(&my_out, &rustdoc); } else if cmd != \"test\" { match mode { Mode::Std => { self.clear_if_dirty(&my_out, &self.rustc(compiler)); for backend in self.codegen_backends(compiler) { self.clear_if_dirty(&my_out, &backend); } }, Mode::Test => { self.clear_if_dirty(&my_out, &libstd_stamp); }, Mode::Rustc => { self.clear_if_dirty(&my_out, &self.rustc(compiler)); self.clear_if_dirty(&my_out, &libstd_stamp); self.clear_if_dirty(&my_out, &libtest_stamp); }, Mode::Codegen => { self.clear_if_dirty(&my_out, &librustc_stamp); }, Mode::ToolBootstrap => { }, Mode::ToolStd => { self.clear_if_dirty(&my_out, &libstd_stamp); }, Mode::ToolTest => { self.clear_if_dirty(&my_out, &libstd_stamp); self.clear_if_dirty(&my_out, &libtest_stamp); }, Mode::ToolRustc => { self.clear_if_dirty(&my_out, &libstd_stamp); self.clear_if_dirty(&my_out, &libtest_stamp); self.clear_if_dirty(&my_out, &librustc_stamp); }, } } cargo"} {"_id":"doc-en-rust-9d639d84c2f0fe53329d4b551bedabea3c30bcb4f1a8908092c0c607b18583a7","title":"","text":"}, } // This tells Cargo (and in turn, rustc) to output more complete // dependency information. Most importantly for rustbuild, this // includes sysroot artifacts, like libstd, which means that we don't // need to track those in rustbuild (an error prone process!). This // feature is currently unstable as there may be some bugs and such, but // it represents a big improvement in rustbuild's reliability on // rebuilds, so we're using it here. // // For some additional context, see #63470 (the PR originally adding // this), as well as #63012 which is the tracking issue for this // feature on the rustc side. cargo.arg(\"-Zbinary-dep-depinfo\"); cargo.arg(\"-j\").arg(self.jobs().to_string()); // Remove make-related flags to ensure Cargo can correctly set things up cargo.env_remove(\"MAKEFLAGS\");"} {"_id":"doc-en-rust-f515d4963da911b191f7faae357370e1be6dc99e30fd6ccb2209db0947d434f6","title":"","text":"let libdir = builder.sysroot_libdir(compiler, target); let hostdir = builder.sysroot_libdir(compiler, compiler.host); add_to_sysroot(&builder, &libdir, &hostdir, &rustdoc_stamp(builder, compiler, target)); builder.cargo(compiler, Mode::ToolRustc, target, \"clean\"); } }"} {"_id":"doc-en-rust-432d9631a7ef91d129d2cfaff55f38dadb459167bf99bc7744fd5bc512bfc321","title":"","text":"use std::process::{Command, Stdio, exit}; use std::str; use build_helper::{output, mtime, t, up_to_date}; use build_helper::{output, t, up_to_date}; use filetime::FileTime; use serde::Deserialize; use serde_json;"} {"_id":"doc-en-rust-093ad82386bc6f2c9804225303004b7374d3bd3f54cc107e31b82a46c2e29d8e","title":"","text":"// for reason why the sanitizers are not built in stage0. copy_apple_sanitizer_dylibs(builder, &builder.native_dir(target), \"osx\", &libdir); } builder.cargo(target_compiler, Mode::ToolStd, target, \"clean\"); } }"} {"_id":"doc-en-rust-4f02897f85d8e9bfdaeae6766e030d8555e33e4613fcd3fb04fedf0d0990a802","title":"","text":"&builder.sysroot_libdir(target_compiler, compiler.host), &libtest_stamp(builder, compiler, target) ); builder.cargo(target_compiler, Mode::ToolTest, target, \"clean\"); } }"} {"_id":"doc-en-rust-d2343b61ee6096e2e13dd91893e26549fb3a997a5898079b8bbabeb6dce96bb6","title":"","text":"&builder.sysroot_libdir(target_compiler, compiler.host), &librustc_stamp(builder, compiler, target) ); builder.cargo(target_compiler, Mode::ToolRustc, target, \"clean\"); } }"} {"_id":"doc-en-rust-d645c75ba90a4081207db3103439b1bcb0c9033b5d6299a205f1ce0b23845741","title":"","text":"deps.push((path_to_add.into(), false)); } // Now we want to update the contents of the stamp file, if necessary. First // we read off the previous contents along with its mtime. If our new // contents (the list of files to copy) is different or if any dep's mtime // is newer then we rewrite the stamp file. deps.sort(); let stamp_contents = fs::read(stamp); let stamp_mtime = mtime(&stamp); let mut new_contents = Vec::new(); let mut max = None; let mut max_path = None; for (dep, proc_macro) in deps.iter() { let mtime = mtime(dep); if Some(mtime) > max { max = Some(mtime); max_path = Some(dep.clone()); } new_contents.extend(if *proc_macro { b\"h\" } else { b\"t\" }); new_contents.extend(dep.to_str().unwrap().as_bytes()); new_contents.extend(b\"0\"); } let max = max.unwrap(); let max_path = max_path.unwrap(); let contents_equal = stamp_contents .map(|contents| contents == new_contents) .unwrap_or_default(); if contents_equal && max <= stamp_mtime { builder.verbose(&format!(\"not updating {:?}; contents equal and {:?} <= {:?}\", stamp, max, stamp_mtime)); return deps.into_iter().map(|(d, _)| d).collect() } if max > stamp_mtime { builder.verbose(&format!(\"updating {:?} as {:?} changed\", stamp, max_path)); } else { builder.verbose(&format!(\"updating {:?} as deps changed\", stamp)); } t!(fs::write(&stamp, &new_contents)); deps.into_iter().map(|(d, _)| d).collect() }"} {"_id":"doc-en-rust-08b015ccef9e1d86e643ae2795da137a9a9befa893f54c699e36bc5bb405de7b","title":"","text":"fn copy_apple_sanitizer_dylibs(builder: &Builder, native_dir: &Path, platform: &str, into: &Path) { for &sanitizer in &[\"asan\", \"tsan\"] { let filename = format!(\"libclang_rt.{}_{}_dynamic.dylib\", sanitizer, platform); let filename = format!(\"lib__rustc__clang_rt.{}_{}_dynamic.dylib\", sanitizer, platform); let mut src_path = native_dir.join(sanitizer); src_path.push(\"build\"); src_path.push(\"lib\");"} {"_id":"doc-en-rust-fd60ee6a2d366165852597c5b576b1bf05706a5d2f6e9eace6b8d6e26d2bc370","title":"","text":"pub out_dir: PathBuf, } impl NativeLibBoilerplate { /// On OSX we don't want to ship the exact filename that compiler-rt builds. /// This conflicts with the system and ours is likely a wildly different /// version, so they can't be substituted. /// /// As a result, we rename it here but we need to also use /// `install_name_tool` on OSX to rename the commands listed inside of it to /// ensure it's linked against correctly. pub fn fixup_sanitizer_lib_name(&self, sanitizer_name: &str) { if env::var(\"TARGET\").unwrap() != \"x86_64-apple-darwin\" { return } let dir = self.out_dir.join(\"build/lib/darwin\"); let name = format!(\"clang_rt.{}_osx_dynamic\", sanitizer_name); let src = dir.join(&format!(\"lib{}.dylib\", name)); let new_name = format!(\"lib__rustc__{}.dylib\", name); let dst = dir.join(&new_name); println!(\"{} => {}\", src.display(), dst.display()); fs::rename(&src, &dst).unwrap(); let status = Command::new(\"install_name_tool\") .arg(\"-id\") .arg(format!(\"@rpath/{}\", new_name)) .arg(&dst) .status() .expect(\"failed to execute `install_name_tool`\"); assert!(status.success()); } } impl Drop for NativeLibBoilerplate { fn drop(&mut self) { if !thread::panicking() {"} {"_id":"doc-en-rust-fc2d1cc79a3e36439f96421a71dbb3eee1e368d3c04feedf30b8914249f22e80","title":"","text":"pub fn sanitizer_lib_boilerplate(sanitizer_name: &str) -> Result<(NativeLibBoilerplate, String), ()> { let (link_name, search_path, dynamic) = match &*env::var(\"TARGET\").unwrap() { let (link_name, search_path, apple) = match &*env::var(\"TARGET\").unwrap() { \"x86_64-unknown-linux-gnu\" => ( format!(\"clang_rt.{}-x86_64\", sanitizer_name), \"build/lib/linux\","} {"_id":"doc-en-rust-789f8f5a09448c1b0beef3310b69f75a5bdb297292e3300be506c2a6bea9a543","title":"","text":"), _ => return Err(()), }; let to_link = if dynamic { format!(\"dylib={}\", link_name) let to_link = if apple { format!(\"dylib=__rustc__{}\", link_name) } else { format!(\"static={}\", link_name) };"} {"_id":"doc-en-rust-e6320ba767747de6125367819649b8366dcef86ae9a1dca2fa225e3d7bb8861d","title":"","text":".out_dir(&native.out_dir) .build_target(&target) .build(); native.fixup_sanitizer_lib_name(\"asan\"); } println!(\"cargo:rerun-if-env-changed=LLVM_CONFIG\"); }"} {"_id":"doc-en-rust-3025cf2f433f59e58f399270a38a30acc5948098e7298f566809e886ae45ebae","title":"","text":".out_dir(&native.out_dir) .build_target(&target) .build(); native.fixup_sanitizer_lib_name(\"tsan\"); } println!(\"cargo:rerun-if-env-changed=LLVM_CONFIG\"); }"} {"_id":"doc-en-rust-e40906f5dccabed66d0773dbc8fa0338e6992883a4df3eee4a735fa15cc6b2cc","title":"","text":"pub trait Seek { /// Seek to an offset, in bytes, in a stream. /// /// A seek beyond the end of a stream is allowed, but implementation /// defined. /// A seek beyond the end of a stream is allowed, but behavior is defined /// by the implementation. /// /// If the seek operation completed successfully, /// this method returns the new position from the start of the stream."} {"_id":"doc-en-rust-55f50da60459e31616d2f7f05340470c69c41cbb12b9f7b3402f2754a3d84552","title":"","text":"} impl Target { /// Given a function ABI, turn \"System\" into the correct ABI for this target. /// Given a function ABI, turn it into the correct ABI for this target. pub fn adjust_abi(&self, abi: Abi) -> Abi { match abi { Abi::System => {"} {"_id":"doc-en-rust-b222d6c566648b1e54c6e450a4f4afcb5bae2271461646efde5a61659936a369","title":"","text":"Abi::C } }, // These ABI kinds are ignored on non-x86 Windows targets. // See https://docs.microsoft.com/en-us/cpp/cpp/argument-passing-and-naming-conventions // and the individual pages for __stdcall et al. Abi::Stdcall | Abi::Fastcall | Abi::Vectorcall | Abi::Thiscall => { if self.options.is_like_windows && self.arch != \"x86\" { Abi::C } else { abi } }, abi => abi } }"} {"_id":"doc-en-rust-197959355bcf33c8b60ebe2f3099b1938a53d26e02d0c691012f7da90ed350a6","title":"","text":"// option. This file may not be copied, modified, or distributed // except according to those terms. // ignore-arm // ignore-aarch64 // Test that `extern \"stdcall\"` is properly translated. // only-x86 // compile-flags: -C no-prepopulate-passes"} {"_id":"doc-en-rust-8b1f2d4236ca072a93cbaa3173add51d3ff9c1eb63a50558816f72dd9f47df79","title":"","text":"let code_model = to_llvm_code_model(sess.code_model()); let features = attributes::llvm_target_features(sess).collect::>(); let mut features = llvm_util::handle_native_features(sess); features.extend(attributes::llvm_target_features(sess).map(|s| s.to_owned())); let mut singlethread = sess.target.singlethread; // On the wasm target once the `atomics` feature is enabled that means that"} {"_id":"doc-en-rust-2d8186d989e0fc71c8f1828c734b50e44572d3ee8c68d37d1133ce703d37ad4a","title":"","text":"PM: &PassManager<'_>, ); pub fn LLVMGetHostCPUFeatures() -> *mut c_char; pub fn LLVMDisposeMessage(message: *mut c_char); // Stuff that's in llvm-wrapper/ because it's not upstream yet. /// Opens an object file."} {"_id":"doc-en-rust-1617f731a33b766b2b5ab20b8680f87f8676b9242090dcf2b2bdea104cc19a8f","title":"","text":"use rustc_session::Session; use rustc_span::symbol::Symbol; use rustc_target::spec::{MergeFunctions, PanicStrategy}; use std::ffi::CString; use std::ffi::{CStr, CString}; use std::slice; use std::str;"} {"_id":"doc-en-rust-af6cbb9ad431269c6e7ecc2bf928452baa1120963af966e5be97a9cad2e77789","title":"","text":"handle_native(name) } pub fn handle_native_features(sess: &Session) -> Vec { match sess.opts.cg.target_cpu { Some(ref s) => { if s != \"native\" { return vec![]; } let features_string = unsafe { let ptr = llvm::LLVMGetHostCPUFeatures(); let features_string = if !ptr.is_null() { CStr::from_ptr(ptr) .to_str() .unwrap_or_else(|e| { bug!(\"LLVM returned a non-utf8 features string: {}\", e); }) .to_owned() } else { bug!(\"could not allocate host CPU features, LLVM returned a `null` string\"); }; llvm::LLVMDisposeMessage(ptr); features_string }; features_string.split(\",\").map(|s| s.to_owned()).collect() } None => vec![], } } pub fn tune_cpu(sess: &Session) -> Option<&str> { match sess.opts.debugging_opts.tune_cpu { Some(ref s) => Some(handle_native(&**s)),"} {"_id":"doc-en-rust-670edca9d3b7a26af25a3ef2d6fa5e345142ae0c33466d2bf02b42b0f2c7723d","title":"","text":"ty::RegionKind::ReLateBound(_, _), ) => {} (ty::RegionKind::ReLateBound(_, _), _) => { (ty::RegionKind::ReLateBound(_, _), _) | (_, ty::RegionKind::ReVar(_)) => { // One of these is true: // The new predicate has a HRTB in a spot where the old // predicate does not (if they both had a HRTB, the previous // match arm would have executed). // match arm would have executed). A HRBT is a 'stricter' // bound than anything else, so we want to keep the newer // predicate (with the HRBT) in place of the old predicate. // // The means we want to remove the older predicate from // user_computed_preds, since having both it and the new // OR // // The old predicate has a region variable where the new // predicate has some other kind of region. An region // variable isn't something we can actually display to a user, // so we choose ther new predicate (which doesn't have a region // varaible). // // In both cases, we want to remove the old predicate, // from user_computed_preds, and replace it with the new // one. Having both the old and the new // predicate in a ParamEnv would confuse SelectionContext // // We're currently in the predicate passed to 'retain', // so we return 'false' to remove the old predicate from // user_computed_preds return false; } (_, ty::RegionKind::ReLateBound(_, _)) => { // This is the opposite situation as the previous arm - the // old predicate has a HRTB lifetime in a place where the // new predicate does not. We want to leave the old (_, ty::RegionKind::ReLateBound(_, _)) | (ty::RegionKind::ReVar(_), _) => { // This is the opposite situation as the previous arm. // One of these is true: // // The old predicate has a HRTB lifetime in a place where the // new predicate does not. // // OR // // The new predicate has a region variable where the old // predicate has some other type of region. // // We want to leave the old // predicate in user_computed_preds, and skip adding // new_pred to user_computed_params. should_add_new = false } }, _ => {} } }"} {"_id":"doc-en-rust-36f21e0600476ef1ca4bc71bcf10a12c311718524b32d7973b4c0e3ebc53690e","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait ScopeHandle<'scope> {} // @has issue_54705/struct.ScopeFutureContents.html // @has - '//*[@id=\"synthetic-implementations-list\"]/*[@class=\"impl\"]//*/code' \"impl<'scope, S> // Send for ScopeFutureContents<'scope, S> where S: Sync\" // // @has - '//*[@id=\"synthetic-implementations-list\"]/*[@class=\"impl\"]//*/code' \"impl<'scope, S> // Sync for ScopeFutureContents<'scope, S> where S: Sync\" pub struct ScopeFutureContents<'scope, S> where S: ScopeHandle<'scope>, { dummy: &'scope S, this: Box>, } struct ScopeFuture<'scope, S> where S: ScopeHandle<'scope>, { contents: ScopeFutureContents<'scope, S>, } unsafe impl<'scope, S> Send for ScopeFuture<'scope, S> where S: ScopeHandle<'scope>, {} unsafe impl<'scope, S> Sync for ScopeFuture<'scope, S> where S: ScopeHandle<'scope>, {} "} {"_id":"doc-en-rust-b779fa5dbd909bb88dbfffd6c9bc396b7a06bfb84a805ac3fb42744794df8b82","title":"","text":" error[E0594]: cannot assign to immutable static item `S` --> $DIR/thread-local-mutation.rs:11:5 | LL | S = \"after\"; //~ ERROR cannot assign to immutable | ^^^^^^^^^^^ cannot assign error: aborting due to previous error For more information about this error, try `rustc --explain E0594`. "} {"_id":"doc-en-rust-d7d3d35c5f8df570724aee609f46e2c1feebd6b2c3672a7002747a1c00594f25","title":"","text":" // Regression test for #54901: immutable thread locals could be mutated. See: // https://github.com/rust-lang/rust/issues/29594#issuecomment-328177697 // https://github.com/rust-lang/rust/issues/54901 #![feature(thread_local)] #[thread_local] static S: &str = \"before\"; fn set_s() { S = \"after\"; //~ ERROR cannot assign to immutable } fn main() { println!(\"{}\", S); set_s(); println!(\"{}\", S); } "} {"_id":"doc-en-rust-d835b88c37b627e38319ac36c22855a98a05372accdefee9240062ccdc38f082","title":"","text":" error[E0594]: cannot assign to immutable thread-local static item --> $DIR/thread-local-mutation.rs:11:5 | LL | S = \"after\"; //~ ERROR cannot assign to immutable | ^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0594`. "} {"_id":"doc-en-rust-7da4a6c535bd013a1a34ebc3b8d9832e6a78c15cfd4fbad08f82a7b07373344d","title":"","text":"hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) | hir::ItemKind::Static(..) | hir::ItemKind::Existential(..) | hir::ItemKind::Const(..) => { intravisit::walk_item(self, &item); }"} {"_id":"doc-en-rust-4a09586829fae00306099e0efc5d6d77679dd97d44900b73f10e4696299da462","title":"","text":" // compile-pass #[deny(warnings)] enum Empty { } trait Bar {} impl Bar for () {} fn boo() -> impl Bar {} fn main() { boo(); } "} {"_id":"doc-en-rust-e25b25a2a722a43cc5453c9f1640fd09c608779f50321307998d4c615fcd5fe7","title":"","text":"fn build_external_function(cx: &DocContext, did: DefId) -> clean::Function { let sig = cx.tcx.fn_sig(did); let constness = if cx.tcx.is_const_fn(did) { let constness = if cx.tcx.is_min_const_fn(did) { hir::Constness::Const } else { hir::Constness::NotConst"} {"_id":"doc-en-rust-4ba56c5bdbb2816a2d4038fb40400b5aebd87b4a2fedfe506a560a74ebe9dd8e","title":"","text":"(self.generics.clean(cx), (&self.decl, self.body).clean(cx)) }); let did = cx.tcx.hir().local_def_id(self.id); let constness = if cx.tcx.is_min_const_fn(did) { hir::Constness::Const } else { hir::Constness::NotConst }; Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx),"} {"_id":"doc-en-rust-72dfd5ce98bda4b7042b0c07064728c6e95da46fd78500b70a3f2759ca75ee0e","title":"","text":"visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), def_id: cx.tcx.hir().local_def_id(self.id), def_id: did, inner: FunctionItem(Function { decl, generics, header: self.header, header: hir::FnHeader { constness, ..self.header }, }), } }"} {"_id":"doc-en-rust-0d5d2ab69064cdbd025c4c5d2270adaaa5ef7a590f858771f82c16b6062bd972","title":"","text":"ty::TraitContainer(_) => self.defaultness.has_value() }; if provided { let constness = if cx.tcx.is_const_fn(self.def_id) { let constness = if cx.tcx.is_min_const_fn(self.def_id) { hir::Constness::Const } else { hir::Constness::NotConst"} {"_id":"doc-en-rust-7f7d2422d27aa4cba089905e4d08ec078cd41ec42eea84fc5f0b05ad650b9143","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![crate_name = \"foo\"] #![unstable(feature = \"humans\", reason = \"who ever let humans program computers, we're apparently really bad at it\", issue = \"0\")] #![feature(rustc_const_unstable, const_fn, foo, foo2)] #![feature(min_const_unsafe_fn)] #![feature(staged_api)] // @has 'foo/fn.foo.html' '//pre' 'pub unsafe fn foo() -> u32' #[stable(feature = \"rust1\", since = \"1.0.0\")] #[rustc_const_unstable(feature=\"foo\")] pub const unsafe fn foo() -> u32 { 42 } // @has 'foo/fn.foo2.html' '//pre' 'pub fn foo2() -> u32' #[unstable(feature = \"humans\", issue=\"0\")] pub const fn foo2() -> u32 { 42 } // @has 'foo/fn.bar2.html' '//pre' 'pub const fn bar2() -> u32' #[stable(feature = \"rust1\", since = \"1.0.0\")] pub const fn bar2() -> u32 { 42 } // @has 'foo/fn.foo2_gated.html' '//pre' 'pub unsafe fn foo2_gated() -> u32' #[unstable(feature = \"foo2\", issue=\"0\")] pub const unsafe fn foo2_gated() -> u32 { 42 } // @has 'foo/fn.bar2_gated.html' '//pre' 'pub const unsafe fn bar2_gated() -> u32' #[stable(feature = \"rust1\", since = \"1.0.0\")] pub const unsafe fn bar2_gated() -> u32 { 42 } // @has 'foo/fn.bar_not_gated.html' '//pre' 'pub unsafe fn bar_not_gated() -> u32' pub const unsafe fn bar_not_gated() -> u32 { 42 } "} {"_id":"doc-en-rust-7072465d7d463c9fb446f655dc828770588add1aeb34cea5758f1cbeeee44458","title":"","text":") -> Option<(ty::ParamEnv<'c>, ty::ParamEnv<'c>)> { let tcx = infcx.tcx; let mut select = SelectionContext::new(&infcx); let mut select = SelectionContext::with_negative(&infcx, true); let mut already_visited = FxHashSet::default(); let mut predicates = VecDeque::new();"} {"_id":"doc-en-rust-ee5eebb676cdd9e34949a00c72b98755d71a3839f38e5210ce083388a1b88c36","title":"","text":"match &result { &Ok(Some(ref vtable)) => { // If we see an explicit negative impl (e.g. 'impl !Send for MyStruct'), // we immediately bail out, since it's impossible for us to continue. match vtable { Vtable::VtableImpl(VtableImplData { impl_def_id, .. }) => { // Blame tidy for the weird bracket placement if infcx.tcx.impl_polarity(*impl_def_id) == hir::ImplPolarity::Negative { debug!(\"evaluate_nested_obligations: Found explicit negative impl {:?}, bailing out\", impl_def_id); return None; } }, _ => {} } let obligations = vtable.clone().nested_obligations().into_iter(); if !self.evaluate_nested_obligations("} {"_id":"doc-en-rust-916a47e650f4e2ed15de7a42b4bbab9fa94ced01a1ad5a6ef42a3c8a2652e359","title":"","text":" // Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(optin_builtin_traits)] // @has issue_55321/struct.A.html // @has - '//*[@id=\"implementations-list\"]/*[@class=\"impl\"]//*/code' \"impl !Send for A\" // @has - '//*[@id=\"implementations-list\"]/*[@class=\"impl\"]//*/code' \"impl !Sync for A\" pub struct A(); impl !Send for A {} impl !Sync for A {} // @has issue_55321/struct.B.html // @has - '//*[@id=\"synthetic-implementations-list\"]/*[@class=\"impl\"]//*/code' \"impl !Send for // B\" // @has - '//*[@id=\"synthetic-implementations-list\"]/*[@class=\"impl\"]//*/code' \"impl !Sync for // B\" pub struct B(A, Box); "} {"_id":"doc-en-rust-db872e73ae74d7f8e503dcee328f19c008b8218ea81eb5509fb1f5ef7d80777b","title":"","text":"let mir_node_id = tcx.hir.as_local_node_id(mir_def_id).expect(\"non-local mir\"); let (return_span, mir_description) = if let hir::ExprKind::Closure(_, _, _, span, gen_move) = tcx.hir.expect_expr(mir_node_id).node { ( tcx.sess.source_map().end_point(span), if gen_move.is_some() { \" of generator\" } else { \" of closure\" }, ) } else { // unreachable? (mir.span, \"\") }; let (return_span, mir_description) = match tcx.hir.get(mir_node_id) { hir::Node::Expr(hir::Expr { node: hir::ExprKind::Closure(_, _, _, span, gen_move), .. }) => ( tcx.sess.source_map().end_point(*span), if gen_move.is_some() { \" of generator\" } else { \" of closure\" }, ), hir::Node::ImplItem(hir::ImplItem { node: hir::ImplItemKind::Method(method_sig, _), .. }) => (method_sig.decl.output.span(), \"\"), _ => (mir.span, \"\"), }; Some(RegionName { // This counter value will already have been used, so this function will increment it"} {"_id":"doc-en-rust-fe3571440a5d3467e937ea21452b4aba874cd1d3ec45b413ed432c6e11c7c49e","title":"","text":" // Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(nll)] struct Bar; struct Foo<'s> { bar: &'s mut Bar, } impl Foo<'_> { fn new(bar: &mut Bar) -> Self { Foo { bar } } } fn main() { } "} {"_id":"doc-en-rust-621e34e45cf1bf9a0cb7eb10d4d95180cb57df920f741c1c6fab6e732941f947","title":"","text":" error: unsatisfied lifetime constraints --> $DIR/issue-55394.rs:21:9 | LL | fn new(bar: &mut Bar) -> Self { | - ---- return type is Foo<'2> | | | let's call the lifetime of this reference `'1` LL | Foo { bar } | ^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2` error: aborting due to previous error "} {"_id":"doc-en-rust-194aefa88179d5a108a580b4ef0cb22e11dde7d7b6c8a0bb8b9183e3d5201ce1","title":"","text":"/// implicit closure bindings. It is needed when the closure is /// borrowing or mutating a mutable referent, e.g.: /// /// let x: &mut isize = ...; /// let y = || *x += 5; /// let x: &mut isize = ...; /// let y = || *x += 5; /// /// If we were to try to translate this closure into a more explicit /// form, we'd encounter an error with the code as written: /// /// struct Env { x: & &mut isize } /// let x: &mut isize = ...; /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn /// fn fn_ptr(env: &mut Env) { **env.x += 5; } /// struct Env { x: & &mut isize } /// let x: &mut isize = ...; /// let y = (&mut Env { &x }, fn_ptr); // Closure is pair of env and fn /// fn fn_ptr(env: &mut Env) { **env.x += 5; } /// /// This is then illegal because you cannot mutate an `&mut` found /// in an aliasable location. To solve, you'd have to translate with /// an `&mut` borrow: /// /// struct Env { x: & &mut isize } /// let x: &mut isize = ...; /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x /// fn fn_ptr(env: &mut Env) { **env.x += 5; } /// struct Env { x: & &mut isize } /// let x: &mut isize = ...; /// let y = (&mut Env { &mut x }, fn_ptr); // changed from &x to &mut x /// fn fn_ptr(env: &mut Env) { **env.x += 5; } /// /// Now the assignment to `**env.x` is legal, but creating a /// mutable pointer to `x` is not because `x` is not mutable. We"} {"_id":"doc-en-rust-81521d73c0d13cbab2c75152ab433ecefaf2f2984938861b6119afbeaa1f4d1a","title":"","text":" error[E0502]: cannot borrow `u.y` as immutable because it is also borrowed as mutable --> $DIR/union-borrow-move-parent-sibling.rs:25:13 | LL | let a = &mut u.x.0; | ---------- mutable borrow occurs here LL | let b = &u.y; //~ ERROR cannot borrow `u.y` | ^^^^ immutable borrow occurs here LL | use_borrow(a); | - mutable borrow later used here error[E0382]: use of moved value: `u` --> $DIR/union-borrow-move-parent-sibling.rs:29:13 --> $DIR/union-borrow-move-parent-sibling.rs:32:13 | LL | let a = u.x.0; | ----- value moved here LL | let a = u.y; //~ ERROR use of moved value: `u.y` LL | let b = u.y; //~ ERROR use of moved value: `u.y` | ^^^ value used here after move | = note: move occurs because `u` has type `U`, which does not implement the `Copy` trait error[E0502]: cannot borrow `u.y` as immutable because it is also borrowed as mutable --> $DIR/union-borrow-move-parent-sibling.rs:38:13 | LL | let a = &mut (u.x.0).0; | -------------- mutable borrow occurs here LL | let b = &u.y; //~ ERROR cannot borrow `u.y` | ^^^^ immutable borrow occurs here LL | use_borrow(a); | - mutable borrow later used here error[E0382]: use of moved value: `u` --> $DIR/union-borrow-move-parent-sibling.rs:41:13 --> $DIR/union-borrow-move-parent-sibling.rs:45:13 | LL | let a = (u.x.0).0; | --------- value moved here LL | let a = u.y; //~ ERROR use of moved value: `u.y` LL | let b = u.y; //~ ERROR use of moved value: `u.y` | ^^^ value used here after move | = note: move occurs because `u` has type `U`, which does not implement the `Copy` trait error[E0502]: cannot borrow `u.x` as immutable because it is also borrowed as mutable --> $DIR/union-borrow-move-parent-sibling.rs:51:13 | LL | let a = &mut *u.y; | --------- mutable borrow occurs here LL | let b = &u.x; //~ ERROR cannot borrow `u` (via `u.x`) | ^^^^ immutable borrow occurs here LL | use_borrow(a); | - mutable borrow later used here error[E0382]: use of moved value: `u` --> $DIR/union-borrow-move-parent-sibling.rs:53:13 --> $DIR/union-borrow-move-parent-sibling.rs:58:13 | LL | let a = *u.y; | ---- value moved here LL | let a = u.x; //~ ERROR use of moved value: `u.x` LL | let b = u.x; //~ ERROR use of moved value: `u.x` | ^^^ value used here after move | = note: move occurs because `u` has type `U`, which does not implement the `Copy` trait error: aborting due to 3 previous errors error: aborting due to 6 previous errors For more information about this error, try `rustc --explain E0382`. Some errors occurred: E0382, E0502. For more information about an error, try `rustc --explain E0382`. "} {"_id":"doc-en-rust-9ecc1462aa9224cc27877fbff45df6b6f55bd2741f2167e98b1506a03ea4f629","title":"","text":"y: Box>, } fn use_borrow(_: &T) {} unsafe fn parent_sibling_borrow() { let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) }; let a = &mut u.x.0; let a = &u.y; //~ ERROR cannot borrow `u.y` let b = &u.y; //~ ERROR cannot borrow `u.y` use_borrow(a); } unsafe fn parent_sibling_move() { let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) }; let a = u.x.0; let a = u.y; //~ ERROR use of moved value: `u.y` let b = u.y; //~ ERROR use of moved value: `u.y` } unsafe fn grandparent_sibling_borrow() { let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) }; let a = &mut (u.x.0).0; let a = &u.y; //~ ERROR cannot borrow `u.y` let b = &u.y; //~ ERROR cannot borrow `u.y` use_borrow(a); } unsafe fn grandparent_sibling_move() { let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) }; let a = (u.x.0).0; let a = u.y; //~ ERROR use of moved value: `u.y` let b = u.y; //~ ERROR use of moved value: `u.y` } unsafe fn deref_sibling_borrow() { let mut u = U { y: Box::default() }; let a = &mut *u.y; let a = &u.x; //~ ERROR cannot borrow `u` (via `u.x`) let b = &u.x; //~ ERROR cannot borrow `u` (via `u.x`) use_borrow(a); } unsafe fn deref_sibling_move() { let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) }; let a = *u.y; let a = u.x; //~ ERROR use of moved value: `u.x` let b = u.x; //~ ERROR use of moved value: `u.x` }"} {"_id":"doc-en-rust-4f2bf96149b05081c215424a00bee0347c9a17c18221b7570f25412ac9712d0d","title":"","text":"error[E0502]: cannot borrow `u.y` as immutable because `u.x.0` is also borrowed as mutable --> $DIR/union-borrow-move-parent-sibling.rs:23:14 --> $DIR/union-borrow-move-parent-sibling.rs:25:14 | LL | let a = &mut u.x.0; | ----- mutable borrow occurs here LL | let a = &u.y; //~ ERROR cannot borrow `u.y` LL | let b = &u.y; //~ ERROR cannot borrow `u.y` | ^^^ immutable borrow occurs here LL | use_borrow(a); LL | } | - mutable borrow ends here error[E0382]: use of moved value: `u.y` --> $DIR/union-borrow-move-parent-sibling.rs:29:9 --> $DIR/union-borrow-move-parent-sibling.rs:32:9 | LL | let a = u.x.0; | - value moved here LL | let a = u.y; //~ ERROR use of moved value: `u.y` LL | let b = u.y; //~ ERROR use of moved value: `u.y` | ^ value used here after move | = note: move occurs because `u.y` has type `[type error]`, which does not implement the `Copy` trait error[E0502]: cannot borrow `u.y` as immutable because `u.x.0.0` is also borrowed as mutable --> $DIR/union-borrow-move-parent-sibling.rs:35:14 --> $DIR/union-borrow-move-parent-sibling.rs:38:14 | LL | let a = &mut (u.x.0).0; | --------- mutable borrow occurs here LL | let a = &u.y; //~ ERROR cannot borrow `u.y` LL | let b = &u.y; //~ ERROR cannot borrow `u.y` | ^^^ immutable borrow occurs here LL | use_borrow(a); LL | } | - mutable borrow ends here error[E0382]: use of moved value: `u.y` --> $DIR/union-borrow-move-parent-sibling.rs:41:9 --> $DIR/union-borrow-move-parent-sibling.rs:45:9 | LL | let a = (u.x.0).0; | - value moved here LL | let a = u.y; //~ ERROR use of moved value: `u.y` LL | let b = u.y; //~ ERROR use of moved value: `u.y` | ^ value used here after move | = note: move occurs because `u.y` has type `[type error]`, which does not implement the `Copy` trait error[E0502]: cannot borrow `u` (via `u.x`) as immutable because `u` is also borrowed as mutable (via `*u.y`) --> $DIR/union-borrow-move-parent-sibling.rs:47:14 --> $DIR/union-borrow-move-parent-sibling.rs:51:14 | LL | let a = &mut *u.y; | ---- mutable borrow occurs here (via `*u.y`) LL | let a = &u.x; //~ ERROR cannot borrow `u` (via `u.x`) LL | let b = &u.x; //~ ERROR cannot borrow `u` (via `u.x`) | ^^^ immutable borrow occurs here (via `u.x`) LL | use_borrow(a); LL | } | - mutable borrow ends here error[E0382]: use of moved value: `u.x` --> $DIR/union-borrow-move-parent-sibling.rs:53:9 --> $DIR/union-borrow-move-parent-sibling.rs:58:9 | LL | let a = *u.y; | - value moved here LL | let a = u.x; //~ ERROR use of moved value: `u.x` LL | let b = u.x; //~ ERROR use of moved value: `u.x` | ^ value used here after move | = note: move occurs because `u.x` has type `[type error]`, which does not implement the `Copy` trait"} {"_id":"doc-en-rust-e6a1c4c2745b7af7869f2aec3a143c5a2eccaf3ca37fb293a258e0416510960f","title":"","text":"match self.tcx().extern_crate(def_id) { Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) { (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => { debug!(\"try_print_visible_def_path: def_id={:?}\", def_id); return Ok(( if !span.is_dummy() { self.print_def_path(def_id, &[])? } else { self.path_crate(cnum)? }, true, )); // NOTE(eddyb) the only reason `span` might be dummy, // that we're aware of, is that it's the `std`/`core` // `extern crate` injected by default. // FIXME(eddyb) find something better to key this on, // or avoid ending up with `ExternCrateSource::Extern`, // for the injected `std`/`core`. if span.is_dummy() { return Ok((self.path_crate(cnum)?, true)); } // Disable `try_print_trimmed_def_path` behavior within // the `print_def_path` call, to avoid infinite recursion // in cases where the `extern crate foo` has non-trivial // parents, e.g. it's nested in `impl foo::Trait for Bar` // (see also issues #55779 and #87932). self = with_no_visible_paths(|| self.print_def_path(def_id, &[]))?; return Ok((self, true)); } (ExternCrateSource::Path, LOCAL_CRATE) => { debug!(\"try_print_visible_def_path: def_id={:?}\", def_id); return Ok((self.path_crate(cnum)?, true)); } _ => {}"} {"_id":"doc-en-rust-0892d6631bf90020ac8a678d4163617c53057e3b5245b6c62452b916d5918741","title":"","text":" pub trait Trait { fn no_op(&self); } "} {"_id":"doc-en-rust-ded35c60e6c6b93cb67c2e6625adf11d339e44d0fedae7e8acf398534df9ffd2","title":"","text":" pub trait Deserialize { fn deserialize(); } "} {"_id":"doc-en-rust-e06c8f0cb03cdfc7657dca9fed290841ec14511ccb6bed2b8ff5e64e5ccd07ac","title":"","text":" // run-pass // edition:2018 // aux-crate:issue_55779_extern_trait=issue-55779-extern-trait.rs use issue_55779_extern_trait::Trait; struct Local; struct Helper; impl Trait for Local { fn no_op(&self) { // (Unused) extern crate declaration necessary to reproduce bug extern crate issue_55779_extern_trait; // This one works // impl Trait for Helper { fn no_op(&self) { } } // This one infinite-loops const _IMPL_SERIALIZE_FOR_HELPER: () = { // (extern crate can also appear here to reproduce bug, // as in originating example from serde) impl Trait for Helper { fn no_op(&self) { } } }; } } fn main() { } "} {"_id":"doc-en-rust-03f4d56a2ede942a12d27033afe9b7aeb3c0e4d2648699cf5ab945afe0fe6912","title":"","text":" // edition:2018 // aux-crate:issue_87932_a=issue-87932-a.rs pub struct A {} impl issue_87932_a::Deserialize for A { fn deserialize() { extern crate issue_87932_a as _a; } } fn main() { A::deserialize(); //~^ ERROR no function or associated item named `deserialize` found for struct `A` } "} {"_id":"doc-en-rust-e2156872654ab42d5afbf9d754fd51cd9e5ee7ea227d3e1a45fac2c500a99bf8","title":"","text":" error[E0599]: no function or associated item named `deserialize` found for struct `A` in the current scope --> $DIR/issue-87932.rs:13:8 | LL | pub struct A {} | ------------ function or associated item `deserialize` not found for this ... LL | A::deserialize(); | ^^^^^^^^^^^ function or associated item not found in `A` | = help: items from traits can only be used if the trait is in scope help: the following trait is implemented but not in scope; perhaps add a `use` for it: | LL | use ::deserialize::_a::Deserialize; | error: aborting due to previous error For more information about this error, try `rustc --explain E0599`. "} {"_id":"doc-en-rust-0948e8e37f710f752cd3c4b82dd9ebe471a8c522fe901a78a2cbdbbf3226c939","title":"","text":" // run-pass // ^-- The above is needed as this issue is related to LLVM/codegen. // min-llvm-version:15.0.0 // ^-- The above is needed as this issue is fixed by the opaque pointers. fn main() { type_error(|x| &x); } fn type_error( _selector: for<'a> fn(&'a Vec Fn(&'b u8)>>) -> &'a Vec>, ) { } "} {"_id":"doc-en-rust-b473a1afe3e65265270067683b1b0150271669aa2426a64446f223d447f2930a","title":"","text":" // check-pass trait Mirror { type Other; } #[derive(Debug)] struct Even(usize); struct Odd; impl Mirror for Even { type Other = Odd; } impl Mirror for Odd { type Other = Even; } trait Dyn: AsRef<::Other> {} impl Dyn for Even {} impl AsRef for Even { fn as_ref(&self) -> &Even { self } } fn code(d: &dyn Dyn) -> &T::Other { d.as_ref() } fn main() { println!(\"{:?}\", code(&Even(22))); } "} {"_id":"doc-en-rust-9a2d688c3fa639e2118f85646c917c89d772eb29bb0de948a4a0b899e20bd1dd","title":"","text":" fn t7p(f: impl Fn(B) -> C, g: impl Fn(A) -> B) -> impl Fn(A) -> C { move |a: A| -> C { f(g(a)) } } fn t8n(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C) where A: Copy, { move |a: A| -> (B, C) { let b = a; let fa = f(a); let ga = g(b); (fa, ga) } } fn main() { let f = |(_, _)| {}; let g = |(a, _)| a; let t7 = |env| |a| |b| t7p(f, g)(((env, a), b)); let t8 = t8n(t7, t7p(f, g)); //~^ ERROR: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)> } "} {"_id":"doc-en-rust-8419251590cf9d5321270b80c25453db0c31bfa58fb418c234cddf2b1b6144ab","title":"","text":" error[E0277]: expected a `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)>` --> $DIR/issue-59494.rs:21:22 | LL | fn t8n(f: impl Fn(A) -> B, g: impl Fn(A) -> C) -> impl Fn(A) -> (B, C) | ---------- required by this bound in `t8n` ... LL | let t8 = t8n(t7, t7p(f, g)); | ^^^^^^^^^ expected an `Fn<(_,)>` closure, found `impl Fn<(((_, _), _),)>` | = help: the trait `Fn<(_,)>` is not implemented for `impl Fn<(((_, _), _),)>` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-f9539003620decdd46e47f872503fcda0271d127664e87f7c24b6244bd178262","title":"","text":" // check-pass pub trait Trait1 { type C; } struct T1; impl Trait1 for T1 { type C = usize; } pub trait Callback: FnMut(::C) {} impl::C)> Callback for F {} pub struct State { callback: Option>>, } impl State { fn new() -> Self { Self { callback: None } } fn test_cb(&mut self, d: ::C) { (self.callback.as_mut().unwrap())(d) } } fn main() { let mut s = State::::new(); s.test_cb(1); } "} {"_id":"doc-en-rust-4cc83a86d95b76ac372d489ef3ff944323dfd3254f3b86d7070803d49c555801","title":"","text":" // check-pass fn any() -> T { loop {} } trait Foo { type V; } trait Callback: Fn(&T, &T::V) {} impl Callback for F {} struct Bar { callback: Box>, } impl Bar { fn event(&self) { (self.callback)(any(), any()); } } struct A; struct B; impl Foo for A { type V = B; } fn main() { let foo = Bar:: { callback: Box::new(|_: &A, _: &B| ()) }; foo.event(); } "} {"_id":"doc-en-rust-1af1a9b02a3a8d7d6e2b22d5a649173118f43fddbe8406fa95d1a643a3c42041","title":"","text":"bx.store_with_flags(val, dest.llval, dest.align, flags); } OperandValue::Pair(a, b) => { for (i, &x) in [a, b].iter().enumerate() { let llptr = bx.struct_gep(dest.llval, i as u64); let val = base::from_immediate(bx, x); bx.store_with_flags(val, llptr, dest.align, flags); } let (a_scalar, b_scalar) = match dest.layout.abi { layout::Abi::ScalarPair(ref a, ref b) => (a, b), _ => bug!(\"store_with_flags: invalid ScalarPair layout: {:#?}\", dest.layout) }; let b_offset = a_scalar.value.size(bx).align_to(b_scalar.value.align(bx).abi); let llptr = bx.struct_gep(dest.llval, 0); let val = base::from_immediate(bx, a); let align = dest.align; bx.store_with_flags(val, llptr, align, flags); let llptr = bx.struct_gep(dest.llval, 1); let val = base::from_immediate(bx, b); let align = dest.align.restrict_for_offset(b_offset); bx.store_with_flags(val, llptr, align, flags); } } }"} {"_id":"doc-en-rust-5f762bff351e7ad311bf728ad3509e1d7390dcc11abe615241373979e59bfa04","title":"","text":" // compile-flags: -C no-prepopulate-passes #![crate_type=\"rlib\"] #[allow(dead_code)] pub struct Foo { foo: u64, bar: T, } // The store writing to bar.1 should have alignment 4. Not checking // other stores here, as the alignment will be platform-dependent. // CHECK: store i32 [[TMP1:%.+]], i32* [[TMP2:%.+]], align 4 #[no_mangle] pub fn test(x: (i32, i32)) -> Foo<(i32, i32)> { Foo { foo: 0, bar: x } } "} {"_id":"doc-en-rust-6ccffde3473faf7afee69948e7e529f05584251a3d93ee6d957fad549e312fb4","title":"","text":"println!(\"cargo:rustc-link-lib=advapi32\"); println!(\"cargo:rustc-link-lib=ws2_32\"); println!(\"cargo:rustc-link-lib=userenv\"); println!(\"cargo:rustc-link-lib=shell32\"); } else if target.contains(\"fuchsia\") { println!(\"cargo:rustc-link-lib=zircon\"); println!(\"cargo:rustc-link-lib=fdio\");"} {"_id":"doc-en-rust-b6432746ae804360064d5d60218f95477db29f76003bb962fe0a18be7daaa6e8","title":"","text":"#![allow(dead_code)] // runtime init functions not used during testing use os::windows::prelude::*; use sys::windows::os::current_exe; use sys::c; use slice; use ops::Range; use ffi::OsString; use libc::{c_int, c_void}; use fmt; use vec; use core::iter; use slice; use path::PathBuf; pub unsafe fn init(_argc: isize, _argv: *const *const u8) { }"} {"_id":"doc-en-rust-ee97c5fef253feeea120e2c3830c2f1ccde3bc081e6a530d3f09ff6f3f3b9cde","title":"","text":"pub fn args() -> Args { unsafe { let mut nArgs: c_int = 0; let lpCmdLine = c::GetCommandLineW(); let szArgList = c::CommandLineToArgvW(lpCmdLine, &mut nArgs); // szArcList can be NULL if CommandLinToArgvW failed, // but in that case nArgs is 0 so we won't actually // try to read a null pointer Args { cur: szArgList, range: 0..(nArgs as isize) } let lp_cmd_line = c::GetCommandLineW(); let parsed_args_list = parse_lp_cmd_line( lp_cmd_line as *const u16, || current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new())); Args { parsed_args_list: parsed_args_list.into_iter() } } } /// Implements the Windows command-line argument parsing algorithm. /// /// Microsoft's documentation for the Windows CLI argument format can be found at /// . /// /// Windows includes a function to do this in shell32.dll, /// but linking with that DLL causes the process to be registered as a GUI application. /// GUI applications add a bunch of overhead, even if no windows are drawn. See /// . /// /// This function was tested for equivalence to the shell32.dll implementation in /// Windows 10 Pro v1803, using an exhaustive test suite available at /// or /// . unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_name: F) -> Vec { const BACKSLASH: u16 = '' as u16; const QUOTE: u16 = '\"' as u16; const TAB: u16 = 't' as u16; const SPACE: u16 = ' ' as u16; let mut ret_val = Vec::new(); if lp_cmd_line.is_null() || *lp_cmd_line == 0 { ret_val.push(exe_name()); return ret_val; } let mut cmd_line = { let mut end = 0; while *lp_cmd_line.offset(end) != 0 { end += 1; } slice::from_raw_parts(lp_cmd_line, end as usize) }; // The executable name at the beginning is special. cmd_line = match cmd_line[0] { // The executable name ends at the next quote mark, // no matter what. QUOTE => { let args = { let mut cut = cmd_line[1..].splitn(2, |&c| c == QUOTE); if let Some(exe) = cut.next() { ret_val.push(OsString::from_wide(exe)); } cut.next() }; if let Some(args) = args { args } else { return ret_val; } } // Implement quirk: when they say whitespace here, // they include the entire ASCII control plane: // \"However, if lpCmdLine starts with any amount of whitespace, CommandLineToArgvW // will consider the first argument to be an empty string. Excess whitespace at the // end of lpCmdLine is ignored.\" 0...SPACE => { ret_val.push(OsString::new()); &cmd_line[1..] }, // The executable name ends at the next whitespace, // no matter what. _ => { let args = { let mut cut = cmd_line.splitn(2, |&c| c > 0 && c <= SPACE); if let Some(exe) = cut.next() { ret_val.push(OsString::from_wide(exe)); } cut.next() }; if let Some(args) = args { args } else { return ret_val; } } }; let mut cur = Vec::new(); let mut in_quotes = false; let mut was_in_quotes = false; let mut backslash_count: usize = 0; for &c in cmd_line { match c { // backslash BACKSLASH => { backslash_count += 1; was_in_quotes = false; }, QUOTE if backslash_count % 2 == 0 => { cur.extend(iter::repeat(b'' as u16).take(backslash_count / 2)); backslash_count = 0; if was_in_quotes { cur.push('\"' as u16); was_in_quotes = false; } else { was_in_quotes = in_quotes; in_quotes = !in_quotes; } } QUOTE if backslash_count % 2 != 0 => { cur.extend(iter::repeat(b'' as u16).take(backslash_count / 2)); backslash_count = 0; was_in_quotes = false; cur.push(b'\"' as u16); } SPACE | TAB if !in_quotes => { cur.extend(iter::repeat(b'' as u16).take(backslash_count)); if !cur.is_empty() || was_in_quotes { ret_val.push(OsString::from_wide(&cur[..])); cur.truncate(0); } backslash_count = 0; was_in_quotes = false; } _ => { cur.extend(iter::repeat(b'' as u16).take(backslash_count)); backslash_count = 0; was_in_quotes = false; cur.push(c); } } } cur.extend(iter::repeat(b'' as u16).take(backslash_count)); // include empty quoted strings at the end of the arguments list if !cur.is_empty() || was_in_quotes || in_quotes { ret_val.push(OsString::from_wide(&cur[..])); } ret_val } pub struct Args { range: Range, cur: *mut *mut u16, parsed_args_list: vec::IntoIter, } pub struct ArgsInnerDebug<'a> {"} {"_id":"doc-en-rust-4b68bd1243319770ab891159980d0bed17529c339b544f1b61d9bd08e2d3b8c1","title":"","text":"impl<'a> fmt::Debug for ArgsInnerDebug<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(\"[\")?; let mut first = true; for i in self.args.range.clone() { if !first { f.write_str(\", \")?; } first = false; // Here we do allocation which could be avoided. fmt::Debug::fmt(&unsafe { os_string_from_ptr(*self.args.cur.offset(i)) }, f)?; } f.write_str(\"]\")?; Ok(()) self.args.parsed_args_list.as_slice().fmt(f) } }"} {"_id":"doc-en-rust-4c75c7a7a1d3e8190cf443c7b348ab8fca1166d786452dae9be45734fecb00fa","title":"","text":"} } unsafe fn os_string_from_ptr(ptr: *mut u16) -> OsString { let mut len = 0; while *ptr.offset(len) != 0 { len += 1; } // Push it onto the list. let ptr = ptr as *const u16; let buf = slice::from_raw_parts(ptr, len as usize); OsStringExt::from_wide(buf) } impl Iterator for Args { type Item = OsString; fn next(&mut self) -> Option { self.range.next().map(|i| unsafe { os_string_from_ptr(*self.cur.offset(i)) } ) } fn size_hint(&self) -> (usize, Option) { self.range.size_hint() } fn next(&mut self) -> Option { self.parsed_args_list.next() } fn size_hint(&self) -> (usize, Option) { self.parsed_args_list.size_hint() } } impl DoubleEndedIterator for Args { fn next_back(&mut self) -> Option { self.range.next_back().map(|i| unsafe { os_string_from_ptr(*self.cur.offset(i)) } ) } fn next_back(&mut self) -> Option { self.parsed_args_list.next_back() } } impl ExactSizeIterator for Args { fn len(&self) -> usize { self.range.len() } fn len(&self) -> usize { self.parsed_args_list.len() } } impl Drop for Args { fn drop(&mut self) { // self.cur can be null if CommandLineToArgvW previously failed, // but LocalFree ignores NULL pointers unsafe { c::LocalFree(self.cur as *mut c_void); } #[cfg(test)] mod tests { use sys::windows::args::*; use ffi::OsString; fn chk(string: &str, parts: &[&str]) { let mut wide: Vec = OsString::from(string).encode_wide().collect(); wide.push(0); let parsed = unsafe { parse_lp_cmd_line(wide.as_ptr() as *const u16, || OsString::from(\"TEST.EXE\")) }; let expected: Vec = parts.iter().map(|k| OsString::from(k)).collect(); assert_eq!(parsed.as_slice(), expected.as_slice()); } #[test] fn empty() { chk(\"\", &[\"TEST.EXE\"]); chk(\"0\", &[\"TEST.EXE\"]); } #[test] fn single_words() { chk(\"EXE one_word\", &[\"EXE\", \"one_word\"]); chk(\"EXE a\", &[\"EXE\", \"a\"]); chk(\"EXE 😅\", &[\"EXE\", \"😅\"]); chk(\"EXE 😅🤦\", &[\"EXE\", \"😅🤦\"]); } #[test] fn official_examples() { chk(r#\"EXE \"abc\" d e\"#, &[\"EXE\", \"abc\", \"d\", \"e\"]); chk(r#\"EXE ab d\"e f\"g h\"#, &[\"EXE\", r#\"ab\"#, \"de fg\", \"h\"]); chk(r#\"EXE a\"b c d\"#, &[\"EXE\", r#\"a\"b\"#, \"c\", \"d\"]); chk(r#\"EXE a\"b c\" d e\"#, &[\"EXE\", r#\"ab c\"#, \"d\", \"e\"]); } #[test] fn whitespace_behavior() { chk(r#\" test\"#, &[\"\", \"test\"]); chk(r#\" test\"#, &[\"\", \"test\"]); chk(r#\" test test2\"#, &[\"\", \"test\", \"test2\"]); chk(r#\" test test2\"#, &[\"\", \"test\", \"test2\"]); chk(r#\"test test2 \"#, &[\"test\", \"test2\"]); chk(r#\"test test2 \"#, &[\"test\", \"test2\"]); chk(r#\"test \"#, &[\"test\"]); } #[test] fn genius_quotes() { chk(r#\"EXE \"\" \"\"\"#, &[\"EXE\", \"\", \"\"]); chk(r#\"EXE \"\" \"\"\"\"#, &[\"EXE\", \"\", \"\"\"]); chk( r#\"EXE \"this is \"\"\"all\"\"\" in the same argument\"\"#, &[\"EXE\", \"this is \"all\" in the same argument\"] ); chk(r#\"EXE \"a\"\"\"#, &[\"EXE\", \"a\"\"]); chk(r#\"EXE \"a\"\" a\"#, &[\"EXE\", \"a\"\", \"a\"]); // quotes cannot be escaped in command names chk(r#\"\"EXE\" check\"#, &[\"EXE\", \"check\"]); chk(r#\"\"EXE check\"\"#, &[\"EXE check\"]); chk(r#\"\"EXE \"\"\"for\"\"\" check\"#, &[\"EXE \", r#\"for\"\"#, \"check\"]); chk(r#\"\"EXE \"for\" check\"#, &[r#\"EXE \"#, r#\"for\"\"#, \"check\"]); } }"} {"_id":"doc-en-rust-3001a0bc83d8a64cf295d90b15e1609f8e959cd7eeac29e9155d320ca4a6b827","title":"","text":"pub fn SetLastError(dwErrCode: DWORD); pub fn GetCommandLineW() -> *mut LPCWSTR; pub fn LocalFree(ptr: *mut c_void); pub fn CommandLineToArgvW(lpCmdLine: *mut LPCWSTR, pNumArgs: *mut c_int) -> *mut *mut u16; pub fn GetTempPathW(nBufferLength: DWORD, lpBuffer: LPCWSTR) -> DWORD; pub fn OpenProcessToken(ProcessHandle: HANDLE,"} {"_id":"doc-en-rust-18ea04d9db9e2d81024658d3bab9475497dedd48985044f87263dfda87331fa2","title":"","text":"# Extra flags needed to compile a working executable with the standard library ifdef IS_WINDOWS ifdef IS_MSVC EXTRACFLAGS := ws2_32.lib userenv.lib shell32.lib advapi32.lib EXTRACFLAGS := ws2_32.lib userenv.lib advapi32.lib else EXTRACFLAGS := -lws2_32 -luserenv endif"} {"_id":"doc-en-rust-3bc4e1820fbe2dc736e2c20720d38e3c454e51406fd378d37f6be823026915b6","title":"","text":"perf debuginfo doc $(foreach docname,$(DOC_TEST_NAMES),$(docname)) $(foreach docname,$(DOC_TEST_NAMES),doc-$(docname)) pretty pretty-rpass pretty-rpass-full "} {"_id":"doc-en-rust-7ef1abcab98ac26a1a9ec02cbb27952fa747c788e98262270ae28951a46f919e","title":"","text":"/// ``` #[lang = \"index\"] #[rustc_on_unimplemented( on( _Self=\"&str\", note=\"you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book \" ), on( _Self=\"str\", note=\"you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book \" ), on( _Self=\"std::string::String\", note=\"you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book \" ), message=\"the type `{Self}` cannot be indexed by `{Idx}`\", label=\"`{Self}` cannot be indexed by `{Idx}`\", )]"} {"_id":"doc-en-rust-5cc809510d9a2729d9e9b318d18316735576aeac758aee8484ba0b06cc0eb62d","title":"","text":"/// ``` #[lang = \"index_mut\"] #[rustc_on_unimplemented( on( _Self=\"&str\", note=\"you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book \" ), on( _Self=\"str\", note=\"you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book \" ), on( _Self=\"std::string::String\", note=\"you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book \" ), message=\"the type `{Self}` cannot be mutably indexed by `{Idx}`\", label=\"`{Self}` cannot be mutably indexed by `{Idx}`\", )]"} {"_id":"doc-en-rust-5abce897af2a9c727ccef312407e76934785e4fd7ca8e186155424a20a85f6bf","title":"","text":"| ^^^^ `str` cannot be indexed by `{integer}` | = help: the trait `std::ops::Index<{integer}>` is not implemented for `str` = note: you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book error: aborting due to previous error"} {"_id":"doc-en-rust-dd0f7a8153ce94d0cc40875857a4574f533e338fc4f5a2f2de3a437d7e448a08","title":"","text":"| ^^^^^^^^^ `str` cannot be mutably indexed by `usize` | = help: the trait `std::ops::IndexMut` is not implemented for `str` = note: you can use `.chars().nth()` or `.bytes().nth()` see chapter in The Book error: aborting due to 3 previous errors"} {"_id":"doc-en-rust-97f2cbf2ad1edd12f89a181133c454920619a378555a9c679cee499e4a80362c","title":"","text":"/// assert_eq!(v.len(), 42); /// } /// ``` /// should be /// /// ```rust /// // should be /// fn foo(v: &[i32]) { /// assert_eq!(v.len(), 42); /// }"} {"_id":"doc-en-rust-7d345cce6e2e516bbcda4d5727ccc0231b644c6f134c02122b861d92bab584ef","title":"","text":"!preds.is_empty() && { let ty_empty_region = cx.tcx.mk_imm_ref(cx.tcx.lifetimes.re_root_empty, ty); preds.iter().all(|t| { let ty_params = &t.skip_binder().trait_ref.substs.iter().skip(1).collect::>(); let ty_params = &t .skip_binder() .trait_ref .substs .iter() .skip(1) .collect::>(); implements_trait(cx, ty_empty_region, t.def_id(), ty_params) }) },"} {"_id":"doc-en-rust-4bb04d4ad7c7b4b4d560fca3ae752b356a25582f3435649c361a216b8a23acba","title":"","text":"/// /// **Example:** /// ```rust /// // Bad /// println!(\"\"); /// /// // Good /// println!(); /// ``` pub PRINTLN_EMPTY_STRING, style,"} {"_id":"doc-en-rust-03691cbb739e01aaa529e796485fdab0a918922d3d0c34e95b4ae5bac7fde485","title":"","text":"declare_clippy_lint! { /// **What it does:** This lint warns when you use `print!()` with a format /// string that ends in a newline. /// string that /// ends in a newline. /// /// **Why is this bad?** You should use `println!()` instead, which appends the /// newline."} {"_id":"doc-en-rust-a9acced614468e7a414888121ccd85e5be9deb168ee45bed4d9e8c264afe1269","title":"","text":"/// ```rust /// # use std::fmt::Write; /// # let mut buf = String::new(); /// /// // Bad /// writeln!(buf, \"\"); /// /// // Good /// writeln!(buf); /// ``` pub WRITELN_EMPTY_STRING, style,"} {"_id":"doc-en-rust-5fc47318dfa11fca9603aefa33d7627df8167aee335e1cc01fd856eed38b648c","title":"","text":"/// # use std::fmt::Write; /// # let mut buf = String::new(); /// # let name = \"World\"; /// /// // Bad /// write!(buf, \"Hello {}!n\", name); /// /// // Good /// writeln!(buf, \"Hello {}!\", name); /// ``` pub WRITE_WITH_NEWLINE, style,"} {"_id":"doc-en-rust-39a08f976d9cf2ea042abefeb2e52efb3a54cd4bb85f03f44da638c54f7cfc2b","title":"","text":"/// ```rust /// # use std::fmt::Write; /// # let mut buf = String::new(); /// /// // Bad /// writeln!(buf, \"{}\", \"foo\"); /// /// // Good /// writeln!(buf, \"foo\"); /// ``` pub WRITE_LITERAL, style,"} {"_id":"doc-en-rust-36e124e3f02bec6f5dc8d47d7666f21b90483c5d8afdba78c68a66cead465744","title":"","text":"if let (Some(fmt_str), expr) = self.check_tts(cx, &mac.args.inner_tokens(), true) { if fmt_str.symbol == Symbol::intern(\"\") { let mut applicability = Applicability::MachineApplicable; let suggestion = if let Some(e) = expr { snippet_with_applicability(cx, e.span, \"v\", &mut applicability) } else { applicability = Applicability::HasPlaceholders; Cow::Borrowed(\"v\") let suggestion = match expr { Some(expr) => snippet_with_applicability(cx, expr.span, \"v\", &mut applicability), None => { applicability = Applicability::HasPlaceholders; Cow::Borrowed(\"v\") }, }; span_lint_and_sugg("} {"_id":"doc-en-rust-19a25cb7546a38869ea883763103fd382bf503f8d4c9a86fe7097c9bd7dd7155","title":"","text":"} fn run_ui_cargo(config: &mut compiletest::Config) { if cargo::is_rustc_test_suite() { return; } fn run_tests( config: &compiletest::Config, filter: &Option,"} {"_id":"doc-en-rust-13ddc92944b64a8c0ff9340c269286f2b556e94680bc56e27e4abd4b75c04f85","title":"","text":" #!/bin/sh CARGO_TARGET_DIR=$(pwd)/target/ export CARGO_TARGET_DIR echo 'Deprecated! `util/dev` usage is deprecated, please use `cargo dev` instead.' cd clippy_dev && cargo run -- \"$@\" "} {"_id":"doc-en-rust-417c296d822bd2c6871de073c16e2a23bc9664f7535d7b87773239b3d574a3e8","title":"","text":"); // See https://github.com/rust-lang/rust/issues/32354 if old_binding.is_import() || new_binding.is_import() { let binding = if new_binding.is_import() && !new_binding.span.is_dummy() { new_binding let directive = match (&new_binding.kind, &old_binding.kind) { (NameBindingKind::Import { directive, .. }, _) if !new_binding.span.is_dummy() => Some((directive, new_binding.span)), (_, NameBindingKind::Import { directive, .. }) if !old_binding.span.is_dummy() => Some((directive, old_binding.span)), _ => None, }; if let Some((directive, binding_span)) = directive { let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() { format!(\"Other{}\", name) } else { old_binding format!(\"other_{}\", name) }; let cm = self.session.source_map(); let rename_msg = \"you can use `as` to change the binding name of the import\"; if let ( Ok(snippet), NameBindingKind::Import { directive, ..}, _dummy @ false, ) = ( cm.span_to_snippet(binding.span), binding.kind.clone(), binding.span.is_dummy(), ) { let suggested_name = if name.as_str().chars().next().unwrap().is_uppercase() { format!(\"Other{}\", name) } else { format!(\"other_{}\", name) }; let mut suggestion = None; match directive.subclass { ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } => suggestion = Some(format!(\"self as {}\", suggested_name)), ImportDirectiveSubclass::SingleImport { source, .. } => { if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0) .map(|pos| pos as usize) { if let Ok(snippet) = self.session.source_map() .span_to_snippet(binding_span) { if pos <= snippet.len() { suggestion = Some(format!( \"{} as {}{}\", &snippet[..pos], suggested_name, if snippet.ends_with(\";\") { \";\" } else { \"\" } )) } } } } ImportDirectiveSubclass::ExternCrate { source, target, .. } => suggestion = Some(format!( \"extern crate {} as {};\", source.unwrap_or(target.name), suggested_name, )), _ => unreachable!(), } let rename_msg = \"you can use `as` to change the binding name of the import\"; if let Some(suggestion) = suggestion { err.span_suggestion_with_applicability( binding.span, &rename_msg, match directive.subclass { ImportDirectiveSubclass::SingleImport { type_ns_only: true, .. } => format!(\"self as {}\", suggested_name), ImportDirectiveSubclass::SingleImport { source, .. } => format!( \"{} as {}{}\", &snippet[..((source.span.hi().0 - binding.span.lo().0) as usize)], suggested_name, if snippet.ends_with(\";\") { \";\" } else { \"\" } ), ImportDirectiveSubclass::ExternCrate { source, target, .. } => format!( \"extern crate {} as {};\", source.unwrap_or(target.name), suggested_name, ), _ => unreachable!(), }, binding_span, rename_msg, suggestion, Applicability::MaybeIncorrect, ); } else { err.span_label(binding.span, rename_msg); err.span_label(binding_span, rename_msg); } }"} {"_id":"doc-en-rust-45ac3499486ef2d242869fb5e78948853d44070866d33c3865bdeb88356d4433","title":"","text":" macro_rules! import { ( $($name:ident),* ) => { $( mod $name; pub use self::$name; //~^ ERROR the name `issue_56411_aux` is defined multiple times //~| ERROR `issue_56411_aux` is private, and cannot be re-exported )* } } import!(issue_56411_aux); fn main() { println!(\"Hello, world!\"); } "} {"_id":"doc-en-rust-a300f928e46834fcc9121fd73d702311f56ca366382d8b716208a1689f9d8da9","title":"","text":" error[E0255]: the name `issue_56411_aux` is defined multiple times --> $DIR/issue-56411.rs:5:21 | LL | mod $name; | ---------- previous definition of the module `issue_56411_aux` here LL | pub use self::$name; | ^^^^^^^^^^^ | | | `issue_56411_aux` reimported here | you can use `as` to change the binding name of the import ... LL | import!(issue_56411_aux); | ------------------------- in this macro invocation | = note: `issue_56411_aux` must be defined only once in the type namespace of this module error[E0365]: `issue_56411_aux` is private, and cannot be re-exported --> $DIR/issue-56411.rs:5:21 | LL | pub use self::$name; | ^^^^^^^^^^^ re-export of private `issue_56411_aux` ... LL | import!(issue_56411_aux); | ------------------------- in this macro invocation | = note: consider declaring type or module `issue_56411_aux` with `pub` error: aborting due to 2 previous errors Some errors occurred: E0255, E0365. For more information about an error, try `rustc --explain E0255`. "} {"_id":"doc-en-rust-8402525181334ba8a9b4780c456a829706ad66ec1bf7966f3e9203a2875fd156","title":"","text":" // compile-pass struct T {} fn main() {} "} {"_id":"doc-en-rust-dfa27842d41aaa2c25c402191fc727e6eb3a4f21856d3b65b622677e1871ca70","title":"","text":"/// /// The following return false: /// /// - private address (10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16) /// - the loopback address (127.0.0.0/8) /// - the link-local address (169.254.0.0/16) /// - the broadcast address (255.255.255.255/32) /// - test addresses used for documentation (192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24) /// - the unspecified address (0.0.0.0) /// - private addresses (see [`is_private()`](#method.is_private)) /// - the loopback address (see [`is_loopback()`](#method.is_loopback)) /// - the link-local address (see [`is_link_local()`](#method.is_link_local)) /// - the broadcast address (see [`is_broadcast()`](#method.is_broadcast)) /// - addresses used for documentation (see [`is_documentation()`](#method.is_documentation)) /// - the unspecified address (see [`is_unspecified()`](#method.is_unspecified)), and the whole /// 0.0.0.0/8 block /// - addresses reserved for future protocols (see /// [`is_ietf_protocol_assignment()`](#method.is_ietf_protocol_assignment), except /// `192.0.0.9/32` and `192.0.0.10/32` which are globally routable /// - addresses reserved for future use (see [`is_reserved()`](#method.is_reserved) /// - addresses reserved for networking devices benchmarking (see /// [`is_benchmarking`](#method.is_benchmarking)) /// /// [ipv4-sr]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml /// [`true`]: ../../std/primitive.bool.html"} {"_id":"doc-en-rust-2bea958c2e629217af66b006a4bbc3ad041102431890e8b8abd33362125c803d","title":"","text":"/// use std::net::Ipv4Addr; /// /// fn main() { /// // private addresses are not global /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false); /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false); /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false); /// /// // the 0.0.0.0/8 block is not global /// assert_eq!(Ipv4Addr::new(0, 1, 2, 3).is_global(), false); /// // in particular, the unspecified address is not global /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_global(), false); /// /// // the loopback address is not global /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_global(), false); /// /// // link local addresses are not global /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false); /// /// // the broadcast address is not global /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_global(), false); /// /// // the broadcast address is not global /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false); /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false); /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false); /// /// // shared addresses are not global /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false); /// /// // addresses reserved for protocol assignment are not global /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_global(), false); /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_global(), false); /// /// // addresses reserved for future use are not global /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false); /// /// // addresses reserved for network devices benchmarking are not global /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false); /// /// // All the other addresses are global /// assert_eq!(Ipv4Addr::new(1, 1, 1, 1).is_global(), true); /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true); /// } /// ``` pub fn is_global(&self) -> bool { !self.is_private() && !self.is_loopback() && !self.is_link_local() && !self.is_broadcast() && !self.is_documentation() && !self.is_unspecified() // check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two // globally routable addresses in the 192.0.0.0/24 range. if u32::from(*self) == 0xc0000009 || u32::from(*self) == 0xc000000a { return true; } !self.is_private() && !self.is_loopback() && !self.is_link_local() && !self.is_broadcast() && !self.is_documentation() && !self.is_shared() && !self.is_ietf_protocol_assignment() && !self.is_reserved() && !self.is_benchmarking() // Make sure the address is not in 0.0.0.0/8 && self.octets()[0] != 0 } /// Returns [`true`] if this address is part of the Shared Address Space defined in /// [IETF RFC 6598] (`100.64.0.0/10`). /// /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598 /// [`true`]: ../../std/primitive.bool.html /// /// # Examples /// /// ``` /// #![feature(ip)] /// use std::net::Ipv4Addr; /// /// fn main() { /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true); /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true); /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false); /// } /// ``` pub fn is_shared(&self) -> bool { self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000) } /// Returns [`true`] if this address is part of `192.0.0.0/24`, which is reserved to /// IANA for IETF protocol assignments, as documented in [IETF RFC 6890]. /// /// Note that parts of this block are in use: /// /// - `192.0.0.8/32` is the \"IPv4 dummy address\" (see [IETF RFC 7600]) /// - `192.0.0.9/32` is the \"Port Control Protocol Anycast\" (see [IETF RFC 7723]) /// - `192.0.0.10/32` is used for NAT traversal (see [IETF RFC 8155]) /// /// [IETF RFC 6890]: https://tools.ietf.org/html/rfc6890 /// [IETF RFC 7600]: https://tools.ietf.org/html/rfc7600 /// [IETF RFC 7723]: https://tools.ietf.org/html/rfc7723 /// [IETF RFC 8155]: https://tools.ietf.org/html/rfc8155 /// [`true`]: ../../std/primitive.bool.html /// /// # Examples /// /// ``` /// #![feature(ip)] /// use std::net::Ipv4Addr; /// /// fn main() { /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_ietf_protocol_assignment(), true); /// assert_eq!(Ipv4Addr::new(192, 0, 0, 8).is_ietf_protocol_assignment(), true); /// assert_eq!(Ipv4Addr::new(192, 0, 0, 9).is_ietf_protocol_assignment(), true); /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_ietf_protocol_assignment(), true); /// assert_eq!(Ipv4Addr::new(192, 0, 1, 0).is_ietf_protocol_assignment(), false); /// assert_eq!(Ipv4Addr::new(191, 255, 255, 255).is_ietf_protocol_assignment(), false); /// } /// ``` pub fn is_ietf_protocol_assignment(&self) -> bool { self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0 } /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0` /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`. /// /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112 /// [errate 423]: https://www.rfc-editor.org/errata/eid423 /// [`true`]: ../../std/primitive.bool.html /// /// # Examples /// /// ``` /// #![feature(ip)] /// use std::net::Ipv4Addr; /// /// fn main() { /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false); /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true); /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true); /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false); /// } /// ``` pub fn is_benchmarking(&self) -> bool { self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18 } /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112] /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the /// broadcast address `255.255.255.255`, but this implementation explicitely excludes it, since /// it is obviously not reserved for future use. /// /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112 /// [`true`]: ../../std/primitive.bool.html /// /// # Examples /// /// ``` /// #![feature(ip)] /// use std::net::Ipv4Addr; /// /// fn main() { /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true); /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true); /// /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false); /// // The broadcast address is not considered as reserved for future use by this /// // implementation /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false); /// } /// ``` pub fn is_reserved(&self) -> bool { self.octets()[0] & 240 == 240 && !self.is_broadcast() } /// Returns [`true`] if this is a multicast address (224.0.0.0/4)."} {"_id":"doc-en-rust-68a7c17fc244b0b822c1d45fa64dc3aed9b8c312972850a66d4d090f124edfea","title":"","text":"} } /// Returns [`true`] if this is a unique local address (fc00::/7). /// Returns [`true`] if this is a unique local address (`fc00::/7`). /// /// This property is defined in [IETF RFC 4193]. ///"} {"_id":"doc-en-rust-c5f9c1bd09b19150b7898577dc686eff15cf9c05e90c69f6e09bab837a6dcafd","title":"","text":"(self.segments()[0] & 0xfe00) == 0xfc00 } /// Returns [`true`] if the address is unicast and link-local (fe80::/10). /// Returns [`true`] if the address is a unicast link-local address (`fe80::/64`). /// /// This property is defined in [IETF RFC 4291]. /// A common mis-conception is to think that \"unicast link-local addresses start with /// `fe80::`\", but the [IETF RFC 4291] actually defines a stricter format for these addresses: /// /// ```no_rust /// | 10 | /// | bits | 54 bits | 64 bits | /// +----------+-------------------------+----------------------------+ /// |1111111010| 0 | interface ID | /// +----------+-------------------------+----------------------------+ /// ``` /// /// This method validates the format defined in the RFC and won't recognize the following /// addresses such as `fe80:0:0:1::` or `fe81::` as unicast link-local addresses for example. /// If you need a less strict validation use [`is_unicast_link_local()`] instead. /// /// # Examples /// /// ``` /// #![feature(ip)] /// /// use std::net::Ipv6Addr; /// /// fn main() { /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0); /// assert!(ip.is_unicast_link_local_strict()); /// /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff); /// assert!(ip.is_unicast_link_local_strict()); /// /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0); /// assert!(!ip.is_unicast_link_local_strict()); /// assert!(ip.is_unicast_link_local()); /// /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0); /// assert!(!ip.is_unicast_link_local_strict()); /// assert!(ip.is_unicast_link_local()); /// } /// ``` /// /// # See also /// /// - [IETF RFC 4291 section 2.5.6] /// - [RFC 4291 errata 4406] /// - [`is_unicast_link_local()`] /// /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291 /// [IETF RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6 /// [`true`]: ../../std/primitive.bool.html /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406 /// [`is_unicast_link_local()`]: ../../std/net/struct.Ipv6Addr.html#method.is_unicast_link_local /// pub fn is_unicast_link_local_strict(&self) -> bool { (self.segments()[0] & 0xffff) == 0xfe80 && (self.segments()[1] & 0xffff) == 0 && (self.segments()[2] & 0xffff) == 0 && (self.segments()[3] & 0xffff) == 0 } /// Returns [`true`] if the address is a unicast link-local address (`fe80::/10`). /// /// This method returns [`true`] for addresses in the range reserved by [RFC 4291 section 2.4], /// i.e. addresses with the following format: /// /// ```no_rust /// | 10 | /// | bits | 54 bits | 64 bits | /// +----------+-------------------------+----------------------------+ /// |1111111010| arbitratry value | interface ID | /// +----------+-------------------------+----------------------------+ /// ``` /// /// As a result, this method consider addresses such as `fe80:0:0:1::` or `fe81::` to be /// unicast link-local addresses, whereas [`is_unicast_link_local_strict()`] does not. If you /// need a strict validation fully compliant with the RFC, use /// [`is_unicast_link_local_strict()`]. /// /// # Examples ///"} {"_id":"doc-en-rust-0e327b342bad07743c6df591e11031f3c3e17a64cb4a2633a26b702b53d83b64","title":"","text":"/// use std::net::Ipv6Addr; /// /// fn main() { /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_link_local(), /// false); /// assert_eq!(Ipv6Addr::new(0xfe8a, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true); /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0); /// assert!(ip.is_unicast_link_local()); /// /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff); /// assert!(ip.is_unicast_link_local()); /// /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0); /// assert!(ip.is_unicast_link_local()); /// assert!(!ip.is_unicast_link_local_strict()); /// /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0); /// assert!(ip.is_unicast_link_local()); /// assert!(!ip.is_unicast_link_local_strict()); /// } /// ``` /// /// # See also /// /// - [IETF RFC 4291 section 2.4] /// - [RFC 4291 errata 4406] /// /// [IETF RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4 /// [`true`]: ../../std/primitive.bool.html /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406 /// [`is_unicast_link_local_strict()`]: ../../std/net/struct.Ipv6Addr.html#method.is_unicast_link_local_strict /// pub fn is_unicast_link_local(&self) -> bool { (self.segments()[0] & 0xffc0) == 0xfe80 } /// Returns [`true`] if this is a deprecated unicast site-local address /// (fec0::/10). /// Returns [`true`] if this is a deprecated unicast site-local address (fec0::/10). The /// unicast site-local address format is defined in [RFC 4291 section 2.5.7] as: /// /// ```no_rust /// | 10 | /// | bits | 54 bits | 64 bits | /// +----------+-------------------------+----------------------------+ /// |1111111011| subnet ID | interface ID | /// +----------+-------------------------+----------------------------+ /// ``` /// /// [`true`]: ../../std/primitive.bool.html /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7 /// /// # Examples ///"} {"_id":"doc-en-rust-45b45d485bd88c1cfebb3dd425198a98de35ee847cdec01d0f1f8ed9e40bc913","title":"","text":"/// /// - the loopback address /// - the link-local addresses /// - the (deprecated) site-local addresses /// - unique local addresses /// - the unspecified address /// - the address range reserved for documentation /// /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7] /// /// ```no_rust /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer /// be supported in new implementations (i.e., new implementations must treat this prefix as /// Global Unicast). /// ``` /// /// [`true`]: ../../std/primitive.bool.html /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7 /// /// # Examples ///"} {"_id":"doc-en-rust-80849e3257b31a1c46b0dd3c65319462b769c21112f05064daf23f95c5002106","title":"","text":"/// ``` pub fn is_unicast_global(&self) -> bool { !self.is_multicast() && !self.is_loopback() && !self.is_unicast_link_local() && !self.is_unicast_site_local() && !self.is_unique_local() && !self.is_unspecified() && !self.is_documentation() && !self.is_loopback() && !self.is_unicast_link_local() && !self.is_unique_local() && !self.is_unspecified() && !self.is_documentation() } /// Returns the address's multicast scope if the address is multicast."} {"_id":"doc-en-rust-01550d3a62c1f8dbf3a85e641a0aa43e97558c507a9e31fbb9a9fb04365f8a13","title":"","text":" // Regression test for issue #57611 // Ensures that we don't ICE // FIXME: This should compile, but it currently doesn't #![feature(trait_alias)] #![feature(type_alias_impl_trait)] trait Foo { type Bar: Baz; fn bar(&self) -> Self::Bar; } struct X; impl Foo for X { type Bar = impl Baz; //~ ERROR type mismatch in closure arguments //~^ ERROR type mismatch resolving fn bar(&self) -> Self::Bar { |x| x } } trait Baz = Fn(&A) -> &B; fn main() {} "} {"_id":"doc-en-rust-e5a703655c6ac5a25a62963adb6bbee3581e8db3dd6a9ab56522ca0d9fdef38c","title":"","text":" error[E0631]: type mismatch in closure arguments --> $DIR/issue-57611-trait-alias.rs:17:5 | LL | type Bar = impl Baz; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected signature of `for<'r> fn(&'r X) -> _` ... LL | |x| x | ----- found signature of `fn(_) -> _` | = note: the return type of a function must have a statically known size error[E0271]: type mismatch resolving `for<'r> <[closure@$DIR/issue-57611-trait-alias.rs:21:9: 21:14] as std::ops::FnOnce<(&'r X,)>>::Output == &'r X` --> $DIR/issue-57611-trait-alias.rs:17:5 | LL | type Bar = impl Baz; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected bound lifetime parameter, found concrete lifetime | = note: the return type of a function must have a statically known size error: aborting due to 2 previous errors Some errors have detailed explanations: E0271, E0631. For more information about an error, try `rustc --explain E0271`. "} {"_id":"doc-en-rust-6acc0b5d516671e91842c496f58bf2ab85341d8f1582912eadb21740cf7ac7b4","title":"","text":" // Regression test for issue #57807 - ensure // that we properly unify associated types within // a type alias impl trait // check-pass #![feature(type_alias_impl_trait)] trait Bar { type A; } impl Bar for () { type A = (); } trait Foo { type A; type B: Bar; fn foo() -> Self::B; } impl Foo for () { type A = (); type B = impl Bar; fn foo() -> Self::B { () } } fn main() {} "} {"_id":"doc-en-rust-ab32fb4dfea5590ce7fea159e1b31bf080a2944a0afde64408446b0d5dbd8de1","title":"","text":"[[package]] name = \"compiler_builtins\" version = \"0.1.32\" version = \"0.1.35\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"7bc4ac2c824d2bfc612cba57708198547e9a26943af0632aff033e0693074d5c\" checksum = \"e3fcd8aba10d17504c87ef12d4f62ef404c6a4703d16682a9eb5543e6cf24455\" dependencies = [ \"cc\", \"rustc-std-workspace-core\","} {"_id":"doc-en-rust-e72f6299730b09657cdb8486e8ea3a46f30c134469ba3a9cc4e92e9c15e09d56","title":"","text":"panic_abort = { path = \"../panic_abort\" } core = { path = \"../core\" } libc = { version = \"0.2.74\", default-features = false, features = ['rustc-dep-of-std'] } compiler_builtins = { version = \"0.1.32\" } compiler_builtins = { version = \"0.1.35\" } profiler_builtins = { path = \"../profiler_builtins\", optional = true } unwind = { path = \"../unwind\" } hashbrown = { version = \"0.8.1\", default-features = false, features = ['rustc-dep-of-std'] }"} {"_id":"doc-en-rust-ae0f1dd513fac11ddd5092a628d19cb1656c4089f6a66d30c55e936aae563cc7","title":"","text":" // check-pass #![feature(existential_type)] existential type A: Iterator; fn def_a() -> A { 0..1 } pub fn use_a() { def_a().map(|x| x); } fn main() {} "} {"_id":"doc-en-rust-e7bbf5f78ef1850d8eb1d35e35864a2fe23e4d2854334bf96f228b0a71142e27","title":"","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":"doc-en-rust-7c37d39505667b3457e3c30615165c38181eeda791f510297d6779a66af6da3a","title":"","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":"doc-en-rust-b523cfd67ece5f2e6a8d67c450dd03609bee563d0fa77dd5e82575f00eb6a222","title":"","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":"doc-en-rust-43dfcf358157d3aea9b597b0480d9d21111bcb7def5cc0a258cd40113fec2089","title":"","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":"doc-en-rust-2f5bc0c189246f20c47a42d98bf8c96ad23df9f1512c62e19e48a684ee31e93c","title":"","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":"doc-en-rust-a0f593b02f0805e6349ad0127582660c3c150be14b11b7324dd781c9a0c345df","title":"","text":" // check-pass #![feature(impl_trait_in_bindings)] #![allow(incomplete_features)] struct A<'a>(&'a ()); trait Trait {} impl Trait for () {} pub fn foo<'a>() { let _x: impl Trait> = (); } fn main() {} "} {"_id":"doc-en-rust-c72a1e364bda38a98ebb595ca93588ad79f841bcdb844f214995cda1f100b8bb","title":"","text":" #![feature(never_type, specialization)] #![allow(incomplete_features)] use std::iter::{self, Empty}; trait Trait { type Out: Iterator; fn f(&self) -> Option; } impl Trait for T { default type Out = !; //~ ERROR: `!` is not an iterator default fn f(&self) -> Option { None } } struct X; impl Trait for X { type Out = Empty; fn f(&self) -> Option { Some(iter::empty()) } } fn f(a: T) { if let Some(iter) = a.f() { println!(\"Some\"); for x in iter { println!(\"x = {}\", x); } } } pub fn main() { f(10); } "} {"_id":"doc-en-rust-ec5d8ba7a76f71b639d2dee2588485967ed2b662d7264e413f7bc6ebd438b149","title":"","text":" error[E0277]: `!` is not an iterator --> $DIR/issue-51506.rs:13:5 | LL | type Out: Iterator; | ------------------------------- required by `Trait::Out` ... LL | default type Out = !; | ^^^^^^^^^^^^^^^^^^^^^ `!` is not an iterator | = help: the trait `std::iter::Iterator` is not implemented for `!` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-a8f22be93271ffce94f0e0a4cea97cc19a6c822b88549b9e21545c4e23d39a82","title":"","text":" #![crate_type = \"lib\"] #![feature(specialization)] #![feature(unsize, coerce_unsized)] #![allow(incomplete_features)] use std::ops::CoerceUnsized; pub struct SmartassPtr(A::Data); pub trait Smartass { type Data; type Data2: CoerceUnsized<*const [u8]>; } pub trait MaybeObjectSafe {} impl MaybeObjectSafe for () {} impl Smartass for T { type Data = ::Data2; default type Data2 = (); //~^ ERROR: the trait bound `(): std::ops::CoerceUnsized<*const [u8]>` is not satisfied } impl Smartass for () { type Data2 = *const [u8; 1]; } impl Smartass for dyn MaybeObjectSafe { type Data = *const [u8]; type Data2 = *const [u8; 0]; } impl CoerceUnsized> for SmartassPtr where ::Data: std::ops::CoerceUnsized<::Data> {} pub fn conv(s: SmartassPtr<()>) -> SmartassPtr { s } "} {"_id":"doc-en-rust-f24c5a9e6f4926b036a7af271b3b8393eb78686dcd8f9b5505fadb8d104741a5","title":"","text":" error[E0277]: the trait bound `(): std::ops::CoerceUnsized<*const [u8]>` is not satisfied --> $DIR/issue-44861.rs:21:5 | LL | type Data2: CoerceUnsized<*const [u8]>; | --------------------------------------- required by `Smartass::Data2` ... LL | default type Data2 = (); | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::ops::CoerceUnsized<*const [u8]>` is not implemented for `()` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-fcf95ebdfc238936020242ab77fb836da17c02a592e428eb984a94dc6c5513fd","title":"","text":" #![feature(specialization)] #![allow(incomplete_features)] struct MyStruct {} trait MyTrait { type MyType: Default; } impl MyTrait for i32 { default type MyType = MyStruct; //~^ ERROR: the trait bound `MyStruct: std::default::Default` is not satisfied } fn main() { let _x: ::MyType = ::MyType::default(); } "} {"_id":"doc-en-rust-2ba07713179c4f3114e52d8de411389cc8b934fd43d0875c47ff2ae312c009ac","title":"","text":" error[E0277]: the trait bound `MyStruct: std::default::Default` is not satisfied --> $DIR/issue-59435.rs:11:5 | LL | type MyType: Default; | --------------------- required by `MyTrait::MyType` ... LL | default type MyType = MyStruct; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::default::Default` is not implemented for `MyStruct` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-84194bd5d7aca18915ff8adbb1bcdff7dca705f8fb2462a4c89f39b297656a83","title":"","text":"per_local.insert(local); } } cx.per_local[IsNotPromotable].insert(local); cx.per_local[IsNotConst].insert(local); } LocalKind::Var if mode == Mode::Fn => {"} {"_id":"doc-en-rust-8c91de4f1e86ec79aeba509276b91de2b6d816f5adfa1a771623819ff8a32e56","title":"","text":"} LocalKind::Temp if !temps[local].is_promotable() => { cx.per_local[IsNotPromotable].insert(local); cx.per_local[IsNotConst].insert(local); } _ => {}"} {"_id":"doc-en-rust-648c57c8c2c990ceb5e2bb743732d366e3f16d2b0f67ed6f6121a77903069326","title":"","text":"} } // Ensure the `IsNotPromotable` qualification is preserved. // Ensure the `IsNotConst` qualification is preserved. // NOTE(eddyb) this is actually unnecessary right now, as // we never replace the local's qualif, but we might in // the future, and so it serves to catch changes that unset"} {"_id":"doc-en-rust-4e5f3f52ce4342419bc2f46b69b500f3073fbf6c8d63caf22405a65fe71b3d5f","title":"","text":"// be replaced with calling `insert` to re-set the bit). if kind == LocalKind::Temp { if !self.temp_promotion_state[index].is_promotable() { assert!(self.cx.per_local[IsNotPromotable].contains(index)); assert!(self.cx.per_local[IsNotConst].contains(index)); } } }"} {"_id":"doc-en-rust-957045bed7caa6954e23010d28385b4534243204450b66195112a6c31071f59d","title":"","text":" // only-x86_64 #[cfg(target_arch = \"x86\")] use std::arch::x86::*; #[cfg(target_arch = \"x86_64\")] use std::arch::x86_64::*; unsafe fn pclmul(a: __m128i, b: __m128i) -> __m128i { let imm8 = 3; _mm_clmulepi64_si128(a, b, imm8) //~ ERROR argument 3 is required to be a constant } fn main() {} "} {"_id":"doc-en-rust-fa8cbcbd13cb60581fb25ed391a8c697225afec8a0f9f862117068de62e697c9","title":"","text":" error: argument 3 is required to be a constant --> $DIR/const_arg_local.rs:10:5 | LL | _mm_clmulepi64_si128(a, b, imm8) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-1173f3983829635337afc8e30bcbdc1a6aecd3a41ef79ff8838a5dd48b50153a","title":"","text":" // only-x86_64 #[cfg(target_arch = \"x86\")] use std::arch::x86::*; #[cfg(target_arch = \"x86_64\")] use std::arch::x86_64::*; unsafe fn pclmul(a: __m128i, b: __m128i) -> __m128i { _mm_clmulepi64_si128(a, b, *&mut 42) //~ ERROR argument 3 is required to be a constant } fn main() {} "} {"_id":"doc-en-rust-f912e43b3bde797d4f3eec09ec9048dc9cd001b3aa02e2e775c664d60c94a619","title":"","text":" error: argument 3 is required to be a constant --> $DIR/const_arg_promotable.rs:9:5 | LL | _mm_clmulepi64_si128(a, b, *&mut 42) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-408de29b4563462d366c394ff5c2cd7d18e98909957a2a1865c91a1ab194f440","title":"","text":" // only-x86_64 #[cfg(target_arch = \"x86\")] use std::arch::x86::*; #[cfg(target_arch = \"x86_64\")] use std::arch::x86_64::*; unsafe fn pclmul(a: __m128i, b: __m128i, imm8: i32) -> __m128i { _mm_clmulepi64_si128(a, b, imm8) //~ ERROR argument 3 is required to be a constant } fn main() {} "} {"_id":"doc-en-rust-93605bb5b0a72aefda7c5c2fd7c6b71e8fd3240564e7b28c4d8aa2c97f555041","title":"","text":" error: argument 3 is required to be a constant --> $DIR/const_arg_wrapper.rs:9:5 | LL | _mm_clmulepi64_si128(a, b, imm8) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-920f23f558e96aca18948711ba00636edb55221b52cff92786272bb75c35b871","title":"","text":" use errors::DiagnosticBuilder; use errors::{Applicability, DiagnosticBuilder}; use syntax::ast::{self, *}; use syntax::source_map::Spanned; use syntax::ext::base::*; use syntax::ext::build::AstBuilder; use syntax::parse::token; use syntax::parse::parser::Parser; use syntax::print::pprust; use syntax::ptr::P; use syntax::symbol::Symbol;"} {"_id":"doc-en-rust-98be43ee7c4ace576dcd3d529967d0dab7e316963b38529808ae4367fc3b28c5","title":"","text":"return Err(err); } Ok(Assert { cond_expr: parser.parse_expr()?, custom_message: if parser.eat(&token::Comma) { let ts = parser.parse_tokens(); if !ts.is_empty() { Some(ts) } else { None } } else { None }, }) let cond_expr = parser.parse_expr()?; // Some crates use the `assert!` macro in the following form (note extra semicolon): // // assert!( // my_function(); // ); // // Warn about semicolon and suggest removing it. Eventually, this should be turned into an // error. if parser.token == token::Semi { let mut err = cx.struct_span_warn(sp, \"macro requires an expression as an argument\"); err.span_suggestion( parser.span, \"try removing semicolon\", String::new(), Applicability::MaybeIncorrect ); err.note(\"this is going to be an error in the future\"); err.emit(); parser.bump(); } // Some crates use the `assert!` macro in the following form (note missing comma before // message): // // assert!(true \"error message\"); // // Parse this as an actual message, and suggest inserting a comma. Eventually, this should be // turned into an error. let custom_message = if let token::Literal(token::Lit::Str_(_), _) = parser.token { let mut err = cx.struct_span_warn(parser.span, \"unexpected string literal\"); let comma_span = cx.source_map().next_point(parser.prev_span); err.span_suggestion_short( comma_span, \"try adding a comma\", \", \".to_string(), Applicability::MaybeIncorrect ); err.note(\"this is going to be an error in the future\"); err.emit(); parse_custom_message(&mut parser) } else if parser.eat(&token::Comma) { parse_custom_message(&mut parser) } else { None }; if parser.token != token::Eof { parser.expect_one_of(&[], &[])?; unreachable!(); } Ok(Assert { cond_expr, custom_message }) } fn parse_custom_message<'a>(parser: &mut Parser<'a>) -> Option { let ts = parser.parse_tokens(); if !ts.is_empty() { Some(ts) } else { None } }"} {"_id":"doc-en-rust-b6d293b70e1d94f35c7b07db72827ee7fecb9b99131d8ee8ead7baaf358af431","title":"","text":" // Ensure assert macro does not ignore trailing garbage. // // See https://github.com/rust-lang/rust/issues/60024 for details. fn main() { assert!(true some extra junk, \"whatever\"); //~^ ERROR expected one of assert!(true some extra junk); //~^ ERROR expected one of assert!(true, \"whatever\" blah); //~^ ERROR no rules expected assert!(true \"whatever\" blah); //~^ WARN unexpected string literal //~^^ ERROR no rules expected assert!(true;); //~^ WARN macro requires an expression assert!(false || true \"error message\"); //~^ WARN unexpected string literal } "} {"_id":"doc-en-rust-d2c2d123ba3cacb41d1561389fdeebdd60a273c877783979b1fd114353af6d29","title":"","text":" error: expected one of `,`, `.`, `?`, or an operator, found `some` --> $DIR/assert-trailing-junk.rs:6:18 | LL | assert!(true some extra junk, \"whatever\"); | ^^^^ expected one of `,`, `.`, `?`, or an operator here error: expected one of `,`, `.`, `?`, or an operator, found `some` --> $DIR/assert-trailing-junk.rs:9:18 | LL | assert!(true some extra junk); | ^^^^ expected one of `,`, `.`, `?`, or an operator here error: no rules expected the token `blah` --> $DIR/assert-trailing-junk.rs:12:30 | LL | assert!(true, \"whatever\" blah); | -^^^^ no rules expected this token in macro call | | | help: missing comma here warning: unexpected string literal --> $DIR/assert-trailing-junk.rs:15:18 | LL | assert!(true \"whatever\" blah); | -^^^^^^^^^^ | | | help: try adding a comma | = note: this is going to be an error in the future error: no rules expected the token `blah` --> $DIR/assert-trailing-junk.rs:15:29 | LL | assert!(true \"whatever\" blah); | -^^^^ no rules expected this token in macro call | | | help: missing comma here warning: macro requires an expression as an argument --> $DIR/assert-trailing-junk.rs:19:5 | LL | assert!(true;); | ^^^^^^^^^^^^-^^ | | | help: try removing semicolon | = note: this is going to be an error in the future warning: unexpected string literal --> $DIR/assert-trailing-junk.rs:22:27 | LL | assert!(false || true \"error message\"); | -^^^^^^^^^^^^^^^ | | | help: try adding a comma | = note: this is going to be an error in the future error: aborting due to 4 previous errors "} {"_id":"doc-en-rust-f8365cbc449518be5c8403dc1a55d408d694025607d731363cced19be4e2ecec","title":"","text":"let predicates_of = tcx.predicates_of(def_id); debug!(\"instantiate_opaque_types: predicates={:#?}\", predicates_of,); let bounds = predicates_of.instantiate(tcx, substs); let param_env = tcx.param_env(def_id); let InferOk { value: bounds, obligations } = infcx.partially_normalize_associated_types_in(span, self.body_id, param_env, &bounds); self.obligations.extend(obligations); debug!(\"instantiate_opaque_types: bounds={:?}\", bounds); let required_region_bounds = tcx.required_region_bounds(ty, bounds.predicates.clone());"} {"_id":"doc-en-rust-14366c5b28d93e94f1962931cbaf72dfa60a2100817687a8d465a466fe139c5c","title":"","text":"&declared_ret_ty, decl.output.span(), ); debug!(\"check_fn: declared_ret_ty: {}, revealed_ret_ty: {}\", declared_ret_ty, revealed_ret_ty); fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty))); fn_sig = fcx.tcx.mk_fn_sig( fn_sig.inputs().iter().cloned(),"} {"_id":"doc-en-rust-3afaaac7632489f05781ff9ab3653b790e10ff78b3a811e4dca6086624be72d7","title":"","text":" // check-pass // edition:2018 #![feature(async_await)] // See issue 60414 trait Trait { type Assoc; } async fn foo>() -> T::Assoc { () } fn main() {} "} {"_id":"doc-en-rust-67762d1cc9e0663f06f2ab3f603435cfbd80fbce8b3b1deb1667255d4924c360","title":"","text":" // compile-fail // edition:2018 #![feature(async_await)] #![feature(existential_type)] #![feature(impl_trait_in_bindings)] //~^ WARNING the feature `impl_trait_in_bindings` is incomplete // See issue 60414 ///////////////////////////////////////////// // Reduction to `impl Trait` struct Foo(T); trait FooLike { type Output; } impl FooLike for Foo { type Output = T; } mod impl_trait { use super::*; trait Trait { type Assoc; } /// `T::Assoc` can't be normalized any further here. fn foo_fail() -> impl FooLike { //~^ ERROR: type mismatch Foo(()) } } ///////////////////////////////////////////// // Same with lifetimes in the trait mod lifetimes { use super::*; trait Trait<'a> { type Assoc; } /// Missing bound constraining `Assoc`, `T::Assoc` can't be normalized further. fn foo2_fail<'a, T: Trait<'a>>() -> impl FooLike { //~^ ERROR: type mismatch Foo(()) } } fn main() {} "} {"_id":"doc-en-rust-e1fd038e5f5ab5eab2b98dbf518104bdcbba1dcd6d6fc336f3717af46c941884","title":"","text":" warning: the feature `impl_trait_in_bindings` is incomplete and may cause the compiler to crash --> $DIR/bound-normalization-fail.rs:6:12 | LL | #![feature(impl_trait_in_bindings)] | ^^^^^^^^^^^^^^^^^^^^^^ error[E0271]: type mismatch resolving ` as FooLike>::Output == ::Assoc` --> $DIR/bound-normalization-fail.rs:30:32 | LL | fn foo_fail() -> impl FooLike { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found associated type | = note: expected type `()` found type `::Assoc` = note: the return type of a function must have a statically known size error[E0271]: type mismatch resolving ` as FooLike>::Output == >::Assoc` --> $DIR/bound-normalization-fail.rs:47:41 | LL | fn foo2_fail<'a, T: Trait<'a>>() -> impl FooLike { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found associated type | = note: expected type `()` found type `>::Assoc` = note: the return type of a function must have a statically known size error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0271`. "} {"_id":"doc-en-rust-39b904afdd378ff36d7427ab0d6f6072e8d14cfe564ee6f854d110927bfaf4c3","title":"","text":" // check-pass // edition:2018 #![feature(async_await)] #![feature(existential_type)] #![feature(impl_trait_in_bindings)] //~^ WARNING the feature `impl_trait_in_bindings` is incomplete // See issue 60414 ///////////////////////////////////////////// // Reduction to `impl Trait` struct Foo(T); trait FooLike { type Output; } impl FooLike for Foo { type Output = T; } mod impl_trait { use super::*; trait Trait { type Assoc; } /// `T::Assoc` should be normalized to `()` here. fn foo_pass>() -> impl FooLike { Foo(()) } } ///////////////////////////////////////////// // Same with lifetimes in the trait mod lifetimes { use super::*; trait Trait<'a> { type Assoc; } /// Like above. /// /// FIXME(#51525) -- the shorter notation `T::Assoc` winds up referencing `'static` here fn foo2_pass<'a, T: Trait<'a, Assoc=()> + 'a>( ) -> impl FooLike>::Assoc> + 'a { Foo(()) } /// Normalization to type containing bound region. /// /// FIXME(#51525) -- the shorter notation `T::Assoc` winds up referencing `'static` here fn foo2_pass2<'a, T: Trait<'a, Assoc=&'a ()> + 'a>( ) -> impl FooLike>::Assoc> + 'a { Foo(&()) } } ///////////////////////////////////////////// // Reduction using `impl Trait` in bindings mod impl_trait_in_bindings { struct Foo; trait FooLike { type Output; } impl FooLike for Foo { type Output = u32; } trait Trait { type Assoc; } fn foo>() { let _: impl FooLike = Foo; } } ///////////////////////////////////////////// // The same applied to `existential type`s mod existential_types { trait Implemented { type Assoc; } impl Implemented for T { type Assoc = u8; } trait Trait { type Out; } impl Trait for () { type Out = u8; } existential type Ex: Trait::Assoc>; fn define() -> Ex { () } } fn main() {} "} {"_id":"doc-en-rust-1530bcc5a2c04dba94dd3842917b9fdf47317666cf73815aa9f4cc31844ea6c1","title":"","text":" warning: the feature `impl_trait_in_bindings` is incomplete and may cause the compiler to crash --> $DIR/bound-normalization-pass.rs:6:12 | LL | #![feature(impl_trait_in_bindings)] | ^^^^^^^^^^^^^^^^^^^^^^ "} {"_id":"doc-en-rust-311977dc66962e3e6a6e263fe17eae752ed651680cef89cd486b0c343d98446d","title":"","text":"visit::walk_generics(this, generics); // Walk the generated arguments for the `async fn`. for a in arguments { for (i, a) in arguments.iter().enumerate() { use visit::Visitor; if let Some(arg) = &a.arg { this.visit_ty(&arg.ty); } else { this.visit_ty(&decl.inputs[i].ty); } }"} {"_id":"doc-en-rust-2c7c2d2d47b4659ef0926f3032e01b9b4b9625448aec7f00cd5533878fe76407","title":"","text":" // compile-pass // edition:2018 #![feature(async_await)] // This is a regression test to ensure that simple bindings (where replacement arguments aren't // created during async fn lowering) that have their DefId used during HIR lowering (such as impl // trait) are visited during def collection and thus have a DefId. async fn foo(ws: impl Iterator) {} fn main() {} "} {"_id":"doc-en-rust-c87e56b9ec5932fc5ed1ab6882ae354a1ea1ed29f99a26a336848953eab95f26","title":"","text":"if !fail { return None; } bug!(\"unexpected const parent path def {:?}\", x); tcx.sess.delay_span_bug( DUMMY_SP, &format!( \"unexpected const parent path def {:?}\", x ), ); tcx.types.err } } }"} {"_id":"doc-en-rust-e3aca3629cb79476ab44ed412b8d6e3e0358ade864bfbcc9e4ae073a809604f6","title":"","text":"if !fail { return None; } bug!(\"unexpected const parent path {:?}\", x); tcx.sess.delay_span_bug( DUMMY_SP, &format!( \"unexpected const parent path {:?}\", x ), ); tcx.types.err } } }"} {"_id":"doc-en-rust-db81a1c26ac25aac70c3ce011770327849ed73264a44b2dd7ae807be7239af72","title":"","text":"if !fail { return None; } bug!(\"unexpected const parent in type_of_def_id(): {:?}\", x); tcx.sess.delay_span_bug( DUMMY_SP, &format!( \"unexpected const parent in type_of_def_id(): {:?}\", x ), ); tcx.types.err } } }"} {"_id":"doc-en-rust-626559eb02689c187aba1f0140e4bfcf5a4b68a2bf73ec33a51c148f6d4a9afa","title":"","text":" #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash // We should probably be able to infer the types here. However, this test is checking that we don't // get an ICE in this case. It may be modified later to not be an error. struct Foo(pub [u8; NUM_BYTES]); fn main() { let _ = Foo::<3>([1, 2, 3]); //~ ERROR type annotations needed } "} {"_id":"doc-en-rust-4e0475c61ae6004c2ed012dbf18f3e83b516568b67f33a77afc0e54ea4274e20","title":"","text":" warning: the feature `const_generics` is incomplete and may cause the compiler to crash --> $DIR/cannot-infer-type-for-const-param.rs:1:12 | LL | #![feature(const_generics)] | ^^^^^^^^^^^^^^ error[E0282]: type annotations needed --> $DIR/cannot-infer-type-for-const-param.rs:10:19 | LL | let _ = Foo::<3>([1, 2, 3]); | ^ cannot infer type for `{integer}` error: aborting due to previous error For more information about this error, try `rustc --explain E0282`. "} {"_id":"doc-en-rust-1e1dfbad1ab9acf8abb0446035681f29f8b6d050640f182b063c4836daa91a62","title":"","text":" use std::convert::TryInto; struct S; fn main() { let _: u32 = 5i32.try_into::<32>().unwrap(); //~ ERROR wrong number of const arguments S.f::<0>(); //~ ERROR no method named `f` S::<0>; //~ ERROR wrong number of const arguments } "} {"_id":"doc-en-rust-b8ecddd76d1eec430f123f0f1f5941a8ea8f4b8b63cd710b11c2b83d27c11f3c","title":"","text":" error[E0107]: wrong number of const arguments: expected 0, found 1 --> $DIR/invalid-const-arg-for-type-param.rs:6:34 | LL | let _: u32 = 5i32.try_into::<32>().unwrap(); | ^^ unexpected const argument error[E0599]: no method named `f` found for type `S` in the current scope --> $DIR/invalid-const-arg-for-type-param.rs:7:7 | LL | struct S; | --------- method `f` not found for this ... LL | S.f::<0>(); | ^ error[E0107]: wrong number of const arguments: expected 0, found 1 --> $DIR/invalid-const-arg-for-type-param.rs:8:9 | LL | S::<0>; | ^ unexpected const argument error: aborting due to 3 previous errors Some errors have detailed explanations: E0107, E0599. For more information about an error, try `rustc --explain E0107`. "} {"_id":"doc-en-rust-c5beaf5f28f5c6401015158a6a491b8e351d6e2cfb8af85e7b7b54a408d95577","title":"","text":"/// Given that a [`panic!`] will call `drop` as it unwinds, any [`panic!`] /// in a `drop` implementation will likely abort. /// /// Note that even if this panics, the value is considered to be dropped; /// you must not cause `drop` to be called again. This is normally automatically /// handled by the compiler, but when using unsafe code, can sometimes occur /// unintentionally, particularly when using [`std::ptr::drop_in_place`]. /// /// [E0040]: ../../error-index.html#E0040 /// [`panic!`]: ../macro.panic.html /// [`std::mem::drop`]: ../../std/mem/fn.drop.html /// [`std::ptr::drop_in_place`]: ../../std/ptr/fn.drop_in_place.html #[stable(feature = \"rust1\", since = \"1.0.0\")] fn drop(&mut self); }"} {"_id":"doc-en-rust-5372cd56f544c742d10517ca9261e76618481bfa4f3aeec1e118f1d9241cd6ca","title":"","text":"/// extract function takes three arguments: a string slice containing the source, an index in /// the slice for the beginning of the span and an index in the slice for the end of the span. fn span_to_source(&self, sp: Span, extract_source: F) -> Result where F: Fn(&str, usize, usize) -> String where F: Fn(&str, usize, usize) -> Result { if sp.lo() > sp.hi() { return Err(SpanSnippetError::IllFormedSpan(sp));"} {"_id":"doc-en-rust-6f937f2bff4e4aeb8f6177e2274b3d851ad0a1e622d0db203eb4d2b93077083d","title":"","text":"} if let Some(ref src) = local_begin.sf.src { return Ok(extract_source(src, start_index, end_index)); return extract_source(src, start_index, end_index); } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() { return Ok(extract_source(src, start_index, end_index)); return extract_source(src, start_index, end_index); } else { return Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone()"} {"_id":"doc-en-rust-47826f27899f6e4cca1449ecea3aef4b40c2eeee2d6086c7a142629db4af66ad","title":"","text":"/// Returns the source snippet as `String` corresponding to the given `Span` pub fn span_to_snippet(&self, sp: Span) -> Result { self.span_to_source(sp, |src, start_index, end_index| src[start_index..end_index] .to_string()) self.span_to_source(sp, |src, start_index, end_index| src.get(start_index..end_index) .map(|s| s.to_string()) .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))) } pub fn span_to_margin(&self, sp: Span) -> Option {"} {"_id":"doc-en-rust-d3e63a90aa0ae85c34303be2c2373c0fde07fe06ceb7a543ba73c54323816973","title":"","text":"/// Returns the source snippet as `String` before the given `Span` pub fn span_to_prev_source(&self, sp: Span) -> Result { self.span_to_source(sp, |src, start_index, _| src[..start_index].to_string()) self.span_to_source(sp, |src, start_index, _| src.get(..start_index) .map(|s| s.to_string()) .ok_or_else(|| SpanSnippetError::IllFormedSpan(sp))) } /// Extend the given `Span` to just after the previous occurrence of `c`. Return the same span"} {"_id":"doc-en-rust-59a357a72eccc3ef5006be3aed277088178cbcdb60900c8fde680428d7b54904","title":"","text":" struct X {} fn main() { vec![X]; //… //~^ ERROR expected value, found struct `X` } "} {"_id":"doc-en-rust-5302f342feb7fdda5a5536b1bf1f8ac201a6d12ce39f56555eee72599b28e57a","title":"","text":" error[E0423]: expected value, found struct `X` --> $DIR/issue-61226.rs:3:10 | LL | vec![X]; //… | ^ did you mean `X { /* fields */ }`? error: aborting due to previous error For more information about this error, try `rustc --explain E0423`. "} {"_id":"doc-en-rust-ecafaef8f17adf0ba19d28c2f2701b1396e3f1aeb46e4dd789f25255097d68ac","title":"","text":"return None } None => { if !tcx.sess.has_errors() { if !tcx.sess.has_errors_or_delayed_span_bugs() { bug!(\"try_mark_previous_green() - Forcing the DepNode should have set its color\") } else { // If the query we just forced has resulted // in some kind of compilation error, we // don't expect that the corresponding // dep-node color has been updated. // If the query we just forced has resulted in // some kind of compilation error, we cannot rely on // the dep-node color having been properly updated. // This means that the query system has reached an // invalid state. We let the compiler continue (by // returning `None`) so it can emit error messages // and wind down, but rely on the fact that this // invalid state will not be persisted to the // incremental compilation cache because of // compilation errors being present. debug!(\"try_mark_previous_green({:?}) - END - dependency {:?} resulted in compilation error\", dep_node, dep_dep_node); return None } } }"} {"_id":"doc-en-rust-c030566be5a89720ea8f11f8e8a076420a81baf46227e2719d2ed716b0c55121","title":"","text":" // revisions: rpass cfail enum A { //[cfail]~^ ERROR 3:1: 3:7: recursive type `A` has infinite size [E0072] B(C), } #[cfg(rpass)] struct C(Box); #[cfg(cfail)] struct C(A); //[cfail]~^ ERROR 12:1: 12:13: recursive type `C` has infinite size [E0072] fn main() {} "} {"_id":"doc-en-rust-e28e502e3060866e8a02973b53dc0aee3eb5b9ff468bac7de250f82ef75d410a","title":"","text":" #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash pub struct MyArray([u8; COUNT + 1]); //~^ ERROR constant expression depends on a generic parameter impl MyArray { fn inner(&self) -> &[u8; COUNT + 1] { //~^ ERROR constant expression depends on a generic parameter &self.0 } } fn main() {} "} {"_id":"doc-en-rust-2a6e46a8e2b77eb3e5351d2934ae7df109b0b2fe15df99be2f240e66a9c89b87","title":"","text":" warning: the feature `const_generics` is incomplete and may cause the compiler to crash --> $DIR/issue-61522-array-len-succ.rs:1:12 | LL | #![feature(const_generics)] | ^^^^^^^^^^^^^^ | = note: `#[warn(incomplete_features)]` on by default error: constant expression depends on a generic parameter --> $DIR/issue-61522-array-len-succ.rs:4:40 | LL | pub struct MyArray([u8; COUNT + 1]); | ^^^^^^^^^^^^^^^ | = note: this may fail depending on what value the parameter takes error: constant expression depends on a generic parameter --> $DIR/issue-61522-array-len-succ.rs:8:24 | LL | fn inner(&self) -> &[u8; COUNT + 1] { | ^^^^^^^^^^^^^^^^ | = note: this may fail depending on what value the parameter takes error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-a0ab9c47fbdc1908e4dae5dc9832a16123a45027d23a35b6ce10fa670665ea37","title":"","text":" // check-pass #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash trait Trait { type Assoc; } impl Trait<\"0\"> for () { type Assoc = (); } fn main() { let _: <() as Trait<\"0\">>::Assoc = (); } "} {"_id":"doc-en-rust-a4fbcfca97d42145b8924ca710ee5542b5acd08a9643210949eb1a70dacd9206","title":"","text":" warning: the feature `const_generics` is incomplete and may cause the compiler to crash --> $DIR/issue-66596-impl-trait-for-str-const-arg.rs:3:12 | LL | #![feature(const_generics)] | ^^^^^^^^^^^^^^ | = note: `#[warn(incomplete_features)]` on by default "} {"_id":"doc-en-rust-a57874f691d537721726e265e86b6786670faa624f6f732c3f916a01d9542cd1","title":"","text":"And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust. The enforcement policies listed above apply to all official Rust venues; including official IRC channels (#rust, #rust-internals, #rust-tools, #rust-libs, #rustc, #rust-beginners, #rust-docs, #rust-community, #rust-lang, and #cargo); GitHub repositories under rust-lang, rust-lang-nursery, and rust-lang-deprecated; and all forums under rust-lang.org (users.rust-lang.org, internals.rust-lang.org). For other projects adopting the Rust Code of Conduct, please contact the maintainers of those projects for enforcement. If you wish to use this code of conduct for your own project, consider explicitly mentioning your moderation policy or making a copy with your own moderation policy so as to avoid confusion. The enforcement policies listed above apply to all official Rust venues; including all communication channels (Rust Discord server, Rust Zulip server); GitHub repositories under rust-lang, rust-lang-nursery, and rust-lang-deprecated; and all forums under rust-lang.org (users.rust-lang.org, internals.rust-lang.org). For other projects adopting the Rust Code of Conduct, please contact the maintainers of those projects for enforcement. If you wish to use this code of conduct for your own project, consider explicitly mentioning your moderation policy or making a copy with your own moderation policy so as to avoid confusion. *Adapted from the [Node.js Policy on Trolling](https://blog.izs.me/2012/08/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).*"} {"_id":"doc-en-rust-5099a583a358753ed5a465142995fb817b0d632efc334262abd0701583aac178","title":"","text":"* [Helpful Links and Information](#helpful-links-and-information) If you have questions, please make a post on [internals.rust-lang.org][internals] or hop on the [Rust Discord server][rust-discord], [Rust Zulip server][rust-zulip] or [#rust-internals][pound-rust-internals]. hop on the [Rust Discord server][rust-discord] or [Rust Zulip server][rust-zulip]. As a reminder, all contributors are expected to follow our [Code of Conduct][coc]."} {"_id":"doc-en-rust-1804033c9d6636cf88be62663cde10cd093390163995fc52c50e43ca393c91b4","title":"","text":"If this is your first time contributing, the [walkthrough] chapter of the guide can give you a good example of how a typical contribution would go. [pound-rust-internals]: https://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-internals [internals]: https://internals.rust-lang.org [rust-discord]: http://discord.gg/rust-lang [rust-zulip]: https://rust-lang.zulipchat.com"} {"_id":"doc-en-rust-10b5ac686e8f802a26a38a02193928e840163b24298885787cb30d759f10ce73","title":"","text":"There are a number of other ways to contribute to Rust that don't deal with this repository. Answer questions in [#rust][pound-rust], or on [users.rust-lang.org][users], Answer questions in the _Get Help!_ channels from the [Rust Discord server][rust-discord], on [users.rust-lang.org][users], or on [StackOverflow][so]. Participate in the [RFC process](https://github.com/rust-lang/rfcs)."} {"_id":"doc-en-rust-c41f56b6ad926145a2d84de5fb8f667bc818a3e5d8c8d229e2b9a018972a01f9","title":"","text":"it to [Crates.io](http://crates.io). Easier said than done, but very, very valuable! [pound-rust]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust [rust-discord]: https://discord.gg/rust-lang [users]: https://users.rust-lang.org/ [so]: http://stackoverflow.com/questions/tagged/rust [community-library]: https://github.com/rust-lang/rfcs/labels/A-community-library"} {"_id":"doc-en-rust-d0f0e6798d568287c567e0aaa98d279bbcd98e275bfa44fc1aada47bdd87488d","title":"","text":"To contribute to Rust, please see [CONTRIBUTING](CONTRIBUTING.md). Rust has an [IRC] culture and most real-time collaboration happens in a variety of channels on Mozilla's IRC network, irc.mozilla.org. The most popular channel is [#rust], a venue for general discussion about Rust. And a good place to ask for help would be [#rust-beginners]. Most real-time collaboration happens in a variety of channels on the [Rust Discord server][rust-discord], with channels dedicated for getting help, community, documentation, and all major contribution areas in the Rust ecosystem. A good place to ask for help would be the #help channel. The [rustc guide] might be a good place to start if you want to find out how various parts of the compiler work. Also, you may find the [rustdocs for the compiler itself][rustdocs] useful. [IRC]: https://en.wikipedia.org/wiki/Internet_Relay_Chat [#rust]: irc://irc.mozilla.org/rust [#rust-beginners]: irc://irc.mozilla.org/rust-beginners [rust-discord]: https://discord.gg/rust-lang [rustc guide]: https://rust-lang.github.io/rustc-guide/about-this-guide.html [rustdocs]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/"} {"_id":"doc-en-rust-2a95e00d5737ea884f708f2a3bead5b091e6b9ee745c50506b31c2ac100ea214","title":"","text":"`Config` struct. * Adding a sanity check? Take a look at `bootstrap/sanity.rs`. If you have any questions feel free to reach out on `#rust-infra` on IRC or ask on internals.rust-lang.org. When you encounter bugs, please file issues on the rust-lang/rust issue tracker. If you have any questions feel free to reach out on `#infra` channel in the [Rust Discord server][rust-discord] or ask on internals.rust-lang.org. When you encounter bugs, please file issues on the rust-lang/rust issue tracker. [rust-discord]: https://discord.gg/rust-lang "} {"_id":"doc-en-rust-96d1470c33090bd5bd857da6e31c33c2893b69f474ee44be571201eb02d450b9","title":"","text":"[[package]] name = \"directories\" version = \"1.0.2\" version = \"2.0.1\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)\", \"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)\", \"cfg-if 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)\", \"dirs-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]]"} {"_id":"doc-en-rust-161a5b1df5f7dce910b5ad118d395316e0a3eed083e180cafc907bef8678f33b","title":"","text":"] [[package]] name = \"dirs-sys\" version = \"0.3.3\" source = \"registry+https://github.com/rust-lang/crates.io-index\" dependencies = [ \"cfg-if 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)\", \"libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)\", \"redox_users 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)\", \"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)\", ] [[package]] name = \"dlmalloc\" version = \"0.1.3\" source = \"registry+https://github.com/rust-lang/crates.io-index\""} {"_id":"doc-en-rust-d9be40c5089d302fa0ac29a9afa976c3fba508518a68af810af36aa389b2b547","title":"","text":"version = \"0.1.0\" dependencies = [ \"byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)\", \"cargo_metadata 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)\", \"cargo_metadata 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)\", \"colored 1.6.0 (registry+https://github.com/rust-lang/crates.io-index)\", \"compiletest_rs 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)\", \"directories 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)\", \"directories 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)\", \"env_logger 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)\", \"hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)\", \"log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)\","} {"_id":"doc-en-rust-aa553445cd4cc5b270fa029388525394c3e2ec78f39e2a72a2fae1a3fcbd518c","title":"","text":"\"checksum diff 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)\" = \"3c2b69f912779fbb121ceb775d74d51e915af17aaebc38d28a592843a2dd0a3a\" \"checksum difference 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198\" \"checksum digest 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)\" = \"03b072242a8cbaf9c145665af9d250c59af3b958f83ed6824e13533cf76d5b90\" \"checksum directories 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)\" = \"72d337a64190607d4fcca2cb78982c5dd57f4916e19696b48a575fa746b6cb0f\" \"checksum directories 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)\" = \"2ccc83e029c3cebb4c8155c644d34e3a070ccdb4ff90d369c74cd73f7cb3c984\" \"checksum dirs 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)\" = \"3fd78930633bd1c6e35c4b42b1df7b0cbc6bc191146e512bb3bedf243fcc3901\" \"checksum dirs-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"937756392ec77d1f2dd9dc3ac9d69867d109a2121479d72c364e42f4cab21e2d\" \"checksum dlmalloc 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)\" = \"f283302e035e61c23f2b86b3093e8c6273a4c3125742d6087e96ade001ca5e63\" \"checksum either 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)\" = \"3be565ca5c557d7f59e7cfcf1844f9e3033650c929c6566f511e8005f205c1d0\" \"checksum elasticlunr-rs 2.3.4 (registry+https://github.com/rust-lang/crates.io-index)\" = \"a99a310cd1f9770e7bf8e48810c7bcbb0e078c8fb23a8c7bcf0da4c2bf61a455\""} {"_id":"doc-en-rust-75ab21664fa191fa046ef74eb1f6134bf51bfa942f0a64756efd0f3375344bd0","title":"","text":" Subproject commit e1a0f66373a1a185334a6e3be24e94161e3b4a43 Subproject commit 965160d4d7976ddead182b4a65b73f59818537de "} {"_id":"doc-en-rust-afe4c045b51c5b8120c5ddde09ec0cf72d057bcf10954fc3b08d721bf2359390","title":"","text":"self.ty_inhabitedness_forest(ty).contains(self, module) } pub fn is_ty_uninhabited_from_all_modules(self, ty: Ty<'tcx>) -> bool { pub fn is_ty_uninhabited_from_any_module(self, ty: Ty<'tcx>) -> bool { !self.ty_inhabitedness_forest(ty).is_empty() }"} {"_id":"doc-en-rust-f5445190239ad17007c7ab3509c4ac7bb939b5b8defa14d41631d89f06cf6bad","title":"","text":")); } } else { let callee_layout = self.layout_of_local(self.frame(), mir::RETURN_PLACE, None)?; if !callee_layout.abi.is_uninhabited() { return err!(FunctionRetMismatch( self.tcx.types.never, callee_layout.ty )); let local = mir::RETURN_PLACE; let ty = self.frame().body.local_decls[local].ty; if !self.tcx.is_ty_uninhabited_from_any_module(ty) { return err!(FunctionRetMismatch(self.tcx.types.never, ty)); } } Ok(())"} {"_id":"doc-en-rust-f8798d9b8dd7bd906a093434b359ba7ecbb2f672d162766ed6294548b368f531","title":"","text":" // compile-fail pub const unsafe fn fake_type() -> T { hint_unreachable() } pub const unsafe fn hint_unreachable() -> ! { fake_type() //~ ERROR any use of this value will cause an error } trait Const { const CONSTANT: i32 = unsafe { fake_type() }; } impl Const for T {} pub fn main() -> () { dbg!(i32::CONSTANT); //~ ERROR erroneous constant used } "} {"_id":"doc-en-rust-0c49a2147dfd852d70e95b59ffcb1d26ac93763588fe5ef8402444d2d7616a64","title":"","text":" error: any use of this value will cause an error --> $DIR/uninhabited-const-issue-61744.rs:8:5 | LL | fake_type() | ^^^^^^^^^^^ | | | tried to call a function with return type T passing return place of type ! | inside call to `hint_unreachable` at $DIR/uninhabited-const-issue-61744.rs:4:5 | inside call to `fake_type::` at $DIR/uninhabited-const-issue-61744.rs:12:36 ... LL | const CONSTANT: i32 = unsafe { fake_type() }; | --------------------------------------------- | = note: #[deny(const_err)] on by default error[E0080]: erroneous constant used --> $DIR/uninhabited-const-issue-61744.rs:18:10 | LL | dbg!(i32::CONSTANT); | ^^^^^^^^^^^^^ referenced constant has errors error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-3be0e84e7ed2c38d37d4c5edf7abda576a4db52d328d48949d8d3217d89c03bd","title":"","text":"let span = self.tcx.def_span(generator_did); // Do not ICE on closure typeck (#66868). if let None = self.tcx.hir().as_local_hir_id(generator_did) { if self.tcx.hir().as_local_hir_id(generator_did).is_none() { return false; }"} {"_id":"doc-en-rust-0d2db88d39079580df872c71dd0304f0ddeabe63f77471176bd14c9dbf454d62","title":"","text":" // check-pass #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash struct Const; impl Const<{C}> { fn successor() -> Const<{C + 1}> { Const } } fn main() { let _x: Const::<2> = Const::<1>::successor(); } "} {"_id":"doc-en-rust-fa68ecb97ce3f9dcecd3bfdc79b7c2009c563852b7513531b238a0d9eec11323","title":"","text":" warning: the feature `const_generics` is incomplete and may cause the compiler to crash --> $DIR/issue-61747.rs:3:12 | LL | #![feature(const_generics)] | ^^^^^^^^^^^^^^ | = note: `#[warn(incomplete_features)]` on by default "} {"_id":"doc-en-rust-ddaf30d2c982b2de2e46294c9a35e3f2819953dc3984c1a9ebdfe742e6a47220","title":"","text":" // check-pass #![allow(incomplete_features, dead_code, unconditional_recursion)] #![feature(const_generics)] fn fact() { fact::<{ N - 1 }>(); } fn main() {} "} {"_id":"doc-en-rust-da3dbe122f84857d7f7aff830919e557b501f4fe1b66b4bbe6871515eab92d58","title":"","text":" // Fixed by #67160 trait Trait1 { type A; } trait Trait2 { type Type1: Trait1; //~^ ERROR: generic associated types are unstable //~| ERROR: type-generic associated types are not yet implemented } fn main() {} "} {"_id":"doc-en-rust-5ffcffe42151dd0dc622c16b11bfce0119cac406e2af476cb4e74b9c96bce2d1","title":"","text":" error[E0658]: generic associated types are unstable --> $DIR/issue-67424.rs:8:5 | LL | type Type1: Trait1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = 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: type-generic associated types are not yet implemented --> $DIR/issue-67424.rs:8:5 | LL | type Type1: Trait1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/44265 error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0658`. "} {"_id":"doc-en-rust-77050b7191609d0a59c19f7fa22db3f8c03eb34e5c3fb46bcc1506bdf36edfc4","title":"","text":" // Regression test for #66270, fixed by #66246 struct Bug { incorrect_field: 0, //~^ ERROR expected type } struct Empty {} fn main() { let Bug { any_field: Empty {}, } = Bug {}; } "} {"_id":"doc-en-rust-5b0ead9168c04aad0c10d9e46f34e2e835a5baaa702931766497750f7acfab09","title":"","text":" error: expected type, found `0` --> $DIR/issue-66270-pat-struct-parser-recovery.rs:4:22 | LL | incorrect_field: 0, | ^ expected type error: aborting due to previous error "} {"_id":"doc-en-rust-fb18e966c81a82b65c8911b19144e4414e3c22666f0e6e6fc5ebf504af45fade","title":"","text":"err.note(\"try using `<*const T>::as_ref()` to get a reference to the type behind the pointer: https://doc.rust-lang.org/std/ primitive.pointer.html#method.as_ref\"); err.note(\"using `<*const T>::as_ref()` on a pointer which is unaligned or points to invalid or uninitialized memory is undefined behavior\"); } err }"} {"_id":"doc-en-rust-aa005eae0c876a47c46e3670071e47c7e5b4429ae9961bbb7a0291eb797a6f5f","title":"","text":"| ^^^^^^^^^ | = note: try using `<*const T>::as_ref()` to get a reference to the type behind the pointer: https://doc.rust-lang.org/std/primitive.pointer.html#method.as_ref = note: using `<*const T>::as_ref()` on a pointer which is unaligned or points to invalid or uninitialized memory is undefined behavior = note: the method `to_string` exists but the following trait bounds were not satisfied: `*const u8 : std::string::ToString`"} {"_id":"doc-en-rust-c75fde32cd4e6d26ae04f2f9294a1b2e49957d483f147f26f6f2002dcd7b2d18","title":"","text":"(Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shallow) | (Reservation(WriteKind::MutableBorrow(bk)), BorrowKind::Shared) if { tcx.migrate_borrowck() tcx.migrate_borrowck() && this.borrow_set.location_map.contains_key(&location) } => { let bi = this.borrow_set.location_map[&location]; debug!("} {"_id":"doc-en-rust-84b7391ba619e3c7cfca1391d25670ab023d85112f2af3a359944738a27be20f","title":"","text":" fn f1<'a>(_: &'a mut ()) {} fn f2

    (_: P, _: ()) {} fn f3<'a>(x: &'a ((), &'a mut ())) { f2(|| x.0, f1(x.1)) //~^ ERROR cannot borrow `*x.1` as mutable, as it is behind a `&` reference //~| ERROR cannot borrow `*x.1` as mutable because it is also borrowed as immutable } fn main() {} "} {"_id":"doc-en-rust-fe7992e3e223308d52a9545fce55d624eb40ac93b52f18b1b19690a1ef4ed655","title":"","text":" error[E0596]: cannot borrow `*x.1` as mutable, as it is behind a `&` reference --> $DIR/issue-61623.rs:6:19 | LL | fn f3<'a>(x: &'a ((), &'a mut ())) { | -------------------- help: consider changing this to be a mutable reference: `&'a mut ((), &'a mut ())` LL | f2(|| x.0, f1(x.1)) | ^^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable error[E0502]: cannot borrow `*x.1` as mutable because it is also borrowed as immutable --> $DIR/issue-61623.rs:6:19 | LL | f2(|| x.0, f1(x.1)) | -- -- - ^^^ mutable borrow occurs here | | | | | | | first borrow occurs due to use of `x` in closure | | immutable borrow occurs here | immutable borrow later used by call error: aborting due to 2 previous errors Some errors have detailed explanations: E0502, E0596. For more information about an error, try `rustc --explain E0502`. "} {"_id":"doc-en-rust-546c5fb5eb1a48fba3f54e051cde4415cad0450dce16c6153cab30f0e29e5a85","title":"","text":"} fn maybe_lint_bare_trait(&self, span: Span, id: NodeId, is_global: bool) { self.sess.buffer_lint_with_diagnostic( builtin::BARE_TRAIT_OBJECTS, id, span, \"trait objects without an explicit `dyn` are deprecated\", builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global), ) // FIXME(davidtwco): This is a hack to detect macros which produce spans of the // call site which do not have a macro backtrace. See #61963. let is_macro_callsite = self.sess.source_map() .span_to_snippet(span) .map(|snippet| snippet.starts_with(\"#[\")) .unwrap_or(true); if !is_macro_callsite { self.sess.buffer_lint_with_diagnostic( builtin::BARE_TRAIT_OBJECTS, id, span, \"trait objects without an explicit `dyn` are deprecated\", builtin::BuiltinLintDiagnostics::BareTraitObject(span, is_global), ) } } fn wrap_in_try_constructor("} {"_id":"doc-en-rust-ccacac1d35e5af7ba5f1796a2c1d0e16c166b5a03afbe8582919e39a089ffc49","title":"","text":" // force-host // no-prefer-dynamic #![crate_type = \"proc-macro\"] extern crate proc_macro; use proc_macro::{Group, TokenStream, TokenTree}; // This macro exists as part of a reproduction of #61963 but without using quote/syn/proc_macro2. #[proc_macro_derive(DomObject)] pub fn expand_token_stream(input: TokenStream) -> TokenStream { // Construct a dummy span - `#0 bytes(0..0)` - which is present in the input because // of the specially crafted generated tokens in the `attribute-crate` proc-macro. let dummy_span = input.clone().into_iter().nth(0).unwrap().span(); // Define what the macro would output if constructed properly from the source using syn/quote. let output: TokenStream = \"impl Bar for ((), Qux >) { } impl Bar for ((), Box) { }\".parse().unwrap(); let mut tokens: Vec<_> = output.into_iter().collect(); // Adjust token spans to match the original crate (which would use `quote`). Some of the // generated tokens point to the dummy span. for token in tokens.iter_mut() { if let TokenTree::Group(group) = token { let mut tokens: Vec<_> = group.stream().into_iter().collect(); for token in tokens.iter_mut().skip(2) { token.set_span(dummy_span); } let mut stream = TokenStream::new(); stream.extend(tokens); *group = Group::new(group.delimiter(), stream); } } let mut output = TokenStream::new(); output.extend(tokens); output } "} {"_id":"doc-en-rust-e75013aedfb72fa8294f0a245641754215c14356e3eca42f3786d726e179334c","title":"","text":" // force-host // no-prefer-dynamic #![crate_type = \"proc-macro\"] extern crate proc_macro; use proc_macro::{Group, Spacing, Punct, TokenTree, TokenStream}; // This macro exists as part of a reproduction of #61963 but without using quote/syn/proc_macro2. #[proc_macro_attribute] pub fn dom_struct(_: TokenStream, input: TokenStream) -> TokenStream { // Construct the expected output tokens - the input but with a `#[derive(DomObject)]` applied. let attributes: TokenStream = \"#[derive(DomObject)]\".to_string().parse().unwrap(); let output: TokenStream = attributes.into_iter() .chain(input.into_iter()).collect(); let mut tokens: Vec<_> = output.into_iter().collect(); // Adjust the spacing of `>` tokens to match what `quote` would produce. for token in tokens.iter_mut() { if let TokenTree::Group(group) = token { let mut tokens: Vec<_> = group.stream().into_iter().collect(); for token in tokens.iter_mut() { if let TokenTree::Punct(p) = token { if p.as_char() == '>' { *p = Punct::new('>', Spacing::Alone); } } } let mut stream = TokenStream::new(); stream.extend(tokens); *group = Group::new(group.delimiter(), stream); } } let mut output = TokenStream::new(); output.extend(tokens); output } "} {"_id":"doc-en-rust-0440909e1e72289fc26744bc626f8d668347b04c26a55fdc64b796bff058369c","title":"","text":" // aux-build:issue-61963.rs // aux-build:issue-61963-1.rs #![deny(bare_trait_objects)] #[macro_use] extern crate issue_61963; #[macro_use] extern crate issue_61963_1; // This test checks that the bare trait object lint does not trigger on macro attributes that // generate code which would trigger the lint. pub struct Baz; pub trait Bar { } pub struct Qux(T); #[dom_struct] pub struct Foo { qux: Qux>, bar: Box, //~^ ERROR trait objects without an explicit `dyn` are deprecated [bare_trait_objects] } fn main() {} "} {"_id":"doc-en-rust-339bfca84b1d788d05b5318bd9b4c5dab834c666401e5c1a48e8be85347bfb7c","title":"","text":" error: trait objects without an explicit `dyn` are deprecated --> $DIR/issue-61963.rs:20:14 | LL | bar: Box, | ^^^ help: use `dyn`: `dyn Bar` | note: lint level defined here --> $DIR/issue-61963.rs:3:9 | LL | #![deny(bare_trait_objects)] | ^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-2c5d7cf0546089045d1f053c120d5089c9e334f66911e50a09c0a0d1db3998c6","title":"","text":"if !is_prelude && max_vis.get() != ty::Visibility::Invisible && // Allow empty globs. !max_vis.get().is_at_least(directive.vis.get(), &*self) { let msg = \"A non-empty glob must import something with the glob's visibility\"; self.r.session.span_err(directive.span, msg); let msg = \"glob import doesn't reexport anything because no candidate is public enough\"; self.r.session.buffer_lint(UNUSED_IMPORTS, directive.id, directive.span, msg); } return None; }"} {"_id":"doc-en-rust-e100dd78abc083f99e66cd3ac0c9591f2b0b96176704402301cfab74c05b5dd1","title":"","text":" #![warn(unused_imports)] mod a { fn foo() {} mod foo {} mod a { pub use super::foo; //~ ERROR cannot be re-exported pub use super::*; //~ ERROR must import something with the glob's visibility pub use super::*; //~^ WARNING glob import doesn't reexport anything because no candidate is public enough } } mod b { pub fn foo() {} mod foo { pub struct S; } mod foo { pub struct S; } pub mod a { pub use super::foo; // This is OK since the value `foo` is visible enough."} {"_id":"doc-en-rust-e81bc549430bcc4da8e18c8aa6bb033c4c640f47e1e25f50f8a0eb25392cc441","title":"","text":"error[E0364]: `foo` is private, and cannot be re-exported --> $DIR/reexports.rs:6:17 --> $DIR/reexports.rs:8:17 | LL | pub use super::foo; | ^^^^^^^^^^ | note: consider marking `foo` as `pub` in the imported module --> $DIR/reexports.rs:6:17 --> $DIR/reexports.rs:8:17 | LL | pub use super::foo; | ^^^^^^^^^^ error: A non-empty glob must import something with the glob's visibility --> $DIR/reexports.rs:7:17 | LL | pub use super::*; | ^^^^^^^^ error[E0603]: module `foo` is private --> $DIR/reexports.rs:28:15 --> $DIR/reexports.rs:33:15 | LL | use b::a::foo::S; | ^^^ error[E0603]: module `foo` is private --> $DIR/reexports.rs:29:15 --> $DIR/reexports.rs:34:15 | LL | use b::b::foo::S as T; | ^^^ error: aborting due to 4 previous errors warning: glob import doesn't reexport anything because no candidate is public enough --> $DIR/reexports.rs:9:17 | LL | pub use super::*; | ^^^^^^^^ | note: lint level defined here --> $DIR/reexports.rs:1:9 | LL | #![warn(unused_imports)] | ^^^^^^^^^^^^^^ error: aborting due to 3 previous errors Some errors have detailed explanations: E0364, E0603. For more information about an error, try `rustc --explain E0364`."} {"_id":"doc-en-rust-86704df67fbee7a75598b4ec01e5e5e9edae516161ee71f94318a14fe2ec230c","title":"","text":"COPY host-x86_64/dist-x86_64-linux/build-binutils.sh /tmp/ RUN ./build-binutils.sh # libssh2 (a dependency of Cargo) requires cmake 2.8.11 or higher but CentOS # only has 2.6.4, so build our own COPY host-x86_64/dist-x86_64-linux/build-cmake.sh /tmp/ RUN ./build-cmake.sh # Need a newer version of gcc than centos has to compile LLVM nowadays # Need at least GCC 5.1 to compile LLVM nowadays COPY host-x86_64/dist-x86_64-linux/build-gcc.sh /tmp/ RUN ./build-gcc.sh RUN ./build-gcc.sh && apt-get remove -y gcc g++ # CentOS 5.5 has Python 2.4 by default, but LLVM needs 2.7+ # 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 # Now build LLVM+Clang 7, afterwards configuring further compilations to use the # 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 # Now build LLVM+Clang, afterwards configuring further compilations to use the # clang/clang++ compilers. COPY host-x86_64/dist-x86_64-linux/build-clang.sh host-x86_64/dist-x86_64-linux/llvm-project-centos.patch /tmp/ COPY host-x86_64/dist-x86_64-linux/build-clang.sh /tmp/ RUN ./build-clang.sh ENV CC=clang CXX=clang++ # Apparently CentOS 5.5 desn't have `git` in yum, but we're gonna need it for # cloning, so download and build it here. COPY host-x86_64/dist-x86_64-linux/build-git.sh /tmp/ RUN ./build-git.sh # for sanitizers, we need kernel headers files newer than the ones CentOS ships # with so we install newer ones here COPY host-x86_64/dist-x86_64-linux/build-headers.sh /tmp/ RUN ./build-headers.sh # OpenSSL requires a more recent version of perl # with so we install newer ones here COPY host-x86_64/dist-x86_64-linux/build-perl.sh /tmp/ RUN ./build-perl.sh COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh"} {"_id":"doc-en-rust-eb323ced085deef56200e4059a069ecb7dc0dfc2336e150f8ea1bbe7ac805c46","title":"","text":"# libcurl, instead it should compile its own. ENV LIBCURL_NO_PKG_CONFIG 1 # There was a bad interaction between \"old\" 32-bit binaries on current 64-bit # kernels with selinux enabled, where ASLR mmap would sometimes choose a low # address and then block it for being below `vm.mmap_min_addr` -> `EACCES`. # This is probably a kernel bug, but setting `ulimit -Hs` works around it. # See also `src/ci/run.sh` where this takes effect. ENV SET_HARD_RLIMIT_STACK 1 ENV DIST_REQUIRE_ALL_TOOLS 1"} {"_id":"doc-en-rust-b335b72fe572704d5ea3ce746b5234372c25c1a7d77b184ce379f85067b347ee","title":"","text":" FROM centos:5 # We use Debian 6 (glibc 2.11, kernel 2.6.32) as a common base for other # distros that still need Rust support: RHEL 6 (glibc 2.12, kernel 2.6.32) and # SLES 11 SP4 (glibc 2.11, kernel 3.0). FROM debian:6 WORKDIR /build # Centos 5 is EOL and is no longer available from the usual mirrors, so switch # to http://vault.centos.org/ RUN sed -i 's/enabled=1/enabled=0/' /etc/yum/pluginconf.d/fastestmirror.conf RUN sed -i 's/mirrorlist/#mirrorlist/' /etc/yum.repos.d/*.repo RUN sed -i 's|#(baseurl.*)mirror.centos.org/centos/$releasever|1vault.centos.org/5.11|' /etc/yum.repos.d/*.repo # Debian 6 is EOL and no longer available from the usual mirrors, # so we'll need to switch to http://archive.debian.org/ RUN sed -i '/updates/d' /etc/apt/sources.list && sed -i 's/httpredir/archive/' /etc/apt/sources.list RUN yum upgrade -y && yum install -y curl RUN apt-get update && apt-get install --allow-unauthenticated -y --no-install-recommends automake bzip2 ca-certificates curl file g++ g++-multilib gcc gcc-c++ gcc-multilib git lib32z1-dev libedit-dev libncurses-dev make glibc-devel patch perl zlib-devel file xz which pkgconfig pkg-config unzip wget autoconf gettext xz-utils zlib1g-dev ENV PATH=/rustroot/bin:$PATH ENV LD_LIBRARY_PATH=/rustroot/lib64:/rustroot/lib ENV LD_LIBRARY_PATH=/rustroot/lib64:/rustroot/lib32:/rustroot/lib ENV PKG_CONFIG_PATH=/rustroot/lib/pkgconfig WORKDIR /tmp RUN mkdir /home/user COPY host-x86_64/dist-x86_64-linux/shared.sh /tmp/ # We need a build of openssl which supports SNI to download artifacts from"} {"_id":"doc-en-rust-656373ef21fd754284e0e19da4ed3494db327b81ae20b0ffbb7be8f712d84cac","title":"","text":"COPY host-x86_64/dist-x86_64-linux/build-openssl.sh /tmp/ RUN ./build-openssl.sh # The `curl` binary on CentOS doesn't support SNI which is needed for fetching # The `curl` binary on Debian 6 doesn't support SNI which is needed for fetching # some https urls we have, so install a new version of libcurl + curl which is # using the openssl we just built previously. # # Note that we also disable a bunch of optional features of curl that we don't # really need. COPY host-x86_64/dist-x86_64-linux/build-curl.sh /tmp/ RUN ./build-curl.sh RUN ./build-curl.sh && apt-get remove -y curl # binutils < 2.22 has a bug where the 32-bit executables it generates # immediately segfault in Rust, so we need to install our own binutils."} {"_id":"doc-en-rust-105fee5e8cff6ca966c8e7276a2157c592068a11adf4dd26a5bbd829cba828a2","title":"","text":"COPY host-x86_64/dist-x86_64-linux/build-binutils.sh /tmp/ RUN ./build-binutils.sh # libssh2 (a dependency of Cargo) requires cmake 2.8.11 or higher but CentOS # only has 2.6.4, so build our own COPY host-x86_64/dist-x86_64-linux/build-cmake.sh /tmp/ RUN ./build-cmake.sh # Build a version of gcc capable of building LLVM 6 # Need at least GCC 5.1 to compile LLVM nowadays COPY host-x86_64/dist-x86_64-linux/build-gcc.sh /tmp/ RUN ./build-gcc.sh RUN ./build-gcc.sh && apt-get remove -y gcc g++ # CentOS 5.5 has Python 2.4 by default, but LLVM needs 2.7+ # 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 # Now build LLVM+Clang 7, afterwards configuring further compilations to use the # 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 # Now build LLVM+Clang, afterwards configuring further compilations to use the # clang/clang++ compilers. COPY host-x86_64/dist-x86_64-linux/build-clang.sh host-x86_64/dist-x86_64-linux/llvm-project-centos.patch /tmp/ COPY host-x86_64/dist-x86_64-linux/build-clang.sh /tmp/ RUN ./build-clang.sh ENV CC=clang CXX=clang++ # Apparently CentOS 5.5 desn't have `git` in yum, but we're gonna need it for # cloning, so download and build it here. COPY host-x86_64/dist-x86_64-linux/build-git.sh /tmp/ RUN ./build-git.sh # for sanitizers, we need kernel headers files newer than the ones CentOS ships # with so we install newer ones here COPY host-x86_64/dist-x86_64-linux/build-headers.sh /tmp/ RUN ./build-headers.sh # OpenSSL requires a more recent version of perl # with so we install newer ones here COPY host-x86_64/dist-x86_64-linux/build-perl.sh /tmp/ RUN ./build-perl.sh COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh"} {"_id":"doc-en-rust-a0e58996ffd8f8577fa88f608132d77e514da3cb89e702eccb49e1446ebad497","title":"","text":"curl -L https://github.com/llvm/llvm-project/archive/$LLVM.tar.gz | tar xzf - --strip-components=1 yum install -y patch patch -Np1 < ../llvm-project-centos.patch mkdir clang-build cd clang-build"} {"_id":"doc-en-rust-147951eaa9bd7cfba78e9f8c8d45cd93951bc1476e28afc0795f5c7e403b33d4","title":"","text":"set -ex source shared.sh curl https://cmake.org/files/v3.6/cmake-3.6.3.tar.gz | tar xzf - CMAKE=3.13.4 curl -L https://github.com/Kitware/CMake/releases/download/v$CMAKE/cmake-$CMAKE.tar.gz | tar xzf - mkdir cmake-build cd cmake-build hide_output ../cmake-3.6.3/configure --prefix=/rustroot hide_output ../cmake-$CMAKE/configure --prefix=/rustroot hide_output make -j10 hide_output make install cd .. rm -rf cmake-build rm -rf cmake-3.6.3 rm -rf cmake-$CMAKE "} {"_id":"doc-en-rust-7f2daa7f707e5e1ba91f4cad7dffef675dc62e149b88dab1724e7df6a36bb7b3","title":"","text":"cd .. rm -rf curl-build rm -rf curl-$VERSION yum erase -y curl "} {"_id":"doc-en-rust-803836717353ca6b73f111855c5accd5b4b473766988ba4367ddf95d70ed2ec7","title":"","text":"cd .. rm -rf gcc-build rm -rf gcc-$GCC yum erase -y gcc gcc-c++ binutils "} {"_id":"doc-en-rust-a2758b9b1e22620c729fe6690090f83f342f595604fa09e3d46d6773f68ed07e","title":"","text":"ulimit -c unlimited fi # There was a bad interaction between \"old\" 32-bit binaries on current 64-bit # kernels with selinux enabled, where ASLR mmap would sometimes choose a low # address and then block it for being below `vm.mmap_min_addr` -> `EACCES`. # This is probably a kernel bug, but setting `ulimit -Hs` works around it. # See also `dist-i686-linux` where this setting is enabled. if [ \"$SET_HARD_RLIMIT_STACK\" = \"1\" ]; then rlimit_stack=$(ulimit -Ss) if [ \"$rlimit_stack\" != \"\" ]; then ulimit -Hs \"$rlimit_stack\" fi fi ci_dir=`cd $(dirname $0) && pwd` source \"$ci_dir/shared.sh\""} {"_id":"doc-en-rust-0051d9e222ec7460cb77e01d785e60d809d54bcb87d0781d810bfd772550d23b","title":"","text":" // ignore-tidy-trailing-newlines // error-pattern: aborting due to 3 previous errors y![ Ϥ, No newline at end of file"} {"_id":"doc-en-rust-13a0b23dd939ca73db5877c491f22c487a1b50359361552b7bf0ca3fe31755e5","title":"","text":" error: this file contains an un-closed delimiter --> $DIR/issue-62524.rs:4:3 | LL | y![ | - un-closed delimiter LL | Ϥ, | ^ error: macros that expand to items must be delimited with braces or followed by a semicolon --> $DIR/issue-62524.rs:3:3 | LL | y![ | ___^ LL | | Ϥ, | |__^ | help: change the delimiters to curly braces | LL | y!{ LL | Ϥ} | help: add a semicolon | LL | Ϥ,; | ^ error: cannot find macro `y` in this scope --> $DIR/issue-62524.rs:3:1 | LL | y![ | ^ error: aborting due to 3 previous errors "} {"_id":"doc-en-rust-2a0ac92a302ae9c5a9ed5cbcbf9e6581cd6461742a90d79c034a6a0f094c0982","title":"","text":" // Ensure the asm for array comparisons is properly optimized. //@ compile-flags: -C opt-level=2 #![crate_type = \"lib\"] // CHECK-LABEL: @compare // CHECK: start: // CHECK-NEXT: ret i1 true #[no_mangle] pub fn compare() -> bool { let bytes = 12.5f32.to_ne_bytes(); bytes == if cfg!(target_endian = \"big\") { [0x41, 0x48, 0x00, 0x00] } else { [0x00, 0x00, 0x48, 0x41] } } "} {"_id":"doc-en-rust-599cb4fa2d2d9e9e135f1508626c8ef6528ae166a2cd749105e7f815292cbcd8","title":"","text":"self.tcx().mk_const( ty::Const { val: ConstValue::Infer(InferConst::Canonical(self.binder_index, var.into())), ty: const_var.ty, ty: self.fold_ty(const_var.ty), } ) }"} {"_id":"doc-en-rust-645fed82f7d7ee2824cf0ed704ddbf7e8d3a1d37cdc725f5dcc2aece03c7239f","title":"","text":" // revisions:rpass1 #![feature(const_generics)] struct Struct(T); impl Struct<[T; N]> { fn f() {} fn g() { Self::f(); } } fn main() { Struct::<[u32; 3]>::g(); } "} {"_id":"doc-en-rust-a65965e8c9699485e3f2a237cc11aa631e9853972de974b7178e6eb09fd4e0c4","title":"","text":" // revisions:rpass1 #![feature(const_generics)] struct FakeArray(T); impl FakeArray { fn len(&self) -> usize { N } } fn main() { let fa = FakeArray::(1); assert_eq!(fa.len(), 32); } "} {"_id":"doc-en-rust-4690080eee9b154292f871490000aeeee106f5decd6c41703460f5e1dac28215","title":"","text":" // revisions:cfail1 #![feature(const_generics)] //[cfail1]~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash struct S([T; N]); fn f(x: T) -> S { panic!() } fn main() { f(0u8); //[cfail1]~^ ERROR type annotations needed } "} {"_id":"doc-en-rust-9ccbdfec69736410b0efef1e8edb5e4e2fe5e6f1569f3a2cac58894ec3530891","title":"","text":" // revisions:cfail1 #![feature(const_generics)] //[cfail1]~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash fn combinator() -> [T; S] {} //[cfail1]~^ ERROR mismatched types fn main() { combinator().into_iter(); //[cfail1]~^ ERROR type annotations needed } "} {"_id":"doc-en-rust-f7b8611a02b3212a29dbf707d4cddcbdf5aca4bc10aa54aab501a564844094bd","title":"","text":" // revisions:rpass1 #![feature(const_generics)] pub struct Foo([T; 0]); impl Foo { pub fn new() -> Self { Foo([]) } } fn main() { let _: Foo = Foo::new(); } "} {"_id":"doc-en-rust-7556d9934befa3f133f74899cd31326a940a57d5d8c9c5d2d613050178930d7c","title":"","text":"F: Fn(&token::Token) -> bool { let attrs = self.parse_arg_attributes()?; if let Ok(Some(mut arg)) = self.parse_self_arg() { if let Some(mut arg) = self.parse_self_arg()? { arg.attrs = attrs.into(); return self.recover_bad_self_arg(arg, is_trait_item); }"} {"_id":"doc-en-rust-fc9bf83c27346d4e30cf1b8b0a24fe6ec0e6e0110d361b55c5a419f4ea099fa7","title":"","text":" // Regression test for issue #62660: if a receiver's type does not // successfully parse, emit the correct error instead of ICE-ing the compiler. struct Foo; impl Foo { pub fn foo(_: i32, self: Box`, found `)` } fn main() {} "} {"_id":"doc-en-rust-7abb08188e9a6bd4734bb28e9c33dd92f4e434a72e4d18858d544dca965c1a15","title":"","text":" error: expected one of `!`, `(`, `+`, `,`, `::`, `<`, or `>`, found `)` --> $DIR/issue-62660.rs:7:38 | LL | pub fn foo(_: i32, self: Box"} {"_id":"doc-en-rust-ceb3ca0b21d1a816d65a598d7ca66a36ee278a92e10dac5d69caaea93d25cf80","title":"","text":"/// consolidate multiple unresolved import errors into a single diagnostic. fn finalize_import(&mut self, import: &'b Import<'b>) -> Option { let orig_vis = import.vis.replace(ty::Visibility::Invisible); let orig_blacklisted_binding = match &import.kind { ImportKind::Single { target_bindings, .. } => { Some(mem::replace(&mut self.r.blacklisted_binding, target_bindings[TypeNS].get())) } _ => None, }; let prev_ambiguity_errors_len = self.r.ambiguity_errors.len(); let path_res = self.r.resolve_path( &import.module_path,"} {"_id":"doc-en-rust-da38693ec3259ab1f2d5981e0519995c8ef20dc7ced19186b79d2c0b64786c1f","title":"","text":"import.crate_lint(), ); let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len; if let Some(orig_blacklisted_binding) = orig_blacklisted_binding { self.r.blacklisted_binding = orig_blacklisted_binding; } import.vis.set(orig_vis); if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res { // Consider erroneous imports used to avoid duplicate diagnostics."} {"_id":"doc-en-rust-280c5619fee8f08964e3c6c8e5481291b8dd73b73e03fff1933366810bb0c918","title":"","text":" // check-pass mod m { pub enum Same { Same, } } use m::*; // The variant `Same` introduced by this import is not considered when resolving the prefix // `Same::` during import validation (issue #62767). use Same::Same; fn main() {} "} {"_id":"doc-en-rust-addaaca558d869a75bf57596fb5c9e8af643bc0be551fe0d0a2af1863b07706a","title":"","text":"let ret = f(self); let last_token = if self.token_cursor.stack.len() == prev { &mut self.token_cursor.frame.last_token } else if self.token_cursor.stack.get(prev).is_none() { // This can happen due to a bad interaction of two unrelated recovery mechanisms with // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(` // (#62881). return Ok((ret?, TokenStream::new(vec![]))); } else { &mut self.token_cursor.stack[prev].last_token };"} {"_id":"doc-en-rust-9d5261a652d7c4ddc4433b155a078ff3ac9dce9bbd634a37c17f2f84d4eb24a8","title":"","text":"// Pull out the tokens that we've collected from the call to `f` above. let mut collected_tokens = match *last_token { LastToken::Collecting(ref mut v) => mem::take(v), LastToken::Was(_) => panic!(\"our vector went away?\"), LastToken::Was(ref was) => { let msg = format!(\"our vector went away? - found Was({:?})\", was); debug!(\"collect_tokens: {}\", msg); self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg); // This can happen due to a bad interaction of two unrelated recovery mechanisms // with mismatched delimiters *and* recovery lookahead on the likely typo // `pub ident(` (#62895, different but similar to the case above). return Ok((ret?, TokenStream::new(vec![]))); } }; // If we're not at EOF our current token wasn't actually consumed by"} {"_id":"doc-en-rust-b18e884983d8c3d2388e4ff8230565fa2a682e9af0dfe93e21c5257476e05c5a","title":"","text":" fn main() {} fn f() -> isize { fn f() -> isize {} pub f< //~^ ERROR missing `fn` or `struct` for function or struct definition //~| ERROR mismatched types //~ ERROR this file contains an un-closed delimiter "} {"_id":"doc-en-rust-297af6a496f40ac0241b367d2bc3d410286b5cf64a0f1d31aaa46109912b0edd","title":"","text":" error: this file contains an un-closed delimiter --> $DIR/issue-62881.rs:6:53 | LL | fn f() -> isize { fn f() -> isize {} pub f< | - un-closed delimiter ... LL | | ^ error: missing `fn` or `struct` for function or struct definition --> $DIR/issue-62881.rs:3:41 | LL | fn f() -> isize { fn f() -> isize {} pub f< | ^ error[E0308]: mismatched types --> $DIR/issue-62881.rs:3:29 | LL | fn f() -> isize { fn f() -> isize {} pub f< | - ^^^^^ expected isize, found () | | | this function's body doesn't return | = note: expected type `isize` found type `()` error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-f50bfb56418ef1acf9cd4336579b5e5f20bee9e9cb9c48d6aca7c40391f2c5fd","title":"","text":" fn main() {} fn v() -> isize { //~ ERROR mismatched types mod _ { //~ ERROR expected identifier pub fn g() -> isizee { //~ ERROR cannot find type `isizee` in this scope mod _ { //~ ERROR expected identifier pub g() -> is //~ ERROR missing `fn` for function definition (), w20); } (), w20); //~ ERROR expected item, found `;` } "} {"_id":"doc-en-rust-5bb18e57c706e54c0ae914e460537ac34bafcebfca3d53348e24e9ce6ae9e7a7","title":"","text":" error: expected identifier, found reserved identifier `_` --> $DIR/issue-62895.rs:4:5 | LL | mod _ { | ^ expected identifier, found reserved identifier error: expected identifier, found reserved identifier `_` --> $DIR/issue-62895.rs:6:5 | LL | mod _ { | ^ expected identifier, found reserved identifier error: missing `fn` for function definition --> $DIR/issue-62895.rs:7:4 | LL | pub g() -> is | ^^^^ help: add `fn` here to parse `g` as a public function | LL | pub fn g() -> is | ^^ error: expected item, found `;` --> $DIR/issue-62895.rs:10:9 | LL | (), w20); | ^ help: remove this semicolon error[E0412]: cannot find type `isizee` in this scope --> $DIR/issue-62895.rs:5:15 | LL | pub fn g() -> isizee { | ^^^^^^ help: a builtin type with a similar name exists: `isize` error[E0308]: mismatched types --> $DIR/issue-62895.rs:3:11 | LL | fn v() -> isize { | - ^^^^^ expected isize, found () | | | this function's body doesn't return | = note: expected type `isize` found type `()` error: aborting due to 6 previous errors Some errors have detailed explanations: E0308, E0412. For more information about an error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-849f8e59cbf3a334040aa782a6f0d7ffd4d680783064d2c7970b8df4590f2eef","title":"","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":"doc-en-rust-edd27e795647abaa01e65c7254ba4776e714d6165cdfe399e2d42f385cfef2b0","title":"","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":"doc-en-rust-69c74f3a5daa5eeec838d8a6294e31fe68cf51253ba379f25f51b47663b36c7b","title":"","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":"doc-en-rust-9f95e81bb222ceabed5391f095fbb15d792eacefde27d0b8011f6b9631a2b2f4","title":"","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":"doc-en-rust-7fc8299a0747ad1f230a31ecb059e27e6c4b7d551aaba4d0f218d16f61244d25","title":"","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":"doc-en-rust-a468b6538250243c917ed9171120bd19a91f19368c21983712d808e368c9d17d","title":"","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":"doc-en-rust-c995a57850762fdfb98ed719113dd4dae4fa3c7da5c8918e978bb4865ed3affc","title":"","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":"doc-en-rust-a5834a441493dd48dd6e9511398821aa40ec96c6c98c623c94ff55135bd7922c","title":"","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":"doc-en-rust-eed52a71d57add94ab698625d80173f76b8972386271fbc6caee12919759ba53","title":"","text":"if let Some((expected, found)) = expected_found { match (terr, is_simple_error, expected == found) { (&TypeError::Sorts(ref values), false, true) => { let sort_string = | a_type: Ty<'tcx> | if let ty::Opaque(def_id, _) = a_type.sty { format!(\" (opaque type at {})\", self.tcx.sess.source_map() .mk_substr_filename(self.tcx.def_span(def_id))) } else { format!(\" ({})\", a_type.sort_string(self.tcx)) }; diag.note_expected_found_extra( &\"type\", expected, found, &format!(\" ({})\", values.expected.sort_string(self.tcx)), &format!(\" ({})\", values.found.sort_string(self.tcx)), &sort_string(values.expected), &sort_string(values.found), ); } (_, false, _) => {"} {"_id":"doc-en-rust-bb5cb54c28f6317c2b2b3c0f6e3ad373be0ede859e35ffdfe42cb654634e9203","title":"","text":"LL | | }.await | |_____- if and else have incompatible types | = note: expected type `impl std::future::Future` (opaque type) found type `impl std::future::Future` (opaque type) = note: expected type `impl std::future::Future` (opaque type at <$DIR/opaque-type-error.rs:8:19>) found type `impl std::future::Future` (opaque type at <$DIR/opaque-type-error.rs:12:19>) = note: distinct uses of `impl Trait` result in different opaque types = help: if both `Future`s have the same `Output` type, consider `.await`ing on both of them"} {"_id":"doc-en-rust-3ec7cbd978da28f1be6a1928c5aa01834454e922abd5b763fdec9053ed880760","title":"","text":" // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // check that the derived impls for the comparison traits shortcircuit // where possible, by having a type that fails when compared as the // second element, so this passes iff the instances shortcircuit. pub struct FailCmp; impl Eq for FailCmp { fn eq(&self, _: &FailCmp) -> bool { fail!(\"eq\") } } impl Ord for FailCmp { fn lt(&self, _: &FailCmp) -> bool { fail!(\"lt\") } } impl TotalEq for FailCmp { fn equals(&self, _: &FailCmp) -> bool { fail!(\"equals\") } } impl TotalOrd for FailCmp { fn cmp(&self, _: &FailCmp) -> Ordering { fail!(\"cmp\") } } #[deriving(Eq,Ord,TotalEq,TotalOrd)] struct ShortCircuit { x: int, y: FailCmp } fn main() { let a = ShortCircuit { x: 1, y: FailCmp }; let b = ShortCircuit { x: 2, y: FailCmp }; assert!(a != b); assert!(a < b); assert!(!a.equals(&b)); assert_eq!(a.cmp(&b), ::std::cmp::Less); } "} {"_id":"doc-en-rust-a4d8c46d6818a1da55af953484609fde87e60310c4c087b684139807c8c79e87","title":"","text":" Subproject commit f2b0c67661f19bb2564225d47aca424ad0449791 Subproject commit 48818e9f5d0f2d5978a9b43ad1a2e8d0b83f6aa0 "} {"_id":"doc-en-rust-b2e1faf2393b648816f1917675cdb4d7e3ff4e0f968a8c81ea9715daa9a28ea9","title":"","text":"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>( ecx: &InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>, mut error: InterpErrorInfo<'tcx>,"} {"_id":"doc-en-rust-77e32a7d9ca7a5c2cc6d5a798507fe8469856f914152ab0a2f7fa4f5a0451960","title":"","text":"let r = match f(self) { Ok(val) => Some(val), Err(error) => { let diagnostic = error_to_const_error(&self.ecx, error); use rustc::mir::interpret::InterpError::*; match diagnostic.error { match error.kind { Exit(_) => bug!(\"the CTFE program cannot exit\"), Unsupported(_) | UndefinedBehavior(_)"} {"_id":"doc-en-rust-0c0dec3acd49e6be6feb7c6f5a30667269d8b3c54fec1479a805588a2aaae9ea","title":"","text":"// Ignore these errors. } Panic(_) => { let diagnostic = error_to_const_error(&self.ecx, error); diagnostic.report_as_lint( self.ecx.tcx, \"this expression will panic at runtime\","} {"_id":"doc-en-rust-5d59b7738d326481cd3b75de93a144d655fe8a30e3b185bf1588917c9cd6d58b","title":"","text":"} else if self.label_right - self.span_left <= self.column_width { // Attempt to fit the code window considering only the spans and labels. let padding_left = (self.column_width - (self.label_right - self.span_left)) / 2; self.computed_left = self.span_left - padding_left; self.computed_left = self.span_left.saturating_sub(padding_left); self.computed_right = self.computed_left + self.column_width; } else if self.span_right - self.span_left <= self.column_width { // Attempt to fit the code window considering the spans and labels plus padding. let padding_left = (self.column_width - (self.span_right - self.span_left)) / 5 * 2; self.computed_left = self.span_left - padding_left; self.computed_left = self.span_left.saturating_sub(padding_left); self.computed_right = self.computed_left + self.column_width; } else { // Mostly give up but still don't show the full line. self.computed_left = self.span_left;"} {"_id":"doc-en-rust-fb86c57021d818a8d01078074522aa9916db762893d7cc3aadba15a0d0a78f40","title":"","text":"}; let column_width = if let Some(width) = self.terminal_width { width width.saturating_sub(code_offset) } else if self.ui_testing { 140 } else { term_size::dimensions().map(|(w, _)| w - code_offset).unwrap_or(140) term_size::dimensions() .map(|(w, _)| w.saturating_sub(code_offset)) .unwrap_or(std::usize::MAX) }; let margin = Margin::new("} {"_id":"doc-en-rust-0124692e33fb7a1b11e559df875935790cf73820e7f3cb16835e4d644a5d39a0","title":"","text":"// Warn for non-block expressions with diverging children. match expr.node { ExprKind::Block(..) | ExprKind::Loop(..) | ExprKind::Match(..) => {}, ExprKind::Call(ref callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, \"call\"), ExprKind::MethodCall(_, ref span, _) => self.warn_if_unreachable(expr.hir_id, *span, \"call\"), _ => self.warn_if_unreachable(expr.hir_id, expr.span, \"expression\"), }"} {"_id":"doc-en-rust-b6b2d81cdda3e727fd468910cf25a7796fa5d4e48e2976a9e3a6d7f4cb65f14c","title":"","text":"| ^^^^^^ = note: `#[warn(unreachable_code)]` implied by `#[warn(unused)]` warning: unreachable expression warning: unreachable call --> $DIR/never-assign-dead-code.rs:10:5 | LL | drop(x); | ^^^^^^^ | ^^^^ warning: unused variable: `x` --> $DIR/never-assign-dead-code.rs:9:9"} {"_id":"doc-en-rust-e29d1e113ab3d9a8f550edde2789ae7f7c5c77b872b47c1f65d5d4019ce6b57a","title":"","text":"LL | #![deny(unreachable_code)] | ^^^^^^^^^^^^^^^^ error: unreachable expression error: unreachable call --> $DIR/expr_call.rs:18:5 | LL | bar(return); | ^^^^^^^^^^^ | ^^^ error: aborting due to 2 previous errors"} {"_id":"doc-en-rust-933b9225efc0e63a787f41ecd163e29614f96103b01e94685a82c6b61b1d260f","title":"","text":"LL | #![deny(unreachable_code)] | ^^^^^^^^^^^^^^^^ error: unreachable expression --> $DIR/expr_method.rs:21:5 error: unreachable call --> $DIR/expr_method.rs:21:9 | LL | Foo.bar(return); | ^^^^^^^^^^^^^^^ | ^^^ error: aborting due to 2 previous errors"} {"_id":"doc-en-rust-94f1bf0d0604a90d685d242863a9e8fb530539a5cabfe110ada13306ebe2c8ee","title":"","text":"get_u8()); //~ ERROR unreachable expression } fn diverge_second() { call( //~ ERROR unreachable expression call( //~ ERROR unreachable call get_u8(), diverge()); }"} {"_id":"doc-en-rust-2a93dd5fd8cacc966c9cee4f3dde5081d83faf170c362c5d5604ed7e0a43e4bf","title":"","text":"LL | #![deny(unreachable_code)] | ^^^^^^^^^^^^^^^^ error: unreachable expression error: unreachable call --> $DIR/unreachable-in-call.rs:17:5 | LL | / call( LL | | get_u8(), LL | | diverge()); | |__________________^ LL | call( | ^^^^ error: aborting due to 2 previous errors"} {"_id":"doc-en-rust-ddcbce222ab4254d3ba333480e78d37ae91ebe4f4f557ffbbbe5e44a92a5f1fe","title":"","text":"32_000_000 // 32MB on other platforms }; rustc_driver::set_sigpipe_handler(); env_logger::init(); env_logger::init_from_env(\"RUSTDOC_LOG\"); let res = std::thread::Builder::new().stack_size(thread_stack_size).spawn(move || { get_args().map(|args| main_args(&args)).unwrap_or(1) }).unwrap().join().unwrap_or(rustc_driver::EXIT_FAILURE);"} {"_id":"doc-en-rust-45d0fbb24e7bfa008c301977c095de37ff013766467f0d2eb1d892c150ae234d","title":"","text":"impl Callbacks for TimePassesCallbacks { fn config(&mut self, config: &mut interface::Config) { // If a --prints=... option has been given, we don't print the \"total\" // time because it will mess up the --prints output. See #64339. self.time_passes = config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time; config.opts.prints.is_empty() && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time); } }"} {"_id":"doc-en-rust-b9e460e2f7cb2e779a1464bed27ff203be96a2bfbea5188fc46e0a5eecd8aba1","title":"","text":"/// header, we convert it to an in-band lifetime. fn collect_fresh_in_band_lifetime(&mut self, span: Span) -> ParamName { assert!(self.is_collecting_in_band_lifetimes); let index = self.lifetimes_to_define.len(); let index = self.lifetimes_to_define.len() + self.in_scope_lifetimes.len(); let hir_name = ParamName::Fresh(index); self.lifetimes_to_define.push((span, hir_name)); hir_name"} {"_id":"doc-en-rust-c1f87b4a6af9fb431b397ed5d7e997a8f025880a4cbba5b68dbf1384d52b60c9","title":"","text":" // check-pass // Check that the anonymous lifetimes used here aren't considered to shadow one // another. Note that `async fn` is different to `fn` here because the lifetimes // are numbered by HIR lowering, rather than lifetime resolution. // edition:2018 struct A<'a, 'b>(&'a &'b i32); struct B<'a>(&'a i32); impl A<'_, '_> { async fn assoc(x: &u32, y: B<'_>) { async fn nested(x: &u32, y: A<'_, '_>) {} } async fn assoc2(x: &u32, y: A<'_, '_>) { impl A<'_, '_> { async fn nested_assoc(x: &u32, y: B<'_>) {} } } } fn main() {} "} {"_id":"doc-en-rust-74588767088f8b655322e6c35c64a42398e500c459a6917f6783e3cb3785e54a","title":"","text":"Cow::Owned(res) } /// Converts a [`Vec`] to a `String`, substituting invalid UTF-8 /// sequences with replacement characters. /// /// See [`from_utf8_lossy`] for more details. /// /// [`from_utf8_lossy`]: String::from_utf8_lossy /// /// Note that this function does not guarantee reuse of the original `Vec` /// allocation. /// /// # Examples /// /// Basic usage: /// /// ``` /// #![feature(string_from_utf8_lossy_owned)] /// // some bytes, in a vector /// let sparkle_heart = vec![240, 159, 146, 150]; /// /// let sparkle_heart = String::from_utf8_lossy_owned(sparkle_heart); /// /// assert_eq!(String::from(\"💖\"), sparkle_heart); /// ``` /// /// Incorrect bytes: /// /// ``` /// #![feature(string_from_utf8_lossy_owned)] /// // some invalid bytes /// let input: Vec = b\"Hello xF0x90x80World\".into(); /// let output = String::from_utf8_lossy_owned(input); /// /// assert_eq!(String::from(\"Hello �World\"), output); /// ``` #[must_use] #[cfg(not(no_global_oom_handling))] #[unstable(feature = \"string_from_utf8_lossy_owned\", issue = \"129436\")] pub fn from_utf8_lossy_owned(v: Vec) -> String { if let Cow::Owned(string) = String::from_utf8_lossy(&v) { string } else { // SAFETY: `String::from_utf8_lossy`'s contract ensures that if // it returns a `Cow::Borrowed`, it is a valid UTF-8 string. // Otherwise, it returns a new allocation of an owned `String`, with // replacement characters for invalid sequences, which is returned // above. unsafe { String::from_utf8_unchecked(v) } } } /// Decode a UTF-16–encoded vector `v` into a `String`, returning [`Err`] /// if `v` contains any invalid data. ///"} {"_id":"doc-en-rust-07e0dc6d7eb12a3f1bdc6c78e714b141488395ba01f120491887c4dfca5b3860","title":"","text":"&self.bytes[..] } /// Converts the bytes into a `String` lossily, substituting invalid UTF-8 /// sequences with replacement characters. /// /// See [`String::from_utf8_lossy`] for more details on replacement of /// invalid sequences, and [`String::from_utf8_lossy_owned`] for the /// `String` function which corresponds to this function. /// /// # Examples /// /// ``` /// #![feature(string_from_utf8_lossy_owned)] /// // some invalid bytes /// let input: Vec = b\"Hello xF0x90x80World\".into(); /// let output = String::from_utf8(input).unwrap_or_else(|e| e.into_utf8_lossy()); /// /// assert_eq!(String::from(\"Hello �World\"), output); /// ``` #[must_use] #[cfg(not(no_global_oom_handling))] #[unstable(feature = \"string_from_utf8_lossy_owned\", issue = \"129436\")] pub fn into_utf8_lossy(self) -> String { String::from_utf8_lossy_owned(self.bytes) } /// Returns the bytes that were attempted to convert to a `String`. /// /// This method is carefully constructed to avoid allocation. It will"} {"_id":"doc-en-rust-94c19b4cdf05af99a8f051d5845b70905f203aef446bf9fdbe364daedfe69d16","title":"","text":"``` \", $Feature, \"assert_eq!(100\", stringify!($SelfT), \".saturating_add(1), 101); assert_eq!(\", stringify!($SelfT), \"::max_value().saturating_add(100), \", stringify!($SelfT), \"::max_value());\", \"::max_value()); assert_eq!(\", stringify!($SelfT), \"::min_value().saturating_add(-1), \", stringify!($SelfT), \"::min_value());\", $EndFeature, \" ```\"),"} {"_id":"doc-en-rust-d540cafe3d99a996bc156d5b345801078c0b04360daf7a763e5bbc06d9a69225","title":"","text":"} } doc_comment! { concat!(\"Saturating integer subtraction. Computes `self - rhs`, saturating at the numeric bounds instead of overflowing."} {"_id":"doc-en-rust-08c47cd6bce9687f2c8613ac40d3db3de3b82fad0a610d51bc2189aaa1c0373e","title":"","text":"``` \", $Feature, \"assert_eq!(100\", stringify!($SelfT), \".saturating_sub(127), -27); assert_eq!(\", stringify!($SelfT), \"::min_value().saturating_sub(100), \", stringify!($SelfT), \"::min_value());\", \"::min_value()); assert_eq!(\", stringify!($SelfT), \"::max_value().saturating_sub(-1), \", stringify!($SelfT), \"::max_value());\", $EndFeature, \" ```\"), #[stable(feature = \"rust1\", since = \"1.0.0\")]"} {"_id":"doc-en-rust-d327a68663d4bffa5b0661d90859b574aa36645fc1d080166a0c1262120befd0","title":"","text":"} else { \"items from traits can only be used if the trait is implemented and in scope\" }); let mut msg = format!( let message = |action| format!( \"the following {traits_define} an item `{name}`, perhaps you need to {action} {one_of_them}:\", traits_define = if candidates.len() == 1 {"} {"_id":"doc-en-rust-ba833a948cf08c1014b53d2988926f7e3123fbcad7da37bfa8eed7cedc447342","title":"","text":"} else { \"traits define\" }, action = if let Some(param) = param_type { format!(\"restrict type parameter `{}` with\", param) } else { \"implement\".to_string() }, action = action, one_of_them = if candidates.len() == 1 { \"it\" } else {"} {"_id":"doc-en-rust-15277cc96da04b9002d17734570ab6610639f7b0e928fe7eda3bd3add7d5ba31","title":"","text":"// Get the `hir::Param` to verify whether it already has any bounds. // We do this to avoid suggesting code that ends up as `T: FooBar`, // instead we suggest `T: Foo + Bar` in that case. let mut has_bounds = None; let mut impl_trait = false; if let Node::GenericParam(ref param) = hir.get(id) { let kind = ¶m.kind; if let hir::GenericParamKind::Type { synthetic: Some(_), .. } = kind { // We've found `fn foo(x: impl Trait)` instead of // `fn foo(x: T)`. We want to suggest the correct // `fn foo(x: impl Trait + TraitBound)` instead of // `fn foo(x: T)`. (See #63706.) impl_trait = true; has_bounds = param.bounds.get(1); } else { has_bounds = param.bounds.get(0); match hir.get(id) { Node::GenericParam(ref param) => { let mut impl_trait = false; let has_bounds = if let hir::GenericParamKind::Type { synthetic: Some(_), .. } = ¶m.kind { // We've found `fn foo(x: impl Trait)` instead of // `fn foo(x: T)`. We want to suggest the correct // `fn foo(x: impl Trait + TraitBound)` instead of // `fn foo(x: T)`. (#63706) impl_trait = true; param.bounds.get(1) } else { param.bounds.get(0) }; let sp = hir.span(id); let sp = if let Some(first_bound) = has_bounds { // `sp` only covers `T`, change it so that it covers // `T:` when appropriate sp.until(first_bound.span()) } else { sp }; // FIXME: contrast `t.def_id` against `param.bounds` to not suggest // traits already there. That can happen when the cause is that // we're in a const scope or associated function used as a method. err.span_suggestions( sp, &message(format!( \"restrict type parameter `{}` with\", param.name.ident().as_str(), )), candidates.iter().map(|t| format!( \"{}{} {}{}\", param.name.ident().as_str(), if impl_trait { \" +\" } else { \":\" }, self.tcx.def_path_str(t.def_id), if has_bounds.is_some() { \" + \"} else { \"\" }, )), Applicability::MaybeIncorrect, ); suggested = true; } Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., bounds, _), ident, .. }) => { let (sp, sep, article) = if bounds.is_empty() { (ident.span.shrink_to_hi(), \":\", \"a\") } else { (bounds.last().unwrap().span().shrink_to_hi(), \" +\", \"another\") }; err.span_suggestions( sp, &message(format!(\"add {} supertrait for\", article)), candidates.iter().map(|t| format!( \"{} {}\", sep, self.tcx.def_path_str(t.def_id), )), Applicability::MaybeIncorrect, ); suggested = true; } _ => {} } let sp = hir.span(id); // `sp` only covers `T`, change it so that it covers `T:` when appropriate. let sp = if let Some(first_bound) = has_bounds { sp.until(first_bound.span()) } else { sp }; // FIXME: contrast `t.def_id` against `param.bounds` to not suggest traits // already there. That can happen when the cause is that we're in a const // scope or associated function used as a method. err.span_suggestions( sp, &msg[..], candidates.iter().map(|t| format!( \"{}{} {}{}\", param, if impl_trait { \" +\" } else { \":\" }, self.tcx.def_path_str(t.def_id), if has_bounds.is_some() { \" + \" } else { \"\" }, )), Applicability::MaybeIncorrect, ); suggested = true; } }; } if !suggested { let mut msg = message(if let Some(param) = param_type { format!(\"restrict type parameter `{}` with\", param) } else { \"implement\".to_string() }); for (i, trait_info) in candidates.iter().enumerate() { msg.push_str(&format!( \"ncandidate #{}: `{}`\","} {"_id":"doc-en-rust-5d8dc1e940ab0b118710e52c0419c2d37d382cf6c9ed5ecfc4d941c6b5fd48c0","title":"","text":" // run-rustfix // check-only #[derive(Debug)] struct Demo { a: String } trait GetString { fn get_a(&self) -> &String; } trait UseString: std::fmt::Debug + GetString { fn use_string(&self) { println!(\"{:?}\", self.get_a()); //~ ERROR no method named `get_a` found for type `&Self` } } trait UseString2: GetString { fn use_string(&self) { println!(\"{:?}\", self.get_a()); //~ ERROR no method named `get_a` found for type `&Self` } } impl GetString for Demo { fn get_a(&self) -> &String { &self.a } } impl UseString for Demo {} impl UseString2 for Demo {} #[cfg(test)] mod tests { use crate::{Demo, UseString}; #[test] fn it_works() { let d = Demo { a: \"test\".to_string() }; d.use_string(); } } fn main() {} "} {"_id":"doc-en-rust-fc8d26f6ecda2e1ef1d0d07c9cb081fb850db21b39efc8ed840014f802d9ce5a","title":"","text":" // run-rustfix // check-only #[derive(Debug)] struct Demo { a: String } trait GetString { fn get_a(&self) -> &String; } trait UseString: std::fmt::Debug { fn use_string(&self) { println!(\"{:?}\", self.get_a()); //~ ERROR no method named `get_a` found for type `&Self` } } trait UseString2 { fn use_string(&self) { println!(\"{:?}\", self.get_a()); //~ ERROR no method named `get_a` found for type `&Self` } } impl GetString for Demo { fn get_a(&self) -> &String { &self.a } } impl UseString for Demo {} impl UseString2 for Demo {} #[cfg(test)] mod tests { use crate::{Demo, UseString}; #[test] fn it_works() { let d = Demo { a: \"test\".to_string() }; d.use_string(); } } fn main() {} "} {"_id":"doc-en-rust-b4f8e9b750d3cd8e7363971026bcea66587a5271e4f60b8e1c8081e3fbff6e02","title":"","text":" error[E0599]: no method named `get_a` found for type `&Self` in the current scope --> $DIR/constrain-trait.rs:15:31 | LL | println!(\"{:?}\", self.get_a()); | ^^^^^ method not found in `&Self` | = help: items from traits can only be used if the type parameter is bounded by the trait help: the following trait defines an item `get_a`, perhaps you need to add another supertrait for it: | LL | trait UseString: std::fmt::Debug + GetString { | ^^^^^^^^^^^ error[E0599]: no method named `get_a` found for type `&Self` in the current scope --> $DIR/constrain-trait.rs:21:31 | LL | println!(\"{:?}\", self.get_a()); | ^^^^^ method not found in `&Self` | = help: items from traits can only be used if the type parameter is bounded by the trait help: the following trait defines an item `get_a`, perhaps you need to add a supertrait for it: | LL | trait UseString2: GetString { | ^^^^^^^^^^^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0599`. "} {"_id":"doc-en-rust-f3b31c4ab1231b857c4b8b517c0e492bc7ce6d89ef9d5e04e52c1969d8ad7893","title":"","text":"/// ``` fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind { // If we got here, the `let` expression is not allowed. self.sess .struct_span_err(span, \"`let` expressions are not supported here\") .note(\"only supported directly in conditions of `if`- and `while`-expressions\") .note(\"as well as when nested within `&&` and parenthesis in those conditions\") .emit(); if self.sess.opts.unstable_features.is_nightly_build() { self.sess .struct_span_err(span, \"`let` expressions are not supported here\") .note(\"only supported directly in conditions of `if`- and `while`-expressions\") .note(\"as well as when nested within `&&` and parenthesis in those conditions\") .emit(); } else { self.sess .struct_span_err(span, \"expected expression, found statement (`let`)\") .note(\"variable declaration using `let` is a statement\") .emit(); } // For better recovery, we emit: // ```"} {"_id":"doc-en-rust-495eb813eb07e8b32e4048147425dc75fc12e7c5cfa88e27dfc6315eea8240fd","title":"","text":"} else if #[cfg(target_os = \"hermit\")] { #[path = \"hermit.rs\"] mod real_imp; } else if #[cfg(all(target_env = \"msvc\", target_arch = \"aarch64\"))] { #[path = \"dummy.rs\"] mod real_imp; } else if #[cfg(target_env = \"msvc\")] { #[path = \"seh.rs\"] mod real_imp;"} {"_id":"doc-en-rust-2a374c56b9000ab72b4a260baeba6e57a8674fc18712967e4f5e37e039a7bbd4","title":"","text":"} } #[cfg(any(target_arch = \"x86_64\", target_arch = \"arm\"))] #[cfg(not(target_arch = \"x86\"))] #[macro_use] mod imp { pub type ptr_t = u32;"} {"_id":"doc-en-rust-35ad80325bccd0931513fbd142737f4db00603b474839407738d9b3299cc8654","title":"","text":" use crate::spec::{LinkerFlavor, PanicStrategy, Target, TargetResult}; use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::windows_msvc_base::opts();"} {"_id":"doc-en-rust-c2ad92ab4e20596481d68f377f209d0ce97a2d6cdb7421ffeb2f6a10eea1f3fa","title":"","text":"base.has_elf_tls = true; base.features = \"+neon,+fp-armv8\".to_string(); // FIXME: this shouldn't be panic=abort, it should be panic=unwind base.panic_strategy = PanicStrategy::Abort; Ok(Target { llvm_target: \"aarch64-pc-windows-msvc\".to_string(), target_endian: \"little\".to_string(),"} {"_id":"doc-en-rust-866f02704766a0bfc9886e4a49d6a5115e41c37fd4260a36a574539810e2dd44","title":"","text":" use crate::spec::{LinkerFlavor, PanicStrategy, Target, TargetResult}; use crate::spec::{LinkerFlavor, Target, TargetResult}; pub fn target() -> TargetResult { let mut base = super::windows_uwp_msvc_base::opts(); base.max_atomic_width = Some(64); base.has_elf_tls = true; // FIXME: this shouldn't be panic=abort, it should be panic=unwind base.panic_strategy = PanicStrategy::Abort; Ok(Target { llvm_target: \"aarch64-pc-windows-msvc\".to_string(), target_endian: \"little\".to_string(),"} {"_id":"doc-en-rust-df457e71e8e922d2452fc2b0201d8f673895c90b04d5ab6d3b0e431d912891f9","title":"","text":" Subproject commit 130721d6f4e6cba3b910ccdf5e0aa62b9dffc95f Subproject commit 027e428197f3702599cfbb632883768175f49173 "} {"_id":"doc-en-rust-0578e66337bac9d47d4d26fa586b138733f491e9c34d28b69c7f12bc5cca6a8c","title":"","text":"// the `enclosing_loops` field and let's coerce the // type of `expr_opt` into what is expected. let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); let ctxt = enclosing_breakables.find_breakable(target_id); let ctxt = match enclosing_breakables.opt_find_breakable(target_id) { Some(ctxt) => ctxt, None => { // Avoid ICE when `break` is inside a closure (#65383). self.tcx.sess.delay_span_bug( expr.span, \"break was outside loop, but no error was emitted\", ); return tcx.types.err; } }; if let Some(ref mut coerce) = ctxt.coerce { if let Some(ref e) = expr_opt { coerce.coerce(self, &cause, e, e_ty);"} {"_id":"doc-en-rust-d8add933207b44c97a51edaa27bac21808871c5914449f67a9516cddfe7d5581","title":"","text":"} } else { // If `ctxt.coerce` is `None`, we can just ignore // the type of the expresison. This is because // the type of the expression. This is because // either this was a break *without* a value, in // which case it is always a legal type (`()`), or // else an error would have been flagged by the"} {"_id":"doc-en-rust-e3db5a785d2beb894d0ef1a5dd521604e70e88277b47afe8beb526ac45d30816","title":"","text":"impl<'tcx> EnclosingBreakables<'tcx> { fn find_breakable(&mut self, target_id: hir::HirId) -> &mut BreakableCtxt<'tcx> { let ix = *self.by_id.get(&target_id).unwrap_or_else(|| { self.opt_find_breakable(target_id).unwrap_or_else(|| { bug!(\"could not find enclosing breakable with id {}\", target_id); }); &mut self.stack[ix] }) } fn opt_find_breakable(&mut self, target_id: hir::HirId) -> Option<&mut BreakableCtxt<'tcx>> { match self.by_id.get(&target_id) { Some(ix) => Some(&mut self.stack[*ix]), None => None, } } }"} {"_id":"doc-en-rust-fa066100f35322fdef9a62bc484974238b07384c98de4d281c88da74260f3806","title":"","text":"let rs: Foo = Foo{t: pth}; let unconstrained = break; //~ ERROR: `break` outside of a loop // This used to ICE because `target_id` passed to `check_expr_break` would be the closure and // not the `loop`, which failed in the call to `find_breakable`. (#65383) 'lab: loop { || { break 'lab; //~ ERROR `break` inside of a closure }; } }"} {"_id":"doc-en-rust-fc5704ed2e2f941b37ebe465dcc2310244ad2e9d9158fb93e4b15c25be3e881d","title":"","text":"LL | let unconstrained = break; | ^^^^^ cannot `break` outside of a loop error: aborting due to 5 previous errors error[E0267]: `break` inside of a closure --> $DIR/break-outside-loop.rs:30:13 | LL | || { | -- enclosing closure LL | break 'lab; | ^^^^^^^^^^ cannot `break` inside of a closure error: aborting due to 6 previous errors Some errors have detailed explanations: E0267, E0268. For more information about an error, try `rustc --explain E0267`."} {"_id":"doc-en-rust-f8ab1afb1059cff02c04bce89ab5de0db994d435ce4363e794060492d818b444","title":"","text":"error_code, pluralize, struct_span_err, Applicability, DiagnosticBuilder, Style, }; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; use rustc_hir::Node;"} {"_id":"doc-en-rust-574bec31ab908f83820c36222f71a3cbce4e3265b32f3d9421d901ff48480d1e","title":"","text":"if let Some(expr_id) = expr { let expr = hir.expect_expr(expr_id); let is_ref = tables.expr_adjustments(expr).iter().any(|adj| adj.is_region_borrow()); debug!(\"target_ty evaluated from {:?}\", expr); let parent = hir.get_parent_node(expr_id); if let Some(hir::Node::Expr(e)) = hir.find(parent) { let method_span = hir.span(parent); if tables.is_method_call(e) && is_ref { let parent_span = hir.span(parent); let parent_did = parent.owner_def_id(); // ```rust // impl T { // fn foo(&self) -> i32 {} // } // T.foo(); // ^^^^^^^ a temporary `&T` created inside this method call due to `&self` // ``` // let is_region_borrow = tables.expr_adjustments(expr).iter().any(|adj| adj.is_region_borrow()); // ```rust // struct Foo(*const u8); // bar(Foo(std::ptr::null())).await; // ^^^^^^^^^^^^^^^^^^^^^ raw-ptr `*T` created inside this struct ctor. // ``` debug!(\"parent_def_kind: {:?}\", self.tcx.def_kind(parent_did)); let is_raw_borrow_inside_fn_like_call = match self.tcx.def_kind(parent_did) { Some(DefKind::Fn) | Some(DefKind::Ctor(..)) => target_ty.is_unsafe_ptr(), _ => false, }; if (tables.is_method_call(e) && is_region_borrow) || is_raw_borrow_inside_fn_like_call { err.span_help( method_span, \"consider moving this method call into a `let` parent_span, \"consider moving this into a `let` binding to create a shorter lived borrow\", ); }"} {"_id":"doc-en-rust-5e910c2d5554ae75488a8d1356f39d214b746daf9b040db200645a559d600806","title":"","text":"... LL | } | - `client` is later dropped here help: consider moving this method call into a `let` binding to create a shorter lived borrow help: consider moving this into a `let` binding to create a shorter lived borrow --> $DIR/issue-64130-4-async-move.rs:19:15 | LL | match client.status() {"} {"_id":"doc-en-rust-456cc9d808f0b4a6bb8a8c3d9c2113eeff83ec5ffd1d89df55f72b1af1c0e2ae","title":"","text":" // edition:2018 struct Foo(*const u8); unsafe impl Send for Foo {} async fn bar(_: Foo) {} fn assert_send(_: T) {} fn main() { assert_send(async { //~^ ERROR future cannot be sent between threads safely bar(Foo(std::ptr::null())).await; }) } "} {"_id":"doc-en-rust-995326f56f7dd13fa19be762efcfb419871e31b4f69d829334819704e4049a82","title":"","text":" error: future cannot be sent between threads safely --> $DIR/issue-65436-raw-ptr-not-send.rs:12:5 | LL | fn assert_send(_: T) {} | ----------- ---- required by this bound in `assert_send` ... LL | assert_send(async { | ^^^^^^^^^^^ future returned by `main` is not `Send` | = help: within `impl std::future::Future`, the trait `std::marker::Send` is not implemented for `*const u8` note: future is not `Send` as this value is used across an await --> $DIR/issue-65436-raw-ptr-not-send.rs:14:9 | LL | bar(Foo(std::ptr::null())).await; | ^^^^^^^^----------------^^^^^^^^- `std::ptr::null()` is later dropped here | | | | | has type `*const u8` | await occurs here, with `std::ptr::null()` maybe used later help: consider moving this into a `let` binding to create a shorter lived borrow --> $DIR/issue-65436-raw-ptr-not-send.rs:14:13 | LL | bar(Foo(std::ptr::null())).await; | ^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-f49e04ae2f9c5904778cfc36a00e60a120fa247d33ab37c694267d9ab2f2071b","title":"","text":"[[package]] name = \"libc\" version = \"0.2.77\" version = \"0.2.79\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"f2f96b10ec2560088a8e76961b00d47107b3a625fecb76dedb29ee7ccbf98235\" checksum = \"2448f6066e80e3bfc792e9c98bf705b4b0fc6e8ef5b43e5889aff0eaa9c58743\" dependencies = [ \"rustc-std-workspace-core\", ]"} {"_id":"doc-en-rust-681de54f276df9f91faf671de9c8bbb5ad7a402249d5ab587a3135e440088aa2","title":"","text":"base.position_independent_executables = true; base.has_elf_tls = false; base.requires_uwtable = true; base.crt_static_respected = false; base }"} {"_id":"doc-en-rust-94e5488e445f9c91451318c93075d0e90a12a757c156c26a7cac5f0c7417e7c4","title":"","text":"position_independent_executables: true, relro_level: RelroLevel::Full, has_elf_tls: true, crt_static_respected: true, ..Default::default() } }"} {"_id":"doc-en-rust-72de40c2a86908bfdce1ce6b5b612a28c054189651e9447772688fa8a197698a","title":"","text":"// These targets statically link libc by default base.crt_static_default = true; // These targets allow the user to choose between static and dynamic linking. base.crt_static_respected = true; base }"} {"_id":"doc-en-rust-865cdda57dd6430fdc01fdf2792ef74703cc29b3550cbf045170bd83d44f6916","title":"","text":"panic_unwind = { path = \"../panic_unwind\", optional = true } panic_abort = { path = \"../panic_abort\" } core = { path = \"../core\" } libc = { version = \"0.2.77\", default-features = false, features = ['rustc-dep-of-std'] } libc = { version = \"0.2.79\", default-features = false, features = ['rustc-dep-of-std'] } compiler_builtins = { version = \"0.1.35\" } profiler_builtins = { path = \"../profiler_builtins\", optional = true } unwind = { path = \"../unwind\" }"} {"_id":"doc-en-rust-8bd01924e82c23e2343d595f06da461bed8c7f7dee3c489fc45de630d95a230e","title":"","text":"} fn exited(&self) -> bool { // On Linux-like OSes this function is safe, on others it is not. See // libc issue: https://github.com/rust-lang/libc/issues/1888. #[cfg_attr( any(target_os = \"linux\", target_os = \"android\", target_os = \"emscripten\"), allow(unused_unsafe) )] unsafe { libc::WIFEXITED(self.0) } libc::WIFEXITED(self.0) } pub fn success(&self) -> bool {"} {"_id":"doc-en-rust-a82e2ce3b21cbb12b5f52623839105347ca09140a4859f96a3ab38210040fb82","title":"","text":"} pub fn code(&self) -> Option { // On Linux-like OSes this function is safe, on others it is not. See // libc issue: https://github.com/rust-lang/libc/issues/1888. #[cfg_attr( any(target_os = \"linux\", target_os = \"android\", target_os = \"emscripten\"), allow(unused_unsafe) )] if self.exited() { Some(unsafe { libc::WEXITSTATUS(self.0) }) } else { None } if self.exited() { Some(libc::WEXITSTATUS(self.0)) } else { None } } pub fn signal(&self) -> Option { // On Linux-like OSes this function is safe, on others it is not. See // libc issue: https://github.com/rust-lang/libc/issues/1888. #[cfg_attr( any(target_os = \"linux\", target_os = \"android\", target_os = \"emscripten\"), allow(unused_unsafe) )] if !self.exited() { Some(unsafe { libc::WTERMSIG(self.0) }) } else { None } if !self.exited() { Some(libc::WTERMSIG(self.0)) } else { None } } }"} {"_id":"doc-en-rust-46aadcd4808a6fdd896b5959b1b561b82d66d05ded39425b2bfc7cd25218af8e","title":"","text":"[dependencies] core = { path = \"../core\" } libc = { version = \"0.2.51\", features = ['rustc-dep-of-std'], default-features = false } libc = { version = \"0.2.79\", features = ['rustc-dep-of-std'], default-features = false } compiler_builtins = \"0.1.0\" cfg-if = \"0.1.8\""} {"_id":"doc-en-rust-c05491ea5c7d1287ef2d9c3e7a85b0597b39e3edc35caa93ab98fd201409f7d8","title":"","text":"} else if target.contains(\"x86_64-fortanix-unknown-sgx\") { llvm_libunwind::compile(); } else if target.contains(\"linux\") { // linking for Linux is handled in lib.rs if target.contains(\"musl\") { // linking for musl is handled in lib.rs llvm_libunwind::compile(); } else if !target.contains(\"android\") { println!(\"cargo:rustc-link-lib=gcc_s\"); } } else if target.contains(\"freebsd\") { println!(\"cargo:rustc-link-lib=gcc_s\");"} {"_id":"doc-en-rust-e6ed2e5564a94a6e1bc77fb1dfafe4469e0fe0d969438656bece631e68052dab","title":"","text":"#[link(name = \"gcc_s\", cfg(not(target_feature = \"crt-static\")))] extern \"C\" {} // When building with crt-static, we get `gcc_eh` from the `libc` crate, since // glibc needs it, and needs it listed later on the linker command line. We // don't want to duplicate it here. #[cfg(all(target_os = \"linux\", target_env = \"gnu\", not(feature = \"llvm-libunwind\")))] #[link(name = \"gcc_s\", cfg(not(target_feature = \"crt-static\")))] extern \"C\" {} #[cfg(target_os = \"redox\")] #[link(name = \"gcc_eh\", kind = \"static-nobundle\", cfg(target_feature = \"crt-static\"))] #[link(name = \"gcc_s\", cfg(not(target_feature = \"crt-static\")))]"} {"_id":"doc-en-rust-9e467815931607ec7a17a3a21a91ca7d5c7b2cae5bf664a7c8bf1bc07f9770ea","title":"","text":"- name: install MSYS2 run: src/ci/scripts/install-msys2.sh if: success() && !env.SKIP_JOB - name: install MSYS2 packages run: src/ci/scripts/install-msys2-packages.sh if: success() && !env.SKIP_JOB - name: install MinGW run: src/ci/scripts/install-mingw.sh if: success() && !env.SKIP_JOB"} {"_id":"doc-en-rust-82e51614b0413a4984b2d835bcd05dd04969ac90c8b75bf724a61f0f09a3efbc","title":"","text":"displayName: Install msys2 condition: and(succeeded(), not(variables.SKIP_JOB)) - bash: src/ci/scripts/install-msys2-packages.sh displayName: Install msys2 packages condition: and(succeeded(), not(variables.SKIP_JOB)) - bash: src/ci/scripts/install-mingw.sh displayName: Install MinGW condition: and(succeeded(), not(variables.SKIP_JOB))"} {"_id":"doc-en-rust-2edbba3efef26f18ee349936e4a56cc032560c9579ebe118669ecacb5081c60c","title":"","text":"run: src/ci/scripts/install-msys2.sh <<: *step - name: install MSYS2 packages run: src/ci/scripts/install-msys2-packages.sh <<: *step - name: install MinGW run: src/ci/scripts/install-mingw.sh <<: *step"} {"_id":"doc-en-rust-d10178388aa1c8283683c5dec762781d01812e08a026f43ca524d367aaecd20a","title":"","text":" #!/bin/bash set -euo pipefail IFS=$'nt' source \"$(cd \"$(dirname \"$0\")\" && pwd)/../shared.sh\" if isWindows; then pacman -S --noconfirm --needed base-devel ca-certificates make diffutils tar binutils # Detect the native Python version installed on the agent. On GitHub # Actions, the C:hostedtoolcachewindowsPython directory contains a # subdirectory for each installed Python version. # # The -V flag of the sort command sorts the input by version number. native_python_version=\"$(ls /c/hostedtoolcache/windows/Python | sort -Vr | head -n 1)\" # 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. python_home=\"/c/hostedtoolcache/windows/Python/${native_python_version}/x64\" cp \"${python_home}/python.exe\" \"${python_home}/python3.exe\" ciCommandAddPath \"C:hostedtoolcachewindowsPython${native_python_version}x64\" ciCommandAddPath \"C:hostedtoolcachewindowsPython${native_python_version}x64Scripts\" fi "} {"_id":"doc-en-rust-d40eaec0a74b3529b0d730cc78863e7219a38110f245200b22f7236ca2b78e73","title":"","text":"#!/bin/bash # Download and install MSYS2, needed primarily for the test suite (run-make) but # also used by the MinGW toolchain for assembling things. # # 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. set -euo pipefail IFS=$'nt'"} {"_id":"doc-en-rust-3642795ec531c306b07feeee17a3d3afcc245a9f38920b5e99448f5d15f0e4cf","title":"","text":"source \"$(cd \"$(dirname \"$0\")\" && pwd)/../shared.sh\" if isWindows; then # Pre-followed the api/v2 URL to the CDN since the API can be a bit flakey curl -sSL https://packages.chocolatey.org/msys2.20190524.0.0.20191030.nupkg > msys2.nupkg curl -sSL https://packages.chocolatey.org/chocolatey-core.extension.1.3.5.1.nupkg > chocolatey-core.extension.nupkg choco install -s . msys2 --params=\"/InstallDir:$(ciCheckoutPath)/msys2 /NoPath\" -y --no-progress rm msys2.nupkg chocolatey-core.extension.nupkg mkdir -p \"$(ciCheckoutPath)/msys2/home/${USERNAME}\" ciCommandAddPath \"$(ciCheckoutPath)/msys2/usr/bin\" msys2Path=\"c:/msys64\" mkdir -p \"${msys2Path}/home/${USERNAME}\" ciCommandAddPath \"${msys2Path}/usr/bin\" echo \"switching shell to use our own bash\" ciCommandSetEnv CI_OVERRIDE_SHELL \"$(ciCheckoutPath)/msys2/usr/bin/bash.exe\" ciCommandSetEnv CI_OVERRIDE_SHELL \"${msys2Path}/usr/bin/bash.exe\" # Detect the native Python version installed on the agent. On GitHub # Actions, the C:hostedtoolcachewindowsPython directory contains a # subdirectory for each installed Python version. # # The -V flag of the sort command sorts the input by version number. native_python_version=\"$(ls /c/hostedtoolcache/windows/Python | sort -Vr | head -n 1)\" # 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. python_home=\"/c/hostedtoolcache/windows/Python/${native_python_version}/x64\" cp \"${python_home}/python.exe\" \"${python_home}/python3.exe\" ciCommandAddPath \"C:hostedtoolcachewindowsPython${native_python_version}x64\" ciCommandAddPath \"C:hostedtoolcachewindowsPython${native_python_version}x64Scripts\" fi"} {"_id":"doc-en-rust-2f03d33ee73fd0d93dd6715ea54ae98aebd59c9f2eb082b252a069744365c3c0","title":"","text":"// ignore-tidy-linelength // ignore-wasm32-bare compiled with panic=abort by default // compile-flags: -Z mir-opt-level=3 #![feature(box_syntax)] fn main() {"} {"_id":"doc-en-rust-e7307b3bb952b9f41a4471df43a8442b2a1f263866dcc88f47fdfd4acf331a89","title":"","text":" // build-pass trait AssociatedConstant { const DATA: (); } impl AssociatedConstant for F where F: FnOnce() -> T, T: AssociatedConstant, { const DATA: () = T::DATA; } impl AssociatedConstant for () { const DATA: () = (); } fn foo() -> impl AssociatedConstant { () } fn get_data(_: T) -> &'static () { &T::DATA } fn main() { get_data(foo); } "} {"_id":"doc-en-rust-03b6078c6212c8f2786f29f3f467992a028d2962eaf0bad7f6cc06037d0b369e","title":"","text":" // build-pass #![feature(type_alias_impl_trait)] use std::marker::PhantomData; /* copied Index and TryFrom for convinience (and simplicity) */ trait MyIndex { type O; fn my_index(self) -> Self::O; } trait MyFrom: Sized { type Error; fn my_from(value: T) -> Result; } /* MCVE starts here */ trait F {} impl F for () {} type DummyT = impl F; fn _dummy_t() -> DummyT {} struct Phantom1(PhantomData); struct Phantom2(PhantomData); struct Scope(Phantom2>); impl Scope { fn new() -> Self { unimplemented!() } } impl MyFrom> for Phantom1 { type Error = (); fn my_from(_: Phantom2) -> Result { unimplemented!() } } impl>>, U> MyIndex> for Scope { type O = T; fn my_index(self) -> Self::O { MyFrom::my_from(self.0).ok().unwrap() } } fn main() { let _pos: Phantom1> = Scope::new().my_index(); } "} {"_id":"doc-en-rust-b71eeedf3456a8e68482610fd4bd4c390497087b08e20938df17f67fc15cfc29","title":"","text":"[[package]] name = \"jsonrpc-core\" version = \"13.1.0\" version = \"13.2.0\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"dd42951eb35079520ee29b7efbac654d85821b397ef88c8151600ef7e2d00217\" checksum = \"91d767c183a7e58618a609499d359ce3820700b3ebb4823a18c343b4a2a41a0d\" dependencies = [ \"futures\", \"log\","} {"_id":"doc-en-rust-fe27cf5b5c1de90933256cfe46f8a405946e8573ad277dbc962767d68904df70","title":"","text":"[[package]] name = \"rls\" version = \"1.39.0\" version = \"1.40.0\" dependencies = [ \"cargo\", \"cargo_metadata 0.8.0\", \"clippy_lints\", \"crossbeam-channel\", \"difference\", \"env_logger 0.6.2\", \"env_logger 0.7.0\", \"failure\", \"futures\", \"heck\","} {"_id":"doc-en-rust-9b66978004e6c3dd8adc6b45dead2b7f5a46767f3c972662e0499cd5828ae748","title":"","text":"\"num_cpus\", \"ordslice\", \"racer\", \"rand 0.6.1\", \"rand 0.7.0\", \"rayon\", \"regex\", \"rls-analysis\","} {"_id":"doc-en-rust-15089504226b79a5c4300aa64f93c6ac382a52ff85c27bc06f8b6ade9fa45739","title":"","text":"\"rls-rustc\", \"rls-span\", \"rls-vfs\", \"rustc-serialize\", \"rustc-workspace-hack\", \"rustc_tools_util 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)\", \"rustfmt-nightly\","} {"_id":"doc-en-rust-064cb92de7efe8859fb5035f9bc2fa0b464e76363a03d3a3f96b7012eaee46a1","title":"","text":"version = \"0.6.0\" dependencies = [ \"clippy_lints\", \"env_logger 0.6.2\", \"env_logger 0.7.0\", \"failure\", \"futures\", \"log\", \"rand 0.6.1\", \"rand 0.7.0\", \"rls-data\", \"rls-ipc\", \"serde\","} {"_id":"doc-en-rust-52ac8ddd14dd95fc60b7252e3183a4652a7af9e34665736a21f94a99cbe06e44","title":"","text":"] [[package]] name = \"rustc-serialize\" version = \"0.3.24\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda\" [[package]] name = \"rustc-std-workspace-alloc\" version = \"1.99.0\" dependencies = ["} {"_id":"doc-en-rust-6a9323dde171f77890d1d5cff7514ed82343d328d737f2e190b856c0f08b068e","title":"","text":" Subproject commit a18df16181947edd5eb593ea0f2321e0035448ee Subproject commit 5db91c7b94ca81eead6b25bcf6196b869a44ece0 "} {"_id":"doc-en-rust-af63aba3198b9444aa3d439e5784fba5ac81bbf6c808d4fd76f66c3b1870784d","title":"","text":"format!(\"are {} arguments\", count) }, )); e.span_label( self.args[pos].span, \"this parameter corresponds to the precision flag\", ); if let Some(arg) = self.args.get(pos) { e.span_label( arg.span, \"this parameter corresponds to the precision flag\", ); } zero_based_note = true; } _ => {}"} {"_id":"doc-en-rust-8eb59b186dada3468775e69ee9aad823e3ada6b9db7a911e93bfa4ead38cace7","title":"","text":"println!(\"{:foo}\", 1); //~ ERROR unknown format trait `foo` println!(\"{5} {:4$} {6:7$}\", 1); //~^ ERROR invalid reference to positional arguments 4, 5, 6 and 7 (there is 1 argument) // We used to ICE here because we tried to unconditionally access the first argument, which // doesn't exist. println!(\"{:.*}\"); //~^ ERROR 2 positional arguments in format string, but no arguments were given }"} {"_id":"doc-en-rust-1e3da8a7aefc568d9c66c60db9068a42e526cefe0f57582a683c535a02d84240","title":"","text":"= note: positional arguments are zero-based = note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html error: 2 positional arguments in format string, but no arguments were given --> $DIR/ifmt-bad-arg.rs:92:15 | LL | println!(\"{:.*}\"); | ^^--^ | | | this precision flag adds an extra required argument at position 0, which is why there are 2 arguments expected | = note: positional arguments are zero-based = note: for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html error[E0308]: mismatched types --> $DIR/ifmt-bad-arg.rs:78:32 |"} {"_id":"doc-en-rust-d8b2ff235cb68abdf831cbafb97dac7f8a322e3ba21346c83447cc4fe6f71b7c","title":"","text":"= note: expected type `&usize` found type `&{float}` error: aborting due to 35 previous errors error: aborting due to 36 previous errors For more information about this error, try `rustc --explain E0308`."} {"_id":"doc-en-rust-e97862e80f899ec9185f223a75571a2d72d289c1c4c5750f74f2dc768588091a","title":"","text":" use std::mem::size_of; struct Foo<'s> { //~ ERROR: parameter `'s` is never used array: [(); size_of::<&Self>()], //~^ ERROR: generic `Self` types are currently not permitted in anonymous constants } // The below is taken from https://github.com/rust-lang/rust/issues/66152#issuecomment-550275017 // as the root cause seems the same. const fn foo() -> usize { 0 } struct Bar<'a> { //~ ERROR: parameter `'a` is never used beta: [(); foo::<&'a ()>()], //~ ERROR: a non-static lifetime is not allowed in a `const` } fn main() {} "} {"_id":"doc-en-rust-e4f5e9de171a36b455dba626d55ab6d0d972442dd4441f77f0e9030f7bc725e0","title":"","text":" error[E0658]: a non-static lifetime is not allowed in a `const` --> $DIR/issue-64173-unused-lifetimes.rs:16:23 | LL | beta: [(); foo::<&'a ()>()], | ^^ | = note: see issue #76560 for more information = help: add `#![feature(generic_const_exprs)]` to the crate attributes to enable error: generic `Self` types are currently not permitted in anonymous constants --> $DIR/issue-64173-unused-lifetimes.rs:4:28 | LL | array: [(); size_of::<&Self>()], | ^^^^ error[E0392]: parameter `'s` is never used --> $DIR/issue-64173-unused-lifetimes.rs:3:12 | LL | struct Foo<'s> { | ^^ unused parameter | = help: consider removing `'s`, referring to it in a field, or using a marker such as `PhantomData` error[E0392]: parameter `'a` is never used --> $DIR/issue-64173-unused-lifetimes.rs:15:12 | LL | struct Bar<'a> { | ^^ unused parameter | = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData` error: aborting due to 4 previous errors Some errors have detailed explanations: E0392, E0658. For more information about an error, try `rustc --explain E0392`. "} {"_id":"doc-en-rust-acebd2d356ba0d55cf90d53727ab9127fccbf64c74807a5568cb102e418f61f3","title":"","text":" // This test ensures that the \"Auto-hide item methods' documentation\" setting is working as // expected. define-function: ( \"check-setting\", (storage_value, setting_attribute_value, toggle_attribute_value), block { assert-local-storage: {\"rustdoc-auto-hide-method-docs\": |storage_value|} click: \"#settings-menu\" wait-for: \"#settings\" assert-property: (\"#auto-hide-method-docs\", {\"checked\": |setting_attribute_value|}) assert-attribute: (\".toggle.method-toggle\", {\"open\": |toggle_attribute_value|}) } ) goto: \"file://\" + |DOC_PATH| + \"/lib2/struct.Foo.html\" // We check that the setting is disabled by default. call-function: (\"check-setting\", { \"storage_value\": null, \"setting_attribute_value\": \"false\", \"toggle_attribute_value\": \"\", }) // Now we change its value. click: \"#auto-hide-method-docs\" assert-local-storage: {\"rustdoc-auto-hide-method-docs\": \"true\"} // We check that the changes were applied as expected. reload: call-function: (\"check-setting\", { \"storage_value\": \"true\", \"setting_attribute_value\": \"true\", \"toggle_attribute_value\": null, }) // And now we re-disable the setting. click: \"#auto-hide-method-docs\" assert-local-storage: {\"rustdoc-auto-hide-method-docs\": \"false\"} // And we check everything is back the way it was before. reload: call-function: (\"check-setting\", { \"storage_value\": \"false\", \"setting_attribute_value\": \"false\", \"toggle_attribute_value\": \"\", }) "} {"_id":"doc-en-rust-5cf0127f7fd466265f33ade06ea5c963345fa237cd541f225f10491c1d7f3908","title":"","text":"use rustc_data_structures::fx::FxHashMap; use rustc_index::vec::IndexVec; use rustc::ty::layout::{ LayoutOf, TyLayout, LayoutError, HasTyCtxt, TargetDataLayout, HasDataLayout, LayoutOf, TyLayout, LayoutError, HasTyCtxt, TargetDataLayout, HasDataLayout, Size, }; use crate::rustc::ty::subst::Subst;"} {"_id":"doc-en-rust-d6b7d04fee0f3cd2f61bf052e4b14100472a7de468aaaaaaf02479c332a63834","title":"","text":"use crate::const_eval::error_to_const_error; use crate::transform::{MirPass, MirSource}; /// The maximum number of bytes that we'll allocate space for a return value. const MAX_ALLOC_LIMIT: u64 = 1024; pub struct ConstProp; impl<'tcx> MirPass<'tcx> for ConstProp {"} {"_id":"doc-en-rust-c1d2797f5e0a912cd0d293cd0fdad1274dd743b2e1d0647c11eaf959138fd67f","title":"","text":"ecx .layout_of(body.return_ty().subst(tcx, substs)) .ok() // Don't bother allocating memory for ZST types which have no values. .filter(|ret_layout| !ret_layout.is_zst()) // Don't bother allocating memory for ZST types which have no values // or for large values. .filter(|ret_layout| !ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)) .map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack)); ecx.push_stack_frame("} {"_id":"doc-en-rust-3abbdcdebdb75745c2635e225e6ef7e055fe3c77a62144d5c8909f50ccf27a98","title":"","text":") -> Option<()> { let span = source_info.span; // #66397: Don't try to eval into large places as that can cause an OOM if place_layout.size >= Size::from_bytes(MAX_ALLOC_LIMIT) { return None; } let overflow_check = self.tcx.sess.overflow_checks(); // Perform any special handling for specific Rvalue types."} {"_id":"doc-en-rust-ee49c55b0e6613225b8b877eaa75eeb5b5587617370a78996b0f956679259df0","title":"","text":" // check-pass // only-x86_64 // Checks that the compiler does not actually try to allocate 4 TB during compilation and OOM crash. fn foo() -> [u8; 4 * 1024 * 1024 * 1024 * 1024] { unimplemented!() } fn main() { foo(); } "} {"_id":"doc-en-rust-9faf1e6ca6dfca36947b5e6bdc946d39a150daadbc8d8960bbcb4640021077db","title":"","text":" // check-pass // only-x86_64 // Checks that the compiler does not actually try to allocate 4 TB during compilation and OOM crash. fn main() { [0; 4 * 1024 * 1024 * 1024 * 1024]; } "} {"_id":"doc-en-rust-7ea0c3ec59bf270f8903866074ff4aecb7b1e5b3edc86c5b7a679483ae8d4ae2","title":"","text":"fallback_has_occurred: bool, mutate_fullfillment_errors: impl Fn(&mut Vec>), ) { if let Err(mut errors) = self.fulfillment_cx.borrow_mut().select_where_possible(self) { let result = self.fulfillment_cx.borrow_mut().select_where_possible(self); if let Err(mut errors) = result { mutate_fullfillment_errors(&mut errors); self.report_fulfillment_errors(&errors, self.inh.body_id, fallback_has_occurred); }"} {"_id":"doc-en-rust-859b3e90eb7d7ebcee4e1c066d5aab8284f717ea3c031053359e7c5a3bdd74b5","title":"","text":" // #66353: ICE when trying to recover from incorrect associated type trait _Func { fn func(_: Self); } trait _A { type AssocT; } fn main() { _Func::< <() as _A>::AssocT >::func(()); //~^ ERROR the trait bound `(): _A` is not satisfied //~| ERROR the trait bound `(): _Func<_>` is not satisfied } "} {"_id":"doc-en-rust-862372c26ce6dc158400bad1726f264ab817301fec8fd8336f641959e73c838e","title":"","text":" error[E0277]: the trait bound `(): _A` is not satisfied --> $DIR/issue-66353.rs:12:14 | LL | _Func::< <() as _A>::AssocT >::func(()); | ^^^^^^^^^^^^^^^^^^ the trait `_A` is not implemented for `()` error[E0277]: the trait bound `(): _Func<_>` is not satisfied --> $DIR/issue-66353.rs:12:41 | LL | fn func(_: Self); | ----------------- required by `_Func::func` ... LL | _Func::< <() as _A>::AssocT >::func(()); | ^^ the trait `_Func<_>` is not implemented for `()` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-3f0f177a12683f86f95a6c56881c05ebee8e66f32569e98745889bd37f56893c","title":"","text":"} fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) { if let &PatKind::Binding(_, _, ident, _) = &p.kind { if let &PatKind::Binding(_, hid, ident, _) = &p.kind { if let hir::Node::Pat(parent_pat) = cx.tcx.hir().get(cx.tcx.hir().get_parent_node(hid)) { if let PatKind::Struct(_, field_pats, _) = &parent_pat.kind { for field in field_pats.iter() { if field.ident != ident { // Only check if a new name has been introduced, to avoid warning // on both the struct definition and this pattern. self.check_snake_case(cx, \"variable\", &ident); } } return; } } self.check_snake_case(cx, \"variable\", &ident); } }"} {"_id":"doc-en-rust-abd91851134d0452ec88bae8a8b48051935650c8b0f5b602799c10cc5a4ff7b5","title":"","text":" #![deny(non_snake_case)] #![allow(unused_variables)] #![allow(dead_code)] enum Foo { Bad { lowerCamelCaseName: bool, //~^ ERROR structure field `lowerCamelCaseName` should have a snake case name }, Good { snake_case_name: bool, }, } fn main() { let b = Foo::Bad { lowerCamelCaseName: true }; match b { Foo::Bad { lowerCamelCaseName } => {} Foo::Good { snake_case_name: lowerCamelCaseBinding } => { } //~^ ERROR variable `lowerCamelCaseBinding` should have a snake case name } if let Foo::Good { snake_case_name: anotherLowerCamelCaseBinding } = b { } //~^ ERROR variable `anotherLowerCamelCaseBinding` should have a snake case name if let Foo::Bad { lowerCamelCaseName: yetAnotherLowerCamelCaseBinding } = b { } //~^ ERROR variable `yetAnotherLowerCamelCaseBinding` should have a snake case name } "} {"_id":"doc-en-rust-3ee5a488ed7aba3ac83eeef84bafb33fd02b2b027cfffd3c3231d37fcdaec10c","title":"","text":" error: structure field `lowerCamelCaseName` should have a snake case name --> $DIR/issue-66362-no-snake-case-warning-for-field-puns.rs:7:9 | LL | lowerCamelCaseName: bool, | ^^^^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `lower_camel_case_name` | note: lint level defined here --> $DIR/issue-66362-no-snake-case-warning-for-field-puns.rs:1:9 | LL | #![deny(non_snake_case)] | ^^^^^^^^^^^^^^ error: variable `lowerCamelCaseBinding` should have a snake case name --> $DIR/issue-66362-no-snake-case-warning-for-field-puns.rs:20:38 | LL | Foo::Good { snake_case_name: lowerCamelCaseBinding } => { } | ^^^^^^^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `lower_camel_case_binding` error: variable `anotherLowerCamelCaseBinding` should have a snake case name --> $DIR/issue-66362-no-snake-case-warning-for-field-puns.rs:24:41 | LL | if let Foo::Good { snake_case_name: anotherLowerCamelCaseBinding } = b { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `another_lower_camel_case_binding` error: variable `yetAnotherLowerCamelCaseBinding` should have a snake case name --> $DIR/issue-66362-no-snake-case-warning-for-field-puns.rs:27:43 | LL | if let Foo::Bad { lowerCamelCaseName: yetAnotherLowerCamelCaseBinding } = b { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `yet_another_lower_camel_case_binding` error: aborting due to 4 previous errors "} {"_id":"doc-en-rust-9ef16e66879a654ef86eecc14ed9f4d9b998a77e3329b46560ba17bde9758bbe","title":"","text":"// are contravariant while return-position lifetimes are // covariant). _marker: PhantomData &'a ()>, // Ensure `Context` is `!Send` and `!Sync` in order to allow // for future `!Send` and / or `!Sync` fields. _marker2: PhantomData<*mut ()>, } impl<'a> Context<'a> {"} {"_id":"doc-en-rust-8accce3db88399bb62ac1ead3ca55a20f04cabf97d000206d5e6fa27b0a27672","title":"","text":"#[must_use] #[inline] pub const fn from_waker(waker: &'a Waker) -> Self { Context { waker, _marker: PhantomData } Context { waker, _marker: PhantomData, _marker2: PhantomData } } /// Returns a reference to the [`Waker`] for the current task."} {"_id":"doc-en-rust-876c353a5ebd9d6d5e46e7e1ae0e48bd6ecff32a9de5d4f6df58b8bbe1c0015e","title":"","text":" use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; use core::task::{Poll, RawWaker, RawWakerVTable, Waker}; #[test] fn poll_const() {"} {"_id":"doc-en-rust-7d0dcfed4463ef882f27def797166c874a42323686ed9cb2c439f6f82ca71d80","title":"","text":"static WAKER: Waker = unsafe { Waker::from_raw(VOID_WAKER) }; static CONTEXT: Context<'static> = Context::from_waker(&WAKER); static WAKER_REF: &'static Waker = CONTEXT.waker(); WAKER_REF.wake_by_ref(); WAKER.wake_by_ref(); }"} {"_id":"doc-en-rust-37cd077b4a10670ee5b5aedb786861c29994e74419aa9e68e108268c98b6d627","title":"","text":" // check-pass #![feature(const_if_match)] enum E { A, B, C } const fn f(e: E) -> usize { match e { _ => 0 } } fn main() { const X: usize = f(E::C); assert_eq!(X, 0); assert_eq!(f(E::A), 0); } "} {"_id":"doc-en-rust-ea431610114ba5dccf9f4e91c5d7f9dd25f5b30f295f08a7e97e1cd93977e0f2","title":"","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":"doc-en-rust-72e60209aeb8c12608cd98adfeb26a27dab5fa303fda88fc621f36621fde0452","title":"","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":"doc-en-rust-fedbed21ca0fcd8a211a5cdb0109e51e2b4e21fe0c8dd1eab26daf9cfbcfe8ad","title":"","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":"doc-en-rust-03704bbf2f682f0a4fbcb6335d6aa1e284ca6d1487ca81a289948d40340397f7","title":"","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":"doc-en-rust-b111cee88113aab44e0e7a620b5688b5e609d8d74eabb1430ecdb1a13081dc57","title":"","text":" // check-pass // ignore-emscripten no llvm_asm! support #![feature(llvm_asm)] pub fn boot(addr: Option) { unsafe { llvm_asm!(\"mov sp, $0\"::\"r\" (addr)); } } fn main() {} "} {"_id":"doc-en-rust-9bbda2951bd1d422a0299f321743b1ffc80223d3d2b4feb84ae91e1615131b62","title":"","text":" // edition:2018 use std::sync::{Arc, Mutex}; pub async fn f(_: ()) {} pub async fn run() { let x: Arc> = unimplemented!(); f(*x.lock().unwrap()).await; } "} {"_id":"doc-en-rust-0171650462e4b54ca96211827890dfed43585caa9d06c87d9b38aa84282859f0","title":"","text":" // aux-build: issue_67893.rs // edition:2018 // dont-check-compiler-stderr // FIXME(#71222): Add above flag because of the difference of stderrs on some env. extern crate issue_67893; fn g(_: impl Send) {} fn main() { g(issue_67893::run()) //~^ ERROR: `std::sync::MutexGuard<'_, ()>` cannot be sent between threads safely } "} {"_id":"doc-en-rust-2ddf6c58ddf4b601141935c77f885ff7fc81a67e0a3f28728e31de8e60e347d2","title":"","text":" #![feature(intrinsics)] extern \"C\" { pub static FOO: extern \"rust-intrinsic\" fn(); } fn main() { FOO() //~ ERROR: use of extern static is unsafe } "} {"_id":"doc-en-rust-347db88b9583cffb99f514a6abdc7080778fc486bcce9801ef67e394bb032380","title":"","text":" error[E0133]: use of extern static is unsafe and requires unsafe function or block --> $DIR/issue-28575.rs:8:5 | LL | FOO() | ^^^ use of extern static | = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior error: aborting due to previous error For more information about this error, try `rustc --explain E0133`. "} {"_id":"doc-en-rust-39cfaec0d2fbd441504c7b401a9cf6dbd1948d7e157379fc88934e375e7cfb63","title":"","text":" pub static TEST_STR: &'static str = \"Hello world\"; "} {"_id":"doc-en-rust-5c74c3295b7cbb090e71d42c4c3e57b5d4abae463790a7a89870ca49933cbeae","title":"","text":" // aux-build: issue_24843.rs // check-pass extern crate issue_24843; static _TEST_STR_2: &'static str = &issue_24843::TEST_STR; fn main() {} "} {"_id":"doc-en-rust-bd03082d9affed24cddc2c0abcc8cce62a7696abaf09494ef5188344ba200860","title":"","text":"/// Typically doesn’t need to be used directly. #[unstable(feature = \"convert_float_to_int\", issue = \"67057\")] pub trait FloatToInt: private::Sealed + Sized { #[unstable(feature = \"float_approx_unchecked_to\", issue = \"67058\")] #[unstable(feature = \"convert_float_to_int\", issue = \"67057\")] #[doc(hidden)] unsafe fn approx_unchecked(self) -> Int; unsafe fn to_int_unchecked(self) -> Int; } macro_rules! impl_float_to_int {"} {"_id":"doc-en-rust-946436d0060273754dc4cd6bfb06bcc3015cdc1994b68f201d9a3789df1c403a","title":"","text":"impl FloatToInt<$Int> for $Float { #[doc(hidden)] #[inline] unsafe fn approx_unchecked(self) -> $Int { crate::intrinsics::float_to_int_approx_unchecked(self) unsafe fn to_int_unchecked(self) -> $Int { #[cfg(bootstrap)] { crate::intrinsics::float_to_int_approx_unchecked(self) } #[cfg(not(bootstrap))] { crate::intrinsics::float_to_int_unchecked(self) } } } )+"} {"_id":"doc-en-rust-8ede03e9f6adf76563a5bebdf43f2c34eaedaf0fd6c61a68a82d24d8f7ccad11","title":"","text":"/// Convert with LLVM’s fptoui/fptosi, which may return undef for values out of range /// () /// This is under stabilization at #[cfg(bootstrap)] pub fn float_to_int_approx_unchecked(value: Float) -> Int; /// Convert with LLVM’s fptoui/fptosi, which may return undef for values out of range /// () /// /// Stabilized as `f32::to_int_unchecked` and `f64::to_int_unchecked`. #[cfg(not(bootstrap))] pub fn float_to_int_unchecked(value: Float) -> Int; /// Returns the number of bits set in an integer type `T` /// /// The stabilized versions of this intrinsic are available on the integer"} {"_id":"doc-en-rust-6ddd7c94341077481bacb2f933eb9f33ce91e532616f87b3d43488138473da28","title":"","text":"/// * Not be `NaN` /// * Not be infinite /// * Be representable in the return type `Int`, after truncating off its fractional part #[unstable(feature = \"float_approx_unchecked_to\", issue = \"67058\")] #[stable(feature = \"float_approx_unchecked_to\", since = \"1.44.0\")] #[inline] pub unsafe fn approx_unchecked_to(self) -> Int pub unsafe fn to_int_unchecked(self) -> Int where Self: FloatToInt, { FloatToInt::::approx_unchecked(self) FloatToInt::::to_int_unchecked(self) } /// Raw transmutation to `u32`."} {"_id":"doc-en-rust-ca6cdf7b094d25e34f9e1866765737b40c355380acf51f6a84c01408c0e54fbb","title":"","text":"/// assuming that the value is finite and fits in that type. /// /// ``` /// #![feature(float_approx_unchecked_to)] /// /// let value = 4.6_f32; /// let rounded = unsafe { value.approx_unchecked_to::() }; /// let rounded = unsafe { value.to_int_unchecked::() }; /// assert_eq!(rounded, 4); /// /// let value = -128.9_f32; /// let rounded = unsafe { value.approx_unchecked_to::() }; /// let rounded = unsafe { value.to_int_unchecked::() }; /// assert_eq!(rounded, std::i8::MIN); /// ``` ///"} {"_id":"doc-en-rust-fcb48e2415025b1766a28806e709400c1969ddfb5f447fa29f1982d82742abd6","title":"","text":"/// * Not be `NaN` /// * Not be infinite /// * Be representable in the return type `Int`, after truncating off its fractional part #[unstable(feature = \"float_approx_unchecked_to\", issue = \"67058\")] #[stable(feature = \"float_approx_unchecked_to\", since = \"1.44.0\")] #[inline] pub unsafe fn approx_unchecked_to(self) -> Int pub unsafe fn to_int_unchecked(self) -> Int where Self: FloatToInt, { FloatToInt::::approx_unchecked(self) FloatToInt::::to_int_unchecked(self) } /// Raw transmutation to `u64`."} {"_id":"doc-en-rust-739fa29423bd5ba2e5a2784f189c63327f0c31b33ae756257c247d61e33f4007","title":"","text":"} } \"float_to_int_approx_unchecked\" => { \"float_to_int_unchecked\" => { if float_type_width(arg_tys[0]).is_none() { span_invalid_monomorphization_error( tcx.sess, span, &format!( \"invalid monomorphization of `float_to_int_approx_unchecked` \"invalid monomorphization of `float_to_int_unchecked` intrinsic: expected basic float type, found `{}`\", arg_tys[0]"} {"_id":"doc-en-rust-e4c1d4c61930878477391eb265d8b095ff16e77efdbf95d175e9fb4e85540c11","title":"","text":"tcx.sess, span, &format!( \"invalid monomorphization of `float_to_int_approx_unchecked` \"invalid monomorphization of `float_to_int_unchecked` intrinsic: expected basic integer type, found `{}`\", ret_ty"} {"_id":"doc-en-rust-9b19f886e7498ce39c8cf9e6579eb927de22522804d002e43db54fa128a2d0ef","title":"","text":"\"fadd_fast\" | \"fsub_fast\" | \"fmul_fast\" | \"fdiv_fast\" | \"frem_fast\" => { (1, vec![param(0), param(0)], param(0)) } \"float_to_int_approx_unchecked\" => (2, vec![param(0)], param(1)), \"float_to_int_unchecked\" => (2, vec![param(0)], param(1)), \"assume\" => (0, vec![tcx.types.bool], tcx.mk_unit()), \"likely\" => (0, vec![tcx.types.bool], tcx.types.bool),"} {"_id":"doc-en-rust-f0386f10cab418a34ef0a377c8c6eab0bf4b7bab0cfc5b219bb39a6895efd23a","title":"","text":"\"rand 0.7.0\", \"rustc-workspace-hack\", \"rustc_version\", \"serde\", \"shell-escape\", \"vergen\", ]"} {"_id":"doc-en-rust-3074a20d9f00d0968d03284ada31b51a1376d435dc37bea62c39d5a757bfe36c","title":"","text":" Subproject commit a0ba079b6af0f8c07c33dd8af72a51c997e58967 Subproject commit 048af409232fc2d7f8fbe5469080dc8bb702c498 "} {"_id":"doc-en-rust-c462aa0a510377d577b98749dab0e21987b55b65ae66b0413f50c3d1f425b66d","title":"","text":"None => return Ok(()), }; // Render the replacements for each suggestion let suggestions = suggestion.splice_lines(&**sm); if suggestions.is_empty() { // Suggestions coming from macros can have malformed spans. This is a heavy handed // approach to avoid ICEs by ignoring the suggestion outright. return Ok(()); } let mut buffer = StyledBuffer::new(); // Render the suggestion message"} {"_id":"doc-en-rust-84a76ef7e8a8e848cc47a3b8eafd85f47db370e72f7667ed4e9d18cdff0e9ad1","title":"","text":"Some(Style::HeaderMsg), ); // Render the replacements for each suggestion let suggestions = suggestion.splice_lines(&**sm); let mut row_num = 2; let mut notice_capitalization = false; for (complete, parts, only_capitalization) in suggestions.iter().take(MAX_SUGGESTIONS) {"} {"_id":"doc-en-rust-ab2eb3e72b10acdf772f8b5b5b61c143310789387fdfcc4515ae118ef6b81fa6","title":"","text":"let show_underline = !(parts.len() == 1 && parts[0].snippet.trim() == complete.trim()) && complete.lines().count() == 1; let lines = sm.span_to_lines(parts[0].span).unwrap(); let lines = sm .span_to_lines(parts[0].span) .expect(\"span_to_lines failed when emitting suggestion\"); assert!(!lines.lines.is_empty());"} {"_id":"doc-en-rust-89936a17ab6826cf7982a2f80a1621cf8670375728d09ac2fd5fefecd32b9eae","title":"","text":"pub use emitter::ColorConfig; use log::debug; use Level::*; use emitter::{is_case_difference, Emitter, EmitterWriter};"} {"_id":"doc-en-rust-7f5ee8f37285b464fd0a1a3b9ef1e9cf732200eb1397b2ed5160bb5e970785f6","title":"","text":"self.substitutions .iter() .filter(|subst| { // Suggestions coming from macros can have malformed spans. This is a heavy // handed approach to avoid ICEs by ignoring the suggestion outright. let invalid = subst.parts.iter().any(|item| cm.is_valid_span(item.span).is_err()); if invalid { debug!(\"splice_lines: suggestion contains an invalid span: {:?}\", subst); } !invalid }) .cloned() .map(|mut substitution| { // Assumption: all spans are in the same file, and all spans"} {"_id":"doc-en-rust-6871631a1062c0012e8bd0325b26d441a3fa2e9bb41164549c898da6a2312807","title":"","text":"lo.line != hi.line } pub fn span_to_lines(&self, sp: Span) -> FileLinesResult { debug!(\"span_to_lines(sp={:?})\", sp); pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> { let lo = self.lookup_char_pos(sp.lo()); debug!(\"span_to_lines: lo={:?}\", lo); let hi = self.lookup_char_pos(sp.hi()); debug!(\"span_to_lines: hi={:?}\", hi); if lo.file.start_pos != hi.file.start_pos { return Err(SpanLinesError::DistinctSources(DistinctSources { begin: (lo.file.name.clone(), lo.file.start_pos), end: (hi.file.name.clone(), hi.file.start_pos), })); } Ok((lo, hi)) } pub fn span_to_lines(&self, sp: Span) -> FileLinesResult { debug!(\"span_to_lines(sp={:?})\", sp); let (lo, hi) = self.is_valid_span(sp)?; assert!(hi.line >= lo.line); let mut lines = Vec::with_capacity(hi.line - lo.line + 1);"} {"_id":"doc-en-rust-c5af145fa1030826aead87a33062ddcf6a744ce9dddc92c6ab425308262aa776","title":"","text":"LL | const MUTABLE_BEHIND_RAW: *mut i32 = &UnsafeCell::new(42) as *const _ as *mut _; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ thread 'rustc' panicked at 'no errors encountered even though `delay_span_bug` issued', src/librustc_errors/lib.rs:346:17 thread 'rustc' panicked at 'no errors encountered even though `delay_span_bug` issued', src/librustc_errors/lib.rs:356:17 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace error: internal compiler error: unexpected panic"} {"_id":"doc-en-rust-2677e6b41201c4791d4d5d3ed67949636389ec4a5c1404c9580048cdc76f02c3","title":"","text":" //xfail-test // Creating a stack closure which references an owned pointer and then // transferring ownership of the owned box before invoking the stack // closure results in a crash. fn twice(x: ~uint) -> uint { *x * 2 } fn invoke(f : &fn() -> uint) { f(); } fn main() { let x : ~uint = ~9; let sq : &fn() -> uint = || { *x * *x }; twice(x); invoke(sq); } No newline at end of file"} {"_id":"doc-en-rust-ee0a1551f9e0f8308d8570b106e51d152e68b34ceea45e58aa4c68fae4f075f7","title":"","text":"if self.regioncx.universal_regions().is_universal_region(r) { Some(r) } else { let upper_bound = self.regioncx.universal_upper_bound(r); // We just want something nameable, even if it's not // actually an upper bound. let upper_bound = self.regioncx.approx_universal_upper_bound(r); if self.regioncx.upper_bound_in_region_scc(r, upper_bound) { self.to_error_region_vid(upper_bound)"} {"_id":"doc-en-rust-bfccf84be9e80d4547c606708f6034936e9497f9537ed2fb578ef98f551a0ea4","title":"","text":"lub } /// Like `universal_upper_bound`, but returns an approximation more suitable /// for diagnostics. If `r` contains multiple disjoint universal regions /// (e.g. 'a and 'b in `fn foo<'a, 'b> { ... }`, we pick the lower-numbered region. /// This corresponds to picking named regions over unnamed regions /// (e.g. picking early-bound regions over a closure late-bound region). /// /// This means that the returned value may not be a true upper bound, since /// only 'static is known to outlive disjoint universal regions. /// Therefore, this method should only be used in diagnostic code, /// where displaying *some* named universal region is better than /// falling back to 'static. pub(in crate::borrow_check) fn approx_universal_upper_bound(&self, r: RegionVid) -> RegionVid { debug!(\"approx_universal_upper_bound(r={:?}={})\", r, self.region_value_str(r)); // Find the smallest universal region that contains all other // universal regions within `region`. let mut lub = self.universal_regions.fr_fn_body; let r_scc = self.constraint_sccs.scc(r); let static_r = self.universal_regions.fr_static; for ur in self.scc_values.universal_regions_outlived_by(r_scc) { let new_lub = self.universal_region_relations.postdom_upper_bound(lub, ur); debug!(\"approx_universal_upper_bound: ur={:?} lub={:?} new_lub={:?}\", ur, lub, new_lub); if ur != static_r && lub != static_r && new_lub == static_r { lub = std::cmp::min(ur, lub); } else { lub = new_lub; } } debug!(\"approx_universal_upper_bound: r={:?} lub={:?}\", r, lub); lub } /// Tests if `test` is true when applied to `lower_bound` at /// `point`. fn eval_verify_bound("} {"_id":"doc-en-rust-ff5630be01fb49fbf0ed846a89a68f766ac333aa60aedb67dd5851f099162091","title":"","text":"{ tcx.fold_regions(&ty, &mut false, |region, _| match *region { ty::ReVar(vid) => { let upper_bound = self.universal_upper_bound(vid); // Find something that we can name let upper_bound = self.approx_universal_upper_bound(vid); self.definitions[upper_bound].external_name.unwrap_or(region) } _ => region,"} {"_id":"doc-en-rust-ee47f99e386409a7822c28a5483267bd6ddcfd47401b21b38c522a81694cfff1","title":"","text":" // edition:2018 // // Regression test for issue #67765 // Tests that we point at the proper location when giving // a lifetime error. fn main() {} async fn func<'a>() -> Result<(), &'a str> { let s = String::new(); let b = &s[..]; Err(b)?; //~ ERROR cannot return value referencing local variable `s` Ok(()) } "} {"_id":"doc-en-rust-d1b0aa210211606caa0e532907d7bd92a8ab65e5e34c1ac68f3230a2a262ace4","title":"","text":" error[E0515]: cannot return value referencing local variable `s` --> $DIR/issue-67765-async-diagnostic.rs:13:11 | LL | let b = &s[..]; | - `s` is borrowed here LL | LL | Err(b)?; | ^ returns a value referencing data owned by the current function error: aborting due to previous error For more information about this error, try `rustc --explain E0515`. "} {"_id":"doc-en-rust-8bdc1116102a6df55f8c443e7f9b105bdffb66954bd330d776ae4307af6609e2","title":"","text":"fn main() { [0].iter().flat_map(|a| [0].iter().map(|_| &a)); //~ ERROR `a` does not live long enough [0].iter().flat_map(|a| [0].iter().map(|_| &a)); //~ ERROR closure may outlive }"} {"_id":"doc-en-rust-c5fb5f3e5846eccc139a594bdfae699a7d902d22ebe619fd825a42628f622678","title":"","text":" error[E0597]: `a` does not live long enough --> $DIR/unnamed-closure-doesnt-life-long-enough-issue-67634.rs:2:49 error[E0373]: closure may outlive the current function, but it borrows `a`, which is owned by the current function --> $DIR/unnamed-closure-doesnt-life-long-enough-issue-67634.rs:2:44 | LL | [0].iter().flat_map(|a| [0].iter().map(|_| &a)); | - ^- ...but `a` will be dropped here, when the enclosing closure returns | | | | | `a` would have to be valid for `'_`... | has type `&i32` | ^^^ - `a` is borrowed here | | | may outlive borrowed value `a` | = note: functions cannot return a borrow to data owned within the function's scope, functions can only return borrows to data passed as arguments = note: to learn more, visit note: closure is returned here --> $DIR/unnamed-closure-doesnt-life-long-enough-issue-67634.rs:2:29 | LL | [0].iter().flat_map(|a| [0].iter().map(|_| &a)); | ^^^^^^^^^^^^^^^^^^^^^^ help: to force the closure to take ownership of `a` (and any other referenced variables), use the `move` keyword | LL | [0].iter().flat_map(|a| [0].iter().map(move |_| &a)); | ^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0597`. For more information about this error, try `rustc --explain E0373`. "} {"_id":"doc-en-rust-ce9d72f410649a46095e8b04b292a636c443b93d96e88f662c39d1c60a06b6dd","title":"","text":" // See https://github.com/rust-lang/rust/pull/67911#issuecomment-576023915 fn f<'a, 'b>(x: i32) -> (&'a i32, &'b i32) { let y = &x; (y, y) //~ ERROR cannot return } fn main() {} "} {"_id":"doc-en-rust-0c3e2794ebfc68b70bff9d10978e0d171c734cdf7fca3d5533f43963d0c78fac","title":"","text":" error[E0515]: cannot return value referencing function parameter `x` --> $DIR/return-disjoint-regions.rs:4:5 | LL | let y = &x; | -- `x` is borrowed here LL | (y, y) | ^^^^^^ returns a value referencing data owned by the current function error: aborting due to previous error For more information about this error, try `rustc --explain E0515`. "} {"_id":"doc-en-rust-d6006530f576be816ee609d5352413c32e1c401584a6a72bce70e0317997e7f6","title":"","text":"use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::{ hir::place::PlaceBase, mir::{self, ClearCrossCrate, Local, LocalDecl, LocalInfo, Location}, mir::{self, ClearCrossCrate, Local, LocalDecl, LocalInfo, LocalKind, Location}, }; use rustc_span::source_map::DesugaringKind; use rustc_span::symbol::{kw, Symbol};"} {"_id":"doc-en-rust-6dd4822ae99f8d53fa48595da97e7d80e31f2467a8d613488eac7676ab571f26","title":"","text":"match label { Some((true, err_help_span, suggested_code)) => { err.span_suggestion( err_help_span, &format!( \"consider changing this to be a mutable {}\", pointer_desc ), suggested_code, Applicability::MachineApplicable, ); let (is_trait_sig, local_trait) = self.is_error_in_trait(local); if !is_trait_sig { err.span_suggestion( err_help_span, &format!( \"consider changing this to be a mutable {}\", pointer_desc ), suggested_code, Applicability::MachineApplicable, ); } else if let Some(x) = local_trait { err.span_suggestion( x, &format!( \"consider changing that to be a mutable {}\", pointer_desc ), suggested_code, Applicability::MachineApplicable, ); } } Some((false, err_label_span, message)) => { err.span_label(err_label_span, &message);"} {"_id":"doc-en-rust-afd691419b0c2bb1282cdd3d703b41fe9faabbd567966b8c5974e7978962ef97","title":"","text":"err.buffer(&mut self.errors_buffer); } /// User cannot make signature of a trait mutable without changing the /// trait. So we find if this error belongs to a trait and if so we move /// suggestion to the trait or disable it if it is out of scope of this crate fn is_error_in_trait(&self, local: Local) -> (bool, Option) { if self.body.local_kind(local) != LocalKind::Arg { return (false, None); } let hir_map = self.infcx.tcx.hir(); let my_def = self.body.source.def_id(); let my_hir = hir_map.local_def_id_to_hir_id(my_def.as_local().unwrap()); let td = if let Some(a) = self.infcx.tcx.impl_of_method(my_def).and_then(|x| self.infcx.tcx.trait_id_of_impl(x)) { a } else { return (false, None); }; ( true, td.as_local().and_then(|tld| { let h = hir_map.local_def_id_to_hir_id(tld); match hir_map.find(h) { Some(Node::Item(hir::Item { kind: hir::ItemKind::Trait(_, _, _, _, items), .. })) => { let mut f_in_trait_opt = None; for hir::TraitItemRef { id: fi, kind: k, .. } in *items { let hi = fi.hir_id(); if !matches!(k, hir::AssocItemKind::Fn { .. }) { continue; } if hir_map.name(hi) != hir_map.name(my_hir) { continue; } f_in_trait_opt = Some(hi); break; } f_in_trait_opt.and_then(|f_in_trait| match hir_map.find(f_in_trait) { Some(Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn( hir::FnSig { decl: hir::FnDecl { inputs, .. }, .. }, _, ), .. })) => { let hir::Ty { span, .. } = inputs[local.index() - 1]; Some(span) } _ => None, }) } _ => None, } }), ) } // point to span of upvar making closure call require mutable borrow fn show_mutating_upvar( &self,"} {"_id":"doc-en-rust-83684e5ac5e778e8524acfbbe193646454bcd2e903c6117218f5984e0623a3c3","title":"","text":" use std::alloc::{GlobalAlloc, Layout}; struct Test(u32); unsafe impl GlobalAlloc for Test { unsafe fn alloc(&self, _layout: Layout) -> *mut u8 { self.0 += 1; //~ ERROR cannot assign 0 as *mut u8 } unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) { unimplemented!(); } } fn main() { } "} {"_id":"doc-en-rust-90333228226ca7e2beb5f88311fe94b126e596ae2d7c44dbf633f2d6f0d4662d","title":"","text":" error[E0594]: cannot assign to `self.0` which is behind a `&` reference --> $DIR/issue-68049-1.rs:7:9 | LL | self.0 += 1; | ^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be written error: aborting due to previous error For more information about this error, try `rustc --explain E0594`. "} {"_id":"doc-en-rust-ccfd68feb53099ed325b6b705412e1a0a1512f0d9f20168a526f880abc2e87ce","title":"","text":" trait Hello { fn example(&self, input: &i32); // should suggest here } struct Test1(i32); impl Hello for Test1 { fn example(&self, input: &i32) { // should not suggest here *input = self.0; //~ ERROR cannot assign } } struct Test2(i32); impl Hello for Test2 { fn example(&self, input: &i32) { // should not suggest here self.0 += *input; //~ ERROR cannot assign } } fn main() { } "} {"_id":"doc-en-rust-01782ad78f726019c8e51f66887c59d86418fceecbb1f690083c31aaba912c64","title":"","text":" error[E0594]: cannot assign to `*input` which is behind a `&` reference --> $DIR/issue-68049-2.rs:9:7 | LL | fn example(&self, input: &i32); // should suggest here | ---- help: consider changing that to be a mutable reference: `&mut i32` ... LL | *input = self.0; | ^^^^^^^^^^^^^^^ `input` is a `&` reference, so the data it refers to cannot be written error[E0594]: cannot assign to `self.0` which is behind a `&` reference --> $DIR/issue-68049-2.rs:17:5 | LL | fn example(&self, input: &i32); // should suggest here | ----- help: consider changing that to be a mutable reference: `&mut self` ... LL | self.0 += *input; | ^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be written error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0594`. "} {"_id":"doc-en-rust-593177600d2ba67a9e05dfa75406f4bdadd50042d20e8e8eea0a1f8544466e16","title":"","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":"doc-en-rust-ac73cd55658f4738286ff4c668c03c0c81dd14360edc9c5ec169057c14b8302e","title":"","text":" fn main() {} #[cfg(FALSE)] fn container() { const unsafe WhereIsFerris Now() {} //~^ ERROR expected one of `extern` or `fn` } "} {"_id":"doc-en-rust-ae07bb08d697e95b96a20955f23b5ed7f611e7e0e38cefdff50d32c098054c3a","title":"","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":"doc-en-rust-a1dae52acc3c2367bff88d7bdd2e939cd40fcb03345c040997d4d6f68e60e3a0","title":"","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":"doc-en-rust-f926511c9e4338b5ef9732fabdf16292a663578281b3edf680c727bc01e3d20c","title":"","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":"doc-en-rust-e052befbed65c0b839e91440c79396dff3284082d46d23b5cda4c61cc309263e","title":"","text":" Subproject commit 4e44aa010c4c7d616182a3078cafb39da6f6c0a2 Subproject commit 6a0f14bef7784e57a57a996cae3f94dbd2490e7a "} {"_id":"doc-en-rust-1584534e611153751ebd32af438b2ba9ab5dfaea72dcc3268cd19c1faa4bf773","title":"","text":"[[package]] name = \"compiler_builtins\" version = \"0.1.24\" version = \"0.1.25\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"b9975aefa63997ef75ca9cf013ff1bb81487aaa0b622c21053afd3b92979a7af\" checksum = \"438ac08ddc5efe81452f984a9e33ba425b00b31d1f48e6acd9e2210aa28cc52e\" dependencies = [ \"cc\", \"rustc-std-workspace-core\","} {"_id":"doc-en-rust-6300e50279b32c7e03dbe652d993cd867cbce71a52c874f970bda75066e6d09b","title":"","text":"let post = format!(\", consider renaming `{}` into `{snippet}`\", suggestion.candidate); (span, snippet, post) } else { (span, suggestion.candidate.to_string(), String::new()) (span, suggestion.candidate.to_ident_string(), String::new()) }; let msg = match suggestion.target { SuggestionTarget::SimilarlyNamed => format!("} {"_id":"doc-en-rust-1752fdb819d03418c7a88bd1d3b0c87f43a291c9292f8b46091277e906cf7482","title":"","text":" fn r#fn() {} fn main() { let r#final = 1; // Should correctly suggest variable defined using raw identifier. fina; //~ ERROR cannot find value // Should correctly suggest function defined using raw identifier. f(); //~ ERROR cannot find function } "} {"_id":"doc-en-rust-3bcaf0b0fecf98c309ea405102dcaddb8672e41406fa9a4ed7bab6424ed13db5","title":"","text":" error[E0425]: cannot find value `fina` in this scope --> $DIR/suggestion-raw-68962.rs:7:5 | LL | fina; | ^^^^ help: a local variable with a similar name exists: `r#final` error[E0425]: cannot find function `f` in this scope --> $DIR/suggestion-raw-68962.rs:10:5 | LL | fn r#fn() {} | --------- similarly named function `r#fn` defined here ... LL | f(); | ^ help: a function with a similar name exists: `r#fn` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0425`. "} {"_id":"doc-en-rust-de68941d225417a9a68a5ec5b7051a59f803f996c563192137e49623f9be2fac","title":"","text":"# Use LLVM libunwind as the implementation for Rust's unwinder. # Accepted values are 'in-tree' (formerly true), 'system' or 'no' (formerly false). # This option only applies for Linux and Fuchsia targets. # On Linux target, if crt-static is not enabled, 'no' means dynamic link to # `libgcc_s.so`, 'in-tree' means static link to the in-tree build of llvm libunwind # and 'system' means dynamic link to `libunwind.so`. If crt-static is enabled, # the behavior is depend on the libc. On musl target, 'no' and 'in-tree' both # means static link to the in-tree build of llvm libunwind, and 'system' means # static link to `libunwind.a` provided by system. Due to the limitation of glibc, # it must link to `libgcc_eh.a` to get a working output, and this option have no effect. #llvm-libunwind = 'no' # Enable Windows Control Flow Guard checks in the standard library."} {"_id":"doc-en-rust-56c0e841f2fc20e688dee10b813baceccb19d80562ab5b106a651318f619d0e7","title":"","text":"cc = \"1.0.67\" [features] # Only applies for Linux and Fuchsia targets # Static link to the in-tree build of llvm libunwind llvm-libunwind = [] # Only applies for Linux and Fuchsia targets # If crt-static is enabled, static link to `libunwind.a` provided by system # If crt-static is disabled, dynamic link to `libunwind.so` provided by system system-llvm-libunwind = []"} {"_id":"doc-en-rust-c18614354a9d3924db1652ee4edf892d2f29125c79caf543c63b2bcd0c1e209e","title":"","text":"println!(\"cargo:rerun-if-changed=build.rs\"); let target = env::var(\"TARGET\").expect(\"TARGET was not set\"); if cfg!(feature = \"system-llvm-libunwind\") { if cfg!(target_os = \"linux\") && cfg!(feature = \"system-llvm-libunwind\") { // linking for Linux is handled in lib.rs return; }"} {"_id":"doc-en-rust-e41269dd2da32ce27e8eb961e06f7a1b80782eb453030a5fca5bc7eea538b0c3","title":"","text":"pub fn compile() { let target = env::var(\"TARGET\").expect(\"TARGET was not set\"); let target_env = env::var(\"CARGO_CFG_TARGET_ENV\").unwrap(); let target_vendor = env::var(\"CARGO_CFG_TARGET_VENDOR\").unwrap(); let target_endian_little = env::var(\"CARGO_CFG_TARGET_ENDIAN\").unwrap() != \"big\"; let cfg = &mut cc::Build::new(); cfg.cpp(true); cfg.cpp_set_stdlib(None); cfg.warnings(false); let mut cc_cfg = cc::Build::new(); let mut cpp_cfg = cc::Build::new(); let root = Path::new(\"../../src/llvm-project/libunwind\"); // libunwind expects a __LITTLE_ENDIAN__ macro to be set for LE archs, cf. #65765 if target_endian_little { cfg.define(\"__LITTLE_ENDIAN__\", Some(\"1\")); cpp_cfg.cpp(true); cpp_cfg.cpp_set_stdlib(None); cpp_cfg.flag(\"-nostdinc++\"); cpp_cfg.flag(\"-fno-exceptions\"); cpp_cfg.flag(\"-fno-rtti\"); cpp_cfg.flag_if_supported(\"-fvisibility-global-new-delete-hidden\"); // Don't set this for clang // By default, Clang builds C code in GNU C17 mode. // By default, Clang builds C++ code according to the C++98 standard, // with many C++11 features accepted as extensions. if cpp_cfg.get_compiler().is_like_gnu() { cpp_cfg.flag(\"-std=c++11\"); cc_cfg.flag(\"-std=c99\"); } if target_env == \"msvc\" { // Don't pull in extra libraries on MSVC cfg.flag(\"/Zl\"); cfg.flag(\"/EHsc\"); cfg.define(\"_CRT_SECURE_NO_WARNINGS\", None); cfg.define(\"_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS\", None); } else if target.contains(\"x86_64-fortanix-unknown-sgx\") { cfg.cpp(false); cfg.static_flag(true); cfg.opt_level(3); cfg.flag(\"-nostdinc++\"); cfg.flag(\"-fno-exceptions\"); cfg.flag(\"-fno-rtti\"); cfg.flag(\"-fstrict-aliasing\"); cfg.flag(\"-funwind-tables\"); cfg.flag(\"-fvisibility=hidden\"); cfg.flag(\"-fno-stack-protector\"); cfg.flag(\"-ffreestanding\"); cfg.flag(\"-fexceptions\"); // easiest way to undefine since no API available in cc::Build to undefine cfg.flag(\"-U_FORTIFY_SOURCE\"); cfg.define(\"_FORTIFY_SOURCE\", \"0\"); cfg.flag_if_supported(\"-fvisibility-global-new-delete-hidden\"); if target.contains(\"x86_64-fortanix-unknown-sgx\") || target_env == \"musl\" { // use the same GCC C compiler command to compile C++ code so we do not need to setup the // C++ compiler env variables on the builders. // Don't set this for clang++, as clang++ is able to compile this without libc++. if cpp_cfg.get_compiler().is_like_gnu() { cpp_cfg.cpp(false); } } cfg.define(\"_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS\", None); cfg.define(\"RUST_SGX\", \"1\"); cfg.define(\"__NO_STRING_INLINES\", None); cfg.define(\"__NO_MATH_INLINES\", None); cfg.define(\"_LIBUNWIND_IS_BAREMETAL\", None); cfg.define(\"__LIBUNWIND_IS_NATIVE_ONLY\", None); cfg.define(\"NDEBUG\", None); } else { cfg.flag(\"-std=c99\"); cfg.flag(\"-std=c++11\"); cfg.flag(\"-nostdinc++\"); cfg.flag(\"-fno-exceptions\"); cfg.flag(\"-fno-rtti\"); for cfg in [&mut cc_cfg, &mut cpp_cfg].iter_mut() { cfg.warnings(false); cfg.flag(\"-fstrict-aliasing\"); cfg.flag(\"-funwind-tables\"); cfg.flag(\"-fvisibility=hidden\"); cfg.flag_if_supported(\"-fvisibility-global-new-delete-hidden\"); cfg.define(\"_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS\", None); cfg.include(root.join(\"include\")); cfg.cargo_metadata(false); if target.contains(\"x86_64-fortanix-unknown-sgx\") { cfg.static_flag(true); cfg.opt_level(3); cfg.flag(\"-fno-stack-protector\"); cfg.flag(\"-ffreestanding\"); cfg.flag(\"-fexceptions\"); // easiest way to undefine since no API available in cc::Build to undefine cfg.flag(\"-U_FORTIFY_SOURCE\"); cfg.define(\"_FORTIFY_SOURCE\", \"0\"); cfg.define(\"RUST_SGX\", \"1\"); cfg.define(\"__NO_STRING_INLINES\", None); cfg.define(\"__NO_MATH_INLINES\", None); cfg.define(\"_LIBUNWIND_IS_BAREMETAL\", None); cfg.define(\"__LIBUNWIND_IS_NATIVE_ONLY\", None); cfg.define(\"NDEBUG\", None); } } let mut unwind_sources = vec![ \"Unwind-EHABI.cpp\", \"Unwind-seh.cpp\", let mut c_sources = vec![ \"Unwind-sjlj.c\", \"UnwindLevel1-gcc-ext.c\", \"UnwindLevel1.c\", \"UnwindRegistersRestore.S\", \"UnwindRegistersSave.S\", \"libunwind.cpp\", ]; if target_vendor == \"apple\" { unwind_sources.push(\"Unwind_AppleExtras.cpp\"); } let cpp_sources = vec![\"Unwind-EHABI.cpp\", \"Unwind-seh.cpp\", \"libunwind.cpp\"]; let cpp_len = cpp_sources.len(); if target.contains(\"x86_64-fortanix-unknown-sgx\") { unwind_sources.push(\"UnwindRustSgx.c\"); c_sources.push(\"UnwindRustSgx.c\"); } let root = Path::new(\"../../src/llvm-project/libunwind\"); cfg.include(root.join(\"include\")); for src in unwind_sources { cfg.file(root.join(\"src\").join(src)); for src in c_sources { cc_cfg.file(root.join(\"src\").join(src).canonicalize().unwrap()); } if target_env == \"musl\" { // use the same C compiler command to compile C++ code so we do not need to setup the // C++ compiler env variables on the builders cfg.cpp(false); // linking for musl is handled in lib.rs cfg.cargo_metadata(false); println!(\"cargo:rustc-link-search=native={}\", env::var(\"OUT_DIR\").unwrap()); for src in cpp_sources { cpp_cfg.file(root.join(\"src\").join(src).canonicalize().unwrap()); } cfg.compile(\"unwind\"); let out_dir = env::var(\"OUT_DIR\").unwrap(); println!(\"cargo:rustc-link-search=native={}\", &out_dir); cpp_cfg.compile(\"unwind-cpp\"); let mut count = 0; for entry in std::fs::read_dir(&out_dir).unwrap() { let obj = entry.unwrap().path().canonicalize().unwrap(); if let Some(ext) = obj.extension() { if ext == \"o\" { cc_cfg.object(&obj); count += 1; } } } assert_eq!(cpp_len, count, \"Can't get object files from {:?}\", &out_dir); cc_cfg.compile(\"unwind\"); } }"} {"_id":"doc-en-rust-3916ad9bf5406bdfb0ef543138744e6f6c6f7d357db9c078cb8551c0562dae60","title":"","text":"} #[cfg(target_env = \"musl\")] #[link(name = \"unwind\", kind = \"static\", cfg(target_feature = \"crt-static\"))] #[link(name = \"gcc_s\", cfg(not(target_feature = \"crt-static\")))] extern \"C\" {} cfg_if::cfg_if! { if #[cfg(all(feature = \"llvm-libunwind\", feature = \"system-llvm-libunwind\"))] { compile_error!(\"`llvm-libunwind` and `system-llvm-libunwind` cannot be enabled at the same time\"); } else if #[cfg(feature = \"llvm-libunwind\")] { #[link(name = \"unwind\", kind = \"static\")] extern \"C\" {} } else if #[cfg(feature = \"system-llvm-libunwind\")] { #[link(name = \"unwind\", kind = \"static-nobundle\", cfg(target_feature = \"crt-static\"))] #[link(name = \"unwind\", cfg(not(target_feature = \"crt-static\")))] extern \"C\" {} } else { #[link(name = \"unwind\", kind = \"static\", cfg(target_feature = \"crt-static\"))] #[link(name = \"gcc_s\", cfg(not(target_feature = \"crt-static\")))] extern \"C\" {} } } // When building with crt-static, we get `gcc_eh` from the `libc` crate, since // glibc needs it, and needs it listed later on the linker command line. We"} {"_id":"doc-en-rust-0a48d988f6e6b92c42c6b7f585971b39d94e2719475dbff2e4d8fdbc5aba2caa","title":"","text":"extern \"C\" {} #[cfg(all(target_vendor = \"fortanix\", target_env = \"sgx\"))] #[link(name = \"unwind\", kind = \"static-nobundle\")] #[link(name = \"unwind\", kind = \"static\")] extern \"C\" {}"} {"_id":"doc-en-rust-cc8893eb4371c317017504553db33144e581b14f6543bb77e8916331757ad9d5","title":"","text":"/// // x is no longer available /// ``` /// /// `move` is also valid before an async block. /// /// ```rust /// let capture = \"hello\"; /// let block = async move { /// println!(\"rust says {} from async block\", capture); /// }; /// ``` /// /// For more information on the `move` keyword, see the [closure]'s section /// of the Rust book or the [threads] section ///"} {"_id":"doc-en-rust-9a63e60df481eb4a56061fbd704f5c24e1bf6ef7816fd369322e993c27a769e0","title":"","text":".unwrap_or(false); let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res { let ty = self.impl_self_ty(span, impl_def_id).ty; let adt_def = ty.ty_adt_def(); let ty = self.normalize_ty(span, tcx.at(span).type_of(impl_def_id)); match ty.kind { ty::Adt(adt_def, substs) if adt_def.has_ctor() => { let variant = adt_def.non_enum_variant();"} {"_id":"doc-en-rust-2b760a5ca3be8026adaf123be5c4e8a2f87c647d1d592731727629fd56bfadd3","title":"","text":"span, \"the `Self` constructor can only be used with tuple or unit structs\", ); if let Some(adt_def) = adt_def { if let Some(adt_def) = ty.ty_adt_def() { match adt_def.adt_kind() { AdtKind::Enum => { err.help(\"did you mean to use one of the enum's variants?\");"} {"_id":"doc-en-rust-e1f7eb17cb9d91d9dff525c838cc18bc8dc80925f3adeb672de54013b2fdb9e5","title":"","text":" fn main() {} struct S0(T); impl S0 { const C: S0 = Self(0); //~^ ERROR mismatched types //~| ERROR mismatched types fn foo() { Self(0); //~^ ERROR mismatched types } } // Testing normalization. trait Fun { type Out; } impl Fun for S0 { type Out = Self; } trait Foo { fn foo(); } impl Foo for as Fun>::Out { fn foo() { Self(0); //~ ERROR mismatched types } } struct S1(T, U); impl S1 { const C: S1 = Self(0, 1); //~^ ERROR mismatched types //~| ERROR mismatched types } struct S2(T); impl S2 { fn map(x: U) -> S2 { Self(x) //~^ ERROR mismatched types //~| ERROR mismatched types } } "} {"_id":"doc-en-rust-9589756fbc655db2d4b538125d65af052d5dd2a56749d03cefc1af629522387a","title":"","text":" error[E0308]: mismatched types --> $DIR/issue-69306.rs:5:28 | LL | impl S0 { | - this type parameter LL | const C: S0 = Self(0); | ^ expected type parameter `T`, found integer | = note: expected type parameter `T` found type `{integer}` = help: type parameters must be constrained to match other types = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters error[E0308]: mismatched types --> $DIR/issue-69306.rs:5:23 | LL | impl S0 { | - this type parameter LL | const C: S0 = Self(0); | ^^^^^^^ expected `u8`, found type parameter `T` | = note: expected struct `S0` found struct `S0` = help: type parameters must be constrained to match other types = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters error[E0308]: mismatched types --> $DIR/issue-69306.rs:10:14 | LL | impl S0 { | - this type parameter ... LL | Self(0); | ^ expected type parameter `T`, found integer | = note: expected type parameter `T` found type `{integer}` = help: type parameters must be constrained to match other types = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters error[E0308]: mismatched types --> $DIR/issue-69306.rs:27:14 | LL | impl Foo for as Fun>::Out { | - this type parameter LL | fn foo() { LL | Self(0); | ^ expected type parameter `T`, found integer | = note: expected type parameter `T` found type `{integer}` = help: type parameters must be constrained to match other types = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters error[E0308]: mismatched types --> $DIR/issue-69306.rs:33:32 | LL | impl S1 { | - this type parameter LL | const C: S1 = Self(0, 1); | ^ expected type parameter `T`, found integer | = note: expected type parameter `T` found type `{integer}` = help: type parameters must be constrained to match other types = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters error[E0308]: mismatched types --> $DIR/issue-69306.rs:33:27 | LL | impl S1 { | - this type parameter LL | const C: S1 = Self(0, 1); | ^^^^^^^^^^ expected `u8`, found type parameter `T` | = note: expected struct `S1` found struct `S1` = help: type parameters must be constrained to match other types = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters error[E0308]: mismatched types --> $DIR/issue-69306.rs:41:14 | LL | impl S2 { | - expected type parameter LL | fn map(x: U) -> S2 { | - found type parameter LL | Self(x) | ^ expected type parameter `T`, found type parameter `U` | = note: expected type parameter `T` found type parameter `U` = note: a type parameter was expected, but a different one was found; you might be missing a type parameter or trait bound = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters error[E0308]: mismatched types --> $DIR/issue-69306.rs:41:9 | LL | impl S2 { | - found type parameter LL | fn map(x: U) -> S2 { | - ----- expected `S2` because of return type | | | expected type parameter LL | Self(x) | ^^^^^^^ expected type parameter `U`, found type parameter `T` | = note: expected struct `S2` found struct `S2` = note: a type parameter was expected, but a different one was found; you might be missing a type parameter or trait bound = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters error: aborting due to 8 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-29ad1f6a8d5b2546224efbd3fbb48dc158339c280817461ed328d8e26b195c04","title":"","text":"sig::set_bit(&mut r.sig, T::PRECISION - 1); } // gcc forces the Quiet bit on, which means (float)(double)(float_sNan) // does not give you back the same bits. This is dubious, and we // don't currently do it. You're really supposed to get // an invalid operation signal at runtime, but nobody does that. status = Status::OK; // Convert of sNaN creates qNaN and raises an exception (invalid op). // This also guarantees that a sNaN does not become Inf on a truncation // that loses all payload bits. if self.is_signaling() { // Quiet signaling NaN. sig::set_bit(&mut r.sig, T::QNAN_BIT); status = Status::INVALID_OP; } else { status = Status::OK; } } else { *loses_info = false; status = Status::OK;"} {"_id":"doc-en-rust-e351675d42d19ab52b2b978586b61f12b82dfa4f3a5a7faf24c9c05dd5d6b140","title":"","text":"} #[test] fn issue_69532() { let f = Double::from_bits(0x7FF0_0000_0000_0001u64 as u128); let mut loses_info = false; let sta = f.convert(&mut loses_info); let r: Single = sta.value; assert!(loses_info); assert!(r.is_nan()); assert_eq!(sta.status, Status::INVALID_OP); } #[test] fn min_num() { let f1 = Double::from_f64(1.0); let f2 = Double::from_f64(2.0);"} {"_id":"doc-en-rust-64b65f85f941d7cfe7879db8bff1feaba903beaa73fad31e693d58a373bd5411","title":"","text":"assert_eq!(4294967295.0, test.to_f64()); assert!(!loses_info); let test = Single::snan(None); let x87_snan = X87DoubleExtended::snan(None); let test: X87DoubleExtended = test.convert(&mut loses_info).value; assert!(test.bitwise_eq(x87_snan)); assert!(!loses_info); let test = Single::qnan(None); let x87_qnan = X87DoubleExtended::qnan(None); let test: X87DoubleExtended = test.convert(&mut loses_info).value; assert!(test.bitwise_eq(x87_qnan)); assert!(!loses_info); let test = X87DoubleExtended::snan(None); let test: X87DoubleExtended = test.convert(&mut loses_info).value; assert!(test.bitwise_eq(x87_snan)); let test = Single::snan(None); let sta = test.convert(&mut loses_info); let test: X87DoubleExtended = sta.value; assert!(test.is_nan()); assert!(!test.is_signaling()); assert!(!loses_info); assert_eq!(sta.status, Status::INVALID_OP); let test = X87DoubleExtended::qnan(None); let test: X87DoubleExtended = test.convert(&mut loses_info).value; assert!(test.bitwise_eq(x87_qnan)); assert!(!loses_info); let test = X87DoubleExtended::snan(None); let sta = test.convert(&mut loses_info); let test: X87DoubleExtended = sta.value; assert!(test.is_nan()); assert!(!test.is_signaling()); assert!(!loses_info); assert_eq!(sta.status, Status::INVALID_OP); } #[test]"} {"_id":"doc-en-rust-73f54938b19c7b8ff3df8f931f6982189f7e0c45548a312e718a0f02dcb20ffb","title":"","text":" // run-pass #![feature(const_fn_transmute)] const fn make_nans() -> (f64, f64, f32, f32) { let nan1: f64 = unsafe { std::mem::transmute(0x7FF0_0001_0000_0001u64) }; let nan2: f64 = unsafe { std::mem::transmute(0x7FF0_0000_0000_0001u64) }; let nan1_32 = nan1 as f32; let nan2_32 = nan2 as f32; (nan1, nan2, nan1_32, nan2_32) } static NANS: (f64, f64, f32, f32) = make_nans(); fn main() { let (nan1, nan2, nan1_32, nan2_32) = NANS; assert!(nan1.is_nan()); assert!(nan2.is_nan()); assert!(nan1_32.is_nan()); assert!(nan2_32.is_nan()); } "} {"_id":"doc-en-rust-4447dbf81ed9e1b8aeab1ab422b5981250acec40ce237b632a9c5d3a2facd2a9","title":"","text":" Subproject commit 23549a8c362a403026432f65a6cb398cb10d44b7 Subproject commit d8e6e4cfcd83d555bd7717ea24224b777ed75773 "} {"_id":"doc-en-rust-b8b986c7f92ad2c9af6568c410b2231ec71eab2cf3b0eee14f052c7128ff1c6e","title":"","text":"(' ' | 'n' | 't', _) if eat_ws => { skips.push(pos); } ('', Some((next_pos, 'n' | 't' | '0' | '' | ''' | '\"'))) => { ('', Some((next_pos, 'n' | 't' | 'r' | '0' | '' | ''' | '\"'))) => { skips.push(*next_pos); let _ = s.next(); }"} {"_id":"doc-en-rust-a7eead4b09e27fbbab0a877337e9fcb5320b36a6e28f88d2d7ff03a8f846db1c","title":"","text":" // Test that multi-byte unicode characters with missing parameters do not ICE. fn main() { println!(\"r¡{}\") //~^ ERROR 1 positional argument in format string } "} {"_id":"doc-en-rust-dd36476bde2bff697f7c17005e7fd0dda91a181900cac6b2f540c85cd7651494","title":"","text":" error: 1 positional argument in format string, but no arguments were given --> $DIR/issue-70381.rs:4:16 | LL | println!(\"r¡{}\") | ^^ error: aborting due to previous error "} {"_id":"doc-en-rust-1dd915ee8c081e115e02e1af3003243d6ee574b4cc9df46505dbbdcca33e7e1c","title":"","text":"/// Checks whether the non-terminal may contain a single (non-keyword) identifier. fn may_be_ident(nt: &token::Nonterminal) -> bool { match *nt { token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) => false, token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) => false, _ => true, } }"} {"_id":"doc-en-rust-94b9b18119ac32a927151a429f56c9611fb53e97472ec15862695502476e399d","title":"","text":" // check-pass macro_rules! foo { ($(: $p:path)? $(: $l:lifetime)? ) => { bar! {$(: $p)? $(: $l)? } }; } macro_rules! bar { ($(: $p:path)? $(: $l:lifetime)? ) => {}; } foo! {: 'a } fn main() {} "} {"_id":"doc-en-rust-444772a1b34f8a07b3322b39d89aa6e32c470c3fc35174b14a284e8b5d3860d0","title":"","text":"}; let sp = cx.with_def_site_ctxt(sp); let e = match env::var(&var.as_str()) { Err(..) => { let value = env::var(&var.as_str()).ok().as_deref().map(Symbol::intern); cx.parse_sess.env_depinfo.borrow_mut().insert((Symbol::intern(&var), value)); let e = match value { None => { let lt = cx.lifetime(sp, Ident::new(kw::StaticLifetime, sp)); cx.expr_path(cx.path_all( sp,"} {"_id":"doc-en-rust-95790ad64670d72a0aa4c1d176eef3342fda7d60f721bcc337ff5bbb0fa4b244","title":"","text":"))], )) } Ok(s) => cx.expr_call_global( Some(value) => cx.expr_call_global( sp, cx.std_path(&[sym::option, sym::Option, sym::Some]), vec![cx.expr_str(sp, Symbol::intern(&s))], vec![cx.expr_str(sp, value)], ), }; MacEager::expr(e)"} {"_id":"doc-en-rust-e63278a51455de8bae18f1753811d63bd0804540df459e6067309488a7598afd","title":"","text":"} let sp = cx.with_def_site_ctxt(sp); let e = match env::var(&*var.as_str()) { Err(_) => { let value = env::var(&*var.as_str()).ok().as_deref().map(Symbol::intern); cx.parse_sess.env_depinfo.borrow_mut().insert((var, value)); let e = match value { None => { cx.span_err(sp, &msg.as_str()); return DummyResult::any(sp); } Ok(s) => cx.expr_str(sp, Symbol::intern(&s)), Some(value) => cx.expr_str(sp, value), }; MacEager::expr(e) }"} {"_id":"doc-en-rust-2d7b05d95f16a7d93047a0255ab045d5755fd1fb2bbec31decdc017059bd8f51","title":"","text":"#![feature(bool_to_option)] #![feature(crate_visibility_modifier)] #![feature(decl_macro)] #![feature(inner_deref)] #![feature(nll)] #![feature(or_patterns)] #![feature(proc_macro_internals)]"} {"_id":"doc-en-rust-1b9c871e4b15a7cbe5af2686915a55091110e6186981f45d199ae0e075a44dcd","title":"","text":"filename.to_string().replace(\" \", \" \") } // Makefile comments only need escaping newlines and ``. // The result can be unescaped by anything that can unescape `escape_default` and friends. fn escape_dep_env(symbol: Symbol) -> String { let s = symbol.as_str(); let mut escaped = String::with_capacity(s.len()); for c in s.chars() { match c { 'n' => escaped.push_str(r\"n\"), 'r' => escaped.push_str(r\"r\"), '' => escaped.push_str(r\"\"), _ => escaped.push(c), } } escaped } fn write_out_deps( sess: &Session, boxed_resolver: &Steal>>,"} {"_id":"doc-en-rust-dd546358021fda9ea3890c3dc621cf8e5b440b890b8d527561a4ba293dda2d34","title":"","text":"for path in files { writeln!(file, \"{}:\", path)?; } // Emit special comments with information about accessed environment variables. let env_depinfo = sess.parse_sess.env_depinfo.borrow(); if !env_depinfo.is_empty() { let mut envs: Vec<_> = env_depinfo .iter() .map(|(k, v)| (escape_dep_env(*k), v.map(escape_dep_env))) .collect(); envs.sort_unstable(); writeln!(file)?; for (k, v) in envs { write!(file, \"# env-dep:{}\", k)?; if let Some(v) = v { write!(file, \"={}\", v)?; } writeln!(file)?; } } Ok(()) })();"} {"_id":"doc-en-rust-9953e9e87255b1000e5fefe0d41b015ee2292db282f830b23e2961513b86d685","title":"","text":"pub symbol_gallery: SymbolGallery, /// The parser has reached `Eof` due to an unclosed brace. Used to silence unnecessary errors. pub reached_eof: Lock, /// Environment variables accessed during the build and their values when they exist. pub env_depinfo: Lock)>>, } impl ParseSess {"} {"_id":"doc-en-rust-a46acd8c00c94a6d9fea43b2a56bc67e2ce213cb123dc5535ec17b7609dfb04a","title":"","text":"gated_spans: GatedSpans::default(), symbol_gallery: SymbolGallery::default(), reached_eof: Lock::new(false), env_depinfo: Default::default(), } }"} {"_id":"doc-en-rust-c02149744916cd57b94551de8dfecb6b3af7df0f11235f7ba071cef30cba28e0","title":"","text":" -include ../../run-make-fulldeps/tools.mk all: EXISTING_ENV=1 EXISTING_OPT_ENV=1 $(RUSTC) --emit dep-info main.rs $(CGREP) \"# env-dep:EXISTING_ENV=1\" < $(TMPDIR)/main.d $(CGREP) \"# env-dep:EXISTING_OPT_ENV=1\" < $(TMPDIR)/main.d $(CGREP) \"# env-dep:NONEXISTENT_OPT_ENV\" < $(TMPDIR)/main.d $(CGREP) \"# env-dep:ESCAPEnESCAPE\" < $(TMPDIR)/main.d "} {"_id":"doc-en-rust-4182df688e093f032bf4b478db19bcb923d5339839fb43c9b82bd03e42bda5a5","title":"","text":" fn main() { env!(\"EXISTING_ENV\"); option_env!(\"EXISTING_OPT_ENV\"); option_env!(\"NONEXISTENT_OPT_ENV\"); option_env!(\"ESCAPEnESCAPE\"); } "} {"_id":"doc-en-rust-ca8c78738fb383b27be43ab60e10ecb431de2fc81d70672c2cd0c0b7cc4fcd0b","title":"","text":"_ => bug!(), }; let param_env = tcx.param_env(source.def_id()); for (local, decl) in body.local_decls.iter_enumerated() { // Ignore locals which are internal or not live if !live_locals.contains(local) || decl.internal { continue; } let decl_ty = tcx.normalize_erasing_regions(param_env, decl.ty); // Sanity check that typeck knows about the type of locals which are // live across a suspension point if !allowed.contains(&decl.ty) && !allowed_upvars.contains(&decl.ty) { if !allowed.contains(&decl_ty) && !allowed_upvars.contains(&decl_ty) { span_bug!( body.span, \"Broken MIR: generator contains type {} in MIR, "} {"_id":"doc-en-rust-08b7eacc849098b4e2c41b5d96b32e81b7db259f5dc8f88022032b69ddc2129a","title":"","text":" // check-pass // edition:2018 // compile-flags: --crate-type=lib pub async fn test() { const C: usize = 4; foo(&mut [0u8; C]).await; } async fn foo(_: &mut [u8]) {} "} {"_id":"doc-en-rust-516bb9c64f74a17cab2ab69b406dda5a30eae5475bffb59b6798d515581cf90d","title":"","text":"format!(\"does not implement `{}`\", trait_ref.print_only_trait_path()) }; let mut explain_yield = |interior_span: Span, yield_span: Span, scope_span: Option| { let mut span = MultiSpan::from_span(yield_span); if let Ok(snippet) = source_map.span_to_snippet(interior_span) { span.push_span_label( yield_span, format!(\"{} occurs here, with `{}` maybe used later\", await_or_yield, snippet), ); // If available, use the scope span to annotate the drop location. if let Some(scope_span) = scope_span { span.push_span_label( source_map.end_point(scope_span), format!(\"`{}` is later dropped here\", snippet), ); let mut explain_yield = |interior_span: Span, yield_span: Span, scope_span: Option| { let mut span = MultiSpan::from_span(yield_span); if let Ok(snippet) = source_map.span_to_snippet(interior_span) { // #70935: If snippet contains newlines, display \"the value\" instead // so that we do not emit complex diagnostics. let snippet = &format!(\"`{}`\", snippet); let snippet = if snippet.contains('n') { \"the value\" } else { snippet }; // The multispan can be complex here, like: // note: future is not `Send` as this value is used across an await // --> $DIR/issue-70935-complex-spans.rs:13:9 // | // LL | baz(|| async{ // | __________^___- // | | _________| // | || // LL | || foo(tx.clone()); // LL | || }).await; // | || - ^- value is later dropped here // | ||_________|______| // | |__________| await occurs here, with value maybe used later // | has type `closure` which is not `Send` // // So, detect it and separate into some notes, like: // // note: future is not `Send` as this value is used across an await // --> $DIR/issue-70935-complex-spans.rs:13:9 // | // LL | / baz(|| async{ // LL | | foo(tx.clone()); // LL | | }).await; // | |________________^ first, await occurs here, with the value maybe used later... // note: the value is later dropped here // --> $DIR/issue-70935-complex-spans.rs:15:17 // | // LL | }).await; // | ^ // // If available, use the scope span to annotate the drop location. if let Some(scope_span) = scope_span { let scope_span = source_map.end_point(scope_span); let is_overlapped = yield_span.overlaps(scope_span) || yield_span.overlaps(interior_span); if is_overlapped { span.push_span_label( yield_span, format!( \"first, {} occurs here, with {} maybe used later...\", await_or_yield, snippet ), ); err.span_note( span, &format!( \"{} {} as this value is used across {}\", future_or_generator, trait_explanation, an_await_or_yield ), ); if source_map.is_multiline(interior_span) { err.span_note( scope_span, &format!(\"{} is later dropped here\", snippet), ); err.span_note( interior_span, &format!( \"this has type `{}` which {}\", target_ty, trait_explanation ), ); } else { let mut span = MultiSpan::from_span(scope_span); span.push_span_label( interior_span, format!(\"has type `{}` which {}\", target_ty, trait_explanation), ); err.span_note(span, &format!(\"{} is later dropped here\", snippet)); } } else { span.push_span_label( yield_span, format!( \"{} occurs here, with {} maybe used later\", await_or_yield, snippet ), ); span.push_span_label( scope_span, format!(\"{} is later dropped here\", snippet), ); span.push_span_label( interior_span, format!(\"has type `{}` which {}\", target_ty, trait_explanation), ); err.span_note( span, &format!( \"{} {} as this value is used across {}\", future_or_generator, trait_explanation, an_await_or_yield ), ); } } else { span.push_span_label( yield_span, format!( \"{} occurs here, with {} maybe used later\", await_or_yield, snippet ), ); span.push_span_label( interior_span, format!(\"has type `{}` which {}\", target_ty, trait_explanation), ); err.span_note( span, &format!( \"{} {} as this value is used across {}\", future_or_generator, trait_explanation, an_await_or_yield ), ); } } } span.push_span_label( interior_span, format!(\"has type `{}` which {}\", target_ty, trait_explanation), ); err.span_note( span, &format!( \"{} {} as this value is used across {}\", future_or_generator, trait_explanation, an_await_or_yield ), ); }; }; match interior_or_upvar_span { GeneratorInteriorOrUpvar::Interior(interior_span) => { if let Some((scope_span, yield_span, expr, from_awaited_ty)) = interior_extra_info {"} {"_id":"doc-en-rust-aebc34780163dcbb8e687f4f1dc5c07bef7611033fe0a6476d3555992f3994e2","title":"","text":" // edition:2018 // #70935: Check if we do not emit snippet // with newlines which lead complex diagnostics. use std::future::Future; async fn baz(_c: impl FnMut() -> T) where T: Future { } fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { //~^ ERROR: future cannot be sent between threads safely async move { baz(|| async{ foo(tx.clone()); }).await; } } fn bar(_s: impl Future + Send) { } fn main() { let (tx, _rx) = std::sync::mpsc::channel(); bar(foo(tx)); } "} {"_id":"doc-en-rust-65d8b0e4c7c6d94a7f043be70a945f2cca58f36c7b7e6503db6d1ec827f2f466","title":"","text":" error: future cannot be sent between threads safely --> $DIR/issue-70935-complex-spans.rs:10:45 | LL | fn foo(tx: std::sync::mpsc::Sender) -> impl Future + Send { | ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send` | = help: the trait `Sync` is not implemented for `Sender` note: future is not `Send` as this value is used across an await --> $DIR/issue-70935-complex-spans.rs:13:9 | LL | / baz(|| async{ LL | | foo(tx.clone()); LL | | }).await; | |________________^ first, await occurs here, with the value maybe used later... note: the value is later dropped here --> $DIR/issue-70935-complex-spans.rs:15:17 | LL | }).await; | ^ note: this has type `[closure@$DIR/issue-70935-complex-spans.rs:13:13: 15:10]` which is not `Send` --> $DIR/issue-70935-complex-spans.rs:13:13 | LL | baz(|| async{ | _____________^ LL | | foo(tx.clone()); LL | | }).await; | |_________^ error: aborting due to previous error "} {"_id":"doc-en-rust-9b034831e0558c47baf7b49788e1a2e58ac0edb7fcfadb441cfb2e80772cb918","title":"","text":"--> $DIR/issue-65436-raw-ptr-not-send.rs:14:9 | LL | bar(Foo(std::ptr::null())).await; | ^^^^^^^^----------------^^^^^^^^- `std::ptr::null()` is later dropped here | | | | | has type `*const u8` which is not `Send` | await occurs here, with `std::ptr::null()` maybe used later | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ first, await occurs here, with `std::ptr::null()` maybe used later... note: `std::ptr::null()` is later dropped here --> $DIR/issue-65436-raw-ptr-not-send.rs:14:41 | LL | bar(Foo(std::ptr::null())).await; | ---------------- ^ | | | has type `*const u8` which is not `Send` help: consider moving this into a `let` binding to create a shorter lived borrow --> $DIR/issue-65436-raw-ptr-not-send.rs:14:13 |"} {"_id":"doc-en-rust-a609b879237088de851b97c080c41e19cdba00e34d451072004dcca400a3cbf6","title":"","text":"} if let Some(non_sm_ty) = structural { let adt_def = match non_sm_ty { traits::NonStructuralMatchTy::Adt(adt_def) => adt_def, let msg = match non_sm_ty { traits::NonStructuralMatchTy::Adt(adt_def) => { let path = self.tcx().def_path_str(adt_def.did); format!( \"to use a constant of type `{}` in a pattern, `{}` must be annotated with `#[derive(PartialEq, Eq)]`\", path, path, ) } traits::NonStructuralMatchTy::Dynamic => { format!(\"trait objects cannot be used in patterns\") } traits::NonStructuralMatchTy::Param => { bug!(\"use of constant whose type is a parameter inside a pattern\") } }; let path = self.tcx().def_path_str(adt_def.did); let make_msg = || -> String { format!( \"to use a constant of type `{}` in a pattern, `{}` must be annotated with `#[derive(PartialEq, Eq)]`\", path, path, ) }; // double-check there even *is* a semantic `PartialEq` to dispatch to. //"} {"_id":"doc-en-rust-5234b52152db1ac0c265147bb05eccd694147325e365b9e028e1f0c5302c0122","title":"","text":"if !ty_is_partial_eq { // span_fatal avoids ICE from resolution of non-existent method (rare case). self.tcx().sess.span_fatal(self.span, &make_msg()); self.tcx().sess.span_fatal(self.span, &msg); } else if mir_structural_match_violation { self.tcx().struct_span_lint_hir( lint::builtin::INDIRECT_STRUCTURAL_MATCH, self.id, self.span, |lint| lint.build(&make_msg()).emit(), |lint| lint.build(&msg).emit(), ); } else { debug!("} {"_id":"doc-en-rust-90d9eaa96203f2a4634bb209893e765cefdd4e3d4833ba86e05cc14aad3ee9c4","title":"","text":"pub enum NonStructuralMatchTy<'tcx> { Adt(&'tcx AdtDef), Param, Dynamic, } /// This method traverses the structure of `ty`, trying to find an"} {"_id":"doc-en-rust-2b72aa9519b815d6e763923e0df5693253cc3be35b144ef300debc13f0e8c3cb","title":"","text":"self.found = Some(NonStructuralMatchTy::Param); return true; // Stop visiting. } ty::Dynamic(..) => { self.found = Some(NonStructuralMatchTy::Dynamic); return true; // Stop visiting. } ty::RawPtr(..) => { // structural-match ignores substructure of // `*const _`/`*mut _`, so skip `super_visit_with`."} {"_id":"doc-en-rust-c2913079f52a16bd47f5ab0e1d387373e06e70bbf5b723509b5d4d5b86d42939","title":"","text":" #![feature(const_generics)] //~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash trait A {} struct B; impl A for B {} fn test() { //~^ ERROR must be annotated with `#[derive(PartialEq, Eq)]` to be used unimplemented!() } fn main() { test::<{ &B }>(); } "} {"_id":"doc-en-rust-63742e8b9fdb4b839dd58722289de23e85e25a3087735f8ae057e294760a1d44","title":"","text":" warning: the feature `const_generics` is incomplete and may cause the compiler to crash --> $DIR/issue-63322-forbid-dyn.rs:1:12 | LL | #![feature(const_generics)] | ^^^^^^^^^^^^^^ | = note: `#[warn(incomplete_features)]` on by default error[E0741]: `&'static (dyn A + 'static)` must be annotated with `#[derive(PartialEq, Eq)]` to be used as the type of a const parameter --> $DIR/issue-63322-forbid-dyn.rs:8:18 | LL | fn test() { | ^^^^^^^^^^^^^^ `&'static (dyn A + 'static)` doesn't derive both `PartialEq` and `Eq` error: aborting due to previous error; 1 warning emitted For more information about this error, try `rustc --explain E0741`. "} {"_id":"doc-en-rust-294e479a0393f549a5954f76633c251c4c2f512257f16c1a23bed52483ef3b3a","title":"","text":" const F: &'static dyn Send = &7u32; fn main() { let a: &dyn Send = &7u32; match a { F => panic!(), //~^ ERROR trait objects cannot be used in patterns _ => {} } } "} {"_id":"doc-en-rust-f44362c8b89bd90242cf8da60c2fe61e3f95b99e366f5b92cea48ba2de51684b","title":"","text":" error: trait objects cannot be used in patterns --> $DIR/issue-70972-dyn-trait.rs:6:9 | LL | F => panic!(), | ^ error: aborting due to previous error "} {"_id":"doc-en-rust-39565ca976f806c69887d6f3d87a9c6020c82eaf6ee3bfada3837329bb8246de","title":"","text":"See the specification for the [GitHub Tables extension][tables] for more details on the exact syntax supported. ### Task lists Task lists can be used as a checklist of items that have been completed. Example: ```md - [x] Complete task - [ ] IncComplete task ``` This will render as

    See the specification for the [task list extension] for more details.
    [`backtrace`]: https://docs.rs/backtrace/0.3.50/backtrace/ [commonmark markdown specification]: https://commonmark.org/ [commonmark quick reference]: https://commonmark.org/help/"} {"_id":"doc-en-rust-194a6d9038fa05289cce313e2bccb2a420f8b7309d84bbe0f03923c76ec186c2","title":"","text":"[`std::env`]: https://doc.rust-lang.org/stable/std/env/index.html#functions [strikethrough]: https://github.github.com/gfm/#strikethrough-extension- [tables]: https://github.github.com/gfm/#tables-extension- [task list extension]: https://github.github.com/gfm/#task-list-items-extension- "} {"_id":"doc-en-rust-89986d80e445dd0887033a387e71a27f5bd4a9d697ebef448fb73ec725f77e7e","title":"","text":"/// Options for rendering Markdown in the main body of documentation. pub(crate) fn opts() -> Options { Options::ENABLE_TABLES | Options::ENABLE_FOOTNOTES | Options::ENABLE_STRIKETHROUGH Options::ENABLE_TABLES | Options::ENABLE_FOOTNOTES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS } /// A subset of [`opts()`] used for rendering summaries."} {"_id":"doc-en-rust-f1385cd613cd783251568d380fb6b18f19b2ffa83d08ec11c6afa635d0a8085f","title":"","text":" // ignore-tidy-linelength // FIXME: this doesn't test as much as I'd like; ideally it would have these query too: // has task_lists/index.html '//li/input[@type=\"checkbox\" and disabled]/following-sibling::text()' 'a' // has task_lists/index.html '//li/input[@type=\"checkbox\"]/following-sibling::text()' 'b' // Unfortunately that requires LXML, because the built-in xml module doesn't support all of xpath. // @has task_lists/index.html '//ul/li/input[@type=\"checkbox\"]' '' // @has task_lists/index.html '//ul/li/input[@disabled]' '' // @has task_lists/index.html '//ul/li' 'a' // @has task_lists/index.html '//ul/li' 'b' //! This tests 'task list' support, a common markdown extension. //! - [ ] a //! - [x] b "} {"_id":"doc-en-rust-935a14836e47b8e00f0259dfc79d1311667eacf91b8a32940b9548bf62433162","title":"","text":"); fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool { followed_by_block && match inner.kind { ExprKind::Ret(_) | ExprKind::Break(..) => true, _ => parser::contains_exterior_struct_lit(&inner), // Prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }` let lhs_needs_parens = { let mut innermost = inner; loop { if let ExprKind::Binary(_, lhs, _rhs) = &innermost.kind { innermost = lhs; if !rustc_ast::util::classify::expr_requires_semi_to_be_stmt(innermost) { break true; } } else { break false; } } }; lhs_needs_parens || (followed_by_block && match inner.kind { ExprKind::Ret(_) | ExprKind::Break(..) => true, _ => parser::contains_exterior_struct_lit(&inner), }) } fn emit_unused_delims_expr("} {"_id":"doc-en-rust-88e57b613f3f9f49ca60beaca226e5b3567b760dd8fcef71d96eccb9a10b61bd","title":"","text":" // check-pass // Make sure unused parens lint doesn't emit a false positive. // See https://github.com/rust-lang/rust/issues/71290 for details. #![deny(unused_parens)] fn x() -> u8 { ({ 0 }) + 1 } fn y() -> u8 { ({ 0 } + 1) } pub fn foo(a: bool, b: bool) -> u8 { (if a { 1 } else { 0 } + if b { 1 } else { 0 }) } pub fn bar() -> u8 { // Make sure nested expressions are handled correctly as well ({ 0 } + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9) } fn main() {} "} {"_id":"doc-en-rust-d72aac8236d7643f4a8e62a79730d3aa84fdcccd4ba74621b38fee4b6d61d179","title":"","text":"return 0; }; let will_be_emitted = |span: Span| { !span.is_dummy() && { let file = sm.lookup_source_file(span.hi()); sm.ensure_source_file_source_present(file) } }; let mut max = 0; for primary_span in msp.primary_spans() { if !primary_span.is_dummy() { if will_be_emitted(*primary_span) { let hi = sm.lookup_char_pos(primary_span.hi()); max = (hi.line).max(max); } } if !self.short_message { for span_label in msp.span_labels() { if !span_label.span.is_dummy() { if will_be_emitted(span_label.span) { let hi = sm.lookup_char_pos(span_label.span.hi()); max = (hi.line).max(max); }"} {"_id":"doc-en-rust-112b9b2dfac53b787b2cc6eac4abb4bd7192112f7dad0b620f0f874cf9828f0c","title":"","text":" // compile-flags: -Z simulate-remapped-rust-src-base=/rustc/xyz -Z ui-testing=no // only-x86_64-unknown-linux-gnu //---^ Limiting target as the above unstable flags don't play well on some environment. struct MyError; impl std::error::Error for MyError {} //~^ ERROR: `MyError` doesn't implement `std::fmt::Display` //~| ERROR: `MyError` doesn't implement `Debug` fn main() {} "} {"_id":"doc-en-rust-74c0152c7d8d85cbd42c5c4e46bcf2e5f043b2b426ddfc6458b2d12d43e652a5","title":"","text":" error[E0277]: `MyError` doesn't implement `std::fmt::Display` --> $DIR/issue-71363.rs:6:6 | 6 | impl std::error::Error for MyError {} | ^^^^^^^^^^^^^^^^^ `MyError` cannot be formatted with the default formatter | = help: the trait `std::fmt::Display` is not implemented for `MyError` = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead note: required by a bound in `std::error::Error` error[E0277]: `MyError` doesn't implement `Debug` --> $DIR/issue-71363.rs:6:6 | 6 | impl std::error::Error for MyError {} | ^^^^^^^^^^^^^^^^^ `MyError` cannot be formatted using `{:?}` | = help: the trait `Debug` is not implemented for `MyError` = note: add `#[derive(Debug)]` to `MyError` or manually `impl Debug for MyError` note: required by a bound in `std::error::Error` help: consider annotating `MyError` with `#[derive(Debug)]` | 5 | #[derive(Debug)] | error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-9ad6931871f8c5f486b1ce778c44c750f5b088ca206156ef6d6e45519986f200","title":"","text":" #![feature(const_generics)] #![allow(incomplete_features)] struct Test(*const usize); type PassArg = (); unsafe extern \"C\" fn pass(args: PassArg) { println!(\"Hello, world!\"); } impl Test { pub fn call_me(&self) { //~^ ERROR: using function pointers as const generic parameters is forbidden self.0 = Self::trampiline:: as _ } unsafe extern \"C\" fn trampiline< Args: Sized, const IDX: usize, const FN: unsafe extern \"C\" fn(Args), //~^ ERROR: using function pointers as const generic parameters is forbidden >( args: Args, ) { FN(args) } } fn main() { let x = Test(); x.call_me::() } "} {"_id":"doc-en-rust-aa60999b60ef951cb0d27cfc4163727739ff5398f4b0c4d39e837d7a4b2c475a","title":"","text":" error: using function pointers as const generic parameters is forbidden --> $DIR/issue-71381.rs:13:61 | LL | pub fn call_me(&self) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: using function pointers as const generic parameters is forbidden --> $DIR/issue-71381.rs:21:19 | LL | const FN: unsafe extern \"C\" fn(Args), | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-91d43e519bb70232a9c66e0f10be65340214e8f71313aca1acb7af02afd76973","title":"","text":" #![feature(const_generics)] #![allow(incomplete_features)] struct Test(); fn pass() { println!(\"Hello, world!\"); } impl Test { pub fn call_me(&self) { self.test::(); } fn test(&self) { //~^ ERROR: using function pointers as const generic parameters is forbidden FN(); } } fn main() { let x = Test(); x.call_me() } "} {"_id":"doc-en-rust-d61f181111561b77b0da01a2f2db7c14581d849778a10b8a11a3d55ec901f3e0","title":"","text":" error: using function pointers as const generic parameters is forbidden --> $DIR/issue-71382.rs:15:23 | LL | fn test(&self) { | ^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-fdbe901f98241e04eeee8b0e8d516c29aa11423fede7057e4fcd5ba3d685ec74","title":"","text":" #![feature(const_generics)] #![allow(incomplete_features)] fn func(outer: A) { //~^ ERROR: using function pointers as const generic parameters is forbidden F(outer); } fn main() {} "} {"_id":"doc-en-rust-cc62024b1d408addf1cbad821c581c705a820289e6df7fac635253df1efa1830","title":"","text":" error: using function pointers as const generic parameters is forbidden --> $DIR/issue-71611.rs:4:21 | LL | fn func(outer: A) { | ^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-e2c9b63c0bc4f1e9b68b3211f383b9f2e76bbf9a68b78e6d0cbc79a0aaaf7c6b","title":"","text":" #![feature(const_generics)] #![allow(incomplete_features)] use std::ffi::{CStr, CString}; unsafe fn unsafely_do_the_thing usize>(ptr: *const i8) -> usize { //~^ ERROR: using function pointers as const generic parameters is forbidden F(CStr::from_ptr(ptr)) } fn safely_do_the_thing(s: &CStr) -> usize { s.to_bytes().len() } fn main() { let baguette = CString::new(\"baguette\").unwrap(); let ptr = baguette.as_ptr(); println!(\"{}\", unsafe { unsafely_do_the_thing::(ptr) }); } "} {"_id":"doc-en-rust-fa88a4858d6f989fd96a8df621553c6656af58dedc2c567e3f6d2b3180113565","title":"","text":" error: using function pointers as const generic parameters is forbidden --> $DIR/issue-72352.rs:6:42 | LL | unsafe fn unsafely_do_the_thing usize>(ptr: *const i8) -> usize { | ^^^^^^^^^^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-fdea7fbeb1970b1aaeca3a5a2841275d3a5651f7f2d85b50d6c2707da78a2bd7","title":"","text":"}; } let binding = if let Some(module) = module { self.resolve_ident_in_module( module, ident, ns, parent_scope, record_used, path_span, ) } else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) { let scopes = ScopeSet::All(ns, opt_ns.is_none()); self.early_resolve_ident_in_lexical_scope( ident, scopes, parent_scope, record_used, record_used, path_span, ) } else { let record_used_id = if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None }; match self.resolve_ident_in_lexical_scope( ident, ns, parent_scope, record_used_id, path_span, &ribs.unwrap()[ns], ) { // we found a locally-imported or available item/module Some(LexicalScopeBinding::Item(binding)) => Ok(binding), // we found a local variable or type param Some(LexicalScopeBinding::Res(res)) if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => { record_segment_res(self, res); return PathResult::NonModule(PartialRes::with_unresolved_segments( res, path.len() - 1, )); enum FindBindingResult<'a> { Binding(Result<&'a NameBinding<'a>, Determinacy>), PathResult(PathResult<'a>), } let find_binding_in_ns = |this: &mut Self, ns| { let binding = if let Some(module) = module { this.resolve_ident_in_module( module, ident, ns, parent_scope, record_used, path_span, ) } else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) { let scopes = ScopeSet::All(ns, opt_ns.is_none()); this.early_resolve_ident_in_lexical_scope( ident, scopes, parent_scope, record_used, record_used, path_span, ) } else { let record_used_id = if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None }; match this.resolve_ident_in_lexical_scope( ident, ns, parent_scope, record_used_id, path_span, &ribs.unwrap()[ns], ) { // we found a locally-imported or available item/module Some(LexicalScopeBinding::Item(binding)) => Ok(binding), // we found a local variable or type param Some(LexicalScopeBinding::Res(res)) if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => { record_segment_res(this, res); return FindBindingResult::PathResult(PathResult::NonModule( PartialRes::with_unresolved_segments(res, path.len() - 1), )); } _ => Err(Determinacy::determined(record_used)), } _ => Err(Determinacy::determined(record_used)), } }; FindBindingResult::Binding(binding) }; let binding = match find_binding_in_ns(self, ns) { FindBindingResult::PathResult(x) => return x, FindBindingResult::Binding(binding) => binding, }; match binding { Ok(binding) => { if i == 1 {"} {"_id":"doc-en-rust-5e374798542cb260387bb043097083a26e87ce4a0e0c57573c66e338d56ec251","title":"","text":"} else if i == 0 { (format!(\"use of undeclared type or module `{}`\", ident), None) } else { (format!(\"could not find `{}` in `{}`\", ident, path[i - 1].ident), None) let mut msg = format!(\"could not find `{}` in `{}`\", ident, path[i - 1].ident); if ns == TypeNS || ns == ValueNS { let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS }; if let FindBindingResult::Binding(Ok(binding)) = find_binding_in_ns(self, ns_to_try) { let mut found = |what| { msg = format!( \"expected {}, found {} `{}` in `{}`\", ns.descr(), what, ident, path[i - 1].ident ) }; if binding.module().is_some() { found(\"module\") } else { match binding.res() { def::Res::::Def(kind, id) => found(kind.descr(id)), _ => found(ns_to_try.descr()), } } }; } (msg, None) }; return PathResult::Failed { span: ident.span,"} {"_id":"doc-en-rust-60a6feca90f316eb29ed665c13eeed8c5469c2fceb7020a45b66efcb50b7eb3c","title":"","text":" use std::sync::mpsc; fn main() { let (tx, rx) = mpsc::channel::new(1); //~^ ERROR expected type, found function `channel` in `mpsc` } "} {"_id":"doc-en-rust-6a4fb80dfdcb8882eba9b22d94407ccd711d9a7363fbcc7865451eac4037f90c","title":"","text":" error[E0433]: failed to resolve: expected type, found function `channel` in `mpsc` --> $DIR/issue-71406.rs:4:26 | LL | let (tx, rx) = mpsc::channel::new(1); | ^^^^^^^ expected type, found function `channel` in `mpsc` error: aborting due to previous error For more information about this error, try `rustc --explain E0433`. "} {"_id":"doc-en-rust-04706eb0e730cc074c33ce48b7d9709da42edb1e419ec8840f7e2938db722087","title":"","text":"&b.item_def_id, ))) } else { let ty = relation.relate(&a.ty, &b.ty)?; let substs = relation.relate(&a.substs, &b.substs)?; let ty = relation.relate_with_variance(ty::Invariant, &a.ty, &b.ty)?; let substs = relation.relate_with_variance(ty::Invariant, &a.substs, &b.substs)?; Ok(ty::ExistentialProjection { item_def_id: a.item_def_id, substs, ty }) } }"} {"_id":"doc-en-rust-7c713e3fa0a14690d4fe470fdd7db5ffea3582fc6f6b0bebb2b01b81352f3c46","title":"","text":"LL | let _ = Box::new(|x| (x as u8)): Box _>; | ^^^^^^^^^^^^^^^^^^^^^^^ expected trait object `dyn std::ops::Fn`, found closure | = note: expected struct `std::boxed::Box _>` = note: expected struct `std::boxed::Box u8>` found struct `std::boxed::Box<[closure@$DIR/coerce-expect-unsized-ascribed.rs:26:22: 26:35]>` error: aborting due to 14 previous errors"} {"_id":"doc-en-rust-51541653772a41037af3eda19a443cf2fbe0962b8d4a801bde51db00e290ca7a","title":"","text":" error[E0277]: the size for values of type `dyn std::iter::Iterator` cannot be known at compilation time error[E0277]: the size for values of type `dyn std::iter::Iterator` cannot be known at compilation time --> $DIR/issue-20605.rs:2:17 | LL | for item in *things { *item = 0 } | ^^^^^^^ doesn't have a size known at compile-time | = help: the trait `std::marker::Sized` is not implemented for `dyn std::iter::Iterator` = help: the trait `std::marker::Sized` is not implemented for `dyn std::iter::Iterator` = note: to learn more, visit = note: required by `std::iter::IntoIterator::into_iter`"} {"_id":"doc-en-rust-af9e8dcecc749139ced3408591aa76f1c39477ec2a38e4f5ed61b0494914a85e","title":"","text":" error: lifetime may not live long enough --> $DIR/variance-associated-types2.rs:13:12 | LL | fn take<'a>(_: &'a u32) { | -- lifetime `'a` defined here LL | let _: Box> = make(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` | = help: consider replacing `'a` with `'static` error: aborting due to previous error "} {"_id":"doc-en-rust-d02ee39f84283a30b164974ea9e510eda396aad1171e60e9e7cc40862d08a801","title":"","text":" // Test that dyn Foo is invariant with respect to T. // Failure to enforce invariance here can be weaponized, see #71550 for details. trait Foo { type Bar; } fn make() -> Box> { panic!() } fn take<'a>(_: &'a u32) { let _: Box> = make(); //~^ ERROR mismatched types [E0308] } fn main() {} "} {"_id":"doc-en-rust-9c1a397ca2afbd2f0b29794967c9366b72cd7c8c4f4f7a4da6c6a1b32e58d868","title":"","text":" error[E0308]: mismatched types --> $DIR/variance-associated-types2.rs:13:42 | LL | let _: Box> = make(); | ^^^^^^ lifetime mismatch | = note: expected trait object `dyn Foo` found trait object `dyn Foo` note: the lifetime `'a` as defined on the function body at 12:9... --> $DIR/variance-associated-types2.rs:12:9 | LL | fn take<'a>(_: &'a u32) { | ^^ = note: ...does not necessarily outlive the static lifetime error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-1130d03eb389b98c1471704e534563b1790a0aa9b995b3845eb1d3da54fe08eb","title":"","text":"printf(\"Available features for this target:n\"); for (auto &Feature : FeatTable) printf(\" %-*s - %s.n\", MaxFeatLen, Feature.Key, Feature.Desc); printf(\"nRust-specific features:n\"); printf(\" %-*s - %s.n\", MaxFeatLen, \"crt-static\", \"Enables libraries with C Run-time Libraries(CRT) to be statically linked\" ); printf(\"n\"); printf(\"Use +feature to enable a feature, or -feature to disable it.n\""} {"_id":"doc-en-rust-8d16b8292d32c7e6dc760c94692a279842f35c1b5b2a976d2bb878186adc7b94","title":"","text":"// We can still be zero-sized in this branch, in which case we have to // return `None`. if size.bytes() == 0 { // We may be reading from a static. // In order to ensure that `static FOO: Type = FOO;` causes a cycle error // instead of magically pulling *any* ZST value from the ether, we need to // actually access the referenced allocation. The caller is likely // to short-circuit on `None`, so we trigger the access here to // make sure it happens. self.get_raw(ptr.alloc_id)?; None } else { Some(ptr) } if size.bytes() == 0 { None } else { Some(ptr) } } }) }"} {"_id":"doc-en-rust-987d82826633507e5aaee37f73ae129781771c1417cd7dd118a830fd6ffb1500","title":"","text":"{ Some(ptr) => ptr, None => { if let Scalar::Ptr(ptr) = mplace.ptr { // We may be reading from a static. // In order to ensure that `static FOO: Type = FOO;` causes a cycle error // instead of magically pulling *any* ZST value from the ether, we need to // actually access the referenced allocation. self.memory.get_raw(ptr.alloc_id)?; } return Ok(Some(ImmTy { // zero-sized type imm: Scalar::zst().into(),"} {"_id":"doc-en-rust-949cabb9647d4cfe27571394df081134180bb18089a3dac12c8cd3ef7115ad4c","title":"","text":" // check-pass // This is a regression test for ICEs from // https://github.com/rust-lang/rust/issues/71612 // and // https://github.com/rust-lang/rust/issues/71709 #[derive(Copy, Clone)] pub struct Glfw; static mut GLFW: Option = None; pub fn new() -> Glfw { unsafe { if let Some(glfw) = GLFW { return glfw; } else { todo!() } }; } extern \"C\" { static _dispatch_queue_attr_concurrent: [u8; 0]; } static DISPATCH_QUEUE_CONCURRENT: &'static [u8; 0] = unsafe { &_dispatch_queue_attr_concurrent }; fn main() { *DISPATCH_QUEUE_CONCURRENT; new(); } "} {"_id":"doc-en-rust-28b6b6e99c07801f6fd47f3cdcad75bcd80da2c2ef6ad1a76cbfc86469401549","title":"","text":"if (!next) { return; } if (next.getElementsByClassName(\"method\").length > 0 && hasClass(e, \"impl\")) { if (hasClass(e, \"impl\") && (next.getElementsByClassName(\"method\").length > 0 || next.getElementsByClassName(\"associatedconstant\").length > 0)) { insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]); } };"} {"_id":"doc-en-rust-a75abe1829b131f834d73336d5b1a8cedfff8962f93f96773e1f46f39ffaab0a","title":"","text":"use crate::middle::cstore::{ExternCrate, ExternCrateSource}; use crate::mir::interpret::{sign_extend, truncate, AllocId, ConstValue, Pointer, Scalar}; use crate::mir::interpret::{ sign_extend, truncate, AllocId, ConstValue, GlobalAlloc, Pointer, Scalar, }; use crate::ty::layout::IntegerExt; use crate::ty::subst::{GenericArg, GenericArgKind, Subst}; use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};"} {"_id":"doc-en-rust-e74ee93613e5393631499d55bce840f557de7716425643ef2e247d02f4fa3496","title":"","text":"}, _, ), ) => { let byte_str = self .tcx() .global_alloc(ptr.alloc_id) .unwrap_memory() .get_bytes(&self.tcx(), ptr, Size::from_bytes(*data)) .unwrap(); p!(pretty_print_byte_str(byte_str)); } ) => match self.tcx().get_global_alloc(ptr.alloc_id) { Some(GlobalAlloc::Memory(alloc)) => { if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), ptr, Size::from_bytes(*data)) { p!(pretty_print_byte_str(byte_str)) } else { p!(write(\"\")) } } // FIXME: for statics and functions, we could in principle print more detail. Some(GlobalAlloc::Static(def_id)) => p!(write(\"\", def_id)), Some(GlobalAlloc::Function(_)) => p!(write(\"\")), None => p!(write(\"\")), }, // Bool (Scalar::Raw { data: 0, .. }, ty::Bool) => p!(write(\"false\")), (Scalar::Raw { data: 1, .. }, ty::Bool) => p!(write(\"true\")),"} {"_id":"doc-en-rust-dc0aca2887b5178a1dd1846f28e4a532babe52d4a7c3e403fb725841436d511e","title":"","text":")?; } (Scalar::Ptr(ptr), ty::FnPtr(_)) => { // FIXME: this can ICE when the ptr is dangling or points to a non-function. // We should probably have a helper method to share code with the \"Byte strings\" // printing above (which also has to handle pointers to all sorts of things). let instance = self.tcx().global_alloc(ptr.alloc_id).unwrap_fn(); self = self.typed_value( |this| this.print_value_path(instance.def_id(), instance.substs),"} {"_id":"doc-en-rust-7257b05b120a34a030016711cba95c99ebc72ff03dab13356e4ee9b260336909","title":"","text":" Subproject commit 77a0125981b293260c9aec6355dff46ec707ab59 Subproject commit 655a1467c98741e332b87661a9046877077ef4dc "} {"_id":"doc-en-rust-3798e21c6481083776265ee24726ad643f19c2a6d392db90f4ec7af4e7107b2a","title":"","text":"} debug!(\"note_type_err(diag={:?})\", diag); enum Mismatch<'a> { Variable(ty::error::ExpectedFound>), Fixed(&'static str), } let (expected_found, exp_found, is_simple_error) = match values { None => (None, None, false), None => (None, Mismatch::Fixed(\"type\"), false), Some(values) => { let (is_simple_error, exp_found) = match values { ValuePairs::Types(exp_found) => {"} {"_id":"doc-en-rust-c9ca9191a6deb85fc807f052fef346cc2f31b3cf18b9a024ff347aadfb2ce416","title":"","text":") .report(diag); (is_simple_err, Some(exp_found)) (is_simple_err, Mismatch::Variable(exp_found)) } _ => (false, None), ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed(\"trait\")), _ => (false, Mismatch::Fixed(\"type\")), }; let vals = match self.values_str(&values) { Some((expected, found)) => Some((expected, found)),"} {"_id":"doc-en-rust-53d627d48b9f4687845c22b7cff4737b5ff19600209502f55a0341bfb64d0d55","title":"","text":"} }; if let Some((expected, found)) = expected_found { let expected_label = exp_found.map_or(\"type\".into(), |ef| ef.expected.prefix_string()); let found_label = exp_found.map_or(\"type\".into(), |ef| ef.found.prefix_string()); let expected_label = match exp_found { Mismatch::Variable(ef) => ef.expected.prefix_string(), Mismatch::Fixed(s) => s.into(), }; let found_label = match exp_found { Mismatch::Variable(ef) => ef.found.prefix_string(), Mismatch::Fixed(s) => s.into(), }; let exp_found = match exp_found { Mismatch::Variable(exp_found) => Some(exp_found), Mismatch::Fixed(_) => None, }; match (&terr, expected == found) { (TypeError::Sorts(values), extra) => { let sort_string = |ty: Ty<'tcx>| match (extra, &ty.kind) {"} {"_id":"doc-en-rust-3fa1cc67dc95899a8185fe2b72b6e46cbfbf90e81b91429595d5275572b52903","title":"","text":"} } } let exp_found = match exp_found { Mismatch::Variable(exp_found) => Some(exp_found), Mismatch::Fixed(_) => None, }; if let Some(exp_found) = exp_found { self.suggest_as_ref_where_appropriate(span, &exp_found, diag); }"} {"_id":"doc-en-rust-220c06ccea47412f6bce7f24662d445304e9e83d338124ca8aa1000ab8db8e74","title":"","text":" trait DynEq {} impl<'a> PartialEq for &'a (dyn DynEq + 'static) { fn eq(&self, _other: &Self) -> bool { true } } impl Eq for &dyn DynEq {} //~ ERROR E0308 fn main() { } "} {"_id":"doc-en-rust-a4cd395090ec6152b68cd6c44032c30a9595ce301123e2fa85ca48f23b012351","title":"","text":" error[E0308]: mismatched types --> $DIR/E0308-2.rs:9:6 | LL | impl Eq for &dyn DynEq {} | ^^ lifetime mismatch | = note: expected trait `std::cmp::PartialEq` found trait `std::cmp::PartialEq` note: the lifetime `'_` as defined on the impl at 9:13... --> $DIR/E0308-2.rs:9:13 | LL | impl Eq for &dyn DynEq {} | ^ = note: ...does not necessarily outlive the static lifetime error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-8317a1d4eb7e15aa2d44bb2d481f93c5f0cc893eeea347c80466c0d87929b7ed","title":"","text":" // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! 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":"doc-en-rust-9764f9e3b31d11297b5310bbca4454373f440ec511a197d05720ba8c8b3b2cac","title":"","text":" // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! 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":"doc-en-rust-5c403273909425ec01c762dcda1727b548953d9bdc8d4d969c4ee3927be2404c","title":"","text":" // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! 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":"doc-en-rust-ddea2bffcc042993a01b929d5e2daea658bb84856dab22b7abb7b540d565adf0","title":"","text":"pub mod c_str; pub mod os; pub mod path; pub mod path2; pub mod rand; pub mod run; pub mod sys;"} {"_id":"doc-en-rust-acd0836ec6130667cba23d990c0eb99bfdd34d1aa97e733a99b2b251200d1b8e","title":"","text":"// check that a comma comes after every field if !ate_comma { let err = ExpectedCommaAfterPatternField { span: self.token.span } let mut err = ExpectedCommaAfterPatternField { span: self.token.span } .into_diagnostic(&self.sess.span_diagnostic); if let Some(mut delayed) = delayed_err { delayed.emit(); } self.recover_misplaced_pattern_modifiers(&fields, &mut err); return Err(err); } ate_comma = false;"} {"_id":"doc-en-rust-2c25bf1c6e12a6c860426ad77b8209ce4ca8c1210d9348fa2055204b3ce805f7","title":"","text":"Ok((fields, etc)) } /// 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 DiagnosticBuilder<'a, ErrorGuaranteed>, ) { if let Some(last) = fields.iter().last() && last.is_shorthand && let PatKind::Ident(binding, ident, None) = last.pat.kind && binding != BindingAnnotation::NONE && self.token == token::Colon // We found `ref mut? ident:`, try to parse a `name,` or `name }`. && let Some(name_span) = self.look_ahead(1, |t| t.is_ident().then(|| t.span)) && self.look_ahead(2, |t| { t == &token::Comma || t == &token::CloseDelim(Delimiter::Brace) }) { let span = last.pat.span.with_hi(ident.span.lo()); // We have `S { ref field: name }` instead of `S { field: ref name }` err.multipart_suggestion( \"the pattern modifiers belong after the `:`\", vec![ (span, String::new()), (name_span.shrink_to_lo(), binding.prefix_str().to_string()), ], Applicability::MachineApplicable, ); } } /// Recover on `...` or `_` as if it were `..` to avoid further errors. /// See issue #46718. fn recover_bad_dot_dot(&self) {"} {"_id":"doc-en-rust-38ea225a6c1ca5015761bb043ddf88af60326b5e38824e9af096b9135aba61cb","title":"","text":" // run-rustfix struct S { field_name: (), } fn main() { match (S {field_name: ()}) { S {field_name: ref _foo} => {} //~ ERROR expected `,` } match (S {field_name: ()}) { S {field_name: mut _foo} => {} //~ ERROR expected `,` } match (S {field_name: ()}) { S {field_name: ref mut _foo} => {} //~ ERROR expected `,` } // Verify that we recover enough to run typeck. let _: usize = 3usize; //~ ERROR mismatched types } "} {"_id":"doc-en-rust-3bbe28e9d2dd3db6772dde234c493f1bd22358d2c6f124c70ac8e7125b8fd740","title":"","text":" // run-rustfix struct S { field_name: (), } fn main() { match (S {field_name: ()}) { S {ref field_name: _foo} => {} //~ ERROR expected `,` } match (S {field_name: ()}) { S {mut field_name: _foo} => {} //~ ERROR expected `,` } match (S {field_name: ()}) { S {ref mut field_name: _foo} => {} //~ ERROR expected `,` } // Verify that we recover enough to run typeck. let _: usize = 3u8; //~ ERROR mismatched types } "} {"_id":"doc-en-rust-b127c872129e80cdc8811755da4c1b6d2cd1d3510ec0764648f46e19322f7908","title":"","text":" error: expected `,` --> $DIR/incorrect-placement-of-pattern-modifiers.rs:8:26 | LL | S {ref field_name: _foo} => {} | - ^ | | | while parsing the fields for this pattern | help: the pattern modifiers belong after the `:` | LL - S {ref field_name: _foo} => {} LL + S {field_name: ref _foo} => {} | error: expected `,` --> $DIR/incorrect-placement-of-pattern-modifiers.rs:11:26 | LL | S {mut field_name: _foo} => {} | - ^ | | | while parsing the fields for this pattern | help: the pattern modifiers belong after the `:` | LL - S {mut field_name: _foo} => {} LL + S {field_name: mut _foo} => {} | error: expected `,` --> $DIR/incorrect-placement-of-pattern-modifiers.rs:14:30 | LL | S {ref mut field_name: _foo} => {} | - ^ | | | while parsing the fields for this pattern | help: the pattern modifiers belong after the `:` | LL - S {ref mut field_name: _foo} => {} LL + S {field_name: ref mut _foo} => {} | error[E0308]: mismatched types --> $DIR/incorrect-placement-of-pattern-modifiers.rs:17:20 | LL | let _: usize = 3u8; | ----- ^^^ expected `usize`, found `u8` | | | expected due to this | help: change the type of the numeric literal from `u8` to `usize` | LL | let _: usize = 3usize; | ~~~~~ error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-05c01ac752dd7f5472d1b4d8618a40e8a1a8df46c28cdd8f4126a9aa419be9ef","title":"","text":") )] #[doc(alias = \"?\")] #[cfg_attr(not(bootstrap), lang = \"try\")] pub trait Try { /// The type of this value when viewed as successful. #[unstable(feature = \"try_trait\", issue = \"42327\")]"} {"_id":"doc-en-rust-6f88b441389c9b82aef4dedba9fba092a019751ecf5eeca0e4145807a2c639c2","title":"","text":"AlignOffsetLangItem, \"align_offset\", align_offset_fn, Target::Fn; TerminationTraitLangItem, \"termination\", termination, Target::Trait; TryTraitLangItem, \"try\", try_trait, Target::Trait; }"} {"_id":"doc-en-rust-2ecc54f1b208da93fd56ae553be730726b09721f6baceb03c7ef0b026c92072e","title":"","text":"self.suggest_remove_reference(&obligation, &mut err, &trait_ref); self.suggest_semicolon_removal(&obligation, &mut err, span, &trait_ref); self.note_version_mismatch(&mut err, &trait_ref); self.suggest_await_before_try(&mut err, &obligation, &trait_ref, span); if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() { self.suggest_await_before_try(&mut err, &obligation, &trait_ref, span); } if self.suggest_impl_trait(&mut err, span, &obligation, &trait_ref) { err.emit(); return;"} {"_id":"doc-en-rust-91fd0442f780979a1e416c884676222d2846b94b88513f9f3de16d1c750cd08b","title":"","text":" // edition:2018 // compile-flags:-Cincremental=tmp/issue-72442 use std::fs::File; use std::future::Future; use std::io::prelude::*; fn main() -> Result<(), Box> { block_on(async { { let path = std::path::Path::new(\".\"); let mut f = File::open(path.to_str())?; //~^ ERROR the trait bound let mut src = String::new(); f.read_to_string(&mut src)?; Ok(()) } }) } fn block_on(f: F) -> F::Output where F: Future>>, { Ok(()) } "} {"_id":"doc-en-rust-d48c7642f61a5881e3d05a1dbe96bc0955b4c9598cb8df1070abae00bfd1e742","title":"","text":" error[E0277]: the trait bound `std::option::Option<&str>: std::convert::AsRef` is not satisfied --> $DIR/issue-72442.rs:12:36 | LL | let mut f = File::open(path.to_str())?; | ^^^^^^^^^^^^^ the trait `std::convert::AsRef` is not implemented for `std::option::Option<&str>` | ::: $SRC_DIR/libstd/fs.rs:LL:COL | LL | pub fn open>(path: P) -> io::Result { | ----------- required by this bound in `std::fs::File::open` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-bdf948d1625515fc81c71d3316ef7a97dfcc775d7ad44283f0670bf7eef2c3ad","title":"","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":"doc-en-rust-2abb820698ea4907c22db32c025f3f67631b7a2300c0c0f28a2933978cdd0572","title":"","text":" fn main() { // There shall be no suggestions here. In particular not `Ok`. let _ = 读文; //~ ERROR cannot find value `读文` in this scope } "} {"_id":"doc-en-rust-befcf4ac885f1d734830dc2b3a94cbb9ef12d9cfefbdb2a81658b13c58e3eb80","title":"","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":"doc-en-rust-0da68f2af998d3554d58742746dfbf839625bc293cb10433b8feee9e2c4cb10a","title":"","text":"fn default() -> Self; } /// Return the default value of a type according to the `Default` trait. /// /// The type to return is inferred from context; this is equivalent to /// `Default::default()` but shorter to type. /// /// For example: /// ``` /// #![feature(default_free_fn)] /// /// use std::default::default; /// /// #[derive(Default)] /// struct AppConfig { /// foo: FooConfig, /// bar: BarConfig, /// } /// /// #[derive(Default)] /// struct FooConfig { /// foo: i32, /// } /// /// #[derive(Default)] /// struct BarConfig { /// bar: f32, /// baz: u8, /// } /// /// fn main() { /// let options = AppConfig { /// foo: default(), /// bar: BarConfig { /// bar: 10.1, /// ..default() /// }, /// }; /// } /// ``` #[unstable(feature = \"default_free_fn\", issue = \"73014\")] #[must_use] #[inline] pub fn default() -> T { Default::default() } /// Derive macro generating an impl of the trait `Default`. #[rustc_builtin_macro(Default, attributes(default))] #[stable(feature = \"builtin_macro_prelude\", since = \"1.38.0\")]"} {"_id":"doc-en-rust-f5fdfd39d2ad7bc79b070db382a53a5b6c3ac130f06378b2032c1e26d8b98f43","title":"","text":" # `default_free_fn` The tracking issue for this feature is: [#73014] [#73014]: https://github.com/rust-lang/rust/issues/73014 ------------------------ Adds a free `default()` function to the `std::default` module. This function just forwards to [`Default::default()`], but may remove repetition of the word \"default\" from the call site. [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default Here is an example: ```rust #![feature(default_free_fn)] use std::default::default; #[derive(Default)] struct AppConfig { foo: FooConfig, bar: BarConfig, } #[derive(Default)] struct FooConfig { foo: i32, } #[derive(Default)] struct BarConfig { bar: f32, baz: u8, } fn main() { let options = AppConfig { foo: default(), bar: BarConfig { bar: 10.1, ..default() }, }; } ``` "} {"_id":"doc-en-rust-68feeeba64b5bb5da8a5d6199d0ad8923aeed24ea429171028602ef8c7fa8cf9","title":"","text":" error[E0425]: cannot find function `default` in this scope --> $DIR/issue-2356.rs:31:5 | LL | default(); | ^^^^^^^ | help: you might have meant to call the associated function | LL | Self::default(); | ~~~~~~~~~~~~~ help: consider importing this function | LL + use std::default::default; | error[E0425]: cannot find value `whiskers` in this scope --> $DIR/issue-2356.rs:39:5 |"} {"_id":"doc-en-rust-874c065d9d2a20e657ae4d25675b7514c88d51e8eef26b48f9602a9a63549f3b","title":"","text":"LL | clone(); | ^^^^^ help: you might have meant to call the method: `self.clone` error[E0425]: cannot find function `default` in this scope --> $DIR/issue-2356.rs:31:5 | LL | default(); | ^^^^^^^ help: you might have meant to call the associated function: `Self::default` error[E0425]: cannot find function `shave` in this scope --> $DIR/issue-2356.rs:41:5 |"} {"_id":"doc-en-rust-39c3e88b9381d1647bd20f37dd88087dc5f3468226601f793622e329fa8f31b1","title":"","text":"// As write_sub_paths, but does not process the last ident in the path (assuming it // will be processed elsewhere). See note on write_sub_paths about global. fn write_sub_paths_truncated(&mut self, path: &'tcx hir::Path<'tcx>) { for seg in &path.segments[..path.segments.len() - 1] { if let Some(data) = self.save_ctxt.get_path_segment_data(seg) { self.dumper.dump_ref(data); if let [segments @ .., _] = path.segments { for seg in segments { if let Some(data) = self.save_ctxt.get_path_segment_data(seg) { self.dumper.dump_ref(data); } } } }"} {"_id":"doc-en-rust-4dee3d48839879b329150a5e81af8189769bfb5a7c48a22734c750b2f3bb89a6","title":"","text":"} } } hir::ExprKind::Struct(hir::QPath::Resolved(_, path), ..) => { hir::ExprKind::Struct(qpath, ..) => { let segment = match qpath { hir::QPath::Resolved(_, path) => path.segments.last().unwrap(), hir::QPath::TypeRelative(_, segment) => segment, }; match self.tables.expr_ty_adjusted(&hir_node).kind { ty::Adt(def, _) if !def.is_enum() => { let sub_span = path.segments.last().unwrap().ident.span; let sub_span = segment.ident.span; filter!(self.span_utils, sub_span); let span = self.span_from_span(sub_span); Some(Data::RefData(Ref {"} {"_id":"doc-en-rust-714532ff63f605b2708cebb978fc0c9190b3cb8f67b729c443541c2ad7f4c4e0","title":"","text":"} _ => { // FIXME bug!(); bug!(\"invalid expression: {:?}\", expr); } } }"} {"_id":"doc-en-rust-4957270aa6b6034274f84e74d3aede675524138ee6bb57197feee6e9b19433aa","title":"","text":" // compile-flags: -Zsave-analysis use {self}; //~ ERROR E0431 fn main () { } "} {"_id":"doc-en-rust-01dc33c36ddba47fb9c83c80aef7ac769e15bd45789309b78570a290d71e2172","title":"","text":" error[E0431]: `self` import can only appear in an import list with a non-empty prefix --> $DIR/issue-73020.rs:2:6 | LL | use {self}; | ^^^^ can only appear in an import list with a non-empty prefix error: aborting due to previous error For more information about this error, try `rustc --explain E0431`. "} {"_id":"doc-en-rust-872209a0ed43d2d997e72f83489275b62c2036af22da6b7047b066051983a6bd","title":"","text":" // build-pass // compile-flags: -Zsave-analysis enum Enum2 { Variant8 { _field: bool }, } impl Enum2 { fn new_variant8() -> Enum2 { Self::Variant8 { _field: true } } } fn main() {} "} {"_id":"doc-en-rust-7b56d10a5d4480a39b01a71e37991cf1d2f380afd8bc4dad46027518801ba001","title":"","text":"use rustc_hir::lang_items::{ FutureTraitLangItem, PinTypeLangItem, SizedTraitLangItem, VaListTypeLangItem, }; use rustc_hir::{ExprKind, GenericArg, HirIdMap, Item, ItemKind, Node, PatKind, QPath}; use rustc_hir::{ExprKind, GenericArg, HirIdMap, ItemKind, Node, PatKind, QPath}; use rustc_index::bit_set::BitSet; use rustc_index::vec::Idx; use rustc_infer::infer;"} {"_id":"doc-en-rust-d6eee26562a556bc0e03096712b5ce2c96771daa4ebced8cc2d0ab472505cb1e","title":"","text":"\"packed type cannot transitively contain a `#[repr(align)]` type\" ); let hir = tcx.hir(); let hir_id = hir.as_local_hir_id(def_spans[0].0.expect_local()); if let Node::Item(Item { ident, .. }) = hir.get(hir_id) { err.span_note( tcx.def_span(def_spans[0].0), &format!(\"`{}` has a `#[repr(align)]` attribute\", ident), ); } err.span_note( tcx.def_span(def_spans[0].0), &format!( \"`{}` has a `#[repr(align)]` attribute\", tcx.item_name(def_spans[0].0) ), ); if def_spans.len() > 2 { let mut first = true; for (adt_def, span) in def_spans.iter().skip(1).rev() { let hir_id = hir.as_local_hir_id(adt_def.expect_local()); if let Node::Item(Item { ident, .. }) = hir.get(hir_id) { err.span_note( *span, &if first { format!( \"`{}` contains a field of type `{}`\", tcx.type_of(def.did), ident ) } else { format!(\"...which contains a field of type `{}`\", ident) }, ); first = false; } let ident = tcx.item_name(*adt_def); err.span_note( *span, &if first { format!( \"`{}` contains a field of type `{}`\", tcx.type_of(def.did), ident ) } else { format!(\"...which contains a field of type `{}`\", ident) }, ); first = false; } }"} {"_id":"doc-en-rust-670798e905a9c00b2ad0121862ae3ac74d17f6bb77563d23c31adcae5aefe466","title":"","text":" #[repr(transparent)] pub struct PageTableEntry { entry: u64, } #[repr(align(4096))] #[repr(C)] pub struct PageTable { entries: [PageTableEntry; 512], } "} {"_id":"doc-en-rust-8cb4bfaca9d6ad02cdfc0513f1d02486c8821a1ec17b8f65621375b905aeea69","title":"","text":" // aux-build:issue-73112.rs extern crate issue_73112; fn main() { use issue_73112::PageTable; #[repr(C, packed)] struct SomeStruct { //~^ ERROR packed type cannot transitively contain a `#[repr(align)]` type [E0588] page_table: PageTable, } } "} {"_id":"doc-en-rust-d551586fe7726e87b236d6fd77d1f7675856106e245253086a8aa53bf3afa46a","title":"","text":" error[E0588]: packed type cannot transitively contain a `#[repr(align)]` type --> $DIR/issue-73112.rs:9:5 | LL | / struct SomeStruct { LL | | LL | | page_table: PageTable, LL | | } | |_____^ | note: `PageTable` has a `#[repr(align)]` attribute --> $DIR/auxiliary/issue-73112.rs:8:1 | LL | / pub struct PageTable { LL | | entries: [PageTableEntry; 512], LL | | } | |_^ error: aborting due to previous error For more information about this error, try `rustc --explain E0588`. "} {"_id":"doc-en-rust-ccca5b0632fcfeb54b32d1f72f4a5a25ade2ed8cfedd75add87b6a27c6be42b4","title":"","text":"/// but shebang isn't a part of rust syntax. pub fn strip_shebang(input: &str) -> Option { // Shebang must start with `#!` literally, without any preceding whitespace. if input.starts_with(\"#!\") { let input_tail = &input[2..]; // Shebang must have something non-whitespace after `#!` on the first line. let first_line_tail = input_tail.lines().next()?; if first_line_tail.contains(|c| !is_whitespace(c)) { // Ok, this is a shebang but if the next non-whitespace token is `[` or maybe // a doc comment (due to `TokenKind::(Line,Block)Comment` ambiguity at lexer level), // then it may be valid Rust code, so consider it Rust code. let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| !matches!(tok, TokenKind::Whitespace | TokenKind::LineComment | TokenKind::BlockComment { .. }) ); if next_non_whitespace_token != Some(TokenKind::OpenBracket) { // No other choice than to consider this a shebang. return Some(2 + first_line_tail.len()); } // For simplicity we consider any line starting with `#!` a shebang, // regardless of restrictions put on shebangs by specific platforms. if let Some(input_tail) = input.strip_prefix(\"#!\") { // Ok, this is a shebang but if the next non-whitespace token is `[` or maybe // a doc comment (due to `TokenKind::(Line,Block)Comment` ambiguity at lexer level), // then it may be valid Rust code, so consider it Rust code. let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| !matches!(tok, TokenKind::Whitespace | TokenKind::LineComment | TokenKind::BlockComment { .. }) ); if next_non_whitespace_token != Some(TokenKind::OpenBracket) { // No other choice than to consider this a shebang. return Some(2 + input_tail.lines().next().unwrap_or_default().len()); } } None"} {"_id":"doc-en-rust-8fcf590ea2ef2e960018095d720eff62bf5eef4930e5aa65dfdddd5e40a3ef27","title":"","text":" #! // check-pass fn main() {} "} {"_id":"doc-en-rust-3d986348461e3495d87c921eacfb99fdadb110a43d73c5d3bd552e3da6ed538b","title":"","text":" #! // check-pass // ignore-tidy-end-whitespace fn main() {} "} {"_id":"doc-en-rust-c4da4e066acd48bf4c504ab7d03e9b9ac438a5026643ab3ae219b78f43a50481","title":"","text":" #!/usr/bin/env rustx // run-pass pub fn main() { println!(\"Hello World\"); } "} {"_id":"doc-en-rust-d9a2349486f2ac83809e118eb65e5628c07d9ef0290f05b8fc83a2cad08dce5d","title":"","text":"debug!(\"QueryNormalizer: result = {:#?}\", result); debug!(\"QueryNormalizer: obligations = {:#?}\", obligations); self.obligations.extend(obligations); Ok(result.normalized_ty) let res = result.normalized_ty; // `tcx.normalize_projection_ty` may normalize to a type that still has // unevaluated consts, so keep normalizing here if that's the case. if res != ty && res.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) { Ok(res.try_super_fold_with(self)?) } else { Ok(res) } } ty::Projection(data) => {"} {"_id":"doc-en-rust-4c10c20c68f52310151407fb648a283b0193d57cbb627454ddf2c7b38265bac5","title":"","text":"debug!(\"QueryNormalizer: result = {:#?}\", result); debug!(\"QueryNormalizer: obligations = {:#?}\", obligations); self.obligations.extend(obligations); Ok(crate::traits::project::PlaceholderReplacer::replace_placeholders( let res = crate::traits::project::PlaceholderReplacer::replace_placeholders( infcx, mapped_regions, mapped_types, mapped_consts, &self.universes, result.normalized_ty, )) ); // `tcx.normalize_projection_ty` may normalize to a type that still has // unevaluated consts, so keep normalizing here if that's the case. if res != ty && res.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) { Ok(res.try_super_fold_with(self)?) } else { Ok(res) } } _ => ty.try_super_fold_with(self), })()?; self.cache.insert(ty, res); Ok(res) }"} {"_id":"doc-en-rust-9e0d2963a7063282ea1c541378620b0b8f5ffe1cd3cf1273acc25503d9508e5d","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] trait TraitOne { const MY_NUM: usize; type MyErr: std::fmt::Debug; fn do_one_stuff(arr: [u8; Self::MY_NUM]) -> Result<(), Self::MyErr>; } trait TraitTwo { fn do_two_stuff(); } impl TraitTwo for O where [(); Self::MY_NUM]:, { fn do_two_stuff() { O::do_one_stuff([5; Self::MY_NUM]).unwrap() } } struct Blargotron; #[derive(Debug)] struct ErrTy([(); N]); impl TraitOne for Blargotron { const MY_NUM: usize = 3; type MyErr = ErrTy<{ Self::MY_NUM }>; fn do_one_stuff(_arr: [u8; Self::MY_NUM]) -> Result<(), Self::MyErr> { Ok(()) } } fn main() { Blargotron::do_two_stuff(); } "} {"_id":"doc-en-rust-4ef1badb8b4e66a0481061d956ea2f925348b4208a4892dc4ac9306eca0f0830","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] use std::convert::AsMut; use std::default::Default; trait Foo: Sized { type Baz: Default + AsMut<[u8]>; fn bar() { Self::Baz::default().as_mut(); } } impl Foo for () { type Baz = [u8; 1 * 1]; //type Baz = [u8; 1]; } fn main() { <() as Foo>::bar(); } "} {"_id":"doc-en-rust-60d8c8ca4707ea67dfc47eb24b5a64bf3b33eda5b8e60fc1d1e31bdd9a29cff4","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] trait Collate { type Pass; type Fail; fn collate(self) -> (Self::Pass, Self::Fail); } impl Collate for () { type Pass = (); type Fail = (); fn collate(self) -> ((), ()) { ((), ()) } } trait CollateStep { type Pass; type Fail; fn collate_step(x: X, prev: Prev) -> (Self::Pass, Self::Fail); } impl CollateStep for () { type Pass = (X, P); type Fail = F; fn collate_step(x: X, (p, f): (P, F)) -> ((X, P), F) { ((x, p), f) } } struct CollateOpImpl; trait CollateOpStep { type NextOp; type Apply; } impl CollateOpStep for CollateOpImpl where CollateOpImpl<{ MASK >> 1 }>: Sized, { type NextOp = CollateOpImpl<{ MASK >> 1 }>; type Apply = (); } impl Collate for (H, T) where T: Collate, Op::Apply: CollateStep, { type Pass = >::Pass; type Fail = >::Fail; fn collate(self) -> (Self::Pass, Self::Fail) { >::collate_step(self.0, self.1.collate()) } } fn collate(x: X) -> (X::Pass, X::Fail) where X: Collate>, { x.collate() } fn main() { dbg!(collate::<_, 5>((\"Hello\", (42, ('!', ()))))); } "} {"_id":"doc-en-rust-dbbb603c5fcc6d5c259f92dbcb0a72c4326cd35c656ab9df4213724672071c38","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] pub trait Foo { fn foo(&self); } pub struct FooImpl; impl Foo for FooImpl { fn foo(&self) {} } pub trait Bar: 'static { type Foo: Foo; fn get() -> &'static Self::Foo; } struct BarImpl; impl Bar for BarImpl { type Foo = FooImpl< { { 4 } }, >; fn get() -> &'static Self::Foo { &FooImpl } } pub fn boom() { B::get().foo(); } fn main() { boom::(); } "} {"_id":"doc-en-rust-384001e7b0aaedf7cb8681fc4e0450067900e9fcf6c15abef529b28445d22f31","title":"","text":" // build-pass #![feature(generic_const_exprs)] #![allow(incomplete_features)] trait Foo { type Output; fn foo() -> Self::Output; } impl Foo for [u8; 3] { type Output = [u8; 1 + 2]; fn foo() -> [u8; 3] { [1u8; 3] } } fn bug() where [u8; N]: Foo, <[u8; N] as Foo>::Output: AsRef<[u8]>, { <[u8; N]>::foo().as_ref(); } fn main() { bug::<3>(); } "} {"_id":"doc-en-rust-d6238cb6db88702eea712aa5a0b07b35fcd2b219ef44271d00151cb8860d3698","title":"","text":" // build-pass #![allow(incomplete_features)] #![feature(generic_const_exprs)] use std::marker::PhantomData; fn main() { let x = FooImpl::> { phantom: PhantomData }; let _ = x.foo::>(); } trait Foo where T: Bar, { fn foo(&self) where T: Operation, >::Output: Bar; } struct FooImpl where T: Bar, { phantom: PhantomData, } impl Foo for FooImpl where T: Bar, { fn foo(&self) where T: Operation, >::Output: Bar, { <>::Output as Bar>::error_occurs_here(); } } trait Bar { fn error_occurs_here(); } struct BarImpl; impl Bar for BarImpl { fn error_occurs_here() {} } trait Operation { type Output; } //// Part-A: This causes error. impl Operation> for BarImpl where BarImpl<{ N + M }>: Sized, { type Output = BarImpl<{ N + M }>; } //// Part-B: This doesn't cause error. // impl Operation> for BarImpl { // type Output = BarImpl; // } //// Part-C: This also doesn't cause error. // impl Operation> for BarImpl { // type Output = BarImpl<{ M }>; // } "} {"_id":"doc-en-rust-8075a9ff8d6ea750ebbdaf8ca45e2734434ecece456d18e35f819199c32907a5","title":"","text":"generics: &Generics, fields: &[@struct_field], visitor: ResolveVisitor) { let mut ident_map = HashMap::new::(); for fields.iter().advance |&field| { match field.node.kind { named_field(ident, _) => { match ident_map.find(&ident) { Some(&prev_field) => { let ident_str = self.session.str_of(ident); self.session.span_err(field.span, fmt!(\"field `%s` is already declared\", ident_str)); self.session.span_note(prev_field.span, \"Previously declared here\"); }, None => { ident_map.insert(ident, field); } } } _ => () } } // If applicable, create a rib for the type parameters. do self.with_type_parameter_rib(HasTypeParameters (generics, id, 0,"} {"_id":"doc-en-rust-0e70cc38cdbb01e65caa870450080966ea02365d8339b56ac8bae4e916c939b1","title":"","text":" // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct BuildData { foo: int, foo: int, //~ ERROR field `foo` is already declared } fn main() { } "} {"_id":"doc-en-rust-017cbc72e8a9356e0f8c22f86564474660659c07b614acdb595bc939a9d952b7","title":"","text":"/// This can be used to safely get a strong reference (by calling [`upgrade`] /// later) or to deallocate the weak count by dropping the `Weak`. /// /// It takes ownership of one weak count (with the exception of pointers created by [`new`], /// as these don't have any corresponding weak count). /// It takes ownership of one weak reference (with the exception of pointers created by [`new`], /// as these don't own anything; the method still works on them). /// /// # Safety /// /// The pointer must have originated from the [`into_raw`] and must still own its potential /// weak reference count. /// The pointer must have originated from the [`into_raw`] and must still own its potential /// weak reference. /// /// It is allowed for the strong count to be 0 at the time of calling this, but the weak count /// must be non-zero or the pointer must have originated from a dangling `Weak` (one created /// by [`new`]). /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this /// takes ownership of one weak reference currently represented as a raw pointer (the weak /// count is not modified by this operation) and therefore it must be paired with a previous /// call to [`into_raw`]. /// /// # Examples ///"} {"_id":"doc-en-rust-1e314e75766469e5419ea1ac40514b6ae43e55aa1a823aa82c5e80100b6fc24f","title":"","text":"/// Consumes the `Weak` and turns it into a raw pointer. /// /// This converts the weak pointer into a raw pointer, preserving the original weak count. It /// can be turned back into the `Weak` with [`from_raw`]. /// This converts the weak pointer into a raw pointer, while still preserving the ownership of /// one weak reference (the weak count is not modified by this operation). It can be turned /// back into the `Weak` with [`from_raw`]. /// /// The same restrictions of accessing the target of the pointer as with /// [`as_ptr`] apply."} {"_id":"doc-en-rust-1762b8109281a6c23ec760b7f0b11eec39286e768dd828282a82855d2c487ff7","title":"","text":"result } /// Converts a raw pointer previously created by [`into_raw`] back into /// `Weak`. /// Converts a raw pointer previously created by [`into_raw`] back into `Weak`. /// /// This can be used to safely get a strong reference (by calling [`upgrade`] /// later) or to deallocate the weak count by dropping the `Weak`. /// /// It takes ownership of one weak count (with the exception of pointers created by [`new`], /// as these don't have any corresponding weak count). /// It takes ownership of one weak reference (with the exception of pointers created by [`new`], /// as these don't own anything; the method still works on them). /// /// # Safety /// /// The pointer must have originated from the [`into_raw`] and must still own its potential /// weak reference count. /// /// It is allowed for the strong count to be 0 at the time of calling this, but the weak count /// must be non-zero or the pointer must have originated from a dangling `Weak` (one created /// by [`new`]). /// weak reference. /// /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this /// takes ownership of one weak reference currently represented as a raw pointer (the weak /// count is not modified by this operation) and therefore it must be paired with a previous /// call to [`into_raw`]. /// # Examples /// /// ```"} {"_id":"doc-en-rust-af365a76a959741d2cbf49876c339f786776c5660635edb87f0696ad28278c29","title":"","text":"Greater | // `{ 42 } > 3` GreaterEqual | // `{ 42 } >= 3` AssignOp(_) | // `{ 42 } +=` LAnd | // `{ 42 } &&foo` As | // `{ 42 } as usize` // Equal | // `{ 42 } == { 42 }` Accepting these here would regress incorrect // NotEqual | // `{ 42 } != { 42 } struct literals parser recovery."} {"_id":"doc-en-rust-1f2dd0ac1d1369b753b38aa3205253bbafd8eaa5b97d768a2f510ba2e8343638","title":"","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::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()) => { if !self.look_ahead(1, |t| t.is_used_keyword()) => { // 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(AssocOp::LAnd)) => { // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`. Separated from the // above due to #74233. // 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);"} {"_id":"doc-en-rust-2e1493202f57516ddd69378154c3fefd8a3cf225266b9e96d5011e3b3856034d","title":"","text":"} self.suggest_boxing_when_appropriate(err, expr, expected, expr_ty); self.suggest_missing_await(err, expr, expected, expr_ty); self.suggest_missing_parentheses(err, expr); self.note_need_for_fn_pointer(err, expected, expr_ty); }"} {"_id":"doc-en-rust-603612eba64d009f4f98ac411d1bcc8914219489af54323a098d304eff0eca6a","title":"","text":"} } fn suggest_missing_parentheses(&self, err: &mut DiagnosticBuilder<'_>, expr: &hir::Expr<'_>) { let sp = self.tcx.sess.source_map().start_point(expr.span); if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) { // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }` self.tcx.sess.parse_sess.expr_parentheses_needed(err, *sp, None); } } fn note_need_for_fn_pointer( &self, err: &mut DiagnosticBuilder<'_>,"} {"_id":"doc-en-rust-5f387b3bd5b9d3f2dbe8a190f9409da8ade059a46ea072ebdf55a57e7bc28714","title":"","text":" // This is not autofixable because we give extra suggestions to end the first expression with `;`. fn foo(a: Option, b: Option) -> bool { if let Some(x) = a { true } else { false } //~^ ERROR mismatched types //~| ERROR mismatched types && //~ ERROR mismatched types if let Some(y) = a { true } else { false } } fn main() {} "} {"_id":"doc-en-rust-b157ee8815497b02894a2d35fd255ddd708c51eea8a8944291389b7620207366","title":"","text":" error[E0308]: mismatched types --> $DIR/expr-as-stmt-2.rs:3:26 | LL | if let Some(x) = a { true } else { false } | ---------------------^^^^------------------ help: consider using a semicolon here | | | | | expected `()`, found `bool` | expected this to be `()` error[E0308]: mismatched types --> $DIR/expr-as-stmt-2.rs:3:40 | LL | if let Some(x) = a { true } else { false } | -----------------------------------^^^^^--- help: consider using a semicolon here | | | | | expected `()`, found `bool` | expected this to be `()` error[E0308]: mismatched types --> $DIR/expr-as-stmt-2.rs:6:5 | LL | fn foo(a: Option, b: Option) -> bool { | ---- expected `bool` because of return type LL | if let Some(x) = a { true } else { false } | ------------------------------------------ help: parentheses are required to parse this as an expression: `(if let Some(x) = a { true } else { false })` ... LL | / && LL | | if let Some(y) = a { true } else { false } | |______________________________________________^ expected `bool`, found `&&bool` error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-db3143fa5c5055171a55dd05b30d117cd1ef07d5c14c85a9e309b3b16f920c17","title":"","text":"//~^ ERROR mismatched types } fn qux(a: Option, b: Option) -> bool { (if let Some(x) = a { true } else { false }) && //~ ERROR expected expression if let Some(y) = a { true } else { false } } fn moo(x: u32) -> bool { (match x { _ => 1,"} {"_id":"doc-en-rust-eb06223c19a091c6638be64b96798f49b2ff151aea08607671a2e04c74e6cd82","title":"","text":"//~^ ERROR mismatched types } fn qux(a: Option, b: Option) -> bool { if let Some(x) = a { true } else { false } && //~ ERROR expected expression if let Some(y) = a { true } else { false } } fn moo(x: u32) -> bool { match x { _ => 1,"} {"_id":"doc-en-rust-e4465ea77789644270ceb4a81ffb558ac3098447849a30c494859a7d40388104","title":"","text":"| | | help: parentheses are required to parse this as an expression: `({ 42 })` error: expected expression, found `&&` --> $DIR/expr-as-stmt.rs:30:5 | LL | if let Some(x) = a { true } else { false } | ------------------------------------------ help: parentheses are required to parse this as an expression: `(if let Some(x) = a { true } else { false })` LL | && | ^^ expected expression error: expected expression, found `>` --> $DIR/expr-as-stmt.rs:37:7 --> $DIR/expr-as-stmt.rs:31:7 | LL | } > 0 | ^ expected expression"} {"_id":"doc-en-rust-ae0fb8697081b39a31facc86eedc17da574b3e9977769526288608c8c9165669","title":"","text":"| | | help: parentheses are required to parse this as an expression: `({ 3 })` error: aborting due to 10 previous errors error: aborting due to 9 previous errors Some errors have detailed explanations: E0308, E0614. For more information about an error, try `rustc --explain E0308`."} {"_id":"doc-en-rust-d50738d8c631767f792984d3e293156db5125c4a7f7e3580e0c536f50c728276","title":"","text":"pat_src: PatternSource, bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet); 1]>, ) { let is_tuple_struct_pat = matches!(pat.kind, PatKind::TupleStruct(_, _)); // Visit all direct subpatterns of this pattern. pat.walk(&mut |pat| { debug!(\"resolve_pattern pat={:?} node={:?}\", pat, pat.kind); match pat.kind { PatKind::Ident(bmode, ident, ref sub) => { // In tuple struct patterns ignore the invalid `ident @ ...`. // It will be handled as an error by the AST lowering. PatKind::Ident(bmode, ident, ref sub) if !(is_tuple_struct_pat && sub.as_ref().filter(|p| p.is_rest()).is_some()) => { // First try to resolve the identifier as some existing entity, // then fall back to a fresh binding. let has_sub = sub.is_some();"} {"_id":"doc-en-rust-15c575abd0dddce9c1a287e366b8a9b56c6560a5ad35fc78ec1b838b5a29e784","title":"","text":" enum E { A(u8, u8), } fn main() { let e = E::A(2, 3); match e { E::A(x @ ..) => { //~ ERROR `x @` is not allowed in a tuple x //~ ERROR cannot find value `x` in this scope } }; } "} {"_id":"doc-en-rust-e12c75bcf1cbd51ce554dd6cb2bd6288ac42ab58bbf6c188008d59891a44bb4e","title":"","text":" error[E0425]: cannot find value `x` in this scope --> $DIR/issue-74539.rs:9:13 | LL | x | ^ help: a local variable with a similar name exists: `e` error: `x @` is not allowed in a tuple struct --> $DIR/issue-74539.rs:8:14 | LL | E::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 | E::A(..) => { | ^^ error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0425`. "} {"_id":"doc-en-rust-cef878f36903062f0f4a3d080e23434cbc24e156ec44a68eb49524dab4de42d4","title":"","text":"use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; use rustc_trait_selection::autoderef::Autoderef; use std::slice; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Type-check `*oprnd_expr` with `oprnd_expr` type-checked already."} {"_id":"doc-en-rust-f9ddc47995026628e0497fdbd4e8a3ef8abb82e44f187e860d41de7ba1b1bd27","title":"","text":"} match expr.kind { hir::ExprKind::Index(ref base_expr, ref index_expr) => { // We need to get the final type in case dereferences were needed for the trait // to apply (#72002). let index_expr_ty = self.typeck_results.borrow().expr_ty_adjusted(index_expr); self.convert_place_op_to_mutable( PlaceOp::Index, expr, base_expr, &[index_expr_ty], ); hir::ExprKind::Index(ref base_expr, ..) => { self.convert_place_op_to_mutable(PlaceOp::Index, expr, base_expr); } hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base_expr) => { self.convert_place_op_to_mutable(PlaceOp::Deref, expr, base_expr, &[]); self.convert_place_op_to_mutable(PlaceOp::Deref, expr, base_expr); } _ => {} }"} {"_id":"doc-en-rust-7350f009129d5ed1fb0341c0dfd4d960842f1ad4bf44735a116d185bb1fd1ed4","title":"","text":"op: PlaceOp, expr: &hir::Expr<'_>, base_expr: &hir::Expr<'_>, arg_tys: &[Ty<'tcx>], ) { debug!(\"convert_place_op_to_mutable({:?}, {:?}, {:?}, {:?})\", op, expr, base_expr, arg_tys); debug!(\"convert_place_op_to_mutable({:?}, {:?}, {:?})\", op, expr, base_expr); if !self.typeck_results.borrow().is_method_call(expr) { debug!(\"convert_place_op_to_mutable - builtin, nothing to do\"); return;"} {"_id":"doc-en-rust-048fd0061d678f61e160a5b39da0de600446d82ca3420673ac236a1afdd2cbb1","title":"","text":".expect(\"place op takes something that is not a ref\") .ty; let arg_ty = match op { PlaceOp::Deref => None, PlaceOp::Index => { // We would need to recover the `T` used when we resolve `<_ as Index>::index` // in try_index_step. This is the subst at index 1. // // Note: we should *not* use `expr_ty` of index_expr here because autoderef // during coercions can cause type of index_expr to differ from `T` (#72002). // We also could not use `expr_ty_adjusted` of index_expr because reborrowing // during coercions can also cause type of index_expr to differ from `T`, // which can potentially cause regionck failure (#74933). Some(self.typeck_results.borrow().node_substs(expr.hir_id).type_at(1)) } }; let arg_tys = match arg_ty { None => &[], Some(ref ty) => slice::from_ref(ty), }; let method = self.try_mutable_overloaded_place_op(expr.span, base_ty, arg_tys, op); let method = match method { Some(ok) => self.register_infer_ok_obligations(ok),"} {"_id":"doc-en-rust-616833a28bd41baf3dc198c0713fa4d9f972da1ac381543a926fa43c53140b2f","title":"","text":" // check-pass // // rust-lang/rust#74933: Lifetime error when indexing with borrowed index use std::ops::{Index, IndexMut}; struct S(V); struct K<'a>(&'a ()); struct V; impl<'a> Index<&'a K<'a>> for S { type Output = V; fn index(&self, _: &'a K<'a>) -> &V { &self.0 } } impl<'a> IndexMut<&'a K<'a>> for S { fn index_mut(&mut self, _: &'a K<'a>) -> &mut V { &mut self.0 } } impl V { fn foo(&mut self) {} } fn test(s: &mut S, k: &K<'_>) { s[k] = V; s[k].foo(); } fn main() { let mut s = S(V); let k = K(&()); test(&mut s, &k); } "} {"_id":"doc-en-rust-f08019a709500727c81579c4bd0bc41485f74a772f16353f6a8a8a7115fbafb9","title":"","text":") = binding.kind { let def_id = (&*self).parent(ctor_def_id).expect(\"no parent for a constructor\"); if let Some(fields) = self.field_names.get(&def_id) { let first_field = fields.first().expect(\"empty field list in the map\"); return Some(fields.iter().fold(first_field.span, |acc, field| acc.to(field.span))); } let fields = self.field_names.get(&def_id)?; let first_field = fields.first()?; // Handle `struct Foo()` return Some(fields.iter().fold(first_field.span, |acc, field| acc.to(field.span))); } None }"} {"_id":"doc-en-rust-529d77caf6b10b1a773ec2eb317a7cb57b9d8c5a70241ed6cc986b0e30d90cda","title":"","text":" // Regression test for issue #75062 // Tests that we don't ICE on a privacy error for a fieldless tuple struct. mod foo { struct Bar(); } fn main() { foo::Bar(); //~ ERROR tuple struct } "} {"_id":"doc-en-rust-7d72d9fa6afdc6adaa5c11201d30d93feb655b2e8ab09b77cac7d4ad3d12518e","title":"","text":" error[E0603]: tuple struct `Bar` is private --> $DIR/issue-75062-fieldless-tuple-struct.rs:9:10 | LL | foo::Bar(); | ^^^ private tuple struct | note: the tuple struct `Bar` is defined here --> $DIR/issue-75062-fieldless-tuple-struct.rs:5:5 | LL | struct Bar(); | ^^^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0603`. "} {"_id":"doc-en-rust-1c74c2d37d1c9dfe6f5d73786afeb261d882af2107751d5d45d44ac9c2b03219","title":"","text":"TyKind::Slice(ref ty) => Slice(box ty.clean(cx)), TyKind::Array(ref ty, ref length) => { let def_id = cx.tcx.hir().local_def_id(length.hir_id); let length = match cx.tcx.const_eval_poly(def_id.to_def_id()) { Ok(length) => { print_const(cx, ty::Const::from_value(cx.tcx, length, cx.tcx.types.usize)) } Err(_) => cx .sess() .source_map() .span_to_snippet(cx.tcx.def_span(def_id)) .unwrap_or_else(|_| \"_\".to_string()), }; // NOTE(min_const_generics): We can't use `const_eval_poly` for constants // as we currently do not supply the parent generics to anonymous constants // but do allow `ConstKind::Param`. // // `const_eval_poly` tries to to first substitute generic parameters which // results in an ICE while manually constructing the constant and using `eval` // does nothing for `ConstKind::Param`. let ct = ty::Const::from_anon_const(cx.tcx, def_id); let param_env = cx.tcx.param_env(def_id); let length = print_const(cx, ct.eval(cx.tcx, param_env)); Array(box ty.clean(cx), length) } TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),"} {"_id":"doc-en-rust-3b89c1b09a58c7f5c3b1afc2d9529a1a7bd577dae65ea4ffb5a0256abfcbead8","title":"","text":" // ignore-tidy-linelength #![feature(min_const_generics)] #![crate_name = \"foo\"] // @has foo/type.CellIndex.html '//pre[@class=\"rust typedef\"]' 'type CellIndex = [i64; D];' pub type CellIndex = [i64; D]; "} {"_id":"doc-en-rust-6776072cb0960fa285c650350073b7648bbe37a45b52e8c5f816115926bf9e73","title":"","text":"use crate::{ cell::{Cell, UnsafeCell}, fmt, marker::PhantomData, mem::{self, MaybeUninit}, ops::{Deref, Drop}, panic::{RefUnwindSafe, UnwindSafe},"} {"_id":"doc-en-rust-bc26ec3acd2cc811cb45ec4511e0fdcd7ff82381c17dec9019f45292a185a2d0","title":"","text":"once: Once, // Whether or not the value is initialized is tracked by `state_and_queue`. value: UnsafeCell>, /// `PhantomData` to make sure dropck understands we're dropping T in our Drop impl. /// /// ```compile_fail,E0597 /// #![feature(once_cell)] /// /// use std::lazy::SyncOnceCell; /// /// struct A<'a>(&'a str); /// /// impl<'a> Drop for A<'a> { /// fn drop(&mut self) {} /// } /// /// let cell = SyncOnceCell::new(); /// { /// let s = String::new(); /// let _ = cell.set(A(&s)); /// } /// ``` _marker: PhantomData, } // Why do we need `T: Send`?"} {"_id":"doc-en-rust-0f6c828ba67c861b1405bac0caa1d14b13b3eddcde6ec13e8445fe8bc18bc2b7","title":"","text":"/// Creates a new empty cell. #[unstable(feature = \"once_cell\", issue = \"74465\")] pub const fn new() -> SyncOnceCell { SyncOnceCell { once: Once::new(), value: UnsafeCell::new(MaybeUninit::uninit()) } SyncOnceCell { once: Once::new(), value: UnsafeCell::new(MaybeUninit::uninit()), _marker: PhantomData, } } /// Gets the reference to the underlying value."} {"_id":"doc-en-rust-585d6b7897376864be750b9b5728574dd3041229ca91a0d500e870cc70438cd3","title":"","text":"self.index = index; } pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { self.stream.0[self.index..].get(n).map(|(tree, _)| tree) pub fn look_ahead(&self, n: usize) -> Option { self.stream.0[self.index..].get(n).map(|(tree, _)| tree.clone()) } }"} {"_id":"doc-en-rust-b5c35ad255a07d84d3efb0e226171e956c351cec3a1b973f372b2f24957bb4f6","title":"","text":"} } impl FromInternal<( TreeAndJoint, Option<&'_ tokenstream::TokenTree>, &'_ ParseSess, &'_ mut Vec, )> for TokenTree impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec)> for TokenTree { fn from_internal( ((tree, is_joint), look_ahead, sess, stack): ( TreeAndJoint, Option<&tokenstream::TokenTree>, &ParseSess, &mut Vec, ), ((tree, is_joint), sess, stack): (TreeAndJoint, &ParseSess, &mut Vec), ) -> Self { use rustc_ast::token::*; let joint = is_joint == Joint && matches!(look_ahead, Some(tokenstream::TokenTree::Token(t)) if t.is_op()); let joint = is_joint == Joint; let Token { kind, span } = match tree { tokenstream::TokenTree::Delimited(span, delim, tts) => { let delimiter = Delimiter::from_internal(delim);"} {"_id":"doc-en-rust-3f5fed3ca494f56c57922995e36653ccb585fde7dffd940f5b85ad6caacc73df","title":"","text":"loop { let tree = iter.stack.pop().or_else(|| { let next = iter.cursor.next_with_joint()?; let lookahead = iter.cursor.look_ahead(0); Some(TokenTree::from_internal((next, lookahead, self.sess, &mut iter.stack))) Some(TokenTree::from_internal((next, self.sess, &mut iter.stack))) })?; // A hack used to pass AST fragments to attribute and derive macros // as a single nonterminal token instead of a token stream."} {"_id":"doc-en-rust-062fb5111e8ce5585c237619d90aad3785fec0d490349fcf6d01a7c21cbd72ce","title":"","text":"} _ => { let tt = TokenTree::Token(self.token.take()); let is_joint = self.bump(); let mut is_joint = self.bump(); if !self.token.is_op() { is_joint = NonJoint; } Ok((tt, is_joint)) } }"} {"_id":"doc-en-rust-b2d34c0fcf38d815d90d8d99d8ac609ad9aadec2a29f6032443b0a8d960efd90","title":"","text":"} let frame = &self.token_cursor.frame; match frame.tree_cursor.look_ahead(dist - 1) { looker(&match frame.tree_cursor.look_ahead(dist - 1) { Some(tree) => match tree { TokenTree::Token(token) => looker(token), TokenTree::Token(token) => token, TokenTree::Delimited(dspan, delim, _) => { looker(&Token::new(token::OpenDelim(delim.clone()), dspan.open)) Token::new(token::OpenDelim(delim), dspan.open) } }, None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), } None => Token::new(token::CloseDelim(frame.delim), frame.span.close), }) } /// Returns whether any of the given keywords are `dist` tokens ahead of the current one."} {"_id":"doc-en-rust-80b50278cb149d112c732bce77235aa294ee91994d3ec8ea23e838dd230090ce","title":"","text":"#![cfg_attr(bootstrap, feature(doc_spotlight))] #![cfg_attr(not(bootstrap), feature(doc_notable_trait))] #![feature(duration_consts_2)] #![feature(duration_saturating_ops)] #![feature(extended_key_value_attributes)] #![feature(extern_types)] #![feature(fundamental)]"} {"_id":"doc-en-rust-88d6e422a804505170fdd0e0be09b69219e9a92bc46199ae59418c9a0d8ea57a","title":"","text":"/// # Examples /// /// ``` /// #![feature(duration_saturating_ops)] /// #![feature(duration_constants)] /// use std::time::Duration; /// /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1)); /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX); /// ``` #[unstable(feature = \"duration_saturating_ops\", issue = \"76416\")] #[stable(feature = \"duration_saturating_ops\", since = \"1.53.0\")] #[inline] #[rustc_const_unstable(feature = \"duration_consts_2\", issue = \"72440\")] pub const fn saturating_add(self, rhs: Duration) -> Duration {"} {"_id":"doc-en-rust-e8430eda8feb466afa122b414e07dfe9a275e10d4c1095aa77eb338bec99cfd8","title":"","text":"/// # Examples /// /// ``` /// #![feature(duration_saturating_ops)] /// #![feature(duration_zero)] /// use std::time::Duration; /// /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1)); /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO); /// ``` #[unstable(feature = \"duration_saturating_ops\", issue = \"76416\")] #[stable(feature = \"duration_saturating_ops\", since = \"1.53.0\")] #[inline] #[rustc_const_unstable(feature = \"duration_consts_2\", issue = \"72440\")] pub const fn saturating_sub(self, rhs: Duration) -> Duration {"} {"_id":"doc-en-rust-9c97c330ff5435c843c9a0949105d5999612d25cad011683cee0024fde571780","title":"","text":"/// # Examples /// /// ``` /// #![feature(duration_saturating_ops)] /// #![feature(duration_constants)] /// use std::time::Duration; /// /// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2)); /// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX); /// ``` #[unstable(feature = \"duration_saturating_ops\", issue = \"76416\")] #[stable(feature = \"duration_saturating_ops\", since = \"1.53.0\")] #[inline] #[rustc_const_unstable(feature = \"duration_consts_2\", issue = \"72440\")] pub const fn saturating_mul(self, rhs: u32) -> Duration {"} {"_id":"doc-en-rust-eae6cdf8f19bbf5d88c3d6b7ee6406580dcff64ecc8e156bb3c20fc416d7e3e3","title":"","text":"#![feature(div_duration)] #![feature(duration_consts_2)] #![feature(duration_constants)] #![feature(duration_saturating_ops)] #![feature(duration_zero)] #![feature(exact_size_is_empty)] #![feature(extern_types)]"} {"_id":"doc-en-rust-06bbe09c17acabc916afc44b4e23f46a22991d70669c2fa0005e199743672c90","title":"","text":"_marker: PhantomData<&'a mut T>, } unsafe impl<'a, T> Sync for DormantMutRef<'a, T> where &'a mut T: Sync {} unsafe impl<'a, T> Send for DormantMutRef<'a, T> where &'a mut T: Send {} impl<'a, T> DormantMutRef<'a, T> { /// Capture a unique borrow, and immediately reborrow it. For the compiler, /// the lifetime of the new reference is the same as the lifetime of the"} {"_id":"doc-en-rust-71f5b06415711b1421a37861b3eae71b09f3b4f09041e5ca7eff9fedbe492496","title":"","text":"} #[test] #[allow(dead_code)] fn test_sync() { fn map(v: &BTreeMap) -> impl Sync + '_ { v } fn into_iter(v: BTreeMap) -> impl Sync { v.into_iter() } fn into_keys(v: BTreeMap) -> impl Sync { v.into_keys() } fn into_values(v: BTreeMap) -> impl Sync { v.into_values() } fn drain_filter(v: &mut BTreeMap) -> impl Sync + '_ { v.drain_filter(|_, _| false) } fn iter(v: &BTreeMap) -> impl Sync + '_ { v.iter() } fn iter_mut(v: &mut BTreeMap) -> impl Sync + '_ { v.iter_mut() } fn keys(v: &BTreeMap) -> impl Sync + '_ { v.keys() } fn values(v: &BTreeMap) -> impl Sync + '_ { v.values() } fn values_mut(v: &mut BTreeMap) -> impl Sync + '_ { v.values_mut() } fn range(v: &BTreeMap) -> impl Sync + '_ { v.range(..) } fn range_mut(v: &mut BTreeMap) -> impl Sync + '_ { v.range_mut(..) } fn entry(v: &mut BTreeMap) -> impl Sync + '_ { v.entry(Default::default()) } fn occupied_entry(v: &mut BTreeMap) -> impl Sync + '_ { match v.entry(Default::default()) { Occupied(entry) => entry, _ => unreachable!(), } } fn vacant_entry(v: &mut BTreeMap) -> impl Sync + '_ { match v.entry(Default::default()) { Vacant(entry) => entry, _ => unreachable!(), } } } #[test] #[allow(dead_code)] fn test_send() { fn map(v: BTreeMap) -> impl Send { v } fn into_iter(v: BTreeMap) -> impl Send { v.into_iter() } fn into_keys(v: BTreeMap) -> impl Send { v.into_keys() } fn into_values(v: BTreeMap) -> impl Send { v.into_values() } fn drain_filter(v: &mut BTreeMap) -> impl Send + '_ { v.drain_filter(|_, _| false) } fn iter(v: &BTreeMap) -> impl Send + '_ { v.iter() } fn iter_mut(v: &mut BTreeMap) -> impl Send + '_ { v.iter_mut() } fn keys(v: &BTreeMap) -> impl Send + '_ { v.keys() } fn values(v: &BTreeMap) -> impl Send + '_ { v.values() } fn values_mut(v: &mut BTreeMap) -> impl Send + '_ { v.values_mut() } fn range(v: &BTreeMap) -> impl Send + '_ { v.range(..) } fn range_mut(v: &mut BTreeMap) -> impl Send + '_ { v.range_mut(..) } fn entry(v: &mut BTreeMap) -> impl Send + '_ { v.entry(Default::default()) } fn occupied_entry(v: &mut BTreeMap) -> impl Send + '_ { match v.entry(Default::default()) { Occupied(entry) => entry, _ => unreachable!(), } } fn vacant_entry(v: &mut BTreeMap) -> impl Send + '_ { match v.entry(Default::default()) { Vacant(entry) => entry, _ => unreachable!(), } } } #[test] fn test_occupied_entry_key() { let mut a = BTreeMap::new(); let key = \"hello there\";"} {"_id":"doc-en-rust-b4af4da9a8e8c6f4f832a5c0a0a1a7c460ed0f3c6b1a0e317a71f97a3b2c6dba","title":"","text":" //! Note: most of the tests relevant to this file can be found (at the time of writing) in //! src/tests/ui/pattern/usefulness. //! Note: tests specific to this file can be found in: //! - ui/pattern/usefulness //! - ui/or-patterns //! - ui/consts/const_in_pattern //! - ui/rfc-2008-non-exhaustive //! - probably many others //! I (Nadrieril) prefer to put new tests in `ui/pattern/usefulness` unless there's a specific //! reason not to, for example if they depend on a particular feature like or_patterns. //! //! This file includes the logic for exhaustiveness and usefulness checking for //! pattern-matching. Specifically, given a list of patterns for a type, we can"} {"_id":"doc-en-rust-31bd4c90e6c21b3ecc8258be4f19a3f3645a8665c5148925f9101107550d3321","title":"","text":"#[derive(Clone, Debug)] crate enum Usefulness<'tcx> { /// Carries a list of unreachable subpatterns. Used only in the presence of or-patterns. Useful(Vec), /// Carries, for each column in the matrix, a set of sub-branches that have been found to be /// unreachable. Used only in the presence of or-patterns, otherwise it stays empty. Useful(Vec>), /// Carries a list of witnesses of non-exhaustiveness. UsefulWithWitness(Vec>), NotUseful,"} {"_id":"doc-en-rust-97f3c9456ff1712dfde233960963d11ffb74c253cc537a3fdf841bd7cbc9dc68","title":"","text":"}; UsefulWithWitness(new_witnesses) } Useful(mut unreachables) => { if !unreachables.is_empty() { // When we apply a constructor, there are `arity` columns of the matrix that // corresponded to its arguments. All the unreachables found in these columns // will, after `apply`, come from the first column. So we take the union of all // the corresponding sets and put them in the first column. // Note that `arity` may be 0, in which case we just push a new empty set. let len = unreachables.len(); let arity = ctor_wild_subpatterns.len(); let mut unioned = FxHashSet::default(); for set in unreachables.drain((len - arity)..) { unioned.extend(set) } unreachables.push(unioned); } Useful(unreachables) } x => x, } }"} {"_id":"doc-en-rust-a4920ff598c48fef46d8211e9e0e0af2c92cd48d89f02e76871627007c2da796","title":"","text":"// If the first pattern is an or-pattern, expand it. if let Some(vs) = v.expand_or_pat() { // We need to push the already-seen patterns into the matrix in order to detect redundant // branches like `Some(_) | Some(0)`. We also keep track of the unreachable subpatterns. let mut matrix = matrix.clone(); // `Vec` of all the unreachable branches of the current or-pattern. let mut unreachable_branches = Vec::new(); // Subpatterns that are unreachable from all branches. E.g. in the following case, the last // `true` is unreachable only from one branch, so it is overall reachable. // We expand the or pattern, trying each of its branches in turn and keeping careful track // of possible unreachable sub-branches. // // If two branches have detected some unreachable sub-branches, we need to be careful. If // they were detected in columns that are not the current one, we want to keep only the // sub-branches that were unreachable in _all_ branches. Eg. in the following, the last // `true` is unreachable in the second branch of the first or-pattern, but not otherwise. // Therefore we don't want to lint that it is unreachable. // // ``` // match (true, true) {"} {"_id":"doc-en-rust-46361f28fd875ca3c463a4653779c6566727a491ad598baca797a423aad385c6","title":"","text":"// (false | true, false | true) => {} // } // ``` let mut unreachable_subpats = FxHashSet::default(); // Whether any branch at all is useful. // If however the sub-branches come from the current column, they come from the inside of // the current or-pattern, and we want to keep them all. Eg. in the following, we _do_ want // to lint that the last `false` is unreachable. // ``` // match None { // Some(false) => {} // None | Some(true | false) => {} // } // ``` let mut matrix = matrix.clone(); // We keep track of sub-branches separately depending on whether they come from this column // or from others. let mut unreachables_this_column: FxHashSet = FxHashSet::default(); let mut unreachables_other_columns: Vec> = Vec::default(); // Whether at least one branch is reachable. let mut any_is_useful = false; for v in vs { let res = is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false); match res { Useful(pats) => { if !any_is_useful { any_is_useful = true; // Initialize with the first set of unreachable subpatterns encountered. unreachable_subpats = pats.into_iter().collect(); } else { // Keep the patterns unreachable from both this and previous branches. unreachable_subpats = pats.into_iter().filter(|p| unreachable_subpats.contains(p)).collect(); Useful(unreachables) => { if let Some((this_column, other_columns)) = unreachables.split_last() { // We keep the union of unreachables found in the first column. unreachables_this_column.extend(this_column); // We keep the intersection of unreachables found in other columns. if unreachables_other_columns.is_empty() { unreachables_other_columns = other_columns.to_vec(); } else { unreachables_other_columns = unreachables_other_columns .into_iter() .zip(other_columns) .map(|(x, y)| x.intersection(&y).copied().collect()) .collect(); } } any_is_useful = true; } NotUseful => unreachable_branches.push(v.head().span), UsefulWithWitness(_) => { bug!(\"Encountered or-pat in `v` during exhaustiveness checking\") NotUseful => { unreachables_this_column.insert(v.head().span); } UsefulWithWitness(_) => bug!( \"encountered or-pat in the expansion of `_` during exhaustiveness checking\" ), } // If pattern has a guard don't add it to the matrix // If pattern has a guard don't add it to the matrix. if !is_under_guard { // We push the already-seen patterns into the matrix in order to detect redundant // branches like `Some(_) | Some(0)`. matrix.push(v); } } if any_is_useful { // Collect all the unreachable patterns. unreachable_branches.extend(unreachable_subpats); return Useful(unreachable_branches); return if any_is_useful { let mut unreachables = if unreachables_other_columns.is_empty() { let n_columns = v.len(); (0..n_columns - 1).map(|_| FxHashSet::default()).collect() } else { unreachables_other_columns }; unreachables.push(unreachables_this_column); Useful(unreachables) } else { return NotUseful; } NotUseful }; } // FIXME(Nadrieril): Hack to work around type normalization issues (see #72476)."} {"_id":"doc-en-rust-82a6b568ce36d82f94dfb477c5d3c9b223080153b3053e6bc34aa334c85ea8b6","title":"","text":"hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {} } } Useful(unreachable_subpatterns) => { for span in unreachable_subpatterns { Useful(unreachables) => { let mut unreachables: Vec<_> = unreachables.into_iter().flatten().collect(); // Emit lints in the order in which they occur in the file. unreachables.sort_unstable(); for span in unreachables { unreachable_pattern(cx.tcx, span, id, None); } }"} {"_id":"doc-en-rust-1c9ffc143f93457b2b440bc1cf897cc01d6c9e938382ffae5a025ea0ed7852b8","title":"","text":"(false | true, false | true) => {} } match (true, true) { (true, false) => {} (false, true) => {} (true, true) => {} (false, false) => {} (false | true, false | true) => {} } // https://github.com/rust-lang/rust/issues/76836 match None { Some(false) => {} None | Some(true | false) => {} //~ ERROR unreachable } // A subpattern that is unreachable in all branches is overall unreachable. match (true, true) { (false, true) => {}"} {"_id":"doc-en-rust-cd23bdbe2f5c9243a770ad9e09d04d44d65e295e3a8b3367f4e9bd60dc587098","title":"","text":"| ^ error: unreachable pattern --> $DIR/exhaustiveness-unreachable-pattern.rs:89:15 --> $DIR/exhaustiveness-unreachable-pattern.rs:88:19 | LL | | false) => {} | ^^^^^ error: unreachable pattern --> $DIR/exhaustiveness-unreachable-pattern.rs:96:15 | LL | | true) => {} | ^^^^ error: unreachable pattern --> $DIR/exhaustiveness-unreachable-pattern.rs:95:15 --> $DIR/exhaustiveness-unreachable-pattern.rs:102:15 | LL | | true, | ^^^^ error: aborting due to 18 previous errors error: aborting due to 19 previous errors "} {"_id":"doc-en-rust-26c3518c5d9149c2232c75ffdd877433a047fa05650733e6a4e897edeee2f83a","title":"","text":"} /// Attribute macro applied to a static to register it as a global allocator. /// /// See also [`std::alloc::GlobalAlloc`](../std/alloc/trait.GlobalAlloc.html). #[stable(feature = \"global_allocator\", since = \"1.28.0\")] #[allow_internal_unstable(rustc_attrs)] #[rustc_builtin_macro]"} {"_id":"doc-en-rust-46a2f5337ca3948d757befb3b56c36a4d8b3d78d02dfa1196aaa1f9032005bab","title":"","text":"// and about 2 * (len1 + len2) comparisons in the worst case // while `extend` takes O(len2 * log(len1)) operations // and about 1 * len2 * log_2(len1) comparisons in the worst case, // assuming len1 >= len2. // assuming len1 >= len2. For larger heaps, the crossover point // no longer follows this reasoning and was determined empirically. #[inline] fn better_to_rebuild(len1: usize, len2: usize) -> bool { 2 * (len1 + len2) < len2 * log2_fast(len1) let tot_len = len1 + len2; if tot_len <= 2048 { 2 * tot_len < len2 * log2_fast(len1) } else { 2 * tot_len < len2 * 11 } } if better_to_rebuild(self.len(), other.len()) {"} {"_id":"doc-en-rust-38fea391f8e15b85b2e6dbe46ba0b8295aa4a226c6b94d130f3347702d31dfaa","title":"","text":"} } hir::InlineAsmOperand::InOut { expr, .. } => { succ = self.write_place(expr, succ, ACC_READ | ACC_WRITE); succ = self.write_place(expr, succ, ACC_READ | ACC_WRITE | ACC_USE); } hir::InlineAsmOperand::SplitInOut { out_expr, .. } => { if let Some(expr) = out_expr {"} {"_id":"doc-en-rust-4e3f8e740f4d855fc38c8d57f6f92ff067f823cd55800ba9655d86f204e7fde4","title":"","text":" // Ensure inout asm! operands are marked as used by the liveness pass // only-x86_64 // check-pass #![feature(asm)] #![allow(dead_code)] #![warn(unused_assignments)] #![warn(unused_variables)] // Test the single inout case unsafe fn f1(mut src: *const u8) { asm!(\"/*{0}*/\", inout(reg) src); //~ WARN value assigned to `src` is never read } unsafe fn f2(mut src: *const u8) -> *const u8 { asm!(\"/*{0}*/\", inout(reg) src); src } // Test the split inout case unsafe fn f3(mut src: *const u8) { asm!(\"/*{0}*/\", inout(reg) src => src); //~ WARN value assigned to `src` is never read } unsafe fn f4(mut src: *const u8) -> *const u8 { asm!(\"/*{0}*/\", inout(reg) src => src); src } // Tests the use of field projections struct S { field: *mut u8, } unsafe fn f5(src: &mut S) { asm!(\"/*{0}*/\", inout(reg) src.field); } unsafe fn f6(src: &mut S) { asm!(\"/*{0}*/\", inout(reg) src.field => src.field); } fn main() {} "} {"_id":"doc-en-rust-dad4714600f2ff5e6f79a1abd16d8dd0b974207830172920366c08a99e11ae8e","title":"","text":" warning: value assigned to `src` is never read --> $DIR/liveness-asm.rs:13:32 | LL | asm!(\"/*{0}*/\", inout(reg) src); | ^^^ | note: the lint level is defined here --> $DIR/liveness-asm.rs:8:9 | LL | #![warn(unused_assignments)] | ^^^^^^^^^^^^^^^^^^ = help: maybe it is overwritten before being read? warning: value assigned to `src` is never read --> $DIR/liveness-asm.rs:23:39 | LL | asm!(\"/*{0}*/\", inout(reg) src => src); | ^^^ | = help: maybe it is overwritten before being read? warning: 2 warnings emitted "} {"_id":"doc-en-rust-9a4eb37f3cb452a45c9b56f91f1398513eb143c7b2ec75c7ed77a310f395d988","title":"","text":"let func_ty = func.ty(body, tcx); if let ty::FnDef(callee, substs) = *func_ty.kind() { let (callee, call_substs) = if let Ok(Some(instance)) = Instance::resolve(tcx, param_env, callee, substs) { (instance.def_id(), instance.substs) } else { (callee, substs) }; let normalized_substs = tcx.normalize_erasing_regions(param_env, substs); let (callee, call_substs) = if let Ok(Some(instance)) = Instance::resolve(tcx, param_env, callee, normalized_substs) { (instance.def_id(), instance.substs) } else { (callee, normalized_substs) }; // FIXME(#57965): Make this work across function boundaries"} {"_id":"doc-en-rust-d678678de54d329dff3b0d5880c07dffd902785a2dd9f33afecd9e563d026418","title":"","text":"impl Drop for InPlaceDrop { #[inline] fn drop(&mut self) { if mem::needs_drop::() { unsafe { ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len())); } unsafe { ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len())); } } }"} {"_id":"doc-en-rust-ee08d40f839f6205c7b4ca484515da7fe1d8fa3a4c931b04b2e090cefc62477e","title":"","text":"} fn drop_remaining(&mut self) { if mem::needs_drop::() { unsafe { ptr::drop_in_place(self.as_mut_slice()); } unsafe { ptr::drop_in_place(self.as_mut_slice()); } self.ptr = self.end; }"} {"_id":"doc-en-rust-0d93a7641b33864d85ddb44735f88c6e3d47a3c3d6b18a8d3845d76c843baabc","title":"","text":" Subproject commit af078ecc0b069ec594982f92d4c6c58af99efbb5 Subproject commit 710fc18ddcb6c7677b3c96359abb35da37f2a488 "} {"_id":"doc-en-rust-f9bf238971f2e21d0777f9db0ce821941196e3ae221713eb161c19e048300841","title":"","text":"code_offset: usize, margin: Margin, ) { // Tabs are assumed to have been replaced by spaces in calling code. assert!(!source_string.contains('t')); let line_len = source_string.len(); // Create the source line we will highlight. let left = margin.left(line_len);"} {"_id":"doc-en-rust-f453efcda1674354029ce8c7d29770a1466bcd8996700d896656ccf4da31536b","title":"","text":"} let source_string = match file.get_line(line.line_index - 1) { Some(s) => s, Some(s) => replace_tabs(&*s), None => return Vec::new(), };"} {"_id":"doc-en-rust-2537b17f4d84b6f7b33527d39d7b4238f0db2b2044a98accf3ef4f10325bd8cd","title":"","text":"let file = annotated_file.file.clone(); let line = &annotated_file.lines[line_idx]; if let Some(source_string) = file.get_line(line.line_index - 1) { let leading_whitespace = source_string.chars().take_while(|c| c.is_whitespace()).count(); let leading_whitespace = source_string .chars() .take_while(|c| c.is_whitespace()) .map(|c| { match c { // Tabs are displayed as 4 spaces 't' => 4, _ => 1, } }) .sum(); if source_string.chars().any(|c| !c.is_whitespace()) { whitespace_margin = min(whitespace_margin, leading_whitespace); }"} {"_id":"doc-en-rust-f5ec1a8d441337bfb4a4ed360d2f70953ca7d9f6e3788e07657115aea199567f","title":"","text":"self.draw_line( &mut buffer, &unannotated_line, &replace_tabs(&unannotated_line), annotated_file.lines[line_idx + 1].line_index - 1, last_buffer_line_num, width_offset,"} {"_id":"doc-en-rust-f6ab292ec39212ec8c3100e4d41d21d9d657eea953e0bf7db2b5dc7e330de588","title":"","text":"); // print the suggestion draw_col_separator(&mut buffer, row_num, max_line_num_len + 1); buffer.append(row_num, line, Style::NoStyle); buffer.append(row_num, &replace_tabs(line), Style::NoStyle); row_num += 1; }"} {"_id":"doc-en-rust-d7ac943461348fc17ee7181ec9ca1a1e864a7676fd8bfaa1d21f6f9165ebff9b","title":"","text":"} } fn replace_tabs(str: &str) -> String { str.replace('t', \" \") } fn draw_col_separator(buffer: &mut StyledBuffer, line: usize, col: usize) { buffer.puts(line, col, \"| \", Style::LineNumber); }"} {"_id":"doc-en-rust-dce2876e682b1650ddf19708125909636bae547ea5641deeedb1234867230211","title":"","text":"StyledBuffer { text: vec![], styles: vec![] } } fn replace_tabs(&mut self) { for (line_pos, line) in self.text.iter_mut().enumerate() { let mut tab_pos = vec![]; for (pos, c) in line.iter().enumerate() { if *c == 't' { tab_pos.push(pos); } } // start with the tabs at the end of the line to replace them with 4 space chars for pos in tab_pos.iter().rev() { assert_eq!(line.remove(*pos), 't'); // fix the position of the style to match up after replacing the tabs let s = self.styles[line_pos].remove(*pos); for _ in 0..4 { line.insert(*pos, ' '); self.styles[line_pos].insert(*pos, s); } } } } pub fn render(&self) -> Vec> { // Tabs are assumed to have been replaced by spaces in calling code. assert!(self.text.iter().all(|r| !r.contains(&'t'))); pub fn render(&mut self) -> Vec> { let mut output: Vec> = vec![]; let mut styled_vec: Vec = vec![]; // before we render, replace tabs with spaces self.replace_tabs(); for (row, row_style) in self.text.iter().zip(&self.styles) { let mut current_style = Style::NoStyle; let mut current_text = String::new();"} {"_id":"doc-en-rust-98fd8470f0fa04f374dab8de32093ac13d46cc82e5151353b4ee66e3a9cfc39c","title":"","text":" // Test for #78438: ensure underline alignment with many tabs on the left, long line on the right // ignore-tidy-linelength // ignore-tidy-tab fn main() { let money = 42i32; match money { v @ 1 | 2 | 3 => panic!(\"You gave me too little money {}\", v), // Long text here: TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT //~^ ERROR variable `v` is not bound in all patterns v => println!(\"Enough money {}\", v), } } "} {"_id":"doc-en-rust-5ab7f62a7f13a5d54d793bedfe3b165b8baed74d6ac643a5eaa193fc964fc6af","title":"","text":" error[E0408]: variable `v` is not bound in all patterns --> $DIR/tabs-trimming.rs:9:16 | LL | ... v @ 1 | 2 | 3 => panic!(\"You gave me too little money {}\", v), // Long text here: TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT... | - ^ ^ pattern doesn't bind `v` | | | | | pattern doesn't bind `v` | variable not in all patterns error: aborting due to previous error For more information about this error, try `rustc --explain E0408`. "} {"_id":"doc-en-rust-abf3fc95e88ce5d91d68565513c4d511b2ea146d12c3528b5f31350ae50b2c52","title":"","text":"return None; } // when the second place is a projection of the first one, it's not safe to calculate their discriminant values sequentially. // for example, this should not be optimized: // // ```rust // enum E<'a> { Empty, Some(&'a E<'a>), } // let Some(Some(_)) = e; // ``` // // ```mir // bb0: { // _2 = discriminant(*_1) // switchInt(_2) -> [...] // } // bb1: { // _3 = discriminant(*(((*_1) as Some).0: &E)) // switchInt(_3) -> [...] // } // ``` let discr_place = discr_info.place_of_adt_discr_read; let this_discr_place = this_bb_discr_info.place_of_adt_discr_read; if discr_place.local == this_discr_place.local && this_discr_place.projection.starts_with(discr_place.projection) { trace!(\"NO: one target is the projection of another\"); return None; } // if we reach this point, the optimization applies, and we should be able to optimize this case // store the info that is needed to apply the optimization"} {"_id":"doc-en-rust-4e74fc3423f299eb3a78345a3d8b6f8b915d8d4f1d67dbcd4c26ad80355ca2cd","title":"","text":" // run-pass // compile-flags: -Z mir-opt-level=2 -C opt-level=0 // example from #78496 pub enum E<'a> { Empty, Some(&'a E<'a>), } fn f(e: &E) -> u32 { if let E::Some(E::Some(_)) = e { 1 } else { 2 } } fn main() { assert_eq!(f(&E::Empty), 2); } "} {"_id":"doc-en-rust-20045b56be8fa825b2f4bf3b3b01511039df9bacba38c31b1ecad251c6046eb9","title":"","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":"doc-en-rust-aa31bc8fe838e27aba3cb7cd7583f6f57de0d63b684a82ebdafafbd3939dfb2d","title":"","text":"pub mod simplify; mod simplify_branches; mod simplify_comparison_integral; mod simplify_try; mod sroa; mod uninhabited_enum_branching; mod unreachable_prop;"} {"_id":"doc-en-rust-0d37cd12c9d586756ac38784c809998d7d0ca6cc2f466b6064108b776482d6d7","title":"","text":"&o1(simplify_branches::SimplifyConstCondition::new(\"after-const-prop\")), &early_otherwise_branch::EarlyOtherwiseBranch, &simplify_comparison_integral::SimplifyComparisonIntegral, &simplify_try::SimplifyArmIdentity, &simplify_try::SimplifyBranchSame, &dead_store_elimination::DeadStoreElimination, &dest_prop::DestinationPropagation, &o1(simplify_branches::SimplifyConstCondition::new(\"final\")),"} {"_id":"doc-en-rust-4a54fc1ad848247fb03fabb1a8a98c8bf200a7b333d58ec1e8ad9867dd34bcb7","title":"","text":" //! The general point of the optimizations provided here is to simplify something like: //! //! ```rust //! # fn foo(x: Result) -> Result { //! match x { //! Ok(x) => Ok(x), //! Err(x) => Err(x) //! } //! # } //! ``` //! //! into just `x`. use crate::{simplify, MirPass}; use itertools::Itertools as _; use rustc_index::{bit_set::BitSet, vec::IndexVec}; use rustc_middle::mir::visit::{NonUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::{self, List, Ty, TyCtxt}; use rustc_target::abi::VariantIdx; use std::iter::{once, Enumerate, Peekable}; use std::slice::Iter; /// Simplifies arms of form `Variant(x) => Variant(x)` to just a move. /// /// This is done by transforming basic blocks where the statements match: /// /// ```ignore (MIR) /// _LOCAL_TMP = ((_LOCAL_1 as Variant ).FIELD: TY ); /// _TMP_2 = _LOCAL_TMP; /// ((_LOCAL_0 as Variant).FIELD: TY) = move _TMP_2; /// discriminant(_LOCAL_0) = VAR_IDX; /// ``` /// /// into: /// /// ```ignore (MIR) /// _LOCAL_0 = move _LOCAL_1 /// ``` pub struct SimplifyArmIdentity; #[derive(Debug)] struct ArmIdentityInfo<'tcx> { /// Storage location for the variant's field local_temp_0: Local, /// Storage location holding the variant being read from local_1: Local, /// The variant field being read from vf_s0: VarField<'tcx>, /// Index of the statement which loads the variant being read get_variant_field_stmt: usize, /// Tracks each assignment to a temporary of the variant's field field_tmp_assignments: Vec<(Local, Local)>, /// Storage location holding the variant's field that was read from local_tmp_s1: Local, /// Storage location holding the enum that we are writing to local_0: Local, /// The variant field being written to vf_s1: VarField<'tcx>, /// Storage location that the discriminant is being written to set_discr_local: Local, /// The variant being written set_discr_var_idx: VariantIdx, /// Index of the statement that should be overwritten as a move stmt_to_overwrite: usize, /// SourceInfo for the new move source_info: SourceInfo, /// Indices of matching Storage{Live,Dead} statements encountered. /// (StorageLive index,, StorageDead index, Local) storage_stmts: Vec<(usize, usize, Local)>, /// The statements that should be removed (turned into nops) stmts_to_remove: Vec, /// Indices of debug variables that need to be adjusted to point to // `{local_0}.{dbg_projection}`. dbg_info_to_adjust: Vec, /// The projection used to rewrite debug info. dbg_projection: &'tcx List>, } fn get_arm_identity_info<'a, 'tcx>( stmts: &'a [Statement<'tcx>], locals_count: usize, debug_info: &'a [VarDebugInfo<'tcx>], ) -> Option> { // This can't possibly match unless there are at least 3 statements in the block // so fail fast on tiny blocks. if stmts.len() < 3 { return None; } let mut tmp_assigns = Vec::new(); let mut nop_stmts = Vec::new(); let mut storage_stmts = Vec::new(); let mut storage_live_stmts = Vec::new(); let mut storage_dead_stmts = Vec::new(); type StmtIter<'a, 'tcx> = Peekable>>>; fn is_storage_stmt(stmt: &Statement<'_>) -> bool { matches!(stmt.kind, StatementKind::StorageLive(_) | StatementKind::StorageDead(_)) } /// Eats consecutive Statements which match `test`, performing the specified `action` for each. /// The iterator `stmt_iter` is not advanced if none were matched. fn try_eat<'a, 'tcx>( stmt_iter: &mut StmtIter<'a, 'tcx>, test: impl Fn(&'a Statement<'tcx>) -> bool, mut action: impl FnMut(usize, &'a Statement<'tcx>), ) { while stmt_iter.peek().map_or(false, |(_, stmt)| test(stmt)) { let (idx, stmt) = stmt_iter.next().unwrap(); action(idx, stmt); } } /// Eats consecutive `StorageLive` and `StorageDead` Statements. /// The iterator `stmt_iter` is not advanced if none were found. fn try_eat_storage_stmts( stmt_iter: &mut StmtIter<'_, '_>, storage_live_stmts: &mut Vec<(usize, Local)>, storage_dead_stmts: &mut Vec<(usize, Local)>, ) { try_eat(stmt_iter, is_storage_stmt, |idx, stmt| { if let StatementKind::StorageLive(l) = stmt.kind { storage_live_stmts.push((idx, l)); } else if let StatementKind::StorageDead(l) = stmt.kind { storage_dead_stmts.push((idx, l)); } }) } fn is_tmp_storage_stmt(stmt: &Statement<'_>) -> bool { use rustc_middle::mir::StatementKind::Assign; if let Assign(box (place, Rvalue::Use(Operand::Copy(p) | Operand::Move(p)))) = &stmt.kind { place.as_local().is_some() && p.as_local().is_some() } else { false } } /// Eats consecutive `Assign` Statements. // The iterator `stmt_iter` is not advanced if none were found. fn try_eat_assign_tmp_stmts( stmt_iter: &mut StmtIter<'_, '_>, tmp_assigns: &mut Vec<(Local, Local)>, nop_stmts: &mut Vec, ) { try_eat(stmt_iter, is_tmp_storage_stmt, |idx, stmt| { use rustc_middle::mir::StatementKind::Assign; if let Assign(box (place, Rvalue::Use(Operand::Copy(p) | Operand::Move(p)))) = &stmt.kind { tmp_assigns.push((place.as_local().unwrap(), p.as_local().unwrap())); nop_stmts.push(idx); } }) } fn find_storage_live_dead_stmts_for_local( local: Local, stmts: &[Statement<'_>], ) -> Option<(usize, usize)> { trace!(\"looking for {:?}\", local); let mut storage_live_stmt = None; let mut storage_dead_stmt = None; for (idx, stmt) in stmts.iter().enumerate() { if stmt.kind == StatementKind::StorageLive(local) { storage_live_stmt = Some(idx); } else if stmt.kind == StatementKind::StorageDead(local) { storage_dead_stmt = Some(idx); } } Some((storage_live_stmt?, storage_dead_stmt.unwrap_or(usize::MAX))) } // Try to match the expected MIR structure with the basic block we're processing. // We want to see something that looks like: // ``` // (StorageLive(_) | StorageDead(_));* // _LOCAL_INTO = ((_LOCAL_FROM as Variant).FIELD: TY); // (StorageLive(_) | StorageDead(_));* // (tmp_n+1 = tmp_n);* // (StorageLive(_) | StorageDead(_));* // (tmp_n+1 = tmp_n);* // ((LOCAL_FROM as Variant).FIELD: TY) = move tmp; // discriminant(LOCAL_FROM) = VariantIdx; // (StorageLive(_) | StorageDead(_));* // ``` let mut stmt_iter = stmts.iter().enumerate().peekable(); try_eat_storage_stmts(&mut stmt_iter, &mut storage_live_stmts, &mut storage_dead_stmts); let (get_variant_field_stmt, stmt) = stmt_iter.next()?; let (local_tmp_s0, local_1, vf_s0, dbg_projection) = match_get_variant_field(stmt)?; try_eat_storage_stmts(&mut stmt_iter, &mut storage_live_stmts, &mut storage_dead_stmts); try_eat_assign_tmp_stmts(&mut stmt_iter, &mut tmp_assigns, &mut nop_stmts); try_eat_storage_stmts(&mut stmt_iter, &mut storage_live_stmts, &mut storage_dead_stmts); try_eat_assign_tmp_stmts(&mut stmt_iter, &mut tmp_assigns, &mut nop_stmts); let (idx, stmt) = stmt_iter.next()?; let (local_tmp_s1, local_0, vf_s1) = match_set_variant_field(stmt)?; nop_stmts.push(idx); let (idx, stmt) = stmt_iter.next()?; let (set_discr_local, set_discr_var_idx) = match_set_discr(stmt)?; let discr_stmt_source_info = stmt.source_info; nop_stmts.push(idx); try_eat_storage_stmts(&mut stmt_iter, &mut storage_live_stmts, &mut storage_dead_stmts); for (live_idx, live_local) in storage_live_stmts { if let Some(i) = storage_dead_stmts.iter().rposition(|(_, l)| *l == live_local) { let (dead_idx, _) = storage_dead_stmts.swap_remove(i); storage_stmts.push((live_idx, dead_idx, live_local)); if live_local == local_tmp_s0 { nop_stmts.push(get_variant_field_stmt); } } } // We sort primitive usize here so we can use unstable sort nop_stmts.sort_unstable(); // Use one of the statements we're going to discard between the point // where the storage location for the variant field becomes live and // is killed. let (live_idx, dead_idx) = find_storage_live_dead_stmts_for_local(local_tmp_s0, stmts)?; let stmt_to_overwrite = nop_stmts.iter().find(|stmt_idx| live_idx < **stmt_idx && **stmt_idx < dead_idx); let mut tmp_assigned_vars = BitSet::new_empty(locals_count); for (l, r) in &tmp_assigns { tmp_assigned_vars.insert(*l); tmp_assigned_vars.insert(*r); } let dbg_info_to_adjust: Vec<_> = debug_info .iter() .enumerate() .filter_map(|(i, var_info)| { if let VarDebugInfoContents::Place(p) = var_info.value { if tmp_assigned_vars.contains(p.local) { return Some(i); } } None }) .collect(); Some(ArmIdentityInfo { local_temp_0: local_tmp_s0, local_1, vf_s0, get_variant_field_stmt, field_tmp_assignments: tmp_assigns, local_tmp_s1, local_0, vf_s1, set_discr_local, set_discr_var_idx, stmt_to_overwrite: *stmt_to_overwrite?, source_info: discr_stmt_source_info, storage_stmts, stmts_to_remove: nop_stmts, dbg_info_to_adjust, dbg_projection, }) } fn optimization_applies<'tcx>( opt_info: &ArmIdentityInfo<'tcx>, local_decls: &IndexVec>, local_uses: &IndexVec, var_debug_info: &[VarDebugInfo<'tcx>], ) -> bool { trace!(\"testing if optimization applies...\"); // FIXME(wesleywiser): possibly relax this restriction? if opt_info.local_0 == opt_info.local_1 { trace!(\"NO: moving into ourselves\"); return false; } else if opt_info.vf_s0 != opt_info.vf_s1 { trace!(\"NO: the field-and-variant information do not match\"); return false; } else if local_decls[opt_info.local_0].ty != local_decls[opt_info.local_1].ty { // FIXME(Centril,oli-obk): possibly relax to same layout? trace!(\"NO: source and target locals have different types\"); return false; } else if (opt_info.local_0, opt_info.vf_s0.var_idx) != (opt_info.set_discr_local, opt_info.set_discr_var_idx) { trace!(\"NO: the discriminants do not match\"); return false; } // Verify the assignment chain consists of the form b = a; c = b; d = c; etc... if opt_info.field_tmp_assignments.is_empty() { trace!(\"NO: no assignments found\"); return false; } let mut last_assigned_to = opt_info.field_tmp_assignments[0].1; let source_local = last_assigned_to; for (l, r) in &opt_info.field_tmp_assignments { if *r != last_assigned_to { trace!(\"NO: found unexpected assignment {:?} = {:?}\", l, r); return false; } last_assigned_to = *l; } // Check that the first and last used locals are only used twice // since they are of the form: // // ``` // _first = ((_x as Variant).n: ty); // _n = _first; // ... // ((_y as Variant).n: ty) = _n; // discriminant(_y) = z; // ``` for (l, r) in &opt_info.field_tmp_assignments { if local_uses[*l] != 2 { warn!(\"NO: FAILED assignment chain local {:?} was used more than twice\", l); return false; } else if local_uses[*r] != 2 { warn!(\"NO: FAILED assignment chain local {:?} was used more than twice\", r); return false; } } // Check that debug info only points to full Locals and not projections. for dbg_idx in &opt_info.dbg_info_to_adjust { let dbg_info = &var_debug_info[*dbg_idx]; if let VarDebugInfoContents::Place(p) = dbg_info.value { if !p.projection.is_empty() { trace!(\"NO: debug info for {:?} had a projection {:?}\", dbg_info.name, p); return false; } } } if source_local != opt_info.local_temp_0 { trace!( \"NO: start of assignment chain does not match enum variant temp: {:?} != {:?}\", source_local, opt_info.local_temp_0 ); return false; } else if last_assigned_to != opt_info.local_tmp_s1 { trace!( \"NO: end of assignment chain does not match written enum temp: {:?} != {:?}\", last_assigned_to, opt_info.local_tmp_s1 ); return false; } trace!(\"SUCCESS: optimization applies!\"); true } impl<'tcx> MirPass<'tcx> for SimplifyArmIdentity { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // FIXME(77359): This optimization can result in unsoundness. if !tcx.sess.opts.unstable_opts.unsound_mir_opts { return; } let source = body.source; trace!(\"running SimplifyArmIdentity on {:?}\", source); let local_uses = LocalUseCounter::get_local_uses(body); for bb in body.basic_blocks.as_mut() { if let Some(opt_info) = get_arm_identity_info(&bb.statements, body.local_decls.len(), &body.var_debug_info) { trace!(\"got opt_info = {:#?}\", opt_info); if !optimization_applies( &opt_info, &body.local_decls, &local_uses, &body.var_debug_info, ) { debug!(\"optimization skipped for {:?}\", source); continue; } // Also remove unused Storage{Live,Dead} statements which correspond // to temps used previously. for (live_idx, dead_idx, local) in &opt_info.storage_stmts { // The temporary that we've read the variant field into is scoped to this block, // so we can remove the assignment. if *local == opt_info.local_temp_0 { bb.statements[opt_info.get_variant_field_stmt].make_nop(); } for (left, right) in &opt_info.field_tmp_assignments { if local == left || local == right { bb.statements[*live_idx].make_nop(); bb.statements[*dead_idx].make_nop(); } } } // Right shape; transform for stmt_idx in opt_info.stmts_to_remove { bb.statements[stmt_idx].make_nop(); } let stmt = &mut bb.statements[opt_info.stmt_to_overwrite]; stmt.source_info = opt_info.source_info; stmt.kind = StatementKind::Assign(Box::new(( opt_info.local_0.into(), Rvalue::Use(Operand::Move(opt_info.local_1.into())), ))); bb.statements.retain(|stmt| stmt.kind != StatementKind::Nop); // Fix the debug info to point to the right local for dbg_index in opt_info.dbg_info_to_adjust { let dbg_info = &mut body.var_debug_info[dbg_index]; assert!( matches!(dbg_info.value, VarDebugInfoContents::Place(_)), \"value was not a Place\" ); if let VarDebugInfoContents::Place(p) = &mut dbg_info.value { assert!(p.projection.is_empty()); p.local = opt_info.local_0; p.projection = opt_info.dbg_projection; } } trace!(\"block is now {:?}\", bb.statements); } } } } struct LocalUseCounter { local_uses: IndexVec, } impl LocalUseCounter { fn get_local_uses(body: &Body<'_>) -> IndexVec { let mut counter = LocalUseCounter { local_uses: IndexVec::from_elem(0, &body.local_decls) }; counter.visit_body(body); counter.local_uses } } impl Visitor<'_> for LocalUseCounter { fn visit_local(&mut self, local: Local, context: PlaceContext, _location: Location) { if context.is_storage_marker() || context == PlaceContext::NonUse(NonUseContext::VarDebugInfo) { return; } self.local_uses[local] += 1; } } /// Match on: /// ```ignore (MIR) /// _LOCAL_INTO = ((_LOCAL_FROM as Variant).FIELD: TY); /// ``` fn match_get_variant_field<'tcx>( stmt: &Statement<'tcx>, ) -> Option<(Local, Local, VarField<'tcx>, &'tcx List>)> { match &stmt.kind { StatementKind::Assign(box ( place_into, Rvalue::Use(Operand::Copy(pf) | Operand::Move(pf)), )) => { let local_into = place_into.as_local()?; let (local_from, vf) = match_variant_field_place(*pf)?; Some((local_into, local_from, vf, pf.projection)) } _ => None, } } /// Match on: /// ```ignore (MIR) /// ((_LOCAL_FROM as Variant).FIELD: TY) = move _LOCAL_INTO; /// ``` fn match_set_variant_field<'tcx>(stmt: &Statement<'tcx>) -> Option<(Local, Local, VarField<'tcx>)> { match &stmt.kind { StatementKind::Assign(box (place_from, Rvalue::Use(Operand::Move(place_into)))) => { let local_into = place_into.as_local()?; let (local_from, vf) = match_variant_field_place(*place_from)?; Some((local_into, local_from, vf)) } _ => None, } } /// Match on: /// ```ignore (MIR) /// discriminant(_LOCAL_TO_SET) = VAR_IDX; /// ``` fn match_set_discr(stmt: &Statement<'_>) -> Option<(Local, VariantIdx)> { match &stmt.kind { StatementKind::SetDiscriminant { place, variant_index } => { Some((place.as_local()?, *variant_index)) } _ => None, } } #[derive(PartialEq, Debug)] struct VarField<'tcx> { field: Field, field_ty: Ty<'tcx>, var_idx: VariantIdx, } /// Match on `((_LOCAL as Variant).FIELD: TY)`. fn match_variant_field_place(place: Place<'_>) -> Option<(Local, VarField<'_>)> { match place.as_ref() { PlaceRef { local, projection: &[ProjectionElem::Downcast(_, var_idx), ProjectionElem::Field(field, ty)], } => Some((local, VarField { field, field_ty: ty, var_idx })), _ => None, } } /// Simplifies `SwitchInt(_) -> [targets]`, /// where all the `targets` have the same form, /// into `goto -> target_first`. pub struct SimplifyBranchSame; impl<'tcx> MirPass<'tcx> for SimplifyBranchSame { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // This optimization is disabled by default for now due to // soundness concerns; see issue #89485 and PR #89489. if !tcx.sess.opts.unstable_opts.unsound_mir_opts { return; } trace!(\"Running SimplifyBranchSame on {:?}\", body.source); let finder = SimplifyBranchSameOptimizationFinder { body, tcx }; let opts = finder.find(); let did_remove_blocks = opts.len() > 0; for opt in opts.iter() { trace!(\"SUCCESS: Applying optimization {:?}\", opt); // Replace `SwitchInt(..) -> [bb_first, ..];` with a `goto -> bb_first;`. body.basic_blocks_mut()[opt.bb_to_opt_terminator].terminator_mut().kind = TerminatorKind::Goto { target: opt.bb_to_goto }; } if did_remove_blocks { // We have dead blocks now, so remove those. simplify::remove_dead_blocks(tcx, body); } } } #[derive(Debug)] struct SimplifyBranchSameOptimization { /// All basic blocks are equal so go to this one bb_to_goto: BasicBlock, /// Basic block where the terminator can be simplified to a goto bb_to_opt_terminator: BasicBlock, } struct SwitchTargetAndValue { target: BasicBlock, // None in case of the `otherwise` case value: Option, } struct SimplifyBranchSameOptimizationFinder<'a, 'tcx> { body: &'a Body<'tcx>, tcx: TyCtxt<'tcx>, } impl<'tcx> SimplifyBranchSameOptimizationFinder<'_, 'tcx> { fn find(&self) -> Vec { self.body .basic_blocks .iter_enumerated() .filter_map(|(bb_idx, bb)| { let (discr_switched_on, targets_and_values) = match &bb.terminator().kind { TerminatorKind::SwitchInt { targets, discr, .. } => { let targets_and_values: Vec<_> = targets.iter() .map(|(val, target)| SwitchTargetAndValue { target, value: Some(val) }) .chain(once(SwitchTargetAndValue { target: targets.otherwise(), value: None })) .collect(); (discr, targets_and_values) }, _ => return None, }; // find the adt that has its discriminant read // assuming this must be the last statement of the block let adt_matched_on = match &bb.statements.last()?.kind { StatementKind::Assign(box (place, rhs)) if Some(*place) == discr_switched_on.place() => { match rhs { Rvalue::Discriminant(adt_place) if adt_place.ty(self.body, self.tcx).ty.is_enum() => adt_place, _ => { trace!(\"NO: expected a discriminant read of an enum instead of: {:?}\", rhs); return None; } } } other => { trace!(\"NO: expected an assignment of a discriminant read to a place. Found: {:?}\", other); return None }, }; let mut iter_bbs_reachable = targets_and_values .iter() .map(|target_and_value| (target_and_value, &self.body.basic_blocks[target_and_value.target])) .filter(|(_, bb)| { // Reaching `unreachable` is UB so assume it doesn't happen. bb.terminator().kind != TerminatorKind::Unreachable }) .peekable(); let bb_first = iter_bbs_reachable.peek().map_or(&targets_and_values[0], |(idx, _)| *idx); let mut all_successors_equivalent = StatementEquality::TrivialEqual; // All successor basic blocks must be equal or contain statements that are pairwise considered equal. for ((target_and_value_l,bb_l), (target_and_value_r,bb_r)) in iter_bbs_reachable.tuple_windows() { let trivial_checks = bb_l.is_cleanup == bb_r.is_cleanup && bb_l.terminator().kind == bb_r.terminator().kind && bb_l.statements.len() == bb_r.statements.len(); let statement_check = || { bb_l.statements.iter().zip(&bb_r.statements).try_fold(StatementEquality::TrivialEqual, |acc,(l,r)| { let stmt_equality = self.statement_equality(*adt_matched_on, &l, target_and_value_l, &r, target_and_value_r); if matches!(stmt_equality, StatementEquality::NotEqual) { // short circuit None } else { Some(acc.combine(&stmt_equality)) } }) .unwrap_or(StatementEquality::NotEqual) }; if !trivial_checks { all_successors_equivalent = StatementEquality::NotEqual; break; } all_successors_equivalent = all_successors_equivalent.combine(&statement_check()); }; match all_successors_equivalent{ StatementEquality::TrivialEqual => { // statements are trivially equal, so just take first trace!(\"Statements are trivially equal\"); Some(SimplifyBranchSameOptimization { bb_to_goto: bb_first.target, bb_to_opt_terminator: bb_idx, }) } StatementEquality::ConsideredEqual(bb_to_choose) => { trace!(\"Statements are considered equal\"); Some(SimplifyBranchSameOptimization { bb_to_goto: bb_to_choose, bb_to_opt_terminator: bb_idx, }) } StatementEquality::NotEqual => { trace!(\"NO: not all successors of basic block {:?} were equivalent\", bb_idx); None } } }) .collect() } /// Tests if two statements can be considered equal /// /// Statements can be trivially equal if the kinds match. /// But they can also be considered equal in the following case A: /// ```ignore (MIR) /// discriminant(_0) = 0; // bb1 /// _0 = move _1; // bb2 /// ``` /// In this case the two statements are equal iff /// - `_0` is an enum where the variant index 0 is fieldless, and /// - bb1 was targeted by a switch where the discriminant of `_1` was switched on fn statement_equality( &self, adt_matched_on: Place<'tcx>, x: &Statement<'tcx>, x_target_and_value: &SwitchTargetAndValue, y: &Statement<'tcx>, y_target_and_value: &SwitchTargetAndValue, ) -> StatementEquality { let helper = |rhs: &Rvalue<'tcx>, place: &Place<'tcx>, variant_index: VariantIdx, switch_value: u128, side_to_choose| { let place_type = place.ty(self.body, self.tcx).ty; let adt = match *place_type.kind() { ty::Adt(adt, _) if adt.is_enum() => adt, _ => return StatementEquality::NotEqual, }; // We need to make sure that the switch value that targets the bb with // SetDiscriminant is the same as the variant discriminant. let variant_discr = adt.discriminant_for_variant(self.tcx, variant_index).val; if variant_discr != switch_value { trace!( \"NO: variant discriminant {} does not equal switch value {}\", variant_discr, switch_value ); return StatementEquality::NotEqual; } let variant_is_fieldless = adt.variant(variant_index).fields.is_empty(); if !variant_is_fieldless { trace!(\"NO: variant {:?} was not fieldless\", variant_index); return StatementEquality::NotEqual; } match rhs { Rvalue::Use(operand) if operand.place() == Some(adt_matched_on) => { StatementEquality::ConsideredEqual(side_to_choose) } _ => { trace!( \"NO: RHS of assignment was {:?}, but expected it to match the adt being matched on in the switch, which is {:?}\", rhs, adt_matched_on ); StatementEquality::NotEqual } } }; match (&x.kind, &y.kind) { // trivial case (x, y) if x == y => StatementEquality::TrivialEqual, // check for case A ( StatementKind::Assign(box (_, rhs)), &StatementKind::SetDiscriminant { ref place, variant_index }, ) if y_target_and_value.value.is_some() => { // choose basic block of x, as that has the assign helper( rhs, place, variant_index, y_target_and_value.value.unwrap(), x_target_and_value.target, ) } ( &StatementKind::SetDiscriminant { ref place, variant_index }, &StatementKind::Assign(box (_, ref rhs)), ) if x_target_and_value.value.is_some() => { // choose basic block of y, as that has the assign helper( rhs, place, variant_index, x_target_and_value.value.unwrap(), y_target_and_value.target, ) } _ => { trace!(\"NO: statements `{:?}` and `{:?}` not considered equal\", x, y); StatementEquality::NotEqual } } } } #[derive(Copy, Clone, Eq, PartialEq)] enum StatementEquality { /// The two statements are trivially equal; same kind TrivialEqual, /// The two statements are considered equal, but may be of different kinds. The BasicBlock field is the basic block to jump to when performing the branch-same optimization. /// For example, `_0 = _1` and `discriminant(_0) = discriminant(0)` are considered equal if 0 is a fieldless variant of an enum. But we don't want to jump to the basic block with the SetDiscriminant, as that is not legal if _1 is not the 0 variant index ConsideredEqual(BasicBlock), /// The two statements are not equal NotEqual, } impl StatementEquality { fn combine(&self, other: &StatementEquality) -> StatementEquality { use StatementEquality::*; match (self, other) { (TrivialEqual, TrivialEqual) => TrivialEqual, (TrivialEqual, ConsideredEqual(b)) | (ConsideredEqual(b), TrivialEqual) => { ConsideredEqual(*b) } (ConsideredEqual(b1), ConsideredEqual(b2)) => { if b1 == b2 { ConsideredEqual(*b1) } else { NotEqual } } (_, NotEqual) | (NotEqual, _) => NotEqual, } } } "} {"_id":"doc-en-rust-ce970c52ebb4d8d7f5c2c9c438ae458312ff689726771c26a4dee4b74a9a94f8","title":"","text":" - // MIR for `encode` before SimplifyBranchSame + // MIR for `encode` after SimplifyBranchSame fn encode(_1: Type) -> Type { debug v => _1; // in scope 0 at $DIR/76803_regression.rs:+0:15: +0:16 let mut _0: Type; // return place in scope 0 at $DIR/76803_regression.rs:+0:27: +0:31 let mut _2: isize; // in scope 0 at $DIR/76803_regression.rs:+2:9: +2:16 bb0: { _2 = discriminant(_1); // scope 0 at $DIR/76803_regression.rs:+1:11: +1:12 switchInt(move _2) -> [0: bb2, otherwise: bb1]; // scope 0 at $DIR/76803_regression.rs:+1:5: +1:12 } bb1: { _0 = move _1; // scope 0 at $DIR/76803_regression.rs:+3:14: +3:15 goto -> bb3; // scope 0 at $DIR/76803_regression.rs:+3:14: +3:15 } bb2: { Deinit(_0); // scope 0 at $DIR/76803_regression.rs:+2:20: +2:27 discriminant(_0) = 1; // scope 0 at $DIR/76803_regression.rs:+2:20: +2:27 goto -> bb3; // scope 0 at $DIR/76803_regression.rs:+2:20: +2:27 } bb3: { return; // scope 0 at $DIR/76803_regression.rs:+5:2: +5:2 } } "} {"_id":"doc-en-rust-80b55407cfb8920297c2e1a47fa2070124932cfd053a41b682d43d58c4d372f4","title":"","text":" // compile-flags: -Z mir-opt-level=1 // EMIT_MIR 76803_regression.encode.SimplifyBranchSame.diff #[derive(Debug, Eq, PartialEq)] pub enum Type { A, B, } pub fn encode(v: Type) -> Type { match v { Type::A => Type::B, _ => v, } } fn main() { assert_eq!(Type::B, encode(Type::A)); } "} {"_id":"doc-en-rust-26b16528091120304415f15f2e603dd093cc307dfb1edf628f87749e717e2008","title":"","text":" - // MIR for `main` before SimplifyArmIdentity + // MIR for `main` after SimplifyArmIdentity fn main() -> () { let mut _0: (); // return place in scope 0 at $DIR/issue_73223.rs:+0:11: +0:11 let _1: i32; // in scope 0 at $DIR/issue_73223.rs:+1:9: +1:14 let mut _2: std::option::Option; // in scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 let mut _3: isize; // in scope 0 at $DIR/issue_73223.rs:+2:9: +2:16 let _4: i32; // in scope 0 at $DIR/issue_73223.rs:+2:14: +2:15 let mut _6: i32; // in scope 0 at $DIR/issue_73223.rs:+6:22: +6:27 let mut _7: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _8: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _11: bool; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _12: bool; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _13: i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _14: i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let _16: !; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _17: core::panicking::AssertKind; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _18: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let _19: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _20: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let _21: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _22: std::option::Option>; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _24: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _25: &i32; // in scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL scope 1 { debug split => _1; // in scope 1 at $DIR/issue_73223.rs:+1:9: +1:14 let _5: std::option::Option; // in scope 1 at $DIR/issue_73223.rs:+6:9: +6:14 scope 3 { debug _prev => _5; // in scope 3 at $DIR/issue_73223.rs:+6:9: +6:14 let _9: &i32; // in scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let _10: &i32; // in scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let mut _23: &i32; // in scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL scope 4 { debug left_val => _9; // in scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL debug right_val => _10; // in scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL let _15: core::panicking::AssertKind; // in scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL scope 5 { debug kind => _15; // in scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL } } } } scope 2 { debug v => _4; // in scope 2 at $DIR/issue_73223.rs:+2:14: +2:15 } bb0: { StorageLive(_1); // scope 0 at $DIR/issue_73223.rs:+1:9: +1:14 StorageLive(_2); // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 Deinit(_2); // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 ((_2 as Some).0: i32) = const 1_i32; // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 discriminant(_2) = 1; // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 _3 = const 1_isize; // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 goto -> bb3; // scope 0 at $DIR/issue_73223.rs:+1:17: +1:30 } bb1: { StorageDead(_2); // scope 0 at $DIR/issue_73223.rs:+4:6: +4:7 StorageDead(_1); // scope 0 at $DIR/issue_73223.rs:+8:1: +8:2 return; // scope 0 at $DIR/issue_73223.rs:+8:2: +8:2 } bb2: { unreachable; // scope 0 at $DIR/issue_73223.rs:+1:23: +1:30 } bb3: { StorageLive(_4); // scope 0 at $DIR/issue_73223.rs:+2:14: +2:15 _4 = ((_2 as Some).0: i32); // scope 0 at $DIR/issue_73223.rs:+2:14: +2:15 _1 = _4; // scope 2 at $DIR/issue_73223.rs:+2:20: +2:21 StorageDead(_4); // scope 0 at $DIR/issue_73223.rs:+2:20: +2:21 StorageDead(_2); // scope 0 at $DIR/issue_73223.rs:+4:6: +4:7 StorageLive(_5); // scope 1 at $DIR/issue_73223.rs:+6:9: +6:14 StorageLive(_6); // scope 1 at $DIR/issue_73223.rs:+6:22: +6:27 _6 = _1; // scope 1 at $DIR/issue_73223.rs:+6:22: +6:27 Deinit(_5); // scope 1 at $DIR/issue_73223.rs:+6:17: +6:28 ((_5 as Some).0: i32) = move _6; // scope 1 at $DIR/issue_73223.rs:+6:17: +6:28 discriminant(_5) = 1; // scope 1 at $DIR/issue_73223.rs:+6:17: +6:28 StorageDead(_6); // scope 1 at $DIR/issue_73223.rs:+6:27: +6:28 StorageLive(_24); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_25); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_7); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _7 = &_1; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _23 = const _; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL // mir::Constant // + span: $SRC_DIR/core/src/macros/mod.rs:LL:COL // + literal: Const { ty: &i32, val: Unevaluated(main, [], Some(promoted[0])) } _8 = _23; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL Deinit(_24); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL Deinit(_25); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _24 = move _7; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _25 = move _8; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_8); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_7); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_9); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _9 = _24; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_10); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _10 = _25; // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_11); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_12); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_13); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _13 = (*_9); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_14); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _14 = const 1_i32; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _12 = Eq(move _13, const 1_i32); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_14); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_13); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _11 = Not(move _12); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_12); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL switchInt(move _11) -> [0: bb5, otherwise: bb4]; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL } bb4: { StorageLive(_15); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL Deinit(_15); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL discriminant(_15) = 0; // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_16); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_17); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _17 = const core::panicking::AssertKind::Eq; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL // mir::Constant // + span: $SRC_DIR/core/src/macros/mod.rs:LL:COL // + literal: Const { ty: core::panicking::AssertKind, val: Value(Scalar(0x00)) } StorageLive(_18); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_19); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _19 = _9; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _18 = _19; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_20); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_21); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _21 = _10; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _20 = _21; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageLive(_22); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL Deinit(_22); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL discriminant(_22) = 0; // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL _16 = core::panicking::assert_failed::(const core::panicking::AssertKind::Eq, move _18, move _20, move _22); // scope 5 at $SRC_DIR/core/src/macros/mod.rs:LL:COL // mir::Constant // + span: $SRC_DIR/core/src/macros/mod.rs:LL:COL // + literal: Const { ty: for<'a, 'b, 'c> fn(core::panicking::AssertKind, &'a i32, &'b i32, Option>) -> ! {core::panicking::assert_failed::}, val: Value() } // mir::Constant // + span: $SRC_DIR/core/src/macros/mod.rs:LL:COL // + literal: Const { ty: core::panicking::AssertKind, val: Value(Scalar(0x00)) } } bb5: { StorageDead(_11); // scope 4 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_10); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_9); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_24); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_25); // scope 3 at $SRC_DIR/core/src/macros/mod.rs:LL:COL StorageDead(_5); // scope 1 at $DIR/issue_73223.rs:+8:1: +8:2 StorageDead(_1); // scope 0 at $DIR/issue_73223.rs:+8:1: +8:2 return; // scope 0 at $DIR/issue_73223.rs:+8:2: +8:2 } } "} {"_id":"doc-en-rust-021ca0a300050d84e80586e97d3ea3eba41c68a6647c0533ac25a8eac371b113","title":"","text":" fn main() { let split = match Some(1) { Some(v) => v, None => return, }; let _prev = Some(split); assert_eq!(split, 1); } // EMIT_MIR issue_73223.main.SimplifyArmIdentity.diff "} {"_id":"doc-en-rust-8858d30bebdc44d9d3f713f6075358ea7af6be3bfd9dbcef09bfb0872362c4e1","title":"","text":"} _ => { self.tcx.sess.emit_err(YieldExprOutsideOfGenerator { span: expr.span }); // Avoid expressions without types during writeback (#78653). self.check_expr(value); self.tcx.mk_unit() } }"} {"_id":"doc-en-rust-5197182d57afc088b76ec12d581df1d6bab9ac6728675b0dcf453e5cf2eacffe","title":"","text":" #![feature(generators)] fn main() { yield || for i in 0 { } //~^ ERROR yield expression outside of generator literal //~| ERROR `{integer}` is not an iterator } "} {"_id":"doc-en-rust-b4de2a27a785a73957725259e5b1ead4147016447189ad0f5088722d331d99fb","title":"","text":" error[E0627]: yield expression outside of generator literal --> $DIR/yield-outside-generator-issue-78653.rs:4:5 | LL | yield || for i in 0 { } | ^^^^^^^^^^^^^^^^^^^^^^^ error[E0277]: `{integer}` is not an iterator --> $DIR/yield-outside-generator-issue-78653.rs:4:23 | LL | yield || for i in 0 { } | ^ `{integer}` is not an iterator | = help: the trait `Iterator` is not implemented for `{integer}` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required because of the requirements on the impl of `IntoIterator` for `{integer}` = note: required by `into_iter` error: aborting due to 2 previous errors Some errors have detailed explanations: E0277, E0627. For more information about an error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-2602f1de197061eb1ae0b17b746c5a884f0a38f8dc38b2b3c5183c75d83b5e14","title":"","text":"const WHILE_PARSING_OR_MSG: &str = \"while parsing this or-pattern starting here\"; /// Whether or not an or-pattern should be gated when occurring in the current context. #[derive(PartialEq)] #[derive(PartialEq, Clone, Copy)] pub(super) enum GateOr { Yes, No,"} {"_id":"doc-en-rust-2c46cee894c3b7ada4f6d4c43fce1d595f3d21261b973c4f2ecdf7a7fb71ae8a","title":"","text":") -> PResult<'a, P> { // Parse the first pattern (`p_0`). let first_pat = self.parse_pat(expected)?; self.maybe_recover_unexpected_comma(first_pat.span, rc)?; self.maybe_recover_unexpected_comma(first_pat.span, rc, gate_or)?; // If the next token is not a `|`, // this is not an or-pattern and we should exit here."} {"_id":"doc-en-rust-088e1bc2192a3d1b129e07129d2403ef808a8167a73269e62cdc2d06bcc50a14","title":"","text":"err.span_label(lo, WHILE_PARSING_OR_MSG); err })?; self.maybe_recover_unexpected_comma(pat.span, rc)?; self.maybe_recover_unexpected_comma(pat.span, rc, gate_or)?; pats.push(pat); } let or_pattern_span = lo.to(self.prev_token.span);"} {"_id":"doc-en-rust-703d8c4099d28f55166e04d438bd8d2417f8ea39262ee018c277cca70e668d5b","title":"","text":"/// Some special error handling for the \"top-level\" patterns in a match arm, /// `for` loop, `let`, &c. (in contrast to subpatterns within such). fn maybe_recover_unexpected_comma(&mut self, lo: Span, rc: RecoverComma) -> PResult<'a, ()> { fn maybe_recover_unexpected_comma( &mut self, lo: Span, rc: RecoverComma, gate_or: GateOr, ) -> PResult<'a, ()> { if rc == RecoverComma::No || self.token != token::Comma { return Ok(()); }"} {"_id":"doc-en-rust-a8e8742d889ee08197910c88ce6717a1010d929d0051e35f283bed7cec08e9a2","title":"","text":"let seq_span = lo.to(self.prev_token.span); let mut err = self.struct_span_err(comma_span, \"unexpected `,` in pattern\"); if let Ok(seq_snippet) = self.span_to_snippet(seq_span) { const MSG: &str = \"try adding parentheses to match on a tuple...\"; let or_suggestion = gate_or == GateOr::No || !self.sess.gated_spans.is_ungated(sym::or_patterns); err.span_suggestion( seq_span, \"try adding parentheses to match on a tuple...\", if or_suggestion { MSG } else { MSG.trim_end_matches('.') }, format!(\"({})\", seq_snippet), Applicability::MachineApplicable, ) .span_suggestion( seq_span, \"...or a vertical bar to match on multiple alternatives\", seq_snippet.replace(\",\", \" |\"), Applicability::MachineApplicable, ); if or_suggestion { err.span_suggestion( seq_span, \"...or a vertical bar to match on multiple alternatives\", seq_snippet.replace(\",\", \" |\"), Applicability::MachineApplicable, ); } } Err(err) }"} {"_id":"doc-en-rust-445952fe15cf4394b60c8c395ce064caf64c6de2bfde61140853584c88ca1943","title":"","text":"--> $DIR/issue-48492-tuple-destructure-missing-parens.rs:67:10 | LL | for x, _barr_body in women.iter().map(|woman| woman.allosomes.clone()) { | ^ | help: try adding parentheses to match on a tuple... | LL | for (x, _barr_body) in women.iter().map(|woman| woman.allosomes.clone()) { | ^^^^^^^^^^^^^^^ help: ...or a vertical bar to match on multiple alternatives | LL | for x | _barr_body in women.iter().map(|woman| woman.allosomes.clone()) { | ^^^^^^^^^^^^^^ | -^----------- help: try adding parentheses to match on a tuple: `(x, _barr_body)` error: unexpected `,` in pattern --> $DIR/issue-48492-tuple-destructure-missing-parens.rs:75:10 | LL | for x, y @ Allosome::Y(_) in men.iter().map(|man| man.allosomes.clone()) { | ^ | help: try adding parentheses to match on a tuple... | LL | for (x, y @ Allosome::Y(_)) in men.iter().map(|man| man.allosomes.clone()) { | ^^^^^^^^^^^^^^^^^^^^^^^ help: ...or a vertical bar to match on multiple alternatives | LL | for x | y @ Allosome::Y(_) in men.iter().map(|man| man.allosomes.clone()) { | ^^^^^^^^^^^^^^^^^^^^^^ | -^------------------- help: try adding parentheses to match on a tuple: `(x, y @ Allosome::Y(_))` error: unexpected `,` in pattern --> $DIR/issue-48492-tuple-destructure-missing-parens.rs:84:14 | LL | let women, men: (Vec, Vec) = genomes.iter().cloned() | ^ | help: try adding parentheses to match on a tuple... | LL | let (women, men): (Vec, Vec) = genomes.iter().cloned() | ^^^^^^^^^^^^ help: ...or a vertical bar to match on multiple alternatives | LL | let women | men: (Vec, Vec) = genomes.iter().cloned() | ^^^^^^^^^^^ | -----^---- help: try adding parentheses to match on a tuple: `(women, men)` error: aborting due to 6 previous errors"} {"_id":"doc-en-rust-6cd5c706d6ff03560bdac27912ee565271e84d2ec60ba3e2ad2d97962584a5d0","title":"","text":"Ok(true) } ty::Float(_) | ty::Int(_) | ty::Uint(_) => { let value = self.ecx.read_scalar(value)?; let value = try_validation!( self.ecx.read_scalar(value), self.path, err_unsup!(ReadPointerAsBytes) => { \"read of part of a pointer\" }, ); // NOTE: Keep this in sync with the array optimization for int/float // types below! if self.ctfe_mode.is_some() {"} {"_id":"doc-en-rust-79aa393b624f54a2e99c47156a08fbd4b26c3741acb8aced3235a4c1a600c124","title":"","text":" // ignore-32bit // This test gives a different error on 32-bit architectures. union Transmute { t: T, u: U, } trait Bar { fn bar(&self) -> u32; } struct Foo { foo: u32, bar: bool, } impl Bar for Foo { fn bar(&self) -> u32 { self.foo } } #[derive(Copy, Clone)] struct Fat<'a>(&'a Foo, &'static VTable); struct VTable { size: Foo, } const FOO: &dyn Bar = &Foo { foo: 128, bar: false, }; const G: Fat = unsafe { Transmute { t: FOO }.u }; //~^ ERROR it is undefined behavior to use this value fn main() {} "} {"_id":"doc-en-rust-853d7432c85a094f995058d56a963708e24a3cea50ed170bc5e99ea31ed334ad","title":"","text":" error[E0080]: it is undefined behavior to use this value --> $DIR/issue-79690.rs:29:1 | LL | const G: Fat = unsafe { Transmute { t: FOO }.u }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered read of part of a pointer at .1..size.foo | = note: 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. error: aborting due to previous error For more information about this error, try `rustc --explain E0080`. "} {"_id":"doc-en-rust-7ba9986608ece219f2317d99a4b77397a9f59ee9f88a3b1282a082dde676a5ee","title":"","text":"use super::{ CheckInAllocMsg, GlobalAlloc, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy, ValueVisitor, ScalarMaybeUninit, ValueVisitor, }; macro_rules! throw_validation_failure {"} {"_id":"doc-en-rust-6a3d7213d17f8a0de9edec1b5ca3f9aefee79fc90da991a6a95e4e70fe7b70d5","title":"","text":"value: OpTy<'tcx, M::PointerTag>, kind: &str, ) -> InterpResult<'tcx> { let value = self.ecx.read_immediate(value)?; let value = try_validation!( self.ecx.read_immediate(value), self.path, err_unsup!(ReadPointerAsBytes) => { \"part of a pointer\" } expected { \"a proper pointer or integer value\" }, ); // Handle wide pointers. // Check metadata early, for better diagnostics let place = try_validation!("} {"_id":"doc-en-rust-c3f4686ef5f2b8ff60be0cc933d8a0adeeafe205adb138a2b370ce92b4862ea2","title":"","text":"Ok(()) } fn read_scalar( &self, op: OpTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx, ScalarMaybeUninit> { Ok(try_validation!( self.ecx.read_scalar(op), self.path, err_unsup!(ReadPointerAsBytes) => { \"(potentially part of) a pointer\" } expected { \"plain (non-pointer) bytes\" }, )) } /// Check if this is a value of primitive type, and if yes check the validity of the value /// at that type. Return `true` if the type is indeed primitive. fn try_visit_primitive("} {"_id":"doc-en-rust-827aed6956ea7c604876dae16e00c426aea50a60ef9ebf2702db9f0082ae72ea","title":"","text":"let ty = value.layout.ty; match ty.kind() { ty::Bool => { let value = self.ecx.read_scalar(value)?; let value = self.read_scalar(value)?; try_validation!( value.to_bool(), self.path,"} {"_id":"doc-en-rust-a849bda3b92157b73919620ddcc17aede5a5719763aa67841c2eb27f1eeef226","title":"","text":"Ok(true) } ty::Char => { let value = self.ecx.read_scalar(value)?; let value = self.read_scalar(value)?; try_validation!( value.to_char(), self.path,"} {"_id":"doc-en-rust-bb5b83a323d1e85c2bead45c2b17e4c2268676d98a359bef792ad4a7df0e443f","title":"","text":"Ok(true) } ty::Float(_) | ty::Int(_) | ty::Uint(_) => { let value = try_validation!( self.ecx.read_scalar(value), self.path, err_unsup!(ReadPointerAsBytes) => { \"read of part of a pointer\" }, ); let value = self.read_scalar(value)?; // NOTE: Keep this in sync with the array optimization for int/float // types below! if self.ctfe_mode.is_some() {"} {"_id":"doc-en-rust-74fd3895b19ba1103199d7b852d1c6ca666ca3f092d28abc08932fbe7a72d3f9","title":"","text":"// actually enforce the strict rules for raw pointers (mostly because // that lets us re-use `ref_to_mplace`). let place = try_validation!( self.ecx.ref_to_mplace(self.ecx.read_immediate(value)?), self.ecx.read_immediate(value).and_then(|i| self.ecx.ref_to_mplace(i)), self.path, err_ub!(InvalidUninitBytes(None)) => { \"uninitialized raw pointer\" }, err_unsup!(ReadPointerAsBytes) => { \"part of a pointer\" } expected { \"a proper pointer or integer value\" }, ); if place.layout.is_unsized() { self.check_wide_ptr_meta(place.meta, place.layout)?;"} {"_id":"doc-en-rust-cb9d70f42361b2541dfd0611505e677e9ddebce7af7b51b3ba8960767047b926","title":"","text":"Ok(true) } ty::FnPtr(_sig) => { let value = self.ecx.read_scalar(value)?; let value = try_validation!( self.ecx.read_immediate(value), self.path, err_unsup!(ReadPointerAsBytes) => { \"part of a pointer\" } expected { \"a proper pointer or integer value\" }, ); let _fn = try_validation!( value.check_init().and_then(|ptr| self.ecx.memory.get_fn(ptr)), value.to_scalar().and_then(|ptr| self.ecx.memory.get_fn(ptr)), self.path, err_ub!(DanglingIntPointer(..)) | err_ub!(InvalidFunctionPointer(..)) |"} {"_id":"doc-en-rust-d0222dfc5f5e19688e5ad3848933517a3b30b48d8531f1b59ffe72718eac6e43","title":"","text":"op: OpTy<'tcx, M::PointerTag>, scalar_layout: &Scalar, ) -> InterpResult<'tcx> { let value = self.ecx.read_scalar(op)?; let value = self.read_scalar(op)?; let valid_range = &scalar_layout.valid_range; let (lo, hi) = valid_range.clone().into_inner(); // Determine the allowed range"} {"_id":"doc-en-rust-c0449d29ab2301fc6c192ff7a09a590140cf88f8e7842952b48fee583513a9d7","title":"","text":"--> $DIR/issue-79690.rs:29:1 | LL | const G: Fat = unsafe { Transmute { t: FOO }.u }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered read of part of a pointer at .1..size.foo | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered (potentially part of) a pointer at .1..size.foo, but expected 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 rustc repository if you believe it should not be considered undefined behavior."} {"_id":"doc-en-rust-ecea18d7213b329f8a30c82d00e7f26ce153ee78a55ab2470d30d42ccaf3f3d1","title":"","text":"CodeBlockKind::Fenced(ref lang) => { LangString::parse_without_check(&lang, self.check_error_codes, false) } CodeBlockKind::Indented => LangString::all_false(), CodeBlockKind::Indented => Default::default(), }; if !parse_result.rust { return Some(Event::Start(Tag::CodeBlock(kind)));"} {"_id":"doc-en-rust-78f03bcbd73979a35bdd0efd40f8b45cb5394de833dba1fb1149ed81587bca92","title":"","text":"let block_info = match kind { CodeBlockKind::Fenced(ref lang) => { if lang.is_empty() { LangString::all_false() Default::default() } else { LangString::parse( lang,"} {"_id":"doc-en-rust-db82d8f8729cfec34c96d34016c88e2e03ec2f59fb5fa74019d4ac45d9c46392","title":"","text":") } } CodeBlockKind::Indented => LangString::all_false(), CodeBlockKind::Indented => Default::default(), }; if !block_info.rust { continue;"} {"_id":"doc-en-rust-0284198d0a17708867602d3cd6d6235b130cc7a113d9037e51a2708087131296","title":"","text":"Some(Vec), } impl LangString { fn all_false() -> LangString { LangString { impl Default for LangString { fn default() -> Self { Self { original: String::new(), should_panic: false, no_run: false, ignore: Ignore::None, rust: true, // NB This used to be `notrust = false` rust: true, test_harness: false, compile_fail: false, error_codes: Vec::new(),"} {"_id":"doc-en-rust-ea8c732911e3d08e456ef47e2a09dedf451b5c42f9cf470fa9ab225950203efe","title":"","text":"edition: None, } } } impl LangString { fn parse_without_check( string: &str, allow_error_code_check: ErrorCodes,"} {"_id":"doc-en-rust-a08bc18cd9a74ece6ff523d383b8afda6abd689e53f8f846f810ce49ccc68a6b","title":"","text":"let allow_error_code_check = allow_error_code_check.as_bool(); let mut seen_rust_tags = false; let mut seen_other_tags = false; let mut data = LangString::all_false(); let mut data = LangString::default(); let mut ignores = vec![]; data.original = string.to_owned();"} {"_id":"doc-en-rust-9a09840bb7a83469303fb8280b19147955df289b262e87f87ffafc45505450a4","title":"","text":"CodeBlockKind::Fenced(syntax) => { let syntax = syntax.as_ref(); let lang_string = if syntax.is_empty() { LangString::all_false() Default::default() } else { LangString::parse(&*syntax, ErrorCodes::Yes, false, Some(extra_info)) };"} {"_id":"doc-en-rust-a1351f675ce843c46680b1d0d7c6fb2dbe4005a5a927eb533fd4331d2bfc76c2","title":"","text":"assert_eq!(LangString::parse(s, ErrorCodes::Yes, true, None), lg) } t(LangString::all_false()); t(LangString { original: \"rust\".into(), ..LangString::all_false() }); t(LangString { original: \"sh\".into(), rust: false, ..LangString::all_false() }); t(LangString { original: \"ignore\".into(), ignore: Ignore::All, ..LangString::all_false() }); t(Default::default()); t(LangString { original: \"rust\".into(), ..Default::default() }); t(LangString { original: \"sh\".into(), rust: false, ..Default::default() }); t(LangString { original: \"ignore\".into(), ignore: Ignore::All, ..Default::default() }); t(LangString { original: \"ignore-foo\".into(), ignore: Ignore::Some(vec![\"foo\".to_string()]), ..LangString::all_false() }); t(LangString { original: \"should_panic\".into(), should_panic: true, ..LangString::all_false() }); t(LangString { original: \"no_run\".into(), no_run: true, ..LangString::all_false() }); t(LangString { original: \"test_harness\".into(), test_harness: true, ..LangString::all_false() ..Default::default() }); t(LangString { original: \"should_panic\".into(), should_panic: true, ..Default::default() }); t(LangString { original: \"no_run\".into(), no_run: true, ..Default::default() }); t(LangString { original: \"test_harness\".into(), test_harness: true, ..Default::default() }); t(LangString { original: \"compile_fail\".into(), no_run: true, compile_fail: true, ..LangString::all_false() }); t(LangString { original: \"allow_fail\".into(), allow_fail: true, ..LangString::all_false() }); t(LangString { original: \"{.no_run .example}\".into(), no_run: true, ..LangString::all_false() ..Default::default() }); t(LangString { original: \"allow_fail\".into(), allow_fail: true, ..Default::default() }); t(LangString { original: \"{.no_run .example}\".into(), no_run: true, ..Default::default() }); t(LangString { original: \"{.sh .should_panic}\".into(), should_panic: true, rust: false, ..LangString::all_false() ..Default::default() }); t(LangString { original: \"{.example .rust}\".into(), ..LangString::all_false() }); t(LangString { original: \"{.example .rust}\".into(), ..Default::default() }); t(LangString { original: \"{.test_harness .rust}\".into(), test_harness: true, ..LangString::all_false() ..Default::default() }); t(LangString { original: \"text, no_run\".into(), no_run: true, rust: false, ..LangString::all_false() ..Default::default() }); t(LangString { original: \"text,no_run\".into(), no_run: true, rust: false, ..LangString::all_false() ..Default::default() }); t(LangString { original: \"edition2015\".into(), edition: Some(Edition::Edition2015), ..LangString::all_false() ..Default::default() }); t(LangString { original: \"edition2018\".into(), edition: Some(Edition::Edition2018), ..LangString::all_false() ..Default::default() }); }"} {"_id":"doc-en-rust-62f9b04cbc42e1f2b7ae308ef90f99708310e5ae29b08d697d2fb79f5fdbf7b4","title":"","text":"use core::mem::*; #[cfg(panic = \"unwind\")] use std::rc::Rc; #[test]"} {"_id":"doc-en-rust-3c3a5dc1f3eaabefbb0a98c7d952f7db919ba5a263953278138cb95be0625bbd","title":"","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":"doc-en-rust-1513dabedb9e974be6318e498a24446899004d19007638da88429e188a4b078e","title":"","text":"use rustc_ast::NodeId; use rustc_ast::{mut_visit, visit}; use rustc_ast::{Attribute, HasAttrs, HasTokens}; use rustc_errors::PResult; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_expand::config::StripUnconfigured; use rustc_expand::configure;"} {"_id":"doc-en-rust-3ffcb8064ae364a22c86ab0480916f10679f09e1b656a673847d6a85ce2f9c3a","title":"","text":"// the location of `#[cfg]` and `#[cfg_attr]` in the token stream. The tokenization // process is lossless, so this process is invisible to proc-macros. let parse_annotatable_with: fn(&mut Parser<'_>) -> _ = match annotatable { Annotatable::Item(_) => { |parser| Annotatable::Item(parser.parse_item(ForceCollect::Yes).unwrap().unwrap()) } Annotatable::TraitItem(_) => |parser| { Annotatable::TraitItem( parser.parse_trait_item(ForceCollect::Yes).unwrap().unwrap().unwrap(), ) }, Annotatable::ImplItem(_) => |parser| { Annotatable::ImplItem( parser.parse_impl_item(ForceCollect::Yes).unwrap().unwrap().unwrap(), ) }, Annotatable::ForeignItem(_) => |parser| { Annotatable::ForeignItem( parser.parse_foreign_item(ForceCollect::Yes).unwrap().unwrap().unwrap(), ) }, Annotatable::Stmt(_) => |parser| { Annotatable::Stmt(P(parser.parse_stmt(ForceCollect::Yes).unwrap().unwrap())) }, Annotatable::Expr(_) => { |parser| Annotatable::Expr(parser.parse_expr_force_collect().unwrap()) } _ => unreachable!(), }; let parse_annotatable_with: for<'a> fn(&mut Parser<'a>) -> PResult<'a, _> = match annotatable { Annotatable::Item(_) => { |parser| Ok(Annotatable::Item(parser.parse_item(ForceCollect::Yes)?.unwrap())) } Annotatable::TraitItem(_) => |parser| { Ok(Annotatable::TraitItem( parser.parse_trait_item(ForceCollect::Yes)?.unwrap().unwrap(), )) }, Annotatable::ImplItem(_) => |parser| { Ok(Annotatable::ImplItem( parser.parse_impl_item(ForceCollect::Yes)?.unwrap().unwrap(), )) }, Annotatable::ForeignItem(_) => |parser| { Ok(Annotatable::ForeignItem( parser.parse_foreign_item(ForceCollect::Yes)?.unwrap().unwrap(), )) }, Annotatable::Stmt(_) => |parser| { Ok(Annotatable::Stmt(P(parser.parse_stmt(ForceCollect::Yes)?.unwrap()))) }, Annotatable::Expr(_) => { |parser| Ok(Annotatable::Expr(parser.parse_expr_force_collect()?)) } _ => unreachable!(), }; // 'Flatten' all nonterminals (i.e. `TokenKind::Interpolated`) // to `None`-delimited groups containing the corresponding tokens. This"} {"_id":"doc-en-rust-60c8b25dd756d9e032b76c563504bdc84472ac10a0dbfe2858a32f1c97b5101a","title":"","text":"let mut parser = rustc_parse::stream_to_parser(&self.cfg.sess.parse_sess, orig_tokens, None); parser.capture_cfg = true; annotatable = parse_annotatable_with(&mut parser); match parse_annotatable_with(&mut parser) { Ok(a) => annotatable = a, Err(mut err) => { err.emit(); return Some(annotatable); } } // Now that we have our re-parsed `AttrTokenStream`, recursively configuring // our attribute target will correctly the tokens as well."} {"_id":"doc-en-rust-7dfd3b14c74d0563a741a09c5b6be87b18918572975d80af574e3aaf15251b78","title":"","text":"panic!(\"Unexpected last token {:?}\", last_token) } } assert!(stack.is_empty(), \"Stack should be empty: final_buf={:?} stack={:?}\", final_buf, stack); AttrTokenStream::new(final_buf.inner) }"} {"_id":"doc-en-rust-566e4e22d1d35fb73d5f5ddd417568cdb1355389e72c9977815eebbac56bb775","title":"","text":" macro_rules! values { ($($token:ident($value:literal) $(as $inner:ty)? => $attr:meta,)*) => { #[derive(Debug)] pub enum TokenKind { $( #[$attr] $token $($inner)? = $value, )* } }; } //~^^^^^ ERROR expected one of `(`, `,`, `=`, `{`, or `}`, found `(String)` //~| ERROR macro expansion ignores token `(String)` and any following values!(STRING(1) as (String) => cfg(test),); //~^ ERROR expected one of `!` or `::`, found `` fn main() {} "} {"_id":"doc-en-rust-68930e9914061ef89c751700643db4d35463fedc1130584362e6a1c911407ef3","title":"","text":" error: expected one of `(`, `,`, `=`, `{`, or `}`, found `(String)` --> $DIR/syntax-error-recovery.rs:7:26 | LL | $token $($inner)? = $value, | ^^^^^^ expected one of `(`, `,`, `=`, `{`, or `}` ... LL | values!(STRING(1) as (String) => cfg(test),); | -------------------------------------------- in this macro invocation | = note: this error originates in the macro `values` (in Nightly builds, run with -Z macro-backtrace for more info) error: macro expansion ignores token `(String)` and any following --> $DIR/syntax-error-recovery.rs:7:26 | LL | $token $($inner)? = $value, | ^^^^^^ ... LL | values!(STRING(1) as (String) => cfg(test),); | -------------------------------------------- caused by the macro expansion here | = note: the usage of `values!` is likely invalid in item context error: expected one of `!` or `::`, found `` --> $DIR/syntax-error-recovery.rs:15:9 | LL | values!(STRING(1) as (String) => cfg(test),); | ^^^^^^ expected one of `!` or `::` error: aborting due to 3 previous errors "} {"_id":"doc-en-rust-25270aca1f3681ea1605bf0c99c3598420823e4f3f32a1de83ae767833d24b21","title":"","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":"doc-en-rust-9d0d990273742042940e8f23b90abf665ab60b6ba1ba128606540d4e1bbc0770","title":"","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":"doc-en-rust-6b375d7e2dc4fcae96d7559dda8d9fd47be427fdf85016198ea0367f85de3e20","title":"","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":"doc-en-rust-077b0797a955bd8741c7f84bcc61f044b4c6c2a2e13b9b9eebb07a3a24284ac8","title":"","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":"doc-en-rust-e7ac36f4474f8c909549840bc2c12bdee67bc0ad3625456d3dec69799d0119bb","title":"","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":"doc-en-rust-4ad7766e15826a6323f75b1ecd14a73a2199957a1329e89de018511bceba6a73","title":"","text":"// We have a valid span in almost all cases, but we don't have one when linting a crate // name provided via the command line. if !ident.span.is_dummy() { let sc_ident = Ident::from_str_and_span(&sc, ident.span); let (message, suggestion) = if sc_ident.is_reserved() { // We shouldn't suggest a reserved identifier to fix non-snake-case identifiers. // Instead, recommend renaming the identifier entirely or, if permitted, // escaping it to create a raw identifier. if sc_ident.name.can_be_raw() { (\"rename the identifier or convert it to a snake case raw identifier\", sc_ident.to_string()) } else { err.note(&format!(\"`{}` cannot be used as a raw identifier\", sc)); (\"rename the identifier\", String::new()) } } else { (\"convert the identifier to snake case\", sc) }; err.span_suggestion( ident.span, \"convert the identifier to snake case\", sc, message, suggestion, Applicability::MaybeIncorrect, ); } else {"} {"_id":"doc-en-rust-425b140502bb95495f5d2cb3cd4c710b1572231a617a7e224277c15bef657fd7","title":"","text":" #![warn(unused)] #![allow(dead_code)] #![deny(non_snake_case)] mod Impl {} //~^ ERROR module `Impl` should have a snake case name fn While() {} //~^ ERROR function `While` should have a snake case name fn main() { let Mod: usize = 0; //~^ ERROR variable `Mod` should have a snake case name //~^^ WARN unused variable: `Mod` let Super: usize = 0; //~^ ERROR variable `Super` should have a snake case name //~^^ WARN unused variable: `Super` } "} {"_id":"doc-en-rust-ecff5cdc3511f2dcd30a50d6b5284d1348b17351699ed639b62f36c83e32b8c5","title":"","text":" warning: unused variable: `Mod` --> $DIR/lint-non-snake-case-identifiers-suggestion-reserved.rs:12:9 | LL | let Mod: usize = 0; | ^^^ help: if this is intentional, prefix it with an underscore: `_Mod` | note: the lint level is defined here --> $DIR/lint-non-snake-case-identifiers-suggestion-reserved.rs:1:9 | LL | #![warn(unused)] | ^^^^^^ = note: `#[warn(unused_variables)]` implied by `#[warn(unused)]` warning: unused variable: `Super` --> $DIR/lint-non-snake-case-identifiers-suggestion-reserved.rs:16:9 | LL | let Super: usize = 0; | ^^^^^ help: if this is intentional, prefix it with an underscore: `_Super` error: module `Impl` should have a snake case name --> $DIR/lint-non-snake-case-identifiers-suggestion-reserved.rs:5:5 | LL | mod Impl {} | ^^^^ | note: the lint level is defined here --> $DIR/lint-non-snake-case-identifiers-suggestion-reserved.rs:3:9 | LL | #![deny(non_snake_case)] | ^^^^^^^^^^^^^^ help: rename the identifier or convert it to a snake case raw identifier | LL | mod r#impl {} | ^^^^^^ error: function `While` should have a snake case name --> $DIR/lint-non-snake-case-identifiers-suggestion-reserved.rs:8:4 | LL | fn While() {} | ^^^^^ | help: rename the identifier or convert it to a snake case raw identifier | LL | fn r#while() {} | ^^^^^^^ error: variable `Mod` should have a snake case name --> $DIR/lint-non-snake-case-identifiers-suggestion-reserved.rs:12:9 | LL | let Mod: usize = 0; | ^^^ | help: rename the identifier or convert it to a snake case raw identifier | LL | let r#mod: usize = 0; | ^^^^^ error: variable `Super` should have a snake case name --> $DIR/lint-non-snake-case-identifiers-suggestion-reserved.rs:16:9 | LL | let Super: usize = 0; | ^^^^^ help: rename the identifier | = note: `super` cannot be used as a raw identifier error: aborting due to 4 previous errors; 2 warnings emitted "} {"_id":"doc-en-rust-7670219916511f73941008c037e7830c387b008de716247a60aab293bd3fe07f","title":"","text":" // Regression test for #75883. pub struct UI {} impl UI { pub fn run() -> Result<_> { //~^ ERROR: this enum takes 2 type arguments but only 1 type argument was supplied //~| ERROR: the type placeholder `_` is not allowed within types on item signatures let mut ui = UI {}; ui.interact(); unimplemented!(); } pub fn interact(&mut self) -> Result<_> { //~^ ERROR: this enum takes 2 type arguments but only 1 type argument was supplied //~| ERROR: the type placeholder `_` is not allowed within types on item signatures unimplemented!(); } } fn main() {} "} {"_id":"doc-en-rust-ae9a6d93522aaeb1ce9b032139a2910eb730f670f3a079f9afb058b1cac3a57a","title":"","text":" error[E0107]: this enum takes 2 type arguments but only 1 type argument was supplied --> $DIR/issue-75883.rs:6:21 | LL | pub fn run() -> Result<_> { | ^^^^^^ - supplied 1 type argument | | | expected 2 type arguments | note: enum defined here, with 2 type parameters: `T`, `E` --> $SRC_DIR/core/src/result.rs:LL:COL | LL | pub enum Result { | ^^^^^^ - - help: add missing type argument | LL | pub fn run() -> Result<_, E> { | ^^^ error[E0107]: this enum takes 2 type arguments but only 1 type argument was supplied --> $DIR/issue-75883.rs:15:35 | LL | pub fn interact(&mut self) -> Result<_> { | ^^^^^^ - supplied 1 type argument | | | expected 2 type arguments | note: enum defined here, with 2 type parameters: `T`, `E` --> $SRC_DIR/core/src/result.rs:LL:COL | LL | pub enum Result { | ^^^^^^ - - help: add missing type argument | LL | pub fn interact(&mut self) -> Result<_, E> { | ^^^ error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/issue-75883.rs:15:42 | LL | pub fn interact(&mut self) -> Result<_> { | ^ not allowed in type signatures error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/issue-75883.rs:6:28 | LL | pub fn run() -> Result<_> { | ^ not allowed in type signatures error: aborting due to 4 previous errors Some errors have detailed explanations: E0107, E0121. For more information about an error, try `rustc --explain E0107`. "} {"_id":"doc-en-rust-72d7fb1950c62075cf6eee18aca72dbde9df96a08efcec80e2df3b7ba92603dc","title":"","text":" // Regression test for #80779. pub struct T<'a>(&'a str); pub fn f<'a>(val: T<'a>) -> _ { //~^ ERROR: the type placeholder `_` is not allowed within types on item signatures g(val) } pub fn g(_: T<'static>) -> _ {} //~^ ERROR: the type placeholder `_` is not allowed within types on item signatures fn main() {} "} {"_id":"doc-en-rust-f7cff5e1facf72154b8ed4d909d59865656c45379294c22e5404489a95d028db","title":"","text":" error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/issue-80779.rs:10:28 | LL | pub fn g(_: T<'static>) -> _ {} | ^ | | | not allowed in type signatures | help: replace with the correct return type: `()` error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/issue-80779.rs:5:29 | LL | pub fn f<'a>(val: T<'a>) -> _ { | ^ | | | not allowed in type signatures | help: replace with the correct return type: `()` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0121`. "} {"_id":"doc-en-rust-b9dc369945ad74dbf654e5581e3b0375c09b1c0c780fdf7d7ba3d15be8fea6c1","title":"","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":"doc-en-rust-8d2861a8f4d4bb11a3f3c65dbe841c6a05173704c144735d92727866f9094b6b","title":"","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":"doc-en-rust-68f8f9bb35ea606efc594300e9e204348e63d48ad901f424b0d2a1b76be683b9","title":"","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":"doc-en-rust-11dc327423f27924868fed5398e3fce78c85f01a6fe8ad95819d35fa57fc40f8","title":"","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":"doc-en-rust-5175c854044606cfa0fda881cb65908c399bcd3fb34d51c9ceef74ca8c507ddd","title":"","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":"doc-en-rust-97d517284db96bebeca19834b53c5f62df229657d49964953ebf6a281fc3335d","title":"","text":"); } else { // Trivial case: `T` needs an extra bound: `T: Bound`. let (sp, suggestion) = match super_traits { None => predicate_constraint( let (sp, suggestion) = match ( generics .params .iter() .filter( |p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: Some(_), ..}), ) .next(), super_traits, ) { (_, None) => predicate_constraint( generics, trait_ref.without_const().to_predicate(tcx).to_string(), ), Some((ident, bounds)) => match bounds { [.., bound] => ( bound.span().shrink_to_hi(), format!(\" + {}\", trait_ref.print_only_trait_path().to_string()), ), [] => ( ident.span.shrink_to_hi(), format!(\": {}\", trait_ref.print_only_trait_path().to_string()), ), }, (None, Some((ident, []))) => ( ident.span.shrink_to_hi(), format!(\": {}\", trait_ref.print_only_trait_path().to_string()), ), (_, Some((_, [.., bounds]))) => ( bounds.span().shrink_to_hi(), format!(\" + {}\", trait_ref.print_only_trait_path().to_string()), ), (Some(_), Some((_, []))) => ( generics.span.shrink_to_hi(), format!(\": {}\", trait_ref.print_only_trait_path().to_string()), ), }; err.span_suggestion_verbose("} {"_id":"doc-en-rust-b515c02e0c21649634dca1c429cc679eb8b0a21f36445a4430611250cf409122","title":"","text":"//~^ ERROR doesn't implement } pub fn main() { } trait Foo: Sized { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } trait Bar: std::fmt::Display + Sized { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } trait Baz: Sized where Self: std::fmt::Display { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } trait Qux: Sized where Self: std::fmt::Display { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } trait Bat: std::fmt::Display + Sized { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } fn main() { } "} {"_id":"doc-en-rust-35eafdd4fe8a1b7e1706cfc2162a0385368852c9bdaec6f0cc44dbe6013bfead","title":"","text":"//~^ ERROR doesn't implement } pub fn main() { } trait Foo { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } trait Bar: std::fmt::Display { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } trait Baz where Self: std::fmt::Display { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } trait Qux where Self: std::fmt::Display { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } trait Bat: std::fmt::Display { const SIZE: usize = core::mem::size_of::(); //~^ ERROR the size for values of type `Self` cannot be known at compilation time } fn main() { } "} {"_id":"doc-en-rust-8675003435a03df635cef3e05cc60dac199418165d8f0dbdbcedb0177f7520d2","title":"","text":"LL | fn test_many_bounds_where(x: X) where X: Sized, X: Sized, X: Debug { | ^^^^^^^^^^ error: aborting due to 6 previous errors error[E0277]: the size for values of type `Self` cannot be known at compilation time --> $DIR/bound-suggestions.rs:44:46 | LL | const SIZE: usize = core::mem::size_of::(); | ^^^^ doesn't have a size known at compile-time | ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | LL | pub const fn size_of() -> usize { | - required by this bound in `std::mem::size_of` | help: consider further restricting `Self` | LL | trait Foo: Sized { | ^^^^^^^ error[E0277]: the size for values of type `Self` cannot be known at compilation time --> $DIR/bound-suggestions.rs:49:46 | LL | const SIZE: usize = core::mem::size_of::(); | ^^^^ doesn't have a size known at compile-time | ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | LL | pub const fn size_of() -> usize { | - required by this bound in `std::mem::size_of` | help: consider further restricting `Self` | LL | trait Bar: std::fmt::Display + Sized { | ^^^^^^^ error[E0277]: the size for values of type `Self` cannot be known at compilation time --> $DIR/bound-suggestions.rs:54:46 | LL | const SIZE: usize = core::mem::size_of::(); | ^^^^ doesn't have a size known at compile-time | ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | LL | pub const fn size_of() -> usize { | - required by this bound in `std::mem::size_of` | help: consider further restricting `Self` | LL | trait Baz: Sized where Self: std::fmt::Display { | ^^^^^^^ error[E0277]: the size for values of type `Self` cannot be known at compilation time --> $DIR/bound-suggestions.rs:59:46 | LL | const SIZE: usize = core::mem::size_of::(); | ^^^^ doesn't have a size known at compile-time | ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | LL | pub const fn size_of() -> usize { | - required by this bound in `std::mem::size_of` | help: consider further restricting `Self` | LL | trait Qux: Sized where Self: std::fmt::Display { | ^^^^^^^ error[E0277]: the size for values of type `Self` cannot be known at compilation time --> $DIR/bound-suggestions.rs:64:46 | LL | const SIZE: usize = core::mem::size_of::(); | ^^^^ doesn't have a size known at compile-time | ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL | LL | pub const fn size_of() -> usize { | - required by this bound in `std::mem::size_of` | help: consider further restricting `Self` | LL | trait Bat: std::fmt::Display + Sized { | ^^^^^^^ error: aborting due to 11 previous errors For more information about this error, try `rustc --explain E0277`."} {"_id":"doc-en-rust-7d0824eebcaaecc09fce7694c5e543656c144b2aa2d7352d81bc5a7e8e0380c6","title":"","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":"doc-en-rust-1807955f33e289ce51071900b664294b03805e2eb4bddd9d13beca5f7d5f6f69","title":"","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":"doc-en-rust-1678d3b7f120953fd4135246d2c4cc0b6ba980e6ceca37e8948c576dda0ce7cd","title":"","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":"doc-en-rust-922ea34f9e71c5e08bf2a47a307c03a2d8436c75b3c239348e8ecf173251848c","title":"","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":"doc-en-rust-dd2b18505fa76b7eff4dcf0a5fae5fcaa88ff821eb49da5938dc2ac2094f15ce","title":"","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":"doc-en-rust-74c8fc58d60a6f1385f59c19c0b20e5a0239df09cbafd062049f78f3532adcf0","title":"","text":"use crate::{lang_items, LangItem, LanguageItems}; use rustc_ast as ast; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stable_map::StableMap; use rustc_span::symbol::{sym, Symbol}; use std::lazy::SyncLazy;"} {"_id":"doc-en-rust-c6cca1af3ab927e11cb3cd7d998de00161738b5ce0d850bbe8816a4d826628a4","title":"","text":"macro_rules! weak_lang_items { ($($name:ident, $item:ident, $sym:ident;)*) => ( pub static WEAK_ITEMS_REFS: SyncLazy> = SyncLazy::new(|| { let mut map = FxHashMap::default(); pub static WEAK_ITEMS_REFS: SyncLazy> = SyncLazy::new(|| { let mut map = StableMap::default(); $(map.insert(sym::$name, LangItem::$item);)* map });"} {"_id":"doc-en-rust-defc2875b59523ea5d9247dd762f91d92eed3f420ad9f2d1028f85d09f42ea57","title":"","text":"} } for (name, &item) in WEAK_ITEMS_REFS.iter() { for (name, item) in WEAK_ITEMS_REFS.clone().into_sorted_vector().into_iter() { if missing.contains(&item) && required(tcx, item) && items.require(item).is_err() { if item == LangItem::PanicImpl { tcx.sess.err(\"`#[panic_handler]` function required, but not found\");"} {"_id":"doc-en-rust-41dd1e7b43fe8347b738112c7e58948cff18cdec080508fbfb2210f90abf8e63","title":"","text":"} } let args = cap.name(\"args\").map_or(vec![], |m| shlex::split(m.as_str()).unwrap()); let args = cap.name(\"args\").map_or(Some(vec![]), |m| shlex::split(m.as_str())); let args = match args { Some(args) => args, None => { print_err( &format!( \"Invalid arguments to shlex::split: `{}`\", cap.name(\"args\").unwrap().as_str() ), lineno, ); errors = true; continue; } }; if !cmd.validate(&args, commands.len(), lineno) { errors = true;"} {"_id":"doc-en-rust-1b99df13f2b06e34c62378b9dc4b978bf9a5d6fac302a008c3ad8b498d9a4c37","title":"","text":"\"deref-methods-{:#}\", type_.print(cx.cache()) ))); debug!(\"Adding {} to deref id map\", type_.print(cx.cache())); cx.deref_id_map .borrow_mut() .insert(type_.def_id_full(cx.cache()).unwrap(), id.clone());"} {"_id":"doc-en-rust-11f3ec81c74e11e9b0b85d14914807c4634979c8100a9f4045de355a3296a142","title":"","text":"_ => None, }) .expect(\"Expected associated type binding\"); debug!(\"Render deref methods for {:#?}, target {:#?}\", impl_.inner_impl().for_, target); let what = AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut }; if let Some(did) = target.def_id_full(cx.cache()) {"} {"_id":"doc-en-rust-54637efbc661fc1b746e3ab53070c54e9785476a0594fd4a6bc21c03146cdf25","title":"","text":"}) { debug!(\"found target, real_target: {:?} {:?}\", target, real_target); if let Some(did) = target.def_id_full(cx.cache()) { if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) { // `impl Deref for S` if did == type_did { // Avoid infinite cycles return; } } } let deref_mut = v .iter() .filter(|i| i.inner_impl().trait_.is_some())"} {"_id":"doc-en-rust-1d297b3ee1db5c32cebadf6769f41b48f822a4867856158858f43d438f1e7a08","title":"","text":".filter(|i| i.inner_impl().trait_.is_some()) .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_trait_did) { if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) { // `impl Deref for S` if target_did == type_did { // Avoid infinite cycles return; } } sidebar_deref_methods(cx, out, target_deref_impl, target_impls); } }"} {"_id":"doc-en-rust-4cb12c6475d5275b042448d2f2bffb5c83820aaf9693cb601d7b1338237755fe","title":"","text":" // check-pass // #81395: Fix ICE when recursing into Deref target only differing in type args pub struct Generic(T); impl<'a> std::ops::Deref for Generic<&'a mut ()> { type Target = Generic<&'a ()>; fn deref(&self) -> &Self::Target { unimplemented!() } } impl<'a> Generic<&'a ()> { pub fn some_method(&self) {} } "} {"_id":"doc-en-rust-dadc3edaba126d644b4620184b9667b91e44e1c3e677e3d3ac719c8465d9c007","title":"","text":"true } }); return INTERNER.intern_path(sysroot); } // Symlink the source root into the same location inside the sysroot,"} {"_id":"doc-en-rust-f5935d3513e1bd527eae101c79837182a53b4d9fffac75972dc56f3114a4950f","title":"","text":"stable = $stable:expr $(,tool_std = $tool_std:literal)? $(,allow_features = $allow_features:expr)? $(,add_bins_to_sysroot = $add_bins_to_sysroot:expr)? ;)+) => { $( #[derive(Debug, Clone, Hash, PartialEq, Eq)]"} {"_id":"doc-en-rust-88d962c83fabccc135ef60b0802ab386846f3ef3851d31a59399bd68f4d1a310","title":"","text":"#[allow(unused_mut)] fn run(mut $sel, $builder: &Builder<'_>) -> Option { $builder.ensure(ToolBuild { let tool = $builder.ensure(ToolBuild { compiler: $sel.compiler, target: $sel.target, tool: $tool_name,"} {"_id":"doc-en-rust-2fa48049fb7193b06c6b394840396223069a3643a98b23dc47a018e7695280e0","title":"","text":"is_optional_tool: true, source_type: SourceType::InTree, allow_features: concat!($($allow_features)*), }) })?; if (false $(|| !$add_bins_to_sysroot.is_empty())?) && $sel.compiler.stage > 0 { let bindir = $builder.sysroot($sel.compiler).join(\"bin\"); t!(fs::create_dir_all(&bindir)); #[allow(unused_variables)] let tools_out = $builder .cargo_out($sel.compiler, Mode::ToolRustc, $sel.target); $(for add_bin in $add_bins_to_sysroot { let bin_source = tools_out.join(exe(add_bin, $sel.target)); let bin_destination = bindir.join(exe(add_bin, $sel.compiler.host)); $builder.copy(&bin_source, &bin_destination); })? let tool = bindir.join(exe($tool_name, $sel.compiler.host)); Some(tool) } else { Some(tool) } } } )+"} {"_id":"doc-en-rust-229e87d8cc3334dd64a4e58f100229b4e0dc1b03d85e94a481ad37b18f55d176","title":"","text":"tool_extended!((self, builder), Cargofmt, \"src/tools/rustfmt\", \"cargo-fmt\", stable=true; CargoClippy, \"src/tools/clippy\", \"cargo-clippy\", stable=true; Clippy, \"src/tools/clippy\", \"clippy-driver\", stable=true; Miri, \"src/tools/miri\", \"miri\", stable=false; CargoMiri, \"src/tools/miri/cargo-miri\", \"cargo-miri\", stable=true; Clippy, \"src/tools/clippy\", \"clippy-driver\", stable=true, add_bins_to_sysroot = [\"clippy-driver\", \"cargo-clippy\"]; Miri, \"src/tools/miri\", \"miri\", stable=false, add_bins_to_sysroot = [\"miri\"]; CargoMiri, \"src/tools/miri/cargo-miri\", \"cargo-miri\", stable=true, add_bins_to_sysroot = [\"cargo-miri\"]; // FIXME: tool_std is not quite right, we shouldn't allow nightly features. // But `builder.cargo` doesn't know how to handle ToolBootstrap in stages other than 0, // and this is close enough for now. Rls, \"src/tools/rls\", \"rls\", stable=true, tool_std=true; RustDemangler, \"src/tools/rust-demangler\", \"rust-demangler\", stable=false, tool_std=true; Rustfmt, \"src/tools/rustfmt\", \"rustfmt\", stable=true; Rustfmt, \"src/tools/rustfmt\", \"rustfmt\", stable=true, add_bins_to_sysroot = [\"rustfmt\", \"cargo-fmt\"]; ); impl<'a> Builder<'a> {"} {"_id":"doc-en-rust-514b7bd853aeacb35a3cb39f9f88144c84d8b49d655c22406d23bddffba9b274","title":"","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":"doc-en-rust-cbe82ed3cd04465455478cb6bbf40f29aeb6bdf238c104f5918b9d053e2cd787","title":"","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":"doc-en-rust-2ae604c63c18fde744b8574f8af047341e8f65c5b567d47c1250bca7b29985f9","title":"","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":"doc-en-rust-1214122dfbf0135bb51d66c7be70fd4c19f7c5798b4a2ad446e386619064d55c","title":"","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":"doc-en-rust-b435f7489b79a1269badc7cf7bddb4a710b3cef2fac2f4a03f3efc4b09d67171","title":"","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":"doc-en-rust-3836b761969c9e3e67b64d7c7bfbb953573b3e785b1094fa214b490b2d4ae282","title":"","text":"source shared.sh LLVM=llvmorg-11.0.1 LLVM=llvmorg-10.0.0 mkdir llvm-project cd llvm-project"} {"_id":"doc-en-rust-8cf298058a790aace42076ee75f34a613f786aabcfa289523f580e479f6f73f4","title":"","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":"doc-en-rust-64ccc67aaa0894ded25afe823441f253f34c49c8e214ed272bc35d3aa241638f","title":"","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":"doc-en-rust-23e7e8cfc748b2060ca2fff45c2a187f51341c003435391c3ea1020dca783923","title":"","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":"doc-en-rust-0d743d604271c8b2cc423b787123d0da9d0ed63c6ab9d23a202629054dc4136b","title":"","text":"LookupResult::Parent(Some(parent)) => { let (_maybe_live, maybe_dead) = self.init_data.maybe_live_dead(parent); if maybe_dead { span_bug!( self.tcx.sess.delay_span_bug( terminator.source_info.span, \"drop of untracked, uninitialized value {:?}, place {:?} ({:?})\", bb, place, path &format!( \"drop of untracked, uninitialized value {:?}, place {:?} ({:?})\", bb, place, path, ), ); } continue;"} {"_id":"doc-en-rust-e484b8b7ee294f730749b89faa6cec93a419a7654c96b8c0376c6b128c2a1653","title":"","text":"bb, ), LookupResult::Parent(..) => { span_bug!( self.tcx.sess.delay_span_bug( terminator.source_info.span, \"drop of untracked value {:?}\", bb &format!(\"drop of untracked value {:?}\", bb), ); } }"} {"_id":"doc-en-rust-e482e78d311c880e8fb300a3568a587857a133f261674a972385c22f6cee4442","title":"","text":" // Regression test for issue 81708 and issue 91816 where running a drop // elaboration on a MIR which failed borrowck lead to an ICE. static A: () = { let a: [String; 1]; //~^ ERROR destructors cannot be evaluated at compile-time a[0] = String::new(); //~^ ERROR destructors cannot be evaluated at compile-time //~| ERROR use of possibly-uninitialized variable }; struct B([T; 1]); impl B { pub const fn f(mut self, other: T) -> Self { let _this = self; //~^ ERROR destructors cannot be evaluated at compile-time self.0[0] = other; //~^ ERROR destructors cannot be evaluated at compile-time //~| ERROR use of moved value self } } fn main() {} "} {"_id":"doc-en-rust-2af707355d3a03ae8252cc97060b1abb7db7695d08712a1522a96f9627ad8c28","title":"","text":" error[E0493]: destructors cannot be evaluated at compile-time --> $DIR/drop-elaboration-after-borrowck-error.rs:7:5 | LL | a[0] = String::new(); | ^^^^ | | | statics cannot evaluate destructors | value is dropped here error[E0493]: destructors cannot be evaluated at compile-time --> $DIR/drop-elaboration-after-borrowck-error.rs:5:9 | LL | let a: [String; 1]; | ^ statics cannot evaluate destructors ... LL | }; | - value is dropped here error[E0381]: use of possibly-uninitialized variable: `a` --> $DIR/drop-elaboration-after-borrowck-error.rs:7:5 | LL | a[0] = String::new(); | ^^^^ use of possibly-uninitialized `a` error[E0493]: destructors cannot be evaluated at compile-time --> $DIR/drop-elaboration-after-borrowck-error.rs:18:9 | LL | self.0[0] = other; | ^^^^^^^^^ | | | constant functions cannot evaluate destructors | value is dropped here error[E0493]: destructors cannot be evaluated at compile-time --> $DIR/drop-elaboration-after-borrowck-error.rs:16:13 | LL | let _this = self; | ^^^^^ constant functions cannot evaluate destructors ... LL | } | - value is dropped here error[E0382]: use of moved value: `self.0` --> $DIR/drop-elaboration-after-borrowck-error.rs:18:9 | LL | pub const fn f(mut self, other: T) -> Self { | -------- move occurs because `self` has type `B`, which does not implement the `Copy` trait LL | let _this = self; | ---- value moved here LL | LL | self.0[0] = other; | ^^^^^^^^^ value used here after move error: aborting due to 6 previous errors Some errors have detailed explanations: E0381, E0382, E0493. For more information about an error, try `rustc --explain E0381`. "} {"_id":"doc-en-rust-8ded6725d0148181fff566b715e723f593b66b40f95e17d303312abba909d697","title":"","text":" // Regression test for #81712. #![feature(generic_associated_types)] #![allow(incomplete_features)] trait A { type BType: B; } trait B { type AType: A; } trait C { type DType: D; //~^ ERROR: missing generics for associated type `C::DType` [E0107] } trait D { type CType: C; } fn main() {} "} {"_id":"doc-en-rust-857e3302012176774b2bda8d91776b8d87221baf689637eb13afb92879f2777a","title":"","text":" error[E0107]: missing generics for associated type `C::DType` --> $DIR/issue-81712-cyclic-traits.rs:14:10 | LL | type DType: D; | ^^^^^ expected 1 type argument | note: associated type defined here, with 1 type parameter: `T` --> $DIR/issue-81712-cyclic-traits.rs:14:10 | LL | type DType: D; | ^^^^^ - help: use angle brackets to add missing type argument | LL | type DType: D; | ^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0107`. "} {"_id":"doc-en-rust-f6c4ed66b1106e4472f90dbf4ee6a192e63383c3a1b613c40753339ce7965416","title":"","text":" // error-pattern: this file contains an unclosed delimiter // error-pattern: mismatched closing delimiter: `]` // error-pattern: expected one of `)` or `,`, found `{` #![crate_name=\"0\"] fn main() {} fn r()->i{0|{#[cfg(r(0{]0 "} {"_id":"doc-en-rust-f4158c7d8e77291b88d06b3c8863756aa81987645a993beb81609079b87313d0","title":"","text":" error: this file contains an unclosed delimiter --> $DIR/issue-81827.rs:11:27 | LL | fn r()->i{0|{#[cfg(r(0{]0 | - - ^ | | | | | unclosed delimiter | unclosed delimiter error: this file contains an unclosed delimiter --> $DIR/issue-81827.rs:11:27 | LL | fn r()->i{0|{#[cfg(r(0{]0 | - - ^ | | | | | unclosed delimiter | unclosed delimiter error: mismatched closing delimiter: `]` --> $DIR/issue-81827.rs:11:23 | LL | fn r()->i{0|{#[cfg(r(0{]0 | - ^^ mismatched closing delimiter | | | | | unclosed delimiter | closing delimiter possibly meant for this error: expected one of `)` or `,`, found `{` --> $DIR/issue-81827.rs:11:23 | LL | fn r()->i{0|{#[cfg(r(0{]0 | ^ expected one of `)` or `,` error: aborting due to 4 previous errors "} {"_id":"doc-en-rust-b5523d17a76477ba49a39f63eb2f1e9d43f3ae52e1dcfe2ae4225e7d9ce6a467","title":"","text":"}; let last_expr_ty = self.node_ty(last_expr.hir_id); let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) { (ty::Opaque(last_def_id, _), ty::Opaque(exp_def_id, _)) if last_def_id == exp_def_id => { StatementAsExpression::CorrectType } (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => { debug!( \"both opaque, likely future {:?} {:?} {:?} {:?}\", last_def_id, last_bounds, exp_def_id, exp_bounds ); let last_hir_id = self.tcx.hir().local_def_id_to_hir_id(last_def_id.expect_local()); let exp_hir_id = self.tcx.hir().local_def_id_to_hir_id(exp_def_id.expect_local()); let (last_local_id, exp_local_id) = match (last_def_id.as_local(), exp_def_id.as_local()) { (Some(last_hir_id), Some(exp_hir_id)) => (last_hir_id, exp_hir_id), (_, _) => return None, }; let last_hir_id = self.tcx.hir().local_def_id_to_hir_id(last_local_id); let exp_hir_id = self.tcx.hir().local_def_id_to_hir_id(exp_local_id); match ( &self.tcx.hir().expect_item(last_hir_id).kind, &self.tcx.hir().expect_item(exp_hir_id).kind,"} {"_id":"doc-en-rust-54c49a8cbb045b55c804cf0cdeccf5e938beaf9468dc364be3a5493237a7ec38","title":"","text":" // edition:2018 pub struct Test {} impl Test { pub async fn answer_str(&self, _s: &str) -> Test { Test {} } } "} {"_id":"doc-en-rust-9e9c29244c154a6fbe6c2fa01042da652ceae845beb0ff0ed7b65d5e341f4c50","title":"","text":" // aux-build:issue-81839.rs // edition:2018 extern crate issue_81839; async fn test(ans: &str, num: i32, cx: &issue_81839::Test) -> u32 { match num { 1 => { cx.answer_str(\"hi\"); } _ => cx.answer_str(\"hi\"), //~ `match` arms have incompatible types } 1 } fn main() {} "} {"_id":"doc-en-rust-f20b28cf5f3992636453638e2e0d858227423b2e06f92a5712d215e1be03eb41","title":"","text":" error[E0308]: `match` arms have incompatible types --> $DIR/issue-81839.rs:11:14 | LL | / match num { LL | | 1 => { LL | | cx.answer_str(\"hi\"); | | -------------------- | | | | | | | help: consider removing this semicolon | | this is found to be of type `()` LL | | } LL | | _ => cx.answer_str(\"hi\"), | | ^^^^^^^^^^^^^^^^^^^ expected `()`, found opaque type LL | | } | |_____- `match` arms have incompatible types | ::: $DIR/auxiliary/issue-81839.rs:6:49 | LL | pub async fn answer_str(&self, _s: &str) -> Test { | ---- the `Output` of this `async fn`'s found opaque type | = note: expected type `()` found opaque type `impl Future` error: aborting due to previous error For more information about this error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-1606e48f3bd1e8619a9acd2a1b6a9d7dc0e1ec14a6def391b21ab38247ba70b1","title":"","text":"| LL | false => async_dummy().await, | ^^^^^^ help: consider removing this semicolon and boxing the expressions | LL | Box::new(async_dummy()) LL | LL | } LL | false => Box::new(async_dummy()), help: consider removing this semicolon | LL | async_dummy() | -- error[E0308]: `match` arms have incompatible types --> $DIR/match-prev-arm-needing-semi.rs:39:18"} {"_id":"doc-en-rust-0c69e660af50102d233fd2d5a8aba1f99ef3893440f57fbaa80a69b481851a66","title":"","text":"struct_span_err!(tcx.sess, span, E0733, \"recursion in an `async fn` requires boxing\") .span_label(span, \"recursive `async fn`\") .note(\"a recursive `async fn` must be rewritten to return a boxed `dyn Future`\") .note( \"consider using the `async_recursion` crate: https://crates.io/crates/async_recursion\", ) .emit(); }"} {"_id":"doc-en-rust-0d2f8f700715bd06f59d2e498ef126cfecc20a1b4342be00fcaaee349667125f","title":"","text":"| ^ recursive `async fn` | = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion error[E0733]: recursion in an `async fn` requires boxing --> $DIR/mutually-recursive-async-impl-trait-type.rs:9:18"} {"_id":"doc-en-rust-9e63504d6c47f4bd211b71383a220005bfe1c00b3e64d06f0c9f1ddbf69457c9","title":"","text":"| ^ recursive `async fn` | = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion error: aborting due to 2 previous errors"} {"_id":"doc-en-rust-2fcceb5447f6b6b469eda22d0b83594b28d96cab9c645fd2d5fdae7c1cabd2ad","title":"","text":"| ^^ recursive `async fn` | = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future` = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion error: aborting due to previous error"} {"_id":"doc-en-rust-adff4a978196666cc4e8dfdc46f9eec1c6f577f5a5920158a6f88d7f7c435c3e","title":"","text":"} impl Attribute { #[inline] pub fn has_name(&self, name: Symbol) -> bool { match self.kind { AttrKind::Normal(ref item, _) => item.path == name,"} {"_id":"doc-en-rust-5e81c75718f40a733f3cde27c32c51a7588108a36c9e79ddd8b4d94d83e365d3","title":"","text":"use rustc_middle::ty::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_ast::{Attribute, LitKind, NestedMetaItem}; use rustc_ast::{Attribute, Lit, LitKind, NestedMetaItem}; use rustc_errors::{pluralize, struct_span_err}; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId;"} {"_id":"doc-en-rust-2c9b7e731b7fd070882cc9cee8f6a4f8ca96a89f479edcdb5a4e7f1ffe6229b6","title":"","text":"self.check_export_name(hir_id, &attr, span, target) } else if self.tcx.sess.check_name(attr, sym::rustc_args_required_const) { self.check_rustc_args_required_const(&attr, span, target, item) } else if self.tcx.sess.check_name(attr, sym::rustc_layout_scalar_valid_range_start) { self.check_rustc_layout_scalar_valid_range(&attr, span, target) } else if self.tcx.sess.check_name(attr, sym::rustc_layout_scalar_valid_range_end) { self.check_rustc_layout_scalar_valid_range(&attr, span, target) } else if self.tcx.sess.check_name(attr, sym::allow_internal_unstable) { self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs) } else if self.tcx.sess.check_name(attr, sym::rustc_allow_const_fn_unstable) {"} {"_id":"doc-en-rust-7d269aec264b68c4821978f5192430f464692b54eeb297e5545d8913ddb07c38","title":"","text":"} } fn check_rustc_layout_scalar_valid_range( &self, attr: &Attribute, span: &Span, target: Target, ) -> bool { if target != Target::Struct { self.tcx .sess .struct_span_err(attr.span, \"attribute should be applied to a struct\") .span_label(*span, \"not a struct\") .emit(); return false; } let list = match attr.meta_item_list() { None => return false, Some(it) => it, }; if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) { true } else { self.tcx .sess .struct_span_err(attr.span, \"expected exactly one integer literal argument\") .emit(); false } } /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument. fn check_rustc_legacy_const_generics( &self,"} {"_id":"doc-en-rust-4d3a9b065ab2c1e56c71e060826c8a544b66708350201e41bc62fdbb7aec16e6","title":"","text":" #![feature(rustc_attrs)] #[rustc_layout_scalar_valid_range_start(u32::MAX)] //~ ERROR pub struct A(u32); #[rustc_layout_scalar_valid_range_end(1, 2)] //~ ERROR pub struct B(u8); #[rustc_layout_scalar_valid_range_end(a = \"a\")] //~ ERROR pub struct C(i32); #[rustc_layout_scalar_valid_range_end(1)] //~ ERROR enum E { X = 1, Y = 14, } fn main() { let _ = A(0); let _ = B(0); let _ = C(0); let _ = E::X; } "} {"_id":"doc-en-rust-49d2057271117b8937cac199ef2a497c0532ec8c4ffcc5613805330fa1db1e00","title":"","text":" error: expected exactly one integer literal argument --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:3:1 | LL | #[rustc_layout_scalar_valid_range_start(u32::MAX)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: expected exactly one integer literal argument --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:6:1 | LL | #[rustc_layout_scalar_valid_range_end(1, 2)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: expected exactly one integer literal argument --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:9:1 | LL | #[rustc_layout_scalar_valid_range_end(a = \"a\")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: attribute should be applied to a struct --> $DIR/invalid_rustc_layout_scalar_valid_range.rs:12:1 | LL | #[rustc_layout_scalar_valid_range_end(1)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | / enum E { LL | | X = 1, LL | | Y = 14, LL | | } | |_- not a struct error: aborting due to 4 previous errors "} {"_id":"doc-en-rust-aeb18219a96ac9199eb7c49527670516788cf7d286a7bbdd340ce719ca5618db","title":"","text":"pub struct Zip { a: A, b: B, // index and len are only used by the specialized version of zip // index, len and a_len are only used by the specialized version of zip index: usize, len: usize, a_len: usize, } impl Zip { pub(in crate::iter) fn new(a: A, b: B) -> Zip {"} {"_id":"doc-en-rust-a6899b34f310834c2ab7c29a421ce77e0e53837f059afdf8a41aea6ce2de669d","title":"","text":"b, index: 0, // unused len: 0, // unused a_len: 0, // unused } }"} {"_id":"doc-en-rust-f2652fa7950fef8e30724a38c7a73ef01b52f9f5639dd7b6da0fc9376e6580e5","title":"","text":"B: TrustedRandomAccess + Iterator, { fn new(a: A, b: B) -> Self { let len = cmp::min(a.size(), b.size()); Zip { a, b, index: 0, len } let a_len = a.size(); let len = cmp::min(a_len, b.size()); Zip { a, b, index: 0, len, a_len } } #[inline]"} {"_id":"doc-en-rust-b1b095e85bf1b3308a31f36d6f7ced4c1a54ecc7462fa110dc0cb6652f293963","title":"","text":"unsafe { Some((self.a.__iterator_get_unchecked(i), self.b.__iterator_get_unchecked(i))) } } else if A::MAY_HAVE_SIDE_EFFECT && self.index < self.a.size() { } else if A::MAY_HAVE_SIDE_EFFECT && self.index < self.a_len { let i = self.index; self.index += 1; self.len += 1;"} {"_id":"doc-en-rust-c80a418dca4d4cb616eddde43bfd21083a294e87f6d146ba8931f6ede4d1a319","title":"","text":"for _ in 0..sz_a - self.len { self.a.next_back(); } self.a_len = self.len; } let sz_b = self.b.size(); if B::MAY_HAVE_SIDE_EFFECT && sz_b > self.len {"} {"_id":"doc-en-rust-2cc08db4569cda8563bfae0123e3188452cc62dd2d54b4ab30ced48bc50242db","title":"","text":"} if self.index < self.len { self.len -= 1; self.a_len -= 1; let i = self.len; // SAFETY: `i` is smaller than the previous value of `self.len`, // which is also smaller than or equal to `self.a.len()` and `self.b.len()`"} {"_id":"doc-en-rust-ee201511a951614f9242d8816dc76a015d84d12f7d9ea8c4aa768a1f269b84a8","title":"","text":"panic!(); } } #[test] fn test_issue_82291() { use std::cell::Cell; let mut v1 = [()]; let v2 = [()]; let called = Cell::new(0); let mut zip = v1 .iter_mut() .map(|r| { called.set(called.get() + 1); r }) .zip(&v2); zip.next_back(); assert_eq!(called.get(), 1); zip.next(); assert_eq!(called.get(), 1); } "} {"_id":"doc-en-rust-0f0f819b852595a28e7121953324f88c1ddfa430fc10d4e7e656f605108789ce","title":"","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":"doc-en-rust-808c2643d085a37e09f91ff9825e8fea956b1a1bb7d1a6f35c44813e7555fa8e","title":"","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":"doc-en-rust-9e5a15545918bb86695b44edf3c577c5ace0b547a05a3dd1baac9c1c4004e102","title":"","text":"format!(\"*{}\", code) }; return Some(( sp, expr.span, message, suggestion, Applicability::MachineApplicable,"} {"_id":"doc-en-rust-b5ef5fa830822948ff108f0fddf2c7cd1728e80c207d9f596d6c5ed0e53f74ec","title":"","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":"doc-en-rust-09c1ab9c6ddef57f859143b85e7eb84f7385e129ae9675b2e7906f44fcdb64ad","title":"","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":"doc-en-rust-294ff737ec17d919ceaa62c9b9d625e7762402b77db3ade4f5160f7e1422766a","title":"","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":"doc-en-rust-1132e6637b2e6cf7be0e65b4c825fc1b92a403b71e1307d0177cd7c711b17718","title":"","text":"name = \"compiletest\" version = \"0.0.0\" dependencies = [ \"colored\", \"diff\", \"getopts\", \"glob\","} {"_id":"doc-en-rust-03c177b1a7110de5ad2b4503d4053072ab7d56487ef2088e520e2539c5066ceb","title":"","text":"\"serde_json\", \"tracing\", \"tracing-subscriber\", \"unified-diff\", \"walkdir\", \"winapi 0.3.9\", ]"} {"_id":"doc-en-rust-332fb501e5440732b71aade605dae8409fef12788a31f0e1a1bc2d1c025b6093","title":"","text":"checksum = \"39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e\" [[package]] name = \"unified-diff\" version = \"0.2.1\" source = \"registry+https://github.com/rust-lang/crates.io-index\" checksum = \"496a3d395ed0c30f411ceace4a91f7d93b148fb5a9b383d5d4cff7850f048d5f\" dependencies = [ \"diff\", ] [[package]] name = \"unstable-book-gen\" version = \"0.1.0\" dependencies = ["} {"_id":"doc-en-rust-922bef6fb379f916ea22d134177215852e9b0d2e6193354f32c948f791c12184","title":"","text":"edition = \"2018\" [dependencies] colored = \"2\" diff = \"0.1.10\" unified-diff = \"0.2.1\" getopts = \"0.2\" tracing = \"0.1\" tracing-subscriber = { version = \"0.2.13\", default-features = false, features = [\"fmt\", \"env-filter\", \"smallvec\", \"parking_lot\", \"ansi\"] }"} {"_id":"doc-en-rust-7cb8db1c14dfcea25a73b796dbd3af7f1bd9fedfcfea4e69d1beb30aa9c49bf0","title":"","text":"use crate::json; use crate::util::get_pointer_width; use crate::util::{logv, PathBufExt}; use crate::ColorConfig; use regex::{Captures, Regex}; use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};"} {"_id":"doc-en-rust-54a6a9d38ed0c7e52573676a7a800229097eaa5c867d8ac9f9beaf3df338390d","title":"","text":"} }) }; let mut diff = Command::new(\"diff\"); // diff recursively, showing context, and excluding .css files diff.args(&[\"-u\", \"-r\", \"-x\", \"*.css\"]).args(&[&compare_dir, out_dir]); let output = if let Some(pager) = pager { let diff_pid = diff.stdout(Stdio::piped()).spawn().expect(\"failed to run `diff`\"); let diff_filename = format!(\"build/tmp/rustdoc-compare-{}.diff\", std::process::id()); { let mut diff_output = File::create(&diff_filename).unwrap(); for entry in walkdir::WalkDir::new(out_dir) { let entry = entry.expect(\"failed to read file\"); let extension = entry.path().extension().and_then(|p| p.to_str()); if entry.file_type().is_file() && (extension == Some(\"html\".into()) || extension == Some(\"js\".into())) { let expected_path = compare_dir.join(entry.path().strip_prefix(&out_dir).unwrap()); let expected = if let Ok(s) = std::fs::read(&expected_path) { s } else { continue }; let actual_path = entry.path(); let actual = std::fs::read(&actual_path).unwrap(); diff_output .write_all(&unified_diff::diff( &expected, &expected_path.to_string_lossy(), &actual, &actual_path.to_string_lossy(), 3, )) .unwrap(); } } } match self.config.color { ColorConfig::AlwaysColor => colored::control::set_override(true), ColorConfig::NeverColor => colored::control::set_override(false), _ => {} } if let Some(pager) = pager { let pager = pager.trim(); if self.config.verbose { eprintln!(\"using pager {}\", pager);"} {"_id":"doc-en-rust-204c4a568b430bae03d063805e040e33b5d95bd8b6ef0fac7946d0e2b9186daf","title":"","text":"let output = Command::new(pager) // disable paging; we want this to be non-interactive .env(\"PAGER\", \"\") .stdin(diff_pid.stdout.unwrap()) .stdin(File::open(&diff_filename).unwrap()) // Capture output and print it explicitly so it will in turn be // captured by libtest. .output() .unwrap(); assert!(output.status.success()); output println!(\"{}\", String::from_utf8_lossy(&output.stdout)); eprintln!(\"{}\", String::from_utf8_lossy(&output.stderr)); } else { eprintln!(\"warning: no pager configured, falling back to `diff --color`\"); use colored::Colorize; eprintln!(\"warning: no pager configured, falling back to unified diff\"); eprintln!( \"help: try configuring a git pager (e.g. `delta`) with `git config --global core.pager delta`\" ); let output = diff.arg(\"--color\").output().unwrap(); assert!(output.status.success() || output.status.code() == Some(1)); output let mut out = io::stdout(); let mut diff = BufReader::new(File::open(&diff_filename).unwrap()); let mut line = Vec::new(); loop { line.truncate(0); match diff.read_until(b'n', &mut line) { Ok(0) => break, Ok(_) => {} Err(e) => eprintln!(\"ERROR: {:?}\", e), } match String::from_utf8(line.clone()) { Ok(line) => { if line.starts_with(\"+\") { write!(&mut out, \"{}\", line.green()).unwrap(); } else if line.starts_with(\"-\") { write!(&mut out, \"{}\", line.red()).unwrap(); } else if line.starts_with(\"@\") { write!(&mut out, \"{}\", line.blue()).unwrap(); } else { out.write_all(line.as_bytes()).unwrap(); } } Err(_) => { write!(&mut out, \"{}\", String::from_utf8_lossy(&line).reversed()).unwrap(); } } } }; println!(\"{}\", String::from_utf8_lossy(&output.stdout)); eprintln!(\"{}\", String::from_utf8_lossy(&output.stderr)); } fn run_rustdoc_json_test(&self) {"} {"_id":"doc-en-rust-7837b19aaefbfc3d7906f71ae396c3e756784e29af565f30ca4cad769a7d69a8","title":"","text":"let id = id.expect_local(); let tables = tcx.typeck(id); let hir_id = tcx.hir().local_def_id_to_hir_id(id); let (span, place) = &tables.closure_kind_origins()[hir_id]; let reason = if let PlaceBase::Upvar(upvar_id) = place.base { let upvar = ty::place_to_string_for_capture(tcx, place); match tables.upvar_capture(upvar_id) { ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind: ty::BorrowKind::MutBorrow | ty::BorrowKind::UniqueImmBorrow, .. }) => { format!(\"mutable borrow of `{}`\", upvar) } ty::UpvarCapture::ByValue(_) => { format!(\"possible mutation of `{}`\", upvar) if let Some((span, place)) = tables.closure_kind_origins().get(hir_id) { let reason = if let PlaceBase::Upvar(upvar_id) = place.base { let upvar = ty::place_to_string_for_capture(tcx, place); match tables.upvar_capture(upvar_id) { ty::UpvarCapture::ByRef(ty::UpvarBorrow { kind: ty::BorrowKind::MutBorrow | ty::BorrowKind::UniqueImmBorrow, .. }) => { format!(\"mutable borrow of `{}`\", upvar) } ty::UpvarCapture::ByValue(_) => { format!(\"possible mutation of `{}`\", upvar) } val => bug!(\"upvar `{}` borrowed, but not mutably: {:?}\", upvar, val), } val => bug!(\"upvar `{}` borrowed, but not mutably: {:?}\", upvar, val), } } else { bug!(\"not an upvar\") }; err.span_label( *span, format!( \"calling `{}` requires mutable binding due to {}\", self.describe_place(the_place_err).unwrap(), reason ), ); } else { bug!(\"not an upvar\") }; err.span_label( *span, format!( \"calling `{}` requires mutable binding due to {}\", self.describe_place(the_place_err).unwrap(), reason ), ); } } // Attempt to search similar mutable associated items for suggestion."} {"_id":"doc-en-rust-4468908976ca26d6c3b4f8defc6980b01923b1f22c323f7da63a1522bf2233bc","title":"","text":" use std::error::Error; struct A { } impl A { pub fn new() -> A { A { } } pub fn f<'a>( &'a self, team_name: &'a str, c: &'a mut dyn FnMut(String, String, u64, u64) ) -> Result<(), Box> { Ok(()) } } fn main() { let A = A::new(); let participant_name = \"A\"; let c = |a, b, c, d| {}; A.f(participant_name, &mut c); //~ ERROR cannot borrow } "} {"_id":"doc-en-rust-10d2208dc165b2ca3123b157412ed13ccb8d07d097637e8ab10c37311740dc7f","title":"","text":" error[E0596]: cannot borrow `c` as mutable, as it is not declared as mutable --> $DIR/issue-82438-mut-without-upvar.rs:27:27 | LL | let c = |a, b, c, d| {}; | - help: consider changing this to be mutable: `mut c` LL | LL | A.f(participant_name, &mut c); | ^^^^^^ cannot borrow as mutable error: aborting due to previous error For more information about this error, try `rustc --explain E0596`. "} {"_id":"doc-en-rust-5c90f9ab6c2137176730f70cfc59c4e44d9f252532e422708cb4a9b9f7f5fc12","title":"","text":"span: Span, ) -> &'tcx Const<'tcx> { bad_placeholder_type(self.tcx(), vec![span]).emit(); // Typeck doesn't expect erased regions to be returned from `type_of`. let ty = self.tcx.fold_regions(ty, &mut false, |r, _| match r { ty::ReErased => self.tcx.lifetimes.re_static, _ => r, }); self.tcx().const_error(ty) }"} {"_id":"doc-en-rust-b6b1229d15c4b9f8b449895f815eac38d527a5f178bcea7a625e903c5d56370a","title":"","text":"match get_infer_ret_ty(&sig.decl.output) { Some(ty) => { let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id]; // Typeck doesn't expect erased regions to be returned from `type_of`. let fn_sig = tcx.fold_regions(fn_sig, &mut false, |r, _| match r { ty::ReErased => tcx.lifetimes.re_static, _ => r, }); let mut visitor = PlaceholderHirTyCollector::default(); visitor.visit_ty(ty); let mut diag = bad_placeholder_type(tcx, visitor.0);"} {"_id":"doc-en-rust-7ca8ed148a7e795df77822e284675465bfc40e031237c9980a2dcf603b653d54","title":"","text":"} } diag.emit(); ty::Binder::bind(fn_sig) } None => AstConv::ty_of_fn("} {"_id":"doc-en-rust-a1e9a1db43d9382ff4fc50a1568d9a37dffbf0732bb36b356096051c3d4fbe8c","title":"","text":"const D: _ = 42; //~^ ERROR the type placeholder `_` is not allowed within types on item signatures } fn map(_: fn() -> Option<&'static T>) -> Option { None } fn value() -> Option<&'static _> { //~^ ERROR the type placeholder `_` is not allowed within types on item signatures Option::<&'static u8>::None } const _: Option<_> = map(value); //~^ ERROR the type placeholder `_` is not allowed within types on item signatures "} {"_id":"doc-en-rust-4ee0a451dc854d690deceda93ea45b592133aae3e41bc4bda857ee6d80f11d76","title":"","text":"| -^ | || | |not allowed in type signatures | help: replace with the correct return type: `&&usize` | help: replace with the correct return type: `&'static &'static usize` error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/typeck_type_placeholder_item.rs:52:52"} {"_id":"doc-en-rust-9dbd54a62b17bae19b1003795cedc28e8d173dc34ee280786d1ca968331ac0ad","title":"","text":"| ^ not allowed in type signatures error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/typeck_type_placeholder_item.rs:216:31 | LL | fn value() -> Option<&'static _> { | ----------------^- | | | | | not allowed in type signatures | help: replace with the correct return type: `Option<&'static u8>` error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/typeck_type_placeholder_item.rs:221:10 | LL | const _: Option<_> = map(value); | ^^^^^^^^^ | | | not allowed in type signatures | help: replace `_` with the correct type: `Option` error[E0121]: the type placeholder `_` is not allowed within types on item signatures --> $DIR/typeck_type_placeholder_item.rs:140:31 | LL | fn method_test1(&self, x: _);"} {"_id":"doc-en-rust-3cedc125fa7a0abcac1d5a4b7f13384b6d3e58d7b08f0b6f987deda3a717eeee","title":"","text":"| not allowed in type signatures | help: replace `_` with the correct type: `i32` error: aborting due to 67 previous errors error: aborting due to 69 previous errors Some errors have detailed explanations: E0121, E0282, E0403. For more information about an error, try `rustc --explain E0121`."} {"_id":"doc-en-rust-528edd14836f3483ba1b9d37309ea09e152c6682efa7c748bab1cde5ad8537a1","title":"","text":"/// destination value, then forgets the original. It's equivalent to C's /// `memcpy` under the hood, just like `transmute_copy`. /// /// Because `transmute` is a by-value operation, alignment of the *transmuted values /// themselves* is not a concern. As with any other function, the compiler already ensures /// both `T` and `U` are properly aligned. However, when transmuting values that *point /// elsewhere* (such as pointers, references, boxes…), the caller has to ensure proper /// alignment of the pointed-to values. /// /// `transmute` is **incredibly** unsafe. There are a vast number of ways to /// cause [undefined behavior][ub] with this function. `transmute` should be /// the absolute last resort."} {"_id":"doc-en-rust-44e0276aea8f68ccba5b811437ac271693cbe43653269d3359555d4267cf0594","title":"","text":"/// assert_eq!(b\"Rust\", &[82, 117, 115, 116]); /// ``` /// /// Turning a `Vec<&T>` into a `Vec>`: /// Turning a `Vec<&T>` into a `Vec>`. /// /// To transmute the inner type of the contents of a container, you must make sure to not /// violate any of the container's invariants. For `Vec`, this means that both the size /// *and alignment* of the inner types have to match. Other containers might rely on the /// size of the type, alignment, or even the `TypeId`, in which case transmuting wouldn't /// be possible at all without violating the container invariants. /// /// ``` /// let store = [0, 1, 2, 3];"} {"_id":"doc-en-rust-041290613e814235f7921bd7691cfe96542767b772cab657754294b15b0bd6ff","title":"","text":"/// /// let v_clone = v_orig.clone(); /// /// // The no-copy, unsafe way, still using transmute, but not relying on the data layout. /// // Like the first approach, this reuses the `Vec` internals. /// // Therefore, the new inner type must have the /// // exact same size, *and the same alignment*, as the old type. /// // The same caveats exist for this method as transmute, for /// // the original inner type (`&i32`) to the converted inner type /// // (`Option<&i32>`), so read the nomicon pages linked above and also /// // consult the [`from_raw_parts`] documentation. /// // This is the proper no-copy, unsafe way of \"transmuting\" a `Vec`, without relying on the /// // data layout. Instead of literally calling `transmute`, we perform a pointer cast, but /// // in terms of converting the original inner type (`&i32`) to the new one (`Option<&i32>`), /// // this has all the same caveats. Besides the information provided above, also consult the /// // [`from_raw_parts`] documentation. /// let v_from_raw = unsafe { // FIXME Update this when vec_into_raw_parts is stabilized /// // Ensure the original vector is not dropped."} {"_id":"doc-en-rust-2b4206d9852609b50fa21150f7666523bfbee7b6ddf62d47aeb13fc9884d32b6","title":"","text":" // run-rustfix #![allow(dead_code, unused_variables)] fn foo1(bar: &str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn foo2(_bar: &str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn foo3(_: &str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn main() {} "} {"_id":"doc-en-rust-d5a43a8001a2d4c59daf9dcfb69d84c681a4a76ae69ab1f31ecdd860e17a2b01","title":"","text":" // run-rustfix #![allow(dead_code, unused_variables)] fn foo1(bar: str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn foo2(_bar: str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn foo3(_: str) {} //~^ ERROR the size for values of type `str` cannot be known at compilation time //~| HELP the trait `Sized` is not implemented for `str` //~| HELP unsized fn params are gated as an unstable feature //~| HELP function arguments must have a statically known size, borrowed types always have a known size fn main() {} "} {"_id":"doc-en-rust-7a0e8d06a00534b48a8841984d0d74319339558a04ccfcc6a8df378836ebb69f","title":"","text":" error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/unsized-function-parameter.rs:5:9 | LL | fn foo1(bar: str) {} | ^^^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `str` = help: unsized fn params are gated as an unstable feature help: function arguments must have a statically known size, borrowed types always have a known size | LL | fn foo1(bar: &str) {} | ^ error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/unsized-function-parameter.rs:11:9 | LL | fn foo2(_bar: str) {} | ^^^^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `str` = help: unsized fn params are gated as an unstable feature help: function arguments must have a statically known size, borrowed types always have a known size | LL | fn foo2(_bar: &str) {} | ^ error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/unsized-function-parameter.rs:17:9 | LL | fn foo3(_: str) {} | ^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `str` = help: unsized fn params are gated as an unstable feature help: function arguments must have a statically known size, borrowed types always have a known size | LL | fn foo3(_: &str) {} | ^ error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-ad094de125d0dcc047c9a8ec5d4c3f70565f1c054260ef28af2bf0e222ac925a","title":"","text":"let dl = self.data_layout(); let pack = repr.pack; if pack.is_some() && repr.align.is_some() { bug!(\"struct cannot be packed and aligned\"); self.tcx.sess.delay_span_bug(DUMMY_SP, \"struct cannot be packed and aligned\"); return Err(LayoutError::Unknown(ty)); } let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align };"} {"_id":"doc-en-rust-88f41df5708749a3148072f471a9eb826f6e2fd509eec7408ab5b1fcb8a5d95c","title":"","text":"if def.is_union() { if def.repr.pack.is_some() && def.repr.align.is_some() { bug!(\"union cannot be packed and aligned\"); self.tcx.sess.delay_span_bug( tcx.def_span(def.did), \"union cannot be packed and aligned\", ); return Err(LayoutError::Unknown(ty)); } let mut align ="} {"_id":"doc-en-rust-e01a0cb829d6c21fb31e7625cbfb947a53f7a44bb2aecdd113e48cf845a4bdb2","title":"","text":"i: i32, } #[repr(packed, align(0x100))] pub struct S(u16); //~ ERROR type has conflicting packed and align representation hints #[repr(packed, align(0x100))] pub union U { //~ ERROR type has conflicting packed and align representation hints u: u16 } static B: U = U { u: 0 }; static A: S = S(0); fn main() {}"} {"_id":"doc-en-rust-67486a67c7bc22d32080650b70b1153063a5e83452889358ff0ed5d529ba1ed3","title":"","text":"LL | | } | |_^ error: aborting due to 10 previous errors error[E0587]: type has conflicting packed and align representation hints --> $DIR/conflicting-repr-hints.rs:70:1 | LL | pub struct S(u16); | ^^^^^^^^^^^^^^^^^^ error[E0587]: type has conflicting packed and align representation hints --> $DIR/conflicting-repr-hints.rs:73:1 | LL | / pub union U { LL | | u: u16 LL | | } | |_^ error: aborting due to 12 previous errors Some errors have detailed explanations: E0566, E0587, E0634. For more information about an error, try `rustc --explain E0566`."} {"_id":"doc-en-rust-10e2e7efa2a7dde5428bfaba3ea72cc8722d5c906979c2db4bd56d6f07c87639","title":"","text":"#[unstable(feature = \"str_internals\", issue = \"none\")] pub use validations::next_code_point; #[unstable(feature = \"str_internals\", issue = \"none\")] pub use validations::utf8_char_width; use iter::MatchIndicesInternal; use iter::SplitInternal; use iter::{MatchesInternal, SplitNInternal};"} {"_id":"doc-en-rust-d3a89a71ae615a075eb03c2f604ff76a023b156e85044f35c6bd6fc8fa02e310","title":"","text":"use crate::sys::c; use crate::sys::cvt; use crate::sys::handle::Handle; use core::str::utf8_char_width; // Don't cache handles but get them fresh for every read/write. This allows us to track changes to // the value over time (such as if a process calls `SetStdHandle` while it's running). See #40490. pub struct Stdin { surrogate: u16, } pub struct Stdout; pub struct Stderr; pub struct Stdout { incomplete_utf8: IncompleteUtf8, } pub struct Stderr { incomplete_utf8: IncompleteUtf8, } struct IncompleteUtf8 { bytes: [u8; 4], len: u8, } // Apparently Windows doesn't handle large reads on stdin or writes to stdout/stderr well (see // #13304 for details)."} {"_id":"doc-en-rust-abd526c308c691ea6d0109a9ba4d44739e82d360aa95c8bd9f065af04ec0209b","title":"","text":"unsafe { c::GetConsoleMode(handle, &mut mode) != 0 } } fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result { fn write( handle_id: c::DWORD, data: &[u8], incomplete_utf8: &mut IncompleteUtf8, ) -> io::Result { if data.is_empty() { return Ok(0); } let handle = get_handle(handle_id)?; if !is_console(handle) { let handle = Handle::new(handle);"} {"_id":"doc-en-rust-7c8a3c1ef615bac167b051cece12b9fb8895e8fbb2a4ac175efb808ad6bbbd3d","title":"","text":"return ret; } // As the console is meant for presenting text, we assume bytes of `data` come from a string // and are encoded as UTF-8, which needs to be encoded as UTF-16. if incomplete_utf8.len > 0 { assert!( incomplete_utf8.len < 4, \"Unexpected number of bytes for incomplete UTF-8 codepoint.\" ); if data[0] >> 6 != 0b10 { incomplete_utf8.len = 0; // not a continuation byte - reject return Err(io::Error::new_const( io::ErrorKind::InvalidData, &\"Windows stdio in console mode does not support writing non-UTF-8 byte sequences\", )); } incomplete_utf8.bytes[incomplete_utf8.len as usize] = data[0]; incomplete_utf8.len += 1; let char_width = utf8_char_width(incomplete_utf8.bytes[0]); if (incomplete_utf8.len as usize) < char_width { // more bytes needed return Ok(1); } let s = str::from_utf8(&incomplete_utf8.bytes[0..incomplete_utf8.len as usize]); incomplete_utf8.len = 0; match s { Ok(s) => { assert_eq!(char_width, s.len()); let written = write_valid_utf8_to_console(handle, s)?; assert_eq!(written, s.len()); // guaranteed by write_valid_utf8_to_console() for single codepoint writes return Ok(1); } Err(_) => { return Err(io::Error::new_const( io::ErrorKind::InvalidData, &\"Windows stdio in console mode does not support writing non-UTF-8 byte sequences\", )); } } } // As the console is meant for presenting text, we assume bytes of `data` are encoded as UTF-8, // which needs to be encoded as UTF-16. // // If the data is not valid UTF-8 we write out as many bytes as are valid. // Only when there are no valid bytes (which will happen on the next call), return an error. // If the first byte is invalid it is either first byte of a multi-byte sequence but the // provided byte slice is too short or it is the first byte of an invalide multi-byte sequence. let len = cmp::min(data.len(), MAX_BUFFER_SIZE / 2); let utf8 = match str::from_utf8(&data[..len]) { Ok(s) => s, Err(ref e) if e.valid_up_to() == 0 => { return Err(io::Error::new_const( io::ErrorKind::InvalidData, &\"Windows stdio in console mode does not support writing non-UTF-8 byte sequences\", )); let first_byte_char_width = utf8_char_width(data[0]); if first_byte_char_width > 1 && data.len() < first_byte_char_width { incomplete_utf8.bytes[0] = data[0]; incomplete_utf8.len = 1; return Ok(1); } else { return Err(io::Error::new_const( io::ErrorKind::InvalidData, &\"Windows stdio in console mode does not support writing non-UTF-8 byte sequences\", )); } } Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(), }; write_valid_utf8_to_console(handle, utf8) } fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result { let mut utf16 = [0u16; MAX_BUFFER_SIZE / 2]; let mut len_utf16 = 0; for (chr, dest) in utf8.encode_utf16().zip(utf16.iter_mut()) {"} {"_id":"doc-en-rust-ff4fc61243b5733b45b154ab504074dbd1932ebeea3f11b037c887722ee0577a","title":"","text":"Ok(written) } impl IncompleteUtf8 { pub const fn new() -> IncompleteUtf8 { IncompleteUtf8 { bytes: [0; 4], len: 0 } } } impl Stdout { pub const fn new() -> Stdout { Stdout Stdout { incomplete_utf8: IncompleteUtf8::new() } } } impl io::Write for Stdout { fn write(&mut self, buf: &[u8]) -> io::Result { write(c::STD_OUTPUT_HANDLE, buf) write(c::STD_OUTPUT_HANDLE, buf, &mut self.incomplete_utf8) } fn flush(&mut self) -> io::Result<()> {"} {"_id":"doc-en-rust-80c0fb718ecc38d799c5aefc979b982c1a6c09ea7b3bb4c336880fa631665e1b","title":"","text":"impl Stderr { pub const fn new() -> Stderr { Stderr Stderr { incomplete_utf8: IncompleteUtf8::new() } } } impl io::Write for Stderr { fn write(&mut self, buf: &[u8]) -> io::Result { write(c::STD_ERROR_HANDLE, buf) write(c::STD_ERROR_HANDLE, buf, &mut self.incomplete_utf8) } fn flush(&mut self) -> io::Result<()> {"} {"_id":"doc-en-rust-942cd02ad71f0e6e4e2b28d10ce4d6a95b705ee0c177f962c2811125a541b0ca","title":"","text":"let mut inserted = FxHashSet::default(); items.extend(doc.foreigns.iter().map(|(item, renamed)| { let item = clean_maybe_renamed_foreign_item(cx, item, *renamed); if let Some(name) = item.name { if let Some(name) = item.name && !item.attrs.lists(sym::doc).has_word(sym::hidden) { inserted.insert((item.type_(), name)); } item })); items.extend(doc.mods.iter().map(|x| { inserted.insert((ItemType::Module, x.name)); clean_doc_module(x, cx) items.extend(doc.mods.iter().filter_map(|x| { if !inserted.insert((ItemType::Module, x.name)) { return None; } let item = clean_doc_module(x, cx); if item.attrs.lists(sym::doc).has_word(sym::hidden) { // Hidden modules are stripped at a later stage. // If a hidden module has the same name as a visible one, we want // to keep both of them around. inserted.remove(&(ItemType::Module, x.name)); } Some(item) })); // Split up imports from all other items."} {"_id":"doc-en-rust-ed24c83e039487d2f23946019e4cfdef44af6f09ca6f891c197e3b7c2a9ddc85","title":"","text":"} let v = clean_maybe_renamed_item(cx, item, *renamed); for item in &v { if let Some(name) = item.name { if let Some(name) = item.name && !item.attrs.lists(sym::doc).has_word(sym::hidden) { inserted.insert((item.type_(), name)); } }"} {"_id":"doc-en-rust-13f4bcb2a050b46d5f93c76b6fb6a1d7608730b3007f592bd0595260a5da7b9d","title":"","text":"self.inside_public_path &= self.cx.tcx.visibility(def_id).is_public(); for &i in m.item_ids { let item = self.cx.tcx.hir().item(i); if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) { continue; } self.visit_item(item, None, &mut om); } for &i in m.item_ids { let item = self.cx.tcx.hir().item(i); // To match the way import precedence works, visit glob imports last. // Later passes in rustdoc will de-duplicate by name and kind, so if glob- // imported items appear last, then they'll be the ones that get discarded. if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) { self.visit_item(item, None, &mut om); } } self.inside_public_path = orig_inside_public_path; om }"} {"_id":"doc-en-rust-9a71082197f73020ecb4d63abc9ce33e420502fde85f84f14b8defd4abe23ff7","title":"","text":" // https://github.com/rust-lang/rust/pull/83872#issuecomment-820101008 #![crate_name=\"foo\"] mod sub4 { /// 0 pub const X: usize = 0; pub mod inner { pub use super::*; /// 1 pub const X: usize = 1; } } #[doc(inline)] pub use sub4::inner::*; // @has 'foo/index.html' // @has - '//div[@class=\"item-right docblock-short\"]' '1' // @!has - '//div[@class=\"item-right docblock-short\"]' '0' fn main() { assert_eq!(X, 1); } "} {"_id":"doc-en-rust-0d0ce244cdd8bec42134436d977ca464bbb3124cadb85ca9306498d1a1c95b20","title":"","text":" // @has 'glob_shadowing/index.html' // @count - '//div[@class=\"item-left module-item\"]' 6 // @!has - '//div[@class=\"item-right docblock-short\"]' 'sub1::describe' // @has - '//div[@class=\"item-right docblock-short\"]' 'sub2::describe' // @!has - '//div[@class=\"item-right docblock-short\"]' 'sub1::describe2' // @!has - '//div[@class=\"item-right docblock-short\"]' 'sub1::prelude' // @has - '//div[@class=\"item-right docblock-short\"]' 'mod::prelude' // @has - '//div[@class=\"item-right docblock-short\"]' 'sub1::Foo (struct)' // @has - '//div[@class=\"item-right docblock-short\"]' 'mod::Foo (function)' // @has - '//div[@class=\"item-right docblock-short\"]' 'sub4::inner::X' // @has 'glob_shadowing/fn.describe.html' // @has - '//div[@class=\"docblock\"]' 'sub2::describe' mod sub1 { // this should be shadowed by sub2::describe /// sub1::describe pub fn describe() -> &'static str { \"sub1::describe\" } // this should be shadowed by mod::prelude /// sub1::prelude pub mod prelude { } // this should *not* be shadowed, because sub1::Foo and mod::Foo are in different namespaces /// sub1::Foo (struct) pub struct Foo; // this should be shadowed, // because both sub1::describe2 and sub3::describe2 are from glob reexport /// sub1::describe2 pub fn describe2() -> &'static str { \"sub1::describe2\" } } mod sub2 { /// sub2::describe pub fn describe() -> &'static str { \"sub2::describe\" } } mod sub3 { // this should be shadowed // because both sub1::describe2 and sub3::describe2 are from glob reexport /// sub3::describe2 pub fn describe2() -> &'static str { \"sub3::describe2\" } } mod sub4 { // this should be shadowed by sub4::inner::X /// sub4::X pub const X: usize = 0; pub mod inner { pub use super::*; /// sub4::inner::X pub const X: usize = 1; } } /// mod::Foo (function) pub fn Foo() {} #[doc(inline)] pub use sub2::describe; #[doc(inline)] pub use sub1::*; #[doc(inline)] pub use sub3::*; #[doc(inline)] pub use sub4::inner::*; /// mod::prelude pub mod prelude {} "} {"_id":"doc-en-rust-fd6f6e8d5f5fcd259faccaaa066fc11893b0848e3fe4ab06ceb1d3a1c4ce47e4","title":"","text":" #![crate_name = \"foo\"] pub mod sub { pub struct Item; pub mod prelude { pub use super::Item; } } #[doc(inline)] pub use sub::*; // @count foo/index.html '//a[@class=\"mod\"][@title=\"foo::prelude mod\"]' 1 // @count foo/prelude/index.html '//div[@class=\"item-row\"]' 0 pub mod prelude {} "} {"_id":"doc-en-rust-da9304ebf18b74355cf97a7c686f71387de11949ff4373b766a8ea789e11e524","title":"","text":" #![crate_name = \"foo\"] pub mod sub { pub struct Item; pub mod prelude { pub use super::Item; } } // @count foo/index.html '//a[@class=\"mod\"][@title=\"foo::prelude mod\"]' 1 // @count foo/prelude/index.html '//div[@class=\"item-row\"]' 0 pub mod prelude {} #[doc(inline)] pub use sub::*; "} {"_id":"doc-en-rust-64423618667e9776da8150cea6f9182f006863595edbf09c2bca128277f5a26a","title":"","text":"def update(self): # type: () -> None table = self.table() capacity = table.GetChildMemberWithName(\"bucket_mask\").GetValueAsUnsigned() + 1 ctrl = table.GetChildMemberWithName(\"ctrl\").GetChildAtIndex(0) inner_table = table.GetChildMemberWithName(\"table\") self.size = table.GetChildMemberWithName(\"items\").GetValueAsUnsigned() capacity = inner_table.GetChildMemberWithName(\"bucket_mask\").GetValueAsUnsigned() + 1 ctrl = inner_table.GetChildMemberWithName(\"ctrl\").GetChildAtIndex(0) self.size = inner_table.GetChildMemberWithName(\"items\").GetValueAsUnsigned() self.pair_type = table.type.template_args[0] if self.pair_type.IsTypedefType(): self.pair_type = self.pair_type.GetTypedefedType() self.pair_type_size = self.pair_type.GetByteSize() self.new_layout = not table.GetChildMemberWithName(\"data\").IsValid() self.new_layout = not inner_table.GetChildMemberWithName(\"data\").IsValid() if self.new_layout: self.data_ptr = ctrl.Cast(self.pair_type.GetPointerType()) else: self.data_ptr = table.GetChildMemberWithName(\"data\").GetChildAtIndex(0) self.data_ptr = inner_table.GetChildMemberWithName(\"data\").GetChildAtIndex(0) u8_type = self.valobj.GetTarget().GetBasicType(eBasicTypeUnsignedChar) u8_type_size = self.valobj.GetTarget().GetBasicType(eBasicTypeUnsignedChar).GetByteSize()"} {"_id":"doc-en-rust-3b920d6c5caad9233577a1edf7eec86f4295952ad01eb12313d05934564faea2","title":"","text":"# HashSet wraps either std HashMap or hashbrown::HashSet, which both # wrap hashbrown::HashMap, so either way we \"unwrap\" twice. hashbrown_hashmap = self.valobj.GetChildAtIndex(0).GetChildAtIndex(0) return hashbrown_hashmap.GetChildMemberWithName(\"table\").GetChildMemberWithName(\"table\") return hashbrown_hashmap.GetChildMemberWithName(\"table\") def has_children(self): # type: () -> bool"} {"_id":"doc-en-rust-f289a9759dd6d13396e2993efbbea0149d74a2cf2c0abafa7d5af2de39ef8a85","title":"","text":"/// scratch space that it may use however it wants. It will generally just do /// whatever is most efficient or otherwise easy to implement. Do not rely on /// removed data to be erased for security purposes. Even if you drop a `Vec`, its /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory /// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory /// first, that might not actually happen because the optimizer does not consider /// this a side-effect that must be preserved. There is one case which we will /// not break, however: using `unsafe` code to write to the excess capacity,"} {"_id":"doc-en-rust-b2cc3002c0205e29179d61ca74d8d45fb0de7902ebbf46c25effda2eeb5ff6f8","title":"","text":"val } fn emit_s390x_va_arg<'ll, 'tcx>( bx: &mut Builder<'_, 'll, 'tcx>, list: OperandRef<'tcx, &'ll Value>, target_ty: Ty<'tcx>, ) -> &'ll Value { // Implementation of the s390x ELF ABI calling convention for va_args see // https://github.com/IBM/s390x-abi (chapter 1.2.4) let va_list_addr = list.immediate(); let va_list_layout = list.deref(bx.cx).layout; let va_list_ty = va_list_layout.llvm_type(bx); let layout = bx.cx.layout_of(target_ty); let in_reg = bx.append_sibling_block(\"va_arg.in_reg\"); let in_mem = bx.append_sibling_block(\"va_arg.in_mem\"); let end = bx.append_sibling_block(\"va_arg.end\"); // FIXME: vector ABI not yet supported. let target_ty_size = bx.cx.size_of(target_ty).bytes(); let indirect: bool = target_ty_size > 8 || !target_ty_size.is_power_of_two(); let unpadded_size = if indirect { 8 } else { target_ty_size }; let padded_size = 8; let padding = padded_size - unpadded_size; let gpr_type = indirect || !layout.is_single_fp_element(bx.cx); let (max_regs, reg_count_field, reg_save_index, reg_padding) = if gpr_type { (5, 0, 2, padding) } else { (4, 1, 16, 0) }; // Check whether the value was passed in a register or in memory. let reg_count = bx.struct_gep( va_list_ty, va_list_addr, va_list_layout.llvm_field_index(bx.cx, reg_count_field), ); let reg_count_v = bx.load(bx.type_i64(), reg_count, Align::from_bytes(8).unwrap()); let use_regs = bx.icmp(IntPredicate::IntULT, reg_count_v, bx.const_u64(max_regs)); bx.cond_br(use_regs, in_reg, in_mem); // Emit code to load the value if it was passed in a register. bx.switch_to_block(in_reg); // Work out the address of the value in the register save area. let reg_ptr = bx.struct_gep(va_list_ty, va_list_addr, va_list_layout.llvm_field_index(bx.cx, 3)); let reg_ptr_v = bx.load(bx.type_i8p(), reg_ptr, bx.tcx().data_layout.pointer_align.abi); let scaled_reg_count = bx.mul(reg_count_v, bx.const_u64(8)); let reg_off = bx.add(scaled_reg_count, bx.const_u64(reg_save_index * 8 + reg_padding)); let reg_addr = bx.gep(bx.type_i8(), reg_ptr_v, &[reg_off]); // Update the register count. let new_reg_count_v = bx.add(reg_count_v, bx.const_u64(1)); bx.store(new_reg_count_v, reg_count, Align::from_bytes(8).unwrap()); bx.br(end); // Emit code to load the value if it was passed in memory. bx.switch_to_block(in_mem); // Work out the address of the value in the argument overflow area. let arg_ptr = bx.struct_gep(va_list_ty, va_list_addr, va_list_layout.llvm_field_index(bx.cx, 2)); let arg_ptr_v = bx.load(bx.type_i8p(), arg_ptr, bx.tcx().data_layout.pointer_align.abi); let arg_off = bx.const_u64(padding); let mem_addr = bx.gep(bx.type_i8(), arg_ptr_v, &[arg_off]); // Update the argument overflow area pointer. let arg_size = bx.cx().const_u64(padded_size); let new_arg_ptr_v = bx.inbounds_gep(bx.type_i8(), arg_ptr_v, &[arg_size]); bx.store(new_arg_ptr_v, arg_ptr, bx.tcx().data_layout.pointer_align.abi); bx.br(end); // Return the appropriate result. bx.switch_to_block(end); let val_addr = bx.phi(bx.type_i8p(), &[reg_addr, mem_addr], &[in_reg, in_mem]); let val_type = layout.llvm_type(bx); let val_addr = if indirect { let ptr_type = bx.cx.type_ptr_to(val_type); let ptr_addr = bx.bitcast(val_addr, bx.cx.type_ptr_to(ptr_type)); bx.load(ptr_type, ptr_addr, bx.tcx().data_layout.pointer_align.abi) } else { bx.bitcast(val_addr, bx.cx.type_ptr_to(val_type)) }; bx.load(val_type, val_addr, layout.align.abi) } pub(super) fn emit_va_arg<'ll, 'tcx>( bx: &mut Builder<'_, 'll, 'tcx>, addr: OperandRef<'tcx, &'ll Value>,"} {"_id":"doc-en-rust-fc21002b979b33d414ecc9822de3278014775c532a302d265ac6c83b15bb7586","title":"","text":"emit_ptr_va_arg(bx, addr, target_ty, false, Align::from_bytes(8).unwrap(), true) } \"aarch64\" => emit_aapcs_va_arg(bx, addr, target_ty), \"s390x\" => emit_s390x_va_arg(bx, addr, target_ty), // Windows x86_64 \"x86_64\" if target.is_like_windows => { let target_ty_size = bx.cx.size_of(target_ty).bytes();"} {"_id":"doc-en-rust-ffa489cd3900d881c8ad2e7c8d36a9f3335c4b61d142d8e8a92d684c129e7507","title":"","text":"/// Basic implementation of a `va_list`. // The name is WIP, using `VaListImpl` for now. #[cfg(any( all(not(target_arch = \"aarch64\"), not(target_arch = \"powerpc\"), not(target_arch = \"x86_64\")), all( not(target_arch = \"aarch64\"), not(target_arch = \"powerpc\"), not(target_arch = \"s390x\"), not(target_arch = \"x86_64\") ), all(target_arch = \"aarch64\", any(target_os = \"macos\", target_os = \"ios\")), target_family = \"wasm\", target_arch = \"asmjs\","} {"_id":"doc-en-rust-beb9e940b0cce4a1f23ffdc4bfe00d9e83668da50c0783d94833d1c49f52f598","title":"","text":"_marker: PhantomData<&'f mut &'f c_void>, } /// s390x ABI implementation of a `va_list`. #[cfg(target_arch = \"s390x\")] #[repr(C)] #[derive(Debug)] #[unstable( feature = \"c_variadic\", reason = \"the `c_variadic` feature has not been properly tested on all supported platforms\", issue = \"44930\" )] #[lang = \"va_list\"] pub struct VaListImpl<'f> { gpr: i64, fpr: i64, overflow_arg_area: *mut c_void, reg_save_area: *mut c_void, _marker: PhantomData<&'f mut &'f c_void>, } /// x86_64 ABI implementation of a `va_list`. #[cfg(all(target_arch = \"x86_64\", not(target_os = \"uefi\"), not(windows)))] #[repr(C)]"} {"_id":"doc-en-rust-332882707b0fbdda2ffe2717d67a097441a3508ad0f7bb738133c77f9e91fc49","title":"","text":"all( not(target_arch = \"aarch64\"), not(target_arch = \"powerpc\"), not(target_arch = \"s390x\"), not(target_arch = \"x86_64\") ), all(target_arch = \"aarch64\", any(target_os = \"macos\", target_os = \"ios\")),"} {"_id":"doc-en-rust-fc13f4f93e907d9027f0778f0fb01df63d70c00c99c3f064defea4113be98ca9","title":"","text":"inner: VaListImpl<'f>, #[cfg(all( any(target_arch = \"aarch64\", target_arch = \"powerpc\", target_arch = \"x86_64\"), any( target_arch = \"aarch64\", target_arch = \"powerpc\", target_arch = \"s390x\", target_arch = \"x86_64\" ), any(not(target_arch = \"aarch64\"), not(any(target_os = \"macos\", target_os = \"ios\"))), not(target_family = \"wasm\"), not(target_arch = \"asmjs\"),"} {"_id":"doc-en-rust-7b94bc40ea3b5f17760fab63e4a9259908534400fe3054a5aebd2fbaa9de8cfc","title":"","text":"} #[cfg(any( all(not(target_arch = \"aarch64\"), not(target_arch = \"powerpc\"), not(target_arch = \"x86_64\")), all( not(target_arch = \"aarch64\"), not(target_arch = \"powerpc\"), not(target_arch = \"s390x\"), not(target_arch = \"x86_64\") ), all(target_arch = \"aarch64\", any(target_os = \"macos\", target_os = \"ios\")), target_family = \"wasm\", target_arch = \"asmjs\","} {"_id":"doc-en-rust-696a6968dcf128204924de394a0d57f67d1ad11247a1138862771c24a3117238","title":"","text":"} #[cfg(all( any(target_arch = \"aarch64\", target_arch = \"powerpc\", target_arch = \"x86_64\"), any( target_arch = \"aarch64\", target_arch = \"powerpc\", target_arch = \"s390x\", target_arch = \"x86_64\" ), any(not(target_arch = \"aarch64\"), not(any(target_os = \"macos\", target_os = \"ios\"))), not(target_family = \"wasm\"), not(target_arch = \"asmjs\"),"} {"_id":"doc-en-rust-7aff9851391de70fa64f3cf59d45710f7b9f44bd53c2c8ca98e1b31572297e71","title":"","text":"use rustc_middle::middle::privacy::AccessLevels; use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; use rustc_resolve as resolve; use rustc_resolve::Namespace::TypeNS; use rustc_session::config::{self, CrateType, ErrorOutputType}; use rustc_session::lint; use rustc_session::DiagnosticOutput; use rustc_session::Session; use rustc_span::def_id::CRATE_DEF_INDEX; use rustc_span::source_map; use rustc_span::symbol::sym; use rustc_span::Span; use rustc_span::{Span, DUMMY_SP}; use std::cell::RefCell; use std::lazy::SyncLazy;"} {"_id":"doc-en-rust-8e268638a440831b957270c6894a6c4b82f3df14788d02b0006b8da687222a64","title":"","text":"} crate fn create_resolver<'a>( externs: config::Externs, queries: &Queries<'a>, sess: &Session, ) -> Rc> { let (krate, resolver, _) = &*abort_on_err(queries.expansion(), sess).peek(); let resolver = resolver.clone(); crate::passes::collect_intra_doc_links::load_intra_link_crates(resolver, krate) let resolver = crate::passes::collect_intra_doc_links::load_intra_link_crates(resolver, krate); // FIXME: somehow rustdoc is still missing crates even though we loaded all // the known necessary crates. Load them all unconditionally until we find a way to fix this. // DO NOT REMOVE THIS without first testing on the reproducer in // https://github.com/jyn514/objr/commit/edcee7b8124abf0e4c63873e8422ff81beb11ebb let extern_names: Vec = externs .iter() .filter(|(_, entry)| entry.add_prelude) .map(|(name, _)| name) .cloned() .collect(); resolver.borrow_mut().access(|resolver| { sess.time(\"load_extern_crates\", || { for extern_name in &extern_names { debug!(\"loading extern crate {}\", extern_name); if let Err(()) = resolver .resolve_str_path_error( DUMMY_SP, extern_name, TypeNS, LocalDefId { local_def_index: CRATE_DEF_INDEX }.to_def_id(), ) { warn!(\"unable to resolve external crate {} (do you have an unused `--extern` crate?)\", extern_name) } } }); }); resolver } crate fn run_global_ctxt("} {"_id":"doc-en-rust-86b4573c44f3bbdbe4fa7f50485711d925a18c62ce279617704cd9b56c507eea","title":"","text":"let default_passes = options.default_passes; let output_format = options.output_format; // FIXME: fix this clone (especially render_options) let externs = options.externs.clone(); let manual_passes = options.manual_passes.clone(); let render_options = options.render_options.clone(); let scrape_examples_options = options.scrape_examples_options.clone();"} {"_id":"doc-en-rust-544a4551eece3040436b82fd0d6ca70aa048d350d68ae13681a4756e93548f65","title":"","text":"// We need to hold on to the complete resolver, so we cause everything to be // cloned for the analysis passes to use. Suboptimal, but necessary in the // current architecture. let resolver = core::create_resolver(queries, sess); let resolver = core::create_resolver(externs, queries, sess); if sess.has_errors() { sess.fatal(\"Compilation failed, aborting rustdoc\");"} {"_id":"doc-en-rust-a1970fea3adb18c916ee4fe0d370e6070b77bfbc7862de9bb56cf0eb2e97faa8","title":"","text":" use ast::visit; use rustc_ast as ast; use rustc_hir::def::Namespace::TypeNS; use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};"} {"_id":"doc-en-rust-3211eaf81da296e3870358c61701b1666bd35940b93f239b434f6c4565fdb094","title":"","text":"let mut loader = IntraLinkCrateLoader { current_mod: CRATE_DEF_ID, resolver }; // `walk_crate` doesn't visit the crate itself for some reason. loader.load_links_in_attrs(&krate.attrs, krate.span); ast::visit::walk_crate(&mut loader, krate); visit::walk_crate(&mut loader, krate); loader.resolver }"} {"_id":"doc-en-rust-438fa164e718bf453688bc69b6e45ca882dff4f14434f29f838a96b898aa84e5","title":"","text":"} } impl ast::visit::Visitor<'_> for IntraLinkCrateLoader { impl visit::Visitor<'_> for IntraLinkCrateLoader { fn visit_foreign_item(&mut self, item: &ast::ForeignItem) { self.load_links_in_attrs(&item.attrs, item.span); visit::walk_foreign_item(self, item) } fn visit_item(&mut self, item: &ast::Item) { use rustc_ast_lowering::ResolverAstLowering;"} {"_id":"doc-en-rust-c11254f639f05f360b3bf2a2db811ecaa9ee4b57f8b2ba27bfbaea0607eace94","title":"","text":"let old_mod = mem::replace(&mut self.current_mod, new_mod); self.load_links_in_attrs(&item.attrs, item.span); ast::visit::walk_item(self, item); visit::walk_item(self, item); self.current_mod = old_mod; } else { self.load_links_in_attrs(&item.attrs, item.span); ast::visit::walk_item(self, item); visit::walk_item(self, item); } } // NOTE: if doc-comments are ever allowed on function parameters, this will have to implement `visit_param` too. fn visit_assoc_item(&mut self, item: &ast::AssocItem, ctxt: visit::AssocCtxt) { self.load_links_in_attrs(&item.attrs, item.span); visit::walk_assoc_item(self, item, ctxt) } fn visit_field_def(&mut self, field: &ast::FieldDef) { self.load_links_in_attrs(&field.attrs, field.span); visit::walk_field_def(self, field) } fn visit_variant(&mut self, v: &ast::Variant) { self.load_links_in_attrs(&v.attrs, v.span); visit::walk_variant(self, v) } }"} {"_id":"doc-en-rust-f5c511a98c46615a4a2265dcfc07857d10a1a95a4fdd1a8af0dc65d247a03b66","title":"","text":" // check-pass // aux-crate:dep1=dep1.rs // aux-crate:dep2=dep2.rs // aux-crate:dep3=dep3.rs // aux-crate:dep4=dep4.rs #![deny(rustdoc::broken_intra_doc_links)] pub trait Trait { /// [dep1] type Item; } pub struct S { /// [dep2] pub x: usize, } extern \"C\" { /// [dep3] pub fn printf(); } pub enum E { /// [dep4] A } "} {"_id":"doc-en-rust-ddaad02b4d8b035e6fd182824c28d33af41e487d38af1a8a0f9e937ef43eb33c","title":"","text":"pub const TRUE: BOOL = 1; pub const FALSE: BOOL = 0; pub const CSTR_LESS_THAN: c_int = 1; pub const CSTR_EQUAL: c_int = 2; pub const CSTR_GREATER_THAN: c_int = 3; pub const FILE_ATTRIBUTE_READONLY: DWORD = 0x1; pub const FILE_ATTRIBUTE_DIRECTORY: DWORD = 0x10; pub const FILE_ATTRIBUTE_REPARSE_POINT: DWORD = 0x400;"} {"_id":"doc-en-rust-1d4b99b95d734173a9df1c2addfd941bb334c61b09985a9837204e920aa1352f","title":"","text":"pub fn ReleaseSRWLockShared(SRWLock: PSRWLOCK); pub fn TryAcquireSRWLockExclusive(SRWLock: PSRWLOCK) -> BOOLEAN; pub fn TryAcquireSRWLockShared(SRWLock: PSRWLOCK) -> BOOLEAN; pub fn CompareStringOrdinal( lpString1: LPCWSTR, cchCount1: c_int, lpString2: LPCWSTR, cchCount2: c_int, bIgnoreCase: BOOL, ) -> c_int; } // Functions that aren't available on every version of Windows that we support,"} {"_id":"doc-en-rust-0c0fef3af2cc8466ab072f48f73c452fe611117e4e34d53b17a764fe676d7005","title":"","text":"mod tests; use crate::borrow::Borrow; use crate::cmp; use crate::collections::BTreeMap; use crate::convert::{TryFrom, TryInto}; use crate::env;"} {"_id":"doc-en-rust-1e9c8ccbfba36ef12ca200389c0cabd42008da3ee75af5eef6529859590d8e1b","title":"","text":"// Command //////////////////////////////////////////////////////////////////////////////// #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] #[derive(Clone, Debug, Eq)] #[doc(hidden)] pub struct EnvKey(OsString); pub struct EnvKey { os_string: OsString, // This stores a UTF-16 encoded string to workaround the mismatch between // Rust's OsString (WTF-8) and the Windows API string type (UTF-16). // Normally converting on every API call is acceptable but here // `c::CompareStringOrdinal` will be called for every use of `==`. utf16: Vec, } // Comparing Windows environment variable keys[1] are behaviourally the // composition of two operations[2]: // // 1. Case-fold both strings. This is done using a language-independent // uppercase mapping that's unique to Windows (albeit based on data from an // older Unicode spec). It only operates on individual UTF-16 code units so // surrogates are left unchanged. This uppercase mapping can potentially change // between Windows versions. // // 2. Perform an ordinal comparison of the strings. A comparison using ordinal // is just a comparison based on the numerical value of each UTF-16 code unit[3]. // // Because the case-folding mapping is unique to Windows and not guaranteed to // be stable, we ask the OS to compare the strings for us. This is done by // calling `CompareStringOrdinal`[4] with `bIgnoreCase` set to `TRUE`. // // [1] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call // [2] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#stringtoupper-and-stringtolower // [3] https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparison?view=net-5.0#System_StringComparison_Ordinal // [4] https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-comparestringordinal impl Ord for EnvKey { fn cmp(&self, other: &Self) -> cmp::Ordering { unsafe { let result = c::CompareStringOrdinal( self.utf16.as_ptr(), self.utf16.len() as _, other.utf16.as_ptr(), other.utf16.len() as _, c::TRUE, ); match result { c::CSTR_LESS_THAN => cmp::Ordering::Less, c::CSTR_EQUAL => cmp::Ordering::Equal, c::CSTR_GREATER_THAN => cmp::Ordering::Greater, // `CompareStringOrdinal` should never fail so long as the parameters are correct. _ => panic!(\"comparing environment keys failed: {}\", Error::last_os_error()), } } } } impl PartialOrd for EnvKey { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for EnvKey { fn eq(&self, other: &Self) -> bool { if self.utf16.len() != other.utf16.len() { false } else { self.cmp(other) == cmp::Ordering::Equal } } } // Environment variable keys should preserve their original case even though // they are compared using a caseless string mapping. impl From for EnvKey { fn from(mut k: OsString) -> Self { k.make_ascii_uppercase(); EnvKey(k) fn from(k: OsString) -> Self { EnvKey { utf16: k.encode_wide().collect(), os_string: k } } } impl From for OsString { fn from(k: EnvKey) -> Self { k.0 k.os_string } } impl Borrow for EnvKey { fn borrow(&self) -> &OsStr { &self.0 &self.os_string } } impl AsRef for EnvKey { fn as_ref(&self) -> &OsStr { &self.0 &self.os_string } }"} {"_id":"doc-en-rust-5b357d37d802d768a155360dfaa4ef1375d19e108de4f616d10190188a941efa","title":"","text":"let mut blk = Vec::new(); for (k, v) in env { blk.extend(ensure_no_nuls(k.0)?.encode_wide()); ensure_no_nuls(k.os_string)?; blk.extend(k.utf16); blk.push('=' as u16); blk.extend(ensure_no_nuls(v)?.encode_wide()); blk.push(0);"} {"_id":"doc-en-rust-ef2f1d74831d61a60bdd52ef5f7cb6c7d3ecc0b1d20028a128af2df65abc3bba","title":"","text":"use super::make_command_line; use crate::env; use crate::ffi::{OsStr, OsString}; use crate::process::Command; #[test] fn test_make_command_line() {"} {"_id":"doc-en-rust-cadba5d45e9655e220b94cfe7a1ceaf65cec98df18c8fb53fbc9c7003ca88371","title":"","text":"\"\"u{03c0}u{042f}u{97f3}u{00e6}u{221e}\"\" ); } // On Windows, environment args are case preserving but comparisons are case-insensitive. // See: #85242 #[test] fn windows_env_unicode_case() { let test_cases = [ (\"ä\", \"Ä\"), (\"ß\", \"SS\"), (\"Ä\", \"Ö\"), (\"Ä\", \"Ö\"), (\"I\", \"İ\"), (\"I\", \"i\"), (\"I\", \"ı\"), (\"i\", \"I\"), (\"i\", \"İ\"), (\"i\", \"ı\"), (\"İ\", \"I\"), (\"İ\", \"i\"), (\"İ\", \"ı\"), (\"ı\", \"I\"), (\"ı\", \"i\"), (\"ı\", \"İ\"), (\"ä\", \"Ä\"), (\"ß\", \"SS\"), (\"Ä\", \"Ö\"), (\"Ä\", \"Ö\"), (\"I\", \"İ\"), (\"I\", \"i\"), (\"I\", \"ı\"), (\"i\", \"I\"), (\"i\", \"İ\"), (\"i\", \"ı\"), (\"İ\", \"I\"), (\"İ\", \"i\"), (\"İ\", \"ı\"), (\"ı\", \"I\"), (\"ı\", \"i\"), (\"ı\", \"İ\"), ]; // Test that `cmd.env` matches `env::set_var` when setting two strings that // may (or may not) be case-folded when compared. for (a, b) in test_cases.iter() { let mut cmd = Command::new(\"cmd\"); cmd.env(a, \"1\"); cmd.env(b, \"2\"); env::set_var(a, \"1\"); env::set_var(b, \"2\"); for (key, value) in cmd.get_envs() { assert_eq!( env::var(key).ok(), value.map(|s| s.to_string_lossy().into_owned()), \"command environment mismatch: {} {}\", a, b ); } } } "} {"_id":"doc-en-rust-ae998563212417699a009782d1ec4313209cb27aa32bee12d33b8fce89c4b1d8","title":"","text":"), ); llvm::set_linkage(llfn, llvm::Linkage::WeakAnyLinkage); llvm::set_visibility(llfn, llvm::Visibility::Hidden); llvm::set_linkage(llfn, llvm::Linkage::PrivateLinkage); llvm::set_visibility(llfn, llvm::Visibility::Default); assert!(cx.instances.borrow_mut().insert(instance, llfn).is_none());"} {"_id":"doc-en-rust-198878532f5e6fc1d4ef98e091ecef1062f3147dcf11a3d71e14d01287cc27b3","title":"","text":" ../coverage/issue-85461.rs: 1| |// Regression test for #85461: MSVC sometimes fail to link with dead code and #[inline(always)] 2| | 3| |extern crate inline_always_with_dead_code; 4| | 5| |use inline_always_with_dead_code::{bar, baz}; 6| | 7| 1|fn main() { 8| 1| bar::call_me(); 9| 1| baz::call_me(); 10| 1|} ../coverage/lib/inline_always_with_dead_code.rs: 1| |// compile-flags: -Zinstrument-coverage -Ccodegen-units=4 -Copt-level=0 2| | 3| |#![allow(dead_code)] 4| | 5| |mod foo { 6| | #[inline(always)] 7| 2| pub fn called() { } 8| | 9| 0| fn uncalled() { } 10| |} 11| | 12| |pub mod bar { 13| 1| pub fn call_me() { 14| 1| super::foo::called(); 15| 1| } 16| |} 17| | 18| |pub mod baz { 19| 1| pub fn call_me() { 20| 1| super::foo::called(); 21| 1| } 22| |} "} {"_id":"doc-en-rust-3db992ea049dd06095d096518927436e01b4a5f660e743c4573c4072c2564870","title":"","text":" // Regression test for #85461: MSVC sometimes fail to link with dead code and #[inline(always)] extern crate inline_always_with_dead_code; use inline_always_with_dead_code::{bar, baz}; fn main() { bar::call_me(); baz::call_me(); } "} {"_id":"doc-en-rust-b51deafabe275eff3f646a3e224418ef5b9f92eb0cceddf19580bec2c6a6f3a7","title":"","text":" // compile-flags: -Zinstrument-coverage -Ccodegen-units=4 -Copt-level=0 #![allow(dead_code)] mod foo { #[inline(always)] pub fn called() { } fn uncalled() { } } pub mod bar { pub fn call_me() { super::foo::called(); } } pub mod baz { pub fn call_me() { super::foo::called(); } } "} {"_id":"doc-en-rust-a0950cbb408dbd28701d708ba543de6db23a142fa2570255d0b537708ffe8916","title":"","text":" // compile-flags: -Zinstrument-coverage -Ccodegen-units=4 --crate-type dylib -Copt-level=0 // build-pass // needs-profiler-support // Regression test for #85461 where MSVC sometimes fails to link instrument-coverage binaries // with dead code and #[inline(always)]. #![allow(dead_code)] mod foo { #[inline(always)] pub fn called() { } fn uncalled() { } } pub mod bar { pub fn call_me() { super::foo::called(); } } pub mod baz { pub fn call_me() { super::foo::called(); } } "} {"_id":"doc-en-rust-92962be3abc1bedfeb28f0dc94b8720fffc1d8f04238f852f2c8f2ab6d4c7668","title":"","text":" // min-llvm-version: 15.0.0 // compile-flags: -O #![crate_type = \"lib\"] #[no_mangle] pub fn u16_be_to_arch(mut data: [u8; 2]) -> [u8; 2] { // CHECK-LABEL: @u16_be_to_arch // CHECK: @llvm.bswap.i16 data.reverse(); data } #[no_mangle] pub fn u32_be_to_arch(mut data: [u8; 4]) -> [u8; 4] { // CHECK-LABEL: @u32_be_to_arch // CHECK: @llvm.bswap.i32 data.reverse(); data } "} {"_id":"doc-en-rust-e1643a7295902ec96b4bdc93150698d965164401e2ffe49f2e37291db8b33f3c","title":"","text":"let size = u64::try_from(self.force_bits(size, pointer_size)?).unwrap(); let align = vtable.read_ptr_sized(pointer_size * 2)?.check_init()?; let align = u64::try_from(self.force_bits(align, pointer_size)?).unwrap(); let align = Align::from_bytes(align) .map_err(|e| err_ub_format!(\"invalid vtable: alignment {}\", e))?; if size >= self.tcx.data_layout.obj_size_bound() { throw_ub_format!("} {"_id":"doc-en-rust-8a31817f49d43a96d0a053bb0d1e80938bc56c8c60a84b28138e772901857641","title":"","text":"size is bigger than largest supported object\" ); } Ok((Size::from_bytes(size), Align::from_bytes(align).unwrap())) Ok((Size::from_bytes(size), align)) } }"} {"_id":"doc-en-rust-0d7b8d9dabc3522dcddb0d0f18b595c947faf284f287e29516be95ac4e3df7b3","title":"","text":" // This test contains code with incorrect vtables in a const context: // - from issue 86132: a trait object with invalid alignment caused an ICE in const eval, and now // triggers an error // - a similar test that triggers a previously-untested const UB error: emitted close to the above // error, it checks the correctness of the size trait Trait {} const INVALID_VTABLE_ALIGNMENT: &dyn Trait = unsafe { std::mem::transmute((&92u8, &[0usize, 1usize, 1000usize])) }; //~^ ERROR any use of this value will cause an error //~| WARNING this was previously accepted by the compiler //~| invalid vtable: alignment `1000` is not a power of 2 const INVALID_VTABLE_SIZE: &dyn Trait = unsafe { std::mem::transmute((&92u8, &[1usize, usize::MAX, 1usize])) }; //~^ ERROR any use of this value will cause an error //~| WARNING this was previously accepted by the compiler //~| invalid vtable: size is bigger than largest supported object fn main() {} "} {"_id":"doc-en-rust-eb939a19e49b952dc1540073fe19ab848aa8da0ebdd3ad8232bf658912cd8d2c","title":"","text":" error: any use of this value will cause an error --> $DIR/ub-incorrect-vtable.rs:10:14 | LL | / const INVALID_VTABLE_ALIGNMENT: &dyn Trait = LL | | unsafe { std::mem::transmute((&92u8, &[0usize, 1usize, 1000usize])) }; | |______________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^__- | | | invalid vtable: alignment `1000` is not a power of 2 | = note: `#[deny(const_err)]` on by default = 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/ub-incorrect-vtable.rs:16:14 | LL | / const INVALID_VTABLE_SIZE: &dyn Trait = LL | | unsafe { std::mem::transmute((&92u8, &[1usize, usize::MAX, 1usize])) }; | |______________^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^__- | | | invalid vtable: size is bigger than largest supported object | = 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 2 previous errors "} {"_id":"doc-en-rust-25a8c66a11ab0c58ac13483b716892c8bb2f5f849723578429127a29a0a12558","title":"","text":"} w.write_str(\")\"); } w.write_str(\"
\"); w.write_str(\"\"); render_stability_since(w, variant, it, cx.tcx()); w.write_str(\"\"); document(w, cx, variant, Some(it)); document_non_exhaustive(w, variant);"} {"_id":"doc-en-rust-b15191dadc7bd96b16cc67e6018db217c9f81cba12dee22c93ca5eb3904dba95","title":"","text":"w.write_str(\"\"); toggle_close(w); } render_stability_since(w, variant, it, cx.tcx()); } } let def_id = it.def_id.expect_real();"} {"_id":"doc-en-rust-5bcf692d09aaddba6f0d366c404ed7afb36c39c411aaaecfa4b718e41aac90a4","title":"","text":"background: transparent; } .small-section-header { display: flex; justify-content: space-between; position: relative; } .small-section-header:hover > .anchor { display: initial; }"} {"_id":"doc-en-rust-a18e3c36493d2dd333d9d2ff8421c6b25b7960d03dc029a903425b46db87b5dc","title":"","text":"let sz_a = self.a.size(); if A::MAY_HAVE_SIDE_EFFECT && sz_a > self.len { for _ in 0..sz_a - self.len { self.a_len -= 1; self.a.next_back(); } self.a_len = self.len; debug_assert_eq!(self.a_len, self.len); } let sz_b = self.b.size(); if B::MAY_HAVE_SIDE_EFFECT && sz_b > self.len {"} {"_id":"doc-en-rust-c66d8a59e68e14a80dfc17f4a056742b4740ce7f3179aafd9e73ee88d9bff4b1","title":"","text":"} #[test] #[cfg(panic = \"unwind\")] fn test_zip_trusted_random_access_next_back_drop() { use std::panic::catch_unwind; use std::panic::AssertUnwindSafe; let mut counter = 0; let it = [42].iter().map(|e| { let c = counter; counter += 1; if c == 0 { panic!(\"bomb\"); } e }); let it2 = [(); 0].iter(); let mut zip = it.zip(it2); catch_unwind(AssertUnwindSafe(|| { zip.next_back(); })) .unwrap_err(); assert!(zip.next().is_none()); assert_eq!(counter, 1); } #[test] fn test_double_ended_zip() { let xs = [1, 2, 3, 4, 5, 6]; let ys = [1, 2, 3, 7];"} {"_id":"doc-en-rust-fcc3f0642d5cdeb4ff6602fa19deb87e4dea7bd39b0f38834d9ff38876426ec8","title":"","text":"use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; use crate::clean::{self, Attributes, AttributesExt, FakeDefId, GetDefId, ToSource}; use crate::clean::{ self, Attributes, AttributesExt, FakeDefId, GetDefId, NestedAttributesExt, ToSource, Type, }; use crate::core::DocContext; use crate::formats::item_type::ItemType;"} {"_id":"doc-en-rust-a1c6539819c0f1f94754b5a3eb686e9b97609f45881bc83b20dc50993772bef1","title":"","text":"if trait_.def_id() == tcx.lang_items().deref_trait() { super::build_deref_target_impls(cx, &trait_items, ret); } // Return if the trait itself or any types of the generic parameters are doc(hidden). let mut stack: Vec<&Type> = trait_.iter().collect(); stack.push(&for_); while let Some(ty) = stack.pop() { if let Some(did) = ty.def_id() { if cx.tcx.get_attrs(did).lists(sym::doc).has_word(sym::hidden) { return; } } if let Some(generics) = ty.generics() { stack.extend(generics); } } if let Some(trait_did) = trait_.def_id() { record_extern_trait(cx, trait_did); }"} {"_id":"doc-en-rust-69f74c843b11074cb3e52eb37d66176b49d13295b2bd4e83dc9d0568dcc0a8d3","title":"","text":" #[doc(hidden)] pub enum HiddenType {} #[doc(hidden)] pub trait HiddenTrait {} "} {"_id":"doc-en-rust-774193bed73449c1019171b0ee4f7b8294d2ef9c0ee5714baff0cac5eafb7e13","title":"","text":" // Issue #86448: test for cross-crate `doc(hidden)` #![crate_name = \"foo\"] // aux-build:cross-crate-hidden-impl-parameter.rs extern crate cross_crate_hidden_impl_parameter; pub use ::cross_crate_hidden_impl_parameter::{HiddenType, HiddenTrait}; // OK, not re-exported pub enum MyLibType {} // @!has foo/enum.MyLibType.html '//*[@id=\"impl-From%3CHiddenType%3E\"]' 'impl From for MyLibType' impl From for MyLibType { fn from(it: HiddenType) -> MyLibType { match it {} } } pub struct T(T); // @!has foo/enum.MyLibType.html '//*[@id=\"impl-From%3CT%3CT%3CT%3CT%3CHiddenType%3E%3E%3E%3E%3E\"]' 'impl From>>>> for MyLibType' impl From>>>> for MyLibType { fn from(it: T>>>) -> MyLibType { todo!() } } // @!has foo/enum.MyLibType.html '//*[@id=\"impl-HiddenTrait\"]' 'impl HiddenTrait for MyLibType' impl HiddenTrait for MyLibType {} // @!has foo/struct.T.html '//*[@id=\"impl-From%3CMyLibType%3E\"]' 'impl From for T>>>' impl From for T>>> { fn from(it: MyLibType) -> T>>> { match it {} } } "} {"_id":"doc-en-rust-124ae1d0d60ea6c4ed12e8cc4e8029ddb2e68c62bcbd6b226f0a095956db3c94","title":"","text":" // test for `doc(hidden)` with impl parameters in the same crate. #![crate_name = \"foo\"] #[doc(hidden)] pub enum HiddenType {} #[doc(hidden)] pub trait HiddenTrait {} pub enum MyLibType {} // @!has foo/enum.MyLibType.html '//*[@id=\"impl-From%3CHiddenType%3E\"]' 'impl From for MyLibType' impl From for MyLibType { fn from(it: HiddenType) -> MyLibType { match it {} } } pub struct T(T); // @!has foo/enum.MyLibType.html '//*[@id=\"impl-From%3CT%3CT%3CT%3CT%3CHiddenType%3E%3E%3E%3E%3E\"]' 'impl From>>>> for MyLibType' impl From>>>> for MyLibType { fn from(it: T>>>) -> MyLibType { todo!() } } // @!has foo/enum.MyLibType.html '//*[@id=\"impl-HiddenTrait\"]' 'impl HiddenTrait for MyLibType' impl HiddenTrait for MyLibType {} // @!has foo/struct.T.html '//*[@id=\"impl-From%3CMyLibType%3E\"]' 'impl From for T>>>' impl From for T>>> { fn from(it: MyLibType) -> T>>> { match it {} } } "} {"_id":"doc-en-rust-80db63f7230e0364f31e50644c315691199db602a11168ac82f04d07d3a9b015","title":"","text":" #![feature(generic_const_exprs, array_map)] #![allow(incomplete_features)] pub struct ConstCheck; pub trait True {} impl True for ConstCheck {} pub trait OrdesDec { type Newlen; type Output; fn pop(self) -> (Self::Newlen, Self::Output); } impl OrdesDec for [T; N] where ConstCheck<{N > 1}>: True, [T; N - 1]: Sized, { type Newlen = [T; N - 1]; type Output = T; fn pop(self) -> (Self::Newlen, Self::Output) { let mut iter = IntoIter::new(self); //~^ ERROR: failed to resolve: use of undeclared type `IntoIter` let end = iter.next_back().unwrap(); let new = [(); N - 1].map(move |()| iter.next().unwrap()); (new, end) } } fn main() {} "} {"_id":"doc-en-rust-3d36b0c86eaa451ed4de6846ff79ac5881996b5bae27ef66eeb1ad9d6c430631","title":"","text":" error[E0433]: failed to resolve: use of undeclared type `IntoIter` --> $DIR/issue-82956.rs:25:24 | LL | let mut iter = IntoIter::new(self); | ^^^^^^^^ not found in this scope | help: consider importing one of these items | LL | use std::array::IntoIter; | LL | use std::collections::binary_heap::IntoIter; | LL | use std::collections::btree_map::IntoIter; | LL | use std::collections::btree_set::IntoIter; | and 8 other candidates error: aborting due to previous error For more information about this error, try `rustc --explain E0433`. "} {"_id":"doc-en-rust-1edbef2b842405bc6c240faefad506c1a310ef325e8dd44b251b4a89748084c9","title":"","text":" #![allow(incomplete_features)] #![feature(generic_const_exprs)] trait Bar {} trait Foo<'a> { const N: usize; type Baz: Bar<{ Self::N }>; //~^ ERROR: unconstrained generic constant } fn main() {} "} {"_id":"doc-en-rust-8f1eff23e80d057508e90c5b2e4741b53f03d9913bfb10d516ab187c5ea05eaf","title":"","text":" error: unconstrained generic constant --> $DIR/issue-84659.rs:8:15 | LL | type Baz: Bar<{ Self::N }>; | ^^^^^^^^^^^^^^^^ | = help: try adding a `where` bound using this expression: `where [(); { Self::N }]:` error: aborting due to previous error "} {"_id":"doc-en-rust-323633d2dad9acd85b794dfa79cab92c92c7a421aa5b49c951c2532bfd62b3b3","title":"","text":" #![feature(generic_const_exprs)] #![allow(incomplete_features)] pub trait X { const Y: usize; } fn z(t: T) where T: X, [(); T::Y]: , { } fn unit_literals() { z(\" \"); //~^ ERROR: the trait bound `&str: X` is not satisfied } fn main() {} "} {"_id":"doc-en-rust-973f4c62afad2a9842a39b036d3beda418ddc71e3e0ed609aea3894368edbb5e","title":"","text":" error[E0277]: the trait bound `&str: X` is not satisfied --> $DIR/issue-86530.rs:16:7 | LL | z(\" \"); | ^^^ the trait `X` is not implemented for `&str` | note: required by a bound in `z` --> $DIR/issue-86530.rs:10:8 | LL | fn z(t: T) | - required by a bound in this LL | where LL | T: X, | ^ required by this bound in `z` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-e8d71d66efad36f420d1cef9afbeb8262eeb6214e5d4a8e4f321777247070517","title":"","text":" // run-pass #![feature(adt_const_params, generic_const_exprs)] #![allow(incomplete_features)] pub trait Foo { const ASSOC_C: usize; fn foo() where [(); Self::ASSOC_C]:; } struct Bar; impl Foo for Bar { const ASSOC_C: usize = 3; fn foo() where [u8; Self::ASSOC_C]: { let _: [u8; Self::ASSOC_C] = loop {}; } } fn main() {} "} {"_id":"doc-en-rust-a98ad518d78654e20609c6f4f2e40a9acc172f561fdba579babeaed622160349","title":"","text":" // run-pass #![feature(adt_const_params, generic_const_exprs)] #![allow(incomplete_features, unused_variables)] struct F; impl X for F<{ S }> { const W: usize = 3; fn d(r: &[u8; Self::W]) -> F<{ S }> { let x: [u8; Self::W] = [0; Self::W]; F } } pub trait X { const W: usize; fn d(r: &[u8; Self::W]) -> Self; } fn main() {} "} {"_id":"doc-en-rust-d075bb47fa22ddf187b0adae1ed35f9cfd926b6ff9d09c9a525f528dc02b9d9e","title":"","text":" trait Trait { const Assoc: usize; } impl Trait for () { const Assoc: usize = 1; } pub const fn foo() where (): Trait { let bar = [(); <()>::Assoc]; //~^ error: constant expression depends on a generic parameter } trait Trait2 { const Assoc2: usize; } impl Trait2 for () { const Assoc2: usize = N - 1; } pub const fn foo2() where (): Trait2 { let bar2 = [(); <()>::Assoc2]; //~^ error: constant expression depends on a generic parameter } fn main() { foo::<0>(); foo2::<0>(); } "} {"_id":"doc-en-rust-cde144b18ab3007439a4cf71bedc60c574325b681c092801c04971c6e90dc3be","title":"","text":" error: constant expression depends on a generic parameter --> $DIR/sneaky-array-repeat-expr.rs:11:20 | LL | let bar = [(); <()>::Assoc]; | ^^^^^^^^^^^ | = note: this may fail depending on what value the parameter takes error: constant expression depends on a generic parameter --> $DIR/sneaky-array-repeat-expr.rs:25:21 | LL | let bar2 = [(); <()>::Assoc2]; | ^^^^^^^^^^^^ | = note: this may fail depending on what value the parameter takes error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-78cbf5b791ecfc5f504438ca19ba526d1b78c1c2a699724902e092d3521788cb","title":"","text":"} macro_rules! tool_doc { ($tool: ident, $should_run: literal, $path: literal, [$($krate: literal),+ $(,)?] $(, binary=$bin:expr)?) => { ($tool: ident, $should_run: literal, $path: literal, [$($krate: literal),+ $(,)?], binary=$bin:expr) => { #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub struct $tool { stage: u32,"} {"_id":"doc-en-rust-021018f314009f23c7ec007d803f1a3e8aa61846d7bedad5e78010c2f1ed4081","title":"","text":"cargo.arg(\"-p\").arg($krate); )+ $(if !$bin { if !$bin { cargo.rustdocflag(\"--document-private-items\"); })? } cargo.rustdocflag(\"--enable-index-page\"); cargo.rustdocflag(\"--show-type-layout\"); cargo.rustdocflag(\"-Zunstable-options\");"} {"_id":"doc-en-rust-9fa021bc0d7fcbab60c78f42a2fd1cd2fa74425a9ea513b74719040c25e7006d","title":"","text":"} } tool_doc!(Rustdoc, \"rustdoc-tool\", \"src/tools/rustdoc\", [\"rustdoc\", \"rustdoc-json-types\"]); tool_doc!( Rustdoc, \"rustdoc-tool\", \"src/tools/rustdoc\", [\"rustdoc\", \"rustdoc-json-types\"], binary = false ); tool_doc!( Rustfmt, \"rustfmt-nightly\","} {"_id":"doc-en-rust-069c56408b2fc2e635ec069f5d541691adfff05b42de3164362af54f7c2096ad","title":"","text":"background: rgba(0, 0, 0, 0); } code { .docblock code { color: #ffb454; } h3 > code, h4 > code, h5 > code {"} {"_id":"doc-en-rust-e5e390d6a7ab1f30a3670b3b13882adacb691fb04ea60ffbe6b3041423f2a16e","title":"","text":" // The ayu theme has a different color for the \"\" tags in the doc blocks. We need to // check that the rule isn't applied on other \"\" elements. goto: file://|DOC_PATH|/test_docs/enum.AnEnum.html // We need to show the text, otherwise the colors aren't \"computed\" by the web browser. show-text: true // We set the theme to ayu. local-storage: {\"rustdoc-theme\": \"ayu\", \"rustdoc-preferred-dark-theme\": \"ayu\", \"rustdoc-use-system-theme\": \"false\"} // We reload to get the text appearing and the theme applied. reload: assert-css: (\".docblock code\", {\"color\": \"rgb(255, 180, 84)\"}, ALL) // It includes variants and the \"titles\" as well (for example: \"impl RefUnwindSafe for AnEnum\"). assert-css: (\"div:not(.docblock) > code\", {\"color\": \"rgb(197, 197, 197)\"}, ALL) "} {"_id":"doc-en-rust-779626d86012486311399d54a47ff9f6512db85764c385e1bb6c2e543bc839bd","title":"","text":"#[doc(cfg(unix))] pub fn replaced_function() {} /// Some doc with `code`! pub enum AnEnum { WithVariants { and: usize, sub: usize, variants: usize }, }"} {"_id":"doc-en-rust-9afb01f98e027cd8b50ca002652419e7e7207b30626cbe24fc73edb79f3c2078","title":"","text":" use crate::mem::{size_of, transmute_copy}; use crate::ptr::write_bytes; pub(super) trait SpecFill { fn spec_fill(&mut self, value: T); }"} {"_id":"doc-en-rust-5fae1dfa9e8cc170fbd029ae3e33adc368fb91c264078b7ad37e96220576473d","title":"","text":"impl SpecFill for [T] { fn spec_fill(&mut self, value: T) { if size_of::() == 1 { // SAFETY: The size_of check above ensures that values are 1 byte wide, as required // for the transmute and write_bytes unsafe { let value: u8 = transmute_copy(&value); write_bytes(self.as_mut_ptr(), value, self.len()); } } else { for item in self.iter_mut() { *item = value; } for item in self.iter_mut() { *item = value; } } }"} {"_id":"doc-en-rust-86b485e6433a802b077812c287a13eacf45733dd14abaef135afa68448176203","title":"","text":"use core::cell::Cell; use core::cmp::Ordering; use core::mem::MaybeUninit; use core::result::Result::{Err, Ok}; #[test]"} {"_id":"doc-en-rust-19db0a7674d17a4304fbe2430a24d8b69d5315226aab17c6872241d9f94101cb","title":"","text":"assert_eq!(x.get(), 1); } #[test] fn test_slice_fill_with_uninit() { // This should not UB. See #87891 let mut a = [MaybeUninit::::uninit(); 10]; a.fill(MaybeUninit::uninit()); } "} {"_id":"doc-en-rust-61476c907914973156625c7ea3d9adbb6ebc2b72eb825ef5b233a9185be448c7","title":"","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":"doc-en-rust-d756f1004d0524a0432aeefcc11c7704e03624a989a2f440007212f39b9d44fe","title":"","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":"doc-en-rust-a3b406c05809be011aa4d817d0c46523c70a528a22772c3fc6310aade58afd63","title":"","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":"doc-en-rust-2ce00ecc3647e9a2bb1e90b231f6149fd9c8c8d75958d2c1067dc983a6f7f49d","title":"","text":"//! normal visitor, which just walks the entire body in one shot, the //! `ExprUseVisitor` determines how expressions are being used. use hir::def::DefKind; // Export these here so that Clippy can use them. pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection};"} {"_id":"doc-en-rust-1e239a994c473a422327d05a6c4183475bc54724a7cd9c2cb8bd49cc0e6a5e8c","title":"","text":"use rustc_infer::infer::InferCtxt; use rustc_middle::hir::place::ProjectionKind; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty::{self, adjustment, TyCtxt}; use rustc_middle::ty::{self, adjustment, Ty, TyCtxt}; use rustc_target::abi::VariantIdx; use std::iter;"} {"_id":"doc-en-rust-c1b2847b0e115cb75be54a4c0bde9ec72f75f69ba9f200c5014731c368c40658","title":"","text":"needs_to_be_read = true; } } PatKind::TupleStruct(..) | PatKind::Path(..) | PatKind::Struct(..) | PatKind::Tuple(..) => { // If the PatKind is a TupleStruct, Path, Struct or Tuple then we want to check // whether the Variant is a MultiVariant or a SingleVariant. We only want // to borrow discr if it is a MultiVariant. // If it is a SingleVariant and creates a binding we will handle that when // this callback gets called again. // Get the type of the Place after all projections have been applied let place_ty = place.place.ty(); if let ty::Adt(def, _) = place_ty.kind() { if def.variants.len() > 1 { PatKind::Path(qpath) => { // A `Path` pattern is just a name like `Foo`. This is either a // named constant or else it refers to an ADT variant let res = self.mc.typeck_results.qpath_res(qpath, pat.hir_id); match res { Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => { // Named constants have to be equated with the value // being matched, so that's a read of the value being matched. // // FIXME: We don't actually reads for ZSTs. needs_to_be_read = true; } } else { // If it is not ty::Adt, then it should be read needs_to_be_read = true; _ => { // Otherwise, this is a struct/enum variant, and so it's // only a read if we need to read the discriminant. needs_to_be_read |= is_multivariant_adt(place.place.ty()); } } } PatKind::TupleStruct(..) | PatKind::Struct(..) | PatKind::Tuple(..) => { // For `Foo(..)`, `Foo { ... }` and `(...)` patterns, check if we are matching // against a multivariant enum or struct. In that case, we have to read // the discriminant. Otherwise this kind of pattern doesn't actually // read anything (we'll get invoked for the `...`, which may indeed // perform some reads). let place_ty = place.place.ty(); needs_to_be_read |= is_multivariant_adt(place_ty); } PatKind::Lit(_) | PatKind::Range(..) => { // If the PatKind is a Lit or a Range then we want // to borrow discr."} {"_id":"doc-en-rust-015a0461b67e9699916d2a9ebea425bc49cb912772287c3ffae27dc185f3d89c","title":"","text":"} } } fn is_multivariant_adt(ty: Ty<'tcx>) -> bool { if let ty::Adt(def, _) = ty.kind() { def.variants.len() > 1 } else { false } } "} {"_id":"doc-en-rust-e83882fd1e2886ecc403af4aaf9cc327f436015df3ba7f0ea3e0821adb1a1823","title":"","text":" // edition:2021 #[derive(Copy, Clone, PartialEq, Eq)] pub struct Opcode(pub u8); impl Opcode { pub const OP1: Opcode = Opcode(0x1); } pub fn example1(msg_type: Opcode) -> impl FnMut(&[u8]) { move |i| match msg_type { //~^ ERROR: non-exhaustive patterns: `Opcode(0_u8)` and `Opcode(2_u8..=u8::MAX)` not covered Opcode::OP1 => unimplemented!(), } } #[derive(Copy, Clone, PartialEq, Eq)] pub struct Opcode2(Opcode); impl Opcode2 { pub const OP2: Opcode2 = Opcode2(Opcode(0x1)); } pub fn example2(msg_type: Opcode2) -> impl FnMut(&[u8]) { move |i| match msg_type { //~^ ERROR: non-exhaustive patterns: `Opcode2(Opcode(0_u8))` and `Opcode2(Opcode(2_u8..=u8::MAX))` not covered Opcode2::OP2=> unimplemented!(), } } fn main() {} "} {"_id":"doc-en-rust-0e98ec751286bc99745c24e3d01954b6f3cc8eb71ab700f2a8cd51c083c2cf21","title":"","text":" error[E0004]: non-exhaustive patterns: `Opcode(0_u8)` and `Opcode(2_u8..=u8::MAX)` not covered --> $DIR/issue-88331.rs:11:20 | LL | pub struct Opcode(pub u8); | -------------------------- `Opcode` defined here ... LL | move |i| match msg_type { | ^^^^^^^^ patterns `Opcode(0_u8)` and `Opcode(2_u8..=u8::MAX)` not covered | = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms = note: the matched value is of type `Opcode` error[E0004]: non-exhaustive patterns: `Opcode2(Opcode(0_u8))` and `Opcode2(Opcode(2_u8..=u8::MAX))` not covered --> $DIR/issue-88331.rs:27:20 | LL | pub struct Opcode2(Opcode); | --------------------------- `Opcode2` defined here ... LL | move |i| match msg_type { | ^^^^^^^^ patterns `Opcode2(Opcode(0_u8))` and `Opcode2(Opcode(2_u8..=u8::MAX))` not covered | = help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms = note: the matched value is of type `Opcode2` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0004`. "} {"_id":"doc-en-rust-f88bbe6a0a7e78f05292ee59f771af8d91c62c4cb7b6aeab84a155d2ed967537","title":"","text":"use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts}; use rustc_middle::ty::{self, adjustment::PointerCast, Instance, InstanceDef, Ty, TyCtxt}; use rustc_middle::ty::{Binder, TraitPredicate, TraitRef}; use rustc_span::{sym, Span, Symbol};"} {"_id":"doc-en-rust-9c14511ea9da651d44722a0e563ef4ddce886ae60caaa968709c8ec95221c239","title":"","text":"let fn_ty = func.ty(body, tcx); let (mut callee, substs) = match *fn_ty.kind() { let (mut callee, mut substs) = match *fn_ty.kind() { ty::FnDef(def_id, substs) => (def_id, substs), ty::FnPtr(_) => {"} {"_id":"doc-en-rust-c4c151210de14a309a5485fe13923906c40391442d12f64c7fd6250f357eef27","title":"","text":".iter() .find(|did| tcx.item_name(**did) == callee_name) { // using internal substs is ok here, since this is only // used for the `resolve` call below substs = InternalSubsts::identity_for_item(tcx, did); callee = did; } } _ => { if !tcx.is_const_fn_raw(callee) { // At this point, it is only legal when the caller is marked with // #[default_method_body_is_const], and the callee is in the same // trait. let callee_trait = tcx.trait_of_item(callee); if callee_trait.is_some() { if tcx.has_attr(caller, sym::default_method_body_is_const) { if tcx.trait_of_item(caller) == callee_trait { nonconst_call_permission = true; } _ if !tcx.is_const_fn_raw(callee) => { // At this point, it is only legal when the caller is marked with // #[default_method_body_is_const], and the callee is in the same // trait. let callee_trait = tcx.trait_of_item(callee); if callee_trait.is_some() { if tcx.has_attr(caller, sym::default_method_body_is_const) { if tcx.trait_of_item(caller) == callee_trait { nonconst_call_permission = true; } } } if !nonconst_call_permission { self.check_op(ops::FnCallNonConst); return; } if !nonconst_call_permission { self.check_op(ops::FnCallNonConst); return; } } _ => {} } // Resolve a trait method call to its concrete implementation, which may be in a"} {"_id":"doc-en-rust-e02f5a9ed7d62a3711cca9cc237e9c2e46df05ce09178d41f617ac67b101a216","title":"","text":" // build-pass #![feature(const_trait_impl)] trait Func { type Output; fn call_once(self, arg: T) -> Self::Output; } struct Closure; impl const Func<&usize> for Closure { type Output = usize; fn call_once(self, arg: &usize) -> Self::Output { *arg } } enum Bug { V(T), } fn main() {} "} {"_id":"doc-en-rust-4622f0cc52caeac218c1114fa3a8ffbd3d6f5b74b3dec61b1495c2d21e49f046","title":"","text":" Subproject commit 7a2f1cadcd5120c44eda3596053de767cd8173a2 Subproject commit 035933186957cf81c488261fb48a98bf523e8006 "} {"_id":"doc-en-rust-55da55ff6fab86ba975a42c259c59fa5b8e67bfb368fbada0083a2dc95ccb3d5","title":"","text":"//! Enforces the Rust effect system. Currently there is just one effect, /// `unsafe`. use middle::ty::{ty_bare_fn, ty_closure, ty_ptr}; use middle::ty; use middle::typeck::method_map; use util::ppaux; use syntax::ast::{UnDeref, ExprCall, ExprInlineAsm, ExprMethodCall}; use syntax::ast::{ExprUnary, unsafe_fn, ExprPath}; use syntax::ast; use syntax::codemap::Span; use syntax::visit::{fk_item_fn, fk_method}; use syntax::visit; use syntax::visit::{Visitor,fn_kind}; use syntax::ast::{fn_decl,Block,NodeId,Expr}; use syntax::visit::Visitor; #[deriving(Eq)] enum UnsafeContext {"} {"_id":"doc-en-rust-2dbfbeb3c3191487a9dfc8b8bfc3c16248641892f3a38049d078997d7fd6deb0","title":"","text":"UnsafeBlock(ast::NodeId), } struct Context { /// The method map. method_map: method_map, /// Whether we're in an unsafe context. unsafe_context: UnsafeContext, } fn type_is_unsafe_function(ty: ty::t) -> bool { match ty::get(ty).sty { ty_bare_fn(ref f) => f.purity == unsafe_fn, ty_closure(ref f) => f.purity == unsafe_fn, ty::ty_bare_fn(ref f) => f.purity == ast::unsafe_fn, ty::ty_closure(ref f) => f.purity == ast::unsafe_fn, _ => false, } } struct EffectCheckVisitor { tcx: ty::ctxt, context: @mut Context, /// The method map. method_map: method_map, /// Whether we're in an unsafe context. unsafe_context: UnsafeContext, } impl EffectCheckVisitor { fn require_unsafe(&mut self, span: Span, description: &str) { match self.context.unsafe_context { match self.unsafe_context { SafeContext => { // Report an error. self.tcx.sess.span_err(span,"} {"_id":"doc-en-rust-b1bc5baa3bcd3a41153f3813f2b3f00759529310406764afaf5e9fedc9adb418","title":"","text":"UnsafeFn => {} } } fn check_str_index(&mut self, e: @ast::Expr) { let base_type = match e.node { ast::ExprIndex(_, base, _) => ty::node_id_to_type(self.tcx, base.id), _ => return }; debug2!(\"effect: checking index with base type {}\", ppaux::ty_to_str(self.tcx, base_type)); match ty::get(base_type).sty { ty::ty_estr(*) => { self.tcx.sess.span_err(e.span, \"modification of string types is not allowed\"); } _ => {} } } } impl Visitor<()> for EffectCheckVisitor { fn visit_fn(&mut self, fn_kind:&fn_kind, fn_decl:&fn_decl, block:&Block, span:Span, node_id:NodeId, _:()) { let (is_item_fn, is_unsafe_fn) = match *fn_kind { fk_item_fn(_, _, purity, _) => (true, purity == unsafe_fn), fk_method(_, _, method) => (true, method.purity == unsafe_fn), _ => (false, false), }; let old_unsafe_context = self.context.unsafe_context; if is_unsafe_fn { self.context.unsafe_context = UnsafeFn } else if is_item_fn { self.context.unsafe_context = SafeContext } fn visit_fn(&mut self, fn_kind: &visit::fn_kind, fn_decl: &ast::fn_decl, block: &ast::Block, span: Span, node_id: ast::NodeId, _:()) { let (is_item_fn, is_unsafe_fn) = match *fn_kind { visit::fk_item_fn(_, _, purity, _) => (true, purity == ast::unsafe_fn), visit::fk_method(_, _, method) => (true, method.purity == ast::unsafe_fn), _ => (false, false), }; let old_unsafe_context = self.unsafe_context; if is_unsafe_fn { self.unsafe_context = UnsafeFn } else if is_item_fn { self.unsafe_context = SafeContext } visit::walk_fn(self, fn_kind, fn_decl, block, span, node_id, ()); visit::walk_fn(self, fn_kind, fn_decl, block, span, node_id, ()); self.context.unsafe_context = old_unsafe_context self.unsafe_context = old_unsafe_context } fn visit_block(&mut self, block:&Block, _:()) { let old_unsafe_context = self.context.unsafe_context; let is_unsafe = match block.rules { ast::UnsafeBlock(*) => true, ast::DefaultBlock => false }; if is_unsafe && self.context.unsafe_context == SafeContext { self.context.unsafe_context = UnsafeBlock(block.id) } fn visit_block(&mut self, block: &ast::Block, _:()) { let old_unsafe_context = self.unsafe_context; let is_unsafe = match block.rules { ast::UnsafeBlock(*) => true, ast::DefaultBlock => false }; if is_unsafe && self.unsafe_context == SafeContext { self.unsafe_context = UnsafeBlock(block.id) } visit::walk_block(self, block, ()); visit::walk_block(self, block, ()); self.context.unsafe_context = old_unsafe_context self.unsafe_context = old_unsafe_context } fn visit_expr(&mut self, expr:@Expr, _:()) { match expr.node { ExprMethodCall(callee_id, _, _, _, _, _) => { let base_type = ty::node_id_to_type(self.tcx, callee_id); debug2!(\"effect: method call case, base type is {}\", ppaux::ty_to_str(self.tcx, base_type)); if type_is_unsafe_function(base_type) { self.require_unsafe(expr.span, \"invocation of unsafe method\") } fn visit_expr(&mut self, expr: @ast::Expr, _:()) { match expr.node { ast::ExprMethodCall(callee_id, _, _, _, _, _) => { let base_type = ty::node_id_to_type(self.tcx, callee_id); debug2!(\"effect: method call case, base type is {}\", ppaux::ty_to_str(self.tcx, base_type)); if type_is_unsafe_function(base_type) { self.require_unsafe(expr.span, \"invocation of unsafe method\") } ExprCall(base, _, _) => { let base_type = ty::node_id_to_type(self.tcx, base.id); debug2!(\"effect: call case, base type is {}\", ppaux::ty_to_str(self.tcx, base_type)); if type_is_unsafe_function(base_type) { self.require_unsafe(expr.span, \"call to unsafe function\") } } ast::ExprCall(base, _, _) => { let base_type = ty::node_id_to_type(self.tcx, base.id); debug2!(\"effect: call case, base type is {}\", ppaux::ty_to_str(self.tcx, base_type)); if type_is_unsafe_function(base_type) { self.require_unsafe(expr.span, \"call to unsafe function\") } ExprUnary(_, UnDeref, base) => { let base_type = ty::node_id_to_type(self.tcx, base.id); debug2!(\"effect: unary case, base type is {}\", ppaux::ty_to_str(self.tcx, base_type)); match ty::get(base_type).sty { ty_ptr(_) => { self.require_unsafe(expr.span, \"dereference of unsafe pointer\") } _ => {} } ast::ExprUnary(_, ast::UnDeref, base) => { let base_type = ty::node_id_to_type(self.tcx, base.id); debug2!(\"effect: unary case, base type is {}\", ppaux::ty_to_str(self.tcx, base_type)); match ty::get(base_type).sty { ty::ty_ptr(_) => { self.require_unsafe(expr.span, \"dereference of unsafe pointer\") } _ => {} } ExprInlineAsm(*) => { self.require_unsafe(expr.span, \"use of inline assembly\") } ExprPath(*) => { match ty::resolve_expr(self.tcx, expr) { ast::DefStatic(_, true) => { self.require_unsafe(expr.span, \"use of mutable static\") } _ => {} } ast::ExprAssign(base, _) | ast::ExprAssignOp(_, _, base, _) => { self.check_str_index(base); } ast::ExprAddrOf(ast::MutMutable, base) => { self.check_str_index(base); } ast::ExprInlineAsm(*) => { self.require_unsafe(expr.span, \"use of inline assembly\") } ast::ExprPath(*) => { match ty::resolve_expr(self.tcx, expr) { ast::DefStatic(_, true) => { self.require_unsafe(expr.span, \"use of mutable static\") } _ => {} } _ => {} } _ => {} } visit::walk_expr(self, expr, ()); visit::walk_expr(self, expr, ()); } } pub fn check_crate(tcx: ty::ctxt, method_map: method_map, crate: &ast::Crate) { let context = @mut Context { method_map: method_map, unsafe_context: SafeContext, }; let mut visitor = EffectCheckVisitor { tcx: tcx, context: context, method_map: method_map, unsafe_context: SafeContext, }; visit::walk_crate(&mut visitor, crate, ());"} {"_id":"doc-en-rust-59c3d29abc75413ffe359f4ae91c28873c1df69b38e361198bc3397e945080b3","title":"","text":" // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let mut s = ~\"test\"; s[0] = 3; //~ ERROR: not allowed s[0] += 3; //~ ERROR: not allowed { let _a = &mut s[0]; //~ ERROR: not allowed } } "} {"_id":"doc-en-rust-9f0119031c9d620cbcea28fb07b638038f6e3eb7b5ad7dcb5819292030e05dce","title":"","text":" // check-fail // edition:2021 // known-bug: #88908 // This should pass, but seems to run into a TAIT bug. #![feature(type_alias_impl_trait)] use std::future::Future; trait Stream { type Item; } struct Empty(T); impl Stream for Empty { type Item = (); } fn empty() -> Empty { todo!() } trait X { type LineStream<'a, Repr>: Stream where Self: 'a; type LineStreamFut<'a,Repr>: Future> where Self: 'a; fn line_stream<'a,Repr>(&'a self) -> Self::LineStreamFut<'a,Repr>; } struct Y; impl X for Y { type LineStream<'a, Repr> = impl Stream; type LineStreamFut<'a, Repr> = impl Future> ; fn line_stream<'a, Repr>(&'a self) -> Self::LineStreamFut<'a, Repr> { async {empty()} } } fn main() {} "} {"_id":"doc-en-rust-117ead81c5c5a12b2cc0a204e022a8c2aa81e16d804408a33d1ca50e958d83dc","title":"","text":" error[E0271]: type mismatch resolving ` as Stream>::Item == Repr` --> $DIR/issue-89008.rs:38:43 | LL | fn line_stream<'a, Repr>(&'a self) -> Self::LineStreamFut<'a, Repr> { | ---- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type mismatch resolving ` as Stream>::Item == Repr` | | | this type parameter | note: expected this to be `()` --> $DIR/issue-89008.rs:17:17 | LL | type Item = (); | ^^ = note: expected unit type `()` found type parameter `Repr` error: aborting due to previous error For more information about this error, try `rustc --explain E0271`. "} {"_id":"doc-en-rust-5df07c8f9f4f01305e295e3d1d70eada1fe7beeace4b01e7cc636ef4b27e1e41","title":"","text":" // check-pass // edition:2021 #![feature(type_alias_impl_trait)] use std::future::Future; use std::marker::PhantomData; trait Stream { type Item; } struct Empty { _phantom: PhantomData, } impl Stream for Empty { type Item = T; } trait X { type LineStream<'a, Repr>: Stream where Self: 'a; type LineStreamFut<'a, Repr>: Future> where Self: 'a; fn line_stream<'a, Repr>(&'a self) -> Self::LineStreamFut<'a, Repr>; } struct Y; impl X for Y { type LineStream<'a, Repr> = impl Stream; type LineStreamFut<'a, Repr> = impl Future>; fn line_stream<'a, Repr>(&'a self) -> Self::LineStreamFut<'a, Repr> { async { Empty { _phantom: PhantomData } } } } fn main() {} "} {"_id":"doc-en-rust-6ebc07dd5f1a47b6e1640c37afaa1f6499c6e2dffa77ed7dee21ff9a81c1eed0","title":"","text":"} else if nanos >= MAX_NANOS_F64 { Err(FromSecsError { kind: FromSecsErrorKind::Overflow }) } else if nanos < 0.0 { Err(FromSecsError { kind: FromSecsErrorKind::Underflow }) Err(FromSecsError { kind: FromSecsErrorKind::Negative }) } else { let nanos = nanos as u128; Ok(Duration {"} {"_id":"doc-en-rust-8b181e9686e970643be5e8458b1ae983a221b80057b4751a1061dcfa69bad2ec","title":"","text":"} else if nanos >= MAX_NANOS_F32 { Err(FromSecsError { kind: FromSecsErrorKind::Overflow }) } else if nanos < 0.0 { Err(FromSecsError { kind: FromSecsErrorKind::Underflow }) Err(FromSecsError { kind: FromSecsErrorKind::Negative }) } else { let nanos = nanos as u128; Ok(Duration {"} {"_id":"doc-en-rust-d5c1975631613c2919a7e47b67408aa41c14a3aab8fab4234286a05d5cfb688a","title":"","text":"impl FromSecsError { const fn description(&self) -> &'static str { match self.kind { FromSecsErrorKind::NonFinite => { \"got non-finite value when converting float to duration\" } FromSecsErrorKind::NonFinite => \"non-finite value when converting float to duration\", FromSecsErrorKind::Overflow => \"overflow when converting float to duration\", FromSecsErrorKind::Underflow => \"underflow when converting float to duration\", FromSecsErrorKind::Negative => \"negative value when converting float to duration\", } } }"} {"_id":"doc-en-rust-f7a0910fac3ca91afd43db569b966265b7c9d5916c518777e157d626dc22f9c1","title":"","text":"#[derive(Debug, Clone, PartialEq, Eq)] enum FromSecsErrorKind { // Value is not a finite value (either infinity or NaN). // Value is not a finite value (either + or - infinity or NaN). NonFinite, // Value is too large to store in a `Duration`. Overflow, // Value is less than `0.0`. Underflow, // Value is negative. Negative, }"} {"_id":"doc-en-rust-b37fb7c69eb1874b8b628c230faf71b0c5face75c8d42700b2a46cc5c07dbe8c","title":"","text":"} } /// Converts inline const patterns. fn lower_inline_const( &mut self, anon_const: &'tcx hir::AnonConst, id: hir::HirId, span: Span, ) -> PatKind<'tcx> { let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id); let value = ty::Const::from_inline_const(self.tcx, anon_const_def_id); // Evaluate early like we do in `lower_path`. let value = value.eval(self.tcx, self.param_env); match value.val { ConstKind::Param(_) => { self.errors.push(PatternError::ConstParamInPattern(span)); return PatKind::Wild; } ConstKind::Unevaluated(_) => { // If we land here it means the const can't be evaluated because it's `TooGeneric`. self.tcx.sess.span_err(span, \"constant pattern depends on a generic parameter\"); return PatKind::Wild; } _ => (), } *self.const_to_pat(value, id, span, false).kind } /// Converts literals, paths and negation of literals to patterns. /// The special case for negation exists to allow things like `-128_i8` /// which would overflow if we tried to evaluate `128_i8` and then negate /// afterwards. fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> { if let hir::ExprKind::Path(ref qpath) = expr.kind { *self.lower_path(qpath, expr.hir_id, expr.span).kind } else { let (lit, neg) = match expr.kind { hir::ExprKind::ConstBlock(ref anon_const) => { let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id); let value = ty::Const::from_inline_const(self.tcx, anon_const_def_id); if matches!(value.val, ConstKind::Param(_)) { let span = self.tcx.hir().span(anon_const.hir_id); self.errors.push(PatternError::ConstParamInPattern(span)); return PatKind::Wild; } return *self.const_to_pat(value, expr.hir_id, expr.span, false).kind; } hir::ExprKind::Lit(ref lit) => (lit, false), hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => { let lit = match expr.kind { hir::ExprKind::Lit(ref lit) => lit, _ => span_bug!(expr.span, \"not a literal: {:?}\", expr), }; (lit, true) } _ => span_bug!(expr.span, \"not a literal: {:?}\", expr), }; let lit_input = LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg }; match self.tcx.at(expr.span).lit_to_const(lit_input) { Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span, false).kind, Err(LitToConstError::Reported) => PatKind::Wild, Err(LitToConstError::TypeError) => bug!(\"lower_lit: had type error\"), let (lit, neg) = match expr.kind { hir::ExprKind::Path(ref qpath) => { return *self.lower_path(qpath, expr.hir_id, expr.span).kind; } hir::ExprKind::ConstBlock(ref anon_const) => { return self.lower_inline_const(anon_const, expr.hir_id, expr.span); } hir::ExprKind::Lit(ref lit) => (lit, false), hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => { let lit = match expr.kind { hir::ExprKind::Lit(ref lit) => lit, _ => span_bug!(expr.span, \"not a literal: {:?}\", expr), }; (lit, true) } _ => span_bug!(expr.span, \"not a literal: {:?}\", expr), }; let lit_input = LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg }; match self.tcx.at(expr.span).lit_to_const(lit_input) { Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span, false).kind, Err(LitToConstError::Reported) => PatKind::Wild, Err(LitToConstError::TypeError) => bug!(\"lower_lit: had type error\"), } } }"} {"_id":"doc-en-rust-a191343f7dba2dc988c375d2003b134c5d831e2cda02d5259c6e768315db9a6a","title":"","text":"#![allow(incomplete_features)] #![feature(inline_const_pat)] #![feature(generic_const_exprs)] // rust-lang/rust#82518: ICE with inline-const in match referencing const-generic parameter fn foo() { match 0 { const { V } => {}, //~^ ERROR const parameters cannot be referenced in patterns [E0158] _ => {}, } match 0 { const { V } => {}, //~^ ERROR const parameters cannot be referenced in patterns [E0158] _ => {}, } } const fn f(x: usize) -> usize { x + 1 } fn bar() where [(); f(V)]: { match 0 { const { f(V) } => {}, //~^ ERROR constant pattern depends on a generic parameter //~| ERROR constant pattern depends on a generic parameter _ => {}, } } fn main() { foo::<1>(); bar::<1>(); }"} {"_id":"doc-en-rust-67db935557abcadc686e40aac0e3f323c3e2be9940e061cbf0d4617a4f3863e5","title":"","text":"error[E0158]: const parameters cannot be referenced in patterns --> $DIR/const-match-pat-generic.rs:8:11 --> $DIR/const-match-pat-generic.rs:9:9 | LL | const { V } => {}, | ^^^^^ LL | const { V } => {}, | ^^^^^^^^^^^ error: aborting due to previous error error: constant pattern depends on a generic parameter --> $DIR/const-match-pat-generic.rs:21:9 | LL | const { f(V) } => {}, | ^^^^^^^^^^^^^^ error: constant pattern depends on a generic parameter --> $DIR/const-match-pat-generic.rs:21:9 | LL | const { f(V) } => {}, | ^^^^^^^^^^^^^^ error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0158`."} {"_id":"doc-en-rust-2a6d904ceec2ffebd7abd2c0ed151aff6ea10fd1e69ecd4c6b19f836377a2693","title":"","text":"drop(linker); save_temp_bitcode(cgcx, &module, \"lto.input\"); // Fat LTO also suffers from the invalid DWARF issue similar to Thin LTO. // Here we rewrite all `DICompileUnit` pointers if there is only one `DICompileUnit`. // This only works around the problem when codegen-units = 1. // Refer to the comments in the `optimize_thin_module` function for more details. let mut cu1 = ptr::null_mut(); let mut cu2 = ptr::null_mut(); unsafe { llvm::LLVMRustLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2) }; if !cu2.is_null() { let _timer = cgcx.prof.generic_activity_with_arg(\"LLVM_fat_lto_patch_debuginfo\", &*module.name); unsafe { llvm::LLVMRustLTOPatchDICompileUnit(llmod, cu1) }; save_temp_bitcode(cgcx, &module, \"fat-lto-after-patch\"); } // Internalize everything below threshold to help strip out more modules and such. unsafe { let ptr = symbols_below_threshold.as_ptr();"} {"_id":"doc-en-rust-b3d13bc3eadf9a1ddcdc485b665d4cb77efb4d7aff96596a39cc08697699471d","title":"","text":"// an error. let mut cu1 = ptr::null_mut(); let mut cu2 = ptr::null_mut(); llvm::LLVMRustLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2); llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2); if !cu2.is_null() { let msg = \"multiple source DICompileUnits found\"; return Err(write::llvm_err(&diag_handler, msg));"} {"_id":"doc-en-rust-b39f41b4f66cc6f307549d2371cf183c592c5d8b908e0fd293a9e9bcbe838eab","title":"","text":"let _timer = cgcx .prof .generic_activity_with_arg(\"LLVM_thin_lto_patch_debuginfo\", thin_module.name()); llvm::LLVMRustLTOPatchDICompileUnit(llmod, cu1); llvm::LLVMRustThinLTOPatchDICompileUnit(llmod, cu1); save_temp_bitcode(cgcx, &module, \"thin-lto-after-patch\"); }"} {"_id":"doc-en-rust-f4fd6c6fc4b346af478189a7c8279f2712b77693df30e408c7a9e0b774e88d3b","title":"","text":"len: usize, out_len: &mut usize, ) -> *const u8; pub fn LLVMRustLTOGetDICompileUnit(M: &Module, CU1: &mut *mut c_void, CU2: &mut *mut c_void); pub fn LLVMRustLTOPatchDICompileUnit(M: &Module, CU: *mut c_void); pub fn LLVMRustThinLTOGetDICompileUnit( M: &Module, CU1: &mut *mut c_void, CU2: &mut *mut c_void, ); pub fn LLVMRustThinLTOPatchDICompileUnit(M: &Module, CU: *mut c_void); pub fn LLVMRustLinkerNew(M: &Module) -> &mut Linker<'_>; pub fn LLVMRustLinkerAdd("} {"_id":"doc-en-rust-a66a9cd17ecbf7c06eeb0682b68161462df2ba21d4ccbfecf71db67a6ebb91ee","title":"","text":"// Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See // the comment in `back/lto.rs` for why this exists. extern \"C\" void LLVMRustLTOGetDICompileUnit(LLVMModuleRef Mod, LLVMRustThinLTOGetDICompileUnit(LLVMModuleRef Mod, DICompileUnit **A, DICompileUnit **B) { Module *M = unwrap(Mod);"} {"_id":"doc-en-rust-adb95aba9e0fa50eb9c3a1bbb28edd34a3e06f561800a4edf89581fac9a81769","title":"","text":"// Rewrite all `DICompileUnit` pointers to the `DICompileUnit` specified. See // the comment in `back/lto.rs` for why this exists. extern \"C\" void LLVMRustLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) { LLVMRustThinLTOPatchDICompileUnit(LLVMModuleRef Mod, DICompileUnit *Unit) { Module *M = unwrap(Mod); // If the original source module didn't have a `DICompileUnit` then try to"} {"_id":"doc-en-rust-0b1c56414ccc1ac8480321f9cb132caf24c63ce1845440ef0cf4045c4d2ae65d","title":"","text":" // Caveat - gdb doesn't know about UTF-32 character encoding and will print a // rust char as only its numerical value. // min-lldb-version: 310 // min-gdb-version: 8.0 // no-prefer-dynamic // compile-flags:-g -C lto // gdb-command:run // gdbg-command:print 'basic_types_globals::B' // gdbr-command:print B // gdb-check:$1 = false // gdbg-command:print 'basic_types_globals::I' // gdbr-command:print I // gdb-check:$2 = -1 // gdbg-command:print 'basic_types_globals::C' // gdbr-command:print C // gdbg-check:$3 = 97 // gdbr-check:$3 = 97 // gdbg-command:print/d 'basic_types_globals::I8' // gdbr-command:print I8 // gdb-check:$4 = 68 // gdbg-command:print 'basic_types_globals::I16' // gdbr-command:print I16 // gdb-check:$5 = -16 // gdbg-command:print 'basic_types_globals::I32' // gdbr-command:print I32 // gdb-check:$6 = -32 // gdbg-command:print 'basic_types_globals::I64' // gdbr-command:print I64 // gdb-check:$7 = -64 // gdbg-command:print 'basic_types_globals::U' // gdbr-command:print U // gdb-check:$8 = 1 // gdbg-command:print/d 'basic_types_globals::U8' // gdbr-command:print U8 // gdb-check:$9 = 100 // gdbg-command:print 'basic_types_globals::U16' // gdbr-command:print U16 // gdb-check:$10 = 16 // gdbg-command:print 'basic_types_globals::U32' // gdbr-command:print U32 // gdb-check:$11 = 32 // gdbg-command:print 'basic_types_globals::U64' // gdbr-command:print U64 // gdb-check:$12 = 64 // gdbg-command:print 'basic_types_globals::F32' // gdbr-command:print F32 // gdb-check:$13 = 2.5 // gdbg-command:print 'basic_types_globals::F64' // gdbr-command:print F64 // gdb-check:$14 = 3.5 // gdb-command:continue #![allow(unused_variables)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] // N.B. These are `mut` only so they don't constant fold away. static mut B: bool = false; static mut I: isize = -1; static mut C: char = 'a'; static mut I8: i8 = 68; static mut I16: i16 = -16; static mut I32: i32 = -32; static mut I64: i64 = -64; static mut U: usize = 1; static mut U8: u8 = 100; static mut U16: u16 = 16; static mut U32: u32 = 32; static mut U64: u64 = 64; static mut F32: f32 = 2.5; static mut F64: f64 = 3.5; fn main() { _zzz(); // #break let a = unsafe { (B, I, C, I8, I16, I32, I64, U, U8, U16, U32, U64, F32, F64) }; } fn _zzz() {()} "} {"_id":"doc-en-rust-ffc43e213caa2517aa26928d43a074cf569a12daa9ca70af94abdd7609c3ab8b","title":"","text":" // Caveats - gdb prints any 8-bit value (meaning rust I8 and u8 values) // as its numerical value along with its associated ASCII char, there // doesn't seem to be any way around this. Also, gdb doesn't know // about UTF-32 character encoding and will print a rust char as only // its numerical value. // Caveat - gdb doesn't know about UTF-32 character encoding and will print a // rust char as only its numerical value. // min-lldb-version: 310 // ignore-gdb // Test temporarily ignored due to debuginfo tests being disabled, see PR 47155 // min-gdb-version: 8.0 // compile-flags:-g // gdb-command:run"} {"_id":"doc-en-rust-0303d5a48184cfb521da65851cd5d6ff81624372cc1a430bd1b7aca77c50cc7c","title":"","text":"// gdbg-command:print 'basic_types_globals::C' // gdbr-command:print C // gdbg-check:$3 = 97 // gdbr-check:$3 = 97 'a' // gdbr-check:$3 = 97 // gdbg-command:print/d 'basic_types_globals::I8' // gdbr-command:print I8 // gdb-check:$4 = 68"} {"_id":"doc-en-rust-ab398cc53b42b83ad70252de08f37f5c2df96a08e7627b94c35b3585b6ba384b","title":"","text":"}) .enumerate() .map(|(i, r)| match r { Err(TypeError::Sorts(exp_found)) => Err(TypeError::ArgumentSorts(exp_found, i)), Err(TypeError::Mutability) => Err(TypeError::ArgumentMutability(i)), Err(TypeError::Sorts(exp_found) | TypeError::ArgumentSorts(exp_found, _)) => { Err(TypeError::ArgumentSorts(exp_found, i)) } Err(TypeError::Mutability | TypeError::ArgumentMutability(_)) => { Err(TypeError::ArgumentMutability(i)) } r => r, }); Ok(ty::FnSig {"} {"_id":"doc-en-rust-ef511aecaf468683b40d1252aad91f96b85808ed692258a9b6befbe5ac9e42a5","title":"","text":"Ok(()) } #[instrument(level = \"debug\", skip(infcx))] fn extract_spans_for_error_reporting<'a, 'tcx>( infcx: &infer::InferCtxt<'a, 'tcx>, terr: &TypeError<'_>,"} {"_id":"doc-en-rust-e44d99c9e811f58d29e5b8a21da2c30f29949d66d4479c0ff43729d9250f5da1","title":"","text":" pub struct A; impl From for A { fn from(_: fn((), (), &mut ())) -> Self { //~^ error: method `from` has an incompatible type for trait loop {} } } pub struct B; impl From for B { fn from(_: fn((), (), u64)) -> Self { //~^ error: method `from` has an incompatible type for trait loop {} } } fn main() {} "} {"_id":"doc-en-rust-7487aef8f9d1843a1ba25fcdfd1b035427fdecaff4557cbe864478b899f9c369","title":"","text":" error[E0053]: method `from` has an incompatible type for trait --> $DIR/issue-90444.rs:3:16 | LL | fn from(_: fn((), (), &mut ())) -> Self { | ^^^^^^^^^^^^^^^^^^^ | | | types differ in mutability | help: change the parameter type to match the trait: `for<'r> fn((), (), &'r ())` | = note: expected fn pointer `fn(for<'r> fn((), (), &'r ())) -> A` found fn pointer `fn(for<'r> fn((), (), &'r mut ())) -> A` error[E0053]: method `from` has an incompatible type for trait --> $DIR/issue-90444.rs:11:16 | LL | fn from(_: fn((), (), u64)) -> Self { | ^^^^^^^^^^^^^^^ | | | expected `u32`, found `u64` | help: change the parameter type to match the trait: `fn((), (), u32)` | = note: expected fn pointer `fn(fn((), (), u32)) -> B` found fn pointer `fn(fn((), (), u64)) -> B` error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0053`. "} {"_id":"doc-en-rust-d190b42d4ffcd4ab345556f26716854721421495c9c61eb940986bfaf6dcd02a","title":"","text":"pub fn staging_dep_graph_path(sess: &Session) -> PathBuf { in_incr_comp_dir_sess(sess, STAGING_DEP_GRAPH_FILENAME) } pub fn dep_graph_path_from(incr_comp_session_dir: &Path) -> PathBuf { in_incr_comp_dir(incr_comp_session_dir, DEP_GRAPH_FILENAME) } pub fn work_products_path(sess: &Session) -> PathBuf { in_incr_comp_dir_sess(sess, WORK_PRODUCTS_FILENAME)"} {"_id":"doc-en-rust-5a01196888b5930ce3094d23af7e89e5d795afd53878ce6c123961689343f4d3","title":"","text":"// Calling `sess.incr_comp_session_dir()` will panic if `sess.opts.incremental.is_none()`. // Fortunately, we just checked that this isn't the case. let path = dep_graph_path_from(&sess.incr_comp_session_dir()); let path = dep_graph_path(&sess); let report_incremental_info = sess.opts.debugging_opts.incremental_info; let expected_hash = sess.opts.dep_tracking_hash(false);"} {"_id":"doc-en-rust-fbfd131c9043b47c7a5136a576d639d933bdcb6518a7405ac8a43d6465aea5cd","title":"","text":"is bootstrapped and in general, some of the technical details of the build system. ## Using rustbuild Note that this README only covers internal information, not how to use the tool. Please check [bootstrapping dev guide][bootstrapping-dev-guide] for further information. The rustbuild build system has a primary entry point, a top level `x.py` script: [bootstrapping-dev-guide]: https://rustc-dev-guide.rust-lang.org/building/bootstrapping.html ```sh $ python ./x.py build ``` Note that if you're on Unix, you should be able to execute the script directly: ```sh $ ./x.py build ``` The script accepts commands, flags, and arguments to determine what to do: * `build` - a general purpose command for compiling code. Alone, `build` will bootstrap the entire compiler, and otherwise, arguments passed indicate what to build. For example: ``` # build the whole compiler ./x.py build --stage 2 # build the stage1 compiler ./x.py build # build stage0 libstd ./x.py build --stage 0 library/std # build a particular crate in stage0 ./x.py build --stage 0 library/test ``` If files that would normally be rebuilt from stage 0 are dirty, the rebuild can be overridden using `--keep-stage 0`. Using `--keep-stage n` will skip all steps that belong to stage n or earlier: ``` # build stage 1, keeping old build products for stage 0 ./x.py build --keep-stage 0 ``` * `test` - a command for executing unit tests. Like the `build` command, this will execute the entire test suite by default, and otherwise, it can be used to select which test suite is run: ``` # run all unit tests ./x.py test # execute tool tests ./x.py test tidy # execute the UI test suite ./x.py test tests/ui # execute only some tests in the UI test suite ./x.py test tests/ui --test-args substring-of-test-name # execute tests in the standard library in stage0 ./x.py test --stage 0 library/std # execute tests in the core and standard library in stage0, # without running doc tests (thus avoid depending on building the compiler) ./x.py test --stage 0 --no-doc library/core library/std ## Introduction # execute all doc tests ./x.py test src/doc ``` The build system defers most of the complicated logic managing invocations of rustc and rustdoc to Cargo itself. However, moving through various stages and copying artifacts is still necessary for it to do. Each time rustbuild is invoked, it will iterate through the list of predefined steps and execute each serially in turn if it matches the paths passed or is a default rule. For each step rustbuild relies on the step internally being incremental and parallel. Note, though, that the `-j` parameter to rustbuild gets forwarded to appropriate test harnesses and such. * `doc` - a command for building documentation. Like above, can take arguments for what to document. ## Configuring rustbuild rustbuild offers a TOML-based configuration system with a `config.toml` file. An example of this configuration can be found at `config.toml.example`, and the configuration file can also be passed as `--config path/to/config.toml` if the build system is being invoked manually (via the python script). You can generate a config.toml using `./configure` options if you want to automate creating the file without having to edit it. Finally, rustbuild makes use of the [cc-rs crate] which has [its own method][env-vars] of configuring C compilers and C flags via environment variables. [cc-rs crate]: https://github.com/alexcrichton/cc-rs [env-vars]: https://github.com/alexcrichton/cc-rs#external-configuration-via-environment-variables ## Build stages ## Build phases The rustbuild build system goes through a few phases to actually build the compiler. What actually happens when you invoke rustbuild is: 1. The entry point script, `x.py` is run. This script is responsible for downloading the stage0 compiler/Cargo binaries, and it then compiles the build system itself (this folder). Finally, it then invokes the actual `bootstrap` binary build system. 1. The entry point script(`x` for unix like systems, `x.ps1` for windows systems, `x.py` cross-platform) is run. This script is responsible for downloading the stage0 compiler/Cargo binaries, and it then compiles the build system itself (this folder). Finally, it then invokes the actual `bootstrap` binary build system. 2. In Rust, `bootstrap` will slurp up all configuration, perform a number of sanity checks (whether compilers exist, for example), and then start building the stage0 artifacts."} {"_id":"doc-en-rust-2cb40171673f25483e0be3c29bcee91c71d00b016a15b37a54585e1aeb140944","title":"","text":"The goal of each stage is to (a) leverage Cargo as much as possible and failing that (b) leverage Rust as much as possible! ## Incremental builds You can configure rustbuild to use incremental compilation with the `--incremental` flag: ```sh $ ./x.py build --incremental ``` The `--incremental` flag will store incremental compilation artifacts in `build//stage0-incremental`. Note that we only use incremental compilation for the stage0 -> stage1 compilation -- this is because the stage1 compiler is changing, and we don't try to cache and reuse incremental artifacts across different versions of the compiler. You can always drop the `--incremental` to build as normal (but you will still be using the local nightly as your bootstrap). ## Directory Layout This build system houses all output under the `build` directory, which looks"} {"_id":"doc-en-rust-81a440ee8fd2bfe2f398c65d0b0edf155d9ce40f54f03b234325cfd4caa0b4ea","title":"","text":"# system will link (using hard links) output from stageN-{std,rustc} into # each of these directories. # # In theory, there is no extra build output in these directories. # In theory these are working rustc sysroot directories, meaning there is # no extra build output in these directories. stage1/ stage2/ stage3/ ``` ## Cargo projects The current build is unfortunately not quite as simple as `cargo build` in a directory, but rather the compiler is split into three different Cargo projects: * `library/std` - the standard library * `library/test` - testing support, depends on libstd * `compiler/rustc` - the actual compiler itself Each \"project\" has a corresponding Cargo.lock file with all dependencies, and this means that building the compiler involves running Cargo three times. The structure here serves two goals: 1. Facilitating dependencies coming from crates.io. These dependencies don't depend on `std`, so libstd is a separate project compiled ahead of time before the actual compiler builds. 2. Splitting \"host artifacts\" from \"target artifacts\". That is, when building code for an arbitrary target, you don't need the entire compiler, but you'll end up needing libraries like libtest that depend on std but also want to use crates.io dependencies. Hence, libtest is split out as its own project that is sequenced after `std` but before `rustc`. This project is built for all targets. There is some loss in build parallelism here because libtest can be compiled in parallel with a number of rustc artifacts, but in theory, the loss isn't too bad! ## Build tools We've actually got quite a few tools that we use in the compiler's build system and for testing. To organize these, each tool is a project in `src/tools` with a corresponding `Cargo.toml`. All tools are compiled with Cargo (currently having independent `Cargo.lock` files) and do not currently explicitly depend on the compiler or standard library. Compiling each tool is sequenced after the appropriate libstd/libtest/librustc compile above. ## Extending rustbuild So, you'd like to add a feature to the rustbuild build system or just fix a bug. Great! One of the major motivational factors for moving away from `make` is that Rust is in theory much easier to read, modify, and write. If you find anything excessively confusing, please open an issue on this, and we'll try to get it documented or simplified, pronto. When you use the bootstrap system, you'll call it through the entry point script (`x`, `x.ps1`, or `x.py`). However, most of the code lives in `src/bootstrap`. `bootstrap` has a difficult problem: it is written in Rust, but yet it is run before the Rust compiler is built! To work around this, there are two components of bootstrap: the main one written in rust, and `bootstrap.py`. `bootstrap.py` is what gets run by entry point script. It takes care of downloading the `stage0` compiler, which will then build the bootstrap binary written in Rust. First up, you'll probably want to read over the documentation above, as that'll give you a high level overview of what rustbuild is doing. You also probably want to play around a bit yourself by just getting it up and running before you dive too much into the actual build system itself. Because there are two separate codebases behind `x.py`, they need to be kept in sync. In particular, both `bootstrap.py` and the bootstrap binary parse `config.toml` and read the same command line arguments. `bootstrap.py` keeps these in sync by setting various environment variables, and the programs sometimes have to add arguments that are explicitly ignored, to be read by the other. After that, each module in rustbuild should have enough documentation to keep you up and running. Some general areas that you may be interested in modifying are: Some general areas that you may be interested in modifying are: * Adding a new build tool? Take a look at `bootstrap/tool.rs` for examples of other tools."} {"_id":"doc-en-rust-f9f7d8ea5be53c66856ac8479071a0534203a5a2ad88d88c0e764bf24427bf04","title":"","text":"Changes that do not affect contributors to the compiler or users building rustc from source don't need an update to `VERSION`. If you have any questions, feel free to reach out on the `#t-infra` channel in the [Rust Zulip server][rust-zulip] or ask on internals.rust-lang.org. When you encounter bugs, please file issues on the rust-lang/rust issue tracker. If you have any questions, feel free to reach out on the `#t-infra/bootstrap` channel at [Rust Bootstrap Zulip server][rust-bootstrap-zulip]. When you encounter bugs, please file issues on the [Rust issue tracker][rust-issue-tracker]. [rust-zulip]: https://rust-lang.zulipchat.com/#narrow/stream/242791-t-infra [rust-bootstrap-zulip]: https://rust-lang.zulipchat.com/#narrow/stream/t-infra.2Fbootstrap [rust-issue-tracker]: https://github.com/rust-lang/rust/issues "} {"_id":"doc-en-rust-98d92901122952573d8434baa0bf8b3cd8688d32147e33824f6cc6e75da7e864","title":"","text":"//! crates.io and Cargo. //! * A standard interface to build across all platforms, including MSVC //! //! ## Architecture //! //! The build system defers most of the complicated logic managing invocations //! of rustc and rustdoc to Cargo itself. However, moving through various stages //! and copying artifacts is still necessary for it to do. Each time rustbuild //! is invoked, it will iterate through the list of predefined steps and execute //! each serially in turn if it matches the paths passed or is a default rule. //! For each step rustbuild relies on the step internally being incremental and //! parallel. Note, though, that the `-j` parameter to rustbuild gets forwarded //! to appropriate test harnesses and such. //! //! Most of the \"meaty\" steps that matter are backed by Cargo, which does indeed //! have its own parallelism and incremental management. Later steps, like //! tests, aren't incremental and simply run the entire suite currently. //! However, compiletest itself tries to avoid running tests when the artifacts //! that are involved (mainly the compiler) haven't changed. //! //! When you execute `x.py build`, the steps executed are: //! //! * First, the python script is run. This will automatically download the //! stage0 rustc and cargo according to `src/stage0.json`, or use the cached //! versions if they're available. These are then used to compile rustbuild //! itself (using Cargo). Finally, control is then transferred to rustbuild. //! //! * Rustbuild takes over, performs sanity checks, probes the environment, //! reads configuration, and starts executing steps as it reads the command //! line arguments (paths) or going through the default rules. //! //! The build output will be something like the following: //! //! Building stage0 std artifacts //! Copying stage0 std //! Building stage0 test artifacts //! Copying stage0 test //! Building stage0 compiler artifacts //! Copying stage0 rustc //! Assembling stage1 compiler //! Building stage1 std artifacts //! Copying stage1 std //! Building stage1 test artifacts //! Copying stage1 test //! Building stage1 compiler artifacts //! Copying stage1 rustc //! Assembling stage2 compiler //! Uplifting stage1 std //! Uplifting stage1 test //! Uplifting stage1 rustc //! //! Let's disect that a little: //! //! ## Building stage0 {std,test,compiler} artifacts //! //! These steps use the provided (downloaded, usually) compiler to compile the //! local Rust source into libraries we can use. //! //! ## Copying stage0 {std,test,rustc} //! //! This copies the build output from Cargo into //! `build/$HOST/stage0-sysroot/lib/rustlib/$ARCH/lib`. FIXME: this step's //! documentation should be expanded -- the information already here may be //! incorrect. //! //! ## Assembling stage1 compiler //! //! This copies the libraries we built in \"building stage0 ... artifacts\" into //! the stage1 compiler's lib directory. These are the host libraries that the //! compiler itself uses to run. These aren't actually used by artifacts the new //! compiler generates. This step also copies the rustc and rustdoc binaries we //! generated into build/$HOST/stage/bin. //! //! The stage1/bin/rustc is a fully functional compiler, but it doesn't yet have //! any libraries to link built binaries or libraries to. The next 3 steps will //! provide those libraries for it; they are mostly equivalent to constructing //! the stage1/bin compiler so we don't go through them individually. //! //! ## Uplifting stage1 {std,test,rustc} //! //! This step copies the libraries from the stage1 compiler sysroot into the //! stage2 compiler. This is done to avoid rebuilding the compiler; libraries //! we'd build in this step should be identical (in function, if not necessarily //! identical on disk) so there's no need to recompile the compiler again. Note //! that if you want to, you can enable the full-bootstrap option to change this //! behavior. //! //! Each step is driven by a separate Cargo project and rustbuild orchestrates //! copying files between steps and otherwise preparing for Cargo to run. //! //! ## Further information //! //! More documentation can be found in each respective module below, and you can"} {"_id":"doc-en-rust-dd628acde0e95cbcbe4792e75e1360d5eaedb351a148ef7d76df767a2baed3db","title":"","text":" fn main() { 2: n([u8; || 1]) //~^ ERROR cannot find type `n` in this scope //~| ERROR mismatched types } "} {"_id":"doc-en-rust-232f665fb37426edce57d2bd6e577b4e39e7127df4ca88875d548861d7136f59","title":"","text":" error[E0412]: cannot find type `n` in this scope --> $DIR/issue-90871.rs:2:8 | LL | 2: n([u8; || 1]) | ^ expecting a type here because of type ascription error[E0308]: mismatched types --> $DIR/issue-90871.rs:2:15 | LL | 2: n([u8; || 1]) | ^^^^ expected `usize`, found closure | = note: expected type `usize` found closure `[closure@$DIR/issue-90871.rs:2:15: 2:17]` help: use parentheses to call this closure | LL | 2: n([u8; (|| 1)()]) | + +++ error: aborting due to 2 previous errors Some errors have detailed explanations: E0308, E0412. For more information about an error, try `rustc --explain E0308`. "} {"_id":"doc-en-rust-afaace0481a4bc69f3b44ac2eccd787ca37fe13b7902989809a339f919fa4cd6","title":"","text":"use crate::meth; use crate::traits::*; use rustc_middle::ty::{self, Ty}; use rustc_target::abi::WrappingRange; pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx: &mut Bx,"} {"_id":"doc-en-rust-7a0e1a4ef663fe17b69f557bb83876b3e36505edea7b79409c5161c4c6150f9e","title":"","text":"} match t.kind() { ty::Dynamic(..) => { // load size/align from vtable // Load size/align from vtable. let vtable = info.unwrap(); ( meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_SIZE) .get_usize(bx, vtable), meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_ALIGN) .get_usize(bx, vtable), ) let size = meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_SIZE) .get_usize(bx, vtable); let align = meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_ALIGN) .get_usize(bx, vtable); // Alignment is always nonzero. bx.range_metadata(align, WrappingRange { start: 1, end: !0 }); (size, align) } ty::Slice(_) | ty::Str => { let unit = layout.field(bx, 0);"} {"_id":"doc-en-rust-2f4454abc8c2f0d98b3eedc95428cdd2913f9c73e9e6bfb87c6ccea874544957","title":"","text":" // compile-flags: -O #![crate_type = \"lib\"] // This test checks that we annotate alignment loads from vtables with nonzero range metadata, // and that this allows LLVM to eliminate redundant `align >= 1` checks. pub trait Trait { fn f(&self); } pub struct WrapperWithAlign1 { x: u8, y: T } pub struct WrapperWithAlign2 { x: u16, y: T } pub struct Struct { _field: i8, dst: W, } // CHECK-LABEL: @eliminates_runtime_check_when_align_1 #[no_mangle] pub fn eliminates_runtime_check_when_align_1( x: &Struct> ) -> &WrapperWithAlign1 { // CHECK: load [[USIZE:i[0-9]+]], {{.+}} !range [[RANGE_META:![0-9]+]] // CHECK-NOT: icmp // CHECK-NOT: select // CHECK: ret &x.dst } // CHECK-LABEL: @does_not_eliminate_runtime_check_when_align_2 #[no_mangle] pub fn does_not_eliminate_runtime_check_when_align_2( x: &Struct> ) -> &WrapperWithAlign2 { // CHECK: [[X0:%[0-9]+]] = load [[USIZE]], {{.+}} !range [[RANGE_META]] // CHECK: [[X1:%[0-9]+]] = icmp {{.+}} [[X0]] // CHECK: [[X2:%[0-9]+]] = select {{.+}} [[X1]] // CHECK: ret &x.dst } // CHECK: [[RANGE_META]] = !{[[USIZE]] 1, [[USIZE]] 0} "} {"_id":"doc-en-rust-0dd44f224e8563f63506801d640485e3766631e1f73b7f082c3623ce35b2fb4c","title":"","text":"// (e.g. the `bootimage` crate). for tool in LLVM_TOOLS { let tool_exe = exe(tool, target_compiler.host); builder.copy(&llvm_bin_dir.join(&tool_exe), &libdir_bin.join(&tool_exe)); let src_path = llvm_bin_dir.join(&tool_exe); // When using `donwload-ci-llvm`, some of the tools // may not exist, so skip trying to copy them. if src_path.exists() { builder.copy(&src_path, &libdir_bin.join(&tool_exe)); } } } }"} {"_id":"doc-en-rust-7412e64d55a581b84516974fc8c91468fd6488f1b0e350b0074bac31bf1f39c8","title":"","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":"doc-en-rust-81becdd5997148649369ef781b03f17a21310d2939f586c1ba637dbf8dac4618","title":"","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":"doc-en-rust-0386c8ada77b6c294dc7fb3969fd5a7eadd377a04cf2cc4a3b83ceacaf574c41","title":"","text":"* other tasks wishing to access the data will block until the closure * finishes running. * * The reason this function is 'unsafe' is because it is possible to * construct a circular reference among multiple Arcs by mutating the * underlying data. This creates potential for deadlock, but worse, this * will guarantee a memory leak of all involved Arcs. Using MutexArcs * inside of other Arcs is safe in absence of circular references. * * If you wish to nest MutexArcs, one strategy for ensuring safety at * runtime is to add a \"nesting level counter\" inside the stored data, and * when traversing the arcs, assert that they monotonically decrease."} {"_id":"doc-en-rust-64a933ce468271cb0dbc0944214402036bf9d8cb8d530a0eff0415777c4d12c0","title":"","text":"* blocked on the mutex) will also fail immediately. */ #[inline] pub unsafe fn unsafe_access(&self, blk: |x: &mut T| -> U) -> U { pub fn access(&self, blk: |x: &mut T| -> U) -> U { let state = self.x.get(); // Borrowck would complain about this if the function were // not already unsafe. See borrow_rwlock, far below. (&(*state).lock).lock(|| { check_poison(true, (*state).failed); let _z = PoisonOnFail::new(&mut (*state).failed); blk(&mut (*state).data) }) unsafe { // Borrowck would complain about this if the code were // not already unsafe. See borrow_rwlock, far below. (&(*state).lock).lock(|| { check_poison(true, (*state).failed); let _z = PoisonOnFail::new(&mut (*state).failed); blk(&mut (*state).data) }) } } /// As unsafe_access(), but with a condvar, as sync::mutex.lock_cond(). /// As access(), but with a condvar, as sync::mutex.lock_cond(). #[inline] pub unsafe fn unsafe_access_cond(&self, blk: |x: &mut T, c: &Condvar| -> U) -> U { pub fn access_cond(&self, blk: |x: &mut T, c: &Condvar| -> U) -> U { let state = self.x.get(); (&(*state).lock).lock_cond(|cond| { check_poison(true, (*state).failed); let _z = PoisonOnFail::new(&mut (*state).failed); blk(&mut (*state).data, &Condvar {is_mutex: true, failed: &(*state).failed, cond: cond }) }) } } impl MutexArc { /** * As unsafe_access. * * The difference between access and unsafe_access is that the former * forbids mutexes to be nested. While unsafe_access can be used on * MutexArcs without freezable interiors, this safe version of access * requires the Freeze bound, which prohibits access on MutexArcs which * might contain nested MutexArcs inside. * * The purpose of this is to offer a safe implementation of MutexArc to be * used instead of RWArc in cases where no readers are needed and slightly * better performance is required. * * Both methods have the same failure behaviour as unsafe_access and * unsafe_access_cond. */ #[inline] pub fn access(&self, blk: |x: &mut T| -> U) -> U { unsafe { self.unsafe_access(blk) } } /// As unsafe_access_cond but safe and Freeze. #[inline] pub fn access_cond(&self, blk: |x: &mut T, c: &Condvar| -> U) -> U { unsafe { self.unsafe_access_cond(blk) } unsafe { (&(*state).lock).lock_cond(|cond| { check_poison(true, (*state).failed); let _z = PoisonOnFail::new(&mut (*state).failed); blk(&mut (*state).data, &Condvar {is_mutex: true, failed: &(*state).failed, cond: cond }) }) } } }"} {"_id":"doc-en-rust-2cfd74c485a73aa7bb3a9584535f5df76995159938ac5fbc00ab222477adc936","title":"","text":"impl Clone for CowArc { /// Duplicate a Copy-on-write Arc. See arc::clone for more details. #[inline] fn clone(&self) -> CowArc { CowArc { x: self.x.clone() } }"} {"_id":"doc-en-rust-ec02f9686599aa11b90648121c98a50b7a37aaf60bef82c20a7179ed8ec253d0","title":"","text":"} #[test] fn test_unsafe_mutex_arc_nested() { unsafe { // Tests nested mutexes and access // to underlaying data. let arc = ~MutexArc::new(1); let arc2 = ~MutexArc::new(*arc); task::spawn(proc() { (*arc2).unsafe_access(|mutex| { (*mutex).access(|one| { assert!(*one == 1); }) fn test_mutex_arc_nested() { // Tests nested mutexes and access // to underlaying data. let arc = ~MutexArc::new(1); let arc2 = ~MutexArc::new(*arc); task::spawn(proc() { (*arc2).access(|mutex| { (*mutex).access(|one| { assert!(*one == 1); }) }); } }) }); } #[test]"} {"_id":"doc-en-rust-a0c137cde7b70521f451024878b58467839bd1a7ab5a9581c29da27e79f05ec0","title":"","text":" // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate sync; use std::task; use sync::MutexArc; fn test_mutex_arc_nested() { let arc = ~MutexArc::new(1); let arc2 = ~MutexArc::new(*arc); task::spawn(proc() { (*arc2).access(|mutex| { //~ ERROR instantiating a type parameter with an incompatible type }) }); } fn main() {} "} {"_id":"doc-en-rust-5d2e94ebff415a832fc3d7a74c8bc16ee3a8e0407d3769a9079e348b4f4c3f0b","title":"","text":"}); assert!(actually_finished.load(Ordering::Relaxed)); } #[test] fn test_scoped_threads_nll() { // this is mostly a *compilation test* for this exact function: fn foo(x: &u8) { thread::scope(|s| { s.spawn(|| drop(x)); }); } // let's also run it for good measure let x = 42_u8; foo(&x); } "} {"_id":"doc-en-rust-737222cc7f70d361323c635fade2aca9e525d2f730868402ffccd3f7af1c7cf3","title":"","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":"doc-en-rust-3da34d5c1259de633307d5029413d5165afe9b4464c554e8f4777f299ba2d5fa","title":"","text":" fn main() { while let 1 = 1 { vec![].last_mut().unwrap() = 3_u8; //~^ ERROR invalid left-hand side of assignment } } "} {"_id":"doc-en-rust-5b4a51ec68eccc4daaa06176f260aeb31773269095a18c1ad8f9f063d7733abc","title":"","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":"doc-en-rust-1f68f1db5202590eae468a574761c3ae2c255ff1560ce67e253429bdd73207f8","title":"","text":"&self, tcx: TyCtxt<'_>, ident: Ident, // Sorted in order of what kinds to look at kinds: &[AssocKind], parent_def_id: DefId, ) -> Option<&ty::AssocItem> { self.filter_by_name_unhygienic(ident.name) .filter(|item| kinds.contains(&item.kind)) .find(|item| tcx.hygienic_eq(ident, item.ident(tcx), parent_def_id)) kinds.iter().find_map(|kind| self.find_by_name_and_kind(tcx, ident, *kind, parent_def_id)) } /// Returns the associated item with the given name in the given `Namespace`, if one exists."} {"_id":"doc-en-rust-b82fca42ae49d6da6854526479bbd13565660d311956d4cfb39cb0f869eaa90e","title":"","text":".find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id) .is_some() } fn trait_defines_associated_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool { fn trait_defines_associated_const_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool { self.tcx() .associated_items(trait_def_id) .find_by_name_and_kinds( self.tcx(), assoc_name, &[ty::AssocKind::Type, ty::AssocKind::Const], trait_def_id, ) .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Const, trait_def_id) .is_some() }"} {"_id":"doc-en-rust-9245954cf945de7a62e36f0c90603ed9d85bec4ea6e5fa76756d17ba80b7fc23","title":"","text":"// We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead // of calling `filter_by_name_and_kind`. let assoc_item = tcx .associated_items(candidate.def_id()) .filter_by_name_unhygienic(assoc_ident.name) .find(|i| { (i.kind == ty::AssocKind::Type || i.kind == ty::AssocKind::Const) && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident }) let find_item_of_kind = |kind| { tcx.associated_items(candidate.def_id()) .filter_by_name_unhygienic(assoc_ident.name) .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident) }; let assoc_item = find_item_of_kind(ty::AssocKind::Type) .or_else(|| find_item_of_kind(ty::AssocKind::Const)) .expect(\"missing associated type\"); if !assoc_item.vis.is_accessible_from(def_scope, tcx) {"} {"_id":"doc-en-rust-bf51a3e24f8b5351ea3add5e46faf5eac4fabb8e627736a562ce1bd45292ca3d","title":"","text":"I: Iterator>, { let mut matching_candidates = all_candidates() .filter(|r| self.trait_defines_associated_named(r.def_id(), assoc_name)); let bound = match matching_candidates.next() { Some(bound) => bound, None => { .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name)); let mut const_candidates = all_candidates() .filter(|r| self.trait_defines_associated_const_named(r.def_id(), assoc_name)); let (bound, next_cand) = match (matching_candidates.next(), const_candidates.next()) { (Some(bound), _) => (bound, matching_candidates.next()), (None, Some(bound)) => (bound, const_candidates.next()), (None, None) => { self.complain_about_assoc_type_not_found( all_candidates, &ty_param_name(),"} {"_id":"doc-en-rust-b692d10a1bc54c3298d04bc839c54860e15d7412c2bb3f65b63d9eb575e13aa7","title":"","text":"return Err(ErrorReported); } }; debug!(\"one_bound_for_assoc_type: bound = {:?}\", bound); if let Some(bound2) = matching_candidates.next() { if let Some(bound2) = next_cand { debug!(\"one_bound_for_assoc_type: bound2 = {:?}\", bound2); let is_equality = is_equality();"} {"_id":"doc-en-rust-05e5f2a540a540e9cab3011e37e0be3ffb8dead102ef405d6e7babd9557c4ff6","title":"","text":"// We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead // of calling `filter_by_name_and_kind`. let item = tcx .associated_items(trait_did) .in_definition_order() .find(|i| { i.kind.namespace() == Namespace::TypeNS && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident }) .expect(\"missing associated type\"); let item = tcx.associated_items(trait_did).in_definition_order().find(|i| { i.kind.namespace() == Namespace::TypeNS && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident }); // Assume that if it's not matched, there must be a const defined with the same name // but it was used in a type position. let Some(item) = item else { let msg = format!(\"found associated const `{assoc_ident}` when type was expected\"); tcx.sess.struct_span_err(span, &msg).emit(); return Err(ErrorReported); }; let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound); let ty = self.normalize_ty(span, ty);"} {"_id":"doc-en-rust-4480328bb89d2c5abbf5f01ea0122052c9c78ffff6fbfae0f861c12ab1798292","title":"","text":" // Checking that none of these ICE, which was introduced in // https://github.com/rust-lang/rust/issues/93553 trait Foo { type Bar; } trait Baz: Foo { const Bar: Self::Bar; } trait Baz2: Foo { const Bar: u32; fn foo() -> Self::Bar; } trait Baz3 { const BAR: usize; const QUX: Self::BAR; //~^ ERROR found associated const } fn main() {} "} {"_id":"doc-en-rust-92b69e9c0de4af05fb1cc83c0571adc41910cf121782e5e36cca1ed51fdcae2b","title":"","text":" error: found associated const `BAR` when type was expected --> $DIR/shadowed-const.rs:19:14 | LL | const QUX: Self::BAR; | ^^^^^^^^^ error: aborting due to previous error "} {"_id":"doc-en-rust-b2dde1b7518400f2cc311d4aa12d20603ba1df993613e96d60c83c5bf3ec211e","title":"","text":"} /// Iterates over the language items in the given crate. fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] { tcx.arena.alloc_from_iter( self.root .lang_items .decode(self) .map(|(def_index, index)| (self.local_def_id(def_index), index)), ) fn get_lang_items(self) -> impl Iterator + 'a { self.root .lang_items .decode(self) .map(move |(def_index, index)| (self.local_def_id(def_index), index)) } /// Iterates over the diagnostic items in the given crate."} {"_id":"doc-en-rust-b3f601b61702075c49fd07354cd455074d92bbb22f57337b36890d1b51ab8a78","title":"","text":"tcx.arena.alloc_slice(&result) } defined_lib_features => { cdata.get_lib_features(tcx) } defined_lang_items => { cdata.get_lang_items(tcx) } defined_lang_items => { tcx.arena.alloc_from_iter(cdata.get_lang_items()) } diagnostic_items => { cdata.get_diagnostic_items() } missing_lang_items => { cdata.get_missing_lang_items(tcx) }"} {"_id":"doc-en-rust-3435b2a7fff2163477e97d8bc82ec5a8ffc1ed7cb4f675ea190acf028065736a","title":"","text":") -> impl Iterator + '_ { self.get_crate_data(cnum).get_inherent_impls() } /// Decodes all lang items in the crate (for rustdoc). pub fn lang_items_untracked(&self, cnum: CrateNum) -> impl Iterator + '_ { self.get_crate_data(cnum).get_lang_items().map(|(def_id, _)| def_id) } } impl CrateStore for CStore {"} {"_id":"doc-en-rust-013f99920fefd1442dd699810e810f10f06869fff2e40c5f0e9fdd38a7ff7983","title":"","text":"Vec::from_iter(self.resolver.cstore().trait_impls_in_crate_untracked(cnum)); let all_inherent_impls = Vec::from_iter(self.resolver.cstore().inherent_impls_in_crate_untracked(cnum)); let all_lang_items = Vec::from_iter(self.resolver.cstore().lang_items_untracked(cnum)); // Querying traits in scope is expensive so we try to prune the impl and traits lists // using privacy, private traits and impls from other crates are never documented in"} {"_id":"doc-en-rust-ad68b11584276ec3f5ef8d7b548960dd43f1ee66011ce6fb169f597d287e7f3f","title":"","text":"self.add_traits_in_parent_scope(impl_def_id); } } for def_id in all_lang_items { self.add_traits_in_parent_scope(def_id); } self.all_traits.extend(all_traits); self.all_trait_impls.extend(all_trait_impls.into_iter().map(|(_, def_id, _)| def_id));"} {"_id":"doc-en-rust-7e70538d724a3320904ae36d1fe60775652c6c535bb25daf964982cc58daa2af","title":"","text":" // no-prefer-dynamic #![feature(lang_items)] #![crate_type = \"rlib\"] #![no_std] pub struct DerefsToF64(f64); impl core::ops::Deref for DerefsToF64 { type Target = f64; fn deref(&self) -> &Self::Target { &self.0 } } mod inner { #[lang = \"f64_runtime\"] impl f64 { /// [f64::clone] pub fn method() {} } } #[lang = \"eh_personality\"] fn foo() {} #[panic_handler] fn bar(_: &core::panic::PanicInfo) -> ! { loop {} } "} {"_id":"doc-en-rust-818dc3a41655767eece9974d2e1e43d3bd512115642e18e62db7e16eb3ab6bc3","title":"","text":" // Reexport of a structure that derefs to a type with lang item impls having doc links in their // comments. The doc link points to an associated item, so we check that traits in scope for that // link are populated. // aux-build:extern-lang-item-impl-dep.rs #![no_std] extern crate extern_lang_item_impl_dep; pub use extern_lang_item_impl_dep::DerefsToF64; "} {"_id":"doc-en-rust-bd0fd48e66e42018865d1ebbc9564ea0d1633524f7133b277aff14e224d20f19","title":"","text":"ty::RawPtr(ty::TypeAndMut { ty: pointee_type, .. }) | ty::Ref(_, pointee_type, _) => { pointer_or_reference_metadata(cx, t, pointee_type, unique_type_id) } ty::Adt(def, _) if def.is_box() => { // Box may have a non-ZST allocator A. In that case, we // cannot treat Box as just an owned alias of `*mut T`. ty::Adt(def, substs) if def.is_box() && cx.layout_of(substs.type_at(1)).is_zst() => { pointer_or_reference_metadata(cx, t, t.boxed_ty(), unique_type_id) } ty::FnDef(..) | ty::FnPtr(_) => subroutine_type_metadata(cx, unique_type_id),"} {"_id":"doc-en-rust-0b2ce242412f56dbc4f872a9e60356213c85626b6a9c761c69fcb637408367c2","title":"","text":" // build-pass // compile-flags: -Cdebuginfo=2 // fixes issue #94725 #![feature(allocator_api)] use std::alloc::{AllocError, Allocator, Layout}; use std::ptr::NonNull; struct ZST; unsafe impl Allocator for &ZST { fn allocate(&self, layout: Layout) -> Result, AllocError> { todo!() } unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { todo!() } } fn main() { let _ = Box::::new_in(43, &ZST); } "} {"_id":"doc-en-rust-82de1d04615ef5bba85fbee35d3db43fcaffb4107480e4e027c3791f17c9fc6b","title":"","text":" // check-pass // build-pass // compile-flags: -Cdebuginfo=2 // fixes issue #94149"} {"_id":"doc-en-rust-e9e6cb4b92ca1233e37eb5cbc7fcf50b20c5ee9934b2337d2b2de42c18576203","title":"","text":" // run-pass // regression test for issue #94923 // min-llvm-version: 15.0.0 // compile-flags: -C opt-level=3 fn f0(mut x: usize) -> usize { for _ in 0..1000 { x *= 123; x %= 99 } x + 321 // function composition is not just longer iteration } fn f1(x: usize) -> usize { f0::<(i8, T)>(f0::<(u8, T)>(x)) } fn f2(x: usize) -> usize { f1::<(i8, T)>(f1::<(u8, T)>(x)) } fn f3(x: usize) -> usize { f2::<(i8, T)>(f2::<(u8, T)>(x)) } fn f4(x: usize) -> usize { f3::<(i8, T)>(f3::<(u8, T)>(x)) } fn f5(x: usize) -> usize { f4::<(i8, T)>(f4::<(u8, T)>(x)) } fn f6(x: usize) -> usize { f5::<(i8, T)>(f5::<(u8, T)>(x)) } fn f7(x: usize) -> usize { f6::<(i8, T)>(f6::<(u8, T)>(x)) } fn f8(x: usize) -> usize { f7::<(i8, T)>(f7::<(u8, T)>(x)) } fn main() { let y = f8::<()>(1); assert_eq!(y, 348); } "} {"_id":"doc-en-rust-c1172e7c1c85d66d6af245ca8b56d8eb75947745ed1bd576fc624630123ae341","title":"","text":"hir::GenericParamKind::Const { ty: hir_ty, default: _ } => { let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id)); let err_ty_str; let mut is_ptr = true; let err = if tcx.features().adt_const_params { match ty.peel_refs().kind() { if tcx.features().adt_const_params { let err = match ty.peel_refs().kind() { ty::FnPtr(_) => Some(\"function pointers\"), ty::RawPtr(_) => Some(\"raw pointers\"), _ => None, }; if let Some(unsupported_type) = err { tcx.sess.span_err( hir_ty.span, &format!( \"using {} as const generic parameters is forbidden\", unsupported_type ), ); } if traits::search_for_structural_match_violation(param.span, tcx, ty).is_some() { // We use the same error code in both branches, because this is really the same // issue: we just special-case the message for type parameters to make it // clearer. if let ty::Param(_) = ty.peel_refs().kind() { // Const parameters may not have type parameters as their types, // because we cannot be sure that the type parameter derives `PartialEq` // and `Eq` (just implementing them is not enough for `structural_match`). struct_span_err!( tcx.sess, hir_ty.span, E0741, \"`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be used as the type of a const parameter\", ty, ) .span_label( hir_ty.span, format!(\"`{}` may not derive both `PartialEq` and `Eq`\", ty), ) .note( \"it is not currently possible to use a type parameter as the type of a const parameter\", ) .emit(); } else { struct_span_err!( tcx.sess, hir_ty.span, E0741, \"`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as the type of a const parameter\", ty, ) .span_label( hir_ty.span, format!(\"`{}` doesn't derive both `PartialEq` and `Eq`\", ty), ) .emit(); } } } else { match ty.kind() { let err_ty_str; let mut is_ptr = true; let err = match ty.kind() { ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None, ty::FnPtr(_) => Some(\"function pointers\"), ty::RawPtr(_) => Some(\"raw pointers\"),"} {"_id":"doc-en-rust-8d8379704973c3e9cfe78f3f0f0c5a5ce591fdf8256876ca7231a3c136b27e5a","title":"","text":"err_ty_str = format!(\"`{}`\", ty); Some(err_ty_str.as_str()) } } }; if let Some(unsupported_type) = err { if is_ptr { tcx.sess.span_err( hir_ty.span, &format!( \"using {} as const generic parameters is forbidden\", unsupported_type ), ); } else { let mut err = tcx.sess.struct_span_err( hir_ty.span, &format!( \"{} is forbidden as the type of a const generic parameter\", unsupported_type ), ); err.note(\"the only supported types are integers, `bool` and `char`\"); if tcx.sess.is_nightly_build() { err.help( }; if let Some(unsupported_type) = err { if is_ptr { tcx.sess.span_err( hir_ty.span, &format!( \"using {} as const generic parameters is forbidden\", unsupported_type ), ); } else { let mut err = tcx.sess.struct_span_err( hir_ty.span, &format!( \"{} is forbidden as the type of a const generic parameter\", unsupported_type ), ); err.note(\"the only supported types are integers, `bool` and `char`\"); if tcx.sess.is_nightly_build() { err.help( \"more complex types are supported with `#![feature(adt_const_params)]`\", ); } err.emit(); } err.emit(); } }; if traits::search_for_structural_match_violation(param.span, tcx, ty).is_some() { // We use the same error code in both branches, because this is really the same // issue: we just special-case the message for type parameters to make it // clearer. if let ty::Param(_) = ty.peel_refs().kind() { // Const parameters may not have type parameters as their types, // because we cannot be sure that the type parameter derives `PartialEq` // and `Eq` (just implementing them is not enough for `structural_match`). struct_span_err!( tcx.sess, hir_ty.span, E0741, \"`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be used as the type of a const parameter\", ty, ) .span_label( hir_ty.span, format!(\"`{}` may not derive both `PartialEq` and `Eq`\", ty), ) .note( \"it is not currently possible to use a type parameter as the type of a const parameter\", ) .emit(); } else { struct_span_err!( tcx.sess, hir_ty.span, E0741, \"`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as the type of a const parameter\", ty, ) .span_label( hir_ty.span, format!(\"`{}` doesn't derive both `PartialEq` and `Eq`\", ty), ) .emit(); } } }"} {"_id":"doc-en-rust-539b1bda413a1acac254800559083d56d96459d1f75e33df712f1cb2b0360e15","title":"","text":"= note: the only supported types are integers, `bool` and `char` = help: more complex types are supported with `#![feature(adt_const_params)]` error[E0741]: `&'static (dyn A + 'static)` must be annotated with `#[derive(PartialEq, Eq)]` to be used as the type of a const parameter --> $DIR/issue-63322-forbid-dyn.rs:9:18 | LL | fn test() { | ^^^^^^^^^^^^^^ `&'static (dyn A + 'static)` doesn't derive both `PartialEq` and `Eq` error: aborting due to 2 previous errors error: aborting due to previous error For more information about this error, try `rustc --explain E0741`. "} {"_id":"doc-en-rust-b457814237599cee9abafc50abd04b7e1ba485a0ea79436e20e082f46124789d","title":"","text":"impl A for B {} fn test() { //~^ ERROR must be annotated with `#[derive(PartialEq, Eq)]` to be used //[full]~^ ERROR must be annotated with `#[derive(PartialEq, Eq)]` to be used //[min]~^^ ERROR `&'static (dyn A + 'static)` is forbidden unimplemented!() }"} {"_id":"doc-en-rust-9298f208f0beb3780296beb3106d38a2e073bdb192d3bb7ec7153de9d8b7934a","title":"","text":"= note: the only supported types are integers, `bool` and `char` = help: more complex types are supported with `#![feature(adt_const_params)]` error[E0015]: cannot call non-const fn `Foo::{constant#0}::Foo::<17_usize>::value` in constants --> $DIR/nested-type.rs:15:5 | LL | Foo::<17>::value() | ^^^^^^^^^^^^^^^^^^ | = note: calls in constants are limited to constant functions, tuple structs and tuple variants error: aborting due to 2 previous errors error: aborting due to previous error For more information about this error, try `rustc --explain E0015`. "} {"_id":"doc-en-rust-9ca9326c8c35e4bd0c88ddc2ff3a404a2ede41c834e498c3055326dec565d52d","title":"","text":"} Foo::<17>::value() //~^ ERROR cannot call non-const fn //[full]~^ ERROR cannot call non-const fn }]>; fn main() {}"} {"_id":"doc-en-rust-059713efaec000a91e30871e16195c4804f0dd968bf31b20624da9e703179a8f","title":"","text":"use super::{Custom, ErrorData, ErrorKind, SimpleMessage}; use alloc::boxed::Box; use core::marker::PhantomData; use core::mem::{align_of, size_of}; use core::ptr::NonNull;"} {"_id":"doc-en-rust-3668d890b2867fbf12a41baebfd58c87746fe22a64f26d0c922d42d19261564a","title":"","text":"const TAG_OS: usize = 0b10; const TAG_SIMPLE: usize = 0b11; /// The internal representation. /// /// See the module docs for more, this is just a way to hack in a check that we /// indeed are not unwind-safe. /// /// ```compile_fail,E0277 /// fn is_unwind_safe() {} /// is_unwind_safe::(); /// ``` #[repr(transparent)] pub(super) struct Repr(NonNull<()>); pub(super) struct Repr(NonNull<()>, PhantomData>>); // All the types `Repr` stores internally are Send + Sync, and so is it. unsafe impl Send for Repr {}"} {"_id":"doc-en-rust-96dc0c8a035ebd5727aa2eaa402818f2017af5867fd2dd2165f7b824e37bbeed","title":"","text":"// box, and `TAG_CUSTOM` just... isn't zero -- it's `0b01`). Therefore, // `TAG_CUSTOM + p` isn't zero and so `tagged` can't be, and the // `new_unchecked` is safe. let res = Self(unsafe { NonNull::new_unchecked(tagged) }); let res = Self(unsafe { NonNull::new_unchecked(tagged) }, PhantomData); // quickly smoke-check we encoded the right thing (This generally will // only run in libstd's tests, unless the user uses -Zbuild-std) debug_assert!(matches!(res.data(), ErrorData::Custom(_)), \"repr(custom) encoding failed\");"} {"_id":"doc-en-rust-c108dec07252ee4a4a2da2dff480546da0e4763c0aa0e1788f8b74d9ffb3e9ad","title":"","text":"pub(super) fn new_os(code: i32) -> Self { let utagged = ((code as usize) << 32) | TAG_OS; // Safety: `TAG_OS` is not zero, so the result of the `|` is not 0. let res = Self(unsafe { NonNull::new_unchecked(utagged as *mut ()) }); let res = Self(unsafe { NonNull::new_unchecked(utagged as *mut ()) }, PhantomData); // quickly smoke-check we encoded the right thing (This generally will // only run in libstd's tests, unless the user uses -Zbuild-std) debug_assert!("} {"_id":"doc-en-rust-0a6e230b8552c6856bbde4ea1e3a4e60706e8af2dc49406a1134a67eec83209e","title":"","text":"pub(super) fn new_simple(kind: ErrorKind) -> Self { let utagged = ((kind as usize) << 32) | TAG_SIMPLE; // Safety: `TAG_SIMPLE` is not zero, so the result of the `|` is not 0. let res = Self(unsafe { NonNull::new_unchecked(utagged as *mut ()) }); let res = Self(unsafe { NonNull::new_unchecked(utagged as *mut ()) }, PhantomData); // quickly smoke-check we encoded the right thing (This generally will // only run in libstd's tests, unless the user uses -Zbuild-std) debug_assert!("} {"_id":"doc-en-rust-a88c1afeaf6871ecf188bba76e4a60da6ddc4ae36e402f32bd2af3d3f993997e","title":"","text":"#[inline] pub(super) const fn new_simple_message(m: &'static SimpleMessage) -> Self { // Safety: References are never null. Self(unsafe { NonNull::new_unchecked(m as *const _ as *mut ()) }) Self(unsafe { NonNull::new_unchecked(m as *const _ as *mut ()) }, PhantomData) } #[inline]"} {"_id":"doc-en-rust-0e22a9dc54f4599c769e46be7f411b179093ffa7bb8a2cfb56ae7d3e2753f820","title":"","text":"//! Everything here is basically just a shim around calling either `rustbook` or //! `rustdoc`. use std::collections::HashSet; use std::fs; use std::io; use std::path::{Path, PathBuf};"} {"_id":"doc-en-rust-7a0f578f9674d38de6489aa5493b0bfbef4b82e25746b87012774b68b36ef4a4","title":"","text":"let paths = builder .paths .iter() .map(components_simplified) .filter_map(|path| { if path.get(0) == Some(&\"compiler\") { path.get(1).map(|p| p.to_owned()) } else { None } .filter(|path| { let components = components_simplified(path); components.len() >= 2 && components[0] == \"compiler\" }) .collect::>();"} {"_id":"doc-en-rust-9032a6447369e4d188e11cd68d4bb2ea6458163d9ea4b11130c780ba50f1d2de","title":"","text":"cargo.rustdocflag(\"--extern-html-root-url\"); cargo.rustdocflag(\"ena=https://docs.rs/ena/latest/\"); let mut compiler_crates = HashSet::new(); if paths.is_empty() { // Find dependencies for top level crates. for root_crate in &[\"rustc_driver\", \"rustc_codegen_llvm\", \"rustc_codegen_ssa\"] { compiler_crates.extend( builder .in_tree_crates(root_crate, Some(target)) .into_iter() .map(|krate| krate.name), ); } let root_crates = if paths.is_empty() { vec![ INTERNER.intern_str(\"rustc_driver\"), INTERNER.intern_str(\"rustc_codegen_llvm\"), INTERNER.intern_str(\"rustc_codegen_ssa\"), ] } else { for root_crate in paths { if !builder.src.join(\"compiler\").join(&root_crate).exists() { builder.info(&format!( \"tskipping - compiler/{} (unknown compiler crate)\", root_crate )); } else { compiler_crates.extend( builder .in_tree_crates(root_crate, Some(target)) .into_iter() .map(|krate| krate.name), ); } } } paths.into_iter().map(|p| builder.crate_paths[p]).collect() }; // Find dependencies for top level crates. let compiler_crates = root_crates.iter().flat_map(|krate| { builder.in_tree_crates(krate, Some(target)).into_iter().map(|krate| krate.name) }); let mut to_open = None; for krate in &compiler_crates { for krate in compiler_crates { // Create all crate output directories first to make sure rustdoc uses // relative links. // FIXME: Cargo should probably do this itself."} {"_id":"doc-en-rust-1ee7413ded6de83c12e4e4c7303727b6715cee7da1d01bddcdd4e0e5fd40c49b","title":"","text":"ar: HashMap, ranlib: HashMap, // Miscellaneous // allow bidirectional lookups: both name -> path and path -> name crates: HashMap, Crate>, crate_paths: HashMap>, is_sudo: bool, ci_env: CiEnv, delayed_failures: RefCell>,"} {"_id":"doc-en-rust-2889c72fe69b9b9ba2fec0e48ef5177ba8f02a3dc0028647445fb0114bd750cd","title":"","text":"ar: HashMap::new(), ranlib: HashMap::new(), crates: HashMap::new(), crate_paths: HashMap::new(), is_sudo, ci_env: CiEnv::current(), delayed_failures: RefCell::new(Vec::new()),"} {"_id":"doc-en-rust-7e1b2101f124d3bc7a2f85fffb37807eae062fd480a55d4c3c79b7d76cc9d0eb","title":"","text":".filter(|dep| dep.source.is_none()) .map(|dep| INTERNER.intern_string(dep.name)) .collect(); build.crates.insert(name, Crate { name, deps, path }); let krate = Crate { name, deps, path }; let relative_path = krate.local_path(build); build.crates.insert(name, krate); let existing_path = build.crate_paths.insert(relative_path, name); assert!(existing_path.is_none(), \"multiple crates with the same path\"); } } }"} {"_id":"doc-en-rust-46b44312813c4248e81d8029b9da044008cd32105ac3f5662dddec5e20baf22f","title":"","text":"use crate::tool::{self, SourceType, Tool}; use crate::toolstate::ToolState; use crate::util::{self, add_link_lib_path, dylib_path, dylib_path_var, output, t}; use crate::Crate as CargoCrate; use crate::{envify, CLang, DocTests, GitRepo, Mode}; const ADB_TEST_DIR: &str = \"/data/tmp/work\";"} {"_id":"doc-en-rust-ae3499aa207188ba108cd0820e0d02cddc3c216cf2e32c62f82cebe351a3c732","title":"","text":"fn make_run(run: RunConfig<'_>) { let builder = run.builder; let compiler = builder.compiler(builder.top_stage, run.build_triple()); let krate = builder.crate_paths[&run.path]; let test_kind = builder.kind.into(); for krate in builder.in_tree_crates(\"rustc-main\", Some(run.target)) { if krate.path.ends_with(&run.path) { let test_kind = builder.kind.into(); builder.ensure(CrateLibrustc { compiler, target: run.target, test_kind, krate: krate.name, }); } } builder.ensure(CrateLibrustc { compiler, target: run.target, test_kind, krate }); } fn run(self, builder: &Builder<'_>) {"} {"_id":"doc-en-rust-ee68da8b4d40ad3df9d8d15f97bfab5b476cd2bd04ca0476117cfefaffedd3fe","title":"","text":"fn make_run(run: RunConfig<'_>) { let builder = run.builder; let compiler = builder.compiler(builder.top_stage, run.build_triple()); let test_kind = builder.kind.into(); let krate = builder.crate_paths[&run.path]; let make = |mode: Mode, krate: &CargoCrate| { let test_kind = builder.kind.into(); builder.ensure(Crate { compiler, target: run.target, mode, test_kind, krate: krate.name, }); }; for krate in builder.in_tree_crates(\"test\", Some(run.target)) { if krate.path.ends_with(&run.path) { make(Mode::Std, krate); } } builder.ensure(Crate { compiler, target: run.target, mode: Mode::Std, test_kind, krate }); } /// Runs all unit tests plus documentation tests for a given crate defined"} {"_id":"doc-en-rust-ee27101fe5a4983e929bfcd5ad2993b515bd5f037089cc621e8f395cf3d4ca46","title":"","text":"if layout_variants.iter().all(|v| v.abi.is_uninhabited()) { abi = Abi::Uninhabited; } else if tag.size(dl) == size || variants.iter().all(|layout| layout.is_empty()) { // Without latter check aligned enums with custom discriminant values // Would result in ICE see the issue #92464 for more info } else if tag.size(dl) == size { // Make sure we only use scalar layout when the enum is entirely its // own tag (i.e. it has no padding nor any non-ZST variant fields). abi = Abi::Scalar(tag); } else { // Try to use a ScalarPair for all tagged enums."} {"_id":"doc-en-rust-573f578d556cbb3b5d08b6debcdd3949daee1534a8add2d2461e11258acad58c","title":"","text":"fn main() { let aligned = Aligned::Zero; let fo = aligned as u8; println!(\"foo {}\",fo); println!(\"foo {}\", fo); assert_eq!(fo, 0); println!(\"{}\", tou8(Aligned::Zero)); assert_eq!(tou8(Aligned::Zero), 0); } #[inline(never)] fn tou8(al: Aligned) -> u8 { // Cast behind a function call so ConstProp does not see it // (so that we can test codegen). al as u8 }"} {"_id":"doc-en-rust-5b10052fbcf0336f6c860328b4358ddf41d9d0854eb10816dc8abcb6b2945d47","title":"","text":" // normalize-stderr-test \"pref: Align([1-8] bytes)\" -> \"pref: $$PREF_ALIGN\" #![crate_type = \"lib\"] #![feature(rustc_attrs)] // This cannot use `Scalar` abi since there is padding. #[rustc_layout(debug)] #[repr(align(8))] pub enum Aligned1 { //~ ERROR: layout_of Zero = 0, One = 1, } // This should use `Scalar` abi. #[rustc_layout(debug)] #[repr(align(1))] pub enum Aligned2 { //~ ERROR: layout_of Zero = 0, One = 1, } "} {"_id":"doc-en-rust-f841fd319ba3a0e8eb178735d13421f38a7706166942a65f79323e36aa32b186","title":"","text":" error: layout_of(Aligned1) = Layout { fields: Arbitrary { offsets: [ Size(0 bytes), ], memory_index: [ 0, ], }, variants: Multiple { tag: Initialized { value: Int( I8, false, ), valid_range: 0..=1, }, tag_encoding: Direct, tag_field: 0, variants: [ Layout { fields: Arbitrary { offsets: [], memory_index: [], }, variants: Single { index: 0, }, abi: Aggregate { sized: true, }, largest_niche: None, align: AbiAndPrefAlign { abi: Align(8 bytes), pref: $PREF_ALIGN, }, size: Size(8 bytes), }, Layout { fields: Arbitrary { offsets: [], memory_index: [], }, variants: Single { index: 1, }, abi: Aggregate { sized: true, }, largest_niche: None, align: AbiAndPrefAlign { abi: Align(8 bytes), pref: $PREF_ALIGN, }, size: Size(8 bytes), }, ], }, abi: Aggregate { sized: true, }, largest_niche: Some( Niche { offset: Size(0 bytes), value: Int( I8, false, ), valid_range: 0..=1, }, ), align: AbiAndPrefAlign { abi: Align(8 bytes), pref: $PREF_ALIGN, }, size: Size(8 bytes), } --> $DIR/issue-96185-overaligned-enum.rs:8:1 | LL | pub enum Aligned1 { | ^^^^^^^^^^^^^^^^^ error: layout_of(Aligned2) = Layout { fields: Arbitrary { offsets: [ Size(0 bytes), ], memory_index: [ 0, ], }, variants: Multiple { tag: Initialized { value: Int( I8, false, ), valid_range: 0..=1, }, tag_encoding: Direct, tag_field: 0, variants: [ Layout { fields: Arbitrary { offsets: [], memory_index: [], }, variants: Single { index: 0, }, abi: Aggregate { sized: true, }, largest_niche: None, align: AbiAndPrefAlign { abi: Align(1 bytes), pref: $PREF_ALIGN, }, size: Size(1 bytes), }, Layout { fields: Arbitrary { offsets: [], memory_index: [], }, variants: Single { index: 1, }, abi: Aggregate { sized: true, }, largest_niche: None, align: AbiAndPrefAlign { abi: Align(1 bytes), pref: $PREF_ALIGN, }, size: Size(1 bytes), }, ], }, abi: Scalar( Initialized { value: Int( I8, false, ), valid_range: 0..=1, }, ), largest_niche: Some( Niche { offset: Size(0 bytes), value: Int( I8, false, ), valid_range: 0..=1, }, ), align: AbiAndPrefAlign { abi: Align(1 bytes), pref: $PREF_ALIGN, }, size: Size(1 bytes), } --> $DIR/issue-96185-overaligned-enum.rs:16:1 | LL | pub enum Aligned2 { | ^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors "} {"_id":"doc-en-rust-0fd6f338fbbedd913ec36513c93edeccc2a24629f8ce79d0ca0666c2055b1945","title":"","text":"// so add an empty section. if file.format() == object::BinaryFormat::Coff { file.add_section(Vec::new(), \".text\".into(), object::SectionKind::Text); // We handle the name decoration of COFF targets in `symbol_export.rs`, so disable the // default mangler in `object` crate. file.set_mangling(object::write::Mangling::None); } for (sym, kind) in symbols.iter() {"} {"_id":"doc-en-rust-d5c437701068d5cc15a6522bbb58e7746e109cb1f7cb4710412fd7f28183d6d9","title":"","text":"for_each_exported_symbols_include_dep(tcx, crate_type, |symbol, info, cnum| { if info.level.is_below_threshold(export_threshold) || info.used { symbols.push(( symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum), symbol_export::linking_symbol_name_for_instance_in_crate(tcx, symbol, cnum), info.kind, )); }"} {"_id":"doc-en-rust-dd43a051e6642f379cc12f4a57b2f63427968ec8d752805f7002bd4ac26e2fa8","title":"","text":"use rustc_middle::ty::query::{ExternProviders, Providers}; use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::Instance; use rustc_middle::ty::{SymbolName, TyCtxt}; use rustc_middle::ty::{self, SymbolName, TyCtxt}; use rustc_session::config::CrateType; use rustc_target::spec::SanitizerSet;"} {"_id":"doc-en-rust-98eb0be447393f66de3ca1d4f297de4afa058683acaebe316488077f7afb9883","title":"","text":"} } /// This is the symbol name of the given instance as seen by the linker. /// /// On 32-bit Windows symbols are decorated according to their calling conventions. pub fn linking_symbol_name_for_instance_in_crate<'tcx>( tcx: TyCtxt<'tcx>, symbol: ExportedSymbol<'tcx>, instantiating_crate: CrateNum, ) -> String { use rustc_target::abi::call::Conv; let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate); let target = &tcx.sess.target; if !target.is_like_windows { // Mach-O has a global \"_\" suffix and `object` crate will handle it. // ELF does not have any symbol decorations. return undecorated; } let x86 = match &target.arch[..] { \"x86\" => true, \"x86_64\" => false, // Only x86/64 use symbol decorations. _ => return undecorated, }; let instance = match symbol { ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _) if tcx.is_static(def_id) => { None } ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)), ExportedSymbol::Generic(def_id, substs) => Some(Instance::new(def_id, substs)), // DropGlue always use the Rust calling convention and thus follow the target's default // symbol decoration scheme. ExportedSymbol::DropGlue(..) => None, // NoDefId always follow the target's default symbol decoration scheme. ExportedSymbol::NoDefId(..) => None, }; let (conv, args) = instance .map(|i| { tcx.fn_abi_of_instance(ty::ParamEnv::reveal_all().and((i, ty::List::empty()))) .unwrap_or_else(|_| bug!(\"fn_abi_of_instance({i:?}) failed\")) }) .map(|fnabi| (fnabi.conv, &fnabi.args[..])) .unwrap_or((Conv::Rust, &[])); // Decorate symbols with prefices, suffices and total number of bytes of arguments. // Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170 let (prefix, suffix) = match conv { Conv::X86Fastcall => (\"@\", \"@\"), Conv::X86Stdcall => (\"_\", \"@\"), Conv::X86VectorCall => (\"\", \"@@\"), _ => { if x86 { undecorated.insert(0, '_'); } return undecorated; } }; let args_in_bytes: u64 = args .iter() .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8)) .sum(); format!(\"{prefix}{undecorated}{suffix}{args_in_bytes}\") } fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> FxHashMap { // Build up a map from DefId to a `NativeLib` structure, where // `NativeLib` internally contains information about"} {"_id":"doc-en-rust-daaca75a3ceeaa47220415734e65e14795dfc8d47164c61c70428f0d068c7c81","title":"","text":"#![feature(nll)] #![feature(associated_type_bounds)] #![feature(strict_provenance)] #![feature(int_roundings)] #![recursion_limit = \"256\"] #![allow(rustc::potential_query_instability)]"} {"_id":"doc-en-rust-9973dec145907285582681456014fce9b87a99c3dffb6ca7662a2f5d9ba3cc76","title":"","text":" // build-pass // only-x86-windows #![crate_type = \"cdylib\"] #![feature(abi_vectorcall)] #[no_mangle] extern \"stdcall\" fn foo(_: bool) {} #[no_mangle] extern \"fastcall\" fn bar(_: u8) {} #[no_mangle] extern \"vectorcall\" fn baz(_: u16) {} "} {"_id":"doc-en-rust-47309ea122299d4c07e74b2e93cfe35c9e23e22c8ddaa54e8aae4eca430861c4","title":"","text":".arg(\"--target-dir\") .arg(&*target_dir.to_string_lossy()) .arg(\"-Zskip-rustdoc-fingerprint\") .arg(\"-Zrustdoc-map\") .rustdocflag(\"--extern-html-root-url\") .rustdocflag(\"std_detect=https://docs.rs/std_detect/latest/\") .rustdocflag(\"--extern-html-root-takes-precedence\") .rustdocflag(\"--resource-suffix\") .rustdocflag(&builder.version); for arg in extra_args {"} {"_id":"doc-en-rust-d1625f2b678c73d7ad875b922b94be2c888508b5442d0fe5da489ee9494d82a0","title":"","text":"entry.unwrap(); } } /// Test the fallback for getting the metadata of files like hiberfil.sys that /// Windows holds a special lock on, preventing normal means of querying /// metadata. See #96980. /// /// Note this fails in CI because `hiberfil.sys` does not actually exist there. /// Therefore it's marked as ignored. #[test] #[ignore] #[cfg(windows)] fn hiberfil_sys() { let hiberfil = Path::new(r\"C:hiberfil.sys\"); assert_eq!(true, hiberfil.try_exists().unwrap()); fs::symlink_metadata(hiberfil).unwrap(); fs::metadata(hiberfil).unwrap(); assert_eq!(true, hiberfil.exists()); } "} {"_id":"doc-en-rust-295558e317533e635e718f479cc56824db5927264182474e5bce1a4c5d95f8ea","title":"","text":"} pub fn metadata(&self) -> io::Result { Ok(FileAttr { attributes: self.data.dwFileAttributes, creation_time: self.data.ftCreationTime, last_access_time: self.data.ftLastAccessTime, last_write_time: self.data.ftLastWriteTime, file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64), reparse_tag: if self.data.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 { // reserved unless this is a reparse point self.data.dwReserved0 } else { 0 }, volume_serial_number: None, number_of_links: None, file_index: None, }) Ok(self.data.into()) } }"} {"_id":"doc-en-rust-00e07ad299f3ac9b1f7b102f2de9586469ccd874f463d748cf270bbe9d9dd597","title":"","text":"self.file_index } } impl From for FileAttr { fn from(wfd: c::WIN32_FIND_DATAW) -> Self { FileAttr { attributes: wfd.dwFileAttributes, creation_time: wfd.ftCreationTime, last_access_time: wfd.ftLastAccessTime, last_write_time: wfd.ftLastWriteTime, file_size: ((wfd.nFileSizeHigh as u64) << 32) | (wfd.nFileSizeLow as u64), reparse_tag: if wfd.dwFileAttributes & c::FILE_ATTRIBUTE_REPARSE_POINT != 0 { // reserved unless this is a reparse point wfd.dwReserved0 } else { 0 }, volume_serial_number: None, number_of_links: None, file_index: None, } } } fn to_u64(ft: &c::FILETIME) -> u64 { (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32)"} {"_id":"doc-en-rust-345256c97b53db3cb045be9129c1253047f73c0952715e75aa6fa894bf79c6b7","title":"","text":"} pub fn stat(path: &Path) -> io::Result { let mut opts = OpenOptions::new(); // No read or write permissions are necessary opts.access_mode(0); // This flag is so we can open directories too opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS); let file = File::open(path, &opts)?; file.file_attr() metadata(path, ReparsePoint::Follow) } pub fn lstat(path: &Path) -> io::Result { metadata(path, ReparsePoint::Open) } #[repr(u32)] #[derive(Clone, Copy, PartialEq, Eq)] enum ReparsePoint { Follow = 0, Open = c::FILE_FLAG_OPEN_REPARSE_POINT, } impl ReparsePoint { fn as_flag(self) -> u32 { self as u32 } } fn metadata(path: &Path, reparse: ReparsePoint) -> io::Result { let mut opts = OpenOptions::new(); // No read or write permissions are necessary opts.access_mode(0); opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | c::FILE_FLAG_OPEN_REPARSE_POINT); let file = File::open(path, &opts)?; file.file_attr() opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS | reparse.as_flag()); // Attempt to open the file normally. // If that fails with `ERROR_SHARING_VIOLATION` then retry using `FindFirstFileW`. // If the fallback fails for any reason we return the original error. match File::open(path, &opts) { Ok(file) => file.file_attr(), Err(e) if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as _) => { // `ERROR_SHARING_VIOLATION` will almost never be returned. // Usually if a file is locked you can still read some metadata. // However, there are special system files, such as // `C:hiberfil.sys`, that are locked in a way that denies even that. unsafe { let path = maybe_verbatim(path)?; // `FindFirstFileW` accepts wildcard file names. // Fortunately wildcards are not valid file names and // `ERROR_SHARING_VIOLATION` means the file exists (but is locked) // therefore it's safe to assume the file name given does not // include wildcards. let mut wfd = mem::zeroed(); let handle = c::FindFirstFileW(path.as_ptr(), &mut wfd); if handle == c::INVALID_HANDLE_VALUE { // This can fail if the user does not have read access to the // directory. Err(e) } else { // We no longer need the find handle. c::FindClose(handle); // `FindFirstFileW` reads the cached file information from the // directory. The downside is that this metadata may be outdated. let attrs = FileAttr::from(wfd); if reparse == ReparsePoint::Follow && attrs.file_type().is_symlink() { Err(e) } else { Ok(attrs) } } } } Err(e) => Err(e), } } pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {"} {"_id":"doc-en-rust-a623aaaee5b37d98e6d7f0592634a0fb32920ba1e680fe0deb2835cc3573167a","title":"","text":"false } /// Build a textual representation of an unevaluated constant expression. /// /// If the const expression is too complex, an underscore `_` is returned. /// For const arguments, it's `{ _ }` to be precise. /// This means that the output is not necessarily valid Rust code. /// /// Currently, only /// /// * literals (optionally with a leading `-`) /// * unit `()` /// * blocks (`{ … }`) around simple expressions and /// * paths without arguments /// /// are considered simple enough. Simple blocks are included since they are /// necessary to disambiguate unit from the unit type. /// This list might get extended in the future. /// /// Without this censoring, in a lot of cases the output would get too large /// and verbose. Consider `match` expressions, blocks and deeply nested ADTs. /// Further, private and `doc(hidden)` fields of structs would get leaked /// since HIR datatypes like the `body` parameter do not contain enough /// semantic information for this function to be able to hide them – /// at least not without significant performance overhead. /// /// Whenever possible, prefer to evaluate the constant first and try to /// use a different method for pretty-printing. Ideally this function /// should only ever be used as a fallback. pub(crate) fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String { let hir = tcx.hir(); let value = &hir.body(body).value; let snippet = if !value.span.from_expansion() { tcx.sess.source_map().span_to_snippet(value.span).ok() } else { None }; #[derive(PartialEq, Eq)] enum Classification { Literal, Simple, Complex, } snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&hir, body.hir_id)) use Classification::*; fn classify(expr: &hir::Expr<'_>) -> Classification { match &expr.kind { hir::ExprKind::Unary(hir::UnOp::Neg, expr) => { if matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex } } hir::ExprKind::Lit(_) => Literal, hir::ExprKind::Tup([]) => Simple, hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => { if classify(expr) == Complex { Complex } else { Simple } } // Paths with a self-type or arguments are too “complex” following our measure since // they may leak private fields of structs (with feature `adt_const_params`). // Consider: `>::CONSTANT`. // Paths without arguments are definitely harmless though. hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => { if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex } } // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty // contains const arguments. Is there a *concise* way to check for this? hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple, // FIXME: Can they contain const arguments and thus leak private struct fields? hir::ExprKind::Path(hir::QPath::LangItem(..)) => Simple, _ => Complex, } } let classification = classify(value); if classification == Literal && !value.span.from_expansion() && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) { // For literals, we avoid invoking the pretty-printer and use the source snippet instead to // preserve certain stylistic choices the user likely made for the sake legibility like // // * hexadecimal notation // * underscores // * character escapes // // FIXME: This passes through `-/*spacer*/0` verbatim. snippet } else if classification == Simple { // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and // other formatting artifacts. rustc_hir_pretty::id_to_string(&hir, body.hir_id) } else if tcx.def_kind(hir.body_owner_def_id(body).to_def_id()) == DefKind::AnonConst { // FIXME: Omit the curly braces if the enclosing expression is an array literal // with a repeated element (an `ExprKind::Repeat`) as in such case it // would not actually need any disambiguation. \"{ _ }\".to_owned() } else { \"_\".to_owned() } } /// Given a type Path, resolve it to a Type using the TyCtxt"} {"_id":"doc-en-rust-472678497b5e5b2fc65944cc9f2b76264ebca51ead6ebe9c916b98d8c899a580","title":"","text":"ty = ty.print(cx), ); if let Some(default) = default { write!(w, \" = \"); // FIXME: `.value()` uses `clean::utils::format_integer_with_underscore_sep` under the // hood which adds noisy underscores and a type suffix to number literals. // This hurts readability in this context especially when more complex expressions // are involved and it doesn't add much of value. // Find a way to print constants here without all that jazz. write!(w, \" = {}\", default.value(cx.tcx()).unwrap_or_else(|| default.expr(cx.tcx()))); write!(w, \"{}\", Escape(&default.value(cx.tcx()).unwrap_or_else(|| default.expr(cx.tcx())))); } }"} {"_id":"doc-en-rust-d21c28c0901b6161192dc771045cffde991384b819a1ad7a0fa88dab77ed4c70","title":"","text":"typ = c.type_.print(cx), ); // FIXME: The code below now prints // ` = _; // 100i32` // if the expression is // `50 + 50` // which looks just wrong. // Should we print // ` = 100i32;` // instead? let value = c.value(cx.tcx()); let is_literal = c.is_literal(cx.tcx()); let expr = c.expr(cx.tcx());"} {"_id":"doc-en-rust-da51bcce301cf530447dbfc4978705a888ceecf73b0f488ac97ea77c9a072344","title":"","text":"// @has assoc_consts/struct.Bar.html '//*[@id=\"associatedconstant.BAR\"]' // 'const BAR: usize' pub const BAR: usize = 3; // @has - '//*[@id=\"associatedconstant.BAR_ESCAPED\"]' // \"const BAR_ESCAPED: &'static str = \"markup\"\" pub const BAR_ESCAPED: &'static str = \"markup\"; } pub struct Baz<'a, U: 'a, T>(T, &'a [U]);"} {"_id":"doc-en-rust-365a821b487fed7c4a85dd92d45098ce195d5589d2a149a4827b28f9e36558d6","title":"","text":"#![crate_name = \"foo\"] // @has 'foo/constant.HOUR_IN_SECONDS.html' // @has - '//*[@class=\"docblock item-decl\"]//code' 'pub const HOUR_IN_SECONDS: u64 = 60 * 60; // 3_600u64' // @has - '//*[@class=\"docblock item-decl\"]//code' 'pub const HOUR_IN_SECONDS: u64 = _; // 3_600u64' pub const HOUR_IN_SECONDS: u64 = 60 * 60; // @has 'foo/constant.NEGATIVE.html' // @has - '//*[@class=\"docblock item-decl\"]//code' 'pub const NEGATIVE: i64 = -60 * 60; // -3_600i64' // @has - '//*[@class=\"docblock item-decl\"]//code' 'pub const NEGATIVE: i64 = _; // -3_600i64' pub const NEGATIVE: i64 = -60 * 60;"} {"_id":"doc-en-rust-97799c0863b8c6de4360f4f6b3a5942688c11b8bc5826e78e6715174479c389e","title":"","text":" // Test that certain unevaluated constant expression arguments that are // deemed too verbose or complex and that may leak private or // `doc(hidden)` struct fields are not displayed in the documentation. // // Read the documentation of `rustdoc::clean::utils::print_const_expr` // for further details. #![feature(const_trait_impl, generic_const_exprs)] #![allow(incomplete_features)] // @has hide_complex_unevaluated_const_arguments/trait.Stage.html pub trait Stage { // A helper constant that prevents const expressions containing it // from getting fully evaluated since it doesn't have a body and // thus is non-reducible. This allows us to specifically test the // pretty-printing of *unevaluated* consts. const ABSTRACT: usize; // Currently considered \"overly complex\" by the `generic_const_exprs` // feature. If / once this expression kind gets supported, this // unevaluated const expression could leak the private struct field. // // FIXME: Once the line below compiles, make this a test that // ensures that the private field is not printed. // //const ARRAY0: [u8; Struct { private: () } + Self::ABSTRACT]; // This assoc. const could leak the private assoc. function `Struct::new`. // Ensure that this does not happen. // // @has - '//*[@id=\"associatedconstant.ARRAY1\"]' // 'const ARRAY1: [u8; { _ }]' const ARRAY1: [u8; Struct::new(/* ... */) + Self::ABSTRACT * 1_000]; // @has - '//*[@id=\"associatedconstant.VERBOSE\"]' // 'const VERBOSE: [u16; { _ }]' const VERBOSE: [u16; compute(\"thing\", 9 + 9) * Self::ABSTRACT]; // Check that we do not leak the private struct field contained within // the path. The output could definitely be improved upon // (e.g. printing sth. akin to `>::OUT`) but // right now “safe is safe”. // // @has - '//*[@id=\"associatedconstant.PATH\"]' // 'const PATH: usize = _' const PATH: usize = >::OUT; } const fn compute(input: &str, extra: usize) -> usize { input.len() + extra } pub trait Helper { const OUT: usize; } impl Helper for St { const OUT: usize = St::ABSTRACT; } // Currently in rustdoc, const arguments are not evaluated in this position // and therefore they fall under the realm of `print_const_expr`. // If rustdoc gets patched to evaluate const arguments, it is fine to replace // this test as long as one can ensure that private fields are not leaked! // // @has hide_complex_unevaluated_const_arguments/trait.Sub.html // '//*[@class=\"rust trait\"]' // 'pub trait Sub: Sup<{ _ }, { _ }> { }' pub trait Sub: Sup<{ 90 * 20 * 4 }, { Struct { private: () } }> {} pub trait Sup {} pub struct Struct { private: () } impl Struct { const fn new() -> Self { Self { private: () } } } impl const std::ops::Add for Struct { type Output = usize; fn add(self, _: usize) -> usize { 0 } } "} {"_id":"doc-en-rust-8aa687eeac35be67213d1c67616737424380c4503c40e5d8edd90476f9b43e93","title":"","text":" // Regression test for issue #97933. // // Test that certain unevaluated constant expressions that are // deemed too verbose or complex and that may leak private or // `doc(hidden)` struct fields are not displayed in the documentation. // // Read the documentation of `rustdoc::clean::utils::print_const_expr` // for further details. // @has hide_complex_unevaluated_consts/trait.Container.html pub trait Container { // A helper constant that prevents const expressions containing it // from getting fully evaluated since it doesn't have a body and // thus is non-reducible. This allows us to specifically test the // pretty-printing of *unevaluated* consts. const ABSTRACT: i32; // Ensure that the private field does not get leaked: // // @has - '//*[@id=\"associatedconstant.STRUCT0\"]' // 'const STRUCT0: Struct = _' const STRUCT0: Struct = Struct { private: () }; // @has - '//*[@id=\"associatedconstant.STRUCT1\"]' // 'const STRUCT1: (Struct,) = _' const STRUCT1: (Struct,) = (Struct{private: /**/()},); // Although the struct field is public here, check that it is not // displayed. In a future version of rustdoc, we definitely want to // show it. However for the time being, the printing logic is a bit // conservative. // // @has - '//*[@id=\"associatedconstant.STRUCT2\"]' // 'const STRUCT2: Record = _' const STRUCT2: Record = Record { public: 5 }; // Test that we do not show the incredibly verbose match expr: // // @has - '//*[@id=\"associatedconstant.MATCH0\"]' // 'const MATCH0: i32 = _' const MATCH0: i32 = match 234 { 0 => 1, _ => Self::ABSTRACT, }; // @has - '//*[@id=\"associatedconstant.MATCH1\"]' // 'const MATCH1: bool = _' const MATCH1: bool = match Self::ABSTRACT { _ => true, }; // Check that we hide complex (arithmetic) operations. // In this case, it is a bit unfortunate since the expression // is not *that* verbose and it might be quite useful to the reader. // // However in general, the expression might be quite large and // contain match expressions and structs with private fields. // We would need to recurse over the whole expression and even more // importantly respect operator precedence when pretty-printing // the potentially partially censored expression. // For now, the implementation is quite simple and the choices // rather conservative. // // @has - '//*[@id=\"associatedconstant.ARITH_OPS\"]' // 'const ARITH_OPS: i32 = _' const ARITH_OPS: i32 = Self::ABSTRACT * 2 + 1; } pub struct Struct { private: () } pub struct Record { pub public: i32 } "} {"_id":"doc-en-rust-9875ad155e2f1f5dfeb820821e751a44ca5168d5ab48259643ed986c0ce9442d","title":"","text":"// @!has show_const_contents/constant.CONST_EQ_TO_VALUE_I32.html '// 42i32' pub const CONST_EQ_TO_VALUE_I32: i32 = 42i32; // @has show_const_contents/constant.CONST_CALC_I32.html '= 42 + 1; // 43i32' // @has show_const_contents/constant.CONST_CALC_I32.html '= _; // 43i32' pub const CONST_CALC_I32: i32 = 42 + 1; // @!has show_const_contents/constant.CONST_REF_I32.html '= &42;'"} {"_id":"doc-en-rust-b199181b9e4a9edf2c6adfea1f7941aa39a321b2241c702feddde6554809b7c9","title":"","text":"/// /// This trait can be used with `#[derive]`. When `derive`d on structs, two /// instances are equal if all fields are equal, and not equal if any fields /// are not equal. When `derive`d on enums, each variant is equal to itself /// and not equal to the other variants. /// are not equal. When `derive`d on enums, two instances are equal if they /// are the same variant and all fields are equal. /// /// ## How can I implement `PartialEq`? ///"} {"_id":"doc-en-rust-74ba464dc05f46a184a14ed2b23a8712ee9dcd2949d9fe4193b0ef02eb60190e","title":"","text":"use crate::ffi::{CStr, CString}; use crate::fmt; use crate::io; use crate::marker::PhantomData; use crate::mem; use crate::num::NonZeroU64; use crate::num::NonZeroUsize;"} {"_id":"doc-en-rust-73a0593db3e7ccbe84e044a6e6413b8c125f0cfe7a7d0ee65c605f5d5299ac27","title":"","text":"unsafe fn spawn_unchecked_<'a, 'scope, F, T>( self, f: F, scope_data: Option<&'scope scoped::ScopeData>, scope_data: Option>, ) -> io::Result> where F: FnOnce() -> T,"} {"_id":"doc-en-rust-4e34b953a72dd59b16c715c571e6c4ea801045726bdb3ca2e0cdb25c4e508dc5","title":"","text":"})); let their_thread = my_thread.clone(); let my_packet: Arc> = Arc::new(Packet { scope: scope_data, result: UnsafeCell::new(None) }); let my_packet: Arc> = Arc::new(Packet { scope: scope_data, result: UnsafeCell::new(None), _marker: PhantomData, }); let their_packet = my_packet.clone(); let output_capture = crate::io::set_output_capture(None);"} {"_id":"doc-en-rust-59b1262e3f7536097feed903f98092e25841b06b4b3afd8111ec37b464c0a5f3","title":"","text":"unsafe { *their_packet.result.get() = Some(try_result) }; }; if let Some(scope_data) = scope_data { if let Some(scope_data) = &my_packet.scope { scope_data.increment_num_running_threads(); }"} {"_id":"doc-en-rust-c02043d7556a6ac6cbbfd1a9ea8f9f7dd835de1c40915c9a8425f59e20989a2c","title":"","text":"// An Arc to the packet is stored into a `JoinInner` which in turns is placed // in `JoinHandle`. struct Packet<'scope, T> { scope: Option<&'scope scoped::ScopeData>, scope: Option>, result: UnsafeCell>>, _marker: PhantomData>, } // Due to the usage of `UnsafeCell` we need to manually implement Sync."} {"_id":"doc-en-rust-4afa7065998f5a589febfa6249a8c53756a92d0a61f7e8743c39f22225a4b13f","title":"","text":"rtabort!(\"thread result panicked on drop\"); } // Book-keeping so the scope knows when it's done. if let Some(scope) = self.scope { if let Some(scope) = &self.scope { // Now that there will be no more user code running on this thread // that can use 'scope, mark the thread as 'finished'. // It's important we only do this after the `result` has been dropped,"} {"_id":"doc-en-rust-3722f042bc4db7d9ff7df00c84b70ea9da310b249ff2a23ca2c97d25d489806c","title":"","text":"/// See [`scope`] for details. #[stable(feature = \"scoped_threads\", since = \"1.63.0\")] pub struct Scope<'scope, 'env: 'scope> { data: ScopeData, data: Arc, /// Invariance over 'scope, to make sure 'scope cannot shrink, /// which is necessary for soundness. ///"} {"_id":"doc-en-rust-1c4e688298487d17fd2405f82f561ca007cbe55063c6b5f8fd65c8fd15b083c5","title":"","text":"where F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T, { // We put the `ScopeData` into an `Arc` so that other threads can finish their // `decrement_num_running_threads` even after this function returns. let scope = Scope { data: ScopeData { data: Arc::new(ScopeData { num_running_threads: AtomicUsize::new(0), main_thread: current(), a_thread_panicked: AtomicBool::new(false), }, }), env: PhantomData, scope: PhantomData, };"} {"_id":"doc-en-rust-c92bfcce27e6e238fa62c212bd4168afd2998d6a598e16507a65a57b5f444912","title":"","text":"F: FnOnce() -> T + Send + 'scope, T: Send + 'scope, { Ok(ScopedJoinHandle(unsafe { self.spawn_unchecked_(f, Some(&scope.data)) }?)) Ok(ScopedJoinHandle(unsafe { self.spawn_unchecked_(f, Some(scope.data.clone())) }?)) } }"} {"_id":"doc-en-rust-8a3eabf6608d726e6f98e700027ff2c34fc14ee1a54f07f1fabbaa5917a3a406","title":"","text":"initializer_span, else_block, visibility_scope, *remainder_scope, remainder_span, pattern, )"} {"_id":"doc-en-rust-20c0b82d75308dbc82424627ec424ec7af0f88cb9cffca4ccb7251bedd360bc0","title":"","text":"initializer_span: Span, else_block: &Block, visibility_scope: Option, remainder_scope: region::Scope, remainder_span: Span, pattern: &Pat<'tcx>, ) -> BlockAnd<()> { let scrutinee = unpack!(block = self.lower_scrutinee(block, init, initializer_span)); let pat = Pat { ty: init.ty, span: else_block.span, kind: Box::new(PatKind::Wild) }; let mut wildcard = Candidate::new(scrutinee.clone(), &pat, false); self.declare_bindings( visibility_scope, remainder_span, pattern, ArmHasGuard(false), Some((None, initializer_span)), ); let mut candidate = Candidate::new(scrutinee.clone(), pattern, false); let fake_borrow_temps = self.lower_match_tree( block, initializer_span, pattern.span, false, &mut [&mut candidate, &mut wildcard], ); // This block is for the matching case let matching = self.bind_pattern( self.source_info(pattern.span), candidate, None, &fake_borrow_temps, initializer_span, None, None, None, ); // This block is for the failure case let failure = self.bind_pattern( self.source_info(else_block.span), wildcard, None, &fake_borrow_temps, initializer_span, None, None, None, ); let (matching, failure) = self.in_if_then_scope(remainder_scope, |this| { let scrutinee = unpack!(block = this.lower_scrutinee(block, init, initializer_span)); let pat = Pat { ty: init.ty, span: else_block.span, kind: Box::new(PatKind::Wild) }; let mut wildcard = Candidate::new(scrutinee.clone(), &pat, false); this.declare_bindings( visibility_scope, remainder_span, pattern, ArmHasGuard(false), Some((None, initializer_span)), ); let mut candidate = Candidate::new(scrutinee.clone(), pattern, false); let fake_borrow_temps = this.lower_match_tree( block, initializer_span, pattern.span, false, &mut [&mut candidate, &mut wildcard], ); // This block is for the matching case let matching = this.bind_pattern( this.source_info(pattern.span), candidate, None, &fake_borrow_temps, initializer_span, None, None, None, ); // This block is for the failure case let failure = this.bind_pattern( this.source_info(else_block.span), wildcard, None, &fake_borrow_temps, initializer_span, None, None, None, ); this.break_for_else(failure, remainder_scope, this.source_info(initializer_span)); matching.unit() }); // This place is not really used because this destination place // should never be used to take values at the end of the failure // block."} {"_id":"doc-en-rust-3c7d421f337f56c2f28d6ff983aa535b3c42198c29114cac6b7c4cc4d73af9f7","title":"","text":"} drops.add_entry(block, drop_idx); // `build_drop_tree` doesn't have access to our source_info, so we // `build_drop_trees` doesn't have access to our source_info, so we // create a dummy terminator now. `TerminatorKind::Resume` is used // because MIR type checking will panic if it hasn't been overwritten. self.cfg.terminate(block, source_info, TerminatorKind::Resume);"} {"_id":"doc-en-rust-7c25713bb87b5c92e7a194245f19e4255b17762c2f8cbdd380dadcf8111f899e","title":"","text":" // run-pass // // from issue #93951, where borrowck complained the temporary that `foo(&x)` was stored in was to // be dropped sometime after `x` was. It then suggested adding a semicolon that was already there. #![feature(let_else)] use std::fmt::Debug; fn foo<'a>(x: &'a str) -> Result { Ok(x) } fn let_else() { let x = String::from(\"Hey\"); let Ok(_) = foo(&x) else { return }; } fn if_let() { let x = String::from(\"Hey\"); let _ = if let Ok(s) = foo(&x) { s } else { return }; } fn main() { let_else(); if_let(); } "} {"_id":"doc-en-rust-993748f1cce656c6f989ef02a262f7e2e7525e52cf2f4f49a954a83656f9223b","title":"","text":"// run-pass #![feature(let_else)] use std::fmt::Display; use std::rc::Rc; use std::sync::atomic::{AtomicU8, Ordering}; static TRACKER: AtomicU8 = AtomicU8::new(0);"} {"_id":"doc-en-rust-18de896f1ecb1b04dde26e1c5806d266590066ae5373daffda5b30d51c147023","title":"","text":"} } fn foo<'a>(x: &'a str) -> Result { Ok(x) } fn main() { assert_eq!(TRACKER.load(Ordering::Acquire), 0); let 0 = Droppy::default().inner else { return }; assert_eq!(TRACKER.load(Ordering::Acquire), 1); println!(\"Should have dropped 👆\"); { // cf. https://github.com/rust-lang/rust/pull/99518#issuecomment-1191520030 struct Foo<'a>(&'a mut u32); impl<'a> Drop for Foo<'a> { fn drop(&mut self) { *self.0 = 0; } } let mut foo = 0; let Foo(0) = Foo(&mut foo) else { *&mut foo = 1; todo!() }; } { let x = String::from(\"Hey\"); let Ok(s) = foo(&x) else { panic!() }; assert_eq!(s.to_string(), x); } { // test let-else drops temps after statement let rc = Rc::new(0); let 0 = *rc.clone() else { unreachable!() }; Rc::try_unwrap(rc).unwrap(); } { let mut rc = Rc::new(0); let mut i = 0; loop { if i > 3 { break; } let 1 = *rc.clone() else { if let Ok(v) = Rc::try_unwrap(rc) { rc = Rc::new(v); } else { panic!() } i += 1; continue }; } } { // test let-else drops temps before else block // NOTE: this test has to be the last block in the `main` // body. let rc = Rc::new(0); let 1 = *rc.clone() else { Rc::try_unwrap(rc).unwrap(); return; }; unreachable!(); } }"} {"_id":"doc-en-rust-261ef322c73209a77f1af1e019f82ffaa266f16478f18b592180a59a71f40ba7","title":"","text":"LazyLock::new(|| { let hook = panic::take_hook(); panic::set_hook(Box::new(|info| { // If the error was caused by a broken pipe then this is not a bug. // Write the error and return immediately. See #98700. #[cfg(windows)] if let Some(msg) = info.payload().downcast_ref::() { if msg.starts_with(\"failed printing to stdout: \") && msg.ends_with(\"(os error 232)\") { early_error_no_abort(ErrorOutputType::default(), &msg); return; } }; // Invoke the default handler, which prints the actual panic message and optionally a backtrace (*DEFAULT_HOOK)(info);"} {"_id":"doc-en-rust-6faaf0804a028cf67bca859d2327a753625bbb613b042ccb572ed4104e4bb16b","title":"","text":"// FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <= // 1, where the method versions of these operations are not inlined. use intrinsics::{ unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub, cttz_nonzero, exact_div, unchecked_rem, unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub, }; let addr = p.addr(); /// Calculate multiplicative modular inverse of `x` modulo `m`. /// /// This implementation is tailored for `align_offset` and has following preconditions:"} {"_id":"doc-en-rust-8bebd388cb8a82e8b4a0c44ff1f224228f1b15bfab84d9d1a9847179903a463d","title":"","text":"} } let addr = p.addr(); let stride = mem::size_of::(); // SAFETY: `a` is a power-of-two, therefore non-zero. let a_minus_one = unsafe { unchecked_sub(a, 1) }; if stride == 1 { // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so // inhibits LLVM's ability to select instructions like `lea`. Instead we compute if stride == 0 { // SPECIAL_CASE: handle 0-sized types. No matter how many times we step, the address will // stay the same, so no offset will be able to align the pointer unless it is already // aligned. This branch _will_ be optimized out as `stride` is known at compile-time. let p_mod_a = addr & a_minus_one; return if p_mod_a == 0 { 0 } else { usize::MAX }; } // SAFETY: `stride == 0` case has been handled by the special case above. let a_mod_stride = unsafe { unchecked_rem(a, stride) }; if a_mod_stride == 0 { // SPECIAL_CASE: In cases where the `a` is divisible by `stride`, byte offset to align a // pointer can be computed more simply through `-p (mod a)`. In the off-chance the byte // offset is not a multiple of `stride`, the input pointer was misaligned and no pointer // offset will be able to produce a `p` aligned to the specified `a`. // // round_up_to_next_alignment(p, a) - p // The naive `-p (mod a)` equation inhibits LLVM's ability to select instructions // like `lea`. We compute `(round_up_to_next_alignment(p, a) - p)` instead. This // redistributes operations around the load-bearing, but pessimizing `and` instruction // sufficiently for LLVM to be able to utilize the various optimizations it knows about. // // which distributes operations around the load-bearing, but pessimizing `and` sufficiently // for LLVM to be able to utilize the various optimizations it knows about. return wrapping_sub(wrapping_add(addr, a_minus_one) & wrapping_sub(0, a), addr); } // LLVM handles the branch here particularly nicely. If this branch needs to be evaluated // at runtime, it will produce a mask `if addr_mod_stride == 0 { 0 } else { usize::MAX }` // in a branch-free way and then bitwise-OR it with whatever result the `-p mod a` // computation produces. // SAFETY: `stride == 0` case has been handled by the special case above. let addr_mod_stride = unsafe { unchecked_rem(addr, stride) }; let pmoda = addr & a_minus_one; if pmoda == 0 { // Already aligned. Yay! return 0; } else if stride == 0 { // If the pointer is not aligned, and the element is zero-sized, then no amount of // elements will ever align the pointer. return usize::MAX; return if addr_mod_stride == 0 { let aligned_address = wrapping_add(addr, a_minus_one) & wrapping_sub(0, a); let byte_offset = wrapping_sub(aligned_address, addr); // SAFETY: `stride` is non-zero. This is guaranteed to divide exactly as well, because // addr has been verified to be aligned to the original type’s alignment requirements. unsafe { exact_div(byte_offset, stride) } } else { usize::MAX }; } let smoda = stride & a_minus_one; // GENERAL_CASE: From here on we’re handling the very general case where `addr` may be // misaligned, there isn’t an obvious relationship between `stride` and `a` that we can take an // advantage of, etc. This case produces machine code that isn’t particularly high quality, // compared to the special cases above. The code produced here is still within the realm of // miracles, given the situations this case has to deal with. // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above. let gcdpow = unsafe { intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)) }; let gcdpow = unsafe { cttz_nonzero(stride).min(cttz_nonzero(a)) }; // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize. let gcd = unsafe { unchecked_shl(1usize, gcdpow) }; // SAFETY: gcd is always greater or equal to 1. if addr & unsafe { unchecked_sub(gcd, 1) } == 0 { // This branch solves for the following linear congruence equation:"} {"_id":"doc-en-rust-e9c20e8d8bffcf588bad6b6f5d08ede245e42379d81ef715483142cbcdba529a","title":"","text":"// ` p' + s'o = 0 mod a' ` // ` o = (a' - (p' mod a')) * (s'^-1 mod a') ` // // The first term is \"the relative alignment of `p` to `a`\" (divided by the `g`), the second // term is \"how does incrementing `p` by `s` bytes change the relative alignment of `p`\" (again // divided by `g`). // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not // co-prime. // The first term is \"the relative alignment of `p` to `a`\" (divided by the `g`), the // second term is \"how does incrementing `p` by `s` bytes change the relative alignment of // `p`\" (again divided by `g`). Division by `g` is necessary to make the inverse well // formed if `a` and `s` are not co-prime. // // Furthermore, the result produced by this solution is not \"minimal\", so it is necessary // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`. // to take the result `o mod lcm(s, a)`. This `lcm(s, a)` is the same as `a'`. // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in // `a`."} {"_id":"doc-en-rust-34b9212e3ffa699936f5704d3e39332d9d1e58a3bbda4090db56f9e8f13c79c3","title":"","text":"let a2minus1 = unsafe { unchecked_sub(a2, 1) }; // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in // `a`. let s2 = unsafe { unchecked_shr(smoda, gcdpow) }; let s2 = unsafe { unchecked_shr(stride & a_minus_one, gcdpow) }; // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will // always be strictly greater than `(p % a) >> gcdpow`. let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(pmoda, gcdpow)) }; let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(addr & a_minus_one, gcdpow)) }; // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2` // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`. return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;"} {"_id":"doc-en-rust-2daffd499b4df14fac47f6aa5ae36009c6d2f983148e8b3e26ed4aedbbec10ab","title":"","text":"} #[test] fn align_offset_stride1() { fn align_offset_stride_one() { // For pointers of stride = 1, the pointer can always be aligned. The offset is equal to // number of bytes. let mut align = 1;"} {"_id":"doc-en-rust-9b482e1bfbc2a5c44b4f73d644d0af21ae56caf52601db2b0adf7a0e5f488fcc","title":"","text":"} #[test] fn align_offset_weird_strides() { #[repr(packed)] struct A3(u16, u8); struct A4(u32); #[repr(packed)] struct A5(u32, u8); #[repr(packed)] struct A6(u32, u16); #[repr(packed)] struct A7(u32, u16, u8); #[repr(packed)] struct A8(u32, u32); #[repr(packed)] struct A9(u32, u32, u8); #[repr(packed)] struct A10(u32, u32, u16); unsafe fn test_weird_stride(ptr: *const T, align: usize) -> bool { fn align_offset_various_strides() { unsafe fn test_stride(ptr: *const T, align: usize) -> bool { let numptr = ptr as usize; let mut expected = usize::MAX; // Naive but definitely correct way to find the *first* aligned element of stride::."} {"_id":"doc-en-rust-46a123b1240f28f2eac4a12dff718c4374eb1456058a86563bdc8628e129d410","title":"","text":"while align < limit { for ptr in 1usize..4 * align { unsafe { x |= test_weird_stride::(ptr::invalid::(ptr), align); x |= test_weird_stride::(ptr::invalid::(ptr), align); x |= test_weird_stride::(ptr::invalid::(ptr), align); x |= test_weird_stride::(ptr::invalid::(ptr), align); x |= test_weird_stride::(ptr::invalid::(ptr), align); x |= test_weird_stride::(ptr::invalid::(ptr), align); x |= test_weird_stride::(ptr::invalid::(ptr), align); x |= test_weird_stride::(ptr::invalid::(ptr), align); #[repr(packed)] struct A3(u16, u8); x |= test_stride::(ptr::invalid::(ptr), align); struct A4(u32); x |= test_stride::(ptr::invalid::(ptr), align); #[repr(packed)] struct A5(u32, u8); x |= test_stride::(ptr::invalid::(ptr), align); #[repr(packed)] struct A6(u32, u16); x |= test_stride::(ptr::invalid::(ptr), align); #[repr(packed)] struct A7(u32, u16, u8); x |= test_stride::(ptr::invalid::(ptr), align); #[repr(packed)] struct A8(u32, u32); x |= test_stride::(ptr::invalid::(ptr), align); #[repr(packed)] struct A9(u32, u32, u8); x |= test_stride::(ptr::invalid::(ptr), align); #[repr(packed)] struct A10(u32, u32, u16); x |= test_stride::(ptr::invalid::(ptr), align); x |= test_stride::(ptr::invalid::(ptr), align); x |= test_stride::(ptr::invalid::(ptr), align); } } align = (align + 1).next_power_of_two();"} {"_id":"doc-en-rust-9d23b2ec8123b1969b1c06a02aea1ffdccf20bda0d16fe314dae6ec52834cf5a","title":"","text":" // assembly-output: emit-asm // compile-flags: -Copt-level=1 // only-x86_64 // min-llvm-version: 14.0 #![crate_type=\"rlib\"] // CHECK-LABEL: align_offset_byte_ptr // CHECK: leaq 31 // CHECK: andq $-32 // CHECK: subq #[no_mangle] pub fn align_offset_byte_ptr(ptr: *const u8) -> usize { ptr.align_offset(32) } // CHECK-LABEL: align_offset_byte_slice // CHECK: leaq 31 // CHECK: andq $-32 // CHECK: subq #[no_mangle] pub fn align_offset_byte_slice(slice: &[u8]) -> usize { slice.as_ptr().align_offset(32) } // CHECK-LABEL: align_offset_word_ptr // CHECK: leaq 31 // CHECK: andq $-32 // CHECK: subq // CHECK: shrq // This `ptr` is not known to be aligned, so it is required to check if it is at all possible to // align. LLVM applies a simple mask. // CHECK: orq #[no_mangle] pub fn align_offset_word_ptr(ptr: *const u32) -> usize { ptr.align_offset(32) } // CHECK-LABEL: align_offset_word_slice // CHECK: leaq 31 // CHECK: andq $-32 // CHECK: subq // CHECK: shrq // `slice` is known to be aligned, so `!0` is not possible as a return // CHECK-NOT: orq #[no_mangle] pub fn align_offset_word_slice(slice: &[u32]) -> usize { slice.as_ptr().align_offset(32) } "} {"_id":"doc-en-rust-3a3ef87f63e53c8e8b0b5ada51fcfbfff08f4bde5cffef290170f2da4c9bcf74","title":"","text":"if !self.report_similar_impl_candidates( impl_candidates, trait_ref, obligation.cause.body_id, &mut err, ) { // This is *almost* equivalent to"} {"_id":"doc-en-rust-78aca2dce9162ad8653940db1519d6af4b3687e8e40b6e58648bf3c953665870","title":"","text":"self.report_similar_impl_candidates( impl_candidates, trait_ref, obligation.cause.body_id, &mut err, ); }"} {"_id":"doc-en-rust-aa002be55296abe0fe11a07962ca10edd934045a2a5f3bbe33ccfa80f645dd9c","title":"","text":"&self, impl_candidates: Vec>, trait_ref: ty::PolyTraitRef<'tcx>, body_id: hir::HirId, err: &mut Diagnostic, ) -> bool;"} {"_id":"doc-en-rust-8bf8b4dadcab3be4826d81a35d50ceac8826143a4f5c375b177de02fd82dd2b5","title":"","text":"&self, impl_candidates: Vec>, trait_ref: ty::PolyTraitRef<'tcx>, body_id: hir::HirId, err: &mut Diagnostic, ) -> bool { let report = |mut candidates: Vec>, err: &mut Diagnostic| {"} {"_id":"doc-en-rust-464963eed2ce11f19d4a9c4a1e496dee0f7d6359f2cb907dee5f69423046b61a","title":"","text":"|| self.tcx.is_builtin_derive(def_id) }) .filter_map(|def_id| self.tcx.impl_trait_ref(def_id)) // Avoid mentioning type parameters. .filter(|trait_ref| !matches!(trait_ref.self_ty().kind(), ty::Param(_))) .filter(|trait_ref| { let self_ty = trait_ref.self_ty(); // Avoid mentioning type parameters. if let ty::Param(_) = self_ty.kind() { false } // Avoid mentioning types that are private to another crate else if let ty::Adt(def, _) = self_ty.peel_refs().kind() { // FIXME(compiler-errors): This could be generalized, both to // be more granular, and probably look past other `#[fundamental]` // types, too. self.tcx .visibility(def.did()) .is_accessible_from(body_id.owner.to_def_id(), self.tcx) } else { true } }) .collect(); return report(normalized_impl_candidates, err); }"} {"_id":"doc-en-rust-5e353742171d134f336d48310a2e4973b4436795b1c560ac4e7cd0a77acab6fc","title":"","text":" pub trait Meow { fn meow(&self) {} } pub struct GlobalMeow; impl Meow for GlobalMeow {} pub(crate) struct PrivateMeow; impl Meow for PrivateMeow {} "} {"_id":"doc-en-rust-9ceac4c9a94f309f3679479006364a9c6a81788510c0b6306cbfd3366916075d","title":"","text":" // aux-build:meow.rs extern crate meow; use meow::Meow; fn needs_meow(t: T) {} fn main() { needs_meow(1usize); //~^ ERROR the trait bound `usize: Meow` is not satisfied } struct LocalMeow; impl Meow for LocalMeow {} "} {"_id":"doc-en-rust-0f9351d83c6d2b524879a38c2fed929b833c15b0cdb5f2070bcd87c64fffcf31","title":"","text":" error[E0277]: the trait bound `usize: Meow` is not satisfied --> $DIR/issue-99080.rs:10:16 | LL | needs_meow(1usize); | ---------- ^^^^^^ the trait `Meow` is not implemented for `usize` | | | required by a bound introduced by this call | = help: the following other types implement trait `Meow`: GlobalMeow LocalMeow note: required by a bound in `needs_meow` --> $DIR/issue-99080.rs:7:18 | LL | fn needs_meow(t: T) {} | ^^^^ required by this bound in `needs_meow` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. "} {"_id":"doc-en-rust-aed386dd6117f7c1b1bdec94a259b60eda31824696a44196f94a473a7c83772a","title":"","text":"&'c &'b str [char; N] char pattern::MultiCharEqPattern = note: required because of the requirements on the impl of `Pattern<'_>` for `u8` error: aborting due to previous error"} {"_id":"doc-en-rust-72c786a35663f5833ff572809bb655c8a001776720294540e7eaae1cfbafecfd","title":"","text":"/// in the given deque. The collection may reserve more space to speculatively avoid /// frequent reallocations. After calling `try_reserve`, capacity will be /// greater than or equal to `self.len() + additional` if it returns /// `Ok(())`. Does nothing if capacity is already sufficient. /// `Ok(())`. Does nothing if capacity is already sufficient. This method /// preserves the contents even if an error occurs. /// /// # Errors ///"} {"_id":"doc-en-rust-9c86e1bf8eb49e9cb2b58ffa744a6684ae4bfa87c27808594b79515d5c436d92","title":"","text":"/// current length. The allocator may reserve more space to speculatively /// avoid frequent allocations. After calling `try_reserve`, capacity will be /// greater than or equal to `self.len() + additional` if it returns /// `Ok(())`. Does nothing if capacity is already sufficient. /// `Ok(())`. Does nothing if capacity is already sufficient. This method /// preserves the contents even if an error occurs. /// /// # Errors ///"} {"_id":"doc-en-rust-f49f30e8e3584639b0140fdfbd82e04ee0d2f784174769dd2486a53f2eaa0eff","title":"","text":"/// in the given `Vec`. The collection may reserve more space to speculatively avoid /// frequent reallocations. After calling `try_reserve`, capacity will be /// greater than or equal to `self.len() + additional` if it returns /// `Ok(())`. Does nothing if capacity is already sufficient. /// `Ok(())`. Does nothing if capacity is already sufficient. This method /// preserves the contents even if an error occurs. /// /// # Errors ///"} {"_id":"doc-en-rust-d96388b2fbf5e2e313661fa66cbd30d0a6c9083cd224b96bda29e1014c25f1cc","title":"","text":"/// in the given `OsString`. The string may reserve more space to speculatively avoid /// frequent reallocations. After calling `try_reserve`, capacity will be /// greater than or equal to `self.len() + additional` if it returns `Ok(())`. /// Does nothing if capacity is already sufficient. /// Does nothing if capacity is already sufficient. This method preserves /// the contents even if an error occurs. /// /// See the main `OsString` documentation information about encoding and capacity units. ///"} {"_id":"doc-en-rust-4a759445f3999d560115f1b2289429ea4838e7dd9a43a18aaf1b59a7d7cf778c","title":"","text":"/// in the given `Wtf8Buf`. The `Wtf8Buf` may reserve more space to avoid /// frequent reallocations. After calling `try_reserve`, capacity will be /// greater than or equal to `self.len() + additional`. Does nothing if /// capacity is already sufficient. /// capacity is already sufficient. This method preserves the contents even /// if an error occurs. /// /// # Errors ///"} {"_id":"doc-en-rust-904c65b75d734534efd78c838a2ffa1d8baa9cfca3266daa8921114ef3065f73","title":"","text":".collect::, _>>()?; let offset = st[i].fields().offset(field_index) + niche.offset; let size = st[i].size(); // Align the total size to the largest alignment. let size = st[i].size().align_to(align.abi); let abi = if st.iter().all(|v| v.abi().is_uninhabited()) { Abi::Uninhabited } else { } else if align == st[i].align() && size == st[i].size() { // When the total alignment and size match, we can use the // same ABI as the scalar variant with the reserved niche. match st[i].abi() { Abi::Scalar(_) => Abi::Scalar(niche_scalar), Abi::ScalarPair(first, second) => {"} {"_id":"doc-en-rust-fa5a4cedc0d29c9043d4ff5a7ad044422f14584ba5f538566b385b8d837f9ba4","title":"","text":"} _ => Abi::Aggregate { sized: true }, } } else { Abi::Aggregate { sized: true } }; let largest_niche = Niche::from_scalar(dl, offset, niche_scalar);"} {"_id":"doc-en-rust-bea8c337ff125844d4977dbd887db71dc257fb0c9ee104ee52a104c6d90e542f","title":"","text":" // normalize-stderr-test \"pref: Align([1-8] bytes)\" -> \"pref: $$PREF_ALIGN\" #![feature(rustc_attrs)] #![crate_type = \"lib\"] // Various tests around the behavior of zero-sized arrays and // enum niches, especially that they have coherent size and alignment. // The original problem in #99836 came from ndarray's `TryFrom` for // `SliceInfo<[SliceInfoElem; 0], Din, Dout>`, where that returns // `Result` ~= `Result`. // This is a close enough approximation: #[rustc_layout(debug)] type AlignedResult = Result<[u32; 0], bool>; //~ ERROR: layout_of // The bug gave that size 1 with align 4, but the size should also be 4. // It was also using the bool niche for the enum tag, which is fine, but // after the fix, layout decides to use a direct tagged repr instead. // Here's another case with multiple ZST alignments, where we should // get the maximal alignment and matching size. #[rustc_layout(debug)] enum MultipleAlignments { //~ ERROR: layout_of Align2([u16; 0]), Align4([u32; 0]), Niche(bool), } // Tagged repr is clever enough to grow tags to fill any padding, e.g.: // 1. `T_FF` (one byte of Tag, one byte of padding, two bytes of align=2 Field) // -> `TTFF` (Tag has expanded to two bytes, i.e. like `#[repr(u16)]`) // 2. `TFF` (one byte of Tag, two bytes of align=1 Field) // -> Tag has no room to expand! // (this outcome can be forced onto 1. by wrapping Field in `Packed<...>`) #[repr(packed)] struct Packed(T); #[rustc_layout(debug)] type NicheLosesToTagged = Result<[u32; 0], Packed>; //~ ERROR: layout_of // Should get tag_encoding: Direct, size == align == 4. #[repr(u16)] enum U16IsZero { _Zero = 0 } #[rustc_layout(debug)] type NicheWinsOverTagged = Result<[u32; 0], Packed>; //~ ERROR: layout_of // Should get tag_encoding: Niche, size == align == 4. "} {"_id":"doc-en-rust-9cc137d8834aef333c73463f92ad2a4e8aee243d5ffdf5fa229ec59323995065","title":"","text":" error: layout_of(std::result::Result<[u32; 0], bool>) = Layout { fields: Arbitrary { offsets: [ Size(0 bytes), ], memory_index: [ 0, ], }, variants: Multiple { tag: Initialized { value: Int( I8, false, ), valid_range: 0..=1, }, tag_encoding: Direct, tag_field: 0, variants: [ Layout { fields: Arbitrary { offsets: [ Size(4 bytes), ], memory_index: [ 0, ], }, variants: Single { index: 0, }, abi: Aggregate { sized: true, }, largest_niche: None, align: AbiAndPrefAlign { abi: Align(4 bytes), pref: $PREF_ALIGN, }, size: Size(4 bytes), }, Layout { fields: Arbitrary { offsets: [ Size(1 bytes), ], memory_index: [ 0, ], }, variants: Single { index: 1, }, abi: Aggregate { sized: true, }, largest_niche: Some( Niche { offset: Size(1 bytes), value: Int( I8, false, ), valid_range: 0..=1, }, ), align: AbiAndPrefAlign { abi: Align(1 bytes), pref: $PREF_ALIGN, }, size: Size(2 bytes), }, ], }, abi: Aggregate { sized: true, }, largest_niche: Some( Niche { offset: Size(0 bytes), value: Int( I8, false, ), valid_range: 0..=1, }, ), align: AbiAndPrefAlign { abi: Align(4 bytes), pref: $PREF_ALIGN, }, size: Size(4 bytes), } --> $DIR/zero-sized-array-enum-niche.rs:13:1 | LL | type AlignedResult = Result<[u32; 0], bool>; | ^^^^^^^^^^^^^^^^^^ error: layout_of(MultipleAlignments) = Layout { fields: Arbitrary { offsets: [ Size(0 bytes), ], memory_index: [ 0, ], }, variants: Multiple { tag: Initialized { value: Int( I8, false, ), valid_range: 0..=2, }, tag_encoding: Direct, tag_field: 0, variants: [ Layout { fields: Arbitrary { offsets: [ Size(2 bytes), ], memory_index: [ 0, ], }, variants: Single { index: 0, }, abi: Aggregate { sized: true, }, largest_niche: None, align: AbiAndPrefAlign { abi: Align(2 bytes), pref: $PREF_ALIGN, }, size: Size(2 bytes), }, Layout { fields: Arbitrary { offsets: [ Size(4 bytes), ], memory_index: [ 0, ], }, variants: Single { index: 1, }, abi: Aggregate { sized: true, }, largest_niche: None, align: AbiAndPrefAlign { abi: Align(4 bytes), pref: $PREF_ALIGN, }, size: Size(4 bytes), }, Layout { fields: Arbitrary { offsets: [ Size(1 bytes), ], memory_index: [ 0, ], }, variants: Single { index: 2, }, abi: Aggregate { sized: true, }, largest_niche: Some( Niche { offset: Size(1 bytes), value: Int( I8, false, ), valid_range: 0..=1, }, ), align: AbiAndPrefAlign { abi: Align(1 bytes), pref: $PREF_ALIGN, }, size: Size(2 bytes), }, ], }, abi: Aggregate { sized: true, }, largest_niche: Some( Niche { offset: Size(0 bytes), value: Int( I8, false, ), valid_range: 0..=2, }, ), align: AbiAndPrefAlign { abi: Align(4 bytes), pref: $PREF_ALIGN, }, size: Size(4 bytes), } --> $DIR/zero-sized-array-enum-niche.rs:21:1 | LL | enum MultipleAlignments { | ^^^^^^^^^^^^^^^^^^^^^^^ error: layout_of(std::result::Result<[u32; 0], Packed>) = Layout { fields: Arbitrary { offsets: [ Size(0 bytes), ], memory_index: [ 0, ], }, variants: Multiple { tag: Initialized { value: Int( I8, false, ), valid_range: 0..=1, }, tag_encoding: Direct, tag_field: 0, variants: [ Layout { fields: Arbitrary { offsets: [ Size(4 bytes), ], memory_index: [ 0, ], }, variants: Single { index: 0, }, abi: Aggregate { sized: true, }, largest_niche: None, align: AbiAndPrefAlign { abi: Align(4 bytes), pref: $PREF_ALIGN, }, size: Size(4 bytes), }, Layout { fields: Arbitrary { offsets: [ Size(1 bytes), ], memory_index: [ 0, ], }, variants: Single { index: 1, }, abi: Aggregate { sized: true, }, largest_niche: Some( Niche { offset: Size(1 bytes), value: Int( I16, false, ), valid_range: 1..=65535, }, ), align: AbiAndPrefAlign { abi: Align(1 bytes), pref: $PREF_ALIGN, }, size: Size(3 bytes), }, ], }, abi: Aggregate { sized: true, }, largest_niche: Some( Niche { offset: Size(0 bytes), value: Int( I8, false, ), valid_range: 0..=1, }, ), align: AbiAndPrefAlign { abi: Align(4 bytes), pref: $PREF_ALIGN, }, size: Size(4 bytes), } --> $DIR/zero-sized-array-enum-niche.rs:37:1 | LL | type NicheLosesToTagged = Result<[u32; 0], Packed>; | ^^^^^^^^^^^^^^^^^^^^^^^ error: layout_of(std::result::Result<[u32; 0], Packed>) = Layout { fields: Arbitrary { offsets: [ Size(0 bytes), ], memory_index: [ 0, ], }, variants: Multiple { tag: Initialized { value: Int( I16, false, ), valid_range: 0..=1, }, tag_encoding: Niche { dataful_variant: 1, niche_variants: 0..=0, niche_start: 1, }, tag_field: 0, variants: [ Layout { fields: Arbitrary { offsets: [ Size(0 bytes), ], memory_index: [ 0, ], }, variants: Single { index: 0, }, abi: Aggregate { sized: true, }, largest_niche: None, align: AbiAndPrefAlign { abi: Align(4 bytes), pref: $PREF_ALIGN, }, size: Size(0 bytes), }, Layout { fields: Arbitrary { offsets: [ Size(0 bytes), ], memory_index: [ 0, ], }, variants: Single { index: 1, }, abi: Aggregate { sized: true, }, largest_niche: Some( Niche { offset: Size(0 bytes), value: Int( I16, false, ), valid_range: 0..=0, }, ), align: AbiAndPrefAlign { abi: Align(1 bytes), pref: $PREF_ALIGN, }, size: Size(2 bytes), }, ], }, abi: Aggregate { sized: true, }, largest_niche: Some( Niche { offset: Size(0 bytes), value: Int( I16, false, ), valid_range: 0..=1, }, ), align: AbiAndPrefAlign { abi: Align(4 bytes), pref: $PREF_ALIGN, }, size: Size(4 bytes), } --> $DIR/zero-sized-array-enum-niche.rs:44:1 | LL | type NicheWinsOverTagged = Result<[u32; 0], Packed>; | ^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 4 previous errors "}