Skip to content

Commit

Permalink
Auto merge of #93738 - m-ou-se:rollup-zjyd2et, r=m-ou-se
Browse files Browse the repository at this point in the history
Rollup of 13 pull requests

Successful merges:

 - #88313 (Make the pre-commit script pre-push instead)
 - #91530 (Suggest 1-tuple parentheses on exprs without existing parens)
 - #92724 (Cleanup c_str.rs)
 - #93208 (Impl {Add,Sub,Mul,Div,Rem,BitXor,BitOr,BitAnd}Assign<$t> for Wrapping<$t> for rust 1.60.0)
 - #93394 (Don't allow {} to refer to implicit captures in format_args.)
 - #93416 (remove `allow_fail` test flag)
 - #93487 (Fix linking stage1 toolchain in `./x.py setup`)
 - #93673 (Linkify sidebar headings for sibling items)
 - #93680 (Drop json::from_reader)
 - #93682 (Update tracking issue for `const_fn_trait_bound`)
 - #93722 (Use shallow clones for submodules managed by rustbuild, not just bootstrap.py)
 - #93723 (Rerun bootstrap's build script when RUSTC changes)
 - #93737 (bootstrap: prefer using '--config' over 'RUST_BOOTSTRAP_CONFIG')

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Feb 7, 2022
2 parents c5e4148 + a6c4810 commit f52c318
Show file tree
Hide file tree
Showing 55 changed files with 470 additions and 389 deletions.
35 changes: 24 additions & 11 deletions compiler/rustc_builtin_macros/src/format.rs
Expand Up @@ -25,6 +25,7 @@ enum ArgumentType {

enum Position {
Exact(usize),
Capture(usize),
Named(Symbol),
}

Expand All @@ -49,6 +50,8 @@ struct Context<'a, 'b> {
/// * `arg_unique_types` (in simplified JSON): `[["o", "x"], ["o", "x"], ["o", "x"]]`
/// * `names` (in JSON): `{"foo": 2}`
args: Vec<P<ast::Expr>>,
/// The number of arguments that were added by implicit capturing.
num_captured_args: usize,
/// Placeholder slot numbers indexed by argument.
arg_types: Vec<Vec<usize>>,
/// Unique format specs seen for each argument.
Expand Down Expand Up @@ -231,6 +234,11 @@ fn parse_args<'a>(
}

impl<'a, 'b> Context<'a, 'b> {
/// The number of arguments that were explicitly given.
fn num_args(&self) -> usize {
self.args.len() - self.num_captured_args
}

fn resolve_name_inplace(&self, p: &mut parse::Piece<'_>) {
// NOTE: the `unwrap_or` branch is needed in case of invalid format
// arguments, e.g., `format_args!("{foo}")`.
Expand Down Expand Up @@ -345,7 +353,7 @@ impl<'a, 'b> Context<'a, 'b> {
}

fn describe_num_args(&self) -> Cow<'_, str> {
match self.args.len() {
match self.num_args() {
0 => "no arguments were given".into(),
1 => "there is 1 argument".into(),
x => format!("there are {} arguments", x).into(),
Expand All @@ -371,7 +379,7 @@ impl<'a, 'b> Context<'a, 'b> {

let count = self.pieces.len()
+ self.arg_with_formatting.iter().filter(|fmt| fmt.precision_span.is_some()).count();
if self.names.is_empty() && !numbered_position_args && count != self.args.len() {
if self.names.is_empty() && !numbered_position_args && count != self.num_args() {
e = self.ecx.struct_span_err(
sp,
&format!(
Expand Down Expand Up @@ -419,7 +427,7 @@ impl<'a, 'b> Context<'a, 'b> {
if let Some(span) = fmt.precision_span {
let span = self.fmtsp.from_inner(span);
match fmt.precision {
parse::CountIsParam(pos) if pos > self.args.len() => {
parse::CountIsParam(pos) if pos > self.num_args() => {
e.span_label(
span,
&format!(
Expand Down Expand Up @@ -462,7 +470,7 @@ impl<'a, 'b> Context<'a, 'b> {
if let Some(span) = fmt.width_span {
let span = self.fmtsp.from_inner(span);
match fmt.width {
parse::CountIsParam(pos) if pos > self.args.len() => {
parse::CountIsParam(pos) if pos > self.num_args() => {
e.span_label(
span,
&format!(
Expand Down Expand Up @@ -494,12 +502,15 @@ impl<'a, 'b> Context<'a, 'b> {
/// Actually verifies and tracks a given format placeholder
/// (a.k.a. argument).
fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
if let Exact(arg) = arg {
if arg >= self.num_args() {
self.invalid_refs.push((arg, self.curpiece));
return;
}
}

match arg {
Exact(arg) => {
if self.args.len() <= arg {
self.invalid_refs.push((arg, self.curpiece));
return;
}
Exact(arg) | Capture(arg) => {
match ty {
Placeholder(_) => {
// record every (position, type) combination only once
Expand All @@ -526,7 +537,7 @@ impl<'a, 'b> Context<'a, 'b> {
match self.names.get(&name) {
Some(&idx) => {
// Treat as positional arg.
self.verify_arg_type(Exact(idx), ty)
self.verify_arg_type(Capture(idx), ty)
}
None => {
// For the moment capturing variables from format strings expanded from macros is
Expand All @@ -541,9 +552,10 @@ impl<'a, 'b> Context<'a, 'b> {
} else {
self.fmtsp
};
self.num_captured_args += 1;
self.args.push(self.ecx.expr_ident(span, Ident::new(name, span)));
self.names.insert(name, idx);
self.verify_arg_type(Exact(idx), ty)
self.verify_arg_type(Capture(idx), ty)
} else {
let msg = format!("there is no argument named `{}`", name);
let sp = if self.is_literal {
Expand Down Expand Up @@ -1051,6 +1063,7 @@ pub fn expand_preparsed_format_args(
let mut cx = Context {
ecx,
args,
num_captured_args: 0,
arg_types,
arg_unique_types,
names,
Expand Down
9 changes: 0 additions & 9 deletions compiler/rustc_builtin_macros/src/test.rs
Expand Up @@ -252,11 +252,6 @@ pub fn expand_test_or_bench(
"ignore",
cx.expr_bool(sp, should_ignore(&cx.sess, &item)),
),
// allow_fail: true | false
field(
"allow_fail",
cx.expr_bool(sp, should_fail(&cx.sess, &item)),
),
// compile_fail: true | false
field("compile_fail", cx.expr_bool(sp, false)),
// no_run: true | false
Expand Down Expand Up @@ -359,10 +354,6 @@ fn should_ignore(sess: &Session, i: &ast::Item) -> bool {
sess.contains_name(&i.attrs, sym::ignore)
}

fn should_fail(sess: &Session, i: &ast::Item) -> bool {
sess.contains_name(&i.attrs, sym::allow_fail)
}

fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
match cx.sess.find_by_name(&i.attrs, sym::should_panic) {
Some(attr) => {
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_feature/src/active.rs
Expand Up @@ -277,8 +277,6 @@ declare_features! (
(incomplete, adt_const_params, "1.56.0", Some(44580), None),
/// Allows defining an `#[alloc_error_handler]`.
(active, alloc_error_handler, "1.29.0", Some(51540), None),
/// Allows a test to fail without failing the whole suite.
(active, allow_fail, "1.19.0", Some(46488), None),
/// Allows explicit discriminants on non-unit enum variants.
(active, arbitrary_enum_discriminant, "1.37.0", Some(60553), None),
/// Allows trait methods with arbitrary self types.
Expand Down Expand Up @@ -332,7 +330,7 @@ declare_features! (
/// Allows using and casting function pointers in a `const fn`.
(active, const_fn_fn_ptr_basics, "1.48.0", Some(57563), None),
/// Allows trait bounds in `const fn`.
(active, const_fn_trait_bound, "1.53.0", Some(57563), None),
(active, const_fn_trait_bound, "1.53.0", Some(93706), None),
/// Allows `for _ in _` loops in const contexts.
(active, const_for, "1.56.0", Some(87575), None),
/// Allows argument and return position `impl Trait` in a `const fn`.
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_feature/src/builtin_attrs.rs
Expand Up @@ -403,7 +403,6 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
},

// Testing:
gated!(allow_fail, Normal, template!(Word), WarnFollowing, experimental!(allow_fail)),
gated!(
test_runner, CrateLevel, template!(List: "path"), ErrorFollowing, custom_test_frameworks,
"custom test frameworks are an unstable feature",
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_feature/src/removed.rs
Expand Up @@ -48,6 +48,8 @@ declare_features! (
(removed, advanced_slice_patterns, "1.0.0", Some(62254), None,
Some("merged into `#![feature(slice_patterns)]`")),
(removed, allocator, "1.0.0", None, None, None),
/// Allows a test to fail without failing the whole suite.
(removed, allow_fail, "1.19.0", Some(46488), None, Some("removed due to no clear use cases")),
(removed, await_macro, "1.38.0", Some(50547), None,
Some("subsumed by `.await` syntax")),
/// Allows comparing raw pointers during const eval.
Expand Down
50 changes: 37 additions & 13 deletions compiler/rustc_infer/src/infer/error_reporting/mod.rs
Expand Up @@ -2044,19 +2044,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
// If a tuple of length one was expected and the found expression has
// parentheses around it, perhaps the user meant to write `(expr,)` to
// build a tuple (issue #86100)
(ty::Tuple(_), _) if expected.tuple_fields().count() == 1 => {
if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
if let Some(code) =
code.strip_prefix('(').and_then(|s| s.strip_suffix(')'))
{
err.span_suggestion(
span,
"use a trailing comma to create a tuple with one element",
format!("({},)", code),
Applicability::MaybeIncorrect,
);
}
}
(ty::Tuple(_), _) => {
self.emit_tuple_wrap_err(&mut err, span, found, expected)
}
// If a character was expected and the found expression is a string literal
// containing a single character, perhaps the user meant to write `'c'` to
Expand Down Expand Up @@ -2119,6 +2108,41 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
diag
}

fn emit_tuple_wrap_err(
&self,
err: &mut DiagnosticBuilder<'tcx>,
span: Span,
found: Ty<'tcx>,
expected: Ty<'tcx>,
) {
let [expected_tup_elem] = &expected.tuple_fields().collect::<Vec<_>>()[..]
else { return };

if !same_type_modulo_infer(expected_tup_elem, found) {
return;
}

let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
else { return };

let msg = "use a trailing comma to create a tuple with one element";
if code.starts_with('(') && code.ends_with(')') {
let before_close = span.hi() - BytePos::from_u32(1);
err.span_suggestion(
span.with_hi(before_close).shrink_to_hi(),
msg,
",".into(),
Applicability::MachineApplicable,
);
} else {
err.multipart_suggestion(
msg,
vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
Applicability::MachineApplicable,
);
}
}

fn values_str(
&self,
values: ValuePairs<'tcx>,
Expand Down
22 changes: 0 additions & 22 deletions compiler/rustc_serialize/src/json.rs
Expand Up @@ -185,8 +185,6 @@ use self::ParserState::*;

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::io;
use std::io::prelude::*;
use std::mem::swap;
use std::num::FpCategory as Fp;
use std::ops::Index;
Expand Down Expand Up @@ -250,7 +248,6 @@ pub enum ErrorCode {
pub enum ParserError {
/// msg, line, col
SyntaxError(ErrorCode, usize, usize),
IoError(io::ErrorKind, String),
}

// Builder and Parser have the same errors.
Expand Down Expand Up @@ -329,10 +326,6 @@ impl fmt::Display for ErrorCode {
}
}

fn io_error_to_error(io: io::Error) -> ParserError {
IoError(io.kind(), io.to_string())
}

impl fmt::Display for ParserError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// FIXME this should be a nicer error
Expand Down Expand Up @@ -2163,21 +2156,6 @@ impl<T: Iterator<Item = char>> Builder<T> {
}
}

/// Decodes a json value from an `&mut io::Read`
pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> {
let mut contents = Vec::new();
match rdr.read_to_end(&mut contents) {
Ok(c) => c,
Err(e) => return Err(io_error_to_error(e)),
};
let s = match str::from_utf8(&contents).ok() {
Some(s) => s,
_ => return Err(SyntaxError(NotUtf8, 0, 0)),
};
let mut builder = Builder::new(s.chars());
builder.build()
}

/// Decodes a json value from a string
pub fn from_str(s: &str) -> Result<Json, BuilderError> {
let mut builder = Builder::new(s.chars());
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_target/src/spec/mod.rs
Expand Up @@ -2148,8 +2148,8 @@ impl Target {
use std::fs;

fn load_file(path: &Path) -> Result<(Target, TargetWarnings), String> {
let contents = fs::read(path).map_err(|e| e.to_string())?;
let obj = json::from_reader(&mut &contents[..]).map_err(|e| e.to_string())?;
let contents = fs::read_to_string(path).map_err(|e| e.to_string())?;
let obj = json::from_str(&contents).map_err(|e| e.to_string())?;
Target::from_json(obj)
}

Expand Down

0 comments on commit f52c318

Please sign in to comment.