<del> // ---------------------------------------------------------------------------- // // Inno Setup Ver:	5.4.2 // Script Version:	1.4.1 // Author:			Jared Breland <jbreland@legroom.net> // Homepage:		http://www.legroom.net/software // License:			GNU Lesser General Public License (LGPL), version 3 //						http://www.gnu.org/licenses/lgpl.html // // Script Function: //	Allow modification of environmental path directly from Inno Setup installers // // Instructions: //	Copy modpath.iss to the same directory as your setup script // //	Add this statement to your [Setup] section //		ChangesEnvironment=true // //	Add this statement to your [Tasks] section //	You can change the Description or Flags //	You can change the Name, but it must match the ModPathName setting below //		Name: modifypath; Description: &Add application directory to your environmental path; Flags: unchecked // //	Add the following to the end of your [Code] section //	ModPathName defines the name of the task defined above //	ModPathType defines whether the 'user' or 'system' path will be modified; //		this will default to user if anything other than system is set //	setArrayLength must specify the total number of dirs to be added //	Result[0] contains first directory, Result[1] contains second, etc. //		const //			ModPathName = 'modifypath'; //			ModPathType = 'user'; // //		function ModPathDir(): TArrayOfString; //		begin //			setArrayLength(Result, 1); //			Result[0] := ExpandConstant('{app}'); //		end; //		#include "modpath.iss" // ---------------------------------------------------------------------------- procedure ModPath(); var oldpath:	String; newpath:	String; updatepath:	Boolean; pathArr:	TArrayOfString; aExecFile:	String; aExecArr:	TArrayOfString; i, d:		Integer; pathdir:	TArrayOfString; regroot:	Integer; regpath:	String; begin // Get constants from main script and adjust behavior accordingly // ModPathType MUST be 'system' or 'user'; force 'user' if invalid if ModPathType = 'system' then begin regroot := HKEY_LOCAL_MACHINE; regpath := 'SYSTEMCurrentControlSetControlSession ManagerEnvironment'; end else begin regroot := HKEY_CURRENT_USER; regpath := 'Environment'; end; // Get array of new directories and act on each individually pathdir := ModPathDir(); for d := 0 to GetArrayLength(pathdir)-1 do begin updatepath := true; // Modify WinNT path if UsingWinNT() = true then begin // Get current path, split into an array RegQueryStringValue(regroot, regpath, 'Path', oldpath); oldpath := oldpath + ';'; i := 0; while (Pos(';', oldpath) > 0) do begin SetArrayLength(pathArr, i+1); pathArr[i] := Copy(oldpath, 0, Pos(';', oldpath)-1); oldpath := Copy(oldpath, Pos(';', oldpath)+1, Length(oldpath)); i := i + 1; // Check if current directory matches app dir if pathdir[d] = pathArr[i-1] then begin // if uninstalling, remove dir from path if IsUninstaller() = true then begin continue; // if installing, flag that dir already exists in path end else begin updatepath := false; end; end; // Add current directory to new path if i = 1 then begin newpath := pathArr[i-1]; end else begin newpath := newpath + ';' + pathArr[i-1]; end; end; // Append app dir to path if not already included if (IsUninstaller() = false) AND (updatepath = true) then newpath := newpath + ';' + pathdir[d]; // Write new path RegWriteStringValue(regroot, regpath, 'Path', newpath); // Modify Win9x path end else begin // Convert to shortened dirname pathdir[d] := GetShortName(pathdir[d]); // If autoexec.bat exists, check if app dir already exists in path aExecFile := 'C:AUTOEXEC.BAT'; if FileExists(aExecFile) then begin LoadStringsFromFile(aExecFile, aExecArr); for i := 0 to GetArrayLength(aExecArr)-1 do begin if IsUninstaller() = false then begin // If app dir already exists while installing, skip add if (Pos(pathdir[d], aExecArr[i]) > 0) then updatepath := false; break; end else begin // If app dir exists and = what we originally set, then delete at uninstall if aExecArr[i] = 'SET PATH=%PATH%;' + pathdir[d] then aExecArr[i] := ''; end; end; end; // If app dir not found, or autoexec.bat didn't exist, then (create and) append to current path if (IsUninstaller() = false) AND (updatepath = true) then begin SaveStringToFile(aExecFile, #13#10 + 'SET PATH=%PATH%;' + pathdir[d], True); // If uninstalling, write the full autoexec out end else begin SaveStringsToFile(aExecFile, aExecArr, False); end; end; end; end; // Split a string into an array using passed delimiter procedure Explode(var Dest: TArrayOfString; Text: String; Separator: String); var i: Integer; begin i := 0; repeat SetArrayLength(Dest, i+1); if Pos(Separator,Text) > 0 then	begin Dest[i] := Copy(Text, 1, Pos(Separator, Text)-1); Text := Copy(Text, Pos(Separator,Text) + Length(Separator), Length(Text)); i := i + 1; end else begin Dest[i] := Text; Text := ''; end; until Length(Text)=0; end; procedure ModPathCurStepChanged(CurStep: TSetupStep); var taskname:	String; begin taskname := ModPathName; if CurStep = ssPostInstall then if IsTaskSelected(taskname) then ModPath(); end; procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); var aSelectedTasks:	TArrayOfString; i:				Integer; taskname:		String; regpath:		String; regstring:		String; appid:			String; begin // only run during actual uninstall if CurUninstallStep = usUninstall then begin // get list of selected tasks saved in registry at install time appid := '{#emit SetupSetting("AppId")}'; if appid = '' then appid := '{#emit SetupSetting("AppName")}'; regpath := ExpandConstant('SoftwareMicrosoftWindowsCurrentVersionUninstall'+appid+'_is1'); RegQueryStringValue(HKLM, regpath, 'Inno Setup: Selected Tasks', regstring); if regstring = '' then RegQueryStringValue(HKCU, regpath, 'Inno Setup: Selected Tasks', regstring); // check each task; if matches modpath taskname, trigger patch removal if regstring <> '' then begin taskname := ModPathName; Explode(aSelectedTasks, regstring, ','); if GetArrayLength(aSelectedTasks) > 0 then begin for i := 0 to GetArrayLength(aSelectedTasks)-1 do begin if comparetext(aSelectedTasks[i], taskname) = 0 then ModPath(); end; end; end; end; end; function NeedRestart(): Boolean; var taskname:	String; begin taskname := ModPathName; if IsTaskSelected(taskname) and not UsingWinNT() then begin Result := True; end else begin Result := False; end; end; </del>


<del> #define CFG_RELEASE_NUM GetEnv("CFG_RELEASE_NUM") #define CFG_RELEASE GetEnv("CFG_RELEASE") #define CFG_PACKAGE_NAME GetEnv("CFG_PACKAGE_NAME") #define CFG_BUILD GetEnv("CFG_BUILD") [Setup] SetupIconFile=rust-logo.ico AppName=Rust AppVersion={#CFG_RELEASE} AppCopyright=Copyright (C) 2006-2014 Mozilla Foundation, MIT license AppPublisher=Mozilla Foundation AppPublisherURL=http://www.rust-lang.org VersionInfoVersion={#CFG_RELEASE_NUM} LicenseFile=LICENSE.txt PrivilegesRequired=lowest DisableWelcomePage=true DisableProgramGroupPage=true DisableReadyPage=true DisableStartupPrompt=true OutputDir=. SourceDir=. OutputBaseFilename={#CFG_PACKAGE_NAME}-{#CFG_BUILD} DefaultDirName={sd}Rust Compression=lzma2/normal InternalCompressLevel=normal SolidCompression=no ChangesEnvironment=true ChangesAssociations=no AllowUNCPath=false AllowNoIcons=true Uninstallable=yes [Tasks] Name: modifypath; Description: &Add {app}bin to your PATH (recommended) [Components] Name: rust; Description: "Rust compiler and standard crates"; Types: full compact custom; Flags: fixed #ifdef MINGW Name: gcc; Description: "Linker and platform libraries"; Types: full #endif Name: docs; Description: "HTML documentation"; Types: full Name: cargo; Description: "Cargo, the Rust package manager"; Types: full Name: std; Description: "The Rust Standard Library"; Types: full // tool-rls-start Name: rls; Description: "RLS, the Rust Language Server" // tool-rls-end [Files] Source: "rustc/*.*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: rust #ifdef MINGW Source: "rust-mingw/*.*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: gcc #endif Source: "rust-docs/*.*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: docs Source: "cargo/*.*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: cargo Source: "rust-std/*.*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: std // tool-rls-start Source: "rls/*.*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: rls Source: "rust-analysis/*.*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: rls // tool-rls-end [Code] const ModPathName = 'modifypath'; ModPathType = 'user'; function ModPathDir(): TArrayOfString; begin setArrayLength(Result, 1) Result[0] := ExpandConstant('{app}bin'); end; #include "modpath.iss" #include "upgrade.iss" // Both modpath.iss and upgrade.iss want to overload CurStepChanged. // This version does the overload then delegates to each. procedure CurStepChanged(CurStep: TSetupStep); begin UpgradeCurStepChanged(CurStep); ModPathCurStepChanged(CurStep); end; </del>


<del> // The following code taken from https://stackoverflow.com/questions/2000296/innosetup-how-to-automatically-uninstall-previous-installed-version // It performs upgrades by running the uninstaller before the install ///////////////////////////////////////////////////////////////////// function GetUninstallString(): String; var sUnInstPath: String; sUnInstallString: String; begin sUnInstPath := ExpandConstant('SoftwareMicrosoftWindowsCurrentVersionUninstallRust_is1'); sUnInstallString := ''; if not RegQueryStringValue(HKLM, sUnInstPath, 'UninstallString', sUnInstallString) then RegQueryStringValue(HKCU, sUnInstPath, 'UninstallString', sUnInstallString); Result := sUnInstallString; end; ///////////////////////////////////////////////////////////////////// function IsUpgrade(): Boolean; begin Result := (GetUninstallString() <> ''); end; ///////////////////////////////////////////////////////////////////// function UnInstallOldVersion(): Integer; var sUnInstallString: String; iResultCode: Integer; begin // Return Values: // 1 - uninstall string is empty // 2 - error executing the UnInstallString // 3 - successfully executed the UnInstallString // default return value Result := 0; // get the uninstall string of the old app sUnInstallString := GetUninstallString(); if sUnInstallString <> '' then begin sUnInstallString := RemoveQuotes(sUnInstallString); if Exec(sUnInstallString, '/SILENT /NORESTART /SUPPRESSMSGBOXES','', SW_HIDE, ewWaitUntilTerminated, iResultCode) then Result := 3 else Result := 2; end else Result := 1; end; ///////////////////////////////////////////////////////////////////// procedure UpgradeCurStepChanged(CurStep: TSetupStep); begin if (CurStep=ssInstall) then begin if (IsUpgrade()) then begin UnInstallOldVersion(); end; end; end; </del>


Repeat{element: elt} } <ins> /// An iterator that yields nothing. #[unstable(feature="iter_empty", reason = "new addition")] pub struct Empty<T>(marker::PhantomData<T>); #[unstable(feature="iter_empty", reason = "new addition")] impl<T> Iterator for Empty<T> { type Item = T; fn next(&mut self) -> Option<T> { None } fn size_hint(&self) -> (usize, Option<usize>){ (0, Some(0)) } } #[unstable(feature="iter_empty", reason = "new addition")] impl<T> DoubleEndedIterator for Empty<T> { fn next_back(&mut self) -> Option<T> { None } } #[unstable(feature="iter_empty", reason = "new addition")] impl<T> ExactSizeIterator for Empty<T> { fn len(&self) -> usize { 0 } } // not #[derive] because that adds a Clone bound on T, // which isn't necessary. #[unstable(feature="iter_empty", reason = "new addition")] impl<T> Clone for Empty<T> { fn clone(&self) -> Empty<T> { Empty(marker::PhantomData) } } // not #[derive] because that adds a Default bound on T, // which isn't necessary. #[unstable(feature="iter_empty", reason = "new addition")] impl<T> Default for Empty<T> { fn default() -> Empty<T> { Empty(marker::PhantomData) } } /// Creates an iterator that yields nothing. #[unstable(feature="iter_empty", reason = "new addition")] pub fn empty<T>() -> Empty<T> { Empty(marker::PhantomData) } /// An iterator that yields an element exactly once. #[unstable(feature="iter_once", reason = "new addition")] pub struct Once<T> { inner: ::option::IntoIter<T> } #[unstable(feature="iter_once", reason = "new addition")] impl<T> Iterator for Once<T> { type Item = T; fn next(&mut self) -> Option<T> { self.inner.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } #[unstable(feature="iter_once", reason = "new addition")] impl<T> DoubleEndedIterator for Once<T> { fn next_back(&mut self) -> Option<T> { self.inner.next_back() } } #[unstable(feature="iter_once", reason = "new addition")] impl<T> ExactSizeIterator for Once<T> { fn len(&self) -> usize { self.inner.len() } } /// Creates an iterator that yields an element exactly once. #[unstable(feature="iter_once", reason = "new addition")] pub fn once<T>(value: T) -> Once<T> { Once { inner: Some(value).into_iter() } } </ins> /// Functions for lexicographical ordering of sequences. /// /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires


// Can't check len now because count consumes. } <ins> #[test] fn test_once() { let mut it = once(42); assert_eq!(it.next(), Some(42)); assert_eq!(it.next(), None); } #[test] fn test_empty() { let mut it = empty::<i32>(); assert_eq!(it.next(), None); } </ins> #[bench] fn bench_rposition(b: &mut Bencher) { let it: Vec<usize> = (0..300).collect();


#![feature(slice_patterns)] #![feature(float_from_str_radix)] #![feature(cell_extras)] <ins> #![feature(iter_empty)] #![feature(iter_once)] </ins> extern crate core; extern crate test;


T=$(command -v $P 2>&1) if [ $? -eq 0 ] then <del> VER0=$($P --version 2>/dev/null | head -1  |  sed -e 's/[^0-9]*([vV]?[0-9.]+[^ ]*).*/1/' ) </del> <ins> VER0=$($P --version 2>/dev/null  |  grep -o '[vV]?[0-9][0-9.][a-z0-9.-]*' | head -1 ) </ins> if [ $? -eq 0 -a "x${VER0}" != "x" ] then VER="($VER0)"


probe_need CFG_GIT     git fi <ins> # Use `md5sum` on GNU platforms, or `md5 -q` on BSD probe CFG_MD5              md5 probe CFG_MD5SUM           md5sum if [ -n "$CFG_MD5" ] then CFG_HASH_COMMAND="$CFG_MD5 -q | head -c 8" elif [ -n "$CFG_MD5SUM" ] then CFG_HASH_COMMAND="$CFG_MD5SUM | head -c 8" else err 'could not find one of: md5 md5sum' fi putvar CFG_HASH_COMMAND </ins> probe CFG_CLANG            clang++ probe CFG_CCACHE           ccache probe CFG_GCC              gcc


# versions (section 9) CFG_PRERELEASE_VERSION=.1 <del> CFG_FILENAME_EXTRA=4e7c5e5c </del> <ins> # Append a version-dependent hash to each library, so we can install different # versions in the same place CFG_FILENAME_EXTRA=$(shell printf '%s' $(CFG_RELEASE) | $(CFG_HASH_COMMAND)) </ins> ifeq ($(CFG_RELEASE_CHANNEL),stable) # This is the normal semver version string, e.g. "0.12.0", "0.12.0-nightly"


$(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # As above but don't bother running tidy. <del> check-notidy: cleantmptestlogs cleantestlibs all check-stage2 </del> <ins> check-notidy: check-sanitycheck cleantmptestlogs cleantestlibs all check-stage2 </ins> $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # A slightly smaller set of tests for smoke testing. <del> check-lite: cleantestlibs cleantmptestlogs  </del> <ins> check-lite: check-sanitycheck cleantestlibs cleantmptestlogs  </ins> $(foreach crate,$(TEST_TARGET_CRATES),check-stage2-$(crate))  check-stage2-rpass check-stage2-rpass-valgrind  check-stage2-rfail check-stage2-cfail check-stage2-pfail check-stage2-rmake $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # Only check the 'reference' tests: rpass/cfail/rfail/rmake. <del> check-ref: cleantestlibs cleantmptestlogs check-stage2-rpass check-stage2-rpass-valgrind  check-stage2-rfail check-stage2-cfail check-stage2-pfail check-stage2-rmake </del> <ins> check-ref: check-sanitycheck cleantestlibs cleantmptestlogs check-stage2-rpass  check-stage2-rpass-valgrind check-stage2-rfail check-stage2-cfail check-stage2-pfail  check-stage2-rmake </ins> $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # Only check the docs. <del> check-docs: cleantestlibs cleantmptestlogs check-stage2-docs </del> <ins> check-docs: check-sanitycheck cleantestlibs cleantmptestlogs check-stage2-docs </ins> $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log # Some less critical tests that are not prone to breakage.


# except according to those terms. import os <ins> import subprocess </ins> import sys import functools STATUS = 0 def error_unless_permitted(env_var, message): global STATUS if not os.getenv(env_var): sys.stderr.write(message) STATUS = 1 def only_on(platforms): def decorator(func): @functools.wraps(func)


return inner return decorator <del> @only_on(('linux', 'darwin', 'freebsd', 'openbsd')) </del> <ins> @only_on(['linux', 'darwin', 'freebsd', 'openbsd']) </ins> def check_rlimit_core(): import resource soft, hard = resource.getrlimit(resource.RLIMIT_CORE)


set ALLOW_NONZERO_RLIMIT_CORE to ignore this warning """ % (soft)) <ins> @only_on(['win32']) def check_console_code_page(): if '65001' not in subprocess.check_output(['cmd', '/c', 'chcp']): sys.stderr.write('Warning: the console output code page is not UTF-8,  some tests may fail. Use `cmd /c "chcp 65001"` to setup UTF-8 code page.n') </ins> def main(): <ins> check_console_code_page() </ins> check_rlimit_core() if __name__ == '__main__':


<ins> // Copyright (c) 2015 Anders Kaseorg <andersk@mit.edu> // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // “Software”), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //! This crate exports a macro `enum_from_primitive!` that wraps an //! `enum` declaration and automatically adds an implementation of //! `num::FromPrimitive` (reexported here), to allow conversion from //! primitive integers to the enum.  It therefore provides an //! alternative to the built-in `#[derive(FromPrimitive)]`, which //! requires the unstable `std::num::FromPrimitive` and is disabled in //! Rust 1.0. //! //! # Example //! //! ``` //! #[macro_use] extern crate enum_primitive; //! extern crate num_traits; //! use num_traits::FromPrimitive; //! //! enum_from_primitive! { //! #[derive(Debug, PartialEq)] //! enum FooBar { //!     Foo = 17, //!     Bar = 42, //!     Baz, //! } //! } //! //! fn main() { //!     assert_eq!(FooBar::from_i32(17), Some(FooBar::Foo)); //!     assert_eq!(FooBar::from_i32(42), Some(FooBar::Bar)); //!     assert_eq!(FooBar::from_i32(43), Some(FooBar::Baz)); //!     assert_eq!(FooBar::from_i32(91), None); //! } //! ``` pub mod num_traits { pub trait FromPrimitive: Sized { fn from_i64(n: i64) -> Option<Self>; fn from_u64(n: u64) -> Option<Self>; } } pub use std::option::Option; pub use num_traits::FromPrimitive; /// Helper macro for internal use by `enum_from_primitive!`. #[macro_export] macro_rules! enum_from_primitive_impl_ty { ($meth:ident, $ty:ty, $name:ident, $( $variant:ident )*) => { #[allow(non_upper_case_globals, unused)] fn $meth(n: $ty) -> $crate::Option<Self> { $( if n == $name::$variant as $ty { $crate::Option::Some($name::$variant) } else )* { $crate::Option::None } } }; } /// Helper macro for internal use by `enum_from_primitive!`. #[macro_export] #[macro_use(enum_from_primitive_impl_ty)] macro_rules! enum_from_primitive_impl { ($name:ident, $( $variant:ident )*) => { impl $crate::FromPrimitive for $name { enum_from_primitive_impl_ty! { from_i64, i64, $name, $( $variant )* } enum_from_primitive_impl_ty! { from_u64, u64, $name, $( $variant )* } } }; } /// Wrap this macro around an `enum` declaration to get an /// automatically generated implementation of `num::FromPrimitive`. #[macro_export] #[macro_use(enum_from_primitive_impl)] macro_rules! enum_from_primitive { ( $( #[$enum_attr:meta] )* enum $name:ident { $( $( #[$variant_attr:meta] )* $variant:ident ),+ $( = $discriminator:expr, $( $( #[$variant_two_attr:meta] )* $variant_two:ident ),+ )* } ) => { $( #[$enum_attr] )* enum $name { $( $( #[$variant_attr] )* $variant ),+ $( = $discriminator, $( $( #[$variant_two_attr] )* $variant_two ),+ )* } enum_from_primitive_impl! { $name, $( $variant )+ $( $( $variant_two )+ )* } }; ( $( #[$enum_attr:meta] )* enum $name:ident { $( $( $( #[$variant_attr:meta] )* $variant:ident ),+ = $discriminator:expr ),* } ) => { $( #[$enum_attr] )* enum $name { $( $( $( #[$variant_attr] )* $variant ),+ = $discriminator ),* } enum_from_primitive_impl! { $name, $( $( $variant )+ )* } }; ( $( #[$enum_attr:meta] )* enum $name:ident { $( $( #[$variant_attr:meta] )* $variant:ident ),+ $( = $discriminator:expr, $( $( #[$variant_two_attr:meta] )* $variant_two:ident ),+ )*, } ) => { $( #[$enum_attr] )* enum $name { $( $( #[$variant_attr] )* $variant ),+ $( = $discriminator, $( $( #[$variant_two_attr] )* $variant_two ),+ )*, } enum_from_primitive_impl! { $name, $( $variant )+ $( $( $variant_two )+ )* } }; ( $( #[$enum_attr:meta] )* enum $name:ident { $( $( $( #[$variant_attr:meta] )* $variant:ident ),+ = $discriminator:expr ),+, } ) => { $( #[$enum_attr] )* enum $name { $( $( $( #[$variant_attr] )* $variant ),+ = $discriminator ),+, } enum_from_primitive_impl! { $name, $( $( $variant )+ )+ } }; ( $( #[$enum_attr:meta] )* pub enum $name:ident { $( $( #[$variant_attr:meta] )* $variant:ident ),+ $( = $discriminator:expr, $( $( #[$variant_two_attr:meta] )* $variant_two:ident ),+ )* } ) => { $( #[$enum_attr] )* pub enum $name { $( $( #[$variant_attr] )* $variant ),+ $( = $discriminator, $( $( #[$variant_two_attr] )* $variant_two ),+ )* } enum_from_primitive_impl! { $name, $( $variant )+ $( $( $variant_two )+ )* } }; ( $( #[$enum_attr:meta] )* pub enum $name:ident { $( $( $( #[$variant_attr:meta] )* $variant:ident ),+ = $discriminator:expr ),* } ) => { $( #[$enum_attr] )* pub enum $name { $( $( $( #[$variant_attr] )* $variant ),+ = $discriminator ),* } enum_from_primitive_impl! { $name, $( $( $variant )+ )* } }; ( $( #[$enum_attr:meta] )* pub enum $name:ident { $( $( #[$variant_attr:meta] )* $variant:ident ),+ $( = $discriminator:expr, $( $( #[$variant_two_attr:meta] )* $variant_two:ident ),+ )*, } ) => { $( #[$enum_attr] )* pub enum $name { $( $( #[$variant_attr] )* $variant ),+ $( = $discriminator, $( $( #[$variant_two_attr] )* $variant_two ),+ )*, } enum_from_primitive_impl! { $name, $( $variant )+ $( $( $variant_two )+ )* } }; ( $( #[$enum_attr:meta] )* pub enum $name:ident { $( $( $( #[$variant_attr:meta] )* $variant:ident ),+ = $discriminator:expr ),+, } ) => { $( #[$enum_attr] )* pub enum $name { $( $( $( #[$variant_attr] )* $variant ),+ = $discriminator ),+, } enum_from_primitive_impl! { $name, $( $( $variant )+ )+ } }; } </ins>


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // ensure this code doesn't stack overflow // aux-build:enum_primitive.rs #[macro_use] extern crate enum_primitive; enum_from_primitive! { pub enum Test { A1,A2,A3,A4,A5,A6, B1,B2,B3,B4,B5,B6, C1,C2,C3,C4,C5,C6, D1,D2,D3,D4,D5,D6, E1,E2,E3,E4,E5,E6, F1,F2,F3,F4,F5,F6, G1,G2,G3,G4,G5,G6, H1,H2,H3,H4,H5,H6, I1,I2,I3,I4,I5,I6, J1,J2,J3,J4,J5,J6, K1,K2,K3,K4,K5,K6, L1,L2,L3,L4,L5,L6, M1,M2,M3,M4,M5,M6, N1,N2,N3,N4,N5,N6, O1,O2,O3,O4,O5,O6, P1,P2,P3,P4,P5,P6, Q1,Q2,Q3,Q4,Q5,Q6, R1,R2,R3,R4,R5,R6, S1,S2,S3,S4,S5,S6, T1,T2,T3,T4,T5,T6, U1,U2,U3,U4,U5,U6, V1,V2,V3,V4,V5,V6, W1,W2,W3,W4,W5,W6, X1,X2,X3,X4,X5,X6, Y1,Y2,Y3,Y4,Y5,Y6, Z1,Z2,Z3,Z4,Z5,Z6, } } </ins>


If you're on Windows, please download either the [32-bit installer][win32] or the [64-bit installer][win64] and run it. <del> [win32]: https://static.rust-lang.org/dist/rust-1.0.0-beta-i686-pc-windows-gnu.msi [win64]: https://static.rust-lang.org/dist/rust-1.0.0-beta-x86_64-pc-windows-gnu.msi </del> <ins> [win32]: https://static.rust-lang.org/dist/rust-1.0.0-i686-pc-windows-gnu.msi [win64]: https://static.rust-lang.org/dist/rust-1.0.0-x86_64-pc-windows-gnu.msi </ins> ## Uninstalling


You should see the version number, commit hash, commit date and build date: ```bash <del> rustc 1.0.0-beta (9854143cb 2015-04-02) (built 2015-04-02) </del> <ins> rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14) </ins> ``` If you did, Rust has been installed successfully! Congrats!


str::from_utf8(&child_output.stdout).unwrap(), str::from_utf8(&child_output.stderr).unwrap())); <del> fs::remove_dir_all(&child_dir).unwrap(); </del> <ins> let res = fs::remove_dir_all(&child_dir); if res.is_err() { // On Windows deleting just executed mytest.exe can fail because it's still locked std::thread::sleep_ms(1000); fs::remove_dir_all(&child_dir).unwrap(); } </ins> }


.TP fBRUST_TEST_THREADSfR The test framework Rust provides executes tests in parallel. This variable sets <del> the maximum number of threads used for this purpose. </del> <ins> the maximum number of threads used for this purpose. This setting is overridden by the --test-threads option. </ins> .TP fBRUST_TEST_NOCAPTUREfR


pub nocapture: bool, pub color: ColorConfig, pub quiet: bool, <ins> pub test_threads: Option<usize>, </ins> } impl TestOpts {


nocapture: false, color: AutoColor, quiet: false, <ins> test_threads: None, </ins> } } }


of stdout", "PATH"), getopts::optflag("", "nocapture", "don't capture stdout/stderr of each  task, allow printing directly"), <ins> getopts::optopt("", "test-threads", "Number of threads used for running tests  in parallel", "n_threads"), </ins> getopts::optflag("q", "quiet", "Display one character per test instead of one line"), getopts::optopt("", "color", "Configure coloring of output: auto   = colorize if stdout is a tty and tests are run on serially (default);


tests whose names contain the filter are run. By default, all tests are run in parallel. This can be altered with the <del> RUST_TEST_THREADS environment variable when running tests (set it to 1). </del> <ins> --test-threads flag or the RUST_TEST_THREADS environment variable when running tests (set it to 1). </ins> All tests have their standard output and standard error captured by default. This can be overridden with the --nocapture flag or setting RUST_TEST_NOCAPTURE


}; } <ins> let test_threads = match matches.opt_str("test-threads") { Some(n_str) => match n_str.parse::<usize>() { Ok(n) => Some(n), Err(e) => return Some(Err(format!("argument for --test-threads must be a number > 0  (error: {})", e))) }, None => None, }; </ins> let color = match matches.opt_str("color").as_ref().map(|s| &**s) { Some("auto") | None => AutoColor, Some("always") => AlwaysColor,


nocapture: nocapture, color: color, quiet: quiet, <ins> test_threads: test_threads, </ins> }; Some(Ok(test_opts))


} }); <del> // It's tempting to just spawn all the tests at once, but since we have // many tests that run in other processes we would be making a big mess. let concurrency = get_concurrency(); </del> <ins> let concurrency = match opts.test_threads { Some(n) => n, None => get_concurrency(), }; </ins> let mut remaining = filtered_tests; remaining.reverse();


Err(_) => false }, color: test::AutoColor, <ins> test_threads: None, </ins> } }


dist-install-dir-$(1): PREPARE_LIB_CMD=$(DEFAULT_PREPARE_LIB_CMD) dist-install-dir-$(1): PREPARE_MAN_CMD=$(DEFAULT_PREPARE_MAN_CMD) dist-install-dir-$(1): PREPARE_CLEAN=true <del> dist-install-dir-$(1): prepare-base-dir-$(1) docs compiler-docs </del> <ins> dist-install-dir-$(1): prepare-base-dir-$(1) docs </ins> $$(Q)mkdir -p $$(PREPARE_DEST_DIR)/share/doc/rust $$(Q)$$(PREPARE_MAN_CMD) $$(S)COPYRIGHT $$(PREPARE_DEST_DIR)/share/doc/rust $$(Q)$$(PREPARE_MAN_CMD) $$(S)LICENSE-APACHE $$(PREPARE_DEST_DIR)/share/doc/rust


--legacy-manifest-dirs=rustlib,cargo $$(Q)rm -R tmp/dist/$$(PKG_NAME)-$(1)-image <del> dist-doc-install-dir-$(1): docs compiler-docs </del> <ins> dist-doc-install-dir-$(1): docs </ins> $$(Q)mkdir -p tmp/dist/$$(DOC_PKG_NAME)-$(1)-image/share/doc/rust $$(Q)cp -r doc tmp/dist/$$(DOC_PKG_NAME)-$(1)-image/share/doc/rust/html


# Just copy the docs to a folder under dist with the appropriate name # for uploading to S3 <del> dist-docs: docs compiler-docs </del> <ins> dist-docs: docs </ins> $(Q) rm -Rf dist/doc $(Q) mkdir -p dist/doc/ $(Q) cp -r doc dist/doc/$(CFG_PACKAGE_VERS)


[tuples]: primitive-types.html#tuples [enums]: enums.html <ins> # Ignoring bindings You can use `_` in a pattern to disregard the value. For example, here’s a `match` against a `Result<T, E>`: ```rust # let some_value: Result<i32, &'static str> = Err("There was an error"); match some_value { Ok(value) => println!("got a value: {}", value), Err(_) => println!("an error occurred"), } ``` In the first arm, we bind the value inside the `Ok` variant to `value`. But in the `Err` arm, we use `_` to disregard the specific error, and just print a general error message. `_` is valid in any pattern that creates a binding. This can be useful to ignore parts of a larger structure: ```rust fn coordinate() -> (i32, i32, i32) { // generate and return some sort of triple tuple # (1, 2, 3) } let (x, _, z) = coordinate(); ``` Here, we bind the first and last element of the tuple to `x` and `z`, but ignore the middle element. </ins> # Mix and Match Whew! That’s a lot of different ways to match things, and they can all be


use build_helper::output; <ins> #[cfg(not(target_os = "solaris"))] const SH_CMD: &'static str = "sh"; // On Solaris, sh is the historical bourne shell, not a POSIX shell, or bash. #[cfg(target_os = "solaris")] const SH_CMD: &'static str = "bash"; </ins> use {Build, Compiler, Mode}; use util::{cp_r, libdir, is_dylib, cp_filtered, copy};


let src = build.out.join(host).join("doc"); cp_r(&src, &dst); <del> let mut cmd = Command::new("sh"); </del> <ins> let mut cmd = Command::new(SH_CMD); </ins> cmd.arg(sanitize_sh(&build.src.join("src/rust-installer/gen-installer.sh"))) .arg("--product-name=Rust-Documentation") .arg("--rel-manifest-dir=rustlib")


.arg(host); build.run(&mut cmd); <del> let mut cmd = Command::new("sh"); </del> <ins> let mut cmd = Command::new(SH_CMD); </ins> cmd.arg(sanitize_sh(&build.src.join("src/rust-installer/gen-installer.sh"))) .arg("--product-name=Rust-MinGW") .arg("--rel-manifest-dir=rustlib")


} // Finally, wrap everything up in a nice tarball! <del> let mut cmd = Command::new("sh"); </del> <ins> let mut cmd = Command::new(SH_CMD); </ins> cmd.arg(sanitize_sh(&build.src.join("src/rust-installer/gen-installer.sh"))) .arg("--product-name=Rust") .arg("--rel-manifest-dir=rustlib")


let src = build.sysroot(compiler).join("lib/rustlib"); cp_r(&src.join(target), &dst); <del> let mut cmd = Command::new("sh"); </del> <ins> let mut cmd = Command::new(SH_CMD); </ins> cmd.arg(sanitize_sh(&build.src.join("src/rust-installer/gen-installer.sh"))) .arg("--product-name=Rust") .arg("--rel-manifest-dir=rustlib")


let image_src = src.join("save-analysis"); let dst = image.join("lib/rustlib").join(target).join("analysis"); t!(fs::create_dir_all(&dst)); <ins> println!("image_src: {:?}, dst: {:?}", image_src, dst); </ins> cp_r(&image_src, &dst); <del> let mut cmd = Command::new("sh"); </del> <ins> let mut cmd = Command::new(SH_CMD); </ins> cmd.arg(sanitize_sh(&build.src.join("src/rust-installer/gen-installer.sh"))) .arg("--product-name=Rust") .arg("--rel-manifest-dir=rustlib")


build.run(&mut cmd); // Create source tarball in rust-installer format <del> let mut cmd = Command::new("sh"); </del> <ins> let mut cmd = Command::new(SH_CMD); </ins> cmd.arg(sanitize_sh(&build.src.join("src/rust-installer/gen-installer.sh"))) .arg("--product-name=Rust") .arg("--rel-manifest-dir=rustlib")


input_tarballs.push_str(&sanitize_sh(&mingw_installer)); } <del> let mut cmd = Command::new("sh"); </del> <ins> let mut cmd = Command::new(SH_CMD); </ins> cmd.arg(sanitize_sh(&build.src.join("src/rust-installer/combine-installers.sh"))) .arg("--product-name=Rust") .arg("--rel-manifest-dir=rustlib")


This emphasizes that we have to go through the whole list of `chars`. <ins> ## Slicing You can get a slice of a string with slicing syntax: ```rust let dog = "hachiko"; let hachi = &dog[0..5]; ``` But note that these are _byte_ offsets, not _character_ offsets. So this will fail at runtime: ```rust,should_panic let dog = "忠犬ハチ公"; let hachi = &dog[0..2]; ``` with this error: ```text thread '<main>' panicked at 'index 0 and/or 2 in `忠犬ハチ公` do not lie on character boundary' ``` </ins> ## Concatenation If you have a `String`, you can concatenate a `&str` to the end of it:


} } <ins> // Format a number with thousands separators fn fmt_thousands_sep(mut n: usize, sep: char) -> String { use std::fmt::Write; let mut output = String::new(); let mut first = true; for &pow in &[9, 6, 3, 0] { let base = 10_usize.pow(pow); if pow == 0 || n / base != 0 { if first { output.write_fmt(format_args!("{}", n / base)).unwrap(); } else { output.write_fmt(format_args!("{:03}", n / base)).unwrap(); } if pow != 0 { output.push(sep); } first = false; } n %= base; } output } </ins> pub fn fmt_bench_samples(bs: &BenchSamples) -> String { <ins> use std::fmt::Write; let mut output = String::new(); let median = bs.ns_iter_summ.median as usize; let deviation = (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize; output.write_fmt(format_args!("{:>11} ns/iter (+/- {})", fmt_thousands_sep(median, ','), fmt_thousands_sep(deviation, ','))).unwrap(); </ins> if bs.mb_s != 0 { <del> format!("{:>9} ns/iter (+/- {}) = {} MB/s", bs.ns_iter_summ.median as usize, (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize, bs.mb_s) } else { format!("{:>9} ns/iter (+/- {})", bs.ns_iter_summ.median as usize, (bs.ns_iter_summ.max - bs.ns_iter_summ.min) as usize) </del> <ins> output.write_fmt(format_args!(" = {} MB/s", bs.mb_s)).unwrap(); </ins> } <ins> output </ins> } // A simple console test runner


branches: - 'master' schedule: <del> - cron: '5 15 * * *' # At 15:05 UTC every day. </del> <ins> - cron: '6 6 * * *' # At 6:06 UTC every day. </ins> env: CARGO_UNSTABLE_SPARSE_REGISTRY: 'true'


strategy: fail-fast: false matrix: <del> build: [linux64, macos, win32] </del> include: <del> - build: linux64 os: ubuntu-latest </del> <ins> - os: ubuntu-latest </ins> host_target: x86_64-unknown-linux-gnu <del> - build: macos os: macos-latest </del> <ins> - os: macos-latest </ins> host_target: x86_64-apple-darwin <del> - build: win32 os: windows-latest </del> <ins> - os: windows-latest </ins> host_target: i686-pc-windows-msvc steps: - uses: actions/checkout@v3


;; i686-pc-windows-msvc) MIRI_TEST_TARGET=x86_64-unknown-linux-gnu run_tests <ins> MIRI_TEST_TARGET=x86_64-pc-windows-gnu run_tests </ins> ;; *) echo "FATAL: unknown OS"


mir, ty::{self, FloatTy, Ty}, }; <del> use rustc_target::abi::Integer; </del> <ins> use rustc_target::abi::{Integer, Size}; </ins> use crate::*; use atomic::EvalContextExt as _;


this.write_bytes_ptr(ptr, iter::repeat(val_byte).take(byte_count.bytes_usize()))?; } <ins> "ptr_mask" => { let [ptr, mask] = check_arg_count(args)?; let ptr = this.read_pointer(ptr)?; let mask = this.read_scalar(mask)?.to_machine_usize(this)?; let masked_addr = Size::from_bytes(ptr.addr().bytes() & mask); this.write_pointer(Pointer::new(ptr.provenance, masked_addr), dest)?; } </ins> // Floating-point operations "fabsf32" => { let [f] = check_arg_count(args)?;


let [name] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; let thread = this.pthread_self()?; let max_len = this.eval_libc("MAXTHREADNAMESIZE")?.to_machine_usize(this)?; <del> this.pthread_setname_np( </del> <ins> let res = this.pthread_setname_np( </ins> thread, this.read_scalar(name)?, max_len.try_into().unwrap(), )?; <ins> // Contrary to the manpage, `pthread_setname_np` on macOS still // returns an integer indicating success. this.write_scalar(res, dest)?; </ins> } "pthread_getname_np" => { let [thread, name, len] =


//@ignore-target-windows: No libc on Windows #![feature(cstr_from_bytes_until_nul)] <del> use std::ffi::CStr; </del> <ins> use std::ffi::{CStr, CString}; </ins> use std::thread; fn main() {


.chain(std::iter::repeat(" yada").take(100)) .collect::<String>(); <ins> fn set_thread_name(name: &CStr) -> i32 { #[cfg(target_os = "linux")] return unsafe { libc::pthread_setname_np(libc::pthread_self(), name.as_ptr().cast()) }; #[cfg(target_os = "macos")] return unsafe { libc::pthread_setname_np(name.as_ptr().cast()) }; } </ins> let result = thread::Builder::new().name(long_name.clone()).spawn(move || { // Rust remembers the full thread name itself. assert_eq!(thread::current().name(), Some(long_name.as_str()));


// But the system is limited -- make sure we successfully set a truncation. let mut buf = vec![0u8; long_name.len() + 1]; unsafe { <del> libc::pthread_getname_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len()); } </del> <ins> libc::pthread_getname_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len()) }; </ins> let cstr = CStr::from_bytes_until_nul(&buf).unwrap(); assert!(cstr.to_bytes().len() >= 15); // POSIX seems to promise at least 15 chars assert!(long_name.as_bytes().starts_with(cstr.to_bytes())); <ins> // Also test directly calling pthread_setname to check its return value. assert_eq!(set_thread_name(&cstr), 0); // But with a too long name it should fail. assert_ne!(set_thread_name(&CString::new(long_name).unwrap()), 0); </ins> }); result.unwrap().join().unwrap(); }


<ins> #![feature(ptr_mask)] #![feature(strict_provenance)] fn main() { let v: u32 = 0xABCDABCD; let ptr: *const u32 = &v; // u32 is 4 aligned, // so the lower `log2(4) = 2` bits of the address are always 0 assert_eq!(ptr.addr() & 0b11, 0); let tagged_ptr = ptr.map_addr(|a| a | 0b11); let tag = tagged_ptr.addr() & 0b11; let masked_ptr = tagged_ptr.mask(!0b11); assert_eq!(tag, 0b11); assert_eq!(unsafe { *masked_ptr }, 0xABCDABCD); } </ins>


concurrent code at compile time. Before we talk about the concurrency features that come with Rust, it's important <del> to understand something: Rust is low-level enough that all of this is provided by the standard library, not by the language. This means that if you don't like some aspect of the way Rust handles concurrency, you can implement an alternative way of doing things. [mio](https://github.com/carllerche/mio) is a real-world example of this principle in action. </del> <ins> to understand something: Rust is low-level enough that the vast majority of this is provided by the standard library, not by the language. This means that if you don't like some aspect of the way Rust handles concurrency, you can implement an alternative way of doing things. [mio](https://github.com/carllerche/mio) is a real-world example of this principle in action. </ins> ## Background: `Send` and `Sync`


repr: Repr, } <del> #[derive(Debug)] </del> enum Repr { Os(i32), Custom(Box<Custom>),


} } <ins> impl fmt::Debug for Repr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match self { &Repr::Os(ref code) => fmt.debug_struct("Os").field("code", code) .field("message", &sys::os::error_string(*code)).finish(), &Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(), } } } </ins> #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {


use error; use error::Error as error_Error; use fmt; <ins> use sys::os::error_string; #[test] fn test_debug_error() { let code = 6; let msg = error_string(code); let err = Error { repr: super::Repr::Os(code) }; let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg); assert_eq!(format!("{:?}", err), expected); } </ins> #[test] fn test_downcasting() {


/// A macro which expands to the line number on which it was invoked. /// <del> /// The expanded expression has type `usize`, and the returned line is not </del> <ins> /// The expanded expression has type `u32`, and the returned line is not </ins> /// the invocation of the `line!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `line!()` macro. ///


/// A macro which expands to the column number on which it was invoked. /// <del> /// The expanded expression has type `usize`, and the returned column is not </del> <ins> /// The expanded expression has type `u32`, and the returned column is not </ins> /// the invocation of the `column!()` macro itself, but rather the first macro /// invocation leading up to the invocation of the `column!()` macro. ///


/// /// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`. <ins> /// /// When this trait is `derive`d, it produces a lexicographic ordering. </ins> #[stable(feature = "rust1", since = "1.0.0")] pub trait Ord: Eq + PartialOrd<Self> { /// This method returns an `Ordering` between `self` and `other`.


encode_item_sort(rbml_w, 't'); encode_family(rbml_w, 'y'); <ins> if let Some(ty) = associated_type.ty { encode_type(ecx, rbml_w, ty); } </ins> is_nonstatic_method = false; } }


// ought to be reported by the type checker method // `check_impl_items_against_trait`, so here we // just return TyError. <ins> debug!("confirm_impl_candidate: no associated type {:?} for {:?}", assoc_ty.name, trait_ref); </ins> return (selcx.tcx().types.err, vec!()); } }


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait Foo { type Input = usize; fn bar(&self, _: Self::Input) {} } impl Foo for () {} </ins>


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // aux-build:xcrate_associated_type_defaults.rs extern crate xcrate_associated_type_defaults; use xcrate_associated_type_defaults::Foo; fn main() { ().bar(5); } </ins>


match base_cmt.cat { mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) | mc::cat_local(vid) => { <del> self.reassigned |= self.node == vid && Some(field) == self.field </del> <ins> self.reassigned |= self.node == vid && (self.field.is_none() || Some(field) == self.field) </ins> }, _ => {} }


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let mut c = (1, "".to_owned()); match c { c2 => { c.0 = 2; assert_eq!(c2.0, 1); } } } </ins>


// FOREIGN STATIC ITEM return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?)); } <del> if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) { </del> <ins> if self.check_keyword(keywords::Fn) { </ins> // FOREIGN FUNCTION ITEM return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?)); }


// compile-flags: -Z parse-only extern { <del> f(); //~ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `f` </del> <ins> f(); //~ ERROR expected one of `fn`, `pub`, `static`, or `}`, found `f` </ins> } fn main() {


extern { const i: isize; <del> //~^ ERROR expected one of `fn`, `pub`, `static`, `unsafe`, or `}`, found `const` </del> <ins> //~^ ERROR expected one of `fn`, `pub`, `static`, or `}`, found `const` </ins> }


/// Inserts the given element just after the element most recently returned by `.next()`. /// The inserted element does not appear in the iteration. /// <del> /// # Examples /// /// ``` /// #![feature(linked_list_extras)] /// /// use std::collections::LinkedList; /// /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect(); /// /// { ///     let mut it = list.iter_mut(); ///     assert_eq!(it.next().unwrap(), &1); ///     // insert `2` after `1` ///     it.insert_next(2); /// } /// { ///     let vec: Vec<_> = list.into_iter().collect(); ///     assert_eq!(vec, [1, 2, 3, 4]); /// } /// ``` </del> <ins> /// This method will be removed soon. </ins> #[inline] #[unstable( feature = "linked_list_extras", reason = "this is probably better handled by a cursor type -- we'll see", issue = "27794" )] <ins> #[rustc_deprecated( reason = "Deprecated in favor of CursorMut methods. This method will be removed soon.", since = "1.47.0" )] </ins> pub fn insert_next(&mut self, element: T) { match self.head { // `push_back` is okay with aliasing `element` references


/// Provides a reference to the next element, without changing the iterator. /// <del> /// # Examples /// /// ``` /// #![feature(linked_list_extras)] /// /// use std::collections::LinkedList; /// /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect(); /// /// let mut it = list.iter_mut(); /// assert_eq!(it.next().unwrap(), &1); /// assert_eq!(it.peek_next().unwrap(), &2); /// // We just peeked at 2, so it was not consumed from the iterator. /// assert_eq!(it.next().unwrap(), &2); /// ``` </del> <ins> /// This method will be removed soon. </ins> #[inline] #[unstable( feature = "linked_list_extras", reason = "this is probably better handled by a cursor type -- we'll see", issue = "27794" )] <ins> #[rustc_deprecated( reason = "Deprecated in favor of CursorMut methods. This method will be removed soon.", since = "1.47.0" )] </ins> pub fn peek_next(&mut self) -> Option<&mut T> { if self.len == 0 { None


} #[test] <del> fn test_insert_prev() { let mut m = list_from(&[0, 2, 4, 6, 8]); let len = m.len(); { let mut it = m.iter_mut(); it.insert_next(-2); loop { match it.next() { None => break, Some(elt) => { it.insert_next(*elt + 1); match it.peek_next() { Some(x) => assert_eq!(*x, *elt + 2), None => assert_eq!(8, *elt), } } } } it.insert_next(0); it.insert_next(1); } check_links(&m); assert_eq!(m.len(), 3 + len * 2); assert_eq!(m.into_iter().collect::<Vec<_>>(), [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]); } #[test] </del> #[cfg_attr(target_os = "emscripten", ignore)] fn test_send() { let n = list_from(&[1, 2, 3]);


#[stable(feature = "fused", since = "1.26.0")] impl<T> FusedIterator for IterMut<'_, T> {} <del> impl<T> IterMut<'_, T> { /// Inserts the given element just after the element most recently returned by `.next()`. /// The inserted element does not appear in the iteration. /// /// This method will be removed soon. #[inline] #[unstable( feature = "linked_list_extras", reason = "this is probably better handled by a cursor type -- we'll see", issue = "27794" )] #[rustc_deprecated( reason = "Deprecated in favor of CursorMut methods. This method will be removed soon.", since = "1.47.0" )] pub fn insert_next(&mut self, element: T) { match self.head { // `push_back` is okay with aliasing `element` references None => self.list.push_back(element), Some(head) => unsafe { let prev = match head.as_ref().prev { // `push_front` is okay with aliasing nodes None => return self.list.push_front(element), Some(prev) => prev, }; let node = Some( Box::leak(box Node { next: Some(head), prev: Some(prev), element }).into(), ); // Not creating references to entire nodes to not invalidate the // reference to `element` we handed to the user. (*prev.as_ptr()).next = node; (*head.as_ptr()).prev = node; self.list.len += 1; }, } } /// Provides a reference to the next element, without changing the iterator. /// /// This method will be removed soon. #[inline] #[unstable( feature = "linked_list_extras", reason = "this is probably better handled by a cursor type -- we'll see", issue = "27794" )] #[rustc_deprecated( reason = "Deprecated in favor of CursorMut methods. This method will be removed soon.", since = "1.47.0" )] pub fn peek_next(&mut self) -> Option<&mut T> { if self.len == 0 { None } else { unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) } } } } </del> /// A cursor over a `LinkedList`. /// /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.


for arg in &fd.inputs { match arg.pat.node { hir::PatIdent(hir::BindByValue(hir::MutImmutable), _, None) => {} <ins> hir::PatWild(_) => {} </ins> _ => { span_err!(self.tcx.sess, arg.pat.span, E0022, "arguments of constant functions can only


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] fn main() {} const fn size_ofs(_: usize) {} const fn size_ofs2(_foo: usize) {} </ins>


.rusttest { display: none; } pre.rust { position: relative; } <del> .test-arrow { </del> <ins> a.test-arrow { </ins> display: inline-block; position: absolute; <del> top: 0; right: 10px; font-size: 150%; -webkit-transform: scaleX(-1); transform: scaleX(-1); </del> <ins> background-color: #4e8bca; color: #f5f5f5; padding: 5px 10px 5px 10px; border-radius: 5px; font-size: 130%; top: 5px; right: 5px; </ins> } .methods .section-header {


} var a = document.createElement('a'); <del> a.textContent = '⇱'; </del> a.setAttribute('class', 'test-arrow'); <ins> a.textContent = 'Run'; </ins> var code = el.previousElementSibling.textContent;


let s = s.as_bytes(); let (integral, s) = eat_digits(s); match s.first() { <del> None => Valid(Decimal::new(integral, b"", 0)), </del> <ins> None => { if integral.is_empty() { return Invalid; // No digits at all } Valid(Decimal::new(integral, b"", 0)) } </ins> Some(&b'e') | Some(&b'E') => { if integral.is_empty() { return Invalid; // No digits before 'e'


} #[test] <ins> fn lonely_sign() { assert!("+".parse::<f32>().is_err()); assert!("-".parse::<f64>().is_err()); } #[test] fn whitespace() { assert!(" 1.0".parse::<f32>().is_err()); assert!("1.0 ".parse::<f64>().is_err()); } #[test] </ins> fn nan() { assert!("NaN".parse::<f32>().unwrap().is_nan()); assert!("NaN".parse::<f64>().unwrap().is_nan());


_ => { if ascii_only && first_source_char > 'x7F' { let last_pos = self.last_pos; <del> self.err_span_char(start, last_pos, "byte constant must be ASCII. Use a xHH escape for a  non-ASCII byte", first_source_char); </del> <ins> self.err_span_(start, last_pos, "byte constant must be ASCII. Use a xHH escape for a  non-ASCII byte"); </ins> return false; } }


``` ptr::read(&v as *const _ as *const SomeType) // `v` transmuted to `SomeType` ``` <ins> 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. </ins> "##, E0152: r##"


fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) -> Box<MacResult + 'static> { <del> static NUMERALS: &'static [(&'static str, u32)] = &[ </del> <ins> static NUMERALS: &'static [(&'static str, usize)] = &[ </ins> ("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C",  100), ("XC",  90), ("L",  50), ("XL",  40), ("X",   10), ("IX",   9), ("V",   5), ("IV",   4), ("I",    1)]; <del> let text = match args { [TokenTree::Token(_, token::Ident(s, _))] => s.to_string(), </del> <ins> if args.len() != 1 { cx.span_err( sp, &format!("argument should be a single identifier, but got {} arguments", args.len())); return DummyResult::any(sp); } let text = match args[0] { TokenTree::Token(_, token::Ident(s, _)) => s.to_string(), </ins> _ => { cx.span_err(sp, "argument should be a single identifier"); return DummyResult::any(sp);


} } <del> MacEager::expr(cx.expr_u32(sp, total)) </del> <ins> MacEager::expr(cx.expr_usize(sp, total)) </ins> } #[plugin_registrar]


("X",   10), ("IX",   9), ("V",   5), ("IV",   4), ("I",    1)]; <del> let text = match args { [TokenTree::Token(_, token::Ident(s, _))] => s.to_string(), </del> <ins> if args.len() != 1 { cx.span_err( sp, &format!("argument should be a single identifier, but got {} arguments", args.len())); return DummyResult::any(sp); } let text = match args[0] { TokenTree::Token(_, token::Ident(s, _)) => s.to_string(), </ins> _ => { cx.span_err(sp, "argument should be a single identifier"); return DummyResult::any(sp);


let path = match def.full_def() { def::DefStruct(def_id) => def_to_path(tcx, def_id), def::DefVariant(_, variant_did, _) => def_to_path(tcx, variant_did), <ins> def::DefFn(..) => return P(hir::Pat { id: expr.id, node: hir::PatLit(P(expr.clone())), span: span, }), </ins> _ => unreachable!() }; let pats = args.iter().map(|expr| const_expr_to_pat(tcx, &**expr, span)).collect();


_ => signal!(e, NonConstPath), }, Some(ast_map::NodeTraitItem(..)) => signal!(e, NonConstPath), <del> Some(_) => unimplemented!(), </del> <ins> Some(_) => signal!(e, UnimplementedConstVal("calling struct, tuple or variant")), </ins> } }


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] enum Cake { BlackForest, Marmor, } use Cake::*; const BOO: (Cake, Cake) = (Marmor, BlackForest); //~^ ERROR: constant evaluation error: non-constant path in constant expression [E0471] const FOO: Cake = BOO.1; const fn foo() -> Cake { Marmor //~ ERROR: constant evaluation error: non-constant path in constant expression [E0471] //~^ ERROR: non-constant path in constant expression } const WORKS: Cake = Marmor; const GOO: Cake = foo(); fn main() { match BlackForest { FOO => println!("hi"), //~ NOTE: in pattern here GOO => println!("meh"), //~ NOTE: in pattern here WORKS => println!("möp"), _ => println!("bye"), } } </ins>


<del> // Copyright 2012 The Rust Project Developers. See the COPYRIGHT </del> <ins> // Copyright 2015 The Rust Project Developers. See the COPYRIGHT </ins> // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //


// option. This file may not be copied, modified, or distributed // except according to those terms. <ins> #![feature(const_fn)] </ins> const FOO: isize = 10; const BAR: isize = 3; <ins> const fn foo() -> isize { 4 } const BOO: isize = foo(); </ins> pub fn main() { let x: isize = 3; let y = match x { FOO => 1, BAR => 2, <ins> BOO => 4, </ins> _ => 3 }; assert_eq!(y, 2);


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] const fn f() -> usize { 5 } struct A { field: usize, } fn main() { let _ = [0; f()]; } </ins>


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(const_fn)] struct A { field: usize, } const fn f() -> usize { 5 } fn main() { let _ = [0; f()]; } </ins>


function name will expand to either `::increment` or `::mylib::increment`. To keep this system simple and correct, `#[macro_use] extern crate ...` may <del> only appear at the root of your crate, not inside `mod`. This ensures that `$crate` is a single identifier. </del> <ins> only appear at the root of your crate, not inside `mod`. </ins> # The deep end


use fmt; use hash::{Hash, self}; use iter::IntoIterator; <del> use marker::{Sized, Unsize}; </del> <ins> use marker::{Copy, Sized, Unsize}; </ins> use option::Option; use slice::{Iter, IterMut, SliceExt};


} #[stable(feature = "rust1", since = "1.0.0")] <ins> impl<T:Copy> Clone for [T; $N] { fn clone(&self) -> [T; $N] { *self } } #[stable(feature = "rust1", since = "1.0.0")] </ins> impl<T: Hash> Hash for [T; $N] { fn hash<H: hash::Hasher>(&self, state: &mut H) { Hash::hash(&self[..], state)


} array_impl_default!{32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T} <del> macro_rules! array_impl_clone { {$n:expr, $i:expr, $($idx:expr,)*} => { #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for [T; $n] { fn clone(&self) -> [T; $n] { [self[$i-$i].clone(), $(self[$i-$idx].clone()),*] } } array_impl_clone!{$i, $($idx,)*} }; {$n:expr,} => { #[stable(feature = "rust1", since = "1.0.0")] impl<T: Clone> Clone for [T; 0] { fn clone(&self) -> [T; 0] { [] } } }; } array_impl_clone! { 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9,  8,  7,  6,  5,  4,  3,  2,  1,  0, } </del>


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // test for issue #30244 #[derive(Copy, Clone)] struct Array { arr: [[u8; 256]; 4] } pub fn main() {} </ins>


use self::Destination::*; <del> use codemap::{self, COMMAND_LINE_SP, COMMAND_LINE_EXPN, Pos, Span}; </del> <ins> use codemap::{self, COMMAND_LINE_SP, COMMAND_LINE_EXPN, DUMMY_SP, Pos, Span}; </ins> use diagnostics; use errors::{Level, RenderSpan, DiagnosticBuilder};


lvl: Level) { let error = match sp { Some(COMMAND_LINE_SP) => self.emit_(FileLine(COMMAND_LINE_SP), msg, code, lvl), <ins> Some(DUMMY_SP) | None => print_diagnostic(&mut self.dst, "", lvl, msg, code), </ins> Some(sp) => self.emit_(FullSpan(sp), msg, code, lvl), <del> None => print_diagnostic(&mut self.dst, "", lvl, msg, code), </del> }; if let Err(e) = error {


ex = ExprBreak(None); } hi = self.last_span.hi; <ins> } else if self.token.is_keyword(keywords::Let) { // Catch this syntax error here, instead of in `check_strict_keywords`, so // that we can explicitly mention that let is not to be used as an expression let mut db = self.fatal("expected expression, found statement (`let`)"); db.note("variable declaration using `let` is a statement"); return Err(db); </ins> } else if self.check(&token::ModSep) || self.token.is_ident() && !self.check_keyword(keywords::True) &&


// ignore-cross-compile <del> // error-pattern:expected identifier, found keyword `let` </del> <ins> // error-pattern:expected expression, found statement (`let`) </ins> #![feature(quote, rustc_private)]


} } <ins> #[stable(feature = "mpsc_debug", since = "1.7.0")] impl<T> fmt::Debug for Sender<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Sender {{ .. }}") } } </ins> //////////////////////////////////////////////////////////////////////////////// // SyncSender ////////////////////////////////////////////////////////////////////////////////


} } <ins> #[stable(feature = "mpsc_debug", since = "1.7.0")] impl<T> fmt::Debug for SyncSender<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "SyncSender {{ .. }}") } } </ins> //////////////////////////////////////////////////////////////////////////////// // Receiver ////////////////////////////////////////////////////////////////////////////////


} } <ins> #[stable(feature = "mpsc_debug", since = "1.7.0")] impl<T> fmt::Debug for Receiver<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Receiver {{ .. }}") } } </ins> #[stable(feature = "rust1", since = "1.0.0")] impl<T> fmt::Debug for SendError<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {


repro() } } <ins> #[test] fn fmt_debug_sender() { let (tx, _) = channel::<i32>(); assert_eq!(format!("{:?}", tx), "Sender { .. }"); } #[test] fn fmt_debug_recv() { let (_, rx) = channel::<i32>(); assert_eq!(format!("{:?}", rx), "Receiver { .. }"); } #[test] fn fmt_debug_sync_sender() { let (tx, _) = sync_channel::<i32>(1); assert_eq!(format!("{:?}", tx), "SyncSender { .. }"); } </ins> }


issue = "27800")] <ins> use fmt; </ins> use core::cell::{Cell, UnsafeCell}; use core::marker; use core::ptr;


} } <ins> #[stable(feature = "mpsc_debug", since = "1.7.0")] impl fmt::Debug for Select { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Select {{ .. }}") } } #[stable(feature = "mpsc_debug", since = "1.7.0")] impl<'rx, T:Send+'rx> fmt::Debug for Handle<'rx, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Handle {{ .. }}") } } </ins> #[cfg(test)] #[allow(unused_imports)] mod tests {


} } } <ins> #[test] fn fmt_debug_select() { let sel = Select::new(); assert_eq!(format!("{:?}", sel), "Select { .. }"); } #[test] fn fmt_debug_handle() { let (_, rx) = channel::<i32>(); let sel = Select::new(); let mut handle = sel.handle(&rx); assert_eq!(format!("{:?}", handle), "Handle { .. }"); } </ins> }


operand: OperandRef<'tcx>) { debug!("store_operand: operand={}", operand.repr(bcx)); <ins> // Avoid generating stores of zero-sized values, because the only way to have a zero-sized // value is through `undef`, and store itself is useless. if common::type_is_zero_size(bcx.ccx(), operand.ty) { return; } </ins> match operand.val { OperandValue::Ref(r) => base::memcpy_ty(bcx, lldest, r, operand.ty), OperandValue::Immediate(s) => base::store_ty(bcx, s, lldest, operand.ty),


}, _ => { for (i, operand) in operands.iter().enumerate() { <del> // Note: perhaps this should be StructGep, but // note that in some cases the values here will // not be structs but arrays. let lldest_i = build::GEPi(bcx, dest.llval, &[0, i]); self.trans_operand_into(bcx, lldest_i, operand); </del> <ins> let op = self.trans_operand(bcx, operand); // Do not generate stores and GEPis for zero-sized fields. if !common::type_is_zero_size(bcx.ccx(), op.ty) { // Note: perhaps this should be StructGep, but // note that in some cases the values here will // not be structs but arrays. let dest = build::GEPi(bcx, dest.llval, &[0, i]); self.store_operand(bcx, dest, op); } </ins> } } }


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-flags: -C no-prepopulate-passes #![feature(rustc_attrs)] #![crate_type = "lib"] use std::marker::PhantomData; struct Zst { phantom: PhantomData<Zst> } // CHECK-LABEL: @mir #[no_mangle] #[rustc_mir] fn mir(){ // CHECK-NOT: getelementptr // CHECK-NOT: store{{.*}}undef let x = Zst { phantom: PhantomData }; } </ins>


impl<R: io::Read> io::Read for Maybe<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { <del> Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), buf.len()), </del> <ins> Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0), </ins> Maybe::Fake => Ok(0) } }


impl Stdio { fn to_handle(&self, stdio_id: c::DWORD) -> io::Result<Handle> { match *self { <ins> // If no stdio handle is available, then inherit means that it // should still be unavailable so propagate the // INVALID_HANDLE_VALUE. </ins> Stdio::Inherit => { <del> stdio::get(stdio_id).and_then(|io| { io.handle().duplicate(0, true, c::DUPLICATE_SAME_ACCESS) }) </del> <ins> match stdio::get(stdio_id) { Ok(io) => io.handle().duplicate(0, true, c::DUPLICATE_SAME_ACCESS), Err(..) => Ok(Handle::new(c::INVALID_HANDLE_VALUE)), } </ins> } Stdio::Raw(handle) => { RawHandle::new(handle).duplicate(0, true, c::DUPLICATE_SAME_ACCESS)


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(libc)] extern crate libc; use std::process::{Command, Stdio}; use std::env; use std::io::{self, Read, Write}; #[cfg(unix)] unsafe fn without_stdio<R, F: FnOnce() -> R>(f: F) -> R { let doit = |a| { let r = libc::dup(a); assert!(r >= 0); return r }; let a = doit(0); let b = doit(1); let c = doit(2); assert!(libc::close(0) >= 0); assert!(libc::close(1) >= 0); assert!(libc::close(2) >= 0); let r = f(); assert!(libc::dup2(a, 0) >= 0); assert!(libc::dup2(b, 1) >= 0); assert!(libc::dup2(c, 2) >= 0); return r } #[cfg(windows)] unsafe fn without_stdio<R, F: FnOnce() -> R>(f: F) -> R { type DWORD = u32; type HANDLE = *mut u8; type BOOL = i32; const STD_INPUT_HANDLE: DWORD = -10i32 as DWORD; const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD; const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD; const INVALID_HANDLE_VALUE: HANDLE = !0 as HANDLE; extern "system" { fn GetStdHandle(which: DWORD) -> HANDLE; fn SetStdHandle(which: DWORD, handle: HANDLE) -> BOOL; } let doit = |id| { let handle = GetStdHandle(id); assert!(handle != INVALID_HANDLE_VALUE); assert!(SetStdHandle(id, INVALID_HANDLE_VALUE) != 0); return handle }; let a = doit(STD_INPUT_HANDLE); let b = doit(STD_OUTPUT_HANDLE); let c = doit(STD_ERROR_HANDLE); let r = f(); let doit = |id, handle| { assert!(SetStdHandle(id, handle) != 0); }; doit(STD_INPUT_HANDLE, a); doit(STD_OUTPUT_HANDLE, b); doit(STD_ERROR_HANDLE, c); return r } fn main() { if env::args().len() > 1 { println!("test"); assert!(io::stdout().write(b"testn").is_ok()); assert!(io::stderr().write(b"testn").is_ok()); assert_eq!(io::stdin().read(&mut [0; 10]).unwrap(), 0); return } // First, make sure reads/writes without stdio work if stdio itself is // missing. let (a, b, c) = unsafe { without_stdio(|| { let a = io::stdout().write(b"testn"); let b = io::stderr().write(b"testn"); let c = io::stdin().read(&mut [0; 10]); (a, b, c) }) }; assert_eq!(a.unwrap(), 5); assert_eq!(b.unwrap(), 5); assert_eq!(c.unwrap(), 0); // Second, spawn a child and do some work with "null" descriptors to make // sure it's ok let me = env::current_exe().unwrap(); let status = Command::new(&me) .arg("next") .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .status().unwrap(); assert!(status.success(), "{:?} isn't a success", status); // Finally, close everything then spawn a child to make sure everything is // *still* ok. let status = unsafe { without_stdio(|| Command::new(&me).arg("next").status()) }.unwrap(); assert!(status.success(), "{:?} isn't a success", status); } </ins>


repair, or remove installation" page and ensure "Add to PATH" is installed on the local hard drive. <ins> Rust does not do its own linking, and so you’ll need to have a linker installed. Doing so will depend on your specific system, consult its documentation for more details. </ins> If not, there are a number of places where we can get help. The easiest is [the #rust IRC channel on irc.mozilla.org][irc], which we can access through [Mibbit][mibbit]. Click that link, and we'll be chatting with other Rustaceans


[expect]: ../std/option/enum.Option.html#method.expect [panic]: error-handling.html <del> If we leave off calling these two methods, our program will compile, but </del> <ins> If we leave off calling this method, our program will compile, but </ins> we’ll get a warning: ```bash


} ``` <del> The new three lines: </del> <ins> The new two lines: </ins> ```rust,ignore let guess: u32 = guess.trim().parse()


/// // got a false, take_while() isn't used any more /// assert_eq!(iter.next(), None); /// ``` <ins> /// /// Because `take_while()` needs to look at the value in order to see if it /// should be included or not, consuming iterators will see that it is /// removed: /// /// ``` /// let a = [1, 2, 3, 4]; /// let mut iter = a.into_iter(); /// /// let result: Vec<i32> = iter.by_ref() ///                            .take_while(|n| **n != 3) ///                            .cloned() ///                            .collect(); /// /// assert_eq!(result, &[1, 2]); /// /// let result: Vec<i32> = iter.cloned().collect(); /// /// assert_eq!(result, &[4]); /// ``` /// /// The `3` is no longer there, because it was consumed in order to see if /// the iteration should stop, but wasn't placed back into the iterator or /// some similar thing. </ins> #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where


run_lints!(cx, check_item, late_passes, it); cx.visit_ids(|v| v.visit_item(it)); hir_visit::walk_item(cx, it); <ins> run_lints!(cx, check_item_post, late_passes, it); </ins> }) }


fn visit_block(&mut self, b: &hir::Block) { run_lints!(self, check_block, late_passes, b); hir_visit::walk_block(self, b); <ins> run_lints!(self, check_block_post, late_passes, b); </ins> } fn visit_arm(&mut self, a: &hir::Arm) {


run_lints!(cx, check_item, early_passes, it); cx.visit_ids(|v| v.visit_item(it)); ast_visit::walk_item(cx, it); <ins> run_lints!(cx, check_item_post, early_passes, it); </ins> }) }


fn visit_block(&mut self, b: &ast::Block) { run_lints!(self, check_block, early_passes, b); ast_visit::walk_block(self, b); <ins> run_lints!(self, check_block_post, early_passes, b); </ins> } fn visit_arm(&mut self, a: &ast::Arm) {


run_lints!(cx, check_crate, late_passes, krate); hir_visit::walk_crate(cx, krate); <ins> run_lints!(cx, check_crate_post, late_passes, krate); </ins> }); // If we missed any lints added to the session, then there's a bug somewhere


run_lints!(cx, check_crate, early_passes, krate); ast_visit::walk_crate(cx, krate); <ins> run_lints!(cx, check_crate_post, early_passes, krate); </ins> }); // Put the lint store back in the session.


pub trait LateLintPass: LintPass { fn check_name(&mut self, _: &LateContext, _: Span, _: ast::Name) { } fn check_crate(&mut self, _: &LateContext, _: &hir::Crate) { } <ins> fn check_crate_post(&mut self, _: &LateContext, _: &hir::Crate) { } </ins> fn check_mod(&mut self, _: &LateContext, _: &hir::Mod, _: Span, _: ast::NodeId) { } fn check_foreign_item(&mut self, _: &LateContext, _: &hir::ForeignItem) { } fn check_item(&mut self, _: &LateContext, _: &hir::Item) { } <ins> fn check_item_post(&mut self, _: &LateContext, _: &hir::Item) { } </ins> fn check_local(&mut self, _: &LateContext, _: &hir::Local) { } fn check_block(&mut self, _: &LateContext, _: &hir::Block) { } <ins> fn check_block_post(&mut self, _: &LateContext, _: &hir::Block) { } </ins> fn check_stmt(&mut self, _: &LateContext, _: &hir::Stmt) { } fn check_arm(&mut self, _: &LateContext, _: &hir::Arm) { } fn check_pat(&mut self, _: &LateContext, _: &hir::Pat) { }


pub trait EarlyLintPass: LintPass { fn check_ident(&mut self, _: &EarlyContext, _: Span, _: ast::Ident) { } fn check_crate(&mut self, _: &EarlyContext, _: &ast::Crate) { } <ins> fn check_crate_post(&mut self, _: &EarlyContext, _: &ast::Crate) { } </ins> fn check_mod(&mut self, _: &EarlyContext, _: &ast::Mod, _: Span, _: ast::NodeId) { } fn check_foreign_item(&mut self, _: &EarlyContext, _: &ast::ForeignItem) { } fn check_item(&mut self, _: &EarlyContext, _: &ast::Item) { } <ins> fn check_item_post(&mut self, _: &EarlyContext, _: &ast::Item) { } </ins> fn check_local(&mut self, _: &EarlyContext, _: &ast::Local) { } fn check_block(&mut self, _: &EarlyContext, _: &ast::Block) { } <ins> fn check_block_post(&mut self, _: &EarlyContext, _: &ast::Block) { } </ins> fn check_stmt(&mut self, _: &EarlyContext, _: &ast::Stmt) { } fn check_arm(&mut self, _: &EarlyContext, _: &ast::Arm) { } fn check_pat(&mut self, _: &EarlyContext, _: &ast::Pat) { }


tmp } <del> /// Variant of read_and_zero that writes the specific drop-flag byte /// (which may be more appropriate than zero). </del> <ins> #[allow(missing_docs)] </ins> #[inline(always)] #[unstable(feature = "filling_drop", reason = "may play a larger role in std::ptr future extensions",


use prelude::v1::*; <ins> use cmp; </ins> use ffi::{CStr, CString}; use fmt; use io::{self, Error, ErrorKind};


} pub fn write(&self, buf: &[u8]) -> io::Result<usize> { <ins> let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t; </ins> let ret = try!(cvt(unsafe { c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, <del> buf.len() as wrlen_t, </del> <ins> len, </ins> 0) })); Ok(ret as usize)


pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() }; let mut addrlen = mem::size_of_val(&storage) as c::socklen_t; <ins> let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t; </ins> let n = try!(cvt(unsafe { c::recvfrom(*self.inner.as_inner(), buf.as_mut_ptr() as *mut c_void, <del> buf.len() as wrlen_t, 0, </del> <ins> len, 0, </ins> &mut storage as *mut _ as *mut _, &mut addrlen) })); Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize)))) } pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> { <ins> let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t; </ins> let (dstp, dstlen) = dst.into_inner(); let ret = try!(cvt(unsafe { c::sendto(*self.inner.as_inner(), <del> buf.as_ptr() as *const c_void, buf.len() as wrlen_t, </del> <ins> buf.as_ptr() as *const c_void, len, </ins> 0, dstp, dstlen) })); Ok(ret as usize)


// option. This file may not be copied, modified, or distributed // except according to those terms. <ins> use cmp; </ins> use io; use libc::{c_int, c_void}; use mem;


pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> { // On unix when a socket is shut down all further reads return 0, so we // do the same on windows to map a shut down socket to returning EOF. <ins> let len = cmp::min(buf.len(), i32::max_value() as usize) as i32; </ins> unsafe { <del> match c::recv(self.0, buf.as_mut_ptr() as *mut c_void, buf.len() as i32, 0) { </del> <ins> match c::recv(self.0, buf.as_mut_ptr() as *mut c_void, len, 0) { </ins> -1 if c::WSAGetLastError() == c::WSAESHUTDOWN => Ok(0), -1 => Err(last_error()), n => Ok(n as usize)


// Define the name or return the existing binding if there is a collision. pub fn try_define_child(&self, name: Name, ns: Namespace, binding: NameBinding<'a>) -> Result<(), &'a NameBinding<'a>> { <del> if self.resolutions.borrow_state() != ::std::cell::BorrowState::Unused { return Ok(()); } </del> self.update_resolution(name, ns, |resolution| { resolution.try_define(self.arenas.alloc_name_binding(binding)) })


fn update_resolution<T, F>(&self, name: Name, ns: Namespace, update: F) -> T where F: FnOnce(&mut NameResolution<'a>) -> T { <del> let mut resolution = &mut *self.resolution(name, ns).borrow_mut(); let was_known = resolution.binding().is_some(); let t = update(resolution); if !was_known { if let Some(binding) = resolution.binding() { self.define_in_glob_importers(name, ns, binding); </del> <ins> // Ensure that `resolution` isn't borrowed during `define_in_glob_importers`, // where it might end up getting re-defined via a glob cycle. let (new_binding, t) = { let mut resolution = &mut *self.resolution(name, ns).borrow_mut(); let was_known = resolution.binding().is_some(); let t = update(resolution); if was_known { return t; } match resolution.binding() { Some(binding) => (binding, t), None => return t, </ins> } <del> } </del> <ins> }; self.define_in_glob_importers(name, ns, new_binding); </ins> t }


// Add to target_module's glob_importers target_module.glob_importers.borrow_mut().push((module_, directive)); <del> for (&(name, ns), resolution) in target_module.resolutions.borrow().iter() { if let Some(binding) = resolution.borrow().binding() { if binding.defined_with(DefModifiers::IMPORTABLE | DefModifiers::PUBLIC) { let _ = module_.try_define_child(name, ns, directive.import(binding, None)); } </del> <ins> // Ensure that `resolutions` isn't borrowed during `try_define_child`, // since it might get updated via a glob cycle. let bindings = target_module.resolutions.borrow().iter().filter_map(|(name, resolution)| { resolution.borrow().binding().map(|binding| (*name, binding)) }).collect::<Vec<_>>(); for ((name, ns), binding) in bindings { if binding.defined_with(DefModifiers::IMPORTABLE | DefModifiers::PUBLIC) { let _ = module_.try_define_child(name, ns, directive.import(binding, None)); </ins> } }


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. mod foo { pub use bar::*; pub use main as f; //~ ERROR has already been imported } mod bar { pub use foo::*; } pub use foo::*; pub use baz::*; //~ ERROR has already been imported mod baz { pub use super::*; } pub fn main() {} </ins>


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub use bar::*; mod bar { pub use super::*; } pub use baz::*; //~ ERROR already been imported mod baz { pub use main as f; } pub fn main() {} </ins>


<ins> // Test to ensure that trait bounds are propertly // checked on specializable associated types #![allow(incomplete_features)] #![feature(specialization)] trait UncheckedCopy: Sized { type Output: From<Self> + Copy + Into<Self>; } impl<T> UncheckedCopy for T { default type Output = Self; //~^ ERROR: the trait bound `T: Copy` is not satisfied } fn unchecked_copy<T: UncheckedCopy>(other: &T::Output) -> T { (*other).into() } fn bug(origin: String) { // Turn the String into it's Output type... // Which we can just do by `.into()`, the assoc type states `From<Self>`. let origin_output = origin.into(); // Make a copy of String::Output, which is a String... let mut copy: String = unchecked_copy::<String>(&origin_output); // Turn the Output type into a String again, // Which we can just do by `.into()`, the assoc type states `Into<Self>`. let mut origin: String = origin_output.into(); // assert both Strings use the same buffer. assert_eq!(copy.as_ptr(), origin.as_ptr()); // Any use of the copy we made becomes invalid, drop(origin); // OH NO! UB UB UB UB! copy.push_str(" world!"); println!("{}", copy); } fn main() { bug(String::from("hello")); } </ins>


<ins> error[E0277]: the trait bound `T: Copy` is not satisfied --> $DIR/issue-33017.rs:12:5 | LL |     type Output: From<Self> + Copy + Into<Self>; |                               ---- required by this bound in `UncheckedCopy::Output` ... LL |     default type Output = Self; |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `T` | help: consider restricting type parameter `T` | LL | impl<T: std::marker::Copy> UncheckedCopy for T { |       ^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. </ins>


<ins> #![allow(incomplete_features)] #![feature(const_generics)] #![feature(const_evaluatable_checked)] #![feature(specialization)] pub trait Trait { type Type; } impl<T: ?Sized> Trait for T { default type Type = [u8; 1]; } impl<T: Trait> Trait for *const T { type Type = [u8; std::mem::size_of::<<T as Trait>::Type>()]; //~^ ERROR: unconstrained generic constant } fn main() {} </ins>


<ins> error: unconstrained generic constant --> $DIR/issue-51892.rs:15:5 | LL |     type Type = [u8; std::mem::size_of::<<T as Trait>::Type>()]; |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: try adding a `where` bound using this expression: `where [(); std::mem::size_of::<<T as Trait>::Type>()]:` error: aborting due to previous error </ins>


Ok(()) }  fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink) -> fmt::Result { if let Some(s) = item.doc_value() { let markdown = if s.contains('n') { format!("{} [Read more]({})", &plain_summary_line(Some(s)), naive_assoc_href(item, link)) } else { format!("{}", &plain_summary_line(Some(s))) }; write!(w, "
{}
", Markdown(&markdown))?; } Ok(()) }  fn item_module(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, items: &[clean::Item]) -> fmt::Result { document(w, cx, item)?;


} fn doctraititem(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item, <del> link: AssocItemLink, render_static: bool, is_default_item: bool, outer_version: Option<&str>) -> fmt::Result { </del> <ins> link: AssocItemLink, render_static: bool, is_default_item: bool, outer_version: Option<&str>, trait_: Option<&clean::Trait>) -> fmt::Result { </ins> let shortty = shortty(item); let name = item.name.as_ref().unwrap();


_ => panic!("can't make docs for trait item with name {:?}", item.name) } <del> if !is_default_item && (!is_static || render_static) { document(w, cx, item) } else { Ok(()) </del> <ins> if !is_static || render_static { if !is_default_item { if item.doc_value().is_some() { document(w, cx, item)?; } else { // In case the item isn't documented, // provide short documentation from the trait if let Some(t) = trait_ { if let Some(it) = t.items.iter() .find(|i| i.name == item.name) { document_short(w, it, link)?; } } } } else { document_short(w, item, link)?; } </ins> } <ins> Ok(()) </ins> } <ins> let traits = &cache().traits; let trait_ = i.trait_did().and_then(|did| traits.get(&did)); </ins> write!(w, "<div class='impl-items'>")?; for trait_item in &i.inner_impl().items { <del> doctraititem(w, cx, trait_item, link, render_header, false, outer_version)?; </del> <ins> doctraititem(w, cx, trait_item, link, render_header, false, outer_version, trait_)?; </ins> } fn render_default_items(w: &mut fmt::Formatter,


let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods); doctraititem(w, cx, trait_item, assoc_link, render_static, true, <del> outer_version)?; </del> <ins> outer_version, None)?; </ins> } Ok(()) } // If we've implemented a trait, then also emit documentation for all // default items which weren't overridden in the implementation block. <del> if let Some(did) = i.trait_did() { if let Some(t) = cache().traits.get(&did) { render_default_items(w, cx, t, &i.inner_impl(), render_header, outer_version)?; } </del> <ins> if let Some(t) = trait_ { render_default_items(w, cx, t, &i.inner_impl(), render_header, outer_version)?; </ins> } write!(w, "</div>")?; Ok(())


fn b_method(&self) -> usize { self.a_method() } <ins> /// Docs associated with the trait c_method definition. /// /// There is another line fn c_method(&self) -> usize { self.a_method() } </ins> } // @has manual_impl/struct.S1.html '//*[@class="trait"]' 'T' // @has  - '//*[@class="docblock"]' 'Docs associated with the S1 trait implementation.' // @has  - '//*[@class="docblock"]' 'Docs associated with the S1 trait a_method implementation.' // @!has - '//*[@class="docblock"]' 'Docs associated with the trait a_method definition.' <del> // @!has - '//*[@class="docblock"]' 'Docs associated with the trait b_method definition.' </del> <ins> // @has - '//*[@class="docblock"]' 'Docs associated with the trait b_method definition.' // @has - '//*[@class="docblock"]' 'Docs associated with the trait b_method definition.' // @has - '//*[@class="docblock"]' 'Docs associated with the trait c_method definition.' // @!has - '//*[@class="docblock"]' 'There is another line' // @has - '//*[@class="docblock"]' 'Read more' </ins> pub struct S1(usize); /// Docs associated with the S1 trait implementation.


// @has manual_impl/struct.S2.html '//*[@class="trait"]' 'T' // @has  - '//*[@class="docblock"]' 'Docs associated with the S2 trait implementation.' // @has  - '//*[@class="docblock"]' 'Docs associated with the S2 trait a_method implementation.' <del> // @has  - '//*[@class="docblock"]' 'Docs associated with the S2 trait b_method implementation.' </del> <ins> // @has  - '//*[@class="docblock"]' 'Docs associated with the S2 trait c_method implementation.' </ins> // @!has - '//*[@class="docblock"]' 'Docs associated with the trait a_method definition.' <del> // @!has - '//*[@class="docblock"]' 'Docs associated with the trait b_method definition.' </del> <ins> // @!has - '//*[@class="docblock"]' 'Docs associated with the trait c_method definition.' // @has - '//*[@class="docblock"]' 'Docs associated with the trait b_method definition.' // @!has - '//*[@class="docblock"]' 'Read more' </ins> pub struct S2(usize); /// Docs associated with the S2 trait implementation.


self.0 } <del> /// Docs associated with the S2 trait b_method implementation. fn b_method(&self) -> usize { </del> <ins> /// Docs associated with the S2 trait c_method implementation. fn c_method(&self) -> usize { </ins> 5 } }


// @has manual_impl/struct.S3.html '//*[@class="trait"]' 'T' // @has  - '//*[@class="docblock"]' 'Docs associated with the S3 trait implementation.' // @has  - '//*[@class="docblock"]' 'Docs associated with the S3 trait b_method implementation.' <del> // @!has - '//*[@class="docblock"]' 'Docs associated with the trait a_method definition.' </del> <ins> // @has - '//*[@class="docblock"]' 'Docs associated with the trait a_method definition.' </ins> pub struct S3(usize); /// Docs associated with the S3 trait implementation.


use super::FnCtxt; use hir::def_id::DefId; <del> use rustc::ty::{Ty, TypeFoldable, PreferMutLvalue}; </del> <ins> use rustc::ty::{Ty, TypeFoldable, PreferMutLvalue, TypeVariants}; </ins> use rustc::infer::type_variable::TypeVariableOrigin; use syntax::ast; use syntax::symbol::Symbol;


"binary operation `{}` cannot be applied to type `{}`", op.node.as_str(), lhs_ty); <ins> if let TypeVariants::TyRef(_, ref ty_mut) = lhs_ty.sty { if !self.infcx.type_moves_by_default(ty_mut.ty, lhs_expr.span) && self.lookup_op_method(expr, ty_mut.ty, vec![rhs_ty_var], Symbol::intern(name), trait_def_id, lhs_expr).is_ok() { err.span_note( lhs_expr.span, &format!( "this is a reference of type that `{}` can be applied to,  you need to dereference this variable once for this  operation to work", op.node.as_str())); } } </ins> let missing_trait = match op.node { hir::BiAdd    => Some("std::ops::Add"), hir::BiSub    => Some("std::ops::Sub"),


<ins> // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; let vr = v.iter().filter(|x| { x % 2 == 0 //~^ ERROR binary operation `%` cannot be applied to type `&&{integer}` //~| NOTE this is a reference of type that `%` can be applied to //~| NOTE an implementation of `std::ops::Rem` might be missing for `&&{integer}` }); println!("{:?}", vr); } </ins>


<ins> // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn main() { let a: &String = &"1".to_owned(); let b: &str = &"2"; let c = a + b; //~^ ERROR binary operation `+` cannot be applied to type `&std::string::String` //~| NOTE an implementation of `std::ops::Add` might be missing for `&std::string::String` println!("{:?}", c); } </ins>


// Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = self.borrow.get(); <del> debug_assert!(borrow != WRITING && borrow != UNUSED); </del> <ins> debug_assert!(borrow != UNUSED); // Prevent the borrow counter from overflowing. assert!(borrow != WRITING); </ins> self.borrow.set(borrow + 1); BorrowRef { borrow: self.borrow } }


the compiler. They are accessible via the `--explain` flag. Each explanation comes with an example of how to trigger it and advice on how to fix it. <ins> Please read [RFC 1567](https://github.com/rust-lang/rfcs/blob/master/text/1567-long-error-codes-explanation-normalization.md) for details on how to format and write long error codes. </ins> * All of them are accessible [online](http://doc.rust-lang.org/error-index.html), which are auto-generated from rustc source code in different places: [librustc](https://github.com/rust-lang/rust/blob/master/src/librustc/diagnostics.rs), <ins> [libsyntax](https://github.com/rust-lang/rust/blob/master/src/libsyntax/diagnostics.rs), </ins> [librustc_borrowck](https://github.com/rust-lang/rust/blob/master/src/librustc_borrowck/diagnostics.rs), [librustc_const_eval](https://github.com/rust-lang/rust/blob/master/src/librustc_const_eval/diagnostics.rs), <del> [librustc_lint](https://github.com/rust-lang/rust/blob/master/src/librustc_lint/types.rs), </del> [librustc_metadata](https://github.com/rust-lang/rust/blob/master/src/librustc_metadata/diagnostics.rs), [librustc_mir](https://github.com/rust-lang/rust/blob/master/src/librustc_mir/diagnostics.rs), [librustc_passes](https://github.com/rust-lang/rust/blob/master/src/librustc_passes/diagnostics.rs), [librustc_privacy](https://github.com/rust-lang/rust/blob/master/src/librustc_privacy/diagnostics.rs), [librustc_resolve](https://github.com/rust-lang/rust/blob/master/src/librustc_resolve/diagnostics.rs), [librustc_trans](https://github.com/rust-lang/rust/blob/master/src/librustc_trans/diagnostics.rs), <ins> [librustc_plugin](https://github.com/rust-lang/rust/blob/master/src/librustc_plugin/diagnostics.rs), </ins> [librustc_typeck](https://github.com/rust-lang/rust/blob/master/src/librustc_typeck/diagnostics.rs). * Explanations have full markdown support. Use it, especially to highlight code with backticks.


* Flags should be orthogonal to each other. For example, if we'd have a json-emitting variant of multiple actions `foo` and `bar`, an additional --json flag is better than adding `--foo-json` and `--bar-json`. <del> * Always give options a long descriptive name, if only for better </del> <ins> * Always give options a long descriptive name, if only for more </ins> understandable compiler scripts. * The `--verbose` flag is for adding verbose information to `rustc` output when not compiling a program. For example, using it with the `--version` flag


let mut base = self; let mut acc = 1; <del> let mut prev_base = self; let mut base_oflo = false; while exp > 0 { </del> <ins> while exp > 1 { </ins> if (exp & 1) == 1 { <del> if base_oflo { // ensure overflow occurs in the same manner it // would have otherwise (i.e. signal any exception // it would have otherwise). acc = acc * (prev_base * prev_base); } else { acc = acc * base; } </del> <ins> acc = acc * base; </ins> } <del> prev_base = base; let (new_base, new_base_oflo) = base.overflowing_mul(base); base = new_base; base_oflo = new_base_oflo; </del> exp /= 2; <ins> base = base * base; </ins> } <ins> // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { acc = acc * base; } </ins> acc }


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:thread 'main' panicked at 'attempt to multiply with overflow' // compile-flags: -C debug-assertions fn main() { let _x = 2i32.pow(1024); } </ins>


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:thread 'main' panicked at 'attempt to multiply with overflow' // compile-flags: -C debug-assertions fn main() { let _x = 2u32.pow(1024); } </ins>


<del> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:thread 'main' panicked at 'attempt to multiply with overflow' // compile-flags: -C debug-assertions fn main() { let _x = 2i32.pow(1024); } </del>


// each trait in the system to its implementations. <del> use metadata::csearch::{each_impl, get_impl_trait}; </del> <ins> use metadata::csearch::{each_impl, get_impl_trait, each_implementation_for_trait}; </ins> use metadata::csearch; use middle::ty::get; use middle::ty::{ImplContainer, lookup_item_type, subst};


pub fn check_implementation_coherence_of(&self, trait_def_id: DefId) { // Unify pairs of polytypes. <del> self.iter_impls_of_trait(trait_def_id, |a| { </del> <ins> self.iter_impls_of_trait_local(trait_def_id, |a| { </ins> let implementation_a = a; let polytype_a = self.get_self_type_for_implementation(implementation_a);


if self.polytypes_unify(polytype_a.clone(), polytype_b) { let session = self.crate_context.tcx.sess; session.span_err( <del> self.span_of_impl(implementation_b), </del> <ins> self.span_of_impl(implementation_a), </ins> format!("conflicting implementations for trait `{}`", ty::item_path_str(self.crate_context.tcx, trait_def_id))); <del> session.span_note(self.span_of_impl(implementation_a), "note conflicting implementation here"); </del> <ins> if implementation_b.did.crate == LOCAL_CRATE { session.span_note(self.span_of_impl(implementation_b), "note conflicting implementation here"); } else { let crate_store = self.crate_context.tcx.sess.cstore; let cdata = crate_store.get_crate_data(implementation_b.did.crate); session.note( "conflicting implementation in crate `" + cdata.name + "`"); } </ins> } } })


} pub fn iter_impls_of_trait(&self, trait_def_id: DefId, f: |@Impl|) { <ins> self.iter_impls_of_trait_local(trait_def_id, |x| f(x)); if trait_def_id.crate == LOCAL_CRATE { return; } let crate_store = self.crate_context.tcx.sess.cstore; csearch::each_implementation_for_trait(crate_store, trait_def_id, |impl_def_id| { let implementation = @csearch::get_impl(self.crate_context.tcx, impl_def_id); let _ = lookup_item_type(self.crate_context.tcx, implementation.did); f(implementation); }); } pub fn iter_impls_of_trait_local(&self, trait_def_id: DefId, f: |@Impl|) { </ins> let trait_impls = self.crate_context.tcx.trait_impls.borrow(); match trait_impls.get().find(&trait_def_id) { Some(impls) => {


<ins> // 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 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub trait Foo { } impl Foo for int { } </ins>