Skip to content

Commit 467a364

Browse files
rustfmt impl restriction
1 parent 22855c9 commit 467a364

2 files changed

Lines changed: 39 additions & 3 deletions

File tree

src/tools/rustfmt/src/items.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1168,6 +1168,7 @@ pub(crate) fn format_trait(
11681168
constness,
11691169
is_auto,
11701170
safety,
1171+
ref impl_restriction,
11711172
ident,
11721173
ref generics,
11731174
ref bounds,
@@ -1176,11 +1177,12 @@ pub(crate) fn format_trait(
11761177

11771178
let mut result = String::with_capacity(128);
11781179
let header = format!(
1179-
"{}{}{}{}trait ",
1180+
"{}{}{}{}{}trait ",
11801181
format_visibility(context, &item.vis),
11811182
format_constness(constness),
11821183
format_safety(safety),
11831184
format_auto(is_auto),
1185+
format_impl_restriction(context, impl_restriction),
11841186
);
11851187
result.push_str(&header);
11861188

src/tools/rustfmt/src/utils.rs

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ use std::borrow::Cow;
22

33
use rustc_ast::YieldKind;
44
use rustc_ast::ast::{
5-
self, Attribute, MetaItem, MetaItemInner, MetaItemKind, NodeId, Path, Visibility,
6-
VisibilityKind,
5+
self, Attribute, ImplRestriction, MetaItem, MetaItemInner, MetaItemKind, NodeId, Path,
6+
RestrictionKind, Visibility, VisibilityKind,
77
};
88
use rustc_ast_pretty::pprust;
99
use rustc_span::{BytePos, LocalExpnId, Span, Symbol, SyntaxContext, sym, symbol};
@@ -74,6 +74,40 @@ pub(crate) fn format_visibility(
7474
}
7575
}
7676

77+
pub(crate) fn format_impl_restriction(
78+
context: &RewriteContext<'_>,
79+
impl_restriction: &ImplRestriction,
80+
) -> String {
81+
format_restriction("impl", context, &impl_restriction.kind)
82+
}
83+
84+
fn format_restriction(
85+
kw: &'static str,
86+
context: &RewriteContext<'_>,
87+
restriction: &RestrictionKind,
88+
) -> String {
89+
match restriction {
90+
RestrictionKind::Unrestricted => format!("{kw} "),
91+
RestrictionKind::Restricted {
92+
ref path,
93+
id: _,
94+
shorthand,
95+
} => {
96+
let Path { ref segments, .. } = **path;
97+
let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
98+
if path.is_global() && segments_iter.next().is_none() {
99+
panic!("non-global path in {kw}(restricted)?");
100+
}
101+
// FIXME use `segments_iter.intersperse("::").collect::<String>()` once
102+
// `#![feature(iter_intersperse)]` is re-stabilized.
103+
let path = itertools::join(segments_iter, "::");
104+
let in_str = if *shorthand { "" } else { "in " };
105+
106+
format!("{kw}({in_str}{path}) ")
107+
}
108+
}
109+
}
110+
77111
#[inline]
78112
pub(crate) fn format_coro(coroutine_kind: &ast::CoroutineKind) -> &'static str {
79113
match coroutine_kind {

0 commit comments

Comments
 (0)