diff --git a/Cargo.lock b/Cargo.lock index 5fda666e480ed..ed2d1ddc3497b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4728,6 +4728,7 @@ version = "0.0.0" dependencies = [ "arrayvec", "askama", + "atty", "expect-test", "itertools 0.9.0", "minifier", diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index fa9a20f2e0358..026937394d012 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -1,3 +1,6 @@ +mod expr; +mod item; + use crate::pp::Breaks::{Consistent, Inconsistent}; use crate::pp::{self, Breaks}; @@ -7,9 +10,9 @@ use rustc_ast::token::{self, BinOpToken, CommentKind, DelimToken, Nonterminal, T use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_ast::util::classify; use rustc_ast::util::comments::{gather_comments, Comment, CommentStyle}; -use rustc_ast::util::parser::{self, AssocOp, Fixity}; +use rustc_ast::util::parser; use rustc_ast::{self as ast, BlockCheckMode, PatKind, RangeEnd, RangeSyntax}; -use rustc_ast::{GenericArg, MacArgs, ModKind}; +use rustc_ast::{GenericArg, MacArgs}; use rustc_ast::{GenericBound, SelfKind, TraitBoundModifier}; use rustc_ast::{InlineAsmOperand, InlineAsmRegOrRegClass}; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; @@ -210,10 +213,6 @@ pub fn literal_to_string(lit: token::Lit) -> String { out } -fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String { - format!("{}{}", State::to_string(|s| s.print_visibility(vis)), s) -} - impl std::ops::Deref for State<'_> { type Target = pp::Printer; fn deref(&self) -> &Self::Target { @@ -938,13 +937,6 @@ impl<'a> State<'a> { self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span) } - crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) { - self.print_inner_attributes(attrs); - for item in &nmod.items { - self.print_foreign_item(item); - } - } - pub fn print_opt_lifetime(&mut self, lifetime: &Option) { if let Some(lt) = *lifetime { self.print_lifetime(lt); @@ -1056,343 +1048,6 @@ impl<'a> State<'a> { self.end(); } - crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) { - let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item; - self.ann.pre(self, AnnNode::SubItem(id)); - self.hardbreak_if_not_bol(); - self.maybe_print_comment(span.lo()); - self.print_outer_attributes(attrs); - match kind { - ast::ForeignItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => { - self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs); - } - ast::ForeignItemKind::Static(ty, mutbl, body) => { - let def = ast::Defaultness::Final; - self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def); - } - ast::ForeignItemKind::TyAlias(box ast::TyAlias { - defaultness, - generics, - bounds, - ty, - }) => { - self.print_associated_type( - ident, - generics, - bounds, - ty.as_deref(), - vis, - *defaultness, - ); - } - ast::ForeignItemKind::MacCall(m) => { - self.print_mac(m); - if m.args.need_semicolon() { - self.word(";"); - } - } - } - self.ann.post(self, AnnNode::SubItem(id)) - } - - fn print_item_const( - &mut self, - ident: Ident, - mutbl: Option, - ty: &ast::Ty, - body: Option<&ast::Expr>, - vis: &ast::Visibility, - defaultness: ast::Defaultness, - ) { - self.head(""); - self.print_visibility(vis); - self.print_defaultness(defaultness); - let leading = match mutbl { - None => "const", - Some(ast::Mutability::Not) => "static", - Some(ast::Mutability::Mut) => "static mut", - }; - self.word_space(leading); - self.print_ident(ident); - self.word_space(":"); - self.print_type(ty); - if body.is_some() { - self.space(); - } - self.end(); // end the head-ibox - if let Some(body) = body { - self.word_space("="); - self.print_expr(body); - } - self.word(";"); - self.end(); // end the outer cbox - } - - fn print_associated_type( - &mut self, - ident: Ident, - generics: &ast::Generics, - bounds: &ast::GenericBounds, - ty: Option<&ast::Ty>, - vis: &ast::Visibility, - defaultness: ast::Defaultness, - ) { - self.head(""); - self.print_visibility(vis); - self.print_defaultness(defaultness); - self.word_space("type"); - self.print_ident(ident); - self.print_generic_params(&generics.params); - self.print_type_bounds(":", bounds); - self.print_where_clause(&generics.where_clause); - if let Some(ty) = ty { - self.space(); - self.word_space("="); - self.print_type(ty); - } - self.word(";"); - self.end(); // end inner head-block - self.end(); // end outer head-block - } - - /// Pretty-prints an item. - crate fn print_item(&mut self, item: &ast::Item) { - self.hardbreak_if_not_bol(); - self.maybe_print_comment(item.span.lo()); - self.print_outer_attributes(&item.attrs); - self.ann.pre(self, AnnNode::Item(item)); - match item.kind { - ast::ItemKind::ExternCrate(orig_name) => { - self.head(visibility_qualified(&item.vis, "extern crate")); - if let Some(orig_name) = orig_name { - self.print_name(orig_name); - self.space(); - self.word("as"); - self.space(); - } - self.print_ident(item.ident); - self.word(";"); - self.end(); // end inner head-block - self.end(); // end outer head-block - } - ast::ItemKind::Use(ref tree) => { - self.head(visibility_qualified(&item.vis, "use")); - self.print_use_tree(tree); - self.word(";"); - self.end(); // end inner head-block - self.end(); // end outer head-block - } - ast::ItemKind::Static(ref ty, mutbl, ref body) => { - let def = ast::Defaultness::Final; - self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def); - } - ast::ItemKind::Const(def, ref ty, ref body) => { - self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def); - } - ast::ItemKind::Fn(box ast::Fn { defaultness, ref sig, ref generics, ref body }) => { - let body = body.as_deref(); - self.print_fn_full( - sig, - item.ident, - generics, - &item.vis, - defaultness, - body, - &item.attrs, - ); - } - ast::ItemKind::Mod(unsafety, ref mod_kind) => { - self.head(Self::to_string(|s| { - s.print_visibility(&item.vis); - s.print_unsafety(unsafety); - s.word("mod"); - })); - self.print_ident(item.ident); - - match mod_kind { - ModKind::Loaded(items, ..) => { - self.nbsp(); - self.bopen(); - self.print_inner_attributes(&item.attrs); - for item in items { - self.print_item(item); - } - let empty = item.attrs.is_empty() && items.is_empty(); - self.bclose(item.span, empty); - } - ModKind::Unloaded => { - self.word(";"); - self.end(); // end inner head-block - self.end(); // end outer head-block - } - } - } - ast::ItemKind::ForeignMod(ref nmod) => { - self.head(Self::to_string(|s| { - s.print_unsafety(nmod.unsafety); - s.word("extern"); - })); - if let Some(abi) = nmod.abi { - self.print_literal(&abi.as_lit()); - self.nbsp(); - } - self.bopen(); - self.print_foreign_mod(nmod, &item.attrs); - let empty = item.attrs.is_empty() && nmod.items.is_empty(); - self.bclose(item.span, empty); - } - ast::ItemKind::GlobalAsm(ref asm) => { - self.head(visibility_qualified(&item.vis, "global_asm!")); - self.print_inline_asm(asm); - self.end(); - } - ast::ItemKind::TyAlias(box ast::TyAlias { - defaultness, - ref generics, - ref bounds, - ref ty, - }) => { - let ty = ty.as_deref(); - self.print_associated_type( - item.ident, - generics, - bounds, - ty, - &item.vis, - defaultness, - ); - } - ast::ItemKind::Enum(ref enum_definition, ref params) => { - self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis); - } - ast::ItemKind::Struct(ref struct_def, ref generics) => { - self.head(visibility_qualified(&item.vis, "struct")); - self.print_struct(struct_def, generics, item.ident, item.span, true); - } - ast::ItemKind::Union(ref struct_def, ref generics) => { - self.head(visibility_qualified(&item.vis, "union")); - self.print_struct(struct_def, generics, item.ident, item.span, true); - } - ast::ItemKind::Impl(box ast::Impl { - unsafety, - polarity, - defaultness, - constness, - ref generics, - ref of_trait, - ref self_ty, - ref items, - }) => { - self.head(""); - self.print_visibility(&item.vis); - self.print_defaultness(defaultness); - self.print_unsafety(unsafety); - self.word("impl"); - - if generics.params.is_empty() { - self.nbsp(); - } else { - self.print_generic_params(&generics.params); - self.space(); - } - - self.print_constness(constness); - - if let ast::ImplPolarity::Negative(_) = polarity { - self.word("!"); - } - - if let Some(ref t) = *of_trait { - self.print_trait_ref(t); - self.space(); - self.word_space("for"); - } - - self.print_type(self_ty); - self.print_where_clause(&generics.where_clause); - - self.space(); - self.bopen(); - self.print_inner_attributes(&item.attrs); - for impl_item in items { - self.print_assoc_item(impl_item); - } - let empty = item.attrs.is_empty() && items.is_empty(); - self.bclose(item.span, empty); - } - ast::ItemKind::Trait(box ast::Trait { - is_auto, - unsafety, - ref generics, - ref bounds, - ref items, - .. - }) => { - self.head(""); - self.print_visibility(&item.vis); - self.print_unsafety(unsafety); - self.print_is_auto(is_auto); - self.word_nbsp("trait"); - self.print_ident(item.ident); - self.print_generic_params(&generics.params); - let mut real_bounds = Vec::with_capacity(bounds.len()); - for b in bounds.iter() { - if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { - self.space(); - self.word_space("for ?"); - self.print_trait_ref(&ptr.trait_ref); - } else { - real_bounds.push(b.clone()); - } - } - self.print_type_bounds(":", &real_bounds); - self.print_where_clause(&generics.where_clause); - self.word(" "); - self.bopen(); - self.print_inner_attributes(&item.attrs); - for trait_item in items { - self.print_assoc_item(trait_item); - } - let empty = item.attrs.is_empty() && items.is_empty(); - self.bclose(item.span, empty); - } - ast::ItemKind::TraitAlias(ref generics, ref bounds) => { - self.head(""); - self.print_visibility(&item.vis); - self.word_nbsp("trait"); - self.print_ident(item.ident); - self.print_generic_params(&generics.params); - let mut real_bounds = Vec::with_capacity(bounds.len()); - // FIXME(durka) this seems to be some quite outdated syntax - for b in bounds.iter() { - if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { - self.space(); - self.word_space("for ?"); - self.print_trait_ref(&ptr.trait_ref); - } else { - real_bounds.push(b.clone()); - } - } - self.nbsp(); - self.print_type_bounds("=", &real_bounds); - self.print_where_clause(&generics.where_clause); - self.word(";"); - } - ast::ItemKind::MacCall(ref mac) => { - self.print_mac(mac); - if mac.args.need_semicolon() { - self.word(";"); - } - } - ast::ItemKind::MacroDef(ref macro_def) => { - self.print_mac_def(macro_def, &item.ident, &item.span, |state| { - state.print_visibility(&item.vis) - }); - } - } - self.ann.post(self, AnnNode::Item(item)) - } - fn print_trait_ref(&mut self, t: &ast::TraitRef) { self.print_path(&t.path, false, 0) } @@ -1410,167 +1065,6 @@ impl<'a> State<'a> { self.print_trait_ref(&t.trait_ref) } - crate fn print_enum_def( - &mut self, - enum_definition: &ast::EnumDef, - generics: &ast::Generics, - ident: Ident, - span: rustc_span::Span, - visibility: &ast::Visibility, - ) { - self.head(visibility_qualified(visibility, "enum")); - self.print_ident(ident); - self.print_generic_params(&generics.params); - self.print_where_clause(&generics.where_clause); - self.space(); - self.print_variants(&enum_definition.variants, span) - } - - crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) { - self.bopen(); - for v in variants { - self.space_if_not_bol(); - self.maybe_print_comment(v.span.lo()); - self.print_outer_attributes(&v.attrs); - self.ibox(INDENT_UNIT); - self.print_variant(v); - self.word(","); - self.end(); - self.maybe_print_trailing_comment(v.span, None); - } - let empty = variants.is_empty(); - self.bclose(span, empty) - } - - crate fn print_visibility(&mut self, vis: &ast::Visibility) { - match vis.kind { - ast::VisibilityKind::Public => self.word_nbsp("pub"), - ast::VisibilityKind::Crate(sugar) => match sugar { - ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"), - ast::CrateSugar::JustCrate => self.word_nbsp("crate"), - }, - ast::VisibilityKind::Restricted { ref path, .. } => { - let path = Self::to_string(|s| s.print_path(path, false, 0)); - if path == "self" || path == "super" { - self.word_nbsp(format!("pub({})", path)) - } else { - self.word_nbsp(format!("pub(in {})", path)) - } - } - ast::VisibilityKind::Inherited => {} - } - } - - crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) { - if let ast::Defaultness::Default(_) = defaultness { - self.word_nbsp("default"); - } - } - - crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) { - self.nbsp(); - self.bopen(); - - let empty = fields.is_empty(); - if !empty { - self.hardbreak_if_not_bol(); - - for field in fields { - self.hardbreak_if_not_bol(); - self.maybe_print_comment(field.span.lo()); - self.print_outer_attributes(&field.attrs); - self.print_visibility(&field.vis); - self.print_ident(field.ident.unwrap()); - self.word_nbsp(":"); - self.print_type(&field.ty); - self.word(","); - } - } - - self.bclose(span, empty); - } - - crate fn print_struct( - &mut self, - struct_def: &ast::VariantData, - generics: &ast::Generics, - ident: Ident, - span: rustc_span::Span, - print_finalizer: bool, - ) { - self.print_ident(ident); - self.print_generic_params(&generics.params); - match struct_def { - ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => { - if let ast::VariantData::Tuple(..) = struct_def { - self.popen(); - self.commasep(Inconsistent, struct_def.fields(), |s, field| { - s.maybe_print_comment(field.span.lo()); - s.print_outer_attributes(&field.attrs); - s.print_visibility(&field.vis); - s.print_type(&field.ty) - }); - self.pclose(); - } - self.print_where_clause(&generics.where_clause); - if print_finalizer { - self.word(";"); - } - self.end(); - self.end(); // Close the outer-box. - } - ast::VariantData::Struct(ref fields, ..) => { - self.print_where_clause(&generics.where_clause); - self.print_record_struct_body(fields, span); - } - } - } - - crate fn print_variant(&mut self, v: &ast::Variant) { - self.head(""); - self.print_visibility(&v.vis); - let generics = ast::Generics::default(); - self.print_struct(&v.data, &generics, v.ident, v.span, false); - if let Some(ref d) = v.disr_expr { - self.space(); - self.word_space("="); - self.print_expr(&d.value) - } - } - - crate fn print_assoc_item(&mut self, item: &ast::AssocItem) { - let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item; - self.ann.pre(self, AnnNode::SubItem(id)); - self.hardbreak_if_not_bol(); - self.maybe_print_comment(span.lo()); - self.print_outer_attributes(attrs); - match kind { - ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => { - self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs); - } - ast::AssocItemKind::Const(def, ty, body) => { - self.print_item_const(ident, None, ty, body.as_deref(), vis, *def); - } - ast::AssocItemKind::TyAlias(box ast::TyAlias { defaultness, generics, bounds, ty }) => { - self.print_associated_type( - ident, - generics, - bounds, - ty.as_deref(), - vis, - *defaultness, - ); - } - ast::AssocItemKind::MacCall(m) => { - self.print_mac(m); - if m.args.need_semicolon() { - self.word(";"); - } - } - } - self.ann.post(self, AnnNode::SubItem(id)) - } - crate fn print_stmt(&mut self, st: &ast::Stmt) { self.maybe_print_comment(st.span.lo()); match st.kind { @@ -1681,42 +1175,6 @@ impl<'a> State<'a> { self.print_expr_cond_paren(expr, Self::cond_needs_par(expr) || npals()) } - fn print_else(&mut self, els: Option<&ast::Expr>) { - if let Some(_else) = els { - match _else.kind { - // Another `else if` block. - ast::ExprKind::If(ref i, ref then, ref e) => { - self.cbox(INDENT_UNIT - 1); - self.ibox(0); - self.word(" else if "); - self.print_expr_as_cond(i); - self.space(); - self.print_block(then); - self.print_else(e.as_deref()) - } - // Final `else` block. - ast::ExprKind::Block(ref b, _) => { - self.cbox(INDENT_UNIT - 1); - self.ibox(0); - self.word(" else "); - self.print_block(b) - } - // Constraints would be great here! - _ => { - panic!("print_if saw if with weird alternative"); - } - } - } - } - - crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) { - self.head("if"); - self.print_expr_as_cond(test); - self.space(); - self.print_block(blk); - self.print_else(elseopt) - } - crate fn print_mac(&mut self, m: &ast::MacCall) { self.print_mac_common( Some(MacHeader::Path(&m.path)), @@ -1729,533 +1187,6 @@ impl<'a> State<'a> { ); } - fn print_call_post(&mut self, args: &[P]) { - self.popen(); - self.commasep_exprs(Inconsistent, args); - self.pclose() - } - - crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) { - self.print_expr_cond_paren(expr, expr.precedence().order() < prec) - } - - /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in - /// `if cond { ... }`. - crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) { - self.print_expr_cond_paren(expr, Self::cond_needs_par(expr)) - } - - // Does `expr` need parentheses when printed in a condition position? - // - // These cases need parens due to the parse error observed in #26461: `if return {}` - // parses as the erroneous construct `if (return {})`, not `if (return) {}`. - fn cond_needs_par(expr: &ast::Expr) -> bool { - match expr.kind { - ast::ExprKind::Break(..) | ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) => true, - _ => parser::contains_exterior_struct_lit(expr), - } - } - - /// Prints `expr` or `(expr)` when `needs_par` holds. - fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) { - if needs_par { - self.popen(); - } - self.print_expr(expr); - if needs_par { - self.pclose(); - } - } - - fn print_expr_vec(&mut self, exprs: &[P]) { - self.ibox(INDENT_UNIT); - self.word("["); - self.commasep_exprs(Inconsistent, exprs); - self.word("]"); - self.end(); - } - - fn print_expr_anon_const(&mut self, expr: &ast::AnonConst) { - self.ibox(INDENT_UNIT); - self.word("const"); - self.print_expr(&expr.value); - self.end(); - } - - fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) { - self.ibox(INDENT_UNIT); - self.word("["); - self.print_expr(element); - self.word_space(";"); - self.print_expr(&count.value); - self.word("]"); - self.end(); - } - - fn print_expr_struct( - &mut self, - qself: &Option, - path: &ast::Path, - fields: &[ast::ExprField], - rest: &ast::StructRest, - ) { - if let Some(qself) = qself { - self.print_qpath(path, qself, true); - } else { - self.print_path(path, true, 0); - } - self.word("{"); - self.commasep_cmnt( - Consistent, - fields, - |s, field| { - s.print_outer_attributes(&field.attrs); - s.ibox(INDENT_UNIT); - if !field.is_shorthand { - s.print_ident(field.ident); - s.word_space(":"); - } - s.print_expr(&field.expr); - s.end(); - }, - |f| f.span, - ); - match rest { - ast::StructRest::Base(_) | ast::StructRest::Rest(_) => { - self.ibox(INDENT_UNIT); - if !fields.is_empty() { - self.word(","); - self.space(); - } - self.word(".."); - if let ast::StructRest::Base(ref expr) = *rest { - self.print_expr(expr); - } - self.end(); - } - ast::StructRest::None if !fields.is_empty() => self.word(","), - _ => {} - } - self.word("}"); - } - - fn print_expr_tup(&mut self, exprs: &[P]) { - self.popen(); - self.commasep_exprs(Inconsistent, exprs); - if exprs.len() == 1 { - self.word(","); - } - self.pclose() - } - - fn print_expr_call(&mut self, func: &ast::Expr, args: &[P]) { - let prec = match func.kind { - ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN, - _ => parser::PREC_POSTFIX, - }; - - self.print_expr_maybe_paren(func, prec); - self.print_call_post(args) - } - - fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P]) { - let base_args = &args[1..]; - self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX); - self.word("."); - self.print_ident(segment.ident); - if let Some(ref args) = segment.args { - self.print_generic_args(args, true); - } - self.print_call_post(base_args) - } - - fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) { - let assoc_op = AssocOp::from_ast_binop(op.node); - let prec = assoc_op.precedence() as i8; - let fixity = assoc_op.fixity(); - - let (left_prec, right_prec) = match fixity { - Fixity::Left => (prec, prec + 1), - Fixity::Right => (prec + 1, prec), - Fixity::None => (prec + 1, prec + 1), - }; - - let left_prec = match (&lhs.kind, op.node) { - // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is - // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead - // of `(x as i32) < ...`. We need to convince it _not_ to do that. - (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => { - parser::PREC_FORCE_PAREN - } - // We are given `(let _ = a) OP b`. - // - // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens - // as the parser will interpret this as `(let _ = a) OP b`. - // - // - Otherwise, e.g. when we have `(let a = b) < c` in AST, - // parens are required since the parser would interpret `let a = b < c` as - // `let a = (b < c)`. To achieve this, we force parens. - (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => { - parser::PREC_FORCE_PAREN - } - _ => left_prec, - }; - - self.print_expr_maybe_paren(lhs, left_prec); - self.space(); - self.word_space(op.node.to_string()); - self.print_expr_maybe_paren(rhs, right_prec) - } - - fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) { - self.word(ast::UnOp::to_string(op)); - self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) - } - - fn print_expr_addr_of( - &mut self, - kind: ast::BorrowKind, - mutability: ast::Mutability, - expr: &ast::Expr, - ) { - self.word("&"); - match kind { - ast::BorrowKind::Ref => self.print_mutability(mutability, false), - ast::BorrowKind::Raw => { - self.word_nbsp("raw"); - self.print_mutability(mutability, true); - } - } - self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) - } - - pub fn print_expr(&mut self, expr: &ast::Expr) { - self.print_expr_outer_attr_style(expr, true) - } - - fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) { - self.maybe_print_comment(expr.span.lo()); - - let attrs = &expr.attrs; - if is_inline { - self.print_outer_attributes_inline(attrs); - } else { - self.print_outer_attributes(attrs); - } - - self.ibox(INDENT_UNIT); - self.ann.pre(self, AnnNode::Expr(expr)); - match expr.kind { - ast::ExprKind::Box(ref expr) => { - self.word_space("box"); - self.print_expr_maybe_paren(expr, parser::PREC_PREFIX); - } - ast::ExprKind::Array(ref exprs) => { - self.print_expr_vec(exprs); - } - ast::ExprKind::ConstBlock(ref anon_const) => { - self.print_expr_anon_const(anon_const); - } - ast::ExprKind::Repeat(ref element, ref count) => { - self.print_expr_repeat(element, count); - } - ast::ExprKind::Struct(ref se) => { - self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest); - } - ast::ExprKind::Tup(ref exprs) => { - self.print_expr_tup(exprs); - } - ast::ExprKind::Call(ref func, ref args) => { - self.print_expr_call(func, &args); - } - ast::ExprKind::MethodCall(ref segment, ref args, _) => { - self.print_expr_method_call(segment, &args); - } - ast::ExprKind::Binary(op, ref lhs, ref rhs) => { - self.print_expr_binary(op, lhs, rhs); - } - ast::ExprKind::Unary(op, ref expr) => { - self.print_expr_unary(op, expr); - } - ast::ExprKind::AddrOf(k, m, ref expr) => { - self.print_expr_addr_of(k, m, expr); - } - ast::ExprKind::Lit(ref lit) => { - self.print_literal(lit); - } - ast::ExprKind::Cast(ref expr, ref ty) => { - let prec = AssocOp::As.precedence() as i8; - self.print_expr_maybe_paren(expr, prec); - self.space(); - self.word_space("as"); - self.print_type(ty); - } - ast::ExprKind::Type(ref expr, ref ty) => { - let prec = AssocOp::Colon.precedence() as i8; - self.print_expr_maybe_paren(expr, prec); - self.word_space(":"); - self.print_type(ty); - } - ast::ExprKind::Let(ref pat, ref scrutinee, _) => { - self.print_let(pat, scrutinee); - } - ast::ExprKind::If(ref test, ref blk, ref elseopt) => { - self.print_if(test, blk, elseopt.as_deref()) - } - ast::ExprKind::While(ref test, ref blk, opt_label) => { - if let Some(label) = opt_label { - self.print_ident(label.ident); - self.word_space(":"); - } - self.head("while"); - self.print_expr_as_cond(test); - self.space(); - self.print_block_with_attrs(blk, attrs); - } - ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => { - if let Some(label) = opt_label { - self.print_ident(label.ident); - self.word_space(":"); - } - self.head("for"); - self.print_pat(pat); - self.space(); - self.word_space("in"); - self.print_expr_as_cond(iter); - self.space(); - self.print_block_with_attrs(blk, attrs); - } - ast::ExprKind::Loop(ref blk, opt_label) => { - if let Some(label) = opt_label { - self.print_ident(label.ident); - self.word_space(":"); - } - self.head("loop"); - self.print_block_with_attrs(blk, attrs); - } - ast::ExprKind::Match(ref expr, ref arms) => { - self.cbox(INDENT_UNIT); - self.ibox(INDENT_UNIT); - self.word_nbsp("match"); - self.print_expr_as_cond(expr); - self.space(); - self.bopen(); - self.print_inner_attributes_no_trailing_hardbreak(attrs); - for arm in arms { - self.print_arm(arm); - } - let empty = attrs.is_empty() && arms.is_empty(); - self.bclose(expr.span, empty); - } - ast::ExprKind::Closure( - capture_clause, - asyncness, - movability, - ref decl, - ref body, - _, - ) => { - self.print_movability(movability); - self.print_asyncness(asyncness); - self.print_capture_clause(capture_clause); - - self.print_fn_params_and_ret(decl, true); - self.space(); - self.print_expr(body); - self.end(); // need to close a box - - // a box will be closed by print_expr, but we didn't want an overall - // wrapper so we closed the corresponding opening. so create an - // empty box to satisfy the close. - self.ibox(0); - } - ast::ExprKind::Block(ref blk, opt_label) => { - if let Some(label) = opt_label { - self.print_ident(label.ident); - self.word_space(":"); - } - // containing cbox, will be closed by print-block at } - self.cbox(INDENT_UNIT); - // head-box, will be closed by print-block after { - self.ibox(0); - self.print_block_with_attrs(blk, attrs); - } - ast::ExprKind::Async(capture_clause, _, ref blk) => { - self.word_nbsp("async"); - self.print_capture_clause(capture_clause); - // cbox/ibox in analogy to the `ExprKind::Block` arm above - self.cbox(INDENT_UNIT); - self.ibox(0); - self.print_block_with_attrs(blk, attrs); - } - ast::ExprKind::Await(ref expr) => { - self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX); - self.word(".await"); - } - ast::ExprKind::Assign(ref lhs, ref rhs, _) => { - let prec = AssocOp::Assign.precedence() as i8; - self.print_expr_maybe_paren(lhs, prec + 1); - self.space(); - self.word_space("="); - self.print_expr_maybe_paren(rhs, prec); - } - ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => { - let prec = AssocOp::Assign.precedence() as i8; - self.print_expr_maybe_paren(lhs, prec + 1); - self.space(); - self.word(op.node.to_string()); - self.word_space("="); - self.print_expr_maybe_paren(rhs, prec); - } - ast::ExprKind::Field(ref expr, ident) => { - self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX); - self.word("."); - self.print_ident(ident); - } - ast::ExprKind::Index(ref expr, ref index) => { - self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX); - self.word("["); - self.print_expr(index); - self.word("]"); - } - ast::ExprKind::Range(ref start, ref end, limits) => { - // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence - // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`. - // Here we use a fake precedence value so that any child with lower precedence than - // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.) - let fake_prec = AssocOp::LOr.precedence() as i8; - if let Some(ref e) = *start { - self.print_expr_maybe_paren(e, fake_prec); - } - if limits == ast::RangeLimits::HalfOpen { - self.word(".."); - } else { - self.word("..="); - } - if let Some(ref e) = *end { - self.print_expr_maybe_paren(e, fake_prec); - } - } - ast::ExprKind::Underscore => self.word("_"), - ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0), - ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true), - ast::ExprKind::Break(opt_label, ref opt_expr) => { - self.word("break"); - if let Some(label) = opt_label { - self.space(); - self.print_ident(label.ident); - } - if let Some(ref expr) = *opt_expr { - self.space(); - self.print_expr_maybe_paren(expr, parser::PREC_JUMP); - } - } - ast::ExprKind::Continue(opt_label) => { - self.word("continue"); - if let Some(label) = opt_label { - self.space(); - self.print_ident(label.ident); - } - } - ast::ExprKind::Ret(ref result) => { - self.word("return"); - if let Some(ref expr) = *result { - self.word(" "); - self.print_expr_maybe_paren(expr, parser::PREC_JUMP); - } - } - ast::ExprKind::InlineAsm(ref a) => { - self.word("asm!"); - self.print_inline_asm(a); - } - ast::ExprKind::LlvmInlineAsm(ref a) => { - self.word("llvm_asm!"); - self.popen(); - self.print_symbol(a.asm, a.asm_str_style); - self.word_space(":"); - - self.commasep(Inconsistent, &a.outputs, |s, out| { - let constraint = out.constraint.as_str(); - let mut ch = constraint.chars(); - match ch.next() { - Some('=') if out.is_rw => { - s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked) - } - _ => s.print_string(&constraint, ast::StrStyle::Cooked), - } - s.popen(); - s.print_expr(&out.expr); - s.pclose(); - }); - self.space(); - self.word_space(":"); - - self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| { - s.print_symbol(co, ast::StrStyle::Cooked); - s.popen(); - s.print_expr(o); - s.pclose(); - }); - self.space(); - self.word_space(":"); - - self.commasep(Inconsistent, &a.clobbers, |s, &co| { - s.print_symbol(co, ast::StrStyle::Cooked); - }); - - let mut options = vec![]; - if a.volatile { - options.push("volatile"); - } - if a.alignstack { - options.push("alignstack"); - } - if a.dialect == ast::LlvmAsmDialect::Intel { - options.push("intel"); - } - - if !options.is_empty() { - self.space(); - self.word_space(":"); - self.commasep(Inconsistent, &options, |s, &co| { - s.print_string(co, ast::StrStyle::Cooked); - }); - } - - self.pclose(); - } - ast::ExprKind::MacCall(ref m) => self.print_mac(m), - ast::ExprKind::Paren(ref e) => { - self.popen(); - self.print_expr(e); - self.pclose(); - } - ast::ExprKind::Yield(ref e) => { - self.word("yield"); - - if let Some(ref expr) = *e { - self.space(); - self.print_expr_maybe_paren(expr, parser::PREC_JUMP); - } - } - ast::ExprKind::Try(ref e) => { - self.print_expr_maybe_paren(e, parser::PREC_POSTFIX); - self.word("?") - } - ast::ExprKind::TryBlock(ref blk) => { - self.head("try"); - self.print_block_with_attrs(blk, attrs) - } - ast::ExprKind::Err => { - self.popen(); - self.word("/*ERROR*/"); - self.pclose() - } - } - self.ann.post(self, AnnNode::Expr(expr)); - self.end(); - } - fn print_inline_asm(&mut self, asm: &ast::InlineAsm) { enum AsmArg<'a> { Template(String), @@ -2551,48 +1482,6 @@ impl<'a> State<'a> { self.ann.post(self, AnnNode::Pat(pat)) } - fn print_arm(&mut self, arm: &ast::Arm) { - // Note, I have no idea why this check is necessary, but here it is. - if arm.attrs.is_empty() { - self.space(); - } - self.cbox(INDENT_UNIT); - self.ibox(0); - self.maybe_print_comment(arm.pat.span.lo()); - self.print_outer_attributes(&arm.attrs); - self.print_pat(&arm.pat); - self.space(); - if let Some(ref e) = arm.guard { - self.word_space("if"); - self.print_expr(e); - self.space(); - } - self.word_space("=>"); - - match arm.body.kind { - ast::ExprKind::Block(ref blk, opt_label) => { - if let Some(label) = opt_label { - self.print_ident(label.ident); - self.word_space(":"); - } - - // The block will close the pattern's ibox. - self.print_block_unclosed_indent(blk); - - // If it is a user-provided unsafe block, print a comma after it. - if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules { - self.word(","); - } - } - _ => { - self.end(); // Close the ibox for the pattern. - self.print_expr(&arm.body); - self.word(","); - } - } - self.end(); // Close enclosing cbox. - } - fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) { match explicit_self.node { SelfKind::Value(m) => { @@ -2614,75 +1503,12 @@ impl<'a> State<'a> { } } - fn print_fn_full( - &mut self, - sig: &ast::FnSig, - name: Ident, - generics: &ast::Generics, - vis: &ast::Visibility, - defaultness: ast::Defaultness, - body: Option<&ast::Block>, - attrs: &[ast::Attribute], - ) { - if body.is_some() { - self.head(""); - } - self.print_visibility(vis); - self.print_defaultness(defaultness); - self.print_fn(&sig.decl, sig.header, Some(name), generics); - if let Some(body) = body { - self.nbsp(); - self.print_block_with_attrs(body, attrs); - } else { - self.word(";"); - } - } - - crate fn print_fn( - &mut self, - decl: &ast::FnDecl, - header: ast::FnHeader, - name: Option, - generics: &ast::Generics, - ) { - self.print_fn_header_info(header); - if let Some(name) = name { - self.nbsp(); - self.print_ident(name); - } - self.print_generic_params(&generics.params); - self.print_fn_params_and_ret(decl, false); - self.print_where_clause(&generics.where_clause) - } - - crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) { - let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") }; - self.word(open); - self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure)); - self.word(close); - self.print_fn_ret_ty(&decl.output) - } - - crate fn print_movability(&mut self, movability: ast::Movability) { - match movability { - ast::Movability::Static => self.word_space("static"), - ast::Movability::Movable => {} - } - } - crate fn print_asyncness(&mut self, asyncness: ast::Async) { if asyncness.is_async() { self.word_nbsp("async"); } } - crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) { - match capture_clause { - ast::CaptureBy::Value => self.word_space("move"), - ast::CaptureBy::Ref => {} - } - } - pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) { if !bounds.is_empty() { self.word(prefix); @@ -2777,83 +1603,6 @@ impl<'a> State<'a> { self.word(">"); } - crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) { - if where_clause.predicates.is_empty() && !where_clause.has_where_token { - return; - } - - self.space(); - self.word_space("where"); - - for (i, predicate) in where_clause.predicates.iter().enumerate() { - if i != 0 { - self.word_space(","); - } - - self.print_where_predicate(predicate); - } - } - - pub fn print_where_predicate(&mut self, predicate: &ast::WherePredicate) { - match predicate { - ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { - bound_generic_params, - bounded_ty, - bounds, - .. - }) => { - self.print_formal_generic_params(bound_generic_params); - self.print_type(bounded_ty); - self.print_type_bounds(":", bounds); - } - ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { - lifetime, - bounds, - .. - }) => { - self.print_lifetime_bounds(*lifetime, bounds); - } - ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { lhs_ty, rhs_ty, .. }) => { - self.print_type(lhs_ty); - self.space(); - self.word_space("="); - self.print_type(rhs_ty); - } - } - } - - crate fn print_use_tree(&mut self, tree: &ast::UseTree) { - match tree.kind { - ast::UseTreeKind::Simple(rename, ..) => { - self.print_path(&tree.prefix, false, 0); - if let Some(rename) = rename { - self.space(); - self.word_space("as"); - self.print_ident(rename); - } - } - ast::UseTreeKind::Glob => { - if !tree.prefix.segments.is_empty() { - self.print_path(&tree.prefix, false, 0); - self.word("::"); - } - self.word("*"); - } - ast::UseTreeKind::Nested(ref items) => { - if tree.prefix.segments.is_empty() { - self.word("{"); - } else { - self.print_path(&tree.prefix, false, 0); - self.word("::{"); - } - self.commasep(Inconsistent, &items, |this, &(ref tree, _)| { - this.print_use_tree(tree) - }); - self.word("}"); - } - } - } - pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) { match mutbl { ast::Mutability::Mut => self.word_nbsp("mut"), diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs new file mode 100644 index 0000000000000..daecc8168d091 --- /dev/null +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -0,0 +1,627 @@ +use crate::pp::Breaks::{Consistent, Inconsistent}; +use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; + +use rustc_ast::ptr::P; +use rustc_ast::util::parser::{self, AssocOp, Fixity}; +use rustc_ast::{self as ast, BlockCheckMode}; + +impl<'a> State<'a> { + fn print_else(&mut self, els: Option<&ast::Expr>) { + if let Some(_else) = els { + match _else.kind { + // Another `else if` block. + ast::ExprKind::If(ref i, ref then, ref e) => { + self.cbox(INDENT_UNIT - 1); + self.ibox(0); + self.word(" else if "); + self.print_expr_as_cond(i); + self.space(); + self.print_block(then); + self.print_else(e.as_deref()) + } + // Final `else` block. + ast::ExprKind::Block(ref b, _) => { + self.cbox(INDENT_UNIT - 1); + self.ibox(0); + self.word(" else "); + self.print_block(b) + } + // Constraints would be great here! + _ => { + panic!("print_if saw if with weird alternative"); + } + } + } + } + + fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) { + self.head("if"); + self.print_expr_as_cond(test); + self.space(); + self.print_block(blk); + self.print_else(elseopt) + } + + fn print_call_post(&mut self, args: &[P]) { + self.popen(); + self.commasep_exprs(Inconsistent, args); + self.pclose() + } + + fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) { + self.print_expr_cond_paren(expr, expr.precedence().order() < prec) + } + + /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in + /// `if cond { ... }`. + fn print_expr_as_cond(&mut self, expr: &ast::Expr) { + self.print_expr_cond_paren(expr, Self::cond_needs_par(expr)) + } + + // Does `expr` need parentheses when printed in a condition position? + // + // These cases need parens due to the parse error observed in #26461: `if return {}` + // parses as the erroneous construct `if (return {})`, not `if (return) {}`. + pub(super) fn cond_needs_par(expr: &ast::Expr) -> bool { + match expr.kind { + ast::ExprKind::Break(..) | ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) => true, + _ => parser::contains_exterior_struct_lit(expr), + } + } + + /// Prints `expr` or `(expr)` when `needs_par` holds. + pub(super) fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) { + if needs_par { + self.popen(); + } + self.print_expr(expr); + if needs_par { + self.pclose(); + } + } + + fn print_expr_vec(&mut self, exprs: &[P]) { + self.ibox(INDENT_UNIT); + self.word("["); + self.commasep_exprs(Inconsistent, exprs); + self.word("]"); + self.end(); + } + + fn print_expr_anon_const(&mut self, expr: &ast::AnonConst) { + self.ibox(INDENT_UNIT); + self.word("const"); + self.print_expr(&expr.value); + self.end(); + } + + fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) { + self.ibox(INDENT_UNIT); + self.word("["); + self.print_expr(element); + self.word_space(";"); + self.print_expr(&count.value); + self.word("]"); + self.end(); + } + + fn print_expr_struct( + &mut self, + qself: &Option, + path: &ast::Path, + fields: &[ast::ExprField], + rest: &ast::StructRest, + ) { + if let Some(qself) = qself { + self.print_qpath(path, qself, true); + } else { + self.print_path(path, true, 0); + } + self.word("{"); + self.commasep_cmnt( + Consistent, + fields, + |s, field| { + s.print_outer_attributes(&field.attrs); + s.ibox(INDENT_UNIT); + if !field.is_shorthand { + s.print_ident(field.ident); + s.word_space(":"); + } + s.print_expr(&field.expr); + s.end(); + }, + |f| f.span, + ); + match rest { + ast::StructRest::Base(_) | ast::StructRest::Rest(_) => { + self.ibox(INDENT_UNIT); + if !fields.is_empty() { + self.word(","); + self.space(); + } + self.word(".."); + if let ast::StructRest::Base(ref expr) = *rest { + self.print_expr(expr); + } + self.end(); + } + ast::StructRest::None if !fields.is_empty() => self.word(","), + _ => {} + } + self.word("}"); + } + + fn print_expr_tup(&mut self, exprs: &[P]) { + self.popen(); + self.commasep_exprs(Inconsistent, exprs); + if exprs.len() == 1 { + self.word(","); + } + self.pclose() + } + + fn print_expr_call(&mut self, func: &ast::Expr, args: &[P]) { + let prec = match func.kind { + ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN, + _ => parser::PREC_POSTFIX, + }; + + self.print_expr_maybe_paren(func, prec); + self.print_call_post(args) + } + + fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P]) { + let base_args = &args[1..]; + self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX); + self.word("."); + self.print_ident(segment.ident); + if let Some(ref args) = segment.args { + self.print_generic_args(args, true); + } + self.print_call_post(base_args) + } + + fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) { + let assoc_op = AssocOp::from_ast_binop(op.node); + let prec = assoc_op.precedence() as i8; + let fixity = assoc_op.fixity(); + + let (left_prec, right_prec) = match fixity { + Fixity::Left => (prec, prec + 1), + Fixity::Right => (prec + 1, prec), + Fixity::None => (prec + 1, prec + 1), + }; + + let left_prec = match (&lhs.kind, op.node) { + // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is + // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead + // of `(x as i32) < ...`. We need to convince it _not_ to do that. + (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => { + parser::PREC_FORCE_PAREN + } + // We are given `(let _ = a) OP b`. + // + // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens + // as the parser will interpret this as `(let _ = a) OP b`. + // + // - Otherwise, e.g. when we have `(let a = b) < c` in AST, + // parens are required since the parser would interpret `let a = b < c` as + // `let a = (b < c)`. To achieve this, we force parens. + (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => { + parser::PREC_FORCE_PAREN + } + _ => left_prec, + }; + + self.print_expr_maybe_paren(lhs, left_prec); + self.space(); + self.word_space(op.node.to_string()); + self.print_expr_maybe_paren(rhs, right_prec) + } + + fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) { + self.word(ast::UnOp::to_string(op)); + self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) + } + + fn print_expr_addr_of( + &mut self, + kind: ast::BorrowKind, + mutability: ast::Mutability, + expr: &ast::Expr, + ) { + self.word("&"); + match kind { + ast::BorrowKind::Ref => self.print_mutability(mutability, false), + ast::BorrowKind::Raw => { + self.word_nbsp("raw"); + self.print_mutability(mutability, true); + } + } + self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) + } + + pub fn print_expr(&mut self, expr: &ast::Expr) { + self.print_expr_outer_attr_style(expr, true) + } + + pub(super) fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) { + self.maybe_print_comment(expr.span.lo()); + + let attrs = &expr.attrs; + if is_inline { + self.print_outer_attributes_inline(attrs); + } else { + self.print_outer_attributes(attrs); + } + + self.ibox(INDENT_UNIT); + self.ann.pre(self, AnnNode::Expr(expr)); + match expr.kind { + ast::ExprKind::Box(ref expr) => { + self.word_space("box"); + self.print_expr_maybe_paren(expr, parser::PREC_PREFIX); + } + ast::ExprKind::Array(ref exprs) => { + self.print_expr_vec(exprs); + } + ast::ExprKind::ConstBlock(ref anon_const) => { + self.print_expr_anon_const(anon_const); + } + ast::ExprKind::Repeat(ref element, ref count) => { + self.print_expr_repeat(element, count); + } + ast::ExprKind::Struct(ref se) => { + self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest); + } + ast::ExprKind::Tup(ref exprs) => { + self.print_expr_tup(exprs); + } + ast::ExprKind::Call(ref func, ref args) => { + self.print_expr_call(func, &args); + } + ast::ExprKind::MethodCall(ref segment, ref args, _) => { + self.print_expr_method_call(segment, &args); + } + ast::ExprKind::Binary(op, ref lhs, ref rhs) => { + self.print_expr_binary(op, lhs, rhs); + } + ast::ExprKind::Unary(op, ref expr) => { + self.print_expr_unary(op, expr); + } + ast::ExprKind::AddrOf(k, m, ref expr) => { + self.print_expr_addr_of(k, m, expr); + } + ast::ExprKind::Lit(ref lit) => { + self.print_literal(lit); + } + ast::ExprKind::Cast(ref expr, ref ty) => { + let prec = AssocOp::As.precedence() as i8; + self.print_expr_maybe_paren(expr, prec); + self.space(); + self.word_space("as"); + self.print_type(ty); + } + ast::ExprKind::Type(ref expr, ref ty) => { + let prec = AssocOp::Colon.precedence() as i8; + self.print_expr_maybe_paren(expr, prec); + self.word_space(":"); + self.print_type(ty); + } + ast::ExprKind::Let(ref pat, ref scrutinee, _) => { + self.print_let(pat, scrutinee); + } + ast::ExprKind::If(ref test, ref blk, ref elseopt) => { + self.print_if(test, blk, elseopt.as_deref()) + } + ast::ExprKind::While(ref test, ref blk, opt_label) => { + if let Some(label) = opt_label { + self.print_ident(label.ident); + self.word_space(":"); + } + self.head("while"); + self.print_expr_as_cond(test); + self.space(); + self.print_block_with_attrs(blk, attrs); + } + ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => { + if let Some(label) = opt_label { + self.print_ident(label.ident); + self.word_space(":"); + } + self.head("for"); + self.print_pat(pat); + self.space(); + self.word_space("in"); + self.print_expr_as_cond(iter); + self.space(); + self.print_block_with_attrs(blk, attrs); + } + ast::ExprKind::Loop(ref blk, opt_label) => { + if let Some(label) = opt_label { + self.print_ident(label.ident); + self.word_space(":"); + } + self.head("loop"); + self.print_block_with_attrs(blk, attrs); + } + ast::ExprKind::Match(ref expr, ref arms) => { + self.cbox(INDENT_UNIT); + self.ibox(INDENT_UNIT); + self.word_nbsp("match"); + self.print_expr_as_cond(expr); + self.space(); + self.bopen(); + self.print_inner_attributes_no_trailing_hardbreak(attrs); + for arm in arms { + self.print_arm(arm); + } + let empty = attrs.is_empty() && arms.is_empty(); + self.bclose(expr.span, empty); + } + ast::ExprKind::Closure( + capture_clause, + asyncness, + movability, + ref decl, + ref body, + _, + ) => { + self.print_movability(movability); + self.print_asyncness(asyncness); + self.print_capture_clause(capture_clause); + + self.print_fn_params_and_ret(decl, true); + self.space(); + self.print_expr(body); + self.end(); // need to close a box + + // a box will be closed by print_expr, but we didn't want an overall + // wrapper so we closed the corresponding opening. so create an + // empty box to satisfy the close. + self.ibox(0); + } + ast::ExprKind::Block(ref blk, opt_label) => { + if let Some(label) = opt_label { + self.print_ident(label.ident); + self.word_space(":"); + } + // containing cbox, will be closed by print-block at } + self.cbox(INDENT_UNIT); + // head-box, will be closed by print-block after { + self.ibox(0); + self.print_block_with_attrs(blk, attrs); + } + ast::ExprKind::Async(capture_clause, _, ref blk) => { + self.word_nbsp("async"); + self.print_capture_clause(capture_clause); + // cbox/ibox in analogy to the `ExprKind::Block` arm above + self.cbox(INDENT_UNIT); + self.ibox(0); + self.print_block_with_attrs(blk, attrs); + } + ast::ExprKind::Await(ref expr) => { + self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX); + self.word(".await"); + } + ast::ExprKind::Assign(ref lhs, ref rhs, _) => { + let prec = AssocOp::Assign.precedence() as i8; + self.print_expr_maybe_paren(lhs, prec + 1); + self.space(); + self.word_space("="); + self.print_expr_maybe_paren(rhs, prec); + } + ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => { + let prec = AssocOp::Assign.precedence() as i8; + self.print_expr_maybe_paren(lhs, prec + 1); + self.space(); + self.word(op.node.to_string()); + self.word_space("="); + self.print_expr_maybe_paren(rhs, prec); + } + ast::ExprKind::Field(ref expr, ident) => { + self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX); + self.word("."); + self.print_ident(ident); + } + ast::ExprKind::Index(ref expr, ref index) => { + self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX); + self.word("["); + self.print_expr(index); + self.word("]"); + } + ast::ExprKind::Range(ref start, ref end, limits) => { + // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence + // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`. + // Here we use a fake precedence value so that any child with lower precedence than + // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.) + let fake_prec = AssocOp::LOr.precedence() as i8; + if let Some(ref e) = *start { + self.print_expr_maybe_paren(e, fake_prec); + } + if limits == ast::RangeLimits::HalfOpen { + self.word(".."); + } else { + self.word("..="); + } + if let Some(ref e) = *end { + self.print_expr_maybe_paren(e, fake_prec); + } + } + ast::ExprKind::Underscore => self.word("_"), + ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0), + ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true), + ast::ExprKind::Break(opt_label, ref opt_expr) => { + self.word("break"); + if let Some(label) = opt_label { + self.space(); + self.print_ident(label.ident); + } + if let Some(ref expr) = *opt_expr { + self.space(); + self.print_expr_maybe_paren(expr, parser::PREC_JUMP); + } + } + ast::ExprKind::Continue(opt_label) => { + self.word("continue"); + if let Some(label) = opt_label { + self.space(); + self.print_ident(label.ident); + } + } + ast::ExprKind::Ret(ref result) => { + self.word("return"); + if let Some(ref expr) = *result { + self.word(" "); + self.print_expr_maybe_paren(expr, parser::PREC_JUMP); + } + } + ast::ExprKind::InlineAsm(ref a) => { + self.word("asm!"); + self.print_inline_asm(a); + } + ast::ExprKind::LlvmInlineAsm(ref a) => { + self.word("llvm_asm!"); + self.popen(); + self.print_symbol(a.asm, a.asm_str_style); + self.word_space(":"); + + self.commasep(Inconsistent, &a.outputs, |s, out| { + let constraint = out.constraint.as_str(); + let mut ch = constraint.chars(); + match ch.next() { + Some('=') if out.is_rw => { + s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked) + } + _ => s.print_string(&constraint, ast::StrStyle::Cooked), + } + s.popen(); + s.print_expr(&out.expr); + s.pclose(); + }); + self.space(); + self.word_space(":"); + + self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| { + s.print_symbol(co, ast::StrStyle::Cooked); + s.popen(); + s.print_expr(o); + s.pclose(); + }); + self.space(); + self.word_space(":"); + + self.commasep(Inconsistent, &a.clobbers, |s, &co| { + s.print_symbol(co, ast::StrStyle::Cooked); + }); + + let mut options = vec![]; + if a.volatile { + options.push("volatile"); + } + if a.alignstack { + options.push("alignstack"); + } + if a.dialect == ast::LlvmAsmDialect::Intel { + options.push("intel"); + } + + if !options.is_empty() { + self.space(); + self.word_space(":"); + self.commasep(Inconsistent, &options, |s, &co| { + s.print_string(co, ast::StrStyle::Cooked); + }); + } + + self.pclose(); + } + ast::ExprKind::MacCall(ref m) => self.print_mac(m), + ast::ExprKind::Paren(ref e) => { + self.popen(); + self.print_expr(e); + self.pclose(); + } + ast::ExprKind::Yield(ref e) => { + self.word("yield"); + + if let Some(ref expr) = *e { + self.space(); + self.print_expr_maybe_paren(expr, parser::PREC_JUMP); + } + } + ast::ExprKind::Try(ref e) => { + self.print_expr_maybe_paren(e, parser::PREC_POSTFIX); + self.word("?") + } + ast::ExprKind::TryBlock(ref blk) => { + self.head("try"); + self.print_block_with_attrs(blk, attrs) + } + ast::ExprKind::Err => { + self.popen(); + self.word("/*ERROR*/"); + self.pclose() + } + } + self.ann.post(self, AnnNode::Expr(expr)); + self.end(); + } + + fn print_arm(&mut self, arm: &ast::Arm) { + // Note, I have no idea why this check is necessary, but here it is. + if arm.attrs.is_empty() { + self.space(); + } + self.cbox(INDENT_UNIT); + self.ibox(0); + self.maybe_print_comment(arm.pat.span.lo()); + self.print_outer_attributes(&arm.attrs); + self.print_pat(&arm.pat); + self.space(); + if let Some(ref e) = arm.guard { + self.word_space("if"); + self.print_expr(e); + self.space(); + } + self.word_space("=>"); + + match arm.body.kind { + ast::ExprKind::Block(ref blk, opt_label) => { + if let Some(label) = opt_label { + self.print_ident(label.ident); + self.word_space(":"); + } + + // The block will close the pattern's ibox. + self.print_block_unclosed_indent(blk); + + // If it is a user-provided unsafe block, print a comma after it. + if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules { + self.word(","); + } + } + _ => { + self.end(); // Close the ibox for the pattern. + self.print_expr(&arm.body); + self.word(","); + } + } + self.end(); // Close enclosing cbox. + } + + fn print_movability(&mut self, movability: ast::Movability) { + match movability { + ast::Movability::Static => self.word_space("static"), + ast::Movability::Movable => {} + } + } + + fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) { + match capture_clause { + ast::CaptureBy::Value => self.word_space("move"), + ast::CaptureBy::Ref => {} + } + } +} diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs new file mode 100644 index 0000000000000..837734bca627f --- /dev/null +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -0,0 +1,644 @@ +use crate::pp::Breaks::Inconsistent; +use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; + +use rustc_ast as ast; +use rustc_ast::GenericBound; +use rustc_ast::ModKind; +use rustc_span::symbol::Ident; + +fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String { + format!("{}{}", State::to_string(|s| s.print_visibility(vis)), s) +} + +impl<'a> State<'a> { + fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) { + self.print_inner_attributes(attrs); + for item in &nmod.items { + self.print_foreign_item(item); + } + } + + fn print_foreign_item(&mut self, item: &ast::ForeignItem) { + let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item; + self.ann.pre(self, AnnNode::SubItem(id)); + self.hardbreak_if_not_bol(); + self.maybe_print_comment(span.lo()); + self.print_outer_attributes(attrs); + match kind { + ast::ForeignItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => { + self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs); + } + ast::ForeignItemKind::Static(ty, mutbl, body) => { + let def = ast::Defaultness::Final; + self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def); + } + ast::ForeignItemKind::TyAlias(box ast::TyAlias { + defaultness, + generics, + bounds, + ty, + }) => { + self.print_associated_type( + ident, + generics, + bounds, + ty.as_deref(), + vis, + *defaultness, + ); + } + ast::ForeignItemKind::MacCall(m) => { + self.print_mac(m); + if m.args.need_semicolon() { + self.word(";"); + } + } + } + self.ann.post(self, AnnNode::SubItem(id)) + } + + fn print_item_const( + &mut self, + ident: Ident, + mutbl: Option, + ty: &ast::Ty, + body: Option<&ast::Expr>, + vis: &ast::Visibility, + defaultness: ast::Defaultness, + ) { + self.head(""); + self.print_visibility(vis); + self.print_defaultness(defaultness); + let leading = match mutbl { + None => "const", + Some(ast::Mutability::Not) => "static", + Some(ast::Mutability::Mut) => "static mut", + }; + self.word_space(leading); + self.print_ident(ident); + self.word_space(":"); + self.print_type(ty); + if body.is_some() { + self.space(); + } + self.end(); // end the head-ibox + if let Some(body) = body { + self.word_space("="); + self.print_expr(body); + } + self.word(";"); + self.end(); // end the outer cbox + } + + fn print_associated_type( + &mut self, + ident: Ident, + generics: &ast::Generics, + bounds: &ast::GenericBounds, + ty: Option<&ast::Ty>, + vis: &ast::Visibility, + defaultness: ast::Defaultness, + ) { + self.head(""); + self.print_visibility(vis); + self.print_defaultness(defaultness); + self.word_space("type"); + self.print_ident(ident); + self.print_generic_params(&generics.params); + self.print_type_bounds(":", bounds); + self.print_where_clause(&generics.where_clause); + if let Some(ty) = ty { + self.space(); + self.word_space("="); + self.print_type(ty); + } + self.word(";"); + self.end(); // end inner head-block + self.end(); // end outer head-block + } + + /// Pretty-prints an item. + crate fn print_item(&mut self, item: &ast::Item) { + self.hardbreak_if_not_bol(); + self.maybe_print_comment(item.span.lo()); + self.print_outer_attributes(&item.attrs); + self.ann.pre(self, AnnNode::Item(item)); + match item.kind { + ast::ItemKind::ExternCrate(orig_name) => { + self.head(visibility_qualified(&item.vis, "extern crate")); + if let Some(orig_name) = orig_name { + self.print_name(orig_name); + self.space(); + self.word("as"); + self.space(); + } + self.print_ident(item.ident); + self.word(";"); + self.end(); // end inner head-block + self.end(); // end outer head-block + } + ast::ItemKind::Use(ref tree) => { + self.head(visibility_qualified(&item.vis, "use")); + self.print_use_tree(tree); + self.word(";"); + self.end(); // end inner head-block + self.end(); // end outer head-block + } + ast::ItemKind::Static(ref ty, mutbl, ref body) => { + let def = ast::Defaultness::Final; + self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def); + } + ast::ItemKind::Const(def, ref ty, ref body) => { + self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def); + } + ast::ItemKind::Fn(box ast::Fn { defaultness, ref sig, ref generics, ref body }) => { + let body = body.as_deref(); + self.print_fn_full( + sig, + item.ident, + generics, + &item.vis, + defaultness, + body, + &item.attrs, + ); + } + ast::ItemKind::Mod(unsafety, ref mod_kind) => { + self.head(Self::to_string(|s| { + s.print_visibility(&item.vis); + s.print_unsafety(unsafety); + s.word("mod"); + })); + self.print_ident(item.ident); + + match mod_kind { + ModKind::Loaded(items, ..) => { + self.nbsp(); + self.bopen(); + self.print_inner_attributes(&item.attrs); + for item in items { + self.print_item(item); + } + let empty = item.attrs.is_empty() && items.is_empty(); + self.bclose(item.span, empty); + } + ModKind::Unloaded => { + self.word(";"); + self.end(); // end inner head-block + self.end(); // end outer head-block + } + } + } + ast::ItemKind::ForeignMod(ref nmod) => { + self.head(Self::to_string(|s| { + s.print_unsafety(nmod.unsafety); + s.word("extern"); + })); + if let Some(abi) = nmod.abi { + self.print_literal(&abi.as_lit()); + self.nbsp(); + } + self.bopen(); + self.print_foreign_mod(nmod, &item.attrs); + let empty = item.attrs.is_empty() && nmod.items.is_empty(); + self.bclose(item.span, empty); + } + ast::ItemKind::GlobalAsm(ref asm) => { + self.head(visibility_qualified(&item.vis, "global_asm!")); + self.print_inline_asm(asm); + self.end(); + } + ast::ItemKind::TyAlias(box ast::TyAlias { + defaultness, + ref generics, + ref bounds, + ref ty, + }) => { + let ty = ty.as_deref(); + self.print_associated_type( + item.ident, + generics, + bounds, + ty, + &item.vis, + defaultness, + ); + } + ast::ItemKind::Enum(ref enum_definition, ref params) => { + self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis); + } + ast::ItemKind::Struct(ref struct_def, ref generics) => { + self.head(visibility_qualified(&item.vis, "struct")); + self.print_struct(struct_def, generics, item.ident, item.span, true); + } + ast::ItemKind::Union(ref struct_def, ref generics) => { + self.head(visibility_qualified(&item.vis, "union")); + self.print_struct(struct_def, generics, item.ident, item.span, true); + } + ast::ItemKind::Impl(box ast::Impl { + unsafety, + polarity, + defaultness, + constness, + ref generics, + ref of_trait, + ref self_ty, + ref items, + }) => { + self.head(""); + self.print_visibility(&item.vis); + self.print_defaultness(defaultness); + self.print_unsafety(unsafety); + self.word("impl"); + + if generics.params.is_empty() { + self.nbsp(); + } else { + self.print_generic_params(&generics.params); + self.space(); + } + + self.print_constness(constness); + + if let ast::ImplPolarity::Negative(_) = polarity { + self.word("!"); + } + + if let Some(ref t) = *of_trait { + self.print_trait_ref(t); + self.space(); + self.word_space("for"); + } + + self.print_type(self_ty); + self.print_where_clause(&generics.where_clause); + + self.space(); + self.bopen(); + self.print_inner_attributes(&item.attrs); + for impl_item in items { + self.print_assoc_item(impl_item); + } + let empty = item.attrs.is_empty() && items.is_empty(); + self.bclose(item.span, empty); + } + ast::ItemKind::Trait(box ast::Trait { + is_auto, + unsafety, + ref generics, + ref bounds, + ref items, + .. + }) => { + self.head(""); + self.print_visibility(&item.vis); + self.print_unsafety(unsafety); + self.print_is_auto(is_auto); + self.word_nbsp("trait"); + self.print_ident(item.ident); + self.print_generic_params(&generics.params); + let mut real_bounds = Vec::with_capacity(bounds.len()); + for b in bounds.iter() { + if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { + self.space(); + self.word_space("for ?"); + self.print_trait_ref(&ptr.trait_ref); + } else { + real_bounds.push(b.clone()); + } + } + self.print_type_bounds(":", &real_bounds); + self.print_where_clause(&generics.where_clause); + self.word(" "); + self.bopen(); + self.print_inner_attributes(&item.attrs); + for trait_item in items { + self.print_assoc_item(trait_item); + } + let empty = item.attrs.is_empty() && items.is_empty(); + self.bclose(item.span, empty); + } + ast::ItemKind::TraitAlias(ref generics, ref bounds) => { + self.head(""); + self.print_visibility(&item.vis); + self.word_nbsp("trait"); + self.print_ident(item.ident); + self.print_generic_params(&generics.params); + let mut real_bounds = Vec::with_capacity(bounds.len()); + // FIXME(durka) this seems to be some quite outdated syntax + for b in bounds.iter() { + if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b { + self.space(); + self.word_space("for ?"); + self.print_trait_ref(&ptr.trait_ref); + } else { + real_bounds.push(b.clone()); + } + } + self.nbsp(); + self.print_type_bounds("=", &real_bounds); + self.print_where_clause(&generics.where_clause); + self.word(";"); + } + ast::ItemKind::MacCall(ref mac) => { + self.print_mac(mac); + if mac.args.need_semicolon() { + self.word(";"); + } + } + ast::ItemKind::MacroDef(ref macro_def) => { + self.print_mac_def(macro_def, &item.ident, &item.span, |state| { + state.print_visibility(&item.vis) + }); + } + } + self.ann.post(self, AnnNode::Item(item)) + } + + fn print_enum_def( + &mut self, + enum_definition: &ast::EnumDef, + generics: &ast::Generics, + ident: Ident, + span: rustc_span::Span, + visibility: &ast::Visibility, + ) { + self.head(visibility_qualified(visibility, "enum")); + self.print_ident(ident); + self.print_generic_params(&generics.params); + self.print_where_clause(&generics.where_clause); + self.space(); + self.print_variants(&enum_definition.variants, span) + } + + fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) { + self.bopen(); + for v in variants { + self.space_if_not_bol(); + self.maybe_print_comment(v.span.lo()); + self.print_outer_attributes(&v.attrs); + self.ibox(INDENT_UNIT); + self.print_variant(v); + self.word(","); + self.end(); + self.maybe_print_trailing_comment(v.span, None); + } + let empty = variants.is_empty(); + self.bclose(span, empty) + } + + crate fn print_visibility(&mut self, vis: &ast::Visibility) { + match vis.kind { + ast::VisibilityKind::Public => self.word_nbsp("pub"), + ast::VisibilityKind::Crate(sugar) => match sugar { + ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"), + ast::CrateSugar::JustCrate => self.word_nbsp("crate"), + }, + ast::VisibilityKind::Restricted { ref path, .. } => { + let path = Self::to_string(|s| s.print_path(path, false, 0)); + if path == "self" || path == "super" { + self.word_nbsp(format!("pub({})", path)) + } else { + self.word_nbsp(format!("pub(in {})", path)) + } + } + ast::VisibilityKind::Inherited => {} + } + } + + fn print_defaultness(&mut self, defaultness: ast::Defaultness) { + if let ast::Defaultness::Default(_) = defaultness { + self.word_nbsp("default"); + } + } + + fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) { + self.nbsp(); + self.bopen(); + + let empty = fields.is_empty(); + if !empty { + self.hardbreak_if_not_bol(); + + for field in fields { + self.hardbreak_if_not_bol(); + self.maybe_print_comment(field.span.lo()); + self.print_outer_attributes(&field.attrs); + self.print_visibility(&field.vis); + self.print_ident(field.ident.unwrap()); + self.word_nbsp(":"); + self.print_type(&field.ty); + self.word(","); + } + } + + self.bclose(span, empty); + } + + fn print_struct( + &mut self, + struct_def: &ast::VariantData, + generics: &ast::Generics, + ident: Ident, + span: rustc_span::Span, + print_finalizer: bool, + ) { + self.print_ident(ident); + self.print_generic_params(&generics.params); + match struct_def { + ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => { + if let ast::VariantData::Tuple(..) = struct_def { + self.popen(); + self.commasep(Inconsistent, struct_def.fields(), |s, field| { + s.maybe_print_comment(field.span.lo()); + s.print_outer_attributes(&field.attrs); + s.print_visibility(&field.vis); + s.print_type(&field.ty) + }); + self.pclose(); + } + self.print_where_clause(&generics.where_clause); + if print_finalizer { + self.word(";"); + } + self.end(); + self.end(); // Close the outer-box. + } + ast::VariantData::Struct(ref fields, ..) => { + self.print_where_clause(&generics.where_clause); + self.print_record_struct_body(fields, span); + } + } + } + + crate fn print_variant(&mut self, v: &ast::Variant) { + self.head(""); + self.print_visibility(&v.vis); + let generics = ast::Generics::default(); + self.print_struct(&v.data, &generics, v.ident, v.span, false); + if let Some(ref d) = v.disr_expr { + self.space(); + self.word_space("="); + self.print_expr(&d.value) + } + } + + fn print_assoc_item(&mut self, item: &ast::AssocItem) { + let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item; + self.ann.pre(self, AnnNode::SubItem(id)); + self.hardbreak_if_not_bol(); + self.maybe_print_comment(span.lo()); + self.print_outer_attributes(attrs); + match kind { + ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => { + self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs); + } + ast::AssocItemKind::Const(def, ty, body) => { + self.print_item_const(ident, None, ty, body.as_deref(), vis, *def); + } + ast::AssocItemKind::TyAlias(box ast::TyAlias { defaultness, generics, bounds, ty }) => { + self.print_associated_type( + ident, + generics, + bounds, + ty.as_deref(), + vis, + *defaultness, + ); + } + ast::AssocItemKind::MacCall(m) => { + self.print_mac(m); + if m.args.need_semicolon() { + self.word(";"); + } + } + } + self.ann.post(self, AnnNode::SubItem(id)) + } + + fn print_fn_full( + &mut self, + sig: &ast::FnSig, + name: Ident, + generics: &ast::Generics, + vis: &ast::Visibility, + defaultness: ast::Defaultness, + body: Option<&ast::Block>, + attrs: &[ast::Attribute], + ) { + if body.is_some() { + self.head(""); + } + self.print_visibility(vis); + self.print_defaultness(defaultness); + self.print_fn(&sig.decl, sig.header, Some(name), generics); + if let Some(body) = body { + self.nbsp(); + self.print_block_with_attrs(body, attrs); + } else { + self.word(";"); + } + } + + crate fn print_fn( + &mut self, + decl: &ast::FnDecl, + header: ast::FnHeader, + name: Option, + generics: &ast::Generics, + ) { + self.print_fn_header_info(header); + if let Some(name) = name { + self.nbsp(); + self.print_ident(name); + } + self.print_generic_params(&generics.params); + self.print_fn_params_and_ret(decl, false); + self.print_where_clause(&generics.where_clause) + } + + crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) { + let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") }; + self.word(open); + self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure)); + self.word(close); + self.print_fn_ret_ty(&decl.output) + } + + fn print_where_clause(&mut self, where_clause: &ast::WhereClause) { + if where_clause.predicates.is_empty() && !where_clause.has_where_token { + return; + } + + self.space(); + self.word_space("where"); + + for (i, predicate) in where_clause.predicates.iter().enumerate() { + if i != 0 { + self.word_space(","); + } + + self.print_where_predicate(predicate); + } + } + + pub fn print_where_predicate(&mut self, predicate: &ast::WherePredicate) { + match predicate { + ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { + bound_generic_params, + bounded_ty, + bounds, + .. + }) => { + self.print_formal_generic_params(bound_generic_params); + self.print_type(bounded_ty); + self.print_type_bounds(":", bounds); + } + ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { + lifetime, + bounds, + .. + }) => { + self.print_lifetime_bounds(*lifetime, bounds); + } + ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { lhs_ty, rhs_ty, .. }) => { + self.print_type(lhs_ty); + self.space(); + self.word_space("="); + self.print_type(rhs_ty); + } + } + } + + fn print_use_tree(&mut self, tree: &ast::UseTree) { + match tree.kind { + ast::UseTreeKind::Simple(rename, ..) => { + self.print_path(&tree.prefix, false, 0); + if let Some(rename) = rename { + self.space(); + self.word_space("as"); + self.print_ident(rename); + } + } + ast::UseTreeKind::Glob => { + if !tree.prefix.segments.is_empty() { + self.print_path(&tree.prefix, false, 0); + self.word("::"); + } + self.word("*"); + } + ast::UseTreeKind::Nested(ref items) => { + if tree.prefix.segments.is_empty() { + self.word("{"); + } else { + self.print_path(&tree.prefix, false, 0); + self.word("::{"); + } + self.commasep(Inconsistent, &items, |this, &(ref tree, _)| { + this.print_use_tree(tree) + }); + self.word("}"); + } + } + } +} diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index f25b2d8f566c0..46817bc9c3f08 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -623,6 +623,11 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ lang, Normal, template!(NameValueStr: "name"), DuplicatesOk, lang_items, "language items are subject to change", ), + rustc_attr!( + rustc_pass_by_value, Normal, + template!(Word), WarnFollowing, + "#[rustc_pass_by_value] is used to mark types that must be passed by value instead of reference." + ), BuiltinAttribute { name: sym::rustc_diagnostic_item, type_: Normal, diff --git a/compiler/rustc_index/src/lib.rs b/compiler/rustc_index/src/lib.rs index 359b1859c6889..7919e40925392 100644 --- a/compiler/rustc_index/src/lib.rs +++ b/compiler/rustc_index/src/lib.rs @@ -9,7 +9,3 @@ pub mod bit_set; pub mod interval; pub mod vec; - -// FIXME(#56935): Work around ICEs during cross-compilation. -#[allow(unused)] -extern crate rustc_macros; diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index c64a67b6b9f1b..7353cd6b876b9 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -5,10 +5,7 @@ use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext} use rustc_ast as ast; use rustc_errors::Applicability; use rustc_hir::def::Res; -use rustc_hir::{ - GenericArg, HirId, Item, ItemKind, MutTy, Mutability, Node, Path, PathSegment, QPath, Ty, - TyKind, -}; +use rustc_hir::{GenericArg, HirId, Item, ItemKind, Node, Path, PathSegment, QPath, Ty, TyKind}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::hygiene::{ExpnKind, MacroKind}; @@ -58,13 +55,6 @@ declare_tool_lint! { report_in_external_macro: true } -declare_tool_lint! { - pub rustc::TY_PASS_BY_REFERENCE, - Allow, - "passing `Ty` or `TyCtxt` by reference", - report_in_external_macro: true -} - declare_tool_lint! { pub rustc::USAGE_OF_QUALIFIED_TY, Allow, @@ -74,7 +64,6 @@ declare_tool_lint! { declare_lint_pass!(TyTyKind => [ USAGE_OF_TY_TYKIND, - TY_PASS_BY_REFERENCE, USAGE_OF_QUALIFIED_TY, ]); @@ -131,26 +120,6 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { } } } - TyKind::Rptr(_, MutTy { ty: inner_ty, mutbl: Mutability::Not }) => { - if let Some(impl_did) = cx.tcx.impl_of_method(ty.hir_id.owner.to_def_id()) { - if cx.tcx.impl_trait_ref(impl_did).is_some() { - return; - } - } - if let Some(t) = is_ty_or_ty_ctxt(cx, &inner_ty) { - cx.struct_span_lint(TY_PASS_BY_REFERENCE, ty.span, |lint| { - lint.build(&format!("passing `{}` by reference", t)) - .span_suggestion( - ty.span, - "try passing by value", - t, - // Changing type of function argument - Applicability::MaybeIncorrect, - ) - .emit(); - }) - } - } _ => {} } } diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index c6145ae0d510b..4aa8505c9408d 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -56,6 +56,7 @@ mod non_ascii_idents; mod non_fmt_panic; mod nonstandard_style; mod noop_method_call; +mod pass_by_value; mod passes; mod redundant_semicolon; mod traits; @@ -85,6 +86,7 @@ use non_ascii_idents::*; use non_fmt_panic::NonPanicFmt; use nonstandard_style::*; use noop_method_call::*; +use pass_by_value::*; use redundant_semicolon::*; use traits::*; use types::*; @@ -490,6 +492,8 @@ fn register_internals(store: &mut LintStore) { store.register_late_pass(|| Box::new(ExistingDocKeyword)); store.register_lints(&TyTyKind::get_lints()); store.register_late_pass(|| Box::new(TyTyKind)); + store.register_lints(&PassByValue::get_lints()); + store.register_late_pass(|| Box::new(PassByValue)); store.register_group( false, "rustc::internal", @@ -497,8 +501,8 @@ fn register_internals(store: &mut LintStore) { vec![ LintId::of(DEFAULT_HASH_TYPES), LintId::of(USAGE_OF_TY_TYKIND), + LintId::of(PASS_BY_VALUE), LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO), - LintId::of(TY_PASS_BY_REFERENCE), LintId::of(USAGE_OF_QUALIFIED_TY), LintId::of(EXISTING_DOC_KEYWORD), ], diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs new file mode 100644 index 0000000000000..26d0560bf89bb --- /dev/null +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -0,0 +1,94 @@ +use crate::{LateContext, LateLintPass, LintContext}; +use rustc_errors::Applicability; +use rustc_hir as hir; +use rustc_hir::def::Res; +use rustc_hir::{GenericArg, PathSegment, QPath, TyKind}; +use rustc_middle::ty; +use rustc_span::symbol::sym; + +declare_tool_lint! { + /// The `rustc_pass_by_value` lint marks a type with `#[rustc_pass_by_value]` requiring it to always be passed by value. + /// This is usually used for types that are thin wrappers around references, so there is no benefit to an extra + /// layer of indirection. (Example: `Ty` which is a reference to a `TyS`) + pub rustc::PASS_BY_VALUE, + Warn, + "pass by reference of a type flagged as `#[rustc_pass_by_value]`", + report_in_external_macro: true +} + +declare_lint_pass!(PassByValue => [PASS_BY_VALUE]); + +impl<'tcx> LateLintPass<'tcx> for PassByValue { + fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx>) { + match &ty.kind { + TyKind::Rptr(_, hir::MutTy { ty: inner_ty, mutbl: hir::Mutability::Not }) => { + if let Some(impl_did) = cx.tcx.impl_of_method(ty.hir_id.owner.to_def_id()) { + if cx.tcx.impl_trait_ref(impl_did).is_some() { + return; + } + } + if let Some(t) = path_for_pass_by_value(cx, &inner_ty) { + cx.struct_span_lint(PASS_BY_VALUE, ty.span, |lint| { + lint.build(&format!("passing `{}` by reference", t)) + .span_suggestion( + ty.span, + "try passing by value", + t, + // Changing type of function argument + Applicability::MaybeIncorrect, + ) + .emit(); + }) + } + } + _ => {} + } + } +} + +fn path_for_pass_by_value(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> Option { + if let TyKind::Path(QPath::Resolved(_, path)) = &ty.kind { + match path.res { + Res::Def(_, def_id) if cx.tcx.has_attr(def_id, sym::rustc_pass_by_value) => { + let name = cx.tcx.item_name(def_id).to_ident_string(); + let path_segment = path.segments.last().unwrap(); + return Some(format!("{}{}", name, gen_args(cx, path_segment))); + } + Res::SelfTy(None, Some((did, _))) => { + if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() { + if cx.tcx.has_attr(adt.did, sym::rustc_pass_by_value) { + return Some(cx.tcx.def_path_str_with_substs(adt.did, substs)); + } + } + } + _ => (), + } + } + + None +} + +fn gen_args(cx: &LateContext<'_>, segment: &PathSegment<'_>) -> String { + if let Some(args) = &segment.args { + let params = args + .args + .iter() + .map(|arg| match arg { + GenericArg::Lifetime(lt) => lt.name.ident().to_string(), + GenericArg::Type(ty) => { + cx.tcx.sess.source_map().span_to_snippet(ty.span).unwrap_or_default() + } + GenericArg::Const(c) => { + cx.tcx.sess.source_map().span_to_snippet(c.span).unwrap_or_default() + } + GenericArg::Infer(_) => String::from("_"), + }) + .collect::>(); + + if !params.is_empty() { + return format!("<{}>", params.join(", ")); + } + } + + String::new() +} diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index ecc6da6da12a7..07e800f5b1a14 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -961,6 +961,7 @@ pub struct FreeRegionInfo { /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/ty.html #[derive(Copy, Clone)] #[rustc_diagnostic_item = "TyCtxt"] +#[cfg_attr(not(bootstrap), rustc_pass_by_value)] pub struct TyCtxt<'tcx> { gcx: &'tcx GlobalCtxt<'tcx>, } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index f1868459f2702..e1272c463a7af 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -464,6 +464,7 @@ impl<'a, 'tcx> HashStable> for TyS<'tcx> { } #[rustc_diagnostic_item = "Ty"] +#[cfg_attr(not(bootstrap), rustc_pass_by_value)] pub type Ty<'tcx> = &'tcx TyS<'tcx>; impl ty::EarlyBoundRegion { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index d7b00699491d4..e700a61ce48ab 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -114,6 +114,7 @@ impl CheckAttrVisitor<'_> { } sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target), sym::must_use => self.check_must_use(hir_id, &attr, span, target), + sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target), sym::rustc_const_unstable | sym::rustc_const_stable | sym::unstable @@ -1066,6 +1067,24 @@ impl CheckAttrVisitor<'_> { is_valid } + /// Warns against some misuses of `#[pass_by_value]` + fn check_pass_by_value(&self, attr: &Attribute, span: &Span, target: Target) -> bool { + match target { + Target::Struct | Target::Enum | Target::TyAlias => true, + _ => { + self.tcx + .sess + .struct_span_err( + attr.span, + "`pass_by_value` attribute should be applied to a struct, enum or type alias.", + ) + .span_label(*span, "is not a struct, enum or type alias") + .emit(); + false + } + } + } + /// Warns against some misuses of `#[must_use]` fn check_must_use( &self, diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index f99d5cfad0ab8..09d38d7580802 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1147,6 +1147,7 @@ symbols! { rustc_paren_sugar, rustc_partition_codegened, rustc_partition_reused, + rustc_pass_by_value, rustc_peek, rustc_peek_definite_init, rustc_peek_liveness, diff --git a/library/alloc/tests/lib.rs b/library/alloc/tests/lib.rs index eec24a5c3f7e6..7b8eeb90b5a80 100644 --- a/library/alloc/tests/lib.rs +++ b/library/alloc/tests/lib.rs @@ -38,6 +38,7 @@ #![feature(const_trait_impl)] #![feature(const_str_from_utf8)] #![feature(nonnull_slice_from_raw_parts)] +#![feature(panic_update_hook)] use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; diff --git a/library/alloc/tests/slice.rs b/library/alloc/tests/slice.rs index 18ea6a2141377..b93d7938bc9a5 100644 --- a/library/alloc/tests/slice.rs +++ b/library/alloc/tests/slice.rs @@ -1783,12 +1783,11 @@ thread_local!(static SILENCE_PANIC: Cell = Cell::new(false)); #[test] #[cfg_attr(target_os = "emscripten", ignore)] // no threads fn panic_safe() { - let prev = panic::take_hook(); - panic::set_hook(Box::new(move |info| { + panic::update_hook(move |prev, info| { if !SILENCE_PANIC.with(|s| s.get()) { prev(info); } - })); + }); let mut rng = thread_rng(); diff --git a/library/proc_macro/src/bridge/client.rs b/library/proc_macro/src/bridge/client.rs index 83a2ac6f0d4f1..9e9750eb8de40 100644 --- a/library/proc_macro/src/bridge/client.rs +++ b/library/proc_macro/src/bridge/client.rs @@ -310,8 +310,7 @@ impl Bridge<'_> { // NB. the server can't do this because it may use a different libstd. static HIDE_PANICS_DURING_EXPANSION: Once = Once::new(); HIDE_PANICS_DURING_EXPANSION.call_once(|| { - let prev = panic::take_hook(); - panic::set_hook(Box::new(move |info| { + panic::update_hook(move |prev, info| { let show = BridgeState::with(|state| match state { BridgeState::NotConnected => true, BridgeState::Connected(_) | BridgeState::InUse => force_show_panics, @@ -319,7 +318,7 @@ impl Bridge<'_> { if show { prev(info) } - })); + }); }); BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f)) diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index 69af598f91e1c..c5afca6d56a2d 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -30,6 +30,7 @@ #![feature(restricted_std)] #![feature(rustc_attrs)] #![feature(min_specialization)] +#![feature(panic_update_hook)] #![recursion_limit = "256"] #[unstable(feature = "proc_macro_internals", issue = "27812")] diff --git a/library/std/src/panic.rs b/library/std/src/panic.rs index c0605b2f4121c..02ecf2e3e822e 100644 --- a/library/std/src/panic.rs +++ b/library/std/src/panic.rs @@ -36,6 +36,9 @@ pub use core::panic::panic_2021; #[stable(feature = "panic_hooks", since = "1.10.0")] pub use crate::panicking::{set_hook, take_hook}; +#[unstable(feature = "panic_update_hook", issue = "92649")] +pub use crate::panicking::update_hook; + #[stable(feature = "panic_hooks", since = "1.10.0")] pub use core::panic::{Location, PanicInfo}; diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 87854fe4f2970..44f573297eed1 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -76,6 +76,12 @@ enum Hook { Custom(*mut (dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send)), } +impl Hook { + fn custom(f: impl Fn(&PanicInfo<'_>) + 'static + Sync + Send) -> Self { + Self::Custom(Box::into_raw(Box::new(f))) + } +} + static HOOK_LOCK: StaticRWLock = StaticRWLock::new(); static mut HOOK: Hook = Hook::Default; @@ -118,6 +124,11 @@ pub fn set_hook(hook: Box) + 'static + Sync + Send>) { panic!("cannot modify the panic hook from a panicking thread"); } + // SAFETY: + // + // - `HOOK` can only be modified while holding write access to `HOOK_LOCK`. + // - The argument of `Box::from_raw` is always a valid pointer that was created using + // `Box::into_raw`. unsafe { let guard = HOOK_LOCK.write(); let old_hook = HOOK; @@ -167,6 +178,11 @@ pub fn take_hook() -> Box) + 'static + Sync + Send> { panic!("cannot modify the panic hook from a panicking thread"); } + // SAFETY: + // + // - `HOOK` can only be modified while holding write access to `HOOK_LOCK`. + // - The argument of `Box::from_raw` is always a valid pointer that was created using + // `Box::into_raw`. unsafe { let guard = HOOK_LOCK.write(); let hook = HOOK; @@ -180,6 +196,69 @@ pub fn take_hook() -> Box) + 'static + Sync + Send> { } } +/// Atomic combination of [`take_hook`] and [`set_hook`]. Use this to replace the panic handler with +/// a new panic handler that does something and then executes the old handler. +/// +/// [`take_hook`]: ./fn.take_hook.html +/// [`set_hook`]: ./fn.set_hook.html +/// +/// # Panics +/// +/// Panics if called from a panicking thread. +/// +/// # Examples +/// +/// The following will print the custom message, and then the normal output of panic. +/// +/// ```should_panic +/// #![feature(panic_update_hook)] +/// use std::panic; +/// +/// // Equivalent to +/// // let prev = panic::take_hook(); +/// // panic::set_hook(move |info| { +/// // println!("..."); +/// // prev(info); +/// // ); +/// panic::update_hook(move |prev, info| { +/// println!("Print custom message and execute panic handler as usual"); +/// prev(info); +/// }); +/// +/// panic!("Custom and then normal"); +/// ``` +#[unstable(feature = "panic_update_hook", issue = "92649")] +pub fn update_hook(hook_fn: F) +where + F: Fn(&(dyn Fn(&PanicInfo<'_>) + Send + Sync + 'static), &PanicInfo<'_>) + + Sync + + Send + + 'static, +{ + if thread::panicking() { + panic!("cannot modify the panic hook from a panicking thread"); + } + + // SAFETY: + // + // - `HOOK` can only be modified while holding write access to `HOOK_LOCK`. + // - The argument of `Box::from_raw` is always a valid pointer that was created using + // `Box::into_raw`. + unsafe { + let guard = HOOK_LOCK.write(); + let old_hook = HOOK; + HOOK = Hook::Default; + + let prev = match old_hook { + Hook::Default => Box::new(default_hook), + Hook::Custom(ptr) => Box::from_raw(ptr), + }; + + HOOK = Hook::custom(move |info| hook_fn(&prev, info)); + drop(guard); + } +} + fn default_hook(info: &PanicInfo<'_>) { // If this is a double panic, make sure that we print a backtrace // for this panic. Otherwise only print it if logging is enabled. diff --git a/src/librustdoc/Cargo.toml b/src/librustdoc/Cargo.toml index 5025342c1d68c..b14ecaf0197b5 100644 --- a/src/librustdoc/Cargo.toml +++ b/src/librustdoc/Cargo.toml @@ -9,6 +9,7 @@ path = "lib.rs" [dependencies] arrayvec = { version = "0.7", default-features = false } askama = { version = "0.11", default-features = false } +atty = "0.2" pulldown-cmark = { version = "0.9", default-features = false } minifier = "0.0.41" rayon = "1.3.1" diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index a647a0fbfa55d..d854aa86b3afd 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -71,7 +71,8 @@ extern crate tikv_jemalloc_sys; use tikv_jemalloc_sys as jemalloc_sys; use std::default::Default; -use std::env; +use std::env::{self, VarError}; +use std::io; use std::process; use rustc_driver::{abort_on_err, describe_lints}; @@ -179,47 +180,20 @@ pub fn main() { } fn init_logging() { - use std::io; - - // FIXME remove these and use winapi 0.3 instead - // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs, rustc_driver/lib.rs - #[cfg(unix)] - fn stdout_isatty() -> bool { - extern crate libc; - unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 } - } - - #[cfg(windows)] - fn stdout_isatty() -> bool { - extern crate winapi; - use winapi::um::consoleapi::GetConsoleMode; - use winapi::um::processenv::GetStdHandle; - use winapi::um::winbase::STD_OUTPUT_HANDLE; - - unsafe { - let handle = GetStdHandle(STD_OUTPUT_HANDLE); - let mut out = 0; - GetConsoleMode(handle, &mut out) != 0 - } - } - - let color_logs = match std::env::var("RUSTDOC_LOG_COLOR") { - Ok(value) => match value.as_ref() { - "always" => true, - "never" => false, - "auto" => stdout_isatty(), - _ => early_error( - ErrorOutputType::default(), - &format!( - "invalid log color value '{}': expected one of always, never, or auto", - value - ), - ), - }, - Err(std::env::VarError::NotPresent) => stdout_isatty(), - Err(std::env::VarError::NotUnicode(_value)) => early_error( + let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() { + Ok("always") => true, + Ok("never") => false, + Ok("auto") | Err(VarError::NotPresent) => atty::is(atty::Stream::Stdout), + Ok(value) => early_error( + ErrorOutputType::default(), + &format!("invalid log color value '{}': expected one of always, never, or auto", value), + ), + Err(VarError::NotUnicode(value)) => early_error( ErrorOutputType::default(), - "non-Unicode log color value: expected one of always, never, or auto", + &format!( + "invalid log color value '{}': expected one of always, never, or auto", + value.to_string_lossy() + ), ), }; let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG"); diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index af62232e792ac..679baed3e3821 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -398,8 +398,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { } match tcx.type_of(did).kind() { ty::Adt(def, _) if def.is_enum() => { - if let Some(field) = - def.all_fields().find(|f| f.ident(tcx).name == variant_field_name) + if let Some(field) = def.all_fields().find(|f| f.name == variant_field_name) { Ok((ty_res, Some(ItemFragment(FragmentKind::VariantField, field.did)))) } else { @@ -770,11 +769,8 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { ty::Adt(def, _) if !def.is_enum() => def, _ => return None, }; - let field = def - .non_enum_variant() - .fields - .iter() - .find(|item| item.ident(tcx).name == item_name)?; + let field = + def.non_enum_variant().fields.iter().find(|item| item.name == item_name)?; Some((root_res, ItemFragment(FragmentKind::StructField, field.did))) } Res::Def(DefKind::Trait, did) => tcx @@ -903,7 +899,18 @@ fn traits_implemented_by<'a>( ty ); // Fast path: if this is a primitive simple `==` will work - let saw_impl = impl_type == ty; + // NOTE: the `match` is necessary; see #92662. + // this allows us to ignore generics because the user input + // may not include the generic placeholders + // e.g. this allows us to match Foo (user comment) with Foo (actual type) + let saw_impl = impl_type == ty + || match (impl_type.kind(), ty.kind()) { + (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => { + debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did, ty_def.did); + impl_def.did == ty_def.did + } + _ => false, + }; if saw_impl { Some(trait_) } else { None } }) diff --git a/src/test/rustdoc/intra-doc/extern-type.rs b/src/test/rustdoc/intra-doc/extern-type.rs index f37ae62dde1aa..ab088ab789d43 100644 --- a/src/test/rustdoc/intra-doc/extern-type.rs +++ b/src/test/rustdoc/intra-doc/extern-type.rs @@ -4,14 +4,34 @@ extern { pub type ExternType; } +pub trait T { + fn test(&self) {} +} + +pub trait G { + fn g(&self, n: N) {} +} + impl ExternType { - pub fn f(&self) { + pub fn f(&self) {} +} - } +impl T for ExternType { + fn test(&self) {} +} + +impl G for ExternType { + fn g(&self, n: usize) {} } // @has 'extern_type/foreigntype.ExternType.html' // @has 'extern_type/fn.links_to_extern_type.html' \ // 'href="foreigntype.ExternType.html#method.f"' +// @has 'extern_type/fn.links_to_extern_type.html' \ +// 'href="foreigntype.ExternType.html#method.test"' +// @has 'extern_type/fn.links_to_extern_type.html' \ +// 'href="foreigntype.ExternType.html#method.g"' /// See also [ExternType::f] +/// See also [ExternType::test] +/// See also [ExternType::g] pub fn links_to_extern_type() {} diff --git a/src/test/rustdoc/intra-doc/generic-trait-impl.rs b/src/test/rustdoc/intra-doc/generic-trait-impl.rs new file mode 100644 index 0000000000000..ba8595abfa959 --- /dev/null +++ b/src/test/rustdoc/intra-doc/generic-trait-impl.rs @@ -0,0 +1,20 @@ +#![deny(rustdoc::broken_intra_doc_links)] + +// Test intra-doc links on trait implementations with generics +// regression test for issue #92662 + +use std::marker::PhantomData; + +pub trait Bar { + fn bar(&self); +} + +pub struct Foo(PhantomData); + +impl Bar for Foo { + fn bar(&self) {} +} + +// @has generic_trait_impl/fn.main.html '//a[@href="struct.Foo.html#method.bar"]' 'Foo::bar' +/// link to [`Foo::bar`] +pub fn main() {} diff --git a/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref.stderr b/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref.stderr deleted file mode 100644 index 2751a37f7419d..0000000000000 --- a/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref.stderr +++ /dev/null @@ -1,80 +0,0 @@ -error: passing `Ty<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:13:13 - | -LL | ty_ref: &Ty<'_>, - | ^^^^^^^ help: try passing by value: `Ty<'_>` - | -note: the lint level is defined here - --> $DIR/pass_ty_by_ref.rs:4:9 - | -LL | #![deny(rustc::ty_pass_by_reference)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: passing `TyCtxt<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:15:18 - | -LL | ty_ctxt_ref: &TyCtxt<'_>, - | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` - -error: passing `Ty<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:19:28 - | -LL | fn ty_multi_ref(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>) {} - | ^^^^^^^ help: try passing by value: `Ty<'_>` - -error: passing `TyCtxt<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:19:55 - | -LL | fn ty_multi_ref(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>) {} - | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` - -error: passing `Ty<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:26:17 - | -LL | ty_ref: &Ty<'_>, - | ^^^^^^^ help: try passing by value: `Ty<'_>` - -error: passing `TyCtxt<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:28:22 - | -LL | ty_ctxt_ref: &TyCtxt<'_>, - | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` - -error: passing `Ty<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:31:41 - | -LL | fn ty_multi_ref_in_trait(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>); - | ^^^^^^^ help: try passing by value: `Ty<'_>` - -error: passing `TyCtxt<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:31:68 - | -LL | fn ty_multi_ref_in_trait(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>); - | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` - -error: passing `Ty<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:53:17 - | -LL | ty_ref: &Ty<'_>, - | ^^^^^^^ help: try passing by value: `Ty<'_>` - -error: passing `TyCtxt<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:55:22 - | -LL | ty_ctxt_ref: &TyCtxt<'_>, - | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` - -error: passing `Ty<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:59:38 - | -LL | fn ty_multi_ref_assoc(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>) {} - | ^^^^^^^ help: try passing by value: `Ty<'_>` - -error: passing `TyCtxt<'_>` by reference - --> $DIR/pass_ty_by_ref.rs:59:65 - | -LL | fn ty_multi_ref_assoc(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>) {} - | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` - -error: aborting due to 12 previous errors - diff --git a/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref_self.stderr b/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref_self.stderr deleted file mode 100644 index 15a06e721ddcb..0000000000000 --- a/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref_self.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error: passing `TyCtxt<'tcx>` by reference - --> $DIR/pass_ty_by_ref_self.rs:18:15 - | -LL | fn by_ref(&self) {} - | ^^^^^ help: try passing by value: `TyCtxt<'tcx>` - | -note: the lint level is defined here - --> $DIR/pass_ty_by_ref_self.rs:8:9 - | -LL | #![deny(rustc::ty_pass_by_reference)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: passing `Ty<'tcx>` by reference - --> $DIR/pass_ty_by_ref_self.rs:31:21 - | -LL | fn by_ref(self: &Ty<'tcx>) {} - | ^^^^^^^^^ help: try passing by value: `Ty<'tcx>` - -error: aborting due to 2 previous errors - diff --git a/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref.rs b/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value.rs similarity index 55% rename from src/test/ui-fulldeps/internal-lints/pass_ty_by_ref.rs rename to src/test/ui-fulldeps/internal-lints/rustc_pass_by_value.rs index e0fdbaeac3069..402c41f376602 100644 --- a/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref.rs +++ b/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value.rs @@ -1,7 +1,8 @@ // compile-flags: -Z unstable-options +#![feature(rustc_attrs)] #![feature(rustc_private)] -#![deny(rustc::ty_pass_by_reference)] +#![deny(rustc::pass_by_value)] #![allow(unused)] extern crate rustc_middle; @@ -61,4 +62,57 @@ impl Foo { //~^^ ERROR passing `TyCtxt<'_>` by reference } +#[rustc_pass_by_value] +enum CustomEnum { + A, + B, +} + +impl CustomEnum { + fn test( + value: CustomEnum, + reference: &CustomEnum, //~ ERROR passing `CustomEnum` by reference + ) { + } +} + +#[rustc_pass_by_value] +struct CustomStruct { + s: u8, +} + +#[rustc_pass_by_value] +type CustomAlias<'a> = &'a CustomStruct; //~ ERROR passing `CustomStruct` by reference + +impl CustomStruct { + fn test( + value: CustomStruct, + reference: &CustomStruct, //~ ERROR passing `CustomStruct` by reference + ) { + } + + fn test_alias( + value: CustomAlias, + reference: &CustomAlias, //~ ERROR passing `CustomAlias<>` by reference + ) { + } +} + +#[rustc_pass_by_value] +struct WithParameters { + slice: [T; N], + m: M, +} + +impl WithParameters { + fn test<'a>( + value: WithParameters, + reference: &'a WithParameters, //~ ERROR passing `WithParameters` by reference + reference_with_m: &WithParameters, //~ ERROR passing `WithParameters` by reference + ) -> &'a WithParameters { + //~^ ERROR passing `WithParameters` by reference + reference as &WithParameters<_, 1> //~ ERROR passing `WithParameters<_, 1>` by reference + } +} + fn main() {} diff --git a/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value.stderr b/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value.stderr new file mode 100644 index 0000000000000..7f6e57b38f38d --- /dev/null +++ b/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value.stderr @@ -0,0 +1,128 @@ +error: passing `Ty<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:14:13 + | +LL | ty_ref: &Ty<'_>, + | ^^^^^^^ help: try passing by value: `Ty<'_>` + | +note: the lint level is defined here + --> $DIR/rustc_pass_by_value.rs:5:9 + | +LL | #![deny(rustc::pass_by_value)] + | ^^^^^^^^^^^^^^^^^^^^ + +error: passing `TyCtxt<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:16:18 + | +LL | ty_ctxt_ref: &TyCtxt<'_>, + | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` + +error: passing `Ty<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:20:28 + | +LL | fn ty_multi_ref(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>) {} + | ^^^^^^^ help: try passing by value: `Ty<'_>` + +error: passing `TyCtxt<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:20:55 + | +LL | fn ty_multi_ref(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>) {} + | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` + +error: passing `Ty<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:27:17 + | +LL | ty_ref: &Ty<'_>, + | ^^^^^^^ help: try passing by value: `Ty<'_>` + +error: passing `TyCtxt<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:29:22 + | +LL | ty_ctxt_ref: &TyCtxt<'_>, + | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` + +error: passing `Ty<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:32:41 + | +LL | fn ty_multi_ref_in_trait(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>); + | ^^^^^^^ help: try passing by value: `Ty<'_>` + +error: passing `TyCtxt<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:32:68 + | +LL | fn ty_multi_ref_in_trait(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>); + | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` + +error: passing `Ty<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:54:17 + | +LL | ty_ref: &Ty<'_>, + | ^^^^^^^ help: try passing by value: `Ty<'_>` + +error: passing `TyCtxt<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:56:22 + | +LL | ty_ctxt_ref: &TyCtxt<'_>, + | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` + +error: passing `Ty<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:60:38 + | +LL | fn ty_multi_ref_assoc(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>) {} + | ^^^^^^^ help: try passing by value: `Ty<'_>` + +error: passing `TyCtxt<'_>` by reference + --> $DIR/rustc_pass_by_value.rs:60:65 + | +LL | fn ty_multi_ref_assoc(ty_multi: &&Ty<'_>, ty_ctxt_multi: &&&&TyCtxt<'_>) {} + | ^^^^^^^^^^^ help: try passing by value: `TyCtxt<'_>` + +error: passing `CustomEnum` by reference + --> $DIR/rustc_pass_by_value.rs:74:20 + | +LL | reference: &CustomEnum, + | ^^^^^^^^^^^ help: try passing by value: `CustomEnum` + +error: passing `CustomStruct` by reference + --> $DIR/rustc_pass_by_value.rs:85:24 + | +LL | type CustomAlias<'a> = &'a CustomStruct; + | ^^^^^^^^^^^^^^^^ help: try passing by value: `CustomStruct` + +error: passing `CustomStruct` by reference + --> $DIR/rustc_pass_by_value.rs:90:20 + | +LL | reference: &CustomStruct, + | ^^^^^^^^^^^^^ help: try passing by value: `CustomStruct` + +error: passing `CustomAlias<>` by reference + --> $DIR/rustc_pass_by_value.rs:96:20 + | +LL | reference: &CustomAlias, + | ^^^^^^^^^^^^ help: try passing by value: `CustomAlias<>` + +error: passing `WithParameters` by reference + --> $DIR/rustc_pass_by_value.rs:110:20 + | +LL | reference: &'a WithParameters, + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try passing by value: `WithParameters` + +error: passing `WithParameters` by reference + --> $DIR/rustc_pass_by_value.rs:111:27 + | +LL | reference_with_m: &WithParameters, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try passing by value: `WithParameters` + +error: passing `WithParameters` by reference + --> $DIR/rustc_pass_by_value.rs:112:10 + | +LL | ) -> &'a WithParameters { + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: try passing by value: `WithParameters` + +error: passing `WithParameters<_, 1>` by reference + --> $DIR/rustc_pass_by_value.rs:114:22 + | +LL | reference as &WithParameters<_, 1> + | ^^^^^^^^^^^^^^^^^^^^^ help: try passing by value: `WithParameters<_, 1>` + +error: aborting due to 20 previous errors + diff --git a/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref_self.rs b/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value_self.rs similarity index 56% rename from src/test/ui-fulldeps/internal-lints/pass_ty_by_ref_self.rs rename to src/test/ui-fulldeps/internal-lints/rustc_pass_by_value_self.rs index 48b140d91744c..2868517774d46 100644 --- a/src/test/ui-fulldeps/internal-lints/pass_ty_by_ref_self.rs +++ b/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value_self.rs @@ -5,10 +5,10 @@ // Considering that all other `internal-lints` are tested here // this seems like the cleaner solution though. #![feature(rustc_attrs)] -#![deny(rustc::ty_pass_by_reference)] +#![deny(rustc::pass_by_value)] #![allow(unused)] -#[rustc_diagnostic_item = "TyCtxt"] +#[rustc_pass_by_value] struct TyCtxt<'tcx> { inner: &'tcx (), } @@ -18,12 +18,11 @@ impl<'tcx> TyCtxt<'tcx> { fn by_ref(&self) {} //~ ERROR passing `TyCtxt<'tcx>` by reference } - struct TyS<'tcx> { inner: &'tcx (), } -#[rustc_diagnostic_item = "Ty"] +#[rustc_pass_by_value] type Ty<'tcx> = &'tcx TyS<'tcx>; impl<'tcx> TyS<'tcx> { @@ -31,4 +30,25 @@ impl<'tcx> TyS<'tcx> { fn by_ref(self: &Ty<'tcx>) {} //~ ERROR passing `Ty<'tcx>` by reference } +#[rustc_pass_by_value] +struct Foo; + +impl Foo { + fn with_ref(&self) {} //~ ERROR passing `Foo` by reference +} + +#[rustc_pass_by_value] +struct WithParameters { + slice: [T; N], + m: M, +} + +impl WithParameters { + fn with_ref(&self) {} //~ ERROR passing `WithParameters` by reference +} + +impl WithParameters { + fn with_ref(&self) {} //~ ERROR passing `WithParameters` by reference +} + fn main() {} diff --git a/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value_self.stderr b/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value_self.stderr new file mode 100644 index 0000000000000..54a7cf7cab757 --- /dev/null +++ b/src/test/ui-fulldeps/internal-lints/rustc_pass_by_value_self.stderr @@ -0,0 +1,38 @@ +error: passing `TyCtxt<'tcx>` by reference + --> $DIR/rustc_pass_by_value_self.rs:18:15 + | +LL | fn by_ref(&self) {} + | ^^^^^ help: try passing by value: `TyCtxt<'tcx>` + | +note: the lint level is defined here + --> $DIR/rustc_pass_by_value_self.rs:8:9 + | +LL | #![deny(rustc::pass_by_value)] + | ^^^^^^^^^^^^^^^^^^^^ + +error: passing `Ty<'tcx>` by reference + --> $DIR/rustc_pass_by_value_self.rs:30:21 + | +LL | fn by_ref(self: &Ty<'tcx>) {} + | ^^^^^^^^^ help: try passing by value: `Ty<'tcx>` + +error: passing `Foo` by reference + --> $DIR/rustc_pass_by_value_self.rs:37:17 + | +LL | fn with_ref(&self) {} + | ^^^^^ help: try passing by value: `Foo` + +error: passing `WithParameters` by reference + --> $DIR/rustc_pass_by_value_self.rs:47:17 + | +LL | fn with_ref(&self) {} + | ^^^^^ help: try passing by value: `WithParameters` + +error: passing `WithParameters` by reference + --> $DIR/rustc_pass_by_value_self.rs:51:17 + | +LL | fn with_ref(&self) {} + | ^^^^^ help: try passing by value: `WithParameters` + +error: aborting due to 5 previous errors + diff --git a/src/test/ui/panics/panic-handler-chain-update-hook.rs b/src/test/ui/panics/panic-handler-chain-update-hook.rs new file mode 100644 index 0000000000000..4dd08ba4ad4e2 --- /dev/null +++ b/src/test/ui/panics/panic-handler-chain-update-hook.rs @@ -0,0 +1,36 @@ +// run-pass +// needs-unwind +#![allow(stable_features)] + +// ignore-emscripten no threads support + +#![feature(std_panic)] +#![feature(panic_update_hook)] + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::panic; +use std::thread; + +static A: AtomicUsize = AtomicUsize::new(0); +static B: AtomicUsize = AtomicUsize::new(0); +static C: AtomicUsize = AtomicUsize::new(0); + +fn main() { + panic::set_hook(Box::new(|_| { A.fetch_add(1, Ordering::SeqCst); })); + panic::update_hook(|prev, info| { + B.fetch_add(1, Ordering::SeqCst); + prev(info); + }); + panic::update_hook(|prev, info| { + C.fetch_add(1, Ordering::SeqCst); + prev(info); + }); + + let _ = thread::spawn(|| { + panic!(); + }).join(); + + assert_eq!(1, A.load(Ordering::SeqCst)); + assert_eq!(1, B.load(Ordering::SeqCst)); + assert_eq!(1, C.load(Ordering::SeqCst)); +}