Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Experiment: Add #[may_ignore] and use that for String::write_fmt. #78822

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2003,7 +2003,6 @@ impl fmt::Display for InlineAsmTemplatePiece {
impl InlineAsmTemplatePiece {
/// Rebuilds the asm template string from its pieces.
pub fn to_string(s: &[Self]) -> String {
use fmt::Write;
let mut out = String::new();
for p in s.iter() {
let _ = write!(out, "{}", p);
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_target::asm;
use std::collections::hash_map::Entry;
use std::fmt::Write;

impl<'hir> LoweringContext<'_, 'hir> {
fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
Expand Down
3 changes: 0 additions & 3 deletions compiler/rustc_builtin_macros/src/format_foreign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ pub mod printf {
/// Returns `None` in cases where the `printf` directive does not have an exact Rust
/// equivalent, rather than guessing.
pub fn translate(&self) -> Option<String> {
use std::fmt::Write;

let (c_alt, c_zero, c_left, c_plus) = {
let mut c_alt = false;
let mut c_zero = false;
Expand Down Expand Up @@ -245,7 +243,6 @@ pub mod printf {
}

fn translate(&self, s: &mut String) -> std::fmt::Result {
use std::fmt::Write;
match *self {
Num::Num(n) => write!(s, "{}", n),
Num::Arg(n) => {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ use tracing::debug;

use libc::{c_longlong, c_uint};
use std::collections::hash_map::Entry;
use std::fmt::{self, Write};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter;
use std::path::{Path, PathBuf};
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_codegen_llvm/src/type_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ use rustc_target::abi::{Int, Pointer, F32, F64};
use rustc_target::abi::{LayoutOf, PointeeInfo, Scalar, Size, TyAndLayoutMethods, Variants};
use tracing::debug;

use std::fmt::Write;

fn uncached_llvm_type<'a, 'tcx>(
cx: &CodegenCx<'a, 'tcx>,
layout: TyAndLayout<'tcx>,
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_middle::ty::{self, subst::SubstsRef, Ty, TyCtxt};

use std::fmt::Write;

// Compute the name of the type as it should be stored in debuginfo. Does not do
// any caching, i.e., calling the function twice with the same type will also do
// the work twice. The `qualified` parameter only affects the first level of the
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_feature/src/active.rs
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,9 @@ declare_features! (
/// Allows unsized fn parameters.
(active, unsized_fn_params, "1.49.0", Some(48055), None),

/// Allow `#[may_ignore]` attribute.
(active, may_ignore, "1.49.0", Some(99999999), None),

// -------------------------------------------------------------------------
// feature-group-end: actual feature gates
// -------------------------------------------------------------------------
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
ungated!(forbid, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
ungated!(deny, Normal, template!(List: r#"lint1, lint2, ..., /*opt*/ reason = "...""#)),
ungated!(must_use, AssumedUsed, template!(Word, NameValueStr: "reason")),
gated!(may_ignore, AssumedUsed, template!(Word), experimental!(may_ignore)),
// FIXME(#14407)
ungated!(
deprecated, Normal,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use rustc_middle::ty::print::{FmtPrinter, Print, RegionHighlightMode};
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, TyCtxt};

use std::fmt::{self, Write};
use std::fmt;

impl NiceRegionError<'me, 'tcx> {
/// When given a `ConcreteFailure` for a function with arguments containing a named region and
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_lint/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ use rustc_trait_selection::traits::misc::can_type_implement_copy;

use crate::nonstandard_style::{method_context, MethodLateContext};

use std::fmt::Write;
use tracing::{debug, trace};

// hardwired lints from librustc_middle
Expand Down
20 changes: 15 additions & 5 deletions compiler/rustc_lint/src/unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,6 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
return;
}

let ty = cx.typeck_results().expr_ty(&expr);
let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);

let mut fn_warned = false;
let mut op_warned = false;
let maybe_def_id = match expr.kind {
hir::ExprKind::Call(ref callee, _) => {
match callee.kind {
Expand All @@ -123,6 +118,21 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
_ => None,
};

if let Some(def_id) = maybe_def_id {
for attr in cx.tcx.get_attrs(def_id).iter() {
if cx.sess().check_name(attr, sym::may_ignore) {
// Don't warn if the function was marked as #[may_ignore].
return;
}
}
}

let ty = cx.typeck_results().expr_ty(&expr);
let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);

let mut fn_warned = false;
let mut op_warned = false;
if let Some(def_id) = maybe_def_id {
fn_warned = check_must_use_def(cx, def_id, s.span, "return value of ", "");
} else if type_permits_lack_of_use {
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_middle/src/mir/mono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,8 +453,6 @@ impl CodegenUnitNameBuilder<'tcx> {
C: fmt::Display,
S: fmt::Display,
{
use std::fmt::Write;

let mut cgu_name = String::with_capacity(64);

// Start out with the crate name and disambiguator
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_mir/src/interpret/validity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
//! to be const-safe.

use std::convert::TryFrom;
use std::fmt::Write;
use std::num::NonZeroUsize;
use std::ops::RangeInclusive;

Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_mir/src/util/pretty.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::collections::BTreeSet;
use std::fmt::Write as _;
use std::fmt::{Debug, Display};
use std::fs;
use std::io::{self, Write};
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,7 @@ symbols! {
maxnumf32,
maxnumf64,
may_dangle,
may_ignore,
maybe_uninit,
maybe_uninit_uninit,
maybe_uninit_zeroed,
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_symbol_mangling/src/v0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use rustc_middle::ty::subst::{GenericArg, GenericArgKind, Subst};
use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable};
use rustc_target::spec::abi::Abi;

use std::fmt::Write;
use std::ops::Range;

pub(super) fn mangle(
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_trait_selection/src/traits/specialize/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,8 +462,6 @@ fn report_conflicting_impls(
/// Recovers the "impl X for Y" signature from `impl_def_id` and returns it as a
/// string.
fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String> {
use std::fmt::Write;

let trait_ref = tcx.impl_trait_ref(impl_def_id)?;
let mut w = "impl".to_owned();

Expand Down
1 change: 1 addition & 0 deletions library/alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@
#![feature(int_bits_const)]
#![feature(lang_items)]
#![feature(layout_for_ptr)]
#![cfg_attr(not(bootstrap), feature(may_ignore))]
#![feature(maybe_uninit_ref)]
#![feature(negative_impls)]
#![feature(never_type)]
Expand Down
9 changes: 8 additions & 1 deletion library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1587,6 +1587,14 @@ impl String {
let slice = self.vec.into_boxed_slice();
unsafe { from_boxed_utf8_unchecked(slice) }
}

#[doc(hidden)]
#[inline]
#[cfg_attr(not(bootstrap), may_ignore)]
#[stable(feature = "string_write_fmt", since = "1.49.0")]
pub fn write_fmt(mut self: &mut Self, args: fmt::Arguments<'_>) -> fmt::Result {
fmt::write(&mut self, args)
}
}

impl FromUtf8Error {
Expand Down Expand Up @@ -2198,7 +2206,6 @@ impl<T: fmt::Display + ?Sized> ToString for T {
// to try to remove it.
#[inline]
default fn to_string(&self) -> String {
use fmt::Write;
let mut buf = String::new();
buf.write_fmt(format_args!("{}", self))
.expect("a Display implementation returned an error unexpectedly");
Expand Down
5 changes: 1 addition & 4 deletions library/core/src/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1048,11 +1048,8 @@ pub trait UpperExp {
/// Please note that using [`write!`] might be preferable. Example:
///
/// ```
/// use std::fmt::Write;
///
/// let mut output = String::new();
/// write!(&mut output, "Hello {}!", "world")
/// .expect("Error occurred while trying to write in String");
/// write!(&mut output, "Hello {}!", "world");
/// assert_eq!(output, "Hello world!");
/// ```
///
Expand Down
38 changes: 0 additions & 38 deletions library/core/src/macros/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,25 +348,6 @@ macro_rules! r#try {
/// }
/// ```
///
/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
/// implementing either, as objects do not typically implement both. However, the module must
/// import the traits qualified so their names do not conflict:
///
/// ```
/// use std::fmt::Write as FmtWrite;
/// use std::io::Write as IoWrite;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut s = String::new();
/// let mut v = Vec::new();
///
/// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
/// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
/// assert_eq!(v, b"s = \"abc 123\"");
/// Ok(())
/// }
/// ```
///
/// Note: This macro can be used in `no_std` setups as well.
/// In a `no_std` setup you are responsible for the implementation details of the components.
///
Expand Down Expand Up @@ -416,25 +397,6 @@ macro_rules! write {
/// Ok(())
/// }
/// ```
///
/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
/// implementing either, as objects do not typically implement both. However, the module must
/// import the traits qualified so their names do not conflict:
///
/// ```
/// use std::fmt::Write as FmtWrite;
/// use std::io::Write as IoWrite;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut s = String::new();
/// let mut v = Vec::new();
///
/// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
/// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
/// assert_eq!(v, b"s = \"abc 123\\n\"\n");
/// Ok(())
/// }
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_unstable(format_args_nl)]
Expand Down
2 changes: 0 additions & 2 deletions library/core/tests/fmt/builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,8 +398,6 @@ mod debug_map {
#[test]
fn test_entry_err() {
// Ensure errors in a map entry don't trigger panics (#65231)
use std::fmt::Write;

struct ErrorFmt;

impl fmt::Debug for ErrorFmt {
Expand Down
2 changes: 0 additions & 2 deletions library/std/src/panicking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -452,8 +452,6 @@ pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
}

fn fill(&mut self) -> &mut String {
use crate::fmt::Write;

let inner = self.inner;
// Lazily, the first time this gets called, run the actual string formatting.
self.string.get_or_insert_with(|| {
Expand Down
2 changes: 0 additions & 2 deletions library/test/src/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ pub struct BenchSamples {
}

pub fn fmt_bench_samples(bs: &BenchSamples) -> String {
use std::fmt::Write;
let mut output = String::new();

let median = bs.ns_iter_summ.median as usize;
Expand All @@ -76,7 +75,6 @@ pub fn fmt_bench_samples(bs: &BenchSamples) -> String {

// 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 trailing = false;
for &pow in &[9, 6, 3, 0] {
Expand Down
1 change: 1 addition & 0 deletions src/bootstrap/setup.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{t, VERSION};
#[allow(unused_imports)]
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
Expand Down
1 change: 0 additions & 1 deletion src/librustdoc/html/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ impl Buffer {
// the fmt::Result return type imposed by fmt::Write (and avoiding the trait
// import).
crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
use fmt::Write;
self.buffer.write_fmt(v).unwrap();
}

Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/html/highlight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

use crate::html::escape::Escape;

use std::fmt::{Display, Write};
use std::fmt::Display;
use std::iter::Peekable;

use rustc_lexer::{LiteralKind, TokenKind};
Expand Down
1 change: 0 additions & 1 deletion src/librustdoc/html/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ use rustc_span::Span;
use std::borrow::Cow;
use std::collections::VecDeque;
use std::default::Default;
use std::fmt::Write;
use std::ops::Range;
use std::str;

Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/html/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use std::cmp::Ordering;
use std::collections::{BTreeMap, VecDeque};
use std::default::Default;
use std::ffi::OsStr;
use std::fmt::{self, Write};
use std::fmt;
use std::fs::{self, File};
use std::io::prelude::*;
use std::io::{self, BufReader};
Expand Down
4 changes: 4 additions & 0 deletions src/test/ui/feature-gate-may_ignore.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#[may_ignore]
//~^ ERROR the `#[may_ignore]` attribute is an experimental feature [E0658]
fn main() {
}
12 changes: 12 additions & 0 deletions src/test/ui/feature-gate-may_ignore.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
error[E0658]: the `#[may_ignore]` attribute is an experimental feature
--> $DIR/feature-gate-may_ignore.rs:1:1
|
LL | #[may_ignore]
| ^^^^^^^^^^^^^
|
= note: see issue #99999999 <https://github.com/rust-lang/rust/issues/99999999> for more information
= help: add `#![feature(may_ignore)]` to the crate attributes to enable

error: aborting due to previous error

For more information about this error, try `rustc --explain E0658`.
2 changes: 0 additions & 2 deletions src/test/ui/impl-trait/example-calendar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
//!
//! Originally converted to Rust by [Daniel Keep](https://github.com/DanielKeep).

use std::fmt::Write;

/// Date representation.
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct NaiveDate(i32, u32, u32);
Expand Down
10 changes: 0 additions & 10 deletions src/test/ui/macros/must-use-in-macro-55516.rs

This file was deleted.

12 changes: 0 additions & 12 deletions src/test/ui/macros/must-use-in-macro-55516.stderr

This file was deleted.

Loading