Skip to content

Commit 8c6fb02

Browse files
committed
Auto merge of rust-lang#61995 - eddyb:hir-sep-ptr, r=petrochenkov
rustc: use a separate copy of P for HIR than for AST. Note: this currently includes/is based on top of rust-lang#61987. Like rust-lang#61968, but goes one step further and uses a separate `P<...>` for the HIR, with no `Clone`, or the ability to mutate after allocation. There is still `into_inner`/`into_iter`, but they're only exposed for `hir::lowering`, and they would take more work to untangle. r? @petrochenkov cc @rust-lang/compiler
2 parents 8301de1 + c6374cf commit 8c6fb02

22 files changed

+183
-34
lines changed

src/librustc/cfg/construct.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
use crate::cfg::*;
22
use crate::middle::region;
33
use rustc_data_structures::graph::implementation as graph;
4-
use syntax::ptr::P;
54
use crate::ty::{self, TyCtxt};
65

76
use crate::hir::{self, PatKind};
87
use crate::hir::def_id::DefId;
8+
use crate::hir::ptr::P;
99

1010
struct CFGBuilder<'a, 'tcx> {
1111
tcx: TyCtxt<'tcx>,

src/librustc/hir/lowering.rs

+13-11
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ use crate::hir::map::{DefKey, DefPathData, Definitions};
3939
use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
4040
use crate::hir::def::{Res, DefKind, PartialRes, PerNS};
4141
use crate::hir::{GenericArg, ConstArg};
42+
use crate::hir::ptr::P;
4243
use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES,
4344
ELIDED_LIFETIMES_IN_PATHS};
4445
use crate::middle::cstore::CrateStore;
@@ -61,7 +62,6 @@ use syntax::ast::*;
6162
use syntax::errors;
6263
use syntax::ext::hygiene::{Mark, SyntaxContext};
6364
use syntax::print::pprust;
64-
use syntax::ptr::P;
6565
use syntax::source_map::{self, respan, ExpnInfo, CompilerDesugaringKind, Spanned};
6666
use syntax::source_map::CompilerDesugaringKind::IfTemporary;
6767
use syntax::std_inject;
@@ -1111,7 +1111,7 @@ impl<'a> LoweringContext<'a> {
11111111
},
11121112
);
11131113

1114-
lowered_generics.params = lowered_generics
1114+
let mut lowered_params: Vec<_> = lowered_generics
11151115
.params
11161116
.into_iter()
11171117
.chain(in_band_defs)
@@ -1121,14 +1121,16 @@ impl<'a> LoweringContext<'a> {
11211121
// unsorted generic parameters at the moment, so we make sure
11221122
// that they're ordered correctly here for now. (When we chain
11231123
// the `in_band_defs`, we might make the order unsorted.)
1124-
lowered_generics.params.sort_by_key(|param| {
1124+
lowered_params.sort_by_key(|param| {
11251125
match param.kind {
11261126
hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime,
11271127
hir::GenericParamKind::Type { .. } => ParamKindOrd::Type,
11281128
hir::GenericParamKind::Const { .. } => ParamKindOrd::Const,
11291129
}
11301130
});
11311131

1132+
lowered_generics.params = lowered_params.into();
1133+
11321134
(lowered_generics, res)
11331135
}
11341136

@@ -1155,13 +1157,13 @@ impl<'a> LoweringContext<'a> {
11551157
&mut self,
11561158
capture_clause: CaptureBy,
11571159
closure_node_id: NodeId,
1158-
ret_ty: Option<&Ty>,
1160+
ret_ty: Option<syntax::ptr::P<Ty>>,
11591161
span: Span,
11601162
body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
11611163
) -> hir::ExprKind {
11621164
let capture_clause = self.lower_capture_clause(capture_clause);
11631165
let output = match ret_ty {
1164-
Some(ty) => FunctionRetTy::Ty(P(ty.clone())),
1166+
Some(ty) => FunctionRetTy::Ty(ty),
11651167
None => FunctionRetTy::Default(span),
11661168
};
11671169
let ast_decl = FnDecl {
@@ -2725,7 +2727,7 @@ impl<'a> LoweringContext<'a> {
27252727

27262728
// ::std::future::Future<future_params>
27272729
let future_path =
2728-
self.std_path(span, &[sym::future, sym::Future], Some(future_params), false);
2730+
P(self.std_path(span, &[sym::future, sym::Future], Some(future_params), false));
27292731

27302732
hir::GenericBound::Trait(
27312733
hir::PolyTraitRef {
@@ -3094,7 +3096,7 @@ impl<'a> LoweringContext<'a> {
30943096

30953097
fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef {
30963098
let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) {
3097-
hir::QPath::Resolved(None, path) => path.and_then(|path| path),
3099+
hir::QPath::Resolved(None, path) => path,
30983100
qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath),
30993101
};
31003102
hir::TraitRef {
@@ -3620,7 +3622,7 @@ impl<'a> LoweringContext<'a> {
36203622
hir::Item {
36213623
hir_id: new_id,
36223624
ident,
3623-
attrs: attrs.clone(),
3625+
attrs: attrs.into_iter().cloned().collect(),
36243626
node: item,
36253627
vis,
36263628
span,
@@ -3705,7 +3707,7 @@ impl<'a> LoweringContext<'a> {
37053707
hir::Item {
37063708
hir_id: new_hir_id,
37073709
ident,
3708-
attrs: attrs.clone(),
3710+
attrs: attrs.into_iter().cloned().collect(),
37093711
node: item,
37103712
vis,
37113713
span: use_tree.span,
@@ -4567,7 +4569,7 @@ impl<'a> LoweringContext<'a> {
45674569
// `|x: u8| future_from_generator(|| -> X { ... })`.
45684570
let body_id = this.lower_fn_body(&outer_decl, |this| {
45694571
let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
4570-
Some(&**ty)
4572+
Some(ty.clone())
45714573
} else { None };
45724574
let async_body = this.make_async_expr(
45734575
capture_clause, closure_id, async_ret_ty, body.span,
@@ -5577,7 +5579,7 @@ impl<'a> LoweringContext<'a> {
55775579
let principal = hir::PolyTraitRef {
55785580
bound_generic_params: hir::HirVec::new(),
55795581
trait_ref: hir::TraitRef {
5580-
path: path.and_then(|path| path),
5582+
path,
55815583
hir_ref_id: hir_id,
55825584
},
55835585
span,

src/librustc/hir/mod.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ pub use self::UnsafeSource::*;
1212

1313
use crate::hir::def::{Res, DefKind};
1414
use crate::hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX};
15+
use crate::hir::ptr::P;
1516
use crate::util::nodemap::{NodeMap, FxHashSet};
1617
use crate::mir::mono::Linkage;
1718

@@ -23,7 +24,6 @@ use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, AsmDialect};
2324
use syntax::ast::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy};
2425
use syntax::attr::{InlineAttr, OptimizeAttr};
2526
use syntax::ext::hygiene::SyntaxContext;
26-
use syntax::ptr::P;
2727
use syntax::symbol::{Symbol, kw};
2828
use syntax::tokenstream::TokenStream;
2929
use syntax::util::parser::ExprPrecedence;
@@ -63,6 +63,7 @@ pub mod lowering;
6363
pub mod map;
6464
pub mod pat_util;
6565
pub mod print;
66+
pub mod ptr;
6667
pub mod upvars;
6768

6869
/// Uniquely identifies a node in the HIR of the current crate. It is
@@ -1979,13 +1980,15 @@ pub struct InlineAsmOutput {
19791980
pub span: Span,
19801981
}
19811982

1983+
// NOTE(eddyb) This is used within MIR as well, so unlike the rest of the HIR,
1984+
// it needs to be `Clone` and use plain `Vec<T>` instead of `HirVec<T>`.
19821985
#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
19831986
pub struct InlineAsm {
19841987
pub asm: Symbol,
19851988
pub asm_str_style: StrStyle,
1986-
pub outputs: HirVec<InlineAsmOutput>,
1987-
pub inputs: HirVec<Symbol>,
1988-
pub clobbers: HirVec<Symbol>,
1989+
pub outputs: Vec<InlineAsmOutput>,
1990+
pub inputs: Vec<Symbol>,
1991+
pub clobbers: Vec<Symbol>,
19891992
pub volatile: bool,
19901993
pub alignstack: bool,
19911994
pub dialect: AsmDialect,
@@ -2217,7 +2220,7 @@ pub enum UseKind {
22172220
/// within the resolution map.
22182221
#[derive(RustcEncodable, RustcDecodable, Debug, HashStable)]
22192222
pub struct TraitRef {
2220-
pub path: Path,
2223+
pub path: P<Path>,
22212224
// Don't hash the ref_id. It is tracked via the thing it is used to access
22222225
#[stable_hasher(ignore)]
22232226
pub hir_ref_id: HirId,

src/librustc/hir/print.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@ use syntax::parse::lexer::comments;
66
use syntax::print::pp::{self, Breaks};
77
use syntax::print::pp::Breaks::{Consistent, Inconsistent};
88
use syntax::print::pprust::{self, PrintState};
9-
use syntax::ptr::P;
109
use syntax::symbol::kw;
1110
use syntax::util::parser::{self, AssocOp, Fixity};
1211
use syntax_pos::{self, BytePos, FileName};
1312

1413
use crate::hir;
1514
use crate::hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
1615
use crate::hir::{GenericParam, GenericParamKind, GenericArg};
16+
use crate::hir::ptr::P;
1717

1818
use std::borrow::Cow;
1919
use std::cell::Cell;

src/librustc/hir/ptr.rs

+141
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
// HACK(eddyb) this is a copy of `syntax::ptr`, minus the mutation (the HIR is
2+
// frozen anyway). The only reason for doing this instead of replacing `P<T>`
3+
// with `Box<T>` in HIR, is that `&Box<[T]>` doesn't implement `IntoIterator`.
4+
5+
use std::fmt::{self, Display, Debug};
6+
use std::iter::FromIterator;
7+
use std::ops::Deref;
8+
use std::{slice, vec};
9+
10+
use serialize::{Encodable, Decodable, Encoder, Decoder};
11+
12+
use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult,
13+
HashStable};
14+
/// An owned smart pointer.
15+
#[derive(Hash, PartialEq, Eq)]
16+
pub struct P<T: ?Sized> {
17+
ptr: Box<T>
18+
}
19+
20+
/// Construct a `P<T>` from a `T` value.
21+
#[allow(non_snake_case)]
22+
pub fn P<T: 'static>(value: T) -> P<T> {
23+
P {
24+
ptr: box value
25+
}
26+
}
27+
28+
impl<T: 'static> P<T> {
29+
// HACK(eddyb) used by HIR lowering in a few places still.
30+
// NOTE: do not make this more public than `pub(super)`.
31+
pub(super) fn into_inner(self) -> T {
32+
*self.ptr
33+
}
34+
}
35+
36+
impl<T: ?Sized> Deref for P<T> {
37+
type Target = T;
38+
39+
fn deref(&self) -> &T {
40+
&self.ptr
41+
}
42+
}
43+
44+
impl<T: ?Sized + Debug> Debug for P<T> {
45+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46+
Debug::fmt(&self.ptr, f)
47+
}
48+
}
49+
50+
impl<T: Display> Display for P<T> {
51+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52+
Display::fmt(&**self, f)
53+
}
54+
}
55+
56+
impl<T: 'static + Decodable> Decodable for P<T> {
57+
fn decode<D: Decoder>(d: &mut D) -> Result<P<T>, D::Error> {
58+
Decodable::decode(d).map(P)
59+
}
60+
}
61+
62+
impl<T: Encodable> Encodable for P<T> {
63+
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
64+
(**self).encode(s)
65+
}
66+
}
67+
68+
impl<T> P<[T]> {
69+
pub const fn new() -> P<[T]> {
70+
// HACK(eddyb) bypass the lack of a `const fn` to create an empty `Box<[T]>`
71+
// (as trait methods, `default` in this case, can't be `const fn` yet).
72+
P {
73+
ptr: unsafe {
74+
use std::ptr::NonNull;
75+
std::mem::transmute(NonNull::<[T; 0]>::dangling() as NonNull<[T]>)
76+
},
77+
}
78+
}
79+
80+
#[inline(never)]
81+
pub fn from_vec(v: Vec<T>) -> P<[T]> {
82+
P { ptr: v.into_boxed_slice() }
83+
}
84+
85+
// HACK(eddyb) used by HIR lowering in a few places still.
86+
// NOTE: do not make this more public than `pub(super)`,
87+
// and do not make this into an `IntoIterator` impl.
88+
pub(super) fn into_iter(self) -> vec::IntoIter<T> {
89+
self.ptr.into_vec().into_iter()
90+
}
91+
}
92+
93+
94+
impl<T> Default for P<[T]> {
95+
/// Creates an empty `P<[T]>`.
96+
fn default() -> P<[T]> {
97+
P::new()
98+
}
99+
}
100+
101+
impl<T> From<Vec<T>> for P<[T]> {
102+
fn from(v: Vec<T>) -> Self {
103+
P::from_vec(v)
104+
}
105+
}
106+
107+
impl<T> FromIterator<T> for P<[T]> {
108+
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> P<[T]> {
109+
P::from_vec(iter.into_iter().collect())
110+
}
111+
}
112+
113+
impl<'a, T> IntoIterator for &'a P<[T]> {
114+
type Item = &'a T;
115+
type IntoIter = slice::Iter<'a, T>;
116+
fn into_iter(self) -> Self::IntoIter {
117+
self.ptr.into_iter()
118+
}
119+
}
120+
121+
impl<T: Encodable> Encodable for P<[T]> {
122+
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
123+
Encodable::encode(&**self, s)
124+
}
125+
}
126+
127+
impl<T: Decodable> Decodable for P<[T]> {
128+
fn decode<D: Decoder>(d: &mut D) -> Result<P<[T]>, D::Error> {
129+
Ok(P::from_vec(Decodable::decode(d)?))
130+
}
131+
}
132+
133+
impl<CTX, T> HashStable<CTX> for P<T>
134+
where T: ?Sized + HashStable<CTX>
135+
{
136+
fn hash_stable<W: StableHasherResult>(&self,
137+
hcx: &mut CTX,
138+
hasher: &mut StableHasher<W>) {
139+
(**self).hash_stable(hcx, hasher);
140+
}
141+
}

src/librustc/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@
3535
#![feature(arbitrary_self_types)]
3636
#![feature(box_patterns)]
3737
#![feature(box_syntax)]
38+
#![feature(const_fn)]
39+
#![feature(const_transmute)]
3840
#![feature(core_intrinsics)]
3941
#![feature(drain_filter)]
4042
#![feature(inner_deref)]

src/librustc/middle/expr_use_visitor.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@ use self::OverloadedCallType::*;
1111

1212
use crate::hir::def::{CtorOf, Res, DefKind};
1313
use crate::hir::def_id::DefId;
14+
use crate::hir::ptr::P;
1415
use crate::infer::InferCtxt;
1516
use crate::middle::mem_categorization as mc;
1617
use crate::middle::region;
1718
use crate::ty::{self, DefIdTree, TyCtxt, adjustment};
1819

1920
use crate::hir::{self, PatKind};
2021
use std::rc::Rc;
21-
use syntax::ptr::P;
2222
use syntax_pos::Span;
2323
use crate::util::nodemap::ItemLocalSet;
2424

src/librustc/middle/liveness.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ use self::VarKind::*;
9999

100100
use crate::hir::def::*;
101101
use crate::hir::Node;
102+
use crate::hir::ptr::P;
102103
use crate::ty::{self, TyCtxt};
103104
use crate::ty::query::Providers;
104105
use crate::lint;
@@ -111,7 +112,6 @@ use std::io::prelude::*;
111112
use std::io;
112113
use std::rc::Rc;
113114
use syntax::ast;
114-
use syntax::ptr::P;
115115
use syntax::symbol::{kw, sym};
116116
use syntax_pos::Span;
117117

src/librustc/middle/resolve_lifetime.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use crate::hir::def::{Res, DefKind};
99
use crate::hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
1010
use crate::hir::map::Map;
11+
use crate::hir::ptr::P;
1112
use crate::hir::{GenericArg, GenericParam, ItemLocalId, LifetimeName, Node, ParamName};
1213
use crate::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
1314

@@ -21,7 +22,6 @@ use std::cell::Cell;
2122
use std::mem::replace;
2223
use syntax::ast;
2324
use syntax::attr;
24-
use syntax::ptr::P;
2525
use syntax::symbol::{kw, sym};
2626
use syntax_pos::Span;
2727

0 commit comments

Comments
 (0)