Merge pull request #5036 from calebcartwright/1.4.38-subtree

sync subtree
This commit is contained in:
Caleb Cartwright 2021-10-19 23:38:47 -05:00 committed by GitHub
commit b9178dc47c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 69 additions and 149 deletions

View File

@ -2,14 +2,13 @@
name = "rustfmt-nightly"
version = "1.4.37"
authors = ["Nicholas Cameron <ncameron@mozilla.com>", "The Rustfmt developers"]
description = "Tool to find and fix Rust formatting issues"
repository = "https://github.com/rust-lang/rustfmt"
readme = "README.md"
license = "Apache-2.0/MIT"
build = "build.rs"
categories = ["development-tools"]
edition = "2018"
edition = "2021"
[[bin]]
name = "rustfmt"

View File

@ -1,7 +1,6 @@
[package]
name = "rustfmt-config_proc_macro"
version = "0.2.0"
authors = ["topecongiro <seuchida@gmail.com>"]
edition = "2018"
description = "A collection of procedural macros for rustfmt"
license = "Apache-2.0/MIT"

View File

@ -1,3 +1,3 @@
[toolchain]
channel = "nightly-2021-07-23"
channel = "nightly-2021-10-20"
components = ["rustc-dev"]

View File

@ -160,6 +160,7 @@ fn rewrite_closure_with_block(
.first()
.map(|attr| attr.span.to(body.span))
.unwrap_or(body.span),
could_be_bare_literal: false,
};
let block = crate::expr::rewrite_block_with_visitor(
context,

View File

@ -616,7 +616,7 @@ struct ControlFlow<'a> {
fn extract_pats_and_cond(expr: &ast::Expr) -> (Option<&ast::Pat>, &ast::Expr) {
match expr.kind {
ast::ExprKind::Let(ref pat, ref cond) => (Some(pat), cond),
ast::ExprKind::Let(ref pat, ref cond, _) => (Some(pat), cond),
_ => (None, expr),
}
}

View File

@ -6,7 +6,7 @@ use std::cmp::{max, min, Ordering};
use regex::Regex;
use rustc_ast::visit;
use rustc_ast::{ast, ptr};
use rustc_span::{symbol, BytePos, Span};
use rustc_span::{symbol, BytePos, Span, DUMMY_SP};
use crate::attr::filter_inline_attrs;
use crate::comment::{
@ -31,7 +31,12 @@ use crate::stmt::Stmt;
use crate::utils::*;
use crate::vertical::rewrite_with_alignment;
use crate::visitor::FmtVisitor;
use crate::DEFAULT_VISIBILITY;
const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
kind: ast::VisibilityKind::Inherited,
span: DUMMY_SP,
tokens: None,
};
fn type_annotation_separator(config: &Config) -> &str {
colon_spaces(config)
@ -48,7 +53,7 @@ impl Rewrite for ast::Local {
skip_out_of_file_lines_range!(context, self.span);
if contains_skip(&self.attrs) {
if contains_skip(&self.attrs) || matches!(self.kind, ast::LocalKind::InitElse(..)) {
return None;
}
@ -97,7 +102,7 @@ impl Rewrite for ast::Local {
infix.push_str(&rewrite);
}
if self.init.is_some() {
if self.kind.init().is_some() {
infix.push_str(" =");
}
@ -106,11 +111,12 @@ impl Rewrite for ast::Local {
result.push_str(&infix);
if let Some(ref ex) = self.init {
if let Some((init, _els)) = self.kind.init_else_opt() {
// 1 = trailing semicolon;
let nested_shape = shape.sub_width(1)?;
result = rewrite_assign_rhs(context, result, &**ex, nested_shape)?;
result = rewrite_assign_rhs(context, result, init, nested_shape)?;
// todo else
}
result.push(';');
@ -972,7 +978,7 @@ impl<'a> StructParts<'a> {
format_header(context, self.prefix, self.ident, self.vis, offset)
}
pub(crate) fn from_variant(variant: &'a ast::Variant) -> Self {
fn from_variant(variant: &'a ast::Variant) -> Self {
StructParts {
prefix: "",
ident: variant.ident,

View File

@ -32,7 +32,7 @@ use std::path::PathBuf;
use std::rc::Rc;
use rustc_ast::ast;
use rustc_span::{symbol, DUMMY_SP};
use rustc_span::symbol;
use thiserror::Error;
use crate::comment::LineClasses;
@ -96,11 +96,6 @@ mod types;
mod vertical;
pub(crate) mod visitor;
const DEFAULT_VISIBILITY: ast::Visibility = ast::Visibility {
kind: ast::VisibilityKind::Inherited,
span: DUMMY_SP,
tokens: None,
};
/// The various errors that can occur during formatting. Note that not all of
/// these can currently be propagated to clients.
#[derive(Error, Debug)]

View File

@ -401,7 +401,7 @@ fn rewrite_macro_inner(
handle_vec_semi(context, shape, arg_vec, macro_name, style)
} else {
// If we are rewriting `vec!` macro or other special macros,
// then we can rewrite this as an usual array literal.
// then we can rewrite this as a usual array literal.
// Otherwise, we must preserve the original existence of trailing comma.
let macro_name = &macro_name.as_str();
let mut force_trailing_comma = if trailing_comma {
@ -762,7 +762,6 @@ impl MacroArgKind {
#[derive(Debug, Clone)]
struct ParsedMacroArg {
kind: MacroArgKind,
span: Span,
}
impl ParsedMacroArg {
@ -780,14 +779,10 @@ impl ParsedMacroArg {
struct MacroArgParser {
/// Either a name of the next metavariable, a separator, or junk.
buf: String,
/// The start position on the current buffer.
lo: BytePos,
/// The first token of the current buffer.
start_tok: Token,
/// `true` if we are parsing a metavariable or a repeat.
is_meta_var: bool,
/// The position of the last token.
hi: BytePos,
/// The last token parsed.
last_tok: Token,
/// Holds the parsed arguments.
@ -807,8 +802,6 @@ fn last_tok(tt: &TokenTree) -> Token {
impl MacroArgParser {
fn new() -> MacroArgParser {
MacroArgParser {
lo: BytePos(0),
hi: BytePos(0),
buf: String::new(),
is_meta_var: false,
last_tok: Token {
@ -824,7 +817,6 @@ impl MacroArgParser {
}
fn set_last_tok(&mut self, tok: &TokenTree) {
self.hi = tok.span().hi();
self.last_tok = last_tok(tok);
}
@ -836,7 +828,6 @@ impl MacroArgParser {
};
self.result.push(ParsedMacroArg {
kind: MacroArgKind::Separator(self.buf.clone(), prefix),
span: mk_sp(self.lo, self.hi),
});
self.buf.clear();
}
@ -849,7 +840,6 @@ impl MacroArgParser {
};
self.result.push(ParsedMacroArg {
kind: MacroArgKind::Other(self.buf.clone(), prefix),
span: mk_sp(self.lo, self.hi),
});
self.buf.clear();
}
@ -858,11 +848,10 @@ impl MacroArgParser {
match iter.next() {
Some(TokenTree::Token(Token {
kind: TokenKind::Ident(name, _),
span,
..
})) => {
self.result.push(ParsedMacroArg {
kind: MacroArgKind::MetaVariable(name, self.buf.clone()),
span: mk_sp(self.lo, span.hi()),
});
self.buf.clear();
@ -873,10 +862,9 @@ impl MacroArgParser {
}
}
fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken, span: Span) {
fn add_delimited(&mut self, inner: Vec<ParsedMacroArg>, delim: DelimToken) {
self.result.push(ParsedMacroArg {
kind: MacroArgKind::Delimited(delim, inner),
span,
});
}
@ -886,19 +874,15 @@ impl MacroArgParser {
inner: Vec<ParsedMacroArg>,
delim: DelimToken,
iter: &mut Cursor,
span: Span,
) -> Option<()> {
let mut buffer = String::new();
let mut first = true;
let mut lo = span.lo();
let mut hi = span.hi();
// Parse '*', '+' or '?.
for tok in iter {
self.set_last_tok(&tok);
if first {
first = false;
lo = tok.span().lo();
}
match tok {
@ -918,7 +902,6 @@ impl MacroArgParser {
}
TokenTree::Token(ref t) => {
buffer.push_str(&pprust::token_to_string(&t));
hi = t.span.hi();
}
_ => return None,
}
@ -930,20 +913,17 @@ impl MacroArgParser {
} else {
Some(Box::new(ParsedMacroArg {
kind: MacroArgKind::Other(buffer, "".to_owned()),
span: mk_sp(lo, hi),
}))
};
self.result.push(ParsedMacroArg {
kind: MacroArgKind::Repeat(delim, inner, another, self.last_tok.clone()),
span: mk_sp(self.lo, self.hi),
});
Some(())
}
fn update_buffer(&mut self, t: &Token) {
if self.buf.is_empty() {
self.lo = t.span.lo();
self.start_tok = t.clone();
} else {
let needs_space = match next_space(&self.last_tok.kind) {
@ -999,7 +979,6 @@ impl MacroArgParser {
// Start keeping the name of this metavariable in the buffer.
self.is_meta_var = true;
self.lo = span.lo();
self.start_tok = Token {
kind: TokenKind::Dollar,
span,
@ -1012,7 +991,7 @@ impl MacroArgParser {
self.add_meta_variable(&mut iter)?;
}
TokenTree::Token(ref t) => self.update_buffer(t),
TokenTree::Delimited(delimited_span, delimited, ref tts) => {
TokenTree::Delimited(_delimited_span, delimited, ref tts) => {
if !self.buf.is_empty() {
if next_space(&self.last_tok.kind) == SpaceState::Always {
self.add_separator();
@ -1022,16 +1001,14 @@ impl MacroArgParser {
}
// Parse the stuff inside delimiters.
let mut parser = MacroArgParser::new();
parser.lo = delimited_span.open.lo();
let parser = MacroArgParser::new();
let delimited_arg = parser.parse(tts.clone())?;
let span = delimited_span.entire();
if self.is_meta_var {
self.add_repeat(delimited_arg, delimited, &mut iter, span)?;
self.add_repeat(delimited_arg, delimited, &mut iter)?;
self.is_meta_var = false;
} else {
self.add_delimited(delimited_arg, delimited, span);
self.add_delimited(delimited_arg, delimited);
}
}
}
@ -1270,7 +1247,12 @@ impl MacroParser {
let data = delimited_span.entire().data();
(
data.hi,
Span::new(data.lo + BytePos(1), data.hi - BytePos(1), data.ctxt),
Span::new(
data.lo + BytePos(1),
data.hi - BytePos(1),
data.ctxt,
data.parent,
),
delimited_span.entire(),
)
}
@ -1417,7 +1399,7 @@ impl MacroBranch {
}
}
/// Format `lazy_static!` from https://crates.io/crates/lazy_static.
/// Format `lazy_static!` from <https://crates.io/crates/lazy_static>.
///
/// # Expected syntax
///

View File

@ -27,7 +27,6 @@ type FileModMap<'ast> = BTreeMap<FileName, Module<'ast>>;
pub(crate) struct Module<'a> {
ast_mod_kind: Option<Cow<'a, ast::ModKind>>,
pub(crate) items: Cow<'a, Vec<rustc_ast::ptr::P<ast::Item>>>,
attrs: Cow<'a, Vec<ast::Attribute>>,
inner_attr: Vec<ast::Attribute>,
pub(crate) span: Span,
}
@ -46,7 +45,6 @@ impl<'a> Module<'a> {
.collect();
Module {
items: mod_items,
attrs: mod_attrs,
inner_attr,
span: mod_span,
ast_mod_kind,

View File

@ -23,11 +23,11 @@ use crate::utils::{format_mutability, mk_sp, mk_sp_lo_plus_one, rewrite_ident};
/// Returns `true` if the given pattern is "short".
/// A short pattern is defined by the following grammar:
///
/// [small, ntp]:
/// `[small, ntp]`:
/// - single token
/// - `&[single-line, ntp]`
///
/// [small]:
/// `[small]`:
/// - `[small, ntp]`
/// - unary tuple constructor `([small, ntp])`
/// - `&[small]`

View File

@ -153,7 +153,7 @@ pub(crate) fn rewrite_string<'a>(
wrap_str(result, fmt.config.max_width(), fmt.shape)
}
/// Returns the index to the end of the URL if the split at index of the given string includes an
/// Returns the index to the end of the URL if the split at index of the given string includes a
/// URL or alike. Otherwise, returns `None`.
fn detect_url(s: &[&str], index: usize) -> Option<usize> {
let start = match s[..=index].iter().rposition(|g| is_whitespace(g)) {

View File

@ -317,6 +317,7 @@ mod tests {
suggestions: vec![],
span: span.unwrap_or_else(MultiSpan::new),
sort_span: DUMMY_SP,
is_lint: false,
}
}

View File

@ -1,15 +1,15 @@
use std::iter::ExactSizeIterator;
use std::ops::Deref;
use rustc_ast::ast::{self, AttrVec, FnRetTy, Mutability};
use rustc_span::{symbol::kw, symbol::Ident, BytePos, Pos, Span};
use rustc_ast::ast::{self, FnRetTy, Mutability};
use rustc_span::{symbol::kw, BytePos, Pos, Span};
use crate::comment::{combine_strs_with_missing_comments, contains_comment};
use crate::config::lists::*;
use crate::config::{IndentStyle, TypeDensity, Version};
use crate::expr::{
format_expr, rewrite_assign_rhs, rewrite_call, rewrite_tuple, rewrite_unary_prefix, ExprType,
};
use crate::items::StructParts;
use crate::lists::{
definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator,
};
@ -24,11 +24,6 @@ use crate::utils::{
colon_spaces, extra_offset, first_line_width, format_extern, format_mutability,
last_line_extendable, last_line_width, mk_sp, rewrite_ident,
};
use crate::DEFAULT_VISIBILITY;
use crate::{
comment::{combine_strs_with_missing_comments, contains_comment},
items::format_struct_struct,
};
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum PathContext {
@ -548,10 +543,10 @@ impl Rewrite for ast::GenericBound {
.map(|s| format!("?{}", s)),
ast::TraitBoundModifier::MaybeConst => poly_trait_ref
.rewrite(context, shape.offset_left(7)?)
.map(|s| format!("?const {}", s)),
.map(|s| format!("~const {}", s)),
ast::TraitBoundModifier::MaybeConstMaybe => poly_trait_ref
.rewrite(context, shape.offset_left(8)?)
.map(|s| format!("?const ?{}", s)),
.map(|s| format!("~const ?{}", s)),
};
rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
}
@ -790,54 +785,6 @@ impl Rewrite for ast::Ty {
ast::TyKind::Tup(ref items) => {
rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
}
ast::TyKind::AnonymousStruct(ref fields, recovered) => {
let ident = Ident::new(
kw::Struct,
mk_sp(self.span.lo(), self.span.lo() + BytePos(6)),
);
let data = ast::VariantData::Struct(fields.clone(), recovered);
let variant = ast::Variant {
attrs: AttrVec::new(),
id: self.id,
span: self.span,
vis: DEFAULT_VISIBILITY,
ident,
data,
disr_expr: None,
is_placeholder: false,
};
format_struct_struct(
&context,
&StructParts::from_variant(&variant),
fields,
shape.indent,
None,
)
}
ast::TyKind::AnonymousUnion(ref fields, recovered) => {
let ident = Ident::new(
kw::Union,
mk_sp(self.span.lo(), self.span.lo() + BytePos(5)),
);
let data = ast::VariantData::Struct(fields.clone(), recovered);
let variant = ast::Variant {
attrs: AttrVec::new(),
id: self.id,
span: self.span,
vis: DEFAULT_VISIBILITY,
ident,
data,
disr_expr: None,
is_placeholder: false,
};
format_struct_struct(
&context,
&StructParts::from_variant(&variant),
fields,
shape.indent,
None,
)
}
ast::TyKind::Path(ref q_self, ref path) => {
rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
}

View File

@ -356,11 +356,11 @@ macro_rules! source {
}
pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
Span::new(lo, hi, SyntaxContext::root())
Span::new(lo, hi, SyntaxContext::root(), None)
}
pub(crate) fn mk_sp_lo_plus_one(lo: BytePos) -> Span {
Span::new(lo, lo + BytePos(1), SyntaxContext::root())
Span::new(lo, lo + BytePos(1), SyntaxContext::root(), None)
}
// Returns `true` if the given span does not intersect with file lines.

View File

@ -36,7 +36,7 @@ pub(crate) struct SnippetProvider {
big_snippet: Lrc<String>,
/// A position of the start of `big_snippet`, used as an offset.
start_pos: usize,
/// A end position of the file that this snippet lives.
/// An end position of the file that this snippet lives.
end_pos: usize,
}

View File

@ -2,7 +2,7 @@
//!
//! The features are detected using the `detect_features` function below.
//! This function uses the CPUID instruction to read the feature flags from the
//! CPU and encodes them in an `usize` where each bit position represents
//! CPU and encodes them in a `usize` where each bit position represents
//! whether a feature is available (bit is set) or unavaiable (bit is cleared).
//!
//! The enum `Feature` is used to map bit positions to feature names, and the

3
tests/source/let_else.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
let Some(1) = Some(1) else { return };
}

View File

@ -140,29 +140,23 @@ fn foo(a: SomeLongComplexType, b: SomeOtherLongComplexType) -> Box<Future<Item =
type MyFn = fn(a: SomeLongComplexType, b: SomeOtherLongComplexType,) -> Box<Future<Item = AnotherLongType, Error = ALongErrorType>>;
// Const opt-out
// Const bound
trait T: ? const Super {}
trait T: ~ const Super {}
const fn maybe_const<S: ? const T>() -> i32 { <S as T>::CONST }
const fn not_quite_const<S: ~ const T>() -> i32 { <S as T>::CONST }
struct S<T:? const ? Sized>(std::marker::PhantomData<T>);
struct S<T:~ const ? Sized>(std::marker::PhantomData<T>);
impl ? const T {}
impl ~ const T {}
fn trait_object() -> &'static dyn ? const T { &S }
fn apit(_: impl ~ const T) {}
fn i(_: impl IntoIterator<Item = Box<dyn ? const T>>) {}
fn apit(_: impl ?const T) {}
fn rpit() -> impl ? const T { S }
fn rpit() -> impl ~ const T { S }
pub struct Foo<T: Trait>(T);
impl<T: ? const Trait> Foo<T> {
impl<T: ~ const Trait> Foo<T> {
fn new(t: T) -> Self {
// not calling methods on `t`, so we opt out of requiring
// `<T as Trait>` to have const methods via `?const`
Self(t)
}
}
@ -171,4 +165,4 @@ impl<T: ? const Trait> Foo<T> {
type T = typeof(
1);
impl T for .. {
}
}

View File

@ -2,7 +2,7 @@
//!
//! The features are detected using the `detect_features` function below.
//! This function uses the CPUID instruction to read the feature flags from the
//! CPU and encodes them in an `usize` where each bit position represents
//! CPU and encodes them in a `usize` where each bit position represents
//! whether a feature is available (bit is set) or unavaiable (bit is cleared).
//!
//! The enum `Feature` is used to map bit positions to feature names, and the

3
tests/target/let_else.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
let Some(1) = Some(1) else { return };
}

View File

@ -145,35 +145,27 @@ type MyFn = fn(
b: SomeOtherLongComplexType,
) -> Box<Future<Item = AnotherLongType, Error = ALongErrorType>>;
// Const opt-out
// Const bound
trait T: ?const Super {}
trait T: ~const Super {}
const fn maybe_const<S: ?const T>() -> i32 {
const fn not_quite_const<S: ~const T>() -> i32 {
<S as T>::CONST
}
struct S<T: ?const ?Sized>(std::marker::PhantomData<T>);
struct S<T: ~const ?Sized>(std::marker::PhantomData<T>);
impl ?const T {}
impl ~const T {}
fn trait_object() -> &'static dyn ?const T {
&S
}
fn apit(_: impl ~const T) {}
fn i(_: impl IntoIterator<Item = Box<dyn ?const T>>) {}
fn apit(_: impl ?const T) {}
fn rpit() -> impl ?const T {
fn rpit() -> impl ~const T {
S
}
pub struct Foo<T: Trait>(T);
impl<T: ?const Trait> Foo<T> {
impl<T: ~const Trait> Foo<T> {
fn new(t: T) -> Self {
// not calling methods on `t`, so we opt out of requiring
// `<T as Trait>` to have const methods via `?const`
Self(t)
}
}