Skip to content

Commit 485c0a1

Browse files
committed
extend to_string space handling
1 parent 9e0edbe commit 485c0a1

File tree

1 file changed

+40
-7
lines changed

1 file changed

+40
-7
lines changed

library/proc_macro/src/bridge/standalone.rs

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,12 @@ impl server::TokenStream for NoRustc {
167167
}
168168

169169
let mut s = String::new();
170-
for tree in &tokens.0 {
171-
s.push_str(&match tree {
170+
let mut last = String::new();
171+
let mut second_last = String::new();
172+
173+
for (idx, tree) in tokens.0.iter().enumerate() {
174+
let mut space = true;
175+
let new_part = match tree {
172176
TokenTree::Group(group) => {
173177
let inner = if let Some(stream) = &group.stream {
174178
self.to_string(stream)
@@ -177,7 +181,13 @@ impl server::TokenStream for NoRustc {
177181
};
178182
match group.delimiter {
179183
Delimiter::Parenthesis => format!("({inner})"),
180-
Delimiter::Brace => format!("{{{inner}}}"),
184+
Delimiter::Brace => {
185+
if inner.is_empty() {
186+
"{ }".to_string()
187+
} else {
188+
format!("{{ {inner} }}")
189+
}
190+
}
181191
Delimiter::Bracket => format!("[{inner}]"),
182192
Delimiter::None => inner,
183193
}
@@ -212,11 +222,34 @@ impl server::TokenStream for NoRustc {
212222
LitKind::StrRaw(raw) => format!("r{0}\"{inner}\"{0}", get_hashes_str(raw)),
213223
}
214224
}
215-
TokenTree::Punct(punct) => (punct.ch as char).to_string(),
216-
});
217-
s.push(' ');
225+
TokenTree::Punct(punct) => {
226+
let c = punct.ch as char;
227+
if c == '\'' {
228+
space = false;
229+
}
230+
c.to_string()
231+
}
232+
};
233+
234+
const NON_SEPARATABLE_TOKENS: &[(char, char)] = &[(':', ':'), ('-', '>')];
235+
236+
for (first, second) in NON_SEPARATABLE_TOKENS {
237+
if second_last == first.to_string() && last == second.to_string() && new_part != ":"
238+
{
239+
s.pop(); // pop ' '
240+
s.pop(); // pop `second`
241+
s.pop(); // pop ' '
242+
s.push(*second);
243+
s.push(' ');
244+
}
245+
}
246+
s.push_str(&new_part);
247+
second_last = last;
248+
last = new_part;
249+
if space && idx + 1 != tokens.0.len() {
250+
s.push(' ');
251+
}
218252
}
219-
s.pop();
220253
s
221254
}
222255

0 commit comments

Comments
 (0)