diff --git a/Cargo.lock b/Cargo.lock index 9d91dcde9b413..8626cd6124456 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3561,6 +3561,7 @@ dependencies = [ "rustc_serialize", "rustc_span", "smallvec", + "thin-vec", "tracing", ] @@ -3581,6 +3582,7 @@ dependencies = [ "rustc_span", "rustc_target", "smallvec", + "thin-vec", "tracing", ] @@ -3600,6 +3602,7 @@ dependencies = [ "rustc_session", "rustc_span", "rustc_target", + "thin-vec", "tracing", ] @@ -3609,6 +3612,7 @@ version = "0.0.0" dependencies = [ "rustc_ast", "rustc_span", + "thin-vec", ] [[package]] @@ -3675,6 +3679,7 @@ dependencies = [ "rustc_span", "rustc_target", "smallvec", + "thin-vec", "tracing", ] @@ -3799,6 +3804,7 @@ dependencies = [ "stable_deref_trait", "stacker", "tempfile", + "thin-vec", "tracing", "winapi", ] @@ -3895,6 +3901,7 @@ dependencies = [ "rustc_session", "rustc_span", "smallvec", + "thin-vec", "tracing", ] @@ -3959,6 +3966,7 @@ dependencies = [ "rustc_serialize", "rustc_session", "rustc_span", + "thin-vec", "tracing", ] @@ -4179,6 +4187,7 @@ dependencies = [ "rustc_target", "rustc_type_ir", "smallvec", + "thin-vec", "tracing", ] @@ -4277,6 +4286,7 @@ dependencies = [ "rustc_macros", "rustc_session", "rustc_span", + "thin-vec", "tracing", "unicode-normalization", "unicode-width", @@ -4363,6 +4373,7 @@ dependencies = [ "rustc_session", "rustc_span", "rustc_target", + "thin-vec", "tracing", ] @@ -4385,6 +4396,7 @@ dependencies = [ "rustc_span", "rustc_target", "smallvec", + "thin-vec", "tracing", ] @@ -4409,6 +4421,7 @@ dependencies = [ "rustc_session", "rustc_span", "smallvec", + "thin-vec", "tracing", ] @@ -4438,6 +4451,7 @@ dependencies = [ "indexmap", "rustc_macros", "smallvec", + "thin-vec", ] [[package]] @@ -4646,6 +4660,7 @@ dependencies = [ "rustc_ty_utils", "rustc_type_ir", "smallvec", + "thin-vec", "tracing", ] @@ -5250,6 +5265,12 @@ version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" +[[package]] +name = "thin-vec" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "104c2cb3180b6fb6d5b2278768e9b88b578d32ba751ea6e8d026688a40d7ed87" + [[package]] name = "thiserror" version = "1.0.30" diff --git a/compiler/rustc_ast/Cargo.toml b/compiler/rustc_ast/Cargo.toml index 9822e9864e210..c24180bacfc1b 100644 --- a/compiler/rustc_ast/Cargo.toml +++ b/compiler/rustc_ast/Cargo.toml @@ -7,12 +7,13 @@ edition = "2021" doctest = false [dependencies] -rustc_serialize = { path = "../rustc_serialize" } -tracing = "0.1" -rustc_span = { path = "../rustc_span" } +bitflags = "1.2.1" rustc_data_structures = { path = "../rustc_data_structures" } rustc_index = { path = "../rustc_index" } rustc_lexer = { path = "../rustc_lexer" } rustc_macros = { path = "../rustc_macros" } +rustc_serialize = { path = "../rustc_serialize" } +rustc_span = { path = "../rustc_span" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } -bitflags = "1.2.1" +thin-vec = "0.2.8" +tracing = "0.1" diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index fb521073a428d..5c3f77fd62028 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -25,21 +25,19 @@ pub use UnsafeSource::*; use crate::ptr::P; use crate::token::{self, CommentKind, Delimiter}; use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream}; - use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::sync::Lrc; -use rustc_data_structures::thin_vec::ThinVec; use rustc_macros::HashStable_Generic; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_span::source_map::{respan, Spanned}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; - use std::cmp::Ordering; use std::convert::TryFrom; use std::fmt; use std::mem; +use thin_vec::{thin_vec, ThinVec}; /// A "Label" is an identifier of some point in sources, /// e.g. in the following code: @@ -93,7 +91,7 @@ pub struct Path { pub span: Span, /// The segments in the path: the things separated by `::`. /// Global paths begin with `kw::PathRoot`. - pub segments: Vec, + pub segments: ThinVec, pub tokens: Option, } @@ -117,7 +115,7 @@ impl Path { // Convert a span and an identifier to the corresponding // one-segment path. pub fn from_ident(ident: Ident) -> Path { - Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None } + Path { segments: thin_vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None } } pub fn is_global(&self) -> bool { @@ -256,7 +254,7 @@ pub struct ParenthesizedArgs { pub span: Span, /// `(A, B)` - pub inputs: Vec>, + pub inputs: ThinVec>, /// ```text /// Foo(A, B) -> C @@ -416,7 +414,7 @@ impl GenericParam { /// a function, enum, trait, etc. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Generics { - pub params: Vec, + pub params: ThinVec, pub where_clause: WhereClause, pub span: Span, } @@ -425,10 +423,10 @@ impl Default for Generics { /// Creates an instance of `Generics`. fn default() -> Generics { Generics { - params: Vec::new(), + params: ThinVec::new(), where_clause: WhereClause { has_where_token: false, - predicates: Vec::new(), + predicates: ThinVec::new(), span: DUMMY_SP, }, span: DUMMY_SP, @@ -443,7 +441,7 @@ pub struct WhereClause { /// if we parsed no predicates (e.g. `struct Foo where {}`). /// This allows us to pretty-print accurately. pub has_where_token: bool, - pub predicates: Vec, + pub predicates: ThinVec, pub span: Span, } @@ -475,7 +473,7 @@ impl WherePredicate { pub struct WhereBoundPredicate { pub span: Span, /// Any generics from a `for` binding. - pub bound_generic_params: Vec, + pub bound_generic_params: ThinVec, /// The type being bounded. pub bounded_ty: P, /// Trait and lifetime bounds (`Clone + Send + 'static`). @@ -548,7 +546,7 @@ pub enum MetaItemKind { /// List meta item. /// /// E.g., `derive(..)` as in `#[derive(..)]`. - List(Vec), + List(ThinVec), /// Name value meta item. /// /// E.g., `feature = "foo"` as in `#[feature = "foo"]`. @@ -611,7 +609,7 @@ impl Pat { // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)` // assuming `T0` to `Tn` are all syntactically valid as types. PatKind::Tuple(pats) => { - let mut tys = Vec::with_capacity(pats.len()); + let mut tys = ThinVec::with_capacity(pats.len()); // FIXME(#48994) - could just be collected into an Option for pat in pats { tys.push(pat.to_ty()?); @@ -722,11 +720,11 @@ pub enum PatKind { Struct(Option, Path, Vec, /* recovered */ bool), /// A tuple struct/variant pattern (`Variant(x, y, .., z)`). - TupleStruct(Option, Path, Vec>), + TupleStruct(Option, Path, ThinVec>), /// An or-pattern `A | B | C`. /// Invariant: `pats.len() >= 2`. - Or(Vec>), + Or(ThinVec>), /// A possibly qualified path pattern. /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants @@ -735,7 +733,7 @@ pub enum PatKind { Path(Option, Path), /// A tuple pattern (`(a, b)`). - Tuple(Vec>), + Tuple(ThinVec>), /// A `box` pattern. Box(P), @@ -750,7 +748,7 @@ pub enum PatKind { Range(Option>, Option>, Spanned), /// A slice pattern `[a, b, c]`. - Slice(Vec>), + Slice(ThinVec>), /// A rest pattern `..`. /// @@ -1156,7 +1154,7 @@ impl Expr { pub fn to_bound(&self) -> Option { match &self.kind { ExprKind::Path(None, path) => Some(GenericBound::Trait( - PolyTraitRef::new(Vec::new(), path.clone(), self.span), + PolyTraitRef::new(ThinVec::new(), path.clone(), self.span), TraitBoundModifier::None, )), _ => None, @@ -1191,7 +1189,7 @@ impl Expr { ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?, ExprKind::Tup(exprs) => { - let tys = exprs.iter().map(|expr| expr.to_ty()).collect::>>()?; + let tys = exprs.iter().map(|expr| expr.to_ty()).collect::>>()?; TyKind::Tup(tys) } @@ -1332,7 +1330,7 @@ pub enum ExprKind { /// and the second field is the list of arguments. /// This also represents calling the constructor of /// tuple-like ADTs such as tuple structs and enum variants. - Call(P, Vec>), + Call(P, ThinVec>), /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`) /// /// The `PathSegment` represents the method name and its generic arguments @@ -1343,9 +1341,9 @@ pub enum ExprKind { /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, x, [a, b, c, d])`. /// This `Span` is the span of the function, without the dot and receiver /// (e.g. `foo(a, b)` in `x.foo(a, b)` - MethodCall(PathSegment, P, Vec>, Span), + MethodCall(PathSegment, P, ThinVec>, Span), /// A tuple (e.g., `(a, b, c, d)`). - Tup(Vec>), + Tup(ThinVec>), /// A binary operation (e.g., `a + b`, `a * b`). Binary(BinOp, P, P), /// A unary operation (e.g., `!x`, `*x`). @@ -1533,7 +1531,7 @@ pub enum ClosureBinder { /// for<'a, 'b> |_: &'a (), _: &'b ()| { ... } /// ^^^^^^ -- this /// ``` - generic_params: P<[GenericParam]>, + generic_params: ThinVec, }, } @@ -1994,7 +1992,7 @@ impl Ty { pub struct BareFnTy { pub unsafety: Unsafe, pub ext: Extern, - pub generic_params: Vec, + pub generic_params: ThinVec, pub decl: P, /// Span of the `fn(...) -> ...` part. pub decl_span: Span, @@ -2016,7 +2014,7 @@ pub enum TyKind { /// The never type (`!`). Never, /// A tuple (`(A, B, C, D,...)`). - Tup(Vec>), + Tup(ThinVec>), /// A path (`module::module::...::Type`), optionally /// "qualified", e.g., ` as SomeTrait>::SomeType`. /// @@ -2297,7 +2295,7 @@ impl Param { /// which contains metadata about function safety, asyncness, constness and ABI. #[derive(Clone, Encodable, Decodable, Debug)] pub struct FnDecl { - pub inputs: Vec, + pub inputs: ThinVec, pub output: FnRetTy, } @@ -2437,7 +2435,7 @@ pub struct ForeignMod { /// semantically by Rust. pub unsafety: Unsafe, pub abi: Option, - pub items: Vec>, + pub items: ThinVec>, } #[derive(Clone, Encodable, Decodable, Debug)] @@ -2475,7 +2473,7 @@ pub enum UseTreeKind { /// namespace. Simple(Option, NodeId, NodeId), /// `use prefix::{...}` - Nested(Vec<(UseTree, NodeId)>), + Nested(ThinVec<(UseTree, NodeId)>), /// `use prefix::*` Glob, } @@ -2580,7 +2578,7 @@ pub struct TraitRef { #[derive(Clone, Encodable, Decodable, Debug)] pub struct PolyTraitRef { /// The `'a` in `for<'a> Foo<&'a T>`. - pub bound_generic_params: Vec, + pub bound_generic_params: ThinVec, /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`. pub trait_ref: TraitRef, @@ -2589,7 +2587,7 @@ pub struct PolyTraitRef { } impl PolyTraitRef { - pub fn new(generic_params: Vec, path: Path, span: Span) -> Self { + pub fn new(generic_params: ThinVec, path: Path, span: Span) -> Self { PolyTraitRef { bound_generic_params: generic_params, trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID }, @@ -2639,11 +2637,11 @@ pub enum VariantData { /// Struct variant. /// /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`. - Struct(Vec, bool), + Struct(ThinVec, bool), /// Tuple variant. /// /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`. - Tuple(Vec, NodeId), + Tuple(ThinVec, NodeId), /// Unit variant. /// /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`. @@ -2755,7 +2753,7 @@ pub struct Trait { pub is_auto: IsAuto, pub generics: Generics, pub bounds: GenericBounds, - pub items: Vec>, + pub items: ThinVec>, } /// The location of a where clause on a `TyAlias` (`Span`) and whether there was @@ -2803,7 +2801,7 @@ pub struct Impl { /// The trait being implemented, if any. pub of_trait: Option, pub self_ty: P, - pub items: Vec>, + pub items: ThinVec>, } #[derive(Clone, Encodable, Decodable, Debug)] @@ -3042,24 +3040,24 @@ mod size_asserts { static_assert_size!(AssocItemKind, 32); static_assert_size!(Attribute, 32); static_assert_size!(Block, 48); - static_assert_size!(Expr, 104); - static_assert_size!(ExprKind, 72); - static_assert_size!(Fn, 192); + static_assert_size!(Expr, 96); + static_assert_size!(ExprKind, 64); + static_assert_size!(Fn, 160); static_assert_size!(ForeignItem, 96); static_assert_size!(ForeignItemKind, 24); - static_assert_size!(GenericBound, 88); - static_assert_size!(Generics, 72); - static_assert_size!(Impl, 200); - static_assert_size!(Item, 184); - static_assert_size!(ItemKind, 112); + static_assert_size!(GenericBound, 56); + static_assert_size!(Generics, 40); + static_assert_size!(Impl, 136); + static_assert_size!(Item, 144); + static_assert_size!(ItemKind, 72); static_assert_size!(Lit, 48); static_assert_size!(LitKind, 24); - static_assert_size!(Pat, 120); - static_assert_size!(PatKind, 96); - static_assert_size!(Path, 40); + static_assert_size!(Pat, 104); + static_assert_size!(PatKind, 80); + static_assert_size!(Path, 24); static_assert_size!(PathSegment, 24); static_assert_size!(Stmt, 32); static_assert_size!(StmtKind, 16); - static_assert_size!(Ty, 96); - static_assert_size!(TyKind, 72); + static_assert_size!(Ty, 80); + static_assert_size!(TyKind, 56); } diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 5b72ec2b6015c..e8f74b3ae6525 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -11,13 +11,12 @@ use crate::tokenstream::{AttrAnnotatedTokenStream, AttrAnnotatedTokenTree}; use crate::tokenstream::{DelimSpan, Spacing, TokenTree}; use crate::tokenstream::{LazyTokenStream, TokenStream}; use crate::util::comments; - use rustc_index::bit_set::GrowableBitSet; use rustc_span::source_map::BytePos; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; - use std::iter; +use thin_vec::{thin_vec, ThinVec}; pub struct MarkedAttrs(GrowableBitSet); @@ -144,7 +143,7 @@ impl Attribute { } } - pub fn meta_item_list(&self) -> Option> { + pub fn meta_item_list(&self) -> Option> { match self.kind { AttrKind::Normal(ref normal) => match normal.item.meta_kind() { Some(MetaItemKind::List(list)) => Some(list), @@ -325,7 +324,7 @@ pub fn mk_name_value_item(ident: Ident, lit_kind: LitKind, lit_span: Span) -> Me MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) } } -pub fn mk_list_item(ident: Ident, items: Vec) -> MetaItem { +pub fn mk_list_item(ident: Ident, items: ThinVec) -> MetaItem { MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::List(items) } } @@ -422,12 +421,12 @@ impl MetaItem { tokens.peek() { tokens.next(); - vec![PathSegment::from_ident(Ident::new(name, span))] + thin_vec![PathSegment::from_ident(Ident::new(name, span))] } else { break 'arm Path::from_ident(Ident::new(name, span)); } } else { - vec![PathSegment::path_root(span)] + thin_vec![PathSegment::path_root(span)] }; loop { if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) = @@ -536,7 +535,7 @@ impl MetaItemKind { fn list_from_tokens(tokens: TokenStream) -> Option { let mut tokens = tokens.into_trees().peekable(); - let mut result = Vec::new(); + let mut result = ThinVec::new(); while tokens.peek().is_some() { let item = NestedMetaItem::from_tokens(&mut tokens)?; result.push(item); diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index 458d1156ec251..247fc42da2d4b 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -17,10 +17,10 @@ use rustc_data_structures::sync::Lrc; use rustc_span::source_map::Spanned; use rustc_span::symbol::Ident; use rustc_span::Span; - use smallvec::{smallvec, Array, SmallVec}; use std::ops::DerefMut; use std::{panic, ptr}; +use thin_vec::ThinVec; pub trait ExpectOne { fn expect_one(self, err: &'static str) -> A::Item; @@ -325,6 +325,17 @@ where } } +// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. +#[inline] +pub fn visit_thin_vec(elems: &mut ThinVec, mut visit_elem: F) +where + F: FnMut(&mut T), +{ + for elem in elems { + visit_elem(elem); + } +} + // No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. #[inline] pub fn visit_opt(opt: &mut Option, mut visit_elem: F) @@ -348,6 +359,11 @@ pub fn visit_exprs(exprs: &mut Vec>, vis: &mut T) { exprs.flat_map_in_place(|expr| vis.filter_map_expr(expr)) } +// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. +pub fn visit_thin_exprs(exprs: &mut ThinVec>, vis: &mut T) { + exprs.flat_map_in_place(|expr| vis.filter_map_expr(expr)) +} + // No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. pub fn visit_bounds(bounds: &mut GenericBounds, vis: &mut T) { visit_vec(bounds, |bound| vis.visit_param_bound(bound)); @@ -464,7 +480,7 @@ pub fn noop_visit_ty(ty: &mut P, vis: &mut T) { vis.visit_fn_decl(decl); vis.visit_span(decl_span); } - TyKind::Tup(tys) => visit_vec(tys, |ty| vis.visit_ty(ty)), + TyKind::Tup(tys) => visit_thin_vec(tys, |ty| vis.visit_ty(ty)), TyKind::Paren(ty) => vis.visit_ty(ty), TyKind::Path(qself, path) => { vis.visit_qself(qself); @@ -562,7 +578,7 @@ pub fn noop_visit_parenthesized_parameter_data( vis: &mut T, ) { let ParenthesizedArgs { inputs, output, span, .. } = args; - visit_vec(inputs, |input| vis.visit_ty(input)); + visit_thin_vec(inputs, |input| vis.visit_ty(input)); noop_visit_fn_ret_ty(output, vis); vis.visit_span(span); } @@ -625,7 +641,7 @@ pub fn noop_visit_meta_item(mi: &mut MetaItem, vis: &mut T) { let MetaItem { path: _, kind, span } = mi; match kind { MetaItemKind::Word => {} - MetaItemKind::List(mis) => visit_vec(mis, |mi| vis.visit_meta_list_item(mi)), + MetaItemKind::List(mis) => visit_thin_vec(mis, |mi| vis.visit_meta_list_item(mi)), MetaItemKind::NameValue(_s) => {} } vis.visit_span(span); @@ -829,9 +845,7 @@ pub fn noop_visit_closure_binder(binder: &mut ClosureBinder, vis: match binder { ClosureBinder::NotPresent => {} ClosureBinder::For { span: _, generic_params } => { - let mut vec = std::mem::take(generic_params).into_vec(); - vec.flat_map_in_place(|param| vis.flat_map_generic_param(param)); - *generic_params = P::from_vec(vec); + generic_params.flat_map_in_place(|param| vis.flat_map_generic_param(param)); } } } @@ -909,7 +923,7 @@ pub fn noop_visit_generics(generics: &mut Generics, vis: &mut T) pub fn noop_visit_where_clause(wc: &mut WhereClause, vis: &mut T) { let WhereClause { has_where_token: _, predicates, span } = wc; - visit_vec(predicates, |predicate| vis.visit_where_predicate(predicate)); + visit_thin_vec(predicates, |predicate| vis.visit_where_predicate(predicate)); vis.visit_span(span); } @@ -1217,7 +1231,7 @@ pub fn noop_visit_pat(pat: &mut P, vis: &mut T) { PatKind::TupleStruct(qself, path, elems) => { vis.visit_qself(qself); vis.visit_path(path); - visit_vec(elems, |elem| vis.visit_pat(elem)); + visit_thin_vec(elems, |elem| vis.visit_pat(elem)); } PatKind::Path(qself, path) => { vis.visit_qself(qself); @@ -1236,7 +1250,7 @@ pub fn noop_visit_pat(pat: &mut P, vis: &mut T) { vis.visit_span(span); } PatKind::Tuple(elems) | PatKind::Slice(elems) | PatKind::Or(elems) => { - visit_vec(elems, |elem| vis.visit_pat(elem)) + visit_thin_vec(elems, |elem| vis.visit_pat(elem)) } PatKind::Paren(inner) => vis.visit_pat(inner), PatKind::MacCall(mac) => vis.visit_mac_call(mac), @@ -1292,17 +1306,17 @@ pub fn noop_visit_expr( vis.visit_expr(expr); vis.visit_anon_const(count); } - ExprKind::Tup(exprs) => visit_exprs(exprs, vis), + ExprKind::Tup(exprs) => visit_thin_exprs(exprs, vis), ExprKind::Call(f, args) => { vis.visit_expr(f); - visit_exprs(args, vis); + visit_thin_exprs(args, vis); } ExprKind::MethodCall(PathSegment { ident, id, args }, receiver, exprs, span) => { vis.visit_ident(ident); vis.visit_id(id); visit_opt(args, |args| vis.visit_generic_args(args)); vis.visit_expr(receiver); - visit_exprs(exprs, vis); + visit_thin_exprs(exprs, vis); vis.visit_span(span); } ExprKind::Binary(_binop, lhs, rhs) => { diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index 9e4a22e1fa3cd..3964e615d66e6 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -426,7 +426,8 @@ impl TokenStream { let attr_annotated = if attrs.is_empty() { tokens.create_token_stream() } else { - let attr_data = AttributesData { attrs: attrs.to_vec().into(), tokens: tokens.clone() }; + let attr_data = + AttributesData { attrs: attrs.iter().cloned().collect(), tokens: tokens.clone() }; AttrAnnotatedTokenStream::new(vec![( AttrAnnotatedTokenTree::Attributes(attr_data), Spacing::Alone, diff --git a/compiler/rustc_ast_lowering/Cargo.toml b/compiler/rustc_ast_lowering/Cargo.toml index 39ba62ef2ffc5..fdc82f742f7d6 100644 --- a/compiler/rustc_ast_lowering/Cargo.toml +++ b/compiler/rustc_ast_lowering/Cargo.toml @@ -8,16 +8,17 @@ doctest = false [dependencies] rustc_arena = { path = "../rustc_arena" } -tracing = "0.1" +rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } -rustc_hir = { path = "../rustc_hir" } -rustc_target = { path = "../rustc_target" } rustc_data_structures = { path = "../rustc_data_structures" } +rustc_errors = { path = "../rustc_errors" } +rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } rustc_middle = { path = "../rustc_middle" } rustc_query_system = { path = "../rustc_query_system" } -rustc_span = { path = "../rustc_span" } -rustc_errors = { path = "../rustc_errors" } rustc_session = { path = "../rustc_session" } -rustc_ast = { path = "../rustc_ast" } +rustc_span = { path = "../rustc_span" } +rustc_target = { path = "../rustc_target" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } +thin-vec = "0.2.8" +tracing = "0.1" diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index bd61f4fa87ab8..40cc9631df495 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -1,7 +1,6 @@ use super::ResolverAstLoweringExt; use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs}; use crate::{FnDeclKind, ImplTraitPosition}; - use rustc_ast::attr; use rustc_ast::ptr::P as AstP; use rustc_ast::*; @@ -13,6 +12,7 @@ use rustc_hir::definitions::DefPathData; use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned}; use rustc_span::symbol::{sym, Ident}; use rustc_span::DUMMY_SP; +use thin_vec::{thin_vec, ThinVec}; impl<'hir> LoweringContext<'_, 'hir> { fn lower_exprs(&mut self, exprs: &[AstP]) -> &'hir [hir::Expr<'hir>] { @@ -348,7 +348,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_legacy_const_generics( &mut self, mut f: Expr, - args: Vec>, + args: ThinVec>, legacy_args_idx: &[usize], ) -> hir::ExprKind<'hir> { let ExprKind::Path(None, ref mut path) = f.kind else { @@ -1591,11 +1591,11 @@ impl<'hir> LoweringContext<'_, 'hir> { let allow_ident = Ident::new(sym::allow, self.lower_span(span)); let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span)); let uc_nested = attr::mk_nested_word_item(uc_ident); - attr::mk_list_item(allow_ident, vec![uc_nested]) + attr::mk_list_item(allow_ident, thin_vec![uc_nested]) }; attr::mk_attr_outer(allow) }; - let attrs: AttrVec = vec![attr].into(); + let attrs: AttrVec = thin_vec![attr]; // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,` let continue_arm = { diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 0f1bab24f96ca..8a22b9e26a577 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -19,8 +19,8 @@ use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; use rustc_target::spec::abi; use smallvec::{smallvec, SmallVec}; - use std::iter; +use thin_vec::ThinVec; pub(super) struct ItemLowerer<'a, 'hir> { pub(super) tcx: TyCtxt<'hir>, @@ -230,7 +230,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name), ItemKind::Use(ref use_tree) => { // Start with an empty prefix. - let prefix = Path { segments: vec![], span: use_tree.span, tokens: None }; + let prefix = Path { segments: ThinVec::new(), span: use_tree.span, tokens: None }; self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs) } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 8ab1daf23e86e..4a0c2ee537cfc 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -63,9 +63,9 @@ use rustc_span::hygiene::MacroKind; use rustc_span::source_map::DesugaringKind; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; - use smallvec::SmallVec; use std::collections::hash_map::Entry; +use thin_vec::ThinVec; macro_rules! arena_vec { ($this:expr; $($x:expr),*) => ( @@ -1196,7 +1196,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| { let bound = this.lower_poly_trait_ref( &PolyTraitRef { - bound_generic_params: vec![], + bound_generic_params: ThinVec::new(), trait_ref: TraitRef { path: path.clone(), ref_id: t.id }, span: t.span }, diff --git a/compiler/rustc_ast_passes/Cargo.toml b/compiler/rustc_ast_passes/Cargo.toml index 37eff9207c128..0a0a54a1292f4 100644 --- a/compiler/rustc_ast_passes/Cargo.toml +++ b/compiler/rustc_ast_passes/Cargo.toml @@ -5,7 +5,7 @@ edition = "2021" [dependencies] itertools = "0.10.1" -tracing = "0.1" +rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } @@ -16,4 +16,5 @@ rustc_parse = { path = "../rustc_parse" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } -rustc_ast = { path = "../rustc_ast" } +thin-vec = "0.2.8" +tracing = "0.1" diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 68fca08101891..939d3b5a377f2 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -10,7 +10,7 @@ use rustc_session::Session; use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; use rustc_span::Span; - +use thin_vec::ThinVec; use tracing::debug; macro_rules! gate_feature_fn { @@ -465,7 +465,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { ast::ItemKind::Struct(..) => { for attr in self.sess.filter_by_name(&i.attrs, sym::repr) { - for item in attr.meta_item_list().unwrap_or_else(Vec::new) { + for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { if item.has_name(sym::simd) { gate_feature_post!( &self, diff --git a/compiler/rustc_ast_pretty/Cargo.toml b/compiler/rustc_ast_pretty/Cargo.toml index 5ad8714e9fec9..8a512b352c5fe 100644 --- a/compiler/rustc_ast_pretty/Cargo.toml +++ b/compiler/rustc_ast_pretty/Cargo.toml @@ -9,3 +9,4 @@ doctest = false [dependencies] rustc_span = { path = "../rustc_span" } rustc_ast = { path = "../rustc_ast" } +thin-vec = "0.2.8" diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 8749a13c5dde1..ec8dc0ce27fa6 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -21,8 +21,8 @@ use rustc_span::edition::Edition; use rustc_span::source_map::{SourceMap, Spanned}; use rustc_span::symbol::{kw, sym, Ident, IdentPrinter, Symbol}; use rustc_span::{BytePos, FileName, Span}; - use std::borrow::Cow; +use thin_vec::{thin_vec, ThinVec}; pub use self::delimited::IterDelimited; @@ -119,7 +119,7 @@ pub fn print_crate<'a>( // `#![feature(prelude_import)]` let pi_nested = attr::mk_nested_word_item(Ident::with_dummy_span(sym::prelude_import)); - let list = attr::mk_list_item(Ident::with_dummy_span(sym::feature), vec![pi_nested]); + let list = attr::mk_list_item(Ident::with_dummy_span(sym::feature), thin_vec![pi_nested]); let fake_attr = attr::mk_attr_inner(list); s.print_attribute(&fake_attr); @@ -1714,10 +1714,10 @@ impl<'a> State<'a> { self.ibox(INDENT_UNIT); self.print_formal_generic_params(generic_params); let generics = ast::Generics { - params: Vec::new(), + params: ThinVec::new(), where_clause: ast::WhereClause { has_where_token: false, - predicates: Vec::new(), + predicates: ThinVec::new(), span: rustc_span::DUMMY_SP, }, span: rustc_span::DUMMY_SP, diff --git a/compiler/rustc_ast_pretty/src/pprust/tests.rs b/compiler/rustc_ast_pretty/src/pprust/tests.rs index 6c8d42f33eb5a..3b2b60a86f06e 100644 --- a/compiler/rustc_ast_pretty/src/pprust/tests.rs +++ b/compiler/rustc_ast_pretty/src/pprust/tests.rs @@ -3,6 +3,7 @@ use super::*; use rustc_ast as ast; use rustc_span::create_default_session_globals_then; use rustc_span::symbol::Ident; +use thin_vec::ThinVec; fn fun_to_string( decl: &ast::FnDecl, @@ -27,8 +28,10 @@ fn test_fun_to_string() { create_default_session_globals_then(|| { let abba_ident = Ident::from_str("abba"); - let decl = - ast::FnDecl { inputs: Vec::new(), output: ast::FnRetTy::Default(rustc_span::DUMMY_SP) }; + let decl = ast::FnDecl { + inputs: ThinVec::new(), + output: ast::FnRetTy::Default(rustc_span::DUMMY_SP), + }; let generics = ast::Generics::default(); assert_eq!( fun_to_string(&decl, ast::FnHeader::default(), abba_ident, &generics), diff --git a/compiler/rustc_builtin_macros/Cargo.toml b/compiler/rustc_builtin_macros/Cargo.toml index 8d8e9d9b5ff4e..6469d0d7b88a6 100644 --- a/compiler/rustc_builtin_macros/Cargo.toml +++ b/compiler/rustc_builtin_macros/Cargo.toml @@ -7,20 +7,21 @@ edition = "2021" doctest = false [dependencies] -rustc_parse_format = { path = "../rustc_parse_format" } -tracing = "0.1" +rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } +rustc_expand = { path = "../rustc_expand" } rustc_feature = { path = "../rustc_feature" } rustc_lexer = { path = "../rustc_lexer" } rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_macros = { path = "../rustc_macros" } +rustc_parse_format = { path = "../rustc_parse_format" } rustc_parse = { path = "../rustc_parse" } -rustc_target = { path = "../rustc_target" } rustc_session = { path = "../rustc_session" } -smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } -rustc_ast = { path = "../rustc_ast" } -rustc_expand = { path = "../rustc_expand" } rustc_span = { path = "../rustc_span" } +rustc_target = { path = "../rustc_target" } +smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } +thin-vec = "0.2.8" +tracing = "0.1" diff --git a/compiler/rustc_builtin_macros/src/assert.rs b/compiler/rustc_builtin_macros/src/assert.rs index 119724b50493e..a41983ea68b3f 100644 --- a/compiler/rustc_builtin_macros/src/assert.rs +++ b/compiler/rustc_builtin_macros/src/assert.rs @@ -11,6 +11,7 @@ use rustc_expand::base::{DummyResult, ExtCtxt, MacEager, MacResult}; use rustc_parse::parser::Parser; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; +use thin_vec::thin_vec; pub fn expand_assert<'cx>( cx: &'cx mut ExtCtxt<'_>, @@ -79,7 +80,7 @@ pub fn expand_assert<'cx>( let then = cx.expr_call_global( call_site_span, cx.std_path(&[sym::panicking, sym::panic]), - vec![cx.expr_str( + thin_vec![cx.expr_str( DUMMY_SP, Symbol::intern(&format!( "assertion failed: {}", diff --git a/compiler/rustc_builtin_macros/src/assert/context.rs b/compiler/rustc_builtin_macros/src/assert/context.rs index d2ee4249989ee..18e10e6633580 100644 --- a/compiler/rustc_builtin_macros/src/assert/context.rs +++ b/compiler/rustc_builtin_macros/src/assert/context.rs @@ -13,6 +13,7 @@ use rustc_span::{ symbol::{sym, Ident, Symbol}, Span, }; +use thin_vec::{thin_vec, ThinVec}; pub(super) struct Context<'cx, 'a> { // An optimization. @@ -116,14 +117,16 @@ impl<'cx, 'a> Context<'cx, 'a> { self.cx.item( self.span, Ident::empty(), - vec![self.cx.attribute(attr::mk_list_item( + thin_vec![self.cx.attribute(attr::mk_list_item( Ident::new(sym::allow, self.span), - vec![attr::mk_nested_word_item(Ident::new(sym::unused_imports, self.span))], - ))] - .into(), + thin_vec![attr::mk_nested_word_item(Ident::new( + sym::unused_imports, + self.span + ))], + ))], ItemKind::Use(UseTree { prefix: self.cx.path(self.span, self.cx.std_path(&[sym::asserting])), - kind: UseTreeKind::Nested(vec![ + kind: UseTreeKind::Nested(thin_vec![ nested_tree(self, sym::TryCaptureGeneric), nested_tree(self, sym::TryCapturePrintable), ]), @@ -139,7 +142,7 @@ impl<'cx, 'a> Context<'cx, 'a> { self.cx.expr_call( self.span, self.cx.expr_path(self.cx.path(self.span, unlikely_path)), - vec![self.cx.expr(self.span, ExprKind::Unary(UnOp::Not, cond_expr))], + thin_vec![self.cx.expr(self.span, ExprKind::Unary(UnOp::Not, cond_expr))], ) } @@ -340,7 +343,7 @@ impl<'cx, 'a> Context<'cx, 'a> { let init = self.cx.expr_call( self.span, self.cx.expr_path(self.cx.path(self.span, init_std_path)), - vec![], + ThinVec::new(), ); let capture = Capture { decl: self.cx.stmt_let(self.span, true, ident, init), ident }; self.capture_decls.push(capture); @@ -367,7 +370,7 @@ impl<'cx, 'a> Context<'cx, 'a> { self.cx.expr_path( self.cx.path(self.span, self.cx.std_path(&[sym::asserting, sym::Wrapper])), ), - vec![self.cx.expr_path(Path::from_ident(local_bind))], + thin_vec![self.cx.expr_path(Path::from_ident(local_bind))], ); let try_capture_call = self .cx @@ -379,7 +382,7 @@ impl<'cx, 'a> Context<'cx, 'a> { ident: Ident::new(sym::try_capture, self.span), }, expr_paren(self.cx, self.span, self.cx.expr_addr_of(self.span, wrapper)), - vec![expr_addr_of_mut( + thin_vec![expr_addr_of_mut( self.cx, self.span, self.cx.expr_path(Path::from_ident(capture)), @@ -442,7 +445,7 @@ fn expr_method_call( cx: &ExtCtxt<'_>, path: PathSegment, receiver: P, - args: Vec>, + args: ThinVec>, span: Span, ) -> P { cx.expr(span, ExprKind::MethodCall(path, receiver, args, span)) diff --git a/compiler/rustc_builtin_macros/src/deriving/clone.rs b/compiler/rustc_builtin_macros/src/deriving/clone.rs index dd7989cf48c37..361ff4271242a 100644 --- a/compiler/rustc_builtin_macros/src/deriving/clone.rs +++ b/compiler/rustc_builtin_macros/src/deriving/clone.rs @@ -1,12 +1,12 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use crate::deriving::path_std; - use rustc_ast::{self as ast, Generics, ItemKind, MetaItem, VariantData}; use rustc_data_structures::fx::FxHashSet; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; +use thin_vec::thin_vec; pub fn expand_deriving_clone( cx: &mut ExtCtxt<'_>, @@ -68,7 +68,7 @@ pub fn expand_deriving_clone( } let inline = cx.meta_word(span, sym::inline); - let attrs = vec![cx.attribute(inline)].into(); + let attrs = thin_vec![cx.attribute(inline)]; let trait_def = TraitDef { span, path: path_std!(clone::Clone), @@ -160,7 +160,7 @@ fn cs_clone( let all_fields; let fn_path = cx.std_path(&[sym::clone, sym::Clone, sym::clone]); let subcall = |cx: &mut ExtCtxt<'_>, field: &FieldInfo| { - let args = vec![field.self_expr.clone()]; + let args = thin_vec![field.self_expr.clone()]; cx.expr_call_global(field.span, fn_path.clone(), args) }; diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs index 9b6d3e5032f94..323781d844e32 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs @@ -7,6 +7,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use thin_vec::thin_vec; pub fn expand_deriving_eq( cx: &mut ExtCtxt<'_>, @@ -18,9 +19,9 @@ pub fn expand_deriving_eq( let span = cx.with_def_site_ctxt(span); let inline = cx.meta_word(span, sym::inline); let hidden = rustc_ast::attr::mk_nested_word_item(Ident::new(sym::hidden, span)); - let doc = rustc_ast::attr::mk_list_item(Ident::new(sym::doc, span), vec![hidden]); + let doc = rustc_ast::attr::mk_list_item(Ident::new(sym::doc, span), thin_vec![hidden]); let no_coverage = cx.meta_word(span, sym::no_coverage); - let attrs = vec![cx.attribute(inline), cx.attribute(doc), cx.attribute(no_coverage)].into(); + let attrs = thin_vec![cx.attribute(inline), cx.attribute(doc), cx.attribute(no_coverage)]; let trait_def = TraitDef { span, path: path_std!(cmp::Eq), diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs index 0e17b95178759..e6c7a609ffb88 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs @@ -1,11 +1,11 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use crate::deriving::path_std; - use rustc_ast::MetaItem; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use thin_vec::thin_vec; pub fn expand_deriving_ord( cx: &mut ExtCtxt<'_>, @@ -15,7 +15,7 @@ pub fn expand_deriving_ord( push: &mut dyn FnMut(Annotatable), ) { let inline = cx.meta_word(span, sym::inline); - let attrs = vec![cx.attribute(inline)].into(); + let attrs = thin_vec![cx.attribute(inline)]; let trait_def = TraitDef { span, path: path_std!(cmp::Ord), @@ -62,7 +62,7 @@ pub fn cs_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> Bl let [other_expr] = &field.other_selflike_exprs[..] else { cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); }; - let args = vec![field.self_expr.clone(), other_expr.clone()]; + let args = thin_vec![field.self_expr.clone(), other_expr.clone()]; cx.expr_call_global(field.span, cmp_path.clone(), args) } CsFold::Combine(span, expr1, expr2) => { diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs index ac1325b92a6f3..42ee65b570a2a 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs @@ -1,12 +1,12 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use crate::deriving::{path_local, path_std}; - use rustc_ast::ptr::P; use rustc_ast::{BinOpKind, BorrowKind, Expr, ExprKind, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::sym; use rustc_span::Span; +use thin_vec::thin_vec; pub fn expand_deriving_partial_eq( cx: &mut ExtCtxt<'_>, @@ -68,7 +68,7 @@ pub fn expand_deriving_partial_eq( // No need to generate `ne`, the default suffices, and not generating it is // faster. let inline = cx.meta_word(span, sym::inline); - let attrs = vec![cx.attribute(inline)].into(); + let attrs = thin_vec![cx.attribute(inline)]; let methods = vec![MethodDef { name: sym::eq, generics: Bounds::empty(), diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs index 7763e55401783..dd9d13494af82 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs @@ -1,11 +1,11 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use crate::deriving::{path_std, pathvec_std}; - use rustc_ast::MetaItem; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use thin_vec::thin_vec; pub fn expand_deriving_partial_ord( cx: &mut ExtCtxt<'_>, @@ -19,7 +19,7 @@ pub fn expand_deriving_partial_ord( Path(Path::new_(pathvec_std!(option::Option), vec![Box::new(ordering_ty)], PathKind::Std)); let inline = cx.meta_word(span, sym::inline); - let attrs = vec![cx.attribute(inline)].into(); + let attrs = thin_vec![cx.attribute(inline)]; let partial_cmp_def = MethodDef { name: sym::partial_cmp, @@ -70,7 +70,7 @@ pub fn cs_partial_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_ let [other_expr] = &field.other_selflike_exprs[..] else { cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); }; - let args = vec![field.self_expr.clone(), other_expr.clone()]; + let args = thin_vec![field.self_expr.clone(), other_expr.clone()]; cx.expr_call_global(field.span, partial_cmp_path.clone(), args) } CsFold::Combine(span, expr1, expr2) => { diff --git a/compiler/rustc_builtin_macros/src/deriving/debug.rs b/compiler/rustc_builtin_macros/src/deriving/debug.rs index 4af7fd8165388..a702eef42d396 100644 --- a/compiler/rustc_builtin_macros/src/deriving/debug.rs +++ b/compiler/rustc_builtin_macros/src/deriving/debug.rs @@ -1,11 +1,11 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use crate::deriving::path_std; - use rustc_ast::{self as ast, MetaItem}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; +use thin_vec::{thin_vec, ThinVec}; pub fn expand_deriving_debug( cx: &mut ExtCtxt<'_>, @@ -72,7 +72,7 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_> if fields.is_empty() { // Special case for no fields. let fn_path_write_str = cx.std_path(&[sym::fmt, sym::Formatter, sym::write_str]); - let expr = cx.expr_call_global(span, fn_path_write_str, vec![fmt, name]); + let expr = cx.expr_call_global(span, fn_path_write_str, thin_vec![fmt, name]); BlockOrExpr::new_expr(expr) } else if fields.len() <= CUTOFF { // Few enough fields that we can use a specific-length method. @@ -83,7 +83,7 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_> }; let fn_path_debug = cx.std_path(&[sym::fmt, sym::Formatter, Symbol::intern(&debug)]); - let mut args = Vec::with_capacity(2 + fields.len() * args_per_field); + let mut args = ThinVec::with_capacity(2 + fields.len() * args_per_field); args.extend([fmt, name]); for i in 0..fields.len() { let field = &fields[i]; @@ -155,7 +155,7 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_> }; let fn_path_debug_internal = cx.std_path(&[sym::fmt, sym::Formatter, sym_debug]); - let mut args = Vec::with_capacity(4); + let mut args = ThinVec::with_capacity(4); args.push(fmt); args.push(name); if is_struct { diff --git a/compiler/rustc_builtin_macros/src/deriving/decodable.rs b/compiler/rustc_builtin_macros/src/deriving/decodable.rs index 7174dbbe7ea8b..4583d55c5967f 100644 --- a/compiler/rustc_builtin_macros/src/deriving/decodable.rs +++ b/compiler/rustc_builtin_macros/src/deriving/decodable.rs @@ -3,12 +3,12 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use crate::deriving::pathvec_std; - use rustc_ast::ptr::P; use rustc_ast::{self as ast, Expr, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; +use thin_vec::thin_vec; pub fn expand_deriving_rustc_decodable( cx: &mut ExtCtxt<'_>, @@ -93,7 +93,7 @@ fn decodable_substructure( cx.expr_call_global( span, fn_read_struct_field_path.clone(), - vec![ + thin_vec![ blkdecoder.clone(), cx.expr_str(span, name), cx.expr_usize(span, field), @@ -109,7 +109,7 @@ fn decodable_substructure( cx.expr_call_global( trait_span, fn_read_struct_path, - vec![ + thin_vec![ decoder, cx.expr_str(trait_span, substr.type_ident.name), cx.expr_usize(trait_span, nfields), @@ -138,7 +138,7 @@ fn decodable_substructure( cx.expr_call_global( span, fn_read_enum_variant_arg_path.clone(), - vec![blkdecoder.clone(), idx, exprdecode.clone()], + thin_vec![blkdecoder.clone(), idx, exprdecode.clone()], ), ) }); @@ -159,7 +159,7 @@ fn decodable_substructure( let result = cx.expr_call_global( trait_span, fn_read_enum_variant_path, - vec![blkdecoder, variant_array_ref, lambda], + thin_vec![blkdecoder, variant_array_ref, lambda], ); let fn_read_enum_path: Vec<_> = cx.def_site_path(&[sym::rustc_serialize, sym::Decoder, sym::read_enum]); @@ -167,7 +167,7 @@ fn decodable_substructure( cx.expr_call_global( trait_span, fn_read_enum_path, - vec![ + thin_vec![ decoder, cx.expr_str(trait_span, substr.type_ident.name), cx.lambda1(trait_span, result, blkarg), diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index f316f01ef6615..d7977c4aa0ddd 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -1,6 +1,5 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; - use rustc_ast as ast; use rustc_ast::{walk_list, EnumDef, VariantData}; use rustc_errors::Applicability; @@ -9,6 +8,7 @@ use rustc_span::symbol::Ident; use rustc_span::symbol::{kw, sym}; use rustc_span::Span; use smallvec::SmallVec; +use thin_vec::{thin_vec, ThinVec}; pub fn expand_deriving_default( cx: &mut ExtCtxt<'_>, @@ -20,7 +20,7 @@ pub fn expand_deriving_default( item.visit_with(&mut DetectNonVariantDefaultAttr { cx }); let inline = cx.meta_word(span, sym::inline); - let attrs = vec![cx.attribute(inline)].into(); + let attrs = thin_vec![cx.attribute(inline)]; let trait_def = TraitDef { span, path: Path::new(vec![kw::Default, sym::Default]), @@ -58,7 +58,7 @@ fn default_struct_substructure( ) -> BlockOrExpr { // Note that `kw::Default` is "default" and `sym::Default` is "Default"! let default_ident = cx.std_path(&[kw::Default, sym::Default, kw::Default]); - let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); + let default_call = |span| cx.expr_call_global(span, default_ident.clone(), ThinVec::new()); let expr = match summary { Unnamed(ref fields, is_tuple) => { diff --git a/compiler/rustc_builtin_macros/src/deriving/encodable.rs b/compiler/rustc_builtin_macros/src/deriving/encodable.rs index b220e54238f46..395fbe8852c71 100644 --- a/compiler/rustc_builtin_macros/src/deriving/encodable.rs +++ b/compiler/rustc_builtin_macros/src/deriving/encodable.rs @@ -88,11 +88,11 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use crate::deriving::pathvec_std; - use rustc_ast::{AttrVec, ExprKind, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; +use thin_vec::{thin_vec, ThinVec}; pub fn expand_deriving_rustc_encodable( cx: &mut ExtCtxt<'_>, @@ -173,12 +173,13 @@ fn encodable_substructure( None => Symbol::intern(&format!("_field{}", i)), }; let self_ref = cx.expr_addr_of(span, self_expr.clone()); - let enc = cx.expr_call(span, fn_path.clone(), vec![self_ref, blkencoder.clone()]); + let enc = + cx.expr_call(span, fn_path.clone(), thin_vec![self_ref, blkencoder.clone()]); let lambda = cx.lambda1(span, enc, blkarg); let call = cx.expr_call_global( span, fn_emit_struct_field_path.clone(), - vec![ + thin_vec![ blkencoder.clone(), cx.expr_str(span, name), cx.expr_usize(span, i), @@ -200,7 +201,7 @@ fn encodable_substructure( // unit structs have no fields and need to return Ok() let blk = if stmts.is_empty() { - let ok = cx.expr_ok(trait_span, cx.expr_tuple(trait_span, vec![])); + let ok = cx.expr_ok(trait_span, cx.expr_tuple(trait_span, ThinVec::new())); cx.lambda1(trait_span, ok, blkarg) } else { cx.lambda_stmts_1(trait_span, stmts, blkarg) @@ -212,7 +213,7 @@ fn encodable_substructure( let expr = cx.expr_call_global( trait_span, fn_emit_struct_path, - vec![ + thin_vec![ encoder, cx.expr_str(trait_span, substr.type_ident.name), cx.expr_usize(trait_span, fields.len()), @@ -238,14 +239,17 @@ fn encodable_substructure( let last = fields.len() - 1; for (i, &FieldInfo { ref self_expr, span, .. }) in fields.iter().enumerate() { let self_ref = cx.expr_addr_of(span, self_expr.clone()); - let enc = - cx.expr_call(span, fn_path.clone(), vec![self_ref, blkencoder.clone()]); + let enc = cx.expr_call( + span, + fn_path.clone(), + thin_vec![self_ref, blkencoder.clone()], + ); let lambda = cx.lambda1(span, enc, blkarg); let call = cx.expr_call_global( span, fn_emit_enum_variant_arg_path.clone(), - vec![blkencoder.clone(), cx.expr_usize(span, i), lambda], + thin_vec![blkencoder.clone(), cx.expr_usize(span, i), lambda], ); let call = if i != last { cx.expr_try(span, call) @@ -255,7 +259,7 @@ fn encodable_substructure( stmts.push(cx.stmt_expr(call)); } } else { - let ok = cx.expr_ok(trait_span, cx.expr_tuple(trait_span, vec![])); + let ok = cx.expr_ok(trait_span, cx.expr_tuple(trait_span, ThinVec::new())); let ret_ok = cx.expr(trait_span, ExprKind::Ret(Some(ok))); stmts.push(cx.stmt_expr(ret_ok)); } @@ -269,7 +273,7 @@ fn encodable_substructure( let call = cx.expr_call_global( trait_span, fn_emit_enum_variant_path, - vec![ + thin_vec![ blkencoder, name, cx.expr_usize(trait_span, idx), @@ -284,7 +288,7 @@ fn encodable_substructure( let expr = cx.expr_call_global( trait_span, fn_emit_enum_path, - vec![encoder, cx.expr_str(trait_span, substr.type_ident.name), blk], + thin_vec![encoder, cx.expr_str(trait_span, substr.type_ident.name), blk], ); BlockOrExpr::new_mixed(vec![me], Some(expr)) } diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index c1bbc601560fa..0ff6cef87ebba 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -162,10 +162,7 @@ pub use StaticFields::*; pub use SubstructureFields::*; -use std::cell::RefCell; -use std::iter; -use std::vec; - +use crate::deriving; use rustc_ast::ptr::P; use rustc_ast::{self as ast, EnumDef, Expr, Generics, PatKind}; use rustc_ast::{GenericArg, GenericParamKind, VariantData}; @@ -173,11 +170,12 @@ use rustc_attr as attr; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; - +use std::cell::RefCell; +use std::iter; +use std::vec; +use thin_vec::{thin_vec, ThinVec}; use ty::{Bounds, Path, Ref, Self_, Ty}; -use crate::deriving; - pub mod ty; pub struct TraitDef<'a> { @@ -293,7 +291,7 @@ pub fn combine_substructure( } struct TypeParameter { - bound_generic_params: Vec, + bound_generic_params: ThinVec, ty: P, } @@ -360,7 +358,7 @@ fn find_type_parameters( struct Visitor<'a, 'b> { cx: &'a ExtCtxt<'b>, ty_param_names: &'a [Symbol], - bound_generic_params_stack: Vec, + bound_generic_params_stack: ThinVec, type_params: Vec, } @@ -399,7 +397,7 @@ fn find_type_parameters( let mut visitor = Visitor { cx, ty_param_names, - bound_generic_params_stack: Vec::new(), + bound_generic_params_stack: ThinVec::new(), type_params: Vec::new(), }; visit::Visitor::visit_ty(&mut visitor, ty); @@ -716,7 +714,7 @@ impl<'a> TraitDef<'a> { let self_type = cx.ty_path(path); let attr = cx.attribute(cx.meta_word(self.span, sym::automatically_derived)); - let attrs = vec![attr].into(); + let attrs = thin_vec![attr]; let opt_trait_ref = Some(trait_ref); cx.item( @@ -891,8 +889,8 @@ impl<'a> MethodDef<'a> { trait_: &TraitDef<'_>, type_ident: Ident, generics: &Generics, - ) -> (Option, Vec>, Vec>, Vec<(Ident, P)>) { - let mut selflike_args = Vec::new(); + ) -> (Option, ThinVec>, Vec>, Vec<(Ident, P)>) { + let mut selflike_args = ThinVec::new(); let mut nonselflike_args = Vec::new(); let mut nonself_arg_tys = Vec::new(); let span = trait_.span; @@ -1135,7 +1133,7 @@ impl<'a> MethodDef<'a> { trait_: &TraitDef<'b>, enum_def: &'b EnumDef, type_ident: Ident, - selflike_args: Vec>, + selflike_args: ThinVec>, nonselflike_args: &[P], ) -> BlockOrExpr { let span = trait_.span; @@ -1189,7 +1187,7 @@ impl<'a> MethodDef<'a> { cx, span, sym::discriminant_value, - vec![selflike_arg.clone()], + thin_vec![selflike_arg.clone()], ); cx.stmt_let(span, false, ident, variant_value) }) @@ -1251,7 +1249,7 @@ impl<'a> MethodDef<'a> { let sp = variant.span.with_ctxt(trait_.span.ctxt()); let variant_path = cx.path(sp, vec![type_ident, variant.ident]); let use_ref_pat = false; // because enums can't be repr(packed) - let mut subpats: Vec<_> = trait_.create_struct_patterns( + let mut subpats = trait_.create_struct_patterns( cx, variant_path, &variant.data, @@ -1327,7 +1325,7 @@ impl<'a> MethodDef<'a> { // ... // _ => ::core::intrinsics::unreachable() // } - let get_match_expr = |mut selflike_args: Vec>| { + let get_match_expr = |mut selflike_args: ThinVec>| { let match_arg = if selflike_args.len() == 1 { selflike_args.pop().unwrap() } else { @@ -1418,7 +1416,7 @@ impl<'a> TraitDef<'a> { struct_def: &'a VariantData, prefixes: &[String], use_ref_pat: bool, - ) -> Vec> { + ) -> ThinVec> { prefixes .iter() .map(|prefix| { diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs index 36e2e29308694..7901c04b41e43 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs @@ -9,6 +9,7 @@ use rustc_expand::base::ExtCtxt; use rustc_span::source_map::{respan, DUMMY_SP}; use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::Span; +use thin_vec::ThinVec; /// A path, e.g., `::std::option::Option::` (global). Has support /// for type parameters. @@ -102,7 +103,7 @@ impl Ty { Path(p) => p.to_ty(cx, span, self_ty, self_generics), Self_ => cx.ty_path(self.to_path(cx, span, self_ty, self_generics)), Unit => { - let ty = ast::TyKind::Tup(vec![]); + let ty = ast::TyKind::Tup(ThinVec::new()); cx.ty(span, ty) } } @@ -188,7 +189,11 @@ impl Bounds { Generics { params, - where_clause: ast::WhereClause { has_where_token: false, predicates: Vec::new(), span }, + where_clause: ast::WhereClause { + has_where_token: false, + predicates: ThinVec::new(), + span, + }, span, } } diff --git a/compiler/rustc_builtin_macros/src/deriving/hash.rs b/compiler/rustc_builtin_macros/src/deriving/hash.rs index f1f02e7ce7787..8b29ea67b5a23 100644 --- a/compiler/rustc_builtin_macros/src/deriving/hash.rs +++ b/compiler/rustc_builtin_macros/src/deriving/hash.rs @@ -1,11 +1,11 @@ use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use crate::deriving::{path_std, pathvec_std}; - use rustc_ast::{AttrVec, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::sym; use rustc_span::Span; +use thin_vec::thin_vec; pub fn expand_deriving_hash( cx: &mut ExtCtxt<'_>, @@ -57,7 +57,7 @@ fn hash_substructure( cx.expr_path(cx.path_global(span, strs)) }; - let expr = cx.expr_call(span, hash_path, vec![expr, state_expr.clone()]); + let expr = cx.expr_call(span, hash_path, thin_vec![expr, state_expr.clone()]); cx.stmt_expr(expr) }; diff --git a/compiler/rustc_builtin_macros/src/deriving/mod.rs b/compiler/rustc_builtin_macros/src/deriving/mod.rs index a65d0bad6de80..fa89283b25fca 100644 --- a/compiler/rustc_builtin_macros/src/deriving/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/mod.rs @@ -6,6 +6,7 @@ use rustc_ast::{GenericArg, Impl, ItemKind, MetaItem}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, MultiItemModifier}; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; +use thin_vec::ThinVec; macro path_local($x:ident) { generic::ty::Path::new_local(sym::$x) @@ -83,7 +84,7 @@ fn call_intrinsic( cx: &ExtCtxt<'_>, span: Span, intrinsic: Symbol, - args: Vec>, + args: ThinVec>, ) -> P { let span = cx.with_def_site_ctxt(span); let path = cx.std_path(&[sym::intrinsics, intrinsic]); @@ -94,7 +95,7 @@ fn call_intrinsic( fn call_unreachable(cx: &ExtCtxt<'_>, span: Span) -> P { let span = cx.with_def_site_ctxt(span); let path = cx.std_path(&[sym::intrinsics, sym::unreachable]); - let call = cx.expr_call_global(span, path, vec![]); + let call = cx.expr_call_global(span, path, ThinVec::new()); cx.expr_block(P(ast::Block { stmts: vec![cx.stmt_expr(call)], @@ -187,7 +188,7 @@ fn inject_impl_of_structural_trait( generics, of_trait: Some(trait_ref), self_ty: self_type, - items: Vec::new(), + items: ThinVec::new(), })), ); diff --git a/compiler/rustc_builtin_macros/src/env.rs b/compiler/rustc_builtin_macros/src/env.rs index b8828fa671a5d..1ad708ae521fc 100644 --- a/compiler/rustc_builtin_macros/src/env.rs +++ b/compiler/rustc_builtin_macros/src/env.rs @@ -8,8 +8,8 @@ use rustc_ast::{self as ast, GenericArg}; use rustc_expand::base::{self, *}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; - use std::env; +use thin_vec::thin_vec; pub fn expand_option_env<'cx>( cx: &'cx mut ExtCtxt<'_>, @@ -41,7 +41,7 @@ pub fn expand_option_env<'cx>( Some(value) => cx.expr_call_global( sp, cx.std_path(&[sym::option, sym::Option, sym::Some]), - vec![cx.expr_str(sp, value)], + thin_vec![cx.expr_str(sp, value)], ), }; MacEager::expr(e) diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index 2816f81fef121..551385e7419be 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -9,16 +9,16 @@ use rustc_ast::{token, BlockCheckMode, UnsafeSource}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_errors::{pluralize, Applicability, MultiSpan, PResult}; use rustc_expand::base::{self, *}; +use rustc_lint_defs::builtin::NAMED_ARGUMENTS_USED_POSITIONALLY; +use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, LintId}; use rustc_parse_format as parse; +use rustc_parse_format::Count; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{BytePos, InnerSpan, Span}; use smallvec::SmallVec; - -use rustc_lint_defs::builtin::NAMED_ARGUMENTS_USED_POSITIONALLY; -use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, LintId}; -use rustc_parse_format::Count; use std::borrow::Cow; use std::collections::hash_map::Entry; +use thin_vec::{thin_vec, ThinVec}; #[derive(PartialEq)] enum ArgumentType { @@ -831,7 +831,7 @@ impl<'a, 'b> Context<'a, 'b> { let mut path = Context::rtpath(self.ecx, sym::Count); path.push(Ident::new(c, sp)); match arg { - Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]), + Some(arg) => self.ecx.expr_call_global(sp, path, thin_vec![arg]), None => self.ecx.expr_path(self.ecx.path_global(sp, path)), } }; @@ -1081,14 +1081,14 @@ impl<'a, 'b> Context<'a, 'b> { // Now create the fmt::Arguments struct with all our locals we created. let (fn_name, fn_args) = if self.all_pieces_simple { - ("new_v1", vec![pieces, args_slice]) + ("new_v1", thin_vec![pieces, args_slice]) } else { // Build up the static array which will store our precompiled // nonstandard placeholders, if there are any. let fmt = self.ecx.expr_array_ref(self.macsp, self.pieces); let path = self.ecx.std_path(&[sym::fmt, sym::UnsafeArg, sym::new]); - let unsafe_arg = self.ecx.expr_call_global(self.macsp, path, Vec::new()); + let unsafe_arg = self.ecx.expr_call_global(self.macsp, path, ThinVec::new()); let unsafe_expr = self.ecx.expr_block(P(ast::Block { stmts: vec![self.ecx.stmt_expr(unsafe_arg)], id: ast::DUMMY_NODE_ID, @@ -1098,7 +1098,7 @@ impl<'a, 'b> Context<'a, 'b> { could_be_bare_literal: false, })); - ("new_v1_formatted", vec![pieces, args_slice, fmt, unsafe_expr]) + ("new_v1_formatted", thin_vec![pieces, args_slice, fmt, unsafe_expr]) }; let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]); @@ -1118,7 +1118,7 @@ impl<'a, 'b> Context<'a, 'b> { Placeholder(trait_) => trait_, Count => { let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]); - return ecx.expr_call_global(macsp, path, vec![arg]); + return ecx.expr_call_global(macsp, path, thin_vec![arg]); } }; let new_fn_name = match trait_ { @@ -1135,7 +1135,7 @@ impl<'a, 'b> Context<'a, 'b> { }; let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, Symbol::intern(new_fn_name)]); - ecx.expr_call_global(sp, path, vec![arg]) + ecx.expr_call_global(sp, path, thin_vec![arg]) } } diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs index 2bad9bbce6650..f3f2e8ff08712 100644 --- a/compiler/rustc_builtin_macros/src/global_allocator.rs +++ b/compiler/rustc_builtin_macros/src/global_allocator.rs @@ -9,6 +9,7 @@ use rustc_ast::{Fn, ItemKind, Mutability, Stmt, Ty, TyKind, Unsafe}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; +use thin_vec::{thin_vec, ThinVec}; pub fn expand( ecx: &mut ExtCtxt<'_>, @@ -50,7 +51,7 @@ pub fn expand( let stmts = ALLOCATOR_METHODS.iter().map(|method| f.allocator_fn(method)).collect(); // Generate anonymous constant serving as container for the allocator methods. - let const_ty = ecx.ty(ty_span, TyKind::Tup(Vec::new())); + let const_ty = ecx.ty(ty_span, TyKind::Tup(ThinVec::new())); let const_body = ecx.expr_block(ecx.block(span, stmts)); let const_item = ecx.item_const(span, Ident::new(kw::Underscore, span), const_ty, const_body); let const_item = if is_stmt { @@ -73,7 +74,7 @@ struct AllocFnFactory<'a, 'b> { impl AllocFnFactory<'_, '_> { fn allocator_fn(&self, method: &AllocatorMethod) -> Stmt { - let mut abi_args = Vec::new(); + let mut abi_args = ThinVec::new(); let mut i = 0; let mut mk = || { let name = Ident::from_str_and_span(&format!("arg{}", i), self.span); @@ -102,7 +103,7 @@ impl AllocFnFactory<'_, '_> { self.cx.stmt_item(self.ty_span, item) } - fn call_allocator(&self, method: Symbol, mut args: Vec>) -> P { + fn call_allocator(&self, method: Symbol, mut args: ThinVec>) -> P { let method = self.cx.std_path(&[sym::alloc, sym::GlobalAlloc, method]); let method = self.cx.expr_path(self.cx.path(self.ty_span, method)); let allocator = self.cx.path_ident(self.ty_span, self.global); @@ -116,13 +117,13 @@ impl AllocFnFactory<'_, '_> { fn attrs(&self) -> AttrVec { let special = sym::rustc_std_internal_symbol; let special = self.cx.meta_word(self.span, special); - vec![self.cx.attribute(special)].into() + thin_vec![self.cx.attribute(special)] } fn arg_ty( &self, ty: &AllocatorTy, - args: &mut Vec, + args: &mut ThinVec, ident: &mut dyn FnMut() -> Ident, ) -> P { match *ty { @@ -139,7 +140,7 @@ impl AllocFnFactory<'_, '_> { let layout_new = self.cx.expr_path(self.cx.path(self.span, layout_new)); let size = self.cx.expr_ident(self.span, size); let align = self.cx.expr_ident(self.span, align); - let layout = self.cx.expr_call(self.span, layout_new, vec![size, align]); + let layout = self.cx.expr_call(self.span, layout_new, thin_vec![size, align]); layout } @@ -173,7 +174,7 @@ impl AllocFnFactory<'_, '_> { (self.ptr_u8(), expr) } - AllocatorTy::Unit => (self.cx.ty(self.span, TyKind::Tup(Vec::new())), expr), + AllocatorTy::Unit => (self.cx.ty(self.span, TyKind::Tup(ThinVec::new())), expr), AllocatorTy::Layout | AllocatorTy::Usize | AllocatorTy::Ptr => { panic!("can't convert `AllocatorTy` to an output") diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index ebe1c3663e3a7..9f3b676a6208c 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -13,6 +13,7 @@ use rustc_span::source_map::SourceMap; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use smallvec::smallvec; +use thin_vec::{thin_vec, ThinVec}; struct ProcMacroDerive { id: NodeId, @@ -315,7 +316,7 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { cx.expr_call( span, proc_macro_ty_method_path(cx, custom_derive), - vec![ + thin_vec![ cx.expr_str(span, cd.trait_name), cx.expr_array_ref( span, @@ -336,7 +337,7 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { cx.expr_call( span, proc_macro_ty_method_path(cx, ident), - vec![ + thin_vec![ cx.expr_str(span, ca.function_name.name), local_path(cx, ca.function_name), ], @@ -370,7 +371,7 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { let deprecated_attr = attr::mk_nested_word_item(Ident::new(sym::deprecated, span)); let allow_deprecated_attr = - attr::mk_list_item(Ident::new(sym::allow, span), vec![deprecated_attr]); + attr::mk_list_item(Ident::new(sym::allow, span), thin_vec![deprecated_attr]); i.attrs.push(cx.attribute(allow_deprecated_attr)); i @@ -383,7 +384,7 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { let anon_constant = cx.item_const( span, Ident::new(kw::Underscore, span), - cx.ty(span, ast::TyKind::Tup(Vec::new())), + cx.ty(span, ast::TyKind::Tup(ThinVec::new())), block, ); diff --git a/compiler/rustc_builtin_macros/src/standard_library_imports.rs b/compiler/rustc_builtin_macros/src/standard_library_imports.rs index 90ea1e457ba80..49ef538f04e14 100644 --- a/compiler/rustc_builtin_macros/src/standard_library_imports.rs +++ b/compiler/rustc_builtin_macros/src/standard_library_imports.rs @@ -6,6 +6,7 @@ use rustc_span::edition::Edition::*; use rustc_span::hygiene::AstPass; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::DUMMY_SP; +use thin_vec::thin_vec; pub fn inject( mut krate: ast::Crate, @@ -51,7 +52,7 @@ pub fn inject( cx.item( span, ident, - vec![cx.attribute(cx.meta_word(span, sym::macro_use))].into(), + thin_vec![cx.attribute(cx.meta_word(span, sym::macro_use))], ast::ItemKind::ExternCrate(None), ), ); @@ -78,7 +79,7 @@ pub fn inject( let use_item = cx.item( span, Ident::empty(), - vec![cx.attribute(cx.meta_word(span, sym::prelude_import))].into(), + thin_vec![cx.attribute(cx.meta_word(span, sym::prelude_import))], ast::ItemKind::Use(ast::UseTree { prefix: cx.path(span, import_path), kind: ast::UseTreeKind::Glob, diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index 03c84f5ec2a74..aeaae8a598ed3 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -1,7 +1,6 @@ /// The expansion from a test function to the appropriate test struct for libtest /// Ideally, this code would be in libtest but for efficiency and error messages it lives here. use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute}; - use rustc_ast as ast; use rustc_ast::attr; use rustc_ast::ptr::P; @@ -11,8 +10,8 @@ use rustc_expand::base::*; use rustc_session::Session; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; - use std::iter; +use thin_vec::{thin_vec, ThinVec}; // #[test_case] is used by custom test authors to mark tests // When building for test, it needs to make the item public and gensym the name @@ -174,19 +173,19 @@ pub fn expand_test_or_bench( cx.expr_call( sp, cx.expr_path(test_path("StaticBenchFn")), - vec![ + thin_vec![ // |b| self::test::assert_test_result( cx.lambda1( sp, cx.expr_call( sp, cx.expr_path(test_path("assert_test_result")), - vec![ + thin_vec![ // super::$test_fn(b) cx.expr_call( sp, cx.expr_path(cx.path(sp, vec![item.ident])), - vec![cx.expr_ident(sp, b)], + thin_vec![cx.expr_ident(sp, b)], ), ], ), @@ -198,7 +197,7 @@ pub fn expand_test_or_bench( cx.expr_call( sp, cx.expr_path(test_path("StaticTestFn")), - vec![ + thin_vec![ // || { cx.lambda0( sp, @@ -206,9 +205,13 @@ pub fn expand_test_or_bench( cx.expr_call( sp, cx.expr_path(test_path("assert_test_result")), - vec![ + thin_vec![ // $test_fn() - cx.expr_call(sp, cx.expr_path(cx.path(sp, vec![item.ident])), vec![]), // ) + cx.expr_call( + sp, + cx.expr_path(cx.path(sp, vec![item.ident])), + ThinVec::new() + ), // ) ], ), // } ), // ) @@ -219,16 +222,15 @@ pub fn expand_test_or_bench( let mut test_const = cx.item( sp, Ident::new(item.ident.name, sp), - vec![ + thin_vec![ // #[cfg(test)] cx.attribute(attr::mk_list_item( Ident::new(sym::cfg, attr_sp), - vec![attr::mk_nested_word_item(Ident::new(sym::test, attr_sp))], + thin_vec![attr::mk_nested_word_item(Ident::new(sym::test, attr_sp))], )), // #[rustc_test_marker] cx.attribute(cx.meta_word(attr_sp, sym::rustc_test_marker)), - ] - .into(), + ], // const $ident: test::TestDescAndFn = ast::ItemKind::Const( ast::Defaultness::Final, @@ -252,7 +254,7 @@ pub fn expand_test_or_bench( cx.expr_call( sp, cx.expr_path(test_path("StaticTestName")), - vec![cx.expr_str( + thin_vec![cx.expr_str( sp, Symbol::intern(&item_path( // skip the name of the root module @@ -296,7 +298,7 @@ pub fn expand_test_or_bench( ShouldPanic::Yes(Some(sym)) => cx.expr_call( sp, cx.expr_path(should_panic_path("YesWithMessage")), - vec![cx.expr_str(sp, sym)], + thin_vec![cx.expr_str(sp, sym)], ), }, ), diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index 093f0f10a3867..7ce9cabe7f120 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -14,6 +14,7 @@ use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use rustc_target::spec::PanicStrategy; use smallvec::{smallvec, SmallVec}; +use thin_vec::{thin_vec, ThinVec}; use tracing::debug; use std::{iter, mem}; @@ -186,7 +187,8 @@ impl<'a> MutVisitor for EntryPointCleaner<'a> { let allow_ident = Ident::new(sym::allow, self.def_site); let dc_nested = attr::mk_nested_word_item(Ident::new(sym::dead_code, self.def_site)); - let allow_dead_code_item = attr::mk_list_item(allow_ident, vec![dc_nested]); + let allow_dead_code_item = + attr::mk_list_item(allow_ident, thin_vec![dc_nested]); let allow_dead_code = attr::mk_attr_outer(allow_dead_code_item); let attrs = attrs .into_iter() @@ -294,7 +296,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P { test_runner.span = sp; let test_main_path_expr = ecx.expr_path(test_runner); - let call_test_main = ecx.expr_call(sp, test_main_path_expr, vec![mk_tests_slice(cx, sp)]); + let call_test_main = ecx.expr_call(sp, test_main_path_expr, thin_vec![mk_tests_slice(cx, sp)]); let call_test_main = ecx.stmt_expr(call_test_main); // extern crate test @@ -308,7 +310,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P { let main_attr = ecx.attribute(main_meta); // pub fn main() { ... } - let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(vec![])); + let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(ThinVec::new())); // If no test runner is provided we need to import the test crate let main_body = if cx.test_runner.is_none() { @@ -317,7 +319,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P { ecx.block(sp, vec![call_test_main]) }; - let decl = ecx.fn_decl(vec![], ast::FnRetTy::Ty(main_ret_ty)); + let decl = ecx.fn_decl(ThinVec::new(), ast::FnRetTy::Ty(main_ret_ty)); let sig = ast::FnSig { decl, header: ast::FnHeader::default(), span: sp }; let defaultness = ast::Defaultness::Final; let main = ast::ItemKind::Fn(Box::new(ast::Fn { @@ -335,7 +337,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P { let main = P(ast::Item { ident: main_id, - attrs: vec![main_attr].into(), + attrs: thin_vec![main_attr], id: ast::DUMMY_NODE_ID, kind: main, vis: ast::Visibility { span: sp, kind: ast::VisibilityKind::Public, tokens: None }, diff --git a/compiler/rustc_data_structures/Cargo.toml b/compiler/rustc_data_structures/Cargo.toml index 5c641f54f686d..2d8658db5e6aa 100644 --- a/compiler/rustc_data_structures/Cargo.toml +++ b/compiler/rustc_data_structures/Cargo.toml @@ -8,25 +8,26 @@ doctest = false [dependencies] arrayvec = { version = "0.7", default-features = false } +bitflags = "1.2.1" +cfg-if = "0.1.2" ena = "0.14" indexmap = { version = "1.9.1" } -tracing = "0.1" jobserver_crate = { version = "0.1.13", package = "jobserver" } -rustc_serialize = { path = "../rustc_serialize" } -rustc_macros = { path = "../rustc_macros" } -rustc_graphviz = { path = "../rustc_graphviz" } -cfg-if = "0.1.2" -stable_deref_trait = "1.0.0" -rayon = { version = "0.4.0", package = "rustc-rayon", optional = true } +libc = "0.2" +measureme = "10.0.0" rayon-core = { version = "0.4.0", package = "rustc-rayon-core", optional = true } +rayon = { version = "0.4.0", package = "rustc-rayon", optional = true } +rustc_graphviz = { path = "../rustc_graphviz" } rustc-hash = "1.1.0" -smallvec = { version = "1.8.1", features = ["const_generics", "union", "may_dangle"] } rustc_index = { path = "../rustc_index", package = "rustc_index" } -bitflags = "1.2.1" -measureme = "10.0.0" -libc = "0.2" +rustc_macros = { path = "../rustc_macros" } +rustc_serialize = { path = "../rustc_serialize" } +smallvec = { version = "1.8.1", features = ["const_generics", "union", "may_dangle"] } +stable_deref_trait = "1.0.0" stacker = "0.1.14" tempfile = "3.2" +thin-vec = "0.2.8" +tracing = "0.1" [dependencies.parking_lot] version = "0.11" diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index c8b09cffe0136..a7429ed008fb8 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -75,7 +75,6 @@ pub mod profiling; pub mod sharded; pub mod stack; pub mod sync; -pub mod thin_vec; pub mod tiny_list; pub mod transitive_relation; pub mod vec_linked_list; diff --git a/compiler/rustc_data_structures/src/map_in_place.rs b/compiler/rustc_data_structures/src/map_in_place.rs index d912211443a89..a0d4b7ade1f33 100644 --- a/compiler/rustc_data_structures/src/map_in_place.rs +++ b/compiler/rustc_data_structures/src/map_in_place.rs @@ -1,6 +1,6 @@ -use crate::thin_vec::ThinVec; use smallvec::{Array, SmallVec}; use std::ptr; +use thin_vec::ThinVec; pub trait MapInPlace: Sized { fn map_in_place(&mut self, mut f: F) diff --git a/compiler/rustc_data_structures/src/thin_vec.rs b/compiler/rustc_data_structures/src/thin_vec.rs deleted file mode 100644 index fce42e709ab74..0000000000000 --- a/compiler/rustc_data_structures/src/thin_vec.rs +++ /dev/null @@ -1,180 +0,0 @@ -use crate::stable_hasher::{HashStable, StableHasher}; - -use std::iter::FromIterator; - -/// A vector type optimized for cases where this size is usually 0 (cf. `SmallVec`). -/// The `Option>` wrapping allows us to represent a zero sized vector with `None`, -/// which uses only a single (null) pointer. -#[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq)] -pub struct ThinVec(Option>>); - -impl ThinVec { - pub fn new() -> Self { - ThinVec(None) - } - - pub fn iter(&self) -> std::slice::Iter<'_, T> { - self.into_iter() - } - - pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> { - self.into_iter() - } - - pub fn push(&mut self, item: T) { - match *self { - ThinVec(Some(ref mut vec)) => vec.push(item), - ThinVec(None) => *self = vec![item].into(), - } - } - - /// Note: if `set_len(0)` is called on a non-empty `ThinVec`, it will - /// remain in the `Some` form. This is required for some code sequences - /// (such as the one in `flat_map_in_place`) that call `set_len(0)` before - /// an operation that might panic, and then call `set_len(n)` again - /// afterwards. - pub unsafe fn set_len(&mut self, new_len: usize) { - match *self { - ThinVec(None) => { - // A prerequisite of `Vec::set_len` is that `new_len` must be - // less than or equal to capacity(). The same applies here. - if new_len != 0 { - panic!("unsafe ThinVec::set_len({})", new_len); - } - } - ThinVec(Some(ref mut vec)) => vec.set_len(new_len), - } - } - - pub fn insert(&mut self, index: usize, value: T) { - match *self { - ThinVec(None) => { - if index == 0 { - *self = vec![value].into(); - } else { - panic!("invalid ThinVec::insert"); - } - } - ThinVec(Some(ref mut vec)) => vec.insert(index, value), - } - } - - pub fn remove(&mut self, index: usize) -> T { - match self { - ThinVec(None) => panic!("invalid ThinVec::remove"), - ThinVec(Some(vec)) => vec.remove(index), - } - } - - pub fn as_slice(&self) -> &[T] { - match self { - ThinVec(None) => &[], - ThinVec(Some(vec)) => vec.as_slice(), - } - } -} - -impl From> for ThinVec { - fn from(vec: Vec) -> Self { - if vec.is_empty() { ThinVec(None) } else { ThinVec(Some(Box::new(vec))) } - } -} - -impl Into> for ThinVec { - fn into(self) -> Vec { - match self { - ThinVec(None) => Vec::new(), - ThinVec(Some(vec)) => *vec, - } - } -} - -impl ::std::ops::Deref for ThinVec { - type Target = [T]; - fn deref(&self) -> &[T] { - match *self { - ThinVec(None) => &[], - ThinVec(Some(ref vec)) => vec, - } - } -} - -impl ::std::ops::DerefMut for ThinVec { - fn deref_mut(&mut self) -> &mut [T] { - match *self { - ThinVec(None) => &mut [], - ThinVec(Some(ref mut vec)) => vec, - } - } -} - -impl FromIterator for ThinVec { - fn from_iter>(iter: I) -> Self { - // `Vec::from_iter()` should not allocate if the iterator is empty. - let vec: Vec<_> = iter.into_iter().collect(); - if vec.is_empty() { ThinVec(None) } else { ThinVec(Some(Box::new(vec))) } - } -} - -impl IntoIterator for ThinVec { - type Item = T; - type IntoIter = std::vec::IntoIter; - - fn into_iter(self) -> Self::IntoIter { - // This is still performant because `Vec::new()` does not allocate. - self.0.map_or_else(Vec::new, |ptr| *ptr).into_iter() - } -} - -impl<'a, T> IntoIterator for &'a ThinVec { - type Item = &'a T; - type IntoIter = std::slice::Iter<'a, T>; - - fn into_iter(self) -> Self::IntoIter { - self.as_ref().iter() - } -} - -impl<'a, T> IntoIterator for &'a mut ThinVec { - type Item = &'a mut T; - type IntoIter = std::slice::IterMut<'a, T>; - - fn into_iter(self) -> Self::IntoIter { - self.as_mut().iter_mut() - } -} - -impl Extend for ThinVec { - fn extend>(&mut self, iter: I) { - match *self { - ThinVec(Some(ref mut vec)) => vec.extend(iter), - ThinVec(None) => *self = iter.into_iter().collect::>().into(), - } - } - - fn extend_one(&mut self, item: T) { - self.push(item) - } - - fn extend_reserve(&mut self, additional: usize) { - match *self { - ThinVec(Some(ref mut vec)) => vec.reserve(additional), - ThinVec(None) => *self = Vec::with_capacity(additional).into(), - } - } -} - -impl, CTX> HashStable for ThinVec { - fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { - (**self).hash_stable(hcx, hasher) - } -} - -impl Default for ThinVec { - fn default() -> Self { - Self(None) - } -} - -#[cfg(test)] -mod tests; diff --git a/compiler/rustc_data_structures/src/thin_vec/tests.rs b/compiler/rustc_data_structures/src/thin_vec/tests.rs deleted file mode 100644 index 0221b9912bbdc..0000000000000 --- a/compiler/rustc_data_structures/src/thin_vec/tests.rs +++ /dev/null @@ -1,42 +0,0 @@ -use super::*; - -impl ThinVec { - fn into_vec(self) -> Vec { - self.into() - } -} - -#[test] -fn test_from_iterator() { - assert_eq!(std::iter::empty().collect::>().into_vec(), Vec::::new()); - assert_eq!(std::iter::once(42).collect::>().into_vec(), vec![42]); - assert_eq!([1, 2].into_iter().collect::>().into_vec(), vec![1, 2]); - assert_eq!([1, 2, 3].into_iter().collect::>().into_vec(), vec![1, 2, 3]); -} - -#[test] -fn test_into_iterator_owned() { - assert_eq!(ThinVec::new().into_iter().collect::>(), Vec::::new()); - assert_eq!(ThinVec::from(vec![1]).into_iter().collect::>(), vec![1]); - assert_eq!(ThinVec::from(vec![1, 2]).into_iter().collect::>(), vec![1, 2]); - assert_eq!(ThinVec::from(vec![1, 2, 3]).into_iter().collect::>(), vec![1, 2, 3]); -} - -#[test] -fn test_into_iterator_ref() { - assert_eq!(ThinVec::new().iter().collect::>(), Vec::<&String>::new()); - assert_eq!(ThinVec::from(vec![1]).iter().collect::>(), vec![&1]); - assert_eq!(ThinVec::from(vec![1, 2]).iter().collect::>(), vec![&1, &2]); - assert_eq!(ThinVec::from(vec![1, 2, 3]).iter().collect::>(), vec![&1, &2, &3]); -} - -#[test] -fn test_into_iterator_ref_mut() { - assert_eq!(ThinVec::new().iter_mut().collect::>(), Vec::<&mut String>::new()); - assert_eq!(ThinVec::from(vec![1]).iter_mut().collect::>(), vec![&mut 1]); - assert_eq!(ThinVec::from(vec![1, 2]).iter_mut().collect::>(), vec![&mut 1, &mut 2]); - assert_eq!( - ThinVec::from(vec![1, 2, 3]).iter_mut().collect::>(), - vec![&mut 1, &mut 2, &mut 3], - ); -} diff --git a/compiler/rustc_expand/Cargo.toml b/compiler/rustc_expand/Cargo.toml index 4ee7b6c42bbf5..192f54171cee6 100644 --- a/compiler/rustc_expand/Cargo.toml +++ b/compiler/rustc_expand/Cargo.toml @@ -8,20 +8,21 @@ build = false doctest = false [dependencies] -rustc_serialize = { path = "../rustc_serialize" } -tracing = "0.1" -rustc_span = { path = "../rustc_span" } -rustc_ast_pretty = { path = "../rustc_ast_pretty" } +crossbeam-channel = "0.5.0" rustc_ast_passes = { path = "../rustc_ast_passes" } +rustc_ast = { path = "../rustc_ast" } +rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_feature = { path = "../rustc_feature" } +rustc_lexer = { path = "../rustc_lexer" } rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_macros = { path = "../rustc_macros" } -rustc_lexer = { path = "../rustc_lexer" } rustc_parse = { path = "../rustc_parse" } +rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } +rustc_span = { path = "../rustc_span" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } -rustc_ast = { path = "../rustc_ast" } -crossbeam-channel = "0.5.0" +thin-vec = "0.2.8" +tracing = "0.1" diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 2bb522caa2d41..bed025dbd40ff 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -22,11 +22,11 @@ use rustc_span::source_map::SourceMap; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{FileName, Span, DUMMY_SP}; use smallvec::{smallvec, SmallVec}; - use std::default::Default; use std::iter; use std::path::PathBuf; use std::rc::Rc; +use thin_vec::ThinVec; pub(crate) use rustc_span::hygiene::MacroKind; @@ -546,7 +546,7 @@ impl DummyResult { pub fn raw_expr(sp: Span, is_error: bool) -> P { P(ast::Expr { id: ast::DUMMY_NODE_ID, - kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) }, + kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(ThinVec::new()) }, span: sp, attrs: ast::AttrVec::new(), tokens: None, @@ -562,7 +562,7 @@ impl DummyResult { pub fn raw_ty(sp: Span, is_error: bool) -> P { P(ast::Ty { id: ast::DUMMY_NODE_ID, - kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) }, + kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(ThinVec::new()) }, span: sp, tokens: None, }) diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index c4890b4a9c413..8626eb084fa26 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -1,13 +1,12 @@ use crate::base::ExtCtxt; - use rustc_ast::attr; use rustc_ast::ptr::P; use rustc_ast::{self as ast, AttrVec, BlockCheckMode, Expr, LocalKind, PatKind, UnOp}; use rustc_data_structures::sync::Lrc; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident, Symbol}; - use rustc_span::Span; +use thin_vec::{thin_vec, ThinVec}; impl<'a> ExtCtxt<'a> { pub fn path(&self, span: Span, strs: Vec) -> ast::Path { @@ -28,7 +27,7 @@ impl<'a> ExtCtxt<'a> { ) -> ast::Path { assert!(!idents.is_empty()); let add_root = global && !idents[0].is_path_segment_keyword(); - let mut segments = Vec::with_capacity(idents.len() + add_root as usize); + let mut segments = ThinVec::with_capacity(idents.len() + add_root as usize); if add_root { segments.push(ast::PathSegment::path_root(span)); } @@ -127,7 +126,7 @@ impl<'a> ExtCtxt<'a> { pub fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef { ast::PolyTraitRef { - bound_generic_params: Vec::new(), + bound_generic_params: ThinVec::new(), trait_ref: self.trait_ref(path), span, } @@ -275,18 +274,23 @@ impl<'a> ExtCtxt<'a> { &self, span: Span, expr: P, - args: Vec>, + args: ThinVec>, ) -> P { self.expr(span, ast::ExprKind::Call(expr, args)) } - pub fn expr_call_ident(&self, span: Span, id: Ident, args: Vec>) -> P { + pub fn expr_call_ident( + &self, + span: Span, + id: Ident, + args: ThinVec>, + ) -> P { self.expr(span, ast::ExprKind::Call(self.expr_ident(span, id), args)) } pub fn expr_call_global( &self, sp: Span, fn_path: Vec, - args: Vec>, + args: ThinVec>, ) -> P { let pathexpr = self.expr_path(self.path_global(sp, fn_path)); self.expr_call(sp, pathexpr, args) @@ -378,14 +382,14 @@ impl<'a> ExtCtxt<'a> { pub fn expr_some(&self, sp: Span, expr: P) -> P { let some = self.std_path(&[sym::option, sym::Option, sym::Some]); - self.expr_call_global(sp, some, vec![expr]) + self.expr_call_global(sp, some, thin_vec![expr]) } pub fn expr_none(&self, sp: Span) -> P { let none = self.std_path(&[sym::option, sym::Option, sym::None]); self.expr_path(self.path_global(sp, none)) } - pub fn expr_tuple(&self, sp: Span, exprs: Vec>) -> P { + pub fn expr_tuple(&self, sp: Span, exprs: ThinVec>) -> P { self.expr(sp, ast::ExprKind::Tup(exprs)) } @@ -393,7 +397,7 @@ impl<'a> ExtCtxt<'a> { self.expr_call_global( span, [sym::std, sym::rt, sym::begin_panic].iter().map(|s| Ident::new(*s, span)).collect(), - vec![self.expr_str(span, msg)], + thin_vec![self.expr_str(span, msg)], ) } @@ -403,7 +407,7 @@ impl<'a> ExtCtxt<'a> { pub fn expr_ok(&self, sp: Span, expr: P) -> P { let ok = self.std_path(&[sym::result, sym::Result, sym::Ok]); - self.expr_call_global(sp, ok, vec![expr]) + self.expr_call_global(sp, ok, thin_vec![expr]) } pub fn expr_try(&self, sp: Span, head: P) -> P { @@ -417,12 +421,12 @@ impl<'a> ExtCtxt<'a> { let binding_expr = self.expr_ident(sp, binding_variable); // `Ok(__try_var)` pattern - let ok_pat = self.pat_tuple_struct(sp, ok_path, vec![binding_pat.clone()]); + let ok_pat = self.pat_tuple_struct(sp, ok_path, thin_vec![binding_pat.clone()]); // `Err(__try_var)` (pattern and expression respectively) - let err_pat = self.pat_tuple_struct(sp, err_path.clone(), vec![binding_pat]); + let err_pat = self.pat_tuple_struct(sp, err_path.clone(), thin_vec![binding_pat]); let err_inner_expr = - self.expr_call(sp, self.expr_path(err_path), vec![binding_expr.clone()]); + self.expr_call(sp, self.expr_path(err_path), thin_vec![binding_expr.clone()]); // `return Err(__try_var)` let err_expr = self.expr(sp, ast::ExprKind::Ret(Some(err_inner_expr))); @@ -465,7 +469,7 @@ impl<'a> ExtCtxt<'a> { &self, span: Span, path: ast::Path, - subpats: Vec>, + subpats: ThinVec>, ) -> P { self.pat(span, PatKind::TupleStruct(None, path, subpats)) } @@ -477,14 +481,14 @@ impl<'a> ExtCtxt<'a> { ) -> P { self.pat(span, PatKind::Struct(None, path, field_pats, false)) } - pub fn pat_tuple(&self, span: Span, pats: Vec>) -> P { + pub fn pat_tuple(&self, span: Span, pats: ThinVec>) -> P { self.pat(span, PatKind::Tuple(pats)) } pub fn pat_some(&self, span: Span, pat: P) -> P { let some = self.std_path(&[sym::option, sym::Option, sym::Some]); let path = self.path_global(span, some); - self.pat_tuple_struct(span, path, vec![pat]) + self.pat_tuple_struct(span, path, thin_vec![pat]) } pub fn arm(&self, span: Span, pat: P, expr: P) -> ast::Arm { @@ -567,7 +571,7 @@ impl<'a> ExtCtxt<'a> { } // `self` is unused but keep it as method for the convenience use. - pub fn fn_decl(&self, inputs: Vec, output: ast::FnRetTy) -> P { + pub fn fn_decl(&self, inputs: ThinVec, output: ast::FnRetTy) -> P { P(ast::FnDecl { inputs, output }) } diff --git a/compiler/rustc_expand/src/placeholders.rs b/compiler/rustc_expand/src/placeholders.rs index 3b0d5ddb97b4e..921d869d1abd5 100644 --- a/compiler/rustc_expand/src/placeholders.rs +++ b/compiler/rustc_expand/src/placeholders.rs @@ -1,14 +1,12 @@ use crate::expand::{AstFragment, AstFragmentKind}; - use rustc_ast as ast; use rustc_ast::mut_visit::*; use rustc_ast::ptr::P; +use rustc_data_structures::fx::FxHashMap; use rustc_span::source_map::DUMMY_SP; use rustc_span::symbol::Ident; - use smallvec::{smallvec, SmallVec}; - -use rustc_data_structures::fx::FxHashMap; +use thin_vec::ThinVec; pub fn placeholder( kind: AstFragmentKind, @@ -17,7 +15,7 @@ pub fn placeholder( ) -> AstFragment { fn mac_placeholder() -> P { P(ast::MacCall { - path: ast::Path { span: DUMMY_SP, segments: Vec::new(), tokens: None }, + path: ast::Path { span: DUMMY_SP, segments: ThinVec::new(), tokens: None }, args: P(ast::MacArgs::Empty), prior_type_ascription: None, }) diff --git a/compiler/rustc_incremental/Cargo.toml b/compiler/rustc_incremental/Cargo.toml index d3c425a072bce..c3a03a178d300 100644 --- a/compiler/rustc_incremental/Cargo.toml +++ b/compiler/rustc_incremental/Cargo.toml @@ -7,16 +7,17 @@ edition = "2021" doctest = false [dependencies] -rustc_graphviz = { path = "../rustc_graphviz" } -tracing = "0.1" rand = "0.8.4" -rustc_middle = { path = "../rustc_middle" } +rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } +rustc_errors = { path = "../rustc_errors" } +rustc_fs_util = { path = "../rustc_fs_util" } +rustc_graphviz = { path = "../rustc_graphviz" } rustc_hir = { path = "../rustc_hir" } -rustc_serialize = { path = "../rustc_serialize" } -rustc_ast = { path = "../rustc_ast" } rustc_macros = { path = "../rustc_macros" } -rustc_span = { path = "../rustc_span" } -rustc_fs_util = { path = "../rustc_fs_util" } +rustc_middle = { path = "../rustc_middle" } +rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } -rustc_errors = { path = "../rustc_errors" } +rustc_span = { path = "../rustc_span" } +thin-vec = "0.2.8" +tracing = "0.1" diff --git a/compiler/rustc_incremental/src/assert_module_sources.rs b/compiler/rustc_incremental/src/assert_module_sources.rs index 89d419bc8e90f..f478bd44c67b9 100644 --- a/compiler/rustc_incremental/src/assert_module_sources.rs +++ b/compiler/rustc_incremental/src/assert_module_sources.rs @@ -29,6 +29,7 @@ use rustc_middle::mir::mono::CodegenUnitNameBuilder; use rustc_middle::ty::TyCtxt; use rustc_session::cgu_reuse_tracker::*; use rustc_span::symbol::{sym, Symbol}; +use thin_vec::ThinVec; #[allow(missing_docs)] pub fn assert_module_sources(tcx: TyCtxt<'_>) { @@ -146,7 +147,7 @@ impl<'tcx> AssertModuleSource<'tcx> { } fn field(&self, attr: &ast::Attribute, name: Symbol) -> Symbol { - for item in attr.meta_item_list().unwrap_or_else(Vec::new) { + for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { if item.has_name(name) { if let Some(value) = item.value_str() { return value; diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 710c4a01b244f..e4ff1fcafcc13 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -31,7 +31,7 @@ use rustc_middle::ty::TyCtxt; use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; use std::iter::FromIterator; -use std::vec::Vec; +use thin_vec::ThinVec; const LOADED_FROM_DISK: Symbol = sym::loaded_from_disk; const EXCEPT: Symbol = sym::except; @@ -210,7 +210,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { /// `loaded_from_disk=` attribute value fn loaded_from_disk(&self, attr: &Attribute) -> Labels { - for item in attr.meta_item_list().unwrap_or_else(Vec::new) { + for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { if item.has_name(LOADED_FROM_DISK) { let value = expect_associated_value(self.tcx, &item); return self.resolve_labels(&item, value); @@ -222,7 +222,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { /// `except=` attribute value fn except(&self, attr: &Attribute) -> Labels { - for item in attr.meta_item_list().unwrap_or_else(Vec::new) { + for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { if item.has_name(EXCEPT) { let value = expect_associated_value(self.tcx, &item); return self.resolve_labels(&item, value); @@ -408,7 +408,7 @@ fn check_config(tcx: TyCtxt<'_>, attr: &Attribute) -> bool { let config = &tcx.sess.parse_sess.config; debug!("check_config: config={:?}", config); let mut cfg = None; - for item in attr.meta_item_list().unwrap_or_else(Vec::new) { + for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { if item.has_name(CFG) { let value = expect_associated_value(tcx, &item); debug!("check_config: searching for cfg {:?}", value); diff --git a/compiler/rustc_middle/Cargo.toml b/compiler/rustc_middle/Cargo.toml index 008d2c7091c1e..cca17a4eccd3a 100644 --- a/compiler/rustc_middle/Cargo.toml +++ b/compiler/rustc_middle/Cargo.toml @@ -7,34 +7,35 @@ edition = "2021" doctest = false [dependencies] -rustc_arena = { path = "../rustc_arena" } bitflags = "1.2.1" +chalk-ir = "0.80.0" either = "1.5.0" gsgdt = "0.1.2" -tracing = "0.1" -rustc-rayon = { version = "0.4.0", optional = true } -rustc-rayon-core = { version = "0.4.0", optional = true } polonius-engine = "0.13.0" +rand = "0.8.4" +rand_xoshiro = "0.6.0" rustc_apfloat = { path = "../rustc_apfloat" } +rustc_arena = { path = "../rustc_arena" } +rustc_ast = { path = "../rustc_ast" } rustc_attr = { path = "../rustc_attr" } -rustc_feature = { path = "../rustc_feature" } -rustc_hir = { path = "../rustc_hir" } -rustc_target = { path = "../rustc_target" } -rustc_macros = { path = "../rustc_macros" } rustc_data_structures = { path = "../rustc_data_structures" } -rustc_query_system = { path = "../rustc_query_system" } rustc_errors = { path = "../rustc_errors" } +rustc_feature = { path = "../rustc_feature" } rustc_graphviz = { path = "../rustc_graphviz" } +rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } +rustc_macros = { path = "../rustc_macros" } +rustc_query_system = { path = "../rustc_query_system" } +rustc-rayon-core = { version = "0.4.0", optional = true } +rustc-rayon = { version = "0.4.0", optional = true } rustc_serialize = { path = "../rustc_serialize" } -rustc_ast = { path = "../rustc_ast" } -rustc_span = { path = "../rustc_span" } -chalk-ir = "0.80.0" -smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } rustc_session = { path = "../rustc_session" } +rustc_span = { path = "../rustc_span" } +rustc_target = { path = "../rustc_target" } rustc_type_ir = { path = "../rustc_type_ir" } -rand = "0.8.4" -rand_xoshiro = "0.6.0" +smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } +thin-vec = "0.2.8" +tracing = "0.1" [features] rustc_use_parallel_compiler = ["rustc-rayon", "rustc-rayon-core"] diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 0a0f45ce1a0d2..be6efdab1341a 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1829,9 +1829,9 @@ pub mod tls { use crate::dep_graph::TaskDepsRef; use crate::ty::query; use rustc_data_structures::sync::{self, Lock}; - use rustc_data_structures::thin_vec::ThinVec; use rustc_errors::Diagnostic; use std::mem; + use thin_vec::ThinVec; #[cfg(not(parallel_compiler))] use std::cell::Cell; diff --git a/compiler/rustc_parse/Cargo.toml b/compiler/rustc_parse/Cargo.toml index c6ca260e9831e..0423b4ad557d9 100644 --- a/compiler/rustc_parse/Cargo.toml +++ b/compiler/rustc_parse/Cargo.toml @@ -8,15 +8,16 @@ doctest = false [dependencies] bitflags = "1.0" -tracing = "0.1" +rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_data_structures = { path = "../rustc_data_structures" } +rustc_errors = { path = "../rustc_errors" } rustc_feature = { path = "../rustc_feature" } rustc_lexer = { path = "../rustc_lexer" } rustc_macros = { path = "../rustc_macros" } -rustc_errors = { path = "../rustc_errors" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } -rustc_ast = { path = "../rustc_ast" } +thin-vec = "0.2.8" +tracing = "0.1" unicode-normalization = "0.1.11" unicode-width = "0.1.4" diff --git a/compiler/rustc_parse/src/parser/attr.rs b/compiler/rustc_parse/src/parser/attr.rs index 72ab96b5ca670..b8bdbfa8ffefd 100644 --- a/compiler/rustc_parse/src/parser/attr.rs +++ b/compiler/rustc_parse/src/parser/attr.rs @@ -6,7 +6,7 @@ use rustc_ast_pretty::pprust; use rustc_errors::{error_code, Diagnostic, PResult}; use rustc_span::{sym, BytePos, Span}; use std::convert::TryInto; - +use thin_vec::ThinVec; use tracing::debug; // Public for rustfmt usage @@ -357,9 +357,9 @@ impl<'a> Parser<'a> { } /// Matches `COMMASEP(meta_item_inner)`. - pub(crate) fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec> { + pub(crate) fn parse_meta_seq_top(&mut self) -> PResult<'a, ThinVec> { // Presumably, the majority of the time there will only be one attr. - let mut nmis = Vec::with_capacity(1); + let mut nmis = ThinVec::with_capacity(1); while self.token.kind != token::Eof { nmis.push(self.parse_meta_item_inner()?); if !self.eat(&token::Comma) { diff --git a/compiler/rustc_parse/src/parser/attr_wrapper.rs b/compiler/rustc_parse/src/parser/attr_wrapper.rs index ed54af9f53fb7..d6a32d888bdbd 100644 --- a/compiler/rustc_parse/src/parser/attr_wrapper.rs +++ b/compiler/rustc_parse/src/parser/attr_wrapper.rs @@ -355,7 +355,7 @@ impl<'a> Parser<'a> { && matches!(self.capture_state.capturing, Capturing::Yes) && has_cfg_or_cfg_attr(final_attrs) { - let attr_data = AttributesData { attrs: final_attrs.to_vec().into(), tokens }; + let attr_data = AttributesData { attrs: final_attrs.iter().cloned().collect(), tokens }; // Replace the entire AST node that we just parsed, including attributes, // with a `FlatToken::AttrTarget`. If this AST node is inside an item diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index b8884dd32d621..befc6212f40b6 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -5,6 +5,7 @@ use super::{ }; use crate::lexer::UnmatchedBrace; +use crate::parser; use rustc_ast as ast; use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter, Lit, LitKind, TokenKind}; @@ -24,11 +25,9 @@ use rustc_macros::{SessionDiagnostic, SessionSubdiagnostic}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, Ident}; use rustc_span::{Span, SpanSnippetError, DUMMY_SP}; -use std::ops::{Deref, DerefMut}; - use std::mem::take; - -use crate::parser; +use std::ops::{Deref, DerefMut}; +use thin_vec::{thin_vec, ThinVec}; use tracing::{debug, trace}; const TURBOFISH_SUGGESTION_STR: &str = @@ -1115,8 +1114,11 @@ impl<'a> Parser<'a> { // field: value, // } let mut snapshot = self.create_snapshot_for_diagnostic(); - let path = - Path { segments: vec![], span: self.prev_token.span.shrink_to_lo(), tokens: None }; + let path = Path { + segments: ThinVec::new(), + span: self.prev_token.span.shrink_to_lo(), + tokens: None, + }; let struct_expr = snapshot.parse_struct_expr(None, path, false); let block_tail = self.parse_block_tail(lo, s, AttemptLocalParseRecovery::No); return Some(match (struct_expr, block_tail) { @@ -1923,7 +1925,7 @@ impl<'a> Parser<'a> { ) -> PResult<'a, P> { self.expect(&token::ModSep)?; - let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP, tokens: None }; + let mut path = ast::Path { segments: ThinVec::new(), span: DUMMY_SP, tokens: None }; self.parse_path_segments(&mut path.segments, T::PATH_STYLE, None)?; path.span = ty_span.to(self.prev_token.span); @@ -2622,7 +2624,7 @@ impl<'a> Parser<'a> { /// the parameters are *names* (so we don't emit errors about not being able to find `b` in /// the local scope), but if we find the same name multiple times, like in `fn foo(i8, i8)`, /// we deduplicate them to not complain about duplicated parameter names. - pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec) { + pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut ThinVec) { let mut seen_inputs = FxHashSet::default(); for input in fn_inputs.iter_mut() { let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) = @@ -2965,7 +2967,7 @@ impl<'a> Parser<'a> { None, Path { span: new_span, - segments: vec![ + segments: thin_vec![ PathSegment::from_ident(*old_ident), PathSegment::from_ident(*ident), ], diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 17117cbc8fbe6..fb6cb7a254c35 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -42,6 +42,7 @@ use rustc_session::SessionDiagnostic; use rustc_span::source_map::{self, Span, Spanned}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{BytePos, Pos}; +use thin_vec::ThinVec; /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression /// dropped into the token stream, which happens while parsing the result of @@ -135,7 +136,7 @@ impl<'a> Parser<'a> { } /// Parses a sequence of expressions delimited by parentheses. - fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec>> { + fn parse_paren_expr_seq(&mut self) -> PResult<'a, ThinVec>> { self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r) } @@ -944,13 +945,18 @@ impl<'a> Parser<'a> { // Stitch the list of outer attributes onto the return value. // A little bit ugly, but the best way given the current code // structure - self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| { - expr.map(|mut expr| { - attrs.extend(expr.attrs); - expr.attrs = attrs; - expr + let res = self.parse_dot_or_call_expr_with_(e0, lo); + if attrs.is_empty() { + res + } else { + res.map(|expr| { + expr.map(|mut expr| { + attrs.extend(expr.attrs); + expr.attrs = attrs; + expr + }) }) - }) + } } fn parse_dot_or_call_expr_with_(&mut self, mut e: P, lo: Span) -> PResult<'a, P> { @@ -2046,7 +2052,7 @@ impl<'a> Parser<'a> { self.sess.gated_spans.gate(sym::closure_lifetime_binder, span); - ClosureBinder::For { span, generic_params: P::from_vec(lifetime_defs) } + ClosureBinder::For { span, generic_params: lifetime_defs } } else { ClosureBinder::NotPresent }; @@ -2130,7 +2136,7 @@ impl<'a> Parser<'a> { /// Parses the `|arg, arg|` header of a closure. fn parse_fn_block_decl(&mut self) -> PResult<'a, P> { let inputs = if self.eat(&token::OrOr) { - Vec::new() + ThinVec::new() } else { self.expect(&token::BinOp(token::Or))?; let args = self @@ -3070,7 +3076,7 @@ impl<'a> Parser<'a> { ExprKind::Index(expr, idx) } - fn mk_call(&self, f: P, args: Vec>) -> ExprKind { + fn mk_call(&self, f: P, args: ThinVec>) -> ExprKind { ExprKind::Call(f, args) } diff --git a/compiler/rustc_parse/src/parser/generics.rs b/compiler/rustc_parse/src/parser/generics.rs index 4d0a8b05eb027..bda1c2012093b 100644 --- a/compiler/rustc_parse/src/parser/generics.rs +++ b/compiler/rustc_parse/src/parser/generics.rs @@ -4,6 +4,7 @@ use rustc_ast::token; use rustc_ast::{self as ast, AttrVec, GenericBounds, GenericParam, GenericParamKind, WhereClause}; use rustc_errors::{Applicability, PResult}; use rustc_span::symbol::kw; +use thin_vec::ThinVec; impl<'a> Parser<'a> { /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. @@ -76,8 +77,8 @@ impl<'a> Parser<'a> { /// Parses a (possibly empty) list of lifetime and type parameters, possibly including /// a trailing comma and erroneous trailing attributes. - pub(super) fn parse_generic_params(&mut self) -> PResult<'a, Vec> { - let mut params = Vec::new(); + pub(super) fn parse_generic_params(&mut self) -> PResult<'a, ThinVec> { + let mut params = ThinVec::new(); let mut done = false; while !done { let attrs = self.parse_outer_attributes()?; @@ -195,13 +196,13 @@ impl<'a> Parser<'a> { self.expect_gt()?; (params, span_lo.to(self.prev_token.span)) } else { - (vec![], self.prev_token.span.shrink_to_hi()) + (ThinVec::new(), self.prev_token.span.shrink_to_hi()) }; Ok(ast::Generics { params, where_clause: WhereClause { has_where_token: false, - predicates: Vec::new(), + predicates: ThinVec::new(), span: self.prev_token.span.shrink_to_hi(), }, span, @@ -216,7 +217,7 @@ impl<'a> Parser<'a> { pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> { let mut where_clause = WhereClause { has_where_token: false, - predicates: Vec::new(), + predicates: ThinVec::new(), span: self.prev_token.span.shrink_to_hi(), }; diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index b743162a7e4d0..197117165f2f6 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -19,9 +19,9 @@ use rustc_span::lev_distance::lev_distance; use rustc_span::source_map::{self, Span}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::DUMMY_SP; - use std::convert::TryFrom; use std::mem; +use thin_vec::ThinVec; use tracing::debug; impl<'a> Parser<'a> { @@ -663,12 +663,12 @@ impl<'a> Parser<'a> { &mut self, attrs: &mut AttrVec, mut parse_item: impl FnMut(&mut Parser<'a>) -> PResult<'a, Option>>, - ) -> PResult<'a, Vec> { + ) -> PResult<'a, ThinVec> { let open_brace_span = self.token.span; self.expect(&token::OpenDelim(Delimiter::Brace))?; attrs.extend(self.parse_inner_attributes()?); - let mut items = Vec::new(); + let mut items = ThinVec::new(); while !self.eat(&token::CloseDelim(Delimiter::Brace)) { if self.recover_doc_comment_before_brace() { continue; @@ -930,7 +930,8 @@ impl<'a> Parser<'a> { fn parse_use_tree(&mut self) -> PResult<'a, UseTree> { let lo = self.token.span; - let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None }; + let mut prefix = + ast::Path { segments: ThinVec::new(), span: lo.shrink_to_lo(), tokens: None }; let kind = if self.check(&token::OpenDelim(Delimiter::Brace)) || self.check(&token::BinOp(token::Star)) || self.is_import_coupler() @@ -972,7 +973,7 @@ impl<'a> Parser<'a> { /// ```text /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`] /// ``` - fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> { + fn parse_use_tree_list(&mut self) -> PResult<'a, ThinVec<(UseTree, ast::NodeId)>> { self.parse_delim_comma_seq(Delimiter::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID))) .map(|(r, _)| r) } @@ -1437,8 +1438,8 @@ impl<'a> Parser<'a> { &mut self, adt_ty: &str, parsed_where: bool, - ) -> PResult<'a, (Vec, /* recovered */ bool)> { - let mut fields = Vec::new(); + ) -> PResult<'a, (ThinVec, /* recovered */ bool)> { + let mut fields = ThinVec::new(); let mut recovered = false; if self.eat(&token::OpenDelim(Delimiter::Brace)) { while self.token != token::CloseDelim(Delimiter::Brace) { @@ -1477,7 +1478,7 @@ impl<'a> Parser<'a> { Ok((fields, recovered)) } - fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec> { + fn parse_tuple_struct_body(&mut self) -> PResult<'a, ThinVec> { // This is the case where we find `struct Foo(T) where T: Copy;` // Unit like structs are handled in parse_item_struct function self.parse_paren_comma_seq(|p| { @@ -2250,7 +2251,7 @@ impl<'a> Parser<'a> { } /// Parses the parameter list of a function, including the `(` and `)` delimiters. - fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec> { + fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, ThinVec> { let mut first_param = true; // Parse the arguments, starting out with `self` being allowed... let (mut params, _) = self.parse_paren_comma_seq(|p| { diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index f6516d3bd4543..1ff17bb9c169a 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -37,10 +37,10 @@ use rustc_errors::{ use rustc_session::parse::ParseSess; use rustc_span::source_map::{Span, DUMMY_SP}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use tracing::debug; - use std::ops::Range; use std::{cmp, mem, slice}; +use thin_vec::ThinVec; +use tracing::debug; bitflags::bitflags! { struct Restrictions: u8 { @@ -755,11 +755,11 @@ impl<'a> Parser<'a> { sep: SeqSep, expect: TokenExpectType, mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { + ) -> PResult<'a, (ThinVec, bool /* trailing */, bool /* recovered */)> { let mut first = true; let mut recovered = false; let mut trailing = false; - let mut v = vec![]; + let mut v = ThinVec::new(); let unclosed_delims = !self.unclosed_delims.is_empty(); while !self.expect_any_with_type(kets, expect) { @@ -935,7 +935,7 @@ impl<'a> Parser<'a> { ket: &TokenKind, sep: SeqSep, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, bool, bool)> { + ) -> PResult<'a, (ThinVec, bool, bool)> { self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) } @@ -947,7 +947,7 @@ impl<'a> Parser<'a> { ket: &TokenKind, sep: SeqSep, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, bool /* trailing */)> { + ) -> PResult<'a, (ThinVec, bool /* trailing */)> { let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; if !recovered { self.eat(ket); @@ -964,7 +964,7 @@ impl<'a> Parser<'a> { ket: &TokenKind, sep: SeqSep, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, bool)> { + ) -> PResult<'a, (ThinVec, bool)> { self.expect(bra)?; self.parse_seq_to_end(ket, sep, f) } @@ -973,7 +973,7 @@ impl<'a> Parser<'a> { &mut self, delim: Delimiter, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, bool)> { + ) -> PResult<'a, (ThinVec, bool)> { self.parse_unspanned_seq( &token::OpenDelim(delim), &token::CloseDelim(delim), @@ -985,7 +985,7 @@ impl<'a> Parser<'a> { fn parse_paren_comma_seq( &mut self, f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, - ) -> PResult<'a, (Vec, bool)> { + ) -> PResult<'a, (ThinVec, bool)> { self.parse_delim_comma_seq(Delimiter::Parenthesis, f) } diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 8b3200d45fccd..b2690595d2874 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -11,6 +11,7 @@ use rustc_ast_pretty::pprust; use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult}; use rustc_span::source_map::{respan, Span, Spanned}; use rustc_span::symbol::{kw, sym, Ident}; +use thin_vec::thin_vec; pub(super) type Expected = Option<&'static str>; @@ -121,7 +122,7 @@ impl<'a> Parser<'a> { // If there was a leading vert, treat this as an or-pattern. This improves // diagnostics. let span = leading_vert_span.to(self.prev_token.span); - return Ok((self.mk_pat(span, PatKind::Or(vec![first_pat])), trailing_vert)); + return Ok((self.mk_pat(span, PatKind::Or(thin_vec![first_pat])), trailing_vert)); } return Ok((first_pat, trailing_vert)); @@ -129,7 +130,7 @@ impl<'a> Parser<'a> { // Parse the patterns `p_1 | ... | p_n` where `n > 0`. let lo = leading_vert_span.unwrap_or(first_pat.span); - let mut pats = vec![first_pat]; + let mut pats = thin_vec![first_pat]; loop { match self.eat_or_separator(Some(lo)) { EatOrResult::AteOr => {} diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index fc7fb866f110f..f673f307df415 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -11,8 +11,8 @@ use rustc_ast::{ use rustc_errors::{pluralize, Applicability, PResult}; use rustc_span::source_map::{BytePos, Span}; use rustc_span::symbol::{kw, sym, Ident}; - use std::mem; +use thin_vec::ThinVec; use tracing::debug; /// Specifies how to parse a path. @@ -64,7 +64,7 @@ impl<'a> Parser<'a> { path_span = path_lo.to(self.prev_token.span); } else { path_span = self.token.span.to(self.token.span); - path = ast::Path { segments: Vec::new(), span: path_span, tokens: None }; + path = ast::Path { segments: ThinVec::new(), span: path_span, tokens: None }; } // See doc comment for `unmatched_angle_bracket_count`. @@ -180,7 +180,7 @@ impl<'a> Parser<'a> { } let lo = self.token.span; - let mut segments = Vec::new(); + let mut segments = ThinVec::new(); let mod_sep_ctxt = self.token.span.ctxt(); if self.eat(&token::ModSep) { segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))); @@ -192,7 +192,7 @@ impl<'a> Parser<'a> { pub(super) fn parse_path_segments( &mut self, - segments: &mut Vec, + segments: &mut ThinVec, style: PathStyle, ty_generics: Option<&Generics>, ) -> PResult<'a, ()> { diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index 4a2cf74905bf5..f5ce72cfd89cd 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -11,6 +11,7 @@ use rustc_ast::{ use rustc_errors::{pluralize, struct_span_err, Applicability, PResult}; use rustc_span::source_map::Span; use rustc_span::symbol::{kw, sym}; +use thin_vec::ThinVec; /// Any `?` or `~const` modifiers that appear at the start of a bound. struct BoundModifiers { @@ -269,7 +270,7 @@ impl<'a> Parser<'a> { TyKind::Infer } else if self.check_fn_front_matter(false) { // Function pointer type - self.parse_ty_bare_fn(lo, Vec::new(), recover_return_sign)? + self.parse_ty_bare_fn(lo, ThinVec::new(), recover_return_sign)? } else if self.check_keyword(kw::For) { // Function pointer type or bound list (trait object type) starting with a poly-trait. // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T` @@ -343,7 +344,7 @@ impl<'a> Parser<'a> { match ty.kind { // `(TY_BOUND_NOPAREN) + BOUND + ...`. TyKind::Path(None, path) if maybe_bounds => { - self.parse_remaining_bounds_path(Vec::new(), path, lo, true) + self.parse_remaining_bounds_path(ThinVec::new(), path, lo, true) } TyKind::TraitObject(bounds, TraitObjectSyntax::None) if maybe_bounds && bounds.len() == 1 && !trailing_plus => @@ -370,7 +371,7 @@ impl<'a> Parser<'a> { fn parse_remaining_bounds_path( &mut self, - generic_params: Vec, + generic_params: ThinVec, path: ast::Path, lo: Span, parse_plus: bool, @@ -515,7 +516,7 @@ impl<'a> Parser<'a> { fn parse_ty_bare_fn( &mut self, lo: Span, - params: Vec, + params: ThinVec, recover_return_sign: RecoverReturnSign, ) -> PResult<'a, TyKind> { let inherited_vis = rustc_ast::Visibility { @@ -605,7 +606,7 @@ impl<'a> Parser<'a> { }))) } else if allow_plus == AllowPlus::Yes && self.check_plus() { // `Trait1 + Trait2 + 'a` - self.parse_remaining_bounds_path(Vec::new(), path, lo, true) + self.parse_remaining_bounds_path(ThinVec::new(), path, lo, true) } else { // Just a type path. Ok(TyKind::Path(None, path)) @@ -877,7 +878,7 @@ impl<'a> Parser<'a> { } /// Optionally parses `for<$generic_params>`. - pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec> { + pub(super) fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, ThinVec> { if self.eat_keyword(kw::For) { self.expect_lt()?; let params = self.parse_generic_params()?; @@ -886,7 +887,7 @@ impl<'a> Parser<'a> { // parameters, and the lifetime parameters must not have bounds. Ok(params) } else { - Ok(Vec::new()) + Ok(ThinVec::new()) } } diff --git a/compiler/rustc_query_impl/Cargo.toml b/compiler/rustc_query_impl/Cargo.toml index c37ae4f32536b..e7f12caaf33e5 100644 --- a/compiler/rustc_query_impl/Cargo.toml +++ b/compiler/rustc_query_impl/Cargo.toml @@ -8,7 +8,6 @@ doctest = false [dependencies] measureme = "10.0.0" -rustc-rayon-core = { version = "0.4.0", optional = true } rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } @@ -17,10 +16,12 @@ rustc_index = { path = "../rustc_index" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } rustc_query_system = { path = "../rustc_query_system" } +rustc-rayon-core = { version = "0.4.0", optional = true } rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } +thin-vec = "0.2.8" tracing = "0.1" [features] diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 339683cf68958..a39b87fc30ed7 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -3,18 +3,16 @@ //! manage the caches, and so forth. use crate::{on_disk_cache, Queries}; +use rustc_data_structures::sync::Lock; +use rustc_errors::{Diagnostic, Handler}; use rustc_middle::dep_graph::{DepNodeIndex, SerializedDepNodeIndex}; use rustc_middle::ty::tls::{self, ImplicitCtxt}; use rustc_middle::ty::TyCtxt; use rustc_query_system::dep_graph::HasDepContext; use rustc_query_system::query::{QueryContext, QueryJobId, QueryMap, QuerySideEffects}; - -use rustc_data_structures::sync::Lock; -use rustc_data_structures::thin_vec::ThinVec; -use rustc_errors::{Diagnostic, Handler}; - use std::any::Any; use std::num::NonZeroU64; +use thin_vec::ThinVec; #[derive(Copy, Clone)] pub struct QueryCtxt<'tcx> { diff --git a/compiler/rustc_query_system/Cargo.toml b/compiler/rustc_query_system/Cargo.toml index b7787aeb8f765..bafc6b0a08233 100644 --- a/compiler/rustc_query_system/Cargo.toml +++ b/compiler/rustc_query_system/Cargo.toml @@ -7,9 +7,8 @@ edition = "2021" doctest = false [dependencies] +parking_lot = "0.11" rustc_arena = { path = "../rustc_arena" } -tracing = "0.1" -rustc-rayon-core = { version = "0.4.0", optional = true } rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } @@ -17,12 +16,14 @@ rustc_feature = { path = "../rustc_feature" } rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } rustc_macros = { path = "../rustc_macros" } +rustc-rayon-core = { version = "0.4.0", optional = true } rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } -parking_lot = "0.11" smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } +thin-vec = "0.2.8" +tracing = "0.1" [features] rustc_use_parallel_compiler = ["rustc-rayon-core"] diff --git a/compiler/rustc_query_system/src/query/mod.rs b/compiler/rustc_query_system/src/query/mod.rs index fb2258434f4d3..6df62512a226e 100644 --- a/compiler/rustc_query_system/src/query/mod.rs +++ b/compiler/rustc_query_system/src/query/mod.rs @@ -15,12 +15,11 @@ mod config; pub use self::config::{QueryConfig, QueryDescription, QueryVTable}; use crate::dep_graph::{DepNodeIndex, HasDepContext, SerializedDepNodeIndex}; - use rustc_data_structures::sync::Lock; -use rustc_data_structures::thin_vec::ThinVec; use rustc_errors::Diagnostic; use rustc_hir::def::DefKind; use rustc_span::Span; +use thin_vec::ThinVec; /// Description of a frame in the query stack. /// diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 5e8ea07d00f99..821bf3292e3d3 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -14,7 +14,6 @@ use rustc_data_structures::profiling::TimingGuard; #[cfg(parallel_compiler)] use rustc_data_structures::sharded::Sharded; use rustc_data_structures::sync::Lock; -use rustc_data_structures::thin_vec::ThinVec; use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, FatalError}; use rustc_session::Session; use rustc_span::{Span, DUMMY_SP}; @@ -24,6 +23,7 @@ use std::fmt::Debug; use std::hash::Hash; use std::mem; use std::ptr; +use thin_vec::ThinVec; pub struct QueryState { #[cfg(parallel_compiler)] diff --git a/compiler/rustc_resolve/Cargo.toml b/compiler/rustc_resolve/Cargo.toml index 5d2b606b43cd5..2f37fe784de1e 100644 --- a/compiler/rustc_resolve/Cargo.toml +++ b/compiler/rustc_resolve/Cargo.toml @@ -8,10 +8,8 @@ doctest = false [dependencies] bitflags = "1.2.1" -tracing = "0.1" -rustc_ast = { path = "../rustc_ast" } rustc_arena = { path = "../rustc_arena" } -rustc_middle = { path = "../rustc_middle" } +rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } @@ -21,7 +19,10 @@ rustc_feature = { path = "../rustc_feature" } rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } rustc_metadata = { path = "../rustc_metadata" } +rustc_middle = { path = "../rustc_middle" } rustc_query_system = { path = "../rustc_query_system" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } +thin-vec = "0.2.8" +tracing = "0.1" diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 25013036d8749..4ea8b5c71c670 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -25,6 +25,7 @@ use rustc_span::lev_distance::find_best_match_for_name; use rustc_span::source_map::SourceMap; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{BytePos, Span}; +use thin_vec::ThinVec; use tracing::debug; use crate::imports::{Import, ImportKind, ImportResolver}; @@ -1265,7 +1266,7 @@ impl<'a> Resolver<'a> { { let mut candidates = Vec::new(); let mut seen_modules = FxHashSet::default(); - let mut worklist = vec![(start_module, Vec::::new(), true)]; + let mut worklist = vec![(start_module, ThinVec::::new(), true)]; let mut worklist_via_import = vec![]; while let Some((in_module, path_segments, accessible)) = match worklist.pop() { diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 4175527da470c..eddc5ccb5bc72 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -33,6 +33,7 @@ use rustc_span::{BytePos, Span}; use std::iter; use std::ops::Deref; +use thin_vec::ThinVec; use tracing::debug; type Res = def::Res; @@ -74,7 +75,7 @@ fn import_candidate_to_enum_paths(suggestion: &ImportSuggestion) -> (String, Str let path_len = suggestion.path.segments.len(); let enum_path = ast::Path { span: suggestion.path.span, - segments: suggestion.path.segments[0..path_len - 1].to_vec(), + segments: suggestion.path.segments[0..path_len - 1].iter().cloned().collect(), tokens: None, }; let enum_path_string = path_names_to_string(&enum_path); @@ -1640,7 +1641,7 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> { fn find_module(&mut self, def_id: DefId) -> Option<(Module<'a>, ImportSuggestion)> { let mut result = None; let mut seen_modules = FxHashSet::default(); - let mut worklist = vec![(self.r.graph_root, Vec::new())]; + let mut worklist = vec![(self.r.graph_root, ThinVec::new())]; while let Some((in_module, path_segments)) = worklist.pop() { // abort if the module is already found diff --git a/compiler/rustc_serialize/Cargo.toml b/compiler/rustc_serialize/Cargo.toml index dbc5c15195c86..3b0b3144f2cd7 100644 --- a/compiler/rustc_serialize/Cargo.toml +++ b/compiler/rustc_serialize/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [dependencies] indexmap = "1.9.1" smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } +thin-vec = "0.2.8" [dev-dependencies] rustc_macros = { path = "../rustc_macros" } diff --git a/compiler/rustc_serialize/src/collection_impls.rs b/compiler/rustc_serialize/src/collection_impls.rs index 5e53f0b104dfc..8f8c504117cc1 100644 --- a/compiler/rustc_serialize/src/collection_impls.rs +++ b/compiler/rustc_serialize/src/collection_impls.rs @@ -1,13 +1,12 @@ //! Implementations of serialization for structures found in liballoc -use std::hash::{BuildHasher, Hash}; - use crate::{Decodable, Decoder, Encodable, Encoder}; +use smallvec::{Array, SmallVec}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, LinkedList, VecDeque}; +use std::hash::{BuildHasher, Hash}; use std::rc::Rc; use std::sync::Arc; - -use smallvec::{Array, SmallVec}; +use thin_vec::ThinVec; impl>> Encodable for SmallVec { fn encode(&self, s: &mut S) { @@ -23,6 +22,19 @@ impl>> Decodable for SmallVec { } } +impl> Encodable for ThinVec { + fn encode(&self, s: &mut S) { + self.as_slice().encode(s); + } +} + +impl> Decodable for ThinVec { + fn decode(d: &mut D) -> ThinVec { + let len = d.read_usize(); + (0..len).map(|_| Decodable::decode(d)).collect() + } +} + impl> Encodable for LinkedList { fn encode(&self, s: &mut S) { s.emit_usize(self.len()); diff --git a/compiler/rustc_typeck/Cargo.toml b/compiler/rustc_typeck/Cargo.toml index cae29c1d3c5f9..8e213e6ca4089 100644 --- a/compiler/rustc_typeck/Cargo.toml +++ b/compiler/rustc_typeck/Cargo.toml @@ -9,25 +9,26 @@ doctest = false [dependencies] rustc_arena = { path = "../rustc_arena" } -tracing = "0.1" -rustc_macros = { path = "../rustc_macros" } -rustc_middle = { path = "../rustc_middle" } +rustc_ast = { path = "../rustc_ast" } rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } +rustc_feature = { path = "../rustc_feature" } rustc_graphviz = { path = "../rustc_graphviz" } rustc_hir = { path = "../rustc_hir" } rustc_hir_pretty = { path = "../rustc_hir_pretty" } -rustc_target = { path = "../rustc_target" } -rustc_session = { path = "../rustc_session" } -smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } -rustc_ast = { path = "../rustc_ast" } -rustc_span = { path = "../rustc_span" } rustc_index = { path = "../rustc_index" } rustc_infer = { path = "../rustc_infer" } -rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_ty_utils = { path = "../rustc_ty_utils" } rustc_lint = { path = "../rustc_lint" } +rustc_macros = { path = "../rustc_macros" } +rustc_middle = { path = "../rustc_middle" } rustc_serialize = { path = "../rustc_serialize" } +rustc_session = { path = "../rustc_session" } +rustc_span = { path = "../rustc_span" } +rustc_target = { path = "../rustc_target" } +rustc_trait_selection = { path = "../rustc_trait_selection" } rustc_type_ir = { path = "../rustc_type_ir" } -rustc_feature = { path = "../rustc_feature" } +rustc_ty_utils = { path = "../rustc_ty_utils" } +smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } +thin-vec = "0.2.8" +tracing = "0.1" diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index 970b39dc845af..09996c37ead1b 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -48,6 +48,7 @@ use rustc_span::{Span, DUMMY_SP}; use rustc_target::spec::{abi, SanitizerSet}; use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName; use std::iter; +use thin_vec::ThinVec; mod item_bounds; mod type_of; @@ -3294,7 +3295,8 @@ fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool { fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option { use rustc_ast::{Lit, LitIntType, LitKind}; let meta_item_list = attr.meta_item_list(); - let meta_item_list: Option<&[ast::NestedMetaItem]> = meta_item_list.as_ref().map(Vec::as_ref); + let meta_item_list: Option<&[ast::NestedMetaItem]> = + meta_item_list.as_ref().map(ThinVec::as_ref); let sole_meta_list = match meta_item_list { Some([item]) => item.literal(), Some(_) => { diff --git a/src/librustdoc/Cargo.toml b/src/librustdoc/Cargo.toml index cbdfea89efb8a..92906ff42a694 100644 --- a/src/librustdoc/Cargo.toml +++ b/src/librustdoc/Cargo.toml @@ -10,18 +10,18 @@ path = "lib.rs" arrayvec = { version = "0.7", default-features = false } askama = { version = "0.11", default-features = false, features = ["config"] } atty = "0.2" -pulldown-cmark = { version = "0.9.2", default-features = false } +itertools = "0.10.1" minifier = "0.2.2" -serde = { version = "1.0", features = ["derive"] } +once_cell = "1.10.0" +pulldown-cmark = { version = "0.9.2", default-features = false } +regex = "1" +rustdoc-json-types = { path = "../rustdoc-json-types" } serde_json = "1.0" +serde = { version = "1.0", features = ["derive"] } smallvec = "1.8.1" tempfile = "3" -itertools = "0.10.1" -regex = "1" -rustdoc-json-types = { path = "../rustdoc-json-types" } tracing = "0.1" tracing-tree = "0.2.0" -once_cell = "1.10.0" [dependencies.tracing-subscriber] version = "0.3.3" diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 5441a7bd29ec0..0239b8da57ee0 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -123,7 +123,7 @@ where kind: Box::new(ImplItem(Box::new(Impl { unsafety: hir::Unsafety::Normal, generics: new_generics, - trait_: Some(clean_trait_ref_with_bindings(self.cx, trait_ref, &[])), + trait_: Some(clean_trait_ref_with_bindings(self.cx, trait_ref, ThinVec::new())), for_: clean_middle_ty(ty, self.cx, None), items: Vec::new(), polarity, diff --git a/src/librustdoc/clean/blanket_impl.rs b/src/librustdoc/clean/blanket_impl.rs index da15c3c2b1fab..cc734389e070b 100644 --- a/src/librustdoc/clean/blanket_impl.rs +++ b/src/librustdoc/clean/blanket_impl.rs @@ -115,7 +115,7 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> { ), // FIXME(eddyb) compute both `trait_` and `for_` from // the post-inference `trait_ref`, as it's more accurate. - trait_: Some(clean_trait_ref_with_bindings(cx, trait_ref.0, &[])), + trait_: Some(clean_trait_ref_with_bindings(cx, trait_ref.0, ThinVec::new())), for_: clean_middle_ty(ty.0, cx, None), items: cx.tcx .associated_items(impl_def_id) diff --git a/src/librustdoc/clean/cfg/tests.rs b/src/librustdoc/clean/cfg/tests.rs index 7f72d5d39a752..8b5b11e516a6e 100644 --- a/src/librustdoc/clean/cfg/tests.rs +++ b/src/librustdoc/clean/cfg/tests.rs @@ -5,6 +5,7 @@ use rustc_ast::Path; use rustc_span::create_default_session_globals_then; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::DUMMY_SP; +use thin_vec::thin_vec; fn word_cfg(s: &str) -> Cfg { Cfg::Cfg(Symbol::intern(s), None) @@ -26,7 +27,7 @@ macro_rules! dummy_meta_item_list { ($name:ident, [$($list:ident),* $(,)?]) => { MetaItem { path: Path::from_ident(Ident::from_str(stringify!($name))), - kind: MetaItemKind::List(vec![ + kind: MetaItemKind::List(thin_vec![ $( NestedMetaItem::MetaItem( dummy_meta_item_word(stringify!($list)), @@ -40,7 +41,7 @@ macro_rules! dummy_meta_item_list { ($name:ident, [$($list:expr),* $(,)?]) => { MetaItem { path: Path::from_ident(Ident::from_str(stringify!($name))), - kind: MetaItemKind::List(vec![ + kind: MetaItemKind::List(thin_vec![ $( NestedMetaItem::MetaItem($list), )* diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index a7048e788b65a..cb94c53c9440d 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -3,9 +3,10 @@ use std::iter::once; use std::sync::Arc; +use thin_vec::ThinVec; + use rustc_ast as ast; use rustc_data_structures::fx::FxHashSet; -use rustc_data_structures::thin_vec::ThinVec; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; @@ -461,7 +462,7 @@ pub(crate) fn build_impl( ), }; let polarity = tcx.impl_polarity(did); - let trait_ = associated_trait.map(|t| clean_trait_ref_with_bindings(cx, t, &[])); + let trait_ = associated_trait.map(|t| clean_trait_ref_with_bindings(cx, t, ThinVec::new())); if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() { super::build_deref_target_impls(cx, &trait_items, ret); } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 5507ffb871b6e..09fd7f5c9709a 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -33,7 +33,8 @@ use std::collections::hash_map::Entry; use std::collections::BTreeMap; use std::default::Default; use std::hash::Hash; -use std::{mem, vec}; +use std::mem; +use thin_vec::ThinVec; use crate::core::{self, DocContext, ImplTraitParam}; use crate::formats::item_type::ItemType; @@ -125,7 +126,7 @@ fn clean_generic_bound<'tcx>( bug!("clean: parenthesized `GenericBound::LangItemTrait`"); }; - let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, &bindings); + let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, bindings); GenericBound::TraitBound( PolyTrait { trait_, generic_params: vec![] }, hir::TraitBoundModifier::None, @@ -147,14 +148,14 @@ fn clean_generic_bound<'tcx>( pub(crate) fn clean_trait_ref_with_bindings<'tcx>( cx: &mut DocContext<'tcx>, trait_ref: ty::TraitRef<'tcx>, - bindings: &[TypeBinding], + bindings: ThinVec, ) -> Path { let kind = cx.tcx.def_kind(trait_ref.def_id).into(); if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) { span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind); } inline::record_extern_fqn(cx, trait_ref.def_id, kind); - let path = external_path(cx, trait_ref.def_id, true, bindings.to_vec(), trait_ref.substs); + let path = external_path(cx, trait_ref.def_id, true, bindings, trait_ref.substs); debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs); @@ -164,7 +165,7 @@ pub(crate) fn clean_trait_ref_with_bindings<'tcx>( fn clean_poly_trait_ref_with_bindings<'tcx>( cx: &mut DocContext<'tcx>, poly_trait_ref: ty::PolyTraitRef<'tcx>, - bindings: &[TypeBinding], + bindings: ThinVec, ) -> GenericBound { let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap(); @@ -327,7 +328,7 @@ fn clean_poly_trait_predicate<'tcx>( let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref); Some(WherePredicate::BoundPredicate { ty: clean_middle_ty(poly_trait_ref.skip_binder().self_ty(), cx, None), - bounds: vec![clean_poly_trait_ref_with_bindings(cx, poly_trait_ref, &[])], + bounds: vec![clean_poly_trait_ref_with_bindings(cx, poly_trait_ref, ThinVec::new())], bound_params: Vec::new(), }) } @@ -402,7 +403,7 @@ fn clean_projection<'tcx>( def_id: Option, ) -> Type { let lifted = ty.lift_to_tcx(cx.tcx).unwrap(); - let trait_ = clean_trait_ref_with_bindings(cx, lifted.trait_ref(cx.tcx), &[]); + let trait_ = clean_trait_ref_with_bindings(cx, lifted.trait_ref(cx.tcx), ThinVec::new()); let self_type = clean_middle_ty(ty.self_ty(), cx, None); let self_def_id = if let Some(def_id) = def_id { cx.tcx.opt_parent(def_id).or(Some(def_id)) @@ -1588,12 +1589,12 @@ pub(crate) fn clean_middle_ty<'tcx>( AdtKind::Enum => ItemType::Enum, }; inline::record_extern_fqn(cx, did, kind); - let path = external_path(cx, did, false, vec![], substs); + let path = external_path(cx, did, false, ThinVec::new(), substs); Type::Path { path } } ty::Foreign(did) => { inline::record_extern_fqn(cx, did, ItemType::ForeignType); - let path = external_path(cx, did, false, vec![], InternalSubsts::empty()); + let path = external_path(cx, did, false, ThinVec::new(), InternalSubsts::empty()); Type::Path { path } } ty::Dynamic(obj, ref reg) => { @@ -1617,7 +1618,7 @@ pub(crate) fn clean_middle_ty<'tcx>( let mut bounds = dids .map(|did| { let empty = cx.tcx.intern_substs(&[]); - let path = external_path(cx, did, false, vec![], empty); + let path = external_path(cx, did, false, ThinVec::new(), empty); inline::record_extern_fqn(cx, did, ItemType::Trait); PolyTrait { trait_: path, generic_params: Vec::new() } }) @@ -1693,7 +1694,7 @@ pub(crate) fn clean_middle_ty<'tcx>( } } - let bindings: Vec<_> = bounds + let bindings: ThinVec<_> = bounds .iter() .filter_map(|bound| { if let ty::PredicateKind::Projection(proj) = bound.kind().skip_binder() @@ -1714,7 +1715,7 @@ pub(crate) fn clean_middle_ty<'tcx>( }) .collect(); - Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, &bindings)) + Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, bindings)) }) .collect::>(); bounds.extend(regions); @@ -1850,12 +1851,8 @@ fn clean_generic_args<'tcx>( }) .collect::>() .into(); - let bindings = generic_args - .bindings - .iter() - .map(|x| clean_type_binding(x, cx)) - .collect::>() - .into(); + let bindings = + generic_args.bindings.iter().map(|x| clean_type_binding(x, cx)).collect::>(); GenericArgs::AngleBracketed { args, bindings } } } diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 4c39021903c5b..abde6b6fec64e 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -8,6 +8,7 @@ use std::sync::OnceLock as OnceCell; use std::{cmp, fmt, iter}; use arrayvec::ArrayVec; +use thin_vec::ThinVec; use rustc_ast::attr; use rustc_ast::util::comments::beautify_doc_string; @@ -15,7 +16,6 @@ use rustc_ast::{self as ast, AttrStyle}; use rustc_attr::{ConstStability, Deprecation, Stability, StabilityLevel}; use rustc_const_eval::const_eval::is_unstable_const_fn; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_data_structures::thin_vec::ThinVec; use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; @@ -1278,7 +1278,7 @@ impl GenericBound { pub(crate) fn maybe_sized(cx: &mut DocContext<'_>) -> GenericBound { let did = cx.tcx.require_lang_item(LangItem::Sized, None); let empty = cx.tcx.intern_substs(&[]); - let path = external_path(cx, did, false, vec![], empty); + let path = external_path(cx, did, false, ThinVec::new(), empty); inline::record_extern_fqn(cx, did, ItemType::Trait); GenericBound::TraitBound( PolyTrait { trait_: path, generic_params: Vec::new() }, diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 718cbbd2b8374..ac9ab33961676 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -12,7 +12,6 @@ use crate::visit_lib::LibEmbargoVisitor; use rustc_ast as ast; use rustc_ast::tokenstream::TokenTree; -use rustc_data_structures::thin_vec::ThinVec; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; @@ -23,6 +22,7 @@ use rustc_middle::ty::{self, DefIdTree, TyCtxt}; use rustc_span::symbol::{kw, sym, Symbol}; use std::fmt::Write as _; use std::mem; +use thin_vec::ThinVec; #[cfg(test)] mod tests; @@ -102,7 +102,7 @@ fn external_generic_args<'tcx>( cx: &mut DocContext<'tcx>, did: DefId, has_self: bool, - bindings: Vec, + bindings: ThinVec, substs: SubstsRef<'tcx>, ) -> GenericArgs { let args = substs_to_args(cx, substs, has_self); @@ -112,7 +112,7 @@ fn external_generic_args<'tcx>( // The trait's first substitution is the one after self, if there is one. match substs.iter().nth(if has_self { 1 } else { 0 }).unwrap().expect_ty().kind() { ty::Tuple(tys) => tys.iter().map(|t| clean_middle_ty(t, cx, None)).collect::>().into(), - _ => return GenericArgs::AngleBracketed { args: args.into(), bindings: bindings.into() }, + _ => return GenericArgs::AngleBracketed { args: args.into(), bindings }, }; let output = None; // FIXME(#20299) return type comes from a projection now @@ -130,7 +130,7 @@ pub(super) fn external_path<'tcx>( cx: &mut DocContext<'tcx>, did: DefId, has_self: bool, - bindings: Vec, + bindings: ThinVec, substs: SubstsRef<'tcx>, ) -> Path { let def_kind = cx.tcx.def_kind(did); diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 8aede1e77a274..09f041170643d 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -62,6 +62,7 @@ extern crate rustc_target; extern crate rustc_trait_selection; extern crate rustc_typeck; extern crate test; +extern crate thin_vec; // See docs in https://github.com/rust-lang/rust/blob/master/compiler/rustc/src/main.rs // about jemalloc. diff --git a/src/test/ui-fulldeps/pprust-expr-roundtrip.rs b/src/test/ui-fulldeps/pprust-expr-roundtrip.rs index 117b798710cf0..0670c49ce046f 100644 --- a/src/test/ui-fulldeps/pprust-expr-roundtrip.rs +++ b/src/test/ui-fulldeps/pprust-expr-roundtrip.rs @@ -25,6 +25,7 @@ extern crate rustc_data_structures; extern crate rustc_parse; extern crate rustc_session; extern crate rustc_span; +extern crate thin_vec; use rustc_ast::mut_visit::{self, visit_clobber, MutVisitor}; use rustc_ast::ptr::P; @@ -35,6 +36,7 @@ use rustc_session::parse::ParseSess; use rustc_span::source_map::FilePathMapping; use rustc_span::source_map::{FileName, Spanned, DUMMY_SP}; use rustc_span::symbol::Ident; +use thin_vec::thin_vec; fn parse_expr(ps: &ParseSess, src: &str) -> Option> { let src_as_string = src.to_string(); @@ -51,7 +53,7 @@ fn expr(kind: ExprKind) -> P { fn make_x() -> P { let seg = PathSegment::from_ident(Ident::from_str("x")); - let path = Path { segments: vec![seg], span: DUMMY_SP, tokens: None }; + let path = Path { segments: thin_vec![seg], span: DUMMY_SP, tokens: None }; expr(ExprKind::Path(None, path)) } @@ -69,14 +71,14 @@ fn iter_exprs(depth: usize, f: &mut dyn FnMut(P)) { for kind in 0..=19 { match kind { 0 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Box(e))), - 1 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Call(e, vec![]))), + 1 => iter_exprs(depth - 1, &mut |e| g(ExprKind::Call(e, thin_vec![]))), 2 => { let seg = PathSegment::from_ident(Ident::from_str("x")); iter_exprs(depth - 1, &mut |e| { - g(ExprKind::MethodCall(seg.clone(), e, vec![make_x()], DUMMY_SP)) + g(ExprKind::MethodCall(seg.clone(), e, thin_vec![make_x()], DUMMY_SP)) }); iter_exprs(depth - 1, &mut |e| { - g(ExprKind::MethodCall(seg.clone(), make_x(), vec![e], DUMMY_SP)) + g(ExprKind::MethodCall(seg.clone(), make_x(), thin_vec![e], DUMMY_SP)) }); } 3..=8 => { @@ -110,7 +112,7 @@ fn iter_exprs(depth: usize, f: &mut dyn FnMut(P)) { iter_exprs(depth - 1, &mut |e| g(ExprKind::If(e, block.clone(), None))); } 11 => { - let decl = P(FnDecl { inputs: vec![], output: FnRetTy::Default(DUMMY_SP) }); + let decl = P(FnDecl { inputs: thin_vec![], output: FnRetTy::Default(DUMMY_SP) }); iter_exprs(depth - 1, &mut |e| { g(ExprKind::Closure( ClosureBinder::NotPresent, diff --git a/src/test/ui/stats/hir-stats.stderr b/src/test/ui/stats/hir-stats.stderr index eb828bb9a2c17..2012cb7210627 100644 --- a/src/test/ui/stats/hir-stats.stderr +++ b/src/test/ui/stats/hir-stats.stderr @@ -3,121 +3,121 @@ PRE EXPANSION AST STATS Name Accumulated Size Count Item Size ---------------------------------------------------------------- +GenericArgs 48 ( 0.6%) 1 48 +- AngleBracketed 48 ( 0.6%) 1 ExprField 48 ( 0.6%) 1 48 -Crate 56 ( 0.7%) 1 56 -Attribute 64 ( 0.8%) 2 32 +WherePredicate 56 ( 0.8%) 1 56 +- BoundPredicate 56 ( 0.8%) 1 +Crate 56 ( 0.8%) 1 56 +Attribute 64 ( 0.9%) 2 32 - Normal 32 ( 0.4%) 1 - DocComment 32 ( 0.4%) 1 -GenericArgs 64 ( 0.8%) 1 64 -- AngleBracketed 64 ( 0.8%) 1 -Local 72 ( 0.9%) 1 72 -WherePredicate 72 ( 0.9%) 1 72 -- BoundPredicate 72 ( 0.9%) 1 -Arm 96 ( 1.1%) 2 48 -ForeignItem 96 ( 1.1%) 1 96 -- Fn 96 ( 1.1%) 1 -FieldDef 160 ( 1.9%) 2 80 -Stmt 160 ( 1.9%) 5 32 +Local 72 ( 1.0%) 1 72 +Arm 96 ( 1.3%) 2 48 +ForeignItem 96 ( 1.3%) 1 96 +- Fn 96 ( 1.3%) 1 +FnDecl 120 ( 1.6%) 5 24 +FieldDef 160 ( 2.2%) 2 80 +Stmt 160 ( 2.2%) 5 32 - Local 32 ( 0.4%) 1 - MacCall 32 ( 0.4%) 1 -- Expr 96 ( 1.1%) 3 -Param 160 ( 1.9%) 4 40 -FnDecl 200 ( 2.4%) 5 40 -Variant 240 ( 2.8%) 2 120 -Block 288 ( 3.4%) 6 48 -GenericBound 352 ( 4.2%) 4 88 -- Trait 352 ( 4.2%) 4 -AssocItem 416 ( 4.9%) 4 104 -- TyAlias 208 ( 2.5%) 2 -- Fn 208 ( 2.5%) 2 -GenericParam 520 ( 6.1%) 5 104 -PathSegment 720 ( 8.5%) 30 24 -Expr 832 ( 9.8%) 8 104 -- Path 104 ( 1.2%) 1 -- Match 104 ( 1.2%) 1 -- Struct 104 ( 1.2%) 1 -- Lit 208 ( 2.5%) 2 -- Block 312 ( 3.7%) 3 -Pat 840 ( 9.9%) 7 120 -- Struct 120 ( 1.4%) 1 -- Wild 120 ( 1.4%) 1 -- Ident 600 ( 7.1%) 5 -Ty 1_344 (15.9%) 14 96 -- Rptr 96 ( 1.1%) 1 -- Ptr 96 ( 1.1%) 1 -- ImplicitSelf 192 ( 2.3%) 2 -- Path 960 (11.4%) 10 -Item 1_656 (19.6%) 9 184 -- Trait 184 ( 2.2%) 1 -- Enum 184 ( 2.2%) 1 -- ForeignMod 184 ( 2.2%) 1 -- Impl 184 ( 2.2%) 1 -- Fn 368 ( 4.4%) 2 -- Use 552 ( 6.5%) 3 +- Expr 96 ( 1.3%) 3 +Param 160 ( 2.2%) 4 40 +Variant 208 ( 2.8%) 2 104 +GenericBound 224 ( 3.0%) 4 56 +- Trait 224 ( 3.0%) 4 +Block 288 ( 3.9%) 6 48 +AssocItem 416 ( 5.6%) 4 104 +- TyAlias 208 ( 2.8%) 2 +- Fn 208 ( 2.8%) 2 +GenericParam 520 ( 7.0%) 5 104 +PathSegment 720 ( 9.7%) 30 24 +Pat 728 ( 9.8%) 7 104 +- Struct 104 ( 1.4%) 1 +- Wild 104 ( 1.4%) 1 +- Ident 520 ( 7.0%) 5 +Expr 768 (10.3%) 8 96 +- Path 96 ( 1.3%) 1 +- Match 96 ( 1.3%) 1 +- Struct 96 ( 1.3%) 1 +- Lit 192 ( 2.6%) 2 +- Block 288 ( 3.9%) 3 +Ty 1_120 (15.1%) 14 80 +- Rptr 80 ( 1.1%) 1 +- Ptr 80 ( 1.1%) 1 +- ImplicitSelf 160 ( 2.2%) 2 +- Path 800 (10.8%) 10 +Item 1_296 (17.5%) 9 144 +- Trait 144 ( 1.9%) 1 +- Enum 144 ( 1.9%) 1 +- ForeignMod 144 ( 1.9%) 1 +- Impl 144 ( 1.9%) 1 +- Fn 288 ( 3.9%) 2 +- Use 432 ( 5.8%) 3 ---------------------------------------------------------------- -Total 8_456 +Total 7_424 POST EXPANSION AST STATS Name Accumulated Size Count Item Size ---------------------------------------------------------------- -ExprField 48 ( 0.5%) 1 48 -Crate 56 ( 0.6%) 1 56 -GenericArgs 64 ( 0.7%) 1 64 -- AngleBracketed 64 ( 0.7%) 1 -Local 72 ( 0.8%) 1 72 -WherePredicate 72 ( 0.8%) 1 72 -- BoundPredicate 72 ( 0.8%) 1 -Arm 96 ( 1.0%) 2 48 -ForeignItem 96 ( 1.0%) 1 96 -- Fn 96 ( 1.0%) 1 -InlineAsm 120 ( 1.3%) 1 120 -Attribute 128 ( 1.4%) 4 32 -- DocComment 32 ( 0.3%) 1 -- Normal 96 ( 1.0%) 3 -FieldDef 160 ( 1.7%) 2 80 -Stmt 160 ( 1.7%) 5 32 -- Local 32 ( 0.3%) 1 -- Semi 32 ( 0.3%) 1 -- Expr 96 ( 1.0%) 3 -Param 160 ( 1.7%) 4 40 -FnDecl 200 ( 2.2%) 5 40 -Variant 240 ( 2.6%) 2 120 -Block 288 ( 3.1%) 6 48 -GenericBound 352 ( 3.8%) 4 88 -- Trait 352 ( 3.8%) 4 -AssocItem 416 ( 4.5%) 4 104 -- TyAlias 208 ( 2.3%) 2 -- Fn 208 ( 2.3%) 2 -GenericParam 520 ( 5.7%) 5 104 -PathSegment 792 ( 8.6%) 33 24 -Pat 840 ( 9.1%) 7 120 -- Struct 120 ( 1.3%) 1 -- Wild 120 ( 1.3%) 1 -- Ident 600 ( 6.5%) 5 -Expr 936 (10.2%) 9 104 -- Path 104 ( 1.1%) 1 -- Match 104 ( 1.1%) 1 -- Struct 104 ( 1.1%) 1 -- InlineAsm 104 ( 1.1%) 1 -- Lit 208 ( 2.3%) 2 -- Block 312 ( 3.4%) 3 -Ty 1_344 (14.6%) 14 96 -- Rptr 96 ( 1.0%) 1 -- Ptr 96 ( 1.0%) 1 -- ImplicitSelf 192 ( 2.1%) 2 -- Path 960 (10.5%) 10 -Item 2_024 (22.0%) 11 184 -- Trait 184 ( 2.0%) 1 -- Enum 184 ( 2.0%) 1 -- ExternCrate 184 ( 2.0%) 1 -- ForeignMod 184 ( 2.0%) 1 -- Impl 184 ( 2.0%) 1 -- Fn 368 ( 4.0%) 2 -- Use 736 ( 8.0%) 4 +GenericArgs 48 ( 0.6%) 1 48 +- AngleBracketed 48 ( 0.6%) 1 +ExprField 48 ( 0.6%) 1 48 +WherePredicate 56 ( 0.7%) 1 56 +- BoundPredicate 56 ( 0.7%) 1 +Crate 56 ( 0.7%) 1 56 +Local 72 ( 0.9%) 1 72 +Arm 96 ( 1.2%) 2 48 +ForeignItem 96 ( 1.2%) 1 96 +- Fn 96 ( 1.2%) 1 +InlineAsm 120 ( 1.5%) 1 120 +FnDecl 120 ( 1.5%) 5 24 +Attribute 128 ( 1.6%) 4 32 +- DocComment 32 ( 0.4%) 1 +- Normal 96 ( 1.2%) 3 +FieldDef 160 ( 2.0%) 2 80 +Stmt 160 ( 2.0%) 5 32 +- Local 32 ( 0.4%) 1 +- Semi 32 ( 0.4%) 1 +- Expr 96 ( 1.2%) 3 +Param 160 ( 2.0%) 4 40 +Variant 208 ( 2.6%) 2 104 +GenericBound 224 ( 2.8%) 4 56 +- Trait 224 ( 2.8%) 4 +Block 288 ( 3.6%) 6 48 +AssocItem 416 ( 5.2%) 4 104 +- TyAlias 208 ( 2.6%) 2 +- Fn 208 ( 2.6%) 2 +GenericParam 520 ( 6.4%) 5 104 +Pat 728 ( 9.0%) 7 104 +- Struct 104 ( 1.3%) 1 +- Wild 104 ( 1.3%) 1 +- Ident 520 ( 6.4%) 5 +PathSegment 792 ( 9.8%) 33 24 +Expr 864 (10.7%) 9 96 +- Path 96 ( 1.2%) 1 +- Match 96 ( 1.2%) 1 +- Struct 96 ( 1.2%) 1 +- InlineAsm 96 ( 1.2%) 1 +- Lit 192 ( 2.4%) 2 +- Block 288 ( 3.6%) 3 +Ty 1_120 (13.9%) 14 80 +- Rptr 80 ( 1.0%) 1 +- Ptr 80 ( 1.0%) 1 +- ImplicitSelf 160 ( 2.0%) 2 +- Path 800 ( 9.9%) 10 +Item 1_584 (19.6%) 11 144 +- Trait 144 ( 1.8%) 1 +- Enum 144 ( 1.8%) 1 +- ExternCrate 144 ( 1.8%) 1 +- ForeignMod 144 ( 1.8%) 1 +- Impl 144 ( 1.8%) 1 +- Fn 288 ( 3.6%) 2 +- Use 576 ( 7.1%) 4 ---------------------------------------------------------------- -Total 9_184 +Total 8_064 HIR STATS diff --git a/src/tools/clippy/clippy_utils/src/ast_utils.rs b/src/tools/clippy/clippy_utils/src/ast_utils.rs index 493991f30e872..0dc3b01c70c78 100644 --- a/src/tools/clippy/clippy_utils/src/ast_utils.rs +++ b/src/tools/clippy/clippy_utils/src/ast_utils.rs @@ -144,7 +144,8 @@ pub fn eq_expr(l: &Expr, r: &Expr) -> bool { (_, Paren(r)) => eq_expr(l, r), (Err, Err) => true, (Box(l), Box(r)) | (Try(l), Try(r)) | (Await(l), Await(r)) => eq_expr(l, r), - (Array(l), Array(r)) | (Tup(l), Tup(r)) => over(l, r, |l, r| eq_expr(l, r)), + (Array(l), Array(r)) => over(l, r, |l, r| eq_expr(l, r)), + (Tup(l), Tup(r)) => over(l, r, |l, r| eq_expr(l, r)), (Repeat(le, ls), Repeat(re, rs)) => eq_expr(le, re) && eq_expr(&ls.value, &rs.value), (Call(lc, la), Call(rc, ra)) => eq_expr(lc, rc) && over(la, ra, |l, r| eq_expr(l, r)), (MethodCall(lc, ls, la, _), MethodCall(rc, rs, ra, _)) => { diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 333f85f6d62b8..860d2fb6d38c0 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -224,6 +224,7 @@ const PERMITTED_DEPENDENCIES: &[&str] = &[ "time", "tinystr", "tinyvec", + "thin-vec", "tracing", "tracing-attributes", "tracing-core",